`bech32` CLI crashes (`fromJust: Nothing`) on valid-checksum strings whose data part cannot convert to bytes

Aperta Adatta ai principianti
#92 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
78/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Ambito
cli

Direzione di ricerca

Il crash si trova in runDecode in bech32/bech32/app/Main.hs, dove fromJust racchiude dataPartToBytes dopo Bech32.decodeLenient. Sostituisci quell'unwrap con un case che chiama fail su Nothing, e rimuovi l'import non utilizzato di fromJust. I test di regressione vanno in bech32/test/AppSpec.hs: a1q3g6mn3 deve terminare con un codice di uscita diverso da zero e un messaggio di errore, invece di un'eccezione non gestita.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Description

The bech32 executable's decode path (bech32/bech32/app/Main.hs, runDecode) calls fromJust $ dataPartToBytes dataPart on the result of Bech32.decodeLenient. decodeLenient verifies the checksum but does not check that the data part converts to bytes; dataPartToBytes returns Nothing whenever the 5-bit-word count leaves a leftover bit-group of 5–7 bits (word counts ≡ 1, 3, 6 mod 8) or non-zero padding bits. Any valid-checksum string in that class — e.g. a1q3g6mn3 (human-readable part a, one data word) — therefore crashes the CLI with an uncaught Maybe.fromJust: Nothing exception instead of producing output or a clean error. The library function itself is total (Maybe); only the CLI's use of fromJust is at fault.

Note the library-level callers handle this correctly — cardano-api/cardano-keys (deserialiseFromBech32) and cardano-addresses (fromBech32) both map Nothing to a proper error (Bech32DataPartToBytesError / "invalid data-part..."). Only this CLI app unwraps with fromJust.

Affected version
  • Repo: IntersectMBO/bech32, commit 4624d3a (release 1.1.11)
  • File: bech32/bech32/app/Main.hs (runDecode)
Reproduction

Prerequisite: a checkout of IntersectMBO/bech32 at commit 4624d3a with GHC/cabal.

cabal build exe:bech32
printf 'a1q3g6mn3' | cabal run exe:bech32

Other triggering inputs (all valid-checksum): a1qqqd87cpp (3 data words), a1qqqqqq3q4q7k (6 data words), addr1qqqwygn75 (3 data words). Any valid-checksum string whose data-word count n satisfies 5n mod 8 ∈ {5, 6, 7} triggers it; strings with n ≡ 2, 5, 7 (mod 8) also trigger it when the leftover padding bits are non-zero.

Bit-math proof (no build needed to see the failure mode):

  • dataPartToBytes → toBase256 → convertBits words 5 8 noPadding.
  • noPadding requires bits < frombits && padValue == 0, i.e. the leftover bit-group after packing into bytes must be fewer than 5 bits and all zero.
  • For a data part of n 5-bit words, leftover bits = 5n mod 8. For n = 1: leftover = 5, and 5 < 5 is false → Nothing.
  • a1q3g6mn3 is a genuine valid bech32 string: HRP a, data words [0], checksum 3g6mn3 computed with the BIP-173 reference algorithm (verified: bech32_polymod(hrp_expand("a") + [0, 17, 8, 26, 27, 19, 5]) == 1). decodeLenient therefore returns Right, and the CLI's fromJust throws.

Relevant code (bech32/bech32/app/Main.hs):

runDecode source =
    case Bech32.decodeLenient source of
        Left err ->
            fail (show err)
        Right (_, dataPart) -> do
            let base16 = convertToBase BA.Base16
            B8.putStrLn $ base16 $ fromJust $ dataPartToBytes dataPart
Expected vs actual behavior

Expected: either the decoded bytes as hex, or a clean error such as "data part cannot be converted to bytes".

Actual: uncaught exception, process aborts:

bech32: Maybe.fromJust: Nothing
Suggested fix

In bech32/bech32/app/Main.hs, replace the fromJust with an explicit error (and drop the now-unused fromJust import):

runDecode source =
    case Bech32.decodeLenient source of
        Left err ->
            fail (show err)
        Right (_, dataPart) ->
            case dataPartToBytes dataPart of
                Nothing ->
                    fail "Unable to convert the data part to bytes: \
                         \the number of data words is not compatible with \
                         \byte conversion (invalid padding)."
                Just bytes ->
                    B8.putStrLn $ convertToBase BA.Base16 bytes

Regression test: add a1q3g6mn3 (and one string from each residue class 1, 3, 6 mod 8) to bech32/test/AppSpec.hs, asserting a clean non-zero exit with an error message rather than an uncaught exception.

Impact note

The bech32 CLI — a user-facing developer tool shipped with the package — aborts with an uncaught exception on valid input. A user decoding a legitimate bech32 string (e.g. a short datum, a key fragment, or any payload whose word count lands in the bad residue classes) gets a crash instead of output or an intelligible error. Impact is confined to the local CLI process: no data loss, no disclosure, no network effect. Scripts that pipe bech32 strings through the CLI and do not expect a crash exit code may mis-handle the failure. The underlying library is not at fault and needs no change.

References
  • CWE-248 (Uncaught Exception).
  • The convertBits/noPadding evaluation for n = 1 was traced step by step: result' is empty ([-3, -11 .. 0] is empty), final noPadding guard 5 < 5 fails → Nothing. The triggering strings were generated with the verbatim BIP-173 reference implementation and cross-checked against a simulation whose polymod reproduces 22/22 of the repo's own valid test vectors.
  • Related but distinct from the long-string crash in locateErrors (a separate issue): this finding needs no long input and a valid checksum, and lives in the CLI app rather than the library.
  • Environment: code audit, 2026-11-23; empirical Haskell check not run.
Lingua principale
Haskell
Stelle
50
Fork
12
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di IntersectMBO/bech32

Tutte le issue di IntersectMBO/bech32

Issue simili

Altre issue su Haskell

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.