Identity.hpp 9.9 KB

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