Locator.hpp 11 KB

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