Ducttape.c 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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 "crypto/AddressCalc.h"
  16. #include "crypto/CryptoAuth.h"
  17. #include "util/log/Log.h"
  18. #include "dht/Address.h"
  19. #include "dht/DHTMessage.h"
  20. #include "dht/DHTModule.h"
  21. #include "dht/DHTModuleRegistry.h"
  22. #include "dht/dhtcore/Node.h"
  23. #include "dht/dhtcore/RouterModule.h"
  24. #include "dht/dhtcore/SearchRunner.h"
  25. #include "dht/dhtcore/RumorMill.h"
  26. #include "interface/tuntap/TUNMessageType.h"
  27. #include "interface/Interface.h"
  28. #include "interface/SessionManager.h"
  29. #include "util/log/Log.h"
  30. #include "memory/Allocator.h"
  31. #include "net/Ducttape_pvt.h"
  32. #include "switch/SwitchCore.h"
  33. #include "switch/LabelSplicer.h"
  34. #include "util/AddrTools.h"
  35. #include "util/Bits.h"
  36. #include "util/Checksum.h"
  37. #include "util/version/Version.h"
  38. #include "util/Assert.h"
  39. #include "tunnel/IpTunnel.h"
  40. #include "util/events/Time.h"
  41. #include "wire/Control.h"
  42. #include "wire/Error.h"
  43. #include "wire/Headers.h"
  44. #include "wire/Ethernet.h"
  45. #include <stdint.h>
  46. /** Size of the per-message workspace. */
  47. #define PER_MESSAGE_BUF_SZ 8192
  48. #define FC_ONE "\xfc\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1"
  49. /**
  50. * In order to easily tell the incoming connection requests from messages which
  51. * are addressed to a specific interface by its handle, the most significant bit
  52. * in the big endian representation of the handle shall be cleared to indicate
  53. * that a session is new and set otherwise.
  54. */
  55. #define HANDLE_FLAG_BIT (0x80000000)
  56. #define HANDLE_FLAG_BIT_be Endian_hostToBigEndian32(HANDLE_FLAG_BIT)
  57. /*--------------------Prototypes--------------------*/
  58. static int handleOutgoing(struct DHTMessage* message,
  59. void* vcontext);
  60. static inline uint8_t incomingDHT(struct Message* message,
  61. struct Address* addr,
  62. struct Ducttape_pvt* context)
  63. {
  64. struct DHTMessage dht = {
  65. .address = addr,
  66. .binMessage = message,
  67. .allocator = message->alloc
  68. };
  69. DHTModuleRegistry_handleIncoming(&dht, context->registry);
  70. // TODO: return something meaningful.
  71. return Error_NONE;
  72. }
  73. /** Header must not be encrypted and must be aligned on the beginning of the ipv6 header. */
  74. static inline uint8_t sendToRouter(struct Message* message,
  75. struct Ducttape_MessageHeader* dtHeader,
  76. struct SessionManager_Session* session,
  77. struct Ducttape_pvt* context)
  78. {
  79. int safeDistance = Headers_SwitchHeader_SIZE;
  80. CryptoAuth_resetIfTimeout(session->internal);
  81. if (CryptoAuth_getState(session->internal) < CryptoAuth_HANDSHAKE3) {
  82. // Bug 104, see Version.h
  83. #ifdef Version_2_COMPAT
  84. if (session->version >= 3) {
  85. #endif
  86. // Put the handle into the message so that it's authenticated.
  87. // see: sendToSwitch()
  88. //Log_debug(context->logger, "Sending receive handle under CryptoAuth");
  89. Message_push(message, &session->receiveHandle_be, 4, NULL);
  90. #ifdef Version_2_COMPAT
  91. } else {
  92. // Otherwise it will be added on the other side.
  93. safeDistance += 4;
  94. }
  95. #endif
  96. safeDistance += Headers_CryptoAuth_SIZE;
  97. } else {
  98. // 16 for the authenticator, 4 for the nonce and 4 for the handle
  99. safeDistance += 24;
  100. }
  101. Message_shift(message, safeDistance, NULL);
  102. if (dtHeader->switchHeader) {
  103. if (message->bytes != (uint8_t*)dtHeader->switchHeader) {
  104. Bits_memmoveConst(message->bytes, dtHeader->switchHeader, Headers_SwitchHeader_SIZE);
  105. dtHeader->switchHeader = (struct Headers_SwitchHeader*) message->bytes;
  106. }
  107. } else {
  108. dtHeader->switchHeader = (struct Headers_SwitchHeader*) message->bytes;
  109. Bits_memset(dtHeader->switchHeader, 0, Headers_SwitchHeader_SIZE);
  110. }
  111. Message_shift(message, -safeDistance, NULL);
  112. dtHeader->switchHeader->label_be = Endian_hostToBigEndian64(dtHeader->switchLabel);
  113. // This comes out in outgoingFromCryptoAuth() then sendToSwitch()
  114. dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
  115. dtHeader->layer = Ducttape_SessionLayer_OUTER;
  116. return Interface_sendMessage(session->internal, message);
  117. }
  118. static struct Ducttape_MessageHeader* getDtHeader(struct Message* message, bool init)
  119. {
  120. int padding = message->padding;
  121. Assert_true(padding > Ducttape_MessageHeader_SIZE);
  122. Message_shift(message, padding, NULL);
  123. struct Ducttape_MessageHeader* dtHeader = (struct Ducttape_MessageHeader*) message->bytes;
  124. Message_shift(message, -padding, NULL);
  125. if (init) {
  126. Bits_memset(dtHeader, 0, Ducttape_MessageHeader_SIZE);
  127. Identity_set(dtHeader);
  128. } else {
  129. Identity_check(dtHeader);
  130. }
  131. return dtHeader;
  132. }
  133. static int handleOutgoing(struct DHTMessage* dmessage,
  134. void* vcontext)
  135. {
  136. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) vcontext);
  137. // Stub out all of the crypto code because setting up a CA session
  138. // with yourself causes problems.
  139. if (dmessage->address->path == 1) {
  140. struct Allocator* alloc = Allocator_child(context->alloc);
  141. Allocator_adopt(alloc, dmessage->binMessage->alloc);
  142. incomingDHT(dmessage->binMessage, dmessage->address, context);
  143. Allocator_free(alloc);
  144. return 0;
  145. }
  146. struct Message* msg = dmessage->binMessage;
  147. {
  148. Message_push(msg, (&(struct Headers_UDPHeader) {
  149. .srcPort_be = 0,
  150. .destPort_be = 0,
  151. .length_be = Endian_hostToBigEndian16(msg->length),
  152. .checksum_be = 0,
  153. }), Headers_UDPHeader_SIZE, NULL);
  154. }
  155. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) msg->bytes;
  156. {
  157. struct Headers_IP6Header ip = {
  158. .versionClassAndFlowLabel = 0,
  159. .flowLabelLow_be = 0,
  160. .nextHeader = 17,
  161. .hopLimit = 0,
  162. .payloadLength_be = Endian_hostToBigEndian16(msg->length),
  163. .sourceAddr = {0}
  164. };
  165. Bits_memcpyConst(ip.sourceAddr,
  166. context->myAddr.ip6.bytes,
  167. Address_SEARCH_TARGET_SIZE);
  168. Bits_memcpyConst(ip.destinationAddr,
  169. dmessage->address->ip6.bytes,
  170. Address_SEARCH_TARGET_SIZE);
  171. Message_push(msg, &ip, Headers_IP6Header_SIZE, NULL);
  172. }
  173. struct Headers_IP6Header* ip = (struct Headers_IP6Header*) msg->bytes;
  174. Assert_true(!((uintptr_t)msg->bytes % 4) || !"alignment fault");
  175. uh->checksum_be = Checksum_udpIp6(ip->sourceAddr,
  176. (uint8_t*) uh,
  177. msg->length - Headers_IP6Header_SIZE);
  178. struct Ducttape_MessageHeader* dtHeader = getDtHeader(msg, true);
  179. dtHeader->ip6Header = ip;
  180. dtHeader->switchLabel = dmessage->address->path;
  181. struct SessionManager_Session* session =
  182. SessionManager_getSession(dmessage->address->ip6.bytes,
  183. dmessage->address->key,
  184. context->sm);
  185. session->version = dmessage->address->protocolVersion;
  186. Assert_true(session->version);
  187. sendToRouter(msg, dtHeader, session, context);
  188. return 0;
  189. }
  190. // Aligned on the beginning of the content.
  191. static inline bool isRouterTraffic(struct Message* message, struct Headers_IP6Header* ip6)
  192. {
  193. if (ip6->nextHeader != 17 || ip6->hopLimit != 0) {
  194. return false;
  195. }
  196. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) message->bytes;
  197. return message->length >= Headers_UDPHeader_SIZE
  198. && uh->srcPort_be == 0
  199. && uh->destPort_be == 0
  200. && (int) Endian_bigEndianToHost16(uh->length_be) ==
  201. (message->length - Headers_UDPHeader_SIZE);
  202. }
  203. #define debugHandles(logger, session, message, ...) \
  204. do { \
  205. uint8_t ip[40]; \
  206. AddrTools_printIp(ip, session->ip6); \
  207. Log_debug(logger, "ver[%u] send[%d] recv[%u] ip[%s] " message, \
  208. session->version, \
  209. Endian_hostToBigEndian32(session->sendHandle_be), \
  210. Endian_hostToBigEndian32(session->receiveHandle_be), \
  211. ip, \
  212. __VA_ARGS__); \
  213. } while (0)
  214. //CHECKFILES_IGNORE expecting a ;
  215. #define debugHandles0(logger, session, message) \
  216. debugHandles(logger, session, message "%s", "")
  217. #define debugHandlesAndLabel(logger, session, label, message, ...) \
  218. do { \
  219. uint8_t path[20]; \
  220. AddrTools_printPath(path, label); \
  221. debugHandles(logger, session, "path[%s] " message, path, __VA_ARGS__); \
  222. } while (0)
  223. //CHECKFILES_IGNORE expecting a ;
  224. #define debugHandlesAndLabel0(logger, session, label, message) \
  225. debugHandlesAndLabel(logger, session, label, "%s", message)
  226. /**
  227. * Message which is for us, message is aligned on the beginning of the content.
  228. * this is called from core() which calls through an interfaceMap.
  229. */
  230. static inline uint8_t incomingForMe(struct Message* message,
  231. struct Ducttape_MessageHeader* dtHeader,
  232. struct SessionManager_Session* session,
  233. struct Ducttape_pvt* context,
  234. uint8_t herPublicKey[32])
  235. {
  236. struct Address addr = { .protocolVersion = session->version };
  237. //Bits_memcpyConst(addr.ip6.bytes, session->ip6, 16);
  238. Bits_memcpyConst(addr.key, herPublicKey, 32);
  239. AddressCalc_addressForPublicKey(addr.ip6.bytes, herPublicKey);
  240. Assert_always(!Bits_memcmp(session->ip6, addr.ip6.bytes, 16));
  241. if (Bits_memcmp(addr.ip6.bytes, dtHeader->ip6Header->sourceAddr, 16)) {
  242. #ifdef Log_DEBUG
  243. uint8_t keyAddr[40];
  244. Address_printIp(keyAddr, &addr);
  245. Bits_memcpyConst(addr.ip6.bytes, dtHeader->ip6Header->sourceAddr, 16);
  246. uint8_t srcAddr[40];
  247. Address_printIp(srcAddr, &addr);
  248. Log_debug(context->logger,
  249. "DROP packet because source address is not same as key.\n"
  250. " %s source addr\n"
  251. " %s hash of key\n",
  252. srcAddr,
  253. keyAddr);
  254. #endif
  255. return Error_INVALID;
  256. }
  257. if (isRouterTraffic(message, dtHeader->ip6Header)) {
  258. // Check the checksum.
  259. struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) message->bytes;
  260. if (Checksum_udpIp6(dtHeader->ip6Header->sourceAddr, (uint8_t*)uh, message->length)) {
  261. #ifdef Log_DEBUG
  262. uint8_t keyAddr[40];
  263. Address_printIp(keyAddr, &addr);
  264. Log_debug(context->logger,
  265. "DROP Router packet with incorrect checksum, from [%s]", keyAddr);
  266. #endif
  267. return Error_INVALID;
  268. }
  269. // Shift off the UDP header.
  270. Message_shift(message, -Headers_UDPHeader_SIZE, NULL);
  271. addr.path = Endian_bigEndianToHost64(dtHeader->switchHeader->label_be);
  272. Bits_memcpyConst(addr.key, herPublicKey, 32);
  273. return incomingDHT(message, &addr, context);
  274. }
  275. if (!context->userIf) {
  276. Log_warn(context->logger, "DROP packet because there is no router interface configured");
  277. return Error_UNDELIVERABLE;
  278. }
  279. // prevent router advertizement schenanigans
  280. if (dtHeader->ip6Header->hopLimit == 255) {
  281. dtHeader->ip6Header->hopLimit--;
  282. }
  283. // Now write a message to the TUN device.
  284. // Need to move the ipv6 header forward up to the content because there's a crypto header
  285. // between the ipv6 header and the content which just got eaten.
  286. Message_shift(message, Headers_IP6Header_SIZE, NULL);
  287. uint16_t sizeDiff = message->bytes - (uint8_t*)dtHeader->ip6Header;
  288. if (sizeDiff) {
  289. dtHeader->ip6Header->payloadLength_be =
  290. Endian_hostToBigEndian16(
  291. Endian_bigEndianToHost16(dtHeader->ip6Header->payloadLength_be) - sizeDiff);
  292. Bits_memmoveConst(message->bytes, dtHeader->ip6Header, Headers_IP6Header_SIZE);
  293. }
  294. TUNMessageType_push(message, Ethernet_TYPE_IP6, NULL);
  295. context->userIf->sendMessage(message, context->userIf);
  296. return Error_NONE;
  297. }
  298. uint8_t Ducttape_injectIncomingForMe(struct Message* message,
  299. struct Ducttape* dt,
  300. uint8_t herPublicKey[32])
  301. {
  302. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)dt);
  303. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
  304. struct Headers_SwitchHeader sh;
  305. Bits_memcpyConst(&sh, message->bytes, Headers_SwitchHeader_SIZE);
  306. dtHeader->switchHeader = &sh;
  307. Message_shift(message, -Headers_SwitchHeader_SIZE, NULL);
  308. struct Headers_IP6Header ip6;
  309. Bits_memcpyConst(&ip6, message->bytes, Headers_IP6Header_SIZE);
  310. dtHeader->ip6Header = &ip6;
  311. Message_shift(message, -Headers_IP6Header_SIZE, NULL);
  312. struct SessionManager_Session s;
  313. AddressCalc_addressForPublicKey(s.ip6, herPublicKey);
  314. s.version = Version_CURRENT_PROTOCOL;
  315. return incomingForMe(message, dtHeader, &s, context, herPublicKey);
  316. }
  317. /**
  318. * Send a message to another switch.
  319. * Switchheader will precede the message.
  320. */
  321. static inline uint8_t sendToSwitch(struct Message* message,
  322. struct Ducttape_MessageHeader* dtHeader,
  323. struct SessionManager_Session* session,
  324. struct Ducttape_pvt* context)
  325. {
  326. uint64_t label = dtHeader->switchLabel;
  327. CryptoAuth_resetIfTimeout(session->internal);
  328. if (CryptoAuth_getState(session->internal) >= CryptoAuth_HANDSHAKE3) {
  329. //debugHandlesAndLabel0(context->logger, session, label, "layer2 sending run message");
  330. uint32_t sendHandle_be = session->sendHandle_be;
  331. #ifdef Version_2_COMPAT
  332. if (session->version < 3) {
  333. sendHandle_be |= HANDLE_FLAG_BIT_be;
  334. }
  335. #endif
  336. Message_push(message, &sendHandle_be, 4, NULL);
  337. } else {
  338. debugHandlesAndLabel0(context->logger, session, label, "layer2 sending start message");
  339. #ifdef Version_2_COMPAT
  340. if (session->version < 3) {
  341. Message_push(message, &session->receiveHandle_be, 4, NULL);
  342. }
  343. #endif
  344. }
  345. Message_shift(message, Headers_SwitchHeader_SIZE, NULL);
  346. Assert_true(message->bytes == (uint8_t*)dtHeader->switchHeader);
  347. return context->switchInterface.receiveMessage(message, &context->switchInterface);
  348. }
  349. static inline bool validEncryptedIP6(struct Message* message)
  350. {
  351. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  352. // Empty ipv6 headers are tolerated at this stage but dropped later.
  353. return message->length >= Headers_IP6Header_SIZE
  354. && AddressCalc_validAddress(header->sourceAddr)
  355. && AddressCalc_validAddress(header->destinationAddr);
  356. }
  357. static inline bool isForMe(struct Message* message, struct Ducttape_pvt* context)
  358. {
  359. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  360. return (Bits_memcmp(header->destinationAddr, context->myAddr.ip6.bytes, 16) == 0);
  361. }
  362. static uint8_t magicInterfaceSendMessage(struct Message* msg, struct Interface* iface)
  363. {
  364. struct Ducttape_pvt* ctx =
  365. Identity_check((struct Ducttape_pvt*)
  366. &((uint8_t*)iface)[-offsetof(struct Ducttape, magicInterface)]);
  367. #ifdef PARANOIA
  368. Assert_true(msg->length >= Headers_IP6Header_SIZE);
  369. struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
  370. Assert_true(!Bits_memcmp(header->destinationAddr, ctx->myAddr.ip6.bytes, 16));
  371. Assert_true(!Bits_memcmp(header->sourceAddr, FC_ONE, 16));
  372. #endif
  373. TUNMessageType_push(msg, Ethernet_TYPE_IP6, NULL);
  374. if (ctx->userIf) {
  375. return Interface_sendMessage(ctx->userIf, msg);
  376. }
  377. return Error_NONE;
  378. }
  379. // Called by the TUN device.
  380. static inline uint8_t incomingFromTun(struct Message* message,
  381. struct Interface* iface)
  382. {
  383. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) iface->receiverContext);
  384. uint16_t ethertype = TUNMessageType_pop(message, NULL);
  385. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  386. int version = Headers_getIpVersion(message->bytes);
  387. if ((ethertype == Ethernet_TYPE_IP4 && version != 4)
  388. || (ethertype == Ethernet_TYPE_IP6 && version != 6))
  389. {
  390. Log_warn(context->logger, "DROP packet because ip version [%d] "
  391. "doesn't match ethertype [%u].", version, Endian_bigEndianToHost16(ethertype));
  392. return Error_INVALID;
  393. }
  394. if (ethertype != Ethernet_TYPE_IP6 || !AddressCalc_validAddress(header->sourceAddr)) {
  395. return context->ipTunnel->tunInterface.sendMessage(message,
  396. &context->ipTunnel->tunInterface);
  397. }
  398. if (Bits_memcmp(header->sourceAddr, context->myAddr.ip6.bytes, 16)) {
  399. uint8_t expectedSource[40];
  400. AddrTools_printIp(expectedSource, context->myAddr.ip6.bytes);
  401. uint8_t packetSource[40];
  402. AddrTools_printIp(packetSource, header->sourceAddr);
  403. Log_warn(context->logger,
  404. "DROP packet from [%s] because all messages must have source address [%s]",
  405. (char*) packetSource, (char*) expectedSource);
  406. return Error_INVALID;
  407. }
  408. if (!Bits_memcmp(header->destinationAddr, context->myAddr.ip6.bytes, 16)) {
  409. // I'm Gonna Sit Right Down and Write Myself a Letter
  410. TUNMessageType_push(message, ethertype, NULL);
  411. iface->sendMessage(message, iface);
  412. return Error_NONE;
  413. }
  414. if (!Bits_memcmp(header->destinationAddr, FC_ONE, 16)) {
  415. return Interface_receiveMessage(&context->pub.magicInterface, message);
  416. }
  417. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
  418. // Add destination to nodesOfInterest, so we can do something useful in the janitor.
  419. struct Address rumorAddr = { .path = 0 };
  420. Bits_memcpyConst(rumorAddr.ip6.bytes, header->destinationAddr, Address_SEARCH_TARGET_SIZE);
  421. RumorMill_addNode(context->nodesOfInterest, &rumorAddr);
  422. struct Node_Two* bestNext = RouterModule_lookup(header->destinationAddr, context->routerModule);
  423. struct SessionManager_Session* nextHopSession;
  424. if (bestNext) {
  425. nextHopSession = SessionManager_getSession(bestNext->address.ip6.bytes,
  426. bestNext->address.key,
  427. context->sm);
  428. bestNext->address.protocolVersion = nextHopSession->version =
  429. (bestNext->address.protocolVersion > nextHopSession->version)
  430. ? bestNext->address.protocolVersion : nextHopSession->version;
  431. dtHeader->switchLabel = bestNext->address.path;
  432. dtHeader->nextHopReceiveHandle = Endian_bigEndianToHost32(nextHopSession->receiveHandle_be);
  433. if (!Bits_memcmp(header->destinationAddr, bestNext->address.ip6.bytes, 16)) {
  434. // Direct send, skip the innermost layer of encryption.
  435. /*#ifdef Log_DEBUG
  436. uint8_t nhAddr[60];
  437. Address_print(nhAddr, &bestNext->address);
  438. Log_debug(context->logger, "Forwarding data to %s (last hop)\n", nhAddr);
  439. #endif*/
  440. return sendToRouter(message, dtHeader, nextHopSession, context);
  441. }
  442. // else { the message will need to be 3 layer encrypted but since we already did a lookup
  443. // of the best node to forward to, we can skip doing another lookup by storing a pointer
  444. // to that node in the context (bestNext).
  445. } else {
  446. #ifdef Log_WARN
  447. uint8_t thisAddr[40];
  448. uint8_t destAddr[40];
  449. AddrTools_printIp(thisAddr, context->myAddr.ip6.bytes);
  450. AddrTools_printIp(destAddr, header->destinationAddr);
  451. Log_warn(context->logger,
  452. "DROP message from TUN because this node [%s] is closest to dest [%s]",
  453. thisAddr, destAddr);
  454. #endif
  455. return Error_UNDELIVERABLE;
  456. }
  457. /*
  458. #ifdef Log_DEBUG
  459. uint8_t destAddr[40];
  460. AddrTools_printIp(destAddr, header->destinationAddr);
  461. uint8_t nhAddr[60];
  462. Address_print(nhAddr, &bestNext->address);
  463. Log_debug(context->logger, "Sending to [%s] via [%s]", destAddr, nhAddr);
  464. #endif
  465. */
  466. struct SessionManager_Session* session =
  467. SessionManager_getSession(header->destinationAddr, NULL, context->sm);
  468. // Copy the IP6 header back from where the CA header will be placed.
  469. // this is a mess.
  470. // We can't just copy the header to a safe place because the CryptoAuth
  471. // might buffer the message and send a connect-to-me packet and when the
  472. // hello packet comes in return, the CA will send the message and the header
  473. // needs to be in the message buffer.
  474. //
  475. // The CryptoAuth may send a 120 byte CA header and it might only send a 4 byte
  476. // nonce and 16 byte authenticator depending on its state.
  477. CryptoAuth_resetIfTimeout(session->internal);
  478. if (CryptoAuth_getState(session->internal) < CryptoAuth_HANDSHAKE3) {
  479. // shift, copy, shift because shifting asserts that there is enough buffer space.
  480. Message_shift(message, Headers_CryptoAuth_SIZE + 4, NULL);
  481. Bits_memcpyConst(message->bytes, header, Headers_IP6Header_SIZE);
  482. Message_shift(message, -(Headers_IP6Header_SIZE + Headers_CryptoAuth_SIZE + 4), NULL);
  483. // now push the receive handle *under* the CA header.
  484. Message_push(message, &session->receiveHandle_be, 4, NULL);
  485. debugHandles0(context->logger, session, "layer3 sending start message");
  486. } else {
  487. // shift, copy, shift because shifting asserts that there is enough buffer space.
  488. Message_shift(message, 20, NULL);
  489. Bits_memmoveConst(message->bytes, header, Headers_IP6Header_SIZE);
  490. Message_shift(message, -(20 + Headers_IP6Header_SIZE), NULL);
  491. debugHandles0(context->logger, session, "layer3 sending run message");
  492. }
  493. // This comes out at outgoingFromCryptoAuth() then outgoingFromMe()
  494. dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
  495. dtHeader->layer = Ducttape_SessionLayer_INNER;
  496. return Interface_sendMessage(session->internal, message);
  497. }
  498. /**
  499. * Send an arbitrary message to a node.
  500. *
  501. * @param message to be sent, must be prefixed with IpTunnel_PacketInfoHeader.
  502. * @param iface an interface for which receiverContext is the ducttape.
  503. */
  504. static uint8_t sendToNode(struct Message* message, struct Interface* iface)
  505. {
  506. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)iface->receiverContext);
  507. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
  508. struct IpTunnel_PacketInfoHeader* header = (struct IpTunnel_PacketInfoHeader*) message->bytes;
  509. Message_shift(message, -IpTunnel_PacketInfoHeader_SIZE, NULL);
  510. struct Node_Two* n = RouterModule_lookup(header->nodeIp6Addr, context->routerModule);
  511. if (n) {
  512. if (!Bits_memcmp(header->nodeKey, n->address.key, 32)) {
  513. // Found the node.
  514. /* noisy
  515. #ifdef Log_DEBUG
  516. uint8_t nhAddr[60];
  517. Address_print(nhAddr, &n->address);
  518. Log_debug(context->logger, "Sending arbitrary data to [%s]", nhAddr);
  519. #endif*/
  520. struct SessionManager_Session* session =
  521. SessionManager_getSession(n->address.ip6.bytes, n->address.key, context->sm);
  522. n->address.protocolVersion = session->version =
  523. (n->address.protocolVersion > session->version)
  524. ? n->address.protocolVersion : session->version;
  525. dtHeader->switchLabel = n->address.path;
  526. return sendToRouter(message, dtHeader, session, context);
  527. }
  528. }
  529. #ifdef Log_DEBUG
  530. uint8_t printedIp6[40];
  531. AddrTools_printIp(printedIp6, header->nodeIp6Addr);
  532. Log_debug(context->logger, "DROP Couldn't find node [%s] for sending to.", printedIp6);
  533. #endif
  534. // Now lets trigger a search for this node.
  535. uint64_t now = Time_currentTimeMilliseconds(context->eventBase);
  536. if (context->timeOfLastSearch + context->timeBetweenSearches < now) {
  537. context->timeOfLastSearch = now;
  538. SearchRunner_search(header->nodeIp6Addr, context->searchRunner, context->alloc);
  539. }
  540. return 0;
  541. }
  542. /**
  543. * Send an arbitrary message to the tun device.
  544. *
  545. * @param message to be sent.
  546. * @param iface an interface for which receiverContext is the ducttape.
  547. */
  548. static uint8_t sendToTun(struct Message* message, struct Interface* iface)
  549. {
  550. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)iface->receiverContext);
  551. uint16_t msgType = TUNMessageType_pop(message, NULL);
  552. if (msgType == Ethernet_TYPE_IP6) {
  553. Assert_always(message->length >= Headers_IP6Header_SIZE);
  554. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  555. if (header->sourceAddr[0] == 0xfc || header->destinationAddr[0] == 0xfc) {
  556. Assert_failure("you can't do that");
  557. }
  558. }
  559. TUNMessageType_push(message, msgType, NULL);
  560. if (context->userIf) {
  561. return context->userIf->sendMessage(message, context->userIf);
  562. }
  563. return 0;
  564. }
  565. /**
  566. * Messages with content encrypted and header decrypted are sent here to be forwarded.
  567. * they may come from us, or from another node and may be to us or to any other node.
  568. * Message is aligned on the beginning of the ipv6 header.
  569. */
  570. static inline int core(struct Message* message,
  571. struct Ducttape_MessageHeader* dtHeader,
  572. struct SessionManager_Session* session,
  573. struct Ducttape_pvt* context)
  574. {
  575. struct Headers_IP6Header* ip6Header = (struct Headers_IP6Header*) message->bytes;
  576. dtHeader->ip6Header = ip6Header;
  577. if (isForMe(message, context)) {
  578. Message_shift(message, -Headers_IP6Header_SIZE, NULL);
  579. if (Bits_memcmp(session->ip6, ip6Header->sourceAddr, 16)) {
  580. // triple encrypted
  581. // This call goes to incomingForMe()
  582. struct SessionManager_Session* session =
  583. SessionManager_getSession(ip6Header->sourceAddr, NULL, context->sm);
  584. #ifdef Log_DEBUG
  585. uint8_t addr[40];
  586. AddrTools_printIp(addr, ip6Header->sourceAddr);
  587. Log_debug(context->logger, "Incoming layer3 message, ostensibly from [%s]", addr);
  588. #endif
  589. dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
  590. dtHeader->layer = Ducttape_SessionLayer_INNER;
  591. return Interface_receiveMessage(&session->external, message);
  592. } else {
  593. // double encrypted, inner layer plaintext.
  594. // The session is still set from the router-to-router traffic and that is the one we use
  595. // to determine the node's id.
  596. return incomingForMe(message, dtHeader, session, context,
  597. CryptoAuth_getHerPublicKey(session->internal));
  598. }
  599. }
  600. if (ip6Header->hopLimit == 0) {
  601. Log_debug(context->logger, "DROP message because hop limit has been exceeded.\n");
  602. // TODO: send back an error message in response.
  603. return Error_UNDELIVERABLE;
  604. }
  605. ip6Header->hopLimit--;
  606. struct SessionManager_Session* nextHopSession = NULL;
  607. if (!dtHeader->nextHopReceiveHandle || !dtHeader->switchLabel) {
  608. struct Node_Two* n = RouterModule_lookup(ip6Header->destinationAddr, context->routerModule);
  609. if (n) {
  610. nextHopSession =
  611. SessionManager_getSession(n->address.ip6.bytes, n->address.key, context->sm);
  612. dtHeader->switchLabel = n->address.path;
  613. }
  614. } else {
  615. nextHopSession =
  616. SessionManager_sessionForHandle(dtHeader->nextHopReceiveHandle, context->sm);
  617. }
  618. if (nextHopSession) {
  619. #ifdef Log_DEBUG
  620. struct Address addr;
  621. Bits_memcpyConst(addr.ip6.bytes, nextHopSession->ip6, 16);
  622. addr.path = dtHeader->switchLabel;
  623. uint8_t nhAddr[60];
  624. Address_print(nhAddr, &addr);
  625. if (Bits_memcmp(ip6Header->destinationAddr, addr.ip6.bytes, 16)) {
  626. // Potentially forwarding for ourselves.
  627. struct Address destination;
  628. Bits_memcpyConst(destination.ip6.bytes, ip6Header->destinationAddr, 16);
  629. uint8_t ipAddr[40];
  630. Address_printIp(ipAddr, &destination);
  631. Log_debug(context->logger, "Forwarding data to %s via %s\n", ipAddr, nhAddr);
  632. } else {
  633. // Definitely forwarding on behalf of someone else.
  634. //Log_debug(context->logger, "Forwarding data to %s (last hop)\n", nhAddr);
  635. }
  636. #endif
  637. return sendToRouter(message, dtHeader, nextHopSession, context);
  638. }
  639. #ifdef Log_INFO
  640. struct Address destination;
  641. Bits_memcpyConst(destination.ip6.bytes, ip6Header->destinationAddr, 16);
  642. uint8_t ipAddr[40];
  643. Address_printIp(ipAddr, &destination);
  644. Log_info(context->logger, "DROP message because this node is the closest known "
  645. "node to the destination %s.", ipAddr);
  646. #endif
  647. return Error_UNDELIVERABLE;
  648. }
  649. /**
  650. * When we send a message it goes into the CryptoAuth.
  651. * for the content level crypto then it goes to outgoingFromCryptoAuth then comes here.
  652. * Message is aligned on the beginning of the CryptoAuth header.
  653. */
  654. static inline uint8_t outgoingFromMe(struct Message* message,
  655. struct Ducttape_MessageHeader* dtHeader,
  656. struct SessionManager_Session* session,
  657. struct Ducttape_pvt* context)
  658. {
  659. // Move back to the beginning of the ip6Header behind the crypto.
  660. Message_shift(message, Headers_IP6Header_SIZE, NULL);
  661. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  662. if (!Bits_memcmp(header->destinationAddr, context->myAddr.ip6.bytes, 16)) {
  663. // This happens when an empty connect-to-me packet is sent to us,
  664. // CryptoAuth is called with a message and instead of returning a decrypted message
  665. // to send to the TUN, it outputs a message to send back down the wire but the
  666. // header is still the same.
  667. // these messages are always empty so we just flip the source and destination around
  668. // and send it back.
  669. Bits_memcpyConst(header->destinationAddr, header->sourceAddr, 16);
  670. Bits_memcpyConst(header->sourceAddr, context->myAddr.ip6.bytes, 16);
  671. } else {
  672. // sanity check.
  673. Assert_true(!Bits_memcmp(header->sourceAddr, context->myAddr.ip6.bytes, 16));
  674. }
  675. // Need to set the length field to take into account
  676. // the crypto headers which are hidden under the ipv6 packet.
  677. header->payloadLength_be =
  678. Endian_hostToBigEndian16(message->length - Headers_IP6Header_SIZE);
  679. // Forward this call to core() which will check its validity
  680. // and since it's not to us, forward it to the correct node.
  681. return core(message, dtHeader, session, context);
  682. }
  683. static inline int incomingFromRouter(struct Message* message,
  684. struct Ducttape_MessageHeader* dtHeader,
  685. struct SessionManager_Session* session,
  686. struct Ducttape_pvt* context)
  687. {
  688. uint8_t* pubKey = CryptoAuth_getHerPublicKey(session->internal);
  689. if (!validEncryptedIP6(message)) {
  690. // Not valid cjdns IPv6, we'll try it as an IPv4 or ICANN-IPv6 packet
  691. // and check if we have an agreement with the node who sent it.
  692. Message_shift(message, IpTunnel_PacketInfoHeader_SIZE, NULL);
  693. struct IpTunnel_PacketInfoHeader* header =
  694. (struct IpTunnel_PacketInfoHeader*) message->bytes;
  695. uint8_t* addr = session->ip6;
  696. Bits_memcpyConst(header->nodeIp6Addr, addr, 16);
  697. Bits_memcpyConst(header->nodeKey, pubKey, 32);
  698. struct Interface* ipTun = &context->ipTunnel->nodeInterface;
  699. return ipTun->sendMessage(message, ipTun);
  700. }
  701. struct Address srcAddr = {
  702. .path = Endian_bigEndianToHost64(dtHeader->switchHeader->label_be)
  703. };
  704. Bits_memcpyConst(srcAddr.key, pubKey, 32);
  705. //Log_debug(context->logger, "Got message from router.\n");
  706. return core(message, dtHeader, session, context);
  707. }
  708. static uint8_t incomingFromCryptoAuth(struct Message* message, struct Interface* iface)
  709. {
  710. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) iface->receiverContext);
  711. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, false);
  712. enum Ducttape_SessionLayer layer = dtHeader->layer;
  713. dtHeader->layer = Ducttape_SessionLayer_INVALID;
  714. struct SessionManager_Session* session =
  715. SessionManager_sessionForHandle(dtHeader->receiveHandle, context->sm);
  716. if (!session) {
  717. // This should never happen but there's no strong preventitive.
  718. Log_info(context->logger, "SESSION DISAPPEARED!");
  719. return 0;
  720. }
  721. // If the packet came from a new session, put the send handle in the session.
  722. if (CryptoAuth_getState(session->internal) < CryptoAuth_ESTABLISHED) {
  723. // If this is true then the incoming message is definitely a handshake.
  724. if (message->length < 4) {
  725. debugHandles0(context->logger, session, "runt");
  726. return Error_INVALID;
  727. }
  728. if (layer == Ducttape_SessionLayer_OUTER) {
  729. #ifdef Version_2_COMPAT
  730. if (dtHeader->currentSessionVersion >= 3) {
  731. session->version = dtHeader->currentSessionVersion;
  732. #endif
  733. Message_pop(message, &session->sendHandle_be, 4, NULL);
  734. #ifdef Version_2_COMPAT
  735. } else {
  736. session->sendHandle_be = dtHeader->currentSessionSendHandle_be;
  737. }
  738. #endif
  739. } else {
  740. // inner layer, always grab the handle
  741. Message_pop(message, &session->sendHandle_be, 4, NULL);
  742. debugHandles0(context->logger, session, "New session, incoming layer3");
  743. }
  744. }
  745. switch (layer) {
  746. case Ducttape_SessionLayer_OUTER:
  747. return incomingFromRouter(message, dtHeader, session, context);
  748. case Ducttape_SessionLayer_INNER:
  749. return incomingForMe(message, dtHeader, session, context,
  750. CryptoAuth_getHerPublicKey(session->internal));
  751. default:
  752. Assert_always(false);
  753. }
  754. // never reached.
  755. return 0;
  756. }
  757. static uint8_t outgoingFromCryptoAuth(struct Message* message, struct Interface* iface)
  758. {
  759. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) iface->senderContext);
  760. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, false);
  761. struct SessionManager_Session* session =
  762. SessionManager_sessionForHandle(dtHeader->receiveHandle, context->sm);
  763. enum Ducttape_SessionLayer layer = dtHeader->layer;
  764. dtHeader->layer = Ducttape_SessionLayer_INVALID;
  765. if (!session) {
  766. // This should never happen but there's no strong preventitive.
  767. Log_info(context->logger, "SESSION DISAPPEARED!");
  768. return 0;
  769. }
  770. if (layer == Ducttape_SessionLayer_OUTER) {
  771. return sendToSwitch(message, dtHeader, session, context);
  772. } else if (layer == Ducttape_SessionLayer_INNER) {
  773. Log_debug(context->logger, "Sending layer3 message");
  774. return outgoingFromMe(message, dtHeader, session, context);
  775. } else {
  776. Assert_always(0);
  777. }
  778. }
  779. /**
  780. * Handle an incoming control message from a switch.
  781. *
  782. * @param context the ducttape context.
  783. * @param message the control message, this should be alligned on the beginning of the content,
  784. * that is to say, after the end of the switch header.
  785. * @param switchHeader the header.
  786. * @param switchIf the interface which leads to the switch.
  787. */
  788. static uint8_t handleControlMessage(struct Ducttape_pvt* context,
  789. struct Message* message,
  790. struct Headers_SwitchHeader* switchHeader,
  791. struct Interface* switchIf)
  792. {
  793. uint8_t labelStr[20];
  794. uint64_t label = Endian_bigEndianToHost64(switchHeader->label_be);
  795. AddrTools_printPath(labelStr, label);
  796. if (message->length < Control_HEADER_SIZE) {
  797. Log_info(context->logger, "DROP runt ctrl packet from [%s]", labelStr);
  798. return Error_NONE;
  799. }
  800. struct Control* ctrl = (struct Control*) message->bytes;
  801. if (Checksum_engine(message->bytes, message->length)) {
  802. Log_info(context->logger, "DROP ctrl packet from [%s] with invalid checksum.", labelStr);
  803. return Error_NONE;
  804. }
  805. bool pong = false;
  806. if (ctrl->type_be == Control_ERROR_be) {
  807. if (message->length < Control_Error_MIN_SIZE) {
  808. Log_info(context->logger, "DROP runt error packet from [%s]", labelStr);
  809. return Error_NONE;
  810. }
  811. uint64_t path = Endian_bigEndianToHost64(switchHeader->label_be);
  812. RouterModule_brokenPath(path, context->routerModule);
  813. uint8_t causeType = Headers_getMessageType(&ctrl->content.error.cause);
  814. if (causeType == Headers_SwitchHeader_TYPE_CONTROL) {
  815. if (message->length < Control_Error_MIN_SIZE + Control_HEADER_SIZE) {
  816. Log_info(context->logger,
  817. "error packet from [%s] containing runt cause packet",
  818. labelStr);
  819. return Error_NONE;
  820. }
  821. struct Control* causeCtrl = (struct Control*) &(&ctrl->content.error.cause)[1];
  822. if (causeCtrl->type_be != Control_PING_be) {
  823. uint32_t errorType = Endian_bigEndianToHost32(ctrl->content.error.errorType_be);
  824. Log_info(context->logger,
  825. "error packet from [%s] caused by [%s] packet ([%s])",
  826. labelStr,
  827. Control_typeString(causeCtrl->type_be),
  828. Error_strerror(errorType));
  829. } else {
  830. if (LabelSplicer_isOneHop(label)
  831. && ctrl->content.error.errorType_be
  832. == Endian_hostToBigEndian32(Error_UNDELIVERABLE))
  833. {
  834. // this is our own InterfaceController complaining
  835. // because the node isn't responding to pings.
  836. return Error_NONE;
  837. }
  838. Log_debug(context->logger,
  839. "error packet from [%s] in response to ping, err [%u], length: [%u].",
  840. labelStr,
  841. Endian_bigEndianToHost32(ctrl->content.error.errorType_be),
  842. message->length);
  843. // errors resulting from pings are forwarded back to the pinger.
  844. pong = true;
  845. }
  846. } else if (causeType != Headers_SwitchHeader_TYPE_DATA) {
  847. Log_info(context->logger,
  848. "error packet from [%s] containing cause of unknown type [%u]",
  849. labelStr, causeType);
  850. } else {
  851. uint32_t errorType = Endian_bigEndianToHost32(ctrl->content.error.errorType_be);
  852. if (errorType != Error_RETURN_PATH_INVALID) {
  853. // Error_RETURN_PATH_INVALID is impossible to prevent so will appear all the time.
  854. Log_info(context->logger,
  855. "error packet from [%s] [%s]",
  856. labelStr,
  857. Error_strerror(errorType));
  858. }
  859. }
  860. } else if (ctrl->type_be == Control_PONG_be) {
  861. pong = true;
  862. } else if (ctrl->type_be == Control_PING_be) {
  863. Message_shift(message, -Control_HEADER_SIZE, NULL);
  864. if (message->length < Control_Ping_MIN_SIZE) {
  865. Log_info(context->logger, "DROP runt ping");
  866. return Error_INVALID;
  867. }
  868. struct Control_Ping* ping = (struct Control_Ping*) message->bytes;
  869. ping->magic = Control_Pong_MAGIC;
  870. ping->version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL);
  871. Message_shift(message, Control_HEADER_SIZE, NULL);
  872. ctrl->type_be = Control_PONG_be;
  873. ctrl->checksum_be = 0;
  874. ctrl->checksum_be = Checksum_engine(message->bytes, message->length);
  875. Message_shift(message, Headers_SwitchHeader_SIZE, NULL);
  876. Log_debug(context->logger, "got switch ping from [%s]", labelStr);
  877. switchIf->receiveMessage(message, switchIf);
  878. } else if (ctrl->type_be == Control_KEYPONG_be) {
  879. pong = true;
  880. } else if (ctrl->type_be == Control_KEYPING_be) {
  881. Message_shift(message, -Control_HEADER_SIZE, NULL);
  882. if (message->length < Control_KeyPing_MIN_SIZE) {
  883. Log_info(context->logger, "DROP runt keyping");
  884. return Error_INVALID;
  885. }
  886. struct Control_KeyPing* keyPing = (struct Control_KeyPing*) message->bytes;
  887. #ifdef Log_DEBUG
  888. struct Address herAddr = {
  889. .protocolVersion = Endian_bigEndianToHost32(keyPing->version_be),
  890. .path = label
  891. };
  892. Bits_memcpyConst(herAddr.key, keyPing->key, 32);
  893. String* addrStr = Address_toString(&herAddr, message->alloc);
  894. Log_debug(context->logger, "got switch keyPing from [%s]", addrStr->bytes);
  895. #endif
  896. if (message->length > Control_KeyPing_MIN_SIZE + 64) {
  897. Log_debug(context->logger, "DROP oversize keyping message");
  898. return Error_INVALID;
  899. }
  900. keyPing->magic = Control_KeyPong_MAGIC;
  901. keyPing->version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL);
  902. Bits_memcpyConst(keyPing->key, context->myAddr.key, 32);
  903. Message_shift(message, Control_HEADER_SIZE, NULL);
  904. ctrl->type_be = Control_KEYPONG_be;
  905. ctrl->checksum_be = 0;
  906. ctrl->checksum_be = Checksum_engine(message->bytes, message->length);
  907. Message_shift(message, Headers_SwitchHeader_SIZE, NULL);
  908. Interface_receiveMessage(switchIf, message);
  909. } else {
  910. Log_info(context->logger,
  911. "control packet of unknown type from [%s], type [%d]",
  912. labelStr, Endian_bigEndianToHost16(ctrl->type_be));
  913. }
  914. if (pong && context->pub.switchPingerIf.receiveMessage) {
  915. // Shift back over the header
  916. Message_shift(message, Headers_SwitchHeader_SIZE, NULL);
  917. context->pub.switchPingerIf.receiveMessage(
  918. message, &context->pub.switchPingerIf);
  919. }
  920. return Error_NONE;
  921. }
  922. #ifdef Version_2_COMPAT
  923. static inline void translateVersion2(struct Message* message,
  924. struct Ducttape_MessageHeader* dtHeader)
  925. {
  926. uint32_t handle = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
  927. uint32_t nonce = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[1]);
  928. dtHeader->currentSessionVersion = 2;
  929. if (handle & HANDLE_FLAG_BIT) {
  930. // We have to doctor their handles to make them conform to the new protocol.
  931. // see sendToSwitch() where they are un-doctored when being sent back.
  932. handle &= ~HANDLE_FLAG_BIT;
  933. ((uint32_t*)message->bytes)[0] = Endian_bigEndianToHost32(handle);
  934. return;
  935. }
  936. // This has a 4 / 4294967296 risk of a false positive, losing a traffic packet
  937. // between 2 version2 nodes because the first 4 bytes of the content are mistaken
  938. // for a nonce.
  939. if (nonce <= 3) {
  940. dtHeader->currentSessionSendHandle_be = Endian_bigEndianToHost32(handle);
  941. Message_shift(message, -4, NULL);
  942. return;
  943. }
  944. dtHeader->currentSessionVersion = 3;
  945. }
  946. #endif
  947. /**
  948. * This is called as sendMessage() by the switch.
  949. * There is only one switch interface which sends all traffic.
  950. * message is aligned on the beginning of the switch header.
  951. */
  952. static uint8_t incomingFromSwitch(struct Message* message, struct Interface* switchIf)
  953. {
  954. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)switchIf->senderContext);
  955. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
  956. struct Headers_SwitchHeader* switchHeader = (struct Headers_SwitchHeader*) message->bytes;
  957. Message_shift(message, -Headers_SwitchHeader_SIZE, NULL);
  958. // The label comes in reversed from the switch because the switch doesn't know that we aren't
  959. // another switch ready to parse more bits, bit reversing the label yields the source address.
  960. switchHeader->label_be = Bits_bitReverse64(switchHeader->label_be);
  961. if (Headers_getMessageType(switchHeader) == Headers_SwitchHeader_TYPE_CONTROL) {
  962. return handleControlMessage(context, message, switchHeader, switchIf);
  963. }
  964. if (message->length < 8) {
  965. Log_info(context->logger, "runt");
  966. return Error_INVALID;
  967. }
  968. #ifdef Version_2_COMPAT
  969. translateVersion2(message, dtHeader);
  970. #endif
  971. // #1 try to get the session using the handle.
  972. uint32_t nonceOrHandle = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
  973. struct SessionManager_Session* session = NULL;
  974. if (nonceOrHandle > 3) {
  975. // Run message, it's a handle.
  976. session = SessionManager_sessionForHandle(nonceOrHandle, context->sm);
  977. Message_shift(message, -4, NULL);
  978. if (session) {
  979. uint32_t nonce = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
  980. if (nonce == ~0u) {
  981. Log_debug(context->logger, "DROP connectToMe packet at switch layer");
  982. return 0;
  983. }
  984. /*
  985. debugHandlesAndLabel(context->logger, session,
  986. Endian_bigEndianToHost64(switchHeader->label_be),
  987. "running session nonce[%u]",
  988. nonce);
  989. */
  990. dtHeader->receiveHandle = nonceOrHandle;
  991. } else {
  992. Log_debug(context->logger, "Got message with unrecognized handle");
  993. }
  994. } else if (message->length >= Headers_CryptoAuth_SIZE) {
  995. union Headers_CryptoAuth* caHeader = (union Headers_CryptoAuth*) message->bytes;
  996. uint8_t ip6[16];
  997. uint8_t* herKey = caHeader->handshake.publicKey;
  998. AddressCalc_addressForPublicKey(ip6, herKey);
  999. // a packet which claims to be "from us" causes problems
  1000. if (AddressCalc_validAddress(ip6) && Bits_memcmp(ip6, &context->myAddr, 16)) {
  1001. session = SessionManager_getSession(ip6, herKey, context->sm);
  1002. debugHandlesAndLabel(context->logger, session,
  1003. Endian_bigEndianToHost64(switchHeader->label_be),
  1004. "new session nonce[%d]", nonceOrHandle);
  1005. dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
  1006. } else {
  1007. Log_debug(context->logger, "Got message with invalid ip addr");
  1008. }
  1009. }
  1010. if (!session) {
  1011. #ifdef Log_INFO
  1012. uint8_t path[20];
  1013. AddrTools_printPath(path, Endian_bigEndianToHost64(switchHeader->label_be));
  1014. Log_info(context->logger, "DROP traffic packet from unknown node. [%s]", path);
  1015. #endif
  1016. return 0;
  1017. }
  1018. // This is needed so that the priority and other information
  1019. // from the switch header can be passed on properly.
  1020. dtHeader->switchHeader = switchHeader;
  1021. // This goes to incomingFromCryptoAuth()
  1022. // then incomingFromRouter() then core()
  1023. dtHeader->layer = Ducttape_SessionLayer_OUTER;
  1024. if (Interface_receiveMessage(&session->external, message) == Error_AUTHENTICATION) {
  1025. debugHandlesAndLabel(context->logger, session,
  1026. Endian_bigEndianToHost64(switchHeader->label_be),
  1027. "DROP Failed decrypting message NoH[%d] state[%s]",
  1028. nonceOrHandle,
  1029. CryptoAuth_stateString(CryptoAuth_getState(session->internal)));
  1030. return Error_AUTHENTICATION;
  1031. }
  1032. return 0;
  1033. }
  1034. static uint8_t incomingFromPinger(struct Message* message, struct Interface* iface)
  1035. {
  1036. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)iface->senderContext);
  1037. return context->switchInterface.receiveMessage(message, &context->switchInterface);
  1038. }
  1039. struct Ducttape* Ducttape_register(uint8_t privateKey[32],
  1040. struct DHTModuleRegistry* registry,
  1041. struct RouterModule* routerModule,
  1042. struct SearchRunner* searchRunner,
  1043. struct RumorMill* nodesOfInterest,
  1044. struct SwitchCore* switchCore,
  1045. struct EventBase* eventBase,
  1046. struct Allocator* allocator,
  1047. struct Log* logger,
  1048. struct IpTunnel* ipTun,
  1049. struct Random* rand)
  1050. {
  1051. struct Ducttape_pvt* context = Allocator_calloc(allocator, sizeof(struct Ducttape_pvt), 1);
  1052. context->registry = registry;
  1053. context->routerModule = routerModule;
  1054. context->nodesOfInterest = nodesOfInterest;
  1055. context->logger = logger;
  1056. context->eventBase = eventBase;
  1057. context->alloc = allocator;
  1058. context->searchRunner = searchRunner;
  1059. Bits_memcpyConst(&context->pub.magicInterface, (&(struct Interface) {
  1060. .sendMessage = magicInterfaceSendMessage,
  1061. .allocator = allocator
  1062. }), sizeof(struct Interface));
  1063. Identity_set(context);
  1064. context->ipTunnel = ipTun;
  1065. ipTun->nodeInterface.receiveMessage = sendToNode;
  1066. ipTun->nodeInterface.receiverContext = context;
  1067. ipTun->tunInterface.receiveMessage = sendToTun;
  1068. ipTun->tunInterface.receiverContext = context;
  1069. struct CryptoAuth* cryptoAuth =
  1070. CryptoAuth_new(allocator, privateKey, eventBase, logger, rand);
  1071. Bits_memcpyConst(context->myAddr.key, cryptoAuth->publicKey, 32);
  1072. Address_getPrefix(&context->myAddr);
  1073. context->sm = SessionManager_new(incomingFromCryptoAuth,
  1074. outgoingFromCryptoAuth,
  1075. context,
  1076. eventBase,
  1077. cryptoAuth,
  1078. rand,
  1079. allocator);
  1080. context->pub.sessionManager = context->sm;
  1081. Bits_memcpyConst(&context->module, (&(struct DHTModule) {
  1082. .name = "Ducttape",
  1083. .context = context,
  1084. .handleOutgoing = handleOutgoing
  1085. }), sizeof(struct DHTModule));
  1086. Bits_memcpyConst(&context->switchInterface, (&(struct Interface) {
  1087. .sendMessage = incomingFromSwitch,
  1088. .senderContext = context,
  1089. .allocator = allocator
  1090. }), sizeof(struct Interface));
  1091. if (DHTModuleRegistry_register(&context->module, context->registry)
  1092. || SwitchCore_setRouterInterface(&context->switchInterface, switchCore))
  1093. {
  1094. return NULL;
  1095. }
  1096. // setup the switch pinger interface.
  1097. Bits_memcpyConst(&context->pub.switchPingerIf, (&(struct Interface) {
  1098. .sendMessage = incomingFromPinger,
  1099. .senderContext = context
  1100. }), sizeof(struct Interface));
  1101. return &context->pub;
  1102. }
  1103. void Ducttape_setUserInterface(struct Ducttape* dt, struct Interface* userIf)
  1104. {
  1105. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) dt);
  1106. context->userIf = userIf;
  1107. userIf->receiveMessage = incomingFromTun;
  1108. userIf->receiverContext = context;
  1109. }