Identity.hpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_IDENTITY_HPP
  27. #define ZT_IDENTITY_HPP
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string>
  31. #include "Constants.hpp"
  32. #include "Array.hpp"
  33. #include "Utils.hpp"
  34. #include "Address.hpp"
  35. #include "C25519.hpp"
  36. #include "Buffer.hpp"
  37. #include "SHA512.hpp"
  38. namespace ZeroTier {
  39. /**
  40. * A ZeroTier identity
  41. *
  42. * An identity consists of a public key, a 40-bit ZeroTier address computed
  43. * from that key in a collision-resistant fashion, and a self-signature.
  44. *
  45. * The address derivation algorithm makes it computationally very expensive to
  46. * search for a different public key that duplicates an existing address. (See
  47. * code for deriveAddress() for this algorithm.)
  48. */
  49. class Identity
  50. {
  51. public:
  52. Identity() :
  53. _privateKey((C25519::Private *)0)
  54. {
  55. }
  56. Identity(const Identity &id) :
  57. _address(id._address),
  58. _publicKey(id._publicKey),
  59. _privateKey((id._privateKey) ? new C25519::Private(*(id._privateKey)) : (C25519::Private *)0)
  60. {
  61. }
  62. Identity(const char *str)
  63. throw(std::invalid_argument) :
  64. _privateKey((C25519::Private *)0)
  65. {
  66. if (!fromString(str))
  67. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  68. }
  69. Identity(const std::string &str)
  70. throw(std::invalid_argument) :
  71. _privateKey((C25519::Private *)0)
  72. {
  73. if (!fromString(str))
  74. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  75. }
  76. template<unsigned int C>
  77. Identity(const Buffer<C> &b,unsigned int startAt = 0) :
  78. _privateKey((C25519::Private *)0)
  79. {
  80. deserialize(b,startAt);
  81. }
  82. ~Identity()
  83. {
  84. delete _privateKey;
  85. }
  86. inline Identity &operator=(const Identity &id)
  87. {
  88. _address = id._address;
  89. _publicKey = id._publicKey;
  90. if (id._privateKey) {
  91. if (!_privateKey)
  92. _privateKey = new C25519::Private();
  93. *_privateKey = *(id._privateKey);
  94. } else {
  95. delete _privateKey;
  96. _privateKey = (C25519::Private *)0;
  97. }
  98. return *this;
  99. }
  100. /**
  101. * Generate a new identity (address, key pair)
  102. *
  103. * This is a time consuming operation.
  104. */
  105. void generate();
  106. /**
  107. * Check the validity of this identity's pairing of key to address
  108. *
  109. * @return True if validation check passes
  110. */
  111. bool locallyValidate() const;
  112. /**
  113. * @return True if this identity contains a private key
  114. */
  115. inline bool hasPrivate() const throw() { return (_privateKey != (C25519::Private *)0); }
  116. /**
  117. * Compute the SHA512 hash of our private key (if we have one)
  118. *
  119. * @param sha Buffer to receive SHA512 (MUST be ZT_SHA512_DIGEST_LEN (64) bytes in length)
  120. * @return True on success, false if no private key
  121. */
  122. inline bool sha512PrivateKey(void *sha) const
  123. {
  124. if (_privateKey) {
  125. SHA512::hash(sha,_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN);
  126. return true;
  127. }
  128. return false;
  129. }
  130. /**
  131. * Sign a message with this identity (private key required)
  132. *
  133. * @param data Data to sign
  134. * @param len Length of data
  135. */
  136. inline C25519::Signature sign(const void *data,unsigned int len) const
  137. throw(std::runtime_error)
  138. {
  139. if (_privateKey)
  140. return C25519::sign(*_privateKey,_publicKey,data,len);
  141. throw std::runtime_error("sign() requires a private key");
  142. }
  143. /**
  144. * Verify a message signature against this identity
  145. *
  146. * @param data Data to check
  147. * @param len Length of data
  148. * @param signature Signature bytes
  149. * @param siglen Length of signature in bytes
  150. * @return True if signature validates and data integrity checks
  151. */
  152. inline bool verify(const void *data,unsigned int len,const void *signature,unsigned int siglen) const
  153. {
  154. if (siglen != ZT_C25519_SIGNATURE_LEN)
  155. return false;
  156. return C25519::verify(_publicKey,data,len,signature);
  157. }
  158. /**
  159. * Verify a message signature against this identity
  160. *
  161. * @param data Data to check
  162. * @param len Length of data
  163. * @param signature Signature
  164. * @return True if signature validates and data integrity checks
  165. */
  166. inline bool verify(const void *data,unsigned int len,const C25519::Signature &signature) const
  167. {
  168. return C25519::verify(_publicKey,data,len,signature);
  169. }
  170. /**
  171. * Shortcut method to perform key agreement with another identity
  172. *
  173. * This identity must have a private key. (Check hasPrivate())
  174. *
  175. * @param id Identity to agree with
  176. * @param key Result parameter to fill with key bytes
  177. * @param klen Length of key in bytes
  178. * @return Was agreement successful?
  179. */
  180. inline bool agree(const Identity &id,void *key,unsigned int klen) const
  181. {
  182. if (_privateKey) {
  183. C25519::agree(*_privateKey,id._publicKey,key,klen);
  184. return true;
  185. }
  186. return false;
  187. }
  188. /**
  189. * @return This identity's address
  190. */
  191. inline const Address &address() const throw() { return _address; }
  192. /**
  193. * Serialize this identity (binary)
  194. *
  195. * @param b Destination buffer to append to
  196. * @param includePrivate If true, include private key component (if present) (default: false)
  197. * @throws std::out_of_range Buffer too small
  198. */
  199. template<unsigned int C>
  200. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  201. {
  202. _address.appendTo(b);
  203. b.append((uint8_t)0); // C25519/Ed25519 identity type
  204. b.append(_publicKey.data,(unsigned int)_publicKey.size());
  205. if ((_privateKey)&&(includePrivate)) {
  206. b.append((unsigned char)_privateKey->size());
  207. b.append(_privateKey->data,(unsigned int)_privateKey->size());
  208. } else b.append((unsigned char)0);
  209. }
  210. /**
  211. * Deserialize a binary serialized identity
  212. *
  213. * If an exception is thrown, the Identity object is left in an undefined
  214. * state and should not be used.
  215. *
  216. * @param b Buffer containing serialized data
  217. * @param startAt Index within buffer of serialized data (default: 0)
  218. * @return Length of serialized data read from buffer
  219. * @throws std::out_of_range Serialized data invalid
  220. * @throws std::invalid_argument Serialized data invalid
  221. */
  222. template<unsigned int C>
  223. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  224. {
  225. delete _privateKey;
  226. _privateKey = (C25519::Private *)0;
  227. unsigned int p = startAt;
  228. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  229. p += ZT_ADDRESS_LENGTH;
  230. if (b[p++] != 0)
  231. throw std::invalid_argument("unsupported identity type");
  232. memcpy(_publicKey.data,b.field(p,(unsigned int)_publicKey.size()),(unsigned int)_publicKey.size());
  233. p += (unsigned int)_publicKey.size();
  234. unsigned int privateKeyLength = (unsigned int)b[p++];
  235. if (privateKeyLength) {
  236. if (privateKeyLength != ZT_C25519_PRIVATE_KEY_LEN)
  237. throw std::invalid_argument("invalid private key");
  238. _privateKey = new C25519::Private();
  239. memcpy(_privateKey->data,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  240. p += ZT_C25519_PRIVATE_KEY_LEN;
  241. }
  242. return (p - startAt);
  243. }
  244. /**
  245. * Serialize to a more human-friendly string
  246. *
  247. * @param includePrivate If true, include private key (if it exists)
  248. * @return ASCII string representation of identity
  249. */
  250. std::string toString(bool includePrivate) const;
  251. /**
  252. * Deserialize a human-friendly string
  253. *
  254. * Note: validation is for the format only. The locallyValidate() method
  255. * must be used to check signature and address/key correspondence.
  256. *
  257. * @param str String to deserialize
  258. * @return True if deserialization appears successful
  259. */
  260. bool fromString(const char *str);
  261. inline bool fromString(const std::string &str) { return fromString(str.c_str()); }
  262. /**
  263. * @return C25519 public key
  264. */
  265. inline const C25519::Public &publicKey() const { return _publicKey; }
  266. /**
  267. * @return C25519 key pair (only returns valid pair if private key is present in this Identity object)
  268. */
  269. inline const C25519::Pair privateKeyPair() const
  270. {
  271. C25519::Pair pair;
  272. pair.pub = _publicKey;
  273. if (_privateKey)
  274. pair.priv = *_privateKey;
  275. else memset(pair.priv.data,0,ZT_C25519_PRIVATE_KEY_LEN);
  276. return pair;
  277. }
  278. /**
  279. * @return True if this identity contains something
  280. */
  281. inline operator bool() const throw() { return (_address); }
  282. inline bool operator==(const Identity &id) const throw() { return ((_address == id._address)&&(_publicKey == id._publicKey)); }
  283. inline bool operator<(const Identity &id) const throw() { return ((_address < id._address)||((_address == id._address)&&(_publicKey < id._publicKey))); }
  284. inline bool operator!=(const Identity &id) const throw() { return !(*this == id); }
  285. inline bool operator>(const Identity &id) const throw() { return (id < *this); }
  286. inline bool operator<=(const Identity &id) const throw() { return !(id < *this); }
  287. inline bool operator>=(const Identity &id) const throw() { return !(*this < id); }
  288. private:
  289. Address _address;
  290. C25519::Public _publicKey;
  291. C25519::Private *_privateKey;
  292. };
  293. } // namespace ZeroTier
  294. #endif