Identity.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_IDENTITY_HPP
  27. #define ZT_IDENTITY_HPP
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include "Constants.hpp"
  31. #include "Utils.hpp"
  32. #include "Address.hpp"
  33. #include "C25519.hpp"
  34. #include "Buffer.hpp"
  35. #include "SHA512.hpp"
  36. #include "ECC384.hpp"
  37. #define ZT_IDENTITY_STRING_BUFFER_LENGTH 512
  38. namespace ZeroTier {
  39. /**
  40. * A ZeroTier identity
  41. *
  42. * An identity consists of a public key, a 40-bit ZeroTier address computed
  43. * from that key in a collision-resistant fashion, and a self-signature.
  44. *
  45. * The address derivation algorithm makes it computationally very expensive to
  46. * search for a different public key that duplicates an existing address. (See
  47. * code for deriveAddress() for this algorithm.)
  48. */
  49. class Identity
  50. {
  51. public:
  52. /**
  53. * Identity type -- numeric values of these enums are protocol constants
  54. */
  55. enum Type
  56. {
  57. C25519 = ZT_CRYPTO_ALG_C25519, // Type 0 -- Curve25519 and Ed25519 (1.x and 2.x, default)
  58. P384 = ZT_CRYPTO_ALG_P384 // Type 1 -- NIST P-384 with linked Curve25519 and Ed25519 secondaries (2.x+)
  59. };
  60. inline Identity() { memset(reinterpret_cast<void *>(this),0,sizeof(Identity)); }
  61. inline Identity(const Identity &id) { memcpy(reinterpret_cast<void *>(this),&id,sizeof(Identity)); }
  62. inline Identity(const char *str)
  63. {
  64. if (!fromString(str))
  65. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  66. }
  67. template<unsigned int C>
  68. inline Identity(const Buffer<C> &b,unsigned int startAt = 0) { deserialize(b,startAt); }
  69. inline ~Identity() { Utils::burn(reinterpret_cast<void *>(this),sizeof(Identity)); }
  70. /**
  71. * Set identity to NIL value (all zero)
  72. */
  73. inline void zero() { Utils::burn(reinterpret_cast<void *>(this),sizeof(Identity)); }
  74. inline Identity &operator=(const Identity &id)
  75. {
  76. memcpy(reinterpret_cast<void *>(this),&id,sizeof(Identity));
  77. return *this;
  78. }
  79. /**
  80. * @return Identity type
  81. */
  82. inline Type type() const { return _type; }
  83. /**
  84. * Generate a new identity (address, key pair)
  85. *
  86. * This is a time consuming operation.
  87. *
  88. * @param t Type of identity to generate
  89. */
  90. void generate(const Type t);
  91. /**
  92. * Check the validity of this identity's pairing of key to address
  93. *
  94. * @return True if validation check passes
  95. */
  96. bool locallyValidate() const;
  97. /**
  98. * @return True if this identity contains a private key
  99. */
  100. inline bool hasPrivate() const { return _hasPrivate; }
  101. /**
  102. * Compute the SHA512 hash of our private key (if we have one)
  103. *
  104. * @param sha Buffer to receive SHA512 (MUST be ZT_SHA512_DIGEST_LEN (64) bytes in length)
  105. * @return True on success, false if no private key
  106. */
  107. inline bool sha512PrivateKey(void *const sha) const
  108. {
  109. if (_hasPrivate) {
  110. switch(_type) {
  111. case C25519:
  112. SHA512(sha,_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  113. return true;
  114. case P384:
  115. SHA512(sha,&_priv,ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE);
  116. return true;
  117. }
  118. }
  119. return false;
  120. }
  121. /**
  122. * Compute a 128-bit short hash of this identity's public key
  123. *
  124. * This is the first 128 bits of a SHA384 hash and is the hash used
  125. * in VERB_WILL_RELAY to report reachability.
  126. *
  127. * @param h 128-bit buffer to receive hash (must be 16 bytes in size)
  128. */
  129. inline void publicKeyHash128(void *const h) const
  130. {
  131. uint8_t tmp[48];
  132. switch(_type) {
  133. case C25519:
  134. SHA384(tmp,_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  135. break;
  136. case P384:
  137. SHA384(tmp,&_pub,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE);
  138. break;
  139. }
  140. for(int i=0;i<16;++i)
  141. ((uint8_t *)h)[i] = tmp[i];
  142. }
  143. /**
  144. * Sign a message with this identity (private key required)
  145. *
  146. * The signature buffer should be large enough for the largest
  147. * signature, which is currently 96 bytes.
  148. *
  149. * @param data Data to sign
  150. * @param len Length of data
  151. * @param sig Buffer to receive signature
  152. * @param siglen Length of buffer
  153. * @return Number of bytes actually written to sig or 0 on error
  154. */
  155. inline unsigned int sign(const void *data,unsigned int len,void *sig,unsigned int siglen) const
  156. {
  157. uint8_t h[48 + ZT_C25519_PUBLIC_KEY_LEN];
  158. if (!_hasPrivate)
  159. return 0;
  160. switch(_type) {
  161. case C25519:
  162. if (siglen < ZT_C25519_SIGNATURE_LEN)
  163. return 0;
  164. C25519::sign(_priv.c25519,_pub.c25519,data,len,sig);
  165. return ZT_C25519_SIGNATURE_LEN;
  166. case P384:
  167. if (siglen < ZT_ECC384_SIGNATURE_SIZE)
  168. return 0;
  169. // Include C25519 public key in input for P-384 signature so the two keys are "bound
  170. // together" and cannot be decoupled in the same identity. An identity can have the
  171. // same C25519 key but a different P-384 key and have the same address, but this
  172. // means its signatures and key agreements will be different.
  173. SHA384(h,data,len);
  174. memcpy(h + 48,_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  175. SHA384(h,h,48 + ZT_C25519_PUBLIC_KEY_LEN);
  176. ECC384ECDSASign(_priv.p384,h,(uint8_t *)sig);
  177. return ZT_ECC384_SIGNATURE_SIZE;
  178. }
  179. return 0;
  180. }
  181. /**
  182. * Verify a message signature against this identity
  183. *
  184. * @param data Data to check
  185. * @param len Length of data
  186. * @param signature Signature bytes
  187. * @param siglen Length of signature in bytes
  188. * @return True if signature validates and data integrity checks
  189. */
  190. inline bool verify(const void *data,unsigned int len,const void *sig,unsigned int siglen) const
  191. {
  192. switch(_type) {
  193. case C25519:
  194. return C25519::verify(_pub.c25519,data,len,sig,siglen);
  195. case P384:
  196. if (siglen == ZT_ECC384_SIGNATURE_SIZE) {
  197. uint8_t h[48 + ZT_C25519_PUBLIC_KEY_LEN];
  198. SHA384(h,data,len);
  199. memcpy(h + 48,_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  200. SHA384(h,h,48 + ZT_C25519_PUBLIC_KEY_LEN);
  201. return ECC384ECDSAVerify(_pub.p384,h,(const uint8_t *)sig);
  202. }
  203. break;
  204. }
  205. return false;
  206. }
  207. /**
  208. * Shortcut method to perform key agreement with another identity
  209. *
  210. * This identity must have a private key. (Check hasPrivate())
  211. *
  212. * @param id Identity to agree with
  213. * @param key Result parameter to fill with key bytes
  214. * @return Was agreement successful?
  215. */
  216. inline bool agree(const Identity &id,uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]) const
  217. {
  218. uint8_t rawkey[128];
  219. uint8_t h[64];
  220. if (_hasPrivate) {
  221. if (_type == C25519) {
  222. if ((id._type == C25519)||(id._type == P384)) {
  223. // If we are a C25519 key we can agree with another C25519 key or with only the
  224. // C25519 portion of a type 1 P-384 key.
  225. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  226. SHA512(h,rawkey,ZT_C25519_SHARED_KEY_LEN);
  227. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  228. return true;
  229. }
  230. } else if (_type == P384) {
  231. if (id._type == P384) {
  232. // Perform key agreement over both curves for the same reason that C25519 public
  233. // keys are included in P-384 signature inputs: to bind the keys together so
  234. // that a type 1 identity with the same C25519 public key (and therefore address)
  235. // but a different P-384 key will not work.
  236. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  237. ECC384ECDH(id._pub.p384,_priv.p384,rawkey + ZT_C25519_SHARED_KEY_LEN);
  238. SHA384(h,rawkey,ZT_C25519_SHARED_KEY_LEN + ZT_ECC384_SHARED_SECRET_SIZE);
  239. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  240. return true;
  241. } else if (id._type == C25519) {
  242. // If the other identity is a C25519 identity we can agree using only that type.
  243. C25519::agree(_priv.c25519,id._pub.c25519,rawkey);
  244. SHA512(h,rawkey,ZT_C25519_SHARED_KEY_LEN);
  245. memcpy(key,h,ZT_PEER_SECRET_KEY_LENGTH);
  246. return true;
  247. }
  248. }
  249. }
  250. return false;
  251. }
  252. /**
  253. * @return This identity's address
  254. */
  255. inline const Address &address() const { return _address; }
  256. /**
  257. * Serialize this identity (binary)
  258. *
  259. * @param b Destination buffer to append to
  260. * @param includePrivate If true, include private key component (if present) (default: false)
  261. * @throws std::out_of_range Buffer too small
  262. */
  263. template<unsigned int C>
  264. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  265. {
  266. _address.appendTo(b);
  267. switch(_type) {
  268. case C25519:
  269. b.append((uint8_t)C25519);
  270. b.append(_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  271. if ((_hasPrivate)&&(includePrivate)) {
  272. b.append((uint8_t)ZT_C25519_PRIVATE_KEY_LEN);
  273. b.append(_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  274. } else {
  275. b.append((uint8_t)0);
  276. }
  277. break;
  278. case P384:
  279. b.append((uint8_t)P384);
  280. b.append(_pub.c25519,ZT_C25519_PUBLIC_KEY_LEN);
  281. b.append(_pub.p384,ZT_ECC384_PUBLIC_KEY_SIZE);
  282. if ((_hasPrivate)&&(includePrivate)) {
  283. b.append((uint8_t)(ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE));
  284. b.append(_priv.c25519,ZT_C25519_PRIVATE_KEY_LEN);
  285. b.append(_priv.p384,ZT_ECC384_PRIVATE_KEY_SIZE);
  286. } else {
  287. b.append((uint8_t)0);
  288. }
  289. break;
  290. }
  291. }
  292. /**
  293. * Deserialize a binary serialized identity
  294. *
  295. * If an exception is thrown, the Identity object is left in an undefined
  296. * state and should not be used.
  297. *
  298. * @param b Buffer containing serialized data
  299. * @param startAt Index within buffer of serialized data (default: 0)
  300. * @return Length of serialized data read from buffer
  301. * @throws std::out_of_range Serialized data invalid
  302. * @throws std::invalid_argument Serialized data invalid
  303. */
  304. template<unsigned int C>
  305. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  306. {
  307. _hasPrivate = false;
  308. unsigned int p = startAt;
  309. unsigned int pkl;
  310. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  311. p += ZT_ADDRESS_LENGTH;
  312. switch((_type = (Type)b[p++])) {
  313. case C25519:
  314. memcpy(_pub.c25519,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  315. p += ZT_C25519_PUBLIC_KEY_LEN;
  316. pkl = (unsigned int)b[p++];
  317. if (pkl) {
  318. if (pkl != ZT_C25519_PRIVATE_KEY_LEN)
  319. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  320. _hasPrivate = true;
  321. memcpy(_priv.c25519,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  322. p += ZT_C25519_PRIVATE_KEY_LEN;
  323. } else {
  324. _hasPrivate = false;
  325. }
  326. break;
  327. case P384:
  328. memcpy(_pub.c25519,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  329. p += ZT_C25519_PUBLIC_KEY_LEN;
  330. memcpy(_pub.p384,b.field(p,ZT_ECC384_PUBLIC_KEY_SIZE),ZT_ECC384_PUBLIC_KEY_SIZE);
  331. p += ZT_ECC384_PUBLIC_KEY_SIZE;
  332. pkl = (unsigned int)b[p++];
  333. if (pkl) {
  334. if (pkl != (ZT_C25519_PRIVATE_KEY_LEN + ZT_ECC384_PRIVATE_KEY_SIZE))
  335. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  336. _hasPrivate = true;
  337. memcpy(_priv.c25519,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  338. p += ZT_C25519_PRIVATE_KEY_LEN;
  339. memcpy(_priv.p384,b.field(p,ZT_ECC384_PRIVATE_KEY_SIZE),ZT_ECC384_PRIVATE_KEY_SIZE);
  340. p += ZT_ECC384_PRIVATE_KEY_SIZE;
  341. } else {
  342. _hasPrivate = false;
  343. }
  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. inline operator bool() const { return (_address); }
  372. 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,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE) == 0);
  380. default:
  381. return false;
  382. }
  383. }
  384. return false;
  385. }
  386. 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,ZT_C25519_PUBLIC_KEY_LEN + ZT_ECC384_PUBLIC_KEY_SIZE) < 0);
  399. }
  400. }
  401. }
  402. return false;
  403. }
  404. inline bool operator!=(const Identity &id) const { return !(*this == id); }
  405. inline bool operator>(const Identity &id) const { return (id < *this); }
  406. inline bool operator<=(const Identity &id) const { return !(id < *this); }
  407. inline bool operator>=(const Identity &id) const { return !(*this < id); }
  408. inline unsigned long hashCode() const { return (unsigned long)_address.toInt(); }
  409. private:
  410. Address _address;
  411. Type _type;
  412. bool _hasPrivate;
  413. ZT_PACKED_STRUCT(struct { // don't re-order these
  414. uint8_t c25519[ZT_C25519_PRIVATE_KEY_LEN];
  415. uint8_t p384[ZT_ECC384_PRIVATE_KEY_SIZE];
  416. }) _priv;
  417. ZT_PACKED_STRUCT(struct { // don't re-order these
  418. uint8_t c25519[ZT_C25519_PUBLIC_KEY_LEN];
  419. uint8_t p384[ZT_ECC384_PUBLIC_KEY_SIZE];
  420. }) _pub;
  421. };
  422. } // namespace ZeroTier
  423. #endif