Identity.hpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_IDENTITY_HPP
  28. #define ZT_IDENTITY_HPP
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string>
  32. #include "Constants.hpp"
  33. #include "Array.hpp"
  34. #include "Utils.hpp"
  35. #include "Address.hpp"
  36. #include "C25519.hpp"
  37. #include "Buffer.hpp"
  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 types
  54. */
  55. enum Type
  56. {
  57. IDENTITY_TYPE_C25519 = 0
  58. };
  59. Identity() :
  60. _privateKey((C25519::Private *)0)
  61. {
  62. }
  63. Identity(const Identity &id) :
  64. _address(id._address),
  65. _publicKey(id._publicKey),
  66. _privateKey((id._privateKey) ? new C25519::Private(*(id._privateKey)) : (C25519::Private *)0)
  67. {
  68. }
  69. Identity(const char *str)
  70. throw(std::invalid_argument) :
  71. _privateKey((C25519::Private *)0)
  72. {
  73. if (!fromString(str))
  74. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  75. }
  76. Identity(const std::string &str)
  77. throw(std::invalid_argument) :
  78. _privateKey((C25519::Private *)0)
  79. {
  80. if (!fromString(str))
  81. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  82. }
  83. template<unsigned int C>
  84. Identity(const Buffer<C> &b,unsigned int startAt = 0)
  85. throw(std::out_of_range,std::invalid_argument) :
  86. _privateKey((C25519::Private *)0)
  87. {
  88. deserialize(b,startAt);
  89. }
  90. ~Identity()
  91. {
  92. delete _privateKey;
  93. }
  94. inline Identity &operator=(const Identity &id)
  95. {
  96. _address = id._address;
  97. _publicKey = id._publicKey;
  98. if (id._privateKey) {
  99. if (!_privateKey)
  100. _privateKey = new C25519::Private();
  101. *_privateKey = *(id._privateKey);
  102. } else {
  103. delete _privateKey;
  104. _privateKey = (C25519::Private *)0;
  105. }
  106. return *this;
  107. }
  108. /**
  109. * Generate a new identity (address, key pair)
  110. *
  111. * This is a time consuming operation.
  112. */
  113. void generate();
  114. /**
  115. * Check the validity of this identity's pairing of key to address
  116. *
  117. * @return True if validation check passes
  118. */
  119. bool locallyValidate() const;
  120. /**
  121. * @return True if this identity contains a private key
  122. */
  123. inline bool hasPrivate() const throw() { return (_privateKey != (C25519::Private *)0); }
  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. throw(std::runtime_error)
  132. {
  133. if (_privateKey)
  134. return C25519::sign(*_privateKey,_publicKey,data,len);
  135. throw std::runtime_error("sign() requires a private key");
  136. }
  137. /**
  138. * Verify a message signature against this identity
  139. *
  140. * @param data Data to check
  141. * @param len Length of data
  142. * @param signature Signature bytes
  143. * @param siglen Length of signature in bytes
  144. * @return True if signature validates and data integrity checks
  145. */
  146. inline bool verify(const void *data,unsigned int len,const void *signature,unsigned int siglen) const
  147. {
  148. if (siglen != ZT_C25519_SIGNATURE_LEN)
  149. return false;
  150. return C25519::verify(_publicKey,data,len,signature);
  151. }
  152. /**
  153. * Verify a message signature against this identity
  154. *
  155. * @param data Data to check
  156. * @param len Length of data
  157. * @param signature Signature
  158. * @return True if signature validates and data integrity checks
  159. */
  160. inline bool verify(const void *data,unsigned int len,const C25519::Signature &signature) const
  161. {
  162. return C25519::verify(_publicKey,data,len,signature);
  163. }
  164. /**
  165. * Shortcut method to perform key agreement with another identity
  166. *
  167. * This identity must have a private key. (Check hasPrivate())
  168. *
  169. * @param id Identity to agree with
  170. * @param key Result parameter to fill with key bytes
  171. * @param klen Length of key in bytes
  172. * @return Was agreement successful?
  173. */
  174. inline bool agree(const Identity &id,void *key,unsigned int klen) const
  175. {
  176. if (_privateKey) {
  177. C25519::agree(*_privateKey,id._publicKey,key,klen);
  178. return true;
  179. }
  180. return false;
  181. }
  182. /**
  183. * @return Identity type
  184. */
  185. inline Type type() const throw() { return IDENTITY_TYPE_C25519; }
  186. /**
  187. * @return This identity's address
  188. */
  189. inline const Address &address() const throw() { return _address; }
  190. /**
  191. * Serialize this identity (binary)
  192. *
  193. * @param b Destination buffer to append to
  194. * @param includePrivate If true, include private key component (if present) (default: false)
  195. * @throws std::out_of_range Buffer too small
  196. */
  197. template<unsigned int C>
  198. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  199. {
  200. _address.appendTo(b);
  201. b.append((unsigned char)IDENTITY_TYPE_C25519);
  202. b.append(_publicKey.data,(unsigned int)_publicKey.size());
  203. if ((_privateKey)&&(includePrivate)) {
  204. b.append((unsigned char)_privateKey->size());
  205. b.append(_privateKey->data,(unsigned int)_privateKey->size());
  206. } else b.append((unsigned char)0);
  207. }
  208. /**
  209. * Deserialize a binary serialized identity
  210. *
  211. * If an exception is thrown, the Identity object is left in an undefined
  212. * state and should not be used.
  213. *
  214. * @param b Buffer containing serialized data
  215. * @param startAt Index within buffer of serialized data (default: 0)
  216. * @return Length of serialized data read from buffer
  217. * @throws std::out_of_range Serialized data invalid
  218. * @throws std::invalid_argument Serialized data invalid
  219. */
  220. template<unsigned int C>
  221. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  222. {
  223. delete _privateKey;
  224. _privateKey = (C25519::Private *)0;
  225. unsigned int p = startAt;
  226. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  227. p += ZT_ADDRESS_LENGTH;
  228. if (b[p++] != IDENTITY_TYPE_C25519)
  229. throw std::invalid_argument("unsupported identity type");
  230. memcpy(_publicKey.data,b.field(p,(unsigned int)_publicKey.size()),(unsigned int)_publicKey.size());
  231. p += (unsigned int)_publicKey.size();
  232. unsigned int privateKeyLength = (unsigned int)b[p++];
  233. if (privateKeyLength) {
  234. if (privateKeyLength != ZT_C25519_PRIVATE_KEY_LEN)
  235. throw std::invalid_argument("invalid private key");
  236. _privateKey = new C25519::Private();
  237. memcpy(_privateKey->data,b.field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  238. p += ZT_C25519_PRIVATE_KEY_LEN;
  239. }
  240. return (p - startAt);
  241. }
  242. /**
  243. * Serialize to a more human-friendly string
  244. *
  245. * @param includePrivate If true, include private key (if it exists)
  246. * @return ASCII string representation of identity
  247. */
  248. std::string toString(bool includePrivate) const;
  249. /**
  250. * Deserialize a human-friendly string
  251. *
  252. * Note: validation is for the format only. The locallyValidate() method
  253. * must be used to check signature and address/key correspondence.
  254. *
  255. * @param str String to deserialize
  256. * @return True if deserialization appears successful
  257. */
  258. bool fromString(const char *str);
  259. inline bool fromString(const std::string &str) { return fromString(str.c_str()); }
  260. /**
  261. * @return True if this identity contains something
  262. */
  263. inline operator bool() const throw() { return (_address); }
  264. inline bool operator==(const Identity &id) const throw() { return ((_address == id._address)&&(_publicKey == id._publicKey)); }
  265. inline bool operator<(const Identity &id) const throw() { return ((_address < id._address)||((_address == id._address)&&(_publicKey < id._publicKey))); }
  266. inline bool operator!=(const Identity &id) const throw() { return !(*this == id); }
  267. inline bool operator>(const Identity &id) const throw() { return (id < *this); }
  268. inline bool operator<=(const Identity &id) const throw() { return !(id < *this); }
  269. inline bool operator>=(const Identity &id) const throw() { return !(*this < id); }
  270. private:
  271. Address _address;
  272. C25519::Public _publicKey;
  273. C25519::Private *_privateKey;
  274. };
  275. } // namespace ZeroTier
  276. #endif