Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions filesystem/squashfs/common_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@ func (c *testCompressorAddBytes) compress(b []byte) ([]byte, error) {
}
return b[:len(b)-len(c.b)], nil
}
func (c *testCompressorAddBytes) decompress(b []byte) ([]byte, error) {
func (c *testCompressorAddBytes) decompress(b []byte, maxSize int) ([]byte, error) {
if c.err != nil {
return nil, c.err
}
return append(b, c.b...), nil
out := make([]byte, 0, len(b)+len(c.b))
out = append(out, b...)
out = append(out, c.b...)
if len(out) > maxSize {
return nil, ErrDecompressedTooLarge
}
return out, nil
}

//nolint:unused,revive // it is important to implement the interface
Expand Down
87 changes: 52 additions & 35 deletions filesystem/squashfs/compressor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"compress/zlib"
"encoding/binary"
"errors"
"fmt"
"io"

Expand All @@ -14,10 +15,13 @@ import (
"github.com/ulikunitz/xz/lzma"
)

// ErrDecompressedTooLarge is returned when a block decompresses to more bytes than its kind allows.
var ErrDecompressedTooLarge = errors.New("decompressed block larger than allowed")

// Compressor defines a compressor. Fulfilled by various implementations in this package
type Compressor interface {
compress([]byte) ([]byte, error)
decompress([]byte) ([]byte, error)
decompress([]byte, int) ([]byte, error)
loadOptions([]byte) error
optionsBytes() []byte
flavour() compression
Expand All @@ -41,17 +45,13 @@ func (c *CompressorLzma) compress(in []byte) ([]byte, error) {
}
return b.Bytes(), nil
}
func (c *CompressorLzma) decompress(in []byte) ([]byte, error) {
func (c *CompressorLzma) decompress(in []byte, maxSize int) ([]byte, error) {
b := bytes.NewReader(in)
lz, err := lzma.NewReader(b)
if err != nil {
return nil, fmt.Errorf("error creating lzma decompressor: %v", err)
}
p, err := io.ReadAll(lz)
if err != nil {
return nil, fmt.Errorf("error decompressing: %v", err)
}
return p, nil
return readAllLimited(lz, maxSize)
}

//nolint:unused,revive // it is important to implement the interface
Expand Down Expand Up @@ -101,15 +101,15 @@ func (c *CompressorGzip) compress(in []byte) ([]byte, error) {
}
return b.Bytes(), nil
}
func (c *CompressorGzip) decompress(in []byte) ([]byte, error) {
func (c *CompressorGzip) decompress(in []byte, maxSize int) ([]byte, error) {
b := bytes.NewReader(in)
gz, err := zlib.NewReader(b)
if err != nil {
return nil, fmt.Errorf("error creating gzip decompressor: %v", err)
}
p, err := io.ReadAll(gz)
p, err := readAllLimited(gz, maxSize)
if err != nil {
return nil, fmt.Errorf("error decompressing: %v", err)
return nil, err
}
if err := gz.Close(); err != nil {
return nil, err
Expand Down Expand Up @@ -187,17 +187,13 @@ func (c *CompressorXz) compress(in []byte) ([]byte, error) {
}
return b.Bytes(), nil
}
func (c *CompressorXz) decompress(in []byte) ([]byte, error) {
func (c *CompressorXz) decompress(in []byte, maxSize int) ([]byte, error) {
b := bytes.NewReader(in)
xzReader, err := xz.NewReader(b)
if err != nil {
return nil, fmt.Errorf("error creating xz decompressor: %v", err)
}
p, err := io.ReadAll(xzReader)
if err != nil {
return nil, fmt.Errorf("error decompressing: %v", err)
}
return p, nil
return readAllLimited(xzReader, maxSize)
}
func (c *CompressorXz) loadOptions(b []byte) error {
expected := 8
Expand Down Expand Up @@ -258,14 +254,10 @@ func (c *CompressorLz4) compress(in []byte) ([]byte, error) {
}
return b.Bytes(), nil
}
func (c *CompressorLz4) decompress(in []byte) ([]byte, error) {
func (c *CompressorLz4) decompress(in []byte, maxSize int) ([]byte, error) {
b := bytes.NewReader(in)
lz := lz4.NewReader(b)
p, err := io.ReadAll(lz)
if err != nil {
return nil, fmt.Errorf("error decompressing: %v", err)
}
return p, nil
return readAllLimited(lz, maxSize)
}
func (c *CompressorLz4) loadOptions(b []byte) error {
expected := 8
Expand Down Expand Up @@ -308,6 +300,8 @@ type CompressorZstd struct {
// Level is the zstd level, 1 to 22. 0 keeps the encoder's default,
// which corresponds to level 3.
Level uint32
// maxMemory is the decoder history a frame may ask for, zstdMaxMemory if 0, see WithZstdMaxMemory
maxMemory uint64
}

const (
Expand Down Expand Up @@ -359,17 +353,26 @@ func (c *CompressorZstd) compress(in []byte) ([]byte, error) {
}
return b.Bytes(), nil
}
func (c *CompressorZstd) decompress(in []byte) ([]byte, error) {
z, err := zstd.NewReader(nil)

// zstdMaxMemory is the default of the decoder history a frame may ask for, by its window or as a single segment, see
// WithZstdMaxMemory. RFC 8878 leaves that limit to the decoder, recommending support for windows up to 8 MiB
// (https://www.rfc-editor.org/rfc/rfc8878#section-3.1.1.1.2). A block is at most 1 MiB, so no frame needs more history
// than that: mksquashfs, compressing each block with its size known, declares at most the block, and the
// klauspost/compress encoder of CompressorZstd.compress declares its default window, 8 MiB.
// The output is bounded by readAllLimited, to the size of the block.
const zstdMaxMemory = 8 << 20

func (c *CompressorZstd) decompress(in []byte, maxSize int) ([]byte, error) {
maxMemory := c.maxMemory
if maxMemory == 0 {
maxMemory = zstdMaxMemory
}
z, err := zstd.NewReader(bytes.NewReader(in), zstd.WithDecoderMaxMemory(maxMemory))
if err != nil {
return nil, fmt.Errorf("failed to create zstd decompressor: %w", err)
}
defer z.Close()
p, err := z.DecodeAll(in, nil)
if err != nil {
return nil, fmt.Errorf("error decompressing zstd: %w", err)
}
return p, nil
return readAllLimited(z, maxSize)
}

type CompressorLzo struct {
Expand All @@ -378,14 +381,16 @@ type CompressorLzo struct {
func (c *CompressorLzo) compress(_ []byte) ([]byte, error) {
return nil, fmt.Errorf("LZO compression not yet supported")
}
func (c *CompressorLzo) decompress(in []byte) ([]byte, error) {
b := bytes.NewReader(in)
lz := lzo.NewReader(b)
p, err := io.ReadAll(lz)
func (c *CompressorLzo) decompress(in []byte, maxSize int) ([]byte, error) {
out := make([]byte, maxSize)
n, err := lzo.Decompress(in, out)
if errors.Is(err, lzo.ErrOutputOverrun) {
return nil, fmt.Errorf("%w: more than %d bytes", ErrDecompressedTooLarge, maxSize)
}
if err != nil {
return nil, fmt.Errorf("error decompressing: %v", err)
return nil, fmt.Errorf("error decompressing: %w", err)
}
return p, nil
return out[:n], nil
}

//nolint:unused,revive // it is important to implement the interface
Expand All @@ -400,6 +405,18 @@ func (c *CompressorLzo) flavour() compression {
return compressionLzo
}

// readAllLimited reads r to the end, failing with ErrDecompressedTooLarge as soon as it produces more than maxSize bytes.
func readAllLimited(r io.Reader, maxSize int) ([]byte, error) {
p, err := io.ReadAll(io.LimitReader(r, int64(maxSize)+1))
if err != nil {
return nil, fmt.Errorf("error decompressing: %w", err)
}
if len(p) > maxSize {
return nil, fmt.Errorf("%w: more than %d bytes", ErrDecompressedTooLarge, maxSize)
}
return p, nil
}

func newCompressor(flavour compression) (Compressor, error) {
var c Compressor
switch flavour {
Expand Down
102 changes: 99 additions & 3 deletions filesystem/squashfs/compressor_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ package squashfs

import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"reflect"
"strings"
"testing"

"github.com/klauspost/compress/zstd"
)

func TestNewCompressor(t *testing.T) {
Expand Down Expand Up @@ -62,7 +66,7 @@ func testCompressAndDecompress(t *testing.T, c Compressor, compressed []byte) {
//nolint:thelper // this is not a helper function
func testDecompress(t *testing.T, c Compressor, compressed []byte, errorStr string) {
t.Run("decompress", func(t *testing.T) {
out, err := c.decompress(compressed)
out, err := c.decompress(compressed, int(maxBlocksize))
switch {
case errorStr != "" && err == nil:
t.Errorf("expected error %q, got nil", errorStr)
Expand Down Expand Up @@ -103,7 +107,7 @@ func testCompress(t *testing.T, c Compressor, errorStr string) {
}
return
}
decompressed, err := c.decompress(out)
decompressed, err := c.decompress(out, int(maxBlocksize))
switch {
case err != nil:
t.Errorf("unexpected error: %v", err)
Expand Down Expand Up @@ -244,8 +248,100 @@ func TestCompressorZstdLevel(t *testing.T) {
if bytes.Equal(fast, best) {
t.Errorf("levels 1 and 19 compressed to the same bytes")
}
out, err := (&CompressorZstd{}).decompress(best)
out, err := (&CompressorZstd{}).decompress(best, int(maxBlocksize))
if err != nil || !bytes.Equal(out, in) {
t.Errorf("round trip failed: %v", err)
}
}

// TestDecompressLimit checks that no decompressor produces more than the size it is given: a small block of zeros
// expands to more than a block, and must fail as soon as it does instead of being decoded to the end.
func TestDecompressLimit(t *testing.T) {
const maxSize = int(maxBlocksize)
bomb := make([]byte, 64*maxSize)

for _, c := range []Compressor{
&CompressorGzip{CompressionLevel: 9},
&CompressorLzma{},
&CompressorXz{},
&CompressorLz4{},
&CompressorZstd{},
} {
t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
compressed, err := c.compress(bomb)
if err != nil {
t.Fatal(err)
}

if _, err := c.decompress(compressed, maxSize); !errors.Is(err, ErrDecompressedTooLarge) {
t.Errorf("%d bytes decompressing to %d: expected %v, got %v", len(compressed), len(bomb), ErrDecompressedTooLarge, err)
}

// exactly the limit is allowed
exact, err := c.compress(bomb[:maxSize])
if err != nil {
t.Fatal(err)
}
out, err := c.decompress(exact, maxSize)
if err != nil || len(out) != maxSize {
t.Errorf("block of exactly %d bytes: got %d bytes, %v", maxSize, len(out), err)
}
})
}

// LZO cannot compress: the fixture of TestCompressionLzo, one byte short of room
t.Run("*squashfs.CompressorLzo", func(t *testing.T) {
compressed := []byte{
0x75, 0xde, 0xc9, 0x4e, 0xd0, 0xef, 0x19, 0xdb, 0x0a, 0x6a, 0x35, 0x26,
0x61, 0x86, 0x2d, 0xa0, 0x42, 0x18, 0xa8, 0x89, 0xe9, 0xc4, 0x7b, 0x1a,
0xc7, 0x85, 0x8e, 0xd6, 0x36, 0xd6, 0x83, 0x84, 0x21, 0xf4, 0x06, 0x38,
0x07, 0x7b, 0x33, 0x3f, 0x72, 0x4c, 0xae, 0xcd, 0xfd, 0xa0, 0xb0, 0x71,
0x2f, 0x64, 0x62, 0x62, 0x2f, 0xc3, 0x5f, 0xa1, 0x21, 0xc6, 0xbf, 0x2c,
0x39, 0xef, 0x56, 0x23, 0x61, 0xb0, 0x98, 0x84, 0xcd, 0x24, 0xc4, 0xbf,
0x30, 0xae, 0xd9, 0x9e, 0xb0, 0x7b, 0xc5, 0xa3, 0x8d, 0xf7, 0x4f, 0xb8,
0xdd, 0x7b, 0x77, 0xb6, 0x8c, 0x5a, 0x10, 0xa4, 0xce, 0xc2, 0x0a, 0x3d,
0x51, 0x23, 0x8c, 0x10, 0x1a, 0x11, 0x00, 0x00,
}
c := &CompressorLzo{}
if _, err := c.decompress(compressed, len(testCompressUncompressed)-1); !errors.Is(err, ErrDecompressedTooLarge) {
t.Errorf("expected %v, got %v", ErrDecompressedTooLarge, err)
}
if out, err := c.decompress(compressed, len(testCompressUncompressed)); err != nil || !bytes.Equal(out, testCompressUncompressed) {
t.Errorf("block of exactly the limit: %v", err)
}
})
}

func TestDecompressZstdMaxMemory(t *testing.T) {
const asked = 10 << 20 // 10 MiB, above the default
magic := []byte{0x28, 0xb5, 0x2f, 0xfd}
lastRawBlock := []byte{0x09, 0x00, 0x00, 'x'} // last block, raw, 1 byte

// https://www.rfc-editor.org/rfc/rfc8878#name-frame-header
// window descriptor: 2^(10+13) + 2 * 2^(10+13)/8 = 10 MiB
window := append(append(bytes.Clone(magic), 0x00, 13<<3|2), lastRawBlock...)
// single segment, 8-byte frame content size, no window descriptor
singleSegment := append(append(bytes.Clone(magic), 0xe0), binary.LittleEndian.AppendUint64(nil, asked)...)
singleSegment = append(singleSegment, lastRawBlock...)

for name, tc := range map[string]struct {
frame []byte
err error
}{
"window": {window, zstd.ErrWindowSizeExceeded},
"single segment": {singleSegment, zstd.ErrDecoderSizeExceeded},
} {
t.Run(name, func(t *testing.T) {
if _, err := (&CompressorZstd{}).decompress(tc.frame, int(maxBlocksize)); !errors.Is(err, tc.err) {
t.Errorf("default limit, frame asking for %d bytes: expected %v, got %v", asked, tc.err, err)
}

// a larger limit reads the header: the frame then decodes, or fails on its 1 byte of content
c := &CompressorZstd{}
ReadOptions{ZstdMaxMemory: 16 << 20}.apply(c)
if _, err := c.decompress(tc.frame, int(maxBlocksize)); errors.Is(err, zstd.ErrWindowSizeExceeded) || errors.Is(err, zstd.ErrDecoderSizeExceeded) {
t.Errorf("16 MiB limit, frame asking for %d bytes: got %v", asked, err)
}
})
}
}
8 changes: 4 additions & 4 deletions filesystem/squashfs/metadatablock.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ func parseMetadata(b []byte, c Compressor) (block *metadatablock, err error) {
}
data := b[2 : 2+size]
if compressed {
data, err = c.decompress(data)
data, err = c.decompress(data, int(metadataBlockSize))
if err != nil {
return nil, fmt.Errorf("decompress error: %v", err)
return nil, fmt.Errorf("decompress error: %w", err)
}
}
return &metadatablock{
Expand Down Expand Up @@ -94,9 +94,9 @@ func (fs *FileSystem) readMetaBlock(r io.ReaderAt, c Compressor, location int64)
if c == nil {
return nil, 0, fmt.Errorf("metadata block at %d compressed, but no compressor provided", location)
}
data, err = c.decompress(b)
data, err = c.decompress(b, int(metadataBlockSize))
if err != nil {
return nil, 0, fmt.Errorf("decompress error: %v", err)
return nil, 0, fmt.Errorf("decompress error: %w", err)
}
}
return data, size + 2, nil
Expand Down
17 changes: 17 additions & 0 deletions filesystem/squashfs/metadatablock_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package squashfs

import (
"bytes"
"errors"
"fmt"
"strings"
"testing"
Expand Down Expand Up @@ -139,3 +140,19 @@ func TestReadMetaBlock(t *testing.T) {
}
}
}

// TestReadMetaBlockLimit checks that a metadata block may decompress to at most 8 KiB.
func TestReadMetaBlockLimit(t *testing.T) {
b := []byte{0x5, 0x00, 1, 2, 3, 4, 5}
// 5 bytes in, metadataBlockSize - 5 added: exactly the limit, then one byte over it
exact := &testCompressorAddBytes{b: make([]byte, metadataBlockSize-5)}
over := &testCompressorAddBytes{b: make([]byte, metadataBlockSize-4)}

fs := &FileSystem{}
if out, _, err := fs.readMetaBlock(bytes.NewReader(b), exact, 0); err != nil || len(out) != int(metadataBlockSize) {
t.Errorf("exactly %d bytes: got %d bytes, %v", metadataBlockSize, len(out), err)
}
if _, _, err := fs.readMetaBlock(bytes.NewReader(b), over, 0); !errors.Is(err, ErrDecompressedTooLarge) {
t.Errorf("%d bytes: expected %v, got %v", metadataBlockSize+1, ErrDecompressedTooLarge, err)
}
}
Loading
Loading