Skip to content

<fstream>: Closing a filebuf after putback falls back to pbackfail leads to heap corruption #342

@Flamefire

Description

@Flamefire

The code at the bottom triggers the behavior.

The issue is caused by putback running over the start of the buffer (enforced by seekg) and hence calling pbackfail which puts the char into an internal buffer and sets that as the new buffer. The pointer to that buffer is stored in the backing structure of a FILE* where normally a heap-allocated buffer is stored. On calling fclose (through the streams close function) the implementation tries to deallocate the buffer without realizing that it is not a heap allocated buffer.

In Debug builds this triggers an assertion but on release builds it silently frees a stack pointer possibly leading to a potential vulnerability.

Depending on the memory manager used this might be used to exploit code that uses or can be forced to use that putback sequence.

#include <fstream>

int main()
{
    {
        std::ofstream f("test.txt");
        f << "ab";
    }
    std::fstream f("test.txt");
    f.seekg(1);
    f.get(); // b
    f.putback('b');
    f.putback('a');
    f.close();
    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixedSomething works now, yay!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions