Identity.hpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 "SHA512.hpp"
  22. #include "ECC384.hpp"
  23. #include "TriviallyCopyable.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)
  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. * Identities currently come in two types: type 0 identities based on just Curve25519
  33. * and Ed25519 and type 1 identities that include both a 25519 key pair and a NIST P-384
  34. * key pair. Type 1 identities use P-384 for signatures but use both key pairs at once
  35. * (hashing both keys together) for key agreement with other type 1 identities, and can
  36. * agree with type 0 identities by only using the Curve25519 component.
  37. *
  38. * Type 1 identities also use a simpler mechanism to rate limit identity generation (as
  39. * a defense in depth against intentional collision) that makes local identity validation
  40. * faster, allowing full identity validation on all unmarshal() operations.
  41. */
  42. class Identity : public TriviallyCopyable
  43. {
  44. public:
  45. /**
  46. * Identity type -- numeric values of these enums are protocol constants
  47. */
  48. enum Type
  49. {
  50. C25519 = ZT_CRYPTO_ALG_C25519, // Type 0 -- Curve25519 and Ed25519 (1.x and 2.x, default)
  51. P384 = ZT_CRYPTO_ALG_P384 // Type 1 -- NIST P-384 with linked Curve25519/Ed25519 secondaries (2.x+)
  52. };
  53. /**
  54. * A nil/empty identity instance
  55. */
  56. static const Identity NIL;
  57. ZT_ALWAYS_INLINE Identity() noexcept { memoryZero(this); }
  58. ZT_ALWAYS_INLINE ~Identity() { Utils::burn(reinterpret_cast<void *>(&this->_priv),sizeof(this->_priv)); }
  59. /**
  60. * Construct identity from string
  61. *
  62. * If the identity is not basically valid (no deep checking is done) the result will
  63. * be a null identity.
  64. *
  65. * @param str Identity in canonical string format
  66. */
  67. explicit ZT_ALWAYS_INLINE Identity(const char *str) { fromString(str); }
  68. /**
  69. * Set identity to NIL value (all zero)
  70. */
  71. ZT_ALWAYS_INLINE void zero() noexcept { memoryZero(this); }
  72. /**
  73. * @return Identity type (undefined if identity is null or invalid)
  74. */
  75. ZT_ALWAYS_INLINE Type type() const noexcept { return _type; }
  76. /**
  77. * Generate a new identity (address, key pair)
  78. *
  79. * This is a time consuming operation taking up to 5-10 seconds on some slower systems.
  80. *
  81. * @param t Type of identity to generate
  82. * @return False if there was an error such as type being an invalid value
  83. */
  84. bool generate(Type t);
  85. /**
  86. * Check the validity of this identity's pairing of key to address
  87. *
  88. * @return True if validation check passes
  89. */
  90. bool locallyValidate() const;
  91. /**
  92. * @return True if this identity contains a private key
  93. */
  94. ZT_ALWAYS_INLINE bool hasPrivate() const noexcept { return _hasPrivate; }
  95. /**
  96. * This gets (computing if needed) a hash of this identity's public key(s).
  97. *
  98. * The hash returned by this function differs by identity type. For C25519 (type 0)
  99. * identities this returns a simple SHA384 of the public key, which is NOT the same
  100. * as the hash used to generate the address. For type 1 C25519+P384 identities this
  101. * returns the same compoound SHA384 hash that is used for purposes of hashcash
  102. * and address computation. This difference is because the v0 hash is expensive while
  103. * the v1 hash is fast.
  104. *
  105. * @return 384-bit/48-byte hash (pointer remains valid as long as Identity object exists)
  106. */
  107. const uint8_t *hash() const;
  108. /**
  109. * Compute a hash of this identity's public and private keys
  110. *
  111. * @param h Buffer to store SHA384 hash
  112. */
  113. void hashWithPrivate(uint8_t h[48]) const;
  114. /**
  115. * Sign a message with this identity (private key required)
  116. *
  117. * The signature buffer should be large enough for the largest
  118. * signature, which is currently 96 bytes.
  119. *
  120. * @param data Data to sign
  121. * @param len Length of data
  122. * @param sig Buffer to receive signature
  123. * @param siglen Length of buffer
  124. * @return Number of bytes actually written to sig or 0 on error
  125. */
  126. unsigned int sign(const void *data,unsigned int len,void *sig,unsigned int siglen) const;
  127. /**
  128. * Verify a message signature against this identity
  129. *
  130. * @param data Data to check
  131. * @param len Length of data
  132. * @param signature Signature bytes
  133. * @param siglen Length of signature in bytes
  134. * @return True if signature validates and data integrity checks
  135. */
  136. bool verify(const void *data,unsigned int len,const void *sig,unsigned int siglen) const;
  137. /**
  138. * Shortcut method to perform key agreement with another identity
  139. *
  140. * This identity must have a private key. (Check hasPrivate())
  141. *
  142. * @param id Identity to agree with
  143. * @param key Result parameter to fill with key bytes
  144. * @return Was agreement successful?
  145. */
  146. bool agree(const Identity &id,uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) const;
  147. /**
  148. * @return This identity's address
  149. */
  150. ZT_ALWAYS_INLINE const Address &address() const noexcept { return _address; }
  151. /**
  152. * Serialize to a more human-friendly string
  153. *
  154. * @param includePrivate If true, include private key (if it exists)
  155. * @param buf Buffer to store string
  156. * @return ASCII string representation of identity (pointer to buf)
  157. */
  158. char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
  159. /**
  160. * Deserialize a human-friendly string
  161. *
  162. * Note: validation is for the format only. The locallyValidate() method
  163. * must be used to check signature and address/key correspondence.
  164. *
  165. * @param str String to deserialize
  166. * @return True if deserialization appears successful
  167. */
  168. bool fromString(const char *str);
  169. /**
  170. * @return True if this identity contains something
  171. */
  172. explicit ZT_ALWAYS_INLINE operator bool() const noexcept { return (_address); }
  173. ZT_ALWAYS_INLINE bool operator==(const Identity &id) const noexcept
  174. {
  175. if ((_address == id._address)&&(_type == id._type)) {
  176. switch(_type) {
  177. case C25519: return (memcmp(_pub.c25519,id._pub.c25519,ZT_C25519_PUBLIC_KEY_LEN) == 0);
  178. // case P384:
  179. default: return (memcmp(&_pub,&id._pub,sizeof(_pub)) == 0);
  180. }
  181. }
  182. return false;
  183. }
  184. ZT_ALWAYS_INLINE bool operator<(const Identity &id) const noexcept
  185. {
  186. if (_address < id._address)
  187. return true;
  188. if (_address == id._address) {
  189. if ((int)_type < (int)id._type)
  190. return true;
  191. if (_type == id._type) {
  192. switch(_type) {
  193. case C25519: return (memcmp(_pub.c25519,id._pub.c25519,ZT_C25519_PUBLIC_KEY_LEN) < 0);
  194. // case P384:
  195. default: return (memcmp(&_pub,&id._pub,sizeof(_pub)) < 0);
  196. }
  197. }
  198. }
  199. return false;
  200. }
  201. ZT_ALWAYS_INLINE bool operator!=(const Identity &id) const noexcept { return !(*this == id); }
  202. ZT_ALWAYS_INLINE bool operator>(const Identity &id) const noexcept { return (id < *this); }
  203. ZT_ALWAYS_INLINE bool operator<=(const Identity &id) const noexcept { return !(id < *this); }
  204. ZT_ALWAYS_INLINE bool operator>=(const Identity &id) const noexcept { return !(*this < id); }
  205. ZT_ALWAYS_INLINE unsigned long hashCode() const noexcept { return ((unsigned long)_address.toInt() + (unsigned long)_pub.c25519[0] + (unsigned long)_pub.c25519[1] + (unsigned long)_pub.c25519[2]); }
  206. static constexpr int marshalSizeMax() noexcept { return ZT_IDENTITY_MARSHAL_SIZE_MAX; }
  207. int marshal(uint8_t data[ZT_IDENTITY_MARSHAL_SIZE_MAX],bool includePrivate = false) const noexcept;
  208. int unmarshal(const uint8_t *data,int len) noexcept;
  209. private:
  210. Address _address;
  211. uint64_t _hash[6]; // hash of public key memo-ized for performance, recalculated when _hash[0] == 0
  212. Type _type; // _type determines which fields in _priv and _pub are used
  213. bool _hasPrivate;
  214. ZT_PACKED_STRUCT(struct { // don't re-order these
  215. uint8_t c25519[ZT_C25519_PRIVATE_KEY_LEN];
  216. uint8_t p384[ZT_ECC384_PRIVATE_KEY_SIZE];
  217. }) _priv;
  218. ZT_PACKED_STRUCT(struct { // don't re-order these
  219. uint8_t c25519[ZT_C25519_PUBLIC_KEY_LEN]; // Curve25519 and Ed25519 public keys
  220. uint8_t p384[ZT_ECC384_PUBLIC_KEY_SIZE]; // NIST P-384 public key
  221. }) _pub;
  222. };
  223. } // namespace ZeroTier
  224. #endif