Identity.hpp 8.9 KB

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