Identity.hpp 8.5 KB

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