2
0

Identity.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. #include <iostream>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <stdint.h>
  32. #include <openssl/sha.h>
  33. #include "Identity.hpp"
  34. #include "Salsa20.hpp"
  35. #include "HMAC.hpp"
  36. #include "Utils.hpp"
  37. namespace ZeroTier {
  38. void Identity::generate()
  39. {
  40. delete [] _keyPair;
  41. // Generate key pair and derive address
  42. do {
  43. _keyPair = new EllipticCurveKeyPair();
  44. _keyPair->generate();
  45. _address = deriveAddress(_keyPair->pub().data(),_keyPair->pub().size());
  46. } while (_address.isReserved());
  47. _publicKey = _keyPair->pub();
  48. // Sign address, key type, and public key with private key (with a zero
  49. // byte between each field). Including this extra data means simply editing
  50. // the address of an identity will be detected as its signature will be
  51. // invalid. Of course, deep verification of address/key relationship is
  52. // required to cover the more elaborate address claim jump attempt case.
  53. SHA256_CTX sha;
  54. unsigned char dig[32];
  55. unsigned char idtype = IDENTITY_TYPE_NIST_P_521,zero = 0;
  56. SHA256_Init(&sha);
  57. SHA256_Update(&sha,_address.data(),ZT_ADDRESS_LENGTH);
  58. SHA256_Update(&sha,&zero,1);
  59. SHA256_Update(&sha,&idtype,1);
  60. SHA256_Update(&sha,&zero,1);
  61. SHA256_Update(&sha,_publicKey.data(),_publicKey.size());
  62. SHA256_Update(&sha,&zero,1);
  63. SHA256_Final(dig,&sha);
  64. _signature = _keyPair->sign(dig);
  65. }
  66. bool Identity::locallyValidate(bool doAddressDerivationCheck) const
  67. {
  68. SHA256_CTX sha;
  69. unsigned char dig[32];
  70. unsigned char idtype = IDENTITY_TYPE_NIST_P_521,zero = 0;
  71. SHA256_Init(&sha);
  72. SHA256_Update(&sha,_address.data(),ZT_ADDRESS_LENGTH);
  73. SHA256_Update(&sha,&zero,1);
  74. SHA256_Update(&sha,&idtype,1);
  75. SHA256_Update(&sha,&zero,1);
  76. SHA256_Update(&sha,_publicKey.data(),_publicKey.size());
  77. SHA256_Update(&sha,&zero,1);
  78. SHA256_Final(dig,&sha);
  79. return ((EllipticCurveKeyPair::verify(dig,_publicKey,_signature.data(),_signature.length()))&&((!doAddressDerivationCheck)||(deriveAddress(_publicKey.data(),_publicKey.size()) == _address)));
  80. }
  81. std::string Identity::toString(bool includePrivate) const
  82. {
  83. std::string r;
  84. r.append(_address.toString());
  85. r.append(":1:"); // 1 == IDENTITY_TYPE_NIST_P_521
  86. r.append(Utils::base64Encode(_publicKey.data(),_publicKey.size()));
  87. r.push_back(':');
  88. r.append(Utils::base64Encode(_signature.data(),_signature.length()));
  89. if ((includePrivate)&&(_keyPair)) {
  90. r.push_back(':');
  91. r.append(Utils::base64Encode(_keyPair->priv().data(),_keyPair->priv().size()));
  92. }
  93. return r;
  94. }
  95. bool Identity::fromString(const char *str)
  96. {
  97. delete _keyPair;
  98. _keyPair = (EllipticCurveKeyPair *)0;
  99. std::vector<std::string> fields(Utils::split(Utils::trim(std::string(str)).c_str(),":","",""));
  100. if (fields.size() < 4)
  101. return false;
  102. if (fields[1] != "1")
  103. return false; // version mismatch
  104. std::string b(Utils::unhex(fields[0]));
  105. if (b.length() != ZT_ADDRESS_LENGTH)
  106. return false;
  107. _address = b.data();
  108. b = Utils::base64Decode(fields[2]);
  109. if ((!b.length())||(b.length() > ZT_EC_MAX_BYTES))
  110. return false;
  111. _publicKey.set(b.data(),b.length());
  112. _signature = Utils::base64Decode(fields[3]);
  113. if (!_signature.length())
  114. return false;
  115. if (fields.size() >= 5) {
  116. b = Utils::base64Decode(fields[4]);
  117. if ((!b.length())||(b.length() > ZT_EC_MAX_BYTES))
  118. return false;
  119. _keyPair = new EllipticCurveKeyPair(_publicKey,EllipticCurveKey(b.data(),b.length()));
  120. }
  121. return true;
  122. }
  123. // These are core protocol parameters and can't be changed without a new
  124. // identity type.
  125. #define ZT_IDENTITY_DERIVEADDRESS_ROUNDS 4
  126. #define ZT_IDENTITY_DERIVEADDRESS_MEMORY 33554432
  127. Address Identity::deriveAddress(const void *keyBytes,unsigned int keyLen)
  128. {
  129. unsigned char dig[32];
  130. Salsa20 s20a,s20b;
  131. SHA256_CTX sha;
  132. /*
  133. * Sequential memory-hard algorithm wedding address to public key
  134. *
  135. * Conventional hashcash with long computations and quick verifications
  136. * unfortunately cannot be used here. If that were used, it would be
  137. * equivalently costly to simply increment/vary the public key and find
  138. * a collision as it would be to find the address. We need something
  139. * that creates a costly 1:~1 mapping from key to address, hence this odd
  140. * algorithm.
  141. *
  142. * This is designed not to be parallelizable and to be resistant to
  143. * implementation on things like GPUs with tiny-memory nodes and poor
  144. * branching capability. Toward that end it throws branching and a large
  145. * memory buffer into the mix. It can only be efficiently computed by a
  146. * single core with at least ~32MB RAM.
  147. *
  148. * Search for "sequential memory hard algorithm" for academic references
  149. * to similar concepts.
  150. *
  151. * Right now this takes ~1700ms on a 2.4ghz Intel Core i5. If this could
  152. * be reduced to 1ms per derivation, it would take about 34 years to search
  153. * the entire 40-bit address space for an average of ~17 years to generate
  154. * a key colliding with a known existing address.
  155. */
  156. // Initial starting digest
  157. SHA256_Init(&sha);
  158. SHA256_Update(&sha,(const unsigned char *)keyBytes,keyLen); // key
  159. SHA256_Final(dig,&sha);
  160. s20a.init(dig,256,"ZeroTier");
  161. unsigned char *ram = new unsigned char[ZT_IDENTITY_DERIVEADDRESS_MEMORY];
  162. // Encrypt and digest a large memory buffer for several rounds
  163. for(unsigned long i=0;i<ZT_IDENTITY_DERIVEADDRESS_MEMORY;++i)
  164. ram[i] = (unsigned char)(i & 0xff) ^ dig[i & 31];
  165. for(unsigned long r=0;r<ZT_IDENTITY_DERIVEADDRESS_ROUNDS;++r) {
  166. SHA256_Init(&sha);
  167. SHA256_Update(&sha,(const unsigned char *)keyBytes,keyLen);
  168. SHA256_Update(&sha,dig,32);
  169. for(unsigned long i=0;i<ZT_IDENTITY_DERIVEADDRESS_MEMORY;++i) {
  170. if (ram[i] == 17) // Forces a branch to be required
  171. ram[i] ^= dig[i & 31];
  172. }
  173. s20b.init(dig,256,"ZeroTier");
  174. s20a.encrypt(ram,ram,ZT_IDENTITY_DERIVEADDRESS_MEMORY);
  175. s20b.encrypt(ram,ram,ZT_IDENTITY_DERIVEADDRESS_MEMORY);
  176. SHA256_Update(&sha,ram,ZT_IDENTITY_DERIVEADDRESS_MEMORY);
  177. SHA256_Final(dig,&sha);
  178. }
  179. // Final digest, executed for twice our number of rounds
  180. SHA256_Init(&sha);
  181. for(unsigned long r=0;r<(ZT_IDENTITY_DERIVEADDRESS_ROUNDS * 2);++r) {
  182. SHA256_Update(&sha,(const unsigned char *)keyBytes,keyLen);
  183. SHA256_Update(&sha,ram,ZT_IDENTITY_DERIVEADDRESS_ROUNDS);
  184. SHA256_Update(&sha,dig,32);
  185. SHA256_Update(&sha,(const unsigned char *)keyBytes,keyLen);
  186. }
  187. SHA256_Final(dig,&sha);
  188. delete [] ram;
  189. return Address(dig); // first 5 bytes of dig[]
  190. }
  191. std::string Identity::encrypt(const Identity &to,const void *data,unsigned int len) const
  192. {
  193. unsigned char key[64];
  194. unsigned char mac[32];
  195. unsigned char iv[8];
  196. if (!agree(to,key,sizeof(key)))
  197. return std::string();
  198. Utils::getSecureRandom(iv,8);
  199. for(int i=0;i<8;++i)
  200. key[i + 32] ^= iv[i]; // perturb HMAC key with IV so IV is effectively included in HMAC
  201. Salsa20 s20(key,256,iv);
  202. std::string compressed;
  203. compressed.reserve(len);
  204. Utils::compress((const char *)data,(const char *)data + len,Utils::StringAppendOutput(compressed));
  205. if (!compressed.length())
  206. return std::string();
  207. char *encrypted = new char[compressed.length() + 16];
  208. try {
  209. s20.encrypt(compressed.data(),encrypted + 16,(unsigned int)compressed.length());
  210. HMAC::sha256(key + 32,32,encrypted + 16,(unsigned int)compressed.length(),mac);
  211. for(int i=0;i<8;++i)
  212. encrypted[i] = iv[i];
  213. for(int i=0;i<8;++i)
  214. encrypted[i + 8] = mac[i];
  215. std::string s(encrypted,compressed.length() + 16);
  216. delete [] encrypted;
  217. return s;
  218. } catch ( ... ) {
  219. delete [] encrypted;
  220. return std::string();
  221. }
  222. }
  223. std::string Identity::decrypt(const Identity &from,const void *cdata,unsigned int len) const
  224. {
  225. unsigned char key[64];
  226. unsigned char mac[32];
  227. if (len < 16)
  228. return std::string();
  229. if (!agree(from,key,sizeof(key)))
  230. return std::string();
  231. for(int i=0;i<8;++i)
  232. key[i + 32] ^= ((const unsigned char *)cdata)[i]; // apply IV to HMAC key
  233. HMAC::sha256(key + 32,32,((const char *)cdata) + 16,(unsigned int)(len - 16),mac);
  234. for(int i=0;i<8;++i) {
  235. if (((const unsigned char *)cdata)[i + 8] != mac[i])
  236. return std::string();
  237. }
  238. char *decbuf = new char[len - 16];
  239. try {
  240. Salsa20 s20(key,256,cdata); // first 8 bytes are IV
  241. len -= 16;
  242. s20.decrypt((const char *)cdata + 16,decbuf,len);
  243. std::string decompressed;
  244. if (Utils::decompress((const char *)decbuf,(const char *)decbuf + len,Utils::StringAppendOutput(decompressed))) {
  245. delete [] decbuf;
  246. return decompressed;
  247. } else {
  248. delete [] decbuf;
  249. return std::string();
  250. }
  251. } catch ( ... ) {
  252. delete [] decbuf;
  253. return std::string();
  254. }
  255. }
  256. } // namespace ZeroTier