wolfpld / tracy

Frame profiler
https://tracy.nereid.pl/
Other
8.67k stars 598 forks source link

Possible TOCTOU race condition when reading a file #721

Closed NaKroTeK closed 5 months ago

NaKroTeK commented 5 months ago

A TOCTOU might occurs between the check of the file attributes using stat() and the subsequent opening and reading of the file with fopen()

https://github.com/wolfpld/tracy/blob/d46ffb4e9f132fc95bdd7d04207d8d669a9d4100/public/client/TracyProfiler.cpp#L3912C1-L3916C43

    if( stat( data, &st ) == 0 && (uint64_t)st.st_mtime < m_exectime )
    {
        if( st.st_size < ( TargetFrameSize - 16 ) )
        {
            FILE* f = fopen( data, "rb" );
            if( f )
            {

A proposition that may mitigate this would be the following :

    FILE* f = fopen(data, "rb");
    if (f)
    {
        struct stat st;
        if (fstat(fileno(f), &st) == 0 && (uint64_t)st.st_mtime < m_exectime && st.st_size < (TargetFrameSize - 16)) {
        auto ptr = (char*)tracy_malloc_fast(st.st_size);
        auto rd = fread(ptr, 1, st.st_size, f);
        fclose(f);
        if (rd == (size_t)st.st_size) {
            TracyLfqPrepare( QueueType::SourceCodeMetadata );
            MemWrite( &item->sourceCodeMetadata.ptr, (uint64_t)ptr );
            MemWrite( &item->sourceCodeMetadata.size, (uint32_t)rd );
            MemWrite( &item->sourceCodeMetadata.id, id );
            TracyLfqCommit;
            ok = true;
        }
    }
wolfpld commented 5 months ago

Fixed in 5037742ab.