Skip to content

Commit f495511

Browse files
committed
safer os.chmod for wallet files and config: set perms before write
Set unix file permissions first, before writing data.
1 parent 6d37e46 commit f495511

File tree

3 files changed

+7
-7
lines changed

3 files changed

+7
-7
lines changed

electrum/gui/qt/main_window.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2332,7 +2332,7 @@ def on_dialog_closed(*args):
23322332

23332333
def do_export_privkeys(self, fileName, pklist, is_csv):
23342334
with open(fileName, "w+") as f:
2335-
os_chmod(fileName, 0o600)
2335+
os_chmod(fileName, 0o600) # set restrictive perms *before* we write data
23362336
if is_csv:
23372337
transaction = csv.writer(f)
23382338
transaction.writerow(["address", "private_key"])

electrum/simple_config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -421,8 +421,8 @@ def save_user_config(self):
421421
s = json.dumps(self.user_config, indent=4, sort_keys=True)
422422
try:
423423
with open(path, "w", encoding='utf-8') as f:
424+
os_chmod(path, stat.S_IREAD | stat.S_IWRITE) # set restrictive perms *before* we write data
424425
f.write(s)
425-
os_chmod(path, stat.S_IREAD | stat.S_IWRITE)
426426
except OSError:
427427
# datadir probably deleted while running... e.g. portable exe running on ejected USB drive
428428
# (in which case it is typically either FileNotFoundError or PermissionError,

electrum/storage.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -87,22 +87,22 @@ def read(self):
8787
return self.decrypted if self.is_encrypted() else self.raw
8888

8989
def write(self, data: str) -> None:
90+
try:
91+
mode = os.stat(self.path).st_mode
92+
except FileNotFoundError:
93+
mode = stat.S_IREAD | stat.S_IWRITE
9094
s = self.encrypt_before_writing(data)
9195
temp_path = "%s.tmp.%s" % (self.path, os.getpid())
9296
with open(temp_path, "wb") as f:
97+
os_chmod(temp_path, mode) # set restrictive perms *before* we write data
9398
f.write(s.encode("utf-8"))
9499
self.pos = f.seek(0, os.SEEK_END)
95100
f.flush()
96101
os.fsync(f.fileno())
97-
try:
98-
mode = os.stat(self.path).st_mode
99-
except FileNotFoundError:
100-
mode = stat.S_IREAD | stat.S_IWRITE
101102
# assert that wallet file does not exist, to prevent wallet corruption (see issue #5082)
102103
if not self.file_exists():
103104
assert not os.path.exists(self.path)
104105
os.replace(temp_path, self.path)
105-
os_chmod(self.path, mode)
106106
self._file_exists = True
107107
self.logger.info(f"saved {self.path}")
108108

0 commit comments

Comments
 (0)