Identity.hpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 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 "Constants.hpp"
  31. #include "Array.hpp"
  32. #include "Utils.hpp"
  33. #include "Address.hpp"
  34. #include "C25519.hpp"
  35. #include "Buffer.hpp"
  36. #include "SHA512.hpp"
  37. #define ZT_IDENTITY_STRING_BUFFER_LENGTH 384
  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. _privateKey((C25519::Private *)0)
  64. {
  65. if (!fromString(str))
  66. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  67. }
  68. template<unsigned int C>
  69. Identity(const Buffer<C> &b,unsigned int startAt = 0) :
  70. _privateKey((C25519::Private *)0)
  71. {
  72. deserialize(b,startAt);
  73. }
  74. ~Identity()
  75. {
  76. if (_privateKey) {
  77. Utils::burn(_privateKey,sizeof(C25519::Private));
  78. delete _privateKey;
  79. }
  80. }
  81. inline Identity &operator=(const Identity &id)
  82. {
  83. _address = id._address;
  84. _publicKey = id._publicKey;
  85. if (id._privateKey) {
  86. if (!_privateKey)
  87. _privateKey = new C25519::Private();
  88. *_privateKey = *(id._privateKey);
  89. } else {
  90. delete _privateKey;
  91. _privateKey = (C25519::Private *)0;
  92. }
  93. return *this;
  94. }
  95. /**
  96. * Generate a new identity (address, key pair)
  97. *
  98. * This is a time consuming operation.
  99. */
  100. void generate();
  101. /**
  102. * Check the validity of this identity's pairing of key to address
  103. *
  104. * @return True if validation check passes
  105. */
  106. bool locallyValidate() const;
  107. /**
  108. * @return True if this identity contains a private key
  109. */
  110. inline bool hasPrivate() const { return (_privateKey != (C25519::Private *)0); }
  111. /**
  112. * Compute the SHA512 hash of our private key (if we have one)
  113. *
  114. * @param sha Buffer to receive SHA512 (MUST be ZT_SHA512_DIGEST_LEN (64) bytes in length)
  115. * @return True on success, false if no private key
  116. */
  117. inline bool sha512PrivateKey(void *sha) const
  118. {
  119. if (_privateKey) {
  120. SHA512::hash(sha,_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN);
  121. return true;
  122. }
  123. return false;
  124. }
  125. /**
  126. * Sign a message with this identity (private key required)
  127. *
  128. * @param data Data to sign
  129. * @param len Length of data
  130. */
  131. inline C25519::Signature sign(const void *data,unsigned int len) const
  132. {
  133. if (_privateKey)
  134. return C25519::sign(*_privateKey,_publicKey,data,len);
  135. throw ZT_EXCEPTION_PRIVATE_KEY_REQUIRED;
  136. }
  137. /**
  138. * Verify a message signature against this identity
  139. *
  140. * @param data Data to check
  141. * @param len Length of data
  142. * @param signature Signature bytes
  143. * @param siglen Length of signature in bytes
  144. * @return True if signature validates and data integrity checks
  145. */
  146. inline bool verify(const void *data,unsigned int len,const void *signature,unsigned int siglen) const
  147. {
  148. if (siglen != ZT_C25519_SIGNATURE_LEN)
  149. return false;
  150. return C25519::verify(_publicKey,data,len,signature);
  151. }
  152. /**
  153. * Verify a message signature against this identity
  154. *
  155. * @param data Data to check
  156. * @param len Length of data
  157. * @param signature Signature
  158. * @return True if signature validates and data integrity checks
  159. */
  160. inline bool verify(const void *data,unsigned int len,const C25519::Signature &signature) const
  161. {
  162. return C25519::verify(_publicKey,data,len,signature);
  163. }
  164. /**
  165. * Shortcut method to perform key agreement with another identity
  166. *
  167. * This identity must have a private key. (Check hasPrivate())
  168. *
  169. * @param id Identity to agree with
  170. * @param key Result parameter to fill with key bytes
  171. * @param klen Length of key in bytes
  172. * @return Was agreement successful?
  173. */
  174. inline bool agree(const Identity &id,void *key,unsigned int klen) const
  175. {
  176. if (_privateKey) {
  177. C25519::agree(*_privateKey,id._publicKey,key,klen);
  178. return true;
  179. }
  180. return false;
  181. }
  182. /**
  183. * @return This identity's address
  184. */
  185. inline const Address &address() const { return _address; }
  186. /**
  187. * Serialize this identity (binary)
  188. *
  189. * @param b Destination buffer to append to
  190. * @param includePrivate If true, include private key component (if present) (default: false)
  191. * @throws std::out_of_range Buffer too small
  192. */
  193. template<unsigned int C>
  194. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  195. {
  196. _address.appendTo(b);
  197. b.append((uint8_t)0); // C25519/Ed25519 identity type
  198. b.append(_publicKey.data,(unsigned int)_publicKey.size());
  199. if ((_privateKey)&&(includePrivate)) {
  200. b.append((unsigned char)_privateKey->size());
  201. b.append(_privateKey->data,(unsigned int)_privateKey->size());
  202. } else b.append((unsigned char)0);
  203. }
  204. /**
  205. * Deserialize a binary serialized identity
  206. *
  207. * If an exception is thrown, the Identity object is left in an undefined
  208. * state and should not be used.
  209. *
  210. * @param b Buffer containing serialized data
  211. * @param startAt Index within buffer of serialized data (default: 0)
  212. * @return Length of serialized data read from buffer
  213. * @throws std::out_of_range Serialized data invalid
  214. * @throws std::invalid_argument Serialized data invalid
  215. */
  216. template<unsigned int C>
  217. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  218. {
  219. delete _privateKey;
  220. _privateKey = (C25519::Private *)0;
  221. unsigned int p = startAt;
  222. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  223. p += ZT_ADDRESS_LENGTH;
  224. if (b[p++] != 0)
  225. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  226. ZT_FAST_MEMCPY(_publicKey.data,b.field(p,(unsigned int)_publicKey.size()),(unsigned int)_publicKey.size());
  227. p += (unsigned int)_publicKey.size();
  228. unsigned int privateKeyLength = (unsigned int)b[p++];
  229. if (privateKeyLength) {
  230. if (privateKeyLength != ZT_C25519_PRIVATE_KEY_LEN)
  231. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  232. _privateKey = new C25519::Private();
  233. ZT_FAST_MEMCPY(_privateKey->data,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  234. p += ZT_C25519_PRIVATE_KEY_LEN;
  235. }
  236. return (p - startAt);
  237. }
  238. /**
  239. * Serialize to a more human-friendly string
  240. *
  241. * @param includePrivate If true, include private key (if it exists)
  242. * @param buf Buffer to store string
  243. * @return ASCII string representation of identity
  244. */
  245. char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
  246. /**
  247. * Deserialize a human-friendly string
  248. *
  249. * Note: validation is for the format only. The locallyValidate() method
  250. * must be used to check signature and address/key correspondence.
  251. *
  252. * @param str String to deserialize
  253. * @return True if deserialization appears successful
  254. */
  255. bool fromString(const char *str);
  256. /**
  257. * @return C25519 public key
  258. */
  259. inline const C25519::Public &publicKey() const { return _publicKey; }
  260. /**
  261. * @return C25519 key pair (only returns valid pair if private key is present in this Identity object)
  262. */
  263. inline const C25519::Pair privateKeyPair() const
  264. {
  265. C25519::Pair pair;
  266. pair.pub = _publicKey;
  267. if (_privateKey)
  268. pair.priv = *_privateKey;
  269. else memset(pair.priv.data,0,ZT_C25519_PRIVATE_KEY_LEN);
  270. return pair;
  271. }
  272. /**
  273. * @return True if this identity contains something
  274. */
  275. inline operator bool() const { return (_address); }
  276. inline bool operator==(const Identity &id) const { return ((_address == id._address)&&(_publicKey == id._publicKey)); }
  277. inline bool operator<(const Identity &id) const { return ((_address < id._address)||((_address == id._address)&&(_publicKey < id._publicKey))); }
  278. inline bool operator!=(const Identity &id) const { return !(*this == id); }
  279. inline bool operator>(const Identity &id) const { return (id < *this); }
  280. inline bool operator<=(const Identity &id) const { return !(id < *this); }
  281. inline bool operator>=(const Identity &id) const { return !(*this < id); }
  282. private:
  283. Address _address;
  284. C25519::Public _publicKey;
  285. C25519::Private *_privateKey;
  286. };
  287. } // namespace ZeroTier
  288. #endif