Identity.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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("invalid string-serialized identity");
  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("invalid string-serialized identity");
  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. * Encrypt a block of data to send to another identity
  162. *
  163. * This identity must have a secret key.
  164. *
  165. * The encrypted data format is:
  166. * <[8] Salsa20 initialization vector>
  167. * <[8] first 8 bytes of HMAC-SHA-256 of ciphertext>
  168. * <[...] encrypted compressed data>
  169. *
  170. * Keying is accomplished using agree() (KDF function is in the
  171. * EllipticCurveKeyPair.cpp source) to generate 64 bytes of key. The first
  172. * 32 bytes are used as the Salsa20 key, and the last 32 bytes are used
  173. * as the HMAC key.
  174. *
  175. * @param to Identity of recipient of encrypted message
  176. * @param data Data to encrypt
  177. * @param len Length of data
  178. * @return Encrypted data or empty string on failure
  179. */
  180. std::string encrypt(const Identity &to,const void *data,unsigned int len) const;
  181. /**
  182. * Decrypt a message encrypted with encrypt()
  183. *
  184. * This identity must have a secret key.
  185. *
  186. * @param from Identity of sender of encrypted message
  187. * @param cdata Encrypted message
  188. * @param len Length of encrypted message
  189. * @return Decrypted data or empty string on failure
  190. */
  191. std::string decrypt(const Identity &from,const void *cdata,unsigned int len) const;
  192. /**
  193. * Shortcut method to perform key agreement with another identity
  194. *
  195. * This identity must have its private portion.
  196. *
  197. * @param id Identity to agree with
  198. * @param key Result parameter to fill with key bytes
  199. * @param klen Length of key in bytes
  200. * @return Was agreement successful?
  201. */
  202. inline bool agree(const Identity &id,void *key,unsigned int klen) const
  203. {
  204. if ((id)&&(_keyPair))
  205. return _keyPair->agree(id._publicKey,(unsigned char *)key,klen);
  206. return false;
  207. }
  208. /**
  209. * Sign a hash with this identity's private key
  210. *
  211. * @param sha256 32-byte hash to sign
  212. * @return ECDSA signature or empty string on failure or if identity has no private portion
  213. */
  214. inline std::string sign(const void *sha256) const
  215. {
  216. if (_keyPair)
  217. return _keyPair->sign(sha256);
  218. return std::string();
  219. }
  220. /**
  221. * Sign a block of data with this identity's private key
  222. *
  223. * This is a shortcut to SHA-256 hashing then signing.
  224. *
  225. * @param sha256 32-byte hash to sign
  226. * @return ECDSA signature or empty string on failure or if identity has no private portion
  227. */
  228. inline std::string sign(const void *data,unsigned int len) const
  229. {
  230. if (_keyPair)
  231. return _keyPair->sign(data,len);
  232. return std::string();
  233. }
  234. /**
  235. * Verify something signed with this identity's public key
  236. *
  237. * @param sha256 32-byte hash to verify
  238. * @param sigbytes Signature bytes
  239. * @param siglen Length of signature
  240. * @return True if signature is valid
  241. */
  242. inline bool verifySignature(const void *sha256,const void *sigbytes,unsigned int siglen) const
  243. {
  244. return EllipticCurveKeyPair::verify(sha256,_publicKey,sigbytes,siglen);
  245. }
  246. /**
  247. * Verify something signed with this identity's public key
  248. *
  249. * @param data Data to verify
  250. * @param len Length of data to verify
  251. * @param sigbytes Signature bytes
  252. * @param siglen Length of signature
  253. * @return True if signature is valid
  254. */
  255. inline bool verifySignature(const void *data,unsigned int len,const void *sigbytes,unsigned int siglen) const
  256. {
  257. return EllipticCurveKeyPair::verify(data,len,_publicKey,sigbytes,siglen);
  258. }
  259. /**
  260. * @return Public key (available in all identities)
  261. */
  262. inline const EllipticCurveKey &publicKey() const throw() { return _publicKey; }
  263. /**
  264. * @return Identity type
  265. */
  266. inline Type type() const throw() { return IDENTITY_TYPE_NIST_P_521; }
  267. /**
  268. * @return This identity's address
  269. */
  270. inline const Address &address() const throw() { return _address; }
  271. /**
  272. * Serialize this identity (binary)
  273. *
  274. * @param b Destination buffer to append to
  275. * @param includePrivate If true, include private key component (if present) (default: false)
  276. * @throws std::out_of_range Buffer too small
  277. */
  278. template<unsigned int C>
  279. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  280. throw(std::out_of_range)
  281. {
  282. b.append(_address.data(),ZT_ADDRESS_LENGTH);
  283. b.append((unsigned char)IDENTITY_TYPE_NIST_P_521);
  284. b.append((unsigned char)(_publicKey.size() & 0xff));
  285. b.append(_publicKey.data(),_publicKey.size());
  286. b.append((unsigned char)(_signature.length() & 0xff));
  287. b.append(_signature);
  288. if ((includePrivate)&&(_keyPair)) {
  289. b.append((unsigned char)(_keyPair->priv().size() & 0xff));
  290. b.append(_keyPair->priv().data(),_keyPair->priv().size());
  291. } else b.append((unsigned char)0);
  292. }
  293. /**
  294. * Deserialize a binary serialized identity
  295. *
  296. * If an exception is thrown, the Identity object is left in an undefined
  297. * state and should not be used.
  298. *
  299. * @param b Buffer containing serialized data
  300. * @param startAt Index within buffer of serialized data (default: 0)
  301. * @return Length of serialized data read from buffer
  302. * @throws std::out_of_range Buffer too small
  303. * @throws std::invalid_argument Serialized data invalid
  304. */
  305. template<unsigned int C>
  306. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  307. throw(std::out_of_range,std::invalid_argument)
  308. {
  309. delete _keyPair;
  310. _keyPair = (EllipticCurveKeyPair *)0;
  311. unsigned int p = startAt;
  312. _address = b.field(p,ZT_ADDRESS_LENGTH);
  313. p += ZT_ADDRESS_LENGTH;
  314. if (b[p++] != IDENTITY_TYPE_NIST_P_521)
  315. throw std::invalid_argument("Identity: deserialize(): unsupported identity type");
  316. unsigned int publicKeyLength = b[p++];
  317. if (!publicKeyLength)
  318. throw std::invalid_argument("Identity: deserialize(): no public key");
  319. _publicKey.set(b.field(p,publicKeyLength),publicKeyLength);
  320. p += publicKeyLength;
  321. unsigned int signatureLength = b[p++];
  322. if (!signatureLength)
  323. throw std::invalid_argument("Identity: deserialize(): no signature");
  324. _signature.assign((const char *)b.field(p,signatureLength),signatureLength);
  325. p += signatureLength;
  326. unsigned int privateKeyLength = b[p++];
  327. if (privateKeyLength) {
  328. _keyPair = new EllipticCurveKeyPair(_publicKey,EllipticCurveKey(b.field(p,privateKeyLength),privateKeyLength));
  329. p += privateKeyLength;
  330. }
  331. return (p - startAt);
  332. }
  333. /**
  334. * Serialize to a more human-friendly string
  335. *
  336. * @param includePrivate If true, include private key (if it exists)
  337. * @return ASCII string representation of identity
  338. */
  339. std::string toString(bool includePrivate) const;
  340. /**
  341. * Deserialize a human-friendly string
  342. *
  343. * Note: validation is for the format only. The locallyValidate() method
  344. * must be used to check signature and address/key correspondence.
  345. *
  346. * @param str String to deserialize
  347. * @return True if deserialization appears successful
  348. */
  349. bool fromString(const char *str);
  350. inline bool fromString(const std::string &str) { return fromString(str.c_str()); }
  351. /**
  352. * @return True if this identity contains something
  353. */
  354. inline operator bool() const throw() { return (_publicKey.size()); }
  355. inline bool operator==(const Identity &id) const
  356. throw()
  357. {
  358. if (_address == id._address) {
  359. if ((_keyPair)&&(id._keyPair))
  360. return (*_keyPair == *id._keyPair);
  361. return (_publicKey == id._publicKey);
  362. }
  363. return false;
  364. }
  365. inline bool operator<(const Identity &id) const
  366. throw()
  367. {
  368. if (_address < id._address)
  369. return true;
  370. else if (_address == id._address)
  371. return (_publicKey < id._publicKey);
  372. return false;
  373. }
  374. inline bool operator!=(const Identity &id) const throw() { return !(*this == id); }
  375. inline bool operator>(const Identity &id) const throw() { return (id < *this); }
  376. inline bool operator<=(const Identity &id) const throw() { return !(id < *this); }
  377. inline bool operator>=(const Identity &id) const throw() { return !(*this < id); }
  378. private:
  379. // Compute an address from public key bytes
  380. static Address deriveAddress(const void *keyBytes,unsigned int keyLen);
  381. EllipticCurveKeyPair *_keyPair;
  382. EllipticCurveKey _publicKey;
  383. Address _address;
  384. std::string _signature;
  385. };
  386. } // namespace ZeroTier
  387. #endif