SessionManager.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 <https://www.gnu.org/licenses/>.
  14. */
  15. #include "memory/Allocator.h"
  16. #include "wire/PFChan.h"
  17. #include "net/SessionManager.h"
  18. #include "crypto/AddressCalc.h"
  19. #include "util/AddrTools.h"
  20. #include "wire/Error.h"
  21. #include "util/events/Time.h"
  22. #include "util/Defined.h"
  23. #include "wire/RouteHeader.h"
  24. #include "util/events/Timeout.h"
  25. #include "util/Checksum.h"
  26. #include "wire/Metric.h"
  27. /** Handle numbers 0-3 are reserved for CryptoAuth nonces. */
  28. #define MIN_FIRST_HANDLE 4
  29. #define MAX_FIRST_HANDLE 100000
  30. struct BufferedMessage
  31. {
  32. struct Message* msg;
  33. struct Allocator* alloc;
  34. uint64_t timeSentMilliseconds;
  35. };
  36. struct Ip6 {
  37. uint8_t bytes[16];
  38. };
  39. #define Map_KEY_TYPE struct Ip6
  40. #define Map_VALUE_TYPE struct BufferedMessage*
  41. #define Map_NAME BufferedMessages
  42. #include "util/Map.h"
  43. #define Map_KEY_TYPE struct Ip6
  44. #define Map_VALUE_TYPE struct SessionManager_Session_pvt*
  45. #define Map_NAME OfSessionsByIp6
  46. #define Map_ENABLE_HANDLES
  47. #include "util/Map.h"
  48. struct SessionManager_pvt
  49. {
  50. struct SessionManager pub;
  51. struct Iface eventIf;
  52. struct Allocator* alloc;
  53. struct Map_BufferedMessages bufMap;
  54. struct Map_OfSessionsByIp6 ifaceMap;
  55. struct Log* log;
  56. Ca_t* cryptoAuth;
  57. struct EventBase* eventBase;
  58. uint32_t firstHandle;
  59. uint8_t ourPubKey[32];
  60. Identity
  61. };
  62. struct SessionManager_Session_pvt
  63. {
  64. struct SessionManager_Session pub;
  65. struct Iface plaintext;
  66. struct Iface ciphertext;
  67. struct SessionManager_pvt* sessionManager;
  68. struct Allocator* alloc;
  69. bool foundKey;
  70. Identity
  71. };
  72. #define debugHandlesAndLabel(logger, session, label, message, ...) \
  73. do { \
  74. if (!Defined(Log_DEBUG)) { break; } \
  75. uint8_t path[20]; \
  76. AddrTools_printPath(path, label); \
  77. uint8_t ip[40]; \
  78. uint8_t ipb[16]; \
  79. Ca_getHerIp6(session->pub.caSession, ipb); \
  80. AddrTools_printIp(ip, ipb); \
  81. Log_debug(logger, "ver[%u] send[%d] recv[%u] ip[%s] path[%s] " message, \
  82. session->pub.version, \
  83. session->pub.sendHandle, \
  84. session->pub.receiveHandle, \
  85. ip, \
  86. path, \
  87. __VA_ARGS__); \
  88. } while (0)
  89. //CHECKFILES_IGNORE expecting a ;
  90. #define debugHandlesAndLabel0(logger, session, label, message) \
  91. debugHandlesAndLabel(logger, session, label, "%s", message)
  92. #define debugSession(logger, session, label, message, ...) \
  93. do { \
  94. if (!Defined(Log_DEBUG)) { break; } \
  95. uint8_t sendPath[20]; \
  96. uint8_t ip[40]; \
  97. uint8_t ipb[16]; \
  98. Ca_getHerIp6(session->pub.caSession, ipb); \
  99. AddrTools_printIp(ip, ipb); \
  100. AddrTools_printPath(sendPath, (label)); \
  101. Log_debug((logger), "Session[%p] [%s.%s] " message, \
  102. (void*)session, \
  103. sendPath, \
  104. ip, \
  105. __VA_ARGS__); \
  106. } while (0)
  107. //CHECKFILES_IGNORE ;
  108. #define debugSession0(logger, session, label, message) \
  109. debugSession(logger, session, label, "%s", message)
  110. static void sendSession(struct SessionManager_Session_pvt* sess,
  111. SessionManager_Path_t* path,
  112. uint32_t destPf,
  113. enum PFChan_Core ev)
  114. {
  115. struct PFChan_Node session = {
  116. .path_be = Endian_hostToBigEndian64(path->label),
  117. .metric_be = Endian_bigEndianToHost32(path->metric),
  118. .version_be = Endian_hostToBigEndian32(sess->pub.version)
  119. };
  120. Ca_getHerPubKey(sess->pub.caSession, session.publicKey);
  121. Ca_getHerIp6(sess->pub.caSession, session.ip6);
  122. struct Allocator* alloc = Allocator_child(sess->alloc);
  123. struct Message* msg = Message_new(0, PFChan_Node_SIZE + 512, alloc);
  124. Er_assert(Message_epush(msg, &session, PFChan_Node_SIZE));
  125. Er_assert(Message_epush32be(msg, destPf));
  126. Er_assert(Message_epush32be(msg, ev));
  127. Iface_send(&sess->sessionManager->eventIf, msg);
  128. Allocator_free(alloc);
  129. }
  130. static inline void check(struct SessionManager_pvt* sm, int mapIndex)
  131. {
  132. struct SessionManager_Session_pvt* ssp = Identity_check(sm->ifaceMap.values[mapIndex]);
  133. if (ssp->foundKey) { return; }
  134. uint8_t herPubKey[32];
  135. Ca_getHerPubKey(ssp->pub.caSession, herPubKey);
  136. if (!Bits_isZero(herPubKey, 32)) {
  137. uint8_t ip6[16];
  138. AddressCalc_addressForPublicKey(ip6, herPubKey);
  139. Assert_true(!Bits_memcmp(&sm->ifaceMap.keys[mapIndex], ip6, 16));
  140. ssp->foundKey = true;
  141. }
  142. }
  143. static inline struct SessionManager_Session_pvt* sessionForHandle(uint32_t handle,
  144. struct SessionManager_pvt* sm)
  145. {
  146. int index = Map_OfSessionsByIp6_indexForHandle(handle - sm->firstHandle, &sm->ifaceMap);
  147. if (index < 0) { return NULL; }
  148. check(sm, index);
  149. return Identity_check(sm->ifaceMap.values[index]);
  150. }
  151. struct SessionManager_Session* SessionManager_sessionForHandle(uint32_t handle,
  152. struct SessionManager* manager)
  153. {
  154. struct SessionManager_pvt* sm = Identity_check((struct SessionManager_pvt*) manager);
  155. return (struct SessionManager_Session*) sessionForHandle(handle, sm);
  156. }
  157. static inline struct SessionManager_Session_pvt* sessionForIp6(uint8_t ip6[16],
  158. struct SessionManager_pvt* sm)
  159. {
  160. int ifaceIndex = Map_OfSessionsByIp6_indexForKey((struct Ip6*)ip6, &sm->ifaceMap);
  161. if (ifaceIndex == -1) { return NULL; }
  162. check(sm, ifaceIndex);
  163. return Identity_check(sm->ifaceMap.values[ifaceIndex]);
  164. }
  165. struct SessionManager_Session* SessionManager_sessionForIp6(uint8_t* ip6,
  166. struct SessionManager* manager)
  167. {
  168. struct SessionManager_pvt* sm = Identity_check((struct SessionManager_pvt*) manager);
  169. return (struct SessionManager_Session*) sessionForIp6(ip6, sm);
  170. }
  171. struct SessionManager_HandleList* SessionManager_getHandleList(struct SessionManager* manager,
  172. struct Allocator* alloc)
  173. {
  174. struct SessionManager_pvt* sm = Identity_check((struct SessionManager_pvt*) manager);
  175. struct SessionManager_HandleList* out =
  176. Allocator_calloc(alloc, sizeof(struct SessionManager_HandleList), 1);
  177. uint32_t* buff = Allocator_calloc(alloc, 4, sm->ifaceMap.count);
  178. out->length = sm->ifaceMap.count;
  179. out->handles = buff;
  180. for (int i = 0; i < out->length; i++) {
  181. buff[i] = sm->ifaceMap.handles[i] + sm->firstHandle;
  182. }
  183. return out;
  184. }
  185. static uint32_t effectiveMetric(struct SessionManager_pvt* sm,
  186. SessionManager_Path_t* path)
  187. {
  188. int64_t x = Time_currentTimeMilliseconds() - path->timeLastValidated;
  189. x += path->metric;
  190. return (x > Metric_NO_INFO) ? Metric_NO_INFO : x;
  191. }
  192. uint32_t SessionManager_effectiveMetric(struct SessionManager_Session* session)
  193. {
  194. struct SessionManager_Session_pvt* sess =
  195. Identity_check((struct SessionManager_Session_pvt*) session);
  196. return effectiveMetric(sess->sessionManager, &sess->pub.paths[0]);
  197. }
  198. static SessionManager_Path_t* pathForLabel(struct SessionManager_Session_pvt* sess, uint64_t label)
  199. {
  200. for (int i = 0; i < SessionManager_PATH_COUNT; i++) {
  201. if (sess->pub.paths[i].label == label) {
  202. return &sess->pub.paths[i];
  203. }
  204. }
  205. return NULL;
  206. }
  207. static SessionManager_Path_t* worstPath(struct SessionManager_Session_pvt* sess)
  208. {
  209. uint32_t worstEm = 0;
  210. int worstI = 0;
  211. for (int i = 0; i < SessionManager_PATH_COUNT; i++) {
  212. uint32_t em = effectiveMetric(sess->sessionManager, &sess->pub.paths[i]);
  213. if (em > worstEm) {
  214. worstEm = em;
  215. worstI = i;
  216. }
  217. }
  218. return &sess->pub.paths[worstI];
  219. }
  220. static void rerankPaths(struct SessionManager_Session_pvt* sess)
  221. {
  222. uint32_t bestEm = Metric_DEAD_LINK;
  223. int bestI = 0;
  224. for (int i = 0; i < SessionManager_PATH_COUNT; i++) {
  225. uint32_t em = effectiveMetric(sess->sessionManager, &sess->pub.paths[i]);
  226. if (em < bestEm) {
  227. bestEm = em;
  228. bestI = i;
  229. }
  230. }
  231. if (bestI != 0) {
  232. SessionManager_Path_t path0;
  233. Bits_memcpy(&path0, &sess->pub.paths[0], sizeof(path0));
  234. Bits_memcpy(&sess->pub.paths[0], &sess->pub.paths[bestI], sizeof(path0));
  235. Bits_memcpy(&sess->pub.paths[bestI], &path0, sizeof(path0));
  236. }
  237. }
  238. // Return true if the new path is an improvement
  239. static bool discoverPath(struct SessionManager_Session_pvt* sess,
  240. uint64_t label,
  241. uint32_t metric)
  242. {
  243. if (!label) {
  244. return false;
  245. }
  246. SessionManager_Path_t* path = pathForLabel(sess, label);
  247. uint64_t now = Time_currentTimeMilliseconds();
  248. if (path) {
  249. if (metric != Metric_DEAD_LINK && effectiveMetric(sess->sessionManager, path) <= metric) {
  250. // already have a better source of truth
  251. return false;
  252. }
  253. path->metric = metric;
  254. path->timeLastValidated = now;
  255. rerankPaths(sess);
  256. return (sess->pub.paths[0].label == label);
  257. } else {
  258. path = worstPath(sess);
  259. if (effectiveMetric(sess->sessionManager, path) <= metric) {
  260. return false;
  261. }
  262. path->label = label;
  263. path->metric = metric;
  264. path->timeLastValidated = now;
  265. rerankPaths(sess);
  266. if (sess->pub.paths[0].label == label) {
  267. sendSession(sess, &sess->pub.paths[0], 0xffffffff, PFChan_Core_DISCOVERED_PATH);
  268. return true;
  269. }
  270. return false;
  271. }
  272. }
  273. static Iface_DEFUN failedDecrypt(struct Message* msg,
  274. uint64_t label_be,
  275. struct SessionManager_pvt* sm)
  276. {
  277. Er_assert(Message_epush32be(msg, Error_AUTHENTICATION));
  278. Er_assert(Message_epush16be(msg, Control_ERROR));
  279. Er_assert(Message_epush16be(msg, 0));
  280. uint16_t csum_be = Checksum_engine_be(msg->msgbytes, Message_getLength(msg));
  281. Er_assert(Message_epop16h(msg));
  282. Er_assert(Message_epush16h(msg, csum_be));
  283. Er_assert(Message_epush32be(msg, 0xffffffff));
  284. struct SwitchHeader sh;
  285. Bits_memset(&sh, 0, SwitchHeader_SIZE);
  286. SwitchHeader_setSuppressErrors(&sh, true);
  287. SwitchHeader_setVersion(&sh, SwitchHeader_CURRENT_VERSION);
  288. sh.label_be = label_be;
  289. Er_assert(Message_epush(msg, &sh, SwitchHeader_SIZE));
  290. return Iface_next(&sm->pub.switchIf, msg);
  291. }
  292. static Iface_DEFUN postDecryption(struct Message* msg, struct Iface* iface)
  293. {
  294. struct SessionManager_Session_pvt* session =
  295. Identity_containerOf(iface, struct SessionManager_Session_pvt, plaintext);
  296. // The switch header is pushed as associated data
  297. uint32_t nonceOrHandle = 0xffffffff;
  298. Er_assert(Message_epopAd(msg, &nonceOrHandle, 4));
  299. struct RouteHeader header = {
  300. .flags = RouteHeader_flags_INCOMING,
  301. .version_be = Endian_hostToBigEndian32(session->pub.version),
  302. };
  303. Er_assert(Message_epopAd(msg, &header.sh, SwitchHeader_SIZE));
  304. Ca_getHerPubKey(session->pub.caSession, header.publicKey);
  305. Ca_getHerIp6(session->pub.caSession, header.ip6);
  306. uint64_t label = Endian_bigEndianToHost64(header.sh.label_be);
  307. enum Ca_DecryptErr ret = Er_assert(Message_epop32h(msg));
  308. if (ret) {
  309. // If CryptoAuth fails to decrypt then it gives us:
  310. // * Ca_DecryptErr - we already popped this
  311. // * first16
  312. // * Ca_DecryptErr
  313. // * state
  314. debugHandlesAndLabel(session->sessionManager->log, session,
  315. label,
  316. "DROP Failed decrypting message NoH[%d] state[%s]",
  317. nonceOrHandle,
  318. Ca_stateString(Ca_getState(session->pub.caSession)));
  319. uint64_t label_be = header.sh.label_be;
  320. // We want to preserve it "as it was" here
  321. header.sh.label_be = Bits_bitReverse64(header.sh.label_be);
  322. Er_assert(Message_epush(msg, &header.sh, SwitchHeader_SIZE));
  323. return failedDecrypt(msg, label_be, session->sessionManager);
  324. }
  325. if (nonceOrHandle <= 3) {
  326. session->pub.sendHandle = Er_assert(Message_epop32be(msg));
  327. debugHandlesAndLabel0(
  328. session->sessionManager->log, session, label, "received start message");
  329. }
  330. session->pub.bytesIn += Message_getLength(msg);
  331. Er_assert(Message_epush(msg, &header, sizeof header));
  332. discoverPath(session, label, Metric_SM_INCOMING);
  333. return Iface_next(&session->sessionManager->pub.insideIf, msg);
  334. }
  335. static Iface_DEFUN afterEncrypt(struct Message* msg, struct Iface* iface)
  336. {
  337. //Assert_true(!Ca_encrypt(sess->pub.caSession, msg));
  338. struct SessionManager_Session_pvt* sess =
  339. Identity_containerOf(iface, struct SessionManager_Session_pvt, ciphertext);
  340. struct RouteHeader header;
  341. Er_assert(Message_epopAd(msg, &header, RouteHeader_SIZE));
  342. if (Ca_getState(sess->pub.caSession) >= Ca_State_RECEIVED_KEY) {
  343. if (0) { // Noisy
  344. debugHandlesAndLabel0(sess->sessionManager->log,
  345. sess,
  346. Endian_bigEndianToHost64(header.sh.label_be),
  347. "sending run message");
  348. }
  349. Er_assert(Message_epush32be(msg, sess->pub.sendHandle));
  350. } else {
  351. debugHandlesAndLabel0(sess->sessionManager->log,
  352. sess,
  353. Endian_bigEndianToHost64(header.sh.label_be),
  354. "sending start message");
  355. }
  356. if (!header.sh.label_be) {
  357. Bits_memset(&header.sh, 0, SwitchHeader_SIZE);
  358. header.sh.label_be = Endian_hostToBigEndian64(sess->pub.paths[0].label);
  359. SwitchHeader_setVersion(&header.sh, SwitchHeader_CURRENT_VERSION);
  360. }
  361. Er_assert(Message_epush(msg, &header.sh, SwitchHeader_SIZE));
  362. return Iface_next(&sess->sessionManager->pub.switchIf, msg);
  363. }
  364. static struct SessionManager_Session_pvt* getSession(struct SessionManager_pvt* sm,
  365. uint8_t ip6[16],
  366. uint8_t pubKey[32],
  367. uint32_t version,
  368. uint64_t label,
  369. uint32_t metric)
  370. {
  371. Assert_true(AddressCalc_validAddress(ip6));
  372. if (!label) { metric = Metric_DEAD_LINK; }
  373. struct SessionManager_Session_pvt* sess = sessionForIp6(ip6, sm);
  374. if (sess) {
  375. sess->pub.version = (sess->pub.version) ? sess->pub.version : version;
  376. if (discoverPath(sess, label, metric)) {
  377. sess->pub.version = (version) ? version : sess->pub.version;
  378. }
  379. return sess;
  380. }
  381. struct Allocator* alloc = Allocator_child(sm->alloc);
  382. sess = Allocator_calloc(alloc, sizeof(struct SessionManager_Session_pvt), 1);
  383. Identity_set(sess);
  384. sess->plaintext.send = postDecryption;
  385. sess->ciphertext.send = afterEncrypt;
  386. sess->pub.caSession = Ca_newSession(sm->cryptoAuth, alloc, pubKey, false, "inner", false);
  387. Iface_plumb(sess->pub.caSession->plaintext, &sess->plaintext);
  388. Iface_plumb(sess->pub.caSession->ciphertext, &sess->ciphertext);
  389. sess->foundKey = !Bits_isZero(pubKey, 32);
  390. if (sess->foundKey) {
  391. uint8_t realIp6[16];
  392. AddressCalc_addressForPublicKey(realIp6, pubKey);
  393. Assert_true(!Bits_memcmp(realIp6, ip6, 16));
  394. }
  395. int ifaceIndex = Map_OfSessionsByIp6_put((struct Ip6*)ip6, &sess, &sm->ifaceMap);
  396. sess->pub.receiveHandle = sm->ifaceMap.handles[ifaceIndex] + sm->firstHandle;
  397. if (Defined(Log_DEBUG)) {
  398. uint8_t printedIp6[40];
  399. AddrTools_printIp(printedIp6, ip6);
  400. Log_debug(sm->log, "Created session for [%s] handle [%u]",
  401. printedIp6, sess->pub.receiveHandle);
  402. }
  403. int64_t now = Time_currentTimeMilliseconds();
  404. sess->alloc = alloc;
  405. sess->sessionManager = sm;
  406. sess->pub.version = version;
  407. sess->pub.paths[0].timeLastValidated = now;
  408. sess->pub.paths[0].label = label;
  409. sess->pub.paths[0].metric = metric;
  410. //Allocator_onFree(alloc, sessionCleanup, sess);
  411. sendSession(sess, &sess->pub.paths[0], 0xffffffff, PFChan_Core_SESSION);
  412. check(sm, ifaceIndex);
  413. return sess;
  414. }
  415. static Iface_DEFUN ctrlFrame(struct Message* msg, struct SessionManager_pvt* sm)
  416. {
  417. struct RouteHeader rh;
  418. Bits_memset(&rh, 0, RouteHeader_SIZE);
  419. Er_assert(Message_epop(msg, &rh.sh, SwitchHeader_SIZE));
  420. Er_assert(Message_epop(msg, NULL, 4));
  421. rh.flags = RouteHeader_flags_INCOMING | RouteHeader_flags_CTRLMSG;
  422. Er_assert(Message_epush(msg, &rh, RouteHeader_SIZE));
  423. return Iface_next(&sm->pub.insideIf, msg);
  424. }
  425. static const uint8_t ADDR_PFX[8] = { 0xff, 0xfb, 0, 0, 0, 0, 0, 0 };
  426. static Iface_DEFUN incomingFromSwitchIf(struct Message* msg, struct Iface* iface)
  427. {
  428. struct SessionManager_pvt* sm =
  429. Identity_containerOf(iface, struct SessionManager_pvt, pub.switchIf);
  430. // SwitchHeader, handle, 0 or more bytes of control frame
  431. if (Message_getLength(msg) < SwitchHeader_SIZE + 4) {
  432. Log_debug(sm->log, "DROP runt");
  433. return Error(msg, "RUNT");
  434. }
  435. struct SwitchHeader switchHeader;
  436. Er_assert(Message_epop(msg, &switchHeader, SwitchHeader_SIZE));
  437. // The label comes in reversed from the switch because the switch doesn't know that we aren't
  438. // another switch ready to parse more bits, bit reversing the label yields the source address.
  439. // (the field is still big endian!)
  440. switchHeader.label_be = Bits_bitReverse64(switchHeader.label_be);
  441. struct SessionManager_Session_pvt* session = NULL;
  442. uint32_t nonceOrHandle = Endian_bigEndianToHost32(((uint32_t*)msg->msgbytes)[0]);
  443. if (nonceOrHandle == 0xffffffff) {
  444. Er_assert(Message_epush(msg, &switchHeader, SwitchHeader_SIZE));
  445. return ctrlFrame(msg, sm);
  446. }
  447. // handle, small cryptoAuth header
  448. if (Message_getLength(msg) < 4 + 20) {
  449. Log_debug(sm->log, "DROP runt");
  450. return Error(msg, "RUNT");
  451. }
  452. if (nonceOrHandle > 3) {
  453. // > 3 it's a handle.
  454. session = sessionForHandle(nonceOrHandle, sm);
  455. if (!session) {
  456. Log_debug(sm->log, "DROP message with unrecognized handle [%u]", nonceOrHandle);
  457. return Error(msg, "INVALID");
  458. }
  459. Er_assert(Message_eshift(msg, -4));
  460. uint32_t nonce = Endian_bigEndianToHost32(((uint32_t*)msg->msgbytes)[0]);
  461. if (nonce < 4) {
  462. Log_debug(sm->log, "DROP setup message [%u] with specified handle [%u]",
  463. nonce, nonceOrHandle);
  464. return Error(msg, "INVALID");
  465. }
  466. } else {
  467. // handle + big cryptoauth header
  468. if (Message_getLength(msg) < CryptoHeader_SIZE + 4) {
  469. Log_debug(sm->log, "DROP runt");
  470. return Error(msg, "RUNT");
  471. }
  472. struct CryptoHeader* caHeader = (struct CryptoHeader*) msg->msgbytes;
  473. uint8_t ip6[16];
  474. // a packet which claims to be "from us" causes problems
  475. if (!AddressCalc_addressForPublicKey(ip6, caHeader->publicKey)) {
  476. Log_debug(sm->log, "DROP Handshake with non-fc key");
  477. return Error(msg, "INVALID");
  478. }
  479. if (!Bits_memcmp(caHeader->publicKey, sm->ourPubKey, 32)) {
  480. Log_debug(sm->log, "DROP Handshake from 'ourselves'");
  481. return Error(msg, "INVALID");
  482. }
  483. uint64_t label = Endian_bigEndianToHost64(switchHeader.label_be);
  484. session = getSession(sm, ip6, caHeader->publicKey, 0, label, Metric_SM_INCOMING);
  485. Ca_resetIfTimeout(session->pub.caSession);
  486. debugHandlesAndLabel(sm->log, session, label, "new session nonce[%d]", nonceOrHandle);
  487. }
  488. Er_assert(Message_epushAd(msg, &switchHeader, SwitchHeader_SIZE));
  489. Er_assert(Message_epushAd(msg, &nonceOrHandle, 4));
  490. Er_assert(Message_epush(msg, &switchHeader.label_be, 8));
  491. Er_assert(Message_epush(msg, ADDR_PFX, 8));
  492. return Iface_next(&session->ciphertext, msg);
  493. }
  494. static void checkTimedOutBuffers(struct SessionManager_pvt* sm)
  495. {
  496. for (int i = 0; i < (int)sm->bufMap.count; i++) {
  497. struct BufferedMessage* buffered = sm->bufMap.values[i];
  498. int64_t lag = Time_currentTimeMilliseconds() - buffered->timeSentMilliseconds;
  499. if (lag < 10000) { continue; }
  500. Map_BufferedMessages_remove(i, &sm->bufMap);
  501. Allocator_free(buffered->alloc);
  502. i--;
  503. }
  504. }
  505. static void unsetupSession(struct SessionManager_pvt* sm, struct SessionManager_Session_pvt* sess)
  506. {
  507. if (!sess->pub.version || sess->pub.paths[0].metric == Metric_DEAD_LINK) {
  508. // Nothing we can do here because it's not ok to send traffic without a version and path.
  509. return;
  510. }
  511. struct Allocator* eventAlloc = Allocator_child(sm->alloc);
  512. struct Message* eventMsg = Message_new(0, 512, eventAlloc);
  513. struct PFChan_Node n = { .metric_be = Endian_hostToBigEndian32(Metric_DEAD_LINK) };
  514. n.path_be = Endian_hostToBigEndian64(sess->pub.paths[0].label);
  515. Assert_true(n.path_be);
  516. n.version_be = Endian_hostToBigEndian32(sess->pub.version);
  517. n.metric_be = Endian_bigEndianToHost32(sess->pub.paths[0].metric);
  518. Ca_getHerPubKey(sess->pub.caSession, n.publicKey);
  519. Ca_getHerIp6(sess->pub.caSession, n.ip6);
  520. Er_assert(Message_epush(eventMsg, &n, PFChan_Node_SIZE));
  521. Er_assert(Message_epush32be(eventMsg, 0xffffffff));
  522. Er_assert(Message_epush32be(eventMsg, PFChan_Core_UNSETUP_SESSION));
  523. Iface_send(&sm->eventIf, eventMsg);
  524. Allocator_free(eventAlloc);
  525. }
  526. static void triggerSearch(struct SessionManager_pvt* sm, uint8_t target[16], uint32_t version)
  527. {
  528. struct Allocator* eventAlloc = Allocator_child(sm->alloc);
  529. struct Message* eventMsg = Message_new(0, 512, eventAlloc);
  530. Er_assert(Message_epush32be(eventMsg, version));
  531. Er_assert(Message_epush32be(eventMsg, 0));
  532. Er_assert(Message_epush(eventMsg, target, 16));
  533. Er_assert(Message_epush32be(eventMsg, 0xffffffff));
  534. Er_assert(Message_epush32be(eventMsg, PFChan_Core_SEARCH_REQ));
  535. Iface_send(&sm->eventIf, eventMsg);
  536. Allocator_free(eventAlloc);
  537. }
  538. static SessionManager_Path_t* mostRecentValidatedPath(struct SessionManager_Session_pvt* sess)
  539. {
  540. int64_t bestTime = 0;
  541. int bestI = 0;
  542. for (int i = 0; i < SessionManager_PATH_COUNT; i++) {
  543. if (sess->pub.paths[i].timeLastValidated > bestTime) {
  544. bestTime = sess->pub.paths[i].timeLastValidated;
  545. bestI = i;
  546. }
  547. }
  548. return &sess->pub.paths[bestI];
  549. }
  550. static void checkTimedOutSessions(struct SessionManager_pvt* sm)
  551. {
  552. for (int i = (int)sm->ifaceMap.count - 1; i >= 0; i--) {
  553. struct SessionManager_Session_pvt* sess = sm->ifaceMap.values[i];
  554. int64_t now = Time_currentTimeMilliseconds();
  555. // Check if the session is timed out...
  556. SessionManager_Path_t* path = mostRecentValidatedPath(sess);
  557. if (now - path->timeLastValidated > sm->pub.sessionTimeoutMilliseconds) {
  558. debugSession0(sm->log, sess, path->label, "ended");
  559. // Only need to send this once because PFChan_Core_SESSION_ENDED
  560. // means the whole session is done
  561. sendSession(sess, path, 0xffffffff, PFChan_Core_SESSION_ENDED);
  562. Map_OfSessionsByIp6_remove(i, &sm->ifaceMap);
  563. Allocator_free(sess->alloc);
  564. continue;
  565. }
  566. if (now - sess->pub.timeOfLastUsage > sm->pub.sessionTimeoutMilliseconds) {
  567. // This session is either only used by the pathfinder or it is nolonger used
  568. // let the pathfinder maintain it if it wants to, otherwise let it drop.
  569. //
  570. // This is a convenience for user tools to know that it's unmanaged.
  571. sess->pub.timeOfLastUsage = 0;
  572. } else if (now - sess->pub.lastSearchTime >= sm->pub.sessionSearchAfterMilliseconds) {
  573. // Session is not in idle state and requires a search
  574. debugSession0(sm->log, sess, sess->pub.paths[0].label,
  575. "it's been a while, triggering search");
  576. uint8_t herIp6[16];
  577. Ca_getHerIp6(sess->pub.caSession, herIp6);
  578. triggerSearch(sm, herIp6, sess->pub.version);
  579. sess->pub.lastSearchTime = now;
  580. } else if (Ca_getState(sess->pub.caSession) < Ca_State_ESTABLISHED) {
  581. debugSession0(sm->log, sess, sess->pub.paths[0].label, "triggering unsetupSession");
  582. unsetupSession(sm, sess);
  583. }
  584. }
  585. }
  586. static void periodically(void* vSessionManager)
  587. {
  588. struct SessionManager_pvt* sm = Identity_check((struct SessionManager_pvt*) vSessionManager);
  589. checkTimedOutSessions(sm);
  590. checkTimedOutBuffers(sm);
  591. }
  592. static void bufferPacket(struct SessionManager_pvt* sm, struct Message* msg)
  593. {
  594. Assert_true(Message_getLength(msg) >= (RouteHeader_SIZE + DataHeader_SIZE));
  595. struct RouteHeader* header = (struct RouteHeader*) msg->msgbytes;
  596. // We should never be sending CJDHT messages without full version, key, path known.
  597. struct DataHeader* dataHeader = (struct DataHeader*) &header[1];
  598. Assert_true(DataHeader_getContentType(dataHeader) != ContentType_CJDHT);
  599. uint8_t ipStr[40];
  600. AddrTools_printIp(ipStr, header->ip6);
  601. int index = Map_BufferedMessages_indexForKey((struct Ip6*)header->ip6, &sm->bufMap);
  602. if (index > -1) {
  603. struct BufferedMessage* buffered = sm->bufMap.values[index];
  604. Map_BufferedMessages_remove(index, &sm->bufMap);
  605. Allocator_free(buffered->alloc);
  606. Log_debug(sm->log, "Buffering a packet to [%s] DROP replacing one in the buffer", ipStr);
  607. } else {
  608. Log_debug(sm->log, "Buffering a packet to [%s]", ipStr);
  609. }
  610. if ((int)sm->bufMap.count >= sm->pub.maxBufferedMessages) {
  611. checkTimedOutBuffers(sm);
  612. if ((int)sm->bufMap.count >= sm->pub.maxBufferedMessages) {
  613. Log_debug(sm->log, "DROP message needing lookup maxBufferedMessages ([%d]) is reached",
  614. sm->pub.maxBufferedMessages);
  615. return;
  616. }
  617. }
  618. struct Allocator* lookupAlloc = Allocator_child(sm->alloc);
  619. struct BufferedMessage* buffered =
  620. Allocator_calloc(lookupAlloc, sizeof(struct BufferedMessage), 1);
  621. buffered->msg = msg;
  622. buffered->alloc = lookupAlloc;
  623. buffered->timeSentMilliseconds = Time_currentTimeMilliseconds();
  624. Allocator_adopt(lookupAlloc, Message_getAlloc(msg));
  625. Assert_true(Map_BufferedMessages_put((struct Ip6*)header->ip6, &buffered, &sm->bufMap) > -1);
  626. }
  627. static void needsLookup(struct SessionManager_pvt* sm, struct Message* msg)
  628. {
  629. struct RouteHeader* header = (struct RouteHeader*) msg->msgbytes;
  630. bufferPacket(sm, msg);
  631. triggerSearch(sm, header->ip6, Endian_hostToBigEndian32(header->version_be));
  632. }
  633. static Iface_DEFUN readyToSend(struct Message* msg,
  634. struct SessionManager_pvt* sm,
  635. struct SessionManager_Session_pvt* sess)
  636. {
  637. struct RouteHeader header;
  638. Er_assert(Message_epop(msg, &header, RouteHeader_SIZE));
  639. Assert_true(header.sh.label_be != 0xffffffffffffffffull);
  640. Ca_resetIfTimeout(sess->pub.caSession);
  641. if (Ca_getState(sess->pub.caSession) < Ca_State_RECEIVED_KEY) {
  642. // Put the handle into the message so that the other end knows how to address the session
  643. Er_assert(Message_epush32be(msg, sess->pub.receiveHandle));
  644. }
  645. sess->pub.bytesOut += Message_getLength(msg);
  646. // Move the route header to additional data
  647. Er_assert(Message_epushAd(msg, &header, RouteHeader_SIZE));
  648. return Iface_next(&sess->plaintext, msg); // --> afterEncrypt
  649. }
  650. static Iface_DEFUN outgoingCtrlFrame(struct Message* msg, struct SessionManager_pvt* sm)
  651. {
  652. Assert_true(Message_getLength(msg) >= RouteHeader_SIZE);
  653. struct RouteHeader* header = (struct RouteHeader*) msg->msgbytes;
  654. if (!Bits_isZero(header->publicKey, 32) || !Bits_isZero(header->ip6, 16)) {
  655. Log_debug(sm->log, "DROP Ctrl frame with non-zero destination key or IP");
  656. return Error(msg, "INVALID");
  657. }
  658. if (!(header->flags & RouteHeader_flags_CTRLMSG)) {
  659. Log_debug(sm->log, "DROP Ctrl frame w/o RouteHeader_flags_CTRLMSG flag");
  660. return Error(msg, "INVALID");
  661. }
  662. struct SwitchHeader sh;
  663. Bits_memcpy(&sh, &header->sh, SwitchHeader_SIZE);
  664. Er_assert(Message_epop(msg, NULL, RouteHeader_SIZE));
  665. Er_assert(Message_epush32be(msg, 0xffffffff));
  666. Er_assert(Message_epush(msg, &sh, SwitchHeader_SIZE));
  667. return Iface_next(&sm->pub.switchIf, msg);
  668. }
  669. static Iface_DEFUN incomingFromInsideIf(struct Message* msg, struct Iface* iface)
  670. {
  671. struct SessionManager_pvt* sm =
  672. Identity_containerOf(iface, struct SessionManager_pvt, pub.insideIf);
  673. Assert_true(Message_getLength(msg) >= RouteHeader_SIZE);
  674. struct RouteHeader* header = (struct RouteHeader*) msg->msgbytes;
  675. if (header->flags & RouteHeader_flags_CTRLMSG) {
  676. return outgoingCtrlFrame(msg, sm);
  677. }
  678. Assert_true(Message_getLength(msg) >= RouteHeader_SIZE + DataHeader_SIZE);
  679. struct DataHeader* dataHeader = (struct DataHeader*) &header[1];
  680. struct SessionManager_Session_pvt* sess = sessionForIp6(header->ip6, sm);
  681. if (!sess) {
  682. if (!Bits_isZero(header->publicKey, 32) && header->version_be) {
  683. sess = getSession(sm,
  684. header->ip6,
  685. header->publicKey,
  686. Endian_bigEndianToHost32(header->version_be),
  687. Endian_bigEndianToHost64(header->sh.label_be),
  688. ((header->sh.label_be) ? Metric_SM_SEND : Metric_DEAD_LINK));
  689. } else {
  690. needsLookup(sm, msg);
  691. return NULL;
  692. }
  693. }
  694. if (!(header->flags & RouteHeader_flags_PATHFINDER)) {
  695. // It's real life user traffic, lets tag the time of last use
  696. sess->pub.timeOfLastUsage = Time_currentTimeMilliseconds();
  697. }
  698. if (header->version_be) { sess->pub.version = Endian_bigEndianToHost32(header->version_be); }
  699. if (!sess->pub.version) {
  700. needsLookup(sm, msg);
  701. return NULL;
  702. }
  703. if (header->sh.label_be) {
  704. // fallthrough
  705. } else if (sess->pub.paths[0].metric < Metric_DEAD_LINK) {
  706. Bits_memset(&header->sh, 0, SwitchHeader_SIZE);
  707. header->sh.label_be = Endian_hostToBigEndian64(sess->pub.paths[0].label);
  708. SwitchHeader_setVersion(&header->sh, SwitchHeader_CURRENT_VERSION);
  709. } else {
  710. needsLookup(sm, msg);
  711. return NULL;
  712. }
  713. // Forward secrecy, only send dht messages until the session is setup.
  714. Ca_resetIfTimeout(sess->pub.caSession);
  715. if (Ca_getState(sess->pub.caSession) < Ca_State_RECEIVED_KEY) {
  716. if (DataHeader_getContentType(dataHeader) == ContentType_CJDHT) {
  717. if (sess->pub.timeOfLastUsage) {
  718. // Any time any message of any kind is sent down a link that is
  719. // currently in use, keep firing off unsetupSession
  720. unsetupSession(sm, sess);
  721. }
  722. } else {
  723. debugSession0(sm->log, sess,
  724. Endian_bigEndianToHost64(header->sh.label_be), "user traffic, unsetupSession");
  725. bufferPacket(sm, msg);
  726. unsetupSession(sm, sess);
  727. return NULL;
  728. }
  729. }
  730. return readyToSend(msg, sm, sess);
  731. }
  732. static Iface_DEFUN sessions(struct SessionManager_pvt* sm,
  733. uint32_t sourcePf,
  734. struct Allocator* tempAlloc)
  735. {
  736. for (int i = 0; i < (int)sm->ifaceMap.count; i++) {
  737. struct SessionManager_Session_pvt* sess = sm->ifaceMap.values[i];
  738. sendSession(sess, &sess->pub.paths[0], sourcePf, PFChan_Core_SESSION);
  739. }
  740. return NULL;
  741. }
  742. static Iface_DEFUN incomingFromEventIf(struct Message* msg, struct Iface* iface)
  743. {
  744. struct SessionManager_pvt* sm = Identity_containerOf(iface, struct SessionManager_pvt, eventIf);
  745. enum PFChan_Pathfinder ev = Er_assert(Message_epop32be(msg));
  746. uint32_t sourcePf = Er_assert(Message_epop32be(msg));
  747. if (ev == PFChan_Pathfinder_SESSIONS) {
  748. Assert_true(!Message_getLength(msg));
  749. return sessions(sm, sourcePf, Message_getAlloc(msg));
  750. }
  751. Assert_true(ev == PFChan_Pathfinder_NODE);
  752. struct PFChan_Node node;
  753. Er_assert(Message_epop(msg, &node, PFChan_Node_SIZE));
  754. Assert_true(!Message_getLength(msg));
  755. int index = Map_BufferedMessages_indexForKey((struct Ip6*)node.ip6, &sm->bufMap);
  756. struct SessionManager_Session_pvt* sess = sessionForIp6(node.ip6, sm);
  757. if (!sess) {
  758. // Node we don't care about.
  759. if (index == -1) { return NULL; }
  760. // Broken path to a node we don't have a session for...
  761. if (node.metric_be == Metric_DEAD_LINK) { return NULL; }
  762. }
  763. sess = getSession(sm,
  764. node.ip6,
  765. node.publicKey,
  766. Endian_bigEndianToHost32(node.version_be),
  767. Endian_bigEndianToHost64(node.path_be),
  768. Endian_bigEndianToHost32(node.metric_be));
  769. // Send what's on the buffer...
  770. if (index > -1 && Ca_getState(sess->pub.caSession) >= Ca_State_RECEIVED_KEY) {
  771. struct BufferedMessage* bm = sm->bufMap.values[index];
  772. Iface_CALL(readyToSend, bm->msg, sm, sess);
  773. Map_BufferedMessages_remove(index, &sm->bufMap);
  774. Allocator_free(bm->alloc);
  775. }
  776. return NULL;
  777. }
  778. struct SessionManager* SessionManager_new(struct Allocator* allocator,
  779. struct EventBase* eventBase,
  780. Ca_t* cryptoAuth,
  781. struct Random* rand,
  782. struct Log* log,
  783. struct EventEmitter* ee)
  784. {
  785. struct Allocator* alloc = Allocator_child(allocator);
  786. struct SessionManager_pvt* sm = Allocator_calloc(alloc, sizeof(struct SessionManager_pvt), 1);
  787. sm->alloc = alloc;
  788. sm->pub.switchIf.send = incomingFromSwitchIf;
  789. sm->pub.insideIf.send = incomingFromInsideIf;
  790. sm->bufMap.allocator = alloc;
  791. sm->ifaceMap.allocator = alloc;
  792. sm->log = log;
  793. sm->cryptoAuth = cryptoAuth;
  794. sm->eventBase = eventBase;
  795. sm->pub.sessionTimeoutMilliseconds = SessionManager_SESSION_TIMEOUT_MILLISECONDS_DEFAULT;
  796. sm->pub.maxBufferedMessages = SessionManager_MAX_BUFFERED_MESSAGES_DEFAULT;
  797. sm->pub.sessionSearchAfterMilliseconds =
  798. SessionManager_SESSION_SEARCH_AFTER_MILLISECONDS_DEFAULT;
  799. Ca_getPubKey(cryptoAuth, sm->ourPubKey);
  800. sm->eventIf.send = incomingFromEventIf;
  801. EventEmitter_regCore(ee, &sm->eventIf, PFChan_Pathfinder_NODE);
  802. EventEmitter_regCore(ee, &sm->eventIf, PFChan_Pathfinder_SESSIONS);
  803. sm->firstHandle =
  804. (Random_uint32(rand) % (MAX_FIRST_HANDLE - MIN_FIRST_HANDLE)) + MIN_FIRST_HANDLE;
  805. Timeout_setInterval(periodically, sm, 1000, eventBase, alloc);
  806. Identity_set(sm);
  807. return &sm->pub;
  808. }