Peer.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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. // Add or update entry in the endpoint cache. If this endpoint
  114. // is already present, its timesSeen count is incremented. Otherwise
  115. // it replaces the lowest ranked entry.
  116. std::sort(m_endpointCache, m_endpointCache + ZT_PEER_ENDPOINT_CACHE_SIZE);
  117. Endpoint thisEndpoint(path->address());
  118. for (unsigned int i = 0;; ++i) {
  119. if (i == (ZT_PEER_ENDPOINT_CACHE_SIZE - 1)) {
  120. m_endpointCache[i].target = thisEndpoint;
  121. m_endpointCache[i].lastSeen = now;
  122. break;
  123. } else if (m_endpointCache[i].target == thisEndpoint) {
  124. m_endpointCache[i].lastSeen = now;
  125. break;
  126. }
  127. }
  128. RR->t->learnedNewPath(tPtr, 0x582fabdd, packetId, m_id, path->address(), old);
  129. } else {
  130. path->sent(now, hello(tPtr, path->localSocket(), path->address(), now));
  131. RR->t->tryingNewPath(tPtr, 0xb7747ddd, m_id, path->address(), path->address(), packetId, (uint8_t)verb, m_id);
  132. }
  133. }
  134. }
  135. }
  136. void Peer::send(void *tPtr, int64_t now, const void *data, unsigned int len) noexcept
  137. {
  138. SharedPtr< Path > via(this->path(now));
  139. if (via) {
  140. via->send(RR, tPtr, data, len, now);
  141. } else {
  142. const SharedPtr< Peer > root(RR->topology->root());
  143. if ((root) && (root.ptr() != this)) {
  144. via = root->path(now);
  145. if (via) {
  146. via->send(RR, tPtr, data, len, now);
  147. root->relayed(now, len);
  148. } else {
  149. return;
  150. }
  151. } else {
  152. return;
  153. }
  154. }
  155. sent(now, len);
  156. }
  157. unsigned int Peer::hello(void *tPtr, int64_t localSocket, const InetAddress &atAddress, const int64_t now)
  158. {
  159. Buf outp;
  160. const uint64_t packetId = m_identityKey->nextMessage(RR->identity.address(), m_id.address());
  161. int ii = Protocol::newPacket(outp, packetId, m_id.address(), RR->identity.address(), Protocol::VERB_HELLO);
  162. outp.wI8(ii, ZT_PROTO_VERSION);
  163. outp.wI8(ii, ZEROTIER_VERSION_MAJOR);
  164. outp.wI8(ii, ZEROTIER_VERSION_MINOR);
  165. outp.wI16(ii, ZEROTIER_VERSION_REVISION);
  166. outp.wI64(ii, (uint64_t)now);
  167. outp.wO(ii, RR->identity);
  168. outp.wO(ii, atAddress);
  169. const int ivStart = ii;
  170. outp.wR(ii, 12);
  171. // LEGACY: the six reserved bytes after the IV exist for legacy compatibility with v1.x nodes.
  172. // Once those are dead they'll become just reserved bytes for future use as flags etc.
  173. outp.wI32(ii, 0); // reserved bytes
  174. void *const legacyMoonCountStart = outp.unsafeData + ii;
  175. outp.wI16(ii, 0);
  176. const uint64_t legacySalsaIv = packetId & ZT_CONST_TO_BE_UINT64(0xfffffffffffffff8ULL);
  177. Salsa20(m_identityKey->secret, &legacySalsaIv).crypt12(legacyMoonCountStart, legacyMoonCountStart, 2);
  178. const int cryptSectionStart = ii;
  179. FCV< uint8_t, 4096 > md;
  180. Dictionary::append(md, ZT_PROTO_HELLO_NODE_META_INSTANCE_ID, RR->instanceId);
  181. outp.wI16(ii, (uint16_t)md.size());
  182. outp.wB(ii, md.data(), (unsigned int)md.size());
  183. if (unlikely((ii + ZT_HMACSHA384_LEN) > ZT_BUF_SIZE)) // sanity check: should be impossible
  184. return 0;
  185. AES::CTR ctr(m_helloCipher);
  186. void *const cryptSection = outp.unsafeData + ii;
  187. ctr.init(outp.unsafeData + ivStart, 0, cryptSection);
  188. ctr.crypt(cryptSection, ii - cryptSectionStart);
  189. ctr.finish();
  190. HMACSHA384(m_helloMacKey, outp.unsafeData, ii, outp.unsafeData + ii);
  191. ii += ZT_HMACSHA384_LEN;
  192. // LEGACY: we also need Poly1305 for v1.x peers.
  193. uint8_t polyKey[ZT_POLY1305_KEY_SIZE], perPacketKey[ZT_SALSA20_KEY_SIZE];
  194. Protocol::salsa2012DeriveKey(m_identityKey->secret, perPacketKey, outp, ii);
  195. Salsa20(perPacketKey, &packetId).crypt12(Utils::ZERO256, polyKey, sizeof(polyKey));
  196. Poly1305 p1305(polyKey);
  197. p1305.update(outp.unsafeData + ZT_PROTO_PACKET_ENCRYPTED_SECTION_START, ii - ZT_PROTO_PACKET_ENCRYPTED_SECTION_START);
  198. uint64_t polyMac[2];
  199. p1305.finish(polyMac);
  200. Utils::storeAsIsEndian< uint64_t >(outp.unsafeData + ZT_PROTO_PACKET_MAC_INDEX, polyMac[0]);
  201. return (likely(RR->node->putPacket(tPtr, localSocket, atAddress, outp.unsafeData, ii))) ? ii : 0;
  202. }
  203. void Peer::pulse(void *const tPtr, const int64_t now, const bool isRoot)
  204. {
  205. RWMutex::Lock l(m_lock);
  206. // Determine if we need a new ephemeral key pair and if a new HELLO needs
  207. // to be sent. The latter happens every ZT_PEER_HELLO_INTERVAL or if a new
  208. // ephemeral key pair is generated.
  209. bool needHello = false;
  210. 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))))) {
  211. m_ephemeralPair.generate();
  212. needHello = true;
  213. } else if ((now - m_lastSentHello) >= ZT_PEER_HELLO_INTERVAL) {
  214. needHello = true;
  215. }
  216. // Prioritize paths and more importantly for here forget dead ones.
  217. m_prioritizePaths(now);
  218. if (m_tryQueue.empty()) {
  219. if (m_alivePathCount == 0) {
  220. // If there are no living paths and nothing in the try queue, try addresses
  221. // from any locator we have on file or that are fetched via the external API
  222. // callback (if one was supplied).
  223. if (m_locator) {
  224. for (Vector< Endpoint >::const_iterator ep(m_locator->endpoints().begin()); ep != m_locator->endpoints().end(); ++ep) {
  225. if (ep->type == ZT_ENDPOINT_TYPE_IP_UDP) {
  226. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr, m_id, -1, ep->ip())) {
  227. int64_t &lt = m_lastTried[*ep];
  228. if ((now - lt) > ZT_PATH_MIN_TRY_INTERVAL) {
  229. lt = now;
  230. RR->t->tryingNewPath(tPtr, 0x84b22322, m_id, ep->ip(), InetAddress::NIL, 0, 0, Identity::NIL);
  231. sent(now, m_sendProbe(tPtr, -1, ep->ip(), nullptr, 0, now));
  232. }
  233. }
  234. }
  235. }
  236. }
  237. for (unsigned int i = 0; i < ZT_PEER_ENDPOINT_CACHE_SIZE; ++i) {
  238. if ((m_endpointCache[i].lastSeen > 0) && (m_endpointCache[i].target.type == ZT_ENDPOINT_TYPE_IP_UDP)) {
  239. if (RR->node->shouldUsePathForZeroTierTraffic(tPtr, m_id, -1, m_endpointCache[i].target.ip())) {
  240. int64_t &lt = m_lastTried[m_endpointCache[i].target];
  241. if ((now - lt) > ZT_PATH_MIN_TRY_INTERVAL) {
  242. lt = now;
  243. RR->t->tryingNewPath(tPtr, 0x84b22343, m_id, m_endpointCache[i].target.ip(), InetAddress::NIL, 0, 0, Identity::NIL);
  244. sent(now, m_sendProbe(tPtr, -1, m_endpointCache[i].target.ip(), nullptr, 0, now));
  245. }
  246. }
  247. }
  248. }
  249. InetAddress addr;
  250. if (RR->node->externalPathLookup(tPtr, m_id, -1, addr)) {
  251. if ((addr) && RR->node->shouldUsePathForZeroTierTraffic(tPtr, m_id, -1, addr)) {
  252. int64_t &lt = m_lastTried[Endpoint(addr)];
  253. if ((now - lt) > ZT_PATH_MIN_TRY_INTERVAL) {
  254. lt = now;
  255. RR->t->tryingNewPath(tPtr, 0x84a10000, m_id, addr, InetAddress::NIL, 0, 0, Identity::NIL);
  256. sent(now, m_sendProbe(tPtr, -1, addr, nullptr, 0, now));
  257. }
  258. }
  259. }
  260. }
  261. } else {
  262. // Attempt up to ZT_NAT_T_MAX_QUEUED_ATTEMPTS_PER_PULSE queued addresses.
  263. // Note that m_lastTried is checked when contact() is called and something
  264. // is added to the try queue, not here.
  265. unsigned int attempts = 0;
  266. for (;;) {
  267. p_TryQueueItem &qi = m_tryQueue.front();
  268. if (qi.target.isInetAddr()) {
  269. // Skip entry if it overlaps with any currently active IP.
  270. for (unsigned int i = 0; i < m_alivePathCount; ++i) {
  271. if (m_paths[i]->address().ipsEqual(qi.target.ip()))
  272. goto discard_queue_item;
  273. }
  274. }
  275. if (qi.target.type == ZT_ENDPOINT_TYPE_IP_UDP) {
  276. ++attempts;
  277. if (qi.iteration < 0) {
  278. // If iteration is less than zero, try to contact the original address.
  279. // It may be set to a larger negative value to try multiple times such
  280. // as e.g. -3 to try 3 times.
  281. sent(now, m_sendProbe(tPtr, -1, qi.target.ip(), nullptr, 0, now));
  282. ++qi.iteration;
  283. goto requeue_item;
  284. } else if (qi.target.ip().isV4() && (m_alivePathCount == 0)) {
  285. // When iteration reaches zero the queue item is dropped unless it's
  286. // IPv4 and we have no direct paths. In that case some heavier NAT-t
  287. // strategies are attempted.
  288. if (qi.target.ip().port() < 1024) {
  289. // If the source port is privileged, we actually scan every possible
  290. // privileged port in random order slowly over multiple iterations
  291. // of pulse(). This is done in batches of ZT_NAT_T_PORT_SCAN_MAX.
  292. uint16_t ports[ZT_NAT_T_PORT_SCAN_MAX];
  293. unsigned int pn = 0;
  294. while ((pn < ZT_NAT_T_PORT_SCAN_MAX) && (qi.iteration < 1023)) {
  295. const uint16_t p = RR->randomPrivilegedPortOrder[qi.iteration++];
  296. if ((unsigned int)p != qi.target.ip().port())
  297. ports[pn++] = p;
  298. }
  299. if (pn > 0)
  300. sent(now, m_sendProbe(tPtr, -1, qi.target.ip(), ports, pn, now));
  301. if (qi.iteration < 1023)
  302. goto requeue_item;
  303. } else {
  304. // For un-privileged ports we'll try ZT_NAT_T_PORT_SCAN_MAX ports
  305. // beyond the one we were sent to catch some sequentially assigning
  306. // symmetric NATs.
  307. InetAddress tmp(qi.target.ip());
  308. unsigned int p = tmp.port() + 1 + (unsigned int)qi.iteration++;
  309. if (p > 65535)
  310. p -= 64512; // wrap back to 1024
  311. tmp.setPort(p);
  312. sent(now, m_sendProbe(tPtr, -1, tmp, nullptr, 0, now));
  313. if (qi.iteration < ZT_NAT_T_PORT_SCAN_MAX)
  314. goto requeue_item;
  315. }
  316. }
  317. }
  318. // Discard front item unless the code skips to requeue_item.
  319. discard_queue_item:
  320. m_tryQueue.pop_front();
  321. if (attempts >= std::min((unsigned int)m_tryQueue.size(), (unsigned int)ZT_NAT_T_PORT_SCAN_MAX))
  322. break;
  323. else continue;
  324. // If the code skips here the front item is instead moved to the back.
  325. requeue_item:
  326. if (m_tryQueue.size() > 1) // no point in doing this splice if there's only one item
  327. m_tryQueue.splice(m_tryQueue.end(), m_tryQueue, m_tryQueue.begin());
  328. if (attempts >= std::min((unsigned int)m_tryQueue.size(), (unsigned int)ZT_NAT_T_PORT_SCAN_MAX))
  329. break;
  330. else continue;
  331. }
  332. }
  333. // Do keepalive on all currently active paths, sending HELLO to the first
  334. // if needHello is true and sending small keepalives to others.
  335. uint64_t randomJunk = Utils::random();
  336. for (unsigned int i = 0; i < m_alivePathCount; ++i) {
  337. if (needHello) {
  338. needHello = false;
  339. const unsigned int bytes = hello(tPtr, m_paths[i]->localSocket(), m_paths[i]->address(), now);
  340. m_paths[i]->sent(now, bytes);
  341. sent(now, bytes);
  342. m_lastSentHello = now;
  343. } else if ((now - m_paths[i]->lastOut()) >= ZT_PATH_KEEPALIVE_PERIOD) {
  344. m_paths[i]->send(RR, tPtr, reinterpret_cast<uint8_t *>(&randomJunk) + (i & 7U), 1, now);
  345. sent(now, 1);
  346. }
  347. }
  348. // Send a HELLO indirectly if we were not able to send one via any direct path.
  349. if (needHello) {
  350. const SharedPtr< Peer > root(RR->topology->root());
  351. if (root) {
  352. const SharedPtr< Path > via(root->path(now));
  353. if (via) {
  354. const unsigned int bytes = hello(tPtr, via->localSocket(), via->address(), now);
  355. via->sent(now, bytes);
  356. root->relayed(now, bytes);
  357. sent(now, bytes);
  358. m_lastSentHello = now;
  359. }
  360. }
  361. }
  362. // Clean m_lastTried
  363. for (Map< Endpoint, int64_t >::iterator i(m_lastTried.begin()); i != m_lastTried.end();) {
  364. if ((now - i->second) > (ZT_PATH_MIN_TRY_INTERVAL * 4))
  365. m_lastTried.erase(i++);
  366. else ++i;
  367. }
  368. }
  369. void Peer::contact(void *tPtr, const int64_t now, const Endpoint &ep, int tries)
  370. {
  371. static uint8_t foo = 0;
  372. RWMutex::Lock l(m_lock);
  373. // See if there's already a path to this endpoint and if so ignore it.
  374. if (ep.isInetAddr()) {
  375. if ((now - m_lastPrioritizedPaths) > ZT_PEER_PRIORITIZE_PATHS_INTERVAL)
  376. m_prioritizePaths(now);
  377. for (unsigned int i = 0; i < m_alivePathCount; ++i) {
  378. if (m_paths[i]->address().ipsEqual(ep.ip()))
  379. return;
  380. }
  381. }
  382. // Check underlying path attempt rate limit.
  383. int64_t &lt = m_lastTried[ep];
  384. if ((now - lt) < ZT_PATH_MIN_TRY_INTERVAL)
  385. return;
  386. lt = now;
  387. // For IPv4 addresses we send a tiny packet with a low TTL, which helps to
  388. // traverse some NAT types. It has no effect otherwise.
  389. if (ep.isInetAddr() && ep.ip().isV4()) {
  390. ++foo;
  391. RR->node->putPacket(tPtr, -1, ep.ip(), &foo, 1, 2);
  392. }
  393. // Make sure address is not already in the try queue. If so just update it.
  394. for (List< p_TryQueueItem >::iterator i(m_tryQueue.begin()); i != m_tryQueue.end(); ++i) {
  395. if (i->target.isSameAddress(ep)) {
  396. i->target = ep;
  397. i->iteration = -tries;
  398. return;
  399. }
  400. }
  401. m_tryQueue.push_back(p_TryQueueItem(ep, -tries));
  402. }
  403. void Peer::resetWithinScope(void *tPtr, InetAddress::IpScope scope, int inetAddressFamily, int64_t now)
  404. {
  405. RWMutex::Lock l(m_lock);
  406. unsigned int pc = 0;
  407. for (unsigned int i = 0; i < m_alivePathCount; ++i) {
  408. if ((m_paths[i]) && ((m_paths[i]->address().family() == inetAddressFamily) && (m_paths[i]->address().ipScope() == scope))) {
  409. const unsigned int bytes = m_sendProbe(tPtr, m_paths[i]->localSocket(), m_paths[i]->address(), nullptr, 0, now);
  410. m_paths[i]->sent(now, bytes);
  411. sent(now, bytes);
  412. } else if (pc != i) {
  413. m_paths[pc++] = m_paths[i];
  414. }
  415. }
  416. m_alivePathCount = pc;
  417. while (pc < ZT_MAX_PEER_NETWORK_PATHS)
  418. m_paths[pc++].zero();
  419. }
  420. bool Peer::directlyConnected(int64_t now)
  421. {
  422. if ((now - m_lastPrioritizedPaths) > ZT_PEER_PRIORITIZE_PATHS_INTERVAL) {
  423. RWMutex::Lock l(m_lock);
  424. m_prioritizePaths(now);
  425. return m_alivePathCount > 0;
  426. } else {
  427. RWMutex::RLock l(m_lock);
  428. return m_alivePathCount > 0;
  429. }
  430. }
  431. void Peer::getAllPaths(Vector< SharedPtr< Path > > &paths)
  432. {
  433. RWMutex::RLock l(m_lock);
  434. paths.clear();
  435. paths.reserve(m_alivePathCount);
  436. paths.assign(m_paths, m_paths + m_alivePathCount);
  437. }
  438. void Peer::save(void *tPtr) const
  439. {
  440. uint8_t buf[8 + ZT_PEER_MARSHAL_SIZE_MAX];
  441. // Prefix each saved peer with the current timestamp.
  442. Utils::storeBigEndian< uint64_t >(buf, (uint64_t)RR->node->now());
  443. const int len = marshal(buf + 8);
  444. if (len > 0) {
  445. uint64_t id[2];
  446. id[0] = m_id.address().toInt();
  447. id[1] = 0;
  448. RR->node->stateObjectPut(tPtr, ZT_STATE_OBJECT_PEER, id, buf, (unsigned int)len + 8);
  449. }
  450. }
  451. int Peer::marshal(uint8_t data[ZT_PEER_MARSHAL_SIZE_MAX]) const noexcept
  452. {
  453. RWMutex::RLock l(m_lock);
  454. if (!m_identityKey)
  455. return -1;
  456. data[0] = 16; // serialized peer version
  457. // Include our identity's address to detect if this changes and require
  458. // recomputation of m_identityKey.
  459. RR->identity.address().copyTo(data + 1);
  460. // SECURITY: encryption in place is only to protect secrets if they are
  461. // cached to local storage. It's not used over the wire. Dumb ECB is fine
  462. // because secret keys are random and have no structure to reveal.
  463. RR->localCacheSymmetric.encrypt(m_identityKey->secret, data + 1 + ZT_ADDRESS_LENGTH);
  464. RR->localCacheSymmetric.encrypt(m_identityKey->secret + 16, data + 1 + ZT_ADDRESS_LENGTH + 16);
  465. RR->localCacheSymmetric.encrypt(m_identityKey->secret + 32, data + 1 + ZT_ADDRESS_LENGTH + 32);
  466. int p = 1 + ZT_ADDRESS_LENGTH + 48;
  467. int s = m_id.marshal(data + p, false);
  468. if (s < 0)
  469. return -1;
  470. p += s;
  471. if (m_locator) {
  472. data[p++] = 1;
  473. s = m_locator->marshal(data + p);
  474. if (s <= 0)
  475. return s;
  476. p += s;
  477. } else {
  478. data[p++] = 0;
  479. }
  480. unsigned int cachedEndpointCount = 0;
  481. for (unsigned int i = 0; i < ZT_PEER_ENDPOINT_CACHE_SIZE; ++i) {
  482. if (m_endpointCache[i].lastSeen > 0)
  483. ++cachedEndpointCount;
  484. }
  485. Utils::storeBigEndian(data + p, (uint16_t)cachedEndpointCount);
  486. p += 2;
  487. for (unsigned int i = 0; i < ZT_PEER_ENDPOINT_CACHE_SIZE; ++i) {
  488. Utils::storeBigEndian(data + p, (uint64_t)m_endpointCache[i].lastSeen);
  489. s = m_endpointCache[i].target.marshal(data + p);
  490. if (s <= 0)
  491. return -1;
  492. p += s;
  493. }
  494. Utils::storeBigEndian(data + p, (uint16_t)m_vProto);
  495. p += 2;
  496. Utils::storeBigEndian(data + p, (uint16_t)m_vMajor);
  497. p += 2;
  498. Utils::storeBigEndian(data + p, (uint16_t)m_vMinor);
  499. p += 2;
  500. Utils::storeBigEndian(data + p, (uint16_t)m_vRevision);
  501. p += 2;
  502. data[p++] = 0;
  503. data[p++] = 0;
  504. return p;
  505. }
  506. int Peer::unmarshal(const uint8_t *restrict data, const int len) noexcept
  507. {
  508. RWMutex::Lock l(m_lock);
  509. if ((len <= (1 + ZT_ADDRESS_LENGTH + 48)) || (data[0] != 16))
  510. return -1;
  511. m_identityKey.zero();
  512. m_ephemeralKeys[0].zero();
  513. m_ephemeralKeys[1].zero();
  514. if (Address(data + 1) == RR->identity.address()) {
  515. uint8_t k[ZT_SYMMETRIC_KEY_SIZE];
  516. static_assert(ZT_SYMMETRIC_KEY_SIZE == 48, "marshal() and unmarshal() must be revisited if ZT_SYMMETRIC_KEY_SIZE is changed");
  517. RR->localCacheSymmetric.decrypt(data + 1 + ZT_ADDRESS_LENGTH, k);
  518. RR->localCacheSymmetric.decrypt(data + 1 + ZT_ADDRESS_LENGTH + 16, k + 16);
  519. RR->localCacheSymmetric.decrypt(data + 1 + ZT_ADDRESS_LENGTH + 32, k + 32);
  520. m_identityKey.set(new SymmetricKey(RR->node->now(), k));
  521. Utils::burn(k, sizeof(k));
  522. }
  523. int p = 1 + ZT_ADDRESS_LENGTH + 48;
  524. int s = m_id.unmarshal(data + p, len - p);
  525. if (s < 0)
  526. return s;
  527. p += s;
  528. if (!m_identityKey) {
  529. uint8_t k[ZT_SYMMETRIC_KEY_SIZE];
  530. if (!RR->identity.agree(m_id, k))
  531. return -1;
  532. m_identityKey.set(new SymmetricKey(RR->node->now(), k));
  533. Utils::burn(k, sizeof(k));
  534. }
  535. if (p >= len)
  536. return -1;
  537. if (data[p] == 0) {
  538. ++p;
  539. m_locator.zero();
  540. } else if (data[p] == 1) {
  541. ++p;
  542. Locator *const loc = new Locator();
  543. s = loc->unmarshal(data + p, len - p);
  544. m_locator.set(loc);
  545. if (s < 0)
  546. return s;
  547. p += s;
  548. } else {
  549. return -1;
  550. }
  551. const unsigned int cachedEndpointCount = Utils::loadBigEndian< uint16_t >(data + p);
  552. p += 2;
  553. for (unsigned int i = 0; i < cachedEndpointCount; ++i) {
  554. if (i < ZT_PEER_ENDPOINT_CACHE_SIZE) {
  555. if ((p + 8) >= len)
  556. return -1;
  557. m_endpointCache[i].lastSeen = (int64_t)Utils::loadBigEndian< uint64_t >(data + p);
  558. p += 8;
  559. s = m_endpointCache[i].target.unmarshal(data + p, len - p);
  560. if (s <= 0)
  561. return -1;
  562. p += s;
  563. }
  564. }
  565. if ((p + 10) > len)
  566. return -1;
  567. m_vProto = Utils::loadBigEndian< uint16_t >(data + p);
  568. p += 2;
  569. m_vMajor = Utils::loadBigEndian< uint16_t >(data + p);
  570. p += 2;
  571. m_vMinor = Utils::loadBigEndian< uint16_t >(data + p);
  572. p += 2;
  573. m_vRevision = Utils::loadBigEndian< uint16_t >(data + p);
  574. p += 2;
  575. p += 2 + (int)Utils::loadBigEndian< uint16_t >(data + p);
  576. m_deriveSecondaryIdentityKeys();
  577. return (p > len) ? -1 : p;
  578. }
  579. struct _PathPriorityComparisonOperator
  580. {
  581. ZT_INLINE bool operator()(const SharedPtr< Path > &a, const SharedPtr< Path > &b) const noexcept
  582. {
  583. // Sort in descending order of most recent receive time.
  584. return (a->lastIn() > b->lastIn());
  585. }
  586. };
  587. void Peer::m_prioritizePaths(int64_t now)
  588. {
  589. // assumes _lock is locked for writing
  590. m_lastPrioritizedPaths = now;
  591. if (m_alivePathCount > 0) {
  592. // Sort paths in descending order of priority.
  593. std::sort(m_paths, m_paths + m_alivePathCount, _PathPriorityComparisonOperator());
  594. // Let go of paths that have expired.
  595. for (unsigned int i = 0; i < ZT_MAX_PEER_NETWORK_PATHS; ++i) {
  596. if ((!m_paths[i]) || (!m_paths[i]->alive(now))) {
  597. m_alivePathCount = i;
  598. for (; i < ZT_MAX_PEER_NETWORK_PATHS; ++i)
  599. m_paths[i].zero();
  600. break;
  601. }
  602. }
  603. }
  604. }
  605. unsigned int Peer::m_sendProbe(void *tPtr, int64_t localSocket, const InetAddress &atAddress, const uint16_t *ports, const unsigned int numPorts, int64_t now)
  606. {
  607. // Assumes m_lock is locked
  608. const SharedPtr< SymmetricKey > k(m_key());
  609. const uint64_t packetId = k->nextMessage(RR->identity.address(), m_id.address());
  610. uint8_t p[ZT_PROTO_MIN_PACKET_LENGTH];
  611. Utils::storeAsIsEndian< uint64_t >(p + ZT_PROTO_PACKET_ID_INDEX, packetId);
  612. m_id.address().copyTo(p + ZT_PROTO_PACKET_DESTINATION_INDEX);
  613. RR->identity.address().copyTo(p + ZT_PROTO_PACKET_SOURCE_INDEX);
  614. p[ZT_PROTO_PACKET_FLAGS_INDEX] = 0;
  615. p[ZT_PROTO_PACKET_VERB_INDEX] = Protocol::VERB_ECHO;
  616. Protocol::armor(p, ZT_PROTO_MIN_PACKET_LENGTH, k, cipher());
  617. RR->expect->sending(packetId, now);
  618. if (numPorts > 0) {
  619. InetAddress tmp(atAddress);
  620. for (unsigned int i = 0; i < numPorts; ++i) {
  621. tmp.setPort(ports[i]);
  622. RR->node->putPacket(tPtr, -1, tmp, p, ZT_PROTO_MIN_PACKET_LENGTH);
  623. }
  624. return ZT_PROTO_MIN_PACKET_LENGTH * numPorts;
  625. } else {
  626. RR->node->putPacket(tPtr, -1, atAddress, p, ZT_PROTO_MIN_PACKET_LENGTH);
  627. return ZT_PROTO_MIN_PACKET_LENGTH;
  628. }
  629. }
  630. void Peer::m_deriveSecondaryIdentityKeys() noexcept
  631. {
  632. uint8_t hk[ZT_SYMMETRIC_KEY_SIZE];
  633. KBKDFHMACSHA384(m_identityKey->secret, ZT_KBKDF_LABEL_HELLO_DICTIONARY_ENCRYPT, 0, 0, hk);
  634. m_helloCipher.init(hk);
  635. Utils::burn(hk, sizeof(hk));
  636. KBKDFHMACSHA384(m_identityKey->secret, ZT_KBKDF_LABEL_PACKET_HMAC, 0, 0, m_helloMacKey);
  637. }
  638. } // namespace ZeroTier