Network.hpp 16 KB

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