Fix the bounds check in a TLV parser
Your task
Your binary protocol carries TLV records: a type byte, a 2-byte length, then that many value bytes. The first parser crashed within seconds of fuzzing because it trusted the length from the wire. The fix walks the packet and rejects it whole if any record does not fit.
An assistant wrote parse_tlv_types(packet). It is in the editor. It has a bug. Find it and fix it.
Input and output:
packet: the packet's bytes, as a list of integers.- Return the type byte of every record, in order, or
[-1]if the packet is malformed.
Rules the tests check:
- If any value is below 0 or above 255, return
[-1]. - Walk the records from index 0. A record at index
ihas its type ati, a big-endian length ati + 1andi + 2(first byte times 256, plus the second), and its value in the nextlengthbytes. - If fewer than 3 bytes remain at
i, return[-1]. - If fewer than
lengthbytes remain after the 3 header bytes, return[-1]. - The next record starts right after the value. The walk ends when it reaches the end of the packet exactly.
- An empty packet has no records, so return
[].
Examples
parse_tlv_types(packet: list[int]) -> list[int]Example 1
Input
parse_tlv_types([1, 0, 2, 65, 66])Output
[1]Example 2
Input
parse_tlv_types([1, 0, 1, 65, 2, 0, 0, 3, 0, 2, 9, 9])Output
[1, 2, 3]Example 3
Input
parse_tlv_types([7, 255, 255, 1, 2])Output
[-1]