CVE-2023-46737: Loop with Unreachable Exit Condition ('Infinite Loop') (CWE-835)
value: Cosign is a sigstore signing tool for OCI containers. Cosign is susceptible to a denial of service by an attacker controlled registry. An attacker who controls a remote registry can return a high number of attestations and/or signatures to Cosign and cause Cosign to enter a long loop resulting in an endless data attack. The root cause is that Cosign loops through all attestations fetched from the remote registry in pkg/cosign.FetchAttestations. The attacker needs to compromise the registry or make a request to a registry they control. When doing so, the attacker must return a high number of attestations in the response to Cosign. The result will be that the attacker can cause Cosign to go into a long or infinite loop that will prevent other users from verifying their data. In Kyvernos case, an attacker whose privileges are limited to making requests to the cluster can make a request with an image reference to their own registry, trigger the infinite loop and deny other users from completing their admission requests. Alternatively, the attacker can obtain control of the registry used by an organization and return a high number of attestations instead the expected number of attestations. The issue can be mitigated rather simply by setting a limit to the limit of attestations that Cosign will loop through. The limit does not need to be high to be within the vast majority of use cases and still prevent the endless data attack. This issue has been patched in version 2.2.1 and users are advised to upgrade.
CWE description: The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
CVSS v3 base score: 5.3
Published: 2023-11-07T18:15Z
Repository: https://github.com/sigstore/cosign
Language: Go
Files changed: pkg/cosign/fetch.go, test/e2e_test.go
Commit date: 2023-11-07 06:59:07 -0500
Commit message: Merge pull request from GHSA-vfp6-jrw2-99g9

* Add limit to number of sigs and attestations

Signed-off-by: AdamKorcz <44787359+AdamKorcz@users.noreply.github.com>

* Update pkg/cosign/fetch.go

Co-authored-by: Cody Soyland <codysoyland@gmail.com>
Signed-off-by: AdamKorcz <44787359+AdamKorcz@users.noreply.github.com>

* Update error message

Signed-off-by: Hayden B <hblauzvern@google.com>

* fix compilation error

Signed-off-by: Hayden Blauzvern <hblauzvern@google.com>

* Add e2e tests

Signed-off-by: Hayden Blauzvern <hblauzvern@google.com>

---------

Signed-off-by: AdamKorcz <44787359+AdamKorcz@users.noreply.github.com>
Signed-off-by: Hayden B <hblauzvern@google.com>
Signed-off-by: Hayden Blauzvern <hblauzvern@google.com>
Co-authored-by: Cody Soyland <codysoyland@gmail.com>
Co-authored-by: Hayden B <hblauzvern@google.com>
Diff: diff --git a/pkg/cosign/fetch.go b/pkg/cosign/fetch.go
index 68cac7ff..ff81be22 100644
--- a/pkg/cosign/fetch.go
+++ b/pkg/cosign/fetch.go
@@ -32,10 +32,12 @@ import (
 	"github.com/sigstore/cosign/v2/pkg/oci"
 	ociremote "github.com/sigstore/cosign/v2/pkg/oci/remote"
 	"golang.org/x/sync/errgroup"
 )
 
+const maxAllowedSigsOrAtts = 100
+
 type SignedPayload struct {
 	Base64Signature  string
 	Payload          []byte
 	Cert             *x509.Certificate
 	Chain            []*x509.Certificate
@@ -82,10 +84,13 @@ func FetchSignaturesForReference(_ context.Context, ref name.Reference, opts ...
 		return nil, fmt.Errorf("fetching signatures: %w", err)
 	}
 	if len(l) == 0 {
 		return nil, fmt.Errorf("no signatures associated with %s", ref)
 	}
+	if len(l) > maxAllowedSigsOrAtts {
+		return nil, fmt.Errorf("maximum number of signatures on an image is %d, found %d", maxAllowedSigsOrAtts, len(l))
+	}
 
 	signatures := make([]SignedPayload, len(l))
 	var g errgroup.Group
 	g.SetLimit(runtime.NumCPU())
 	for i, sig := range l {
@@ -143,10 +148,14 @@ func FetchAttestations(se oci.SignedEntity, predicateType string) ([]Attestation
 		return nil, fmt.Errorf("fetching attestations: %w", err)
 	}
 	if len(l) == 0 {
 		return nil, errors.New("found no attestations")
 	}
+	if len(l) > maxAllowedSigsOrAtts {
+		errMsg := fmt.Sprintf("maximum number of attestations on an image is %d, found %d", maxAllowedSigsOrAtts, len(l))
+		return nil, errors.New(errMsg)
+	}
 
 	attestations := make([]AttestationPayload, 0, len(l))
 	var attMu sync.Mutex
 
 	var g errgroup.Group
diff --git a/test/e2e_test.go b/test/e2e_test.go
index bef1e0db..ff81877f 100644
--- a/test/e2e_test.go
+++ b/test/e2e_test.go
@@ -659,10 +659,92 @@ func TestAttestationReplaceCreate(t *testing.T) {
 	if len(attestations) != 1 {
 		t.Fatal(fmt.Errorf("expected len(attestations) == 1, got %d", len(attestations)))
 	}
 }
 
+func TestExcessiveAttestations(t *testing.T) {
+	repo, stop := reg(t)
+	defer stop()
+	td := t.TempDir()
+
+	imgName := path.Join(repo, "cosign-attest-download-e2e")
+
+	_, _, cleanup := mkimage(t, imgName)
+	defer cleanup()
+
+	_, privKeyPath, _ := keypair(t, td)
+	ko := options.KeyOpts{KeyRef: privKeyPath, PassFunc: passFunc}
+
+	ctx := context.Background()
+
+	slsaAttestation := `{ "buildType": "x", "builder": { "id": "2" }, "recipe": {} }`
+	slsaAttestationPath := filepath.Join(td, "attestation.slsa.json")
+	if err := os.WriteFile(slsaAttestationPath, []byte(slsaAttestation), 0600); err != nil {
+		t.Fatal(err)
+	}
+
+	vulnAttestation := `
+	{
+    "invocation": {
+      "parameters": null,
+      "uri": "invocation.example.com/cosign-testing",
+      "event_id": "",
+      "builder.id": ""
+    },
+    "scanner": {
+      "uri": "fakescanner.example.com/cosign-testing",
+      "version": "",
+      "db": {
+        "uri": "",
+        "version": ""
+      },
+      "result": null
+    },
+    "metadata": {
+      "scanStartedOn": "2022-04-12T00:00:00Z",
+      "scanFinishedOn": "2022-04-12T00:10:00Z"
+    }
+}
+`
+	ref, err := name.ParseReference(imgName)
+	if err != nil {
+		t.Fatal(err)
+	}
+	regOpts := options.RegistryOptions{}
+	ociremoteOpts, err := regOpts.ClientOpts(ctx)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	for i := 0; i < 102; i++ {
+		vulnAttestationPath := filepath.Join(td, fmt.Sprintf("attestation-%d.vuln.json", i))
+		if err := os.WriteFile(vulnAttestationPath, []byte(vulnAttestation), 0600); err != nil {
+			t.Fatal(err)
+		}
+
+		// Attest to create a vuln attestation
+		attestCommand := attest.AttestCommand{
+			KeyOpts:       ko,
+			PredicatePath: vulnAttestationPath,
+			PredicateType: "vuln",
+			Timeout:       30 * time.Second,
+			Replace:       false,
+		}
+		must(attestCommand.Exec(ctx, imgName), t)
+	}
+
+	attOpts := options.AttestationDownloadOptions{}
+	_, err = cosign.FetchAttestationsForReference(ctx, ref, attOpts.PredicateType, ociremoteOpts...)
+	if err == nil {
+		t.Fatalf("Expected an error, but 'err' was 'nil'")
+	}
+	expectedError := "maximum number of attestations on an image is 100, found 102"
+	if err.Error() != expectedError {
+		t.Errorf("Exted the error to be: '%s' but it was '%s'", expectedError, err.Error())
+	}
+}
+
 func TestAttestationReplace(t *testing.T) {
 	repo, stop := reg(t)
 	defer stop()
 	td := t.TempDir()
 
@@ -1252,10 +1334,42 @@ func TestDuplicateSign(t *testing.T) {
 	if len(signatures) > 1 {
 		t.Errorf("expected there to only be one signature, got %v", signatures)
 	}
 }
 
+func TestExcessiveSignatures(t *testing.T) {
+	repo, stop := reg(t)
+	defer stop()
+	td := t.TempDir()
+
+	imgName := path.Join(repo, "cosign-e2e")
+
+	_, _, cleanup := mkimage(t, imgName)
+	defer cleanup()
+
+	ctx := context.Background()
+
+	for i := 0; i < 102; i++ {
+		_, privKeyPath, _ := keypair(t, td)
+
+		// Sign the image
+		ko := options.KeyOpts{KeyRef: privKeyPath, PassFunc: passFunc}
+		so := options.SignOptions{
+			Upload: true,
+		}
+		must(sign.SignCmd(ro, ko, so, []string{imgName}), t)
+	}
+	err := download.SignatureCmd(ctx, options.RegistryOptions{}, imgName)
+	if err == nil {
+		t.Fatal("Expected an error, but 'err' was 'nil'")
+	}
+	expectedErr := "maximum number of signatures on an image is 100, found 102"
+	if err.Error() != expectedErr {
+		t.Fatalf("Expected the error '%s', but got the error '%s'", expectedErr, err.Error())
+	}
+}
+
 func TestKeyURLVerify(t *testing.T) {
 	// TODO: re-enable once distroless images are being signed by the new client
 	t.Skip()
 	// Verify that an image can be verified via key url
 	keyRef := "https://raw.githubusercontent.com/GoogleContainerTools/distroless/main/cosign.pub"

Fixed code: const maxAllowedSigsOrAtts = 100

	if len(l) > maxAllowedSigsOrAtts {
		return nil, fmt.Errorf("maximum number of signatures on an image is %d, found %d", maxAllowedSigsOrAtts, len(l))
	}
	if len(l) > maxAllowedSigsOrAtts {
		errMsg := fmt.Sprintf("maximum number of attestations on an image is %d, found %d", maxAllowedSigsOrAtts, len(l))
		return nil, errors.New(errMsg)
	}
func TestExcessiveAttestations(t *testing.T) {
	repo, stop := reg(t)
	defer stop()
	td := t.TempDir()

	imgName := path.Join(repo, "cosign-attest-download-e2e")

	_, _, cleanup := mkimage(t, imgName)
	defer cleanup()

	_, privKeyPath, _ := keypair(t, td)
	ko := options.KeyOpts{KeyRef: privKeyPath, PassFunc: passFunc}

	ctx := context.Background()

	slsaAttestation := `{ "buildType": "x", "builder": { "id": "2" }, "recipe": {} }`
	slsaAttestationPath := filepath.Join(td, "attestation.slsa.json")
	if err := os.WriteFile(slsaAttestationPath, []byte(slsaAttestation), 0600); err != nil {
		t.Fatal(err)
	}

	vulnAttestation := `
	{
    "invocation": {
      "parameters": null,
      "uri": "invocation.example.com/cosign-testing",
      "event_id": "",
      "builder.id": ""
    },
    "scanner": {
      "uri": "fakescanner.example.com/cosign-testing",
      "version": "",
      "db": {
        "uri": "",
        "version": ""
      },
      "result": null
    },
    "metadata": {
      "scanStartedOn": "2022-04-12T00:00:00Z",
      "scanFinishedOn": "2022-04-12T00:10:00Z"
    }
}
`
	ref, err := name.ParseReference(imgName)
	if err != nil {
		t.Fatal(err)
	}
	regOpts := options.RegistryOptions{}
	ociremoteOpts, err := regOpts.ClientOpts(ctx)
	if err != nil {
		t.Fatal(err)
	}

	for i := 0; i < 102; i++ {
		vulnAttestationPath := filepath.Join(td, fmt.Sprintf("attestation-%d.vuln.json", i))
		if err := os.WriteFile(vulnAttestationPath, []byte(vulnAttestation), 0600); err != nil {
			t.Fatal(err)
		}

		// Attest to create a vuln attestation
		attestCommand := attest.AttestCommand{
			KeyOpts:       ko,
			PredicatePath: vulnAttestationPath,
			PredicateType: "vuln",
			Timeout:       30 * time.Second,
			Replace:       false,
		}
		must(attestCommand.Exec(ctx, imgName), t)
	}

	attOpts := options.AttestationDownloadOptions{}
	_, err = cosign.FetchAttestationsForReference(ctx, ref, attOpts.PredicateType, ociremoteOpts...)
	if err == nil {
		t.Fatalf("Expected an error, but 'err' was 'nil'")
	}
	expectedError := "maximum number of attestations on an image is 100, found 102"
	if err.Error() != expectedError {
		t.Errorf("Exted the error to be: '%s' but it was '%s'", expectedError, err.Error())
	}
}

func TestExcessiveSignatures(t *testing.T) {
	repo, stop := reg(t)
	defer stop()
	td := t.TempDir()

	imgName := path.Join(repo, "cosign-e2e")

	_, _, cleanup := mkimage(t, imgName)
	defer cleanup()

	ctx := context.Background()

	for i := 0; i < 102; i++ {
		_, privKeyPath, _ := keypair(t, td)

		// Sign the image
		ko := options.KeyOpts{KeyRef: privKeyPath, PassFunc: passFunc}
		so := options.SignOptions{
			Upload: true,
		}
		must(sign.SignCmd(ro, ko, so, []string{imgName}), t)
	}
	err := download.SignatureCmd(ctx, options.RegistryOptions{}, imgName)
	if err == nil {
		t.Fatal("Expected an error, but 'err' was 'nil'")
	}
	expectedErr := "maximum number of signatures on an image is 100, found 102"
	if err.Error() != expectedErr {
		t.Fatalf("Expected the error '%s', but got the error '%s'", expectedErr, err.Error())
	}
}