Identity.hpp 9.1 KB

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