Network.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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: 2025-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_NETWORK_HPP
  14. #define ZT_NETWORK_HPP
  15. #include <stdint.h>
  16. #include "../include/ZeroTierOne.h"
  17. #include <string>
  18. #include <map>
  19. #include <vector>
  20. #include <algorithm>
  21. #include <stdexcept>
  22. #include "Constants.hpp"
  23. #include "Hashtable.hpp"
  24. #include "Address.hpp"
  25. #include "Mutex.hpp"
  26. #include "SharedPtr.hpp"
  27. #include "AtomicCounter.hpp"
  28. #include "MulticastGroup.hpp"
  29. #include "MAC.hpp"
  30. #include "Dictionary.hpp"
  31. #include "Multicaster.hpp"
  32. #include "Membership.hpp"
  33. #include "NetworkConfig.hpp"
  34. #include "CertificateOfMembership.hpp"
  35. #define ZT_NETWORK_MAX_INCOMING_UPDATES 3
  36. #define ZT_NETWORK_MAX_UPDATE_CHUNKS ((ZT_NETWORKCONFIG_DICT_CAPACITY / 1024) + 1)
  37. namespace zeroidc {
  38. typedef struct ZeroIDC ZeroIDC;
  39. }
  40. namespace ZeroTier {
  41. class RuntimeEnvironment;
  42. class Peer;
  43. /**
  44. * A virtual LAN
  45. */
  46. class Network
  47. {
  48. friend class SharedPtr<Network>;
  49. public:
  50. /**
  51. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  52. */
  53. static const MulticastGroup BROADCAST;
  54. /**
  55. * Compute primary controller device ID from network ID
  56. */
  57. static inline Address controllerFor(uint64_t nwid) { return Address(nwid >> 24); }
  58. /**
  59. * Construct a new network
  60. *
  61. * Note that init() should be called immediately after the network is
  62. * constructed to actually configure the port.
  63. *
  64. * @param renv Runtime environment
  65. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  66. * @param nwid Network ID
  67. * @param uptr Arbitrary pointer used by externally-facing API (for user use)
  68. * @param nconf Network config, if known
  69. */
  70. Network(const RuntimeEnvironment *renv,void *tPtr,uint64_t nwid,void *uptr,const NetworkConfig *nconf);
  71. ~Network();
  72. inline uint64_t id() const { return _id; }
  73. inline Address controller() const { return Address(_id >> 24); }
  74. inline bool multicastEnabled() const { return (_config.multicastLimit > 0); }
  75. inline bool hasConfig() const { return (_config); }
  76. inline uint64_t lastConfigUpdate() const { return _lastConfigUpdate; }
  77. inline ZT_VirtualNetworkStatus status() const { Mutex::Lock _l(_lock); return _status(); }
  78. inline const NetworkConfig &config() const { return _config; }
  79. inline const MAC &mac() const { return _mac; }
  80. /**
  81. * Apply filters to an outgoing packet
  82. *
  83. * This applies filters from our network config and, if that doesn't match,
  84. * our capabilities in ascending order of capability ID. Additional actions
  85. * such as TEE may be taken, and credentials may be pushed, so this is not
  86. * side-effect-free. It's basically step one in sending something over VL2.
  87. *
  88. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  89. * @param noTee If true, do not TEE anything anywhere (for two-pass filtering as done with multicast and bridging)
  90. * @param ztSource Source ZeroTier address
  91. * @param ztDest Destination ZeroTier address
  92. * @param macSource Ethernet layer source address
  93. * @param macDest Ethernet layer destination address
  94. * @param frameData Ethernet frame data
  95. * @param frameLen Ethernet frame payload length
  96. * @param etherType 16-bit ethernet type ID
  97. * @param vlanId 16-bit VLAN ID
  98. * @return True if packet should be sent, false if dropped or redirected
  99. */
  100. bool filterOutgoingPacket(
  101. void *tPtr,
  102. const bool noTee,
  103. const Address &ztSource,
  104. const Address &ztDest,
  105. const MAC &macSource,
  106. const MAC &macDest,
  107. const uint8_t *frameData,
  108. const unsigned int frameLen,
  109. const unsigned int etherType,
  110. const unsigned int vlanId,
  111. uint8_t &qosBucket);
  112. /**
  113. * Apply filters to an incoming packet
  114. *
  115. * This applies filters from our network config and, if that doesn't match,
  116. * the peer's capabilities in ascending order of capability ID. If there is
  117. * a match certain actions may be taken such as sending a copy of the packet
  118. * to a TEE or REDIRECT target.
  119. *
  120. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  121. * @param sourcePeer Source Peer
  122. * @param ztDest Destination ZeroTier address
  123. * @param macSource Ethernet layer source address
  124. * @param macDest Ethernet layer destination address
  125. * @param frameData Ethernet frame data
  126. * @param frameLen Ethernet frame payload length
  127. * @param etherType 16-bit ethernet type ID
  128. * @param vlanId 16-bit VLAN ID
  129. * @return 0 == drop, 1 == accept, 2 == accept even if bridged
  130. */
  131. int filterIncomingPacket(
  132. void *tPtr,
  133. const SharedPtr<Peer> &sourcePeer,
  134. const Address &ztDest,
  135. const MAC &macSource,
  136. const MAC &macDest,
  137. const uint8_t *frameData,
  138. const unsigned int frameLen,
  139. const unsigned int etherType,
  140. const unsigned int vlanId);
  141. /**
  142. * Check whether we are subscribed to a multicast group
  143. *
  144. * @param mg Multicast group
  145. * @param includeBridgedGroups If true, also check groups we've learned via bridging
  146. * @return True if this network endpoint / peer is a member
  147. */
  148. bool subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const;
  149. /**
  150. * Subscribe to a multicast group
  151. *
  152. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  153. * @param mg New multicast group
  154. */
  155. void multicastSubscribe(void *tPtr,const MulticastGroup &mg);
  156. /**
  157. * Unsubscribe from a multicast group
  158. *
  159. * @param mg Multicast group
  160. */
  161. void multicastUnsubscribe(const MulticastGroup &mg);
  162. /**
  163. * Handle an inbound network config chunk
  164. *
  165. * This is called from IncomingPacket to handle incoming network config
  166. * chunks via OK(NETWORK_CONFIG_REQUEST) or NETWORK_CONFIG. It verifies
  167. * each chunk and once assembled applies the configuration.
  168. *
  169. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  170. * @param packetId Packet ID or 0 if none (e.g. via cluster path)
  171. * @param source Address of sender of chunk or NULL if none (e.g. via cluster path)
  172. * @param chunk Buffer containing chunk
  173. * @param ptr Index of chunk and related fields in packet
  174. * @return Update ID if update was fully assembled and accepted or 0 otherwise
  175. */
  176. uint64_t handleConfigChunk(void *tPtr,const uint64_t packetId,const Address &source,const Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &chunk,unsigned int ptr);
  177. /**
  178. * Set network configuration
  179. *
  180. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  181. * @param nconf Network configuration
  182. * @param saveToDisk Save to disk? Used during loading, should usually be true otherwise.
  183. * @return 0 == bad, 1 == accepted but duplicate/unchanged, 2 == accepted and new
  184. */
  185. int setConfiguration(void *tPtr,const NetworkConfig &nconf,bool saveToDisk);
  186. /**
  187. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  188. */
  189. inline void setAccessDenied()
  190. {
  191. Mutex::Lock _l(_lock);
  192. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  193. }
  194. /**
  195. * Set netconf failure to 'not found' -- called by IncomingPacket when controller reports this
  196. */
  197. inline void setNotFound()
  198. {
  199. Mutex::Lock _l(_lock);
  200. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  201. }
  202. /**
  203. * Set netconf failure to 'authentication required' possibly with an authorization URL
  204. */
  205. inline void setAuthenticationRequired(const char *url)
  206. {
  207. Mutex::Lock _l(_lock);
  208. _netconfFailure = NETCONF_FAILURE_AUTHENTICATION_REQUIRED;
  209. _authenticationURL = (url) ? url : "";
  210. _config.ssoEnabled = true;
  211. _config.ssoVersion = 0;
  212. }
  213. /**
  214. * set netconf failure to 'authentication required' along with info needed
  215. * for sso full flow authentication.
  216. */
  217. void setAuthenticationRequired(const char* issuerURL, const char* centralEndpoint, const char* clientID, const char* nonce, const char* state);
  218. /**
  219. * Causes this network to request an updated configuration from its master node now
  220. *
  221. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  222. */
  223. void requestConfiguration(void *tPtr);
  224. /**
  225. * Determine whether this peer is permitted to communicate on this network
  226. *
  227. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  228. * @param peer Peer to check
  229. */
  230. bool gate(void *tPtr,const SharedPtr<Peer> &peer);
  231. /**
  232. * Check whether a given peer has recently had an association with this network
  233. *
  234. * This checks whether a peer has communicated with us recently about this
  235. * network and has possessed a valid certificate of membership. This may return
  236. * true even if the peer has been offline for a while or no longer has a valid
  237. * certificate of membership but had one recently.
  238. *
  239. * @param addr Peer address
  240. * @return True if peer has recently associated
  241. */
  242. bool recentlyAssociatedWith(const Address &addr);
  243. /**
  244. * Do periodic cleanup and housekeeping tasks
  245. */
  246. void clean();
  247. /**
  248. * Push state to members such as multicast group memberships and latest COM (if needed)
  249. *
  250. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  251. */
  252. inline void sendUpdatesToMembers(void *tPtr)
  253. {
  254. Mutex::Lock _l(_lock);
  255. _sendUpdatesToMembers(tPtr,(const MulticastGroup *)0);
  256. }
  257. /**
  258. * Find the node on this network that has this MAC behind it (if any)
  259. *
  260. * @param mac MAC address
  261. * @return ZeroTier address of bridge to this MAC
  262. */
  263. inline Address findBridgeTo(const MAC &mac) const
  264. {
  265. Mutex::Lock _l(_lock);
  266. const Address *const br = _remoteBridgeRoutes.get(mac);
  267. return ((br) ? *br : Address());
  268. }
  269. /**
  270. * @return True if QoS is in effect for this network
  271. */
  272. inline bool qosEnabled() { return false; }
  273. /**
  274. * Set a bridge route
  275. *
  276. * @param mac MAC address of destination
  277. * @param addr Bridge this MAC is reachable behind
  278. */
  279. void learnBridgeRoute(const MAC &mac,const Address &addr);
  280. /**
  281. * Learn a multicast group that is bridged to our tap device
  282. *
  283. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  284. * @param mg Multicast group
  285. * @param now Current time
  286. */
  287. void learnBridgedMulticastGroup(void *tPtr,const MulticastGroup &mg,int64_t now);
  288. /**
  289. * Validate a credential and learn it if it passes certificate and other checks
  290. */
  291. Membership::AddCredentialResult addCredential(void *tPtr,const CertificateOfMembership &com);
  292. /**
  293. * Validate a credential and learn it if it passes certificate and other checks
  294. */
  295. inline Membership::AddCredentialResult addCredential(void *tPtr,const Capability &cap)
  296. {
  297. if (cap.networkId() != _id)
  298. return Membership::ADD_REJECTED;
  299. Mutex::Lock _l(_lock);
  300. return _membership(cap.issuedTo()).addCredential(RR,tPtr,_config,cap);
  301. }
  302. /**
  303. * Validate a credential and learn it if it passes certificate and other checks
  304. */
  305. inline Membership::AddCredentialResult addCredential(void *tPtr,const Tag &tag)
  306. {
  307. if (tag.networkId() != _id)
  308. return Membership::ADD_REJECTED;
  309. Mutex::Lock _l(_lock);
  310. return _membership(tag.issuedTo()).addCredential(RR,tPtr,_config,tag);
  311. }
  312. /**
  313. * Validate a credential and learn it if it passes certificate and other checks
  314. */
  315. Membership::AddCredentialResult addCredential(void *tPtr,const Address &sentFrom,const Revocation &rev);
  316. /**
  317. * Validate a credential and learn it if it passes certificate and other checks
  318. */
  319. inline Membership::AddCredentialResult addCredential(void *tPtr,const CertificateOfOwnership &coo)
  320. {
  321. if (coo.networkId() != _id)
  322. return Membership::ADD_REJECTED;
  323. Mutex::Lock _l(_lock);
  324. return _membership(coo.issuedTo()).addCredential(RR,tPtr,_config,coo);
  325. }
  326. /**
  327. * Force push credentials (COM, etc.) to a peer now
  328. *
  329. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  330. * @param to Destination peer address
  331. * @param now Current time
  332. */
  333. inline void pushCredentialsNow(void *tPtr,const Address &to,const int64_t now)
  334. {
  335. Mutex::Lock _l(_lock);
  336. _membership(to).pushCredentials(RR,tPtr,now,to,_config);
  337. }
  338. /**
  339. * Push credentials if we haven't done so in a very long time
  340. *
  341. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  342. * @param to Destination peer address
  343. * @param now Current time
  344. */
  345. inline void pushCredentialsIfNeeded(void *tPtr,const Address &to,const int64_t now)
  346. {
  347. Mutex::Lock _l(_lock);
  348. Membership &m = _membership(to);
  349. if (m.shouldPushCredentials(now))
  350. m.pushCredentials(RR,tPtr,now,to,_config);
  351. }
  352. /**
  353. * Destroy this network
  354. *
  355. * This sets the network to completely remove itself on delete. This also prevents the
  356. * call of the normal port shutdown event on delete.
  357. */
  358. void destroy();
  359. /**
  360. * Get this network's config for export via the ZT core API
  361. *
  362. * @param ec Buffer to fill with externally-visible network configuration
  363. */
  364. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  365. {
  366. Mutex::Lock _l(_lock);
  367. _externalConfig(ec);
  368. }
  369. /**
  370. * @return Externally usable pointer-to-pointer exported via the core API
  371. */
  372. inline void **userPtr() { return &_uPtr; }
  373. private:
  374. ZT_VirtualNetworkStatus _status() const;
  375. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  376. bool _gate(const SharedPtr<Peer> &peer);
  377. void _sendUpdatesToMembers(void *tPtr,const MulticastGroup *const newMulticastGroup);
  378. void _announceMulticastGroupsTo(void *tPtr,const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups);
  379. std::vector<MulticastGroup> _allMulticastGroups() const;
  380. Membership &_membership(const Address &a);
  381. const RuntimeEnvironment *const RR;
  382. void *_uPtr;
  383. const uint64_t _id;
  384. uint64_t _lastAnnouncedMulticastGroupsUpstream;
  385. MAC _mac; // local MAC address
  386. bool _portInitialized;
  387. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
  388. Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  389. Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  390. NetworkConfig _config;
  391. uint64_t _lastConfigUpdate;
  392. struct _IncomingConfigChunk
  393. {
  394. _IncomingConfigChunk() { memset(this,0,sizeof(_IncomingConfigChunk)); }
  395. uint64_t ts;
  396. uint64_t updateId;
  397. uint64_t haveChunkIds[ZT_NETWORK_MAX_UPDATE_CHUNKS];
  398. unsigned long haveChunks;
  399. unsigned long haveBytes;
  400. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> data;
  401. };
  402. _IncomingConfigChunk _incomingConfigChunks[ZT_NETWORK_MAX_INCOMING_UPDATES];
  403. bool _destroyed;
  404. enum {
  405. NETCONF_FAILURE_NONE,
  406. NETCONF_FAILURE_ACCESS_DENIED,
  407. NETCONF_FAILURE_NOT_FOUND,
  408. NETCONF_FAILURE_INIT_FAILED,
  409. NETCONF_FAILURE_AUTHENTICATION_REQUIRED
  410. } _netconfFailure;
  411. int _portError; // return value from port config callback
  412. std::string _authenticationURL;
  413. Hashtable<Address,Membership> _memberships;
  414. Mutex _lock;
  415. AtomicCounter __refCount;
  416. zeroidc::ZeroIDC *_idc;
  417. };
  418. } // namespace ZeroTier
  419. #endif