Topology.cpp 17 KB

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