Просмотр исходного кода

Add TDX, SEV-SNP and Confidential Space verifiers to attestation

The verifiers take raw evidence and return attestation types, so that
the remote-attest-01 challenge, and anything else that verifies the
same evidence, can share them.

- tdx verifies version 4 quotes with collateral and revocation from
  Intel's PCS. go-tdx-guest refuses any TCB status other than UpToDate,
  and debug trust domains are refused.
- sevsnp verifies reports. It always passes explicit AMD roots, so
  go-sev-guest's pre-v0.15.0 trust of the evidence's own ARK can never
  apply, and it refuses guests whose policy allows debugging.
- collateral is the shared one-hour cache of PCS and KDS responses.
- confidentialspace verifies PKI tokens: x5c to configured roots, RS256,
  iss, aud, time claims, maximum age, the nonce count, and dbgstat equal
  to disabled-since-boot. The optional workload expectations are kept
  separate from the verifier.
- tsm parses configfs-tsm reports in Veraison's tsm-report media types.
  Blobs are base64url in JSON, and standard base64 and padding are also
  accepted.

If a TDX or SEV-SNP verification fails because a collateral fetch
failed, the error is not marked as invalid evidence, so the caller can
tell an unreachable service from a bad quote.

sevsnptest and confidentialspacetest are test helpers for code that
verifies such evidence.

go-sev-guest moves from v0.14.0 (indirect) to v0.15.0. go-tdx-guest is
added at v0.3.2-0.20250814004405-ffb0869e6f4d.

Claude-Session: https://claude.ai/code/session_01CjfEMLGpnHQaWsmxe1zmLF
Josh Drake 1 месяц назад
Родитель
Сommit
04410c4e52

+ 121 - 0
attestation/collateral/collateral.go

@@ -0,0 +1,121 @@
+// Package collateral fetches and caches the collateral that TEE evidence is
+// verified with: TCB information, identities, certificates and revocation
+// lists from Intel's provisioning certification service and AMD's key
+// distribution service.
+package collateral
+
+import (
+	"context"
+	"fmt"
+	"io"
+	"net/http"
+	"sync"
+	"time"
+)
+
+// TTL is how long a Getter keeps a response. The verifiers still check each
+// item's own validity.
+const TTL = time.Hour
+
+// MaxSize limits the size of a response.
+const MaxSize = 1 << 20
+
+// HTTPClient is the interface of the client a Getter fetches with, which
+// *http.Client implements.
+type HTTPClient interface {
+	Do(*http.Request) (*http.Response, error)
+}
+
+// Getter fetches collateral and caches successful responses for TTL, so that
+// verifying evidence does not depend on, or overload, the vendors' services on
+// every request.
+type Getter struct {
+	client  HTTPClient
+	now     func() time.Time
+	mu      sync.Mutex
+	entries map[string]entry
+}
+
+type entry struct {
+	header  http.Header
+	body    []byte
+	expires time.Time
+}
+
+// New returns a Getter that fetches with the given client.
+func New(client HTTPClient) *Getter {
+	return &Getter{
+		client:  client,
+		now:     time.Now,
+		entries: make(map[string]entry),
+	}
+}
+
+func (g *Getter) get(ctx context.Context, url string) (http.Header, []byte, error) {
+	now := g.now()
+	g.mu.Lock()
+	e, ok := g.entries[url]
+	g.mu.Unlock()
+	if ok && now.Before(e.expires) {
+		return e.header, e.body, nil
+	}
+
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
+	if err != nil {
+		return nil, nil, err
+	}
+	resp, err := g.client.Do(req)
+	if err != nil {
+		return nil, nil, fmt.Errorf("error fetching %s: %w", url, err)
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return nil, nil, fmt.Errorf("error fetching %s: status code %d", url, resp.StatusCode)
+	}
+	body, err := io.ReadAll(io.LimitReader(resp.Body, MaxSize))
+	if err != nil {
+		return nil, nil, fmt.Errorf("error reading %s: %w", url, err)
+	}
+
+	g.mu.Lock()
+	g.entries[url] = entry{
+		header:  resp.Header,
+		body:    body,
+		expires: now.Add(TTL),
+	}
+	g.mu.Unlock()
+	return resp.Header, body, nil
+}
+
+// TDX adapts a Getter to go-tdx-guest's trust.HTTPSGetter and
+// trust.ContextHTTPSGetter, which return the response headers too.
+type TDX struct {
+	*Getter
+}
+
+// Get implements go-tdx-guest's trust.HTTPSGetter.
+func (g TDX) Get(url string) (map[string][]string, []byte, error) {
+	return g.GetContext(context.Background(), url)
+}
+
+// GetContext implements go-tdx-guest's trust.ContextHTTPSGetter.
+func (g TDX) GetContext(ctx context.Context, url string) (map[string][]string, []byte, error) {
+	return g.get(ctx, url)
+}
+
+// SEVSNP adapts a Getter to go-sev-guest's trust.HTTPSGetter and
+// trust.ContextHTTPSGetter.
+type SEVSNP struct {
+	*Getter
+}
+
+// Get implements go-sev-guest's trust.HTTPSGetter.
+func (g SEVSNP) Get(url string) ([]byte, error) {
+	return g.GetContext(context.Background(), url)
+}
+
+// GetContext implements go-sev-guest's trust.ContextHTTPSGetter.
+func (g SEVSNP) GetContext(ctx context.Context, url string) ([]byte, error) {
+	_, body, err := g.get(ctx, url)
+	return body, err
+}

+ 57 - 0
attestation/collateral/collateral_test.go

@@ -0,0 +1,57 @@
+package collateral
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+func TestGetter(t *testing.T) {
+	var hits atomic.Int32
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		hits.Add(1)
+		if r.URL.Path == "/missing" {
+			http.NotFound(w, r)
+			return
+		}
+		w.Header().Set("TCB-Info-Issuer-Chain", "chain")
+		_, _ = w.Write([]byte("collateral"))
+	}))
+	t.Cleanup(srv.Close)
+
+	now := time.Now()
+	g := New(srv.Client())
+	g.now = func() time.Time { return now }
+	tdx := TDX{g}
+	sev := SEVSNP{g}
+
+	header, body, err := tdx.Get(srv.URL + "/tcb")
+	require.NoError(t, err)
+	assert.Equal(t, []byte("collateral"), body)
+	assert.Equal(t, []string{"chain"}, header["Tcb-Info-Issuer-Chain"])
+
+	// A cached response is served without a request, to either library.
+	body, err = sev.GetContext(context.Background(), srv.URL+"/tcb")
+	require.NoError(t, err)
+	assert.Equal(t, []byte("collateral"), body)
+	assert.Equal(t, int32(1), hits.Load())
+
+	// After the TTL it is fetched again.
+	now = now.Add(TTL + time.Second)
+	_, err = sev.Get(srv.URL + "/tcb")
+	require.NoError(t, err)
+	assert.Equal(t, int32(2), hits.Load())
+
+	// Failures are not cached.
+	for range 2 {
+		_, _, err = tdx.GetContext(context.Background(), srv.URL+"/missing")
+		assert.ErrorContains(t, err, "status code 404")
+	}
+	assert.Equal(t, int32(4), hits.Load())
+}

+ 293 - 0
attestation/confidentialspace/confidentialspace.go

@@ -0,0 +1,293 @@
+// Package confidentialspace verifies the PKI attestation tokens that Google
+// Cloud Attestation issues to Confidential Space workloads.
+package confidentialspace
+
+import (
+	"crypto/rsa"
+	"crypto/x509"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"slices"
+	"time"
+
+	"go.step.sm/crypto/jose"
+
+	"github.com/smallstep/certificates/attestation"
+)
+
+// Issuer is the issuer of Google Cloud Attestation tokens.
+const Issuer = "https://confidentialcomputing.googleapis.com"
+
+// Leeway is the clock skew allowed when validating the exp, nbf and iat claims
+// of a token.
+const Leeway = time.Minute
+
+// DefaultMaxTokenAge is the default maximum age of a token, measured from its
+// iat claim.
+const DefaultMaxTokenAge = 5 * time.Minute
+
+// MaxNonces is the maximum number of nonces Google Cloud Attestation puts in a
+// token.
+const MaxNonces = 6
+
+// DebugDisabled is the value of the dbgstat claim of a workload that has not
+// been debuggable since it booted, which Verify requires.
+const DebugDisabled = "disabled-since-boot"
+
+// Nonces is the eat_nonce claim of a token, which is either a string or an
+// array of strings.
+type Nonces []string
+
+// UnmarshalJSON implements [json.Unmarshaler].
+func (n *Nonces) UnmarshalJSON(data []byte) error {
+	var s string
+	if err := json.Unmarshal(data, &s); err == nil {
+		*n = Nonces{s}
+		return nil
+	}
+	var ss []string
+	if err := json.Unmarshal(data, &ss); err != nil {
+		return fmt.Errorf("eat_nonce must be a string or an array of strings: %w", err)
+	}
+	*n = ss
+	return nil
+}
+
+// Claims are the claims of a Google Cloud Attestation token that this package
+// reads.
+type Claims struct {
+	jose.Claims
+	EATNonce              Nonces   `json:"eat_nonce"`
+	HWModel               string   `json:"hwmodel"`
+	SWName                string   `json:"swname"`
+	DebugStatus           string   `json:"dbgstat"`
+	GoogleServiceAccounts []string `json:"google_service_accounts"`
+	Submods               struct {
+		ConfidentialSpace struct {
+			SupportAttributes []string `json:"support_attributes"`
+		} `json:"confidential_space"`
+		Container struct {
+			ImageDigest     string `json:"image_digest"`
+			ImageSignatures []struct {
+				KeyID string `json:"key_id"`
+			} `json:"image_signatures"`
+		} `json:"container"`
+		GCE struct {
+			ProjectID  string `json:"project_id"`
+			InstanceID string `json:"instance_id"`
+		} `json:"gce"`
+	} `json:"submods"`
+}
+
+// Token is a verified Google Cloud Attestation token.
+type Token struct {
+	// Leaf is the certificate that signed the token.
+	Leaf *x509.Certificate
+	// Claims are the claims this package reads.
+	Claims Claims
+	// RawClaims are all the claims of the token.
+	RawClaims map[string]any
+}
+
+// Result returns the token's claims as an attestation result.
+func (t *Token) Result() *attestation.ConfidentialSpace {
+	return &attestation.ConfidentialSpace{
+		Claims:             t.RawClaims,
+		SignerSerialNumber: t.Leaf.SerialNumber.String(),
+	}
+}
+
+// Options are the options Verify verifies a token with.
+type Options struct {
+	// Roots are the roots of Google Cloud Attestation's PKI. They are
+	// required.
+	Roots *x509.CertPool
+	// Audience is the audience the token must have been requested for.
+	Audience string
+	// MaxTokenAge is the maximum age of the token. It defaults to
+	// DefaultMaxTokenAge.
+	MaxTokenAge time.Duration
+	// MinNonces is the minimum number of nonces the token must carry. It
+	// defaults to 1.
+	MinNonces int
+	// Now is the time the token is verified at. It defaults to the current
+	// time.
+	Now time.Time
+}
+
+// Verify verifies a Google Cloud Attestation PKI token: the x5c chain of the
+// token against the roots, its RS256 signature with the leaf of the chain, the
+// issuer, the audience, the exp, nbf and iat claims, the age of the token, the
+// number of nonces, and that the workload has not been debuggable since boot.
+// Errors of the token match attestation.ErrInvalidEvidence.
+func Verify(token string, opts Options) (*Token, error) {
+	// A nil pool would make x509 use the system roots.
+	if opts.Roots == nil {
+		return nil, errors.New("no roots to verify the attestation token with")
+	}
+	if opts.MaxTokenAge <= 0 {
+		opts.MaxTokenAge = DefaultMaxTokenAge
+	}
+	if opts.MinNonces <= 0 {
+		opts.MinNonces = 1
+	}
+	if opts.Now.IsZero() {
+		opts.Now = time.Now()
+	}
+
+	jwt, err := jose.ParseSigned(token)
+	if err != nil {
+		return nil, attestation.Invalidf("error parsing attestation token: %w", err)
+	}
+	if len(jwt.Headers) != 1 {
+		return nil, attestation.Invalidf("attestation token must have exactly one signature")
+	}
+	header := jwt.Headers[0]
+	if header.Algorithm != jose.RS256 {
+		return nil, attestation.Invalidf("unsupported attestation token algorithm %q", header.Algorithm)
+	}
+
+	chains, err := header.Certificates(x509.VerifyOptions{
+		Roots:       opts.Roots,
+		CurrentTime: opts.Now,
+		KeyUsages:   []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
+	})
+	if err != nil {
+		return nil, attestation.Invalidf("attestation token x5c is not valid: %w", err)
+	}
+	leaf := chains[0][0]
+	if _, ok := leaf.PublicKey.(*rsa.PublicKey); !ok {
+		return nil, attestation.Invalidf("attestation token x5c leaf has an unsupported key type %T", leaf.PublicKey)
+	}
+
+	var (
+		claims    Claims
+		rawClaims map[string]any
+	)
+	if err := jwt.Claims(leaf.PublicKey, &claims, &rawClaims); err != nil {
+		return nil, attestation.Invalidf("error verifying attestation token: %w", err)
+	}
+	if err := claims.ValidateWithLeeway(jose.Expected{
+		Issuer:   Issuer,
+		Audience: jose.Audience{opts.Audience},
+		Time:     opts.Now,
+	}, Leeway); err != nil {
+		return nil, attestation.Invalidf("attestation token is not valid: %w", err)
+	}
+	if claims.Expiry == nil || claims.IssuedAt == nil {
+		return nil, attestation.Invalidf("attestation token must have exp and iat claims")
+	}
+	if age := opts.Now.Sub(claims.IssuedAt.Time()); age > opts.MaxTokenAge {
+		return nil, attestation.Invalidf("attestation token is too old: issued %s ago, the maximum is %s", age, opts.MaxTokenAge)
+	}
+	if n := len(claims.EATNonce); n < opts.MinNonces || n > MaxNonces {
+		return nil, attestation.Invalidf("attestation token must have between %d and %d nonces, it has %d", opts.MinNonces, MaxNonces, n)
+	}
+	if claims.DebugStatus != DebugDisabled {
+		return nil, attestation.Invalidf("attestation token dbgstat is %q, not %q", claims.DebugStatus, DebugDisabled)
+	}
+
+	return &Token{
+		Leaf:      leaf,
+		Claims:    claims,
+		RawClaims: rawClaims,
+	}, nil
+}
+
+// Expectations are the values a verified token's workload must match. Each one
+// that is set must be met. The field names follow the claims they are compared
+// with.
+type Expectations struct {
+	// ImageDigests are the allowed values of the
+	// submods.container.image_digest claim.
+	ImageDigests []string `json:"imageDigests,omitempty"`
+
+	// ImageSignerKeyIDs are the allowed values of the key_id of an element
+	// of the submods.container.image_signatures claim. If ImageDigests is
+	// also set, matching either is enough.
+	ImageSignerKeyIDs []string `json:"imageSignerKeyIDs,omitempty"`
+
+	// RequireSupportAttributes are the values that must all be present in
+	// the submods.confidential_space.support_attributes claim, for example
+	// STABLE.
+	RequireSupportAttributes []string `json:"requireSupportAttributes,omitempty"`
+
+	// HWModels are the allowed values of the hwmodel claim, for example
+	// GCP_INTEL_TDX.
+	HWModels []string `json:"hwmodels,omitempty"`
+
+	// SWNames are the allowed values of the swname claim, for example
+	// CONFIDENTIAL_SPACE.
+	SWNames []string `json:"swnames,omitempty"`
+
+	// ProjectIDs are the allowed values of the submods.gce.project_id claim.
+	ProjectIDs []string `json:"projectIDs,omitempty"`
+
+	// ServiceAccounts are the allowed service accounts; at least one of them
+	// must be present in the google_service_accounts claim.
+	ServiceAccounts []string `json:"serviceAccounts,omitempty"`
+}
+
+// Validate returns an error if an expectation has an empty value.
+func (e *Expectations) Validate() error {
+	if e == nil {
+		return nil
+	}
+	for _, f := range []struct {
+		name   string
+		values []string
+	}{
+		{"imageDigests", e.ImageDigests},
+		{"imageSignerKeyIDs", e.ImageSignerKeyIDs},
+		{"requireSupportAttributes", e.RequireSupportAttributes},
+		{"hwmodels", e.HWModels},
+		{"swnames", e.SWNames},
+		{"projectIDs", e.ProjectIDs},
+		{"serviceAccounts", e.ServiceAccounts},
+	} {
+		if slices.Contains(f.values, "") {
+			return fmt.Errorf("%s cannot contain empty values", f.name)
+		}
+	}
+	return nil
+}
+
+// Check returns an error, which matches attestation.ErrInvalidEvidence, if the
+// claims do not meet the expectations. It returns nil if none are set.
+func (e *Expectations) Check(c *Claims) error {
+	if e == nil {
+		return nil
+	}
+	if len(e.ImageDigests) > 0 || len(e.ImageSignerKeyIDs) > 0 {
+		allowed := slices.Contains(e.ImageDigests, c.Submods.Container.ImageDigest)
+		for _, sig := range c.Submods.Container.ImageSignatures {
+			if slices.Contains(e.ImageSignerKeyIDs, sig.KeyID) {
+				allowed = true
+			}
+		}
+		if !allowed {
+			return attestation.Invalidf("container image %q is neither an allowed digest nor signed by an allowed key", c.Submods.Container.ImageDigest)
+		}
+	}
+	for _, a := range e.RequireSupportAttributes {
+		if !slices.Contains(c.Submods.ConfidentialSpace.SupportAttributes, a) {
+			return attestation.Invalidf("support attribute %q is not present", a)
+		}
+	}
+	if len(e.HWModels) > 0 && !slices.Contains(e.HWModels, c.HWModel) {
+		return attestation.Invalidf("hwmodel %q is not allowed", c.HWModel)
+	}
+	if len(e.SWNames) > 0 && !slices.Contains(e.SWNames, c.SWName) {
+		return attestation.Invalidf("swname %q is not allowed", c.SWName)
+	}
+	if len(e.ProjectIDs) > 0 && !slices.Contains(e.ProjectIDs, c.Submods.GCE.ProjectID) {
+		return attestation.Invalidf("project %q is not allowed", c.Submods.GCE.ProjectID)
+	}
+	if len(e.ServiceAccounts) > 0 && !slices.ContainsFunc(c.GoogleServiceAccounts, func(sa string) bool {
+		return slices.Contains(e.ServiceAccounts, sa)
+	}) {
+		return attestation.Invalidf("none of the service accounts %q is allowed", c.GoogleServiceAccounts)
+	}
+	return nil
+}

+ 234 - 0
attestation/confidentialspace/confidentialspace_test.go

@@ -0,0 +1,234 @@
+package confidentialspace
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/json"
+	"errors"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"go.step.sm/crypto/jose"
+	"go.step.sm/crypto/minica"
+
+	"github.com/smallstep/certificates/attestation"
+	cstest "github.com/smallstep/certificates/attestation/confidentialspace/confidentialspacetest"
+)
+
+const testAudience = "https://ca.example.com/acme/acme/directory"
+
+func TestNonces_UnmarshalJSON(t *testing.T) {
+	tests := []struct {
+		name    string
+		data    string
+		want    Nonces
+		wantErr bool
+	}{
+		{"ok string", `"nonce-0123"`, Nonces{"nonce-0123"}, false},
+		{"ok array", `["nonce-0123","nonce-4567"]`, Nonces{"nonce-0123", "nonce-4567"}, false},
+		{"fail number", `123`, nil, true},
+		{"fail object", `{"a":"b"}`, nil, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			var got Nonces
+			err := json.Unmarshal([]byte(tt.data), &got)
+			if tt.wantErr {
+				assert.Error(t, err)
+				return
+			}
+			require.NoError(t, err)
+			assert.Equal(t, tt.want, got)
+		})
+	}
+}
+
+func TestVerify(t *testing.T) {
+	pki := cstest.New(t)
+	otherPKI := cstest.New(t)
+	now := time.Now().Truncate(time.Second)
+	nonces := []string{"nonce-for-key-authorization", "nonce-for-key-digest"}
+
+	ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	require.NoError(t, err)
+	ca, err := minica.New(minica.WithName("Test EC Attestation"))
+	require.NoError(t, err)
+	ecLeaf, err := ca.Sign(&x509.Certificate{Subject: pkix.Name{CommonName: "EC Signer"}, PublicKey: ecKey.Public()})
+	require.NoError(t, err)
+	ecRoots := x509.NewCertPool()
+	ecRoots.AddCert(ca.Root)
+	otherRSAKey, err := rsa.GenerateKey(rand.Reader, 2048)
+	require.NoError(t, err)
+
+	claims := func() map[string]any { return cstest.Claims(now, testAudience, nonces...) }
+	claimsWith := func(fn func(c map[string]any)) map[string]any {
+		c := claims()
+		fn(c)
+		return c
+	}
+	defaultOpts := Options{
+		Roots:     pki.Roots(),
+		Audience:  testAudience,
+		MinNonces: 2,
+		Now:       now,
+	}
+
+	tests := []struct {
+		name    string
+		token   string
+		opts    func(o *Options)
+		wantErr string
+	}{
+		{"ok", pki.Mint(t, claims()), nil, ""},
+		{"ok audience array", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["aud"] = []string{"other", testAudience}
+		})), nil, ""},
+		{"ok six nonces", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["eat_nonce"] = append(nonces, "nonce-2-pass", "nonce-3-pass", "nonce-4-pass", "nonce-5-pass")
+		})), nil, ""},
+		{"ok expired within leeway", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["iat"] = now.Add(-2 * time.Minute).Unix()
+			c["exp"] = now.Add(-30 * time.Second).Unix()
+		})), nil, ""},
+		{"ok default min nonces", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["eat_nonce"] = "single-nonce"
+		})), func(o *Options) { o.MinNonces = 0 }, ""},
+		{"fail nil roots", pki.Mint(t, claims()), func(o *Options) { o.Roots = nil }, "no roots"},
+		{"fail parse", "not-a-token", nil, "error parsing attestation token"},
+		{"fail algorithm", cstest.Mint(t, ecKey, jose.ES256, []*x509.Certificate{ecLeaf, ca.Intermediate, ca.Root}, claims()),
+			func(o *Options) { o.Roots = ecRoots }, `unsupported attestation token algorithm "ES256"`},
+		{"fail no x5c", cstest.Mint(t, pki.LeafKey, jose.RS256, nil, claims()), nil, "attestation token x5c is not valid"},
+		{"fail untrusted root", otherPKI.Mint(t, claims()), nil, "attestation token x5c is not valid"},
+		{"fail leaf key type", cstest.Mint(t, otherRSAKey, jose.RS256, []*x509.Certificate{ecLeaf, ca.Intermediate, ca.Root}, claims()),
+			func(o *Options) { o.Roots = ecRoots }, "attestation token x5c leaf has an unsupported key type"},
+		{"fail signature", cstest.Mint(t, otherRSAKey, jose.RS256, pki.Chain(), claims()), nil, "error verifying attestation token"},
+		{"fail leaf expired", pki.Mint(t, claims()), func(o *Options) { o.Now = now.Add(48 * time.Hour) },
+			"attestation token x5c is not valid"},
+		{"fail issuer", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["iss"] = "https://portal.trustauthority.intel.com"
+		})), nil, "attestation token is not valid"},
+		{"fail audience", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["aud"] = "https://sts.googleapis.com"
+		})), nil, "attestation token is not valid"},
+		{"fail expired", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["iat"] = now.Add(-3 * time.Minute).Unix()
+			c["exp"] = now.Add(-2 * time.Minute).Unix()
+		})), nil, "attestation token is not valid"},
+		{"fail not yet valid", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["nbf"] = now.Add(2 * time.Minute).Unix()
+		})), nil, "attestation token is not valid"},
+		{"fail issued in the future", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["iat"] = now.Add(2 * time.Minute).Unix()
+		})), nil, "attestation token is not valid"},
+		{"fail missing exp", pki.Mint(t, claimsWith(func(c map[string]any) { delete(c, "exp") })), nil,
+			"attestation token must have exp and iat claims"},
+		{"fail missing iat", pki.Mint(t, claimsWith(func(c map[string]any) { delete(c, "iat") })), nil,
+			"attestation token must have exp and iat claims"},
+		{"fail too old", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["iat"] = now.Add(-10 * time.Minute).Unix()
+		})), nil, "attestation token is too old"},
+		{"fail single nonce", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["eat_nonce"] = "nonce-for-key-authorization"
+		})), nil, "attestation token must have between 2 and 6 nonces, it has 1"},
+		{"fail no nonces", pki.Mint(t, claimsWith(func(c map[string]any) { delete(c, "eat_nonce") })), nil,
+			"attestation token must have between 2 and 6 nonces, it has 0"},
+		{"fail seven nonces", pki.Mint(t, claimsWith(func(c map[string]any) {
+			c["eat_nonce"] = append(nonces, "nonce-2", "nonce-3", "nonce-4", "nonce-5", "nonce-6")
+		})), nil, "attestation token must have between 2 and 6 nonces, it has 7"},
+		{"fail debuggable", pki.Mint(t, claimsWith(func(c map[string]any) { c["dbgstat"] = "enabled" })), nil,
+			`attestation token dbgstat is "enabled"`},
+		{"fail no dbgstat", pki.Mint(t, claimsWith(func(c map[string]any) { delete(c, "dbgstat") })), nil,
+			`attestation token dbgstat is ""`},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			opts := defaultOpts
+			if tt.opts != nil {
+				tt.opts(&opts)
+			}
+			got, err := Verify(tt.token, opts)
+			if tt.wantErr != "" {
+				assert.ErrorContains(t, err, tt.wantErr)
+				// A missing root is the caller's error, not the token's.
+				assert.Equal(t, opts.Roots != nil, errors.Is(err, attestation.ErrInvalidEvidence))
+				return
+			}
+			require.NoError(t, err)
+			assert.Equal(t, pki.Leaf, got.Leaf)
+			assert.Equal(t, cstest.InstanceID, got.Claims.Submods.GCE.InstanceID)
+			assert.Equal(t, "GCP_INTEL_TDX", got.RawClaims["hwmodel"])
+			result := got.Result()
+			assert.Equal(t, got.RawClaims, result.Claims)
+			assert.Equal(t, pki.Leaf.SerialNumber.String(), result.SignerSerialNumber)
+		})
+	}
+
+	t.Run("ok default max age and time", func(t *testing.T) {
+		_, err := Verify(pki.Mint(t, cstest.Claims(time.Now(), testAudience, nonces...)), Options{
+			Roots:    pki.Roots(),
+			Audience: testAudience,
+		})
+		require.NoError(t, err)
+	})
+}
+
+func TestExpectations(t *testing.T) {
+	pki := cstest.New(t)
+	now := time.Now()
+	tok, err := Verify(pki.Mint(t, cstest.Claims(now, testAudience, "nonce-0", "nonce-1")), Options{
+		Roots:    pki.Roots(),
+		Audience: testAudience,
+		Now:      now,
+	})
+	require.NoError(t, err)
+	claims := &tok.Claims
+
+	tests := []struct {
+		name    string
+		e       *Expectations
+		wantErr string
+	}{
+		{"ok nil", nil, ""},
+		{"ok empty", &Expectations{}, ""},
+		{"ok digest", &Expectations{ImageDigests: []string{"sha256:0f0e0d0c0b0a09080706050403020100"}}, ""},
+		{"ok signer", &Expectations{ImageSignerKeyIDs: []string{"c0ffee"}}, ""},
+		{"ok digest or signer", &Expectations{ImageDigests: []string{"sha256:other"}, ImageSignerKeyIDs: []string{"c0ffee"}}, ""},
+		{"ok all", &Expectations{
+			RequireSupportAttributes: []string{"STABLE", "USABLE"},
+			HWModels:                 []string{"GCP_AMD_SEV", "GCP_INTEL_TDX"},
+			SWNames:                  []string{"CONFIDENTIAL_SPACE"},
+			ProjectIDs:               []string{"my-project"},
+			ServiceAccounts:          []string{"other@my-project.iam.gserviceaccount.com", "workload@my-project.iam.gserviceaccount.com"},
+		}, ""},
+		{"fail image", &Expectations{ImageDigests: []string{"sha256:other"}, ImageSignerKeyIDs: []string{"other"}},
+			"is neither an allowed digest nor signed by an allowed key"},
+		{"fail support attribute", &Expectations{RequireSupportAttributes: []string{"EXPERIMENTAL"}}, `support attribute "EXPERIMENTAL"`},
+		{"fail hwmodel", &Expectations{HWModels: []string{"GCP_AMD_SEV"}}, `hwmodel "GCP_INTEL_TDX" is not allowed`},
+		{"fail swname", &Expectations{SWNames: []string{"OTHER"}}, `swname "CONFIDENTIAL_SPACE" is not allowed`},
+		{"fail project", &Expectations{ProjectIDs: []string{"other"}}, `project "my-project" is not allowed`},
+		{"fail service account", &Expectations{ServiceAccounts: []string{"other@my-project.iam.gserviceaccount.com"}}, "none of the service accounts"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			err := tt.e.Check(claims)
+			if tt.wantErr == "" {
+				assert.NoError(t, err)
+				return
+			}
+			assert.ErrorContains(t, err, tt.wantErr)
+			assert.ErrorIs(t, err, attestation.ErrInvalidEvidence)
+		})
+	}
+}
+
+func TestExpectations_Validate(t *testing.T) {
+	assert.NoError(t, (*Expectations)(nil).Validate())
+	assert.NoError(t, (&Expectations{HWModels: []string{"GCP_INTEL_TDX"}}).Validate())
+	assert.EqualError(t, (&Expectations{SWNames: []string{""}}).Validate(), "swnames cannot contain empty values")
+}

+ 144 - 0
attestation/confidentialspace/confidentialspacetest/confidentialspacetest.go

@@ -0,0 +1,144 @@
+// Package confidentialspacetest mints Google Cloud Attestation PKI tokens with
+// a synthetic PKI, for tests of code that verifies them.
+package confidentialspacetest
+
+import (
+	"crypto"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/base64"
+	"encoding/pem"
+	"testing"
+	"time"
+
+	"go.step.sm/crypto/jose"
+	"go.step.sm/crypto/minica"
+)
+
+// InstanceID is the Compute Engine instance id in the claims Claims returns.
+const InstanceID = "1234567890123456789"
+
+// PKI is a synthetic Google Cloud Attestation PKI: a root, an intermediate and
+// an RSA leaf that signs tokens.
+type PKI struct {
+	Root         *x509.Certificate
+	Intermediate *x509.Certificate
+	Leaf         *x509.Certificate
+	LeafKey      crypto.Signer
+}
+
+// New returns a new PKI.
+func New(t testing.TB) *PKI {
+	t.Helper()
+	ca, err := minica.New(minica.WithName("Test Attestation"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	key, err := rsa.GenerateKey(rand.Reader, 2048)
+	if err != nil {
+		t.Fatal(err)
+	}
+	leaf, err := ca.Sign(&x509.Certificate{
+		Subject:   pkix.Name{CommonName: "Test Attestation Signer"},
+		PublicKey: key.Public(),
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	return &PKI{
+		Root:         ca.Root,
+		Intermediate: ca.Intermediate,
+		Leaf:         leaf,
+		LeafKey:      key,
+	}
+}
+
+// RootPEM returns the PKI's root as PEM.
+func (p *PKI) RootPEM() []byte {
+	return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: p.Root.Raw})
+}
+
+// Roots returns a pool with the PKI's root.
+func (p *PKI) Roots() *x509.CertPool {
+	pool := x509.NewCertPool()
+	pool.AddCert(p.Root)
+	return pool
+}
+
+// Chain returns the PKI's chain, leaf first.
+func (p *PKI) Chain() []*x509.Certificate {
+	return []*x509.Certificate{p.Leaf, p.Intermediate, p.Root}
+}
+
+// Mint signs the claims as a PKI token with the leaf of the PKI.
+func (p *PKI) Mint(t testing.TB, claims map[string]any) string {
+	t.Helper()
+	return Mint(t, p.LeafKey, jose.RS256, p.Chain(), claims)
+}
+
+// Mint signs the claims with the given key and algorithm, with the chain, if
+// any, in the x5c header.
+func Mint(t testing.TB, key crypto.Signer, alg jose.SignatureAlgorithm, chain []*x509.Certificate, claims map[string]any) string {
+	t.Helper()
+	so := new(jose.SignerOptions).WithType("JWT")
+	if len(chain) > 0 {
+		x5c := make([]string, len(chain))
+		for i, c := range chain {
+			x5c[i] = base64.StdEncoding.EncodeToString(c.Raw)
+		}
+		so = so.WithHeader("x5c", x5c)
+	}
+	signer, err := jose.NewSigner(jose.SigningKey{Algorithm: alg, Key: key}, so)
+	if err != nil {
+		t.Fatal(err)
+	}
+	token, err := jose.Signed(signer).Claims(claims).CompactSerialize()
+	if err != nil {
+		t.Fatal(err)
+	}
+	return token
+}
+
+// Claims returns the claims of a Confidential Space token, following the claims
+// Google documents, issued at now.
+func Claims(now time.Time, audience string, nonces ...string) map[string]any {
+	return map[string]any{
+		"iss":                     "https://confidentialcomputing.googleapis.com",
+		"sub":                     "https://www.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/instances/workload-1",
+		"aud":                     audience,
+		"iat":                     now.Unix(),
+		"nbf":                     now.Unix(),
+		"exp":                     now.Add(time.Hour).Unix(),
+		"eat_nonce":               nonces,
+		"eat_profile":             "https://cloud.google.com/confidential-computing/confidential-space/docs/reference/token-claims",
+		"hwmodel":                 "GCP_INTEL_TDX",
+		"swname":                  "CONFIDENTIAL_SPACE",
+		"swversion":               []string{"260900"},
+		"secboot":                 true,
+		"dbgstat":                 "disabled-since-boot",
+		"attester_tcb":            []string{"INTEL"},
+		"google_service_accounts": []string{"workload@my-project.iam.gserviceaccount.com"},
+		"submods": map[string]any{
+			"confidential_space": map[string]any{
+				"support_attributes": []string{"LATEST", "STABLE", "USABLE"},
+			},
+			"container": map[string]any{
+				"image_reference": "us-docker.pkg.dev/my-project/workload/workload:1",
+				"image_digest":    "sha256:0f0e0d0c0b0a09080706050403020100",
+				"image_signatures": []map[string]any{
+					{"key_id": "c0ffee", "signature_algorithm": "ECDSA_P256_SHA256", "signature": "c2ln"},
+				},
+				"restart_policy": "Never",
+			},
+			"gce": map[string]any{
+				"project_id":     "my-project",
+				"project_number": "123456789012",
+				"zone":           "us-central1-a",
+				"instance_id":    InstanceID,
+				"instance_name":  "workload-1",
+			},
+		},
+	}
+}

+ 227 - 0
attestation/sevsnp/sevsnp.go

@@ -0,0 +1,227 @@
+// Package sevsnp verifies AMD SEV-SNP attestation reports.
+package sevsnp
+
+import (
+	"bytes"
+	"context"
+	"crypto/x509"
+	"encoding/hex"
+	"encoding/pem"
+	"errors"
+	"fmt"
+	"strings"
+	"sync"
+	"sync/atomic"
+	"time"
+
+	"github.com/google/go-sev-guest/abi"
+	"github.com/google/go-sev-guest/kds"
+	spb "github.com/google/go-sev-guest/proto/sevsnp"
+	sevverify "github.com/google/go-sev-guest/verify"
+	sevtrust "github.com/google/go-sev-guest/verify/trust"
+
+	"github.com/smallstep/certificates/attestation"
+)
+
+// ReportDataSize is the size of an SEV-SNP report's report data.
+const ReportDataSize = 64
+
+// Verifier verifies AMD SEV-SNP attestation reports: the report's signature by
+// the chip's VCEK or the provider's VLEK, and that key's chain through the ASK
+// or ASVK to the ARK of the product line. Certificates the workload does not
+// send are fetched from AMD's key distribution service, as are the revocation
+// lists. Reports from guests whose policy allows debugging are refused. The TCB
+// versions are reported, not checked against a minimum.
+type Verifier struct {
+	// roots are the ARK, ASK and ASVK certificates to trust per product
+	// line: the configured ones, or AMD's.
+	roots  map[string][]*sevtrust.AMDRootCerts
+	getter sevtrust.HTTPSGetter
+	// checkRevocations is always true outside of tests.
+	checkRevocations bool
+	now              func() time.Time
+}
+
+// amdRoots are AMD's ARK, ASK and ASVK certificates for every product line,
+// from the VCEK and VLEK bundles embedded in go-sev-guest.
+var amdRoots = sync.OnceValues(func() (map[string][]*sevtrust.AMDRootCerts, error) {
+	return parseRoots(bytes.Join([][]byte{
+		sevtrust.AskArkMilanVcekBytes, sevtrust.AskArkMilanVlekBytes,
+		sevtrust.AskArkGenoaVcekBytes, sevtrust.AskArkGenoaVlekBytes,
+		sevtrust.AskArkTurinVcekBytes, sevtrust.AskArkTurinVlekBytes,
+	}, []byte("\n")))
+})
+
+// New returns a Verifier that fetches certificates and revocation lists with
+// the given getter. If roots, a PEM bundle of ARK, ASK and ASVK certificates, is
+// not empty, it replaces AMD's roots.
+func New(roots []byte, getter sevtrust.HTTPSGetter) (*Verifier, error) {
+	v := &Verifier{
+		getter:           getter,
+		checkRevocations: true,
+		now:              time.Now,
+	}
+	// The roots are always passed to go-sev-guest. Before v0.15.0, without
+	// them it took the ARK and ASK from the evidence's own certificate table
+	// and, because its embedded roots hold no AMD SEV format certificates to
+	// cross-check them with, trusted whatever ARK the workload sent.
+	var err error
+	if len(roots) > 0 {
+		v.roots, err = parseRoots(roots)
+	} else {
+		v.roots, err = amdRoots()
+	}
+	if err != nil {
+		return nil, err
+	}
+	return v, nil
+}
+
+// parseRoots reads the ARK, ASK and ASVK certificates in a PEM bundle and
+// groups them by product line, which AMD names in their common names: ARK-Milan,
+// SEV-Milan and SEV-VLEK-Milan for Milan. Each product line needs its ARK and at
+// least one of its ASK and ASVK.
+func parseRoots(data []byte) (map[string][]*sevtrust.AMDRootCerts, error) {
+	certs := make(map[string]*sevtrust.ProductCerts)
+	line := func(name string) *sevtrust.ProductCerts {
+		if certs[name] == nil {
+			certs[name] = new(sevtrust.ProductCerts)
+		}
+		return certs[name]
+	}
+	for rest := data; len(rest) > 0; {
+		var block *pem.Block
+		if block, rest = pem.Decode(rest); block == nil {
+			break
+		}
+		if block.Type != "CERTIFICATE" {
+			continue
+		}
+		cert, err := x509.ParseCertificate(block.Bytes)
+		if err != nil {
+			return nil, fmt.Errorf("error parsing the sev-snp roots: %w", err)
+		}
+		switch cn := cert.Subject.CommonName; {
+		case strings.HasPrefix(cn, "ARK-"):
+			line(strings.TrimPrefix(cn, "ARK-")).Ark = cert
+		case strings.HasPrefix(cn, "SEV-VLEK-"):
+			line(strings.TrimPrefix(cn, "SEV-VLEK-")).Asvk = cert
+		case strings.HasPrefix(cn, "SEV-"):
+			line(strings.TrimPrefix(cn, "SEV-")).Ask = cert
+		default:
+			return nil, fmt.Errorf("sev-snp roots: %q is not an AMD ARK, ASK or ASVK", cn)
+		}
+	}
+	if len(certs) == 0 {
+		return nil, errors.New("no certificates found in the sev-snp roots")
+	}
+	roots := make(map[string][]*sevtrust.AMDRootCerts, len(certs))
+	for name, pc := range certs {
+		if pc.Ark == nil || (pc.Ask == nil && pc.Asvk == nil) {
+			return nil, fmt.Errorf("sev-snp roots: product line %s needs its ARK and its ASK or ASVK", name)
+		}
+		r := sevtrust.AMDRootCertsProduct(name)
+		r.ProductCerts = pc
+		roots[name] = []*sevtrust.AMDRootCerts{r}
+	}
+	return roots, nil
+}
+
+// Verify verifies an SEV-SNP attestation report, with the certificate table an
+// extended report returns if it is not empty, and returns the report's
+// measurements and its report data. Errors of the report match
+// attestation.ErrInvalidEvidence; a failure to fetch certificates or revocation
+// lists does not.
+func (v *Verifier) Verify(ctx context.Context, rawReport, certTable []byte) (*attestation.SEVSNP, []byte, error) {
+	report, err := abi.ReportToProto(rawReport)
+	if err != nil {
+		return nil, nil, attestation.Invalidf("error parsing sev-snp report: %w", err)
+	}
+	att := &spb.Attestation{Report: report}
+	if len(certTable) > 0 {
+		var table abi.CertTable
+		if err := table.Unmarshal(certTable); err != nil {
+			return nil, nil, attestation.Invalidf("error parsing sev-snp certificate table: %w", err)
+		}
+		att.CertificateChain = table.Proto()
+	}
+
+	getter := &recordingGetter{getter: v.getter}
+	opts := &sevverify.Options{
+		CheckRevocations: v.checkRevocations,
+		Getter:           getter,
+		Now:              v.now(),
+		TrustedRoots:     v.roots,
+	}
+	if err := sevverify.SnpAttestationContext(ctx, att, opts); err != nil {
+		if getter.failed.Load() {
+			return nil, nil, fmt.Errorf("error fetching sev-snp certificates: %w", err)
+		}
+		return nil, nil, attestation.Invalidf("error verifying sev-snp report: %w", err)
+	}
+
+	policy, err := abi.ParseSnpPolicy(report.GetPolicy())
+	if err != nil {
+		return nil, nil, attestation.Invalidf("error parsing sev-snp guest policy: %w", err)
+	}
+	if policy.Debug {
+		return nil, nil, attestation.Invalidf("sev-snp report is from a guest whose policy allows debugging")
+	}
+	signer, err := abi.ParseSignerInfo(report.GetSignerInfo())
+	if err != nil {
+		return nil, nil, attestation.Invalidf("error parsing sev-snp signer info: %w", err)
+	}
+	product := kds.ProductLine(att.GetProduct())
+	if fms := report.GetCpuid1EaxFms(); fms != 0 {
+		product = kds.ProductLineFromFms(fms)
+	}
+
+	reportData := report.GetReportData()
+	if len(reportData) != ReportDataSize {
+		return nil, nil, attestation.Invalidf("sev-snp report data has %d bytes, not %d", len(reportData), ReportDataSize)
+	}
+	return &attestation.SEVSNP{
+		Measurement:     hex.EncodeToString(report.GetMeasurement()),
+		HostData:        hex.EncodeToString(report.GetHostData()),
+		IDKeyDigest:     hex.EncodeToString(report.GetIdKeyDigest()),
+		AuthorKeyDigest: hex.EncodeToString(report.GetAuthorKeyDigest()),
+		FamilyID:        hex.EncodeToString(report.GetFamilyId()),
+		ImageID:         hex.EncodeToString(report.GetImageId()),
+		GuestSVN:        report.GetGuestSvn(),
+		Policy:          report.GetPolicy(),
+		VMPL:            report.GetVmpl(),
+		CurrentTCB:      report.GetCurrentTcb(),
+		ReportedTCB:     report.GetReportedTcb(),
+		LaunchTCB:       report.GetLaunchTcb(),
+		ChipID:          hex.EncodeToString(report.GetChipId()),
+		SigningKey:      strings.ToLower(signer.SigningKey.String()),
+		Product:         product,
+	}, reportData, nil
+}
+
+// recordingGetter records whether a fetch failed, so that a report that cannot
+// be verified because a service is unreachable is not called invalid.
+type recordingGetter struct {
+	getter sevtrust.HTTPSGetter
+	failed atomic.Bool
+}
+
+func (g *recordingGetter) Get(url string) ([]byte, error) {
+	body, err := g.getter.Get(url)
+	if err != nil {
+		g.failed.Store(true)
+	}
+	return body, err
+}
+
+func (g *recordingGetter) GetContext(ctx context.Context, url string) ([]byte, error) {
+	cg, ok := g.getter.(sevtrust.ContextHTTPSGetter)
+	if !ok {
+		return g.Get(url)
+	}
+	body, err := cg.GetContext(ctx, url)
+	if err != nil {
+		g.failed.Store(true)
+	}
+	return body, err
+}

+ 122 - 0
attestation/sevsnp/sevsnp_test.go

@@ -0,0 +1,122 @@
+//go:build unix
+
+package sevsnp
+
+import (
+	"context"
+	"encoding/pem"
+	"errors"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	"github.com/smallstep/certificates/attestation"
+	"github.com/smallstep/certificates/attestation/sevsnp/sevsnptest"
+)
+
+// failingGetter fails every fetch, so a test fails if the verifier needs AMD's
+// key distribution service, and stands for an unreachable service.
+type failingGetter struct{}
+
+func (failingGetter) Get(url string) ([]byte, error) {
+	return nil, errors.New("unexpected fetch of " + url)
+}
+
+func newVerifier(t *testing.T, roots []byte) *Verifier {
+	t.Helper()
+	v, err := New(roots, failingGetter{})
+	require.NoError(t, err)
+	v.checkRevocations = false
+	return v
+}
+
+func TestVerifier(t *testing.T) {
+	s := sevsnptest.New(t, false)
+	other := sevsnptest.New(t, true)
+	reportData := make([]byte, ReportDataSize)
+	for i := range reportData {
+		reportData[i] = byte(i)
+	}
+
+	t.Run("ok", func(t *testing.T) {
+		got, gotReportData, err := newVerifier(t, s.Roots).Verify(context.Background(), s.Report(t, reportData, false), s.CertTable)
+		require.NoError(t, err)
+		assert.Equal(t, reportData, gotReportData)
+		assert.Len(t, got.Measurement, 96)
+		assert.Len(t, got.HostData, 64)
+		assert.Len(t, got.ChipID, 128)
+		assert.Equal(t, "vcek", got.SigningKey)
+		assert.Equal(t, "Milan", got.Product)
+	})
+
+	tests := []struct {
+		name        string
+		v           *Verifier
+		report      []byte
+		certTable   []byte
+		wantErr     string
+		wantInvalid bool
+	}{
+		{"fail debug", newVerifier(t, s.Roots), s.Report(t, reportData, true), s.CertTable,
+			"policy allows debugging", true},
+		// A report under the workload's own ARK, sent in its certificate
+		// table, is not trusted when the verifier has AMD's roots.
+		{"fail amd roots", newVerifier(t, nil), s.Report(t, reportData, false), s.CertTable,
+			"could not be verified by any trusted roots", true},
+		// go-sev-guest before v0.15.0 trusted the evidence's own ARK when it
+		// was given no roots; the verifier never relies on that, and this
+		// case fails if the module is downgraded below the fix.
+		{"fail library default roots", &Verifier{getter: failingGetter{}, now: time.Now},
+			s.Report(t, reportData, false), s.CertTable, "could not be verified by any trusted roots", true},
+		{"fail other vcek", newVerifier(t, s.Roots), other.Report(t, reportData, false), s.CertTable,
+			"error verifying sev-snp report", true},
+		// Without a certificate table, the VCEK is fetched, and the failure
+		// to fetch it is not the report's.
+		{"fail vcek unreachable", newVerifier(t, s.Roots), s.Report(t, reportData, false), nil,
+			"error fetching sev-snp certificates", false},
+		{"fail tampered", newVerifier(t, s.Roots), func() []byte {
+			report := s.Report(t, reportData, false)
+			report[0x50] ^= 1 // the first byte of REPORT_DATA
+			return report
+		}(), s.CertTable, "error verifying sev-snp report", true},
+		{"fail parse", newVerifier(t, s.Roots), []byte("not a report"), nil, "error parsing sev-snp report", true},
+		{"fail certificate table", newVerifier(t, s.Roots), s.Report(t, reportData, false), []byte("not a table"),
+			"error parsing sev-snp certificate table", true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			_, _, err := tt.v.Verify(context.Background(), tt.report, tt.certTable)
+			assert.ErrorContains(t, err, tt.wantErr)
+			assert.Equal(t, tt.wantInvalid, errors.Is(err, attestation.ErrInvalidEvidence))
+		})
+	}
+}
+
+func TestParseRoots(t *testing.T) {
+	s := sevsnptest.New(t, false)
+	roots, err := parseRoots(s.Roots)
+	require.NoError(t, err)
+	require.Contains(t, roots, "Milan")
+	require.Len(t, roots["Milan"], 1)
+	assert.Equal(t, s.Ark(), roots["Milan"][0].ProductCerts.Ark)
+	assert.Equal(t, s.Ask(), roots["Milan"][0].ProductCerts.Ask)
+	assert.Equal(t, s.Asvk(), roots["Milan"][0].ProductCerts.Asvk)
+
+	_, err = parseRoots(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: s.Ask().Raw}))
+	assert.ErrorContains(t, err, "product line Milan needs its ARK")
+
+	_, err = parseRoots([]byte("not pem"))
+	assert.ErrorContains(t, err, "no certificates found")
+
+	amd, err := amdRoots()
+	require.NoError(t, err)
+	for _, line := range []string{"Milan", "Genoa", "Turin"} {
+		require.Len(t, amd[line], 1, line)
+		pc := amd[line][0].ProductCerts
+		assert.Equal(t, "ARK-"+line, pc.Ark.Subject.CommonName)
+		assert.Equal(t, "SEV-"+line, pc.Ask.Subject.CommonName)
+		assert.Equal(t, "SEV-VLEK-"+line, pc.Asvk.Subject.CommonName)
+	}
+}

+ 112 - 0
attestation/sevsnp/sevsnptest/sevsnptest.go

@@ -0,0 +1,112 @@
+//go:build unix
+
+// go-sev-guest's testing package, which signs reports with test-only AMD keys,
+// imports golang.org/x/sys/unix.
+
+// Package sevsnptest signs AMD SEV-SNP attestation reports with test-only AMD
+// keys, for tests of code that verifies them.
+package sevsnptest
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/x509"
+	"encoding/binary"
+	"encoding/pem"
+	"testing"
+	"time"
+
+	"github.com/google/go-sev-guest/abi"
+	"github.com/google/go-sev-guest/kds"
+	sevtest "github.com/google/go-sev-guest/testing"
+)
+
+// Signer signs SEV-SNP reports with test-only AMD keys.
+type Signer struct {
+	signer *sevtest.AmdSigner
+	// Roots is the signer's ARK, ASK and ASVK as PEM, to configure as the
+	// trusted roots.
+	Roots []byte
+	// CertTable is the signer's certificate table, as an extended report
+	// returns it.
+	CertTable []byte
+}
+
+// New returns a signer with go-sev-guest's fixed test keys, or, with otherVCEK,
+// with a VCEK of its own under the same ARK and ASK.
+func New(t testing.TB, otherVCEK bool) *Signer {
+	t.Helper()
+	keys := sevtest.DefaultAmdKeys()
+	if otherVCEK {
+		vcek, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
+		if err != nil {
+			t.Fatal(err)
+		}
+		keys.Vcek = vcek
+	}
+	created := time.Now().Add(-time.Hour)
+	b := &sevtest.AmdSignerBuilder{
+		Keys:             keys,
+		ProductName:      kds.ProductName(abi.DefaultSevProduct()),
+		CSPID:            "go-sev-guest",
+		ArkCreationTime:  created,
+		AskCreationTime:  created,
+		AsvkCreationTime: created,
+		VcekCreationTime: created,
+		VlekCreationTime: created,
+	}
+	signer, err := b.TestOnlyCertChain()
+	if err != nil {
+		t.Fatal(err)
+	}
+	certs, err := signer.CertTableBytes()
+	if err != nil {
+		t.Fatal(err)
+	}
+	return &Signer{
+		signer:    signer,
+		Roots:     pemEncode(signer.Ark, signer.Ask, signer.Asvk),
+		CertTable: certs,
+	}
+}
+
+// Ark returns the signer's ARK.
+func (s *Signer) Ark() *x509.Certificate { return s.signer.Ark }
+
+// Ask returns the signer's ASK.
+func (s *Signer) Ask() *x509.Certificate { return s.signer.Ask }
+
+// Asvk returns the signer's ASVK.
+func (s *Signer) Asvk() *x509.Certificate { return s.signer.Asvk }
+
+// Report returns a signed version 3 report with the given report data, from a
+// guest whose policy allows debugging if debug is set.
+func (s *Signer) Report(t testing.TB, reportData []byte, debug bool) []byte {
+	t.Helper()
+	raw := sevtest.CreateRawReport(&sevtest.TestReportOptions{
+		ReportData: reportData,
+		Version:    3,
+		FMS:        abi.MaskedCpuid1EaxFromSevProduct(abi.DefaultSevProduct()),
+	})
+	// The report is the start of the response CreateRawReport fills.
+	report := append([]byte(nil), raw[:abi.ReportSize]...)
+	// CreateRawReport's policy allows debugging.
+	binary.LittleEndian.PutUint64(report[0x08:0x10], abi.SnpPolicyToBytes(abi.SnpPolicy{Debug: debug, SMT: true}))
+	r, sig, err := s.signer.Sign(abi.SignedComponent(report))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := abi.SetSignature(r, sig, report); err != nil {
+		t.Fatal(err)
+	}
+	return report
+}
+
+func pemEncode(certs ...*x509.Certificate) []byte {
+	var out []byte
+	for _, c := range certs {
+		out = append(out, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Raw})...)
+	}
+	return out
+}

+ 164 - 0
attestation/tdx/tdx.go

@@ -0,0 +1,164 @@
+// Package tdx verifies Intel TDX quotes.
+package tdx
+
+import (
+	"context"
+	"crypto/x509"
+	"encoding/binary"
+	"encoding/hex"
+	"errors"
+	"fmt"
+	"sync/atomic"
+	"time"
+
+	"github.com/google/go-tdx-guest/abi"
+	"github.com/google/go-tdx-guest/pcs"
+	tdxpb "github.com/google/go-tdx-guest/proto/tdx"
+	tdxverify "github.com/google/go-tdx-guest/verify"
+	tdxtrust "github.com/google/go-tdx-guest/verify/trust"
+
+	"github.com/smallstep/certificates/attestation"
+)
+
+// ReportDataSize is the size of a TDX quote's report data.
+const ReportDataSize = 64
+
+// attributesDebug is the DEBUG bit of a TD's TD_ATTRIBUTES.
+const attributesDebug = 1 << 0
+
+// Verifier verifies Intel TDX quotes: the quote's signature by its attestation
+// key, the quoting enclave's report, the PCK certificate chain to Intel's SGX
+// root CA, and, with collateral from Intel's provisioning certification
+// service, the revocation of the chain and the TCB status of the platform and
+// the quoting enclave. go-tdx-guest refuses a TCB status other than UpToDate.
+// Quotes from debug trust domains are refused.
+type Verifier struct {
+	// roots replaces Intel's SGX root CA, embedded in go-tdx-guest, if set.
+	roots  *x509.CertPool
+	getter tdxtrust.HTTPSGetter
+	// getCollateral is always true outside of tests: without collateral the
+	// TCB status and the revocation of the PCK chain are not checked.
+	getCollateral bool
+	now           func() time.Time
+}
+
+// New returns a Verifier that fetches collateral with the given getter. If
+// roots, a PEM bundle, is not empty, it replaces Intel's root.
+func New(roots []byte, getter tdxtrust.HTTPSGetter) (*Verifier, error) {
+	v := &Verifier{
+		getter:        getter,
+		getCollateral: true,
+		now:           time.Now,
+	}
+	if len(roots) > 0 {
+		v.roots = x509.NewCertPool()
+		if !v.roots.AppendCertsFromPEM(roots) {
+			return nil, errors.New("no certificates found in the tdx roots")
+		}
+	}
+	return v, nil
+}
+
+// Verify verifies a version 4 TDX quote and returns its measurements and its
+// report data. Errors of the quote match attestation.ErrInvalidEvidence; a
+// failure to fetch collateral does not.
+func (v *Verifier) Verify(ctx context.Context, rawQuote []byte) (*attestation.TDX, []byte, error) {
+	q, err := abi.QuoteToProto(rawQuote)
+	if err != nil {
+		return nil, nil, attestation.Invalidf("error parsing tdx quote: %w", err)
+	}
+	quote, ok := q.(*tdxpb.QuoteV4)
+	if !ok {
+		return nil, nil, attestation.Invalidf("unsupported tdx quote type %T", q)
+	}
+
+	getter := &recordingGetter{getter: v.getter}
+	now := v.now()
+	opts := &tdxverify.Options{
+		CheckRevocations: v.getCollateral,
+		GetCollateral:    v.getCollateral,
+		Getter:           getter,
+		TrustedRoots:     v.roots,
+		Now: &tdxverify.TimeSet{
+			PckCertChain: now,
+			TcbInfo:      now,
+			QeIdentity:   now,
+			PckCrl:       now,
+			RootCaCrl:    now,
+		},
+	}
+	if err := tdxverify.TdxQuoteContext(ctx, quote, opts); err != nil {
+		if getter.failed.Load() {
+			return nil, nil, fmt.Errorf("error fetching tdx collateral: %w", err)
+		}
+		return nil, nil, attestation.Invalidf("error verifying tdx quote: %w", err)
+	}
+
+	body := quote.GetTdQuoteBody()
+	if attrs := body.GetTdAttributes(); len(attrs) != 8 || binary.LittleEndian.Uint64(attrs)&attributesDebug != 0 {
+		return nil, nil, attestation.Invalidf("tdx quote is from a debug trust domain")
+	}
+
+	result := &attestation.TDX{
+		MRTD:          hex.EncodeToString(body.GetMrTd()),
+		MRSeam:        hex.EncodeToString(body.GetMrSeam()),
+		MRConfigID:    hex.EncodeToString(body.GetMrConfigId()),
+		MROwner:       hex.EncodeToString(body.GetMrOwner()),
+		MROwnerConfig: hex.EncodeToString(body.GetMrOwnerConfig()),
+		TDAttributes:  hex.EncodeToString(body.GetTdAttributes()),
+		XFAM:          hex.EncodeToString(body.GetXfam()),
+		TEETCBSVN:     hex.EncodeToString(body.GetTeeTcbSvn()),
+	}
+	for _, rtmr := range body.GetRtmrs() {
+		result.RTMRs = append(result.RTMRs, hex.EncodeToString(rtmr))
+	}
+	chain, err := tdxverify.ExtractChainFromQuote(quote)
+	if err != nil {
+		return nil, nil, attestation.Invalidf("error reading tdx pck certificate chain: %w", err)
+	}
+	exts, err := pcs.PckCertificateExtensions(chain.PCKCertificate)
+	if err != nil {
+		return nil, nil, attestation.Invalidf("error reading tdx pck certificate extensions: %w", err)
+	}
+	result.FMSPC = exts.FMSPC
+	if v.getCollateral {
+		tcb, _, err := tdxverify.SupportedTcbLevelsFromCollateral(quote, opts)
+		if err != nil {
+			return nil, nil, fmt.Errorf("error reading tdx tcb status: %w", err)
+		}
+		result.TCBStatus = string(tcb.TcbStatus)
+	}
+
+	reportData := body.GetReportData()
+	if len(reportData) != ReportDataSize {
+		return nil, nil, attestation.Invalidf("tdx quote report data has %d bytes, not %d", len(reportData), ReportDataSize)
+	}
+	return result, reportData, nil
+}
+
+// recordingGetter records whether a fetch failed, so that a quote that cannot
+// be verified because a service is unreachable is not called invalid.
+type recordingGetter struct {
+	getter tdxtrust.HTTPSGetter
+	failed atomic.Bool
+}
+
+func (g *recordingGetter) Get(url string) (map[string][]string, []byte, error) {
+	header, body, err := g.getter.Get(url)
+	if err != nil {
+		g.failed.Store(true)
+	}
+	return header, body, err
+}
+
+func (g *recordingGetter) GetContext(ctx context.Context, url string) (map[string][]string, []byte, error) {
+	cg, ok := g.getter.(tdxtrust.ContextHTTPSGetter)
+	if !ok {
+		return g.Get(url)
+	}
+	header, body, err := cg.GetContext(ctx, url)
+	if err != nil {
+		g.failed.Store(true)
+	}
+	return header, body, err
+}

+ 91 - 0
attestation/tdx/tdx_test.go

@@ -0,0 +1,91 @@
+package tdx
+
+import (
+	"context"
+	"errors"
+	"testing"
+	"time"
+
+	tdxtest "github.com/google/go-tdx-guest/testing"
+	"github.com/google/go-tdx-guest/testing/testdata"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	"github.com/smallstep/certificates/attestation"
+)
+
+// testTime is a time at which go-tdx-guest's sample quote, its PCK chain and
+// its sample collateral are all valid.
+var testTime = time.Date(2023, time.July, 1, 1, 0, 0, 0, time.UTC)
+
+// failingGetter fails every fetch, as an unreachable service would.
+type failingGetter struct{}
+
+func (failingGetter) Get(url string) (map[string][]string, []byte, error) {
+	return nil, nil, errors.New("unexpected fetch of " + url)
+}
+
+func newVerifier(t *testing.T, getCollateral bool, now time.Time) *Verifier {
+	t.Helper()
+	v, err := New(nil, tdxtest.TestGetter)
+	require.NoError(t, err)
+	v.getCollateral = getCollateral
+	v.now = func() time.Time { return now }
+	return v
+}
+
+func TestVerifier(t *testing.T) {
+	t.Run("ok", func(t *testing.T) {
+		// Without collateral, the quote's signature, its quoting enclave's
+		// report and its PCK chain to Intel's embedded root are verified.
+		got, reportData, err := newVerifier(t, false, testTime).Verify(context.Background(), testdata.RawQuote)
+		require.NoError(t, err)
+		assert.Len(t, got.MRTD, 96)
+		assert.Len(t, got.RTMRs, 4)
+		for _, rtmr := range got.RTMRs {
+			assert.Len(t, rtmr, 96)
+		}
+		assert.Len(t, got.MRConfigID, 96)
+		assert.Len(t, got.TDAttributes, 16)
+		assert.Equal(t, "50806f000000", got.FMSPC)
+		assert.Empty(t, got.TCBStatus)
+		assert.Len(t, reportData, ReportDataSize)
+	})
+
+	unreachable := newVerifier(t, true, testTime)
+	unreachable.getter = failingGetter{}
+
+	tests := []struct {
+		name        string
+		verifier    *Verifier
+		quote       []byte
+		wantErr     string
+		wantInvalid bool
+	}{
+		// The sample collateral's TCB levels do not match the sample quote's
+		// TEE_TCB_SVN, so a verifier that checks the TCB status refuses it.
+		{"fail tcb status", newVerifier(t, true, testTime), testdata.RawQuote, "no matching TCB level found", true},
+		{"fail collateral unreachable", unreachable, testdata.RawQuote, "error fetching tdx collateral", false},
+		{"fail expired", newVerifier(t, false, time.Date(2053, time.July, 1, 0, 0, 0, 0, time.UTC)), testdata.RawQuote,
+			"error verifying tdx quote", true},
+		{"fail parse", newVerifier(t, false, testTime), []byte("not a quote"), "error parsing tdx quote", true},
+		{"fail signature", newVerifier(t, false, testTime), func() []byte {
+			quote := append([]byte(nil), testdata.RawQuote...)
+			// Flip a bit of the report data in the signed TD quote body.
+			quote[48+520] ^= 1
+			return quote
+		}(), "error verifying tdx quote", true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			_, _, err := tt.verifier.Verify(context.Background(), tt.quote)
+			assert.ErrorContains(t, err, tt.wantErr)
+			assert.Equal(t, tt.wantInvalid, errors.Is(err, attestation.ErrInvalidEvidence))
+		})
+	}
+}
+
+func TestNew(t *testing.T) {
+	_, err := New([]byte("not pem"), tdxtest.TestGetter)
+	assert.EqualError(t, err, "no certificates found in the tdx roots")
+}

+ 128 - 0
attestation/tsm/tsm.go

@@ -0,0 +1,128 @@
+// Package tsm parses Linux configfs-tsm reports in the media types Veraison
+// registered for them, application/vnd.veraison.tsm-report+json and
+// application/vnd.veraison.tsm-report+cbor, described by
+// https://github.com/veraison/ratsd/blob/main/docs/tsm-report.cddl.
+package tsm
+
+import (
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"mime"
+	"strings"
+
+	"github.com/fxamacker/cbor/v2"
+
+	"github.com/smallstep/certificates/attestation"
+)
+
+// The media types of a configfs-tsm report.
+const (
+	MediaTypeJSON = "application/vnd.veraison.tsm-report+json"
+	MediaTypeCBOR = "application/vnd.veraison.tsm-report+cbor"
+)
+
+// The providers of the configfs-tsm reports this package's callers verify.
+const (
+	// ProviderTDX is an Intel TDX guest, whose outblob is a quote.
+	ProviderTDX = "tdx_guest"
+	// ProviderSEVSNP is an AMD SEV-SNP guest, whose outblob is an attestation
+	// report and whose auxblob is its certificate table.
+	ProviderSEVSNP = "sev_guest"
+)
+
+// Report is a configfs-tsm report.
+type Report struct {
+	// Provider names the format of OutBlob, for example tdx_guest.
+	Provider string
+	// OutBlob is the evidence the provider generated.
+	OutBlob []byte
+	// AuxBlob is the provider's auxiliary data, if any.
+	AuxBlob []byte
+}
+
+// IsMediaType reports whether mediaType, with or without parameters, is one of
+// the media types of a configfs-tsm report.
+func IsMediaType(mediaType string) bool {
+	mt, _, err := mime.ParseMediaType(mediaType)
+	return err == nil && (mt == MediaTypeJSON || mt == MediaTypeCBOR)
+}
+
+// Parse parses a configfs-tsm report sent with the given media type. If the
+// media type has a provider parameter, it must match the report's provider.
+// Errors match attestation.ErrInvalidEvidence.
+func Parse(mediaType string, value []byte) (*Report, error) {
+	mt, params, err := mime.ParseMediaType(mediaType)
+	if err != nil {
+		return nil, attestation.Invalidf("error parsing media type %q: %w", mediaType, err)
+	}
+
+	var r *Report
+	switch mt {
+	case MediaTypeJSON:
+		r, err = parseJSON(value)
+	case MediaTypeCBOR:
+		r, err = parseCBOR(value)
+	default:
+		return nil, attestation.Invalidf("media type %q is not a tsm report", mt)
+	}
+	if err != nil {
+		return nil, attestation.Invalid(err)
+	}
+
+	if r.Provider == "" {
+		return nil, attestation.Invalidf("tsm report has no provider")
+	}
+	if len(r.OutBlob) == 0 {
+		return nil, attestation.Invalidf("tsm report has no outblob")
+	}
+	if p, ok := params["provider"]; ok && p != r.Provider {
+		return nil, attestation.Invalidf("tsm report provider %q does not match the media type's provider %q", r.Provider, p)
+	}
+	return r, nil
+}
+
+func parseJSON(value []byte) (*Report, error) {
+	var v struct {
+		Provider string `json:"provider"`
+		OutBlob  string `json:"outblob"`
+		AuxBlob  string `json:"auxblob"`
+	}
+	if err := json.Unmarshal(value, &v); err != nil {
+		return nil, fmt.Errorf("error parsing tsm report: %w", err)
+	}
+	out, err := decodeBase64(v.OutBlob)
+	if err != nil {
+		return nil, fmt.Errorf("tsm report outblob must be base64url: %w", err)
+	}
+	aux, err := decodeBase64(v.AuxBlob)
+	if err != nil {
+		return nil, fmt.Errorf("tsm report auxblob must be base64url: %w", err)
+	}
+	return &Report{Provider: v.Provider, OutBlob: out, AuxBlob: aux}, nil
+}
+
+func parseCBOR(value []byte) (*Report, error) {
+	var v struct {
+		Provider string `cbor:"provider"`
+		OutBlob  []byte `cbor:"outblob"`
+		AuxBlob  []byte `cbor:"auxblob"`
+	}
+	if err := cbor.Unmarshal(value, &v); err != nil {
+		return nil, fmt.Errorf("error parsing tsm report: %w", err)
+	}
+	return &Report{Provider: v.Provider, OutBlob: v.OutBlob, AuxBlob: v.AuxBlob}, nil
+}
+
+// decodeBase64 decodes base64url, as the CDDL requires, and also accepts the
+// standard alphabet and padding.
+func decodeBase64(s string) ([]byte, error) {
+	s = strings.TrimRight(s, "=")
+	if s == "" {
+		return nil, nil
+	}
+	if strings.ContainsAny(s, "+/") {
+		return base64.RawStdEncoding.DecodeString(s)
+	}
+	return base64.RawURLEncoding.DecodeString(s)
+}

+ 63 - 0
attestation/tsm/tsm_test.go

@@ -0,0 +1,63 @@
+package tsm
+
+import (
+	"testing"
+
+	"github.com/fxamacker/cbor/v2"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	"github.com/smallstep/certificates/attestation"
+)
+
+func TestIsMediaType(t *testing.T) {
+	assert.True(t, IsMediaType(MediaTypeJSON))
+	assert.True(t, IsMediaType(MediaTypeCBOR+`; provider="sev_guest"`))
+	assert.False(t, IsMediaType("application/eat+jwt"))
+	assert.False(t, IsMediaType("not a media type;"))
+}
+
+func TestParse(t *testing.T) {
+	// The blobs hold bytes whose base64 differs between the alphabets.
+	out := []byte{0xfb, 0xff, 0x01}
+	aux := []byte{0xfa, 0xfe}
+	cborReport, err := cbor.Marshal(map[string]any{"provider": "sev_guest", "outblob": out, "auxblob": aux, "service_provider": "svsm"})
+	require.NoError(t, err)
+
+	tests := []struct {
+		name      string
+		mediaType string
+		value     string
+		want      *Report
+		wantErr   string
+	}{
+		{"ok json", MediaTypeJSON + `; provider="tdx_guest"`, `{"provider":"tdx_guest","outblob":"-_8B"}`,
+			&Report{Provider: "tdx_guest", OutBlob: out}, ""},
+		{"ok json standard alphabet and padding", MediaTypeJSON, `{"provider":"sev_guest","outblob":"+/8B","auxblob":"+v4="}`,
+			&Report{Provider: "sev_guest", OutBlob: out, AuxBlob: aux}, ""},
+		{"ok cbor", MediaTypeCBOR, string(cborReport),
+			&Report{Provider: "sev_guest", OutBlob: out, AuxBlob: aux}, ""},
+		{"fail media type", MediaTypeJSON + "; provider", `{}`, nil, "error parsing media type"},
+		{"fail other media type", "application/eat+jwt", `{}`, nil, "is not a tsm report"},
+		{"fail json", MediaTypeJSON, `{`, nil, "error parsing tsm report"},
+		{"fail json outblob", MediaTypeJSON, `{"provider":"tdx_guest","outblob":"*"}`, nil, "outblob must be base64url"},
+		{"fail json auxblob", MediaTypeJSON, `{"provider":"tdx_guest","outblob":"-_8B","auxblob":"*"}`, nil, "auxblob must be base64url"},
+		{"fail cbor", MediaTypeCBOR, "\xa1", nil, "error parsing tsm report"},
+		{"fail no provider", MediaTypeJSON, `{"outblob":"-_8B"}`, nil, "has no provider"},
+		{"fail no outblob", MediaTypeJSON, `{"provider":"tdx_guest"}`, nil, "has no outblob"},
+		{"fail provider mismatch", MediaTypeJSON + `; provider="sev_guest"`, `{"provider":"tdx_guest","outblob":"-_8B"}`, nil,
+			`provider "tdx_guest" does not match the media type's provider "sev_guest"`},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := Parse(tt.mediaType, []byte(tt.value))
+			if tt.wantErr != "" {
+				assert.ErrorContains(t, err, tt.wantErr)
+				assert.ErrorIs(t, err, attestation.ErrInvalidEvidence)
+				return
+			}
+			require.NoError(t, err)
+			assert.Equal(t, tt.want, got)
+		})
+	}
+}

+ 4 - 0
go.mod

@@ -15,6 +15,8 @@ require (
 	github.com/go-chi/chi/v5 v5.5.0
 	github.com/go-jose/go-jose/v3 v3.0.5
 	github.com/google/go-cmp v0.7.0
+	github.com/google/go-sev-guest v0.15.0
+	github.com/google/go-tdx-guest v0.3.2-0.20250814004405-ffb0869e6f4d
 	github.com/google/go-tpm v0.9.8
 	github.com/google/uuid v1.6.0
 	github.com/googleapis/gax-go/v2 v2.27.0
@@ -108,6 +110,7 @@ require (
 	github.com/google/certificate-transparency-go v1.3.2 // indirect
 	github.com/google/go-tpm-tools v0.4.9 // indirect
 	github.com/google/go-tspi v0.3.0 // indirect
+	github.com/google/logger v1.1.1 // indirect
 	github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 // indirect
 	github.com/google/s2a-go v0.1.11 // indirect
 	github.com/googleapis/enterprise-certificate-proxy v0.3.23 // indirect
@@ -162,6 +165,7 @@ require (
 	go.opentelemetry.io/otel/log v1.47.0 // indirect
 	go.opentelemetry.io/otel/metric v1.47.0 // indirect
 	go.opentelemetry.io/otel/trace v1.47.0 // indirect
+	go.uber.org/multierr v1.11.0 // indirect
 	go.yaml.in/yaml/v3 v3.0.5 // indirect
 	golang.org/x/mod v0.42.0 // indirect
 	golang.org/x/oauth2 v0.37.0 // indirect

+ 3 - 2
go.sum

@@ -195,8 +195,8 @@ github.com/google/go-configfs-tsm v0.3.3-0.20240919001351-b4b5b84fdcbc h1:SG12DW
 github.com/google/go-configfs-tsm v0.3.3-0.20240919001351-b4b5b84fdcbc/go.mod h1:EL1GTDFMb5PZQWDviGfZV9n87WeGTR/JUg13RfwkgRo=
 github.com/google/go-eventlog v0.0.3-0.20260416001248-6807b85eecf0 h1:STyioPkz8nqMMIk3+YlyJ/WyEJZxho1YUZXu99uAbQ0=
 github.com/google/go-eventlog v0.0.3-0.20260416001248-6807b85eecf0/go.mod h1:7huE5P8w2NTObSwSJjboHmB7ioBNblkijdzoVa2skfQ=
-github.com/google/go-sev-guest v0.14.0 h1:dCb4F3YrHTtrDX3cYIPTifEDz7XagZmXQioxRBW4wOo=
-github.com/google/go-sev-guest v0.14.0/go.mod h1:SK9vW+uyfuzYdVN0m8BShL3OQCtXZe/JPF7ZkpD3760=
+github.com/google/go-sev-guest v0.15.0 h1:Xzfut5mbhcVb7TyPiyc5PolLUzdai7VH3QpyvXwcW9Y=
+github.com/google/go-sev-guest v0.15.0/go.mod h1:SK9vW+uyfuzYdVN0m8BShL3OQCtXZe/JPF7ZkpD3760=
 github.com/google/go-tdx-guest v0.3.2-0.20250814004405-ffb0869e6f4d h1:Ff8goEP/ue2/rZT5qyoRicuySCYDbAXEZS8Cf1fgsUo=
 github.com/google/go-tdx-guest v0.3.2-0.20250814004405-ffb0869e6f4d/go.mod h1:uHy3VaNXNXhl0fiPxKqTxieeouqQmW6A0EfLcaeCYBk=
 github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
@@ -488,6 +488,7 @@ golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7w
 golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210426230700-d19ff857e887/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=