Skip to content

Reject '+', '_' and whitespace in integers and string lengths - #187

Open
bardrop wants to merge 1 commit into
whtsky:masterfrom
bardrop-oss:reject-non-canonical-numbers
Open

bardrop wants to merge 1 commit into
whtsky:masterfrom
bardrop-oss:reject-non-canonical-numbers

Conversation

@bardrop

@bardrop bardrop commented Nov 21, 2026

Copy link
Copy Markdown

bdecode accepts integers and string lengths that are not plain ASCII digits, because decode_int and decode_string hand the bytes to int(), which also allows +, _ and surrounding whitespace:

>>> bdecode(b'i1_0e')
10
>>> bdecode(b'i 1 e')
1
>>> bdecode(b'1_0:aaaaaaaaaa')
b'aaaaaaaaaa'

BEP 3 allows only digits (with an optional leading - for integers). Accepting these also means a torrent can decode to the same value as a different byte string, so re-encoding it changes the info hash.

The fix checks the bytes with bytes.isdigit() (ASCII only) before int(). The existing leading-zero and -0 checks are unchanged.

New test test_decode_rejects_non_canonical_numbers fails before and passes after; pytest: 23 passed. I also ran 8k random/mutated inputs against a strict BEP 3 decoder: the only differences left are unsorted/duplicate dict keys, which this library accepts on purpose.

decode_int and decode_string passed the bytes to int(), which accepts
'+1', '1_0' and ' 1 '. So i1_0e decoded as 10 and 1_0:... as a
10-byte string, although bencode only allows ASCII digits (and a
leading '-' for integers).
@sonarqubecloud

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant