Ducttape.c 54 KB

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