CertificateOfMembership.hpp 12 KB

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