Identity.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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: 2023-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 "ECC384.hpp"
  24. #define ZT_IDENTITY_STRING_BUFFER_LENGTH 512
  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. /**
  40. * Identity type -- numeric values of these enums are protocol constants
  41. */
  42. enum Type
  43. {
  44. C25519 = ZT_CRYPTO_ALG_C25519, // Type 0 -- Curve25519 and Ed25519 (1.x and 2.x, default)
  45. P384 = ZT_CRYPTO_ALG_P384 // Type 1 -- NIST P-384 with linked Curve25519 and Ed25519 secondaries (2.x+)
  46. };
  47. ZT_ALWAYS_INLINE Identity() { memset(reinterpret_cast<void *>(this),0,sizeof(Identity)); }
  48. ZT_ALWAYS_INLINE Identity(const Identity &id) { memcpy(reinterpret_cast<void *>(this),&id,sizeof(Identity)); }
  49. inline Identity(const char *str)
  50. {
  51. if (!fromString(str))
  52. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  53. }
  54. template<unsigned int C>
  55. inline Identity(const Buffer<C> &b,unsigned int startAt = 0) { deserialize(b,startAt); }
  56. ZT_ALWAYS_INLINE ~Identity() { Utils::burn(reinterpret_cast<void *>(this),sizeof(Identity)); }
  57. /**
  58. * Set identity to NIL value (all zero)
  59. */
  60. ZT_ALWAYS_INLINE void zero() { Utils::burn(reinterpret_cast<void *>(this),sizeof(Identity)); }
  61. ZT_ALWAYS_INLINE Identity &operator=(const Identity &id)
  62. {
  63. memcpy(reinterpret_cast<void *>(this),&id,sizeof(Identity));
  64. return *this;
  65. }
  66. /**
  67. * @return Identity type
  68. */
  69. ZT_ALWAYS_INLINE Type type() const { return _type; }
  70. /**
  71. * Generate a new identity (address, key pair)
  72. *
  73. * This is a time consuming operation.
  74. *
  75. * @param t Type of identity to generate
  76. */
  77. void generate(const Type t);
  78. /**
  79. * Check the validity of this identity's pairing of key to address
  80. *
  81. * @return True if validation check passes
  82. */
  83. bool locallyValidate() const;
  84. /**
  85. * @return True if this identity contains a private key
  86. */
  87. ZT_ALWAYS_INLINE bool hasPrivate() const { return _hasPrivate; }
  88. /**
  89. * Compute the SHA512 hash of our private key (if we have one)
  90. *
  91. * @param sha Buffer to receive SHA512 (MUST be ZT_SHA512_DIGEST_LEN (64) bytes in length)
  92. * @return True on success, false if no private key
  93. */
  94. inline bool sha512PrivateKey(void *const sha) const
  95. {
  96. if (_hasPrivate) {
  97. switch(_type) {
  98. case C25519:
  99. SHA512(sha,_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  100. return true;
  101. case P384:
  102. SHA512(sha,&_priv,ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE);
  103. return true;
  104. }
  105. }
  106. return false;
  107. }
  108. /**
  109. * Compute a 128-bit short hash of this identity's public key
  110. *
  111. * This is the first 128 bits of a SHA384 hash and is the hash used
  112. * in VERB_WILL_RELAY to report reachability.
  113. *
  114. * @param h 128-bit buffer to receive hash (must be 16 bytes in size)
  115. */
  116. inline void publicKeyHash128(void *const h) const
  117. {
  118. uint8_t tmp[48];
  119. switch(_type) {
  120. case C25519:
  121. SHA384(tmp,_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  122. break;
  123. case P384:
  124. SHA384(tmp,&_pub,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE);
  125. break;
  126. }
  127. for(int i=0;i<16;++i)
  128. ((uint8_t *)h)[i] = tmp[i];
  129. }
  130. /**
  131. * Sign a message with this identity (private key required)
  132. *
  133. * The signature buffer should be large enough for the largest
  134. * signature, which is currently 96 bytes.
  135. *
  136. * @param data Data to sign
  137. * @param len Length of data
  138. * @param sig Buffer to receive signature
  139. * @param siglen Length of buffer
  140. * @return Number of bytes actually written to sig or 0 on error
  141. */
  142. inline unsigned int sign(const void *data,unsigned int len,void *sig,unsigned int siglen) const
  143. {
  144. if (_hasPrivate) {
  145. switch(_type) {
  146. case C25519:
  147. if (siglen >= ZT_C25519_SIGNATURE_LEN) {
  148. C25519::sign(_priv.c25519,_pub.c25519,data,len,sig);
  149. return ZT_C25519_SIGNATURE_LEN;
  150. }
  151. case P384:
  152. if (siglen >= ZT_ECC384_SIGNATURE_SIZE) {
  153. // Signature is a hash of the message followed by the c25519/ed25519 type 0
  154. // identity public keys to ensure that the two public keys are not separable.
  155. uint8_t h[48];
  156. SHA384(h,data,len,_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  157. ECC384ECDSASign(_priv.p384,h,(uint8_t *)sig);
  158. return ZT_ECC384_SIGNATURE_SIZE;
  159. }
  160. }
  161. }
  162. return 0;
  163. }
  164. /**
  165. * Verify a message signature against this identity
  166. *
  167. * @param data Data to check
  168. * @param len Length of data
  169. * @param signature Signature bytes
  170. * @param siglen Length of signature in bytes
  171. * @return True if signature validates and data integrity checks
  172. */
  173. inline bool verify(const void *data,unsigned int len,const void *sig,unsigned int siglen) const
  174. {
  175. switch(_type) {
  176. case C25519:
  177. return C25519::verify(_pub.c25519,data,len,sig,siglen);
  178. case P384:
  179. if (siglen == ZT_ECC384_SIGNATURE_SIZE) {
  180. uint8_t h[48];
  181. SHA384(h,data,len,_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  182. return ECC384ECDSAVerify(_pub.p384,h,(const uint8_t *)sig);
  183. }
  184. break;
  185. }
  186. return false;
  187. }
  188. /**
  189. * Shortcut method to perform key agreement with another identity
  190. *
  191. * This identity must have a private key. (Check hasPrivate())
  192. *
  193. * @param id Identity to agree with
  194. * @param key Result parameter to fill with key bytes
  195. * @return Was agreement successful?
  196. */
  197. inline bool agree(const Identity &id,uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) const
  198. {
  199. uint8_t rawkey[128];
  200. uint8_t h[64];
  201. if (_hasPrivate) {
  202. if (_type == C25519) {
  203. if ((id._type == C25519)||(id._type == P384)) {
  204. // If we are a C25519 key we can agree with another C25519 key or with only the
  205. // C25519 portion of a type 1 P-384 key.
  206. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  207. SHA512(h,rawkey,ZT_C25519_SHARED_KEY_LEN);
  208. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  209. return true;
  210. }
  211. } else if (_type == P384) {
  212. if (id._type == P384) {
  213. // Perform key agreement over both curves for the same reason that C25519 public
  214. // keys are included in P-384 signature inputs: to bind the keys together so
  215. // that a type 1 identity with the same C25519 public key (and therefore address)
  216. // but a different P-384 key will not work.
  217. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  218. ECC384ECDH(id._pub.p384,_priv.p384,rawkey + ZT_C25519_SHARED_KEY_LEN);
  219. SHA384(h,rawkey,ZT_C25519_SHARED_KEY_LEN + ZT_ECC384_SHARED_SECRET_SIZE);
  220. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  221. return true;
  222. } else if (id._type == C25519) {
  223. // If the other identity is a C25519 identity we can agree using only that type.
  224. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  225. SHA512(h,rawkey,ZT_C25519_SHARED_KEY_LEN);
  226. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  227. return true;
  228. }
  229. }
  230. }
  231. return false;
  232. }
  233. /**
  234. * @return This identity's address
  235. */
  236. ZT_ALWAYS_INLINE const Address &address() const { return _address; }
  237. /**
  238. * Serialize this identity (binary)
  239. *
  240. * @param b Destination buffer to append to
  241. * @param includePrivate If true, include private key component (if present) (default: false)
  242. * @throws std::out_of_range Buffer too small
  243. */
  244. template<unsigned int C>
  245. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  246. {
  247. _address.appendTo(b);
  248. switch(_type) {
  249. case C25519:
  250. b.append((uint8_t)C25519);
  251. b.append(_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  252. if ((_hasPrivate)&&(includePrivate)) {
  253. b.append((uint8_t)ZT_C25519_PRIVATE_KEY_LEN);
  254. b.append(_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  255. } else {
  256. b.append((uint8_t)0);
  257. }
  258. break;
  259. case P384:
  260. b.append((uint8_t)P384);
  261. b.append(_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  262. b.append(_pub.p384,ZT_ECC384_PUBLIC_KEY_SIZE);
  263. if ((_hasPrivate)&&(includePrivate)) {
  264. b.append((uint8_t)(ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE));
  265. b.append(_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  266. b.append(_priv.p384,ZT_ECC384_PRIVATE_KEY_SIZE);
  267. } else {
  268. b.append((uint8_t)0);
  269. }
  270. break;
  271. }
  272. }
  273. /**
  274. * Deserialize a binary serialized identity
  275. *
  276. * If an exception is thrown, the Identity object is left in an undefined
  277. * state and should not be used.
  278. *
  279. * @param b Buffer containing serialized data
  280. * @param startAt Index within buffer of serialized data (default: 0)
  281. * @return Length of serialized data read from buffer
  282. * @throws std::out_of_range Serialized data invalid
  283. * @throws std::invalid_argument Serialized data invalid
  284. */
  285. template<unsigned int C>
  286. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  287. {
  288. _hasPrivate = false;
  289. unsigned int p = startAt;
  290. unsigned int pkl;
  291. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  292. p += ZT_ADDRESS_LENGTH;
  293. switch((_type = (Type)b[p++])) {
  294. case C25519:
  295. memcpy(_pub.c25519,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  296. p += ZT_C25519_PUBLIC_KEY_LEN;
  297. pkl = (unsigned int)b[p++];
  298. if (pkl) {
  299. if (pkl != ZT_C25519_PRIVATE_KEY_LEN)
  300. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  301. _hasPrivate = true;
  302. memcpy(_priv.c25519,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  303. p += ZT_C25519_PRIVATE_KEY_LEN;
  304. } else {
  305. _hasPrivate = false;
  306. }
  307. break;
  308. case P384:
  309. memcpy(_pub.c25519,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  310. p += ZT_C25519_PUBLIC_KEY_LEN;
  311. memcpy(_pub.p384,b.field(p,ZT_ECC384_PUBLIC_KEY_SIZE),ZT_ECC384_PUBLIC_KEY_SIZE);
  312. p += ZT_ECC384_PUBLIC_KEY_SIZE;
  313. pkl = (unsigned int)b[p++];
  314. if (pkl) {
  315. if (pkl != (ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE))
  316. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  317. _hasPrivate = true;
  318. memcpy(_priv.c25519,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  319. p += ZT_C25519_PRIVATE_KEY_LEN;
  320. memcpy(_priv.p384,b.field(p,ZT_ECC384_PRIVATE_KEY_SIZE),ZT_ECC384_PRIVATE_KEY_SIZE);
  321. p += ZT_ECC384_PRIVATE_KEY_SIZE;
  322. } else {
  323. _hasPrivate = false;
  324. }
  325. break;
  326. default:
  327. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  328. }
  329. return (p - startAt);
  330. }
  331. /**
  332. * Serialize to a more human-friendly string
  333. *
  334. * @param includePrivate If true, include private key (if it exists)
  335. * @param buf Buffer to store string
  336. * @return ASCII string representation of identity
  337. */
  338. char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
  339. /**
  340. * Deserialize a human-friendly string
  341. *
  342. * Note: validation is for the format only. The locallyValidate() method
  343. * must be used to check signature and address/key correspondence.
  344. *
  345. * @param str String to deserialize
  346. * @return True if deserialization appears successful
  347. */
  348. bool fromString(const char *str);
  349. /**
  350. * @return True if this identity contains something
  351. */
  352. ZT_ALWAYS_INLINE operator bool() const { return (_address); }
  353. inline bool operator==(const Identity &id) const
  354. {
  355. if ((_address == id._address)&&(_type == id._type)) {
  356. switch(_type) {
  357. case C25519:
  358. return (memcmp(_pub.c25519,id._pub.c25519,ZT_C25519_PUBLIC_KEY_LEN) == 0);
  359. case P384:
  360. return (memcmp(&_pub,&id._pub,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE) == 0);
  361. default:
  362. return false;
  363. }
  364. }
  365. return false;
  366. }
  367. inline bool operator<(const Identity &id) const
  368. {
  369. if (_address < id._address)
  370. return true;
  371. if (_address == id._address) {
  372. if ((int)_type < (int)id._type)
  373. return true;
  374. if (_type == id._type) {
  375. switch(_type) {
  376. case C25519:
  377. return (memcmp(_pub.c25519,id._pub.c25519,ZT_C25519_PUBLIC_KEY_LEN) < 0);
  378. case P384:
  379. return (memcmp(&_pub,&id._pub,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE) < 0);
  380. }
  381. }
  382. }
  383. return false;
  384. }
  385. ZT_ALWAYS_INLINE bool operator!=(const Identity &id) const { return !(*this == id); }
  386. ZT_ALWAYS_INLINE bool operator>(const Identity &id) const { return (id < *this); }
  387. ZT_ALWAYS_INLINE bool operator<=(const Identity &id) const { return !(id < *this); }
  388. ZT_ALWAYS_INLINE bool operator>=(const Identity &id) const { return !(*this < id); }
  389. ZT_ALWAYS_INLINE unsigned long hashCode() const { return ((unsigned long)(_address.toInt() << 8) + (unsigned long)_pub.c25519[0] + (unsigned long)_pub.c25519[1] + (unsigned long)_pub.c25519[2]); }
  390. private:
  391. Address _address;
  392. Type _type;
  393. bool _hasPrivate;
  394. ZT_PACKED_STRUCT(struct { // don't re-order these
  395. uint8_t c25519[ZT_C25519_PRIVATE_KEY_LEN];
  396. uint8_t p384[ZT_ECC384_PRIVATE_KEY_SIZE];
  397. }) _priv;
  398. ZT_PACKED_STRUCT(struct { // don't re-order these
  399. uint8_t c25519[ZT_C25519_PUBLIC_KEY_LEN];
  400. uint8_t p384[ZT_ECC384_PUBLIC_KEY_SIZE];
  401. }) _pub;
  402. };
  403. } // namespace ZeroTier
  404. #endif