Ducttape.c 53 KB

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