diff --git a/hwilib/key.py b/hwilib/key.py index 506fb1aad..6e5930c4c 100644 --- a/hwilib/key.py +++ b/hwilib/key.py @@ -335,11 +335,21 @@ def _parse_path(nstr: str, allow_multipath: bool) -> List[List[int]]: def str_to_harden(x: str) -> int: if x.startswith("-"): - return H_(abs(int(x))) - elif x.endswith(("h", "'")): - return H_(int(x[:-1])) - else: - return int(x) + body = x[1:] + if not (body.isascii() and body.isdigit()): + raise ValueError(f"Invalid BIP32 path component: {x}") + index = int(body) + if index >= HARDENED_FLAG: + raise ValueError(f"Invalid BIP32 path component: {x}") + return H_(abs(index)) + harden = x.endswith(("h", "'")) + body = x[:-1] if harden else x + if not (body.isascii() and body.isdigit()): + raise ValueError(f"Invalid BIP32 path component: {x}") + index = int(body) + if index >= HARDENED_FLAG: + raise ValueError(f"Invalid BIP32 path component: {x}") + return H_(index) if harden else index def parse_index(x: str, seen_multipath: bool) -> Tuple[List[int], bool]: if x.startswith("<"): diff --git a/test/test_bip32.py b/test/test_bip32.py index 5a88d8243..1e1c31655 100755 --- a/test/test_bip32.py +++ b/test/test_bip32.py @@ -122,6 +122,20 @@ def test_deriv_path(self): xprv_der = par_xprv.derive_pub_path(path) self.assertEqual(xprv_der.to_string(), child_xpub) + def test_parse_path_rejects_underscore(self): + with self.assertRaises(ValueError): + parse_path("m/1_0") + self.assertEqual(parse_path("m/10"), [10]) + self.assertEqual(parse_path("m/1h"), [0x80000001]) + + def test_parse_path_rejects_non_ascii_digits_and_out_of_range(self): + for path in ("m/١", "m/1h", "m/2147483648", "m/2147483648h", "m/4294967296"): + with self.subTest(path=path): + with self.assertRaises(ValueError): + parse_path(path) + self.assertEqual(parse_path("m/2147483647"), [2147483647]) + self.assertEqual(parse_path("m/2147483647h"), [2147483647 | 0x80000000]) + if __name__ == "__main__": unittest.main()