Membership.hpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. * Copyright (c)2019 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: 2023-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. #ifndef ZT_MEMBERSHIP_HPP
  14. #define ZT_MEMBERSHIP_HPP
  15. #include <stdint.h>
  16. #include "Constants.hpp"
  17. #include "../include/ZeroTierOne.h"
  18. #include "Credential.hpp"
  19. #include "Hashtable.hpp"
  20. #include "CertificateOfMembership.hpp"
  21. #include "Capability.hpp"
  22. #include "Tag.hpp"
  23. #include "Revocation.hpp"
  24. #include "NetworkConfig.hpp"
  25. #define ZT_MEMBERSHIP_CRED_ID_UNUSED 0xffffffffffffffffULL
  26. namespace ZeroTier {
  27. class RuntimeEnvironment;
  28. class Network;
  29. /**
  30. * A container for certificates of membership and other network credentials
  31. *
  32. * This is essentially a relational join between Peer and Network.
  33. *
  34. * This class is not thread safe. It must be locked externally.
  35. */
  36. class Membership
  37. {
  38. public:
  39. enum AddCredentialResult
  40. {
  41. ADD_REJECTED,
  42. ADD_ACCEPTED_NEW,
  43. ADD_ACCEPTED_REDUNDANT,
  44. ADD_DEFERRED_FOR_WHOIS
  45. };
  46. Membership();
  47. /**
  48. * Send COM and other credentials to this peer
  49. *
  50. * @param RR Runtime environment
  51. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  52. * @param now Current time
  53. * @param peerAddress Address of member peer (the one that this Membership describes)
  54. * @param nconf My network config
  55. */
  56. void pushCredentials(const RuntimeEnvironment *RR,void *tPtr,const int64_t now,const Address &peerAddress,const NetworkConfig &nconf);
  57. /**
  58. * @return Time we last pushed credentials to this member
  59. */
  60. ZT_ALWAYS_INLINE int64_t lastPushedCredentials() const { return _lastPushedCredentials; }
  61. /**
  62. * Check whether we should push MULTICAST_LIKEs to this peer, and update last sent time if true
  63. *
  64. * @param now Current time
  65. * @return True if we should update multicasts
  66. */
  67. ZT_ALWAYS_INLINE bool multicastLikeGate(const int64_t now)
  68. {
  69. if ((now - _lastUpdatedMulticast) >= ZT_MULTICAST_ANNOUNCE_PERIOD) {
  70. _lastUpdatedMulticast = now;
  71. return true;
  72. }
  73. return false;
  74. }
  75. /**
  76. * Check whether the peer represented by this Membership should be allowed on this network at all
  77. *
  78. * @param nconf Our network config
  79. * @return True if this peer is allowed on this network at all
  80. */
  81. ZT_ALWAYS_INLINE bool isAllowedOnNetwork(const NetworkConfig &nconf) const
  82. {
  83. if (nconf.isPublic()) return true; // public network
  84. if (_com.timestamp() <= _comRevocationThreshold) return false; // COM has been revoked
  85. return nconf.com.agreesWith(_com); // check timestamp agreement window
  86. }
  87. /**
  88. * @return True if this peer has sent us a valid certificate within ZT_PEER_ACTIVITY_TIMEOUT
  89. */
  90. ZT_ALWAYS_INLINE bool recentlyAssociated(const int64_t now) const { return ((_com)&&((now - _com.timestamp()) < ZT_PEER_ACTIVITY_TIMEOUT)); }
  91. /**
  92. * Check whether the peer represented by this Membership owns a given address
  93. *
  94. * @tparam Type of resource: InetAddress or MAC
  95. * @param nconf Our network config
  96. * @param r Resource to check
  97. * @return True if this peer has a certificate of ownership for the given resource
  98. */
  99. template<typename T>
  100. inline bool peerOwnsAddress(const NetworkConfig &nconf,const T &r) const
  101. {
  102. if (_isUnspoofableAddress(nconf,r))
  103. return true;
  104. uint32_t *k = (uint32_t *)0;
  105. CertificateOfOwnership *v = (CertificateOfOwnership *)0;
  106. Hashtable< uint32_t,CertificateOfOwnership >::Iterator i(*(const_cast< Hashtable< uint32_t,CertificateOfOwnership> *>(&_remoteCoos)));
  107. while (i.next(k,v)) {
  108. if (_isCredentialTimestampValid(nconf,*v)&&(v->owns(r)))
  109. return true;
  110. }
  111. return false;
  112. }
  113. /**
  114. * Get a remote member's tag (if we have it)
  115. *
  116. * @param nconf Network configuration
  117. * @param id Tag ID
  118. * @return Pointer to tag or NULL if not found
  119. */
  120. inline const Tag *getTag(const NetworkConfig &nconf,const uint32_t id) const
  121. {
  122. const Tag *const t = _remoteTags.get(id);
  123. return (((t)&&(_isCredentialTimestampValid(nconf,*t))) ? t : (Tag *)0);
  124. }
  125. AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const CertificateOfMembership &com);
  126. AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Tag &tag);
  127. AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Capability &cap);
  128. AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const CertificateOfOwnership &coo);
  129. AddCredentialResult addCredential(const RuntimeEnvironment *RR,void *tPtr,const NetworkConfig &nconf,const Revocation &rev);
  130. /**
  131. * Clean internal databases of stale entries
  132. *
  133. * @param now Current time
  134. * @param nconf Current network configuration
  135. */
  136. void clean(const int64_t now,const NetworkConfig &nconf);
  137. /**
  138. * Generates a key for internal use in indexing credentials by type and credential ID
  139. */
  140. static uint64_t credentialKey(const Credential::Type &t,const uint32_t i) { return (((uint64_t)t << 32) | (uint64_t)i); }
  141. /**
  142. * @return Bytes received so far
  143. */
  144. ZT_ALWAYS_INLINE uint64_t receivedBytes() const { return _received; }
  145. /**
  146. * @return Bytes sent so far
  147. */
  148. ZT_ALWAYS_INLINE uint64_t sentBytes() const { return _sent; }
  149. /**
  150. * @param bytes Bytes received
  151. */
  152. ZT_ALWAYS_INLINE void logReceivedBytes(const unsigned int bytes) { _received = (uint64_t)bytes; }
  153. /**
  154. * @param bytes Bytes sent
  155. */
  156. ZT_ALWAYS_INLINE void logSentBytes(const unsigned int bytes) { _sent = (uint64_t)bytes; }
  157. private:
  158. // This returns true if a resource is an IPv6 NDP-emulated address. These embed the ZT
  159. // address of the peer and therefore cannot be spoofed, causing peerOwnsAddress() to
  160. // always return true for them. A certificate is not required for these.
  161. inline bool _isUnspoofableAddress(const NetworkConfig &nconf,const MAC &m) const { return false; }
  162. inline bool _isUnspoofableAddress(const NetworkConfig &nconf,const InetAddress &ip) const
  163. {
  164. if ((ip.isV6())&&(nconf.ndpEmulation())) {
  165. const InetAddress sixpl(InetAddress::makeIpv66plane(nconf.networkId,nconf.issuedTo.toInt()));
  166. for(unsigned int i=0;i<nconf.staticIpCount;++i) {
  167. if (nconf.staticIps[i].ipsEqual(sixpl)) {
  168. bool prefixMatches = true;
  169. for(unsigned int j=0;j<5;++j) { // check for match on /40
  170. if ((((const struct sockaddr_in6 *)&ip)->sin6_addr.s6_addr)[j] != (((const struct sockaddr_in6 *)&sixpl)->sin6_addr.s6_addr)[j]) {
  171. prefixMatches = false;
  172. break;
  173. }
  174. }
  175. if (prefixMatches)
  176. return true;
  177. break;
  178. }
  179. }
  180. const InetAddress rfc4193(InetAddress::makeIpv6rfc4193(nconf.networkId,nconf.issuedTo.toInt()));
  181. for(unsigned int i=0;i<nconf.staticIpCount;++i) {
  182. if (nconf.staticIps[i].ipsEqual(rfc4193)) {
  183. bool prefixMatches = true;
  184. for(unsigned int j=0;j<11;++j) { // check for match on /88
  185. if ((((const struct sockaddr_in6 *)&ip)->sin6_addr.s6_addr)[j] != (((const struct sockaddr_in6 *)&rfc4193)->sin6_addr.s6_addr)[j]) {
  186. prefixMatches = false;
  187. break;
  188. }
  189. }
  190. if (prefixMatches)
  191. return true;
  192. break;
  193. }
  194. }
  195. }
  196. return false;
  197. }
  198. // This compares the remote credential's timestamp to the timestamp in our network config
  199. // plus or minus the permitted maximum timestamp delta.
  200. template<typename C>
  201. inline bool _isCredentialTimestampValid(const NetworkConfig &nconf,const C &remoteCredential) const
  202. {
  203. const int64_t ts = remoteCredential.timestamp();
  204. if (((ts >= nconf.timestamp) ? (ts - nconf.timestamp) : (nconf.timestamp - ts)) <= nconf.credentialTimeMaxDelta) {
  205. const int64_t *threshold = _revocations.get(credentialKey(C::credentialType(),remoteCredential.id()));
  206. return ((!threshold)||(ts > *threshold));
  207. }
  208. return false;
  209. }
  210. template<typename C>
  211. inline void _cleanCredImpl(const NetworkConfig &nconf,Hashtable<uint32_t,C> &remoteCreds)
  212. {
  213. uint32_t *k = (uint32_t *)0;
  214. C *v = (C *)0;
  215. typename Hashtable<uint32_t,C>::Iterator i(remoteCreds);
  216. while (i.next(k,v)) {
  217. if (!_isCredentialTimestampValid(nconf,*v))
  218. remoteCreds.erase(*k);
  219. }
  220. }
  221. // Last time we pushed MULTICAST_LIKE(s)
  222. int64_t _lastUpdatedMulticast;
  223. // Revocation threshold for COM or 0 if none
  224. int64_t _comRevocationThreshold;
  225. // Time we last pushed credentials
  226. int64_t _lastPushedCredentials;
  227. // Number of Ethernet frame bytes received
  228. uint64_t _received;
  229. // Number of Ethernet frame bytes sent
  230. uint64_t _sent;
  231. // Remote member's latest network COM
  232. CertificateOfMembership _com;
  233. // Revocations by credentialKey()
  234. Hashtable< uint64_t,int64_t > _revocations;
  235. // Remote credentials that we have received from this member (and that are valid)
  236. Hashtable< uint32_t,Tag > _remoteTags;
  237. Hashtable< uint32_t,Capability > _remoteCaps;
  238. Hashtable< uint32_t,CertificateOfOwnership > _remoteCoos;
  239. public:
  240. class CapabilityIterator
  241. {
  242. public:
  243. ZT_ALWAYS_INLINE CapabilityIterator(Membership &m,const NetworkConfig &nconf) :
  244. _hti(m._remoteCaps),
  245. _k((uint32_t *)0),
  246. _c((Capability *)0),
  247. _m(m),
  248. _nconf(nconf)
  249. {
  250. }
  251. ZT_ALWAYS_INLINE Capability *next()
  252. {
  253. while (_hti.next(_k,_c)) {
  254. if (_m._isCredentialTimestampValid(_nconf,*_c))
  255. return _c;
  256. }
  257. return (Capability *)0;
  258. }
  259. private:
  260. Hashtable< uint32_t,Capability >::Iterator _hti;
  261. uint32_t *_k;
  262. Capability *_c;
  263. Membership &_m;
  264. const NetworkConfig &_nconf;
  265. };
  266. };
  267. } // namespace ZeroTier
  268. #endif