Identity.hpp 8.9 KB

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