Skip to content

Commit

Permalink
gzip: Error out if reserved bits are set (#891)
Browse files Browse the repository at this point in the history
RFC 1952 states: Reserved FLG bits must be zero.
  • Loading branch information
klauspost authored Nov 28, 2023
1 parent c4e922d commit c63a492
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
5 changes: 5 additions & 0 deletions gzip/gunzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,11 @@ func (z *Reader) readHeader() (hdr Header, err error) {
}
}

// Reserved FLG bits must be zero.
if flg>>5 != 0 {
return hdr, ErrHeader
}

z.digest = 0
if z.decompressor == nil {
z.decompressor = flate.NewReader(z.r)
Expand Down
23 changes: 21 additions & 2 deletions gzip/gunzip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"bytes"
oldgz "compress/gzip"
"crypto/rand"
"errors"
"io"
"os"
"strings"
Expand Down Expand Up @@ -408,11 +409,14 @@ func TestDecompressor(t *testing.T) {
}

func TestIssue6550(t *testing.T) {
f, err := os.Open("testdata/issue6550.gz")
b, err := os.ReadFile("testdata/issue6550.gz")
if err != nil {
t.Fatal(err)
}
gzip, err := NewReader(f)
// issue6550.gz has invalid flag bit set.
// TestReservedBits tests that. Fix it up for this test.
b[3] &= 0x1f
gzip, err := NewReader(bytes.NewReader(b))
if err != nil {
t.Fatalf("NewReader(testdata/issue6550.gz): %v", err)
}
Expand All @@ -435,6 +439,21 @@ func TestIssue6550(t *testing.T) {
}
}

func TestReservedBits(t *testing.T) {
f, err := os.Open("testdata/issue6550.gz")
if err != nil {
t.Fatal(err)
}
defer f.Close()
_, err = NewReader(f)
if err == nil {
t.Fatalf("Reserved bits did not result in error")
}
if !errors.Is(err, ErrHeader) {
t.Fatal("Expected ErrHeader, got", err)
}
}

func TestInitialReset(t *testing.T) {
var r Reader
if err := r.Reset(bytes.NewReader(gunzipTests[1].gzip)); err != nil {
Expand Down

0 comments on commit c63a492

Please sign in to comment.