Identity.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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_IDENTITY_HPP
  28. #define _ZT_IDENTITY_HPP
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string>
  32. #include "EllipticCurveKey.hpp"
  33. #include "EllipticCurveKeyPair.hpp"
  34. #include "Array.hpp"
  35. #include "Utils.hpp"
  36. #include "Address.hpp"
  37. #include "Buffer.hpp"
  38. /**
  39. * Maximum length for a serialized identity
  40. */
  41. #define IDENTITY_MAX_BINARY_SERIALIZED_LENGTH ((ZT_EC_MAX_BYTES * 2) + 256)
  42. namespace ZeroTier {
  43. /**
  44. * A ZeroTier identity
  45. *
  46. * An identity consists of a public key, a 40-bit ZeroTier address computed
  47. * from that key in a collision-resistant fashion, and a self-signature.
  48. *
  49. * The address derivation algorithm makes it computationally very expensive to
  50. * search for a different public key that duplicates an existing address. (See
  51. * code for deriveAddress() for this algorithm.)
  52. *
  53. * After derivation, the address must be checked against isReserved(). If the
  54. * address is reserved, generation is repeated until a valid address results.
  55. *
  56. * Serialization of an identity:
  57. *
  58. * <[5] address> - 40-bit ZeroTier network address
  59. * <[1] type> - Identity type ID (rest is type-dependent)
  60. * <[1] key length> - Length of public key
  61. * <[n] public key> - Elliptic curve public key
  62. * <[1] sig length> - Length of ECDSA self-signature
  63. * <[n] signature> - ECDSA signature of first four fields
  64. * [<[1] key length>] - [Optional] Length of private key
  65. * [<[n] private key>] - [Optional] Private key
  66. *
  67. * Local storage of an identity also requires storage of its private key.
  68. */
  69. class Identity
  70. {
  71. public:
  72. /**
  73. * Identity types
  74. */
  75. enum Type
  76. {
  77. /* Elliptic curve NIST-P-521 and ECDSA signature */
  78. IDENTITY_TYPE_NIST_P_521 = 1
  79. /* We won't need another identity type until quantum computers with
  80. * tens of thousands of qubits are a reality. */
  81. };
  82. Identity() :
  83. _keyPair((EllipticCurveKeyPair *)0)
  84. {
  85. }
  86. Identity(const Identity &id) :
  87. _keyPair((id._keyPair) ? new EllipticCurveKeyPair(*id._keyPair) : (EllipticCurveKeyPair *)0),
  88. _publicKey(id._publicKey),
  89. _address(id._address),
  90. _signature(id._signature)
  91. {
  92. }
  93. Identity(const char *str)
  94. throw(std::invalid_argument) :
  95. _keyPair((EllipticCurveKeyPair *)0)
  96. {
  97. if (!fromString(str))
  98. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  99. }
  100. Identity(const std::string &str)
  101. throw(std::invalid_argument) :
  102. _keyPair((EllipticCurveKeyPair *)0)
  103. {
  104. if (!fromString(str))
  105. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  106. }
  107. template<unsigned int C>
  108. Identity(const Buffer<C> &b,unsigned int startAt = 0)
  109. throw(std::out_of_range,std::invalid_argument) :
  110. _keyPair((EllipticCurveKeyPair *)0)
  111. {
  112. deserialize(b,startAt);
  113. }
  114. ~Identity()
  115. {
  116. delete _keyPair;
  117. }
  118. inline Identity &operator=(const Identity &id)
  119. {
  120. _keyPair = (id._keyPair) ? new EllipticCurveKeyPair(*id._keyPair) : (EllipticCurveKeyPair *)0;
  121. _publicKey = id._publicKey;
  122. _address = id._address;
  123. _signature = id._signature;
  124. return *this;
  125. }
  126. /**
  127. * Generate a new identity (address, key pair)
  128. *
  129. * This is a somewhat time consuming operation by design, as the address
  130. * is derived from the key using a purposefully expensive many-round
  131. * hash/encrypt/hash operation. This took about two seconds on a 2.4ghz
  132. * Intel Core i5 in 2013.
  133. *
  134. * In the very unlikely event that a reserved address is created, generate
  135. * will automatically run again.
  136. */
  137. void generate();
  138. /**
  139. * Performs local validation, with two levels available
  140. *
  141. * With the parameter false, this performs self-signature verification
  142. * which checks the basic integrity of the key and identity. Setting the
  143. * parameter to true performs a fairly time consuming computation to
  144. * check that the address was properly derived from the key. This is
  145. * normally not done unless a conflicting identity is received, in
  146. * which case the invalid identity is thrown out.
  147. *
  148. * @param doAddressDerivationCheck If true, do the time-consuming address check
  149. * @return True if validation check passes
  150. */
  151. bool locallyValidate(bool doAddressDerivationCheck) const;
  152. /**
  153. * @return Private key pair or NULL if not included with this identity
  154. */
  155. inline const EllipticCurveKeyPair *privateKeyPair() const throw() { return _keyPair; }
  156. /**
  157. * @return True if this identity has its private portion
  158. */
  159. inline bool hasPrivate() const throw() { return (_keyPair); }
  160. /**
  161. * Shortcut method to perform key agreement with another identity
  162. *
  163. * This identity must have its private portion.
  164. *
  165. * @param id Identity to agree with
  166. * @param key Result parameter to fill with key bytes
  167. * @param klen Length of key in bytes
  168. * @return Was agreement successful?
  169. */
  170. inline bool agree(const Identity &id,void *key,unsigned int klen) const
  171. {
  172. if ((id)&&(_keyPair))
  173. return _keyPair->agree(id._publicKey,(unsigned char *)key,klen);
  174. return false;
  175. }
  176. /**
  177. * Sign a hash with this identity's private key
  178. *
  179. * @param sha256 32-byte hash to sign
  180. * @return ECDSA signature or empty string on failure or if identity has no private portion
  181. */
  182. inline std::string sign(const void *sha256) const
  183. {
  184. if (_keyPair)
  185. return _keyPair->sign(sha256);
  186. return std::string();
  187. }
  188. /**
  189. * Sign a block of data with this identity's private key
  190. *
  191. * This is a shortcut to SHA-256 hashing then signing.
  192. *
  193. * @param sha256 32-byte hash to sign
  194. * @return ECDSA signature or empty string on failure or if identity has no private portion
  195. */
  196. inline std::string sign(const void *data,unsigned int len) const
  197. {
  198. if (_keyPair)
  199. return _keyPair->sign(data,len);
  200. return std::string();
  201. }
  202. /**
  203. * Verify something signed with this identity's public key
  204. *
  205. * @param sha256 32-byte hash to verify
  206. * @param sigbytes Signature bytes
  207. * @param siglen Length of signature
  208. * @return True if signature is valid
  209. */
  210. inline bool verifySignature(const void *sha256,const void *sigbytes,unsigned int siglen) const
  211. {
  212. return EllipticCurveKeyPair::verify(sha256,_publicKey,sigbytes,siglen);
  213. }
  214. /**
  215. * Verify something signed with this identity's public key
  216. *
  217. * @param data Data to verify
  218. * @param len Length of data to verify
  219. * @param sigbytes Signature bytes
  220. * @param siglen Length of signature
  221. * @return True if signature is valid
  222. */
  223. inline bool verifySignature(const void *data,unsigned int len,const void *sigbytes,unsigned int siglen) const
  224. {
  225. return EllipticCurveKeyPair::verify(data,len,_publicKey,sigbytes,siglen);
  226. }
  227. /**
  228. * @return Public key (available in all identities)
  229. */
  230. inline const EllipticCurveKey &publicKey() const throw() { return _publicKey; }
  231. /**
  232. * @return Identity type
  233. */
  234. inline Type type() const throw() { return IDENTITY_TYPE_NIST_P_521; }
  235. /**
  236. * @return This identity's address
  237. */
  238. inline const Address &address() const throw() { return _address; }
  239. /**
  240. * Serialize this identity (binary)
  241. *
  242. * @param b Destination buffer to append to
  243. * @param includePrivate If true, include private key component (if present) (default: false)
  244. * @throws std::out_of_range Buffer too small
  245. */
  246. template<unsigned int C>
  247. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  248. throw(std::out_of_range)
  249. {
  250. _address.appendTo(b);
  251. b.append((unsigned char)IDENTITY_TYPE_NIST_P_521);
  252. b.append((unsigned char)(_publicKey.size() & 0xff));
  253. b.append(_publicKey.data(),_publicKey.size());
  254. b.append((unsigned char)(_signature.length() & 0xff));
  255. b.append(_signature);
  256. if ((includePrivate)&&(_keyPair)) {
  257. b.append((unsigned char)(_keyPair->priv().size() & 0xff));
  258. b.append(_keyPair->priv().data(),_keyPair->priv().size());
  259. } else b.append((unsigned char)0);
  260. }
  261. /**
  262. * Deserialize a binary serialized identity
  263. *
  264. * If an exception is thrown, the Identity object is left in an undefined
  265. * state and should not be used.
  266. *
  267. * @param b Buffer containing serialized data
  268. * @param startAt Index within buffer of serialized data (default: 0)
  269. * @return Length of serialized data read from buffer
  270. * @throws std::out_of_range Buffer too small
  271. * @throws std::invalid_argument Serialized data invalid
  272. */
  273. template<unsigned int C>
  274. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  275. throw(std::out_of_range,std::invalid_argument)
  276. {
  277. delete _keyPair;
  278. _keyPair = (EllipticCurveKeyPair *)0;
  279. unsigned int p = startAt;
  280. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  281. p += ZT_ADDRESS_LENGTH;
  282. if (b[p++] != IDENTITY_TYPE_NIST_P_521)
  283. throw std::invalid_argument("Identity: deserialize(): unsupported identity type");
  284. unsigned int publicKeyLength = b[p++];
  285. if (!publicKeyLength)
  286. throw std::invalid_argument("Identity: deserialize(): no public key");
  287. _publicKey.set(b.field(p,publicKeyLength),publicKeyLength);
  288. p += publicKeyLength;
  289. unsigned int signatureLength = b[p++];
  290. if (!signatureLength)
  291. throw std::invalid_argument("Identity: deserialize(): no signature");
  292. _signature.assign((const char *)b.field(p,signatureLength),signatureLength);
  293. p += signatureLength;
  294. unsigned int privateKeyLength = b[p++];
  295. if (privateKeyLength) {
  296. _keyPair = new EllipticCurveKeyPair(_publicKey,EllipticCurveKey(b.field(p,privateKeyLength),privateKeyLength));
  297. p += privateKeyLength;
  298. }
  299. return (p - startAt);
  300. }
  301. /**
  302. * Serialize to a more human-friendly string
  303. *
  304. * @param includePrivate If true, include private key (if it exists)
  305. * @return ASCII string representation of identity
  306. */
  307. std::string toString(bool includePrivate) const;
  308. /**
  309. * Deserialize a human-friendly string
  310. *
  311. * Note: validation is for the format only. The locallyValidate() method
  312. * must be used to check signature and address/key correspondence.
  313. *
  314. * @param str String to deserialize
  315. * @return True if deserialization appears successful
  316. */
  317. bool fromString(const char *str);
  318. inline bool fromString(const std::string &str) { return fromString(str.c_str()); }
  319. /**
  320. * @return True if this identity contains something
  321. */
  322. inline operator bool() const throw() { return (_publicKey.size()); }
  323. inline bool operator==(const Identity &id) const
  324. throw()
  325. {
  326. if (_address == id._address) {
  327. if ((_keyPair)&&(id._keyPair))
  328. return (*_keyPair == *id._keyPair);
  329. return (_publicKey == id._publicKey);
  330. }
  331. return false;
  332. }
  333. inline bool operator<(const Identity &id) const
  334. throw()
  335. {
  336. if (_address < id._address)
  337. return true;
  338. else if (_address == id._address)
  339. return (_publicKey < id._publicKey);
  340. return false;
  341. }
  342. inline bool operator!=(const Identity &id) const throw() { return !(*this == id); }
  343. inline bool operator>(const Identity &id) const throw() { return (id < *this); }
  344. inline bool operator<=(const Identity &id) const throw() { return !(id < *this); }
  345. inline bool operator>=(const Identity &id) const throw() { return !(*this < id); }
  346. private:
  347. // Compute an address from public key bytes
  348. static Address deriveAddress(const void *keyBytes,unsigned int keyLen);
  349. EllipticCurveKeyPair *_keyPair;
  350. EllipticCurveKey _publicKey;
  351. Address _address;
  352. std::string _signature;
  353. };
  354. } // namespace ZeroTier
  355. #endif