Peer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "Constants.hpp"
  14. #include "RuntimeEnvironment.hpp"
  15. #include "Trace.hpp"
  16. #include "Peer.hpp"
  17. #include "Topology.hpp"
  18. #include "SelfAwareness.hpp"
  19. #include "InetAddress.hpp"
  20. #include "Protocol.hpp"
  21. #include "Endpoint.hpp"
  22. #include "Expect.hpp"
  23. namespace ZeroTier {
  24. Peer::Peer(const RuntimeEnvironment *renv) :
  25. RR(renv),
  26. m_ephemeralPairTimestamp(0),
  27. m_lastReceive(0),
  28. m_lastSend(0),
  29. m_lastSentHello(),
  30. m_lastWhoisRequestReceived(0),
  31. m_lastEchoRequestReceived(0),
  32. m_lastPrioritizedPaths(0),
  33. m_lastProbeReceived(0),
  34. m_alivePathCount(0),
  35. m_tryQueue(),
  36. m_vProto(0),
  37. m_vMajor(0),
  38. m_vMinor(0),
  39. m_vRevision(0)
  40. {
  41. }
  42. Peer::~Peer()
  43. {
  44. Utils::burn(m_helloMacKey, sizeof(m_helloMacKey));
  45. }
  46. bool Peer::init(const Identity &peerIdentity)
  47. {
  48. RWMutex::Lock l(m_lock);
  49. if (m_id) // already initialized sanity check
  50. return false;
  51. m_id = peerIdentity;
  52. uint8_t k[ZT_SYMMETRIC_KEY_SIZE];
  53. if (!RR->identity.agree(peerIdentity, k))
  54. return false;
  55. m_identityKey.set(new SymmetricKey(RR->node->now(), k));
  56. Utils::burn(k, sizeof(k));
  57. m_deriveSecondaryIdentityKeys();
  58. return true;
  59. }
  60. void Peer::received(
  61. void *tPtr,
  62. const SharedPtr<Path> &path,
  63. const unsigned int hops,
  64. const uint64_t packetId,
  65. const unsigned int payloadLength,
  66. const Protocol::Verb verb,
  67. const Protocol::Verb inReVerb)
  68. {
  69. const int64_t now = RR->node->now();
  70. m_lastReceive = now;
  71. m_inMeter.log(now, payloadLength);
  72. if (hops == 0) {
  73. RWMutex::RMaybeWLock l(m_lock);
  74. // If this matches an existing path, skip path learning stuff. For the small number
  75. // of paths a peer will have linear scan is the fastest way to do lookup.
  76. for (unsigned int i = 0;i < m_alivePathCount;++i) {
  77. if (m_paths[i] == path)
  78. return;
  79. }
  80. // If we made it here, we don't already know this path.
  81. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr, m_id, path->localSocket(), path->address())) {
  82. // SECURITY: note that if we've made it here we expected this OK, see Expect.hpp.
  83. // There is replay protection in effect for OK responses.
  84. if (verb == Protocol::VERB_OK) {
  85. // If we're learning a new path convert the lock to an exclusive write lock.
  86. l.writing();
  87. // If the path list is full, replace the least recently active path. Otherwise append new path.
  88. unsigned int newPathIdx = 0;
  89. if (m_alivePathCount == ZT_MAX_PEER_NETWORK_PATHS) {
  90. int64_t lastReceiveTimeMax = 0;
  91. for (unsigned int i = 0;i < m_alivePathCount;++i) {
  92. if ((m_paths[i]->address().family() == path->address().family()) &&
  93. (m_paths[i]->localSocket() == path->localSocket()) && // TODO: should be localInterface when multipath is integrated
  94. (m_paths[i]->address().ipsEqual2(path->address()))) {
  95. // Replace older path if everything is the same except the port number, since NAT/firewall reboots
  96. // and other wacky stuff can change port number assignments.
  97. m_paths[i] = path;
  98. return;
  99. } else if (m_paths[i]->lastIn() >= lastReceiveTimeMax) {
  100. lastReceiveTimeMax = m_paths[i]->lastIn();
  101. newPathIdx = i;
  102. }
  103. }
  104. } else {
  105. newPathIdx = m_alivePathCount++;
  106. }
  107. InetAddress old;
  108. if (m_paths[newPathIdx])
  109. old = m_paths[newPathIdx]->address();
  110. m_paths[newPathIdx] = path;
  111. // Re-prioritize paths to include the new one.
  112. m_prioritizePaths(now);
  113. RR->t->learnedNewPath(tPtr, 0x582fabdd, packetId, m_id, path->address(), old);
  114. } else {
  115. path->sent(now, hello(tPtr, path->localSocket(), path->address(), now));
  116. RR->t->tryingNewPath(tPtr, 0xb7747ddd, m_id, path->address(), path->address(), packetId, (uint8_t)verb, m_id);
  117. }
  118. }
  119. }
  120. }
  121. void Peer::send(void *tPtr, int64_t now, const void *data, unsigned int len) noexcept
  122. {
  123. SharedPtr<Path> via(this->path(now));
  124. if (via) {
  125. via->send(RR, tPtr, data, len, now);
  126. } else {
  127. const SharedPtr<Peer> root(RR->topology->root());
  128. if ((root) && (root.ptr() != this)) {
  129. via = root->path(now);
  130. if (via) {
  131. via->send(RR, tPtr, data, len, now);
  132. root->relayed(now, len);
  133. } else {
  134. return;
  135. }
  136. } else {
  137. return;
  138. }
  139. }
  140. sent(now, len);
  141. }
  142. unsigned int Peer::hello(void *tPtr, int64_t localSocket, const InetAddress &atAddress, const int64_t now)
  143. {
  144. Buf outp;
  145. const uint64_t packetId = m_identityKey->nextMessage(RR->identity.address(), m_id.address());
  146. int ii = Protocol::newPacket(outp, packetId, m_id.address(), RR->identity.address(), Protocol::VERB_HELLO);
  147. outp.wI8(ii, ZT_PROTO_VERSION);
  148. outp.wI8(ii, ZEROTIER_VERSION_MAJOR);
  149. outp.wI8(ii, ZEROTIER_VERSION_MINOR);
  150. outp.wI16(ii, ZEROTIER_VERSION_REVISION);
  151. outp.wI64(ii, (uint64_t)now);
  152. outp.wO(ii, RR->identity);
  153. outp.wO(ii, atAddress);
  154. const int ivStart = ii;
  155. outp.wR(ii, 12);
  156. // LEGACY: the six reserved bytes after the IV exist for legacy compatibility with v1.x nodes.
  157. // Once those are dead they'll become just reserved bytes for future use as flags etc.
  158. outp.wI32(ii, 0); // reserved bytes
  159. void *const legacyMoonCountStart = outp.unsafeData + ii;
  160. outp.wI16(ii, 0);
  161. const uint64_t legacySalsaIv = packetId & ZT_CONST_TO_BE_UINT64(0xfffffffffffffff8ULL);
  162. Salsa20(m_identityKey->secret, &legacySalsaIv).crypt12(legacyMoonCountStart, legacyMoonCountStart, 2);
  163. const int cryptSectionStart = ii;
  164. FCV<uint8_t, 4096> md;
  165. Dictionary::append(md, ZT_PROTO_HELLO_NODE_META_INSTANCE_ID, RR->instanceId);
  166. outp.wI16(ii, (uint16_t)md.size());
  167. outp.wB(ii, md.data(), (unsigned int)md.size());
  168. if (unlikely((ii + ZT_HMACSHA384_LEN) > ZT_BUF_SIZE)) // sanity check: should be impossible
  169. return 0;
  170. AES::CTR ctr(m_helloCipher);
  171. void *const cryptSection = outp.unsafeData + ii;
  172. ctr.init(outp.unsafeData + ivStart, 0, cryptSection);
  173. ctr.crypt(cryptSection, ii - cryptSectionStart);
  174. ctr.finish();
  175. HMACSHA384(m_helloMacKey, outp.unsafeData, ii, outp.unsafeData + ii);
  176. ii += ZT_HMACSHA384_LEN;
  177. // LEGACY: we also need Poly1305 for v1.x peers.
  178. uint8_t polyKey[ZT_POLY1305_KEY_SIZE], perPacketKey[ZT_SALSA20_KEY_SIZE];
  179. Protocol::salsa2012DeriveKey(m_identityKey->secret, perPacketKey, outp, ii);
  180. Salsa20(perPacketKey, &packetId).crypt12(Utils::ZERO256, polyKey, sizeof(polyKey));
  181. Poly1305 p1305(polyKey);
  182. p1305.update(outp.unsafeData + ZT_PROTO_PACKET_ENCRYPTED_SECTION_START, ii - ZT_PROTO_PACKET_ENCRYPTED_SECTION_START);
  183. uint64_t polyMac[2];
  184. p1305.finish(polyMac);
  185. Utils::storeAsIsEndian<uint64_t>(outp.unsafeData + ZT_PROTO_PACKET_MAC_INDEX, polyMac[0]);
  186. return (likely(RR->node->putPacket(tPtr, localSocket, atAddress, outp.unsafeData, ii))) ? ii : 0;
  187. }
  188. void Peer::pulse(void *const tPtr, const int64_t now, const bool isRoot)
  189. {
  190. RWMutex::Lock l(m_lock);
  191. // Determine if we need a new ephemeral key pair and if a new HELLO needs
  192. // to be sent. The latter happens every ZT_PEER_HELLO_INTERVAL or if a new
  193. // ephemeral key pair is generated.
  194. bool needHello = false;
  195. if ((m_vProto >= 11) && (((now - m_ephemeralPairTimestamp) >= (ZT_SYMMETRIC_KEY_TTL / 2)) || ((m_ephemeralKeys[0]) && (m_ephemeralKeys[0]->odometer() >= (ZT_SYMMETRIC_KEY_TTL_MESSAGES / 2))))) {
  196. m_ephemeralPair.generate();
  197. needHello = true;
  198. } else if ((now - m_lastSentHello) >= ZT_PEER_HELLO_INTERVAL) {
  199. needHello = true;
  200. }
  201. // Prioritize paths and more importantly for here forget dead ones.
  202. m_prioritizePaths(now);
  203. if (m_tryQueue.empty()) {
  204. if (m_alivePathCount == 0) {
  205. // If there are no living paths and nothing in the try queue, try addresses
  206. // from any locator we have on file or that are fetched via the external API
  207. // callback (if one was supplied).
  208. if (m_locator) {
  209. for (Vector<Endpoint>::const_iterator ep(m_locator->endpoints().begin());ep != m_locator->endpoints().end();++ep) {
  210. if (ep->type == ZT_ENDPOINT_TYPE_IP_UDP) {
  211. RR->t->tryingNewPath(tPtr, 0x84b22322, m_id, ep->ip(), InetAddress::NIL, 0, 0, Identity::NIL);
  212. sent(now, m_sendProbe(tPtr, -1, ep->ip(), nullptr, 0, now));
  213. }
  214. }
  215. }
  216. InetAddress addr;
  217. if (RR->node->externalPathLookup(tPtr, m_id, -1, addr)) {
  218. if ((addr) && (RR->node->shouldUsePathForZeroTierTraffic(tPtr, m_id, -1, addr))) {
  219. RR->t->tryingNewPath(tPtr, 0x84a10000, m_id, addr, InetAddress::NIL, 0, 0, Identity::NIL);
  220. sent(now, m_sendProbe(tPtr, -1, addr, nullptr, 0, now));
  221. }
  222. }
  223. }
  224. } else {
  225. // Attempt up to ZT_NAT_T_MAX_QUEUED_ATTEMPTS_PER_PULSE queued addresses.
  226. unsigned int attempts = 0;
  227. for(;;) {
  228. p_TryQueueItem &qi = m_tryQueue.front();
  229. if (qi.target.isInetAddr()) {
  230. // Skip entry if it overlaps with any currently active IP.
  231. for (unsigned int i = 0;i < m_alivePathCount;++i) {
  232. if (m_paths[i]->address().ipsEqual(qi.target.ip()))
  233. goto discard_queue_item;
  234. }
  235. }
  236. if (qi.target.type == ZT_ENDPOINT_TYPE_IP_UDP) {
  237. ++attempts;
  238. if (qi.iteration < 0) {
  239. // If iteration is less than zero, try to contact the original address.
  240. // It may be set to a larger negative value to try multiple times such
  241. // as e.g. -3 to try 3 times.
  242. sent(now, m_sendProbe(tPtr, -1, qi.target.ip(), nullptr, 0, now));
  243. ++qi.iteration;
  244. goto requeue_item;
  245. } else if (qi.target.ip().isV4() && (m_alivePathCount == 0)) {
  246. // When iteration reaches zero the queue item is dropped unless it's
  247. // IPv4 and we have no direct paths. In that case some heavier NAT-t
  248. // strategies are attempted.
  249. if (qi.target.ip().port() < 1024) {
  250. // If the source port is privileged, we actually scan every possible
  251. // privileged port in random order slowly over multiple iterations
  252. // of pulse(). This is done in batches of ZT_NAT_T_PORT_SCAN_MAX.
  253. uint16_t ports[ZT_NAT_T_PORT_SCAN_MAX];
  254. unsigned int pn = 0;
  255. while ((pn < ZT_NAT_T_PORT_SCAN_MAX) && (qi.iteration < 1023)) {
  256. const uint16_t p = RR->randomPrivilegedPortOrder[qi.iteration++];
  257. if ((unsigned int)p != qi.target.ip().port())
  258. ports[pn++] = p;
  259. }
  260. if (pn > 0)
  261. sent(now, m_sendProbe(tPtr, -1, qi.target.ip(), ports, pn, now));
  262. if (qi.iteration < 1023)
  263. goto requeue_item;
  264. } else {
  265. // For un-privileged ports we'll try ZT_NAT_T_PORT_SCAN_MAX ports
  266. // beyond the one we were sent to catch some sequentially assigning
  267. // symmetric NATs.
  268. InetAddress tmp(qi.target.ip());
  269. unsigned int p = tmp.port() + 1 + (unsigned int)qi.iteration++;
  270. if (p > 65535)
  271. p -= 64512; // wrap back to 1024
  272. tmp.setPort(p);
  273. sent(now, m_sendProbe(tPtr, -1, tmp, nullptr, 0, now));
  274. if (qi.iteration < ZT_NAT_T_PORT_SCAN_MAX)
  275. goto requeue_item;
  276. }
  277. }
  278. }
  279. // Discard front item unless the code skips to requeue_item.
  280. discard_queue_item:
  281. m_tryQueue.pop_front();
  282. if ((m_tryQueue.empty()) || (attempts >= ZT_NAT_T_PORT_SCAN_MAX))
  283. break;
  284. else continue;
  285. // If the code skips here the front item is instead moved to the back.
  286. requeue_item:
  287. if (m_tryQueue.size() > 1)
  288. m_tryQueue.splice(m_tryQueue.end(), m_tryQueue, m_tryQueue.begin());
  289. if (attempts >= ZT_NAT_T_PORT_SCAN_MAX)
  290. break;
  291. else continue;
  292. }
  293. }
  294. // Do keepalive on all currently active paths, sending HELLO to the first
  295. // if needHello is true and sending small keepalives to others.
  296. uint64_t randomJunk = Utils::random();
  297. for (unsigned int i = 0;i < m_alivePathCount;++i) {
  298. if (needHello) {
  299. needHello = false;
  300. const unsigned int bytes = hello(tPtr, m_paths[i]->localSocket(), m_paths[i]->address(), now);
  301. m_paths[i]->sent(now, bytes);
  302. sent(now, bytes);
  303. m_lastSentHello = now;
  304. } else if ((now - m_paths[i]->lastOut()) >= ZT_PATH_KEEPALIVE_PERIOD) {
  305. m_paths[i]->send(RR, tPtr, reinterpret_cast<uint8_t *>(&randomJunk) + (i & 7U), 1, now);
  306. sent(now, 1);
  307. }
  308. }
  309. // Send a HELLO indirectly if we were not able to send one via any direct path.
  310. if (needHello) {
  311. const SharedPtr<Peer> root(RR->topology->root());
  312. if (root) {
  313. const SharedPtr<Path> via(root->path(now));
  314. if (via) {
  315. const unsigned int bytes = hello(tPtr, via->localSocket(), via->address(), now);
  316. via->sent(now, bytes);
  317. root->relayed(now, bytes);
  318. sent(now, bytes);
  319. m_lastSentHello = now;
  320. }
  321. }
  322. }
  323. }
  324. void Peer::contact(void *tPtr, const int64_t now, const Endpoint &ep, int tries)
  325. {
  326. static uint8_t foo = 0;
  327. RWMutex::Lock l(m_lock);
  328. // See if there's already a path to this endpoint and if so ignore it.
  329. if (ep.isInetAddr()) {
  330. if ((now - m_lastPrioritizedPaths) > ZT_PEER_PRIORITIZE_PATHS_INTERVAL)
  331. m_prioritizePaths(now);
  332. for (unsigned int i = 0;i < m_alivePathCount;++i) {
  333. if (m_paths[i]->address().ipsEqual(ep.ip()))
  334. return;
  335. }
  336. }
  337. // For IPv4 addresses we send a tiny packet with a low TTL, which helps to
  338. // traverse some NAT types. It has no effect otherwise.
  339. if (ep.isInetAddr() && ep.ip().isV4()) {
  340. ++foo;
  341. RR->node->putPacket(tPtr, -1, ep.ip(), &foo, 1, 2);
  342. }
  343. // Make sure address is not already in the try queue. If so just update it.
  344. for (List<p_TryQueueItem>::iterator i(m_tryQueue.begin());i != m_tryQueue.end();++i) {
  345. if (i->target.isSameAddress(ep)) {
  346. i->target = ep;
  347. i->iteration = -tries;
  348. return;
  349. }
  350. }
  351. m_tryQueue.push_back(p_TryQueueItem(ep, -tries));
  352. }
  353. void Peer::resetWithinScope(void *tPtr, InetAddress::IpScope scope, int inetAddressFamily, int64_t now)
  354. {
  355. RWMutex::Lock l(m_lock);
  356. unsigned int pc = 0;
  357. for (unsigned int i = 0;i < m_alivePathCount;++i) {
  358. if ((m_paths[i]) && ((m_paths[i]->address().family() == inetAddressFamily) && (m_paths[i]->address().ipScope() == scope))) {
  359. const unsigned int bytes = m_sendProbe(tPtr, m_paths[i]->localSocket(), m_paths[i]->address(), nullptr, 0, now);
  360. m_paths[i]->sent(now, bytes);
  361. sent(now, bytes);
  362. } else if (pc != i) {
  363. m_paths[pc++] = m_paths[i];
  364. }
  365. }
  366. m_alivePathCount = pc;
  367. while (pc < ZT_MAX_PEER_NETWORK_PATHS)
  368. m_paths[pc++].zero();
  369. }
  370. bool Peer::directlyConnected(int64_t now)
  371. {
  372. if ((now - m_lastPrioritizedPaths) > ZT_PEER_PRIORITIZE_PATHS_INTERVAL) {
  373. RWMutex::Lock l(m_lock);
  374. m_prioritizePaths(now);
  375. return m_alivePathCount > 0;
  376. } else {
  377. RWMutex::RLock l(m_lock);
  378. return m_alivePathCount > 0;
  379. }
  380. }
  381. void Peer::getAllPaths(Vector<SharedPtr<Path> > &paths)
  382. {
  383. RWMutex::RLock l(m_lock);
  384. paths.clear();
  385. paths.reserve(m_alivePathCount);
  386. paths.assign(m_paths, m_paths + m_alivePathCount);
  387. }
  388. void Peer::save(void *tPtr) const
  389. {
  390. uint8_t buf[8 + ZT_PEER_MARSHAL_SIZE_MAX];
  391. // Prefix each saved peer with the current timestamp.
  392. Utils::storeBigEndian<uint64_t>(buf, (uint64_t)RR->node->now());
  393. const int len = marshal(buf + 8);
  394. if (len > 0) {
  395. uint64_t id[2];
  396. id[0] = m_id.address().toInt();
  397. id[1] = 0;
  398. RR->node->stateObjectPut(tPtr, ZT_STATE_OBJECT_PEER, id, buf, (unsigned int)len + 8);
  399. }
  400. }
  401. int Peer::marshal(uint8_t data[ZT_PEER_MARSHAL_SIZE_MAX]) const noexcept
  402. {
  403. RWMutex::RLock l(m_lock);
  404. if (!m_identityKey)
  405. return -1;
  406. data[0] = 0; // serialized peer version
  407. // Include our identity's address to detect if this changes and require
  408. // recomputation of m_identityKey.
  409. RR->identity.address().copyTo(data + 1);
  410. // SECURITY: encryption in place is only to protect secrets if they are
  411. // cached to local storage. It's not used over the wire. Dumb ECB is fine
  412. // because secret keys are random and have no structure to reveal.
  413. RR->localCacheSymmetric.encrypt(m_identityKey->secret, data + 6);
  414. RR->localCacheSymmetric.encrypt(m_identityKey->secret + 22, data + 17);
  415. RR->localCacheSymmetric.encrypt(m_identityKey->secret + 38, data + 33);
  416. int p = 54;
  417. int s = m_id.marshal(data + p, false);
  418. if (s < 0)
  419. return -1;
  420. p += s;
  421. if (m_locator) {
  422. data[p++] = 1;
  423. s = m_locator->marshal(data + p);
  424. if (s <= 0)
  425. return s;
  426. p += s;
  427. } else {
  428. data[p++] = 0;
  429. }
  430. Utils::storeBigEndian(data + p, (uint16_t)m_vProto);
  431. p += 2;
  432. Utils::storeBigEndian(data + p, (uint16_t)m_vMajor);
  433. p += 2;
  434. Utils::storeBigEndian(data + p, (uint16_t)m_vMinor);
  435. p += 2;
  436. Utils::storeBigEndian(data + p, (uint16_t)m_vRevision);
  437. p += 2;
  438. data[p++] = 0;
  439. data[p++] = 0;
  440. return p;
  441. }
  442. int Peer::unmarshal(const uint8_t *restrict data, const int len) noexcept
  443. {
  444. RWMutex::Lock l(m_lock);
  445. if ((len <= 54) || (data[0] != 0))
  446. return -1;
  447. m_identityKey.zero();
  448. m_ephemeralKeys[0].zero();
  449. m_ephemeralKeys[1].zero();
  450. if (Address(data + 1) == RR->identity.address()) {
  451. uint8_t k[ZT_SYMMETRIC_KEY_SIZE];
  452. static_assert(ZT_SYMMETRIC_KEY_SIZE == 48, "marshal() and unmarshal() must be revisited if ZT_SYMMETRIC_KEY_SIZE is changed");
  453. RR->localCacheSymmetric.decrypt(data + 1, k);
  454. RR->localCacheSymmetric.decrypt(data + 17, k + 16);
  455. RR->localCacheSymmetric.decrypt(data + 33, k + 32);
  456. m_identityKey.set(new SymmetricKey(RR->node->now(), k));
  457. Utils::burn(k, sizeof(k));
  458. }
  459. int p = 49;
  460. int s = m_id.unmarshal(data + 38, len - 38);
  461. if (s < 0)
  462. return s;
  463. p += s;
  464. if (!m_identityKey) {
  465. uint8_t k[ZT_SYMMETRIC_KEY_SIZE];
  466. if (!RR->identity.agree(m_id, k))
  467. return -1;
  468. m_identityKey.set(new SymmetricKey(RR->node->now(), k));
  469. Utils::burn(k, sizeof(k));
  470. }
  471. if (data[p] == 0) {
  472. ++p;
  473. m_locator.zero();
  474. } else if (data[p] == 1) {
  475. ++p;
  476. Locator *const loc = new Locator();
  477. s = loc->unmarshal(data + p, len - p);
  478. m_locator.set(loc);
  479. if (s < 0)
  480. return s;
  481. p += s;
  482. } else {
  483. return -1;
  484. }
  485. if ((p + 10) > len)
  486. return -1;
  487. m_vProto = Utils::loadBigEndian<uint16_t>(data + p);
  488. p += 2;
  489. m_vMajor = Utils::loadBigEndian<uint16_t>(data + p);
  490. p += 2;
  491. m_vMinor = Utils::loadBigEndian<uint16_t>(data + p);
  492. p += 2;
  493. m_vRevision = Utils::loadBigEndian<uint16_t>(data + p);
  494. p += 2;
  495. p += 2 + (int)Utils::loadBigEndian<uint16_t>(data + p);
  496. m_deriveSecondaryIdentityKeys();
  497. return (p > len) ? -1 : p;
  498. }
  499. struct _PathPriorityComparisonOperator
  500. {
  501. ZT_INLINE bool operator()(const SharedPtr<Path> &a, const SharedPtr<Path> &b) const noexcept
  502. {
  503. // Sort in descending order of most recent receive time.
  504. return (a->lastIn() > b->lastIn());
  505. }
  506. };
  507. void Peer::m_prioritizePaths(int64_t now)
  508. {
  509. // assumes _lock is locked for writing
  510. m_lastPrioritizedPaths = now;
  511. if (m_alivePathCount > 0) {
  512. // Sort paths in descending order of priority.
  513. std::sort(m_paths, m_paths + m_alivePathCount, _PathPriorityComparisonOperator());
  514. // Let go of paths that have expired.
  515. for (unsigned int i = 0;i < ZT_MAX_PEER_NETWORK_PATHS;++i) {
  516. if ((!m_paths[i]) || (!m_paths[i]->alive(now))) {
  517. m_alivePathCount = i;
  518. for (;i < ZT_MAX_PEER_NETWORK_PATHS;++i)
  519. m_paths[i].zero();
  520. break;
  521. }
  522. }
  523. }
  524. }
  525. unsigned int Peer::m_sendProbe(void *tPtr, int64_t localSocket, const InetAddress &atAddress, const uint16_t *ports, const unsigned int numPorts, int64_t now)
  526. {
  527. // Assumes m_lock is locked
  528. const SharedPtr<SymmetricKey> k(m_key());
  529. const uint64_t packetId = k->nextMessage(RR->identity.address(), m_id.address());
  530. uint8_t p[ZT_PROTO_MIN_PACKET_LENGTH];
  531. Utils::storeAsIsEndian<uint64_t>(p + ZT_PROTO_PACKET_ID_INDEX, packetId);
  532. m_id.address().copyTo(p + ZT_PROTO_PACKET_DESTINATION_INDEX);
  533. RR->identity.address().copyTo(p + ZT_PROTO_PACKET_SOURCE_INDEX);
  534. p[ZT_PROTO_PACKET_FLAGS_INDEX] = 0;
  535. p[ZT_PROTO_PACKET_VERB_INDEX] = Protocol::VERB_ECHO;
  536. Protocol::armor(p, ZT_PROTO_MIN_PACKET_LENGTH, k, cipher());
  537. RR->expect->sending(packetId, now);
  538. if (numPorts > 0) {
  539. InetAddress tmp(atAddress);
  540. for (unsigned int i = 0;i < numPorts;++i) {
  541. tmp.setPort(ports[i]);
  542. RR->node->putPacket(tPtr, -1, tmp, p, ZT_PROTO_MIN_PACKET_LENGTH);
  543. }
  544. return ZT_PROTO_MIN_PACKET_LENGTH * numPorts;
  545. } else {
  546. RR->node->putPacket(tPtr, -1, atAddress, p, ZT_PROTO_MIN_PACKET_LENGTH);
  547. return ZT_PROTO_MIN_PACKET_LENGTH;
  548. }
  549. }
  550. void Peer::m_deriveSecondaryIdentityKeys() noexcept
  551. {
  552. uint8_t hk[ZT_SYMMETRIC_KEY_SIZE];
  553. KBKDFHMACSHA384(m_identityKey->secret, ZT_KBKDF_LABEL_HELLO_DICTIONARY_ENCRYPT, 0, 0, hk);
  554. m_helloCipher.init(hk);
  555. Utils::burn(hk, sizeof(hk));
  556. KBKDFHMACSHA384(m_identityKey->secret, ZT_KBKDF_LABEL_PACKET_HMAC, 0, 0, m_helloMacKey);
  557. }
  558. } // namespace ZeroTier