CertificateOfMembership.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #ifndef ZT_CERTIFICATEOFMEMBERSHIP_HPP
  19. #define ZT_CERTIFICATEOFMEMBERSHIP_HPP
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include <string>
  23. #include <stdexcept>
  24. #include <algorithm>
  25. #include "Constants.hpp"
  26. #include "Buffer.hpp"
  27. #include "Address.hpp"
  28. #include "C25519.hpp"
  29. #include "Identity.hpp"
  30. #include "Utils.hpp"
  31. /**
  32. * Default window of time for certificate agreement
  33. *
  34. * Right now we use time for 'revision' so this is the maximum time divergence
  35. * between two certs for them to agree. It comes out to five minutes, which
  36. * gives a lot of margin for error if the controller hiccups or its clock
  37. * drifts but causes de-authorized peers to fall off fast enough.
  38. */
  39. #define ZT_NETWORK_COM_DEFAULT_REVISION_MAX_DELTA (ZT_NETWORK_AUTOCONF_DELAY * 5)
  40. /**
  41. * Maximum number of qualifiers in a COM
  42. */
  43. #define ZT_NETWORK_COM_MAX_QUALIFIERS 16
  44. namespace ZeroTier {
  45. /**
  46. * Certificate of network membership
  47. *
  48. * The COM contains a sorted set of three-element tuples called qualifiers.
  49. * These contain an id, a value, and a maximum delta.
  50. *
  51. * The ID is arbitrary and should be assigned using a scheme that makes
  52. * every ID globally unique. IDs beneath 65536 are reserved for global
  53. * assignment by ZeroTier Networks.
  54. *
  55. * The value's meaning is ID-specific and isn't important here. What's
  56. * important is the value and the third member of the tuple: the maximum
  57. * delta. The maximum delta is the maximum difference permitted between
  58. * values for a given ID between certificates for the two certificates to
  59. * themselves agree.
  60. *
  61. * Network membership is checked by checking whether a peer's certificate
  62. * agrees with your own. The timestamp provides the fundamental criterion--
  63. * each member of a private network must constantly obtain new certificates
  64. * often enough to stay within the max delta for this qualifier. But other
  65. * criteria could be added in the future for very special behaviors, things
  66. * like latitude and longitude for instance.
  67. *
  68. * This is a memcpy()'able structure and is safe (in a crash sense) to modify
  69. * without locks.
  70. */
  71. class CertificateOfMembership
  72. {
  73. public:
  74. /**
  75. * Certificate type codes, used in serialization
  76. *
  77. * Only one so far, and only one hopefully there shall be for quite some
  78. * time.
  79. */
  80. enum Type
  81. {
  82. COM_UINT64_ED25519 = 1 // tuples of unsigned 64's signed with Ed25519
  83. };
  84. /**
  85. * Reserved qualifier IDs
  86. *
  87. * IDs below 65536 should be considered reserved for future global
  88. * assignment here.
  89. *
  90. * Addition of new required fields requires that code in hasRequiredFields
  91. * be updated as well.
  92. */
  93. enum ReservedId
  94. {
  95. /**
  96. * Revision number of certificate
  97. *
  98. * Certificates may differ in revision number by a designated max
  99. * delta. Differences wider than this cause certificates not to agree.
  100. */
  101. COM_RESERVED_ID_REVISION = 0,
  102. /**
  103. * Network ID for which certificate was issued
  104. *
  105. * maxDelta here is zero, since this must match.
  106. */
  107. COM_RESERVED_ID_NETWORK_ID = 1,
  108. /**
  109. * ZeroTier address to whom certificate was issued
  110. *
  111. * maxDelta will be 0xffffffffffffffff here since it's permitted to differ
  112. * from peers obviously.
  113. */
  114. COM_RESERVED_ID_ISSUED_TO = 2
  115. };
  116. /**
  117. * Create an empty certificate
  118. */
  119. CertificateOfMembership() :
  120. _qualifierCount(0)
  121. {
  122. memset(_signature.data,0,_signature.size());
  123. }
  124. CertificateOfMembership(const CertificateOfMembership &c)
  125. {
  126. memcpy(this,&c,sizeof(CertificateOfMembership));
  127. }
  128. /**
  129. * Create from required fields common to all networks
  130. *
  131. * @param revision Revision number of certificate
  132. * @param timestampMaxDelta Maximum variation between timestamps on this net
  133. * @param nwid Network ID
  134. * @param issuedTo Certificate recipient
  135. */
  136. CertificateOfMembership(uint64_t revision,uint64_t revisionMaxDelta,uint64_t nwid,const Address &issuedTo)
  137. {
  138. _qualifiers[0].id = COM_RESERVED_ID_REVISION;
  139. _qualifiers[0].value = revision;
  140. _qualifiers[0].maxDelta = revisionMaxDelta;
  141. _qualifiers[1].id = COM_RESERVED_ID_NETWORK_ID;
  142. _qualifiers[1].value = nwid;
  143. _qualifiers[1].maxDelta = 0;
  144. _qualifiers[2].id = COM_RESERVED_ID_ISSUED_TO;
  145. _qualifiers[2].value = issuedTo.toInt();
  146. _qualifiers[2].maxDelta = 0xffffffffffffffffULL;
  147. _qualifierCount = 3;
  148. memset(_signature.data,0,_signature.size());
  149. }
  150. inline CertificateOfMembership &operator=(const CertificateOfMembership &c)
  151. {
  152. memcpy(this,&c,sizeof(CertificateOfMembership));
  153. return *this;
  154. }
  155. #ifdef ZT_SUPPORT_OLD_STYLE_NETCONF
  156. /**
  157. * Create from string-serialized data
  158. *
  159. * @param s String-serialized COM
  160. */
  161. CertificateOfMembership(const char *s) { fromString(s); }
  162. /**
  163. * Create from string-serialized data
  164. *
  165. * @param s String-serialized COM
  166. */
  167. CertificateOfMembership(const std::string &s) { fromString(s.c_str()); }
  168. #endif // ZT_SUPPORT_OLD_STYLE_NETCONF
  169. /**
  170. * Create from binary-serialized COM in buffer
  171. *
  172. * @param b Buffer to deserialize from
  173. * @param startAt Position to start in buffer
  174. */
  175. template<unsigned int C>
  176. CertificateOfMembership(const Buffer<C> &b,unsigned int startAt = 0)
  177. {
  178. deserialize(b,startAt);
  179. }
  180. /**
  181. * @return True if there's something here
  182. */
  183. inline operator bool() const throw() { return (_qualifierCount != 0); }
  184. /**
  185. * Check for presence of all required fields common to all networks
  186. *
  187. * @return True if all required fields are present
  188. */
  189. inline bool hasRequiredFields() const
  190. {
  191. if (_qualifierCount < 3)
  192. return false;
  193. if (_qualifiers[0].id != COM_RESERVED_ID_REVISION)
  194. return false;
  195. if (_qualifiers[1].id != COM_RESERVED_ID_NETWORK_ID)
  196. return false;
  197. if (_qualifiers[2].id != COM_RESERVED_ID_ISSUED_TO)
  198. return false;
  199. return true;
  200. }
  201. /**
  202. * @return Maximum delta for mandatory revision field or 0 if field missing
  203. */
  204. inline uint64_t revisionMaxDelta() const
  205. {
  206. for(unsigned int i=0;i<_qualifierCount;++i) {
  207. if (_qualifiers[i].id == COM_RESERVED_ID_REVISION)
  208. return _qualifiers[i].maxDelta;
  209. }
  210. return 0ULL;
  211. }
  212. /**
  213. * @return Revision number for this cert
  214. */
  215. inline uint64_t revision() const
  216. {
  217. for(unsigned int i=0;i<_qualifierCount;++i) {
  218. if (_qualifiers[i].id == COM_RESERVED_ID_REVISION)
  219. return _qualifiers[i].value;
  220. }
  221. return 0ULL;
  222. }
  223. /**
  224. * @return Address to which this cert was issued
  225. */
  226. inline Address issuedTo() const
  227. {
  228. for(unsigned int i=0;i<_qualifierCount;++i) {
  229. if (_qualifiers[i].id == COM_RESERVED_ID_ISSUED_TO)
  230. return Address(_qualifiers[i].value);
  231. }
  232. return Address();
  233. }
  234. /**
  235. * @return Network ID for which this cert was issued
  236. */
  237. inline uint64_t networkId() const
  238. {
  239. for(unsigned int i=0;i<_qualifierCount;++i) {
  240. if (_qualifiers[i].id == COM_RESERVED_ID_NETWORK_ID)
  241. return _qualifiers[i].value;
  242. }
  243. return 0ULL;
  244. }
  245. /**
  246. * Add or update a qualifier in this certificate
  247. *
  248. * Any signature is invalidated and signedBy is set to null.
  249. *
  250. * @param id Qualifier ID
  251. * @param value Qualifier value
  252. * @param maxDelta Qualifier maximum allowed difference (absolute value of difference)
  253. */
  254. void setQualifier(uint64_t id,uint64_t value,uint64_t maxDelta);
  255. inline void setQualifier(ReservedId id,uint64_t value,uint64_t maxDelta) { setQualifier((uint64_t)id,value,maxDelta); }
  256. #ifdef ZT_SUPPORT_OLD_STYLE_NETCONF
  257. /**
  258. * @return String-serialized representation of this certificate
  259. */
  260. std::string toString() const;
  261. /**
  262. * Set this certificate equal to the hex-serialized string
  263. *
  264. * Invalid strings will result in invalid or undefined certificate
  265. * contents. These will subsequently fail validation and comparison.
  266. * Empty strings will result in an empty certificate.
  267. *
  268. * @param s String to deserialize
  269. */
  270. void fromString(const char *s);
  271. #endif // ZT_SUPPORT_OLD_STYLE_NETCONF
  272. /**
  273. * Compare two certificates for parameter agreement
  274. *
  275. * This compares this certificate with the other and returns true if all
  276. * paramters in this cert are present in the other and if they agree to
  277. * within this cert's max delta value for each given parameter.
  278. *
  279. * Tuples present in other but not in this cert are ignored, but any
  280. * tuples present in this cert but not in other result in 'false'.
  281. *
  282. * @param other Cert to compare with
  283. * @return True if certs agree and 'other' may be communicated with
  284. */
  285. bool agreesWith(const CertificateOfMembership &other) const;
  286. /**
  287. * Sign this certificate
  288. *
  289. * @param with Identity to sign with, must include private key
  290. * @return True if signature was successful
  291. */
  292. bool sign(const Identity &with);
  293. /**
  294. * Verify certificate against an identity
  295. *
  296. * @param id Identity to verify against
  297. * @return True if certificate is signed by this identity and verification was successful
  298. */
  299. bool verify(const Identity &id) const;
  300. /**
  301. * @return True if signed
  302. */
  303. inline bool isSigned() const throw() { return (_signedBy); }
  304. /**
  305. * @return Address that signed this certificate or null address if none
  306. */
  307. inline const Address &signedBy() const throw() { return _signedBy; }
  308. template<unsigned int C>
  309. inline void serialize(Buffer<C> &b) const
  310. {
  311. b.append((unsigned char)COM_UINT64_ED25519);
  312. b.append((uint16_t)_qualifierCount);
  313. for(unsigned int i=0;i<_qualifierCount;++i) {
  314. b.append(_qualifiers[i].id);
  315. b.append(_qualifiers[i].value);
  316. b.append(_qualifiers[i].maxDelta);
  317. }
  318. _signedBy.appendTo(b);
  319. if (_signedBy)
  320. b.append(_signature.data,(unsigned int)_signature.size());
  321. }
  322. template<unsigned int C>
  323. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  324. {
  325. unsigned int p = startAt;
  326. _qualifierCount = 0;
  327. _signedBy.zero();
  328. if (b[p++] != COM_UINT64_ED25519)
  329. throw std::invalid_argument("invalid type");
  330. unsigned int numq = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  331. uint64_t lastId = 0;
  332. for(unsigned int i=0;i<numq;++i) {
  333. const uint64_t qid = b.template at<uint64_t>(p);
  334. if (qid < lastId)
  335. throw std::invalid_argument("qualifiers not sorted");
  336. else lastId = qid;
  337. if (_qualifierCount < ZT_NETWORK_COM_MAX_QUALIFIERS) {
  338. _qualifiers[_qualifierCount].id = qid;
  339. _qualifiers[_qualifierCount].value = b.template at<uint64_t>(p + 8);
  340. _qualifiers[_qualifierCount].maxDelta = b.template at<uint64_t>(p + 16);
  341. p += 24;
  342. ++_qualifierCount;
  343. } else {
  344. throw std::invalid_argument("too many qualifiers");
  345. }
  346. }
  347. _signedBy.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  348. p += ZT_ADDRESS_LENGTH;
  349. if (_signedBy) {
  350. memcpy(_signature.data,b.field(p,(unsigned int)_signature.size()),_signature.size());
  351. p += (unsigned int)_signature.size();
  352. }
  353. return (p - startAt);
  354. }
  355. inline bool operator==(const CertificateOfMembership &c) const
  356. throw()
  357. {
  358. if (_signedBy != c._signedBy)
  359. return false;
  360. if (_qualifierCount != c._qualifierCount)
  361. return false;
  362. for(unsigned int i=0;i<_qualifierCount;++i) {
  363. const _Qualifier &a = _qualifiers[i];
  364. const _Qualifier &b = c._qualifiers[i];
  365. if ((a.id != b.id)||(a.value != b.value)||(a.maxDelta != b.maxDelta))
  366. return false;
  367. }
  368. return (_signature == c._signature);
  369. }
  370. inline bool operator!=(const CertificateOfMembership &c) const throw() { return (!(*this == c)); }
  371. private:
  372. struct _Qualifier
  373. {
  374. _Qualifier() : id(0),value(0),maxDelta(0) {}
  375. uint64_t id;
  376. uint64_t value;
  377. uint64_t maxDelta;
  378. inline bool operator<(const _Qualifier &q) const throw() { return (id < q.id); } // sort order
  379. };
  380. Address _signedBy;
  381. _Qualifier _qualifiers[ZT_NETWORK_COM_MAX_QUALIFIERS];
  382. unsigned int _qualifierCount;
  383. C25519::Signature _signature;
  384. };
  385. } // namespace ZeroTier
  386. #endif