Identity.hpp 14 KB

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