Topology.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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 "Topology.hpp"
  14. #include "Defaults.hpp"
  15. namespace ZeroTier {
  16. Topology::Topology(const RuntimeEnvironment *renv, void *tPtr, const int64_t now) :
  17. RR(renv),
  18. m_lastRankedRoots(0)
  19. {
  20. char tmp[32];
  21. Dictionary d;
  22. Vector< uint8_t > trustData(RR->node->stateObjectGet(tPtr, ZT_STATE_OBJECT_TRUST_STORE, Utils::ZERO256));
  23. if (trustData.empty() || (!d.decode(trustData.data(), (unsigned int)trustData.size()))) {
  24. if (!d.decode(Defaults::CERTIFICATES, Defaults::CERTIFICATES_BYTES))
  25. d.clear();
  26. }
  27. if (!d.empty()) {
  28. const unsigned long certCount = (unsigned long)d.getUI("c$");
  29. for (unsigned long idx = 0; idx < certCount; ++idx) {
  30. uint64_t id[6];
  31. const Vector< uint8_t > &serialNo = d[Dictionary::arraySubscript(tmp, sizeof(tmp), "c$.s", idx)];
  32. if (serialNo.size() == ZT_SHA384_DIGEST_SIZE) {
  33. Utils::copy< 48 >(id, serialNo.data());
  34. Certificate cert;
  35. Vector< uint8_t > enc(RR->node->stateObjectGet(tPtr, ZT_STATE_OBJECT_CERT, id));
  36. if (cert.decode(enc.data(), (unsigned int)enc.size()))
  37. addCertificate(tPtr, cert, now, (unsigned int)d.getUI(Dictionary::arraySubscript(tmp, sizeof(tmp), "c$.lt", idx)), false, false, false);
  38. }
  39. }
  40. m_cleanCertificates(tPtr, now);
  41. m_updateRootPeers(tPtr, now);
  42. }
  43. }
  44. SharedPtr< Peer > Topology::add(void *tPtr, const SharedPtr< Peer > &peer)
  45. {
  46. RWMutex::Lock _l(m_peers_l);
  47. SharedPtr< Peer > &hp = m_peers[peer->address()];
  48. if (hp)
  49. return hp;
  50. m_loadCached(tPtr, peer->address(), hp);
  51. if (hp)
  52. return hp;
  53. hp = peer;
  54. return peer;
  55. }
  56. void Topology::allPeers(Vector< SharedPtr< Peer > > &allPeers, Vector< SharedPtr< Peer > > &rootPeers) const
  57. {
  58. allPeers.clear();
  59. {
  60. RWMutex::RLock l(m_peers_l);
  61. allPeers.reserve(m_peers.size());
  62. for (Map< Address, SharedPtr< Peer > >::const_iterator i(m_peers.begin()); i != m_peers.end(); ++i)
  63. allPeers.push_back(i->second);
  64. }
  65. {
  66. RWMutex::RLock l(m_roots_l);
  67. rootPeers = m_roots;
  68. }
  69. }
  70. void Topology::doPeriodicTasks(void *tPtr, const int64_t now)
  71. {
  72. // Peer and path delete operations are batched to avoid holding write locks on
  73. // these structures for any length of time. A list is compiled in read mode,
  74. // then the write lock is acquired for each delete. This adds overhead if there
  75. // are a lot of deletions, but that's not common.
  76. // Clean any expired certificates
  77. {
  78. Mutex::Lock l1(m_certs_l);
  79. if (m_cleanCertificates(tPtr, now)) {
  80. RWMutex::Lock l3(m_peers_l);
  81. RWMutex::Lock l2(m_roots_l);
  82. m_updateRootPeers(tPtr, now);
  83. }
  84. }
  85. // Delete peers that are stale or offline and are not roots.
  86. {
  87. Vector< uintptr_t > rootLookup;
  88. {
  89. RWMutex::RLock l2(m_roots_l);
  90. rootLookup.reserve(m_roots.size());
  91. for (Vector< SharedPtr< Peer > >::const_iterator r(m_roots.begin()); r != m_roots.end(); ++r)
  92. rootLookup.push_back((uintptr_t)r->ptr());
  93. }
  94. std::sort(rootLookup.begin(), rootLookup.end());
  95. Vector< Address > toDelete;
  96. {
  97. RWMutex::RLock l1(m_peers_l);
  98. for (Map< Address, SharedPtr< Peer > >::iterator i(m_peers.begin()); i != m_peers.end(); ++i) {
  99. // TODO: also delete if the peer has not exchanged meaningful communication in a while, such as
  100. // a network frame or non-trivial control packet.
  101. if (((now - i->second->lastReceive()) > ZT_PEER_ALIVE_TIMEOUT) && (!std::binary_search(rootLookup.begin(), rootLookup.end(), (uintptr_t)i->second.ptr())))
  102. toDelete.push_back(i->first);
  103. }
  104. }
  105. for (Vector< Address >::iterator i(toDelete.begin()); i != toDelete.end(); ++i) {
  106. RWMutex::Lock l1(m_peers_l);
  107. const Map< Address, SharedPtr< Peer > >::iterator p(m_peers.find(*i));
  108. if (likely(p != m_peers.end())) {
  109. p->second->save(tPtr);
  110. m_peers.erase(p);
  111. }
  112. }
  113. }
  114. // Delete paths that are no longer held by anyone else ("weak reference" type behavior).
  115. {
  116. Vector< UniqueID > toDelete;
  117. {
  118. RWMutex::RLock l1(m_paths_l);
  119. for (Map< UniqueID, SharedPtr< Path > >::iterator i(m_paths.begin()); i != m_paths.end(); ++i) {
  120. if (i->second.weakGC())
  121. toDelete.push_back(i->first);
  122. }
  123. }
  124. for (Vector< UniqueID >::iterator i(toDelete.begin()); i != toDelete.end(); ++i) {
  125. RWMutex::Lock l1(m_paths_l);
  126. const Map< UniqueID, SharedPtr< Path > >::iterator p(m_paths.find(*i));
  127. if (likely(p != m_paths.end()))
  128. m_paths.erase(p);
  129. }
  130. }
  131. }
  132. void Topology::saveAll(void *tPtr)
  133. {
  134. {
  135. RWMutex::RLock l(m_peers_l);
  136. for (Map< Address, SharedPtr< Peer > >::iterator i(m_peers.begin()); i != m_peers.end(); ++i) {
  137. i->second->save(tPtr);
  138. }
  139. }
  140. {
  141. char tmp[32];
  142. Dictionary d;
  143. {
  144. Mutex::Lock l(m_certs_l);
  145. unsigned long idx = 0;
  146. d.add("c$", (uint64_t)m_certs.size());
  147. for (Map< SHA384Hash, std::pair< SharedPtr< const Certificate >, unsigned int > >::const_iterator c(m_certs.begin()); c != m_certs.end(); ++c) {
  148. d[Dictionary::arraySubscript(tmp, sizeof(tmp), "c$.s", idx)].assign(c->first.data, c->first.data + ZT_SHA384_DIGEST_SIZE);
  149. d.add(Dictionary::arraySubscript(tmp, sizeof(tmp), "c$.lt", idx), (uint64_t)c->second.second);
  150. ++idx;
  151. }
  152. }
  153. Vector< uint8_t > trustStore;
  154. d.encode(trustStore);
  155. RR->node->stateObjectPut(tPtr, ZT_STATE_OBJECT_TRUST_STORE, Utils::ZERO256, trustStore.data(), (unsigned int)trustStore.size());
  156. }
  157. }
  158. ZT_CertificateError Topology::addCertificate(void *tPtr, const Certificate &cert, const int64_t now, const unsigned int localTrust, const bool writeToLocalStore, const bool refreshRootSets, const bool verify)
  159. {
  160. {
  161. Mutex::Lock l1(m_certs_l);
  162. // Check to see if we already have this specific certificate.
  163. const SHA384Hash serial(cert.serialNo);
  164. if (m_certs.find(serial) != m_certs.end())
  165. return ZT_CERTIFICATE_ERROR_NONE;
  166. // Verify certificate all the way to a trusted root. This also verifies inner
  167. // signatures such as those of locators or the subject unique ID.
  168. if (verify) {
  169. const ZT_CertificateError err = m_verifyCertificate(cert, now, localTrust, false);
  170. if (err != ZT_CERTIFICATE_ERROR_NONE)
  171. return err;
  172. }
  173. // Create entry containing copy of certificate and trust flags.
  174. const std::pair< SharedPtr< const Certificate >, unsigned int > certEntry(SharedPtr< const Certificate >(new Certificate(cert)), localTrust);
  175. // If the subject contains a unique ID, check if we already have a cert for the
  176. // same uniquely identified subject. If so, check its subject timestamp and keep
  177. // the one we have if newer. Otherwise replace it. Note that the verification
  178. // function will have checked the unique ID proof signature already if a unique
  179. // ID was present.
  180. if ((cert.subject.uniqueId) && (cert.subject.uniqueIdSize > 0)) {
  181. SHA384Hash uniqueIdHash;
  182. SHA384(uniqueIdHash.data, cert.subject.uniqueId, cert.subject.uniqueIdSize);
  183. std::pair< SharedPtr< const Certificate >, unsigned int > &bySubjectUniqueId = m_certsBySubjectUniqueId[uniqueIdHash];
  184. if (bySubjectUniqueId.first) {
  185. if (bySubjectUniqueId.first->subject.timestamp >= cert.subject.timestamp)
  186. return ZT_CERTIFICATE_ERROR_HAVE_NEWER_CERT;
  187. m_eraseCertificate(tPtr, bySubjectUniqueId.first, &uniqueIdHash);
  188. m_certsBySubjectUniqueId[uniqueIdHash] = certEntry;
  189. } else {
  190. bySubjectUniqueId = certEntry;
  191. }
  192. }
  193. // Save certificate by serial number.
  194. m_certs[serial] = certEntry;
  195. // Add certificate to sets of certificates whose subject references a given identity.
  196. for (unsigned int i = 0; i < cert.subject.identityCount; ++i) {
  197. const Identity *const ii = reinterpret_cast<const Identity *>(cert.subject.identities[i].identity);
  198. if (ii)
  199. m_certsBySubjectIdentity[ii->fingerprint()].insert(certEntry);
  200. }
  201. // Clean any certificates whose chains are now broken, which can happen if there was
  202. // an update that replaced an old cert with a given unique ID. Otherwise this generally
  203. // does nothing here. Skip if verify is false since this means we're mindlessly loading
  204. // certificates, which right now only happens on startup when they're loaded from the
  205. // local certificate cache.
  206. if (verify)
  207. m_cleanCertificates(tPtr, now);
  208. // Refresh the root peers lists, since certs may enumerate roots.
  209. if (refreshRootSets) {
  210. RWMutex::Lock l3(m_peers_l);
  211. RWMutex::Lock l2(m_roots_l);
  212. m_updateRootPeers(tPtr, now);
  213. }
  214. }
  215. if (writeToLocalStore) {
  216. // Write certificate data prefixed by local trust flags as a 32-bit integer.
  217. Vector< uint8_t > certData(cert.encode());
  218. uint64_t id[6];
  219. Utils::copy< 48 >(id, cert.serialNo);
  220. RR->node->stateObjectPut(tPtr, ZT_STATE_OBJECT_CERT, id, certData.data(), (unsigned int)certData.size());
  221. }
  222. return ZT_CERTIFICATE_ERROR_NONE;
  223. }
  224. struct p_RootRankingComparisonOperator
  225. {
  226. ZT_INLINE bool operator()(const SharedPtr< Peer > &a, const SharedPtr< Peer > &b) const noexcept
  227. {
  228. // Sort roots first in order of which root has spoken most recently, but
  229. // only at a resolution of ZT_PATH_KEEPALIVE_PERIOD/2 units of time. This
  230. // means that living roots that seem responsive are ranked the same. Then
  231. // they're sorted in descending order of latency so that the apparently
  232. // fastest root is ranked first.
  233. const int64_t alr = a->lastReceive() / (ZT_PATH_KEEPALIVE_PERIOD / 2);
  234. const int64_t blr = b->lastReceive() / (ZT_PATH_KEEPALIVE_PERIOD / 2);
  235. if (alr < blr) {
  236. return true;
  237. } else if (blr == alr) {
  238. const int bb = b->latency();
  239. if (bb < 0)
  240. return true;
  241. return bb < a->latency();
  242. }
  243. return false;
  244. }
  245. };
  246. void Topology::m_rankRoots(const int64_t now)
  247. {
  248. // assumes m_roots is locked
  249. m_lastRankedRoots = now;
  250. std::sort(m_roots.begin(), m_roots.end(), p_RootRankingComparisonOperator());
  251. }
  252. void Topology::m_eraseCertificate(void *tPtr, const SharedPtr< const Certificate > &cert, const SHA384Hash *uniqueIdHash)
  253. {
  254. // assumes m_certs is locked for writing
  255. const SHA384Hash serialNo(cert->serialNo);
  256. m_certs.erase(serialNo);
  257. RR->node->stateObjectDelete(tPtr, ZT_STATE_OBJECT_CERT, serialNo.data);
  258. if (uniqueIdHash)
  259. m_certsBySubjectUniqueId.erase(*uniqueIdHash);
  260. for (unsigned int i = 0; i < cert->subject.identityCount; ++i) {
  261. const Identity *const ii = reinterpret_cast<const Identity *>(cert->subject.identities[i].identity);
  262. Map< Fingerprint, Map< SharedPtr< const Certificate >, unsigned int > >::iterator
  263. bySubjectIdentity(m_certsBySubjectIdentity.find(ii->fingerprint()));
  264. if (bySubjectIdentity != m_certsBySubjectIdentity.end()) {
  265. bySubjectIdentity->second.erase(cert);
  266. if (bySubjectIdentity->second.empty())
  267. m_certsBySubjectIdentity.erase(bySubjectIdentity);
  268. }
  269. }
  270. }
  271. bool Topology::m_cleanCertificates(void *tPtr, int64_t now)
  272. {
  273. // assumes m_certs is locked for writing
  274. bool deleted = false;
  275. Vector< SharedPtr< const Certificate >> toDelete;
  276. for (;;) {
  277. for (Map< SHA384Hash, std::pair< SharedPtr< const Certificate >, unsigned int > >::iterator c(m_certs.begin()); c != m_certs.end(); ++c) {
  278. // Verify, but the last boolean option tells it to skip signature checks as this would
  279. // already have been done. This will therefore just check the path and validity times
  280. // of the certificate.
  281. const ZT_CertificateError err = m_verifyCertificate(*(c->second.first), now, c->second.second, true);
  282. if (err != ZT_CERTIFICATE_ERROR_NONE)
  283. toDelete.push_back(c->second.first);
  284. }
  285. if (toDelete.empty())
  286. break;
  287. deleted = true;
  288. SHA384Hash uniqueIdHash;
  289. for (Vector< SharedPtr< const Certificate > >::iterator c(toDelete.begin()); c != toDelete.end(); ++c) {
  290. if ((*c)->subject.uniqueId) {
  291. SHA384(uniqueIdHash.data, (*c)->subject.uniqueId, (*c)->subject.uniqueIdSize);
  292. m_eraseCertificate(tPtr, *c, &uniqueIdHash);
  293. } else {
  294. m_eraseCertificate(tPtr, *c, nullptr);
  295. }
  296. }
  297. toDelete.clear();
  298. }
  299. return deleted;
  300. }
  301. bool Topology::m_verifyCertificateChain(const Certificate *current, const int64_t now) const
  302. {
  303. // assumes m_certs is at least locked for reading
  304. Map< Fingerprint, Map< SharedPtr< const Certificate >, unsigned int > >::const_iterator c(m_certsBySubjectIdentity.find(reinterpret_cast<const Identity *>(current->issuer)->fingerprint()));
  305. if (c != m_certsBySubjectIdentity.end()) {
  306. for (Map< SharedPtr< const Certificate >, unsigned int >::const_iterator cc(c->second.begin()); cc != c->second.end(); ++cc) {
  307. if (
  308. (cc->first->maxPathLength > current->maxPathLength) &&
  309. (cc->first->validity[0] <= now) && // not before now
  310. (cc->first->validity[1] >= now) && // not after now
  311. (cc->first->validity[0] <= current->timestamp) && // not before child cert's timestamp
  312. (cc->first->validity[1] >= current->timestamp) // not after child cert's timestamp
  313. ) {
  314. if ((cc->second & ZT_CERTIFICATE_LOCAL_TRUST_FLAG_ROOT_CA) != 0)
  315. return true;
  316. if (m_verifyCertificateChain(cc->first.ptr(), now))
  317. return true;
  318. }
  319. }
  320. }
  321. return false;
  322. }
  323. ZT_CertificateError Topology::m_verifyCertificate(const Certificate &cert, const int64_t now, unsigned int localTrust, bool skipSignatureCheck) const
  324. {
  325. // assumes m_certs is at least locked for reading
  326. // Check certificate time window against current time.
  327. if ((cert.validity[0] > now) || (cert.validity[1] < now))
  328. return ZT_CERTIFICATE_ERROR_OUT_OF_VALID_TIME_WINDOW;
  329. // Verify primary and internal signatures and other objects unless the caller
  330. // elected to skip, which is done to re-check certs already in the DB.
  331. if (!skipSignatureCheck) {
  332. const ZT_CertificateError err = cert.verify();
  333. if (err != ZT_CERTIFICATE_ERROR_NONE)
  334. return err;
  335. }
  336. // If this is a root CA, we can skip this as we're already there. Otherwise we
  337. // recurse up the tree until we hit a root CA.
  338. if ((localTrust & ZT_CERTIFICATE_LOCAL_TRUST_FLAG_ROOT_CA) == 0) {
  339. if (!m_verifyCertificateChain(&cert, now))
  340. return ZT_CERTIFICATE_ERROR_INVALID_CHAIN;
  341. }
  342. return ZT_CERTIFICATE_ERROR_NONE;
  343. }
  344. void Topology::m_loadCached(void *tPtr, const Address &zta, SharedPtr< Peer > &peer)
  345. {
  346. // does not require any locks to be held
  347. try {
  348. uint64_t id[2];
  349. id[0] = zta.toInt();
  350. id[1] = 0;
  351. Vector< uint8_t > data(RR->node->stateObjectGet(tPtr, ZT_STATE_OBJECT_PEER, id));
  352. if (data.size() > 8) {
  353. const uint8_t *d = data.data();
  354. int dl = (int)data.size();
  355. const int64_t ts = (int64_t)Utils::loadBigEndian< uint64_t >(d);
  356. Peer *const p = new Peer(RR);
  357. int n = p->unmarshal(d + 8, dl - 8);
  358. if (n < 0) {
  359. delete p;
  360. return;
  361. }
  362. if ((RR->node->now() - ts) < ZT_PEER_GLOBAL_TIMEOUT) {
  363. // TODO: handle many peers, same address (?)
  364. peer.set(p);
  365. return;
  366. }
  367. }
  368. } catch (...) {
  369. peer.zero();
  370. }
  371. }
  372. SharedPtr< Peer > Topology::m_peerFromCached(void *tPtr, const Address &zta)
  373. {
  374. SharedPtr< Peer > p;
  375. m_loadCached(tPtr, zta, p);
  376. if (p) {
  377. RWMutex::Lock l(m_peers_l);
  378. SharedPtr< Peer > &hp = m_peers[zta];
  379. if (hp)
  380. return hp;
  381. hp = p;
  382. }
  383. return p;
  384. }
  385. SharedPtr< Path > Topology::m_newPath(const int64_t l, const InetAddress &r, const UniqueID &k)
  386. {
  387. SharedPtr< Path > p(new Path(l, r));
  388. RWMutex::Lock lck(m_paths_l);
  389. SharedPtr< Path > &p2 = m_paths[k];
  390. if (p2)
  391. return p2;
  392. p2 = p;
  393. return p;
  394. }
  395. void Topology::m_updateRootPeers(void *tPtr, const int64_t now)
  396. {
  397. // assumes m_certs_l, m_peers_l, and m_roots_l are locked for write
  398. Set< Identity > rootIdentities;
  399. for (Map< Fingerprint, Map< SharedPtr< const Certificate >, unsigned int > >::const_iterator c(m_certsBySubjectIdentity.begin()); c != m_certsBySubjectIdentity.end(); ++c) {
  400. for (Map< SharedPtr< const Certificate >, unsigned int >::const_iterator cc(c->second.begin()); cc != c->second.end(); ++cc) {
  401. if ((cc->second & ZT_CERTIFICATE_LOCAL_TRUST_FLAG_ZEROTIER_ROOT_SET) != 0) {
  402. for (unsigned int i = 0; i < cc->first->subject.identityCount; ++i) {
  403. if (cc->first->subject.identities[i].identity)
  404. rootIdentities.insert(*reinterpret_cast<const Identity *>(cc->first->subject.identities[i].identity));
  405. }
  406. }
  407. }
  408. }
  409. m_roots.clear();
  410. for (Set< Identity >::const_iterator i(rootIdentities.begin()); i != rootIdentities.end(); ++i) {
  411. SharedPtr< Peer > &p = m_peers[i->address()];
  412. if ((!p) || (p->identity() != *i)) {
  413. p.set(new Peer(RR));
  414. p->init(*i);
  415. }
  416. m_roots.push_back(p);
  417. }
  418. m_rankRoots(now);
  419. }
  420. } // namespace ZeroTier