Identity.hpp 11 KB

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