Identity.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. inline Identity() { memset(reinterpret_cast<void *>(this),0,sizeof(Identity)); }
  48. 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. inline ~Identity() { Utils::burn(reinterpret_cast<void *>(this),sizeof(Identity)); }
  57. /**
  58. * Set identity to NIL value (all zero)
  59. */
  60. inline void zero() { Utils::burn(reinterpret_cast<void *>(this),sizeof(Identity)); }
  61. 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. 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. 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. uint8_t h[48 + ZT_C25519_PUBLIC_KEY_LEN];
  145. if (!_hasPrivate)
  146. return 0;
  147. switch(_type) {
  148. case C25519:
  149. if (siglen < ZT_C25519_SIGNATURE_LEN)
  150. return 0;
  151. C25519::sign(_priv.c25519,_pub.c25519,data,len,sig);
  152. return ZT_C25519_SIGNATURE_LEN;
  153. case P384:
  154. if (siglen < ZT_ECC384_SIGNATURE_SIZE)
  155. return 0;
  156. // Include C25519 public key in input for P-384 signature so the two keys are "bound
  157. // together" and cannot be decoupled in the same identity. An identity can have the
  158. // same C25519 key but a different P-384 key and have the same address, but this
  159. // means its signatures and key agreements will be different.
  160. SHA384(h,data,len);
  161. memcpy(h + 48,_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  162. SHA384(h,h,48 + ZT_C25519_PUBLIC_KEY_LEN);
  163. ECC384ECDSASign(_priv.p384,h,(uint8_t *)sig);
  164. return ZT_ECC384_SIGNATURE_SIZE;
  165. }
  166. return 0;
  167. }
  168. /**
  169. * Verify a message signature against this identity
  170. *
  171. * @param data Data to check
  172. * @param len Length of data
  173. * @param signature Signature bytes
  174. * @param siglen Length of signature in bytes
  175. * @return True if signature validates and data integrity checks
  176. */
  177. inline bool verify(const void *data,unsigned int len,const void *sig,unsigned int siglen) const
  178. {
  179. switch(_type) {
  180. case C25519:
  181. return C25519::verify(_pub.c25519,data,len,sig,siglen);
  182. case P384:
  183. if (siglen == ZT_ECC384_SIGNATURE_SIZE) {
  184. uint8_t h[48 + ZT_C25519_PUBLIC_KEY_LEN];
  185. SHA384(h,data,len);
  186. memcpy(h + 48,_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  187. SHA384(h,h,48 + ZT_C25519_PUBLIC_KEY_LEN);
  188. return ECC384ECDSAVerify(_pub.p384,h,(const uint8_t *)sig);
  189. }
  190. break;
  191. }
  192. return false;
  193. }
  194. /**
  195. * Shortcut method to perform key agreement with another identity
  196. *
  197. * This identity must have a private key. (Check hasPrivate())
  198. *
  199. * @param id Identity to agree with
  200. * @param key Result parameter to fill with key bytes
  201. * @return Was agreement successful?
  202. */
  203. inline bool agree(const Identity &id,uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) const
  204. {
  205. uint8_t rawkey[128];
  206. uint8_t h[64];
  207. if (_hasPrivate) {
  208. if (_type == C25519) {
  209. if ((id._type == C25519)||(id._type == P384)) {
  210. // If we are a C25519 key we can agree with another C25519 key or with only the
  211. // C25519 portion of a type 1 P-384 key.
  212. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  213. SHA512(h,rawkey,ZT_C25519_SHARED_KEY_LEN);
  214. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  215. return true;
  216. }
  217. } else if (_type == P384) {
  218. if (id._type == P384) {
  219. // Perform key agreement over both curves for the same reason that C25519 public
  220. // keys are included in P-384 signature inputs: to bind the keys together so
  221. // that a type 1 identity with the same C25519 public key (and therefore address)
  222. // but a different P-384 key will not work.
  223. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  224. ECC384ECDH(id._pub.p384,_priv.p384,rawkey + ZT_C25519_SHARED_KEY_LEN);
  225. SHA384(h,rawkey,ZT_C25519_SHARED_KEY_LEN + ZT_ECC384_SHARED_SECRET_SIZE);
  226. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  227. return true;
  228. } else if (id._type == C25519) {
  229. // If the other identity is a C25519 identity we can agree using only that type.
  230. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  231. SHA512(h,rawkey,ZT_C25519_SHARED_KEY_LEN);
  232. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  233. return true;
  234. }
  235. }
  236. }
  237. return false;
  238. }
  239. /**
  240. * @return This identity's address
  241. */
  242. inline const Address &address() const { return _address; }
  243. /**
  244. * Serialize this identity (binary)
  245. *
  246. * @param b Destination buffer to append to
  247. * @param includePrivate If true, include private key component (if present) (default: false)
  248. * @throws std::out_of_range Buffer too small
  249. */
  250. template<unsigned int C>
  251. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  252. {
  253. _address.appendTo(b);
  254. switch(_type) {
  255. case C25519:
  256. b.append((uint8_t)C25519);
  257. b.append(_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  258. if ((_hasPrivate)&&(includePrivate)) {
  259. b.append((uint8_t)ZT_C25519_PRIVATE_KEY_LEN);
  260. b.append(_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  261. } else {
  262. b.append((uint8_t)0);
  263. }
  264. break;
  265. case P384:
  266. b.append((uint8_t)P384);
  267. b.append(_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  268. b.append(_pub.p384,ZT_ECC384_PUBLIC_KEY_SIZE);
  269. if ((_hasPrivate)&&(includePrivate)) {
  270. b.append((uint8_t)(ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE));
  271. b.append(_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  272. b.append(_priv.p384,ZT_ECC384_PRIVATE_KEY_SIZE);
  273. } else {
  274. b.append((uint8_t)0);
  275. }
  276. break;
  277. }
  278. }
  279. /**
  280. * Deserialize a binary serialized identity
  281. *
  282. * If an exception is thrown, the Identity object is left in an undefined
  283. * state and should not be used.
  284. *
  285. * @param b Buffer containing serialized data
  286. * @param startAt Index within buffer of serialized data (default: 0)
  287. * @return Length of serialized data read from buffer
  288. * @throws std::out_of_range Serialized data invalid
  289. * @throws std::invalid_argument Serialized data invalid
  290. */
  291. template<unsigned int C>
  292. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  293. {
  294. _hasPrivate = false;
  295. unsigned int p = startAt;
  296. unsigned int pkl;
  297. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  298. p += ZT_ADDRESS_LENGTH;
  299. switch((_type = (Type)b[p++])) {
  300. case C25519:
  301. memcpy(_pub.c25519,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  302. p += ZT_C25519_PUBLIC_KEY_LEN;
  303. pkl = (unsigned int)b[p++];
  304. if (pkl) {
  305. if (pkl != ZT_C25519_PRIVATE_KEY_LEN)
  306. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  307. _hasPrivate = true;
  308. memcpy(_priv.c25519,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  309. p += ZT_C25519_PRIVATE_KEY_LEN;
  310. } else {
  311. _hasPrivate = false;
  312. }
  313. break;
  314. case P384:
  315. memcpy(_pub.c25519,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  316. p += ZT_C25519_PUBLIC_KEY_LEN;
  317. memcpy(_pub.p384,b.field(p,ZT_ECC384_PUBLIC_KEY_SIZE),ZT_ECC384_PUBLIC_KEY_SIZE);
  318. p += ZT_ECC384_PUBLIC_KEY_SIZE;
  319. pkl = (unsigned int)b[p++];
  320. if (pkl) {
  321. if (pkl != (ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE))
  322. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  323. _hasPrivate = true;
  324. memcpy(_priv.c25519,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  325. p += ZT_C25519_PRIVATE_KEY_LEN;
  326. memcpy(_priv.p384,b.field(p,ZT_ECC384_PRIVATE_KEY_SIZE),ZT_ECC384_PRIVATE_KEY_SIZE);
  327. p += ZT_ECC384_PRIVATE_KEY_SIZE;
  328. } else {
  329. _hasPrivate = false;
  330. }
  331. break;
  332. default:
  333. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  334. }
  335. return (p - startAt);
  336. }
  337. /**
  338. * Serialize to a more human-friendly string
  339. *
  340. * @param includePrivate If true, include private key (if it exists)
  341. * @param buf Buffer to store string
  342. * @return ASCII string representation of identity
  343. */
  344. char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
  345. /**
  346. * Deserialize a human-friendly string
  347. *
  348. * Note: validation is for the format only. The locallyValidate() method
  349. * must be used to check signature and address/key correspondence.
  350. *
  351. * @param str String to deserialize
  352. * @return True if deserialization appears successful
  353. */
  354. bool fromString(const char *str);
  355. /**
  356. * @return True if this identity contains something
  357. */
  358. inline operator bool() const { return (_address); }
  359. inline bool operator==(const Identity &id) const
  360. {
  361. if ((_address == id._address)&&(_type == id._type)) {
  362. switch(_type) {
  363. case C25519:
  364. return (memcmp(_pub.c25519,id._pub.c25519,ZT_C25519_PUBLIC_KEY_LEN) == 0);
  365. case P384:
  366. return (memcmp(&_pub,&id._pub,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE) == 0);
  367. default:
  368. return false;
  369. }
  370. }
  371. return false;
  372. }
  373. inline bool operator<(const Identity &id) const
  374. {
  375. if (_address < id._address)
  376. return true;
  377. if (_address == id._address) {
  378. if ((int)_type < (int)id._type)
  379. return true;
  380. if (_type == id._type) {
  381. switch(_type) {
  382. case C25519:
  383. return (memcmp(_pub.c25519,id._pub.c25519,ZT_C25519_PUBLIC_KEY_LEN) < 0);
  384. case P384:
  385. return (memcmp(&_pub,&id._pub,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE) < 0);
  386. }
  387. }
  388. }
  389. return false;
  390. }
  391. inline bool operator!=(const Identity &id) const { return !(*this == id); }
  392. inline bool operator>(const Identity &id) const { return (id < *this); }
  393. inline bool operator<=(const Identity &id) const { return !(id < *this); }
  394. inline bool operator>=(const Identity &id) const { return !(*this < id); }
  395. inline unsigned long hashCode() const { return (unsigned long)_address.toInt(); }
  396. private:
  397. Address _address;
  398. Type _type;
  399. bool _hasPrivate;
  400. ZT_PACKED_STRUCT(struct { // don't re-order these
  401. uint8_t c25519[ZT_C25519_PRIVATE_KEY_LEN];
  402. uint8_t p384[ZT_ECC384_PRIVATE_KEY_SIZE];
  403. }) _priv;
  404. ZT_PACKED_STRUCT(struct { // don't re-order these
  405. uint8_t c25519[ZT_C25519_PUBLIC_KEY_LEN];
  406. uint8_t p384[ZT_ECC384_PUBLIC_KEY_SIZE];
  407. }) _pub;
  408. };
  409. } // namespace ZeroTier
  410. #endif