Locator.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_LOCATOR_HPP
  27. #define ZT_LOCATOR_HPP
  28. #include "Constants.hpp"
  29. #include "Identity.hpp"
  30. #include "InetAddress.hpp"
  31. #include "Utils.hpp"
  32. #include "Buffer.hpp"
  33. #include "SHA512.hpp"
  34. #include "Str.hpp"
  35. #include <algorithm>
  36. #include <vector>
  37. #define ZT_LOCATOR_MAX_PHYSICAL_ADDRESSES 255
  38. #define ZT_LOCATOR_MAX_VIRTUAL_ADDRESSES 255
  39. namespace ZeroTier {
  40. /**
  41. * Signed information about a node's location on the network
  42. *
  43. * A locator is a signed record that contains information about where a node
  44. * may be found. It can contain static physical addresses or virtual ZeroTier
  45. * addresses of nodes that can forward to the target node. Locator records
  46. * can be stored in signed DNS TXT record sets, in LF by roots, in caches,
  47. * etc. Version 2.x nodes can sign their own locators. Roots can create
  48. * signed locators using their own signature for version 1.x nodes. Locators
  49. * signed by the node whose location they describe always take precedence
  50. * over locators signed by other nodes.
  51. */
  52. class Locator
  53. {
  54. public:
  55. inline Locator() : _signatureLength(0) {}
  56. inline const Identity &id() const { return _id; }
  57. inline const Identity &signer() const { return ((_signedBy) ? _signedBy : _id); }
  58. inline const std::vector<InetAddress> &phy() const { return _physical; }
  59. inline const std::vector<Identity> &virt() const { return _virtual; }
  60. /**
  61. * Add a physical address to this locator (call before finish() to build a new Locator)
  62. */
  63. inline void add(const InetAddress &ip)
  64. {
  65. if (_physical.size() < ZT_LOCATOR_MAX_PHYSICAL_ADDRESSES)
  66. _physical.push_back(ip);
  67. }
  68. /**
  69. * Add a forwarding ZeroTier node to this locator (call before finish() to build a new Locator)
  70. */
  71. inline void add(const Identity &zt)
  72. {
  73. if (_virtual.size() < ZT_LOCATOR_MAX_VIRTUAL_ADDRESSES)
  74. _virtual.push_back(zt);
  75. }
  76. /**
  77. * Method to be called after add() is called for each address or forwarding node
  78. *
  79. * This sets timestamp and ID information and sorts and deduplicates target
  80. * lists but does not sign the locator. The sign() method should be used after
  81. * finish().
  82. */
  83. inline void finish(const Identity &id,const int64_t ts)
  84. {
  85. _ts = ts;
  86. _id = id;
  87. std::sort(_physical.begin(),_physical.end());
  88. _physical.erase(std::unique(_physical.begin(),_physical.end()),_physical.end());
  89. std::sort(_virtual.begin(),_virtual.end());
  90. _virtual.erase(std::unique(_virtual.begin(),_virtual.end()),_virtual.end());
  91. }
  92. /**
  93. * Sign this locator (must be called after finish())
  94. */
  95. inline bool sign(const Identity &signingId)
  96. {
  97. if (!signingId.hasPrivate())
  98. return false;
  99. if (signingId == _id) {
  100. _signedBy.zero();
  101. } else {
  102. _signedBy = signingId;
  103. }
  104. Buffer<65536> *tmp = new Buffer<65536>();
  105. try {
  106. serialize(*tmp,true);
  107. _signatureLength = signingId.sign(tmp->data(),tmp->size(),_signature,ZT_SIGNATURE_BUFFER_SIZE);
  108. delete tmp;
  109. return (_signatureLength > 0);
  110. } catch ( ... ) {
  111. delete tmp;
  112. return false;
  113. }
  114. }
  115. /**
  116. * Verify this locator's signature against its embedded signing identity
  117. */
  118. inline bool verify() const
  119. {
  120. if ((_signatureLength == 0)||(_signatureLength > sizeof(_signature)))
  121. return false;
  122. Buffer<65536> *tmp = nullptr;
  123. try {
  124. tmp = new Buffer<65536>();
  125. serialize(*tmp,true);
  126. const bool ok = (_signedBy) ? _signedBy.verify(tmp->data(),tmp->size(),_signature,_signatureLength) : _id.verify(tmp->data(),tmp->size(),_signature,_signatureLength);
  127. delete tmp;
  128. return ok;
  129. } catch ( ... ) {
  130. if (tmp) delete tmp;
  131. return false;
  132. }
  133. }
  134. /**
  135. * Make DNS TXT records for this locator
  136. *
  137. * DNS TXT records are signed by an entirely separate key that is added along
  138. * with DNS names to nodes to allow them to verify DNS results. It's separate
  139. * from the locator's signature so that a single DNS record can point to more
  140. * than one locator or be served by things like geo-aware DNS.
  141. *
  142. * Right now only NIST P-384 is supported for signing DNS records. NIST EDDSA
  143. * is used here so that FIPS-only nodes can always use DNS to locate roots as
  144. * FIPS-only nodes may be required to disable non-FIPS algorithms.
  145. */
  146. inline std::vector<Str> makeTxtRecords(const uint8_t p384SigningKeyPublic[ZT_ECC384_PUBLIC_KEY_SIZE],const uint8_t p384SigningKeyPrivate[ZT_ECC384_PUBLIC_KEY_SIZE])
  147. {
  148. uint8_t s384[48],dnsSig[ZT_ECC384_SIGNATURE_SIZE];
  149. char enc[256];
  150. Buffer<65536> *const tmp = new Buffer<65536>();
  151. serialize(*tmp,false);
  152. SHA384(s384,tmp->data(),tmp->size());
  153. ECC384ECDSASign(p384SigningKeyPrivate,s384,dnsSig);
  154. tmp->append(dnsSig,ZT_ECC384_SIGNATURE_SIZE);
  155. // Blob must be broken into multiple TXT records that must remain sortable so they are prefixed by a hex value.
  156. // 186-byte chunks yield 248-byte base64 chunks which leaves some margin below the limit of 255.
  157. std::vector<Str> txtRecords;
  158. for(unsigned int p=0;p<tmp->size();p+=186) {
  159. unsigned int rem = tmp->size() - p;
  160. if (rem > 186) rem = 186;
  161. Utils::b64e(((const uint8_t *)tmp->data()) + p,rem,enc,sizeof(enc));
  162. txtRecords.push_back(Str());
  163. txtRecords.back() << Utils::HEXCHARS[(p >> 4) & 0xf] << Utils::HEXCHARS[p & 0xf] << enc;
  164. }
  165. delete tmp;
  166. return txtRecords;
  167. }
  168. /**
  169. * Decode TXT records
  170. *
  171. * The supplied TXT records must be sorted in ascending natural sort order prior
  172. * to calling this method. The iterators supplied must be read iterators that
  173. * point to string objects supporting the c_str() method, which can be Str or
  174. * std::string.
  175. *
  176. * This method checks the decoded locator's signature using the supplied DNS TXT
  177. * record signing public key. False is returned if the TXT records are invalid,
  178. * incomplete, or fail signature check. If true is returned this Locator object
  179. * now contains the contents of the supplied TXT records.
  180. */
  181. template<typename I>
  182. inline bool decodeTxtRecords(I start,I end,const uint8_t p384SigningKeyPublic[ZT_ECC384_PUBLIC_KEY_SIZE])
  183. {
  184. uint8_t dec[256],s384[48];
  185. Buffer<65536> *tmp = nullptr;
  186. try {
  187. tmp = new Buffer<65536>();
  188. while (start != end) {
  189. tmp->append(dec,Utils::b64d(start->c_str(),dec,sizeof(dec)));
  190. ++start;
  191. }
  192. if (tmp->size() <= ZT_ECC384_SIGNATURE_SIZE) {
  193. delete tmp;
  194. return false;
  195. }
  196. SHA384(s384,tmp->data(),tmp->size() - ZT_ECC384_SIGNATURE_SIZE);
  197. if (!ECC384ECDSAVerify(p384SigningKeyPublic,s384,((const uint8_t *)tmp->data()) + (tmp->size() - ZT_ECC384_SIGNATURE_SIZE))) {
  198. delete tmp;
  199. return false;
  200. }
  201. deserialize(*tmp,0);
  202. delete tmp;
  203. return verify();
  204. } catch ( ... ) {
  205. if (tmp) delete tmp;
  206. return false;
  207. }
  208. }
  209. template<unsigned int C>
  210. inline void serialize(Buffer<C> &b,const bool forSign = false) const
  211. {
  212. if (forSign) b.append((uint64_t)0x7f7f7f7f7f7f7f7fULL);
  213. b.append((uint8_t)0); // version/flags, currently 0
  214. b.append((uint64_t)_ts);
  215. _id.serialise(b,false);
  216. if (_signedBy) {
  217. b.append((uint8_t)1); // number of signers, current max is 1
  218. _signedBy.serialize(b,false);
  219. } else {
  220. b.append((uint8_t)0); // signer is _id
  221. }
  222. b.append((uint8_t)_physical.size());
  223. for(std::vector<InetAddress>::const_iterator i(_physical.begin());i!=_physical.end();++i)
  224. i->serialize(b);
  225. b.append((uint8_t)_virtual.size());
  226. for(std::vector<Identity>::const_iterator i(_virtual.begin());i!=_virtual.end();++i)
  227. i->serialize(b,false);
  228. if (!forSign) {
  229. b.append((uint16_t)_signatureLength);
  230. b.append(_signature,_signatureLength);
  231. }
  232. b.append((uint16_t)0); // length of additional fields, currently 0
  233. if (forSign) b.append((uint64_t)0x7f7f7f7f7f7f7f7fULL);
  234. }
  235. template<unsigned int C>
  236. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  237. {
  238. unsigned int p = startAt;
  239. if (b[p++] != 0)
  240. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  241. _ts = (int64_t)b.template at<uint64_t>(p); p += 8;
  242. p += _id.deserialize(b,p);
  243. const unsigned int signerCount = b[p++];
  244. if (signerCount > 1) /* only one third party signer is currently supported */
  245. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
  246. if (signerCount == 1) {
  247. p += _signedBy.deserialize(b,p);
  248. } else {
  249. _signedBy.zero();
  250. }
  251. const unsigned int physicalCount = b[p++];
  252. _physical.resize(physicalCount);
  253. for(unsigned int i=0;i<physicalCount;++i)
  254. p += _physical[i].deserialize(b,p);
  255. const unsigned int virtualCount = b[p++];
  256. _virtual.resize(virtualCount);
  257. for(unsigned int i=0;i<virtualCount;++i)
  258. p += _virtual[i].deserialize(b,p);
  259. _signatureLen = b.template at<uint16_t>(p); p += 2;
  260. if (_signatureLength > ZT_SIGNATURE_BUFFER_SIZE)
  261. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
  262. memcpy(_signature,b.field(p,_signatureLength),_signatureLength);
  263. p += _signatureLength;
  264. p += b.template at<uint16_t>(p); p += 2;
  265. if (p > b.size())
  266. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
  267. return (p - startAt);
  268. }
  269. inline operator bool() const { return (_id); }
  270. inline bool operator==(const Locator &l) const { return ((_ts == l._ts)&&(_id == l._id)&&(_signedBy == l._signedBy)&&(_physical == l._physical)&&(_virtual == l._virtual)&&(_signatureLength == l._signatureLength)&&(memcmp(_signature,l._signature,_signatureLength) == 0)); }
  271. inline bool operator!=(const Locator &l) const { return (!(*this == l)); }
  272. inline bool operator<(const Locator &l) const
  273. {
  274. if (_id < l._id) return true;
  275. if (_ts < l._ts) return true;
  276. if (_signedBy < l._signedBy) return true;
  277. if (_physical < l._physical) return true;
  278. if (_virtual < l._virtual) return true;
  279. return false;
  280. }
  281. inline bool operator>(const Locator &l) const { return (l < *this); }
  282. inline bool operator<=(const Locator &l) const { return (!(l < *this)); }
  283. inline bool operator>=(const Locator &l) const { return (!(*this < l)); }
  284. inline unsigned long hashCode() const { return (unsigned long)(_id.address().toInt() ^ (uint64_t)_ts); }
  285. private:
  286. int64_t _ts;
  287. Identity _id;
  288. Identity _signedBy; // signed by _id if nil/zero
  289. std::vector<InetAddress> _physical;
  290. std::vector<Identity> _virtual;
  291. unsigned int _signatureLength;
  292. uint8_t _signature[ZT_SIGNATURE_BUFFER_SIZE];
  293. };
  294. } // namespace ZeroTier
  295. #endif