Ducttape.c 52 KB

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