Exploit database

GH-77b084c651f84d76fe59d880f4600f96

genaforvena/mishe-tauftauf2shell

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

412 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files19

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

lab/frontier/kicad2shell/realcfb/driver-vuln.cpp

C++ · 22,281 bytes
/* Generated by realcfb/run.sh. Only #line regions are upstream bytes. */
#include "stubs.hpp"

#line 124 "altium_binary_parser.h"
class ALTIUM_BINARY_PARSER
{
public:
    ALTIUM_BINARY_PARSER( const ALTIUM_COMPOUND_FILE& aFile, const CFB::COMPOUND_FILE_ENTRY* aEntry );
    ALTIUM_BINARY_PARSER( std::unique_ptr<char[]>& aContent, size_t aSize );
    ~ALTIUM_BINARY_PARSER() = default;

    template <typename Type>
    Type Read()
    {
        const size_t remainingBytes = GetRemainingBytes();

        if( remainingBytes >= sizeof( Type ) )
        {
            Type val = *(Type*) ( m_pos );
            m_pos += sizeof( Type );
            return val;
        }
        else
        {
            m_pos += remainingBytes; // Ensure remaining bytes are zero
            m_error = true;
            return 0;
        }
    }

    template <typename Type>
    Type Peek()
    {
        char* const oldPos = m_pos;
        const bool  oldError = m_error;
        Type        result = Read<Type>();
        m_pos = oldPos;
        m_error = oldError;
        return result;
    }

    wxScopedCharBuffer ReadCharBuffer()
    {
        uint8_t len = Read<uint8_t>();

        if( GetRemainingBytes() >= len )
        {
            char* buf = static_cast<char*>( malloc( len ) );
            memcpy( buf, m_pos, len );
            m_pos += len;

            return wxScopedCharBuffer::CreateOwned( buf, len );
        }
        else
        {
            m_error = true;
            return wxScopedCharBuffer();
        }
    }

    wxString ReadWxString()
    {
        // TODO: Identify where the actual code page is stored. For now, this default code page
        //       has limited impact, because recent Altium files come with a UTF16 string table
        return wxString( ReadCharBuffer(), wxConvISO8859_1 );
    }

    std::map<uint32_t, wxString> ReadWideStringTable()
    {
        std::map<uint32_t, wxString> table;
        size_t                       remaining = GetRemainingBytes();

        while( remaining >= 8 )
        {
            uint32_t index = Read<uint32_t>();
            uint32_t length = Read<uint32_t>();
            wxString str;
            remaining -= 8;

            if( length <= 2 )
            {
                length = 0; // for empty strings, not even the null bytes are present
            }
            else
            {
                if( length > remaining )
                    break;

                str = wxString( m_pos, wxMBConvUTF16LE(), length - 2 );
            }

            table.emplace( index, str );
            m_pos += length;
            remaining -= length;
        }

        return table;
    }

    std::vector<char> ReadVector( size_t aSize )
    {
        if( aSize > GetRemainingBytes() )
        {
            m_error = true;
            return {};
        }
        else
        {
            std::vector<char> data( m_pos, m_pos + aSize );
            m_pos += aSize;
            return data;
        }
    }

    int ReadBytes( char* aOut, size_t aSize )
    {
        if( aSize > GetRemainingBytes() )
        {
            m_error = true;
            return 0;
        }
        else
        {
            memcpy( aOut, m_pos, aSize );
            m_pos += aSize;
            return aSize;
        }
    }

    int32_t ReadKicadUnit()
    {
        return ALTIUM_PROPS_UTILS::ConvertToKicadUnit( Read<int32_t>() );
    }

    int32_t ReadKicadUnitX()
    {
        return ReadKicadUnit();
    }

    int32_t ReadKicadUnitY()
    {
        return -ReadKicadUnit();
    }

    VECTOR2I ReadVector2IPos()
    {
        int32_t x = ReadKicadUnitX();
        int32_t y = ReadKicadUnitY();
        return { x, y };
    }

    VECTOR2I ReadVector2ISize()
    {
        int32_t x = ReadKicadUnit();
        int32_t y = ReadKicadUnit();
        return { x, y };
    }

    size_t ReadAndSetSubrecordLength()
    {
        uint32_t length = Read<uint32_t>();
        m_subrecord_end = m_pos + length;
        return length;
    }

    std::map<wxString, wxString> ReadProperties(
            std::function<std::map<wxString, wxString>( const std::string& )> handleBinaryData =
                    []( const std::string& )
                    {
                        return std::map<wxString, wxString>();
                    } );

    void Skip( size_t aLength )
    {
        if( GetRemainingBytes() < aLength )
        {
            m_error = true;
            return;
        }

        m_pos += aLength;
    }

    void SkipSubrecord()
    {
        if( m_subrecord_end == nullptr || m_subrecord_end < m_pos )
        {
            m_error = true;
            return;
        }

        m_pos = m_subrecord_end;
    };

    size_t GetRemainingBytes() const
    {
        if( m_pos == nullptr || m_content.get() + m_size < m_pos )
            return 0;

        return m_size - ( m_pos - m_content.get() );
    }

    size_t GetRemainingSubrecordBytes() const
    {
        if( m_pos == nullptr || m_subrecord_end == nullptr || m_subrecord_end < m_pos )
            return 0;

        return m_subrecord_end - m_pos;
    };

    bool HasParsingError() { return m_error; }

private:
    std::unique_ptr<char[]> m_content;
    size_t                  m_size;

    char*                   m_pos;           // current read pointer
    char*                   m_subrecord_end; // pointer which points to next subrecord start
    bool                    m_error;
};

#line 319 "altium_binary_parser.cpp"
ALTIUM_BINARY_PARSER::ALTIUM_BINARY_PARSER( const ALTIUM_COMPOUND_FILE&     aFile,
                              const CFB::COMPOUND_FILE_ENTRY* aEntry )
{
    m_subrecord_end = nullptr;
    m_size          = static_cast<size_t>( aEntry->size );
    m_error         = false;
    m_content.reset( new char[m_size] );
    m_pos = m_content.get();

    // read file into buffer
    aFile.GetCompoundFileReader().ReadFile( aEntry, 0, m_content.get(), m_size );
}


ALTIUM_BINARY_PARSER::ALTIUM_BINARY_PARSER( std::unique_ptr<char[]>& aContent, size_t aSize )
{
    m_subrecord_end = nullptr;
    m_size = aSize;
    m_error = false;
    m_content = std::move( aContent );
    m_pos = m_content.get();
}

#line 343 "altium_binary_parser.cpp"
std::map<wxString, wxString> ALTIUM_BINARY_PARSER::ReadProperties(
        std::function<std::map<wxString, wxString>( const std::string& )> handleBinaryData )
{
    // TSAN reports calling this wx macro is not thread-safe
    static wxCSConv convISO8859_1 = wxConvISO8859_1;

    std::map<wxString, wxString> kv;

    uint32_t length = Read<uint32_t>();
    bool isBinary = ( length & 0xff000000 ) != 0;

    length &= 0x00ffffff;

    if( length > GetRemainingBytes() )
    {
        m_error = true;
        return kv;
    }

    if( length == 0 )
    {
        return kv;
    }

    // There is one case by kliment where Board6 ends with "|NEARDISTANCE=1000mi".
    // Both the 'l' and the null-byte are missing, which looks like Altium swallowed two bytes.
    bool hasNullByte = m_pos[length - 1] == '\0';

    if( !hasNullByte && !isBinary )
    {
        wxLogTrace( "ALTIUM", wxT( "Missing null byte at end of property list. Imported data "
                                   "might be  malformed or missing." ) );
    }

    // we use std::string because std::string can handle NULL-bytes
    // wxString would end the string at the first NULL-byte
    std::string str = std::string( m_pos, length - ( ( hasNullByte && !isBinary ) ? 1 : 0 ) );
    m_pos += length;

    if( isBinary )
    {
        return handleBinaryData( str );
    }

    std::size_t token_end = 0;

    while( token_end < str.size() && token_end != std::string::npos )
    {
        std::size_t token_start = str.find( '|', token_end );
        std::size_t token_equal = str.find( '=', token_end );
        std::size_t key_start;

        if( token_start <= token_equal )
        {
            key_start = token_start + 1;
        }
        else
        {
            // Leading "|" before "RECORD=28" may be missing in older schematic versions.
            key_start = token_end;
        }

        token_end = str.find( '|', key_start );

        if( token_equal >= token_end )
        {
            continue; // this looks like an error: skip the entry. Also matches on std::string::npos
        }

        if( token_end == std::string::npos )
        {
            token_end = str.size() + 1; // this is the correct offset
        }

        std::string keyS = str.substr( key_start, token_equal - key_start );
        std::string valueS = str.substr( token_equal + 1, token_end - token_equal - 1 );

        // convert the strings to wxStrings, since we use them everywhere
        // value can have non-ASCII characters, so we convert them from LATIN1/ISO8859-1
        wxString key( keyS.c_str(), convISO8859_1 );

        // Altium stores keys either in Upper, or in CamelCase. Lets unify it.
        wxString canonicalKey = key.Trim( false ).Trim( true ).MakeUpper();

        // If the key starts with '%UTF8%' we have to parse the value using UTF8
        wxString value;

        if( canonicalKey.StartsWith( "%UTF8%" ) )
            value = wxString( valueS.c_str(), wxConvUTF8 );
        else
            value = wxString( valueS.c_str(), convISO8859_1 );

        if( canonicalKey != wxS( "PATTERN" ) && canonicalKey != wxS( "SOURCEFOOTPRINTLIBRARY" ) )
        {
            // Breathless hack because I haven't a clue what the story is here (but this character
            // appears in a lot of radial dimensions and is rendered by Altium as a space).
            value.Replace( wxT( "ÿ" ), wxT( " " ) );
        }

        kv.insert( { canonicalKey, value.Trim() } );
    }

    // DESIGNATOR/NAME/TEXT carry Altium overbar markup that must be converted for every record
    // type except RECORD=4 (LABEL). Older schematics emit those keys ahead of RECORD, so the type
    // is only reliably known once the whole record has been read; deciding mid-stream both misses
    // the exemption and, via operator[], leaves an empty RECORD that shadows the real value.
    auto recordIt = kv.find( wxT( "RECORD" ) );

    if( recordIt == kv.end() || recordIt->second != wxT( "4" ) )
    {
        for( const wxString& key : { wxT( "DESIGNATOR" ), wxT( "NAME" ), wxT( "TEXT" ) } )
        {
            auto valueIt = kv.find( key );

            if( valueIt != kv.end() )
                valueIt->second = AltiumPropertyToKiCadString( valueIt->second );
        }
    }

    return kv;
}

#line 5883 "sch_io_altium.cpp.vuln"
void SCH_IO_ALTIUM::ParseLibHeader( const ALTIUM_COMPOUND_FILE& aAltiumSchFile,
                                    std::vector<int>& aFontSizes )
{
    const CFB::COMPOUND_FILE_ENTRY* file = aAltiumSchFile.FindStream( { "FileHeader" } );

    if( file == nullptr )
        THROW_IO_ERROR( wxT( "FileHeader not found" ) );

    ALTIUM_BINARY_PARSER reader( aAltiumSchFile, file );

    if( reader.GetRemainingBytes() <= 0 )
        THROW_IO_ERROR( wxT( "FileHeader does not contain any data" ) );

    std::map<wxString, wxString> properties = reader.ReadProperties();

    wxString libtype = ALTIUM_PROPS_UTILS::ReadString( properties, "HEADER", "" );

    if( libtype.CmpNoCase( "Protel for Windows - Schematic Library Editor Binary File Version 5.0" ) )
        THROW_IO_ERROR( _( "Expected Altium Schematic Library file version 5.0" ) );

    for( auto& [key, value] : properties )
    {
        wxString upperKey = key.Upper();
        wxString remaining;

        if( upperKey.StartsWith( "SIZE", &remaining ) )
        {
            if( !remaining.empty() )
            {
                int ind = wxAtoi( remaining );

                if( static_cast<int>( aFontSizes.size() ) < ind )
                    aFontSizes.resize( ind );

                // Altium stores in pt.  1 pt = 1/72 inch.  1 mil = 1/1000 inch.
                int scaled = schIUScale.MilsToIU( wxAtoi( value ) * 72.0 / 10.0 );
                aFontSizes[ind - 1] = scaled;
            }
        }
    }
}

/* #line reset: lab driver below.
 *
 * REAL MS-CFB (OLE2) reader.  Unlike the realparser lane's pre-built byte
 * shim, this walks a genuine compound-file container: header -> DIFAT ->
 * FAT -> directory (UTF-16 name match) -> miniFAT -> mini stream.  The bytes
 * delivered to the VERBATIM upstream ReadProperties() and pinned
 * ParseLibHeader() are extracted from that container, not hand-assembled.
 *
 * Scope of "real": a v3 (512-byte sector) file with the FAT in the 109-entry
 * DIFAT array and no DIFAT chain is exercised; the fixture satisfies that
 * layout and olefile read-back confirms it.  wxWidgets and KiCad's own CFB
 * class are still not linked; this is a lab implementation of the CFB walk.
 */
#include <fstream>
#include <iterator>
#include <string>

static const uint32_t CFB_FREESECT = 0xFFFFFFFFu;
static const uint32_t CFB_ENDOFCHAIN = 0xFFFFFFFEu;
static const uint32_t CFB_FATSECT = 0xFFFFFFFDu;

static uint32_t rd32( const unsigned char* p )
{
    return (uint32_t) p[0] | ( (uint32_t) p[1] << 8 ) | ( (uint32_t) p[2] << 16 )
           | ( (uint32_t) p[3] << 24 );
}

struct RealCFB
{
    std::vector<unsigned char> b;
    uint32_t sectorSize = 512, miniSectorSize = 64, cutoff = 4096;
    uint32_t firstDir = 0, firstMiniFat = CFB_ENDOFCHAIN, numMiniFat = 0;
    uint32_t firstDifat = CFB_ENDOFCHAIN, numDifat = 0;
    std::vector<uint32_t> fat;
    std::vector<unsigned char> miniStream;
    std::string err;

    const unsigned char* sector( uint32_t id ) const
    {
        size_t off = 512u + (size_t) id * sectorSize;
        if( id >= CFB_FREESECT || off + sectorSize > b.size() ) return nullptr;
        return b.data() + off;
    }

    std::vector<uint32_t> chain( uint32_t start ) const
    {
        std::vector<uint32_t> out;
        uint32_t s = start;
        while( s < CFB_ENDOFCHAIN && out.size() < fat.size() + 1 )
        {
            out.push_back( s );
            s = s < fat.size() ? fat[s] : CFB_FREESECT;
        }
        return out;
    }

    bool load( const char* path )
    {
        std::ifstream f( path, std::ios::binary );
        if( !f ) { err = "open failed"; return false; }
        b.assign( std::istreambuf_iterator<char>( f ), std::istreambuf_iterator<char>() );
        static const unsigned char sig[8] = { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 };
        if( b.size() < 512 || std::memcmp( b.data(), sig, 8 ) ) { err = "bad signature"; return false; }
        auto u16 = [&]( size_t o ) { return (uint32_t) b[o] | ( (uint32_t) b[o + 1] << 8 ); };
        auto u32 = [&]( size_t o ) { return rd32( b.data() + o ); };
        sectorSize = 1u << u16( 30 );
        miniSectorSize = 1u << u16( 32 );
        uint32_t numFat = u32( 44 );
        firstDir = u32( 48 );
        cutoff = u32( 56 );
        firstMiniFat = u32( 60 );
        numMiniFat = u32( 64 );
        firstDifat = u32( 68 );
        numDifat = u32( 72 );
        if( sectorSize < 128 || sectorSize > 4096 ) { err = "bad sector shift"; return false; }

        std::vector<uint32_t> fatSecs;
        for( int i = 0; i < 109; ++i )
        {
            uint32_t s = u32( 76 + 4 * i );
            if( s < CFB_ENDOFCHAIN ) fatSecs.push_back( s );
        }
        uint32_t d = firstDifat;
        for( uint32_t i = 0; i < numDifat && d < CFB_ENDOFCHAIN; ++i )
        {
            const unsigned char* p = sector( d );
            if( !p ) { err = "bad DIFAT sector"; return false; }
            for( uint32_t j = 0; j + 1 < sectorSize / 4; ++j )
            {
                uint32_t s = rd32( p + 4 * j );
                if( s < CFB_ENDOFCHAIN ) fatSecs.push_back( s );
            }
            d = rd32( p + sectorSize - 4 );
        }
        if( fatSecs.size() < numFat ) { err = "short DIFAT"; return false; }
        fatSecs.resize( numFat );
        for( uint32_t s : fatSecs )
        {
            const unsigned char* p = sector( s );
            if( !p ) { err = "bad FAT sector"; return false; }
            for( uint32_t j = 0; j < sectorSize / 4; ++j ) fat.push_back( rd32( p + 4 * j ) );
        }
        return true;
    }

    // Directory entry fields: name at 0, name length at 64, type at 66,
    // start at 116, 8-byte size at 120.
    bool findStream( const char* name, uint32_t& start, uint64_t& size, int& type ) const
    {
        std::wstring wname( name, name + std::strlen( name ) );
        for( uint32_t s : chain( firstDir ) )
        {
            const unsigned char* p = sector( s );
            if( !p ) return false;
            for( uint32_t e = 0; e < sectorSize / 128; ++e )
            {
                const unsigned char* de = p + e * 128;
                uint32_t nameLen = (uint32_t) de[64] | ( (uint32_t) de[65] << 8 );
                int otype = de[66];
                if( otype == 0 || nameLen < 2 || nameLen > 64 ) continue;
                bool match = nameLen == wname.size() * 2 + 2;
                if( match )
                {
                    for( size_t k = 0; k < wname.size() && match; ++k )
                    {
                        uint32_t c = (uint32_t) wname[k];
                        if( de[2 * k] != (unsigned char) ( c & 0xff )
                            || de[2 * k + 1] != (unsigned char) ( c >> 8 ) ) match = false;
                    }
                }
                if( match )
                {
                    start = rd32( de + 116 );
                    size = (uint64_t) rd32( de + 120 ) | ( (uint64_t) rd32( de + 124 ) << 32 );
                    type = otype;
                    return true;
                }
            }
        }
        return false;
    }

    bool loadMiniStream()
    {
        // Root entry's start sector and size are the mini-stream container.
        for( uint32_t s : chain( firstDir ) )
        {
            const unsigned char* p = sector( s );
            if( !p ) return false;
            if( p[66] != 5 ) continue;
            uint32_t start = rd32( p + 116 );
            uint64_t size = (uint64_t) rd32( p + 120 ) | ( (uint64_t) rd32( p + 124 ) << 32 );
            for( uint32_t sec : chain( start ) )
            {
                const unsigned char* q = sector( sec );
                if( !q ) return false;
                size_t take = std::min<size_t>( sectorSize, (size_t) std::min<uint64_t>( size, size ) );
                miniStream.insert( miniStream.end(), q, q + take );
                if( size >= sectorSize ) size -= sectorSize; else size = 0;
                if( size == 0 ) break;
            }
            return true;
        }
        return false;
    }

    bool readStream( const char* name, std::vector<unsigned char>& out )
    {
        uint32_t start = 0; uint64_t size = 0; int type = 0;
        if( !findStream( name, start, size, type ) ) { err = "stream not found"; return false; }
        if( size < cutoff )
        {
            if( miniStream.empty() && !loadMiniStream() ) { err = "no mini stream"; return false; }
            std::vector<uint32_t> mfat;
            for( uint32_t s : chain( firstMiniFat ) )
            {
                const unsigned char* p = sector( s );
                if( !p ) { err = "bad miniFAT"; return false; }
                for( uint32_t j = 0; j < sectorSize / 4; ++j ) mfat.push_back( rd32( p + 4 * j ) );
            }
            uint32_t m = start;
            while( m < CFB_ENDOFCHAIN && out.size() < size )
            {
                size_t off = (size_t) m * miniSectorSize;
                if( off + miniSectorSize > miniStream.size() ) { err = "mini sector OOB"; return false; }
                size_t take = std::min<size_t>( miniSectorSize, (size_t) size - out.size() );
                out.insert( out.end(), miniStream.begin() + off, miniStream.begin() + off + take );
                m = m < mfat.size() ? mfat[m] : CFB_FREESECT;
            }
        }
        else
        {
            for( uint32_t s : chain( start ) )
            {
                const unsigned char* p = sector( s );
                if( !p ) { err = "bad stream sector"; return false; }
                size_t take = std::min<size_t>( sectorSize, (size_t) size - out.size() );
                out.insert( out.end(), p, p + take );
                if( out.size() >= size ) break;
            }
        }
        if( out.size() != size ) { err = "short stream"; return false; }
        return true;
    }
};

int main( int argc, char** argv )
{
    setvbuf( stdout, nullptr, _IONBF, 0 );
    const char* path = argc > 1 ? argv[1] : "fixtures/FileHeader-attackz.SchLib";

    RealCFB cfb;
    if( !cfb.load( path ) )
    {
        std::fprintf( stderr, "cfb-load-failed: %s\n", cfb.err.c_str() );
        return 2;
    }
    std::vector<unsigned char> stream;
    if( !cfb.readStream( "FileHeader", stream ) )
    {
        std::fprintf( stderr, "cfb-stream-failed: %s\n", cfb.err.c_str() );
        return 2;
    }
    g_streamBytes.assign( stream.begin(), stream.end() );

    std::printf( "cfb: file=%s sectors=%zu fat=%zu mini_stream=%zu stream=%zu\n",
                 path, cfb.b.size() / 512 - 1, cfb.fat.size(), cfb.miniStream.size(), stream.size() );

    /* Diagnostic first read with the real parser on the extracted bytes. */
    std::unique_ptr<char[]> bytes( new char[stream.size()] );
    std::memcpy( bytes.get(), stream.data(), stream.size() );
    ALTIUM_BINARY_PARSER reader( bytes, stream.size() );
    std::map<wxString, wxString> props = reader.ReadProperties();
    std::printf( "real-reader: bytes=%zu props=%zu parse_error=%d\n",
                 stream.size(), props.size(), (int) reader.HasParsingError() );
    for( const auto& kv : props )
        if( kv.first.s.rfind( "SIZE", 0 ) == 0 )
            std::printf( "real-key: %s=%s\n", kv.first.s.c_str(), kv.second.s.c_str() );

    volatile int* guard = new int[8];
    for( int i = 0; i < 8; ++i ) guard[i] = 0x11111111;

    std::vector<int> fontSizes;
    ALTIUM_COMPOUND_FILE lib;
    SCH_IO_ALTIUM sch;
    try { sch.ParseLibHeader( lib, fontSizes ); }
    catch( ... ) { delete[] guard; std::printf( "THREW\n" ); return 3; }

    std::printf( "rc=0 size=%zu first=%d GUARD7=%08x\n", fontSizes.size(),
                 fontSizes.empty() ? -1 : fontSizes[0], (unsigned) guard[7] );
    delete[] guard;
    return 0;
}