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 "interface/tuntap/TUNMessageType.h"
  24. #include "memory/Allocator.h"
  25. #include "tunnel/IpTunnel.h"
  26. #include "tunnel/RouteGen.h"
  27. #include "crypto/AddressCalc.h"
  28. #include "util/platform/netdev/NetDev.h"
  29. #include "util/Checksum.h"
  30. #include "util/AddrTools.h"
  31. #include "util/events/EventBase.h"
  32. #include "util/Identity.h"
  33. #include "util/events/Timeout.h"
  34. #include "util/Defined.h"
  35. #include "util/Escape.h"
  36. #include "wire/Error.h"
  37. #include "wire/Headers.h"
  38. #include "wire/Ethernet.h"
  39. #include "wire/DataHeader.h"
  40. #include <stddef.h>
  41. struct IpTunnel_pvt
  42. {
  43. struct IpTunnel pub;
  44. struct Allocator* allocator;
  45. struct Log* logger;
  46. struct RouteGen* rg;
  47. uint32_t connectionCapacity;
  48. /** An always incrementing number which represents the connections. */
  49. uint32_t nextConnectionNumber;
  50. /** To get the name of the TUN interface so that ip addresses can be added. */
  51. struct GlobalConfig* globalConf;
  52. /**
  53. * Every 10 seconds check for connections which the other end has
  54. * not provided ip addresses and send more requests.
  55. */
  56. struct Timeout* timeout;
  57. struct Random* rand;
  58. /** For verifying the integrity of the structure. */
  59. Identity
  60. };
  61. static struct IpTunnel_Connection* newConnection(bool isOutgoing, struct IpTunnel_pvt* context)
  62. {
  63. if (context->pub.connectionList.count == context->connectionCapacity) {
  64. uint32_t newSize = (context->connectionCapacity + 4) * sizeof(struct IpTunnel_Connection);
  65. context->pub.connectionList.connections =
  66. Allocator_realloc(context->allocator, context->pub.connectionList.connections, newSize);
  67. context->connectionCapacity += 4;
  68. }
  69. struct IpTunnel_Connection* conn =
  70. &context->pub.connectionList.connections[context->pub.connectionList.count];
  71. // If it's an incoming connection, it must be lower on the list than any outgoing connections.
  72. if (!isOutgoing) {
  73. for (int i = (int)context->pub.connectionList.count - 1; i >= 0; i--) {
  74. if (!context->pub.connectionList.connections[i].isOutgoing
  75. && conn != &context->pub.connectionList.connections[i + 1])
  76. {
  77. Bits_memcpy(conn,
  78. &context->pub.connectionList.connections[i + 1],
  79. sizeof(struct IpTunnel_Connection));
  80. conn = &context->pub.connectionList.connections[i + 1];
  81. }
  82. }
  83. }
  84. context->pub.connectionList.count++;
  85. Bits_memset(conn, 0, sizeof(struct IpTunnel_Connection));
  86. conn->number = context->nextConnectionNumber++;
  87. conn->isOutgoing = isOutgoing;
  88. // if there are 2 billion calls, die.
  89. Assert_true(context->nextConnectionNumber < (UINT32_MAX >> 1));
  90. return conn;
  91. }
  92. static void deleteConnection(struct IpTunnel_Connection* conn, struct IpTunnel_pvt* context)
  93. {
  94. // Delete connection and shift the list elements following the removed connection
  95. int i = (((char *)conn)-((char *)&context->pub.connectionList.connections[0]))
  96. / sizeof(struct IpTunnel_Connection);
  97. // Sanity check
  98. Assert_true(i >= 0 && i < (signed int)context->pub.connectionList.count);
  99. for (; (unsigned int)i < context->pub.connectionList.count-1; ++i) {
  100. Bits_memcpy(&context->pub.connectionList.connections[i],
  101. &context->pub.connectionList.connections[i + 1],
  102. sizeof(struct IpTunnel_Connection));
  103. }
  104. int last = context->pub.connectionList.count-1;
  105. if (last > 0) {
  106. Bits_memset(&context->pub.connectionList.connections[last], 0,
  107. sizeof(struct IpTunnel_Connection));
  108. }
  109. context->pub.connectionList.count--;
  110. }
  111. static struct IpTunnel_Connection* connectionByPubKey(uint8_t pubKey[32],
  112. struct IpTunnel_pvt* context)
  113. {
  114. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  115. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  116. if (!Bits_memcmp(pubKey, conn->routeHeader.publicKey, 32)) {
  117. return conn;
  118. }
  119. }
  120. return NULL;
  121. }
  122. /**
  123. * Allow another node to tunnel IPv4 and/or ICANN IPv6 through this node.
  124. *
  125. * @param publicKeyOfAuthorizedNode the key for the node which will be allowed to connect.
  126. * @param ip6Addr the IPv6 address which the node will be issued or NULL.
  127. * @param ip6Prefix the IPv6 netmask/prefix length.
  128. * @param ip4Addr the IPv4 address which the node will be issued or NULL.
  129. * @param ip4Prefix the IPv4 netmask/prefix length.
  130. * @param tunnel the IpTunnel.
  131. * @return an connection number which is usable with IpTunnel_remove().
  132. */
  133. int IpTunnel_allowConnection(uint8_t publicKeyOfAuthorizedNode[32],
  134. struct Sockaddr* ip6Addr,
  135. uint8_t ip6Prefix,
  136. uint8_t ip6Alloc,
  137. struct Sockaddr* ip4Addr,
  138. uint8_t ip4Prefix,
  139. uint8_t ip4Alloc,
  140. struct IpTunnel* tunnel)
  141. {
  142. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  143. Log_debug(context->logger, "IPv4 Prefix to allow: %d", ip4Prefix);
  144. uint8_t* ip6Address = NULL;
  145. uint8_t* ip4Address = NULL;
  146. if (ip6Addr) {
  147. Sockaddr_getAddress(ip6Addr, &ip6Address);
  148. }
  149. if (ip4Addr) {
  150. Sockaddr_getAddress(ip4Addr, &ip4Address);
  151. }
  152. struct IpTunnel_Connection* conn = newConnection(false, context);
  153. Bits_memcpy(conn->routeHeader.publicKey, publicKeyOfAuthorizedNode, 32);
  154. AddressCalc_addressForPublicKey(conn->routeHeader.ip6, publicKeyOfAuthorizedNode);
  155. if (ip4Address) {
  156. Bits_memcpy(conn->connectionIp4, ip4Address, 4);
  157. conn->connectionIp4Prefix = ip4Prefix;
  158. conn->connectionIp4Alloc = ip4Alloc;
  159. Assert_true(ip4Alloc);
  160. }
  161. if (ip6Address) {
  162. Bits_memcpy(conn->connectionIp6, ip6Address, 16);
  163. conn->connectionIp6Prefix = ip6Prefix;
  164. conn->connectionIp6Alloc = ip6Alloc;
  165. Assert_true(ip6Alloc);
  166. }
  167. return conn->number;
  168. }
  169. static Iface_DEFUN sendToNode(struct Message* message,
  170. struct IpTunnel_Connection* connection,
  171. struct IpTunnel_pvt* context)
  172. {
  173. Er_assert(Message_epush(message, NULL, DataHeader_SIZE));
  174. struct DataHeader* dh = (struct DataHeader*) message->bytes;
  175. DataHeader_setContentType(dh, ContentType_IPTUN);
  176. DataHeader_setVersion(dh, DataHeader_CURRENT_VERSION);
  177. Er_assert(Message_epush(message, &connection->routeHeader, RouteHeader_SIZE));
  178. return Iface_next(&context->pub.nodeInterface, message);
  179. }
  180. static void sendControlMessage(Dict* dict,
  181. struct IpTunnel_Connection* connection,
  182. struct Allocator* requestAlloc,
  183. struct IpTunnel_pvt* context)
  184. {
  185. struct Message* msg = Message_new(0, 1024, requestAlloc);
  186. Er_assert(BencMessageWriter_write(dict, msg));
  187. int length = msg->length;
  188. // do UDP header.
  189. Er_assert(Message_eshift(msg, Headers_UDPHeader_SIZE));
  190. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) msg->bytes;
  191. uh->srcPort_be = 0;
  192. uh->destPort_be = 0;
  193. uh->length_be = Endian_hostToBigEndian16(length);
  194. uh->checksum_be = 0;
  195. uint16_t payloadLength = msg->length;
  196. Er_assert(Message_eshift(msg, Headers_IP6Header_SIZE));
  197. struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
  198. header->versionClassAndFlowLabel = 0;
  199. header->flowLabelLow_be = 0;
  200. header->nextHeader = 17;
  201. header->hopLimit = 0;
  202. header->payloadLength_be = Endian_hostToBigEndian16(payloadLength);
  203. Headers_setIpVersion(header);
  204. // zero the source and dest addresses.
  205. Bits_memset(header->sourceAddr, 0, 32);
  206. uh->checksum_be = Checksum_udpIp6(header->sourceAddr,
  207. (uint8_t*) uh,
  208. msg->length - Headers_IP6Header_SIZE);
  209. Iface_CALL(sendToNode, msg, connection, context);
  210. }
  211. static void requestAddresses(struct IpTunnel_Connection* conn, struct IpTunnel_pvt* context)
  212. {
  213. if (Defined(Log_DEBUG)) {
  214. uint8_t addr[40];
  215. AddrTools_printIp(addr, conn->routeHeader.ip6);
  216. Log_debug(context->logger, "Requesting addresses from [%s] for connection [%d]",
  217. addr, conn->number);
  218. }
  219. int number = conn->number;
  220. Dict d = Dict_CONST(
  221. String_CONST("q"), String_OBJ(String_CONST("IpTunnel_getAddresses")), Dict_CONST(
  222. String_CONST("txid"), String_OBJ((&(String){ .len = 4, .bytes = (char*)&number })),
  223. NULL
  224. ));
  225. struct Allocator* msgAlloc = Allocator_child(context->allocator);
  226. sendControlMessage(&d, conn, msgAlloc, context);
  227. Allocator_free(msgAlloc);
  228. }
  229. /**
  230. * Connect to another node and get IPv4 and/or IPv6 addresses from it.
  231. *
  232. * @param publicKeyOfNodeToConnectTo the key for the node to connect to.
  233. * @param tunnel the IpTunnel.
  234. * @return an connection number which is usable with IpTunnel_remove().
  235. */
  236. int IpTunnel_connectTo(uint8_t publicKeyOfNodeToConnectTo[32], struct IpTunnel* tunnel)
  237. {
  238. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  239. struct IpTunnel_Connection* conn = newConnection(true, context);
  240. Bits_memcpy(conn->routeHeader.publicKey, publicKeyOfNodeToConnectTo, 32);
  241. AddressCalc_addressForPublicKey(conn->routeHeader.ip6, publicKeyOfNodeToConnectTo);
  242. if (Defined(Log_DEBUG)) {
  243. uint8_t addr[40];
  244. AddrTools_printIp(addr, conn->routeHeader.ip6);
  245. Log_debug(context->logger, "Trying to connect to [%s]", addr);
  246. }
  247. requestAddresses(conn, context);
  248. return conn->number;
  249. }
  250. /**
  251. * Disconnect from a node or remove authorization to connect.
  252. *
  253. * @param connection the connection to remove.
  254. * @param tunnel the IpTunnel.
  255. */
  256. int IpTunnel_removeConnection(int connectionNumber, struct IpTunnel* tunnel)
  257. {
  258. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  259. for (int i = 0; i < (int)tunnel->connectionList.count; ++i)
  260. {
  261. if (tunnel->connectionList.connections[i].number==connectionNumber)
  262. {
  263. deleteConnection(&tunnel->connectionList.connections[i], context);
  264. return 0;
  265. }
  266. }
  267. return IpTunnel_removeConnection_NOT_FOUND;
  268. }
  269. static bool isControlMessageInvalid(struct Message* message, struct IpTunnel_pvt* context)
  270. {
  271. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  272. uint16_t length = Endian_bigEndianToHost16(header->payloadLength_be);
  273. if (header->nextHeader != 17 || message->length < length + Headers_IP6Header_SIZE) {
  274. Log_warn(context->logger, "Invalid IPv6 packet (not UDP or length field too big)");
  275. return true;
  276. }
  277. Er_assert(Message_eshift(message, -Headers_IP6Header_SIZE));
  278. struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) message->bytes;
  279. if (Checksum_udpIp6(header->sourceAddr, message->bytes, length)) {
  280. Log_warn(context->logger, "Checksum mismatch");
  281. return true;
  282. }
  283. length -= Headers_UDPHeader_SIZE;
  284. if (Endian_bigEndianToHost16(udp->length_be) != length
  285. || udp->srcPort_be != 0
  286. || udp->destPort_be != 0)
  287. {
  288. Log_warn(context->logger, "Invalid UDP packet (length mismatch or wrong ports)");
  289. return true;
  290. }
  291. Er_assert(Message_eshift(message, -Headers_UDPHeader_SIZE));
  292. message->length = length;
  293. return false;
  294. }
  295. static Iface_DEFUN requestForAddresses(Dict* request,
  296. struct IpTunnel_Connection* conn,
  297. struct Allocator* requestAlloc,
  298. struct IpTunnel_pvt* context)
  299. {
  300. if (Defined(Log_DEBUG)) {
  301. uint8_t addr[40];
  302. AddrTools_printIp(addr, conn->routeHeader.ip6);
  303. Log_debug(context->logger, "Got request for addresses from [%s]", addr);
  304. }
  305. if (conn->isOutgoing) {
  306. Log_warn(context->logger, "got request for addresses from outgoing connection");
  307. return 0;
  308. }
  309. Dict* addresses = Dict_new(requestAlloc);
  310. bool noAddresses = true;
  311. if (!Bits_isZero(conn->connectionIp6, 16)) {
  312. Dict_putStringC(addresses,
  313. "ip6",
  314. String_newBinary((char*)conn->connectionIp6, 16, requestAlloc),
  315. requestAlloc);
  316. Dict_putIntC(addresses,
  317. "ip6Prefix", (int64_t)conn->connectionIp6Prefix,
  318. requestAlloc);
  319. Dict_putIntC(addresses,
  320. "ip6Alloc", (int64_t)conn->connectionIp6Alloc,
  321. requestAlloc);
  322. noAddresses = false;
  323. }
  324. if (!Bits_isZero(conn->connectionIp4, 4)) {
  325. Dict_putStringC(addresses,
  326. "ip4",
  327. String_newBinary((char*)conn->connectionIp4, 4, requestAlloc),
  328. requestAlloc);
  329. Dict_putIntC(addresses,
  330. "ip4Prefix", (int64_t)conn->connectionIp4Prefix,
  331. requestAlloc);
  332. Dict_putIntC(addresses,
  333. "ip4Alloc", (int64_t)conn->connectionIp4Alloc,
  334. requestAlloc);
  335. noAddresses = false;
  336. }
  337. if (noAddresses) {
  338. Log_warn(context->logger, "no addresses to provide");
  339. return 0;
  340. }
  341. Dict* msg = Dict_new(requestAlloc);
  342. Dict_putDictC(msg, "addresses", addresses, requestAlloc);
  343. String* txid = Dict_getStringC(request, "txid");
  344. if (txid) {
  345. Dict_putStringC(msg, "txid", txid, requestAlloc);
  346. }
  347. sendControlMessage(msg, conn, requestAlloc, context);
  348. return 0;
  349. }
  350. static void addAddress(char* printedAddr, uint8_t prefixLen,
  351. uint8_t allocSize, struct IpTunnel_pvt* ctx,
  352. struct Allocator* tempAlloc)
  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 Er_Ret* er = NULL;
  367. Er_check(&er, NetDev_addAddress(tunName->bytes, &ss.addr, ctx->logger, tempAlloc));
  368. if (er) {
  369. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", er->message);
  370. return;
  371. }
  372. ss.addr.prefix = prefixLen;
  373. bool installRoute = false;
  374. if (Sockaddr_getFamily(&ss.addr) == Sockaddr_AF_INET) {
  375. installRoute = (prefixLen < 32);
  376. } else if (Sockaddr_getFamily(&ss.addr) == Sockaddr_AF_INET6) {
  377. installRoute = (prefixLen < 128);
  378. } else {
  379. Assert_failure("bad address family");
  380. }
  381. if (installRoute) {
  382. RouteGen_addPrefix(ctx->rg, &ss.addr);
  383. }
  384. }
  385. static Iface_DEFUN incomingAddresses(Dict* d,
  386. struct IpTunnel_Connection* conn,
  387. struct Allocator* alloc,
  388. struct IpTunnel_pvt* context)
  389. {
  390. if (!conn->isOutgoing) {
  391. Log_warn(context->logger, "got offer of addresses from incoming connection");
  392. return 0;
  393. }
  394. String* txid = Dict_getStringC(d, "txid");
  395. if (!txid || txid->len != 4) {
  396. Log_info(context->logger, "missing or wrong length txid");
  397. return 0;
  398. }
  399. int number;
  400. Bits_memcpy(&number, txid->bytes, 4);
  401. if (number < 0 || number >= (int)context->nextConnectionNumber) {
  402. Log_info(context->logger, "txid out of range");
  403. return 0;
  404. }
  405. if (number != conn->number) {
  406. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  407. if (context->pub.connectionList.connections[i].number == number) {
  408. if (Bits_memcmp(conn->routeHeader.publicKey,
  409. context->pub.connectionList.connections[i].routeHeader.publicKey,
  410. 32))
  411. {
  412. Log_info(context->logger, "txid doesn't match origin");
  413. return 0;
  414. } else {
  415. conn = &context->pub.connectionList.connections[i];
  416. }
  417. }
  418. }
  419. }
  420. Dict* addresses = Dict_getDictC(d, "addresses");
  421. String* ip4 = Dict_getStringC(addresses, "ip4");
  422. int64_t* ip4Prefix = Dict_getIntC(addresses, "ip4Prefix");
  423. int64_t* ip4Alloc = Dict_getIntC(addresses, "ip4Alloc");
  424. if (ip4 && ip4->len == 4) {
  425. Bits_memcpy(conn->connectionIp4, ip4->bytes, 4);
  426. if (ip4Prefix && *ip4Prefix >= 0 && *ip4Prefix <= 32) {
  427. conn->connectionIp4Prefix = (uint8_t) *ip4Prefix;
  428. } else {
  429. conn->connectionIp4Prefix = 32;
  430. }
  431. if (ip4Alloc && *ip4Alloc >= 0 && *ip4Alloc <= 32) {
  432. conn->connectionIp4Alloc = (uint8_t) *ip4Alloc;
  433. } else {
  434. conn->connectionIp4Alloc = 32;
  435. }
  436. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
  437. uint8_t* addrBytes = NULL;
  438. Sockaddr_getAddress(sa, &addrBytes);
  439. Bits_memcpy(addrBytes, ip4->bytes, 4);
  440. char* printedAddr = Sockaddr_print(sa, alloc);
  441. Log_info(context->logger, "Got issued address [%s/%d:%d] for connection [%d]",
  442. printedAddr, conn->connectionIp4Alloc, conn->connectionIp4Prefix, conn->number);
  443. addAddress(printedAddr,
  444. conn->connectionIp4Prefix, conn->connectionIp4Alloc, context, alloc);
  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,
  469. conn->connectionIp6Prefix, conn->connectionIp6Alloc, context, alloc);
  470. }
  471. if (context->rg->hasUncommittedChanges) {
  472. String* tunName = GlobalConfig_getTunName(context->globalConf);
  473. if (!tunName) {
  474. Log_error(context->logger, "Failed to set routes because TUN interface is not setup");
  475. return 0;
  476. }
  477. struct Er_Ret* er = NULL;
  478. Er_check(&er, RouteGen_commit(context->rg, tunName->bytes, alloc));
  479. if (er) {
  480. Log_error(context->logger, "Error setting routes for TUN [%s]", er->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. const 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_debug(context->logger, "Message of unknown type from TUN");
  614. return 0;
  615. }
  616. if (!conn) {
  617. Log_debug(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. Er_assert(TUNMessageType_push(message, Ethernet_TYPE_IP6));
  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. Er_assert(TUNMessageType_push(message, Ethernet_TYPE_IP4));
  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. Er_assert(Message_eshift(message, -(RouteHeader_SIZE + DataHeader_SIZE)));
  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. }