Ducttape.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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(cjd): 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_true(!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. Assert_ifParanoid(msg->length >= Headers_IP6Header_SIZE);
  368. #ifdef PARANOIA
  369. struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
  370. Assert_ifParanoid(!Bits_memcmp(header->destinationAddr, ctx->myAddr.ip6.bytes, 16));
  371. Assert_ifParanoid(!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. struct Node_Two* bestNext = RouterModule_lookup(header->destinationAddr, context->routerModule);
  426. struct SessionManager_Session* nextHopSession;
  427. if (bestNext) {
  428. nextHopSession = SessionManager_getSession(bestNext->address.ip6.bytes,
  429. bestNext->address.key,
  430. context->sm);
  431. bestNext->address.protocolVersion = nextHopSession->version =
  432. (bestNext->address.protocolVersion > nextHopSession->version)
  433. ? bestNext->address.protocolVersion : nextHopSession->version;
  434. dtHeader->switchLabel = bestNext->address.path;
  435. dtHeader->nextHopReceiveHandle = Endian_bigEndianToHost32(nextHopSession->receiveHandle_be);
  436. if (!Bits_memcmp(header->destinationAddr, bestNext->address.ip6.bytes, 16)) {
  437. // Direct send, skip the innermost layer of encryption.
  438. /*#ifdef Log_DEBUG
  439. uint8_t nhAddr[60];
  440. Address_print(nhAddr, &bestNext->address);
  441. Log_debug(context->logger, "Forwarding data to %s (last hop)\n", nhAddr);
  442. #endif*/
  443. return sendToRouter(message, dtHeader, nextHopSession, context);
  444. }
  445. // else { the message will need to be 3 layer encrypted but since we already did a lookup
  446. // of the best node to forward to, we can skip doing another lookup by storing a pointer
  447. // to that node in the context (bestNext).
  448. } else {
  449. #ifdef Log_WARN
  450. uint8_t thisAddr[40];
  451. uint8_t destAddr[40];
  452. AddrTools_printIp(thisAddr, context->myAddr.ip6.bytes);
  453. AddrTools_printIp(destAddr, header->destinationAddr);
  454. Log_warn(context->logger,
  455. "DROP message from TUN because this node [%s] is closest to dest [%s]",
  456. thisAddr, destAddr);
  457. #endif
  458. return Error_UNDELIVERABLE;
  459. }
  460. /*
  461. #ifdef Log_DEBUG
  462. uint8_t destAddr[40];
  463. AddrTools_printIp(destAddr, header->destinationAddr);
  464. uint8_t nhAddr[60];
  465. Address_print(nhAddr, &bestNext->address);
  466. Log_debug(context->logger, "Sending to [%s] via [%s]", destAddr, nhAddr);
  467. #endif
  468. */
  469. struct SessionManager_Session* session =
  470. SessionManager_getSession(header->destinationAddr, NULL, context->sm);
  471. // Copy the IP6 header back from where the CA header will be placed.
  472. // this is a mess.
  473. // We can't just copy the header to a safe place because the CryptoAuth
  474. // might buffer the message and send a connect-to-me packet and when the
  475. // hello packet comes in return, the CA will send the message and the header
  476. // needs to be in the message buffer.
  477. //
  478. // The CryptoAuth may send a 120 byte CA header and it might only send a 4 byte
  479. // nonce and 16 byte authenticator depending on its state.
  480. CryptoAuth_resetIfTimeout(session->internal);
  481. if (CryptoAuth_getState(session->internal) < CryptoAuth_HANDSHAKE3) {
  482. // shift, copy, shift because shifting asserts that there is enough buffer space.
  483. Message_shift(message, Headers_CryptoAuth_SIZE + 4, NULL);
  484. Bits_memcpyConst(message->bytes, header, Headers_IP6Header_SIZE);
  485. Message_shift(message, -(Headers_IP6Header_SIZE + Headers_CryptoAuth_SIZE + 4), NULL);
  486. // now push the receive handle *under* the CA header.
  487. Message_push(message, &session->receiveHandle_be, 4, NULL);
  488. debugHandles0(context->logger, session, "layer3 sending start message");
  489. } else {
  490. // shift, copy, shift because shifting asserts that there is enough buffer space.
  491. Message_shift(message, 20, NULL);
  492. Bits_memmoveConst(message->bytes, header, Headers_IP6Header_SIZE);
  493. Message_shift(message, -(20 + Headers_IP6Header_SIZE), NULL);
  494. debugHandles0(context->logger, session, "layer3 sending run message");
  495. }
  496. // This comes out at outgoingFromCryptoAuth() then outgoingFromMe()
  497. dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
  498. dtHeader->layer = Ducttape_SessionLayer_INNER;
  499. return Interface_sendMessage(session->internal, message);
  500. }
  501. /**
  502. * Send an arbitrary message to a node.
  503. *
  504. * @param message to be sent, must be prefixed with IpTunnel_PacketInfoHeader.
  505. * @param iface an interface for which receiverContext is the ducttape.
  506. */
  507. static uint8_t sendToNode(struct Message* message, struct Interface* iface)
  508. {
  509. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)iface->receiverContext);
  510. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
  511. struct IpTunnel_PacketInfoHeader* header = (struct IpTunnel_PacketInfoHeader*) message->bytes;
  512. Message_shift(message, -IpTunnel_PacketInfoHeader_SIZE, NULL);
  513. struct Node_Two* n = RouterModule_lookup(header->nodeIp6Addr, context->routerModule);
  514. if (n) {
  515. if (!Bits_memcmp(header->nodeKey, n->address.key, 32)) {
  516. // Found the node.
  517. /* noisy
  518. #ifdef Log_DEBUG
  519. uint8_t nhAddr[60];
  520. Address_print(nhAddr, &n->address);
  521. Log_debug(context->logger, "Sending arbitrary data to [%s]", nhAddr);
  522. #endif*/
  523. struct SessionManager_Session* session =
  524. SessionManager_getSession(n->address.ip6.bytes, n->address.key, context->sm);
  525. n->address.protocolVersion = session->version =
  526. (n->address.protocolVersion > session->version)
  527. ? n->address.protocolVersion : session->version;
  528. dtHeader->switchLabel = n->address.path;
  529. return sendToRouter(message, dtHeader, session, context);
  530. }
  531. }
  532. #ifdef Log_DEBUG
  533. uint8_t printedIp6[40];
  534. AddrTools_printIp(printedIp6, header->nodeIp6Addr);
  535. Log_debug(context->logger, "DROP Couldn't find node [%s] for sending to.", printedIp6);
  536. #endif
  537. // Now lets trigger a search for this node.
  538. uint64_t now = Time_currentTimeMilliseconds(context->eventBase);
  539. if (context->timeOfLastSearch + context->timeBetweenSearches < now) {
  540. context->timeOfLastSearch = now;
  541. SearchRunner_search(header->nodeIp6Addr, context->searchRunner, context->alloc);
  542. }
  543. return 0;
  544. }
  545. /**
  546. * Send an arbitrary message to the tun device.
  547. *
  548. * @param message to be sent.
  549. * @param iface an interface for which receiverContext is the ducttape.
  550. */
  551. static uint8_t sendToTun(struct Message* message, struct Interface* iface)
  552. {
  553. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)iface->receiverContext);
  554. uint16_t msgType = TUNMessageType_pop(message, NULL);
  555. if (msgType == Ethernet_TYPE_IP6) {
  556. Assert_true(message->length >= Headers_IP6Header_SIZE);
  557. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  558. if (header->sourceAddr[0] == 0xfc || header->destinationAddr[0] == 0xfc) {
  559. Assert_failure("you can't do that");
  560. }
  561. }
  562. TUNMessageType_push(message, msgType, NULL);
  563. if (context->userIf) {
  564. return context->userIf->sendMessage(message, context->userIf);
  565. }
  566. return 0;
  567. }
  568. /**
  569. * Messages with content encrypted and header decrypted are sent here to be forwarded.
  570. * they may come from us, or from another node and may be to us or to any other node.
  571. * Message is aligned on the beginning of the ipv6 header.
  572. */
  573. static inline int core(struct Message* message,
  574. struct Ducttape_MessageHeader* dtHeader,
  575. struct SessionManager_Session* session,
  576. struct Ducttape_pvt* context)
  577. {
  578. struct Headers_IP6Header* ip6Header = (struct Headers_IP6Header*) message->bytes;
  579. dtHeader->ip6Header = ip6Header;
  580. if (isForMe(message, context)) {
  581. Message_shift(message, -Headers_IP6Header_SIZE, NULL);
  582. if (Bits_memcmp(session->ip6, ip6Header->sourceAddr, 16)) {
  583. // triple encrypted
  584. // This call goes to incomingForMe()
  585. struct SessionManager_Session* session =
  586. SessionManager_getSession(ip6Header->sourceAddr, NULL, context->sm);
  587. #ifdef Log_DEBUG
  588. uint8_t addr[40];
  589. AddrTools_printIp(addr, ip6Header->sourceAddr);
  590. Log_debug(context->logger, "Incoming layer3 message, ostensibly from [%s]", addr);
  591. #endif
  592. dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
  593. dtHeader->layer = Ducttape_SessionLayer_INNER;
  594. return Interface_receiveMessage(&session->external, message);
  595. } else {
  596. // double encrypted, inner layer plaintext.
  597. // The session is still set from the router-to-router traffic and that is the one we use
  598. // to determine the node's id.
  599. return incomingForMe(message, dtHeader, session, context,
  600. CryptoAuth_getHerPublicKey(session->internal));
  601. }
  602. }
  603. if (ip6Header->hopLimit == 0) {
  604. Log_debug(context->logger, "DROP message because hop limit has been exceeded.\n");
  605. // TODO(cjd): send back an error message in response.
  606. return Error_UNDELIVERABLE;
  607. }
  608. ip6Header->hopLimit--;
  609. struct SessionManager_Session* nextHopSession = NULL;
  610. if (!dtHeader->nextHopReceiveHandle || !dtHeader->switchLabel) {
  611. struct Node_Two* n = RouterModule_lookup(ip6Header->destinationAddr, context->routerModule);
  612. if (n) {
  613. nextHopSession =
  614. SessionManager_getSession(n->address.ip6.bytes, n->address.key, context->sm);
  615. dtHeader->switchLabel = n->address.path;
  616. }
  617. } else {
  618. nextHopSession =
  619. SessionManager_sessionForHandle(dtHeader->nextHopReceiveHandle, context->sm);
  620. }
  621. if (nextHopSession) {
  622. #ifdef Log_DEBUG
  623. struct Address addr;
  624. Bits_memcpyConst(addr.ip6.bytes, nextHopSession->ip6, 16);
  625. addr.path = dtHeader->switchLabel;
  626. uint8_t nhAddr[60];
  627. Address_print(nhAddr, &addr);
  628. if (Bits_memcmp(ip6Header->destinationAddr, addr.ip6.bytes, 16)) {
  629. // Potentially forwarding for ourselves.
  630. struct Address destination;
  631. Bits_memcpyConst(destination.ip6.bytes, ip6Header->destinationAddr, 16);
  632. uint8_t ipAddr[40];
  633. Address_printIp(ipAddr, &destination);
  634. Log_debug(context->logger, "Forwarding data to %s via %s\n", ipAddr, nhAddr);
  635. } else {
  636. // Definitely forwarding on behalf of someone else.
  637. //Log_debug(context->logger, "Forwarding data to %s (last hop)\n", nhAddr);
  638. }
  639. #endif
  640. return sendToRouter(message, dtHeader, nextHopSession, context);
  641. }
  642. #ifdef Log_INFO
  643. struct Address destination;
  644. Bits_memcpyConst(destination.ip6.bytes, ip6Header->destinationAddr, 16);
  645. uint8_t ipAddr[40];
  646. Address_printIp(ipAddr, &destination);
  647. Log_info(context->logger, "DROP message because this node is the closest known "
  648. "node to the destination %s.", ipAddr);
  649. #endif
  650. return Error_UNDELIVERABLE;
  651. }
  652. /**
  653. * When we send a message it goes into the CryptoAuth.
  654. * for the content level crypto then it goes to outgoingFromCryptoAuth then comes here.
  655. * Message is aligned on the beginning of the CryptoAuth header.
  656. */
  657. static inline uint8_t outgoingFromMe(struct Message* message,
  658. struct Ducttape_MessageHeader* dtHeader,
  659. struct SessionManager_Session* session,
  660. struct Ducttape_pvt* context)
  661. {
  662. // Move back to the beginning of the ip6Header behind the crypto.
  663. Message_shift(message, Headers_IP6Header_SIZE, NULL);
  664. struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
  665. if (!Bits_memcmp(header->destinationAddr, context->myAddr.ip6.bytes, 16)) {
  666. // This happens when an empty connect-to-me packet is sent to us,
  667. // CryptoAuth is called with a message and instead of returning a decrypted message
  668. // to send to the TUN, it outputs a message to send back down the wire but the
  669. // header is still the same.
  670. // these messages are always empty so we just flip the source and destination around
  671. // and send it back.
  672. Bits_memcpyConst(header->destinationAddr, header->sourceAddr, 16);
  673. Bits_memcpyConst(header->sourceAddr, context->myAddr.ip6.bytes, 16);
  674. } else {
  675. // sanity check.
  676. Assert_ifParanoid(!Bits_memcmp(header->sourceAddr, context->myAddr.ip6.bytes, 16));
  677. }
  678. // Need to set the length field to take into account
  679. // the crypto headers which are hidden under the ipv6 packet.
  680. header->payloadLength_be =
  681. Endian_hostToBigEndian16(message->length - Headers_IP6Header_SIZE);
  682. // Forward this call to core() which will check its validity
  683. // and since it's not to us, forward it to the correct node.
  684. return core(message, dtHeader, session, context);
  685. }
  686. static inline int incomingFromRouter(struct Message* message,
  687. struct Ducttape_MessageHeader* dtHeader,
  688. struct SessionManager_Session* session,
  689. struct Ducttape_pvt* context)
  690. {
  691. uint8_t* pubKey = CryptoAuth_getHerPublicKey(session->internal);
  692. if (!validEncryptedIP6(message)) {
  693. // Not valid cjdns IPv6, we'll try it as an IPv4 or ICANN-IPv6 packet
  694. // and check if we have an agreement with the node who sent it.
  695. Message_shift(message, IpTunnel_PacketInfoHeader_SIZE, NULL);
  696. struct IpTunnel_PacketInfoHeader* header =
  697. (struct IpTunnel_PacketInfoHeader*) message->bytes;
  698. uint8_t* addr = session->ip6;
  699. Bits_memcpyConst(header->nodeIp6Addr, addr, 16);
  700. Bits_memcpyConst(header->nodeKey, pubKey, 32);
  701. struct Interface* ipTun = &context->ipTunnel->nodeInterface;
  702. return ipTun->sendMessage(message, ipTun);
  703. }
  704. struct Address srcAddr = {
  705. .path = Endian_bigEndianToHost64(dtHeader->switchHeader->label_be)
  706. };
  707. Bits_memcpyConst(srcAddr.key, pubKey, 32);
  708. //Log_debug(context->logger, "Got message from router.\n");
  709. return core(message, dtHeader, session, context);
  710. }
  711. static uint8_t incomingFromCryptoAuth(struct Message* message, struct Interface* iface)
  712. {
  713. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) iface->receiverContext);
  714. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, false);
  715. enum Ducttape_SessionLayer layer = dtHeader->layer;
  716. dtHeader->layer = Ducttape_SessionLayer_INVALID;
  717. struct SessionManager_Session* session =
  718. SessionManager_sessionForHandle(dtHeader->receiveHandle, context->sm);
  719. if (!session) {
  720. // This should never happen but there's no strong preventitive.
  721. Log_info(context->logger, "SESSION DISAPPEARED!");
  722. return 0;
  723. }
  724. // If the packet came from a new session, put the send handle in the session.
  725. if (CryptoAuth_getState(session->internal) < CryptoAuth_ESTABLISHED) {
  726. // If this is true then the incoming message is definitely a handshake.
  727. if (message->length < 4) {
  728. debugHandles0(context->logger, session, "runt");
  729. return Error_INVALID;
  730. }
  731. if (layer == Ducttape_SessionLayer_OUTER) {
  732. #ifdef Version_2_COMPAT
  733. if (dtHeader->currentSessionVersion >= 3) {
  734. session->version = dtHeader->currentSessionVersion;
  735. #endif
  736. Message_pop(message, &session->sendHandle_be, 4, NULL);
  737. #ifdef Version_2_COMPAT
  738. } else {
  739. session->sendHandle_be = dtHeader->currentSessionSendHandle_be;
  740. }
  741. #endif
  742. } else {
  743. // inner layer, always grab the handle
  744. Message_pop(message, &session->sendHandle_be, 4, NULL);
  745. debugHandles0(context->logger, session, "New session, incoming layer3");
  746. }
  747. }
  748. switch (layer) {
  749. case Ducttape_SessionLayer_OUTER:
  750. return incomingFromRouter(message, dtHeader, session, context);
  751. case Ducttape_SessionLayer_INNER:
  752. return incomingForMe(message, dtHeader, session, context,
  753. CryptoAuth_getHerPublicKey(session->internal));
  754. default:
  755. Assert_true(false);
  756. }
  757. // never reached.
  758. return 0;
  759. }
  760. static uint8_t outgoingFromCryptoAuth(struct Message* message, struct Interface* iface)
  761. {
  762. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) iface->senderContext);
  763. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, false);
  764. struct SessionManager_Session* session =
  765. SessionManager_sessionForHandle(dtHeader->receiveHandle, context->sm);
  766. enum Ducttape_SessionLayer layer = dtHeader->layer;
  767. dtHeader->layer = Ducttape_SessionLayer_INVALID;
  768. if (!session) {
  769. // This should never happen but there's no strong preventitive.
  770. Log_info(context->logger, "SESSION DISAPPEARED!");
  771. return 0;
  772. }
  773. if (layer == Ducttape_SessionLayer_OUTER) {
  774. return sendToSwitch(message, dtHeader, session, context);
  775. } else if (layer == Ducttape_SessionLayer_INNER) {
  776. Log_debug(context->logger, "Sending layer3 message");
  777. return outgoingFromMe(message, dtHeader, session, context);
  778. } else {
  779. Assert_true(0);
  780. }
  781. }
  782. /**
  783. * Handle an incoming control message from a switch.
  784. *
  785. * @param context the ducttape context.
  786. * @param message the control message, this should be alligned on the beginning of the content,
  787. * that is to say, after the end of the switch header.
  788. * @param switchHeader the header.
  789. * @param switchIf the interface which leads to the switch.
  790. */
  791. static uint8_t handleControlMessage(struct Ducttape_pvt* context,
  792. struct Message* message,
  793. struct Headers_SwitchHeader* switchHeader,
  794. struct Interface* switchIf)
  795. {
  796. uint8_t labelStr[20];
  797. uint64_t label = Endian_bigEndianToHost64(switchHeader->label_be);
  798. AddrTools_printPath(labelStr, label);
  799. if (message->length < Control_HEADER_SIZE) {
  800. Log_info(context->logger, "DROP runt ctrl packet from [%s]", labelStr);
  801. return Error_NONE;
  802. }
  803. struct Control* ctrl = (struct Control*) message->bytes;
  804. if (Checksum_engine(message->bytes, message->length)) {
  805. Log_info(context->logger, "DROP ctrl packet from [%s] with invalid checksum.", labelStr);
  806. return Error_NONE;
  807. }
  808. bool pong = false;
  809. if (ctrl->type_be == Control_ERROR_be) {
  810. if (message->length < Control_Error_MIN_SIZE) {
  811. Log_info(context->logger, "DROP runt error packet from [%s]", labelStr);
  812. return Error_NONE;
  813. }
  814. uint64_t path = Endian_bigEndianToHost64(switchHeader->label_be);
  815. RouterModule_brokenPath(path, context->routerModule);
  816. uint8_t causeType = Headers_getMessageType(&ctrl->content.error.cause);
  817. if (causeType == Headers_SwitchHeader_TYPE_CONTROL) {
  818. if (message->length < Control_Error_MIN_SIZE + Control_HEADER_SIZE) {
  819. Log_info(context->logger,
  820. "error packet from [%s] containing runt cause packet",
  821. labelStr);
  822. return Error_NONE;
  823. }
  824. struct Control* causeCtrl = (struct Control*) &(&ctrl->content.error.cause)[1];
  825. if (causeCtrl->type_be != Control_PING_be) {
  826. #ifdef Log_INFO
  827. uint32_t errorType =
  828. Endian_bigEndianToHost32(ctrl->content.error.errorType_be);
  829. Log_info(context->logger,
  830. "error packet from [%s] caused by [%s] packet ([%s])",
  831. labelStr,
  832. Control_typeString(causeCtrl->type_be),
  833. Error_strerror(errorType));
  834. #endif
  835. } else {
  836. if (LabelSplicer_isOneHop(label)
  837. && ctrl->content.error.errorType_be
  838. == Endian_hostToBigEndian32(Error_UNDELIVERABLE))
  839. {
  840. // this is our own InterfaceController complaining
  841. // because the node isn't responding to pings.
  842. return Error_NONE;
  843. }
  844. Log_debug(context->logger,
  845. "error packet from [%s] in response to ping, err [%u], length: [%u].",
  846. labelStr,
  847. Endian_bigEndianToHost32(ctrl->content.error.errorType_be),
  848. message->length);
  849. // errors resulting from pings are forwarded back to the pinger.
  850. pong = true;
  851. }
  852. } else if (causeType != Headers_SwitchHeader_TYPE_DATA) {
  853. Log_info(context->logger,
  854. "error packet from [%s] containing cause of unknown type [%u]",
  855. labelStr, causeType);
  856. } else {
  857. uint32_t errorType = Endian_bigEndianToHost32(ctrl->content.error.errorType_be);
  858. if (errorType != Error_RETURN_PATH_INVALID) {
  859. // Error_RETURN_PATH_INVALID is impossible to prevent so will appear all the time.
  860. Log_info(context->logger,
  861. "error packet from [%s] [%s]",
  862. labelStr,
  863. Error_strerror(errorType));
  864. }
  865. }
  866. } else if (ctrl->type_be == Control_PONG_be) {
  867. pong = true;
  868. } else if (ctrl->type_be == Control_PING_be) {
  869. Message_shift(message, -Control_HEADER_SIZE, NULL);
  870. if (message->length < Control_Ping_MIN_SIZE) {
  871. Log_info(context->logger, "DROP runt ping");
  872. return Error_INVALID;
  873. }
  874. struct Control_Ping* ping = (struct Control_Ping*) message->bytes;
  875. ping->magic = Control_Pong_MAGIC;
  876. ping->version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL);
  877. Message_shift(message, Control_HEADER_SIZE, NULL);
  878. ctrl->type_be = Control_PONG_be;
  879. ctrl->checksum_be = 0;
  880. ctrl->checksum_be = Checksum_engine(message->bytes, message->length);
  881. Message_shift(message, Headers_SwitchHeader_SIZE, NULL);
  882. Log_debug(context->logger, "got switch ping from [%s]", labelStr);
  883. switchIf->receiveMessage(message, switchIf);
  884. } else if (ctrl->type_be == Control_KEYPONG_be) {
  885. pong = true;
  886. } else if (ctrl->type_be == Control_KEYPING_be) {
  887. Message_shift(message, -Control_HEADER_SIZE, NULL);
  888. if (message->length < Control_KeyPing_MIN_SIZE) {
  889. Log_info(context->logger, "DROP runt keyping");
  890. return Error_INVALID;
  891. }
  892. struct Control_KeyPing* keyPing = (struct Control_KeyPing*) message->bytes;
  893. #ifdef Log_DEBUG
  894. struct Address herAddr = {
  895. .protocolVersion = Endian_bigEndianToHost32(keyPing->version_be),
  896. .path = label
  897. };
  898. Bits_memcpyConst(herAddr.key, keyPing->key, 32);
  899. String* addrStr = Address_toString(&herAddr, message->alloc);
  900. Log_debug(context->logger, "got switch keyPing from [%s]", addrStr->bytes);
  901. #endif
  902. if (message->length > Control_KeyPing_MIN_SIZE + 64) {
  903. Log_debug(context->logger, "DROP oversize keyping message");
  904. return Error_INVALID;
  905. }
  906. keyPing->magic = Control_KeyPong_MAGIC;
  907. keyPing->version_be = Endian_hostToBigEndian32(Version_CURRENT_PROTOCOL);
  908. Bits_memcpyConst(keyPing->key, context->myAddr.key, 32);
  909. Message_shift(message, Control_HEADER_SIZE, NULL);
  910. ctrl->type_be = Control_KEYPONG_be;
  911. ctrl->checksum_be = 0;
  912. ctrl->checksum_be = Checksum_engine(message->bytes, message->length);
  913. Message_shift(message, Headers_SwitchHeader_SIZE, NULL);
  914. Interface_receiveMessage(switchIf, message);
  915. } else {
  916. Log_info(context->logger,
  917. "control packet of unknown type from [%s], type [%d]",
  918. labelStr, Endian_bigEndianToHost16(ctrl->type_be));
  919. }
  920. if (pong && context->pub.switchPingerIf.receiveMessage) {
  921. // Shift back over the header
  922. Message_shift(message, Headers_SwitchHeader_SIZE, NULL);
  923. context->pub.switchPingerIf.receiveMessage(
  924. message, &context->pub.switchPingerIf);
  925. }
  926. return Error_NONE;
  927. }
  928. #ifdef Version_2_COMPAT
  929. static inline void translateVersion2(struct Message* message,
  930. struct Ducttape_MessageHeader* dtHeader)
  931. {
  932. uint32_t handle = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
  933. uint32_t nonce = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[1]);
  934. dtHeader->currentSessionVersion = 2;
  935. if (handle & HANDLE_FLAG_BIT) {
  936. // We have to doctor their handles to make them conform to the new protocol.
  937. // see sendToSwitch() where they are un-doctored when being sent back.
  938. handle &= ~HANDLE_FLAG_BIT;
  939. ((uint32_t*)message->bytes)[0] = Endian_bigEndianToHost32(handle);
  940. return;
  941. }
  942. // This has a 4 / 4294967296 risk of a false positive, losing a traffic packet
  943. // between 2 version2 nodes because the first 4 bytes of the content are mistaken
  944. // for a nonce.
  945. if (nonce <= 3) {
  946. dtHeader->currentSessionSendHandle_be = Endian_bigEndianToHost32(handle);
  947. Message_shift(message, -4, NULL);
  948. return;
  949. }
  950. dtHeader->currentSessionVersion = 3;
  951. }
  952. #endif
  953. /**
  954. * This is called as sendMessage() by the switch.
  955. * There is only one switch interface which sends all traffic.
  956. * message is aligned on the beginning of the switch header.
  957. */
  958. static uint8_t incomingFromSwitch(struct Message* message, struct Interface* switchIf)
  959. {
  960. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)switchIf->senderContext);
  961. struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
  962. struct Headers_SwitchHeader* switchHeader = (struct Headers_SwitchHeader*) message->bytes;
  963. Message_shift(message, -Headers_SwitchHeader_SIZE, NULL);
  964. // The label comes in reversed from the switch because the switch doesn't know that we aren't
  965. // another switch ready to parse more bits, bit reversing the label yields the source address.
  966. switchHeader->label_be = Bits_bitReverse64(switchHeader->label_be);
  967. if (Headers_getMessageType(switchHeader) == Headers_SwitchHeader_TYPE_CONTROL) {
  968. return handleControlMessage(context, message, switchHeader, switchIf);
  969. }
  970. if (message->length < 8) {
  971. Log_info(context->logger, "runt");
  972. return Error_INVALID;
  973. }
  974. #ifdef Version_2_COMPAT
  975. translateVersion2(message, dtHeader);
  976. #endif
  977. // #1 try to get the session using the handle.
  978. uint32_t nonceOrHandle = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
  979. struct SessionManager_Session* session = NULL;
  980. if (nonceOrHandle > 3) {
  981. // Run message, it's a handle.
  982. session = SessionManager_sessionForHandle(nonceOrHandle, context->sm);
  983. Message_shift(message, -4, NULL);
  984. if (session) {
  985. uint32_t nonce = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
  986. if (nonce == ~0u) {
  987. Log_debug(context->logger, "DROP connectToMe packet at switch layer");
  988. return 0;
  989. }
  990. /*
  991. debugHandlesAndLabel(context->logger, session,
  992. Endian_bigEndianToHost64(switchHeader->label_be),
  993. "running session nonce[%u]",
  994. nonce);
  995. */
  996. dtHeader->receiveHandle = nonceOrHandle;
  997. } else {
  998. Log_debug(context->logger, "Got message with unrecognized handle");
  999. }
  1000. } else if (message->length >= Headers_CryptoAuth_SIZE) {
  1001. union Headers_CryptoAuth* caHeader = (union Headers_CryptoAuth*) message->bytes;
  1002. uint8_t ip6[16];
  1003. uint8_t* herKey = caHeader->handshake.publicKey;
  1004. AddressCalc_addressForPublicKey(ip6, herKey);
  1005. // a packet which claims to be "from us" causes problems
  1006. if (AddressCalc_validAddress(ip6) && Bits_memcmp(ip6, &context->myAddr, 16)) {
  1007. session = SessionManager_getSession(ip6, herKey, context->sm);
  1008. debugHandlesAndLabel(context->logger, session,
  1009. Endian_bigEndianToHost64(switchHeader->label_be),
  1010. "new session nonce[%d]", nonceOrHandle);
  1011. dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
  1012. } else {
  1013. Log_debug(context->logger, "Got message with invalid ip addr");
  1014. }
  1015. }
  1016. if (!session) {
  1017. #ifdef Log_INFO
  1018. uint8_t path[20];
  1019. AddrTools_printPath(path, Endian_bigEndianToHost64(switchHeader->label_be));
  1020. Log_info(context->logger, "DROP traffic packet from unknown node. [%s]", path);
  1021. #endif
  1022. return 0;
  1023. }
  1024. // This is needed so that the priority and other information
  1025. // from the switch header can be passed on properly.
  1026. dtHeader->switchHeader = switchHeader;
  1027. // This goes to incomingFromCryptoAuth()
  1028. // then incomingFromRouter() then core()
  1029. dtHeader->layer = Ducttape_SessionLayer_OUTER;
  1030. if (Interface_receiveMessage(&session->external, message) == Error_AUTHENTICATION) {
  1031. debugHandlesAndLabel(context->logger, session,
  1032. Endian_bigEndianToHost64(switchHeader->label_be),
  1033. "DROP Failed decrypting message NoH[%d] state[%s]",
  1034. nonceOrHandle,
  1035. CryptoAuth_stateString(CryptoAuth_getState(session->internal)));
  1036. return Error_AUTHENTICATION;
  1037. }
  1038. return 0;
  1039. }
  1040. static uint8_t incomingFromPinger(struct Message* message, struct Interface* iface)
  1041. {
  1042. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)iface->senderContext);
  1043. return context->switchInterface.receiveMessage(message, &context->switchInterface);
  1044. }
  1045. struct Ducttape* Ducttape_register(uint8_t privateKey[32],
  1046. struct DHTModuleRegistry* registry,
  1047. struct RouterModule* routerModule,
  1048. struct SearchRunner* searchRunner,
  1049. struct SwitchCore* switchCore,
  1050. struct EventBase* eventBase,
  1051. struct Allocator* allocator,
  1052. struct Log* logger,
  1053. struct IpTunnel* ipTun,
  1054. struct Random* rand)
  1055. {
  1056. struct Ducttape_pvt* context = Allocator_calloc(allocator, sizeof(struct Ducttape_pvt), 1);
  1057. context->registry = registry;
  1058. context->routerModule = routerModule;
  1059. context->logger = logger;
  1060. context->eventBase = eventBase;
  1061. context->alloc = allocator;
  1062. context->searchRunner = searchRunner;
  1063. Bits_memcpyConst(&context->pub.magicInterface, (&(struct Interface) {
  1064. .sendMessage = magicInterfaceSendMessage,
  1065. .allocator = allocator
  1066. }), sizeof(struct Interface));
  1067. Identity_set(context);
  1068. context->ipTunnel = ipTun;
  1069. ipTun->nodeInterface.receiveMessage = sendToNode;
  1070. ipTun->nodeInterface.receiverContext = context;
  1071. ipTun->tunInterface.receiveMessage = sendToTun;
  1072. ipTun->tunInterface.receiverContext = context;
  1073. struct CryptoAuth* cryptoAuth =
  1074. CryptoAuth_new(allocator, privateKey, eventBase, logger, rand);
  1075. Bits_memcpyConst(context->myAddr.key, cryptoAuth->publicKey, 32);
  1076. Address_getPrefix(&context->myAddr);
  1077. context->sm = SessionManager_new(incomingFromCryptoAuth,
  1078. outgoingFromCryptoAuth,
  1079. context,
  1080. eventBase,
  1081. cryptoAuth,
  1082. rand,
  1083. allocator);
  1084. context->pub.sessionManager = context->sm;
  1085. Bits_memcpyConst(&context->module, (&(struct DHTModule) {
  1086. .name = "Ducttape",
  1087. .context = context,
  1088. .handleOutgoing = handleOutgoing
  1089. }), sizeof(struct DHTModule));
  1090. Bits_memcpyConst(&context->switchInterface, (&(struct Interface) {
  1091. .sendMessage = incomingFromSwitch,
  1092. .senderContext = context,
  1093. .allocator = allocator
  1094. }), sizeof(struct Interface));
  1095. if (DHTModuleRegistry_register(&context->module, context->registry)
  1096. || SwitchCore_setRouterInterface(&context->switchInterface, switchCore))
  1097. {
  1098. return NULL;
  1099. }
  1100. // setup the switch pinger interface.
  1101. Bits_memcpyConst(&context->pub.switchPingerIf, (&(struct Interface) {
  1102. .sendMessage = incomingFromPinger,
  1103. .senderContext = context
  1104. }), sizeof(struct Interface));
  1105. return &context->pub;
  1106. }
  1107. void Ducttape_setUserInterface(struct Ducttape* dt, struct Interface* userIf)
  1108. {
  1109. struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) dt);
  1110. context->userIf = userIf;
  1111. userIf->receiveMessage = incomingFromTun;
  1112. userIf->receiverContext = context;
  1113. }