CertificateOfMembership.hpp 12 KB

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