IpTunnel.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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/serialization/standard/BencMessageWriter.h"
  18. #include "benc/serialization/standard/BencMessageReader.h"
  19. #include "crypto/AddressCalc.h"
  20. #include "crypto/random/Random.h"
  21. #include "interface/tuntap/TUNMessageType.h"
  22. #include "memory/Allocator.h"
  23. #include "tunnel/IpTunnel.h"
  24. #include "rust/cjdns_sys/RTypes.h"
  25. #include "rust/cjdns_sys/Rffi.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(Message_t* message,
  170. struct IpTunnel_Connection* connection,
  171. struct IpTunnel_pvt* context)
  172. {
  173. Err(Message_epush(message, NULL, DataHeader_SIZE));
  174. struct DataHeader* dh = (struct DataHeader*) Message_bytes(message);
  175. DataHeader_setContentType(dh, ContentType_IPTUN);
  176. DataHeader_setVersion(dh, DataHeader_CURRENT_VERSION);
  177. Err(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. Message_t* msg = Message_new(0, 1024, requestAlloc);
  186. Err_assert(BencMessageWriter_write(dict, msg));
  187. int length = Message_getLength(msg);
  188. // do UDP header.
  189. Err_assert(Message_eshift(msg, Headers_UDPHeader_SIZE));
  190. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) Message_bytes(msg);
  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. Err_assert(Message_eshift(msg, Headers_IP6Header_SIZE));
  197. struct Headers_IP6Header* header = (struct Headers_IP6Header*) Message_bytes(msg);
  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(Message_t* message, struct IpTunnel_pvt* context)
  272. {
  273. struct Headers_IP6Header* header = (struct Headers_IP6Header*) Message_bytes(message);
  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. Err_assert(Message_eshift(message, -Headers_IP6Header_SIZE));
  280. struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) Message_bytes(message);
  281. if (Checksum_udpIp6_be(header->sourceAddr, Message_bytes(message), 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. Err_assert(Message_eshift(message, -Headers_UDPHeader_SIZE));
  294. Err_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. RTypes_Error_t* er = NetDev_addAddress(tunName->bytes, &ss.addr, ctx->logger, tempAlloc);
  370. if (er) {
  371. Log_error(ctx->logger, "Error setting ip address on TUN [%s]",
  372. Rffi_printError(er, tempAlloc));
  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. Err(RouteGen_commit(context->rg, tunName->bytes, alloc));
  481. }
  482. return NULL;
  483. }
  484. static Iface_DEFUN incomingControlMessage(Message_t* message,
  485. struct IpTunnel_Connection* conn,
  486. struct IpTunnel_pvt* context)
  487. {
  488. if (Defined(Log_DEBUG)) {
  489. uint8_t addr[40];
  490. AddrTools_printIp(addr, conn->routeHeader.ip6);
  491. Log_debug(context->logger, "Got incoming message from [%s]", addr);
  492. }
  493. // This aligns the message on the content.
  494. if (isControlMessageInvalid(message, context)) {
  495. return Error(message, "INVALID");
  496. }
  497. Log_debug(context->logger, "Message content [%s]",
  498. Escape_getEscaped(Message_bytes(message), Message_getLength(message), Message_getAlloc(message)));
  499. struct Allocator* alloc = Allocator_child(Message_getAlloc(message));
  500. Dict* d = NULL;
  501. const char* err = BencMessageReader_readNoExcept(message, alloc, &d);
  502. if (err) {
  503. Log_info(context->logger, "Failed to parse message [%s]", err);
  504. return Error(message, "INVALID");
  505. }
  506. if (Dict_getDictC(d, "addresses")) {
  507. return incomingAddresses(d, conn, alloc, context);
  508. }
  509. if (String_equals(String_CONST("IpTunnel_getAddresses"),
  510. Dict_getStringC(d, "q")))
  511. {
  512. return requestForAddresses(d, conn, alloc, context);
  513. }
  514. Log_warn(context->logger, "Message which is unhandled");
  515. return Error(message, "INVALID");
  516. }
  517. #define GET64(buffer) \
  518. (__extension__ ({ \
  519. Assert_true(!((uintptr_t)(buffer) % 4)); \
  520. uint64_t x = (uint64_t) (((uint32_t*)(buffer))[0]); \
  521. x |= (( (uint64_t) ((uint32_t*)(buffer))[1]) << 32); \
  522. Endian_bigEndianToHost64(x); \
  523. }))
  524. #define GET32(buffer) \
  525. (__extension__ ({ \
  526. Assert_true(!((uintptr_t)(buffer) % 4)); \
  527. uint32_t x = (((uint32_t*)(buffer))[0]); \
  528. Endian_bigEndianToHost32(x); \
  529. }))
  530. static bool prefixMatches6(uint8_t* addressA, uint8_t* refAddr, uint8_t prefixLen)
  531. {
  532. if (!prefixLen) {
  533. Assert_true(Bits_isZero(refAddr, 16));
  534. return false;
  535. }
  536. Assert_true(prefixLen && prefixLen <= 128);
  537. uint64_t a0 = GET64(addressA);
  538. uint64_t b0 = GET64(refAddr);
  539. if (prefixLen <= 64) {
  540. return !( (a0 ^ b0) >> (64 - prefixLen) );
  541. }
  542. uint64_t a1 = GET64(addressA + 8);
  543. uint64_t b1 = GET64(refAddr + 8);
  544. return !( (a0 ^ b0) | ((a1 ^ b1) >> (128 - prefixLen)) );
  545. }
  546. static bool prefixMatches4(uint8_t* addressA, uint8_t* refAddr, uint32_t prefixLen)
  547. {
  548. if (!prefixLen) {
  549. Assert_true(Bits_isZero(refAddr, 4));
  550. return false;
  551. }
  552. Assert_true(prefixLen && prefixLen <= 32);
  553. uint32_t a = GET32(addressA);
  554. uint32_t b = GET32(refAddr);
  555. return !((a ^ b) >> (32 - prefixLen));
  556. }
  557. static bool isValidAddress4(uint8_t sourceIp4[4],
  558. uint8_t destIp4[4],
  559. bool isFromTun,
  560. struct IpTunnel_Connection* conn)
  561. {
  562. uint8_t* compareAddr = (isFromTun)
  563. ? ((conn->isOutgoing) ? sourceIp4 : destIp4)
  564. : ((conn->isOutgoing) ? destIp4 : sourceIp4);
  565. return prefixMatches4(compareAddr, conn->connectionIp4, conn->connectionIp4Alloc);
  566. }
  567. static bool isValidAddress6(uint8_t sourceIp6[16],
  568. uint8_t destIp6[16],
  569. bool isFromTun,
  570. struct IpTunnel_Connection* conn)
  571. {
  572. if (AddressCalc_validAddress(sourceIp6) || AddressCalc_validAddress(destIp6)) {
  573. return false;
  574. }
  575. uint8_t* compareAddr = (isFromTun)
  576. ? ((conn->isOutgoing) ? sourceIp6 : destIp6)
  577. : ((conn->isOutgoing) ? destIp6 : sourceIp6);
  578. return prefixMatches6(compareAddr, conn->connectionIp6, conn->connectionIp6Alloc);
  579. }
  580. static struct IpTunnel_Connection* findConnection(uint8_t sourceIp6[16],
  581. uint8_t destIp6[16],
  582. uint8_t sourceIp4[4],
  583. uint8_t destIp4[4],
  584. bool isFromTun,
  585. struct IpTunnel_pvt* context)
  586. {
  587. for (int i = 0; i < (int)context->pub.connectionList.count; i++) {
  588. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  589. if (sourceIp6 && destIp6 && isValidAddress6(sourceIp6, destIp6, isFromTun, conn)) {
  590. return conn;
  591. }
  592. if (sourceIp4 && destIp4 && isValidAddress4(sourceIp4, destIp4, isFromTun, conn)) {
  593. return conn;
  594. }
  595. }
  596. return NULL;
  597. }
  598. static Iface_DEFUN incomingFromTun(Message_t* message, struct Iface* tunIf)
  599. {
  600. struct IpTunnel_pvt* context = Identity_check((struct IpTunnel_pvt*)tunIf);
  601. if (Message_getLength(message) < 20) {
  602. Log_debug(context->logger, "DROP runt");
  603. return Error(message, "RUNT");
  604. }
  605. struct IpTunnel_Connection* conn = NULL;
  606. if (!context->pub.connectionList.connections) {
  607. // No connections authorized, fall through to "unrecognized address"
  608. } else if (Message_getLength(message) > 40 && Headers_getIpVersion(Message_bytes(message)) == 6) {
  609. struct Headers_IP6Header* header = (struct Headers_IP6Header*) Message_bytes(message);
  610. conn = findConnection(
  611. header->sourceAddr, header->destinationAddr, NULL, NULL, true, context);
  612. } else if (Message_getLength(message) > 20 && Headers_getIpVersion(Message_bytes(message)) == 4) {
  613. struct Headers_IP4Header* header = (struct Headers_IP4Header*) Message_bytes(message);
  614. conn = findConnection(NULL, NULL, header->sourceAddr, header->destAddr, true, context);
  615. } else {
  616. Log_debug(context->logger, "Message of unknown type from TUN");
  617. return Error(message, "INVALID");
  618. }
  619. if (!conn) {
  620. Log_debug(context->logger, "Message with unrecognized address from TUN");
  621. return Error(message, "INVALID");
  622. }
  623. return sendToNode(message, conn, context);
  624. }
  625. static Iface_DEFUN ip6FromNode(Message_t* message,
  626. struct IpTunnel_Connection* conn,
  627. struct IpTunnel_pvt* context)
  628. {
  629. struct Headers_IP6Header* header = (struct Headers_IP6Header*) Message_bytes(message);
  630. if (Bits_isZero(header->sourceAddr, 16) || Bits_isZero(header->destinationAddr, 16)) {
  631. if (Bits_isZero(header->sourceAddr, 32)) {
  632. return incomingControlMessage(message, conn, context);
  633. }
  634. Log_debug(context->logger, "Got message with zero address");
  635. return Error(message, "INVALID");
  636. }
  637. if (!isValidAddress6(header->sourceAddr, header->destinationAddr, false, conn)) {
  638. uint8_t addr[40];
  639. AddrTools_printIp(addr, header->sourceAddr);
  640. Log_debug(context->logger, "Got message with wrong address for connection [%s]", addr);
  641. return Error(message, "INVALID");
  642. }
  643. Err(TUNMessageType_push(message, Ethernet_TYPE_IP6));
  644. return Iface_next(&context->pub.tunInterface, message);
  645. }
  646. static Iface_DEFUN ip4FromNode(Message_t* message,
  647. struct IpTunnel_Connection* conn,
  648. struct IpTunnel_pvt* context)
  649. {
  650. struct Headers_IP4Header* header = (struct Headers_IP4Header*) Message_bytes(message);
  651. if (Bits_isZero(header->sourceAddr, 4) || Bits_isZero(header->destAddr, 4)) {
  652. Log_debug(context->logger, "Got message with zero address");
  653. return Error(message, "INVALID");
  654. } else if (!isValidAddress4(header->sourceAddr, header->destAddr, false, conn)) {
  655. Log_debug(context->logger, "Got message with wrong address [%d.%d.%d.%d] for connection "
  656. "[%d.%d.%d.%d/%d:%d]",
  657. header->sourceAddr[0], header->sourceAddr[1],
  658. header->sourceAddr[2], header->sourceAddr[3],
  659. conn->connectionIp4[0], conn->connectionIp4[1],
  660. conn->connectionIp4[2], conn->connectionIp4[3],
  661. conn->connectionIp4Alloc, conn->connectionIp4Prefix);
  662. return Error(message, "INVALID");
  663. }
  664. Err(TUNMessageType_push(message, Ethernet_TYPE_IP4));
  665. return Iface_next(&context->pub.tunInterface, message);
  666. }
  667. static Iface_DEFUN incomingFromNode(Message_t* message, struct Iface* nodeIf)
  668. {
  669. struct IpTunnel_pvt* context =
  670. Identity_containerOf(nodeIf, struct IpTunnel_pvt, pub.nodeInterface);
  671. //Log_debug(context->logger, "Got incoming message");
  672. Assert_true(Message_getLength(message) >= RouteHeader_SIZE + DataHeader_SIZE);
  673. struct RouteHeader* rh = (struct RouteHeader*) Message_bytes(message);
  674. struct DataHeader* dh = (struct DataHeader*) &rh[1];
  675. Assert_true(DataHeader_getContentType(dh) == ContentType_IPTUN);
  676. struct IpTunnel_Connection* conn = connectionByPubKey(rh->publicKey, context);
  677. if (!conn) {
  678. if (Defined(Log_DEBUG)) {
  679. uint8_t addr[40];
  680. AddrTools_printIp(addr, rh->ip6);
  681. Log_debug(context->logger, "Got message from unrecognized node [%s]", addr);
  682. }
  683. return NULL;
  684. }
  685. Err(Message_eshift(message, -(RouteHeader_SIZE + DataHeader_SIZE)));
  686. if (Message_getLength(message) > 40 && Headers_getIpVersion(Message_bytes(message)) == 6) {
  687. return ip6FromNode(message, conn, context);
  688. }
  689. if (Message_getLength(message) > 20 && Headers_getIpVersion(Message_bytes(message)) == 4) {
  690. return ip4FromNode(message, conn, context);
  691. }
  692. if (Defined(Log_DEBUG)) {
  693. uint8_t addr[40];
  694. AddrTools_printIp(addr, rh->ip6);
  695. Log_debug(context->logger,
  696. "Got message of unknown type, length: [%d], IP version [%d] from [%s]",
  697. Message_getLength(message),
  698. (Message_getLength(message) > 1) ? Headers_getIpVersion(Message_bytes(message)) : 0,
  699. addr);
  700. }
  701. return Error(message, "INVALID");
  702. }
  703. static void timeout(void* vcontext)
  704. {
  705. struct IpTunnel_pvt* context = vcontext;
  706. if (!context->pub.connectionList.count) {
  707. return;
  708. }
  709. Log_debug(context->logger, "Checking for connections to poll. Total connections [%u]",
  710. context->pub.connectionList.count);
  711. uint32_t beginning = Random_uint32(context->rand) % context->pub.connectionList.count;
  712. uint32_t i = beginning;
  713. do {
  714. Assert_true(i < context->pub.connectionList.count);
  715. struct IpTunnel_Connection* conn = &context->pub.connectionList.connections[i];
  716. if (conn->isOutgoing
  717. && Bits_isZero(conn->connectionIp6, 16)
  718. && Bits_isZero(conn->connectionIp4, 4))
  719. {
  720. requestAddresses(conn, context);
  721. break;
  722. }
  723. i = (i + 1) % context->pub.connectionList.count;
  724. } while (i != beginning);
  725. }
  726. struct IpTunnel* IpTunnel_new(struct Log* logger,
  727. EventBase_t* eventBase,
  728. struct Allocator* alloc,
  729. struct Random* rand,
  730. struct RouteGen* rg,
  731. struct GlobalConfig* globalConf)
  732. {
  733. struct IpTunnel_pvt* context = Allocator_clone(alloc, (&(struct IpTunnel_pvt) {
  734. .pub = {
  735. .tunInterface = { .send = incomingFromTun },
  736. .nodeInterface = { .send = incomingFromNode }
  737. },
  738. .allocator = alloc,
  739. .logger = logger,
  740. .rand = rand,
  741. .rg = rg,
  742. .globalConf = globalConf
  743. }));
  744. context->timeout = Timeout_setInterval(timeout, context, 10000, eventBase, alloc);
  745. Identity_set(context);
  746. return &context->pub;
  747. }