Files
Greg Lamberson 42320260a2 feat(fuzz)!: add egfx_zgfx_decompress oracle and harden the ZGFX decoder against attacker-controlled input (#1333)
## Summary

- Implements target 3 of #1316 (egfx fuzz-coverage umbrella):
`egfx_zgfx_decompress` oracle and target.
- Target shape mirrors PR #1285's `bulk_*` pattern: panic plus sanitizer
oracle on `Decompressor::decompress`, fresh decompressor per iteration
so history state does not leak between fuzz inputs.
- Ships alongside a complete input-validation audit of the ZGFX decoder,
following PR #1271's precedent for "target plus the bugs it surfaces in
one PR."

## Hardening

Eight input-validation gaps closed in `ironrdp-graphics` (all class-(c)
per #1314: reachable via attacker-controlled wire inputs). Each one was
surfaced by a rigorous smoke-fuzz iteration:

1. `Bits::try_split_to` (new in `utils.rs`) provides the checked
counterpart to `split_to` that every fix below builds on.
2. `SegmentedDataPdu::from_buffer` multipart segment-size:
`split_at_checked` plus a defensive `Vec::with_capacity` cap mirroring
PR #1271.
3. `decompress_segment` trailing-unused-bits subtraction: `checked_mul`
+ `checked_sub`.
4. `decompress_segment` token loop: checked prefix indexing + checked
`split_to(8)` for the NullLiteral value.
5. `handle_match`: checked distance-bits split, `checked_add` for
`distance_base + value`, plus `distance > HISTORY_SIZE` bound check.
6. `read_unencoded_bytes`: checked splits for the 15-bit length,
pad-to-boundary, and `length * 8` payload.
7. `read_encoded_bytes`: checked splits + `usize::BITS` bound on
`load_be::<usize>()` + `checked_shl` replacing `pow` + `checked_add` for
`base + value`.
8. `FixedCircularBuffer::read_with_offset`: defense-in-depth `offset >
buffer.len()` bound check below the caller-side guard.

Plus memory-budget enforcement, which a match-copy chain makes
necessary: it can expand a few bytes of input into unbounded output, and
an unbounded run reached a 1.5 GB peak.

9. New `MAX_DECOMPRESSED_PER_SEGMENT = 64 MiB` ceiling on a single
segment's decompressed output, enforced per-token in
`decompress_segment` and threaded through the match-copy paths so it is
checked before any allocation. **This is an implementation resource
limit, not a wire requirement**, and the code says so, but MS-RDPEGFX
3.1.9.1.2 ("RDP 8.0 compressor limits") does supply a number: a
compliant compressor MUST NOT produce any single segment past 65,535
uncompressed bytes. This crate's production compressor path honors that:
`wrapper.rs`'s `wrap_compressed` panics above 65,535, and
`compress_and_wrap_egfx`, the only production caller, falls back to
uncompressed rather than risk exceeding it. The
`compress_high_entropy_round_trips_and_bounds_table` test that an
earlier revision of this PR body cited as evidence real traffic exceeds
65,535 does not show that: it calls `Compressor::compress` directly and
feeds the result straight to `decompress_segment`, bypassing the wrapper
every real sender uses. 64 MiB is still used here, not 65,535, because
this ceiling exists to catch non-conforming or hostile input, not to
police conforming input: a decoder that hard-rejects at exactly the
compressor-side limit has no margin for a peer implementation with a
minor, benign spec deviation. Same footing as the compositor's
total-byte budget in #1460.
10. Multipart running-total check against the declared
`uncompressedSize`, surfacing early detection of segments that
collectively exceed the wire-declared bound. Unlike item 9 this one *is*
spec-grounded: 2.2.5.1 defines `uncompressedSize` as the size of
`segmentArray` once reassembled and decompressed, and 3.1.9.1.2.1 states
it MUST equal the total number of decompressed bytes across all
segments.

The sender side is unchanged and already agreed with the spec:
`ZGFX_SEGMENTED_MAXSIZE = 65535` in `wrapper.rs` splits into multipart
above that, which is exactly the encoder-side behaviour 3.1.9.1.2.1
describes.

Seven new `ZgfxError` variants total with matching Display and
`Error::source` impl entries.

## Breaking change

`ZgfxError` is a public exhaustive enum, so the seven added variants
(`InvalidTrailingBitCount`, `SegmentSizeExceedsBuffer`,
`IncompleteBitStream`, `MatchDistanceOutOfRange`,
`LengthTokenSizeTooLarge`, `SegmentDecompressedSizeExceedsLimit`,
`MultipartTotalExceedsDeclared`) break exhaustive matches downstream.
Confirmed by `cargo semver-checks --baseline-rev <merge-base>`: seven
`enum_variant_added` failures on `ironrdp-graphics`. Title carries `!`
accordingly.

## Validation

- `cargo xtask check fmt/lints/tests/typos/locks` all pass.
- `check_egfx_zgfx_decompress` regression-replay passes against both
shipped crash artifacts.
- 46 existing ZGFX unit tests continue to pass against the hardened
code.
- Final 15-minute rigorous fuzz: 2,942,961 iterations in 901 seconds
(~3,266 exec/s sustained), peak RSS 84 MB, zero panics, zero sanitizer
reports, zero OOMs.

Iterative audit progression on a 15-minute libFuzzer + ASan budget per
round:
- Round 1 (no fixes): crash at iter ~30 (trailing-bit underflow)
- Round 2 (after fixes 1-2): crash at iter ~28 (bit-budget)
- Round 3 (after F1-F8 audit): OOM at iter ~9877 (1.5 GB peak)
- Round 4 (after F1-F10 complete): clean

## Notes

- Crash artifacts for the two header-parse bugs added to
`crates/ironrdp-testsuite-core/test_data/fuzz_regression/egfx_zgfx_decompress/`.
The later-round crashes are not added as separate regression entries
because the libFuzzer corpus accumulated 161 representative inputs and
the unit-tested error paths cover the cases directly.
- The MS-RDPEGFX 3.1.9.1.2 ("RDP 8.0 compressor limits") per-segment
bound is a semantic change: inputs that previously decoded to more than
65,535 bytes per segment now return `Err`. Such inputs were never
spec-conformant. Codebase precedent (PR #1097 et seq.) is to add
`ZgfxError` variants without a `!` marker on the commit; following that
convention.
- Memory-budget design discussion lives on #1120
(`issuecomment-4558356535`) rather than in this PR body so future
readers find the rationale on the canonical fuzz-umbrella thread.

Refs #1316.

## Note on the fuzz numbers above

The iteration counts and the 84 MB peak RSS were measured while the
per-segment cap was 65,535. Raising it to 64 MiB does not change what
the oracle exercises, but those figures describe the earlier revision
rather than what ships here.


## Rebase 2026-08-19

Rebased onto current master (was CONFLICTING after the RDPEUDP/RDPEMT
series landed). Two conflicts, both purely additive insertions colliding
with unrelated new master content at the same point:

- `fuzz/Cargo.toml`: master's 8 new RDPEUDP/RDPEMT `[[bin]]` entries
plus this PR's own `egfx_zgfx_decompress` entry, both kept.
- `crates/ironrdp-fuzzing/src/oracles/mod.rs`: master's 8 new oracle
functions plus this PR's own, both appended. The automatic merge dropped
this PR's own closing brace for `egfx_zgfx_decompress`, attaching the
shared trailing syntax to master's last function instead of both (the
same failure mode hit #1337's rebase the other way around, master's
brace dropped there). Caught before continuing the rebase this time by
diffing the resolved file against both source commits directly; fixed
and re-verified byte-identical to both.

None of the ZGFX hardening code (`utils.rs`, `zgfx/circular_buffer.rs`,
`zgfx/control_messages.rs`, `zgfx/mod.rs`) had any conflict; it applied
unchanged. All checks re-run on the new head: `cargo xtask check
fmt/lints/tests/typos/locks`, a direct `cargo check --all-targets` in
`fuzz/`, and `cargo xtask wasm check`, all green. `fuzz/Cargo.lock`
unchanged.


## Review round 2026-08-20

Four findings addressed, three of them posted as review-body text rather
than inline threads and never actually worked despite the PR reading as
fully resolved. (1) `ZgfxError` marked `#[non_exhaustive]`, matching the
same convention already on `DecodeErrorKind`/`EncodeErrorKind` in
ironrdp-core; this PR adds several new variants and every downstream
exhaustive match would have broken without it. (2) Corrected the doc
comment on `MAX_DECOMPRESSED_PER_SEGMENT`: MS-RDPEGFX 3.1.9.1.2's
compressor-limits list does supply a bound (65,535 uncompressed bytes
per segment for a compliant compressor), and this crate's own compressor
honors it (`wrapper.rs` panics above it, the only production caller
falls back to uncompressed instead of risking it). (3) Closed a real
gap: the multipart aggregate memory budget was only checked against the
sender's own declared `uncompressedSize`, a fully attacker-controlled
32-bit field, so a message built from small segments could drive real
allocation to roughly 4.29 GiB before that check fired. Added
`MAX_DECOMPRESSED_TOTAL` (256 MiB, same footing as
`MAX_COMPOSITOR_BYTES` in ironrdp-egfx's compositor.rs), checked
independently. (4) Masked the trailer byte to its low 3 bits per
MS-RDPEGFX 3.1.9.1.2.4 ("the five high-order bits... are reserved");
reading the whole byte let a sender's nonzero reserved bits get misread
as part of the unused-bit count. Both (3) and (4) ship with regression
tests negative-verified against the code without the fix. All 6 gates
green throughout.



## Rebase 2026-08-20

Rebased onto current master, 9 behind to 0. Two conflicts, both pure
unions with master's own new fuzz-target entries in `fuzz/Cargo.toml`
and `fuzz_regression.rs`, same shape as the earlier rebase round.
`oracles/mod.rs` auto-merged without conflict markers this time;
explicitly re-checked it did not repeat the closing-brace-drop failure
from that earlier round (the function's own closing brace confirmed
present, then a full `cargo check -p ironrdp-fuzzing --all-targets` run
clean). All 6 gates green, fuzz workspace lock stable.
2026-08-28 20:13:40 -04:00
..

IronRDP fuzzing

Difference between fuzzing and property testing

ironrdp correctness is validated in various ways. Two of these are fuzzing and property testing. Both of these methods involve feeding random inputs to the API in order to check if the program is behaving as expected or not.

However,

  • Fuzzing is well suited for black-box-like testing. Inputs are typically guided by instrumentalizing the code (coverage…) rather than manually informed.

  • Property testing requires the developer to describe the interesting inputs and properties to test.

  • When fuzzing, some properties are tested as well, but those are typically simple (absence of crash, round-trip…).

  • In contrast, property testing is well suited when testing more complex properties.

  • With fuzzing, we are actively trying to show that something is (unexpectedly) broken.

  • With property testing, we are actively trying to show that the properties are holding (as expected).

Targets

pdu_decoding

Feeds random inputs to PDU decoding code.

bitmap_stream

Feeds random inputs to the RDP6 bitmap decoder.

rle_decompression

Feeds random inputs to the interleaved Run-Length Encoding (RLE) bitmap decoder.

bulk_mppc

Feeds random inputs to the MPPC bulk decompressor (ironrdp-bulk). The first input byte selects between RDP4 mode (low bit clear, 8 KB history) and RDP5 mode (low bit set, 64 KB history); remaining bytes are the compressed payload.

bulk_ncrush

Feeds random inputs to the NCRUSH bulk decompressor (RDP6.0, ironrdp-bulk).

bulk_xcrush

Feeds random inputs to the XCRUSH bulk decompressor (RDP6.1, ironrdp-bulk). XCRUSH has the largest sliding-window history of the bulk family (2 MB).

bulk_round_trip

Compresses arbitrary input via BulkCompressor::compress, then decompresses the result via BulkCompressor::decompress, and asserts byte-equality with the original input. First input byte selects the algorithm (RDP4 / RDP5 / RDP6 / RDP6.1). Catches asymmetric bugs where the compressor produces output the decompressor cannot consume, or the decompressor produces output that does not equal the original input.

Building crates with the arbitrary feature

Several crates expose an optional arbitrary feature that enables arbitrary::Arbitrary implementations on their PDU types. This is the foundation for structure-aware fuzzing harnesses that generate valid-looking inputs rather than raw bytes.

To verify the feature compiles cleanly for a single crate:

cargo check -p ironrdp-pdu --features arbitrary

The feature is also compatible with the no_std + alloc build path:

cargo check -p ironrdp-pdu --no-default-features --features arbitrary,alloc

A handful of PDU types do not implement Arbitrary. They fall into two categories:

  • Types with non-derivable fields (e.g., StaticChannelSet keyed by TypeId). These are either skipped via #[arbitrary(default)] on the containing struct's field, or hand-rolled with a placeholder.
  • Error types that are not part of the wire-protocol surface (e.g., ServerLicenseError). Most error enums fall here: they are constructed locally rather than decoded from the wire, so the fuzzer has no reason to generate them. The exception is wire-protocol error PDUs such as DisconnectProviderUltimatum in mcs.rs, which do implement Arbitrary because they are decoded from the wire.

Inline source comments mark each skip with the rationale.