IpTunnel.c 29 KB

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