Skip to content

Commit abfe6a1

Browse files
committed
Reject non-ASCII normalized input
Reject non-ASCII identifiers, indices, and raw CLI creation headers before lowercasing so Unicode lookalikes cannot normalize into valid Bech32 symbols. Make whole-card confirmation fold ASCII case only. Non-ASCII lookalikes now stay visibly mismatched and enter the normal retry flow for shared, unshared, and derived cards instead of being accepted or reaching the ceremony callback as an apparent match. Document the ASCII-only confirmation boundary in the API and security model. Validation: 867 tests passed normally and under python -O; Ruff check and format passed; strict mypy passed; git diff --check passed.
1 parent a860035 commit abfe6a1

10 files changed

Lines changed: 88 additions & 13 deletions

File tree

‎docs/developer/api.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,9 @@ generic parse-length failure.
7777
- `_cli_input.py` retains at most nine artifacts and delegates partial-set
7878
compatibility to `bip93.py`. Card confirmation clears the terminal and saved
7979
scrollback where supported, then displays only entered text after a mismatch.
80-
Canonical text removes whitespace for comparison; presentation state retains
81-
entered spacing and case. Grouped alignment preserves entered ownership;
80+
Canonical text removes whitespace and folds ASCII case for comparison;
81+
non-ASCII lookalikes remain mismatches. Presentation state retains entered
82+
spacing and case. Grouped alignment preserves entered ownership;
8283
unspaced alignment minimizes character edits before disturbed groups.
8384
Codex32 entry uses a separate `> ` line; correction candidates use ordinary card formatting without a prompt marker;
8485
fixed prefixes follow that marker. The `xprv` and wallet recovery paths begin

‎docs/security/model.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ available through `codex32`.
126126

127127
Creation retries show only entered text in contiguous regions: bold red means review the card, with reverse video added for the active region. Original card formatting is display-only; editable prefills retain entered case and spacing.
128128
Complete matching canonical groups freeze; local alignment preserves entered group ownership before edit minimization and proceeds without crossing frozen boundaries (see the API alignment rules).
129-
Empty retries fail; retries are unlimited. Correct full-string retries confirm; incorrect recognizable full-string retries preserve progress and clarify the active region. Only complete case/whitespace-normalized equality confirms, with no expected characters, error classifications, prescribed edits, or repairs.
129+
Empty retries fail; retries are unlimited. Correct full-string retries confirm; incorrect recognizable full-string retries preserve progress and clarify the active region. Only complete ASCII-case/whitespace-normalized equality confirms; non-ASCII lookalikes remain mismatches and must be re-entered. No expected characters, error classifications, prescribed edits, or repairs are supplied.
130130
Progressive group-level correctness feedback is explicitly accepted and does not change the confirmation boundary.
131131

132132
Confirmation shows that the operator can produce the correct recovery string during setup. It cannot prove that the physical backup was corrected rather than reconstructed using confirmation feedback.

‎src/codex32/_cli_input.py‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ class InteractiveConfirmationRequired(Exception):
6666
pass
6767

6868

69+
def _ascii_lower(value: str) -> str:
70+
"""Lowercase ASCII letters without normalizing Unicode lookalikes."""
71+
return "".join(character.lower() if character.isascii() else character for character in value)
72+
73+
6974
def _confirmation_input(prompt: str) -> str:
7075
if sys.stdin.isatty():
7176
return _editable_input(prompt)
@@ -239,13 +244,13 @@ def _entered_groups(observed: str, expected: str) -> tuple[list[str], set[int]]:
239244
compact = "".join(observed.split())
240245
expected = "".join(expected.split()).lower()
241246
tokens = observed.split()
242-
grouped = len(tokens) > 1 and compact.lower() != expected
247+
grouped = len(tokens) > 1 and _ascii_lower(compact) != expected
243248
boundaries = {0}
244249
splits: set[tuple[int, int]] = set()
245250
position = 0
246251
for token in tokens:
247252
for offset in range(0, len(expected), 4):
248-
if expected[offset : offset + len(token)] == token.lower() and (
253+
if expected[offset : offset + len(token)] == _ascii_lower(token) and (
249254
len(token) % 4 == 0 or offset + len(token) == len(expected)
250255
):
251256
splits.update((position + i, offset + i) for i in range(4, len(token), 4))
@@ -261,7 +266,7 @@ def _entered_groups(observed: str, expected: str) -> tuple[list[str], set[int]]:
261266
if end > start:
262267
current = [(end - start, b"\x02" * (end - start))]
263268
for j, char in enumerate(canonical, 1):
264-
edit = compact[end - 1].lower() != char
269+
edit = _ascii_lower(compact[end - 1]) != char
265270
current.append(
266271
min(
267272
(row[j - 1][0] + edit, row[j - 1][1] + bytes([edit])),
@@ -274,7 +279,7 @@ def _entered_groups(observed: str, expected: str) -> tuple[list[str], set[int]]:
274279
continue
275280
score = (
276281
edits + row[-1][0],
277-
disturbed + (not grouped and compact[start:end].lower() != canonical),
282+
disturbed + (not grouped and _ascii_lower(compact[start:end]) != canonical),
278283
trace + row[-1][1],
279284
(*ends, end),
280285
)
@@ -288,7 +293,9 @@ def _entered_groups(observed: str, expected: str) -> tuple[list[str], set[int]]:
288293
groups.append(observed[start:stop])
289294
start = stop
290295
changed = {
291-
i for i, value in enumerate(groups) if "".join(value.split()).lower() != expected[i * 4 : i * 4 + 4]
296+
i
297+
for i, value in enumerate(groups)
298+
if _ascii_lower("".join(value.split())) != expected[i * 4 : i * 4 + 4]
292299
}
293300
return groups, changed
294301

‎src/codex32/bip93.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,15 @@ def __post_init__(self) -> None:
5555
raise InvalidThreshold("threshold must be 0 or an integer from 2 through 9")
5656
if not isinstance(self.identifier, str):
5757
raise InvalidIdentifier("identifier must be str")
58+
if not self.identifier.isascii():
59+
raise InvalidIdentifier("identifier must contain only ASCII Bech32 symbols")
5860
identifier = self.identifier.lower()
5961
if len(identifier) != 4 or any(character not in CHARSET for character in identifier):
6062
raise InvalidIdentifier("identifier must be exactly four Bech32 symbols")
6163
if not isinstance(self.index, str):
6264
raise InvalidShareIndex("share index must be str")
65+
if not self.index.isascii():
66+
raise InvalidShareIndex("share index must be an ASCII Bech32 symbol")
6367
index = self.index.lower()
6468
if len(index) != 1 or index not in CHARSET:
6569
raise InvalidShareIndex("share index must be one Bech32 symbol")
@@ -352,6 +356,8 @@ def recover_secret(shares: Sequence[Share]) -> Secret:
352356
def _normalize_target(value: object, *, label: str) -> str:
353357
if not isinstance(value, str):
354358
raise InvalidTargetIndex(f"{label} must be one Bech32 symbol")
359+
if not value.isascii():
360+
raise InvalidTargetIndex(f"{label} must be an ASCII Bech32 symbol")
355361
normalized = value.lower()
356362
if len(normalized) != 1 or normalized not in CHARSET or normalized == "s":
357363
raise InvalidTargetIndex(f"{label} must be one of {IDX_SORT[1:].upper()}")

‎src/codex32/cli.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from codex32._cli_input import (
2121
CorrectionDeclined,
2222
InteractiveConfirmationRequired,
23+
_ascii_lower,
2324
_card_text,
2425
_case_interpretation,
2526
_confirm_correction,
@@ -203,6 +204,8 @@ def _share_command(index: str, plain: bool, context: _CliContext, core: BitcoinC
203204
def _creation_header(value: str | None) -> tuple[Profile, int | None, str | None]:
204205
if value is None:
205206
return Profile.MS, None, None
207+
if not value.isascii():
208+
raise _UsageError("The set header must contain only ASCII characters.")
206209
lowered = value.lower()
207210
if lowered != value and value.upper() != value:
208211
raise _UsageError("The set header must use either uppercase or lowercase.")
@@ -310,10 +313,10 @@ def _confirm_card(artifact: Artifact, confirm: Callable[[str], ConfirmationResul
310313
prefill=prefill,
311314
)
312315
compact = "".join(replacement.split())
313-
if compact.lower() == expected.lower():
316+
if _ascii_lower(compact) == expected.lower():
314317
groups = [replacement]
315318
break
316-
if len(compact) > len(expected[start * 4 : end * 4]) and compact.lower().startswith(
319+
if len(compact) > len(expected[start * 4 : end * 4]) and _ascii_lower(compact).startswith(
317320
(expected.split("1", 1)[0] + "1").lower()
318321
):
319322
_print(
@@ -327,7 +330,7 @@ def _confirm_card(artifact: Artifact, confirm: Callable[[str], ConfirmationResul
327330
changed.difference_update(range(start, end))
328331
changed.update(start + i for i in remaining)
329332
entered = "".join(groups)
330-
if "".join(entered.split()).lower() != expected.lower():
333+
if _ascii_lower("".join(entered.split())) != expected.lower():
331334
raise RuntimeError("Confirmation mismatch.")
332335
if confirm is not None and not confirm(entered).accepted:
333336
raise RuntimeError("Confirmation rejected.")

‎src/codex32/generation.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ def _threshold(value: object, *, allow_zero: bool = True) -> int:
6969
def _identifier(value: object) -> str:
7070
if not isinstance(value, str):
7171
raise InvalidIdentifier("identifier must be str")
72+
if not value.isascii():
73+
raise InvalidIdentifier("identifier must contain only ASCII Bech32 symbols")
7274
value = value.lower()
7375
if len(value) != 4 or any(character not in CHARSET for character in value):
7476
raise InvalidIdentifier("identifier must be four Bech32 symbols")
@@ -78,6 +80,8 @@ def _identifier(value: object) -> str:
7880
def _index(value: object) -> str:
7981
if not isinstance(value, str) or len(value) != 1:
8082
raise InvalidShareSelection("each output index must be one Bech32 symbol")
83+
if not value.isascii():
84+
raise InvalidShareSelection("each output index must be an ASCII Bech32 symbol")
8185
value = value.lower()
8286
if value not in ORDINARY_INDICES:
8387
raise InvalidShareSelection("output indices must be ordinary non-S symbols")
@@ -355,7 +359,9 @@ def confirm(self, text: str) -> ConfirmationResult:
355359
raise CeremonyStateError("request a card before confirming it")
356360
if not isinstance(text, str):
357361
raise TypeError("confirmation text must be str")
358-
observed = "".join(text.split()).lower()
362+
observed = "".join(text.split())
363+
if observed.isascii():
364+
observed = observed.lower()
359365
expected = self._pending.text.lower()
360366
mismatched = tuple(
361367
group + 1

‎tests/test_cli.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1467,6 +1467,34 @@ def answer(prompt: str, **options: object) -> str:
14671467
assert "\x1b[3J\x1b[2J\x1b[H" in prompts[1][0]
14681468

14691469

1470+
def test_creation_confirmation_retries_unicode_aliases_before_accepting(
1471+
monkeypatch: pytest.MonkeyPatch,
1472+
) -> None:
1473+
cli_module = importlib.import_module("codex32.cli")
1474+
1475+
class Card:
1476+
text = "MS10TESK"
1477+
1478+
answers = iter(("", "MS10TESK", "TESK"))
1479+
prefills: list[str] = []
1480+
confirmed: list[str] = []
1481+
1482+
def answer(_prompt: str, **options: object) -> str:
1483+
if "prefill" in options:
1484+
prefills.append(str(options["prefill"]))
1485+
return next(answers)
1486+
1487+
def confirm(value: str) -> ConfirmationResult:
1488+
confirmed.append(value)
1489+
return ConfirmationResult(True)
1490+
1491+
monkeypatch.setattr(cli_module, "_text", answer)
1492+
cli_module._confirm_card(Card(), confirm)
1493+
1494+
assert prefills == ["TESK"]
1495+
assert confirmed == [Card.text]
1496+
1497+
14701498
@pytest.mark.parametrize(
14711499
("observed", "shown", "red"),
14721500
(
@@ -1596,6 +1624,13 @@ def test_create_accepts_positional_headers_and_preserves_index_order() -> None:
15961624
assert recover_secret(basis).header.identifier == "cash"
15971625

15981626

1627+
def test_create_rejects_unicode_header_aliases_before_normalizing() -> None:
1628+
result = _invoke(["create", "MS12TESK"])
1629+
1630+
assert result.exit_code == 2
1631+
assert "ASCII" in result.stderr
1632+
1633+
15991634
@pytest.mark.parametrize(("threshold", "count"), ((2, 3), (3, 5)))
16001635
def test_create_has_reviewed_share_count_presets(threshold: int, count: int) -> None:
16011636
result = _invoke_confirmed_create(["create", f"{threshold}test"])

‎tests/test_generation.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,20 @@ def test_raw_bytes_accept_random_or_explicit_identifiers() -> None:
147147
secret = generate_master_seed(raw, identifier="TEST")
148148
assert len(random_secret.header.identifier) == 4
149149
assert secret.header.identifier == "test"
150+
with pytest.raises(InvalidIdentifier):
151+
generate_master_seed(raw, identifier="tesK")
152+
153+
154+
def test_confirmation_rejects_unicode_that_lowercases_to_bech32(
155+
monkeypatch: pytest.MonkeyPatch,
156+
) -> None:
157+
value = bytes([generation_module.CHARSET.index("k")]) * 26
158+
monkeypatch.setattr(generation_module.secrets, "token_bytes", lambda _length: value)
159+
ceremony = CreationCeremony.master_seed(threshold=2, indices="ac", identifier="test")
160+
pending = ceremony.next_share()
161+
invalid = pending.text.replace("k", "K", 1)
162+
assert invalid != pending.text
163+
assert not ceremony.confirm(invalid).accepted
150164

151165

152166
def test_supplied_seed_must_form_a_valid_bip32_root(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -178,6 +192,7 @@ def test_explicit_and_random_output_order_contracts() -> None:
178192
{"threshold": 2, "share_count": 32},
179193
{"threshold": 2, "indices": "a"},
180194
{"threshold": 2, "indices": "aa"},
195+
{"threshold": 2, "indices": "aK"},
181196
{"threshold": 2, "indices": "sa"},
182197
{"threshold": 2, "indices": "ia"},
183198
),

‎tests/test_public_api.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,9 @@ def test_master_seed_factory_can_only_construct_index_s() -> None:
122122
((1, "test", "s"), InvalidThreshold),
123123
((2.0, "test", "a"), InvalidThreshold),
124124
((2, "bad", "a"), InvalidIdentifier),
125+
((2, "tesK", "a"), InvalidIdentifier),
125126
((0, "test", "a"), InvalidShareIndex),
127+
((2, "test", "K"), InvalidShareIndex),
126128
),
127129
)
128130
def test_header_invariants(arguments: tuple[object, ...], error: type[Exception]) -> None:

‎tests/test_sharing.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def __getitem__(self, _position: int) -> Share:
153153
recover_secret(OversizedSequence()) # type: ignore[arg-type]
154154

155155

156-
@pytest.mark.parametrize("target", ("s", "i", "b", "?", "aa", "", 3))
156+
@pytest.mark.parametrize("target", ("s", "i", "b", "?", "aa", "", "K", 3))
157157
def test_invalid_targets_are_rejected(target: object) -> None:
158158
secret, masks = _ms_basis()
159159
with pytest.raises(InvalidTargetIndex):

0 commit comments

Comments
 (0)