1
0

Ducttape.c 49 KB

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