Peer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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. if (likely(RR->node->putPacket(tPtr,localSocket,atAddress,outp.unsafeData,ii)))
  187. return ii;
  188. return 0;
  189. }
  190. void Peer::pulse(void *const tPtr,const int64_t now,const bool isRoot)
  191. {
  192. RWMutex::Lock l(m_lock);
  193. // Determine if we need a new ephemeral key pair and if a new HELLO needs
  194. // to be sent. The latter happens every ZT_PEER_HELLO_INTERVAL or if a new
  195. // ephemeral key pair is generated.
  196. bool needHello = false;
  197. 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))) ) ) {
  198. m_ephemeralPair.generate();
  199. needHello = true;
  200. } else if ((now - m_lastSentHello) >= ZT_PEER_HELLO_INTERVAL) {
  201. needHello = true;
  202. }
  203. // Prioritize paths and more importantly for here forget dead ones.
  204. m_prioritizePaths(now);
  205. if (m_tryQueue.empty()) {
  206. if (m_alivePathCount == 0) {
  207. // If there are no living paths and nothing in the try queue, try addresses
  208. // from any locator we have on file or that are fetched via the external API
  209. // callback (if one was supplied).
  210. if (m_locator) {
  211. for(Vector<Endpoint>::const_iterator ep(m_locator->endpoints().begin());ep!=m_locator->endpoints().end();++ep) {
  212. if (ep->type == ZT_ENDPOINT_TYPE_IP_UDP) {
  213. RR->t->tryingNewPath(tPtr, 0x84b22322, m_id, ep->ip(), InetAddress::NIL, 0, 0, Identity::NIL);
  214. sent(now,m_sendProbe(tPtr,-1,ep->ip(),nullptr,0,now));
  215. }
  216. }
  217. }
  218. InetAddress addr;
  219. if (RR->node->externalPathLookup(tPtr, m_id, -1, addr)) {
  220. if ((addr)&&(RR->node->shouldUsePathForZeroTierTraffic(tPtr, m_id, -1, addr))) {
  221. RR->t->tryingNewPath(tPtr, 0x84a10000, m_id, addr, InetAddress::NIL, 0, 0, Identity::NIL);
  222. sent(now,m_sendProbe(tPtr,-1,addr,nullptr,0,now));
  223. }
  224. }
  225. }
  226. } else {
  227. // Attempt up to ZT_NAT_T_MAX_QUEUED_ATTEMPTS_PER_PULSE queued addresses.
  228. for (int k=0;k<ZT_NAT_T_MAX_QUEUED_ATTEMPTS_PER_PULSE;++k) {
  229. p_TryQueueItem &qi = m_tryQueue.front();
  230. if (likely((now - qi.ts) < ZT_PATH_ALIVE_TIMEOUT)) {
  231. if (qi.target.type == ZT_ENDPOINT_TYPE_IP_UDP) {
  232. // Skip entry if it overlaps with any currently active IP.
  233. for(unsigned int i=0;i<m_alivePathCount;++i) {
  234. if (m_paths[i]->address().ipsEqual(qi.target.ip()))
  235. goto skip_tryQueue_item;
  236. }
  237. if ((m_alivePathCount == 0) && (qi.natMustDie) && (RR->node->natMustDie())) {
  238. // Attempt aggressive NAT traversal if both requested and enabled. This sends a probe
  239. // to all ports under 1024, which assumes that the peer has bound to such a port and
  240. // has attempted to initiate a connection through it. This can traverse a decent number
  241. // of symmetric NATs at the cost of 32KiB per attempt and the potential to trigger IDS
  242. // systems by looking like a port scan (because it is).
  243. uint16_t ports[1023];
  244. for (unsigned int i=0;i<1023;++i)
  245. ports[i] = (uint64_t)(i + 1);
  246. for (unsigned int i=0;i<512;++i) {
  247. const uint64_t rn = Utils::random();
  248. const unsigned int a = (unsigned int)rn % 1023;
  249. const unsigned int b = (unsigned int)(rn >> 32U) % 1023;
  250. if (a != b) {
  251. const uint16_t tmp = ports[a];
  252. ports[a] = ports[b];
  253. ports[b] = tmp;
  254. }
  255. }
  256. sent(now,m_sendProbe(tPtr, -1, qi.target.ip(), ports, 1023, now));
  257. } else {
  258. sent(now,m_sendProbe(tPtr, -1, qi.target.ip(), nullptr, 0, now));
  259. }
  260. }
  261. }
  262. skip_tryQueue_item:
  263. m_tryQueue.pop_front();
  264. if (m_tryQueue.empty())
  265. break;
  266. }
  267. }
  268. // Do keepalive on all currently active paths, sending HELLO to the first
  269. // if needHello is true and sending small keepalives to others.
  270. uint64_t randomJunk = Utils::random();
  271. for(unsigned int i=0;i<m_alivePathCount;++i) {
  272. if (needHello) {
  273. needHello = false;
  274. const unsigned int bytes = hello(tPtr, m_paths[i]->localSocket(), m_paths[i]->address(), now);
  275. m_paths[i]->sent(now, bytes);
  276. sent(now,bytes);
  277. m_lastSentHello = now;
  278. } else if ((now - m_paths[i]->lastOut()) >= ZT_PATH_KEEPALIVE_PERIOD) {
  279. m_paths[i]->send(RR, tPtr, reinterpret_cast<uint8_t *>(&randomJunk) + (i & 7U), 1, now);
  280. sent(now,1);
  281. }
  282. }
  283. // Send a HELLO indirectly if we were not able to send one via any direct path.
  284. if (needHello) {
  285. const SharedPtr<Peer> root(RR->topology->root());
  286. if (root) {
  287. const SharedPtr<Path> via(root->path(now));
  288. if (via) {
  289. const unsigned int bytes = hello(tPtr,via->localSocket(),via->address(),now);
  290. via->sent(now,bytes);
  291. root->relayed(now,bytes);
  292. sent(now,bytes);
  293. m_lastSentHello = now;
  294. }
  295. }
  296. }
  297. }
  298. void Peer::contact(void *tPtr,const int64_t now,const Endpoint &ep,const bool natMustDie)
  299. {
  300. static uint8_t foo = 0;
  301. RWMutex::Lock l(m_lock);
  302. if (ep.isInetAddr()&&ep.ip().isV4()) {
  303. // For IPv4 addresses we send a tiny packet with a low TTL, which helps to
  304. // traverse some NAT types. It has no effect otherwise. It's important to
  305. // send this right away in case this is a coordinated attempt via RENDEZVOUS.
  306. RR->node->putPacket(tPtr,-1,ep.ip(),&foo,1,2);
  307. ++foo;
  308. }
  309. for(List<p_TryQueueItem>::iterator i(m_tryQueue.begin());i!=m_tryQueue.end();++i) {
  310. if (i->target == ep) {
  311. i->ts = now;
  312. i->natMustDie = natMustDie;
  313. return;
  314. }
  315. }
  316. m_tryQueue.push_back(p_TryQueueItem(now, ep, natMustDie));
  317. }
  318. void Peer::resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now)
  319. {
  320. RWMutex::Lock l(m_lock);
  321. unsigned int pc = 0;
  322. for(unsigned int i=0;i<m_alivePathCount;++i) {
  323. if ((m_paths[i]) && ((m_paths[i]->address().family() == inetAddressFamily) && (m_paths[i]->address().ipScope() == scope))) {
  324. const unsigned int bytes = m_sendProbe(tPtr, m_paths[i]->localSocket(), m_paths[i]->address(), nullptr, 0, now);
  325. m_paths[i]->sent(now, bytes);
  326. sent(now,bytes);
  327. } else if (pc != i) {
  328. m_paths[pc++] = m_paths[i];
  329. }
  330. }
  331. m_alivePathCount = pc;
  332. while (pc < ZT_MAX_PEER_NETWORK_PATHS)
  333. m_paths[pc++].zero();
  334. }
  335. bool Peer::directlyConnected(int64_t now)
  336. {
  337. if ((now - m_lastPrioritizedPaths) > ZT_PEER_PRIORITIZE_PATHS_INTERVAL) {
  338. RWMutex::Lock l(m_lock);
  339. m_prioritizePaths(now);
  340. return m_alivePathCount > 0;
  341. } else {
  342. RWMutex::RLock l(m_lock);
  343. return m_alivePathCount > 0;
  344. }
  345. }
  346. void Peer::getAllPaths(Vector< SharedPtr<Path> > &paths)
  347. {
  348. RWMutex::RLock l(m_lock);
  349. paths.clear();
  350. paths.reserve(m_alivePathCount);
  351. paths.assign(m_paths, m_paths + m_alivePathCount);
  352. }
  353. void Peer::save(void *tPtr) const
  354. {
  355. uint8_t buf[8 + ZT_PEER_MARSHAL_SIZE_MAX];
  356. // Prefix each saved peer with the current timestamp.
  357. Utils::storeBigEndian<uint64_t>(buf,(uint64_t)RR->node->now());
  358. const int len = marshal(buf + 8);
  359. if (len > 0) {
  360. uint64_t id[2];
  361. id[0] = m_id.address().toInt();
  362. id[1] = 0;
  363. RR->node->stateObjectPut(tPtr,ZT_STATE_OBJECT_PEER,id,buf,(unsigned int)len + 8);
  364. }
  365. }
  366. int Peer::marshal(uint8_t data[ZT_PEER_MARSHAL_SIZE_MAX]) const noexcept
  367. {
  368. RWMutex::RLock l(m_lock);
  369. if (!m_identityKey)
  370. return -1;
  371. data[0] = 0; // serialized peer version
  372. // Include our identity's address to detect if this changes and require
  373. // recomputation of m_identityKey.
  374. RR->identity.address().copyTo(data + 1);
  375. // SECURITY: encryption in place is only to protect secrets if they are
  376. // cached to local storage. It's not used over the wire. Dumb ECB is fine
  377. // because secret keys are random and have no structure to reveal.
  378. RR->localCacheSymmetric.encrypt(m_identityKey->secret,data + 6);
  379. RR->localCacheSymmetric.encrypt(m_identityKey->secret + 22,data + 17);
  380. RR->localCacheSymmetric.encrypt(m_identityKey->secret + 38,data + 33);
  381. int p = 54;
  382. int s = m_id.marshal(data + p, false);
  383. if (s < 0)
  384. return -1;
  385. p += s;
  386. if (m_locator) {
  387. data[p++] = 1;
  388. s = m_locator->marshal(data + p);
  389. if (s <= 0)
  390. return s;
  391. p += s;
  392. } else {
  393. data[p++] = 0;
  394. }
  395. Utils::storeBigEndian(data + p,(uint16_t)m_vProto);
  396. p += 2;
  397. Utils::storeBigEndian(data + p,(uint16_t)m_vMajor);
  398. p += 2;
  399. Utils::storeBigEndian(data + p,(uint16_t)m_vMinor);
  400. p += 2;
  401. Utils::storeBigEndian(data + p,(uint16_t)m_vRevision);
  402. p += 2;
  403. data[p++] = 0;
  404. data[p++] = 0;
  405. return p;
  406. }
  407. int Peer::unmarshal(const uint8_t *restrict data,const int len) noexcept
  408. {
  409. RWMutex::Lock l(m_lock);
  410. if ((len <= 54) || (data[0] != 0))
  411. return -1;
  412. m_identityKey.zero();
  413. m_ephemeralKeys[0].zero();
  414. m_ephemeralKeys[1].zero();
  415. if (Address(data + 1) == RR->identity.address()) {
  416. uint8_t k[ZT_SYMMETRIC_KEY_SIZE];
  417. static_assert(ZT_SYMMETRIC_KEY_SIZE == 48,"marshal() and unmarshal() must be revisited if ZT_SYMMETRIC_KEY_SIZE is changed");
  418. RR->localCacheSymmetric.decrypt(data + 1,k);
  419. RR->localCacheSymmetric.decrypt(data + 17,k + 16);
  420. RR->localCacheSymmetric.decrypt(data + 33,k + 32);
  421. m_identityKey.set(new SymmetricKey(RR->node->now(),k));
  422. Utils::burn(k,sizeof(k));
  423. }
  424. int p = 49;
  425. int s = m_id.unmarshal(data + 38, len - 38);
  426. if (s < 0)
  427. return s;
  428. p += s;
  429. if (!m_identityKey) {
  430. uint8_t k[ZT_SYMMETRIC_KEY_SIZE];
  431. if (!RR->identity.agree(m_id,k))
  432. return -1;
  433. m_identityKey.set(new SymmetricKey(RR->node->now(),k));
  434. Utils::burn(k,sizeof(k));
  435. }
  436. if (data[p] == 0) {
  437. ++p;
  438. m_locator.zero();
  439. } else if (data[p] == 1) {
  440. ++p;
  441. Locator *const loc = new Locator();
  442. s = loc->unmarshal(data + p, len - p);
  443. m_locator.set(loc);
  444. if (s < 0)
  445. return s;
  446. p += s;
  447. } else {
  448. return -1;
  449. }
  450. if ((p + 10) > len)
  451. return -1;
  452. m_vProto = Utils::loadBigEndian<uint16_t>(data + p); p += 2;
  453. m_vMajor = Utils::loadBigEndian<uint16_t>(data + p); p += 2;
  454. m_vMinor = Utils::loadBigEndian<uint16_t>(data + p); p += 2;
  455. m_vRevision = Utils::loadBigEndian<uint16_t>(data + p); p += 2;
  456. p += 2 + (int)Utils::loadBigEndian<uint16_t>(data + p);
  457. m_deriveSecondaryIdentityKeys();
  458. return (p > len) ? -1 : p;
  459. }
  460. struct _PathPriorityComparisonOperator
  461. {
  462. ZT_INLINE bool operator()(const SharedPtr<Path> &a,const SharedPtr<Path> &b) const noexcept
  463. {
  464. // Sort in descending order of most recent receive time.
  465. return (a->lastIn() > b->lastIn());
  466. }
  467. };
  468. void Peer::m_prioritizePaths(int64_t now)
  469. {
  470. // assumes _lock is locked for writing
  471. m_lastPrioritizedPaths = now;
  472. if (m_alivePathCount > 0) {
  473. // Sort paths in descending order of priority.
  474. std::sort(m_paths, m_paths + m_alivePathCount, _PathPriorityComparisonOperator());
  475. // Let go of paths that have expired.
  476. for (unsigned int i = 0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  477. if ((!m_paths[i]) || (!m_paths[i]->alive(now))) {
  478. m_alivePathCount = i;
  479. for (;i < ZT_MAX_PEER_NETWORK_PATHS;++i)
  480. m_paths[i].zero();
  481. break;
  482. }
  483. }
  484. }
  485. }
  486. unsigned int Peer::m_sendProbe(void *tPtr,int64_t localSocket,const InetAddress &atAddress,const uint16_t *ports,const unsigned int numPorts,int64_t now)
  487. {
  488. // Assumes m_lock is locked
  489. const SharedPtr<SymmetricKey> k(m_key());
  490. const uint64_t packetId = k->nextMessage(RR->identity.address(),m_id.address());
  491. uint8_t p[ZT_PROTO_MIN_PACKET_LENGTH + 1];
  492. Utils::storeAsIsEndian<uint64_t>(p + ZT_PROTO_PACKET_ID_INDEX,packetId);
  493. m_id.address().copyTo(p + ZT_PROTO_PACKET_DESTINATION_INDEX);
  494. RR->identity.address().copyTo(p + ZT_PROTO_PACKET_SOURCE_INDEX);
  495. p[ZT_PROTO_PACKET_FLAGS_INDEX] = 0;
  496. p[ZT_PROTO_PACKET_VERB_INDEX] = Protocol::VERB_ECHO;
  497. p[ZT_PROTO_PACKET_VERB_INDEX + 1] = 0; // arbitrary payload
  498. Protocol::armor(p,ZT_PROTO_MIN_PACKET_LENGTH + 1,k,cipher());
  499. RR->expect->sending(packetId,now);
  500. if (numPorts > 0) {
  501. InetAddress tmp(atAddress);
  502. for(unsigned int i=0;i<numPorts;++i) {
  503. tmp.setPort(ports[i]);
  504. RR->node->putPacket(tPtr,-1,tmp,p,ZT_PROTO_MIN_PACKET_LENGTH + 1);
  505. }
  506. return ZT_PROTO_MIN_PACKET_LENGTH * numPorts;
  507. } else {
  508. RR->node->putPacket(tPtr,-1,atAddress,p,ZT_PROTO_MIN_PACKET_LENGTH + 1);
  509. return ZT_PROTO_MIN_PACKET_LENGTH;
  510. }
  511. }
  512. void Peer::m_deriveSecondaryIdentityKeys() noexcept
  513. {
  514. uint8_t hk[ZT_SYMMETRIC_KEY_SIZE];
  515. KBKDFHMACSHA384(m_identityKey->secret,ZT_KBKDF_LABEL_HELLO_DICTIONARY_ENCRYPT,0,0,hk);
  516. m_helloCipher.init(hk);
  517. Utils::burn(hk,sizeof(hk));
  518. KBKDFHMACSHA384(m_identityKey->secret,ZT_KBKDF_LABEL_PACKET_HMAC,0,0,m_helloMacKey);
  519. }
  520. } // namespace ZeroTier