Locator.hpp 11 KB

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