Skip to content

Commit 608d2be

Browse files
nobuhsbt
authored andcommitted
Fix buffer overflow at ungetc
1 parent 5d50b22 commit 608d2be

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

ext/zlib/zlib.c

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -860,9 +860,7 @@ zstream_buffer_ungets(struct zstream *z, const Bytef *b, unsigned long len)
860860
char *bufptr;
861861
long filled;
862862

863-
if (NIL_P(z->buf) || (long)rb_str_capacity(z->buf) <= ZSTREAM_BUF_FILLED(z)) {
864-
zstream_expand_buffer_into(z, len);
865-
}
863+
zstream_expand_buffer_into(z, len);
866864

867865
RSTRING_GETMEM(z->buf, bufptr, filled);
868866
memmove(bufptr + len, bufptr, filled);

test/zlib/test_zlib.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -882,6 +882,25 @@ def test_ungetc_at_start_of_file
882882
assert_equal(-1, r.pos, "[ruby-core:81488][Bug #13616]")
883883
end
884884

885+
def test_ungetc_buffer_underflow
886+
initial_bufsize = 1024
887+
payload = "A" * initial_bufsize
888+
gzip_io = StringIO.new
889+
Zlib::GzipWriter.wrap(gzip_io) { |gz| gz.write(payload) }
890+
compressed = gzip_io.string
891+
892+
reader = Zlib::GzipReader.new(StringIO.new(compressed))
893+
reader.read(1)
894+
overflow_bytes = "B" * (initial_bufsize)
895+
reader.ungetc(overflow_bytes)
896+
data = reader.read(overflow_bytes.bytesize)
897+
assert_equal overflow_bytes.bytesize, data.bytesize, data
898+
assert_empty data.delete("B"), data
899+
data = reader.read()
900+
assert_equal initial_bufsize - 1, data.bytesize, data
901+
assert_empty data.delete("A"), data
902+
end
903+
885904
def test_open
886905
Tempfile.create("test_zlib_gzip_reader_open") {|t|
887906
t.close

0 commit comments

Comments
 (0)