CVE-2022-23649 (Go, published 2022-02-18T22:15Z)
Description: value: Cosign provides container signing, verification, and storage in an OCI registry for the sigstore project. Prior to version 1.5.2, Cosign can be manipulated to claim that an entry for a signature exists in the Rekor transparency log even if it doesn't. This requires the attacker to have pull and push permissions for the signature in OCI. This can happen with both standard signing with a keypair and "keyless signing" with Fulcio. If an attacker has access to the signature in OCI, they can manipulate cosign into believing the entry was stored in Rekor even though it wasn't. The vulnerability has been patched in v1.5.2 of Cosign. The `signature` in the `signedEntryTimestamp` provided by Rekor is now compared to the `signature` that is being verified. If these don't match, then an error is returned. If a valid bundle is copied to a different signature, verification should fail. Cosign output now only informs the user that certificates were verified if a certificate was in fact verified. There is currently no known workaround.
Severity: LOW (CVSS v3 base score: 3.3)
Weakness: CWE-295 \u2014 Improper Certificate Validation
The product does not validate, or incorrectly validates, a certificate.
Repository: https://github.com/sigstore/cosign
Files changed:
cmd/cosign/cli/verify/verify.go
cmd/cosign/cli/verify/verify_attestation.go
pkg/cosign/verify.go
pkg/cosign/verify_test.go
pkg/sget/sget.go
test/e2e_test.go
Commit message: Merge pull request from GHSA-ccxc-vr6p-4858

* Make sure signature in Rekor bundle matches signature being verified

Signed-off-by: Priya Wadhwa <priya@chainguard.dev>

* Only print "fulcio verified" when using Fulcio

Currently we tell users that we've verified against the Fulcio root
trust when verifying but this isn't always true. This work ensures we
only say this when we actually use the Fulcio root cert for
verification.

Signed-off-by: Nathan Smith <nathan@chainguard.dev>

* Add e2e test

Signed-off-by: Nathan Smith <nathan@chainguard.dev>

Co-authored-by: Priya Wadhwa <priya@chainguard.dev>

Vulnerable code:
			PrintVerificationHeader(img, co, bundleVerified)
			PrintVerificationHeader(ref.Name(), co, bundleVerified)
func PrintVerificationHeader(imgRef string, co *cosign.CheckOpts, bundleVerified bool) {
	fmt.Fprintln(os.Stderr, "  - Any certificates were verified against the Fulcio roots.")
		PrintVerificationHeader(imageRef, co, bundleVerified)
		verify.PrintVerificationHeader(sg.ImageRef, co, bundleVerified)

Fixed code:
	// NB: There are only 2 kinds of verification right now:
	// 1. You gave us the public key explicitly to verify against so co.SigVerifier is non-nil or,
	// 2. We're going to find an x509 certificate on the signature and verify against Fulcio root trust
	// TODO(nsmith5): Refactor this verification logic to pass back _how_ verification
	// was performed so we don't need to use this fragile logic here.
	fulcioVerified := (co.SigVerifier == nil)

			PrintVerificationHeader(img, co, bundleVerified, fulcioVerified)
			PrintVerificationHeader(ref.Name(), co, bundleVerified, fulcioVerified)
func PrintVerificationHeader(imgRef string, co *cosign.CheckOpts, bundleVerified, fulcioVerified bool) {
	if fulcioVerified {
		fmt.Fprintln(os.Stderr, "  - Any certificates were verified against the Fulcio roots.")
	}
	// NB: There are only 2 kinds of verification right now:
	// 1. You gave us the public key explicitly to verify against so co.SigVerifier is non-nil or,
	// 2. We're going to find an x509 certificate on the signature and verify against Fulcio root trust
	// TODO(nsmith5): Refactor this verification logic to pass back _how_ verification
	// was performed so we don't need to use this fragile logic here.
	fulcioVerified := (co.SigVerifier == nil)

		PrintVerificationHeader(imageRef, co, bundleVerified, fulcioVerified)
	if err := compareSigs(bundle.Payload.Body.(string), sig); err != nil {
		return false, err
	}

// compare bundle signature to the signature we are verifying
func compareSigs(bundleBody string, sig oci.Signature) error {
	// TODO(nsmith5): modify function signature to make it more clear _why_
	// we've returned nil (there are several reasons possible here).
	actualSig, err := sig.Base64Signature()
	if err != nil {
		return errors.Wrap(err, "base64 signature")
	}
	if actualSig == "" {
		// NB: empty sig means this is an attestation
		return nil
	}
	bundleSignature, err := bundleSig(bundleBody)
	if err != nil {
		return errors.Wrap(err, "failed to extract signature from bundle")
	}
	if bundleSignature == "" {
		return nil
	}
	if bundleSignature != actualSig {
		return fmt.Errorf("signature in bundle does not match signature being verified")
	}
	return nil
}

// bundleSig extracts the signature from the rekor bundle body
func bundleSig(bundleBody string) (string, error) {
	var rekord models.Rekord
	var hrekord models.Hashedrekord
	var rekordObj models.RekordV001Schema
	var hrekordObj models.HashedrekordV001Schema

	bodyDecoded, err := base64.StdEncoding.DecodeString(bundleBody)
	if err != nil {
		return "", errors.Wrap(err, "decoding bundleBody")
	}

	// Try Rekord
	if err := json.Unmarshal(bodyDecoded, &rekord); err == nil {
		specMarshal, err := json.Marshal(rekord.Spec)
		if err != nil {
			return "", err
		}
		if err := json.Unmarshal(specMarshal, &rekordObj); err != nil {
			return "", err
		}
		return rekordObj.Signature.Content.String(), nil
	}

	// Try hashedRekordObj
	if err := json.Unmarshal(bodyDecoded, &hrekord); err != nil {
		return "", err
	}
	specMarshal, err := json.Marshal(hrekord.Spec)
	if err != nil {
		return "", err
	}
	if err := json.Unmarshal(specMarshal, &hrekordObj); err != nil {
		return "", err
	}
	return hrekordObj.Signature.Content.String(), nil
}

	"github.com/sigstore/cosign/pkg/oci/static"

func TestCompareSigs(t *testing.T) {
	//TODO(nsmith5): Add test cases for invalid signature, missing signature etc
	tests := []struct {
		description string
		b64sig      string
		bundleBody  string
		shouldErr   bool
	}{
		{
			description: "sigs match",
			b64sig:      "MEQCIDO3XHbLovPWK+bk8ItCig2cwlr/8MXbLvz3UFzxMGIMAiA1lqdM9IqqUvCUqzOjufTq3sKU3qSn7R5tPqPz0ddNwQ==",
			bundleBody:  `eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIzODE1MmQxZGQzMjZhZjQwNWY4OTlkYmNjMmNlMzUwYjVmMTZkNDVkZjdmMjNjNDg4ZjQ4NTBhZmExY2Q4NmQxIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FUUNJRE8zWEhiTG92UFdLK2JrOEl0Q2lnMmN3bHIvOE1YYkx2ejNVRnp4TUdJTUFpQTFscWRNOUlxcVV2Q1Vxek9qdWZUcTNzS1UzcVNuN1I1dFBxUHowZGROd1E9PSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdEx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LTFMwdExTMUZUa1FnVUZWQ1RFbERJRXRGV1MwdExTMHRDZz09In19fX0=`,
			shouldErr:   true,
		},
	}
	for _, test := range tests {
		t.Run(test.description, func(t *testing.T) {
			sig, err := static.NewSignature([]byte("payload"), test.b64sig)
			if err != nil {
				t.Fatalf("failed to create static signature: %v", err)
			}
			err = compareSigs(test.bundleBody, sig)
			if err == nil && test.shouldErr {
				t.Fatal("test should have errored")
			}
			if err != nil && !test.shouldErr {
				t.Fatal(err)
			}
		})
	}
}
		// NB: There are only 2 kinds of verification right now:
		// 1. You gave us the public key explicitly to verify against so co.SigVerifier is non-nil or,
		// 2. We're going to find an x509 certificate on the signature and verify against Fulcio root trust
		// TODO(nsmith5): Refactor this verification logic to pass back _how_ verification
		// was performed so we don't need to use this fragile logic here.
		fulcioVerified := (co.SigVerifier == nil)

		verify.PrintVerificationHeader(sg.ImageRef, co, bundleVerified, fulcioVerified)
	"github.com/sigstore/cosign/pkg/oci/mutate"

// If a signature has a bundle, but *not for that signature*, cosign verification should fail
// This test is pretty long, so here are the basic points:
//    1. Sign image1 with a keypair, store entry in rekor
//    2. Sign image2 with keypair, DO NOT store entry in rekor
//    3. Take the bundle from image1 and store it on the signature in image2
//    4. Verification of image2 should now fail, since the bundle is for a different signature
func TestInvalidBundle(t *testing.T) {
	regName, stop := reg(t)
	defer stop()
	td := t.TempDir()

	img1 := path.Join(regName, "cosign-e2e")

	imgRef, _, cleanup := mkimage(t, img1)
	defer cleanup()

	_, privKeyPath, pubKeyPath := keypair(t, td)

	ctx := context.Background()

	// Sign image1 and store the entry in rekor
	// (we're just using it for its bundle)
	defer setenv(t, options.ExperimentalEnv, "1")()
	remoteOpts := ociremote.WithRemoteOptions(registryClientOpts(ctx)...)
	ko := sign.KeyOpts{KeyRef: privKeyPath, PassFunc: passFunc, RekorURL: rekorURL}
	regOpts := options.RegistryOptions{}

	must(sign.SignCmd(ro, ko, regOpts, nil, []string{img1}, "", true, "", "", "", true, false, ""), t)
	// verify image1
	must(verify(pubKeyPath, img1, true, nil, ""), t)
	// extract the bundle from image1
	si, err := ociremote.SignedImage(imgRef, remoteOpts)
	must(err, t)
	imgSigs, err := si.Signatures()
	must(err, t)
	sigs, err := imgSigs.Get()
	must(err, t)
	if l := len(sigs); l != 1 {
		t.Error("expected one signature")
	}
	bund, err := sigs[0].Bundle()
	must(err, t)
	if bund == nil {
		t.Fail()
	}

	// Now, we move on to image2
	// Sign image2 and DO NOT store the entry in rekor
	defer setenv(t, options.ExperimentalEnv, "0")()
	img2 := path.Join(regName, "unrelated")
	imgRef2, _, cleanup := mkimage(t, img2)
	defer cleanup()
	must(sign.SignCmd(ro, ko, regOpts, nil, []string{img2}, "", true, "", "", "", false, false, ""), t)
	must(verify(pubKeyPath, img2, true, nil, ""), t)

	si2, err := ociremote.SignedEntity(imgRef2, remoteOpts)
	must(err, t)
	sigs2, err := si2.Signatures()
	must(err, t)
	gottenSigs2, err := sigs2.Get()
	must(err, t)
	if len(gottenSigs2) != 1 {
		t.Fatal("there should be one signature")
	}
	sigsTag, err := ociremote.SignatureTag(imgRef2)
	if err != nil {
		t.Fatal(err)
	}

	// At this point, we would mutate the signature to add the bundle annotation
	// since we don't have a function for it at the moment, mock this by deleting the signature
	// and pushing a new signature with the additional bundle annotation
	if err := remote.Delete(sigsTag); err != nil {
		t.Fatal(err)
	}
	mustErr(verify(pubKeyPath, img2, true, nil, ""), t)

	newSig, err := mutate.Signature(gottenSigs2[0], mutate.WithBundle(bund))
	must(err, t)
	si2, err = ociremote.SignedEntity(imgRef2, remoteOpts)
	must(err, t)
	newImage, err := mutate.AttachSignatureToEntity(si2, newSig)
	must(err, t)
	if err := ociremote.WriteSignatures(sigsTag.Repository, newImage); err != nil {
		t.Fatal(err)
	}

	// veriyfing image2 now should fail
	mustErr(verify(pubKeyPath, img2, true, nil, ""), t)
}