1
0

SessionManager.c 37 KB

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