Fix device wipe on final PIN attempt (#380)
What changed, and why it matters
This commit fixes a bug in the Specter DIY hardware wallet's PIN retry logic. Previously, on the 10th and final PIN attempt, the device would wipe itself before checking whether the entered PIN was actually correct. That meant a legitimate user who simply mistyped nine times and then entered the right PIN on the 10th try would still lose all wallet data. The fix checks the PIN first on the final attempt, wiping only if the final attempt is wrong, and also ensures a power cut cannot be exploited to gain an extra attempt.
Users running affected firmware should upgrade to a version containing this commit to avoid the risk of legitimate PINs wiping the device on the final attempt. Developers should review any custom keystore implementations for similar counter decrement/verify ordering bugs.
Security signals we found
PIN brute-force counter off-by-one causing premature wipe on correct final PIN
Power-cut rewind attack mitigated by persisting counter before PIN verification
Fail-closed behavior on reboot with exhausted or negative attempt counter
Local wipe failure no longer suppresses critical-wipe exception propagation
Security model documentation updated to describe corrected behavior
Evidence from the diff
The patch changes src/keystore/flash.py so that _unlock() first verifies whether the persisted attempt counter is already exhausted and wipes immediately in that case (fail-closed on reboot). It then decrements and persists the counter before PIN verification (to prevent power-cut rewind attacks), but only triggers the wipe if the final attempt’s PIN is incorrect. A new helper _wipe_critical() ensures that even if the local wipe() call fails, the global CriticalErrorWipeImmediately exception is still raised. The security model documentation is updated to reflect that the 10th correct PIN now unlocks, while an incorrect 10th PIN wipes. New unit tests cover the state machine, including persisted-zero/negative counters and local wipe failures.
Changed components
src/keystore/flash.pydocs/security-model.mdtest/tests_native/test_keystore.pyInspect captured patch +193 / −14
### docs/security-model.md
@@ -165,12 +165,12 @@ enabling readout protection (see "Readout and write protection").
Brute-force protection is enforced on the device:
-- At most **10 PIN attempts** are allowed; afterwards the device wipes
- itself. Note: in the current implementation the attempt counter is
- decremented and persisted *before* the PIN is checked, so the 10th
- attempt already triggers the wipe without verifying the PIN first —
- effectively 9 verification attempts instead of the intended 10 (fail-safe
- direction; a correct PIN entered on the 10th attempt still wipes).
+- At most **10 PIN attempts** are allowed. The counter is decremented and
+ persisted before each PIN check; the correct 10th PIN still unlocks, while
+ an incorrect 10th PIN wipes the device.
+- If the device boots with an exhausted counter (`<= 0`), it wipes without
+ performing another PIN check. Thus a power cut after consuming the last
+ attempt cannot create an additional attempt.
- The PIN check is an HMAC keyed with the internal secret, so the PIN
cannot be brute-forced offline from flash contents alone.
- The PIN state file is authenticated; tampering with it triggers a wipe
### src/keystore/flash.py
@@ -63,11 +63,17 @@ def load_state(self):
self._pin_attempts_left = data["pin_attempts_left"]
except Exception as e:
# this happens if someone tries to change PIN file
- self.wipe(self.path)
- raise CriticalErrorWipeImmediately(
+ self._wipe_critical(
"Something went terribly wrong!\nDevice is wiped!\n%s" % e
)
+ def _wipe_critical(self, message):
+ """Wipe locally, but always propagate the global critical-wipe error."""
+ try:
+ self.wipe(self.path)
+ finally:
+ raise CriticalErrorWipeImmediately(message)
+
def create_empty_pin_file(self):
self.pin = None
self._pin_attempts_max = 10
@@ -111,23 +117,30 @@ def _unlock(self, pin):
Unlock the keystore, raises PinError if PIN is invalid.
Raises CriticalErrorWipeImmediately if no attempts left.
"""
- # if anything goes wrong here - wipe
+ # A persisted exhausted counter is terminal. Check it before any
+ # decrement or PIN verification so a power cut cannot create a new
+ # usable attempt.
try:
+ if self._pin_attempts_left <= 0:
+ self._wipe_critical("No more PIN attempts!\nWipe!")
# decrease the counter
self._pin_attempts_left -= 1
self.save_state()
- # check we have attempts
- if self._pin_attempts_left <= 0:
- self.wipe(self.path)
- raise CriticalErrorWipeImmediately("No more PIN attempts!\nWipe!")
+ except CriticalErrorWipeImmediately:
+ raise
except Exception as e:
# convert any error to a critical error to wipe the device
raise CriticalErrorWipeImmediately(str(e))
# calculate hmac with entered PIN
key = tagged_hash("pin", self.secret)
pin_hmac = hmac.new(key=key, msg=pin.encode(), digestmod="sha256").digest()
- # check hmac is the same (constant-time compare, L6 - do not replace with == / !=)
+ # Check the HMAC with a constant-time comparison (L6).
if not consteq(pin_hmac, self.pin):
+ # The counter is decreased before verification to protect against
+ # power-cut rewind attacks. Wipe only when the final attempt was
+ # actually wrong.
+ if self._pin_attempts_left <= 0:
+ self._wipe_critical("No more PIN attempts!\nWipe!")
raise PinError(
"Invalid PIN!\n%d of %d attempts left..."
% (self._pin_attempts_left, self._pin_attempts_max)
### test/tests_native/__init__.py
@@ -8,3 +8,4 @@
from .test_transaction_confirmation import *
from .test_change_security import *
from .test_embed_git_info import *
+from .test_keystore import *
### test/tests_native/test_keystore.py
@@ -0,0 +1,165 @@
+import hmac
+from unittest import TestCase
+from unittest.mock import patch
+
+import keystore.flash as flash_module
+import platform
+from helpers import tagged_hash
+from keystore.core import PinError
+from keystore.flash import FlashKeyStore
+
+
+CORRECT_PIN = "1234"
+WRONG_PIN = "0000"
+
+
+class InMemoryFlashKeyStore(FlashKeyStore):
+ """Small persistence/wipe double for the PIN state-machine tests."""
+
+ def __init__(self, state=None):
+ super().__init__()
+ self.state = {} if state is None else state
+ self.wipe_calls = 0
+ self.wipe_error = None
+
+ def save_state(self):
+ self.state.update(
+ pin=self.pin,
+ pin_attempts_max=self._pin_attempts_max,
+ pin_attempts_left=self._pin_attempts_left,
+ )
+
+ def load_state(self):
+ if self.state:
+ self.pin = self.state["pin"]
+ self._pin_attempts_max = self.state["pin_attempts_max"]
+ self._pin_attempts_left = self.state["pin_attempts_left"]
+
+ def load_enc_secret(self):
+ self.enc_secret = b"encryption secret"
+
+ def wipe(self, path):
+ self.wipe_calls += 1
+ if self.wipe_error is not None:
+ raise self.wipe_error
+
+
+class FailingLoadStateKeyStore(FlashKeyStore):
+ def __init__(self):
+ super().__init__()
+ self.wipe_calls = 0
+ self.wipe_error = None
+
+ def load_aead(self, path, key=None):
+ raise RuntimeError("invalid PIN state")
+
+ def wipe(self, path):
+ self.wipe_calls += 1
+ if self.wipe_error is not None:
+ raise self.wipe_error
+
+
+def configure_pin(keystore, attempts_left=10):
+ keystore.secret = b"s" * 32
+ keystore.pin = hmac.new(
+ tagged_hash("pin", keystore.secret),
+ CORRECT_PIN.encode(),
+ digestmod="sha256",
+ ).digest()
+ keystore._pin_attempts_left = attempts_left
+ keystore._pin_attempts_max = 10
+ keystore._is_locked = True
+ keystore.save_state()
+
+
+class FlashKeyStorePinStateTest(TestCase):
+ def test_nine_wrong_pins_leave_one_attempt(self):
+ keystore = InMemoryFlashKeyStore()
+ configure_pin(keystore)
+ for _ in range(9):
+ with self.assertRaises(PinError):
+ keystore._unlock(WRONG_PIN)
+ self.assertEqual(keystore.pin_attempts_left, 1)
+ self.assertEqual(keystore.wipe_calls, 0)
+
+ def test_correct_tenth_pin_unlocks_and_resets_counter(self):
+ keystore = InMemoryFlashKeyStore()
+ configure_pin(keystore)
+ for _ in range(9):
+ with self.assertRaises(PinError):
+ keystore._unlock(WRONG_PIN)
+ keystore._unlock(CORRECT_PIN)
+ self.assertEqual(keystore.pin_attempts_left, keystore.pin_attempts_max)
+ self.assertFalse(keystore.is_locked)
+ self.assertEqual(keystore.wipe_calls, 0)
+
+ def test_wrong_tenth_pin_triggers_critical_wipe(self):
+ keystore = InMemoryFlashKeyStore()
+ configure_pin(keystore)
+ for _ in range(9):
+ with self.assertRaises(PinError):
+ keystore._unlock(WRONG_PIN)
+ with self.assertRaises(platform.CriticalErrorWipeImmediately):
+ keystore._unlock(WRONG_PIN)
+ self.assertEqual(keystore.pin_attempts_left, 0)
+ self.assertEqual(keystore.wipe_calls, 1)
+
+ def test_persisted_zero_reboot_skips_pin_verification(self):
+ state = {}
+ keystore = InMemoryFlashKeyStore(state)
+ configure_pin(keystore, attempts_left=0)
+ rebooted = InMemoryFlashKeyStore(state)
+ rebooted.load_state()
+ with patch.object(
+ flash_module, "tagged_hash", side_effect=AssertionError("PIN checked")
+ ):
+ with self.assertRaises(platform.CriticalErrorWipeImmediately):
+ rebooted._unlock(CORRECT_PIN)
+ self.assertEqual(rebooted.pin_attempts_left, 0)
+ self.assertEqual(rebooted.wipe_calls, 1)
+
+ def test_negative_persisted_counter_is_fail_closed(self):
+ state = {}
+ keystore = InMemoryFlashKeyStore(state)
+ configure_pin(keystore, attempts_left=-1)
+ rebooted = InMemoryFlashKeyStore(state)
+ rebooted.load_state()
+ with patch.object(
+ flash_module, "tagged_hash", side_effect=AssertionError("PIN checked")
+ ):
+ with self.assertRaises(platform.CriticalErrorWipeImmediately):
+ rebooted._unlock(CORRECT_PIN)
+ self.assertEqual(rebooted.pin_attempts_left, -1)
+ self.assertEqual(rebooted.wipe_calls, 1)
+
+ def test_failed_local_wipe_still_triggers_critical_wipe(self):
+ keystore = InMemoryFlashKeyStore()
+ configure_pin(keystore, attempts_left=1)
+ keystore.wipe_error = RuntimeError("wipe failed")
+ with self.assertRaises(platform.CriticalErrorWipeImmediately):
+ keystore._unlock(WRONG_PIN)
+ self.assertEqual(keystore.wipe_calls, 1)
+
+ def test_power_cut_after_persisting_zero_cannot_add_attempt(self):
+ state = {}
+ keystore = InMemoryFlashKeyStore(state)
+ configure_pin(keystore, attempts_left=1)
+ keystore._pin_attempts_left -= 1
+ keystore.save_state()
+ rebooted = InMemoryFlashKeyStore(state)
+ rebooted.load_state()
+ with patch.object(
+ flash_module, "tagged_hash", side_effect=AssertionError("PIN checked")
+ ):
+ with self.assertRaises(platform.CriticalErrorWipeImmediately):
+ rebooted._unlock(CORRECT_PIN)
+ self.assertEqual(rebooted.pin_attempts_left, 0)
+
+ def test_load_state_wipe_failure_still_triggers_critical_wipe(self):
+ keystore = FailingLoadStateKeyStore()
+ keystore.path = "testdir"
+ keystore.wipe_error = RuntimeError("wipe failed")
+ with patch.object(flash_module.platform, "file_exists", return_value=True):
+ with self.assertRaises(platform.CriticalErrorWipeImmediately):
+ keystore.load_state()
+ self.assertEqual(keystore.wipe_calls, 1)Why this scored 60/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.