IpTunnel.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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 <http://www.gnu.org/licenses/>.
  14. */
  15. #include "admin/angel/Hermes.h"
  16. #include "benc/String.h"
  17. #include "benc/Dict.h"
  18. #include "benc/List.h"
  19. #include "benc/Int.h"
  20. #include "benc/serialization/standard/BencMessageWriter.h"
  21. #include "benc/serialization/standard/BencMessageReader.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 "crypto/AddressCalc.h"
  28. #include "util/Checksum.h"
  29. #include "util/AddrTools.h"
  30. #include "util/events/EventBase.h"
  31. #include "util/Identity.h"
  32. #include "util/events/Timeout.h"
  33. #include "wire/Error.h"
  34. #include "wire/Headers.h"
  35. #include "wire/Ethernet.h"
  36. #include <stddef.h>
  37. struct IpTunnel_pvt
  38. {
  39. struct IpTunnel pub;
  40. struct Allocator* allocator;
  41. struct Log* logger;
  42. uint32_t connectionCapacity;
  43. /** An always incrementing number which represents the connections. */
  44. uint32_t nextConnectionNumber;
  45. /** The name of the TUN interface so that ip addresses can be added. */
  46. String* ifName;
  47. /**
  48. * Every 10 seconds check for connections which the other end has
  49. * not provided ip addresses and send more requests.
  50. */
  51. struct Timeout* timeout;
  52. struct Random* rand;
  53. /** The angel connector for setting IP addresses. */
  54. struct Hermes* hermes;
  55. /** For verifying the integrity of the structure. */
  56. Identity
  57. };
  58. static struct IpTunnel_Connection* newConnection(bool isOutgoing, struct IpTunnel_pvt* context)
  59. {
  60. if (context->pub.connectionList.count == context->connectionCapacity) {
  61. uint32_t newSize = (context->connectionCapacity + 4) * sizeof(struct IpTunnel_Connection);
  62. context->pub.connectionList.connections =
  63. Allocator_realloc(context->allocator, context->pub.connectionList.connections, newSize);
  64. context->connectionCapacity += 4;
  65. }
  66. struct IpTunnel_Connection* conn =
  67. &context->pub.connectionList.connections[context->pub.connectionList.count];
  68. // If it's an incoming connection, it must be lower on the list than any outgoing connections.
  69. if (!isOutgoing) {
  70. for (int i = (int)context->pub.connectionList.count - 1; i >= 0; i--) {
  71. if (!context->pub.connectionList.connections[i].isOutgoing
  72. && conn != &context->pub.connectionList.connections[i + 1])
  73. {
  74. Bits_memcpyConst(conn,
  75. &context->pub.connectionList.connections[i + 1],
  76. sizeof(struct IpTunnel_Connection));
  77. conn = &context->pub.connectionList.connections[i + 1];
  78. }
  79. }
  80. }
  81. context->pub.connectionList.count++;
  82. Bits_memset(conn, 0, sizeof(struct IpTunnel_Connection));
  83. conn->number = context->nextConnectionNumber++;
  84. conn->isOutgoing = isOutgoing;
  85. // if there are 2 billion calls, die.
  86. Assert_true(context->nextConnectionNumber < (UINT32_MAX >> 1));
  87. return conn;
  88. }
  89. static struct IpTunnel_Connection* connectionByPubKey(uint8_t pubKey[32],
  90. struct IpTunnel_pvt* context)
  91. {
  92. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  93. if (!Bits_memcmp(pubKey, context->pub.connectionList.connections[i].header.nodeKey, 32)) {
  94. return &context->pub.connectionList.connections[i];
  95. }
  96. }
  97. return NULL;
  98. }
  99. /**
  100. * Allow another node to tunnel IPv4 and/or ICANN IPv6 through this node.
  101. *
  102. * @param publicKeyOfAuthorizedNode the key for the node which will be allowed to connect.
  103. * @param ip6Addr the IPv6 address which the node will be issued or NULL.
  104. * @param ip6Prefix the IPv6 netmask/prefix length.
  105. * @param ip4Addr the IPv4 address which the node will be issued or NULL.
  106. * @param ip4Prefix the IPv4 netmask/prefix length.
  107. * @param tunnel the IpTunnel.
  108. * @return an connection number which is usable with IpTunnel_remove().
  109. */
  110. int IpTunnel_allowConnection(uint8_t publicKeyOfAuthorizedNode[32],
  111. struct Sockaddr* ip6Addr, uint8_t ip6Prefix,
  112. struct Sockaddr* ip4Addr, uint8_t ip4Prefix,
  113. struct IpTunnel* tunnel)
  114. {
  115. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  116. Log_debug(context->logger, "IPv4 Prefix to allow: %d", ip4Prefix);
  117. uint8_t* ip6Address = NULL;
  118. uint8_t* ip4Address = NULL;
  119. if (ip6Addr) {
  120. Sockaddr_getAddress(ip6Addr, &ip6Address);
  121. }
  122. if (ip4Addr) {
  123. Sockaddr_getAddress(ip4Addr, &ip4Address);
  124. }
  125. struct IpTunnel_Connection* conn = newConnection(false, context);
  126. Bits_memcpyConst(conn->header.nodeKey, publicKeyOfAuthorizedNode, 32);
  127. AddressCalc_addressForPublicKey(conn->header.nodeIp6Addr, publicKeyOfAuthorizedNode);
  128. if (ip4Address) {
  129. Bits_memcpyConst(conn->connectionIp4, ip4Address, 4);
  130. conn->connectionIp4Prefix = ip4Prefix;
  131. }
  132. if (ip6Address) {
  133. Bits_memcpyConst(conn->connectionIp6, ip6Address, 16);
  134. conn->connectionIp6Prefix = ip6Prefix;
  135. }
  136. return conn->number;
  137. }
  138. static uint8_t sendToNode(struct Message* message,
  139. struct IpTunnel_Connection* connection,
  140. struct IpTunnel_pvt* context)
  141. {
  142. Message_push(message, &connection->header, IpTunnel_PacketInfoHeader_SIZE, NULL);
  143. if (context->pub.nodeInterface.receiveMessage) {
  144. return context->pub.nodeInterface.receiveMessage(message, &context->pub.nodeInterface);
  145. }
  146. Log_info(context->logger, "Message undeliverable because IpTunnel is not registered");
  147. return Error_UNDELIVERABLE;
  148. }
  149. static uint8_t sendControlMessage(Dict* dict,
  150. struct IpTunnel_Connection* connection,
  151. struct Allocator* requestAlloc,
  152. struct IpTunnel_pvt* context)
  153. {
  154. struct Message* msg = Message_new(0, 1024, requestAlloc);
  155. BencMessageWriter_write(dict, msg, NULL);
  156. int length = msg->length;
  157. // do UDP header.
  158. Message_shift(msg, Headers_UDPHeader_SIZE, NULL);
  159. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) msg->bytes;
  160. uh->srcPort_be = 0;
  161. uh->destPort_be = 0;
  162. uh->length_be = Endian_hostToBigEndian16(length);
  163. uh->checksum_be = 0;
  164. uint16_t payloadLength = msg->length;
  165. Message_shift(msg, Headers_IP6Header_SIZE, NULL);
  166. struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
  167. header->versionClassAndFlowLabel = 0;
  168. header->flowLabelLow_be = 0;
  169. header->nextHeader = 17;
  170. header->hopLimit = 0;
  171. header->payloadLength_be = Endian_hostToBigEndian16(payloadLength);
  172. Headers_setIpVersion(header);
  173. // zero the source and dest addresses.
  174. Bits_memset(header->sourceAddr, 0, 32);
  175. uh->checksum_be = Checksum_udpIp6(header->sourceAddr,
  176. (uint8_t*) uh,
  177. msg->length - Headers_IP6Header_SIZE);
  178. return sendToNode(msg, connection, context);
  179. }
  180. static uint8_t requestAddresses(struct IpTunnel_Connection* conn,
  181. struct IpTunnel_pvt* context)
  182. {
  183. #ifdef Log_DEBUG
  184. uint8_t addr[40];
  185. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  186. Log_debug(context->logger, "Requesting addresses from [%s] for connection [%d]",
  187. addr, conn->number);
  188. #endif
  189. int number = conn->number;
  190. Dict d = Dict_CONST(
  191. String_CONST("q"), String_OBJ(String_CONST("IpTunnel_getAddresses")), Dict_CONST(
  192. String_CONST("txid"), String_OBJ((&(String){ .len = 4, .bytes = (char*)&number })),
  193. NULL
  194. ));
  195. struct Allocator* msgAlloc = Allocator_child(context->allocator);
  196. uint8_t ret = sendControlMessage(&d, conn, msgAlloc, context);
  197. Allocator_free(msgAlloc);
  198. return ret;
  199. }
  200. /**
  201. * Connect to another node and get IPv4 and/or IPv6 addresses from it.
  202. *
  203. * @param publicKeyOfNodeToConnectTo the key for the node to connect to.
  204. * @param tunnel the IpTunnel.
  205. * @return an connection number which is usable with IpTunnel_remove().
  206. */
  207. int IpTunnel_connectTo(uint8_t publicKeyOfNodeToConnectTo[32], struct IpTunnel* tunnel)
  208. {
  209. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  210. struct IpTunnel_Connection* conn = newConnection(true, context);
  211. Bits_memcpyConst(conn->header.nodeKey, publicKeyOfNodeToConnectTo, 32);
  212. AddressCalc_addressForPublicKey(conn->header.nodeIp6Addr, publicKeyOfNodeToConnectTo);
  213. #ifdef Log_DEBUG
  214. uint8_t addr[40];
  215. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  216. Log_debug(context->logger, "Trying to connect to [%s]", addr);
  217. #endif
  218. requestAddresses(conn, context);
  219. return conn->number;
  220. }
  221. /**
  222. * Disconnect from a node or remove authorization to connect.
  223. *
  224. * @param connection the connection to remove.
  225. * @param tunnel the IpTunnel.
  226. */
  227. int IpTunnel_removeConnection(int connectionNumber, struct IpTunnel* tunnel)
  228. {
  229. //struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunnel);
  230. return 0;
  231. }
  232. static uint8_t isControlMessageInvalid(struct Message* message, struct IpTunnel_pvt* context)
  233. {
  234. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  235. uint16_t length = Endian_bigEndianToHost16(header->payloadLength_be);
  236. if (header->nextHeader != 17 || message->length < length + Headers_IP6Header_SIZE) {
  237. Log_warn(context->logger, "Invalid IPv6 packet (not UDP or length field too big)");
  238. return Error_INVALID;
  239. }
  240. Message_shift(message, -Headers_IP6Header_SIZE, NULL);
  241. struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) message->bytes;
  242. if (Checksum_udpIp6(header->sourceAddr, message->bytes, length)) {
  243. Log_warn(context->logger, "Checksum mismatch");
  244. return Error_INVALID;
  245. }
  246. length -= Headers_UDPHeader_SIZE;
  247. if (Endian_bigEndianToHost16(udp->length_be) != length
  248. || udp->srcPort_be != 0
  249. || udp->destPort_be != 0)
  250. {
  251. Log_warn(context->logger, "Invalid UDP packet (length mismatch or wrong ports)");
  252. return Error_INVALID;
  253. }
  254. Message_shift(message, -Headers_UDPHeader_SIZE, NULL);
  255. message->length = length;
  256. return 0;
  257. }
  258. static uint8_t requestForAddresses(Dict* request,
  259. struct IpTunnel_Connection* conn,
  260. struct Allocator* requestAlloc,
  261. struct IpTunnel_pvt* context)
  262. {
  263. #ifdef Log_DEBUG
  264. uint8_t addr[40];
  265. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  266. Log_debug(context->logger, "Got request for addresses from [%s]", addr);
  267. #endif
  268. if (conn->isOutgoing) {
  269. Log_warn(context->logger, "got request for addresses from outgoing connection");
  270. return Error_INVALID;
  271. }
  272. Dict* addresses = Dict_new(requestAlloc);
  273. bool noAddresses = true;
  274. if (!Bits_isZero(conn->connectionIp6, 16)) {
  275. Dict_putString(addresses,
  276. String_CONST("ip6"),
  277. String_newBinary((char*)conn->connectionIp6, 16, requestAlloc),
  278. requestAlloc);
  279. Dict_putInt(addresses,
  280. String_CONST("ip6Prefix"), (int64_t)conn->connectionIp6Prefix,
  281. requestAlloc);
  282. noAddresses = false;
  283. }
  284. if (!Bits_isZero(conn->connectionIp4, 4)) {
  285. Dict_putString(addresses,
  286. String_CONST("ip4"),
  287. String_newBinary((char*)conn->connectionIp4, 4, requestAlloc),
  288. requestAlloc);
  289. Dict_putInt(addresses,
  290. String_CONST("ip4Prefix"), (int64_t)conn->connectionIp4Prefix,
  291. requestAlloc);
  292. noAddresses = false;
  293. }
  294. if (noAddresses) {
  295. Log_warn(context->logger, "no addresses to provide");
  296. return 0;
  297. }
  298. Dict* msg = Dict_new(requestAlloc);
  299. Dict_putDict(msg, String_CONST("addresses"), addresses, requestAlloc);
  300. String* txid = Dict_getString(request, String_CONST("txid"));
  301. if (txid) {
  302. Dict_putString(msg, String_CONST("txid"), txid, requestAlloc);
  303. }
  304. return sendControlMessage(msg, conn, requestAlloc, context);
  305. }
  306. static void addAddressCallback(Dict* responseMessage, void* vcontext)
  307. {
  308. struct IpTunnel_pvt* ctx = Identity_check((struct IpTunnel_pvt*) vcontext);
  309. char* err = "invalid response";
  310. String* error = Dict_getString(responseMessage, String_CONST("error"));
  311. if (error) {
  312. err = error->bytes;
  313. }
  314. if (!error || !String_equals(error, String_CONST("none"))) {
  315. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", err);
  316. #ifndef Log_ERROR
  317. // this whole function does essentially nothing but log an error so unused vars.
  318. err = err;
  319. ctx = ctx;
  320. #endif
  321. }
  322. }
  323. static void addAddress(char* printedAddr, uint8_t prefixLen, struct IpTunnel_pvt* ctx)
  324. {
  325. if (!ctx->ifName) {
  326. Log_error(ctx->logger, "Failed to set IP address because TUN interface is not setup");
  327. return;
  328. }
  329. struct Jmp j;
  330. Jmp_try(j) {
  331. Dict args = Dict_CONST(
  332. String_CONST("address"), String_OBJ(String_CONST(printedAddr)), Dict_CONST(
  333. String_CONST("interfaceName"), String_OBJ(ctx->ifName), Dict_CONST(
  334. String_CONST("prefixLen"), Int_OBJ(prefixLen), NULL
  335. )));
  336. Dict msg = Dict_CONST(
  337. String_CONST("args"), Dict_OBJ(&args), Dict_CONST(
  338. String_CONST("q"), String_OBJ(String_CONST("Angel_addIp")), NULL
  339. ));
  340. Hermes_callAngel(&msg, addAddressCallback, ctx, ctx->allocator, &j.handler, ctx->hermes);
  341. } Jmp_catch {
  342. Log_error(ctx->logger, "Error setting ip address on TUN [%s]", j.message);
  343. }
  344. }
  345. static int incomingAddresses(Dict* d,
  346. struct IpTunnel_Connection* conn,
  347. struct Allocator* alloc,
  348. struct IpTunnel_pvt* context)
  349. {
  350. if (!conn->isOutgoing) {
  351. Log_warn(context->logger, "got offer of addresses from incoming connection");
  352. return Error_INVALID;
  353. }
  354. String* txid = Dict_getString(d, String_CONST("txid"));
  355. if (!txid || txid->len != 4) {
  356. Log_info(context->logger, "missing or wrong length txid");
  357. return Error_INVALID;
  358. }
  359. int number;
  360. Bits_memcpyConst(&number, txid->bytes, 4);
  361. if (number < 0 || number >= (int)context->nextConnectionNumber) {
  362. Log_info(context->logger, "txid out of range");
  363. return Error_INVALID;
  364. }
  365. if (number != conn->number) {
  366. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  367. if (context->pub.connectionList.connections[i].number == number) {
  368. if (Bits_memcmp(conn->header.nodeKey,
  369. context->pub.connectionList.connections[i].header.nodeKey,
  370. 32))
  371. {
  372. Log_info(context->logger, "txid doesn't match origin");
  373. return Error_INVALID;
  374. } else {
  375. conn = &context->pub.connectionList.connections[i];
  376. }
  377. }
  378. }
  379. }
  380. Dict* addresses = Dict_getDict(d, String_CONST("addresses"));
  381. String* ip4 = Dict_getString(addresses, String_CONST("ip4"));
  382. int64_t* ip4Prefix = Dict_getInt(addresses, String_CONST("ip4Prefix"));
  383. if (ip4 && ip4->len == 4) {
  384. Bits_memcpyConst(conn->connectionIp4, ip4->bytes, 4);
  385. if (ip4Prefix && *ip4Prefix >= 0 && *ip4Prefix <= 32) {
  386. conn->connectionIp4Prefix = (uint8_t) *ip4Prefix;
  387. } else {
  388. conn->connectionIp4Prefix = 0;
  389. }
  390. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
  391. uint8_t* addrBytes = NULL;
  392. Sockaddr_getAddress(sa, &addrBytes);
  393. Bits_memcpy(addrBytes, ip4->bytes, 4);
  394. char* printedAddr = Sockaddr_print(sa, alloc);
  395. Log_info(context->logger, "Got issued address [%s/%d] for connection [%d]",
  396. printedAddr, conn->connectionIp4Prefix, conn->number);
  397. addAddress(printedAddr, conn->connectionIp4Prefix, context);
  398. }
  399. String* ip6 = Dict_getString(addresses, String_CONST("ip6"));
  400. int64_t* ip6Prefix = Dict_getInt(addresses, String_CONST("ip6Prefix"));
  401. if (ip6 && ip6->len == 16) {
  402. Bits_memcpyConst(conn->connectionIp6, ip6->bytes, 16);
  403. if (ip6Prefix && *ip6Prefix >= 0 && *ip6Prefix <= 128) {
  404. conn->connectionIp6Prefix = (uint8_t) *ip6Prefix;
  405. } else {
  406. conn->connectionIp6Prefix = 0;
  407. }
  408. #ifdef Darwin
  409. if (conn->connectionIp6Prefix < 3) {
  410. // Apple doesn't handle prefix length of 0 properly. 3 covers
  411. // all IPv6 unicast space.
  412. conn->connectionIp6Prefix = 3;
  413. }
  414. #endif
  415. struct Sockaddr* sa = Sockaddr_clone(Sockaddr_LOOPBACK6, alloc);
  416. uint8_t* addrBytes = NULL;
  417. Sockaddr_getAddress(sa, &addrBytes);
  418. Bits_memcpy(addrBytes, ip6->bytes, 16);
  419. char* printedAddr = Sockaddr_print(sa, alloc);
  420. Log_info(context->logger, "Got issued address [%s/%d] for connection [%d]",
  421. printedAddr, conn->connectionIp6Prefix, conn->number);
  422. addAddress(printedAddr, conn->connectionIp6Prefix, context);
  423. }
  424. return 0;
  425. }
  426. static uint8_t incomingControlMessage(struct Message* message,
  427. struct IpTunnel_Connection* conn,
  428. struct IpTunnel_pvt* context)
  429. {
  430. #ifdef Log_DEBUG
  431. uint8_t addr[40];
  432. AddrTools_printIp(addr, conn->header.nodeIp6Addr);
  433. Log_debug(context->logger, "Got incoming message from [%s]", addr);
  434. #endif
  435. // This aligns the message on the content.
  436. if (isControlMessageInvalid(message, context)) {
  437. return Error_INVALID;
  438. }
  439. #ifdef Log_DEBUG
  440. uint8_t lastChar = message->bytes[message->length - 1];
  441. message->bytes[message->length - 1] = '\0';
  442. Log_debug(context->logger, "Message content [%s%c]", message->bytes, lastChar);
  443. message->bytes[message->length - 1] = lastChar;
  444. #endif
  445. struct Allocator* alloc = Allocator_child(message->alloc);
  446. Dict* d = NULL;
  447. char* err = BencMessageReader_readNoExcept(message, alloc, &d);
  448. if (err) {
  449. Log_info(context->logger, "Failed to parse message [%s]", err);
  450. return Error_INVALID;
  451. }
  452. if (Dict_getDict(d, String_CONST("addresses"))) {
  453. return incomingAddresses(d, conn, alloc, context);
  454. }
  455. if (String_equals(String_CONST("IpTunnel_getAddresses"),
  456. Dict_getString(d, String_CONST("q"))))
  457. {
  458. return requestForAddresses(d, conn, alloc, context);
  459. }
  460. Log_warn(context->logger, "Message which is unhandled");
  461. return Error_INVALID;
  462. }
  463. /**
  464. * If there are multiple connections to the same server,
  465. * the ip address on the packet might belong to the wrong one.
  466. * In that case we get the right connection.
  467. * If the other party has sent a packet from an address which is not
  468. * valid, this will return NULL and their packet can be dropped.
  469. *
  470. * @param conn the connection which matches the other node's key.
  471. * @param sourceAndDestIp6 the source and destination IPv6 addresses,
  472. * must be NULL if sourceAndDestIp4 is specified.
  473. * @param sourceAndDestIp4 the source and destination IPv4 addresses.
  474. * must be NULL if sourceAndDestIp6 is specified.
  475. * @param context
  476. * @return the real connection or null if the packet is invalid.
  477. */
  478. static struct IpTunnel_Connection* getConnection(struct IpTunnel_Connection* conn,
  479. uint8_t sourceAndDestIp6[32],
  480. uint8_t sourceAndDestIp4[8],
  481. bool isFromTun,
  482. struct IpTunnel_pvt* context)
  483. {
  484. uint8_t* source = (sourceAndDestIp6) ? sourceAndDestIp6 : sourceAndDestIp4;
  485. uint32_t length = (sourceAndDestIp6) ? 16 : 4;
  486. uint8_t* destination = source + length;
  487. if (sourceAndDestIp6) {
  488. // never allowed
  489. if (source[0] == 0xfc || destination[0] == 0xfc) {
  490. return NULL;
  491. }
  492. }
  493. struct IpTunnel_Connection* lastConnection =
  494. &context->pub.connectionList.connections[context->pub.connectionList.count];
  495. do {
  496. // If this is an incoming message from the w0rld, and we're the client, we want
  497. // to make sure it's addressed to us (destination), if we're the server we want to make
  498. // sure our clients are using the addresses we gave them (source).
  499. //
  500. // If this is an outgoing message from the TUN, we just want to find a sutable server to
  501. // handle it. The behavior of this function relies on the fact that all incoming
  502. // connections are first on the list.
  503. //
  504. uint8_t* compareAddr = (isFromTun)
  505. ? ((conn->isOutgoing) ? source : destination)
  506. : ((conn->isOutgoing) ? destination : source);
  507. uint8_t* connectionAddr = (sourceAndDestIp6) ? conn->connectionIp6 : conn->connectionIp4;
  508. if (!Bits_memcmp(compareAddr, connectionAddr, length)) {
  509. return conn;
  510. }
  511. conn++;
  512. } while (conn <= lastConnection);
  513. return NULL;
  514. }
  515. static uint8_t incomingFromTun(struct Message* message, struct Interface* tunIf)
  516. {
  517. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunIf);
  518. if (message->length < 20) {
  519. Log_debug(context->logger, "Dropping runt.");
  520. }
  521. struct IpTunnel_Connection* conn = NULL;
  522. if (!context->pub.connectionList.connections) {
  523. // No connections authorized, fall through to "unrecognized address"
  524. } else if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  525. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  526. conn = getConnection(context->pub.connectionList.connections,
  527. header->sourceAddr,
  528. NULL,
  529. true,
  530. context);
  531. } else if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  532. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  533. conn = getConnection(context->pub.connectionList.connections,
  534. NULL,
  535. header->sourceAddr,
  536. true,
  537. context);
  538. } else {
  539. Log_info(context->logger, "Message of unknown type from TUN");
  540. return Error_INVALID;
  541. }
  542. if (!conn) {
  543. Log_info(context->logger, "Message with unrecognized address from TUN");
  544. return Error_INVALID;
  545. }
  546. return sendToNode(message, conn, context);
  547. }
  548. static uint8_t ip6FromNode(struct Message* message,
  549. struct IpTunnel_Connection* conn,
  550. struct IpTunnel_pvt* context)
  551. {
  552. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  553. if (Bits_isZero(header->sourceAddr, 16) || Bits_isZero(header->destinationAddr, 16)) {
  554. if (Bits_isZero(header->sourceAddr, 32)) {
  555. return incomingControlMessage(message, conn, context);
  556. }
  557. Log_debug(context->logger, "Got message with zero address");
  558. return Error_INVALID;
  559. }
  560. if (!getConnection(conn, header->sourceAddr, NULL, false, context)) {
  561. Log_debug(context->logger, "Got message with wrong address for connection");
  562. return Error_INVALID;
  563. }
  564. TUNMessageType_push(message, Ethernet_TYPE_IP6, NULL);
  565. struct Interface* tunIf = &context->pub.tunInterface;
  566. if (tunIf->receiveMessage) {
  567. tunIf->receiveMessage(message, tunIf);
  568. }
  569. return 0;
  570. }
  571. static uint8_t ip4FromNode(struct Message* message,
  572. struct IpTunnel_Connection* conn,
  573. struct IpTunnel_pvt* context)
  574. {
  575. struct Headers_IP4Header* header = (struct Headers_IP4Header*) message->bytes;
  576. if (Bits_isZero(header->sourceAddr, 4) || Bits_isZero(header->destAddr, 4)) {
  577. Log_debug(context->logger, "Got message with zero address");
  578. return Error_INVALID;
  579. }
  580. if (!getConnection(conn, NULL, header->sourceAddr, false, context)) {
  581. Log_debug(context->logger, "Got message with wrong address for connection");
  582. return Error_INVALID;
  583. }
  584. TUNMessageType_push(message, Ethernet_TYPE_IP4, NULL);
  585. struct Interface* tunIf = &context->pub.tunInterface;
  586. if (tunIf->receiveMessage) {
  587. return tunIf->receiveMessage(message, tunIf);
  588. }
  589. return 0;
  590. }
  591. static uint8_t incomingFromNode(struct Message* message, struct Interface* nodeIf)
  592. {
  593. struct IpTunnel_pvt* context =
  594. (struct IpTunnel_pvt*)(((char*)nodeIf) - offsetof(struct IpTunnel, nodeInterface));
  595. Identity_check(context);
  596. //Log_debug(context->logger, "Got incoming message");
  597. Assert_true(message->length >= IpTunnel_PacketInfoHeader_SIZE);
  598. struct IpTunnel_PacketInfoHeader* header = (struct IpTunnel_PacketInfoHeader*) message->bytes;
  599. struct IpTunnel_Connection* conn = connectionByPubKey(header->nodeKey, context);
  600. if (!conn) {
  601. #ifdef Log_DEBUG
  602. uint8_t addr[40];
  603. AddrTools_printIp(addr, header->nodeIp6Addr);
  604. Log_debug(context->logger, "Got message from unrecognized node [%s]", addr);
  605. #endif
  606. return 0;
  607. }
  608. Message_shift(message, -IpTunnel_PacketInfoHeader_SIZE, NULL);
  609. if (message->length > 40 && Headers_getIpVersion(message->bytes) == 6) {
  610. return ip6FromNode(message, conn, context);
  611. }
  612. if (message->length > 20 && Headers_getIpVersion(message->bytes) == 4) {
  613. return ip4FromNode(message, conn, context);
  614. }
  615. #ifdef Log_DEBUG
  616. uint8_t addr[40];
  617. AddrTools_printIp(addr, header->nodeIp6Addr);
  618. Log_debug(context->logger,
  619. "Got message of unknown type, length: [%d], IP version [%d] from [%s]",
  620. message->length,
  621. (message->length > 1) ? Headers_getIpVersion(message->bytes) : 0,
  622. addr);
  623. #endif
  624. return 0;
  625. }
  626. static void timeout(void* vcontext)
  627. {
  628. struct IpTunnel_pvt* context = vcontext;
  629. if (!context->pub.connectionList.count) {
  630. return;
  631. }
  632. Log_debug(context->logger, "Checking for connections to poll. Total connections [%u]",
  633. context->pub.connectionList.count);
  634. uint32_t beginning = Random_uint32(context->rand) % context->pub.connectionList.count;
  635. uint32_t i = beginning;
  636. do {
  637. Assert_true(i < context->pub.connectionList.count);
  638. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  639. if (conn->isOutgoing
  640. && Bits_isZero(conn->connectionIp6, 16)
  641. && Bits_isZero(conn->connectionIp4, 4))
  642. {
  643. requestAddresses(conn, context);
  644. break;
  645. }
  646. i = (i + 1) % context->pub.connectionList.count;
  647. } while (i != beginning);
  648. }
  649. void IpTunnel_setTunName(char* interfaceName, struct IpTunnel* ipTun)
  650. {
  651. struct IpTunnel_pvt* ctx = Identity_check((struct IpTunnel_pvt*) ipTun);
  652. ctx->ifName = String_new(interfaceName, ctx->allocator);
  653. }
  654. struct IpTunnel* IpTunnel_new(struct Log* logger,
  655. struct EventBase* eventBase,
  656. struct Allocator* alloc,
  657. struct Random* rand,
  658. struct Hermes* hermes)
  659. {
  660. struct IpTunnel_pvt* context = Allocator_clone(alloc, (&(struct IpTunnel_pvt) {
  661. .pub = {
  662. .tunInterface = { .sendMessage = incomingFromTun },
  663. .nodeInterface = { .sendMessage = incomingFromNode }
  664. },
  665. .allocator = alloc,
  666. .logger = logger,
  667. .rand = rand,
  668. .hermes = hermes
  669. }));
  670. context->timeout = Timeout_setInterval(timeout, context, 10000, eventBase, alloc);
  671. Identity_set(context);
  672. return &context->pub;
  673. }