CVE-2024-29902 (Go, published 2024-04-10T23:15Z)
Description: value: Cosign provides code signing and transparency for containers and binaries. Prior to version 2.2.4, a remote image with a malicious attachment can cause denial of service of the host machine running Cosign. This can impact other services on the machine that rely on having memory available such as a Redis database which can result in data loss. It can also impact the availability of other services on the machine that will not be available for the duration of the machine denial. The root cause of this issue is that Cosign reads the attachment from a remote image entirely into memory without checking the size of the attachment first. As such, a large attachment can make Cosign read a large attachment into memory; If the attachments size is larger than the machine has memory available, the machine will be denied of service. The Go runtime will make a SigKill after a few seconds of system-wide denial. This issue can allow a supply-chain escalation from a compromised registry to the Cosign user: If an attacher has compromised a registry or the account of an image vendor, they can include a malicious attachment and hurt the image consumer. Version 2.2.4 contains a patch for the vulnerability.
Severity: nan (CVSS v3 base score: )
Weakness: NVD-CWE-noinfo \u2014 Insufficient Information
There is insufficient information about the issue to classify it; details are unkown or unspecified.
Repository: https://github.com/sigstore/cosign
Files changed:
cmd/cosign/cli/verify/verify_blob_attestation.go
cmd/cosign/cli/verify/verify_blob_attestation_test.go
go.mod
internal/pkg/cosign/payload/size/errors.go
internal/pkg/cosign/payload/size/size.go
internal/pkg/cosign/payload/size/size_test.go
pkg/cosign/env/env.go
pkg/oci/errors.go
pkg/oci/internal/signature/layer.go
pkg/oci/internal/signature/layer_test.go
pkg/oci/layout/signatures.go
pkg/oci/layout/signatures_test.go
pkg/oci/mutate/signatures.go
pkg/oci/mutate/signatures_test.go
pkg/oci/remote/remote.go
pkg/oci/remote/remote_test.go
pkg/oci/remote/signatures.go
pkg/oci/remote/signatures_test.go
pkg/oci/signature/layer.go
pkg/oci/signature/layer_test.go
pkg/oci/static/file.go
pkg/oci/static/file_test.go
Commit message: Fixes for GHSA-88jx-383q-w4qc and GHSA-95pr-fxf5-86gv (#3661)

* Merge pull request from GHSA-95pr-fxf5-86gv

An Image may come from an untrusted source and contain an unknown number
of signatures in the .sig manifest. A common pattern in cosign is to use
the number of signatures as the capacity for a new slice. But this means
the size of the slice is based on an unvalidated external input and
could result in cosign running out of memory.

This change adds validation for certain implementations of the
oci.Signatures Get() method to limit the number of image descriptors
returned. This way, callers can rely on the returned slice of signatures
being a reasonable size to process safely.

The limit is set to 1000, which is a generous size based on the
practical restrictions that container registries set for image manifest
size and approximations of memory allocations for signature layers.

Signed-off-by: Colleen Murphy <colleenmurphy@google.com>

* Merge pull request from GHSA-88jx-383q-w4qc

When downloading an attestation or SBOM from an external source, check
its size before reading it into memory. This protects the host from
potentially reading a maliciously large attachment into memory and
exhausting the system.

SBOMs can vary widely in size, and there could be legitimate SBOMs of up
to 700MB. However, reading a 700MB SBOM into memory would easily bring
down a small cloud VM. Moreover, most SBOMs are not going to be that
large. This change sets a reasonable default of 128MiB, and allows
overriding the default by setting the environment variable
`COSIGN_MAX_ATTACHMENT_SIZE`.

Signed-off-by: Colleen Murphy <colleenmurphy@google.com>

---------

Signed-off-by: Colleen Murphy <colleenmurphy@google.com>


Vulnerable code:
	signatures := make([]oci.Signature, 0, len(manifest.Layers))
	file, err := NewFile([]byte(payload), WithLayerMediaType("foo"), WithAnnotations(map[string]string{"foo": "bar"}))
	layers, err := file.Layers()
		gotMT, err := file.FileMediaType()
		gotPayload, err := file.Payload()
		fileCfg, err := file.ConfigFile()
		m, err := file.Manifest()

Fixed code:
	payloadsize "github.com/sigstore/cosign/v2/internal/pkg/cosign/payload/size"
		fileInfo, err := f.Stat()
		if err != nil {
			return err
		}
		err = payloadsize.CheckSize(uint64(fileInfo.Size()))
		if err != nil {
			return err
		}
	hugeBlobContents                     = "hugepayloadhugepayloadhugepayloadhugepayloadhugepayloadhugepayloadhugepayloadhugepayloadhugepayloadhugepayloadhugepayloadhugepayloadhugepayload"
	hugeBlobPath := writeBlobFile(t, td, hugeBlobContents, "huge-blob")
		env           map[string]string
		}, {
			description: "override file size limit",
			signature:   blobSLSAProvenanceSignature,
			blobPath:    hugeBlobPath,
			env:         map[string]string{"COSIGN_MAX_ATTACHMENT_SIZE": "128"},
			shouldErr:   true,
			for k, v := range test.env {
				t.Setenv(k, v)
			}
	github.com/dustin/go-humanize v1.0.1
// Copyright 2024 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package payload

import "fmt"

// MaxLayerSizeExceeded is an error indicating that the layer is too big to read into memory and cosign should abort processing it.
type MaxLayerSizeExceeded struct {
	value   uint64
	maximum uint64
}

func NewMaxLayerSizeExceeded(value, maximum uint64) *MaxLayerSizeExceeded {
	return &MaxLayerSizeExceeded{value, maximum}
}

func (e *MaxLayerSizeExceeded) Error() string {
	return fmt.Sprintf("size of layer (%d) exceeded the limit (%d)", e.value, e.maximum)
}
// Copyright 2024 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package payload

import (
	"github.com/dustin/go-humanize"
	"github.com/sigstore/cosign/v2/pkg/cosign/env"
)

const defaultMaxSize = uint64(134217728) // 128MiB

func CheckSize(size uint64) error {
	maxSize := defaultMaxSize
	maxSizeOverride, exists := env.LookupEnv(env.VariableMaxAttachmentSize)
	if exists {
		var err error
		maxSize, err = humanize.ParseBytes(maxSizeOverride)
		if err != nil {
			maxSize = defaultMaxSize
		}
	}
	if size > maxSize {
		return NewMaxLayerSizeExceeded(size, maxSize)
	}
	return nil
}
// Copyright 2024 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package payload

import (
	"testing"
)

func TestCheckSize(t *testing.T) {
	tests := []struct {
		name    string
		input   uint64
		setting string
		wantErr bool
	}{
		{
			name:    "size is within default limit",
			input:   1000,
			wantErr: false,
		},
		{
			name:    "size exceeds default limit",
			input:   200000000,
			wantErr: true,
		},
		{
			name:    "size is within overridden limit (bytes)",
			input:   1000,
			setting: "1024",
			wantErr: false,
		},
		{
			name:    "size is exceeds overridden limit (bytes)",
			input:   2000,
			setting: "1024",
			wantErr: true,
		},
		{
			name:    "size is within overridden limit (megabytes, short form)",
			input:   1999999,
			setting: "2M",
			wantErr: false,
		},
		{
			name:    "size exceeds overridden limit (megabytes, short form)",
			input:   2000001,
			setting: "2M",
			wantErr: true,
		},
		{
			name:    "size is within overridden limit (megabytes, long form)",
			input:   1999999,
			setting: "2MB",
			wantErr: false,
		},
		{
			name:    "size exceeds overridden limit (megabytes, long form)",
			input:   2000001,
			setting: "2MB",
			wantErr: true,
		},
		{
			name:    "size is within overridden limit (mebibytes)",
			input:   2097151,
			setting: "2MiB",
			wantErr: false,
		},
		{
			name:    "size exceeds overridden limit (mebibytes)",
			input:   2097153,
			setting: "2MiB",
			wantErr: true,
		},
		{
			name:    "size is negative results in default",
			input:   5121,
			setting: "-5KiB",
			wantErr: false,
		},
		{
			name:    "invalid setting results in default",
			input:   5121,
			setting: "five kilobytes",
			wantErr: false,
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			if test.setting != "" {
				t.Setenv("COSIGN_MAX_ATTACHMENT_SIZE", test.setting)
			}
			got := CheckSize(test.input)
			if (got != nil) != (test.wantErr) {
				t.Errorf("CheckSize() = %v, expected %v", got, test.wantErr)
			}
		})
	}
}
	VariableMaxAttachmentSize       Variable = "COSIGN_MAX_ATTACHMENT_SIZE"
		VariableMaxAttachmentSize: {
			Description: "maximum attachment size to download (default 128MiB)",
			Expects:     "human-readable unit of memory, e.g. 5120, 20K, 3M, 45MiB, 1GB",
			Sensitive:   false,
		},
// Copyright 2024 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package oci

import "fmt"

// MaxLayersExceeded is an error indicating that the artifact has too many layers and cosign should abort processing it.
type MaxLayersExceeded struct {
	value   int64
	maximum int64
}

func NewMaxLayersExceeded(value, maximum int64) *MaxLayersExceeded {
	return &MaxLayersExceeded{value, maximum}
}

func (e *MaxLayersExceeded) Error() string {
	return fmt.Sprintf("number of layers (%d) exceeded the limit (%d)", e.value, e.maximum)
}
	payloadsize "github.com/sigstore/cosign/v2/internal/pkg/cosign/payload/size"
	size, err := s.Layer.Size()
	if err != nil {
		return nil, err
	}
	err = payloadsize.CheckSize(uint64(size))
	if err != nil {
		return nil, err
	}
	"io"
	"strings"
		env            map[string]string
	}, {
		name: "payload size exceeds default limit",
		l: &sigLayer{
			Layer: &mockLayer{size: 134217728 + 42}, // 128MB + 42 bytes
		},
		wantPayloadErr: errors.New("size of layer (134217770) exceeded the limit (134217728)"),
	}, {
		name: "payload size exceeds overridden limit",
		l: &sigLayer{
			Layer: &mockLayer{size: 1000000000 + 42}, // 1GB + 42 bytes
		},
		env:            map[string]string{"COSIGN_MAX_ATTACHMENT_SIZE": "1GB"},
		wantPayloadErr: errors.New("size of layer (1000000042) exceeded the limit (1000000000)"),
	}, {
		name: "payload size is within overridden limit",
		l: &sigLayer{
			Layer: layer,
			desc: v1.Descriptor{
				Digest: digest,
				Annotations: map[string]string{
					sigkey: "blah",
				},
			},
		},
		env:     map[string]string{"COSIGN_MAX_ATTACHMENT_SIZE": "5KB"},
		wantSig: "blah",
			for k, v := range test.env {
				t.Setenv(k, v)
			}
			if err != nil {
				return
			}

type mockLayer struct {
	size int64
}

func (m *mockLayer) Size() (int64, error) {
	return m.size, nil
}

func (m *mockLayer) Compressed() (io.ReadCloser, error) {
	return io.NopCloser(strings.NewReader("data")), nil
}

func (m *mockLayer) Digest() (v1.Hash, error)             { panic("not implemented") }
func (m *mockLayer) DiffID() (v1.Hash, error)             { panic("not implemented") }
func (m *mockLayer) Uncompressed() (io.ReadCloser, error) { panic("not implemented") }
func (m *mockLayer) MediaType() (types.MediaType, error)  { panic("not implemented") }
const maxLayers = 1000

	numLayers := int64(len(manifest.Layers))
	if numLayers > maxLayers {
		return nil, oci.NewMaxLayersExceeded(numLayers, maxLayers)
	}
	signatures := make([]oci.Signature, 0, numLayers)
// Copyright 2024 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package layout

import (
	"errors"
	"testing"

	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/fake"
)

func TestGet(t *testing.T) {
	tests := []struct {
		name      string
		layers    int
		wantError error
	}{
		{
			name:      "within limit",
			layers:    23,
			wantError: nil,
		},
		{
			name:      "exceeds limit",
			layers:    4242,
			wantError: errors.New("number of layers (4242) exceeded the limit (1000)"),
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			s := sigs{
				Image: &fake.FakeImage{
					ManifestStub: func() (*v1.Manifest, error) {
						return &v1.Manifest{
							Layers: make([]v1.Descriptor, test.layers),
						}, nil
					},
				},
			}
			_, err := s.Get()
			if test.wantError != nil && test.wantError.Error() != err.Error() {
				t.Fatalf("Get() = %v, wanted %v", err, test.wantError)
			}
			if test.wantError == nil && err != nil {
				t.Fatalf("Get() = %v, wanted %v", err, test.wantError)
			}
		})
	}
}
const maxLayers = 1000

	sumLayers := int64(len(sl) + len(sa.sigs))
	if sumLayers > maxLayers {
		return nil, oci.NewMaxLayersExceeded(sumLayers, maxLayers)
	}
	"errors"
	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/sigstore/cosign/v2/pkg/oci"

func TestGet(t *testing.T) {
	tests := []struct {
		name         string
		baseLayers   int
		appendLayers int
		wantError    error
	}{
		{
			name:         "within limit",
			baseLayers:   1,
			appendLayers: 1,
			wantError:    nil,
		},
		{
			name:         "base exceeds limit",
			baseLayers:   2000,
			appendLayers: 1,
			wantError:    errors.New("number of layers (2001) exceeded the limit (1000)"),
		},
		{
			name:         "append exceeds limit",
			baseLayers:   1,
			appendLayers: 1300,
			wantError:    errors.New("number of layers (1301) exceeded the limit (1000)"),
		},
		{
			name:         "sum exceeds limit",
			baseLayers:   666,
			appendLayers: 666,
			wantError:    errors.New("number of layers (1332) exceeded the limit (1000)"),
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			sa := sigAppender{
				base: &mockOCISignatures{
					signatures: make([]oci.Signature, test.baseLayers),
				},
				sigs: make([]oci.Signature, test.appendLayers),
			}
			_, err := sa.Get()
			if test.wantError != nil && test.wantError.Error() != err.Error() {
				t.Fatalf("Get() = %v, wanted %v", err, test.wantError)
			}
			if test.wantError == nil && err != nil {
				t.Fatalf("Get() = %v, wanted %v", err, test.wantError)
			}
		})
	}
}

type mockOCISignatures struct {
	v1.Image
	signatures []oci.Signature
}

func (m *mockOCISignatures) Get() ([]oci.Signature, error) {
	return m.signatures, nil
}
	payloadsize "github.com/sigstore/cosign/v2/internal/pkg/cosign/payload/size"
	size, err := f.layer.Size()
	if err != nil {
		return nil, err
	}
	err = payloadsize.CheckSize(uint64(size))
	if err != nil {
		return nil, err
	}

	"io"
	"strings"
	"github.com/google/go-containerregistry/pkg/v1/types"

func TestPayload(t *testing.T) {
	tests := []struct {
		name      string
		size      int64
		env       map[string]string
		wantError error
	}{
		{
			name:      "within default limit",
			size:      1000,
			wantError: nil,
		},
		{
			name:      "excceds default limit",
			size:      1073741824,
			wantError: errors.New("size of layer (1073741824) exceeded the limit (134217728)"),
		},
		{
			name:      "exceeds overridden limit",
			size:      5120,
			env:       map[string]string{"COSIGN_MAX_ATTACHMENT_SIZE": "1KB"},
			wantError: errors.New("size of layer (5120) exceeded the limit (1000)"),
		},
		{
			name: "within overridden limit",
			size: 5120,
			env:  map[string]string{"COSIGN_MAX_ATTACHMENT_SIZE": "10KB"},
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			for k, v := range test.env {
				t.Setenv(k, v)
			}
			a := attached{
				layer: &mockLayer{
					size: test.size,
				},
			}
			_, err := a.Payload()
			if test.wantError != nil && test.wantError.Error() != err.Error() {
				t.Fatalf("Payload() = %v, wanted %v", err, test.wantError)
			}
			if test.wantError == nil && err != nil {
				t.Fatalf("Payload() = %v, wanted %v", err, test.wantError)
			}
		})
	}
}

type mockLayer struct {
	size int64
}

func (m *mockLayer) Compressed() (io.ReadCloser, error) {
	return io.NopCloser(strings.NewReader("test payload")), nil
}

func (m *mockLayer) Size() (int64, error) {
	return m.size, nil
}

func (m *mockLayer) Digest() (v1.Hash, error)             { panic("not implemented") }
func (m *mockLayer) DiffID() (v1.Hash, error)             { panic("not implemented") }
func (m *mockLayer) Uncompressed() (io.ReadCloser, error) { panic("not implemented") }
func (m *mockLayer) MediaType() (types.MediaType, error)  { panic("not implemented") }
const maxLayers = 1000

	numLayers := int64(len(m.Layers))
	if numLayers > maxLayers {
		return nil, oci.NewMaxLayersExceeded(numLayers, maxLayers)
	}
	"github.com/google/go-containerregistry/pkg/v1/fake"

	t.Run("too many layers", func(t *testing.T) {
		remoteImage = func(_ name.Reference, _ ...remote.Option) (v1.Image, error) {
			return &fake.FakeImage{
				ManifestStub: func() (*v1.Manifest, error) {
					return &v1.Manifest{
						Layers: make([]v1.Descriptor, 10000),
					}, nil
				},
			}, nil
		}
		sigs, err := Signatures(name.MustParseReference("gcr.io/distroless/static:sha256-deadbeef.sig"))
		if err != nil {
			t.Fatalf("Signatures() = %v", err)
		}
		want := errors.New("number of layers (10000) exceeded the limit (1000)")
		_, err = sigs.Get()
		if err == nil || want.Error() != err.Error() {
			t.Fatalf("Get() = %v", err)
		}
	})
	payloadsize "github.com/sigstore/cosign/v2/internal/pkg/cosign/payload/size"
	size, err := s.Layer.Size()
	if err != nil {
		return nil, err
	}
	err = payloadsize.CheckSize(uint64(size))
	if err != nil {
		return nil, err
	}
	"io"
	"strings"
		env            map[string]string
	}, {
		name: "payload size exceeds default limit",
		l: &sigLayer{
			Layer: &mockLayer{size: 134217728 + 42}, // 128MiB + 42 bytes
		},
		wantPayloadErr: errors.New("size of layer (134217770) exceeded the limit (134217728)"),
	}, {
		name: "payload size exceeds overridden limit",
		l: &sigLayer{
			Layer: &mockLayer{size: 1000000000 + 42}, // 1GB + 42 bytes
		},
		env:            map[string]string{"COSIGN_MAX_ATTACHMENT_SIZE": "1GB"},
		wantPayloadErr: errors.New("size of layer (1000000042) exceeded the limit (1000000000)"),
	}, {
		name: "payload size is within overridden limit",
		l: &sigLayer{
			Layer: layer,
			desc: v1.Descriptor{
				Digest: digest,
				Annotations: map[string]string{
					sigkey: "blah",
				},
			},
		},
		env:     map[string]string{"COSIGN_MAX_ATTACHMENT_SIZE": "5KB"},
		wantSig: "blah",
			for k, v := range test.env {
				t.Setenv(k, v)
			}
			if err != nil {
				return
			}

type mockLayer struct {
	size int64
}

func (m *mockLayer) Size() (int64, error) {
	return m.size, nil
}

func (m *mockLayer) Compressed() (io.ReadCloser, error) {
	return io.NopCloser(strings.NewReader("data")), nil
}

func (m *mockLayer) Digest() (v1.Hash, error)             { panic("not implemented") }
func (m *mockLayer) DiffID() (v1.Hash, error)             { panic("not implemented") }
func (m *mockLayer) Uncompressed() (io.ReadCloser, error) { panic("not implemented") }
func (m *mockLayer) MediaType() (types.MediaType, error)  { panic("not implemented") }
	payloadsize "github.com/sigstore/cosign/v2/internal/pkg/cosign/payload/size"
	size, err := f.layer.Size()
	if err != nil {
		return nil, err
	}
	err = payloadsize.CheckSize(uint64(size))
	if err != nil {
		return nil, err
	}
	"errors"
	f, err := NewFile([]byte(payload), WithLayerMediaType("foo"), WithAnnotations(map[string]string{"foo": "bar"}))
	layers, err := f.Layers()
		gotMT, err := f.FileMediaType()
		gotPayload, err := f.Payload()
		fileCfg, err := f.ConfigFile()
		m, err := f.Manifest()

	t.Run("huge file payload", func(t *testing.T) {
		// default limit
		f := file{
			layer: &mockLayer{200000000},
		}
		want := errors.New("size of layer (200000000) exceeded the limit (134217728)")
		_, err = f.Payload()
		if err == nil || want.Error() != err.Error() {
			t.Errorf("Payload() = %v, wanted %v", err, want)
		}
		// override limit
		t.Setenv("COSIGN_MAX_ATTACHMENT_SIZE", "512MiB")
		_, err = f.Payload()
		if err != nil {
			t.Errorf("Payload() = %v, wanted nil", err)
		}
	})

type mockLayer struct {
	size int64
}

func (m *mockLayer) Size() (int64, error) {
	return m.size, nil
}

func (m *mockLayer) Uncompressed() (io.ReadCloser, error) {
	return io.NopCloser(strings.NewReader("data")), nil
}

func (m *mockLayer) Digest() (v1.Hash, error)            { panic("not implemented") }
func (m *mockLayer) DiffID() (v1.Hash, error)            { panic("not implemented") }
func (m *mockLayer) Compressed() (io.ReadCloser, error)  { panic("not implemented") }
func (m *mockLayer) MediaType() (types.MediaType, error) { panic("not implemented") }