Identity.hpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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_NIST_P_521 = 1, // OBSOLETE -- only present in some early alpha versions
  58. IDENTITY_TYPE_C25519 = 2
  59. };
  60. Identity() :
  61. _privateKey((C25519::Private *)0)
  62. {
  63. }
  64. Identity(const Identity &id) :
  65. _address(id._address),
  66. _publicKey(id._publicKey),
  67. _signature(id._signature),
  68. _privateKey((id._privateKey) ? new C25519::Private(*(id._privateKey)) : (C25519::Private *)0)
  69. {
  70. }
  71. Identity(const char *str)
  72. throw(std::invalid_argument) :
  73. _privateKey((C25519::Private *)0)
  74. {
  75. if (!fromString(str))
  76. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  77. }
  78. Identity(const std::string &str)
  79. throw(std::invalid_argument) :
  80. _privateKey((C25519::Private *)0)
  81. {
  82. if (!fromString(str))
  83. throw std::invalid_argument(std::string("invalid string-serialized identity: ") + str);
  84. }
  85. template<unsigned int C>
  86. Identity(const Buffer<C> &b,unsigned int startAt = 0)
  87. throw(std::out_of_range,std::invalid_argument) :
  88. _privateKey((C25519::Private *)0)
  89. {
  90. deserialize(b,startAt);
  91. }
  92. ~Identity()
  93. {
  94. delete _privateKey;
  95. }
  96. inline Identity &operator=(const Identity &id)
  97. {
  98. _address = id._address;
  99. _publicKey = id._publicKey;
  100. _signature = id._signature;
  101. if (id._privateKey) {
  102. if (!_privateKey)
  103. _privateKey = new C25519::Private();
  104. *_privateKey = *(id._privateKey);
  105. } else {
  106. delete _privateKey;
  107. _privateKey = (C25519::Private *)0;
  108. }
  109. return *this;
  110. }
  111. /**
  112. * Generate a new identity (address, key pair)
  113. *
  114. * This is a time consuming operation.
  115. */
  116. void generate();
  117. /**
  118. * Performs local validation, with two levels available
  119. *
  120. * With the parameter false, this performs self-signature verification
  121. * which checks the basic integrity of the key and identity. Setting the
  122. * parameter to true performs a fairly time consuming computation to
  123. * check that the address was properly derived from the key. This is
  124. * normally not done unless a conflicting identity is received, in
  125. * which case the invalid identity is thrown out.
  126. *
  127. * @param doAddressDerivationCheck If true, do the time-consuming address check
  128. * @return True if validation check passes
  129. */
  130. bool locallyValidate(bool doAddressDerivationCheck) const;
  131. /**
  132. * @return True if this identity contains a private key
  133. */
  134. inline bool hasPrivate() const throw() { return (_privateKey != (C25519::Private *)0); }
  135. /**
  136. * Shortcut method to perform key agreement with another identity
  137. *
  138. * This identity must have a private key. (Check hasPrivate())
  139. *
  140. * @param id Identity to agree with
  141. * @param key Result parameter to fill with key bytes
  142. * @param klen Length of key in bytes
  143. * @return Was agreement successful?
  144. */
  145. inline bool agree(const Identity &id,void *key,unsigned int klen) const
  146. {
  147. if (_privateKey) {
  148. C25519::agree(*_privateKey,id._publicKey,key,klen);
  149. return true;
  150. }
  151. return false;
  152. }
  153. /**
  154. * @return Identity type
  155. */
  156. inline Type type() const throw() { return IDENTITY_TYPE_C25519; }
  157. /**
  158. * @return This identity's address
  159. */
  160. inline const Address &address() const throw() { return _address; }
  161. /**
  162. * Serialize this identity (binary)
  163. *
  164. * @param b Destination buffer to append to
  165. * @param includePrivate If true, include private key component (if present) (default: false)
  166. * @throws std::out_of_range Buffer too small
  167. */
  168. template<unsigned int C>
  169. inline void serialize(Buffer<C> &b,bool includePrivate = false) const
  170. throw(std::out_of_range)
  171. {
  172. _address.appendTo(b);
  173. b.append((unsigned char)IDENTITY_TYPE_C25519);
  174. b.append(_publicKey.data,_publicKey.size());
  175. b.append(_signature.data,_signature.size());
  176. if ((_privateKey)&&(includePrivate)) {
  177. b.append((unsigned char)_privateKey.size());
  178. b.append(_privateKey.data,_privateKey.size());
  179. } else b.append((unsigned char)0);
  180. }
  181. /**
  182. * Deserialize a binary serialized identity
  183. *
  184. * If an exception is thrown, the Identity object is left in an undefined
  185. * state and should not be used.
  186. *
  187. * @param b Buffer containing serialized data
  188. * @param startAt Index within buffer of serialized data (default: 0)
  189. * @return Length of serialized data read from buffer
  190. * @throws std::out_of_range Buffer too small
  191. * @throws std::invalid_argument Serialized data invalid
  192. */
  193. template<unsigned int C>
  194. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  195. throw(std::out_of_range,std::invalid_argument)
  196. {
  197. delete _privateKey;
  198. _privateKey = (C25519::Private *)0;
  199. unsigned int p = startAt;
  200. _address.setTo(b.field(p,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH);
  201. p += ZT_ADDRESS_LENGTH;
  202. if (b[p++] != IDENTITY_TYPE_C25519)
  203. throw std::invalid_argument("Identity: deserialize(): unsupported identity type");
  204. memcpy(_publicKey.data,field(p,_publicKey.size()),_publicKey.size());
  205. p += _publicKey.size();
  206. memcpy(_signature.data,field(p,_signature.size()),_signature.size());
  207. p += _signature.size();
  208. unsigned int privateKeyLength = b[p++];
  209. if ((privateKeyLength)&&(privateKeyLength == ZT_C25519_PRIVATE_KEY_LEN)) {
  210. _privateKey = new C25519::Private();
  211. memcpy(_privateKey->data,field(p,ZT_C25519_PRIVATE_KEY_LEN),ZT_C25519_PRIVATE_KEY_LEN);
  212. p += ZT_C25519_PRIVATE_KEY_LEN;
  213. }
  214. return (p - startAt);
  215. }
  216. /**
  217. * Serialize to a more human-friendly string
  218. *
  219. * @param includePrivate If true, include private key (if it exists)
  220. * @return ASCII string representation of identity
  221. */
  222. std::string toString(bool includePrivate) const;
  223. /**
  224. * Deserialize a human-friendly string
  225. *
  226. * Note: validation is for the format only. The locallyValidate() method
  227. * must be used to check signature and address/key correspondence.
  228. *
  229. * @param str String to deserialize
  230. * @return True if deserialization appears successful
  231. */
  232. bool fromString(const char *str);
  233. inline bool fromString(const std::string &str) { return fromString(str.c_str()); }
  234. /**
  235. * @return True if this identity contains something
  236. */
  237. inline operator bool() const throw() { return (_address); }
  238. inline bool operator==(const Identity &id) const throw() { return ((_address == id._address)&&(_publicKey == id._publicKey)); }
  239. inline bool operator<(const Identity &id) const throw() { return ((_address < id._address)||((_address == id._address)&&(_publicKey < id._publicKey))); }
  240. inline bool operator!=(const Identity &id) const throw() { return !(*this == id); }
  241. inline bool operator>(const Identity &id) const throw() { return (id < *this); }
  242. inline bool operator<=(const Identity &id) const throw() { return !(id < *this); }
  243. inline bool operator>=(const Identity &id) const throw() { return !(*this < id); }
  244. private:
  245. // Compute an address from public key bytes
  246. static Address deriveAddress(const void *keyBytes,unsigned int keyLen);
  247. Address _address;
  248. C25519::Public _publicKey;
  249. C25519::Signature _signature;
  250. C25519::Private *_privateKey;
  251. };
  252. } // namespace ZeroTier
  253. #endif