Skip to content

[FIX] matroska: accumulate EBML element IDs in an unsigned int - #2407

Open
pranayr710 wants to merge 2 commits into
CCExtractor:masterfrom
pranayr710:fix/mkv-ebml-id-signed-shift
Open

pranayr710 wants to merge 2 commits into
CCExtractor:masterfrom
pranayr710:fix/mkv-ebml-id-signed-shift

Conversation

@pranayr710

@pranayr710 pranayr710 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Reason for this PR:

  • This PR fixes a bug — undefined behaviour in the MKV parser, confirmed with UBSan on a generated corpus.

Sanity check:

  • I have read and understood the contributors guide.
  • I have checked that another pull request for this purpose does not exist.
  • Bug fix, so NOT added to the changelog.
  • Not adding new C code — one type change, eight places.

What was wrong

Every EBML parse loop in matroska.c accumulates the element ID a byte at a time into a signed int:

int code = 0, code_len = 0;
while (pos + len > get_current_byte(file))
{
        code <<= 8;
        code += mkv_read_byte(file);

An EBML ID is at most four bytes, and the loops do bound code to that: every matching case resets it through MATROSKA_SWITCH_BREAK, and the default arm resets it once code_len == MATROSKA_MAX_ID_LENGTH. So the accumulator never grows past four bytes.

The overflow is on that fourth byte. Going into the fourth iteration code holds three bytes; code <<= 8 moves them into bits 8–31. If the first of those bytes is >= 0x80 the result needs bit 31, which int cannot represent — signed left-shift overflow, undefined behaviour under C11 6.5.7p4. It needs no malformed input beyond an unknown four-byte ID whose first byte has the top bit set.

UBSan on master reports it at:

../src/lib_ccx/matroska.c:620:8:  runtime error: left shift of 8521680 by 8 places
                                  cannot be represented in type 'int'
../src/lib_ccx/matroska.c:1969:8: same

The change

code becomes uint32_t in all eight loops — an EBML ID is exactly 32 bits, so the fixed-width type says what is meant and unsigned shift/wraparound is well defined. The "Unknown element" and "Deprecated element" diagnostics now print it with "0x%" PRIx32 to match.

code_len is left as int; it is only a counter.

Reproducing

# any MKV with a subtitle track; mutate some SimpleBlock size bytes
ffmpeg -f lavfi -i "testsrc=size=160x120:rate=10:duration=8" -i subs.srt \
       -map 0:v -map 1:s -c:v libx264 -c:s srt base.mkv
# then build with -fsanitize=undefined and run
ccextractor fuzzed.mkv --out=srt -o out.srt

One gotcha that cost me time: CCExtractor writes each MKV subtitle track to a file next to the input, so with a read-only input directory it stops at Error: Cannot create output file for subtitle track before reaching the parser loops. The input directory has to be writable to reach this code.

Verification

Built master and this branch from identical source in the same image.

master this PR
UBSan over a 25-file fuzzed MKV corpus reports at 2 sites none
Well-formed MKV extracted track a58ba9a536 a58ba9a536 (stable over 5 runs each)
Compiler warnings 15 15 (all pre-existing)

One thing to be straight about: three truncated inputs show differing stdout between the two builds — but master already differs from itself on those. Its "Unknown element" diagnostic prints the accumulator, whose value was undefined precisely because of this bug. Running master alone five times produces the same set of hashes that the comparison flagged:

t25  master:{adc1cc3a, e982434a}   this PR:{adc1cc3a, e982434a}
t50  master:{0812afe2, cc9a3f71}   this PR:{0812afe2, cc9a3f71}

So that is pre-existing nondeterminism on malformed input, not a change in behaviour. Well-formed files are byte-identical.

This is UB a compiler is entitled to exploit rather than an observed misbehaviour — on x86/GCC today the shift does what you would naively expect. Same category as #2353.

(Prepared with AI assistance; the reproducers and the sanitizer runs are my own.)

Every EBML parse loop in matroska.c builds the element ID one byte at a
time into a signed int:

    int code = 0, code_len = 0;
    while (pos + len > get_current_byte(file))
    {
            code <<= 8;
            code += mkv_read_byte(file);

On a well-formed file the switch matches within four bytes and code is
reset, but nothing resets it when no case matches, so the shift walks
past INT_MAX and signed overflow is undefined behaviour.

UBSan on a fuzzed MKV corpus reports it at four of the eight identical
loops:

    matroska.c:489:8:  runtime error: left shift of 8521680 by 8 places
                       cannot be represented in type 'int'
    matroska.c:1229, matroska.c:1275, matroska.c:1963: same

Make code unsigned in all eight. EBML IDs are at most four bytes, every
case label is a positive constant, and the existing diagnostics already
print it with "0x%x", which expects unsigned. Unsigned wraparound is
well defined, so the accumulator keeps the behaviour the format implies.

Verified against master built from the same source in the same image:

  UBSan over a 25-file fuzzed MKV corpus: 3 sites -> 0
  Well-formed MKV: byte-identical extracted track, stable over 5 runs
  Compiler warnings: 15 before, 15 after (all pre-existing)

Three truncated inputs differ in stdout, but master already differs from
itself on those: its diagnostics print the accumulator, whose value was
undefined precisely because of this bug. Repeated runs of master alone
produce the same set of hashes flagged in the comparison.

@cfsmp3 cfsmp3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is Carlos' claude doing the first pass. Before Carlos takes a look, please address these issues.

The UB is real: UBSan on master reports matroska.c:620 and matroska.c:1969 (left shift of a 3-byte value by 8 when the first ID byte is >= 0x80). Your change removes it, and output is byte-identical on our MKV samples.

  1. The project uses fixed-width types. An EBML ID is exactly 32 bits, so please declare the accumulator as uint32_t code = 0; in all eight loops instead of unsigned int, and print it with "0x%" PRIx32 in the "Unknown element" / "Deprecated element" diagnostics.
  2. The description says nothing resets code. That's wrong: each loop resets it after 4 bytes (code_len == MATROSKA_MAX_ID_LENGTH). The overflow happens on the 4th byte when the first byte has its top bit set. Please correct the description.

Review feedback: an EBML ID is exactly 32 bits, so say so with a
fixed-width type rather than unsigned int, and print it with PRIx32 in
the "Unknown element" and "Deprecated element" diagnostics.
@pranayr710

Copy link
Copy Markdown
Contributor Author

Thanks — both points were right, and the second one was a real error in my description rather than a wording problem.

1. Fixed-width type. code is now uint32_t in all eight loops, and the "Unknown element" / "Deprecated element" diagnostics print it with "0x%" PRIx32. (inttypes.h already reaches matroska.c through lib_ccx.h → ccx_common_platform.h, so no new include.)

2. The description was wrong and I have rewritten it. I wrote that nothing resets code, which implied unbounded accumulation across an arbitrarily long run of bytes. That is not what happens: every matching case resets it via MATROSKA_SWITCH_BREAK, and the default arm resets it once code_len == MATROSKA_MAX_ID_LENGTH, so the accumulator is bounded to four bytes exactly as you say. The overflow is the single shift on the fourth byte — three accumulated bytes move into bits 8–31, and if the leading one is >= 0x80 the result needs bit 31, which int cannot represent. That also means it does not need malformed input in the way I implied; an unknown four-byte ID with the top bit set in its first byte is enough.

I also corrected the UBSan figures. The old description said four sites in prose and three in the table, which was careless; re-measured on this corpus it is what you reported.

No functional change from the previous revision — type and format specifiers only.

@ccextractor-bot

Copy link
Copy Markdown
Collaborator
CCExtractor CI platform finished running the test files on linux. 171/238 tests matched the approved output:
Report Name Tests Passed
Broken 9/13
CEA-708 2/14
DVB 0/7
DVD 3/3
DVR-MS 2/2
General 25/28
Hardsubx 1/1
Hauppage 3/3
MP4 3/3
NoCC 10/10
Options 69/86
Teletext 0/21
WTV 12/13
XDS 32/34

67 tests do not match the approved output. That is the pass/fail verdict. Whether this branch caused it is a separate question, answered below.


Compared with the tip of master — test 9878, commit 185fe3f:

  • 1 pass there and fail here
  • 0 fail there and pass here
  • 0 fail on both, with different output
  • 66 fail on both, byte for byte the same

Pass there, fail here:

  • ccextractor --autoprogram --out=ttxt --latin1 --ucla c41f73056a...

Compared with the commit this branch was cut from — test 9750, commit d7eb132:

  • 0 pass there and fail here
  • 44 fail there and pass here
  • 28 fail on both, with different output
  • 39 fail on both, byte for byte the same
  • 1 have no result in that run

Fail on both but produce different output — behaviour moved even though the verdict did not:

Fail there, pass here:


This branch changes the behaviour of 1 test(s) relative to the tip of master. Those are the ones worth looking at; anything else in the list fails the same way on both sides.

@ccextractor-bot

Copy link
Copy Markdown
Collaborator
CCExtractor CI platform finished running the test files on windows. 171/238 tests matched the approved output:
Report Name Tests Passed
Broken 9/13
CEA-708 2/14
DVB 0/7
DVD 3/3
DVR-MS 2/2
General 26/28
Hardsubx 1/1
Hauppage 3/3
MP4 3/3
NoCC 10/10
Options 69/86
Teletext 0/21
WTV 11/13
XDS 32/34

67 tests do not match the approved output. That is the pass/fail verdict. Whether this branch caused it is a separate question, answered below.


Compared with the tip of master — test 9693, commit af4b28d:

  • 0 pass there and fail here
  • 156 fail there and pass here
  • 42 fail on both, with different output
  • 25 fail on both, byte for byte the same
  • 1 have no result in that run

Fail on both but produce different output — behaviour moved even though the verdict did not:

Fail there, pass here:


Compared with the commit this branch was cut from: the same run as the tip of master (test 9693), so the comparison above already covers it.


This branch changes the behaviour of 42 test(s) relative to the tip of master. Those are the ones worth looking at; anything else in the list fails the same way on both sides.

@pranayr710
pranayr710 requested a review from cfsmp3 November 10, 2026 15:55
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.

4 participants