IpTunnel.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "benc/String.h"
  16. #include "benc/Dict.h"
  17. #include "benc/List.h"
  18. #include "benc/Int.h"
  19. #include "benc/serialization/standard/BencMessageWriter.h"
  20. #include "benc/serialization/standard/BencMessageReader.h"
  21. #include "crypto/AddressCalc.h"
  22. #include "crypto/random/Random.h"
  23. #include "exception/Jmp.h"
  24. #include "interface/tuntap/TUNMessageType.h"
  25. #include "memory/Allocator.h"
  26. #include "tunnel/IpTunnel.h"
  27. #include "tunnel/RouteGen.h"
  28. #include "crypto/AddressCalc.h"
  29. #include "util/platform/netdev/NetDev.h"
  30. #include "util/Checksum.h"
  31. #include "util/AddrTools.h"
  32. #include "util/events/EventBase.h"
  33. #include "util/Identity.h"
  34. #include "util/events/Timeout.h"
  35. #include "util/Defined.h"
  36. #include "util/Escape.h"
  37. #include "wire/Error.h"
  38. #include "wire/Headers.h"
  39. #include "wire/Ethernet.h"
  40. #include "wire/DataHeader.h"
  41. #include <stddef.h>
  42. struct IpTunnel_pvt
  43. {
  44. struct IpTunnel pub;
  45. struct Allocator* allocator;
  46. struct Log* logger;
  47. struct RouteGen* rg;
  48. uint32_t connectionCapacity;
  49. /** An always incrementing number which represents the connections. */
  50. uint32_t nextConnectionNumber;
  51. /** To get the name of the TUN interface so that ip addresses can be added. */
  52. struct GlobalConfig* globalConf;
  53. /**
  54. * Every 10 seconds check for connections which the other end has
  55. * not provided ip addresses and send more requests.
  56. */
  57. struct Timeout* timeout;
  58. struct Random* rand;
  59. /** For verifying the integrity of the structure. */
  60. Identity
  61. };
  62. static struct IpTunnel_Connection* newConnection(bool isOutgoing, struct IpTunnel_pvt* context)
  63. {
  64. if (context->pub.connectionList.count == context->connectionCapacity) {
  65. uint32_t newSize = (context->connectionCapacity + 4) * sizeof(struct IpTunnel_Connection);
  66. context->pub.connectionList.connections =
  67. Allocator_realloc(context->allocator, context->pub.connectionList.connections, newSize);
  68. context->connectionCapacity += 4;
  69. }
  70. struct IpTunnel_Connection* conn =
  71. &context->pub.connectionList.connections[context->pub.connectionList.count];
  72. // If it's an incoming connection, it must be lower on the list than any outgoing connections.
  73. if (!isOutgoing) {
  74. for (int i = (int)context->pub.connectionList.count - 1; i >= 0; i--) {
  75. if (!context->pub.connectionList.connections[i].isOutgoing
  76. && conn != &context->pub.connectionList.connections[i + 1])
  77. {
  78. Bits_memcpy(conn,
  79. &context->pub.connectionList.connections[i + 1],
  80. sizeof(struct IpTunnel_Connection));
  81. conn = &context->pub.connectionList.connections[i + 1];
  82. }
  83. }
  84. }
  85. context->pub.connectionList.count++;
  86. Bits_memset(conn, 0, sizeof(struct IpTunnel_Connection));
  87. conn->number = context->nextConnectionNumber++;
  88. conn->isOutgoing = isOutgoing;
  89. // if there are 2 billion calls, die.
  90. Assert_true(context->nextConnectionNumber < (UINT32_MAX >> 1));
  91. return conn;
  92. }
  93. static void deleteConnection(struct IpTunnel_Connection* conn, struct IpTunnel_pvt* context)
  94. {
  95. // Delete connection and shift the list elements following the removed connection
  96. int i = (((char *)conn)-((char *)&context->pub.connectionList.connections[0]))
  97. / sizeof(struct IpTunnel_Connection);
  98. // Sanity check
  99. Assert_true(i >= 0 && i < (signed int)context->pub.connectionList.count);
  100. for (; (unsigned int)i < context->pub.connectionList.count-1; ++i) {
  101. Bits_memcpy(&context->pub.connectionList.connections[i],
  102. &context->pub.connectionList.connections[i + 1],
  103. sizeof(struct IpTunnel_Connection));
  104. }
  105. int last = context->pub.connectionList.count-1;
  106. if (last > 0) {
  107. Bits_memset(&context->pub.connectionList.connections[last], 0,
  108. sizeof(struct IpTunnel_Connection));
  109. }
  110. context->pub.connectionList.count--;
  111. }
  112. static struct IpTunnel_Connection* connectionByPubKey(uint8_t pubKey[32],
  113. struct IpTunnel_pvt* context)
  114. {
  115. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  116. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  117. if (!Bits_memcmp(pubKey, conn->routeHeader.publicKey, 32)) {
  118. return conn;
  119. }
  120. }
  121. return NULL;
  122. }
  123. /**
  124. * Allow another node to tunnel IPv4 and/or ICANN IPv6 through this node.
  125. *
  126. * @param publicKeyOfAuthorizedNode the key for the node which will be allowed to connect.
  127. * @param ip6Addr the IPv6 address which the node will be issued or NULL.
  128. * @param ip6Prefix the IPv6 netmask/prefix length.
  129. * @param ip4Addr the IPv4 address which the node will be issued or NULL.
  130. * @param ip4Prefix the IPv4 netmask/prefix length.
  131. * @param tunnel the IpTunnel.
  132. * @return an connection number which is usable with IpTunnel_remove().
  133. */
  134. int IpTunnel_allowConnection(uint8_t publicKeyOfAuthorizedNode[32],
  135. struct Sockaddr* ip6Addr,
  136. uint8_t ip6Prefix,
  137. uint8_t ip6Alloc,
  138. struct Sockaddr* ip4Addr,
  139. uint8_t ip4Prefix,
  140. uint8_t ip4Alloc,
  141. struct IpTunnel* tunnel)
  142. {
  143. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  144. Log_debug(context->logger, "IPv4 Prefix to allow: %d", ip4Prefix);
  145. uint8_t* ip6Address = NULL;
  146. uint8_t* ip4Address = NULL;
  147. if (ip6Addr) {
  148. Sockaddr_getAddress(ip6Addr, &ip6Address);
  149. }
  150. if (ip4Addr) {
  151. Sockaddr_getAddress(ip4Addr, &ip4Address);
  152. }
  153. struct IpTunnel_Connection* conn = newConnection(false, context);
  154. Bits_memcpy(conn->routeHeader.publicKey, publicKeyOfAuthorizedNode, 32);
  155. AddressCalc_addressForPublicKey(conn->routeHeader.ip6, publicKeyOfAuthorizedNode);
  156. if (ip4Address) {
  157. Bits_memcpy(conn->connectionIp4, ip4Address, 4);
  158. conn->connectionIp4Prefix = ip4Prefix;
  159. conn->connectionIp4Alloc = ip4Alloc;
  160. Assert_true(ip4Alloc);
  161. }
  162. if (ip6Address) {
  163. Bits_memcpy(conn->connectionIp6, ip6Address, 16);
  164. conn->connectionIp6Prefix = ip6Prefix;
  165. conn->connectionIp6Alloc = ip6Alloc;
  166. Assert_true(ip6Alloc);
  167. }
  168. return conn->number;
  169. }
  170. static Iface_DEFUN sendToNode(struct Message* message,
  171. struct IpTunnel_Connection* connection,
  172. struct IpTunnel_pvt* context)
  173. {
  174. Message_push(message, NULL, DataHeader_SIZE, NULL);
  175. struct DataHeader* dh = (struct DataHeader*) message->bytes;
  176. DataHeader_setContentType(dh, ContentType_IPTUN);
  177. DataHeader_setVersion(dh, DataHeader_CURRENT_VERSION);
  178. Message_push(message, &connection->routeHeader, RouteHeader_SIZE, NULL);
  179. return Iface_next(&context->pub.nodeInterface, message);
  180. }
  181. static void sendControlMessage(Dict* dict,
  182. struct IpTunnel_Connection* connection,
  183. struct Allocator* requestAlloc,
  184. struct IpTunnel_pvt* context)
  185. {
  186. struct Message* msg = Message_new(0, 1024, requestAlloc);
  187. BencMessageWriter_write(dict, msg, NULL);
  188. int length = msg->length;
  189. // do UDP header.
  190. Message_shift(msg, Headers_UDPHeader_SIZE, NULL);
  191. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) msg->bytes;
  192. uh->srcPort_be = 0;
  193. uh->destPort_be = 0;
  194. uh->length_be = Endian_hostToBigEndian16(length);
  195. uh->checksum_be = 0;
  196. uint16_t payloadLength = msg->length;
  197. Message_shift(msg, Headers_IP6Header_SIZE, NULL);
  198. struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
  199. header->versionClassAndFlowLabel = 0;
  200. header->flowLabelLow_be = 0;
  201. header->nextHeader = 17;
  202. header->hopLimit = 0;
  203. header->payloadLength_be = Endian_hostToBigEndian16(payloadLength);
  204. Headers_setIpVersion(header);
  205. // zero the source and dest addresses.
  206. Bits_memset(header->sourceAddr, 0, 32);
  207. uh->checksum_be = Checksum_udpIp6(header->sourceAddr,
  208. (uint8_t*) uh,
  209. msg->length - Headers_IP6Header_SIZE);
  210. Iface_CALL(sendToNode, msg, connection, context);
  211. }
  212. static void requestAddresses(struct IpTunnel_Connection* conn, struct IpTunnel_pvt* context)
  213. {
  214. if (Defined(Log_DEBUG)) {
  215. uint8_t addr[40];
  216. AddrTools_printIp(addr, conn->routeHeader.ip6);
  217. Log_debug(context->logger, "Requesting addresses from [%s] for connection [%d]",
  218. addr, conn->number);
  219. }
  220. int number = conn->number;
  221. Dict d = Dict_CONST(
  222. String_CONST("q"), String_OBJ(String_CONST("IpTunnel_getAddresses")), Dict_CONST(
  223. String_CONST("txid"), String_OBJ((&(String){ .len = 4, .bytes = (char*)&number })),
  224. NULL
  225. ));
  226. struct Allocator* msgAlloc = Allocator_child(context->allocator);
  227. sendControlMessage(&d, conn, msgAlloc, context);
  228. Allocator_free(msgAlloc);
  229. }
  230. /**
  231. * Connect to another node and get IPv4 and/or IPv6 addresses from it.
  232. *
  233. * @param publicKeyOfNodeToConnectTo the key for the node to connect to.
  234. * @param tunnel the IpTunnel.
  235. * @return an connection number which is usable with IpTunnel_remove().
  236. */
  237. int IpTunnel_connectTo(uint8_t publicKeyOfNodeToConnectTo[32], struct IpTunnel* tunnel)
  238. {
  239. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  240. struct IpTunnel_Connection* conn = newConnection(true, context);
  241. Bits_memcpy(conn->routeHeader.publicKey, publicKeyOfNodeToConnectTo, 32);
  242. AddressCalc_addressForPublicKey(conn->routeHeader.ip6, publicKeyOfNodeToConnectTo);
  243. if (Defined(Log_DEBUG)) {
  244. uint8_t addr[40];
  245. AddrTools_printIp(addr, conn->routeHeader.ip6);
  246. Log_debug(context->logger, "Trying to connect to [%s]", addr);
  247. }
  248. requestAddresses(conn, context);
  249. return conn->number;
  250. }
  251. /**
  252. * Disconnect from a node or remove authorization to connect.
  253. *
  254. * @param connection the connection to remove.
  255. * @param tunnel the IpTunnel.
  256. */
  257. int IpTunnel_removeConnection(int connectionNumber, struct IpTunnel* tunnel)
  258. {
  259. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  260. for (int i = 0; i < (int)tunnel->connectionList.count; ++i)
  261. {
  262. if (tunnel->connectionList.connections[i].number==connectionNumber)
  263. {
  264. deleteConnection(&tunnel->connectionList.connections[i], context);
  265. return 0;
  266. }
  267. }
  268. return IpTunnel_removeConnection_NOT_FOUND;
  269. }
  270. static bool isControlMessageInvalid(struct Message* message, struct IpTunnel_pvt* context)
  271. {
  272. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  273. uint16_t length = Endian_bigEndianToHost16(header->payloadLength_be);
  274. if (header->nextHeader != 17 || message->length < length + Headers_IP6Header_SIZE) {
  275. Log_warn(context->logger, "Invalid IPv6 packet (not UDP or length field too big)");
  276. return true;
  277. }
  278. Message_shift(message, -Headers_IP6Header_SIZE, NULL);
  279. struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) message->bytes;
  280. if (Checksum_udpIp6(header->sourceAddr, message->bytes, length)) {
  281. Log_warn(context->logger, "Checksum mismatch");
  282. return true;
  283. }
  284. length -= Headers_UDPHeader_SIZE;
  285. if (Endian_bigEndianToHost16(udp->length_be) != length
  286. || udp->srcPort_be != 0
  287. || udp->destPort_be != 0)
  288. {
  289. Log_warn(context->logger, "Invalid UDP packet (length mismatch or wrong ports)");
  290. return true;
  291. }
  292. Message_shift(message, -Headers_UDPHeader_SIZE, NULL);
  293. message->length = length;
  294. return false;
  295. }
  296. static Iface_DEFUN requestForAddresses(Dict* request,
  297. struct IpTunnel_Connection* conn,
  298. struct Allocator* requestAlloc,
  299. struct IpTunnel_pvt* context)
  300. {
  301. if (Defined(Log_DEBUG)) {
  302. uint8_t addr[40];
  303. AddrTools_printIp(addr, conn->routeHeader.ip6);
  304. Log_debug(context->logger, "Got request for addresses from [%s]", addr);
  305. }
  306. if (conn->isOutgoing) {
  307. Log_warn(context->logger, "got request for addresses from outgoing connection");
  308. return 0;
  309. }
  310. Dict* addresses = Dict_new(requestAlloc);
  311. bool noAddresses = true;
  312. if (!Bits_isZero(conn->connectionIp6, 16)) {
  313. Dict_putStringC(addresses,
  314. "ip6",
  315. String_newBinary((char*)conn->connectionIp6, 16, requestAlloc),
  316. requestAlloc);
  317. Dict_putIntC(addresses,
  318. "ip6Prefix", (int64_t)conn->connectionIp6Prefix,
  319. requestAlloc);
  320. Dict_putIntC(addresses,
  321. "ip6Alloc", (int64_t)conn->connectionIp6Alloc,
  322. requestAlloc);
  323. noAddresses = false;
  324. }
  325. if (!Bits_isZero(conn->connectionIp4, 4)) {
  326. Dict_putStringC(addresses,
  327. "ip4",
  328. String_newBinary((char*)conn->connectionIp4, 4, requestAlloc),
  329. requestAlloc);
  330. Dict_putIntC(addresses,
  331. "ip4Prefix", (int64_t)conn->connectionIp4Prefix,
  332. requestAlloc);
  333. Dict_putIntC(addresses,
  334. "ip4Alloc", (int64_t)conn->connectionIp4Alloc,
  335. requestAlloc);
  336. noAddresses = false;
  337. }
  338. if (noAddresses) {
  339. Log_warn(context->logger, "no addresses to provide");
  340. return 0;
  341. }
  342. Dict* msg = Dict_new(requestAlloc);
  343. Dict_putDictC(msg, "addresses", addresses, requestAlloc);
  344. String* txid = Dict_getStringC(request, "txid");
  345. if (txid) {
  346. Dict_putStringC(msg, "txid", txid, requestAlloc);
  347. }
  348. sendControlMessage(msg, conn, requestAlloc, context);
  349. return 0;
  350. }
  351. static void addAddress(char* printedAddr, uint8_t prefixLen,
  352. uint8_t allocSize, struct IpTunnel_pvt* ctx)
  353. {
  354. String* tunName = GlobalConfig_getTunName(ctx->globalConf);
  355. if (!tunName) {
  356. Log_error(ctx->logger, "Failed to set IP address because TUN interface is not setup");
  357. return;
  358. }
  359. struct Sockaddr_storage ss;
  360. if (Sockaddr_parse(printedAddr, &ss)) {
  361. Log_error(ctx->logger, "Invalid ip, setting ip address on TUN");
  362. return;
  363. }
  364. ss.addr.flags |= Sockaddr_flags_PREFIX;
  365. ss.addr.prefix = allocSize;
  366. struct Jmp j;
  367. Jmp_try(j) {
  368. NetDev_addAddress(tunName->bytes, &ss.addr, ctx->logger, &j.handler);
  369. } Jmp_catch {
  370. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", j.message);
  371. return;
  372. }
  373. ss.addr.prefix = prefixLen;
  374. bool installRoute = false;
  375. if (Sockaddr_getFamily(&ss.addr) == Sockaddr_AF_INET) {
  376. installRoute = (prefixLen < 32);
  377. } else if (Sockaddr_getFamily(&ss.addr) == Sockaddr_AF_INET6) {
  378. installRoute = (prefixLen < 128);
  379. } else {
  380. Assert_failure("bad address family");
  381. }
  382. if (installRoute) {
  383. RouteGen_addPrefix(ctx->rg, &ss.addr);
  384. }
  385. }
  386. static Iface_DEFUN incomingAddresses(Dict* d,
  387. struct IpTunnel_Connection* conn,
  388. struct Allocator* alloc,
  389. struct IpTunnel_pvt* context)
  390. {
  391. if (!conn->isOutgoing) {
  392. Log_warn(context->logger, "got offer of addresses from incoming connection");
  393. return 0;
  394. }
  395. String* txid = Dict_getStringC(d, "txid");
  396. if (!txid || txid->len != 4) {
  397. Log_info(context->logger, "missing or wrong length txid");
  398. return 0;
  399. }
  400. int number;
  401. Bits_memcpy(&number, txid->bytes, 4);
  402. if (number < 0 || number >= (int)context->nextConnectionNumber) {
  403. Log_info(context->logger, "txid out of range");
  404. return 0;
  405. }
  406. if (number != conn->number) {
  407. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  408. if (context->pub.connectionList.connections[i].number == number) {
  409. if (Bits_memcmp(conn->routeHeader.publicKey,
  410. context->pub.connectionList.connections[i].routeHeader.publicKey,
  411. 32))
  412. {
  413. Log_info(context->logger, "txid doesn't match origin");
  414. return 0;
  415. } else {
  416. conn = &context->pub.connectionList.connections[i];
  417. }
  418. }
  419. }
  420. }
  421. Dict* addresses = Dict_getDictC(d, "addresses");
  422. String* ip4 = Dict_getStringC(addresses, "ip4");
  423. int64_t* ip4Prefix = Dict_getIntC(addresses, "ip4Prefix");
  424. int64_t* ip4Alloc = Dict_getIntC(addresses, "ip4Alloc");
  425. if (ip4 && ip4->len == 4) {
  426. Bits_memcpy(conn->connectionIp4, ip4->bytes, 4);
  427. if (ip4Prefix && *ip4Prefix >= 0 && *ip4Prefix <= 32) {
  428. conn->connectionIp4Prefix = (uint8_t) *ip4Prefix;
  429. } else {
  430. conn->connectionIp4Prefix = 32;
  431. }
  432. if (ip4Alloc && *ip4Alloc >= 0 && *ip4Alloc <= 32) {
  433. conn->connectionIp4Alloc = (uint8_t) *ip4Alloc;
  434. } else {
  435. conn->connectionIp4Alloc = 32;
  436. }
  437. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
  438. uint8_t* addrBytes = NULL;
  439. Sockaddr_getAddress(sa, &addrBytes);
  440. Bits_memcpy(addrBytes, ip4->bytes, 4);
  441. char* printedAddr = Sockaddr_print(sa, alloc);
  442. Log_info(context->logger, "Got issued address [%s/%d:%d] for connection [%d]",
  443. printedAddr, conn->connectionIp4Alloc, conn->connectionIp4Prefix, conn->number);
  444. addAddress(printedAddr, conn->connectionIp4Prefix, conn->connectionIp4Alloc, context);
  445. }
  446. String* ip6 = Dict_getStringC(addresses, "ip6");
  447. int64_t* ip6Prefix = Dict_getIntC(addresses, "ip6Prefix");
  448. int64_t* ip6Alloc = Dict_getIntC(addresses, "ip6Alloc");
  449. if (ip6 && ip6->len == 16) {
  450. Bits_memcpy(conn->connectionIp6, ip6->bytes, 16);
  451. if (ip6Prefix && *ip6Prefix >= 0 && *ip6Prefix <= 128) {
  452. conn->connectionIp6Prefix = (uint8_t) *ip6Prefix;
  453. } else {
  454. conn->connectionIp6Prefix = 128;
  455. }
  456. if (ip6Alloc && *ip6Alloc >= 0 && *ip6Alloc <= 128) {
  457. conn->connectionIp6Alloc = (uint8_t) *ip6Alloc;
  458. } else {
  459. conn->connectionIp6Alloc = 128;
  460. }
  461. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK6, alloc);
  462. uint8_t* addrBytes = NULL;
  463. Sockaddr_getAddress(sa, &addrBytes);
  464. Bits_memcpy(addrBytes, ip6->bytes, 16);
  465. char* printedAddr = Sockaddr_print(sa, alloc);
  466. Log_info(context->logger, "Got issued address block [%s/%d:%d] for connection [%d]",
  467. printedAddr, conn->connectionIp6Alloc, conn->connectionIp6Prefix, conn->number);
  468. addAddress(printedAddr, conn->connectionIp6Prefix, conn->connectionIp6Alloc, context);
  469. }
  470. if (context->rg->hasUncommittedChanges) {
  471. String* tunName = GlobalConfig_getTunName(context->globalConf);
  472. if (!tunName) {
  473. Log_error(context->logger, "Failed to set routes because TUN interface is not setup");
  474. return 0;
  475. }
  476. struct Jmp j;
  477. Jmp_try(j) {
  478. RouteGen_commit(context->rg, tunName->bytes, alloc, &j.handler);
  479. } Jmp_catch {
  480. Log_error(context->logger, "Error setting routes for TUN [%s]", j.message);
  481. return 0;
  482. }
  483. }
  484. return 0;
  485. }
  486. static Iface_DEFUN incomingControlMessage(struct Message* message,
  487. struct IpTunnel_Connection* conn,
  488. struct IpTunnel_pvt* context)
  489. {
  490. if (Defined(Log_DEBUG)) {
  491. uint8_t addr[40];
  492. AddrTools_printIp(addr, conn->routeHeader.ip6);
  493. Log_debug(context->logger, "Got incoming message from [%s]", addr);
  494. }
  495. // This aligns the message on the content.
  496. if (isControlMessageInvalid(message, context)) {
  497. return 0;
  498. }
  499. Log_debug(context->logger, "Message content [%s]",
  500. Escape_getEscaped(message->bytes, message->length, message->alloc));
  501. struct Allocator* alloc = Allocator_child(message->alloc);
  502. Dict* d = NULL;
  503. char* err = BencMessageReader_readNoExcept(message, alloc, &d);
  504. if (err) {
  505. Log_info(context->logger, "Failed to parse message [%s]", err);
  506. return 0;
  507. }
  508. if (Dict_getDictC(d, "addresses")) {
  509. return incomingAddresses(d, conn, alloc, context);
  510. }
  511. if (String_equals(String_CONST("IpTunnel_getAddresses"),
  512. Dict_getStringC(d, "q")))
  513. {
  514. return requestForAddresses(d, conn, alloc, context);
  515. }
  516. Log_warn(context->logger, "Message which is unhandled");
  517. return 0;
  518. }
  519. #define GET64(buffer) \
  520. (__extension__ ({ \
  521. Assert_true(!((long)(buffer) % 4)); \
  522. uint64_t x = (uint64_t) (((uint32_t*)(buffer))[0]); \
  523. x |= (( (uint64_t) ((uint32_t*)(buffer))[1]) << 32); \
  524. Endian_bigEndianToHost64(x); \
  525. }))
  526. #define GET32(buffer) \
  527. (__extension__ ({ \
  528. Assert_true(!((long)(buffer) % 4)); \
  529. uint32_t x = (((uint32_t*)(buffer))[0]); \
  530. Endian_bigEndianToHost32(x); \
  531. }))
  532. static bool prefixMatches6(uint8_t* addressA, uint8_t* refAddr, uint8_t prefixLen)
  533. {
  534. if (!prefixLen) {
  535. Assert_true(Bits_isZero(refAddr, 16));
  536. return false;
  537. }
  538. Assert_true(prefixLen && prefixLen <= 128);
  539. uint64_t a0 = GET64(addressA);
  540. uint64_t b0 = GET64(refAddr);
  541. if (prefixLen <= 64) {
  542. return !( (a0 ^ b0) >> (64 - prefixLen) );
  543. }
  544. uint64_t a1 = GET64(addressA + 8);
  545. uint64_t b1 = GET64(refAddr + 8);
  546. return !( (a0 ^ b0) | ((a1 ^ b1) >> (128 - prefixLen)) );
  547. }
  548. static bool prefixMatches4(uint8_t* addressA, uint8_t* refAddr, uint32_t prefixLen)
  549. {
  550. if (!prefixLen) {
  551. Assert_true(Bits_isZero(refAddr, 4));
  552. return false;
  553. }
  554. Assert_true(prefixLen && prefixLen <= 32);
  555. uint32_t a = GET32(addressA);
  556. uint32_t b = GET32(refAddr);
  557. return !((a ^ b) >> (32 - prefixLen));
  558. }
  559. static bool isValidAddress4(uint8_t sourceAndDestIp4[8],
  560. bool isFromTun,
  561. struct IpTunnel_Connection* conn)
  562. {
  563. uint8_t* compareAddr = (isFromTun)
  564. ? ((conn->isOutgoing) ? sourceAndDestIp4 : &sourceAndDestIp4[4])
  565. : ((conn->isOutgoing) ? &sourceAndDestIp4[4] : sourceAndDestIp4);
  566. return prefixMatches4(compareAddr, conn->connectionIp4, conn->connectionIp4Alloc);
  567. }
  568. static bool isValidAddress6(uint8_t sourceAndDestIp6[32],
  569. bool isFromTun,
  570. struct IpTunnel_Connection* conn)
  571. {
  572. if (AddressCalc_validAddress(sourceAndDestIp6)
  573. || AddressCalc_validAddress(&sourceAndDestIp6[16])) {
  574. return false;
  575. }
  576. uint8_t* compareAddr = (isFromTun)
  577. ? ((conn->isOutgoing) ? sourceAndDestIp6 : &sourceAndDestIp6[16])
  578. : ((conn->isOutgoing) ? &sourceAndDestIp6[16] : sourceAndDestIp6);
  579. return prefixMatches6(compareAddr, conn->connectionIp6, conn->connectionIp6Alloc);
  580. }
  581. static struct IpTunnel_Connection* findConnection(uint8_t sourceAndDestIp6[32],
  582. uint8_t sourceAndDestIp4[8],
  583. bool isFromTun,
  584. struct IpTunnel_pvt* context)
  585. {
  586. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  587. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  588. if (sourceAndDestIp6 && isValidAddress6(sourceAndDestIp6, isFromTun, conn)) {
  589. return conn;
  590. }
  591. if (sourceAndDestIp4 && isValidAddress4(sourceAndDestIp4, isFromTun, conn)) {
  592. return conn;
  593. }
  594. }
  595. return NULL;
  596. }
  597. static Iface_DEFUN incomingFromTun(struct Message* message, struct Iface* tunIf)
  598. {
  599. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunIf);
  600. if (message->length < 20) {
  601. Log_debug(context->logger, "DROP runt");
  602. }
  603. struct IpTunnel_Connection* conn = NULL;
  604. if (!context->pub.connectionList.connections) {
  605. // No connections authorized, fall through to "unrecognized address"
  606. } else if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  607. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  608. conn = findConnection(header->sourceAddr, NULL, true, context);
  609. } else if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  610. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  611. conn = findConnection(NULL, header->sourceAddr, true, context);
  612. } else {
  613. Log_info(context->logger, "Message of unknown type from TUN");
  614. return 0;
  615. }
  616. if (!conn) {
  617. Log_info(context->logger, "Message with unrecognized address from TUN");
  618. return 0;
  619. }
  620. return sendToNode(message, conn, context);
  621. }
  622. static Iface_DEFUN ip6FromNode(struct Message* message,
  623. struct IpTunnel_Connection* conn,
  624. struct IpTunnel_pvt* context)
  625. {
  626. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  627. if (Bits_isZero(header->sourceAddr, 16) || Bits_isZero(header->destinationAddr, 16)) {
  628. if (Bits_isZero(header->sourceAddr, 32)) {
  629. return incomingControlMessage(message, conn, context);
  630. }
  631. Log_debug(context->logger, "Got message with zero address");
  632. return 0;
  633. }
  634. if (!isValidAddress6(header->sourceAddr, false, conn)) {
  635. uint8_t addr[40];
  636. AddrTools_printIp(addr, header->sourceAddr);
  637. Log_debug(context->logger, "Got message with wrong address for connection [%s]", addr);
  638. return 0;
  639. }
  640. TUNMessageType_push(message, Ethernet_TYPE_IP6, NULL);
  641. return Iface_next(&context->pub.tunInterface, message);
  642. }
  643. static Iface_DEFUN ip4FromNode(struct Message* message,
  644. struct IpTunnel_Connection* conn,
  645. struct IpTunnel_pvt* context)
  646. {
  647. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  648. if (Bits_isZero(header->sourceAddr, 4) || Bits_isZero(header->destAddr, 4)) {
  649. Log_debug(context->logger, "Got message with zero address");
  650. return 0;
  651. } else if (!isValidAddress4(header->sourceAddr, false, conn)) {
  652. Log_debug(context->logger, "Got message with wrong address [%d.%d.%d.%d] for connection "
  653. "[%d.%d.%d.%d/%d:%d]",
  654. header->sourceAddr[0], header->sourceAddr[1],
  655. header->sourceAddr[2], header->sourceAddr[3],
  656. conn->connectionIp4[0], conn->connectionIp4[1],
  657. conn->connectionIp4[2], conn->connectionIp4[3],
  658. conn->connectionIp4Alloc, conn->connectionIp4Prefix);
  659. return 0;
  660. }
  661. TUNMessageType_push(message, Ethernet_TYPE_IP4, NULL);
  662. return Iface_next(&context->pub.tunInterface, message);
  663. }
  664. static Iface_DEFUN incomingFromNode(struct Message* message, struct Iface* nodeIf)
  665. {
  666. struct IpTunnel_pvt* context =
  667. Identity_containerOf(nodeIf, struct IpTunnel_pvt, pub.nodeInterface);
  668. //Log_debug(context->logger, "Got incoming message");
  669. Assert_true(message->length >= RouteHeader_SIZE + DataHeader_SIZE);
  670. struct RouteHeader* rh = (struct RouteHeader*) message->bytes;
  671. struct DataHeader* dh = (struct DataHeader*) &rh[1];
  672. Assert_true(DataHeader_getContentType(dh) == ContentType_IPTUN);
  673. struct IpTunnel_Connection* conn = connectionByPubKey(rh->publicKey, context);
  674. if (!conn) {
  675. if (Defined(Log_DEBUG)) {
  676. uint8_t addr[40];
  677. AddrTools_printIp(addr, rh->ip6);
  678. Log_debug(context->logger, "Got message from unrecognized node [%s]", addr);
  679. }
  680. return 0;
  681. }
  682. Message_shift(message, -(RouteHeader_SIZE + DataHeader_SIZE), NULL);
  683. if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  684. return ip6FromNode(message, conn, context);
  685. }
  686. if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  687. return ip4FromNode(message, conn, context);
  688. }
  689. if (Defined(Log_DEBUG)) {
  690. uint8_t addr[40];
  691. AddrTools_printIp(addr, rh->ip6);
  692. Log_debug(context->logger,
  693. "Got message of unknown type, length: [%d], IP version [%d] from [%s]",
  694. message->length,
  695. (message->length > 1) ? Headers_getIpVersion(message->bytes) : 0,
  696. addr);
  697. }
  698. return 0;
  699. }
  700. static void timeout(void* vcontext)
  701. {
  702. struct IpTunnel_pvt* context = vcontext;
  703. if (!context->pub.connectionList.count) {
  704. return;
  705. }
  706. Log_debug(context->logger, "Checking for connections to poll. Total connections [%u]",
  707. context->pub.connectionList.count);
  708. uint32_t beginning = Random_uint32(context->rand) % context->pub.connectionList.count;
  709. uint32_t i = beginning;
  710. do {
  711. Assert_true(i < context->pub.connectionList.count);
  712. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  713. if (conn->isOutgoing
  714. && Bits_isZero(conn->connectionIp6, 16)
  715. && Bits_isZero(conn->connectionIp4, 4))
  716. {
  717. requestAddresses(conn, context);
  718. break;
  719. }
  720. i = (i + 1) % context->pub.connectionList.count;
  721. } while (i != beginning);
  722. }
  723. struct IpTunnel* IpTunnel_new(struct Log* logger,
  724. struct EventBase* eventBase,
  725. struct Allocator* alloc,
  726. struct Random* rand,
  727. struct RouteGen* rg,
  728. struct GlobalConfig* globalConf)
  729. {
  730. struct IpTunnel_pvt* context = Allocator_clone(alloc, (&(struct IpTunnel_pvt) {
  731. .pub = {
  732. .tunInterface = { .send = incomingFromTun },
  733. .nodeInterface = { .send = incomingFromNode }
  734. },
  735. .allocator = alloc,
  736. .logger = logger,
  737. .rand = rand,
  738. .rg = rg,
  739. .globalConf = globalConf
  740. }));
  741. context->timeout = Timeout_setInterval(timeout, context, 10000, eventBase, alloc);
  742. Identity_set(context);
  743. return &context->pub;
  744. }