Locator.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. ZT_ALWAYS_INLINE Locator() : _ts(0),_signatureLength(0) {}
  44. ZT_ALWAYS_INLINE const Identity &id() const { return _id; }
  45. ZT_ALWAYS_INLINE const Identity &signer() const { return ((_signedBy) ? _signedBy : _id); }
  46. ZT_ALWAYS_INLINE int64_t timestamp() const { return _ts; }
  47. ZT_ALWAYS_INLINE const std::vector<InetAddress> &phy() const { return _physical; }
  48. ZT_ALWAYS_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. ZT_ALWAYS_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. ZT_ALWAYS_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. ZT_ALWAYS_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. ZT_ALWAYS_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. ZT_ALWAYS_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 a DNS name contiaining a public key that can sign DNS entries
  120. *
  121. * This generates the initial fields of a DNS name that contains an
  122. * encoded public key. Users may append any domain suffix to this name.
  123. *
  124. * @return First field(s) of DNS name
  125. */
  126. static inline Str makeSecureDnsName(const uint8_t p384SigningKeyPublic[ZT_ECC384_PUBLIC_KEY_SIZE])
  127. {
  128. uint8_t tmp[ZT_ECC384_PUBLIC_KEY_SIZE+2];
  129. memcpy(tmp,p384SigningKeyPublic,ZT_ECC384_PUBLIC_KEY_SIZE);
  130. const uint16_t crc = Utils::crc16(tmp,ZT_ECC384_PUBLIC_KEY_SIZE);
  131. tmp[ZT_ECC384_PUBLIC_KEY_SIZE-2] = (uint8_t)(crc >> 8);
  132. tmp[ZT_ECC384_PUBLIC_KEY_SIZE-1] = (uint8_t)(crc);
  133. Str name;
  134. char b32[128];
  135. Utils::b32e(tmp,35,b32,sizeof(b32));
  136. name << b32;
  137. Utils::b32e(tmp + 35,(ZT_ECC384_PUBLIC_KEY_SIZE+2) - 35,b32,sizeof(b32));
  138. name << '.';
  139. name << b32;
  140. return name;
  141. }
  142. /**
  143. * @return True if a key was found and successfully decoded
  144. */
  145. static inline bool decodeSecureDnsName(const char *name,uint8_t p384SigningKeyPublic[ZT_ECC384_PUBLIC_KEY_SIZE])
  146. {
  147. uint8_t b32[128];
  148. unsigned int b32ptr = 0;
  149. char tmp[1024];
  150. Utils::scopy(tmp,sizeof(tmp),name);
  151. bool ok = false;
  152. for(char *saveptr=(char *)0,*p=Utils::stok(tmp,".",&saveptr);p;p=Utils::stok((char *)0,".",&saveptr)) {
  153. if (b32ptr >= sizeof(b32))
  154. break;
  155. int s = Utils::b32d(p,b32 + b32ptr,sizeof(b32) - b32ptr);
  156. if (s > 0) {
  157. b32ptr += (unsigned int)s;
  158. if (b32ptr > 2) {
  159. const uint16_t crc = Utils::crc16(b32,b32ptr);
  160. if ((b32[b32ptr-2] == (uint8_t)(crc >> 8))&&(b32[b32ptr-1] == (uint8_t)(crc & 0xff))) {
  161. ok = true;
  162. break;
  163. }
  164. }
  165. } else break;
  166. }
  167. if (ok) {
  168. if (b32ptr == (ZT_ECC384_PUBLIC_KEY_SIZE + 2)) {
  169. memcpy(p384SigningKeyPublic,b32,ZT_ECC384_PUBLIC_KEY_SIZE);
  170. return true;
  171. }
  172. }
  173. return false;
  174. }
  175. /**
  176. * Make DNS TXT records for this locator
  177. *
  178. * DNS TXT records are signed by an entirely separate key that is added along
  179. * with DNS names to nodes to allow them to verify DNS results. It's separate
  180. * from the locator's signature so that a single DNS record can point to more
  181. * than one locator or be served by things like geo-aware DNS.
  182. *
  183. * Right now only NIST P-384 is supported for signing DNS records. NIST EDDSA
  184. * is used here so that FIPS-only nodes can always use DNS to locate roots as
  185. * FIPS-only nodes may be required to disable non-FIPS algorithms.
  186. */
  187. inline std::vector<Str> makeTxtRecords(const uint8_t p384SigningKeyPublic[ZT_ECC384_PUBLIC_KEY_SIZE],const uint8_t p384SigningKeyPrivate[ZT_ECC384_PUBLIC_KEY_SIZE])
  188. {
  189. uint8_t s384[48];
  190. char enc[256];
  191. ScopedPtr< Buffer<65536> > tmp(new Buffer<65536>());
  192. serialize(*tmp,false);
  193. SHA384(s384,tmp->data(),tmp->size());
  194. ECC384ECDSASign(p384SigningKeyPrivate,s384,((uint8_t *)tmp->unsafeData()) + tmp->size());
  195. tmp->addSize(ZT_ECC384_SIGNATURE_SIZE);
  196. // Blob must be broken into multiple TXT records that must remain sortable so they are prefixed by a hex value.
  197. // 186-byte chunks yield 248-byte base64 chunks which leaves some margin below the limit of 255.
  198. std::vector<Str> txtRecords;
  199. unsigned int txtRecNo = 0;
  200. for(unsigned int p=0;p<tmp->size();) {
  201. unsigned int chunkSize = tmp->size() - p;
  202. if (chunkSize > 186) chunkSize = 186;
  203. Utils::b64e(((const uint8_t *)tmp->data()) + p,chunkSize,enc,sizeof(enc));
  204. p += chunkSize;
  205. txtRecords.push_back(Str());
  206. txtRecords.back() << Utils::HEXCHARS[(txtRecNo >> 4) & 0xf] << Utils::HEXCHARS[txtRecNo & 0xf] << enc;
  207. ++txtRecNo;
  208. }
  209. return txtRecords;
  210. }
  211. /**
  212. * Decode TXT records
  213. *
  214. * TXT records can be provided as an iterator over std::string, Str, or char *
  215. * values, and TXT records can be provided in any order. Any oversize or empty
  216. * entries will be ignored.
  217. *
  218. * This method checks the decoded locator's signature using the supplied DNS TXT
  219. * record signing public key. False is returned if the TXT records are invalid,
  220. * incomplete, or fail signature check. If true is returned this Locator object
  221. * now contains the contents of the supplied TXT records.
  222. *
  223. * @return True if new Locator is valid
  224. */
  225. template<typename I>
  226. inline bool decodeTxtRecords(const Str &dnsName,I start,I end)
  227. {
  228. uint8_t dec[256],s384[48];
  229. try {
  230. std::vector<Str> txtRecords;
  231. while (start != end) {
  232. try {
  233. if (start->length() > 2)
  234. txtRecords.push_back(*start);
  235. } catch ( ... ) {} // skip any records that trigger out of bounds exceptions
  236. ++start;
  237. }
  238. if (txtRecords.empty())
  239. return false;
  240. std::sort(txtRecords.begin(),txtRecords.end());
  241. ScopedPtr< Buffer<65536> > tmp(new Buffer<65536>());
  242. for(std::vector<Str>::const_iterator i(txtRecords.begin());i!=txtRecords.end();++i)
  243. tmp->append(dec,Utils::b64d(i->c_str() + 2,dec,sizeof(dec)));
  244. uint8_t p384SigningKeyPublic[ZT_ECC384_PUBLIC_KEY_SIZE];
  245. if (decodeSecureDnsName(dnsName.c_str(),p384SigningKeyPublic)) {
  246. if (tmp->size() <= ZT_ECC384_SIGNATURE_SIZE)
  247. return false;
  248. SHA384(s384,tmp->data(),tmp->size() - ZT_ECC384_SIGNATURE_SIZE);
  249. if (!ECC384ECDSAVerify(p384SigningKeyPublic,s384,((const uint8_t *)tmp->data()) + (tmp->size() - ZT_ECC384_SIGNATURE_SIZE)))
  250. return false;
  251. }
  252. deserialize(*tmp,0);
  253. return verify();
  254. } catch ( ... ) {
  255. return false;
  256. }
  257. }
  258. template<unsigned int C>
  259. inline void serialize(Buffer<C> &b,const bool forSign = false) const
  260. {
  261. if (forSign) b.append((uint64_t)0x7f7f7f7f7f7f7f7fULL);
  262. b.append((uint8_t)0); // version/flags, currently 0
  263. b.append((uint64_t)_ts);
  264. _id.serialize(b,false);
  265. if (_signedBy) {
  266. b.append((uint8_t)1); // number of signers, current max is 1
  267. _signedBy.serialize(b,false); // be sure not to include private key!
  268. } else {
  269. b.append((uint8_t)0); // signer is _id
  270. }
  271. b.append((uint8_t)_physical.size());
  272. for(std::vector<InetAddress>::const_iterator i(_physical.begin());i!=_physical.end();++i)
  273. i->serialize(b);
  274. b.append((uint8_t)_virtual.size());
  275. for(std::vector<Identity>::const_iterator i(_virtual.begin());i!=_virtual.end();++i)
  276. i->serialize(b,false);
  277. if (!forSign) {
  278. b.append((uint16_t)_signatureLength);
  279. b.append(_signature,_signatureLength);
  280. }
  281. b.append((uint16_t)0); // length of additional fields, currently 0
  282. if (forSign) b.append((uint64_t)0x7f7f7f7f7f7f7f7fULL);
  283. }
  284. template<unsigned int C>
  285. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  286. {
  287. unsigned int p = startAt;
  288. if (b[p++] != 0)
  289. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  290. _ts = (int64_t)b.template at<uint64_t>(p); p += 8;
  291. p += _id.deserialize(b,p);
  292. const unsigned int signerCount = b[p++];
  293. if (signerCount > 1) /* only one third party signer is currently supported */
  294. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
  295. if (signerCount == 1) {
  296. p += _signedBy.deserialize(b,p);
  297. } else {
  298. _signedBy.zero();
  299. }
  300. const unsigned int physicalCount = b[p++];
  301. _physical.resize(physicalCount);
  302. for(unsigned int i=0;i<physicalCount;++i)
  303. p += _physical[i].deserialize(b,p);
  304. const unsigned int virtualCount = b[p++];
  305. _virtual.resize(virtualCount);
  306. for(unsigned int i=0;i<virtualCount;++i)
  307. p += _virtual[i].deserialize(b,p);
  308. _signatureLength = b.template at<uint16_t>(p); p += 2;
  309. if (_signatureLength > ZT_SIGNATURE_BUFFER_SIZE)
  310. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
  311. memcpy(_signature,b.field(p,_signatureLength),_signatureLength);
  312. p += _signatureLength;
  313. p += b.template at<uint16_t>(p); p += 2;
  314. if (p > b.size())
  315. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
  316. return (p - startAt);
  317. }
  318. ZT_ALWAYS_INLINE operator bool() const { return (_id); }
  319. ZT_ALWAYS_INLINE bool addressesEqual(const Locator &l) const { return ((_physical == l._physical)&&(_virtual == l._virtual)); }
  320. ZT_ALWAYS_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)); }
  321. ZT_ALWAYS_INLINE bool operator!=(const Locator &l) const { return (!(*this == l)); }
  322. ZT_ALWAYS_INLINE bool operator<(const Locator &l) const
  323. {
  324. if (_id < l._id) return true;
  325. if (_ts < l._ts) return true;
  326. if (_signedBy < l._signedBy) return true;
  327. if (_physical < l._physical) return true;
  328. if (_virtual < l._virtual) return true;
  329. return false;
  330. }
  331. ZT_ALWAYS_INLINE bool operator>(const Locator &l) const { return (l < *this); }
  332. ZT_ALWAYS_INLINE bool operator<=(const Locator &l) const { return (!(l < *this)); }
  333. ZT_ALWAYS_INLINE bool operator>=(const Locator &l) const { return (!(*this < l)); }
  334. ZT_ALWAYS_INLINE unsigned long hashCode() const { return (unsigned long)(_id.address().toInt() ^ (uint64_t)_ts); }
  335. private:
  336. int64_t _ts;
  337. Identity _id;
  338. Identity _signedBy; // signed by _id if nil/zero
  339. std::vector<InetAddress> _physical;
  340. std::vector<Identity> _virtual;
  341. unsigned int _signatureLength;
  342. uint8_t _signature[ZT_SIGNATURE_BUFFER_SIZE];
  343. };
  344. } // namespace ZeroTier
  345. #endif