Identity.hpp 9.2 KB

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