Identity.hpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. #define ZT_IDENTITY_STRING_BUFFER_LENGTH 384
  37. namespace ZeroTier {
  38. /**
  39. * A ZeroTier identity
  40. *
  41. * An identity consists of a public key, a 40-bit ZeroTier address computed
  42. * from that key in a collision-resistant fashion, and a self-signature.
  43. *
  44. * The address derivation algorithm makes it computationally very expensive to
  45. * search for a different public key that duplicates an existing address. (See
  46. * code for deriveAddress() for this algorithm.)
  47. */
  48. class Identity
  49. {
  50. public:
  51. Identity() :
  52. _privateKey((C25519::Private *)0)
  53. {
  54. }
  55. Identity(const Identity &id) :
  56. _address(id._address),
  57. _publicKey(id._publicKey),
  58. _privateKey((id._privateKey) ? new C25519::Private(*(id._privateKey)) : (C25519::Private *)0)
  59. {
  60. }
  61. Identity(const char *str) :
  62. _privateKey((C25519::Private *)0)
  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) :
  69. _privateKey((C25519::Private *)0)
  70. {
  71. deserialize(b,startAt);
  72. }
  73. ~Identity()
  74. {
  75. if (_privateKey) {
  76. Utils::burn(_privateKey,sizeof(C25519::Private));
  77. delete _privateKey;
  78. }
  79. }
  80. inline Identity &operator=(const Identity &id)
  81. {
  82. _address = id._address;
  83. _publicKey = id._publicKey;
  84. if (id._privateKey) {
  85. if (!_privateKey)
  86. _privateKey = new C25519::Private();
  87. *_privateKey = *(id._privateKey);
  88. } else {
  89. delete _privateKey;
  90. _privateKey = (C25519::Private *)0;
  91. }
  92. return *this;
  93. }
  94. /**
  95. * Generate a new identity (address, key pair)
  96. *
  97. * This is a time consuming operation.
  98. */
  99. void generate();
  100. /**
  101. * Check the validity of this identity's pairing of key to address
  102. *
  103. * @return True if validation check passes
  104. */
  105. bool locallyValidate() const;
  106. /**
  107. * @return True if this identity contains a private key
  108. */
  109. inline bool hasPrivate() const { return (_privateKey != (C25519::Private *)0); }
  110. /**
  111. * Compute the SHA512 hash of our private key (if we have one)
  112. *
  113. * @param sha Buffer to receive SHA512 (MUST be ZT_SHA512_DIGEST_LEN (64) bytes in length)
  114. * @return True on success, false if no private key
  115. */
  116. inline bool sha512PrivateKey(void *sha) const
  117. {
  118. if (_privateKey) {
  119. SHA512::hash(sha,_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN);
  120. return true;
  121. }
  122. return false;
  123. }
  124. /**
  125. * Sign a message with this identity (private key required)
  126. *
  127. * @param data Data to sign
  128. * @param len Length of data
  129. */
  130. inline C25519::Signature sign(const void *data,unsigned int len) const
  131. {
  132. if (_privateKey)
  133. return C25519::sign(*_privateKey,_publicKey,data,len);
  134. throw ZT_EXCEPTION_PRIVATE_KEY_REQUIRED;
  135. }
  136. /**
  137. * Verify a message signature against this identity
  138. *
  139. * @param data Data to check
  140. * @param len Length of data
  141. * @param signature Signature bytes
  142. * @param siglen Length of signature in bytes
  143. * @return True if signature validates and data integrity checks
  144. */
  145. inline bool verify(const void *data,unsigned int len,const void *signature,unsigned int siglen) const
  146. {
  147. if (siglen != ZT_C25519_SIGNATURE_LEN)
  148. return false;
  149. return C25519::verify(_publicKey,data,len,signature);
  150. }
  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
  157. * @return True if signature validates and data integrity checks
  158. */
  159. inline bool verify(const void *data,unsigned int len,const C25519::Signature &signature) const
  160. {
  161. return C25519::verify(_publicKey,data,len,signature);
  162. }
  163. /**
  164. * Shortcut method to perform key agreement with another identity
  165. *
  166. * This identity must have a private key. (Check hasPrivate())
  167. *
  168. * @param id Identity to agree with
  169. * @param key Result parameter to fill with key bytes
  170. * @param klen Length of key in bytes
  171. * @return Was agreement successful?
  172. */
  173. inline bool agree(const Identity &id,void *key,unsigned int klen) const
  174. {
  175. if (_privateKey) {
  176. C25519::agree(*_privateKey,id._publicKey,key,klen);
  177. return true;
  178. }
  179. return false;
  180. }
  181. /**
  182. * @return This identity's address
  183. */
  184. inline const Address &address() const { return _address; }
  185. /**
  186. * Serialize this identity (binary)
  187. *
  188. * @param b Destination buffer to append to
  189. * @param includePrivate If true, include private key component (if present) (default: false)
  190. * @throws std::out_of_range Buffer too small
  191. */
  192. template<unsigned int C>
  193. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  194. {
  195. _address.appendTo(b);
  196. b.append((uint8_t)0); // C25519/Ed25519 identity type
  197. b.append(_publicKey.data,ZT_C25519_PUBLIC_KEY_LEN);
  198. if ((_privateKey)&&(includePrivate)) {
  199. b.append((unsigned char)ZT_C25519_PRIVATE_KEY_LEN);
  200. b.append(_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN);
  201. } else b.append((unsigned char)0);
  202. }
  203. /**
  204. * Deserialize a binary serialized identity
  205. *
  206. * If an exception is thrown, the Identity object is left in an undefined
  207. * state and should not be used.
  208. *
  209. * @param b Buffer containing serialized data
  210. * @param startAt Index within buffer of serialized data (default: 0)
  211. * @return Length of serialized data read from buffer
  212. * @throws std::out_of_range Serialized data invalid
  213. * @throws std::invalid_argument Serialized data invalid
  214. */
  215. template<unsigned int C>
  216. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  217. {
  218. delete _privateKey;
  219. _privateKey = (C25519::Private *)0;
  220. unsigned int p = startAt;
  221. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  222. p += ZT_ADDRESS_LENGTH;
  223. if (b[p++] != 0)
  224. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_TYPE;
  225. memcpy(_publicKey.data,b.field(p,ZT_C25519_PUBLIC_KEY_LEN),ZT_C25519_PUBLIC_KEY_LEN);
  226. p += ZT_C25519_PUBLIC_KEY_LEN;
  227. unsigned int privateKeyLength = (unsigned int)b[p++];
  228. if (privateKeyLength) {
  229. if (privateKeyLength != ZT_C25519_PRIVATE_KEY_LEN)
  230. throw ZT_EXCEPTION_INVALID_SERIALIZED_DATA_INVALID_CRYPTOGRAPHIC_TOKEN;
  231. _privateKey = new C25519::Private();
  232. memcpy(_privateKey->data,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  233. p += ZT_C25519_PRIVATE_KEY_LEN;
  234. }
  235. return (p - startAt);
  236. }
  237. /**
  238. * Serialize to a more human-friendly string
  239. *
  240. * @param includePrivate If true, include private key (if it exists)
  241. * @param buf Buffer to store string
  242. * @return ASCII string representation of identity
  243. */
  244. char *toString(bool includePrivate,char buf[ZT_IDENTITY_STRING_BUFFER_LENGTH]) const;
  245. /**
  246. * Deserialize a human-friendly string
  247. *
  248. * Note: validation is for the format only. The locallyValidate() method
  249. * must be used to check signature and address/key correspondence.
  250. *
  251. * @param str String to deserialize
  252. * @return True if deserialization appears successful
  253. */
  254. bool fromString(const char *str);
  255. /**
  256. * @return C25519 public key
  257. */
  258. inline const C25519::Public &publicKey() const { return _publicKey; }
  259. /**
  260. * @return C25519 key pair (only returns valid pair if private key is present in this Identity object)
  261. */
  262. inline const C25519::Pair privateKeyPair() const
  263. {
  264. C25519::Pair pair;
  265. pair.pub = _publicKey;
  266. if (_privateKey)
  267. pair.priv = *_privateKey;
  268. else memset(pair.priv.data,0,ZT_C25519_PRIVATE_KEY_LEN);
  269. return pair;
  270. }
  271. /**
  272. * @return True if this identity contains something
  273. */
  274. inline operator bool() const { return (_address); }
  275. inline bool operator==(const Identity &id) const { return ((_address == id._address)&&(memcmp(_publicKey.data,id._publicKey.data,ZT_C25519_PUBLIC_KEY_LEN) == 0)); }
  276. inline bool operator<(const Identity &id) const { return ((_address < id._address)||((_address == id._address)&&(memcmp(_publicKey.data,id._publicKey.data,ZT_C25519_PUBLIC_KEY_LEN) < 0))); }
  277. inline bool operator!=(const Identity &id) const { return !(*this == id); }
  278. inline bool operator>(const Identity &id) const { return (id < *this); }
  279. inline bool operator<=(const Identity &id) const { return !(id < *this); }
  280. inline bool operator>=(const Identity &id) const { return !(*this < id); }
  281. private:
  282. Address _address;
  283. C25519::Public _publicKey;
  284. C25519::Private *_privateKey;
  285. };
  286. } // namespace ZeroTier
  287. #endif