Ducttape.c 51 KB

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