Identity.cpp 9.4 KB

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