IpTunnel.c 30 KB

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