Merge pull request #735 from Foundation-Devices/sft-8555-update-restore-checks
What changed, and why it matters
This commit adds security checks when restoring a backup file to a Passport hardware wallet. Previously, multisig wallet configurations stored in a backup were restored without verifying that they actually belong to the seed being restored. The new code validates each multisig configuration: it checks that the structure is correct, that the keys are valid, and that any key claiming to belong to the restored seed really derives from it. Bad multisig records are now dropped instead of causing the entire restore to fail, so the seed is still recovered and the user can re-import a valid multisig config later. This prevents a malicious or corrupted backup from sneaking a fake multisig wallet onto the device.
Users should update to firmware containing this commit before restoring backups that include multisig configurations. Reviewers should verify that `validate_backup_multisig_records()` covers all deserialization edge cases and that the `derive_backup_node()` helper correctly handles hardened derivation paths without leaking sensitive material.
Security signals we found
Validation of multisig backup records against restored seed
Derivation verification for xpubs claiming backup root fingerprint
Dropping malformed records instead of failing entire restore
Parity with existing wallet_policy backup validation
New unit tests for attack scenarios (impostor key, wrong chain, reencoded duplicate, type confusion)
Evidence from the diff
The patch introduces validate_backup_multisig_records() in multisig_wallet.py, which is called during restore_backup_task.py. It deserializes each multisig record, validates M-of-N constraints, address format, chain type, xpub parseability, derivation path depth, duplicate cosigner keys, and critically verifies that any xpub claiming the restored seed’s fingerprint derives correctly from the backup root node. Failing records are dropped rather than aborting restore. The change mirrors existing validation for wallet policies and includes unit tests covering valid records, impostor keys, wrong chains, malformed fields, and non-deserializable records.
Changed components
ports/stm32/boards/Passport/modules/multisig_wallet.pyports/stm32/boards/Passport/modules/tasks/restore_backup_task.pyPassport firmware backup restore flowMultisig wallet configuration restoreInspect captured patch +242 / −7
### ports/stm32/boards/Passport/modules/multisig_wallet.py
@@ -1082,4 +1082,66 @@ def import_xpub(ln):
# looked like one, but failed to deserialize
return None
+
+def _backup_record_usable(record, root_xfp, derive_node):
+ # A field of the wrong type raises partway through the checks below. That
+ # must drop only this record, never fail the restore of the seed.
+ try:
+ return _backup_record_checks_pass(record, root_xfp, derive_node)
+ except Exception:
+ return False
+
+
+def _backup_record_checks_pass(record, root_xfp, derive_node):
+ wallet = MultisigWallet.deserialize(record)
+
+ if not (1 <= wallet.M <= wallet.N <= MAX_SIGNERS) or wallet.N != len(wallet.xpubs):
+ return False
+ if not wallet.addr_fmt & AFC_SCRIPT:
+ return False
+
+ keys = set()
+ for xfp, deriv, xpub in wallet.xpubs:
+ parsed = import_xpub(xpub) if isinstance(xpub, str) else None
+ if parsed is None:
+ return False
+ node, chain, _ = parsed
+ if chain.ctype != wallet.chain_type:
+ return False
+
+ # Each cosigner must be a different key, as on import.
+ key = node.public_key()[1:]
+ if key in keys:
+ return False
+ keys.add(key)
+ if not isinstance(deriv, str) or deriv[0:1] != 'm' or deriv.count('/') != node.depth():
+ return False
+
+ # Keys under any other fingerprint, including a passphrase wallet's
+ # own key, cannot be checked against the backup's root here.
+ if xfp == root_xfp:
+ own = derive_node(wallet.xfp_paths[xfp][1:])
+ try:
+ if own.public_key() != node.public_key() or own.chain_code() != node.chain_code():
+ return False
+ finally:
+ stash.blank_object(own)
+
+ return True
+
+
+def validate_backup_multisig_records(records, root_xfp, derive_node):
+ """Return the multisig records from a backup that this firmware can use.
+
+ A record is kept when it deserializes, its M-of-N and key count are in
+ range, it uses a script address format, every xpub parses on the record's
+ chain with a derivation path of matching depth, no two cosigners share a
+ key, and any key claiming the backup's root fingerprint derives from that
+ root. Records that fail are dropped instead of failing the restore: a
+ multisig config can be imported again, and the seed is still recovered.
+ """
+ if not isinstance(records, list):
+ return []
+ return [record for record in records if _backup_record_usable(record, root_xfp, derive_node)]
+
# EOF
### ports/stm32/boards/Passport/modules/tasks/restore_backup_task.py
@@ -122,6 +122,12 @@ async def restore_backup_task(on_done, decryption_password, backup_file_path):
await on_done(Error.CORRUPT_BACKUP_FILE)
return
+ def derive_backup_node(path):
+ child = node.clone()
+ for element in path:
+ child.derive(element)
+ return child
+
# Wallet policies are security-critical and cannot be restored as
# opaque settings. Validate their identity, xpub encodings, network,
# and declared Passport-owned key against the backup's root node before
@@ -132,19 +138,20 @@ async def restore_backup_task(on_done, decryption_password, backup_file_path):
from wallet_policy import validate_backup_policy_records
expected_fingerprint = xfp2str(node.my_fingerprint()).lower()
- def derive_policy_node(path):
- child = node.clone()
- for element in path:
- child.derive(element)
- return child
-
vals['setting.wallet_policies'] = validate_backup_policy_records(
- policy_records, expected_fingerprint, derive_policy_node,
+ policy_records, expected_fingerprint, derive_backup_node,
chains.get_chain)
elif not isinstance(policy_records, list):
await on_done(Error.CORRUPT_BACKUP_FILE)
return
+ # Multisig configs are checked too, but one that fails is dropped
+ # rather than failing the restore, since it can be imported again.
+ if 'setting.multisig' in vals:
+ from multisig_wallet import validate_backup_multisig_records
+ vals['setting.multisig'] = validate_backup_multisig_records(
+ vals['setting.multisig'], node.my_fingerprint(), derive_backup_node)
+
except Exception as e:
await on_done(Error.CORRUPT_BACKUP_FILE)
return
### ports/stm32/boards/Passport/modules/tests/test_unit.py
@@ -144,6 +144,10 @@ def test_multisig_xpub_validation(test):
assert test('multisig_xpub_validation.py') == b'OK'
+def test_multisig_backup_records(test):
+ assert test('multisig_backup_records.py') == b'OK'
+
+
def test_psbt_fee(test):
assert test('psbt_fee.py') == b'OK'
### ports/stm32/boards/Passport/modules/tests/unit/multisig_backup_records.py
@@ -0,0 +1,118 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Multisig records restored from a backup are kept only when this firmware can
+# use them.
+
+import chains
+import trezorcrypto
+
+from multisig_wallet import MultisigWallet, validate_backup_multisig_records
+from public_constants import AF_P2SH, AF_P2WSH
+
+DERIVATION = "m/48'/0'/0'/2'"
+PATH = [0x80000000 | 48, 0x80000000, 0x80000000, 0x80000000 | 2]
+TESTNET_DERIVATION = "m/48'/1'/0'/2'"
+TESTNET_PATH = [0x80000000 | 48, 0x80000000 | 1, 0x80000000, 0x80000000 | 2]
+
+
+def root_from(seed_byte):
+ seed = trezorcrypto.bip39.seed(trezorcrypto.bip39.from_data(bytes([seed_byte]) * 16), '')
+ return trezorcrypto.bip32.from_seed(seed, 'secp256k1')
+
+
+def derive(root, path):
+ child = root.clone()
+ for element in path:
+ child.derive(element)
+ return child
+
+
+def key_entry(root, chain_name='BTC', derivation=DERIVATION, path=PATH):
+ xpub = chains.get_chain(chain_name).serialize_public(derive(root, path), AF_P2SH)
+ return (root.my_fingerprint(), derivation, xpub)
+
+
+def record(keys, m=2, addr_fmt=AF_P2WSH, chain_type='BTC', name='Vault'):
+ return MultisigWallet(name, (m, len(keys)), keys, 1, addr_fmt=addr_fmt,
+ chain_type=chain_type, deriv=keys[0][1]).serialize()
+
+
+ROOT = root_from(1)
+COSIGNER_A = root_from(2)
+COSIGNER_B = root_from(3)
+ROOT_XFP = ROOT.my_fingerprint()
+
+
+def derive_root_node(path):
+ return derive(ROOT, path)
+
+
+def kept(records):
+ return validate_backup_multisig_records(records, ROOT_XFP, derive_root_node)
+
+
+mine = key_entry(ROOT)
+cosigner_a = key_entry(COSIGNER_A)
+cosigner_b = key_entry(COSIGNER_B)
+
+# A record Passport itself would have created is kept unchanged.
+valid = record([mine, cosigner_a, cosigner_b])
+assert kept([valid]) == [valid]
+
+# So is one where no key claims the backup's root, as with a config created
+# while a passphrase was active: those keys cannot be checked here.
+passphrase_wallet = record([cosigner_a, cosigner_b])
+assert kept([passphrase_wallet]) == [passphrase_wallet]
+
+# Testnet records are checked against the testnet chain.
+testnet = record([key_entry(ROOT, 'TBTC', TESTNET_DERIVATION, TESTNET_PATH),
+ key_entry(COSIGNER_A, 'TBTC', TESTNET_DERIVATION, TESTNET_PATH)],
+ chain_type='TBTC')
+assert kept([testnet]) == [testnet]
+
+# A key that claims the backup's root fingerprint must derive from that root.
+impostor = (ROOT_XFP, DERIVATION, cosigner_a[2])
+assert kept([record([impostor, cosigner_b])]) == []
+
+# Each xpub must belong to the record's chain.
+assert kept([record([mine, cosigner_a], chain_type='TBTC')]) == []
+
+# The derivation path depth must match the xpub's depth.
+shallow = (cosigner_a[0], "m/48'/0'/0'", cosigner_a[2])
+assert kept([record([mine, shallow])]) == []
+
+# M-of-N and key counts must be in range, and the format must be a script.
+assert kept([record([mine, cosigner_a], m=3)]) == []
+assert kept([record([mine, cosigner_a], addr_fmt=0)]) == []
+wrong_count = list(valid)
+wrong_count[1] = (2, 4)
+assert kept([wrong_count]) == []
+
+# Every xpub must parse.
+assert kept([record([mine, (cosigner_a[0], DERIVATION, 'xpub' + 'A' * 107)])]) == []
+
+# Each cosigner must be a different key, whatever fingerprint labels it and
+# however it is encoded.
+repeated = (0x44444444, DERIVATION, cosigner_a[2])
+assert kept([record([mine, cosigner_a, repeated])]) == []
+reencoded = (0x44444444, DERIVATION, chains.get_chain('BTC').serialize_public(derive(COSIGNER_A, PATH), AF_P2WSH))
+assert kept([record([mine, cosigner_a, reencoded])]) == []
+
+# A field of the wrong type drops the record instead of raising out of the
+# validation, which would fail the whole restore.
+string_m = list(valid)
+string_m[1] = ['2', 3]
+string_format = list(valid)
+string_format[3] = dict(valid[3])
+string_format[3]['ft'] = 'p2wsh'
+assert kept([valid, string_m, string_format, passphrase_wallet]) == [valid, passphrase_wallet]
+
+# Records that do not even deserialize, and a non-list, are dropped.
+assert kept(['garbage', None, ('name', (2, 2))]) == []
+assert kept('not a list') == []
+
+# Invalid records are dropped individually; valid ones around them are kept.
+assert kept([valid, 'garbage', passphrase_wallet]) == [valid, passphrase_wallet]
+
+return_value.write(b'OK')
### ports/stm32/boards/Passport/modules/tests/unit/restore_backup.py
@@ -51,8 +51,11 @@ def set(self, key, value):
import stash
import trezorcrypto
import uasyncio as asyncio
+import ujson
import tasks.restore_backup_task as restore_module
+from multisig_wallet import MultisigWallet
+from public_constants import AF_P2SH, AF_P2WSH
from tasks.restore_backup_task import restore_backup_task
from ubinascii import hexlify as b2a_hex
@@ -73,6 +76,40 @@ def set(self, key, value):
assert expected_xfp != ATTACKER_XFP
+# One multisig record that belongs to the restored seed, and one whose key
+# claims the restored seed's fingerprint but is another seed's xpub.
+MULTISIG_DERIVATION = "m/48'/0'/0'/2'"
+MULTISIG_PATH = [0x80000000 | 48, 0x80000000, 0x80000000, 0x80000000 | 2]
+
+
+def multisig_xpub(root):
+ node = root.clone()
+ for element in MULTISIG_PATH:
+ node.derive(element)
+ return chains.get_chain('BTC').serialize_public(node, AF_P2SH)
+
+
+cosigner_root = trezorcrypto.bip32.from_seed(
+ trezorcrypto.bip39.seed(trezorcrypto.bip39.from_data(bytes(range(16, 32))), ''), 'secp256k1')
+own_key = (expected_xfp, MULTISIG_DERIVATION, multisig_xpub(expected_node))
+cosigner_key = (cosigner_root.my_fingerprint(), MULTISIG_DERIVATION, multisig_xpub(cosigner_root))
+impostor_key = (expected_xfp, MULTISIG_DERIVATION, multisig_xpub(cosigner_root))
+# The JSON round trip turns tuples into the lists a restored record contains.
+valid_multisig = ujson.loads(ujson.dumps(MultisigWallet(
+ 'Vault', (1, 2), [own_key, cosigner_key], 1, addr_fmt=AF_P2WSH, deriv=MULTISIG_DERIVATION).serialize()))
+impostor_multisig = MultisigWallet(
+ 'Swap', (1, 2), [impostor_key, (0x33333333, MULTISIG_DERIVATION, cosigner_key[2])], 2,
+ addr_fmt=AF_P2WSH, deriv=MULTISIG_DERIVATION).serialize()
+second_multisig = ujson.loads(ujson.dumps(MultisigWallet(
+ 'Joint', (2, 2), [own_key, cosigner_key], 3, addr_fmt=AF_P2WSH, deriv=MULTISIG_DERIVATION).serialize()))
+
+# Records that deserialize but hold a field of the wrong type, so a check
+# raises partway through instead of returning False.
+string_m = ujson.loads(ujson.dumps(valid_multisig))
+string_m[1] = ['1', 2]
+string_format = ujson.loads(ujson.dumps(valid_multisig))
+string_format[3]['ft'] = 'p2wsh'
+
BACKUP_LINES = (
'# Passport backup file! DO NOT CHANGE.',
'raw_secret = "%s"' % b2a_hex(secret).decode(),
@@ -83,6 +120,8 @@ def set(self, key, value):
'setting.bip39_passphrase = "runtime-only"',
'setting.units = "sats"',
'setting.backup_quiz = true',
+ 'setting.multisig = %s' % ujson.dumps(
+ [valid_multisig, string_m, impostor_multisig, string_format, second_multisig]),
)
BACKUP_CONTENTS = ('\n'.join(BACKUP_LINES) + '\n').encode()
@@ -207,4 +246,9 @@ async def on_done(error):
assert 'root_xfp' not in stored.persisted
assert 'bip39_passphrase' not in stored.persisted
+# The multisig records that belong to the restored seed are restored. The one
+# whose key does not derive from it and the two with mistyped fields are
+# dropped, and the seed is still restored.
+assert stored.persisted['multisig'] == [valid_multisig, second_multisig]
+
return_value.write(b'OK')Why this scored 62/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.