SecretStore.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file SecretStore.cpp
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #include "SecretStore.h"
  19. #include <thread>
  20. #include <mutex>
  21. #include <boost/algorithm/string.hpp>
  22. #include <boost/filesystem.hpp>
  23. #include <libdevcore/Log.h>
  24. #include <libdevcore/Guards.h>
  25. #include <libdevcore/SHA3.h>
  26. #include <libdevcore/FileSystem.h>
  27. #include <json_spirit/JsonSpiritHeaders.h>
  28. #include <libdevcrypto/Exceptions.h>
  29. using namespace std;
  30. using namespace dev;
  31. namespace js = json_spirit;
  32. namespace fs = boost::filesystem;
  33. static const int c_keyFileVersion = 3;
  34. /// Upgrade the json-format to the current version.
  35. static js::mValue upgraded(string const& _s)
  36. {
  37. js::mValue v;
  38. js::read_string(_s, v);
  39. if (v.type() != js::obj_type)
  40. return js::mValue();
  41. js::mObject ret = v.get_obj();
  42. unsigned version = ret.count("Version") ? stoi(ret["Version"].get_str()) : ret.count("version") ? ret["version"].get_int() : 0;
  43. if (version == 1)
  44. {
  45. // upgrade to version 2
  46. js::mObject old;
  47. swap(old, ret);
  48. ret["id"] = old["Id"];
  49. js::mObject c;
  50. c["ciphertext"] = old["Crypto"].get_obj()["CipherText"];
  51. c["cipher"] = "aes-128-cbc";
  52. {
  53. js::mObject cp;
  54. cp["iv"] = old["Crypto"].get_obj()["IV"];
  55. c["cipherparams"] = cp;
  56. }
  57. c["kdf"] = old["Crypto"].get_obj()["KeyHeader"].get_obj()["Kdf"];
  58. {
  59. js::mObject kp;
  60. kp["salt"] = old["Crypto"].get_obj()["Salt"];
  61. for (auto const& i: old["Crypto"].get_obj()["KeyHeader"].get_obj()["KdfParams"].get_obj())
  62. if (i.first != "SaltLen")
  63. kp[boost::to_lower_copy(i.first)] = i.second;
  64. c["kdfparams"] = kp;
  65. }
  66. c["sillymac"] = old["Crypto"].get_obj()["MAC"];
  67. c["sillymacjson"] = _s;
  68. ret["crypto"] = c;
  69. version = 2;
  70. }
  71. if (ret.count("Crypto") && !ret.count("crypto"))
  72. {
  73. ret["crypto"] = ret["Crypto"];
  74. ret.erase("Crypto");
  75. }
  76. if (version == 2)
  77. {
  78. ret["crypto"].get_obj()["cipher"] = "aes-128-ctr";
  79. ret["crypto"].get_obj()["compat"] = "2";
  80. version = 3;
  81. }
  82. if (version == c_keyFileVersion)
  83. return ret;
  84. return js::mValue();
  85. }
  86. SecretStore::SecretStore(string const& _path): m_path(_path)
  87. {
  88. load();
  89. }
  90. void SecretStore::setPath(string const& _path)
  91. {
  92. m_path = _path;
  93. load();
  94. }
  95. bytesSec SecretStore::secret(h128 const& _uuid, function<string()> const& _pass, bool _useCache) const
  96. {
  97. auto rit = m_cached.find(_uuid);
  98. if (_useCache && rit != m_cached.end())
  99. return rit->second;
  100. auto it = m_keys.find(_uuid);
  101. bytesSec key;
  102. if (it != m_keys.end())
  103. {
  104. key = bytesSec(decrypt(it->second.encryptedKey, _pass()));
  105. if (!key.empty())
  106. m_cached[_uuid] = key;
  107. }
  108. return key;
  109. }
  110. bytesSec SecretStore::secret(Address const& _address, function<string()> const& _pass) const
  111. {
  112. bytesSec ret;
  113. if (auto k = key(_address))
  114. ret = bytesSec(decrypt(k->second.encryptedKey, _pass()));
  115. return ret;
  116. }
  117. bytesSec SecretStore::secret(string const& _content, string const& _pass)
  118. {
  119. try
  120. {
  121. js::mValue u = upgraded(_content);
  122. if (u.type() != js::obj_type)
  123. return bytesSec();
  124. return decrypt(js::write_string(u.get_obj()["crypto"], false), _pass);
  125. }
  126. catch (...)
  127. {
  128. return bytesSec();
  129. }
  130. }
  131. h128 SecretStore::importSecret(bytesSec const& _s, string const& _pass)
  132. {
  133. h128 r = h128::random();
  134. EncryptedKey key{encrypt(_s.ref(), _pass), toUUID(r), KeyPair(Secret(_s)).address()};
  135. m_cached[r] = _s;
  136. m_keys[r] = move(key);
  137. save();
  138. return r;
  139. }
  140. h128 SecretStore::importSecret(bytesConstRef _s, string const& _pass)
  141. {
  142. h128 r = h128::random();
  143. EncryptedKey key{encrypt(_s, _pass), toUUID(r), KeyPair(Secret(_s)).address()};
  144. m_cached[r] = bytesSec(_s);
  145. m_keys[r] = move(key);
  146. save();
  147. return r;
  148. }
  149. void SecretStore::kill(h128 const& _uuid)
  150. {
  151. m_cached.erase(_uuid);
  152. if (m_keys.count(_uuid))
  153. {
  154. fs::remove(m_keys[_uuid].filename);
  155. m_keys.erase(_uuid);
  156. }
  157. }
  158. void SecretStore::clearCache() const
  159. {
  160. m_cached.clear();
  161. }
  162. void SecretStore::save(string const& _keysPath)
  163. {
  164. fs::path p(_keysPath);
  165. fs::create_directories(p);
  166. DEV_IGNORE_EXCEPTIONS(fs::permissions(p, fs::owner_all));
  167. for (auto& k: m_keys)
  168. {
  169. string uuid = toUUID(k.first);
  170. string filename = (p / uuid).string() + ".json";
  171. js::mObject v;
  172. js::mValue crypto;
  173. js::read_string(k.second.encryptedKey, crypto);
  174. v["address"] = k.second.address.hex();
  175. v["crypto"] = crypto;
  176. v["id"] = uuid;
  177. v["version"] = c_keyFileVersion;
  178. writeFile(filename, js::write_string(js::mValue(v), true));
  179. swap(k.second.filename, filename);
  180. if (!filename.empty() && !fs::equivalent(filename, k.second.filename))
  181. fs::remove(filename);
  182. }
  183. }
  184. bool SecretStore::noteAddress(h128 const& _uuid, Address const& _address)
  185. {
  186. if (m_keys.find(_uuid) != m_keys.end() && m_keys[_uuid].address == ZeroAddress)
  187. {
  188. m_keys[_uuid].address = _address;
  189. return true;
  190. }
  191. return false;
  192. }
  193. void SecretStore::load(string const& _keysPath)
  194. {
  195. fs::path p(_keysPath);
  196. try
  197. {
  198. for (fs::directory_iterator it(p); it != fs::directory_iterator(); ++it)
  199. if (fs::is_regular_file(it->path()))
  200. readKey(it->path().string(), true);
  201. }
  202. catch (...) {}
  203. }
  204. h128 SecretStore::readKey(string const& _file, bool _takeFileOwnership)
  205. {
  206. ctrace << "Reading" << _file;
  207. return readKeyContent(contentsString(_file), _takeFileOwnership ? _file : string());
  208. }
  209. h128 SecretStore::readKeyContent(string const& _content, string const& _file)
  210. {
  211. try
  212. {
  213. js::mValue u = upgraded(_content);
  214. if (u.type() == js::obj_type)
  215. {
  216. js::mObject& o = u.get_obj();
  217. auto uuid = fromUUID(o["id"].get_str());
  218. Address address = ZeroAddress;
  219. if (o.find("address") != o.end() && isHex(o["address"].get_str()))
  220. address = Address(o["address"].get_str());
  221. else
  222. cwarn << "Account address is either not defined or not in hex format" << _file;
  223. m_keys[uuid] = EncryptedKey{js::write_string(o["crypto"], false), _file, address};
  224. return uuid;
  225. }
  226. else
  227. cwarn << "Invalid JSON in key file" << _file;
  228. return h128();
  229. }
  230. catch (...)
  231. {
  232. return h128();
  233. }
  234. }
  235. bool SecretStore::recode(Address const& _address, string const& _newPass, function<string()> const& _pass, KDF _kdf)
  236. {
  237. if (auto k = key(_address))
  238. {
  239. bytesSec s = secret(_address, _pass);
  240. if (s.empty())
  241. return false;
  242. else
  243. {
  244. k->second.encryptedKey = encrypt(s.ref(), _newPass, _kdf);
  245. save();
  246. return true;
  247. }
  248. }
  249. return false;
  250. }
  251. pair<h128 const, SecretStore::EncryptedKey> const* SecretStore::key(Address const& _address) const
  252. {
  253. for (auto const& k: m_keys)
  254. if (k.second.address == _address)
  255. return &k;
  256. return nullptr;
  257. }
  258. pair<h128 const, SecretStore::EncryptedKey>* SecretStore::key(Address const& _address)
  259. {
  260. for (auto& k: m_keys)
  261. if (k.second.address == _address)
  262. return &k;
  263. return nullptr;
  264. }
  265. bool SecretStore::recode(h128 const& _uuid, string const& _newPass, function<string()> const& _pass, KDF _kdf)
  266. {
  267. bytesSec s = secret(_uuid, _pass, true);
  268. if (s.empty())
  269. return false;
  270. m_cached.erase(_uuid);
  271. m_keys[_uuid].encryptedKey = encrypt(s.ref(), _newPass, _kdf);
  272. save();
  273. return true;
  274. }
  275. static bytesSec deriveNewKey(string const& _pass, KDF _kdf, js::mObject& o_ret)
  276. {
  277. unsigned dklen = 32;
  278. unsigned iterations = 1 << 18;
  279. bytes salt = h256::random().asBytes();
  280. if (_kdf == KDF::Scrypt)
  281. {
  282. unsigned p = 1;
  283. unsigned r = 8;
  284. o_ret["kdf"] = "scrypt";
  285. {
  286. js::mObject params;
  287. params["n"] = int64_t(iterations);
  288. params["r"] = int(r);
  289. params["p"] = int(p);
  290. params["dklen"] = int(dklen);
  291. params["salt"] = toHex(salt);
  292. o_ret["kdfparams"] = params;
  293. }
  294. return scrypt(_pass, salt, iterations, r, p, dklen);
  295. }
  296. else
  297. {
  298. o_ret["kdf"] = "pbkdf2";
  299. {
  300. js::mObject params;
  301. params["prf"] = "hmac-sha256";
  302. params["c"] = int(iterations);
  303. params["salt"] = toHex(salt);
  304. params["dklen"] = int(dklen);
  305. o_ret["kdfparams"] = params;
  306. }
  307. return pbkdf2(_pass, salt, iterations, dklen);
  308. }
  309. }
  310. string SecretStore::encrypt(bytesConstRef _v, string const& _pass, KDF _kdf)
  311. {
  312. js::mObject ret;
  313. bytesSec derivedKey = deriveNewKey(_pass, _kdf, ret);
  314. if (derivedKey.empty())
  315. BOOST_THROW_EXCEPTION(crypto::CryptoException() << errinfo_comment("Key derivation failed."));
  316. ret["cipher"] = "aes-128-ctr";
  317. SecureFixedHash<16> key(derivedKey, h128::AlignLeft);
  318. h128 iv = h128::random();
  319. {
  320. js::mObject params;
  321. params["iv"] = toHex(iv.ref());
  322. ret["cipherparams"] = params;
  323. }
  324. // cipher text
  325. bytes cipherText = encryptSymNoAuth(key, iv, _v);
  326. if (cipherText.empty())
  327. BOOST_THROW_EXCEPTION(crypto::CryptoException() << errinfo_comment("Key encryption failed."));
  328. ret["ciphertext"] = toHex(cipherText);
  329. // and mac.
  330. h256 mac = sha3(derivedKey.ref().cropped(16, 16).toBytes() + cipherText);
  331. ret["mac"] = toHex(mac.ref());
  332. return js::write_string(js::mValue(ret), true);
  333. }
  334. bytesSec SecretStore::decrypt(string const& _v, string const& _pass)
  335. {
  336. js::mObject o;
  337. {
  338. js::mValue ov;
  339. js::read_string(_v, ov);
  340. o = ov.get_obj();
  341. }
  342. // derive key
  343. bytesSec derivedKey;
  344. if (o["kdf"].get_str() == "pbkdf2")
  345. {
  346. auto params = o["kdfparams"].get_obj();
  347. if (params["prf"].get_str() != "hmac-sha256")
  348. {
  349. cwarn << "Unknown PRF for PBKDF2" << params["prf"].get_str() << "not supported.";
  350. return bytesSec();
  351. }
  352. unsigned iterations = params["c"].get_int();
  353. bytes salt = fromHex(params["salt"].get_str());
  354. derivedKey = pbkdf2(_pass, salt, iterations, params["dklen"].get_int());
  355. }
  356. else if (o["kdf"].get_str() == "scrypt")
  357. {
  358. auto p = o["kdfparams"].get_obj();
  359. derivedKey = scrypt(_pass, fromHex(p["salt"].get_str()), p["n"].get_int(), p["r"].get_int(), p["p"].get_int(), p["dklen"].get_int());
  360. }
  361. else
  362. {
  363. cwarn << "Unknown KDF" << o["kdf"].get_str() << "not supported.";
  364. return bytesSec();
  365. }
  366. if (derivedKey.size() < 32 && !(o.count("compat") && o["compat"].get_str() == "2"))
  367. {
  368. cwarn << "Derived key's length too short (<32 bytes)";
  369. return bytesSec();
  370. }
  371. bytes cipherText = fromHex(o["ciphertext"].get_str());
  372. // check MAC
  373. if (o.count("mac"))
  374. {
  375. h256 mac(o["mac"].get_str());
  376. h256 macExp;
  377. if (o.count("compat") && o["compat"].get_str() == "2")
  378. macExp = sha3(derivedKey.ref().cropped(derivedKey.size() - 16).toBytes() + cipherText);
  379. else
  380. macExp = sha3(derivedKey.ref().cropped(16, 16).toBytes() + cipherText);
  381. if (mac != macExp)
  382. {
  383. cwarn << "Invalid key - MAC mismatch; expected" << toString(macExp) << ", got" << toString(mac);
  384. return bytesSec();
  385. }
  386. }
  387. else if (o.count("sillymac"))
  388. {
  389. h256 mac(o["sillymac"].get_str());
  390. h256 macExp = sha3(asBytes(o["sillymacjson"].get_str()) + derivedKey.ref().cropped(derivedKey.size() - 16).toBytes() + cipherText);
  391. if (mac != macExp)
  392. {
  393. cwarn << "Invalid key - MAC mismatch; expected" << toString(macExp) << ", got" << toString(mac);
  394. return bytesSec();
  395. }
  396. }
  397. else
  398. cwarn << "No MAC. Proceeding anyway.";
  399. // decrypt
  400. if (o["cipher"].get_str() == "aes-128-ctr")
  401. {
  402. auto params = o["cipherparams"].get_obj();
  403. h128 iv(params["iv"].get_str());
  404. if (o.count("compat") && o["compat"].get_str() == "2")
  405. {
  406. SecureFixedHash<16> key(sha3Secure(derivedKey.ref().cropped(derivedKey.size() - 16)), h128::AlignRight);
  407. return decryptSymNoAuth(key, iv, &cipherText);
  408. }
  409. else
  410. return decryptSymNoAuth(SecureFixedHash<16>(derivedKey, h128::AlignLeft), iv, &cipherText);
  411. }
  412. else
  413. {
  414. cwarn << "Unknown cipher" << o["cipher"].get_str() << "not supported.";
  415. return bytesSec();
  416. }
  417. }