Network.hpp 16 KB

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