IpTunnel.c 32 KB

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