Identity.hpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. /**
  45. * Identity types
  46. */
  47. enum Type
  48. {
  49. IDENTITY_TYPE_C25519 = 0
  50. };
  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. 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. Identity(const std::string &str)
  69. throw(std::invalid_argument) :
  70. _privateKey((C25519::Private *)0)
  71. {
  72. if (!fromString(str))
  73. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  74. }
  75. template<unsigned int C>
  76. Identity(const Buffer<C> &b,unsigned int startAt = 0) :
  77. _privateKey((C25519::Private *)0)
  78. {
  79. deserialize(b,startAt);
  80. }
  81. ~Identity()
  82. {
  83. delete _privateKey;
  84. }
  85. inline Identity &operator=(const Identity &id)
  86. {
  87. _address = id._address;
  88. _publicKey = id._publicKey;
  89. if (id._privateKey) {
  90. if (!_privateKey)
  91. _privateKey = new C25519::Private();
  92. *_privateKey = *(id._privateKey);
  93. } else {
  94. delete _privateKey;
  95. _privateKey = (C25519::Private *)0;
  96. }
  97. return *this;
  98. }
  99. /**
  100. * Generate a new identity (address, key pair)
  101. *
  102. * This is a time consuming operation.
  103. */
  104. void generate();
  105. /**
  106. * Check the validity of this identity's pairing of key to address
  107. *
  108. * @return True if validation check passes
  109. */
  110. bool locallyValidate() const;
  111. /**
  112. * @return True if this identity contains a private key
  113. */
  114. inline bool hasPrivate() const throw() { return (_privateKey != (C25519::Private *)0); }
  115. /**
  116. * Compute the SHA512 hash of our private key (if we have one)
  117. *
  118. * @param sha Buffer to receive SHA512 (MUST be ZT_SHA512_DIGEST_LEN (64) bytes in length)
  119. * @return True on success, false if no private key
  120. */
  121. inline bool sha512PrivateKey(void *sha) const
  122. {
  123. if (_privateKey) {
  124. SHA512::hash(sha,_privateKey->data,ZT_C25519_PRIVATE_KEY_LEN);
  125. return true;
  126. }
  127. return false;
  128. }
  129. /**
  130. * Sign a message with this identity (private key required)
  131. *
  132. * @param data Data to sign
  133. * @param len Length of data
  134. */
  135. inline C25519::Signature sign(const void *data,unsigned int len) const
  136. throw(std::runtime_error)
  137. {
  138. if (_privateKey)
  139. return C25519::sign(*_privateKey,_publicKey,data,len);
  140. throw std::runtime_error("sign() requires a private key");
  141. }
  142. /**
  143. * Verify a message signature against this identity
  144. *
  145. * @param data Data to check
  146. * @param len Length of data
  147. * @param signature Signature bytes
  148. * @param siglen Length of signature in bytes
  149. * @return True if signature validates and data integrity checks
  150. */
  151. inline bool verify(const void *data,unsigned int len,const void *signature,unsigned int siglen) const
  152. {
  153. if (siglen != ZT_C25519_SIGNATURE_LEN)
  154. return false;
  155. return C25519::verify(_publicKey,data,len,signature);
  156. }
  157. /**
  158. * Verify a message signature against this identity
  159. *
  160. * @param data Data to check
  161. * @param len Length of data
  162. * @param signature Signature
  163. * @return True if signature validates and data integrity checks
  164. */
  165. inline bool verify(const void *data,unsigned int len,const C25519::Signature &signature) const
  166. {
  167. return C25519::verify(_publicKey,data,len,signature);
  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. if (_privateKey) {
  182. C25519::agree(*_privateKey,id._publicKey,key,klen);
  183. return true;
  184. }
  185. return false;
  186. }
  187. /**
  188. * @return Identity type
  189. */
  190. inline Type type() const throw() { return IDENTITY_TYPE_C25519; }
  191. /**
  192. * @return This identity's address
  193. */
  194. inline const Address &address() const throw() { return _address; }
  195. /**
  196. * Serialize this identity (binary)
  197. *
  198. * @param b Destination buffer to append to
  199. * @param includePrivate If true, include private key component (if present) (default: false)
  200. * @throws std::out_of_range Buffer too small
  201. */
  202. template<unsigned int C>
  203. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  204. {
  205. _address.appendTo(b);
  206. b.append((unsigned char)IDENTITY_TYPE_C25519);
  207. b.append(_publicKey.data,(unsigned int)_publicKey.size());
  208. if ((_privateKey)&&(includePrivate)) {
  209. b.append((unsigned char)_privateKey->size());
  210. b.append(_privateKey->data,(unsigned int)_privateKey->size());
  211. } else b.append((unsigned char)0);
  212. }
  213. /**
  214. * Deserialize a binary serialized identity
  215. *
  216. * If an exception is thrown, the Identity object is left in an undefined
  217. * state and should not be used.
  218. *
  219. * @param b Buffer containing serialized data
  220. * @param startAt Index within buffer of serialized data (default: 0)
  221. * @return Length of serialized data read from buffer
  222. * @throws std::out_of_range Serialized data invalid
  223. * @throws std::invalid_argument Serialized data invalid
  224. */
  225. template<unsigned int C>
  226. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  227. {
  228. delete _privateKey;
  229. _privateKey = (C25519::Private *)0;
  230. unsigned int p = startAt;
  231. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  232. p += ZT_ADDRESS_LENGTH;
  233. if (b[p++] != IDENTITY_TYPE_C25519)
  234. throw std::invalid_argument("unsupported identity type");
  235. memcpy(_publicKey.data,b.field(p,(unsigned int)_publicKey.size()),(unsigned int)_publicKey.size());
  236. p += (unsigned int)_publicKey.size();
  237. unsigned int privateKeyLength = (unsigned int)b[p++];
  238. if (privateKeyLength) {
  239. if (privateKeyLength != ZT_C25519_PRIVATE_KEY_LEN)
  240. throw std::invalid_argument("invalid private key");
  241. _privateKey = new C25519::Private();
  242. memcpy(_privateKey->data,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  243. p += ZT_C25519_PRIVATE_KEY_LEN;
  244. }
  245. return (p - startAt);
  246. }
  247. /**
  248. * Serialize to a more human-friendly string
  249. *
  250. * @param includePrivate If true, include private key (if it exists)
  251. * @return ASCII string representation of identity
  252. */
  253. std::string toString(bool includePrivate) const;
  254. /**
  255. * Deserialize a human-friendly string
  256. *
  257. * Note: validation is for the format only. The locallyValidate() method
  258. * must be used to check signature and address/key correspondence.
  259. *
  260. * @param str String to deserialize
  261. * @return True if deserialization appears successful
  262. */
  263. bool fromString(const char *str);
  264. inline bool fromString(const std::string &str) { return fromString(str.c_str()); }
  265. /**
  266. * @return True if this identity contains something
  267. */
  268. inline operator bool() const throw() { return (_address); }
  269. inline bool operator==(const Identity &id) const throw() { return ((_address == id._address)&&(_publicKey == id._publicKey)); }
  270. inline bool operator<(const Identity &id) const throw() { return ((_address < id._address)||((_address == id._address)&&(_publicKey < id._publicKey))); }
  271. inline bool operator!=(const Identity &id) const throw() { return !(*this == id); }
  272. inline bool operator>(const Identity &id) const throw() { return (id < *this); }
  273. inline bool operator<=(const Identity &id) const throw() { return !(id < *this); }
  274. inline bool operator>=(const Identity &id) const throw() { return !(*this < id); }
  275. private:
  276. Address _address;
  277. C25519::Public _publicKey;
  278. C25519::Private *_privateKey;
  279. };
  280. } // namespace ZeroTier
  281. #endif