libstaroffice 0.0.7: lengths read from the file are added to the stream position before they are compared with the end of the zone. In WebAssembly, where long is 32 bits, a length near 4 GB wraps that sum below the end and passes the check: a Calc multi-record's size table then had libstaroffice push a billion offsets (half a gigabyte) from a 16 KB file. Each check now compares the length with what is left of the zone instead: the Calc multi-record size table and its content offsets (StarObjectSpreadsheet.cxx), a compressed bitmap's coded size (StarBitmap.cxx) and a style's size in the item pool (StarItemPool.cxx). (johnmcm.com, found by fuzzing and review; MPL-2.0 like the files it changes.) --- a/src/lib/StarObjectSpreadsheet.cxx +++ b/src/lib/StarObjectSpreadsheet.cxx @@ -124,6 +124,9 @@ uint16_t id; uint32_t tableLen; *input>>id >> tableLen; + // long is 32 bits in WebAssembly: a length near 4 GB must not wrap below lastPos. + if (tableLen > static_cast(lastPos - input->tell())) + tableLen = static_cast(lastPos - input->tell()) + 1; m_endRecordPos=input->tell()+long(tableLen); if (id!=0x4200 || m_endRecordPos > lastPos) { STOFF_DEBUG_MSG(("StarObjectSpreadsheetInternal::ScMultiRecord::open: oops can not find the size data\n")); @@ -181,7 +184,7 @@ } STOFFInputStreamPtr input=m_zone.input(); if (m_actualRecord >= m_numRecord || m_actualRecord >= uint32_t(m_offsetList.size()) || - input->tell()+long(m_offsetList[size_t(m_actualRecord)])>m_endPos) + input->tell()>m_endPos || m_offsetList[size_t(m_actualRecord)]>static_cast(m_endPos-input->tell())) return false; // ScMultipleReadHeader::StartEntry m_endContentPos=input->tell()+long(m_offsetList[size_t(m_actualRecord)]); --- a/src/lib/StarBitmap.cxx +++ b/src/lib/StarBitmap.cxx @@ -267,7 +267,7 @@ f << "size[coded]=" << codeSize << ","; f << "size[uncoded]=" << uncodeSize << ","; if (bitmap.m_compression) f << "compression=" << bitmap.m_compression << ","; - if (input->tell()+long(codeSize)>lastPos || uncodeSize==0 || uncodeSize>10000000) { + if (input->tell()>lastPos || codeSize>static_cast(lastPos-input->tell()) || uncodeSize==0 || uncodeSize>10000000) { STOFF_DEBUG_MSG(("StarBitmap::readBitmap: bad code size\n")); f << "###codeSize=" << codeSize << ","; ascFile.addPos(pos); --- a/src/lib/StarItemPool.cxx +++ b/src/lib/StarItemPool.cxx @@ -1946,7 +1946,7 @@ uint32_t nSize; *input>>nVer>>nSize; if (nVer) f << "version=" << nVer << ","; - if (input->tell()+long(nSize)>lastPos) { + if (input->tell()>lastPos || nSize>static_cast(lastPos-input->tell())) { STOFF_DEBUG_MSG(("StarItemPool::readStyles: something is bad\n")); f << "###nSize=" << nSize << ","; ascii.addPos(pos);