Identity.hpp 12 KB

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