CertificateOfMembership.hpp 14 KB

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