diff --git a/filesystem/squashfs/common_internal_test.go b/filesystem/squashfs/common_internal_test.go index 9c4ce8a7..6ebf4534 100644 --- a/filesystem/squashfs/common_internal_test.go +++ b/filesystem/squashfs/common_internal_test.go @@ -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 diff --git a/filesystem/squashfs/compressor.go b/filesystem/squashfs/compressor.go index a124b0aa..cfddc5dd 100644 --- a/filesystem/squashfs/compressor.go +++ b/filesystem/squashfs/compressor.go @@ -4,6 +4,7 @@ import ( "bytes" "compress/zlib" "encoding/binary" + "errors" "fmt" "io" @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 ( @@ -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 { @@ -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 @@ -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 { diff --git a/filesystem/squashfs/compressor_internal_test.go b/filesystem/squashfs/compressor_internal_test.go index 0c635c89..3d11e41b 100644 --- a/filesystem/squashfs/compressor_internal_test.go +++ b/filesystem/squashfs/compressor_internal_test.go @@ -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) { @@ -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) @@ -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) @@ -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) + } + }) + } +} diff --git a/filesystem/squashfs/metadatablock.go b/filesystem/squashfs/metadatablock.go index 0436aa72..9ac03e98 100644 --- a/filesystem/squashfs/metadatablock.go +++ b/filesystem/squashfs/metadatablock.go @@ -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{ @@ -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 diff --git a/filesystem/squashfs/metadatablock_internal_test.go b/filesystem/squashfs/metadatablock_internal_test.go index 72bc67b8..cb597914 100644 --- a/filesystem/squashfs/metadatablock_internal_test.go +++ b/filesystem/squashfs/metadatablock_internal_test.go @@ -2,6 +2,7 @@ package squashfs import ( "bytes" + "errors" "fmt" "strings" "testing" @@ -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) + } +} diff --git a/filesystem/squashfs/squashfs.go b/filesystem/squashfs/squashfs.go index 3aa05bb3..c904dacd 100644 --- a/filesystem/squashfs/squashfs.go +++ b/filesystem/squashfs/squashfs.go @@ -156,6 +156,39 @@ func Create(b backend.Storage, size, start, blocksize int64) (*FileSystem, error // // rclone -P --transfers 16 --checkers 16 copy :archive:/path/to/tensorflow.sqfs /tmp/tensorflow func Read(b backend.Storage, size, start, blocksize int64) (*FileSystem, error) { + return ReadWithOptions(b, size, start, blocksize) +} + +type ReadOption func(*ReadOptions) + +type ReadOptions struct { + // ZstdMaxMemory is the decoder history a zstd frame may ask for. + ZstdMaxMemory uint64 +} + +// WithZstdMaxMemory sets the decoder history, in bytes, a zstd frame may ask for, by its window or as a single +// segment. A frame asking for more fails to decompress. The default, 8 MiB, reads the images of mksquashfs and of this +// package; a larger one reads frames compressed with a larger window, as zstd --long or --ultra may write, at the cost +// of as much memory per decompression. 0 keeps the default. +func WithZstdMaxMemory(n uint64) ReadOption { + return func(o *ReadOptions) { + o.ZstdMaxMemory = n + } +} + +func (o ReadOptions) apply(c Compressor) { + if z, ok := c.(*CompressorZstd); ok { + z.maxMemory = o.ZstdMaxMemory + } +} + +// ReadWithOptions reads a filesystem from a given disk, like Read, with the given options applied. +func ReadWithOptions(b backend.Storage, size, start, blocksize int64, opts ...ReadOption) (*FileSystem, error) { + var o ReadOptions + for _, opt := range opts { + opt(&o) + } + var ( read int err error @@ -196,12 +229,16 @@ func Read(b backend.Storage, size, start, blocksize int64) (*FileSystem, error) if err != nil { return nil, fmt.Errorf("error parsing superblock: %v", err) } + if err := validateBlocksize(int64(s.blocksize)); err != nil { + return nil, fmt.Errorf("invalid superblock: %w", err) + } // create the compressor function we will use compress, err := newCompressor(s.compression) if err != nil { return nil, fmt.Errorf("unable to create compressor: %v", err) } + o.apply(compress) // load fragments fragments, err := readFragmentTable(s, b, compress) @@ -739,9 +776,9 @@ func (fs *FileSystem) readBlock(location int64, compressed bool, size uint32) ([ return nil, fmt.Errorf("read %d bytes instead of expected %d", read, size) } if compressed { - b, err = fs.compressor.decompress(b) + b, err = fs.compressor.decompress(b, int(fs.blocksize)) if err != nil { - return nil, fmt.Errorf("decompress error: %v", err) + return nil, fmt.Errorf("decompress error: %w", err) } } return b, nil @@ -756,6 +793,9 @@ func (fs *FileSystem) readFragment(index, offset uint32, fragmentSize int64) ([] return nil, fmt.Errorf("cannot find fragment block with index %d", index) } fragmentInfo := fs.fragments[index] + if int64(fragmentInfo.size) > fs.blocksize { + return nil, fmt.Errorf("fragment block %d is %d bytes, more than the block size %d", index, fragmentInfo.size, fs.blocksize) + } pos := int64(fragmentInfo.start) data, _, err := fs.cache.get(pos, func() (data []byte, size uint16, err error) { // figure out the size of the compressed block and if it is compressed @@ -773,9 +813,9 @@ func (fs *FileSystem) readFragment(index, offset uint32, fragmentSize int64) ([] if fs.compressor == nil { return nil, 0, fmt.Errorf("fragment compressed but do not have valid compressor") } - data, err = fs.compressor.decompress(b) + data, err = fs.compressor.decompress(b, int(fs.blocksize)) if err != nil { - return nil, 0, fmt.Errorf("decompress error: %v", err) + return nil, 0, fmt.Errorf("decompress error: %w", err) } } return data, 0, nil @@ -783,6 +823,9 @@ func (fs *FileSystem) readFragment(index, offset uint32, fragmentSize int64) ([] if err != nil { return nil, err } + if fragmentSize < 0 || int64(offset)+fragmentSize > int64(len(data)) { + return nil, fmt.Errorf("fragment of %d bytes at offset %d is outside fragment block %d of %d bytes", fragmentSize, offset, index, len(data)) + } // now get the data from the offset return data[offset : int64(offset)+fragmentSize], nil } diff --git a/filesystem/squashfs/squashfs_internal_test.go b/filesystem/squashfs/squashfs_internal_test.go index 8d202751..c7a153dc 100644 --- a/filesystem/squashfs/squashfs_internal_test.go +++ b/filesystem/squashfs/squashfs_internal_test.go @@ -3,9 +3,11 @@ package squashfs import ( "bytes" "encoding/binary" + "errors" "fmt" "io" "math" + "os" "strings" "testing" @@ -277,6 +279,7 @@ func TestReadBlock(t *testing.T) { fs := &FileSystem{ backend: file.New(testFile, true), compressor: tt.compressor, + blocksize: minBlocksize, } b, err := fs.readBlock(tt.location, tt.compressed, size) switch { @@ -326,14 +329,19 @@ func TestReadFragment(t *testing.T) { {2, 2, 5, nil, nil, fmt.Errorf("fragment compressed but do not have valid compressor")}, {2, 2, 9, &testCompressorAddBytes{b: []byte{0x40}}, append(data[32:40], 0x40), nil}, {2, 2, 5, &testCompressorAddBytes{err: fmt.Errorf("foo")}, nil, fmt.Errorf("decompress error: foo")}, - {3, 2, 5, nil, nil, fmt.Errorf("cannot find fragment block with index %d", 3)}, + {4, 2, 5, nil, nil, fmt.Errorf("cannot find fragment block with index %d", 4)}, + {1, 8, 5, nil, nil, fmt.Errorf("fragment of 5 bytes at offset 8 is outside fragment block 1 of 10 bytes")}, + {2, 2, 5, &testCompressorAddBytes{b: make([]byte, minBlocksize)}, nil, fmt.Errorf("decompress error: %w", ErrDecompressedTooLarge)}, + {3, 0, 5, nil, nil, fmt.Errorf("fragment block 3 is %d bytes, more than the block size %d", minBlocksize+1, minBlocksize)}, } for i, tt := range tests { fs := &FileSystem{ - fragments: fragments, + fragments: append(fragments[:len(fragments):len(fragments)], + &fragmentEntry{start: 0, size: uint32(minBlocksize) + 1, compressed: false}), backend: file.New(testFile, true), compressor: tt.compressor, + blocksize: minBlocksize, } b, err := fs.readFragment(tt.index, tt.offset, tt.size) switch { @@ -341,6 +349,8 @@ func TestReadFragment(t *testing.T) { t.Errorf("%d: mismatched error, actual then expected", i) t.Logf("%v", err) t.Logf("%v", tt.err) + case errors.Unwrap(tt.err) != nil && !errors.Is(err, errors.Unwrap(tt.err)): + t.Errorf("%d: error does not wrap %v: %v", i, errors.Unwrap(tt.err), err) case !bytes.Equal(b, tt.data): t.Errorf("%d: Mismatched data, actual then expected", i) t.Logf("% x", b) @@ -396,3 +406,37 @@ func TestReadUidsGids(t *testing.T) { t.Logf("%#v", expected) } } + +// TestReadInvalidBlocksize checks that Read refuses an image whose superblock declares a block size mksquashfs would +// not: every block, and every sparse block allocation, is bounded by it. +func TestReadInvalidBlocksize(t *testing.T) { + image, err := os.ReadFile(Squashfsfile) + if err != nil { + t.Fatal(err) + } + + for _, blocksize := range []uint32{0, 1 << 11, 1 << 21, 1 << 31} { + // the block log parseSuperblock expects, so that only the block size check can refuse the image: for 0, what + // uint16(-Inf) converts to on this platform + blocklog := uint16(math.Log2(float64(blocksize))) + patched := bytes.Clone(image) + binary.LittleEndian.PutUint32(patched[12:16], blocksize) + binary.LittleEndian.PutUint16(patched[22:24], blocklog) + + t.Run(fmt.Sprintf("blocksize %d", blocksize), func(t *testing.T) { + f, err := os.CreateTemp(t.TempDir(), "image_*.sqs") + if err != nil { + t.Fatal(err) + } + defer f.Close() + if _, err := f.Write(patched); err != nil { + t.Fatal(err) + } + + _, err = Read(file.New(f, true), int64(len(patched)), 0, 0) + if err == nil || !strings.Contains(err.Error(), "invalid superblock") { + t.Errorf("expected an invalid superblock error, got %v", err) + } + }) + } +}