CertificateOfMembership.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. * Maximum number of qualifiers allowed in a COM (absolute max: 65535)
  33. */
  34. #define ZT_NETWORK_COM_MAX_QUALIFIERS 8
  35. namespace ZeroTier {
  36. class RuntimeEnvironment;
  37. /**
  38. * Certificate of network membership
  39. *
  40. * The COM contains a sorted set of three-element tuples called qualifiers.
  41. * These contain an id, a value, and a maximum delta.
  42. *
  43. * The ID is arbitrary and should be assigned using a scheme that makes
  44. * every ID globally unique. IDs beneath 65536 are reserved for global
  45. * assignment by ZeroTier Networks.
  46. *
  47. * The value's meaning is ID-specific and isn't important here. What's
  48. * important is the value and the third member of the tuple: the maximum
  49. * delta. The maximum delta is the maximum difference permitted between
  50. * values for a given ID between certificates for the two certificates to
  51. * themselves agree.
  52. *
  53. * Network membership is checked by checking whether a peer's certificate
  54. * agrees with your own. The timestamp provides the fundamental criterion--
  55. * each member of a private network must constantly obtain new certificates
  56. * often enough to stay within the max delta for this qualifier. But other
  57. * criteria could be added in the future for very special behaviors, things
  58. * like latitude and longitude for instance.
  59. *
  60. * This is a memcpy()'able structure and is safe (in a crash sense) to modify
  61. * without locks.
  62. */
  63. class CertificateOfMembership
  64. {
  65. public:
  66. /**
  67. * Reserved qualifier IDs
  68. *
  69. * IDs below 1024 are reserved for use as standard IDs. Others are available
  70. * for user-defined use.
  71. *
  72. * Addition of new required fields requires that code in hasRequiredFields
  73. * be updated as well.
  74. */
  75. enum ReservedId
  76. {
  77. /**
  78. * Timestamp of certificate
  79. */
  80. COM_RESERVED_ID_TIMESTAMP = 0,
  81. /**
  82. * Network ID for which certificate was issued
  83. */
  84. COM_RESERVED_ID_NETWORK_ID = 1,
  85. /**
  86. * ZeroTier address to whom certificate was issued
  87. */
  88. COM_RESERVED_ID_ISSUED_TO = 2
  89. };
  90. /**
  91. * Create an empty certificate of membership
  92. */
  93. CertificateOfMembership()
  94. {
  95. memset(this,0,sizeof(CertificateOfMembership));
  96. }
  97. CertificateOfMembership(const CertificateOfMembership &c)
  98. {
  99. memcpy(this,&c,sizeof(CertificateOfMembership));
  100. }
  101. /**
  102. * Create from required fields common to all networks
  103. *
  104. * @param timestamp Timestamp of certificate
  105. * @param timestampMaxDelta Maximum variation between timestamps on this net
  106. * @param nwid Network ID
  107. * @param issuedTo Certificate recipient
  108. */
  109. CertificateOfMembership(uint64_t timestamp,uint64_t timestampMaxDelta,uint64_t nwid,const Address &issuedTo)
  110. {
  111. _qualifiers[0].id = COM_RESERVED_ID_TIMESTAMP;
  112. _qualifiers[0].value = timestamp;
  113. _qualifiers[0].maxDelta = timestampMaxDelta;
  114. _qualifiers[1].id = COM_RESERVED_ID_NETWORK_ID;
  115. _qualifiers[1].value = nwid;
  116. _qualifiers[1].maxDelta = 0;
  117. _qualifiers[2].id = COM_RESERVED_ID_ISSUED_TO;
  118. _qualifiers[2].value = issuedTo.toInt();
  119. _qualifiers[2].maxDelta = 0xffffffffffffffffULL;
  120. _qualifierCount = 3;
  121. memset(_signature.data,0,_signature.size());
  122. }
  123. inline CertificateOfMembership &operator=(const CertificateOfMembership &c)
  124. {
  125. memcpy(this,&c,sizeof(CertificateOfMembership));
  126. return *this;
  127. }
  128. /**
  129. * Create from binary-serialized COM in buffer
  130. *
  131. * @param b Buffer to deserialize from
  132. * @param startAt Position to start in buffer
  133. */
  134. template<unsigned int C>
  135. CertificateOfMembership(const Buffer<C> &b,unsigned int startAt = 0)
  136. {
  137. deserialize(b,startAt);
  138. }
  139. /**
  140. * @return True if there's something here
  141. */
  142. inline operator bool() const throw() { return (_qualifierCount != 0); }
  143. /**
  144. * @return Timestamp for this cert and maximum delta for timestamp
  145. */
  146. inline std::pair<uint64_t,uint64_t> timestamp() const
  147. {
  148. for(unsigned int i=0;i<_qualifierCount;++i) {
  149. if (_qualifiers[i].id == COM_RESERVED_ID_TIMESTAMP)
  150. return std::pair<uint64_t,uint64_t>(_qualifiers[i].value,_qualifiers[i].maxDelta);
  151. }
  152. return std::pair<uint64_t,uint64_t>(0ULL,0ULL);
  153. }
  154. /**
  155. * @return Address to which this cert was issued
  156. */
  157. inline Address issuedTo() const
  158. {
  159. for(unsigned int i=0;i<_qualifierCount;++i) {
  160. if (_qualifiers[i].id == COM_RESERVED_ID_ISSUED_TO)
  161. return Address(_qualifiers[i].value);
  162. }
  163. return Address();
  164. }
  165. /**
  166. * @return Network ID for which this cert was issued
  167. */
  168. inline uint64_t networkId() const
  169. {
  170. for(unsigned int i=0;i<_qualifierCount;++i) {
  171. if (_qualifiers[i].id == COM_RESERVED_ID_NETWORK_ID)
  172. return _qualifiers[i].value;
  173. }
  174. return 0ULL;
  175. }
  176. /**
  177. * Add or update a qualifier in this certificate
  178. *
  179. * Any signature is invalidated and signedBy is set to null.
  180. *
  181. * @param id Qualifier ID
  182. * @param value Qualifier value
  183. * @param maxDelta Qualifier maximum allowed difference (absolute value of difference)
  184. */
  185. void setQualifier(uint64_t id,uint64_t value,uint64_t maxDelta);
  186. inline void setQualifier(ReservedId id,uint64_t value,uint64_t maxDelta) { setQualifier((uint64_t)id,value,maxDelta); }
  187. #ifdef ZT_SUPPORT_OLD_STYLE_NETCONF
  188. /**
  189. * @return String-serialized representation of this certificate
  190. */
  191. std::string toString() const;
  192. /**
  193. * Set this certificate equal to the hex-serialized string
  194. *
  195. * Invalid strings will result in invalid or undefined certificate
  196. * contents. These will subsequently fail validation and comparison.
  197. * Empty strings will result in an empty certificate.
  198. *
  199. * @param s String to deserialize
  200. */
  201. void fromString(const char *s);
  202. #endif // ZT_SUPPORT_OLD_STYLE_NETCONF
  203. /**
  204. * Compare two certificates for parameter agreement
  205. *
  206. * This compares this certificate with the other and returns true if all
  207. * paramters in this cert are present in the other and if they agree to
  208. * within this cert's max delta value for each given parameter.
  209. *
  210. * Tuples present in other but not in this cert are ignored, but any
  211. * tuples present in this cert but not in other result in 'false'.
  212. *
  213. * @param other Cert to compare with
  214. * @return True if certs agree and 'other' may be communicated with
  215. */
  216. bool agreesWith(const CertificateOfMembership &other) const;
  217. /**
  218. * Sign this certificate
  219. *
  220. * @param with Identity to sign with, must include private key
  221. * @return True if signature was successful
  222. */
  223. bool sign(const Identity &with);
  224. /**
  225. * Verify this COM and its signature
  226. *
  227. * @param RR Runtime environment for looking up peers
  228. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  229. */
  230. int verify(const RuntimeEnvironment *RR) const;
  231. /**
  232. * @return True if signed
  233. */
  234. inline bool isSigned() const throw() { return (_signedBy); }
  235. /**
  236. * @return Address that signed this certificate or null address if none
  237. */
  238. inline const Address &signedBy() const throw() { return _signedBy; }
  239. template<unsigned int C>
  240. inline void serialize(Buffer<C> &b) const
  241. {
  242. b.append((uint8_t)1);
  243. b.append((uint16_t)_qualifierCount);
  244. for(unsigned int i=0;i<_qualifierCount;++i) {
  245. b.append(_qualifiers[i].id);
  246. b.append(_qualifiers[i].value);
  247. b.append(_qualifiers[i].maxDelta);
  248. }
  249. _signedBy.appendTo(b);
  250. if (_signedBy)
  251. b.append(_signature.data,(unsigned int)_signature.size());
  252. }
  253. template<unsigned int C>
  254. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  255. {
  256. unsigned int p = startAt;
  257. _qualifierCount = 0;
  258. _signedBy.zero();
  259. if (b[p++] != 1)
  260. throw std::invalid_argument("invalid object");
  261. unsigned int numq = b.template at<uint16_t>(p); p += sizeof(uint16_t);
  262. uint64_t lastId = 0;
  263. for(unsigned int i=0;i<numq;++i) {
  264. const uint64_t qid = b.template at<uint64_t>(p);
  265. if (qid < lastId)
  266. throw std::invalid_argument("qualifiers not sorted");
  267. else lastId = qid;
  268. if (_qualifierCount < ZT_NETWORK_COM_MAX_QUALIFIERS) {
  269. _qualifiers[_qualifierCount].id = qid;
  270. _qualifiers[_qualifierCount].value = b.template at<uint64_t>(p + 8);
  271. _qualifiers[_qualifierCount].maxDelta = b.template at<uint64_t>(p + 16);
  272. p += 24;
  273. ++_qualifierCount;
  274. } else {
  275. throw std::invalid_argument("too many qualifiers");
  276. }
  277. }
  278. _signedBy.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  279. p += ZT_ADDRESS_LENGTH;
  280. if (_signedBy) {
  281. memcpy(_signature.data,b.field(p,(unsigned int)_signature.size()),_signature.size());
  282. p += (unsigned int)_signature.size();
  283. }
  284. return (p - startAt);
  285. }
  286. inline bool operator==(const CertificateOfMembership &c) const
  287. throw()
  288. {
  289. if (_signedBy != c._signedBy)
  290. return false;
  291. if (_qualifierCount != c._qualifierCount)
  292. return false;
  293. for(unsigned int i=0;i<_qualifierCount;++i) {
  294. const _Qualifier &a = _qualifiers[i];
  295. const _Qualifier &b = c._qualifiers[i];
  296. if ((a.id != b.id)||(a.value != b.value)||(a.maxDelta != b.maxDelta))
  297. return false;
  298. }
  299. return (_signature == c._signature);
  300. }
  301. inline bool operator!=(const CertificateOfMembership &c) const throw() { return (!(*this == c)); }
  302. private:
  303. struct _Qualifier
  304. {
  305. _Qualifier() : id(0),value(0),maxDelta(0) {}
  306. uint64_t id;
  307. uint64_t value;
  308. uint64_t maxDelta;
  309. inline bool operator<(const _Qualifier &q) const throw() { return (id < q.id); } // sort order
  310. };
  311. Address _signedBy;
  312. _Qualifier _qualifiers[ZT_NETWORK_COM_MAX_QUALIFIERS];
  313. unsigned int _qualifierCount;
  314. C25519::Signature _signature;
  315. };
  316. } // namespace ZeroTier
  317. #endif