Skip to content

Keep the inflated member alive in GzipReader.zcat - #191

Open
vytautaskubilius wants to merge 1 commit into
ruby:masterfrom
vytautaskubilius:fix-zcat-gc-guard
Open

vytautaskubilius wants to merge 1 commit into
ruby:masterfrom
vytautaskubilius:fix-zcat-gc-guard

Conversation

@vytautaskubilius

Copy link
Copy Markdown

Zlib::GzipReader.zcat copies each inflated member into the result with rb_str_cat(buf, RSTRING_PTR(tmpbuf), RSTRING_LEN(tmpbuf)), but nothing references tmpbuf after its pointer and length are read. Growing buf can trigger a GC, which can then free tmpbuf in the middle of the copy. Depending on what happens to the freed memory, this either crashes in memcpy (via str_buf_cat4), or returns data of the right length that is all NUL bytes or otherwise corrupted.

We ran into this in production after faraday-gzip 3.2.0 switched from GzipReader#read to GzipReader.zcat - a ~23MB gzip HTTP response decompressed into ~31MB of NUL bytes, while GzipReader#read, Zlib::Inflate and Zlib.gunzip returned the correct data for the same bytes in the same process. Something along these lines reproduces it in ruby:3.4.12-slim-trixie (aarch64, zlib 1.3.1), though not on every run:

data = SecureRandom.base64(23_000_000)
Zlib::GzipReader.zcat(StringIO.new(Zlib.gzip(data))) == data
#=> false, or [BUG] Segmentation fault

Running 12 cases like this (1-31MB, random and text payloads, written in one go and with periodic sync flushes) three times, the current code crashed or returned corrupted data in every round, and with this change it didn't once. I couldn't turn it into a deterministic test - I tried EnvUtil.under_gc_stress with a 1MB member and it passes without the fix too, I think because the freed buffer has to be large enough to be unmapped or reused before the bad copy becomes visible.

I reported this to security@ruby-lang.org first, and they're treating it as a regular bug.

🤖 Generated with Claude Code

Zlib::GzipReader.zcat copied each inflated member into the result with rb_str_cat, but nothing referenced the member string after its pointer and length were read, so a GC triggered while growing the result could free it in the middle of the copy. With members of tens of MB this crashed in memcpy, or returned data of the right length that was all NUL bytes or otherwise corrupted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants