Identity.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 384
  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.0 and 2.0, default)
  58. P384 = ZT_CRYPTO_ALG_P384 // Type 1 -- NIST P-384 ECDH and ECDSA (2.0+ only)
  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. inline void zero() { Utils::burn(reinterpret_cast<void *>(this),sizeof(Identity)); }
  71. inline Identity &operator=(const Identity &id)
  72. {
  73. memcpy(reinterpret_cast<void *>(this),&id,sizeof(Identity));
  74. return *this;
  75. }
  76. /**
  77. * @return Identity type
  78. */
  79. inline Type type() const { return _type; }
  80. /**
  81. * Generate a new identity (address, key pair)
  82. *
  83. * This is a time consuming operation.
  84. *
  85. * @param t Type of identity to generate
  86. */
  87. void generate(const Type t);
  88. /**
  89. * Check the validity of this identity's pairing of key to address
  90. *
  91. * @return True if validation check passes
  92. */
  93. bool locallyValidate() const;
  94. /**
  95. * @return True if this identity contains a private key
  96. */
  97. inline bool hasPrivate() const { return _hasPrivate; }
  98. /**
  99. * Compute the SHA512 hash of our private key (if we have one)
  100. *
  101. * @param sha Buffer to receive SHA512 (MUST be ZT_SHA512_DIGEST_LEN (64) bytes in length)
  102. * @return True on success, false if no private key
  103. */
  104. inline bool sha512PrivateKey(void *sha) const
  105. {
  106. if (_hasPrivate) {
  107. switch(_type) {
  108. case C25519:
  109. SHA512(sha,_k.t0.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  110. return true;
  111. case P384:
  112. SHA512(sha,_k.t1.priv,ZT_ECC384_PRIVATE_KEY_SIZE);
  113. return true;
  114. }
  115. }
  116. return false;
  117. }
  118. /**
  119. * Compute the SHA512 hash of our public key
  120. *
  121. * @param sha Buffer to receive hash bytes
  122. * @return True on success, false if identity is empty or invalid
  123. */
  124. inline bool sha512PublicKey(void *sha) const
  125. {
  126. if (_hasPrivate) {
  127. switch(_type) {
  128. case C25519:
  129. SHA512(sha,_k.t0.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  130. return true;
  131. case P384:
  132. SHA512(sha,_k.t1.pub,ZT_ECC384_PUBLIC_KEY_SIZE);
  133. return true;
  134. }
  135. }
  136. return false;
  137. }
  138. /**
  139. * Sign a message with this identity (private key required)
  140. *
  141. * The signature buffer should be large enough for the largest
  142. * signature, which is currently 96 bytes.
  143. *
  144. * @param data Data to sign
  145. * @param len Length of data
  146. * @param sig Buffer to receive signature
  147. * @param siglen Length of buffer
  148. * @return Number of bytes actually written to sig or 0 on error
  149. */
  150. inline unsigned int sign(const void *data,unsigned int len,void *sig,unsigned int siglen) const
  151. {
  152. uint8_t h[48];
  153. if (!_hasPrivate)
  154. return 0;
  155. switch(_type) {
  156. case C25519:
  157. if (siglen < ZT_C25519_SIGNATURE_LEN)
  158. return 0;
  159. C25519::sign(_k.t0.priv,_k.t0.pub,data,len,sig);
  160. return ZT_C25519_SIGNATURE_LEN;
  161. case P384:
  162. if (siglen < ZT_ECC384_SIGNATURE_SIZE)
  163. return 0;
  164. SHA384(h,data,len);
  165. ECC384ECDSASign(_k.t1.priv,h,(uint8_t *)sig);
  166. return ZT_ECC384_SIGNATURE_SIZE;
  167. }
  168. return 0;
  169. }
  170. /**
  171. * Verify a message signature against this identity
  172. *
  173. * @param data Data to check
  174. * @param len Length of data
  175. * @param signature Signature bytes
  176. * @param siglen Length of signature in bytes
  177. * @return True if signature validates and data integrity checks
  178. */
  179. inline bool verify(const void *data,unsigned int len,const void *sig,unsigned int siglen) const
  180. {
  181. switch(_type) {
  182. case C25519:
  183. return C25519::verify(_k.t0.pub,data,len,sig,siglen);
  184. case P384:
  185. if (siglen == ZT_ECC384_SIGNATURE_SIZE) {
  186. uint8_t h[48];
  187. SHA384(h,data,len);
  188. return ECC384ECDSAVerify(_k.t1.pub,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. * @param klen Length of key in bytes
  202. * @return Was agreement successful?
  203. */
  204. inline bool agree(const Identity &id,void *key,unsigned int klen) const
  205. {
  206. uint8_t ecc384RawSecret[ZT_ECC384_SHARED_SECRET_SIZE];
  207. uint8_t h[48];
  208. if (_hasPrivate) {
  209. switch(_type) {
  210. case C25519:
  211. C25519::agree(_k.t0.priv,id._k.t0.pub,key,klen);
  212. return true;
  213. case P384:
  214. ECC384ECDH(id._k.t1.pub,_k.t1.priv,ecc384RawSecret);
  215. SHA384(h,ecc384RawSecret,sizeof(ecc384RawSecret));
  216. for(unsigned int i=0,hi=0;i<klen;++i) {
  217. if (hi == 48) {
  218. hi = 0;
  219. SHA384(h,h,48);
  220. }
  221. ((uint8_t *)key)[i] = h[hi++];
  222. }
  223. return true;
  224. }
  225. }
  226. return false;
  227. }
  228. /**
  229. * @return This identity's address
  230. */
  231. inline const Address &address() const { return _address; }
  232. /**
  233. * Serialize this identity (binary)
  234. *
  235. * @param b Destination buffer to append to
  236. * @param includePrivate If true, include private key component (if present) (default: false)
  237. * @throws std::out_of_range Buffer too small
  238. */
  239. template<unsigned int C>
  240. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  241. {
  242. _address.appendTo(b);
  243. switch(_type) {
  244. case C25519:
  245. b.append((uint8_t)C25519);
  246. b.append(_k.t0.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  247. if ((_hasPrivate)&&(includePrivate)) {
  248. b.append((uint8_t)ZT_C25519_PRIVATE_KEY_LEN);
  249. b.append(_k.t0.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  250. } else {
  251. b.append((uint8_t)0);
  252. }
  253. break;
  254. case P384:
  255. b.append((uint8_t)P384);
  256. b.append(_k.t1.pub,ZT_ECC384_PUBLIC_KEY_SIZE);
  257. if ((_hasPrivate)&&(includePrivate)) {
  258. b.append((uint8_t)ZT_ECC384_PRIVATE_KEY_SIZE);
  259. b.append(_k.t1.priv,ZT_ECC384_PRIVATE_KEY_SIZE);
  260. } else {
  261. b.append((uint8_t)0);
  262. }
  263. break;
  264. }
  265. }
  266. /**
  267. * Deserialize a binary serialized identity
  268. *
  269. * If an exception is thrown, the Identity object is left in an undefined
  270. * state and should not be used.
  271. *
  272. * @param b Buffer containing serialized data
  273. * @param startAt Index within buffer of serialized data (default: 0)
  274. * @return Length of serialized data read from buffer
  275. * @throws std::out_of_range Serialized data invalid
  276. * @throws std::invalid_argument Serialized data invalid
  277. */
  278. template<unsigned int C>
  279. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  280. {
  281. _hasPrivate = false;
  282. unsigned int p = startAt;
  283. unsigned int pkl;
  284. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  285. p += ZT_ADDRESS_LENGTH;
  286. _type = (Type)b[p++];
  287. switch(_type) {
  288. case C25519:
  289. memcpy(_k.t0.pub.data,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  290. p += ZT_C25519_PUBLIC_KEY_LEN;
  291. pkl = (unsigned int)b[p++];
  292. if (pkl) {
  293. if (pkl != ZT_C25519_PRIVATE_KEY_LEN)
  294. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  295. _hasPrivate = true;
  296. memcpy(_k.t0.priv.data,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  297. p += ZT_C25519_PRIVATE_KEY_LEN;
  298. } else {
  299. memset(_k.t0.priv.data,0,ZT_C25519_PRIVATE_KEY_LEN);
  300. _hasPrivate = false;
  301. }
  302. break;
  303. case P384:
  304. memcpy(_k.t0.pub.data,b.field(p,ZT_ECC384_PUBLIC_KEY_SIZE),ZT_ECC384_PUBLIC_KEY_SIZE);
  305. p += ZT_ECC384_PUBLIC_KEY_SIZE;
  306. pkl = (unsigned int)b[p++];
  307. if (pkl) {
  308. if (pkl != ZT_ECC384_PRIVATE_KEY_SIZE)
  309. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  310. _hasPrivate = true;
  311. memcpy(_k.t1.priv,b.field(p,ZT_ECC384_PRIVATE_KEY_SIZE),ZT_ECC384_PRIVATE_KEY_SIZE);
  312. p += ZT_ECC384_PRIVATE_KEY_SIZE;
  313. } else {
  314. memset(_k.t1.priv,0,ZT_ECC384_PRIVATE_KEY_SIZE);
  315. _hasPrivate = false;
  316. }
  317. break;
  318. default:
  319. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  320. }
  321. return (p - startAt);
  322. }
  323. /**
  324. * Serialize to a more human-friendly string
  325. *
  326. * @param includePrivate If true, include private key (if it exists)
  327. * @param buf Buffer to store string
  328. * @return ASCII string representation of identity
  329. */
  330. char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
  331. /**
  332. * Deserialize a human-friendly string
  333. *
  334. * Note: validation is for the format only. The locallyValidate() method
  335. * must be used to check signature and address/key correspondence.
  336. *
  337. * @param str String to deserialize
  338. * @return True if deserialization appears successful
  339. */
  340. bool fromString(const char *str);
  341. /**
  342. * @return True if this identity contains something
  343. */
  344. inline operator bool() const { return (_address); }
  345. inline bool operator==(const Identity &id) const
  346. {
  347. if ((_address == id._address)&&(_type == id._type)) {
  348. switch(_type) {
  349. case C25519:
  350. return (memcmp(_k.t0.pub.data,id._k.t0.pub.data,ZT_C25519_PUBLIC_KEY_LEN) == 0);
  351. case P384:
  352. return (memcmp(_k.t1.pub,id._k.t1.pub,ZT_ECC384_PUBLIC_KEY_SIZE) == 0);
  353. default:
  354. return false;
  355. }
  356. }
  357. return false;
  358. }
  359. inline bool operator<(const Identity &id) const
  360. {
  361. if (_address < id._address)
  362. return true;
  363. if (_address == id._address) {
  364. if ((int)_type < (int)id._type)
  365. return true;
  366. if (_type == id._type) {
  367. switch(_type) {
  368. case C25519:
  369. return (memcmp(_k.t0.pub.data,id._k.t0.pub.data,ZT_C25519_PUBLIC_KEY_LEN) < 0);
  370. case P384:
  371. return (memcmp(_k.t1.pub,id._k.t1.pub,ZT_ECC384_PUBLIC_KEY_SIZE) < 0);
  372. }
  373. }
  374. }
  375. return false;
  376. }
  377. inline bool operator!=(const Identity &id) const { return !(*this == id); }
  378. inline bool operator>(const Identity &id) const { return (id < *this); }
  379. inline bool operator<=(const Identity &id) const { return !(id < *this); }
  380. inline bool operator>=(const Identity &id) const { return !(*this < id); }
  381. inline unsigned long hashCode() const { return (unsigned long)_address.toInt(); }
  382. private:
  383. Address _address;
  384. union {
  385. struct {
  386. C25519::Public pub;
  387. C25519::Private priv;
  388. } t0;
  389. struct {
  390. uint8_t pub[ZT_ECC384_PUBLIC_KEY_SIZE];
  391. uint8_t priv[ZT_ECC384_PRIVATE_KEY_SIZE];
  392. } t1;
  393. } _k;
  394. Type _type;
  395. bool _hasPrivate;
  396. };
  397. } // namespace ZeroTier
  398. #endif