Use constant-time comparison for security-sensitive MAC/PIN checks (#388)
What changed, and why it matters
This commit fixes a timing side-channel leak in Specter DIY, a hardware wallet. Previously, when the device compared a user-entered PIN or a secure-channel MAC against the expected value, it used Python's ordinary `==` on bytes, which stops at the first mismatching byte. An attacker with very precise timing measurements could potentially learn how many leading bytes were correct, narrowing down guesses. The patch replaces those comparisons with a constant-time function that always scans every byte, and adds tests to prevent accidental regression. The practical exploit is hard because it requires local, high-precision timing access to a hardware wallet, but the fix is clearly security-relevant.
Ensure this commit is included in any release firmware build. Run the new tests (`test_helpers.py`, `test_keystore.py`, `test_securechannel.py`) in CI to prevent regressions. Review any remaining `==`/`!=` comparisons on secret or authentication values elsewhere in the codebase. Consider whether the non-constant-time length check in `consteq` is acceptable for all call sites (it is for fixed-length HMACs/PINs, but should not be used for secret-length data).
Security signals we found
Timing side-channel fix for MAC/PIN comparisons
New constant-time comparison helper `consteq`
Replaced `==` on HMACs with `consteq` in AEAD, PIN, and secure-channel code
Added regression tests for tampered MAC rejection and PIN behavior
Comments warn against reverting to `==` or adding early-exit returns
Evidence from the diff
The change introduces helpers.consteq(a: bytes, b: bytes) -> bool, a fixed-work XOR-OR comparison suitable for fixed-length authentication tags. It replaces plain == comparisons in three security-critical paths: (1) AEAD storage MAC verification in helpers.aead_decrypt, (2) PIN HMAC verification in keystore.flash.FlashKeyStore._unlock, and (3) smartcard secure-channel HMAC verification in keystore.javacard.applets.securechannel during open() (both EE and SE modes) and decrypt(). The patch also adds regression tests for consteq, AEAD tampering, PIN unlock behavior, and SecureChannel HMAC rejection. The commit message and comments explicitly frame this as a security fix against timing side channels.
Changed components
src/helpers.pysrc/keystore/flash.pysrc/keystore/javacard/applets/securechannel.pytest/tests/test_helpers.pytest/tests/test_keystore.pytest/tests/test_securechannel.pyInspect captured patch +343 / −9
### src/helpers.py
@@ -36,6 +36,34 @@ def tagged_hash(tag: str, data: bytes) -> bytes:
return hashlib.sha256(hashtag + hashtag + data).digest()
+def consteq(a: bytes, b: bytes) -> bool:
+ """
+ Fixed-work comparison for MACs, HMACs and other fixed-length
+ authentication values. Plain `==`/`!=` on bytes can stop as soon as
+ a differing byte is found, so its timing can leak how many leading
+ bytes matched; for equal-length inputs this instead compares every
+ byte without an early exit that depends on where they differ. The
+ length check below is NOT constant-time and input length is not
+ treated as secret, so this is only appropriate where both inputs
+ have a fixed, public length (e.g. a 32-byte HMAC-SHA256 digest) -
+ do not use it to compare secret-dependent variable-length data.
+ Used because the MicroPython build on this device (custom C `hmac`
+ usermod) has no `hmac.compare_digest()`.
+
+ SECURITY: do not "simplify" the loop below back to `a == b` / `!=`,
+ and do not add an early `return False` inside the loop - either
+ change reintroduces the timing side channel this function exists
+ to remove. A test asserting equal() == equal() cannot catch that
+ regression, since both implementations return the same booleans.
+ """
+ if len(a) != len(b):
+ return False
+ result = 0
+ for x, y in zip(a, b):
+ result |= x ^ y
+ return result == 0
+
+
def encrypt(plain: bytes, key: bytes) -> bytes:
"""Encrypt data with bit padding (0x80...)"""
iv = rng.get_random_bytes(IV_SIZE)
@@ -93,7 +121,8 @@ def aead_decrypt(ciphertext: bytes, key: bytes) -> tuple:
aes_key = tagged_hash("aes", key)
hmac_key = tagged_hash("hmac", key)
- if mac != hmac.new(hmac_key, ct, digestmod="sha256").digest():
+ # constant-time compare (L6) - do not replace with == / !=
+ if not consteq(mac, hmac.new(hmac_key, ct, digestmod="sha256").digest()):
raise Exception("Invalid HMAC")
b = BytesIO(ct)
l = compact.read_from(b)
### src/keystore/flash.py
@@ -11,7 +11,7 @@
from binascii import hexlify, unhexlify
from rng import get_random_bytes
from embit import ec, bip39, bip32
-from helpers import tagged_hash
+from helpers import tagged_hash, consteq
from gui.screens import Alert, PinScreen, Menu, MnemonicScreen, InputScreen
@@ -126,8 +126,8 @@ def _unlock(self, pin):
# 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
- if pin_hmac != self.pin:
+ # check hmac is the same (constant-time compare, L6 - do not replace with == / !=)
+ if not consteq(pin_hmac, self.pin):
raise PinError(
"Invalid PIN!\n%d of %d attempts left..."
% (self._pin_attempts_left, self._pin_attempts_max)
### src/keystore/javacard/applets/securechannel.py
@@ -5,6 +5,7 @@
from rng import get_random_bytes
from ucryptolib import aes
from binascii import hexlify
+from helpers import consteq
AES_BLOCK = 16
IV_SIZE = 16
@@ -99,7 +100,8 @@ def open(self, mode=None):
h = hmac.new(self.card_mac_key, digestmod="sha256")
h.update(data)
expected_hmac = h.digest()[:MAC_SIZE]
- if expected_hmac != recv_hmac:
+ # constant-time compare (L6) - do not replace with == / !=
+ if not consteq(expected_hmac, recv_hmac):
raise SecureChannelError("Wrong HMAC.")
data += recv_hmac
raw_sig = s.read()
@@ -129,7 +131,8 @@ def open(self, mode=None):
h = hmac.new(self.card_mac_key, digestmod="sha256")
h.update(data)
expected_hmac = h.digest()[:MAC_SIZE]
- if expected_hmac != recv_hmac:
+ # constant-time compare (L6) - do not replace with == / !=
+ if not consteq(expected_hmac, recv_hmac):
raise SecureChannelError("Wrong HMAC.")
data += recv_hmac
sig = secp256k1.ecdsa_signature_parse_der(s.read())
@@ -167,7 +170,8 @@ def decrypt(self, ct):
h.update(iv)
h.update(ct)
expected_hmac = h.digest()[:MAC_SIZE]
- if expected_hmac != recv_hmac:
+ # constant-time compare (L6) - do not replace with == / !=
+ if not consteq(expected_hmac, recv_hmac):
raise SecureChannelError("Wrong HMAC.")
crypto = aes(self.card_aes_key, AES_CBC, iv)
plain = crypto.decrypt(ct)
### test/native_support.py
@@ -64,6 +64,27 @@ def off(self):
pyb.UART = lambda *args, **kwargs: None
pyb.USB_VCP = lambda *args, **kwargs: None
+ class _DummyPinNamespace:
+ """Stands in for pyb.Pin.cpu.<NAME> (e.g. Pin.cpu.A2)"""
+ def __getattr__(self, name):
+ return name
+
+ class _DummyPin:
+ cpu = _DummyPinNamespace()
+
+ pyb.Pin = _DummyPin
+
+ uscard = _ensure_module("uscard")
+ if not hasattr(uscard, "Reader"):
+ class _DummyReader:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def createConnection(self):
+ return None
+
+ uscard.Reader = _DummyReader
+
lvgl = _ensure_module("lvgl")
if not hasattr(lvgl, "SYMBOL"):
class _Symbol:
### test/tests/__init__.py
@@ -4,3 +4,4 @@
from .test_revault import *
from .test_compatibility import *
from .test_helpers import *
+from .test_securechannel import *
### test/tests/test_helpers.py
@@ -1,7 +1,43 @@
from unittest import TestCase
-from helpers import conv_time
+from helpers import conv_time, consteq, aead_encrypt, aead_decrypt
class HelpersTest(TestCase):
+ def test_consteq(self):
+ """consteq() must agree with regular equality on all these cases (L6)"""
+ self.assertTrue(consteq(b"", b""))
+ self.assertTrue(consteq(b"abcdef", b"abcdef"))
+ # mismatch in the first byte
+ self.assertFalse(consteq(b"abcdef", b"xbcdef"))
+ # mismatch in the last byte
+ self.assertFalse(consteq(b"abcdef", b"abcdex"))
+ # mismatch in the middle
+ self.assertFalse(consteq(b"abcdef", b"abXdef"))
+ # different lengths, same prefix
+ self.assertFalse(consteq(b"abc", b"abcd"))
+ self.assertFalse(consteq(b"abcd", b"abc"))
+ # different lengths, one empty
+ self.assertFalse(consteq(b"", b"a"))
+ self.assertFalse(consteq(b"a", b""))
+
+ def test_aead_roundtrip(self):
+ """Valid storage MAC still authenticates and decrypts (L6)"""
+ key = b"0" * 32
+ adata = b"associated-data"
+ plaintext = b"top secret mnemonic"
+ ct = aead_encrypt(key, adata, plaintext)
+ out_adata, out_plaintext = aead_decrypt(ct, key)
+ self.assertEqual(out_adata, adata)
+ self.assertEqual(out_plaintext, plaintext)
+
+ def test_aead_rejects_tampered_mac(self):
+ """A tampered/invalid storage MAC is still rejected (L6)"""
+ key = b"0" * 32
+ ct = aead_encrypt(key, b"ad", b"top secret mnemonic")
+ # flip the last bit of the MAC
+ tampered = ct[:-1] + bytes([ct[-1] ^ 0x01])
+ with self.assertRaises(Exception):
+ aead_decrypt(tampered, key)
+
def test_conv_time(self):
"""Test conv_time function: used for converting nLocktime to human-readable timestamp"""
self.assertEqual(conv_time(0), (1970, 1, 1, 0, 0, 0, 3, 1))
### test/tests/test_keystore.py
@@ -1,5 +1,5 @@
from unittest import TestCase
-from keystore import FlashKeyStore
+from keystore import FlashKeyStore, PinError
import os
import platform
@@ -55,6 +55,35 @@ def test_change_secret(self):
self.assertFalse("secret" in files)
self.assertFalse("pin" in files)
+ def test_pin_verification(self):
+ """Correct PIN unlocks, incorrect PIN is rejected (L6 constant-time comparison)"""
+ import hmac
+ from helpers import tagged_hash
+
+ ks = self.get_keystore()
+ init_keystore(ks)
+ pin = "1234"
+ key = tagged_hash("pin", ks.secret)
+ ks.pin = hmac.new(key=key, msg=pin.encode(), digestmod="sha256").digest()
+ ks.save_state()
+
+ # correct PIN unlocks and resets the attempt counter
+ ks._unlock(pin)
+ self.assertFalse(ks.is_locked)
+ self.assertEqual(ks.pin_attempts_left, ks.pin_attempts_max)
+
+ # wrong PIN is rejected and consumes one attempt, without wiping
+ ks.lock()
+ attempts_before = ks.pin_attempts_left
+ with self.assertRaises(PinError):
+ ks._unlock("0000")
+ self.assertTrue(ks.is_locked)
+ self.assertEqual(ks.pin_attempts_left, attempts_before - 1)
+
+ # correct PIN still works afterwards
+ ks._unlock(pin)
+ self.assertFalse(ks.is_locked)
+
def test_change_pin_file(self):
"""Test wipe exception if pin state changed"""
# create keystore
### test/tests/test_securechannel.py
@@ -0,0 +1,214 @@
+from unittest import TestCase
+from keystore.javacard.applets.securechannel import SecureChannel, SecureChannelError
+import hashlib
+import hmac
+import secp256k1
+from rng import get_random_bytes
+from ucryptolib import aes
+
+AES_BLOCK = 16
+IV_SIZE = 16
+AES_CBC = 2
+MAC_SIZE = 14
+
+
+def card_encrypt(sc, data):
+ """
+ Builds a ciphertext the way the real card would encrypt a response
+ to the host, using sc's card_aes_key/card_mac_key/iv - i.e. exactly
+ what SecureChannel.decrypt() is expected to be able to open.
+ """
+ d = data + b"\x80"
+ if len(d) % AES_BLOCK != 0:
+ d += b"\x00" * (AES_BLOCK - (len(d) % AES_BLOCK))
+ iv = sc.iv.to_bytes(IV_SIZE, "big")
+ crypto = aes(sc.card_aes_key, AES_CBC, iv)
+ ct = crypto.encrypt(d)
+ h = hmac.new(sc.card_mac_key, digestmod="sha256")
+ h.update(iv)
+ h.update(ct)
+ ct += h.digest()[:MAC_SIZE]
+ return ct
+
+
+def get_channel():
+ sc = SecureChannel(applet=None)
+ sc.card_aes_key = b"1" * 32
+ sc.card_mac_key = b"2" * 32
+ sc.iv = 0
+ return sc
+
+
+class SecureChannelDecryptTest(TestCase):
+ """
+ Regression tests for the L6 constant-time HMAC check in
+ SecureChannel.decrypt(). No smartcard/simulator is needed: decrypt()
+ only depends on card_aes_key/card_mac_key/iv, which are set directly.
+ """
+
+ def test_valid_mac_decrypts(self):
+ sc = get_channel()
+ ct = card_encrypt(sc, b"hello from card")
+ self.assertEqual(sc.decrypt(ct), b"hello from card")
+
+ def test_first_mac_byte_flipped_rejected(self):
+ sc = get_channel()
+ ct = bytearray(card_encrypt(sc, b"hello from card"))
+ ct[-MAC_SIZE] ^= 0xFF
+ with self.assertRaises(SecureChannelError):
+ sc.decrypt(bytes(ct))
+
+ def test_middle_mac_byte_flipped_rejected(self):
+ sc = get_channel()
+ ct = bytearray(card_encrypt(sc, b"hello from card"))
+ ct[-(MAC_SIZE // 2)] ^= 0xFF
+ with self.assertRaises(SecureChannelError):
+ sc.decrypt(bytes(ct))
+
+ def test_last_mac_byte_flipped_rejected(self):
+ sc = get_channel()
+ ct = bytearray(card_encrypt(sc, b"hello from card"))
+ ct[-1] ^= 0xFF
+ with self.assertRaises(SecureChannelError):
+ sc.decrypt(bytes(ct))
+
+ def test_tampered_ciphertext_rejected(self):
+ """A flipped ciphertext byte must be caught by the MAC check,
+ never silently decrypted to different plaintext."""
+ sc = get_channel()
+ ct = bytearray(card_encrypt(sc, b"hello from card"))
+ ct[0] ^= 0xFF
+ with self.assertRaises(SecureChannelError):
+ sc.decrypt(bytes(ct))
+
+ def test_wrong_key_rejected(self):
+ sc = get_channel()
+ ct = card_encrypt(sc, b"hello from card")
+ wrong = get_channel()
+ wrong.card_mac_key = b"3" * 32
+ with self.assertRaises(SecureChannelError):
+ wrong.decrypt(ct)
+
+
+def _decode(payload):
+ """Reverse of keystore.javacard.util.encode(): bytes([len]) + data"""
+ l = payload[0]
+ return payload[1:1 + l]
+
+
+class MockCardApplet:
+ """
+ Stands in for the real smartcard applet during open(). Simulates the
+ card's side of the ee/se handshake using genuine secp256k1 operations
+ (real ECDH + real ECDSA signatures over the card's static key), so
+ these tests exercise the same crypto path as the real protocol -
+ only the transport (self.applet.request) is mocked.
+ """
+
+ def __init__(self, card_static_secret, tamper_hmac=False, tamper_sig=False):
+ self.card_static_secret = card_static_secret
+ self.tamper_hmac = tamper_hmac
+ self.tamper_sig = tamper_sig
+
+ def _sign(self, data):
+ sig = secp256k1.ecdsa_sign(hashlib.sha256(data).digest(), self.card_static_secret)
+ der = secp256k1.ecdsa_signature_serialize_der(sig)
+ if self.tamper_sig:
+ der = bytes([der[0] ^ 0xFF]) + der[1:]
+ return der
+
+ def request(self, payload):
+ cmd, body = payload[:4], payload[4:]
+ if cmd == SecureChannel.OPEN_EE:
+ host_pub_bytes = _decode(body)
+ host_pub = secp256k1.ec_pubkey_parse(host_pub_bytes)
+
+ card_secret = get_random_bytes(32)
+ card_pub = secp256k1.ec_pubkey_create(card_secret)
+ card_pub_bytes = secp256k1.ec_pubkey_serialize(card_pub, secp256k1.EC_UNCOMPRESSED)
+
+ shared_point = secp256k1.ec_pubkey_parse(host_pub_bytes)
+ secp256k1.ec_pubkey_tweak_mul(shared_point, card_secret)
+ shared_secret = hashlib.sha256(
+ secp256k1.ec_pubkey_serialize(shared_point)[1:33]
+ ).digest()
+
+ card_side = SecureChannel(applet=None)
+ card_side.derive_keys(shared_secret)
+
+ h = hmac.new(card_side.card_mac_key, digestmod="sha256")
+ h.update(card_pub_bytes)
+ mac = h.digest()[:MAC_SIZE]
+ if self.tamper_hmac:
+ mac = bytes([mac[0] ^ 0xFF]) + mac[1:]
+
+ der = self._sign(card_pub_bytes + mac)
+ return card_pub_bytes + mac + der
+
+ elif cmd == SecureChannel.OPEN_SE:
+ host_pub_bytes = _decode(body)
+
+ card_static_pub = secp256k1.ec_pubkey_create(self.card_static_secret)
+ shared_point = secp256k1.ec_pubkey_parse(host_pub_bytes)
+ secp256k1.ec_pubkey_tweak_mul(shared_point, self.card_static_secret)
+ shared_secret = secp256k1.ec_pubkey_serialize(shared_point)[1:33]
+
+ nonce_card = get_random_bytes(32)
+ secret_with_nonces = hashlib.sha256(shared_secret + nonce_card).digest()
+ card_side = SecureChannel(applet=None)
+ card_side.derive_keys(secret_with_nonces)
+
+ h = hmac.new(card_side.card_mac_key, digestmod="sha256")
+ h.update(nonce_card)
+ mac = h.digest()[:MAC_SIZE]
+ if self.tamper_hmac:
+ mac = bytes([mac[0] ^ 0xFF]) + mac[1:]
+
+ der = self._sign(nonce_card + mac)
+ return nonce_card + mac + der
+
+ raise AssertionError("Unexpected request in mock applet: %r" % cmd)
+
+
+class SecureChannelOpenTest(TestCase):
+ """
+ Regression tests for the L6 constant-time HMAC checks in
+ SecureChannel.open() (both "ee" and "se" handshake modes). A mock
+ applet simulates the card's side with genuine secp256k1 ECDH/ECDSA,
+ so a tampered HMAC is rejected for the same reason a tampered
+ signature would be - not because the mock is unrealistic.
+ """
+
+ def test_open_ee_succeeds_with_valid_card_response(self):
+ card_secret = get_random_bytes(32)
+ applet = MockCardApplet(card_secret)
+ sc = SecureChannel(applet)
+ sc.card_pubkey = secp256k1.ec_pubkey_create(card_secret)
+ sc.open(mode="ee")
+ self.assertTrue(sc.is_open)
+
+ def test_open_ee_tampered_hmac_rejected(self):
+ card_secret = get_random_bytes(32)
+ applet = MockCardApplet(card_secret, tamper_hmac=True)
+ sc = SecureChannel(applet)
+ sc.card_pubkey = secp256k1.ec_pubkey_create(card_secret)
+ with self.assertRaises(SecureChannelError):
+ sc.open(mode="ee")
+ self.assertFalse(sc.is_open)
+
+ def test_open_se_succeeds_with_valid_card_response(self):
+ card_secret = get_random_bytes(32)
+ applet = MockCardApplet(card_secret)
+ sc = SecureChannel(applet)
+ sc.card_pubkey = secp256k1.ec_pubkey_create(card_secret)
+ sc.open(mode="se")
+ self.assertTrue(sc.is_open)
+
+ def test_open_se_tampered_hmac_rejected(self):
+ card_secret = get_random_bytes(32)
+ applet = MockCardApplet(card_secret, tamper_hmac=True)
+ sc = SecureChannel(applet)
+ sc.card_pubkey = secp256k1.ec_pubkey_create(card_secret)
+ with self.assertRaises(SecureChannelError):
+ sc.open(mode="se")
+ self.assertFalse(sc.is_open)Why this scored 65/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.