Ducttape.c 53 KB

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