Network.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef _ZT_NETWORK_HPP
  28. #define _ZT_NETWORK_HPP
  29. #include <stdint.h>
  30. #include <string>
  31. #include <set>
  32. #include <map>
  33. #include <vector>
  34. #include <stdexcept>
  35. #include "Constants.hpp"
  36. #include "Utils.hpp"
  37. #include "EthernetTap.hpp"
  38. #include "Address.hpp"
  39. #include "Mutex.hpp"
  40. #include "SharedPtr.hpp"
  41. #include "AtomicCounter.hpp"
  42. #include "MulticastGroup.hpp"
  43. #include "NonCopyable.hpp"
  44. #include "MAC.hpp"
  45. #include "Dictionary.hpp"
  46. #include "Identity.hpp"
  47. #include "InetAddress.hpp"
  48. #include "BandwidthAccount.hpp"
  49. namespace ZeroTier {
  50. class RuntimeEnvironment;
  51. class NodeConfig;
  52. /**
  53. * A virtual LAN
  54. *
  55. * Networks can be open or closed. Each network has an ID whose most
  56. * significant 40 bits are the ZeroTier address of the node that should
  57. * be contacted for network configuration. The least significant 24
  58. * bits are arbitrary, allowing up to 2^24 networks per managing
  59. * node.
  60. *
  61. * Open networks do not track membership. Anyone is allowed to communicate
  62. * over them.
  63. *
  64. * Closed networks track membership by way of timestamped signatures. When
  65. * the network requests its configuration, one of the fields returned is
  66. * a signature for the identity of the peer on the network. This signature
  67. * includes a timestamp. When a peer communicates with other peers on a
  68. * closed network, it periodically (and pre-emptively) propagates this
  69. * signature to the peers with which it is communicating. Peers reject
  70. * packets with an error if no recent signature is on file.
  71. */
  72. class Network : NonCopyable
  73. {
  74. friend class SharedPtr<Network>;
  75. friend class NodeConfig;
  76. public:
  77. /**
  78. * Certificate of network membership
  79. *
  80. * The COM consists of a series of three-element 64-bit tuples. These values
  81. * are an id, a value, and a maximum delta. The ID is arbitrary and should be
  82. * assigned using a scheme that makes every ID globally unique for a given
  83. * type of parameter. ID 0 is reserved for the always-present timestamp
  84. * parameter. The value is parameter-specific. The maximum delta is the
  85. * maximum difference that is permitted between two values for determining
  86. * whether a certificate permits two peers to speak to one another. A value
  87. * of zero indicates that the values must equal.
  88. *
  89. * Certificates of membership must be signed by the netconf master for the
  90. * network in question. This permits members to verify these certs against
  91. * the netconf master's public key before testing them.
  92. */
  93. class CertificateOfMembership
  94. {
  95. public:
  96. CertificateOfMembership() throw() {}
  97. CertificateOfMembership(const char *s) { fromString(s); }
  98. CertificateOfMembership(const std::string &s) { fromString(s.c_str()); }
  99. /**
  100. * Add a paramter to this certificate
  101. *
  102. * @param id Parameter ID
  103. * @param value Parameter value
  104. * @param maxDelta Parameter maximum difference with others
  105. */
  106. void addParameter(uint64_t id,uint64_t value,uint64_t maxDelta);
  107. /**
  108. * @return Hex-serialized representation of this certificate (minus signature)
  109. */
  110. std::string toString() const;
  111. /**
  112. * Set this certificate equal to the hex-serialized string
  113. *
  114. * Invalid strings will result in invalid or undefined certificate
  115. * contents. These will subsequently fail validation and comparison.
  116. *
  117. * @param s String to deserialize
  118. */
  119. void fromString(const char *s);
  120. inline void fromString(const std::string &s) { fromString(s.c_str()); }
  121. /**
  122. * Compare two certificates for parameter agreement
  123. *
  124. * This compares this certificate with the other and returns true if all
  125. * paramters in this cert are present in the other and if they agree to
  126. * within this cert's max delta value for each given parameter.
  127. *
  128. * @param other Cert to compare with
  129. * @return True if certs agree and 'other' may be communicated with
  130. */
  131. bool compare(const CertificateOfMembership &other) const
  132. throw();
  133. private:
  134. struct _Parameter
  135. {
  136. _Parameter() throw() {}
  137. _Parameter(uint64_t i,uint64_t v,uint64_t m) throw() :
  138. id(i),
  139. value(v),
  140. maxDelta(m) {}
  141. uint64_t id;
  142. uint64_t value;
  143. uint64_t maxDelta;
  144. };
  145. // Used with std::sort to ensure that _params are sorted
  146. struct _SortByIdComparison
  147. {
  148. inline bool operator()(const _Parameter &a,const _Parameter &b) const
  149. throw()
  150. {
  151. return (a.id < b.id);
  152. }
  153. };
  154. std::vector<_Parameter> _params;
  155. };
  156. /**
  157. * A certificate of network membership for private network participation
  158. *
  159. * Certificates consist of a dictionary containing one or more values with
  160. * optional max delta paramters. A max delta paramter defines the maximum
  161. * absolute value of the difference between each set of two values in order
  162. * for two certificates to match. If there is no max delta parameter, each
  163. * value is compared for straightforward string equality. Values must be
  164. * in hexadecimal (and may be negative) for max delta comparison purposes.
  165. * Decimals are not allowed, so decimal values must be multiplied by some
  166. * factor to convert them to integers with the required relative precision.
  167. * Math is done in 64-bit, allowing plenty of room for this.
  168. *
  169. * This allows membership in a network to be defined not only in terms of
  170. * absolute parameters but also relative comparisons. For example, a network
  171. * could be created that defined membership in terms of a geographic radius.
  172. * Its certificates would contain latitude, longitude, and a max delta for
  173. * each defining the radius.
  174. *
  175. * Max deltas are prefixed by "~". For example, a max delta for "longitude"
  176. * would be "~longitude".
  177. *
  178. * One value and its associated max delta is just about always present: a
  179. * timestamp. This represents the time the certificate was issued by the
  180. * netconf controller. Each peer requests netconf updates periodically with
  181. * new certificates, so this causes peers that are no longer members of the
  182. * network to lose the ability to communicate with their certificate's "ts"
  183. * field differs from everyone else's "ts" by more than "~ts".
  184. */
  185. class Certificate : private Dictionary
  186. {
  187. public:
  188. Certificate() {}
  189. Certificate(const char *s) : Dictionary(s) {}
  190. Certificate(const std::string &s) : Dictionary(s) {}
  191. inline std::string toString() const { return Dictionary::toString(); }
  192. /**
  193. * Sign this certificate
  194. *
  195. * @param with Signing identity -- the identity of this network's controller
  196. * @return Signature or empty string on failure
  197. */
  198. inline std::string sign(const Identity &with) const
  199. {
  200. unsigned char dig[32];
  201. _shaForSignature(dig);
  202. return with.sign(dig);
  203. }
  204. /**
  205. * Verify this certificate's signature
  206. *
  207. * @param with Signing identity -- the identity of this network's controller
  208. * @param sig Signature
  209. * @param siglen Length of signature in bytes
  210. */
  211. inline bool verify(const Identity &with,const void *sig,unsigned int siglen) const
  212. {
  213. unsigned char dig[32];
  214. _shaForSignature(dig);
  215. return with.verifySignature(dig,sig,siglen);
  216. }
  217. /**
  218. * Check if another peer is indeed a current member of this network
  219. *
  220. * Fields with companion ~fields are compared with the defined maximum
  221. * delta in this certificate. Fields without ~fields are compared for
  222. * equality.
  223. *
  224. * This does not verify the certificate's signature!
  225. *
  226. * @param mc Peer membership certificate
  227. * @return True if mc's membership in this network is current
  228. */
  229. bool qualifyMembership(const Certificate &mc) const;
  230. private:
  231. void _shaForSignature(unsigned char *dig) const;
  232. };
  233. /**
  234. * Preload and rates of accrual for multicast group bandwidth limits
  235. *
  236. * Key is multicast group in lower case hex format: MAC (without :s) /
  237. * ADI (hex). Value is preload, maximum balance, and rate of accrual in
  238. * hex. These are signed hex numbers, so a negative value can be prefixed
  239. * with '-'.
  240. */
  241. class MulticastRates : private Dictionary
  242. {
  243. public:
  244. /**
  245. * Preload and accrual parameter tuple
  246. */
  247. struct Rate
  248. {
  249. Rate() {}
  250. Rate(int32_t pl,int32_t maxb,int32_t acc)
  251. {
  252. preload = pl;
  253. maxBalance = maxb;
  254. accrual = acc;
  255. }
  256. int32_t preload;
  257. int32_t maxBalance;
  258. int32_t accrual;
  259. };
  260. MulticastRates() {}
  261. MulticastRates(const char *s) : Dictionary(s) {}
  262. MulticastRates(const std::string &s) : Dictionary(s) {}
  263. inline std::string toString() const { return Dictionary::toString(); }
  264. /**
  265. * A very minimal default rate, fast enough for ARP
  266. */
  267. static const Rate GLOBAL_DEFAULT_RATE;
  268. /**
  269. * @return Default rate, or GLOBAL_DEFAULT_RATE if not specified
  270. */
  271. inline Rate defaultRate() const
  272. {
  273. Rate r;
  274. const_iterator dfl(find("*"));
  275. if (dfl == end())
  276. return GLOBAL_DEFAULT_RATE;
  277. return _toRate(dfl->second);
  278. }
  279. /**
  280. * Get the rate for a given multicast group
  281. *
  282. * @param mg Multicast group
  283. * @return Rate or default() rate if not specified
  284. */
  285. inline Rate get(const MulticastGroup &mg) const
  286. {
  287. const_iterator r(find(mg.toString()));
  288. if (r == end())
  289. return defaultRate();
  290. return _toRate(r->second);
  291. }
  292. private:
  293. static inline Rate _toRate(const std::string &s)
  294. {
  295. char tmp[16384];
  296. Utils::scopy(tmp,sizeof(tmp),s.c_str());
  297. Rate r(0,0,0);
  298. char *saveptr = (char *)0;
  299. unsigned int fn = 0;
  300. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  301. switch(fn++) {
  302. case 0:
  303. r.preload = (int32_t)Utils::hexStrToLong(f);
  304. break;
  305. case 1:
  306. r.maxBalance = (int32_t)Utils::hexStrToLong(f);
  307. break;
  308. case 2:
  309. r.accrual = (int32_t)Utils::hexStrToLong(f);
  310. break;
  311. }
  312. }
  313. return r;
  314. }
  315. };
  316. /**
  317. * A network configuration for a given node
  318. *
  319. * Configuration fields:
  320. *
  321. * nwid=<hex network ID> (required)
  322. * name=short name
  323. * desc=long(er) description
  324. * com=Certificate (serialized dictionary)
  325. * mr=MulticastRates (serialized dictionary)
  326. * o=open network? (1 or 0, default false if missing)
  327. * et=ethertype whitelist (comma-delimited list of ethertypes in decimal)
  328. * v4s=IPv4 static assignments / netmasks (comma-delimited)
  329. * v6s=IPv6 static assignments / netmasks (comma-delimited)
  330. */
  331. class Config : private Dictionary
  332. {
  333. public:
  334. Config() {}
  335. Config(const char *s) : Dictionary(s) {}
  336. Config(const std::string &s) : Dictionary(s) {}
  337. inline std::string toString() const { return Dictionary::toString(); }
  338. /**
  339. * @return True if configuration is valid and contains required fields
  340. */
  341. inline operator bool() const throw() { return (find("nwid") != end()); }
  342. /**
  343. * @return Network ID
  344. * @throws std::invalid_argument Network ID field missing
  345. */
  346. inline uint64_t networkId() const
  347. throw(std::invalid_argument)
  348. {
  349. return Utils::hexStrToU64(get("nwid").c_str());
  350. }
  351. /**
  352. * Get this network's short name, or its ID in hex if unspecified
  353. *
  354. * @return Short name of this network (e.g. "earth")
  355. */
  356. inline std::string name() const
  357. {
  358. const_iterator n(find("name"));
  359. if (n == end())
  360. return get("nwid");
  361. return n->second;
  362. }
  363. /**
  364. * @return Long description of network or empty string if not present
  365. */
  366. inline std::string desc() const
  367. {
  368. return get("desc",std::string());
  369. }
  370. /**
  371. * @return Certificate of membership for this network, or empty cert if none
  372. */
  373. inline Certificate certificateOfMembership() const
  374. {
  375. const_iterator cm(find("com"));
  376. if (cm == end())
  377. return Certificate();
  378. else return Certificate(cm->second);
  379. }
  380. /**
  381. * @return Multicast rates for this network
  382. */
  383. inline MulticastRates multicastRates() const
  384. {
  385. const_iterator mr(find("mr"));
  386. if (mr == end())
  387. return MulticastRates();
  388. else return MulticastRates(mr->second);
  389. }
  390. /**
  391. * @return True if this is an open non-access-controlled network
  392. */
  393. inline bool isOpen() const
  394. {
  395. const_iterator o(find("o"));
  396. if (o == end())
  397. return false;
  398. else if (!o->second.length())
  399. return false;
  400. else return (o->second[0] == '1');
  401. }
  402. /**
  403. * @return Network ethertype whitelist
  404. */
  405. inline std::set<unsigned int> etherTypes() const
  406. {
  407. char tmp[16384];
  408. char *saveptr = (char *)0;
  409. std::set<unsigned int> et;
  410. if (!Utils::scopy(tmp,sizeof(tmp),get("et","").c_str()))
  411. return et; // sanity check, packet can't really be that big
  412. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  413. unsigned int t = Utils::hexStrToUInt(f);
  414. if (t)
  415. et.insert(t);
  416. }
  417. return et;
  418. }
  419. /**
  420. * @return All static addresses / netmasks, IPv4 or IPv6
  421. */
  422. inline std::set<InetAddress> staticAddresses() const
  423. {
  424. std::set<InetAddress> sa;
  425. std::vector<std::string> ips(Utils::split(get("v4s","").c_str(),",","",""));
  426. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  427. sa.insert(InetAddress(*i));
  428. ips = Utils::split(get("v6s","").c_str(),",","","");
  429. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  430. sa.insert(InetAddress(*i));
  431. return sa;
  432. }
  433. };
  434. /**
  435. * Status for networks
  436. */
  437. enum Status
  438. {
  439. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  440. NETWORK_OK,
  441. NETWORK_ACCESS_DENIED
  442. };
  443. /**
  444. * @param s Status
  445. * @return String description
  446. */
  447. static const char *statusString(const Status s)
  448. throw();
  449. private:
  450. // Only NodeConfig can create, only SharedPtr can delete
  451. // Actual construction happens in newInstance()
  452. Network()
  453. throw() :
  454. _tap((EthernetTap *)0)
  455. {
  456. }
  457. ~Network();
  458. /**
  459. * Create a new Network instance and restore any saved state
  460. *
  461. * If there is no saved state, a dummy .conf is created on disk to remember
  462. * this network across restarts.
  463. *
  464. * @param renv Runtime environment
  465. * @param id Network ID
  466. * @return Reference counted pointer to new network
  467. * @throws std::runtime_error Unable to create tap device or other fatal error
  468. */
  469. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,uint64_t id)
  470. throw(std::runtime_error);
  471. /**
  472. * Causes all persistent disk presence to be erased on delete
  473. */
  474. inline void destroyOnDelete()
  475. {
  476. _destroyOnDelete = true;
  477. }
  478. public:
  479. /**
  480. * @return Network ID
  481. */
  482. inline uint64_t id() const throw() { return _id; }
  483. /**
  484. * @return Ethernet tap
  485. */
  486. inline EthernetTap &tap() throw() { return *_tap; }
  487. /**
  488. * @return Address of network's controlling node
  489. */
  490. inline Address controller() throw() { return Address(_id >> 24); }
  491. /**
  492. * @return Network ID in hexadecimal form
  493. */
  494. inline std::string toString()
  495. {
  496. char buf[64];
  497. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  498. return std::string(buf);
  499. }
  500. /**
  501. * @return True if network is open (no membership required)
  502. */
  503. inline bool isOpen() const
  504. throw()
  505. {
  506. try {
  507. Mutex::Lock _l(_lock);
  508. return _configuration.isOpen();
  509. } catch ( ... ) {
  510. return false;
  511. }
  512. }
  513. /**
  514. * Update multicast groups for this network's tap
  515. *
  516. * @return True if internal multicast group set has changed
  517. */
  518. inline bool updateMulticastGroups()
  519. {
  520. Mutex::Lock _l(_lock);
  521. return _tap->updateMulticastGroups(_multicastGroups);
  522. }
  523. /**
  524. * @return Latest set of multicast groups for this network's tap
  525. */
  526. inline std::set<MulticastGroup> multicastGroups() const
  527. {
  528. Mutex::Lock _l(_lock);
  529. return _multicastGroups;
  530. }
  531. /**
  532. * Set or update this network's configuration
  533. *
  534. * This is called by PacketDecoder when an update comes over the wire, or
  535. * internally when an old config is reloaded from disk.
  536. *
  537. * @param conf Configuration in key/value dictionary form
  538. */
  539. void setConfiguration(const Config &conf);
  540. /**
  541. * Causes this network to request an updated configuration from its master node now
  542. */
  543. void requestConfiguration();
  544. /**
  545. * Add or update a peer's membership certificate
  546. *
  547. * The certificate must already have been validated via signature checking.
  548. *
  549. * @param peer Peer that owns certificate
  550. * @param cert Certificate itself
  551. */
  552. void addMembershipCertificate(const Address &peer,const Certificate &cert);
  553. /**
  554. * @param peer Peer address to check
  555. * @return True if peer is allowed to communicate on this network
  556. */
  557. bool isAllowed(const Address &peer) const;
  558. /**
  559. * Perform cleanup and possibly save state
  560. */
  561. void clean();
  562. /**
  563. * @return Time of last updated configuration or 0 if none
  564. */
  565. inline uint64_t lastConfigUpdate() const
  566. throw()
  567. {
  568. return _lastConfigUpdate;
  569. }
  570. /**
  571. * @return Status of this network
  572. */
  573. Status status() const;
  574. /**
  575. * Determine whether frames of a given ethernet type are allowed on this network
  576. *
  577. * @param etherType Ethernet frame type
  578. * @return True if network permits this type
  579. */
  580. inline bool permitsEtherType(unsigned int etherType) const
  581. throw()
  582. {
  583. if (!etherType)
  584. return false;
  585. else if (etherType > 65535)
  586. return false;
  587. else return ((_etWhitelist[etherType / 8] & (unsigned char)(1 << (etherType % 8))) != 0);
  588. }
  589. /**
  590. * Update multicast balance for an address and multicast group, return whether packet is allowed
  591. *
  592. * @param a Address that wants to send/relay packet
  593. * @param mg Multicast group
  594. * @param bytes Size of packet
  595. * @return True if packet is within budget
  596. */
  597. inline bool updateAndCheckMulticastBalance(const Address &a,const MulticastGroup &mg,unsigned int bytes)
  598. {
  599. Mutex::Lock _l(_lock);
  600. std::pair<Address,MulticastGroup> k(a,mg);
  601. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(k));
  602. if (bal == _multicastRateAccounts.end()) {
  603. MulticastRates::Rate r(_mcRates.get(mg));
  604. bal = _multicastRateAccounts.insert(std::pair< std::pair<Address,MulticastGroup>,BandwidthAccount >(k,BandwidthAccount(r.preload,r.maxBalance,r.accrual))).first;
  605. }
  606. return (bal->second.update((int32_t)bytes) >= 0);
  607. }
  608. private:
  609. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  610. void _restoreState();
  611. const RuntimeEnvironment *_r;
  612. // Multicast bandwidth accounting for peers on this network
  613. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount > _multicastRateAccounts;
  614. // Tap and tap multicast memberships for this node on this network
  615. EthernetTap *_tap;
  616. std::set<MulticastGroup> _multicastGroups;
  617. // Membership certificates supplied by other peers on this network
  618. std::map<Address,Certificate> _membershipCertificates;
  619. // Configuration from network master node
  620. Config _configuration;
  621. Certificate _myCertificate; // memoized from _configuration
  622. MulticastRates _mcRates; // memoized from _configuration
  623. // Ethertype whitelist bit field, set from config, for really fast lookup
  624. unsigned char _etWhitelist[65536 / 8];
  625. uint64_t _id;
  626. volatile uint64_t _lastConfigUpdate;
  627. volatile bool _destroyOnDelete;
  628. volatile bool _ready;
  629. Mutex _lock;
  630. AtomicCounter __refCount;
  631. };
  632. } // naemspace ZeroTier
  633. #endif