RAR3 PPMd: read error in input stream escapes a throw() callback and aborts the process

Open
#269 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
54/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
cpp
Domain
backend, security

Research direction

Read CPP/7zip/Compress/Rar3Decoder.cpp around Wrap_ReadByte and Wrap_ReadBits8, then inspect CPP/7zip/Common/InBuffer.cpp around ReadBlock and the existing CWrappers.cpp callback behavior. Reproduce with the supplied archive and password, and check both reported failure paths under ASan. Done means decoding reports a data error without aborting or accessing an invalid buffer.

Written by the indexing model from the issue text.

Description

Summary

7-Zip 26.05 aborts (std::terminate, SIGABRT) when decoding a RAR3 PPMd stream whose
input stream returns a read error. An exception thrown inside CInBuffer escapes through a C
callback declared throw(), so the process is killed instead of reporting a data error.

This is a robustness / DoS issue: a 117-byte archive is enough to abort 7zz, and the same
code path is inside 7z.so, so any program linking the codec (GUI file managers etc.) dies
with it. I have not found a way to turn it into memory corruption on its own, but see
"catch-only fix is not sufficient" below — with the exception merely caught, the decoder
continues into a stale CFilterCoder and ASan reports a heap-buffer-overflow.

Version / environment

  • 7-Zip 26.05, tag 26.05, commit b88c6bc09339de32f7d18bbab900686b244f42ba (current main)
  • built from source: cd CPP/7zip/Bundles/Alone2 && make -f makefile.gcc (unmodified tree)
  • also reproducible with 7z.so from Bundles/Format7zF through IInArchive (see below)
  • Ubuntu 22.04, x86_64, g++ 11.4.0, Linux 5.15

No local patches were applied — the archive below was produced by mutating a valid fixture
(libarchive test_read_format_rar4_solid_encrypted.rar) during fuzzing.

Reproduction

crash.rar (117 bytes, SHA-256 36930593f7ee380997f161aae2fe649857ec61c45d8e7ecb09e155e846159584):

UmFyIRoHADvQcwgADQAAAAAAAAAhYXTElDIAMAAAABIAAAACVW5a7mRXdlgdMwUAIAAAAGEudHh0
AAAAAAAAAAAA8PxMG9xMy2AT2EwAAAI1PZqUbld2WB0A8Pthj36jLA4HgVUnbTncMI4apqbEPZwA
QAcA
$ base64 -d > crash.rar <<'EOF'
...the block above...
EOF
$ sha256sum crash.rar
36930593f7ee380997f161aae2fe649857ec61c45d8e7ecb09e155e846159584  crash.rar

$ ./7zz t -bb0 -pa crash.rar
...
ERRORS:
Unexpected end of archive

terminate called after throwing an instance of 'CInBufferException'
Aborted (core dumped)

$ echo $?
134

x aborts the same way:

$ ./7zz x -y -oout -pa crash.rar    # -> 134

The archive is a single encrypted, solid file a.txt (RAR4 block header, UnPackVersion 29,
method 0x33 = PPMd, salt present); its packed stream is 48 bytes declared but only 47 are
present, so the AES filter fails part-way through the PPMd stream.

Note that the abort depends on the password indirectly: some passwords make the filter fail on
a different path and the run ends cleanly with exit code 2 (-px, -pabc, -ppassword), while
-pa, -pb, -pSecret, -p123456 and an empty password abort. Front ends that link the
codec are affected the same way: driving 7z.so built from Bundles/Format7zF through
IInArchive (the path a GUI file manager uses) aborts with the identical terminate message.

Backtrace (gdb, relinked with -g):

#12 __cxa_throw
#13 CInBufferBase::ReadBlock() [clone .cold]
#14 CInBufferBase::ReadByte_FromNewBlock()
#15 Wrap_ReadByte ()
#16 Ppmd7a_DecodeSymbol ()
#17 NCompress::NRar3::CDecoder::DecodePPM(int, bool&)
#18 NCompress::NRar3::CDecoder::CodeReal(ICompressProgressInfo*)
#19 NCompress::NRar3::CDecoder::Code(...)
#20 NArchive::NRar::CHandler::Extract(...)

Root cause

CPP/7zip/Compress/Rar3Decoder.cpp:41 and :47 — the two callbacks handed to the C PPMd
decoder are declared throw() and do not catch anything:

static Byte Wrap_ReadByte(IByteInPtr pp) throw()
{
  CByteIn *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj);
  return p->BitDecoder.Stream.ReadByte();     // may throw CInBufferException
}

CPP/7zip/Common/InBuffer.cpp:64-69 — ReadBlock() throws whenever the underlying stream
returns an error:

const HRESULT result = _stream->Read(_bufBase, (UInt32)_bufSize, &processed);
...
if (result != S_OK)
  throw CInBufferException(result);

Here the underlying stream is the RAR AES CFilterCoder, which returns S_FALSE from
CFilterCoder::Read (CPP/7zip/Common/FilterCoder.cpp:526, the convSize > bufPos case,
i.e. ciphertext that did not decrypt to a whole block) — an ordinary data error for a wrong
password or a truncated stream. It propagates out of Wrap_ReadByte, crosses the throw()
boundary and calls std::terminate.

NCompress::NRar3::CDecoder::Code (Rar3Decoder.cpp:925) does have a
catch(const CInBufferException &e), but it is too late: the exception never gets there
because it is thrown from inside a noexcept frame.

I traced the failing call: FilterCoder::Read returns S_FALSE with convSize=16,
bufPos=15, processed=0; ReadBlock then throws. 7zz t on the unmodified upstream tree
prints DBG ReadBlock: stream->Read returned 0x00000001 processed=0 wasFinished=0
(S_FALSE == 1).

Everything above was verified against a build of the pristine upstream tag; the same abort also
reproduces through the IInArchive path used by GUI front ends.

Suggested fix

Two parts are needed; either one alone leaves a defect.

1. Do not let the exception cross the C callback. Treat a read error as end of input, so
the existing InputEofError_Fast() (NumExtraBytes > 2) stops DecodePPM with S_FALSE:

static Byte Wrap_ReadByte(IByteInPtr pp) throw()
{
  CByteIn *p = Z7_CONTAINER_FROM_VTBL_CLS(pp, CByteIn, IByteIn_obj);
  try
  {
    return p->BitDecoder.Stream.ReadByte();
  }
  catch(...)
  {
    p->BitDecoder.Stream.NumExtraBytes++;
    return 0xFF;
  }
}

and the same for Wrap_ReadBits8 (wrapping ReadByteFromAligned()).

2. Do not re-enter a stream that already failed. CInBuffer::ReadBlock throws before
setting _wasFinished, so after the exception is caught the decoder keeps calling the
CFilterCoder whose state is no longer valid. Mark the buffer finished first:

if (result != S_OK)
{
  _wasFinished = true;          // later reads see end of stream
  throw CInBufferException(result);
}

Catch-only fix is not sufficient — evidence: with patch 1 alone the abort becomes a
heap-buffer-overflow, ASan reports READ of size 1 at
CFilterCoder.cpp:495 (the buf[i] = buf[convPos + i] compaction loop) with the buffer
allocated in CAlignedMidBuffer::AllocAligned from CFilterCoder::SetOutStreamSize, reached
from Wrap_ReadByte → Ppmd7a_DecodeSymbol → DecodePPM. With both patches applied, the same
archive gives a clean ERROR: Data Error in encrypted file. Wrong password? and exit code 2.

Also worth checking the same shape elsewhere: other throw() callbacks reachable from a
C decoder (e.g. CByteInBufWrap::ReadByteFromNewBlock in CPP/7zip/Common/CWrappers.cpp
swallows errors into Extra = true, which is the behaviour these RAR3 callbacks should have
had).

Not affected

  • Plain (unencrypted) RAR3 PPMd files: no failing stream, no throw.
  • RAR1/RAR2: they use CInBuffer directly without a C callback boundary, and their Code
    catches CInBufferException.

I also re-ran a 19,000-case fuzz campaign over the tree with both patches applied (seeded with
the same input that found this) — no further abort, sanitizer report, or timeout.

Dominant language
C++
Stars
4.6k
Forks
519
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ip7z/7zip

All issues in ip7z/7zip

Similar issues

More C++ issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.