forked from cryptoadvance/specter-diy
-
Notifications
You must be signed in to change notification settings - Fork 0
Add SeedKeeper keystore support #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Amperstrand
wants to merge
4
commits into
hardwareintheloop
Choose a base branch
from
seedkeeper
base: hardwareintheloop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Submodule f469-disco
updated
13 files
| +1 −0 | .envrc | |
| +38 −0 | .github/workflows/ci.yml | |
| +39 −0 | .github/workflows/release.yml | |
| +62 −0 | docs/build.md | |
| +5 −0 | docs/readme.md | |
| +40 −0 | docs/release.md | |
| +78 −0 | flake.lock | |
| +30 −0 | flake.nix | |
| +9 −9 | tests/tests/test_bech32.py | |
| +15 −15 | tests/tests/test_psbt.py | |
| +9 −0 | usermods/scard/connection.c | |
| +39 −0 | usermods/scard/ports/stm32/scard_io.c | |
| +7 −0 | usermods/scard/ports/stm32/scard_io.h |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| """Debug info screen shown during multi-keystore detection. | ||
|
|
||
| Displays firmware version, card presence, and detected applets | ||
| while polling for an available keystore in select_keystore(). | ||
| """ | ||
| import lvgl as lv | ||
| from .screen import Screen | ||
| from ..common import add_label | ||
| from ..core import update | ||
|
|
||
|
|
||
| class DebugInfoScreen(Screen): | ||
| """Shows firmware version, card presence, and detected applets.""" | ||
|
|
||
| def __init__(self): | ||
| super().__init__() | ||
| self.title = add_label("Specter Debug Info", scr=self, style="title") | ||
|
|
||
| self.version_label = add_label("", scr=self, style="hint") | ||
| self.version_label.align(self.title, lv.ALIGN.OUT_BOTTOM_MID, 0, 20) | ||
|
|
||
| self.card_label = add_label("Card: checking...", scr=self, style="small") | ||
| self.card_label.align(self.version_label, lv.ALIGN.OUT_BOTTOM_MID, 0, 30) | ||
|
|
||
| self.applets_label = add_label("Applets: --", scr=self, style="small") | ||
| self.applets_label.align(self.card_label, lv.ALIGN.OUT_BOTTOM_MID, 0, 20) | ||
|
|
||
| self.status_label = add_label("", scr=self, style="hint") | ||
| self.status_label.align(self.applets_label, lv.ALIGN.OUT_BOTTOM_MID, 0, 20) | ||
|
|
||
| self.hint_label = add_label("Waiting for keystore...", scr=self, style="hint") | ||
| self.hint_label.set_y(700) | ||
|
|
||
| self._set_firmware_info() | ||
|
|
||
| def load(self): | ||
| lv.scr_load(self) | ||
| update() | ||
|
|
||
| def _set_firmware_info(self): | ||
| try: | ||
| from platform import get_git_info, get_version | ||
| repo, branch, commit = get_git_info() | ||
| ver = get_version() | ||
| lines = "Firmware: %s" % ver | ||
| if branch != "unknown": | ||
| lines += "\nBranch: %s" % branch | ||
| if commit != "unknown": | ||
| lines += "\nCommit: %s" % commit | ||
| self.version_label.set_text(lines) | ||
| except Exception: | ||
| self.version_label.set_text("Firmware: unknown") | ||
|
|
||
| def update_info(self, info: dict) -> None: | ||
| if not info: | ||
| info = {} | ||
|
|
||
| card_present = info.get("card_present", False) | ||
| applets = info.get("applets", []) | ||
| status = info.get("status", "") | ||
|
|
||
| if not isinstance(applets, (list, tuple)): | ||
| applets = [] | ||
|
|
||
| if card_present: | ||
| self.card_label.set_text("Card: present") | ||
| else: | ||
| self.card_label.set_text("Card: not detected") | ||
|
|
||
| if applets: | ||
| self.applets_label.set_text("Applets:\n" + "\n".join([" - " + str(a) for a in applets])) | ||
| else: | ||
| self.applets_label.set_text("Applets: (none detected)") | ||
|
|
||
| if status: | ||
| self.status_label.set_text(str(status)) | ||
| else: | ||
| self.status_label.set_text("") | ||
|
|
||
| update() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
144 changes: 144 additions & 0 deletions
144
src/keystore/javacard/applets/satochip_securechannel.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| """ | ||
| Satochip Secure Channel - Crypto primitives for SeedKeeper and Satochip applets. | ||
|
|
||
| Implements ECDH key exchange, AES-CBC encryption, and HMAC-SHA1 authentication. | ||
| This is the Satochip/SeedKeeper protocol, distinct from MemoryCard's SecureChannel | ||
| (which uses HMAC-SHA256 and a different key derivation scheme). | ||
| """ | ||
|
|
||
| import hashlib | ||
| import secp256k1 | ||
| from ucryptolib import aes | ||
| from rng import get_random_bytes | ||
|
|
||
|
|
||
| AES_BLOCK = 16 | ||
|
|
||
|
|
||
| def hmac_sha1(key: bytes, msg: bytes) -> bytes: | ||
| BLOCK_SIZE = 64 | ||
| if len(key) > BLOCK_SIZE: | ||
| key = hashlib.sha1(key).digest() | ||
| elif len(key) < BLOCK_SIZE: | ||
| key = key + b'\x00' * (BLOCK_SIZE - len(key)) | ||
| ipad = b'\x36' * BLOCK_SIZE | ||
| opad = b'\x5c' * BLOCK_SIZE | ||
| key_ipad = bytes(a ^ b for a, b in zip(key, ipad)) | ||
| key_opad = bytes(a ^ b for a, b in zip(key, opad)) | ||
| inner_hash = hashlib.sha1(key_ipad + msg).digest() | ||
| return hashlib.sha1(key_opad + inner_hash).digest() | ||
|
|
||
|
|
||
| def pkcs7_pad(data: bytes, block_size: int = 16) -> bytes: | ||
| pad_len = block_size - (len(data) % block_size) | ||
| return data + bytes([pad_len] * pad_len) | ||
|
|
||
|
|
||
| def pkcs7_unpad(data: bytes) -> bytes: | ||
| padding_len = data[-1] | ||
| if padding_len == 0: | ||
| raise ValueError("Invalid PKCS#7 padding") | ||
| for i in range(1, padding_len + 1): | ||
| if data[-i] != padding_len: | ||
| raise ValueError("Invalid PKCS#7 padding") | ||
| return data[:-padding_len] | ||
|
|
||
|
|
||
| class SatochipSecureChannel: | ||
| """Secure channel for Satochip/SeedKeeper JavaCard applets. | ||
|
|
||
| ECDH key exchange with AES-CBC encryption and HMAC-SHA1 authentication. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| self.aes_key = None | ||
| self.mac_key = None | ||
| self.iv_counter = 1 | ||
| self.is_initialized = False | ||
| self.card_pubkey = None | ||
|
|
||
| def initiate(self, connection, cla=0xB0): | ||
| """Perform ECDH key exchange via INS 0x81.""" | ||
| try: | ||
| from platform import hil_test_mode | ||
| except Exception: | ||
| hil_test_mode = False | ||
| secret = get_random_bytes(32) | ||
| if hil_test_mode: | ||
| from debug_trace import log | ||
| log("SC", "ECDH: generating pubkey...") | ||
| pubkey = secp256k1.ec_pubkey_create(secret) | ||
| pub_bytes = secp256k1.ec_pubkey_serialize(pubkey, secp256k1.EC_UNCOMPRESSED) | ||
|
|
||
| apdu = bytes([cla, 0x81, 0x00, 0x00, 0x41]) + pub_bytes | ||
| if hil_test_mode: | ||
| log("SC", "ECDH: transmitting %d bytes..." % len(apdu)) | ||
| data = connection.transmit(apdu) | ||
| if hil_test_mode: | ||
| log("SC", "ECDH: got response, len=%d" % len(data)) | ||
| resp_data = data[0] | ||
| sw1, sw2 = data[1], data[2] | ||
| if hil_test_mode: | ||
| log("SC", "ECDH: SW=%02X%02X" % (sw1, sw2)) | ||
| if sw1 != 0x90 or sw2 != 0x00: | ||
| raise ValueError('INIT_SC failed: SW={:02X}{:02X}'.format(sw1, sw2)) | ||
|
|
||
| if hil_test_mode: | ||
| log("SC", "ECDH: parsing card pubkey...") | ||
| coordx_size = (resp_data[0] << 8) | resp_data[1] | ||
| coordx = bytes(resp_data[2:2 + coordx_size]) | ||
|
|
||
| card_pubkey_compressed = bytes([0x02]) + coordx | ||
|
|
||
| card_pubkey = secp256k1.ec_pubkey_parse(card_pubkey_compressed) | ||
| self.card_pubkey = card_pubkey | ||
|
|
||
| shared_point = secp256k1.ec_pubkey_parse( | ||
| secp256k1.ec_pubkey_serialize(card_pubkey) | ||
| ) | ||
| secp256k1.ec_pubkey_tweak_mul(shared_point, secret) | ||
| shared_bytes = secp256k1.ec_pubkey_serialize(shared_point, secp256k1.EC_UNCOMPRESSED) | ||
| shared_secret = shared_bytes[1:33] | ||
|
|
||
| self.aes_key = hmac_sha1(shared_secret, b'sc_key')[:16] | ||
| self.mac_key = hmac_sha1(shared_secret, b'sc_mac') | ||
| self.is_initialized = True | ||
| if hil_test_mode: | ||
| log("SC", "ECDH: secure channel initialized") | ||
|
|
||
| def reset(self): | ||
| self.aes_key = None | ||
| self.mac_key = None | ||
| self.iv_counter = 1 | ||
| self.is_initialized = False | ||
| self.card_pubkey = None | ||
|
|
||
| def encrypt_apdu(self, inner_apdu: bytes, cla=0xB0) -> bytes: | ||
| if not self.is_initialized: | ||
| raise ValueError("Secure channel not initialized") | ||
|
|
||
| iv = get_random_bytes(12) + self.iv_counter.to_bytes(4, 'big') | ||
| if iv[15] % 2 == 0: | ||
| iv = iv[:15] + bytes([iv[15] | 0x01]) | ||
|
|
||
| padded = pkcs7_pad(inner_apdu, AES_BLOCK) | ||
| cipher = aes(self.aes_key, 2, iv) | ||
| ciphertext = cipher.encrypt(padded) | ||
|
|
||
| mac_data = iv + len(ciphertext).to_bytes(2, 'big') + ciphertext | ||
| mac = hmac_sha1(self.mac_key, mac_data) | ||
|
|
||
| payload = iv + len(ciphertext).to_bytes(2, 'big') + ciphertext + (20).to_bytes(2, 'big') + mac | ||
| wrapped = bytes([cla, 0x82, 0x00, 0x00, len(payload)]) + payload | ||
|
|
||
| self.iv_counter += 2 | ||
| return wrapped | ||
|
|
||
| def decrypt_response(self, encrypted_response: bytes) -> bytes: | ||
| card_iv = encrypted_response[:16] | ||
| data_size = int.from_bytes(encrypted_response[16:18], 'big') | ||
| ciphertext = encrypted_response[18:18 + data_size] | ||
|
|
||
| cipher = aes(self.aes_key, 2, card_iv) | ||
| plaintext = cipher.decrypt(ciphertext) | ||
| return pkcs7_unpad(plaintext) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Response handling decrypts ciphertext immediately and never validates any message authentication tag, even though request wrapping includes a MAC. With no integrity check, a faulty or malicious card/link can alter encrypted response bytes and, if padding remains syntactically valid, the device may accept corrupted secret material (including mnemonic data) without detection.
Useful? React with 👍 / 👎.