forked from spesmilo/electrum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.py
More file actions
349 lines (304 loc) · 12.7 KB
/
storage.py
File metadata and controls
349 lines (304 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import threading
import stat
import hashlib
import base64
import zlib
from enum import IntEnum
from . import ecc
from .util import profiler, InvalidPassword, WalletFileException, bfh, standardize_path
from .plugin import run_hook, plugin_loaders
from .json_db import WalletDB
from .logging import Logger
import hmac
from .crypto import aes_encrypt_with_iv, aes_decrypt_with_iv
def get_derivation_used_for_hw_device_encryption():
return ("m"
"/4541509'" # ascii 'ELE' as decimal ("BIP43 purpose")
"/1112098098'") # ascii 'BIE2' as decimal
class StorageEncryptionVersion(IntEnum):
PLAINTEXT = 0
USER_PASSWORD = 1
XPUB_PASSWORD = 2
class StorageReadWriteError(Exception): pass
class WalletStorage(Logger):
def __init__(self, path, *, manual_upgrades=False):
Logger.__init__(self)
self.path = standardize_path(path)
self._file_exists = bool(self.path and os.path.exists(self.path))
self.logger.info(f"wallet path {self.path}")
self.pubkey = None
self._test_read_write_permissions(self.path)
if self.file_exists():
with open(self.path, "rb") as f:
self.raw = f.read()
self._encryption_version = self._init_encryption_version()
if not self.is_encrypted():
self.db = WalletDB(self.raw.decode('utf8'), manual_upgrades=manual_upgrades)
self._write()
self.load_plugins()
else:
self._encryption_version = StorageEncryptionVersion.PLAINTEXT
# avoid new wallets getting 'upgraded'
self.db = WalletDB('', manual_upgrades=False)
@classmethod
def _test_read_write_permissions(cls, path):
# note: There might already be a file at 'path'.
# Make sure we do NOT overwrite/corrupt that!
temp_path = "%s.tmptest.%s" % (path, os.getpid())
echo = b"fs r/w test"
try:
# test READ permissions for actual path
if os.path.exists(path):
with open(path, "rb") as f:
f.read(1) # read 1 byte
# test R/W sanity for "similar" path
with open(temp_path, "wb") as f:
f.write(echo)
with open(temp_path, "rb") as f:
echo2 = f.read()
os.remove(temp_path)
except Exception as e:
raise StorageReadWriteError(e) from e
if echo != echo2:
raise StorageReadWriteError('echo sanity-check failed')
def load_plugins(self):
wallet_type = self.db.get('wallet_type')
if wallet_type in plugin_loaders:
plugin_loaders[wallet_type]()
def put(self, key,value):
self.db.put(key, value)
def get(self, key, default=None):
return self.db.get(key, default)
@profiler
def write(self):
with self.db.lock:
if self.file_exists():
self._write_pending_changes()
else:
#if self.pending_changes:
self._write()
def _write_pending_changes(self):
if threading.currentThread().isDaemon():
self.logger.warning('daemon thread cannot write db')
return
if not self.db.pending_changes:
return
s = ''.join([',\n' + x for x in self.db.pending_changes])
s = self.encrypt_for_append(s)
with open(self.path, "rb+") as f:
f.seek(0, os.SEEK_END)
if self.pubkey:
size = f.tell()
f.seek(size-48, 0)
f.write(s)
f.flush()
os.fsync(f.fileno())
self.db.pending_changes = []
def _write(self):
if threading.currentThread().isDaemon():
self.logger.warning('daemon thread cannot write db')
return
if not self.db.modified():
return
s = self.encrypt_for_write(self.db.dump())
temp_path = "%s.tmp.%s" % (self.path, os.getpid())
with open(temp_path, "wb") as f:
f.write(s)
f.flush()
os.fsync(f.fileno())
mode = os.stat(self.path).st_mode if self.file_exists() else stat.S_IREAD | stat.S_IWRITE
# assert that wallet file does not exist, to prevent wallet corruption (see issue #5082)
if not self.file_exists():
assert not os.path.exists(self.path)
os.replace(temp_path, self.path)
os.chmod(self.path, mode)
self._file_exists = True
self.logger.info(f"saved {self.path}")
self.db.pending_changes = []
self.db.set_modified(False)
def file_exists(self) -> bool:
return self._file_exists
def is_past_initial_decryption(self):
"""Return if storage is in a usable state for normal operations.
The value is True exactly
if encryption is disabled completely (self.is_encrypted() == False),
or if encryption is enabled but the contents have already been decrypted.
"""
try:
return bool(self.db.data)
except AttributeError:
return False
def is_encrypted(self):
"""Return if storage encryption is currently enabled."""
return self.get_encryption_version() != StorageEncryptionVersion.PLAINTEXT
def is_encrypted_with_user_pw(self):
return self.get_encryption_version() == StorageEncryptionVersion.USER_PASSWORD
def is_encrypted_with_hw_device(self):
return self.get_encryption_version() == StorageEncryptionVersion.XPUB_PASSWORD
def get_encryption_version(self):
"""Return the version of encryption used for this storage.
0: plaintext / no encryption
ECIES, private key derived from a password,
1: password is provided by user
2: password is derived from an xpub; used with hw wallets
"""
return self._encryption_version
def _init_encryption_version(self):
try:
s = base64.b64decode(self.raw)
if s.startswith(b'BIE'):
self.raw = s
self.is_base64 = True
else:
self.is_base64 = False
except:
self.is_base64 = False
magic = self.raw[0:4]
if magic == b'BIE1':
return StorageEncryptionVersion.USER_PASSWORD
elif magic == b'BIE2':
return StorageEncryptionVersion.XPUB_PASSWORD
else:
return StorageEncryptionVersion.PLAINTEXT
@staticmethod
def get_eckey_from_password(password):
secret = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), b'', iterations=1024)
ec_key = ecc.ECPrivkey.from_arbitrary_size_secret(secret)
return ec_key
def _get_encryption_magic(self):
v = self._encryption_version
if v == StorageEncryptionVersion.USER_PASSWORD:
return b'BIE1'
elif v == StorageEncryptionVersion.XPUB_PASSWORD:
return b'BIE2'
else:
raise WalletFileException('no encryption magic for version: %s' % v)
def decrypt(self, password):
ec_key = self.get_eckey_from_password(password)
if self.raw:
encrypted = self.raw
enc_magic = self._get_encryption_magic()
self.key_e, self.key_m, iv, ciphertext, mac = ec_key.decode_encrypted(encrypted, enc_magic)
self.mac = hmac.new(self.key_m, encrypted[:-32-16], hashlib.sha256)
m2 = self.mac.copy()
assert ciphertext[-16:] == encrypted[-32-16:-32]
m2.update(ciphertext[-16:])
if m2.digest() != mac:
raise InvalidPassword()
last_block = ciphertext[-16:]
s = aes_decrypt_with_iv(self.key_e, iv, ciphertext)
iv2 = iv if len(ciphertext)==16 else ciphertext[-32:-16]
last_blob = aes_decrypt_with_iv(self.key_e, iv2, last_block)
assert last_block == aes_encrypt_with_iv(self.key_e, iv2, last_blob)
#assert last_blob
self.iv = iv2
self.last_blob = last_blob
else:
s = None
if self.is_base64:
s = zlib.decompress(s)
self.pubkey = ec_key.get_public_key_hex()
s = s.decode('utf8')
self.db = WalletDB(s, manual_upgrades=True)
self._write()
self.load_plugins()
def encrypt_for_write(self, plaintext: str) -> str:
s = bytes(plaintext, 'utf8')
if self.pubkey:
enc_magic = self._get_encryption_magic()
public_key = ecc.ECPubkey(bfh(self.pubkey))
encrypted, ciphertext, key_e, key_m, iv, mac = public_key._encrypt_message(s, enc_magic)
s = encrypted + mac
# save mac, last_blob, key_e, key_m, and iv, for subsequent encr
self.key_e = key_e
self.key_m = key_m
self.iv = ciphertext[-32:-16]
self.last_blob = aes_decrypt_with_iv(self.key_e, self.iv, ciphertext[-16:])
self.mac = hmac.new(self.key_m, encrypted[:-16], hashlib.sha256)
return s
def encrypt_for_append(self, plaintext: str) -> str:
s = bytes(plaintext, 'utf8')
if self.pubkey:
enc_magic = self._get_encryption_magic()
ciphertext = aes_encrypt_with_iv(self.key_e, self.iv, self.last_blob + s)
self.iv = self.iv if len(ciphertext)==16 else ciphertext[-32:-16]
self.last_blob = aes_decrypt_with_iv(self.key_e, self.iv, ciphertext[-16:])
# self.mac does not include the last block
self.mac.update(ciphertext[0:-16])
m2 = self.mac.copy()
m2.update(ciphertext[-16:])
mac = m2.digest()
s = ciphertext + mac
return s
def check_password(self, password):
"""Raises an InvalidPassword exception on invalid password"""
if not self.is_encrypted():
return
if self.pubkey and self.pubkey != self.get_eckey_from_password(password).get_public_key_hex():
raise InvalidPassword()
def set_keystore_encryption(self, enable):
self.put('use_encryption', enable)
def set_password(self, password, enc_version=None):
"""Set a password to be used for encrypting this storage."""
if enc_version is None:
enc_version = self._encryption_version
if password and enc_version != StorageEncryptionVersion.PLAINTEXT:
ec_key = self.get_eckey_from_password(password)
self.pubkey = ec_key.get_public_key_hex()
self._encryption_version = enc_version
else:
self.pubkey = None
self._encryption_version = StorageEncryptionVersion.PLAINTEXT
# make sure next storage.write() saves changes
self.db.set_modified(True)
def requires_upgrade(self):
if not self.is_past_initial_decryption():
raise Exception("storage not yet decrypted!")
return self.db.requires_upgrade()
def is_ready_to_be_used_by_wallet(self):
return not self.requires_upgrade() and self.db._called_after_upgrade_tasks
def upgrade(self):
self.db.upgrade()
self._write()
def requires_split(self):
return self.db.requires_split()
def split_accounts(self):
out = []
result = self.db.split_accounts()
for data in result:
path = self.path + '.' + data['suffix']
storage = WalletStorage(path)
storage.db.data = data
storage.db._called_after_upgrade_tasks = False
storage.db.upgrade()
storage.write()
out.append(path)
return out
def get_action(self):
action = run_hook('get_action', self)
return action