Identity.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. Identity() { memset(reinterpret_cast<void *>(this),0,sizeof(Identity)); }
  61. Identity(const Identity &id) { memcpy(reinterpret_cast<void *>(this),&id,sizeof(Identity)); }
  62. 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. Identity(const Buffer<C> &b,unsigned int startAt = 0) { deserialize(b,startAt); }
  69. ~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. unsigned int sign(const void *data,unsigned int len,void *sig,unsigned int siglen) const;
  151. /**
  152. * Verify a message signature against this identity
  153. *
  154. * @param data Data to check
  155. * @param len Length of data
  156. * @param signature Signature bytes
  157. * @param siglen Length of signature in bytes
  158. * @return True if signature validates and data integrity checks
  159. */
  160. bool verify(const void *data,unsigned int len,const void *sig,unsigned int siglen) const;
  161. /**
  162. * Shortcut method to perform key agreement with another identity
  163. *
  164. * This identity must have a private key. (Check hasPrivate())
  165. *
  166. * @param id Identity to agree with
  167. * @param key Result parameter to fill with key bytes
  168. * @param klen Length of key in bytes
  169. * @return Was agreement successful?
  170. */
  171. bool agree(const Identity &id,void *key,unsigned int klen) const;
  172. /**
  173. * @return This identity's address
  174. */
  175. inline const Address &address() const { return _address; }
  176. /**
  177. * Serialize this identity (binary)
  178. *
  179. * @param b Destination buffer to append to
  180. * @param includePrivate If true, include private key component (if present) (default: false)
  181. * @throws std::out_of_range Buffer too small
  182. */
  183. template<unsigned int C>
  184. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  185. {
  186. _address.appendTo(b);
  187. switch(_type) {
  188. case C25519:
  189. b.append((uint8_t)C25519);
  190. b.append(_k.t0.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  191. if ((_hasPrivate)&&(includePrivate)) {
  192. b.append((uint8_t)ZT_C25519_PRIVATE_KEY_LEN);
  193. b.append(_k.t0.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  194. } else {
  195. b.append((uint8_t)0);
  196. }
  197. break;
  198. case P384:
  199. b.append((uint8_t)P384);
  200. b.append(_k.t1.pub,ZT_ECC384_PUBLIC_KEY_SIZE);
  201. if ((_hasPrivate)&&(includePrivate)) {
  202. b.append((uint8_t)ZT_ECC384_PRIVATE_KEY_SIZE);
  203. b.append(_k.t1.priv,ZT_ECC384_PRIVATE_KEY_SIZE);
  204. } else {
  205. b.append((uint8_t)0);
  206. }
  207. break;
  208. }
  209. }
  210. /**
  211. * Deserialize a binary serialized identity
  212. *
  213. * If an exception is thrown, the Identity object is left in an undefined
  214. * state and should not be used.
  215. *
  216. * @param b Buffer containing serialized data
  217. * @param startAt Index within buffer of serialized data (default: 0)
  218. * @return Length of serialized data read from buffer
  219. * @throws std::out_of_range Serialized data invalid
  220. * @throws std::invalid_argument Serialized data invalid
  221. */
  222. template<unsigned int C>
  223. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  224. {
  225. _hasPrivate = false;
  226. unsigned int p = startAt;
  227. unsigned int pkl;
  228. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  229. p += ZT_ADDRESS_LENGTH;
  230. _type = (Type)b[p++];
  231. switch(_type) {
  232. case C25519:
  233. memcpy(_k.t0.pub.data,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  234. p += ZT_C25519_PUBLIC_KEY_LEN;
  235. pkl = (unsigned int)b[p++];
  236. if (pkl) {
  237. if (pkl != ZT_C25519_PRIVATE_KEY_LEN)
  238. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  239. _hasPrivate = true;
  240. memcpy(_k.t0.priv.data,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  241. p += ZT_C25519_PRIVATE_KEY_LEN;
  242. } else {
  243. memset(_k.t0.priv.data,0,ZT_C25519_PRIVATE_KEY_LEN);
  244. _hasPrivate = false;
  245. }
  246. break;
  247. case P384:
  248. memcpy(_k.t0.pub.data,b.field(p,ZT_ECC384_PUBLIC_KEY_SIZE),ZT_ECC384_PUBLIC_KEY_SIZE);
  249. p += ZT_ECC384_PUBLIC_KEY_SIZE;
  250. pkl = (unsigned int)b[p++];
  251. if (pkl) {
  252. if (pkl != ZT_ECC384_PRIVATE_KEY_SIZE)
  253. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  254. _hasPrivate = true;
  255. memcpy(_k.t1.priv,b.field(p,ZT_ECC384_PRIVATE_KEY_SIZE),ZT_ECC384_PRIVATE_KEY_SIZE);
  256. p += ZT_ECC384_PRIVATE_KEY_SIZE;
  257. } else {
  258. memset(_k.t1.priv,0,ZT_ECC384_PRIVATE_KEY_SIZE);
  259. _hasPrivate = false;
  260. }
  261. break;
  262. default:
  263. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  264. }
  265. return (p - startAt);
  266. }
  267. /**
  268. * Serialize to a more human-friendly string
  269. *
  270. * @param includePrivate If true, include private key (if it exists)
  271. * @param buf Buffer to store string
  272. * @return ASCII string representation of identity
  273. */
  274. char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
  275. /**
  276. * Deserialize a human-friendly string
  277. *
  278. * Note: validation is for the format only. The locallyValidate() method
  279. * must be used to check signature and address/key correspondence.
  280. *
  281. * @param str String to deserialize
  282. * @return True if deserialization appears successful
  283. */
  284. bool fromString(const char *str);
  285. /**
  286. * @return True if this identity contains something
  287. */
  288. inline operator bool() const { return (_address); }
  289. inline bool operator==(const Identity &id) const
  290. {
  291. if ((_address == id._address)&&(_type == id._type)) {
  292. switch(_type) {
  293. case C25519:
  294. return (memcmp(_k.t0.pub.data,id._k.t0.pub.data,ZT_C25519_PUBLIC_KEY_LEN) == 0);
  295. case P384:
  296. return (memcmp(_k.t1.pub,id._k.t1.pub,ZT_ECC384_PUBLIC_KEY_SIZE) == 0);
  297. default:
  298. return false;
  299. }
  300. }
  301. return false;
  302. }
  303. inline bool operator<(const Identity &id) const
  304. {
  305. if (_address < id._address)
  306. return true;
  307. if (_address == id._address) {
  308. if ((int)_type < (int)id._type)
  309. return true;
  310. if (_type == id._type) {
  311. switch(_type) {
  312. case C25519:
  313. return (memcmp(_k.t0.pub.data,id._k.t0.pub.data,ZT_C25519_PUBLIC_KEY_LEN) < 0);
  314. case P384:
  315. return (memcmp(_k.t1.pub,id._k.t1.pub,ZT_ECC384_PUBLIC_KEY_SIZE) < 0);
  316. }
  317. }
  318. }
  319. return false;
  320. }
  321. inline bool operator!=(const Identity &id) const { return !(*this == id); }
  322. inline bool operator>(const Identity &id) const { return (id < *this); }
  323. inline bool operator<=(const Identity &id) const { return !(id < *this); }
  324. inline bool operator>=(const Identity &id) const { return !(*this < id); }
  325. inline unsigned long hashCode() const { return (unsigned long)_address.toInt(); }
  326. private:
  327. Address _address;
  328. union {
  329. struct {
  330. C25519::Public pub;
  331. C25519::Private priv;
  332. } t0;
  333. struct {
  334. uint8_t pub[ZT_ECC384_PUBLIC_KEY_SIZE];
  335. uint8_t priv[ZT_ECC384_PRIVATE_KEY_SIZE];
  336. } t1;
  337. } _k;
  338. Type _type;
  339. bool _hasPrivate;
  340. };
  341. } // namespace ZeroTier
  342. #endif