CertificateOfMembership.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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_CERTIFICATEOFMEMBERSHIP_HPP
  14. #define ZT_CERTIFICATEOFMEMBERSHIP_HPP
  15. #include <stdint.h>
  16. #include <string.h>
  17. #include <string>
  18. #include <stdexcept>
  19. #include <algorithm>
  20. #include "Constants.hpp"
  21. #include "Credential.hpp"
  22. #include "Buffer.hpp"
  23. #include "Address.hpp"
  24. #include "C25519.hpp"
  25. #include "Identity.hpp"
  26. #include "Utils.hpp"
  27. /**
  28. * Maximum number of qualifiers allowed in a COM (absolute max: 65535)
  29. */
  30. #define ZT_NETWORK_COM_MAX_QUALIFIERS 8
  31. namespace ZeroTier {
  32. class RuntimeEnvironment;
  33. /**
  34. * Certificate of network membership
  35. *
  36. * The COM contains a sorted set of three-element tuples called qualifiers.
  37. * These contain an id, a value, and a maximum delta.
  38. *
  39. * The ID is arbitrary and should be assigned using a scheme that makes
  40. * every ID globally unique. IDs beneath 65536 are reserved for global
  41. * assignment by ZeroTier Networks.
  42. *
  43. * The value's meaning is ID-specific and isn't important here. What's
  44. * important is the value and the third member of the tuple: the maximum
  45. * delta. The maximum delta is the maximum difference permitted between
  46. * values for a given ID between certificates for the two certificates to
  47. * themselves agree.
  48. *
  49. * Network membership is checked by checking whether a peer's certificate
  50. * agrees with your own. The timestamp provides the fundamental criterion--
  51. * each member of a private network must constantly obtain new certificates
  52. * often enough to stay within the max delta for this qualifier. But other
  53. * criteria could be added in the future for very special behaviors, things
  54. * like latitude and longitude for instance.
  55. *
  56. * This is a memcpy()'able structure and is safe (in a crash sense) to modify
  57. * without locks.
  58. */
  59. class CertificateOfMembership : public Credential
  60. {
  61. friend class Credential;
  62. public:
  63. static inline Credential::Type credentialType() { return Credential::CREDENTIAL_TYPE_COM; }
  64. /**
  65. * Reserved qualifier IDs
  66. *
  67. * IDs below 1024 are reserved for use as standard IDs. Others are available
  68. * for user-defined use.
  69. *
  70. * Addition of new required fields requires that code in hasRequiredFields
  71. * be updated as well.
  72. */
  73. enum ReservedId
  74. {
  75. /**
  76. * Timestamp of certificate
  77. */
  78. COM_RESERVED_ID_TIMESTAMP = 0,
  79. /**
  80. * Network ID for which certificate was issued
  81. */
  82. COM_RESERVED_ID_NETWORK_ID = 1,
  83. /**
  84. * ZeroTier address to whom certificate was issued
  85. */
  86. COM_RESERVED_ID_ISSUED_TO = 2
  87. };
  88. /**
  89. * Create an empty certificate of membership
  90. */
  91. inline CertificateOfMembership() :
  92. _qualifierCount(0),
  93. _signatureLength(0) {}
  94. /**
  95. * Create from required fields common to all networks
  96. *
  97. * @param timestamp Timestamp of certificate
  98. * @param timestampMaxDelta Maximum variation between timestamps on this net
  99. * @param nwid Network ID
  100. * @param issuedTo Certificate recipient
  101. */
  102. inline CertificateOfMembership(uint64_t timestamp,uint64_t timestampMaxDelta,uint64_t nwid,const Address &issuedTo)
  103. {
  104. _qualifiers[0].id = COM_RESERVED_ID_TIMESTAMP;
  105. _qualifiers[0].value = timestamp;
  106. _qualifiers[0].maxDelta = timestampMaxDelta;
  107. _qualifiers[1].id = COM_RESERVED_ID_NETWORK_ID;
  108. _qualifiers[1].value = nwid;
  109. _qualifiers[1].maxDelta = 0;
  110. _qualifiers[2].id = COM_RESERVED_ID_ISSUED_TO;
  111. _qualifiers[2].value = issuedTo.toInt();
  112. _qualifiers[2].maxDelta = 0xffffffffffffffffULL;
  113. _qualifierCount = 3;
  114. _signatureLength = 0;
  115. }
  116. /**
  117. * Create from binary-serialized COM in buffer
  118. *
  119. * @param b Buffer to deserialize from
  120. * @param startAt Position to start in buffer
  121. */
  122. template<unsigned int C>
  123. inline CertificateOfMembership(const Buffer<C> &b,unsigned int startAt = 0)
  124. {
  125. deserialize(b,startAt);
  126. }
  127. /**
  128. * @return True if there's something here
  129. */
  130. ZT_ALWAYS_INLINE operator bool() const { return (_qualifierCount != 0); }
  131. /**
  132. * @return Credential ID, always 0 for COMs
  133. */
  134. ZT_ALWAYS_INLINE uint32_t id() const { return 0; }
  135. /**
  136. * @return Timestamp for this cert and maximum delta for timestamp
  137. */
  138. ZT_ALWAYS_INLINE int64_t timestamp() const
  139. {
  140. for(unsigned int i=0;i<_qualifierCount;++i) {
  141. if (_qualifiers[i].id == COM_RESERVED_ID_TIMESTAMP)
  142. return (int64_t)_qualifiers[i].value;
  143. }
  144. return 0;
  145. }
  146. /**
  147. * @return Address to which this cert was issued
  148. */
  149. ZT_ALWAYS_INLINE Address issuedTo() const
  150. {
  151. for(unsigned int i=0;i<_qualifierCount;++i) {
  152. if (_qualifiers[i].id == COM_RESERVED_ID_ISSUED_TO)
  153. return Address(_qualifiers[i].value);
  154. }
  155. return Address();
  156. }
  157. /**
  158. * @return Network ID for which this cert was issued
  159. */
  160. ZT_ALWAYS_INLINE uint64_t networkId() const
  161. {
  162. for(unsigned int i=0;i<_qualifierCount;++i) {
  163. if (_qualifiers[i].id == COM_RESERVED_ID_NETWORK_ID)
  164. return _qualifiers[i].value;
  165. }
  166. return 0ULL;
  167. }
  168. /**
  169. * Add or update a qualifier in this certificate
  170. *
  171. * Any signature is invalidated and signedBy is set to null.
  172. *
  173. * @param id Qualifier ID
  174. * @param value Qualifier value
  175. * @param maxDelta Qualifier maximum allowed difference (absolute value of difference)
  176. */
  177. inline void setQualifier(uint64_t id,uint64_t value,uint64_t maxDelta)
  178. {
  179. _signedBy.zero();
  180. for(unsigned int i=0;i<_qualifierCount;++i) {
  181. if (_qualifiers[i].id == id) {
  182. _qualifiers[i].value = value;
  183. _qualifiers[i].maxDelta = maxDelta;
  184. return;
  185. }
  186. }
  187. if (_qualifierCount < ZT_NETWORK_COM_MAX_QUALIFIERS) {
  188. _qualifiers[_qualifierCount].id = id;
  189. _qualifiers[_qualifierCount].value = value;
  190. _qualifiers[_qualifierCount].maxDelta = maxDelta;
  191. ++_qualifierCount;
  192. std::sort(&(_qualifiers[0]),&(_qualifiers[_qualifierCount]));
  193. }
  194. }
  195. inline void setQualifier(ReservedId id,uint64_t value,uint64_t maxDelta) { setQualifier((uint64_t)id,value,maxDelta); }
  196. /**
  197. * Compare two certificates for parameter agreement
  198. *
  199. * This compares this certificate with the other and returns true if all
  200. * parameters in this cert are present in the other and if they agree to
  201. * within this cert's max delta value for each given parameter.
  202. *
  203. * Tuples present in other but not in this cert are ignored, but any
  204. * tuples present in this cert but not in other result in 'false'.
  205. *
  206. * @param other Cert to compare with
  207. * @return True if certs agree and 'other' may be communicated with
  208. */
  209. inline bool agreesWith(const CertificateOfMembership &other) const
  210. {
  211. unsigned int myidx = 0;
  212. unsigned int otheridx = 0;
  213. if ((_qualifierCount == 0)||(other._qualifierCount == 0))
  214. return false;
  215. while (myidx < _qualifierCount) {
  216. // Fail if we're at the end of other, since this means the field is
  217. // missing.
  218. if (otheridx >= other._qualifierCount)
  219. return false;
  220. // Seek to corresponding tuple in other, ignoring tuples that
  221. // we may not have. If we run off the end of other, the tuple is
  222. // missing. This works because tuples are sorted by ID.
  223. while (other._qualifiers[otheridx].id != _qualifiers[myidx].id) {
  224. ++otheridx;
  225. if (otheridx >= other._qualifierCount)
  226. return false;
  227. }
  228. // Compare to determine if the absolute value of the difference
  229. // between these two parameters is within our maxDelta.
  230. const uint64_t a = _qualifiers[myidx].value;
  231. const uint64_t b = other._qualifiers[myidx].value;
  232. if (((a >= b) ? (a - b) : (b - a)) > _qualifiers[myidx].maxDelta)
  233. return false;
  234. ++myidx;
  235. }
  236. return true;
  237. }
  238. /**
  239. * Sign this certificate
  240. *
  241. * @param with Identity to sign with, must include private key
  242. * @return True if signature was successful
  243. */
  244. inline bool sign(const Identity &with)
  245. {
  246. uint64_t buf[ZT_NETWORK_COM_MAX_QUALIFIERS * 3];
  247. unsigned int ptr = 0;
  248. for(unsigned int i=0;i<_qualifierCount;++i) {
  249. buf[ptr++] = Utils::hton(_qualifiers[i].id);
  250. buf[ptr++] = Utils::hton(_qualifiers[i].value);
  251. buf[ptr++] = Utils::hton(_qualifiers[i].maxDelta);
  252. }
  253. try {
  254. _signatureLength = with.sign(buf,ptr * sizeof(uint64_t),_signature,sizeof(_signature));
  255. _signedBy = with.address();
  256. return true;
  257. } catch ( ... ) {
  258. _signedBy.zero();
  259. return false;
  260. }
  261. }
  262. /**
  263. * Verify this COM and its signature
  264. *
  265. * @param RR Runtime environment for looking up peers
  266. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  267. */
  268. inline Credential::VerifyResult verify(const RuntimeEnvironment *RR,void *tPtr) const { return _verify(RR,tPtr,*this); }
  269. /**
  270. * @return True if signed
  271. */
  272. inline bool isSigned() const { return (_signedBy); }
  273. /**
  274. * @return Address that signed this certificate or null address if none
  275. */
  276. inline const Address &signedBy() const { return _signedBy; }
  277. template<unsigned int C>
  278. inline void serialize(Buffer<C> &b) const
  279. {
  280. b.append((uint8_t)1);
  281. b.append((uint16_t)_qualifierCount);
  282. for(unsigned int i=0;i<_qualifierCount;++i) {
  283. b.append(_qualifiers[i].id);
  284. b.append(_qualifiers[i].value);
  285. b.append(_qualifiers[i].maxDelta);
  286. }
  287. _signedBy.appendTo(b);
  288. if ((_signedBy)&&(_signatureLength == 96)) {
  289. // UGLY: Ed25519 signatures in ZT are 96 bytes (64 + 32 bytes of hash).
  290. // P-384 signatures are also 96 bytes, praise the horned one. That means
  291. // we don't need to include a length. If we ever do we will need a new
  292. // serialized object version, but only for those with length != 96.
  293. b.append(_signature,96);
  294. }
  295. }
  296. template<unsigned int C>
  297. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  298. {
  299. unsigned int p = startAt;
  300. _signedBy.zero();
  301. _qualifierCount = 0;
  302. _signatureLength = 0;
  303. if (b[p++] != 1)
  304. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  305. unsigned int numq = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  306. uint64_t lastId = 0;
  307. for(unsigned int i=0;i<numq;++i) {
  308. const uint64_t qid = b.template at<uint64_t>(p);
  309. if (qid < lastId)
  310. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_BAD_ENCODING;
  311. else lastId = qid;
  312. if (_qualifierCount < ZT_NETWORK_COM_MAX_QUALIFIERS) {
  313. _qualifiers[_qualifierCount].id = qid;
  314. _qualifiers[_qualifierCount].value = b.template at<uint64_t>(p + 8);
  315. _qualifiers[_qualifierCount].maxDelta = b.template at<uint64_t>(p + 16);
  316. p += 24;
  317. ++_qualifierCount;
  318. } else {
  319. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_OVERFLOW;
  320. }
  321. }
  322. _signedBy.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  323. p += ZT_ADDRESS_LENGTH;
  324. if (_signedBy) {
  325. // See "UGLY" comment in serialize()...
  326. _signatureLength = 96;
  327. memcpy(_signature,b.field(p,96),96);
  328. p += 96;
  329. }
  330. return (p - startAt);
  331. }
  332. ZT_ALWAYS_INLINE bool operator==(const CertificateOfMembership &c) const
  333. {
  334. if (_signedBy != c._signedBy)
  335. return false;
  336. if (_qualifierCount != c._qualifierCount)
  337. return false;
  338. if (_signatureLength != c._signatureLength)
  339. return false;
  340. for(unsigned int i=0;i<_qualifierCount;++i) {
  341. const _Qualifier &a = _qualifiers[i];
  342. const _Qualifier &b = c._qualifiers[i];
  343. if ((a.id != b.id)||(a.value != b.value)||(a.maxDelta != b.maxDelta))
  344. return false;
  345. }
  346. return (memcmp(_signature,c._signature,_signatureLength) == 0);
  347. }
  348. ZT_ALWAYS_INLINE bool operator!=(const CertificateOfMembership &c) const { return (!(*this == c)); }
  349. private:
  350. struct _Qualifier
  351. {
  352. _Qualifier() : id(0),value(0),maxDelta(0) {}
  353. uint64_t id;
  354. uint64_t value;
  355. uint64_t maxDelta;
  356. inline bool operator<(const _Qualifier &q) const { return (id < q.id); } // sort order
  357. };
  358. Address _signedBy;
  359. _Qualifier _qualifiers[ZT_NETWORK_COM_MAX_QUALIFIERS];
  360. unsigned int _qualifierCount;
  361. unsigned int _signatureLength;
  362. uint8_t _signature[ZT_SIGNATURE_BUFFER_SIZE];
  363. };
  364. } // namespace ZeroTier
  365. #endif