pezmaster31 / bamtools

C++ API & command-line toolkit for working with BAM data
MIT License
418 stars 153 forks source link

Heap Overflow in BgzfStream::ReadBlock leading to code execution #200

Closed ret2fail closed 3 years ago

ret2fail commented 4 years ago

Hi there!

Love the tool! Been playing around for a while with it and I found that ReadBlock doesn't validate correctly the size of the block to read on a bam file, and that causes a heap overflow, which allows you to overwrite (among other things), the vtable of m_device. After failing to read the file, the program calls BgzfStream::Close(). This triggers the m_device->IsOpen() method, which allows us to exploit the overwritten vtable.

The problem, I think, is here: https://github.com/pezmaster31/bamtools/blob/9000c6b75f5fb3a9a9d4ab0d8984da953c18d1bb/src/api/internal/io/BgzfStream_p.cpp#L373

If the header provides a blockLength such that blockLength < Constants::BGZF_BLOCK_HEADER_LENGTH

we underflow remaining, which then overflows the heap.

To trigger the bug I used the command bamtools index -in corrupted_file.bam

SoapZA commented 3 years ago

could you post your corrupted_file.bam so I can use it for debugging?

SoapZA commented 3 years ago

Reopen if you have more insight