Skip to content

Commit 4e87d34

Browse files
author
Matt Corallo
committed
Add wallet privkey encryption.
This commit adds support for ckeys, or enCrypted private keys, to the wallet. All keys are stored in memory in their encrypted form and thus the passphrase is required from the user to spend coins, or to create new addresses. Keys are encrypted with AES-256-CBC using OpenSSL's EVP library. The key is calculated via EVP_BytesToKey using SHA512 with (by default) 25000 rounds and a random salt. By default, the user's wallet remains unencrypted until they call the RPC command encryptwallet <passphrase> or, from the GUI menu, Options-> Encrypt Wallet. When the user is attempting to call RPC functions which require the password to unlock the wallet, an error will be returned unless they call walletpassphrase <passphrase> <time to keep key in memory> first. A keypoolrefill command has been added which tops up the users keypool (requiring the passphrase via walletpassphrase first). keypoolsize has been added to the output of getinfo to show the user the number of keys left before they need to specify their passphrase (and call keypoolrefill). Note that walletpassphrase will automatically fill keypool in a separate thread which it spawns when the passphrase is set. This could cause some delays in other threads waiting for locks on the wallet passphrase, including one which could cause the passphrase to be stored longer than expected, however it will not allow the passphrase to be used longer than expected as ThreadCleanWalletPassphrase will attempt to get a lock on the key as soon as the specified lock time has arrived. When the keypool runs out (and wallet is locked) GetOrReuseKeyFromPool returns vchDefaultKey, meaning miners may start to generate many blocks to vchDefaultKey instead of a new key each time. A walletpassphrasechange <oldpassphrase> <newpassphrase> has been added to allow the user to change their password via RPC. Whenever keying material (unencrypted private keys, the user's passphrase, the wallet's AES key) is stored unencrypted in memory, any reasonable attempt is made to mlock/VirtualLock that memory before storing the keying material. This is not true in several (commented) cases where mlock/VirtualLocking the memory is not possible. Although encryption of private keys in memory can be very useful on desktop systems (as some small amount of protection against stupid viruses), on an RPC server, the password is entered fairly insecurely. Thus, the only main advantage encryption has for RPC servers is for RPC servers that do not spend coins, except in rare cases, eg. a webserver of a merchant which only receives payment except for cases of manual intervention. Thanks to jgarzik for the original patch and sipa, gmaxwell and many others for all their input. Conflicts: src/wallet.cpp
1 parent a48c671 commit 4e87d34

File tree

19 files changed

+1199
-169
lines changed

19 files changed

+1199
-169
lines changed

share/uiproject.fbp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,36 @@
162162
<event name="OnMenuSelection">OnMenuOptionsChangeYourAddress</event>
163163
<event name="OnUpdateUI"></event>
164164
</object>
165+
<object class="wxMenuItem" expanded="1">
166+
<property name="bitmap"></property>
167+
<property name="checked">0</property>
168+
<property name="enabled">1</property>
169+
<property name="help"></property>
170+
<property name="id">wxID_ANY</property>
171+
<property name="kind">wxITEM_NORMAL</property>
172+
<property name="label">&amp;Encrypt Wallet...</property>
173+
<property name="name">m_menuOptionsEncryptWallet</property>
174+
<property name="permission">none</property>
175+
<property name="shortcut"></property>
176+
<property name="unchecked_bitmap"></property>
177+
<event name="OnMenuSelection">OnMenuOptionsEncryptWallet</event>
178+
<event name="OnUpdateUI"></event>
179+
</object>
180+
<object class="wxMenuItem" expanded="1">
181+
<property name="bitmap"></property>
182+
<property name="checked">0</property>
183+
<property name="enabled">1</property>
184+
<property name="help"></property>
185+
<property name="id">wxID_ANY</property>
186+
<property name="kind">wxITEM_NORMAL</property>
187+
<property name="label">&amp;Change Wallet Encryption Passphrase...</property>
188+
<property name="name">m_menuOptionsChangeWalletPassphrase</property>
189+
<property name="permission">none</property>
190+
<property name="shortcut"></property>
191+
<property name="unchecked_bitmap"></property>
192+
<event name="OnMenuSelection">OnMenuOptionsChangeWalletPassphrase</event>
193+
<event name="OnUpdateUI"></event>
194+
</object>
165195
<object class="wxMenuItem" expanded="1">
166196
<property name="bitmap"></property>
167197
<property name="checked">0</property>

src/crypter.cpp

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
// Copyright (c) 2011 The Bitcoin Developers
2+
// Distributed under the MIT/X11 software license, see the accompanying
3+
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4+
5+
#include <openssl/aes.h>
6+
#include <openssl/evp.h>
7+
#include <vector>
8+
#include <string>
9+
#include "headers.h"
10+
#ifdef __WXMSW__
11+
#include <windows.h>
12+
#endif
13+
14+
#include "crypter.h"
15+
#include "main.h"
16+
#include "util.h"
17+
18+
bool CCrypter::SetKeyFromPassphrase(const std::string& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
19+
{
20+
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
21+
return false;
22+
23+
// Try to keep the keydata out of swap (and be a bit over-careful to keep the IV that we don't even use out of swap)
24+
// Note that this does nothing about suspend-to-disk (which will put all our key data on disk)
25+
// Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process.
26+
mlock(&chKey[0], sizeof chKey);
27+
mlock(&chIV[0], sizeof chIV);
28+
29+
int i = 0;
30+
if (nDerivationMethod == 0)
31+
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
32+
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
33+
34+
if (i != WALLET_CRYPTO_KEY_SIZE)
35+
{
36+
memset(&chKey, 0, sizeof chKey);
37+
memset(&chIV, 0, sizeof chIV);
38+
return false;
39+
}
40+
41+
fKeySet = true;
42+
return true;
43+
}
44+
45+
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
46+
{
47+
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
48+
return false;
49+
50+
// Try to keep the keydata out of swap
51+
// Note that this does nothing about suspend-to-disk (which will put all our key data on disk)
52+
// Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process.
53+
mlock(&chKey[0], sizeof chKey);
54+
mlock(&chIV[0], sizeof chIV);
55+
56+
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
57+
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
58+
59+
fKeySet = true;
60+
return true;
61+
}
62+
63+
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
64+
{
65+
if (!fKeySet)
66+
return false;
67+
68+
// max ciphertext len for a n bytes of plaintext is
69+
// n + AES_BLOCK_SIZE - 1 bytes
70+
int nLen = vchPlaintext.size();
71+
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
72+
vchCiphertext = std::vector<unsigned char> (nCLen);
73+
74+
EVP_CIPHER_CTX ctx;
75+
76+
EVP_CIPHER_CTX_init(&ctx);
77+
EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
78+
79+
EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
80+
EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
81+
82+
EVP_CIPHER_CTX_cleanup(&ctx);
83+
84+
vchCiphertext.resize(nCLen + nFLen);
85+
return true;
86+
}
87+
88+
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
89+
{
90+
if (!fKeySet)
91+
return false;
92+
93+
// plaintext will always be equal to or lesser than length of ciphertext
94+
int nLen = vchCiphertext.size();
95+
int nPLen = nLen, nFLen = 0;
96+
97+
vchPlaintext = CKeyingMaterial(nPLen);
98+
99+
EVP_CIPHER_CTX ctx;
100+
101+
EVP_CIPHER_CTX_init(&ctx);
102+
EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
103+
104+
EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
105+
EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
106+
107+
EVP_CIPHER_CTX_cleanup(&ctx);
108+
109+
vchPlaintext.resize(nPLen + nFLen);
110+
return true;
111+
}
112+
113+
114+
bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
115+
{
116+
CCrypter cKeyCrypter;
117+
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
118+
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
119+
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
120+
return false;
121+
return cKeyCrypter.Encrypt((CKeyingMaterial)vchPlaintext, vchCiphertext);
122+
}
123+
124+
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CSecret& vchPlaintext)
125+
{
126+
CCrypter cKeyCrypter;
127+
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
128+
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
129+
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
130+
return false;
131+
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
132+
}

src/crypter.h

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
// Copyright (c) 2011 The Bitcoin Developers
2+
// Distributed under the MIT/X11 software license, see the accompanying
3+
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4+
#ifndef __CRYPTER_H__
5+
#define __CRYPTER_H__
6+
7+
#include "key.h"
8+
9+
const unsigned int WALLET_CRYPTO_KEY_SIZE = 32;
10+
const unsigned int WALLET_CRYPTO_SALT_SIZE = 8;
11+
12+
/*
13+
Private key encryption is done based on a CMasterKey,
14+
which holds a salt and random encryption key.
15+
16+
CMasterKeys is encrypted using AES-256-CBC using a key
17+
derived using derivation method nDerivationMethod
18+
(0 == EVP_sha512()) and derivation iterations nDeriveIterations.
19+
vchOtherDerivationParameters is provided for alternative algorithms
20+
which may require more parameters (such as scrypt).
21+
22+
Wallet Private Keys are then encrypted using AES-256-CBC
23+
with the double-sha256 of the private key as the IV, and the
24+
master key's key as the encryption key.
25+
*/
26+
27+
class CMasterKey
28+
{
29+
public:
30+
std::vector<unsigned char> vchCryptedKey;
31+
std::vector<unsigned char> vchSalt;
32+
// 0 = EVP_sha512()
33+
// 1 = scrypt()
34+
unsigned int nDerivationMethod;
35+
unsigned int nDeriveIterations;
36+
// Use this for more parameters to key derivation,
37+
// such as the various parameters to scrypt
38+
std::vector<unsigned char> vchOtherDerivationParameters;
39+
40+
IMPLEMENT_SERIALIZE
41+
(
42+
READWRITE(vchCryptedKey);
43+
READWRITE(vchSalt);
44+
READWRITE(nDerivationMethod);
45+
READWRITE(nDeriveIterations);
46+
READWRITE(vchOtherDerivationParameters);
47+
)
48+
CMasterKey()
49+
{
50+
// 25000 rounds is just under 0.1 seconds on a 1.86 GHz Pentium M
51+
// ie slightly lower than the lowest hardware we need bother supporting
52+
nDeriveIterations = 25000;
53+
nDerivationMethod = 0;
54+
vchOtherDerivationParameters = std::vector<unsigned char>(0);
55+
}
56+
};
57+
58+
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial;
59+
60+
class CCrypter
61+
{
62+
private:
63+
unsigned char chKey[WALLET_CRYPTO_KEY_SIZE];
64+
unsigned char chIV[WALLET_CRYPTO_KEY_SIZE];
65+
bool fKeySet;
66+
67+
public:
68+
bool SetKeyFromPassphrase(const std::string &strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod);
69+
bool Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext);
70+
bool Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext);
71+
bool SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV);
72+
73+
void CleanKey()
74+
{
75+
memset(&chKey, 0, sizeof chKey);
76+
memset(&chIV, 0, sizeof chIV);
77+
munlock(&chKey, sizeof chKey);
78+
munlock(&chIV, sizeof chIV);
79+
fKeySet = false;
80+
}
81+
82+
CCrypter()
83+
{
84+
fKeySet = false;
85+
}
86+
87+
~CCrypter()
88+
{
89+
CleanKey();
90+
}
91+
};
92+
93+
bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext);
94+
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char> &vchCiphertext, const uint256& nIV, CSecret &vchPlaintext);
95+
96+
#endif

src/db.cpp

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -778,7 +778,29 @@ bool CWalletDB::LoadWallet(CWallet* pwallet)
778778
ssValue >> wkey;
779779
key.SetPrivKey(wkey.vchPrivKey);
780780
}
781-
pwallet->LoadKey(key);
781+
if (!pwallet->LoadKey(key))
782+
return false;
783+
}
784+
else if (strType == "mkey")
785+
{
786+
unsigned int nID;
787+
ssKey >> nID;
788+
CMasterKey kMasterKey;
789+
ssValue >> kMasterKey;
790+
if(pwallet->mapMasterKeys.count(nID) != 0)
791+
return false;
792+
pwallet->mapMasterKeys[nID] = kMasterKey;
793+
if (pwallet->nMasterKeyMaxID < nID)
794+
pwallet->nMasterKeyMaxID = nID;
795+
}
796+
else if (strType == "ckey")
797+
{
798+
vector<unsigned char> vchPubKey;
799+
ssKey >> vchPubKey;
800+
vector<unsigned char> vchPrivKey;
801+
ssValue >> vchPrivKey;
802+
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
803+
return false;
782804
}
783805
else if (strType == "defaultkey")
784806
{

src/db.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,25 @@ class CWalletDB : public CDB
391391
return Write(std::make_pair(std::string("key"), vchPubKey), vchPrivKey, false);
392392
}
393393

394+
bool WriteCryptedKey(const std::vector<unsigned char>& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, bool fEraseUnencryptedKey = true)
395+
{
396+
nWalletDBUpdated++;
397+
if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false))
398+
return false;
399+
if (fEraseUnencryptedKey)
400+
{
401+
Erase(std::make_pair(std::string("key"), vchPubKey));
402+
Erase(std::make_pair(std::string("wkey"), vchPubKey));
403+
}
404+
return true;
405+
}
406+
407+
bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
408+
{
409+
nWalletDBUpdated++;
410+
return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
411+
}
412+
394413
bool WriteBestBlock(const CBlockLocator& locator)
395414
{
396415
nWalletDBUpdated++;

0 commit comments

Comments
 (0)