Identity.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c)2013-2020 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: 2024-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 <cstdio>
  16. #include <cstdlib>
  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 "ECC384.hpp"
  24. #define ZT_IDENTITY_STRING_BUFFER_LENGTH 1024
  25. #define ZT_IDENTITY_P384_COMPOUND_PUBLIC_KEY_SIZE (ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE + ZT_C25519_SIGNATURE_LEN + ZT_ECC384_SIGNATURE_SIZE)
  26. #define ZT_IDENTITY_P384_COMPOUND_PRIVATE_KEY_SIZE (ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE)
  27. #define ZT_IDENTITY_MARSHAL_SIZE_MAX (ZT_ADDRESS_LENGTH + 4 + ZT_IDENTITY_P384_COMPOUND_PUBLIC_KEY_SIZE + ZT_IDENTITY_P384_COMPOUND_PRIVATE_KEY_SIZE)
  28. namespace ZeroTier {
  29. /**
  30. * A ZeroTier identity
  31. *
  32. * An identity consists of a public key, a 40-bit ZeroTier address computed
  33. * from that key in a collision-resistant fashion, and a self-signature.
  34. *
  35. * The address derivation algorithm makes it computationally very expensive to
  36. * search for a different public key that duplicates an existing address. (See
  37. * code for deriveAddress() for this algorithm.)
  38. */
  39. class Identity
  40. {
  41. public:
  42. /**
  43. * Identity type -- numeric values of these enums are protocol constants
  44. */
  45. enum Type
  46. {
  47. C25519 = ZT_CRYPTO_ALG_C25519, // Type 0 -- Curve25519 and Ed25519 (1.x and 2.x, default)
  48. P384 = ZT_CRYPTO_ALG_P384 // Type 1 -- NIST P-384 with linked Curve25519/Ed25519 secondaries (2.x+)
  49. };
  50. ZT_ALWAYS_INLINE Identity() { memset(reinterpret_cast<void *>(this),0,sizeof(Identity)); }
  51. ZT_ALWAYS_INLINE ~Identity() { Utils::burn(reinterpret_cast<void *>(&this->_priv),sizeof(this->_priv)); }
  52. /**
  53. * Construct identity from string
  54. *
  55. * If the identity is not basically valid (no deep checking is done) the result will
  56. * be a null identity.
  57. *
  58. * @param str Identity in canonical string format
  59. */
  60. explicit ZT_ALWAYS_INLINE Identity(const char *str) { fromString(str); }
  61. /**
  62. * Set identity to NIL value (all zero)
  63. */
  64. ZT_ALWAYS_INLINE void zero() { memset(reinterpret_cast<void *>(this),0,sizeof(Identity)); }
  65. /**
  66. * @return Identity type (undefined if identity is null or invalid)
  67. */
  68. ZT_ALWAYS_INLINE Type type() const { return _type; }
  69. /**
  70. * Generate a new identity (address, key pair)
  71. *
  72. * This is a time consuming operation taking up to 5-10 seconds on some slower systems.
  73. *
  74. * @param t Type of identity to generate
  75. */
  76. void generate(Type t);
  77. /**
  78. * Check the validity of this identity's pairing of key to address
  79. *
  80. * @return True if validation check passes
  81. */
  82. bool locallyValidate() const;
  83. /**
  84. * @return True if this identity contains a private key
  85. */
  86. ZT_ALWAYS_INLINE bool hasPrivate() const { return _hasPrivate; }
  87. /**
  88. * @return 384-bit/48-byte hash of this identity's public key(s)
  89. */
  90. ZT_ALWAYS_INLINE const uint8_t *hash() const
  91. {
  92. if (_hash[0] == 0)
  93. const_cast<Identity *>(this)->_computeHash();
  94. return reinterpret_cast<const uint8_t *>(_hash);
  95. }
  96. /**
  97. * Compute a hash of this identity's public and private keys
  98. *
  99. * @param h Buffer to store SHA384 hash
  100. */
  101. void hashWithPrivate(uint8_t h[48]) const;
  102. /**
  103. * Sign a message with this identity (private key required)
  104. *
  105. * The signature buffer should be large enough for the largest
  106. * signature, which is currently 96 bytes.
  107. *
  108. * @param data Data to sign
  109. * @param len Length of data
  110. * @param sig Buffer to receive signature
  111. * @param siglen Length of buffer
  112. * @return Number of bytes actually written to sig or 0 on error
  113. */
  114. unsigned int sign(const void *data,unsigned int len,void *sig,unsigned int siglen) const;
  115. /**
  116. * Verify a message signature against this identity
  117. *
  118. * @param data Data to check
  119. * @param len Length of data
  120. * @param signature Signature bytes
  121. * @param siglen Length of signature in bytes
  122. * @return True if signature validates and data integrity checks
  123. */
  124. bool verify(const void *data,unsigned int len,const void *sig,unsigned int siglen) const;
  125. /**
  126. * Shortcut method to perform key agreement with another identity
  127. *
  128. * This identity must have a private key. (Check hasPrivate())
  129. *
  130. * @param id Identity to agree with
  131. * @param key Result parameter to fill with key bytes
  132. * @return Was agreement successful?
  133. */
  134. bool agree(const Identity &id,uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) const;
  135. /**
  136. * @return This identity's address
  137. */
  138. ZT_ALWAYS_INLINE const Address &address() const { return _address; }
  139. /**
  140. * Serialize this identity (binary)
  141. *
  142. * @param b Destination buffer to append to
  143. * @param includePrivate If true, include private key component (if present) (default: false)
  144. */
  145. template<unsigned int C>
  146. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  147. {
  148. _address.appendTo(b);
  149. switch(_type) {
  150. case C25519:
  151. b.append((uint8_t)C25519);
  152. b.append(_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  153. if ((_hasPrivate)&&(includePrivate)) {
  154. b.append((uint8_t)ZT_C25519_PRIVATE_KEY_LEN);
  155. b.append(_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  156. } else {
  157. b.append((uint8_t)0);
  158. }
  159. break;
  160. case P384:
  161. b.append((uint8_t)P384);
  162. b.append(&_pub,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE + ZT_C25519_SIGNATURE_LEN + ZT_ECC384_SIGNATURE_SIZE);
  163. if ((_hasPrivate)&&(includePrivate)) {
  164. b.append((uint8_t)(ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE));
  165. b.append(_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  166. b.append(_priv.p384,ZT_ECC384_PRIVATE_KEY_SIZE);
  167. } else {
  168. b.append((uint8_t)0);
  169. }
  170. b.append((uint8_t)0); // size of additional fields (should have included such a thing in v0!)
  171. break;
  172. }
  173. }
  174. /**
  175. * Deserialize a binary serialized identity
  176. *
  177. * If an exception is thrown, the Identity object is left in an undefined
  178. * state and should not be used.
  179. *
  180. * @param b Buffer containing serialized data
  181. * @param startAt Index within buffer of serialized data (default: 0)
  182. * @return Length of serialized data read from buffer
  183. */
  184. template<unsigned int C>
  185. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  186. {
  187. _hasPrivate = false;
  188. unsigned int p = startAt;
  189. unsigned int pkl;
  190. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  191. p += ZT_ADDRESS_LENGTH;
  192. switch((_type = (Type)b[p++])) {
  193. case C25519:
  194. memcpy(_pub.c25519,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  195. p += ZT_C25519_PUBLIC_KEY_LEN;
  196. pkl = (unsigned int)b[p++];
  197. if (pkl) {
  198. if (pkl != ZT_C25519_PRIVATE_KEY_LEN)
  199. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  200. _hasPrivate = true;
  201. memcpy(_priv.c25519,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  202. p += ZT_C25519_PRIVATE_KEY_LEN;
  203. } else {
  204. _hasPrivate = false;
  205. }
  206. break;
  207. case P384:
  208. memcpy(&_pub,b.field(p,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE + ZT_C25519_SIGNATURE_LEN + ZT_ECC384_SIGNATURE_SIZE),ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE + ZT_C25519_SIGNATURE_LEN + ZT_ECC384_SIGNATURE_SIZE);
  209. p += ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE + ZT_C25519_SIGNATURE_LEN + ZT_ECC384_SIGNATURE_SIZE;
  210. pkl = (unsigned int)b[p++];
  211. if (pkl) {
  212. if (pkl != (ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE))
  213. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  214. _hasPrivate = true;
  215. memcpy(_priv.c25519,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  216. p += ZT_C25519_PRIVATE_KEY_LEN;
  217. memcpy(_priv.p384,b.field(p,ZT_ECC384_PRIVATE_KEY_SIZE),ZT_ECC384_PRIVATE_KEY_SIZE);
  218. p += ZT_ECC384_PRIVATE_KEY_SIZE;
  219. } else {
  220. _hasPrivate = false;
  221. }
  222. p += b.template at<uint8_t>(p) + 2;
  223. break;
  224. default:
  225. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  226. }
  227. return (p - startAt);
  228. }
  229. /**
  230. * Serialize to a more human-friendly string
  231. *
  232. * @param includePrivate If true, include private key (if it exists)
  233. * @param buf Buffer to store string
  234. * @return ASCII string representation of identity (pointer to buf)
  235. */
  236. char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
  237. /**
  238. * Deserialize a human-friendly string
  239. *
  240. * Note: validation is for the format only. The locallyValidate() method
  241. * must be used to check signature and address/key correspondence.
  242. *
  243. * @param str String to deserialize
  244. * @return True if deserialization appears successful
  245. */
  246. bool fromString(const char *str);
  247. /**
  248. * @return True if this identity contains something
  249. */
  250. explicit ZT_ALWAYS_INLINE operator bool() const { return (_address); }
  251. ZT_ALWAYS_INLINE bool operator==(const Identity &id) const
  252. {
  253. if ((_address == id._address)&&(_type == id._type)) {
  254. switch(_type) {
  255. case C25519: return (memcmp(_pub.c25519,id._pub.c25519,ZT_C25519_PUBLIC_KEY_LEN) == 0);
  256. // case P384:
  257. default: return (memcmp(&_pub,&id._pub,sizeof(_pub)) == 0);
  258. }
  259. }
  260. return false;
  261. }
  262. ZT_ALWAYS_INLINE bool operator<(const Identity &id) const
  263. {
  264. if (_address < id._address)
  265. return true;
  266. if (_address == id._address) {
  267. if ((int)_type < (int)id._type)
  268. return true;
  269. if (_type == id._type) {
  270. switch(_type) {
  271. case C25519: return (memcmp(_pub.c25519,id._pub.c25519,ZT_C25519_PUBLIC_KEY_LEN) < 0);
  272. // case P384:
  273. default: return (memcmp(&_pub,&id._pub,sizeof(_pub)) < 0);
  274. }
  275. }
  276. }
  277. return false;
  278. }
  279. ZT_ALWAYS_INLINE bool operator!=(const Identity &id) const { return !(*this == id); }
  280. ZT_ALWAYS_INLINE bool operator>(const Identity &id) const { return (id < *this); }
  281. ZT_ALWAYS_INLINE bool operator<=(const Identity &id) const { return !(id < *this); }
  282. ZT_ALWAYS_INLINE bool operator>=(const Identity &id) const { return !(*this < id); }
  283. ZT_ALWAYS_INLINE unsigned long hashCode() const { return ((unsigned long)_address.toInt() + (unsigned long)_pub.c25519[0] + (unsigned long)_pub.c25519[1] + (unsigned long)_pub.c25519[2]); }
  284. static ZT_ALWAYS_INLINE int marshalSizeMax() { return ZT_IDENTITY_MARSHAL_SIZE_MAX; }
  285. int marshal(uint8_t data[ZT_IDENTITY_MARSHAL_SIZE_MAX],bool includePrivate = false) const;
  286. int unmarshal(const uint8_t *data,int len);
  287. private:
  288. void _computeHash(); // recompute _hash
  289. Address _address;
  290. uint64_t _hash[6]; // hash of public key memo-ized for performance, recalculated when _hash[0] == 0
  291. Type _type; // _type determines which fields in _priv and _pub are used
  292. bool _hasPrivate;
  293. ZT_PACKED_STRUCT(struct { // don't re-order these
  294. uint8_t c25519[ZT_C25519_PRIVATE_KEY_LEN];
  295. uint8_t p384[ZT_ECC384_PRIVATE_KEY_SIZE];
  296. }) _priv;
  297. ZT_PACKED_STRUCT(struct { // don't re-order these
  298. uint8_t c25519[ZT_C25519_PUBLIC_KEY_LEN]; // Curve25519 and Ed25519 public keys
  299. uint8_t p384[ZT_ECC384_PUBLIC_KEY_SIZE]; // NIST P-384 public key
  300. uint8_t c25519s[ZT_C25519_SIGNATURE_LEN]; // signature of both keys with ed25519
  301. uint8_t p384s[ZT_ECC384_SIGNATURE_SIZE]; // signature of both keys with p384
  302. }) _pub;
  303. };
  304. } // namespace ZeroTier
  305. #endif