Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 136 additions & 11 deletions src/seedsigner/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from PIL.Image import Image

from seedsigner.gui.toast import BaseToastOverlayManagerThread
from seedsigner.helpers.secure_delete import wipe_dict, wipe_private_key, wipe_value
from seedsigner.models.psbt_parser import PSBTParser
from seedsigner.models.seed import Seed
from seedsigner.models.seed_storage import SeedStorage
Expand All @@ -20,6 +21,7 @@
from seedsigner.models.settings import SettingsConstants
from seedsigner.models.singleton import Singleton
from seedsigner.models.threads import BaseThread
from seedsigner.models.wif import WIFKey
from seedsigner.models.settings_definition import SettingsConstants
from seedsigner.views.screensaver import ScreensaverScreen
from seedsigner.views.view import Destination, View
Expand Down Expand Up @@ -135,13 +137,23 @@ def run(self):
controller = Controller.get_instance()
buttons = HardwareButtons.get_instance()
while self.keep_running:
wipe_minutes = controller.settings.get_value(SettingsConstants.SETTING__WIPE_TIMER)
if wipe_minutes and wipe_minutes != SettingsConstants.WIPE_TIMER__DISABLED:
controller.wipe_timer_ms = wipe_minutes * 60 * 1000
cur = int(time.time() * 1000)
if controller.wipe_timer_ms and cur - buttons.last_input_time > controller.wipe_timer_ms:
controller.handle_wipe_timeout()
buttons.update_last_input_time()
# This thread is the only thing that runs the inactivity wipe. An
# exception that ended it would turn the wipe off, without a word,
# for the rest of the session.
try:
wipe_minutes = controller.settings.get_value(SettingsConstants.SETTING__WIPE_TIMER)
if wipe_minutes and wipe_minutes != SettingsConstants.WIPE_TIMER__DISABLED:
controller.wipe_timer_ms = wipe_minutes * 60 * 1000
cur = int(time.time() * 1000)
if controller.wipe_timer_ms and cur - buttons.last_input_time > controller.wipe_timer_ms:
try:
controller.handle_wipe_timeout()
finally:
# A failed wipe is retried after the next full
# interval, not every second.
buttons.update_last_input_time()
except Exception:
logger.exception("Inactivity wipe failed; the timer keeps running")
time.sleep(1)


Expand Down Expand Up @@ -573,6 +585,10 @@ def run(self):
if next_destination.View_cls == MainMenuView:
# Home always wipes the back_stack
self.clear_back_stack()

# A WIF or BIP38 key never enters SeedStorage: once the
# psbt state below drops it, nothing else can zero it.
self.wipe_psbt_wif_keys()

# Home always wipes the back_stack/state of temp vars
self.resume_main_flow = None
Expand Down Expand Up @@ -793,12 +809,69 @@ def handle_wipe_timeout(self):
except Exception:
logger.debug("Error wiping seed on auto-wipe", exc_info=True)
self.storage.seeds = []
self.storage.clear_pending_seed()
# A half-finished seed entry keeps its words in SeedStorage rather than
# in a Seed, so those buffers need clearing too. Each clear is looked up
# and called on its own: whatever one of them does, the wipe still has
# to finish.
for clear_buffer in ("clear_pending_seed", "discard_pending_mnemonic",
"discard_pending_slip39_shares"):
clear = getattr(self.storage, clear_buffer, None)
if clear is None:
logger.warning("Storage has no %s; those buffers stay", clear_buffer)
continue
try:
clear()
except Exception:
logger.debug("Error in %s on auto-wipe", clear_buffer, exc_info=True)
if self._storage2:
# The key typed or scanned to decrypt an EncryptedQR.
encryptedqr = self._storage2.encryptedqr
self._wipe_step("the EncryptedQR key", wipe_value,
getattr(encryptedqr, "encryption_key", None))
self._storage2.clear_encryptedqr()

# psbt_seed can hold a WIFKey, which never enters storage.seeds and so
# is missed by the loop above. The parser can hold one that psbt_seed
# has already let go of: Back from the overview and a signature that
# did not verify both clear psbt_seed alone. Wiped here, before
# anything below lets go of the references.
parser = self.psbt_parser
signers = [self.psbt_seed]
parser_seed = getattr(parser, "seed", None)
if parser_seed is not self.psbt_seed:
signers.append(parser_seed)
for signer in signers:
if signer is None:
continue
try:
signer.wipe()
except Exception:
logger.debug("Error wiping a psbt signer on auto-wipe", exc_info=True)

# The parser also keeps a root key of its own. From a BIP-39 seed it is
# a new HDKey, which wiping the seed does not reach. Zeroed here only:
# an XprvSeed hands the parser its own root, and a route that keeps
# the seed, such as Home, must leave that intact.
if parser is not None:
self._wipe_step("the psbt parser's root key", wipe_private_key,
getattr(parser, "root", None))

# GlobalPlatform card master keys: plaintext ENC/MAC/DEK that can
# re-key or unlock a JavaCard, so they cannot outlive the session.
# Only the keys are secret; the "type" tag is a code constant.
self._wipe_step("the JavaCard keys", wipe_dict, self.javacard_keys,
("key", "enc", "mac", "dek"))
self.javacard_keys = None

self._wipe_step("the smartcard session secrets",
self._wipe_smartcard_session_secrets)

# Raw password-generator entropy (dice rolls / BIP85 bytes) must not
# survive the inactivity wipe either.
# survive the inactivity wipe either. The password type and entropy
# source next to it are code constants, not secrets.
self._wipe_step("the password entropy", wipe_dict,
self.password_generator_entropy_cache,
("roll_data", "entropy_bytes"))
self.password_generator_entropy_cache = None

self.psbt = None
Expand Down Expand Up @@ -834,6 +907,55 @@ def handle_wipe_timeout(self):
HardwareButtons.get_instance().trigger_override()


@staticmethod
def _wipe_step(what: str, wipe, *args) -> None:
"""Run one zeroing step of the inactivity wipe, logging a failure.

Every secret has to be zeroed even when zeroing another one fails, so
no step may raise into the ones after it.
"""
try:
wipe(*args)
except Exception:
logger.debug("Error wiping %s on auto-wipe", what, exc_info=True)


def _wipe_smartcard_session_secrets(self):
"""Zero the smartcard session secrets where they are held.

The card PINs and the Satodime unlock secrets are lists of ints, and
the OpenPGP admin PIN is a str. Setting the attributes to None only
drops the references. The connector's own copy of the PIN goes back
to None rather than an empty list: pysatochip reuses a cached PIN
that is not None, and an empty one would cost a PIN try.
"""
connector = self.Satochip_Connector
for secret in (self.Satochip_PIN, getattr(connector, "pin", None), self.GPG_Admin_PIN):
wipe_value(secret)
for secret in (self.Satodime_unlock_secrets or {}).values():
wipe_value(secret)
for _card_id, secret in (self.Satodime_unlock_nicknames or {}).values():
wipe_value(secret)
if connector is not None:
connector.pin = None


def wipe_psbt_wif_keys(self):
"""Zero any WIF key the psbt flow holds, in psbt_seed or in the parser.

Back from the overview and a signature that did not verify clear
psbt_seed alone, so the parser can be the last holder. A stored seed
is left alone: it outlives the flow, and an XprvSeed shares its root
key with the parser.
"""
for signer in (self.psbt_seed, getattr(self.psbt_parser, "seed", None)):
if isinstance(signer, WIFKey):
try:
signer.wipe()
except Exception:
logger.debug("Error wiping a WIF key", exc_info=True)


def handle_exception(self, e) -> Destination:
"""
Displays a user-friendly error screen and includes debugging info to help
Expand Down Expand Up @@ -888,6 +1010,9 @@ def is_screensaver_start_allowed(self) -> bool:
- The current active view allows screensaver activity.
"""
from seedsigner.views import MainMenuView
# Confusingly, the top item in the `BackStack` is actually the *current* View
active_view = self.back_stack[-1].view if self.back_stack else MainMenuView()
# Confusingly, the top item in the `BackStack` is actually the *current* View.
# A Destination has no view until it has run, and the inactivity wipe
# leaves one for the main menu that the loop has yet to run.
top = self.back_stack[-1] if self.back_stack else None
active_view = getattr(top, "view", None) or MainMenuView()
return not self.is_screensaver_running and active_view.is_screensaver_allowed
66 changes: 64 additions & 2 deletions src/seedsigner/helpers/secure_delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,19 @@ def _collect_wordlist_ids() -> frozenset:
def _is_shared(obj) -> bool:
"""Return True if *obj* appears to be shared or immortal.

Two detection mechanisms are used:
Three detection mechanisms are used:

1. **Wordlist-ID check**: if ``id(obj)`` is in the pre-computed set of
BIP-39 / SLIP-39 wordlist entry IDs the string is always considered
shared. This is reliable on all CPython versions because the wordlist
objects are module-level singletons that live for the entire process.

2. **Refcount check**: if the reference count returned by
2. **Length check**: CPython keeps a single object for each one-byte
bytes value and each Latin-1 one-character str. Before 3.11 their
refcounts are ordinary, so the refcount check cannot tell them from
a private copy.

3. **Refcount check**: if the reference count returned by
``sys.getrefcount`` is at or above ``_SHARED_REFCOUNT_LIMIT`` the
string is considered shared. This catches immortal strings on
CPython 3.12+ (where the sentinel refcount is ~4 billion) as well as
Expand All @@ -97,6 +102,8 @@ def _is_shared(obj) -> bool:
"""
if isinstance(obj, str) and id(obj) in _WORDLIST_IDS:
return True
if isinstance(obj, (str, bytes)) and len(obj) == 1:
return True
return sys.getrefcount(obj) >= _SHARED_REFCOUNT_LIMIT


Expand All @@ -122,6 +129,15 @@ def wipe_bytes(b: bytes | bytearray | None) -> None:
b[i] = 0
return
if isinstance(b, bytes) and len(b) > 0:
# Same guard as wipe_string(): a bytes object the interpreter shares
# would be zeroed for every other user of it.
if _is_shared(b):
logger.warning(
"wipe_bytes: refusing to wipe shared/immortal bytes "
"(refcount=%d)",
sys.getrefcount(b),
)
return
_wipe_buffer(b, len(b))


Expand Down Expand Up @@ -163,4 +179,50 @@ def wipe_list(lst: list | None) -> None:
wipe_bytes(item)
elif isinstance(item, str):
wipe_string(item)
# The slots give a secret away too. An int element (a PIN digit, a byte of
# an unlock secret) has no buffer to zero, only the cached int it points
# at, and a wordlist word the guard left alone is known by its address.
# clear() frees the slot array with those pointers still in it.
for index in range(len(lst)):
lst[index] = 0
lst.clear()


def wipe_value(value) -> None:
"""Wipe one secret held as str, bytes, bytearray or list; ignore the rest."""
if isinstance(value, (bytes, bytearray)):
wipe_bytes(value)
elif isinstance(value, str):
wipe_string(value)
elif isinstance(value, list):
wipe_list(value)


def wipe_dict(d: dict | None, keys) -> None:
"""Wipe the values stored under *keys*, then clear the dict.

Only the named values are wiped. A dict of secrets carries metadata too,
such as a type tag or a source name, and that is usually a code constant.
On CPython < 3.12 a constant is not immortal and has fewer references than
_SHARED_REFCOUNT_LIMIT, so wipe_string() would zero it in place for every
other user of the same object.
"""
if d is None:
return
for key in keys:
wipe_value(d.get(key))
d.clear()


def wipe_private_key(key) -> None:
"""Zero an embit private key in place: a PrivateKey, or a private HDKey.

A public key is left alone. It is not secret, and it can be shared with
state that still needs it.
"""
if key is None or not getattr(key, "is_private", False):
return
inner = getattr(key, "key", key)
wipe_bytes(getattr(inner, "_secret", None))
if inner is not key:
wipe_bytes(getattr(key, "chain_code", None))
8 changes: 7 additions & 1 deletion src/seedsigner/models/seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from embit.networks import NETWORKS
from typing import List

from seedsigner.helpers.secure_delete import wipe_bytes, wipe_string, wipe_list
from seedsigner.helpers.secure_delete import wipe_bytes, wipe_string, wipe_list, wipe_private_key
from seedsigner.models.settings import SettingsConstants
from seedsigner.models import aezeed

Expand Down Expand Up @@ -338,6 +338,8 @@ def __init__(self, mnemonics: List[str], slip39_passphrase: str = "") -> None:
# Passphrase used to decrypt the shares
self._slip39_passphrase: str = unicodedata.normalize("NFKD", slip39_passphrase) if slip39_passphrase else ""

self._mnemonic: List[str] = []
self._passphrase: str = ""
self.seed_bytes: bytes = None
self.master_secret: bytes | None = None
self._initial_master_secret: bytes | None = None
Expand Down Expand Up @@ -489,6 +491,7 @@ def __init__(self, xprv: str) -> None:
self._xprv = normalized
self._root = root
self._wordlist_language_code = SettingsConstants.WORDLIST_LANGUAGE__ENGLISH
self._mnemonic: List[str] = []
self._passphrase = ""
self.seed_bytes = None
self.master_secret = None
Expand Down Expand Up @@ -535,6 +538,9 @@ def wipe(self):
"""Securely clear xprv-specific fields, then delegate to parent."""
wipe_string(self._xprv)
self._xprv = ""
# The HDKey parsed from the xprv holds the key and chain code in bytes
# of its own; dropping the reference leaves them in freed memory.
wipe_private_key(self._root)
self._root = None
super().wipe()

Expand Down
16 changes: 13 additions & 3 deletions src/seedsigner/models/seed_storage.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import logging
from typing import List
from seedsigner.helpers.secure_delete import wipe_bytes, wipe_list
from seedsigner.models.seed import Seed, ElectrumSeed, AezeedSeed, Slip39Seed, InvalidSeedException
from seedsigner.models.settings_definition import SettingsConstants

logger = logging.getLogger(__name__)



class SeedStorage:
Expand Down Expand Up @@ -37,9 +40,16 @@ def finalize_pending_seed(self) -> Seed:


def clear_pending_seed(self):
if self.pending_seed is not None:
self.pending_seed.wipe()
self.pending_seed = None
# Zeroing the secret material is best-effort, as in
# Controller.discard_seed(): a failed wipe must not leave the caller
# holding on to a seed it asked to drop.
try:
if self.pending_seed is not None:
self.pending_seed.wipe()
except Exception:
logger.debug("Error wiping pending seed", exc_info=True)
finally:
self.pending_seed = None


def validate_mnemonic(self, mnemonic: List[str]) -> bool:
Expand Down
12 changes: 12 additions & 0 deletions src/seedsigner/models/wif.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from embit import ec, hashes

from seedsigner.helpers.secure_delete import wipe_private_key, wipe_string
from seedsigner.models.seed import InvalidSeedException
from seedsigner.models.settings import SettingsConstants

Expand All @@ -17,6 +18,17 @@ def __init__(self, wif: str):
raise InvalidSeedException("Invalid WIF") from e
self.wif = wif

def wipe(self):
"""Zero the key material, to the same contract as Seed.wipe().

A WIFKey never enters SeedStorage, so nothing else zeroes it; dropping
the reference would leave the secret in freed heap pages.
"""
wipe_private_key(self.privkey)
self.privkey = None
wipe_string(self.wif)
self.wif = ""

def get_fingerprint(self, network: str = SettingsConstants.MAINNET) -> str:
"""Return BIP32-style fingerprint for the key's public key."""
pub = self.privkey.get_public_key()
Expand Down
Loading