KeyManager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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 KeyManager.cpp
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #include "KeyManager.h"
  19. #include <thread>
  20. #include <mutex>
  21. #include <boost/filesystem.hpp>
  22. #include <json_spirit/JsonSpiritHeaders.h>
  23. #include <libdevcore/Log.h>
  24. #include <libdevcore/Guards.h>
  25. #include <libdevcore/RLP.h>
  26. #include <libdevcore/SHA3.h>
  27. using namespace std;
  28. using namespace dev;
  29. using namespace eth;
  30. namespace js = json_spirit;
  31. namespace fs = boost::filesystem;
  32. KeyManager::KeyManager(string const& _keysFile, string const& _secretsPath):
  33. m_keysFile(_keysFile), m_store(_secretsPath)
  34. {
  35. for (auto const& uuid: m_store.keys())
  36. {
  37. auto addr = m_store.address(uuid);
  38. m_addrLookup[addr] = uuid;
  39. m_uuidLookup[uuid] = addr;
  40. }
  41. }
  42. KeyManager::~KeyManager()
  43. {}
  44. bool KeyManager::exists() const
  45. {
  46. return !contents(m_keysFile + ".salt").empty() && !contents(m_keysFile).empty();
  47. }
  48. void KeyManager::create(string const& _pass)
  49. {
  50. m_defaultPasswordDeprecated = asString(h256::random().asBytes());
  51. write(_pass, m_keysFile);
  52. }
  53. bool KeyManager::recode(Address const& _address, string const& _newPass, string const& _hint, function<string()> const& _pass, KDF _kdf)
  54. {
  55. noteHint(_newPass, _hint);
  56. h128 u = uuid(_address);
  57. if (!store().recode(u, _newPass, [&](){ return getPassword(u, _pass); }, _kdf))
  58. return false;
  59. m_keyInfo[_address].passHash = hashPassword(_newPass);
  60. write();
  61. return true;
  62. }
  63. bool KeyManager::recode(Address const& _address, SemanticPassword _newPass, function<string()> const& _pass, KDF _kdf)
  64. {
  65. h128 u = uuid(_address);
  66. string p;
  67. if (_newPass == SemanticPassword::Existing)
  68. p = getPassword(u, _pass);
  69. else if (_newPass == SemanticPassword::Master)
  70. p = defaultPassword();
  71. else
  72. return false;
  73. return recode(_address, p, string(), _pass, _kdf);
  74. }
  75. bool KeyManager::load(string const& _pass)
  76. {
  77. try
  78. {
  79. bytes salt = contents(m_keysFile + ".salt");
  80. bytes encKeys = contents(m_keysFile);
  81. if (encKeys.empty())
  82. return false;
  83. m_keysFileKey = SecureFixedHash<16>(pbkdf2(_pass, salt, 262144, 16));
  84. bytesSec bs = decryptSymNoAuth(m_keysFileKey, h128(), &encKeys);
  85. RLP s(bs.ref());
  86. unsigned version = unsigned(s[0]);
  87. if (version == 1)
  88. {
  89. bool saveRequired = false;
  90. for (auto const& i: s[1])
  91. {
  92. h128 uuid(i[1]);
  93. Address addr(i[0]);
  94. if (uuid)
  95. {
  96. if (m_store.contains(uuid))
  97. {
  98. m_addrLookup[addr] = uuid;
  99. m_uuidLookup[uuid] = addr;
  100. m_keyInfo[addr] = KeyInfo(h256(i[2]), string(i[3]), i.itemCount() > 4 ? string(i[4]) : "");
  101. if (m_store.noteAddress(uuid, addr))
  102. saveRequired = true;
  103. }
  104. else
  105. cwarn << "Missing key:" << uuid << addr;
  106. }
  107. else
  108. {
  109. // TODO: brain wallet.
  110. m_keyInfo[addr] = KeyInfo(h256(i[2]), string(i[3]), i.itemCount() > 4 ? string(i[4]) : "");
  111. }
  112. // cdebug << toString(addr) << toString(uuid) << toString((h256)i[2]) << (string)i[3];
  113. }
  114. if (saveRequired)
  115. m_store.save();
  116. for (auto const& i: s[2])
  117. m_passwordHint[h256(i[0])] = string(i[1]);
  118. m_defaultPasswordDeprecated = string(s[3]);
  119. }
  120. // cdebug << hashPassword(m_password) << toHex(m_password);
  121. cachePassword(m_defaultPasswordDeprecated);
  122. // cdebug << hashPassword(asString(m_key.ref())) << m_key.hex();
  123. cachePassword(asString(m_keysFileKey.ref()));
  124. // cdebug << hashPassword(_pass) << _pass;
  125. m_master = hashPassword(_pass);
  126. cachePassword(_pass);
  127. return true;
  128. }
  129. catch (...)
  130. {
  131. return false;
  132. }
  133. }
  134. Secret KeyManager::secret(Address const& _address, function<string()> const& _pass, bool _usePasswordCache) const
  135. {
  136. if (m_addrLookup.count(_address))
  137. return secret(m_addrLookup.at(_address), _pass, _usePasswordCache);
  138. else
  139. return brain(_pass());
  140. }
  141. Secret KeyManager::secret(h128 const& _uuid, function<string()> const& _pass, bool _usePasswordCache) const
  142. {
  143. if (_usePasswordCache)
  144. return Secret(m_store.secret(_uuid, [&](){ return getPassword(_uuid, _pass); }, _usePasswordCache));
  145. else
  146. return Secret(m_store.secret(_uuid, _pass, _usePasswordCache));
  147. }
  148. string KeyManager::getPassword(h128 const& _uuid, function<string()> const& _pass) const
  149. {
  150. h256 ph;
  151. auto ait = m_uuidLookup.find(_uuid);
  152. if (ait != m_uuidLookup.end())
  153. {
  154. auto kit = m_keyInfo.find(ait->second);
  155. if (kit != m_keyInfo.end())
  156. ph = kit->second.passHash;
  157. }
  158. return getPassword(ph, _pass);
  159. }
  160. string KeyManager::getPassword(h256 const& _passHash, function<string()> const& _pass) const
  161. {
  162. auto it = m_cachedPasswords.find(_passHash);
  163. if (it != m_cachedPasswords.end())
  164. return it->second;
  165. for (unsigned i = 0; i < 10; ++i)
  166. {
  167. string p = _pass();
  168. if (p.empty())
  169. break;
  170. if (_passHash == UnknownPassword || hashPassword(p) == _passHash)
  171. {
  172. cachePassword(p);
  173. return p;
  174. }
  175. }
  176. return string();
  177. }
  178. h128 KeyManager::uuid(Address const& _a) const
  179. {
  180. auto it = m_addrLookup.find(_a);
  181. if (it == m_addrLookup.end())
  182. return h128();
  183. return it->second;
  184. }
  185. Address KeyManager::address(h128 const& _uuid) const
  186. {
  187. auto it = m_uuidLookup.find(_uuid);
  188. if (it == m_uuidLookup.end())
  189. return Address();
  190. return it->second;
  191. }
  192. h128 KeyManager::import(Secret const& _s, string const& _accountName, string const& _pass, string const& _passwordHint)
  193. {
  194. Address addr = KeyPair(_s).address();
  195. auto passHash = hashPassword(_pass);
  196. cachePassword(_pass);
  197. m_passwordHint[passHash] = _passwordHint;
  198. auto uuid = m_store.importSecret(_s.asBytesSec(), _pass);
  199. m_keyInfo[addr] = KeyInfo{passHash, _accountName, ""};
  200. m_addrLookup[addr] = uuid;
  201. m_uuidLookup[uuid] = addr;
  202. write(m_keysFile);
  203. return uuid;
  204. }
  205. Secret KeyManager::brain(string const& _seed)
  206. {
  207. h256 r = sha3(_seed);
  208. for (auto i = 0; i < 16384; ++i)
  209. r = sha3(r);
  210. Secret ret(r);
  211. r.ref().cleanse();
  212. while (toAddress(ret)[0])
  213. ret = sha3(ret);
  214. return ret;
  215. }
  216. Secret KeyManager::subkey(Secret const& _s, unsigned _index)
  217. {
  218. RLPStream out(2);
  219. out << _s.ref();
  220. out << _index;
  221. bytesSec r;
  222. out.swapOut(r.writable());
  223. return sha3(r);
  224. }
  225. Address KeyManager::importBrain(string const& _seed, string const& _accountName, string const& _passwordHint)
  226. {
  227. Address addr = toAddress(brain(_seed));
  228. m_keyInfo[addr].accountName = _accountName;
  229. m_keyInfo[addr].passwordHint = _passwordHint;
  230. write();
  231. return addr;
  232. }
  233. void KeyManager::importExistingBrain(Address const& _a, string const& _accountName, string const& _passwordHint)
  234. {
  235. m_keyInfo[_a].accountName = _accountName;
  236. m_keyInfo[_a].passwordHint = _passwordHint;
  237. write();
  238. }
  239. void KeyManager::importExisting(h128 const& _uuid, string const& _info, string const& _pass, string const& _passwordHint)
  240. {
  241. bytesSec key = m_store.secret(_uuid, [&](){ return _pass; });
  242. if (key.empty())
  243. return;
  244. Address a = KeyPair(Secret(key)).address();
  245. auto passHash = hashPassword(_pass);
  246. if (!m_cachedPasswords.count(passHash))
  247. cachePassword(_pass);
  248. importExisting(_uuid, _info, a, passHash, _passwordHint);
  249. }
  250. void KeyManager::importExisting(h128 const& _uuid, string const& _accountName, Address const& _address, h256 const& _passHash, string const& _passwordHint)
  251. {
  252. if (!m_passwordHint.count(_passHash))
  253. m_passwordHint[_passHash] = _passwordHint;
  254. m_uuidLookup[_uuid] = _address;
  255. m_addrLookup[_address] = _uuid;
  256. m_keyInfo[_address].passHash = _passHash;
  257. m_keyInfo[_address].accountName = _accountName;
  258. write(m_keysFile);
  259. }
  260. void KeyManager::kill(Address const& _a)
  261. {
  262. auto id = m_addrLookup[_a];
  263. m_uuidLookup.erase(id);
  264. m_addrLookup.erase(_a);
  265. m_keyInfo.erase(_a);
  266. m_store.kill(id);
  267. write(m_keysFile);
  268. }
  269. KeyPair KeyManager::presaleSecret(std::string const& _json, function<string(bool)> const& _password)
  270. {
  271. js::mValue val;
  272. json_spirit::read_string(_json, val);
  273. auto obj = val.get_obj();
  274. string p = _password(true);
  275. if (obj["encseed"].type() == js::str_type)
  276. {
  277. auto encseed = fromHex(obj["encseed"].get_str());
  278. KeyPair k;
  279. for (bool gotit = false; !gotit;)
  280. {
  281. gotit = true;
  282. k = KeyPair::fromEncryptedSeed(&encseed, p);
  283. if (obj["ethaddr"].type() == js::str_type)
  284. {
  285. Address a(obj["ethaddr"].get_str());
  286. Address b = k.address();
  287. if (a != b)
  288. {
  289. if ((p = _password(false)).empty())
  290. BOOST_THROW_EXCEPTION(PasswordUnknown());
  291. else
  292. gotit = false;
  293. }
  294. }
  295. }
  296. return k;
  297. }
  298. else
  299. BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("encseed type is not js::str_type"));
  300. }
  301. Addresses KeyManager::accounts() const
  302. {
  303. set<Address> addresses;
  304. for (auto const& i: m_keyInfo)
  305. addresses.insert(i.first);
  306. for (auto const& key: m_store.keys())
  307. addresses.insert(m_store.address(key));
  308. // Remove the zero address if present
  309. return Addresses{addresses.upper_bound(Address()), addresses.end()};
  310. }
  311. bool KeyManager::hasAccount(Address const& _address) const
  312. {
  313. if (!_address)
  314. return false;
  315. if (m_keyInfo.count(_address))
  316. return true;
  317. for (auto const& key: m_store.keys())
  318. if (m_store.address(key) == _address)
  319. return true;
  320. return false;
  321. }
  322. string const& KeyManager::accountName(Address const& _address) const
  323. {
  324. try
  325. {
  326. return m_keyInfo.at(_address).accountName;
  327. }
  328. catch (...)
  329. {
  330. return EmptyString;
  331. }
  332. }
  333. void KeyManager::changeName(Address const& _address, std::string const& _name)
  334. {
  335. auto it = m_keyInfo.find(_address);
  336. if (it != m_keyInfo.end())
  337. {
  338. it->second.accountName = _name;
  339. write(m_keysFile);
  340. }
  341. }
  342. string const& KeyManager::passwordHint(Address const& _address) const
  343. {
  344. try
  345. {
  346. auto& info = m_keyInfo.at(_address);
  347. if (info.passwordHint.size())
  348. return info.passwordHint;
  349. return m_passwordHint.at(info.passHash);
  350. }
  351. catch (...)
  352. {
  353. return EmptyString;
  354. }
  355. }
  356. h256 KeyManager::hashPassword(string const& _pass) const
  357. {
  358. // TODO SECURITY: store this a bit more securely; Scrypt perhaps?
  359. return h256(pbkdf2(_pass, asBytes(m_defaultPasswordDeprecated), 262144, 32).makeInsecure());
  360. }
  361. void KeyManager::cachePassword(string const& _password) const
  362. {
  363. m_cachedPasswords[hashPassword(_password)] = _password;
  364. }
  365. bool KeyManager::write(string const& _keysFile) const
  366. {
  367. if (!m_keysFileKey)
  368. return false;
  369. write(m_keysFileKey, _keysFile);
  370. return true;
  371. }
  372. void KeyManager::write(string const& _pass, string const& _keysFile) const
  373. {
  374. bytes salt = h256::random().asBytes();
  375. writeFile(_keysFile + ".salt", salt, true);
  376. auto key = SecureFixedHash<16>(pbkdf2(_pass, salt, 262144, 16));
  377. cachePassword(_pass);
  378. m_master = hashPassword(_pass);
  379. write(key, _keysFile);
  380. }
  381. void KeyManager::write(SecureFixedHash<16> const& _key, string const& _keysFile) const
  382. {
  383. RLPStream s(4);
  384. s << 1; // version
  385. s.appendList(m_keyInfo.size());
  386. for (auto const& info: m_keyInfo)
  387. {
  388. h128 id = uuid(info.first);
  389. auto const& ki = info.second;
  390. s.appendList(5) << info.first << id << ki.passHash << ki.accountName << ki.passwordHint;
  391. }
  392. s.appendList(m_passwordHint.size());
  393. for (auto const& i: m_passwordHint)
  394. s.appendList(2) << i.first << i.second;
  395. s.append(m_defaultPasswordDeprecated);
  396. writeFile(_keysFile, encryptSymNoAuth(_key, h128(), &s.out()), true);
  397. m_keysFileKey = _key;
  398. cachePassword(defaultPassword());
  399. }
  400. KeyPair KeyManager::newKeyPair(KeyManager::NewKeyType _type)
  401. {
  402. KeyPair p;
  403. bool keepGoing = true;
  404. unsigned done = 0;
  405. function<void()> f = [&]() {
  406. KeyPair lp;
  407. while (keepGoing)
  408. {
  409. done++;
  410. if (done % 1000 == 0)
  411. cnote << "Tried" << done << "keys";
  412. lp = KeyPair::create();
  413. auto a = lp.address();
  414. if (_type == NewKeyType::NoVanity ||
  415. (_type == NewKeyType::DirectICAP && !a[0]) ||
  416. (_type == NewKeyType::FirstTwo && a[0] == a[1]) ||
  417. (_type == NewKeyType::FirstTwoNextTwo && a[0] == a[1] && a[2] == a[3]) ||
  418. (_type == NewKeyType::FirstThree && a[0] == a[1] && a[1] == a[2]) ||
  419. (_type == NewKeyType::FirstFour && a[0] == a[1] && a[1] == a[2] && a[2] == a[3])
  420. )
  421. break;
  422. }
  423. if (keepGoing)
  424. p = lp;
  425. keepGoing = false;
  426. };
  427. vector<std::thread*> ts;
  428. for (unsigned t = 0; t < std::thread::hardware_concurrency() - 1; ++t)
  429. ts.push_back(new std::thread(f));
  430. f();
  431. for (std::thread* t: ts)
  432. {
  433. t->join();
  434. delete t;
  435. }
  436. return p;
  437. }