Bladeren bron

Move the tpm device attestation verifier to attestation/tpm

The verifier of the "tpm" format of device-attest-01 moves from
acme/challenge.go to attestation/tpm, with the AK certificate checks.
tpm.Verify takes the attestation statement, the roots and the key
authorization, which acme computes, and returns the AK certificate, its
verified chains, its permanent identifiers and the attested key's
fingerprint. The format has no default roots: without roots Verify fails
with an error that is not an evidence error, which acme turns into the
same internal error as before. acme keeps the permanent identifier check.

The AK certificate tests and the simulator test of the verifier move with
it; the simulator test's key authorization failure, now acme's, becomes a
case of the acme simulator test. Two unused OID variables of the acme
simulator test go with the verifier test they sat next to.

The draft-ietf-acme-rats (remote-attest-01) work on this branch needs one
place for attestation verifiers.

Claude-Session: https://claude.ai/code/session_01CjfEMLGpnHQaWsmxe1zmLF
Josh Drake 1 maand geleden
bovenliggende
commit
f745105a78
6 gewijzigde bestanden met toevoegingen van 1148 en 1044 verwijderingen
  1. 7 309
      acme/challenge.go
  2. 0 299
      acme/challenge_test.go
  3. 98 436
      acme/challenge_tpmsimulator_test.go
  4. 329 0
      attestation/tpm/tpm.go
  5. 316 0
      attestation/tpm/tpm_test.go
  6. 398 0
      attestation/tpm/tpm_tpmsimulator_test.go

+ 7 - 309
acme/challenge.go

@@ -29,19 +29,17 @@ import (
 
 	"github.com/coreos/go-oidc/v3/oidc"
 	"github.com/fxamacker/cbor/v2"
-	"github.com/google/go-tpm/legacy/tpm2"
 
 	androidattestation "github.com/smallstep/android-attestation"
-	"github.com/smallstep/go-attestation/attest"
 	"go.step.sm/crypto/jose"
 	"go.step.sm/crypto/keyutil"
 	"go.step.sm/crypto/mldsa"
 	"go.step.sm/crypto/pemutil"
-	"go.step.sm/crypto/x509util"
 
 	"github.com/smallstep/certificates/acme/wire"
 	"github.com/smallstep/certificates/attestation"
 	"github.com/smallstep/certificates/attestation/apple"
+	"github.com/smallstep/certificates/attestation/tpm"
 	"github.com/smallstep/certificates/attestation/yubikey"
 	"github.com/smallstep/certificates/authority/provisioner"
 	wireprovisioner "github.com/smallstep/certificates/authority/provisioner/wire"
@@ -944,15 +942,13 @@ func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose
 		az.Fingerprint = data.Fingerprint
 
 	case "tpm":
-		data, err := doTPMAttestationFormat(ctx, prov, ch, jwk, &att)
+		keyAuth, err := KeyAuthorization(ch.Token, jwk)
 		if err != nil {
-			if acmeError, ok := errors.AsType[*Error](err); ok {
-				if acmeError.Status == 500 {
-					return acmeError
-				}
-				return storeError(ctx, db, ch, true, acmeError)
-			}
-			return WrapErrorISE(err, "error validating attestation")
+			return WrapErrorISE(err, "failed creating key auth digest")
+		}
+		data, err := tpm.Verify(att.AttStatement, attestationRoots(prov), []byte(keyAuth))
+		if err != nil {
+			return storeAttestationError(ctx, db, ch, err)
 		}
 
 		// TODO(hs): currently this will allow a request for which no PermanentIdentifiers have been
@@ -1027,304 +1023,6 @@ func storeAttestationError(ctx context.Context, db DB, ch *Challenge, err error)
 	return storeError(ctx, db, ch, true, acmeErr)
 }
 
-var (
-	oidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
-)
-
-type tpmAttestationData struct {
-	Certificate          *x509.Certificate
-	VerifiedChains       [][]*x509.Certificate
-	PermanentIdentifiers []string
-	Fingerprint          string
-}
-
-// coseAlgorithmIdentifier models a COSEAlgorithmIdentifier.
-// Also see https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier.
-type coseAlgorithmIdentifier int32
-
-const (
-	coseAlgES256 = coseAlgorithmIdentifier(-7)
-	coseAlgRS256 = coseAlgorithmIdentifier(-257)
-	coseAlgRS1   = coseAlgorithmIdentifier(-65535) // deprecated, but (still) often used in TPMs
-)
-
-func doTPMAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*tpmAttestationData, error) {
-	ver, ok := att.AttStatement["ver"].(string)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "ver not present")
-	}
-	if ver != "2.0" {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "version %q is not supported", ver)
-	}
-
-	x5c, ok := att.AttStatement["x5c"].([]any)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
-	}
-	if len(x5c) == 0 {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
-	}
-
-	akCertBytes, ok := x5c[0].([]byte)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
-	}
-	akCert, err := x509.ParseCertificate(akCertBytes)
-	if err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
-	}
-
-	intermediates := x509.NewCertPool()
-	for _, v := range x5c[1:] {
-		intCertBytes, vok := v.([]byte)
-		if !vok {
-			return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
-		}
-		intCert, err := x509.ParseCertificate(intCertBytes)
-		if err != nil {
-			return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
-		}
-		intermediates.AddCert(intCert)
-	}
-
-	// TODO(hs): this can be removed when permanent-identifier/hardware-module-name are handled correctly in
-	// the stdlib in https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/crypto/x509/parser.go;drc=b5b2cf519fe332891c165077f3723ee74932a647;l=362,
-	// but I doubt that will happen.
-	if len(akCert.UnhandledCriticalExtensions) > 0 {
-		unhandledCriticalExtensions := akCert.UnhandledCriticalExtensions[:0]
-		for _, extOID := range akCert.UnhandledCriticalExtensions {
-			if !extOID.Equal(oidSubjectAlternativeName) {
-				// critical extensions other than the Subject Alternative Name remain unhandled
-				unhandledCriticalExtensions = append(unhandledCriticalExtensions, extOID)
-			}
-		}
-		akCert.UnhandledCriticalExtensions = unhandledCriticalExtensions
-	}
-
-	roots, ok := prov.GetAttestationRoots()
-	if !ok {
-		return nil, NewErrorISE("no root CA bundle available to verify the attestation certificate")
-	}
-
-	// verify that the AK certificate was signed by a trusted root,
-	// chained to by the intermediates provided by the client. As part
-	// of building the verified certificate chain, the signature over the
-	// AK certificate is checked to be a valid signature of one of the
-	// provided intermediates. Signatures over the intermediates are in
-	// turn also verified to be valid signatures from one of the trusted
-	// roots.
-	verifiedChains, err := akCert.Verify(x509.VerifyOptions{
-		Roots:         roots,
-		Intermediates: intermediates,
-		CurrentTime:   time.Now().Truncate(time.Second),
-		KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
-	})
-	if err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
-	}
-
-	// validate additional AK certificate requirements
-	if err := validateAKCertificate(akCert); err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "AK certificate is not valid")
-	}
-
-	// TODO(hs): implement revocation check; Verify() doesn't perform CRL check nor OCSP lookup.
-
-	sans, err := x509util.ParseSubjectAlternativeNames(akCert)
-	if err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing AK certificate Subject Alternative Names")
-	}
-
-	permanentIdentifiers := make([]string, len(sans.PermanentIdentifiers))
-	for i, pi := range sans.PermanentIdentifiers {
-		permanentIdentifiers[i] = pi.Identifier
-	}
-
-	// extract and validate pubArea, sig, certInfo and alg properties from the request body
-	pubArea, ok := att.AttStatement["pubArea"].([]byte)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid pubArea in attestation statement")
-	}
-	if len(pubArea) == 0 {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "pubArea is empty")
-	}
-
-	sig, ok := att.AttStatement["sig"].([]byte)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid sig in attestation statement")
-	}
-	if len(sig) == 0 {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is empty")
-	}
-
-	certInfo, ok := att.AttStatement["certInfo"].([]byte)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid certInfo in attestation statement")
-	}
-	if len(certInfo) == 0 {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "certInfo is empty")
-	}
-
-	alg, ok := att.AttStatement["alg"].(int64)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg in attestation statement")
-	}
-
-	algI32, err := cast.SafeInt32(alg)
-	if err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid alg %d in attestation statement", alg)
-	}
-
-	var hash crypto.Hash
-	switch coseAlgorithmIdentifier(algI32) {
-	case coseAlgRS256, coseAlgES256:
-		hash = crypto.SHA256
-	case coseAlgRS1:
-		hash = crypto.SHA1
-	default:
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg %d in attestation statement", alg)
-	}
-
-	// recreate the generated key certification parameter values and verify
-	// the attested key using the public key of the AK.
-	certificationParameters := &attest.CertificationParameters{
-		Public:            pubArea,  // the public key that was attested
-		CreateAttestation: certInfo, // the attested properties of the key
-		CreateSignature:   sig,      // signature over the attested properties
-	}
-	verifyOpts := attest.VerifyOpts{
-		Public: akCert.PublicKey, // public key of the AK that attested the key
-		Hash:   hash,
-	}
-	if err = certificationParameters.Verify(verifyOpts); err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid certification parameters")
-	}
-
-	// decode the "certInfo" data. This won't fail, as it's also done as part of Verify().
-	tpmCertInfo, err := tpm2.DecodeAttestationData(certInfo)
-	if err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding attestation data")
-	}
-
-	keyAuth, err := KeyAuthorization(ch.Token, jwk)
-	if err != nil {
-		return nil, WrapErrorISE(err, "failed creating key auth digest")
-	}
-	hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
-
-	// verify the WebAuthn object contains the expect key authorization digest, which is carried
-	// within the encoded `certInfo` property of the attestation statement.
-	if subtle.ConstantTimeCompare(hashedKeyAuth[:], []byte(tpmCertInfo.ExtraData)) == 0 {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "key authorization invalid")
-	}
-
-	// decode the (attested) public key and determine its fingerprint.  This won't fail, as it's also done as part of Verify().
-	pub, err := tpm2.DecodePublic(pubArea)
-	if err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding pubArea")
-	}
-
-	publicKey, err := pub.Key()
-	if err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed getting public key")
-	}
-
-	data := &tpmAttestationData{
-		Certificate:          akCert,
-		VerifiedChains:       verifiedChains,
-		PermanentIdentifiers: permanentIdentifiers,
-	}
-
-	if data.Fingerprint, err = keyutil.Fingerprint(publicKey); err != nil {
-		return nil, WrapErrorISE(err, "error calculating key fingerprint")
-	}
-
-	// TODO(hs): pass more attestation data, so that that can be used/recorded too?
-	return data, nil
-}
-
-var (
-	oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
-	oidTCGKpAIKCertificate       = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
-)
-
-// validateAKCertificate validates the X.509 AK certificate to be
-// in accordance with the required properties. The requirements come from:
-// https://www.w3.org/TR/webauthn-2/#sctn-tpm-cert-requirements.
-//
-//   - Version MUST be set to 3.
-//   - Subject field MUST be set to empty.
-//   - The Subject Alternative Name extension MUST be set as defined
-//     in [TPMv2-EK-Profile] section 3.2.9.
-//   - The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
-//     ("joint-iso-itu-t(2) international-organizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)").
-//   - The Basic Constraints extension MUST have the CA component set to false.
-//   - An Authority Information Access (AIA) extension with entry id-ad-ocsp
-//     and a CRL Distribution Point extension [RFC5280] are both OPTIONAL as
-//     the status of many attestation certificates is available through metadata
-//     services. See, for example, the FIDO Metadata Service.
-func validateAKCertificate(c *x509.Certificate) error {
-	if c.Version != 3 {
-		return fmt.Errorf("AK certificate has invalid version %d; only version 3 is allowed", c.Version)
-	}
-	if c.Subject.String() != "" {
-		return fmt.Errorf("AK certificate subject must be empty; got %q", c.Subject)
-	}
-	if c.IsCA {
-		return errors.New("AK certificate must not be a CA")
-	}
-	if err := validateAKCertificateExtendedKeyUsage(c); err != nil {
-		return err
-	}
-	return validateAKCertificateSubjectAlternativeNames(c)
-}
-
-// validateAKCertificateSubjectAlternativeNames checks if the AK certificate
-// has TPM hardware details set.
-func validateAKCertificateSubjectAlternativeNames(c *x509.Certificate) error {
-	sans, err := x509util.ParseSubjectAlternativeNames(c)
-	if err != nil {
-		return fmt.Errorf("failed parsing AK certificate Subject Alternative Names: %w", err)
-	}
-
-	details := sans.TPMHardwareDetails
-	manufacturer, model, version := details.Manufacturer, details.Model, details.Version
-
-	switch {
-	case manufacturer == "":
-		return errors.New("missing TPM manufacturer")
-	case model == "":
-		return errors.New("missing TPM model")
-	case version == "":
-		return errors.New("missing TPM version")
-	}
-
-	return nil
-}
-
-// validateAKCertificateExtendedKeyUsage checks if the AK certificate
-// has the "tcg-kp-AIKCertificate" Extended Key Usage set.
-func validateAKCertificateExtendedKeyUsage(c *x509.Certificate) error {
-	var (
-		valid = false
-		ekus  []asn1.ObjectIdentifier
-	)
-	for _, ext := range c.Extensions {
-		if ext.Id.Equal(oidExtensionExtendedKeyUsage) {
-			if _, err := asn1.Unmarshal(ext.Value, &ekus); err != nil || len(ekus) == 0 || !ekus[0].Equal(oidTCGKpAIKCertificate) {
-				return errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")
-			}
-			valid = true
-		}
-	}
-
-	if !valid {
-		return errors.New("AK certificate is missing Extended Key Usage extension")
-	}
-
-	return nil
-}
-
 // Android RSA Root CA
 // https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate
 var androidRSARootCA = `-----BEGIN CERTIFICATE-----

+ 0 - 299
acme/challenge_test.go

@@ -39,7 +39,6 @@ import (
 	"go.step.sm/crypto/keyutil"
 	"go.step.sm/crypto/minica"
 	"go.step.sm/crypto/pemutil"
-	"go.step.sm/crypto/x509util"
 
 	"github.com/smallstep/certificates/attestation"
 	"github.com/smallstep/certificates/attestation/yubikey"
@@ -4727,304 +4726,6 @@ func Test_deviceAttest01Validate(t *testing.T) {
 	}
 }
 
-var (
-	oidTPMManufacturer = asn1.ObjectIdentifier{2, 23, 133, 2, 1}
-	oidTPMModel        = asn1.ObjectIdentifier{2, 23, 133, 2, 2}
-	oidTPMVersion      = asn1.ObjectIdentifier{2, 23, 133, 2, 3}
-)
-
-func generateValidAKCertificate(t *testing.T) *x509.Certificate {
-	t.Helper()
-	signer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
-	require.NoError(t, err)
-	template := &x509.Certificate{
-		PublicKey:          signer.Public(),
-		Version:            3,
-		IsCA:               false,
-		UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
-	}
-	asn1Value := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMModel, "SLB 9670 TPM2.0", oidTPMVersion, "7.55"))
-	sans := []x509util.SubjectAlternativeName{
-		{Type: x509util.DirectoryNameType,
-			ASN1Value: asn1Value},
-	}
-	ext, err := createSubjectAltNameExtension(nil, nil, nil, nil, sans, true)
-	require.NoError(t, err)
-	ext.Set(template)
-	ca, err := minica.New()
-	require.NoError(t, err)
-	cert, err := ca.Sign(template)
-	require.NoError(t, err)
-
-	return cert
-}
-
-func Test_validateAKCertificate(t *testing.T) {
-	cert := generateValidAKCertificate(t)
-	tests := []struct {
-		name   string
-		c      *x509.Certificate
-		expErr error
-	}{
-		{
-			name:   "ok",
-			c:      cert,
-			expErr: nil,
-		},
-		{
-			name: "fail/version",
-			c: &x509.Certificate{
-				Version: 1,
-			},
-			expErr: errors.New("AK certificate has invalid version 1; only version 3 is allowed"),
-		},
-		{
-			name: "fail/subject",
-			c: &x509.Certificate{
-				Version: 3,
-				Subject: pkix.Name{CommonName: "fail!"},
-			},
-			expErr: errors.New(`AK certificate subject must be empty; got "CN=fail!"`),
-		},
-		{
-			name: "fail/isCA",
-			c: &x509.Certificate{
-				Version: 3,
-				IsCA:    true,
-			},
-			expErr: errors.New("AK certificate must not be a CA"),
-		},
-		{
-			name: "fail/extendedKeyUsage",
-			c: &x509.Certificate{
-				Version: 3,
-			},
-			expErr: errors.New("AK certificate is missing Extended Key Usage extension"),
-		},
-	}
-	for _, tt := range tests {
-		t.Run(tt.name, func(t *testing.T) {
-			err := validateAKCertificate(tt.c)
-			if tt.expErr != nil {
-				if assert.Error(t, err) {
-					assert.EqualError(t, err, tt.expErr.Error())
-				}
-				return
-			}
-
-			assert.NoError(t, err)
-		})
-	}
-}
-
-func Test_validateAKCertificateSubjectAlternativeNames(t *testing.T) {
-	ok := generateValidAKCertificate(t)
-	t.Helper()
-	signer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
-	require.NoError(t, err)
-
-	getBase := func() *x509.Certificate {
-		return &x509.Certificate{
-			PublicKey:          signer.Public(),
-			Version:            3,
-			IsCA:               false,
-			UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
-		}
-	}
-
-	ca, err := minica.New()
-	require.NoError(t, err)
-	missingManufacturerASN1 := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMModel, "SLB 9670 TPM2.0", oidTPMVersion, "7.55"))
-	sans := []x509util.SubjectAlternativeName{
-		{Type: x509util.DirectoryNameType,
-			ASN1Value: missingManufacturerASN1},
-	}
-	ext, err := createSubjectAltNameExtension(nil, nil, nil, nil, sans, true)
-	require.NoError(t, err)
-	missingManufacturer := getBase()
-	ext.Set(missingManufacturer)
-
-	missingManufacturer, err = ca.Sign(missingManufacturer)
-	require.NoError(t, err)
-
-	missingModelASN1 := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMVersion, "7.55"))
-	sans = []x509util.SubjectAlternativeName{
-		{Type: x509util.DirectoryNameType,
-			ASN1Value: missingModelASN1},
-	}
-	ext, err = createSubjectAltNameExtension(nil, nil, nil, nil, sans, true)
-	require.NoError(t, err)
-	missingModel := getBase()
-	ext.Set(missingModel)
-
-	missingModel, err = ca.Sign(missingModel)
-	require.NoError(t, err)
-
-	missingFirmwareVersionASN1 := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMModel, "SLB 9670 TPM2.0"))
-	sans = []x509util.SubjectAlternativeName{
-		{Type: x509util.DirectoryNameType,
-			ASN1Value: missingFirmwareVersionASN1},
-	}
-	ext, err = createSubjectAltNameExtension(nil, nil, nil, nil, sans, true)
-	require.NoError(t, err)
-	missingFirmwareVersion := getBase()
-	ext.Set(missingFirmwareVersion)
-
-	missingFirmwareVersion, err = ca.Sign(missingFirmwareVersion)
-	require.NoError(t, err)
-
-	tests := []struct {
-		name   string
-		c      *x509.Certificate
-		expErr error
-	}{
-		{"ok", ok, nil},
-		{"fail/missing-manufacturer", missingManufacturer, errors.New("missing TPM manufacturer")},
-		{"fail/missing-model", missingModel, errors.New("missing TPM model")},
-		{"fail/missing-firmware-version", missingFirmwareVersion, errors.New("missing TPM version")},
-	}
-	for _, tt := range tests {
-		t.Run(tt.name, func(t *testing.T) {
-			err := validateAKCertificateSubjectAlternativeNames(tt.c)
-			if tt.expErr != nil {
-				if assert.Error(t, err) {
-					assert.EqualError(t, err, tt.expErr.Error())
-				}
-				return
-			}
-
-			assert.NoError(t, err)
-		})
-	}
-}
-
-func Test_validateAKCertificateExtendedKeyUsage(t *testing.T) {
-	ok := generateValidAKCertificate(t)
-	missingEKU := &x509.Certificate{}
-	t.Helper()
-	signer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
-	require.NoError(t, err)
-	template := &x509.Certificate{
-		PublicKey:   signer.Public(),
-		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
-	}
-	ca, err := minica.New()
-	require.NoError(t, err)
-	wrongEKU, err := ca.Sign(template)
-	require.NoError(t, err)
-	emptyEKU, err := ca.Sign(&x509.Certificate{
-		PublicKey: signer.Public(),
-		ExtraExtensions: []pkix.Extension{{
-			Id:    oidExtensionExtendedKeyUsage,
-			Value: []byte{0x30, 0x00}, // DER: empty SEQUENCE
-		}},
-	})
-	require.NoError(t, err)
-
-	tests := []struct {
-		name   string
-		c      *x509.Certificate
-		expErr error
-	}{
-		{"ok", ok, nil},
-		{"fail/wrong-eku", wrongEKU, errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")},
-		{"fail/empty-eku", emptyEKU, errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")},
-		{"fail/missing-eku", missingEKU, errors.New("AK certificate is missing Extended Key Usage extension")},
-	}
-	for _, tt := range tests {
-		t.Run(tt.name, func(t *testing.T) {
-			err := validateAKCertificateExtendedKeyUsage(tt.c)
-			if tt.expErr != nil {
-				if assert.Error(t, err) {
-					assert.EqualError(t, err, tt.expErr.Error())
-				}
-				return
-			}
-
-			assert.NoError(t, err)
-		})
-	}
-}
-
-// createSubjectAltNameExtension will construct an Extension containing all
-// SubjectAlternativeNames held in a Certificate. It implements more types than
-// the golang x509 library, so it is used whenever OtherName or RegisteredID
-// type SANs are present in the certificate.
-//
-// See also https://datatracker.ietf.org/doc/html/rfc5280.html#section-4.2.1.6
-//
-// TODO(hs): this was copied from go.step.sm/crypto/x509util to make it easier
-// to create the SAN extension for testing purposes. Should it be exposed instead?
-func createSubjectAltNameExtension(dnsNames, emailAddresses x509util.MultiString, ipAddresses x509util.MultiIP, uris x509util.MultiURL, sans []x509util.SubjectAlternativeName, subjectIsEmpty bool) (x509util.Extension, error) {
-	var zero x509util.Extension
-
-	var rawValues []asn1.RawValue
-	for _, dnsName := range dnsNames {
-		rawValue, err := x509util.SubjectAlternativeName{
-			Type: x509util.DNSType, Value: dnsName,
-		}.RawValue()
-		if err != nil {
-			return zero, err
-		}
-
-		rawValues = append(rawValues, rawValue)
-	}
-
-	for _, emailAddress := range emailAddresses {
-		rawValue, err := x509util.SubjectAlternativeName{
-			Type: x509util.EmailType, Value: emailAddress,
-		}.RawValue()
-		if err != nil {
-			return zero, err
-		}
-
-		rawValues = append(rawValues, rawValue)
-	}
-
-	for _, ip := range ipAddresses {
-		rawValue, err := x509util.SubjectAlternativeName{
-			Type: x509util.IPType, Value: ip.String(),
-		}.RawValue()
-		if err != nil {
-			return zero, err
-		}
-
-		rawValues = append(rawValues, rawValue)
-	}
-
-	for _, uri := range uris {
-		rawValue, err := x509util.SubjectAlternativeName{
-			Type: x509util.URIType, Value: uri.String(),
-		}.RawValue()
-		if err != nil {
-			return zero, err
-		}
-
-		rawValues = append(rawValues, rawValue)
-	}
-
-	for _, san := range sans {
-		rawValue, err := san.RawValue()
-		if err != nil {
-			return zero, err
-		}
-
-		rawValues = append(rawValues, rawValue)
-	}
-
-	// Now marshal the rawValues into the ASN1 sequence, and create an Extension object to hold the extension
-	rawBytes, err := asn1.Marshal(rawValues)
-	if err != nil {
-		return zero, fmt.Errorf("error marshaling SubjectAlternativeName extension to ASN1: %w", err)
-	}
-
-	return x509util.Extension{
-		ID:       x509util.ObjectIdentifier(oidSubjectAlternativeName),
-		Critical: subjectIsEmpty,
-		Value:    rawBytes,
-	}, nil
-}
-
 func Test_tlsAlpn01ChallengeHost(t *testing.T) {
 	type args struct {
 		name string

+ 98 - 436
acme/challenge_tpmsimulator_test.go

@@ -11,7 +11,6 @@ import (
 	"encoding/base64"
 	"encoding/json"
 	"encoding/pem"
-	"errors"
 	"fmt"
 	"net/url"
 	"testing"
@@ -301,6 +300,34 @@ func Test_deviceAttest01ValidateWithTPMSimulator(t *testing.T) {
 				wantErr: nil,
 			}
 		},
+		"fail/doTPMAttestationFormat-keyAuthorization": func(t *testing.T) test {
+			_, keyAuth := mustAccountAndKeyAuthorization(t, "token")
+			payload, _, root := mustAttestTPM(t, keyAuth, nil)
+			caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
+			ctx := NewProvisionerContext(context.Background(), mustAttestationProvisioner(t, caRoot))
+			return test{
+				args: args{
+					ctx: ctx,
+					jwk: &jose.JSONWebKey{Key: []byte("not an asymmetric key")},
+					ch: &Challenge{
+						ID:              "chID",
+						AuthorizationID: "azID",
+						Token:           "token",
+						Type:            "device-attest-01",
+						Status:          StatusPending,
+						Value:           "device.id.12345678",
+					},
+					payload: payload,
+					db: &MockDB{
+						MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
+							assert.Equal(t, "azID", id)
+							return &Authorization{ID: "azID"}, nil
+						},
+					},
+				},
+				wantErr: NewErrorISE("failed creating key auth digest: error generating JWK thumbprint: go-jose/go-jose: unknown key type '[]uint8'"),
+			}
+		},
 		"ok": func(t *testing.T) test {
 			jwk, keyAuth := mustAccountAndKeyAuthorization(t, "token")
 			payload, signer, root := mustAttestTPM(t, keyAuth, nil) // TODO: value(s) for AK cert?
@@ -403,457 +430,92 @@ func Test_deviceAttest01ValidateWithTPMSimulator(t *testing.T) {
 	}
 }
 
-func newBadAttestationStatementError(msg string) *Error {
-	return &Error{
-		Type:   "urn:ietf:params:acme:error:badAttestationStatement",
-		Status: 400,
-		Err:    errors.New(msg),
-	}
-}
-
-func newInternalServerError(msg string) *Error {
-	return &Error{
-		Type:   "urn:ietf:params:acme:error:serverInternal",
-		Status: 500,
-		Err:    errors.New(msg),
-	}
-}
+var (
+	oidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
+	oidTCGKpAIKCertificate    = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
+)
 
 var (
-	oidPermanentIdentifier          = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 8, 3}
-	oidHardwareModuleNameIdentifier = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 8, 4}
+	oidTPMManufacturer = asn1.ObjectIdentifier{2, 23, 133, 2, 1}
+	oidTPMModel        = asn1.ObjectIdentifier{2, 23, 133, 2, 2}
+	oidTPMVersion      = asn1.ObjectIdentifier{2, 23, 133, 2, 3}
 )
 
-func Test_doTPMAttestationFormat(t *testing.T) {
-	ctx := context.Background()
-	aca, err := minica.New(
-		minica.WithName("TPM Testing"),
-		minica.WithGetSignerFunc(
-			func() (crypto.Signer, error) {
-				return keyutil.GenerateSigner("RSA", "", 2048)
-			},
-		),
-	)
-	require.NoError(t, err)
-	acaRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: aca.Root.Raw})
+// createSubjectAltNameExtension will construct an Extension containing all
+// SubjectAlternativeNames held in a Certificate. It implements more types than
+// the golang x509 library, so it is used whenever OtherName or RegisteredID
+// type SANs are present in the certificate.
+//
+// See also https://datatracker.ietf.org/doc/html/rfc5280.html#section-4.2.1.6
+//
+// TODO(hs): this was copied from go.step.sm/crypto/x509util to make it easier
+// to create the SAN extension for testing purposes. Should it be exposed instead?
+func createSubjectAltNameExtension(dnsNames, emailAddresses x509util.MultiString, ipAddresses x509util.MultiIP, uris x509util.MultiURL, sans []x509util.SubjectAlternativeName, subjectIsEmpty bool) (x509util.Extension, error) {
+	var zero x509util.Extension
+
+	var rawValues []asn1.RawValue
+	for _, dnsName := range dnsNames {
+		rawValue, err := x509util.SubjectAlternativeName{
+			Type: x509util.DNSType, Value: dnsName,
+		}.RawValue()
+		if err != nil {
+			return zero, err
+		}
 
-	// prepare simulated TPM and create an AK
-	stpm := newSimulatedTPM(t)
-	eks, err := stpm.GetEKs(context.Background())
-	require.NoError(t, err)
-	ak, err := stpm.CreateAK(context.Background(), "first-ak")
-	require.NoError(t, err)
-	require.NotNil(t, ak)
+		rawValues = append(rawValues, rawValue)
+	}
 
-	// extract the AK public key // TODO(hs): replace this when there's a simpler method to get the AK public key (e.g. ak.Public())
-	ap, err := ak.AttestationParameters(context.Background())
-	require.NoError(t, err)
-	akp, err := attest.ParseAKPublic(attest.TPMVersion20, ap.Public)
-	require.NoError(t, err)
+	for _, emailAddress := range emailAddresses {
+		rawValue, err := x509util.SubjectAlternativeName{
+			Type: x509util.EmailType, Value: emailAddress,
+		}.RawValue()
+		if err != nil {
+			return zero, err
+		}
 
-	// create template and sign certificate for the AK public key
-	keyID := generateKeyID(t, eks[0].Public())
-	template := &x509.Certificate{
-		PublicKey:          akp.Public,
-		IsCA:               false,
-		UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
+		rawValues = append(rawValues, rawValue)
 	}
-	sans := []x509util.SubjectAlternativeName{}
-	uris := []*url.URL{{Scheme: "urn", Opaque: "ek:sha256:" + base64.StdEncoding.EncodeToString(keyID)}}
-	asn1Value := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMModel, "SLB 9670 TPM2.0", oidTPMVersion, "7.55"))
-	sans = append(sans, x509util.SubjectAlternativeName{
-		Type:      x509util.DirectoryNameType,
-		ASN1Value: asn1Value,
-	})
-	ext, err := createSubjectAltNameExtension(nil, nil, nil, uris, sans, true)
-	require.NoError(t, err)
-	ext.Set(template)
-	akCert, err := aca.Sign(template)
-	require.NoError(t, err)
-	require.NotNil(t, akCert)
 
-	invalidTemplate := &x509.Certificate{
-		PublicKey:          akp.Public,
-		IsCA:               false,
-		UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
+	for _, ip := range ipAddresses {
+		rawValue, err := x509util.SubjectAlternativeName{
+			Type: x509util.IPType, Value: ip.String(),
+		}.RawValue()
+		if err != nil {
+			return zero, err
+		}
+
+		rawValues = append(rawValues, rawValue)
 	}
-	invalidAKCert, err := aca.Sign(invalidTemplate)
-	require.NoError(t, err)
-	require.NotNil(t, invalidAKCert)
 
-	// generate a JWK and the key authorization value
-	jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
-	require.NoError(t, err)
-	keyAuthorization, err := KeyAuthorization("token", jwk)
-	require.NoError(t, err)
+	for _, uri := range uris {
+		rawValue, err := x509util.SubjectAlternativeName{
+			Type: x509util.URIType, Value: uri.String(),
+		}.RawValue()
+		if err != nil {
+			return zero, err
+		}
 
-	// create a new key attested by the AK, while including
-	// the key authorization bytes as qualifying data.
-	keyAuthSum := sha256.Sum256([]byte(keyAuthorization))
-	config := tpm.AttestKeyConfig{
-		Algorithm:      "RSA",
-		Size:           2048,
-		QualifyingData: keyAuthSum[:],
+		rawValues = append(rawValues, rawValue)
 	}
-	key, err := stpm.AttestKey(context.Background(), "first-ak", "first-key", config)
-	require.NoError(t, err)
-	require.NotNil(t, key)
-	params, err := key.CertificationParameters(context.Background())
-	require.NoError(t, err)
 
-	signer, err := key.Signer(context.Background())
-	require.NoError(t, err)
-	fingerprint, err := keyutil.Fingerprint(signer.Public())
-	require.NoError(t, err)
-
-	// attest another key and get its certification parameters
-	anotherKey, err := stpm.AttestKey(context.Background(), "first-ak", "another-key", config)
-	require.NoError(t, err)
-	require.NotNil(t, key)
-	anotherKeyParams, err := anotherKey.CertificationParameters(context.Background())
-	require.NoError(t, err)
+	for _, san := range sans {
+		rawValue, err := san.RawValue()
+		if err != nil {
+			return zero, err
+		}
 
-	type args struct {
-		ctx  context.Context
-		prov Provisioner
-		ch   *Challenge
-		jwk  *jose.JSONWebKey
-		att  *attestationObject
+		rawValues = append(rawValues, rawValue)
 	}
-	tests := []struct {
-		name   string
-		args   args
-		want   *tpmAttestationData
-		expErr *Error
-	}{
-		{"ok", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, nil},
-		{"fail ver not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("ver not present")},
-		{"fail ver type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      []interface{}{},
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("ver not present")},
-		{"fail bogus ver", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "bogus",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError(`version "bogus" is not supported`)},
-		{"fail x5c not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("x5c not present")},
-		{"fail x5c type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      [][]byte{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("x5c not present")},
-		{"fail x5c empty", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("x5c is empty")},
-		{"fail leaf type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "step",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{"leaf", aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("x5c is malformed")},
-		{"fail leaf parse", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "step",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw[:100], aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("x5c is malformed: x509: malformed certificate")},
-		{"fail intermediate type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "step",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, "intermediate"},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("x5c is malformed")},
-		{"fail intermediate parse", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "step",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw[:100]},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("x5c is malformed: x509: malformed certificate")},
-		{"fail roots", args{ctx, mustAttestationProvisioner(t, nil), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newInternalServerError("no root CA bundle available to verify the attestation certificate")},
-		{"fail verify", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "step",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("x5c is not valid: x509: certificate signed by unknown authority")},
-		{"fail validateAKCertificate", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{invalidAKCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("AK certificate is not valid: missing TPM manufacturer")},
-		{"fail pubArea not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-			},
-		}}, nil, newBadAttestationStatementError("invalid pubArea in attestation statement")},
-		{"fail pubArea type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  []interface{}{},
-			},
-		}}, nil, newBadAttestationStatementError("invalid pubArea in attestation statement")},
-		{"fail pubArea empty", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  []byte{},
-			},
-		}}, nil, newBadAttestationStatementError("pubArea is empty")},
-		{"fail sig not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("invalid sig in attestation statement")},
-		{"fail sig type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      []interface{}{},
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("invalid sig in attestation statement")},
-		{"fail sig empty", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      []byte{},
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("sig is empty")},
-		{"fail certInfo not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":     "2.0",
-				"x5c":     []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":     int64(-257), // RS256
-				"sig":     params.CreateSignature,
-				"pubArea": params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("invalid certInfo in attestation statement")},
-		{"fail certInfo type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": []interface{}{},
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("invalid certInfo in attestation statement")},
-		{"fail certInfo empty", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": []byte{},
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("certInfo is empty")},
-		{"fail alg not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("invalid alg in attestation statement")},
-		{"fail alg type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(0), // invalid alg
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("invalid alg 0 in attestation statement")},
-		{"fail attestation verification", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  anotherKeyParams.Public,
-			},
-		}}, nil, newBadAttestationStatementError("invalid certification parameters: certification refers to a different key")},
-		{"fail keyAuthorization", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, &jose.JSONWebKey{Key: []byte("not an asymmetric key")}, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), // RS256
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newInternalServerError("failed creating key auth digest: error generating JWK thumbprint: go-jose/go-jose: unknown key type '[]uint8'")},
-		{"fail different keyAuthorization", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "aDifferentToken"}, jwk, &attestationObject{
-			Format: "tpm",
-			AttStatement: map[string]interface{}{
-				"ver":      "2.0",
-				"x5c":      []interface{}{akCert.Raw, aca.Intermediate.Raw},
-				"alg":      int64(-257), //
-				"sig":      params.CreateSignature,
-				"certInfo": params.CreateAttestation,
-				"pubArea":  params.Public,
-			},
-		}}, nil, newBadAttestationStatementError("key authorization invalid")},
-	}
-	for _, tt := range tests {
-		t.Run(tt.name, func(t *testing.T) {
-			got, err := doTPMAttestationFormat(tt.args.ctx, tt.args.prov, tt.args.ch, tt.args.jwk, tt.args.att)
-			if tt.expErr != nil {
-				var ae *Error
-				if assert.True(t, errors.As(err, &ae)) {
-					assert.EqualError(t, err, tt.expErr.Error())
-					assert.Equal(t, ae.StatusCode(), tt.expErr.StatusCode())
-					assert.Equal(t, ae.Type, tt.expErr.Type)
-				}
-				assert.Nil(t, got)
-				return
-			}
 
-			assert.NoError(t, err)
-			if assert.NotNil(t, got) {
-				assert.Equal(t, akCert, got.Certificate)
-				assert.Equal(t, [][]*x509.Certificate{
-					{
-						akCert, aca.Intermediate, aca.Root,
-					},
-				}, got.VerifiedChains)
-				assert.Equal(t, fingerprint, got.Fingerprint)
-				assert.Empty(t, got.PermanentIdentifiers) // currently expected to be always empty
-			}
-		})
+	// Now marshal the rawValues into the ASN1 sequence, and create an Extension object to hold the extension
+	rawBytes, err := asn1.Marshal(rawValues)
+	if err != nil {
+		return zero, fmt.Errorf("error marshaling SubjectAlternativeName extension to ASN1: %w", err)
 	}
+
+	return x509util.Extension{
+		ID:       x509util.ObjectIdentifier(oidSubjectAlternativeName),
+		Critical: subjectIsEmpty,
+		Value:    rawBytes,
+	}, nil
 }

+ 329 - 0
attestation/tpm/tpm.go

@@ -0,0 +1,329 @@
+// Package tpm verifies attestation statements of the "tpm" format of ACME
+// device-attest-01 challenges, made with the attestation keys of TPM 2.0
+// devices.
+package tpm
+
+import (
+	"crypto"
+	"crypto/sha256"
+	"crypto/subtle"
+	"crypto/x509"
+	"encoding/asn1"
+	"errors"
+	"fmt"
+	"time"
+
+	"github.com/google/go-tpm/legacy/tpm2"
+	"github.com/smallstep/go-attestation/attest"
+	"go.step.sm/crypto/keyutil"
+	"go.step.sm/crypto/x509util"
+
+	"github.com/smallstep/certificates/attestation"
+	"github.com/smallstep/certificates/internal/cast"
+)
+
+var (
+	oidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
+)
+
+// Data is what a verified "tpm" attestation statement attests.
+type Data struct {
+	// Certificate is the AK certificate, the leaf of the x5c chain.
+	Certificate *x509.Certificate
+	// VerifiedChains are the chains from the AK certificate to the roots.
+	VerifiedChains [][]*x509.Certificate
+	// PermanentIdentifiers are the permanent identifiers in the Subject
+	// Alternative Names of the AK certificate.
+	PermanentIdentifiers []string
+	// Fingerprint is the fingerprint of the attested key.
+	Fingerprint string
+}
+
+// coseAlgorithmIdentifier models a COSEAlgorithmIdentifier.
+// Also see https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier.
+type coseAlgorithmIdentifier int32
+
+const (
+	coseAlgES256 = coseAlgorithmIdentifier(-7)
+	coseAlgRS256 = coseAlgorithmIdentifier(-257)
+	coseAlgRS1   = coseAlgorithmIdentifier(-65535) // deprecated, but (still) often used in TPMs
+)
+
+// Verify verifies a "tpm" attestation statement: the x5c chain of its AK
+// certificate against roots, the requirements on the AK certificate, the
+// certification of the attested key by the AK, and that the certification's
+// extra data is the SHA-256 digest of keyAuth, the key authorization of the
+// challenge. It returns what the AK certificate and the certification attest.
+// There are no default roots: Verify fails if roots is nil. Errors of the
+// statement match attestation.ErrInvalidEvidence.
+func Verify(attStmt map[string]any, roots *x509.CertPool, keyAuth []byte) (*Data, error) {
+	ver, ok := attStmt["ver"].(string)
+	if !ok {
+		return nil, attestation.Invalidf("ver not present")
+	}
+	if ver != "2.0" {
+		return nil, attestation.Invalidf("version %q is not supported", ver)
+	}
+
+	x5c, ok := attStmt["x5c"].([]any)
+	if !ok {
+		return nil, attestation.Invalidf("x5c not present")
+	}
+	if len(x5c) == 0 {
+		return nil, attestation.Invalidf("x5c is empty")
+	}
+
+	akCertBytes, ok := x5c[0].([]byte)
+	if !ok {
+		return nil, attestation.Invalidf("x5c is malformed")
+	}
+	akCert, err := x509.ParseCertificate(akCertBytes)
+	if err != nil {
+		return nil, attestation.Invalidf("x5c is malformed: %w", err)
+	}
+
+	intermediates := x509.NewCertPool()
+	for _, v := range x5c[1:] {
+		intCertBytes, vok := v.([]byte)
+		if !vok {
+			return nil, attestation.Invalidf("x5c is malformed")
+		}
+		intCert, err := x509.ParseCertificate(intCertBytes)
+		if err != nil {
+			return nil, attestation.Invalidf("x5c is malformed: %w", err)
+		}
+		intermediates.AddCert(intCert)
+	}
+
+	// TODO(hs): this can be removed when permanent-identifier/hardware-module-name are handled correctly in
+	// the stdlib in https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/crypto/x509/parser.go;drc=b5b2cf519fe332891c165077f3723ee74932a647;l=362,
+	// but I doubt that will happen.
+	if len(akCert.UnhandledCriticalExtensions) > 0 {
+		unhandledCriticalExtensions := akCert.UnhandledCriticalExtensions[:0]
+		for _, extOID := range akCert.UnhandledCriticalExtensions {
+			if !extOID.Equal(oidSubjectAlternativeName) {
+				// critical extensions other than the Subject Alternative Name remain unhandled
+				unhandledCriticalExtensions = append(unhandledCriticalExtensions, extOID)
+			}
+		}
+		akCert.UnhandledCriticalExtensions = unhandledCriticalExtensions
+	}
+
+	if roots == nil {
+		return nil, errors.New("no root CA bundle available to verify the attestation certificate")
+	}
+
+	// verify that the AK certificate was signed by a trusted root,
+	// chained to by the intermediates provided by the client. As part
+	// of building the verified certificate chain, the signature over the
+	// AK certificate is checked to be a valid signature of one of the
+	// provided intermediates. Signatures over the intermediates are in
+	// turn also verified to be valid signatures from one of the trusted
+	// roots.
+	verifiedChains, err := akCert.Verify(x509.VerifyOptions{
+		Roots:         roots,
+		Intermediates: intermediates,
+		CurrentTime:   time.Now().Truncate(time.Second),
+		KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
+	})
+	if err != nil {
+		return nil, attestation.Invalidf("x5c is not valid: %w", err)
+	}
+
+	// validate additional AK certificate requirements
+	if err := validateAKCertificate(akCert); err != nil {
+		return nil, attestation.Invalidf("AK certificate is not valid: %w", err)
+	}
+
+	// TODO(hs): implement revocation check; Verify() doesn't perform CRL check nor OCSP lookup.
+
+	sans, err := x509util.ParseSubjectAlternativeNames(akCert)
+	if err != nil {
+		return nil, attestation.Invalidf("failed parsing AK certificate Subject Alternative Names: %w", err)
+	}
+
+	permanentIdentifiers := make([]string, len(sans.PermanentIdentifiers))
+	for i, pi := range sans.PermanentIdentifiers {
+		permanentIdentifiers[i] = pi.Identifier
+	}
+
+	// extract and validate pubArea, sig, certInfo and alg properties from the request body
+	pubArea, ok := attStmt["pubArea"].([]byte)
+	if !ok {
+		return nil, attestation.Invalidf("invalid pubArea in attestation statement")
+	}
+	if len(pubArea) == 0 {
+		return nil, attestation.Invalidf("pubArea is empty")
+	}
+
+	sig, ok := attStmt["sig"].([]byte)
+	if !ok {
+		return nil, attestation.Invalidf("invalid sig in attestation statement")
+	}
+	if len(sig) == 0 {
+		return nil, attestation.Invalidf("sig is empty")
+	}
+
+	certInfo, ok := attStmt["certInfo"].([]byte)
+	if !ok {
+		return nil, attestation.Invalidf("invalid certInfo in attestation statement")
+	}
+	if len(certInfo) == 0 {
+		return nil, attestation.Invalidf("certInfo is empty")
+	}
+
+	alg, ok := attStmt["alg"].(int64)
+	if !ok {
+		return nil, attestation.Invalidf("invalid alg in attestation statement")
+	}
+
+	algI32, err := cast.SafeInt32(alg)
+	if err != nil {
+		return nil, attestation.Invalidf("invalid alg %d in attestation statement: %w", alg, err)
+	}
+
+	var hash crypto.Hash
+	switch coseAlgorithmIdentifier(algI32) {
+	case coseAlgRS256, coseAlgES256:
+		hash = crypto.SHA256
+	case coseAlgRS1:
+		hash = crypto.SHA1
+	default:
+		return nil, attestation.Invalidf("invalid alg %d in attestation statement", alg)
+	}
+
+	// recreate the generated key certification parameter values and verify
+	// the attested key using the public key of the AK.
+	certificationParameters := &attest.CertificationParameters{
+		Public:            pubArea,  // the public key that was attested
+		CreateAttestation: certInfo, // the attested properties of the key
+		CreateSignature:   sig,      // signature over the attested properties
+	}
+	verifyOpts := attest.VerifyOpts{
+		Public: akCert.PublicKey, // public key of the AK that attested the key
+		Hash:   hash,
+	}
+	if err = certificationParameters.Verify(verifyOpts); err != nil {
+		return nil, attestation.Invalidf("invalid certification parameters: %w", err)
+	}
+
+	// decode the "certInfo" data. This won't fail, as it's also done as part of Verify().
+	tpmCertInfo, err := tpm2.DecodeAttestationData(certInfo)
+	if err != nil {
+		return nil, attestation.Invalidf("failed decoding attestation data: %w", err)
+	}
+
+	hashedKeyAuth := sha256.Sum256(keyAuth)
+
+	// verify the WebAuthn object contains the expect key authorization digest, which is carried
+	// within the encoded `certInfo` property of the attestation statement.
+	if subtle.ConstantTimeCompare(hashedKeyAuth[:], []byte(tpmCertInfo.ExtraData)) == 0 {
+		return nil, attestation.Invalidf("key authorization invalid")
+	}
+
+	// decode the (attested) public key and determine its fingerprint.  This won't fail, as it's also done as part of Verify().
+	pub, err := tpm2.DecodePublic(pubArea)
+	if err != nil {
+		return nil, attestation.Invalidf("failed decoding pubArea: %w", err)
+	}
+
+	publicKey, err := pub.Key()
+	if err != nil {
+		return nil, attestation.Invalidf("failed getting public key: %w", err)
+	}
+
+	data := &Data{
+		Certificate:          akCert,
+		VerifiedChains:       verifiedChains,
+		PermanentIdentifiers: permanentIdentifiers,
+	}
+
+	if data.Fingerprint, err = keyutil.Fingerprint(publicKey); err != nil {
+		return nil, fmt.Errorf("error calculating key fingerprint: %w", err)
+	}
+
+	// TODO(hs): pass more attestation data, so that that can be used/recorded too?
+	return data, nil
+}
+
+var (
+	oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
+	oidTCGKpAIKCertificate       = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
+)
+
+// validateAKCertificate validates the X.509 AK certificate to be
+// in accordance with the required properties. The requirements come from:
+// https://www.w3.org/TR/webauthn-2/#sctn-tpm-cert-requirements.
+//
+//   - Version MUST be set to 3.
+//   - Subject field MUST be set to empty.
+//   - The Subject Alternative Name extension MUST be set as defined
+//     in [TPMv2-EK-Profile] section 3.2.9.
+//   - The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
+//     ("joint-iso-itu-t(2) international-organizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)").
+//   - The Basic Constraints extension MUST have the CA component set to false.
+//   - An Authority Information Access (AIA) extension with entry id-ad-ocsp
+//     and a CRL Distribution Point extension [RFC5280] are both OPTIONAL as
+//     the status of many attestation certificates is available through metadata
+//     services. See, for example, the FIDO Metadata Service.
+func validateAKCertificate(c *x509.Certificate) error {
+	if c.Version != 3 {
+		return fmt.Errorf("AK certificate has invalid version %d; only version 3 is allowed", c.Version)
+	}
+	if c.Subject.String() != "" {
+		return fmt.Errorf("AK certificate subject must be empty; got %q", c.Subject)
+	}
+	if c.IsCA {
+		return errors.New("AK certificate must not be a CA")
+	}
+	if err := validateAKCertificateExtendedKeyUsage(c); err != nil {
+		return err
+	}
+	return validateAKCertificateSubjectAlternativeNames(c)
+}
+
+// validateAKCertificateSubjectAlternativeNames checks if the AK certificate
+// has TPM hardware details set.
+func validateAKCertificateSubjectAlternativeNames(c *x509.Certificate) error {
+	sans, err := x509util.ParseSubjectAlternativeNames(c)
+	if err != nil {
+		return fmt.Errorf("failed parsing AK certificate Subject Alternative Names: %w", err)
+	}
+
+	details := sans.TPMHardwareDetails
+	manufacturer, model, version := details.Manufacturer, details.Model, details.Version
+
+	switch {
+	case manufacturer == "":
+		return errors.New("missing TPM manufacturer")
+	case model == "":
+		return errors.New("missing TPM model")
+	case version == "":
+		return errors.New("missing TPM version")
+	}
+
+	return nil
+}
+
+// validateAKCertificateExtendedKeyUsage checks if the AK certificate
+// has the "tcg-kp-AIKCertificate" Extended Key Usage set.
+func validateAKCertificateExtendedKeyUsage(c *x509.Certificate) error {
+	var (
+		valid = false
+		ekus  []asn1.ObjectIdentifier
+	)
+	for _, ext := range c.Extensions {
+		if ext.Id.Equal(oidExtensionExtendedKeyUsage) {
+			if _, err := asn1.Unmarshal(ext.Value, &ekus); err != nil || len(ekus) == 0 || !ekus[0].Equal(oidTCGKpAIKCertificate) {
+				return errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")
+			}
+			valid = true
+		}
+	}
+
+	if !valid {
+		return errors.New("AK certificate is missing Extended Key Usage extension")
+	}
+
+	return nil
+}

+ 316 - 0
attestation/tpm/tpm_test.go

@@ -0,0 +1,316 @@
+package tpm
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/asn1"
+	"errors"
+	"fmt"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"go.step.sm/crypto/minica"
+	"go.step.sm/crypto/x509util"
+)
+
+var (
+	oidTPMManufacturer = asn1.ObjectIdentifier{2, 23, 133, 2, 1}
+	oidTPMModel        = asn1.ObjectIdentifier{2, 23, 133, 2, 2}
+	oidTPMVersion      = asn1.ObjectIdentifier{2, 23, 133, 2, 3}
+)
+
+func generateValidAKCertificate(t *testing.T) *x509.Certificate {
+	t.Helper()
+	signer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	require.NoError(t, err)
+	template := &x509.Certificate{
+		PublicKey:          signer.Public(),
+		Version:            3,
+		IsCA:               false,
+		UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
+	}
+	asn1Value := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMModel, "SLB 9670 TPM2.0", oidTPMVersion, "7.55"))
+	sans := []x509util.SubjectAlternativeName{
+		{Type: x509util.DirectoryNameType,
+			ASN1Value: asn1Value},
+	}
+	ext, err := createSubjectAltNameExtension(nil, nil, nil, nil, sans, true)
+	require.NoError(t, err)
+	ext.Set(template)
+	ca, err := minica.New()
+	require.NoError(t, err)
+	cert, err := ca.Sign(template)
+	require.NoError(t, err)
+
+	return cert
+}
+
+func Test_validateAKCertificate(t *testing.T) {
+	cert := generateValidAKCertificate(t)
+	tests := []struct {
+		name   string
+		c      *x509.Certificate
+		expErr error
+	}{
+		{
+			name:   "ok",
+			c:      cert,
+			expErr: nil,
+		},
+		{
+			name: "fail/version",
+			c: &x509.Certificate{
+				Version: 1,
+			},
+			expErr: errors.New("AK certificate has invalid version 1; only version 3 is allowed"),
+		},
+		{
+			name: "fail/subject",
+			c: &x509.Certificate{
+				Version: 3,
+				Subject: pkix.Name{CommonName: "fail!"},
+			},
+			expErr: errors.New(`AK certificate subject must be empty; got "CN=fail!"`),
+		},
+		{
+			name: "fail/isCA",
+			c: &x509.Certificate{
+				Version: 3,
+				IsCA:    true,
+			},
+			expErr: errors.New("AK certificate must not be a CA"),
+		},
+		{
+			name: "fail/extendedKeyUsage",
+			c: &x509.Certificate{
+				Version: 3,
+			},
+			expErr: errors.New("AK certificate is missing Extended Key Usage extension"),
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			err := validateAKCertificate(tt.c)
+			if tt.expErr != nil {
+				if assert.Error(t, err) {
+					assert.EqualError(t, err, tt.expErr.Error())
+				}
+				return
+			}
+
+			assert.NoError(t, err)
+		})
+	}
+}
+
+func Test_validateAKCertificateSubjectAlternativeNames(t *testing.T) {
+	ok := generateValidAKCertificate(t)
+	t.Helper()
+	signer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	require.NoError(t, err)
+
+	getBase := func() *x509.Certificate {
+		return &x509.Certificate{
+			PublicKey:          signer.Public(),
+			Version:            3,
+			IsCA:               false,
+			UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
+		}
+	}
+
+	ca, err := minica.New()
+	require.NoError(t, err)
+	missingManufacturerASN1 := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMModel, "SLB 9670 TPM2.0", oidTPMVersion, "7.55"))
+	sans := []x509util.SubjectAlternativeName{
+		{Type: x509util.DirectoryNameType,
+			ASN1Value: missingManufacturerASN1},
+	}
+	ext, err := createSubjectAltNameExtension(nil, nil, nil, nil, sans, true)
+	require.NoError(t, err)
+	missingManufacturer := getBase()
+	ext.Set(missingManufacturer)
+
+	missingManufacturer, err = ca.Sign(missingManufacturer)
+	require.NoError(t, err)
+
+	missingModelASN1 := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMVersion, "7.55"))
+	sans = []x509util.SubjectAlternativeName{
+		{Type: x509util.DirectoryNameType,
+			ASN1Value: missingModelASN1},
+	}
+	ext, err = createSubjectAltNameExtension(nil, nil, nil, nil, sans, true)
+	require.NoError(t, err)
+	missingModel := getBase()
+	ext.Set(missingModel)
+
+	missingModel, err = ca.Sign(missingModel)
+	require.NoError(t, err)
+
+	missingFirmwareVersionASN1 := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMModel, "SLB 9670 TPM2.0"))
+	sans = []x509util.SubjectAlternativeName{
+		{Type: x509util.DirectoryNameType,
+			ASN1Value: missingFirmwareVersionASN1},
+	}
+	ext, err = createSubjectAltNameExtension(nil, nil, nil, nil, sans, true)
+	require.NoError(t, err)
+	missingFirmwareVersion := getBase()
+	ext.Set(missingFirmwareVersion)
+
+	missingFirmwareVersion, err = ca.Sign(missingFirmwareVersion)
+	require.NoError(t, err)
+
+	tests := []struct {
+		name   string
+		c      *x509.Certificate
+		expErr error
+	}{
+		{"ok", ok, nil},
+		{"fail/missing-manufacturer", missingManufacturer, errors.New("missing TPM manufacturer")},
+		{"fail/missing-model", missingModel, errors.New("missing TPM model")},
+		{"fail/missing-firmware-version", missingFirmwareVersion, errors.New("missing TPM version")},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			err := validateAKCertificateSubjectAlternativeNames(tt.c)
+			if tt.expErr != nil {
+				if assert.Error(t, err) {
+					assert.EqualError(t, err, tt.expErr.Error())
+				}
+				return
+			}
+
+			assert.NoError(t, err)
+		})
+	}
+}
+
+func Test_validateAKCertificateExtendedKeyUsage(t *testing.T) {
+	ok := generateValidAKCertificate(t)
+	missingEKU := &x509.Certificate{}
+	t.Helper()
+	signer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	require.NoError(t, err)
+	template := &x509.Certificate{
+		PublicKey:   signer.Public(),
+		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+	}
+	ca, err := minica.New()
+	require.NoError(t, err)
+	wrongEKU, err := ca.Sign(template)
+	require.NoError(t, err)
+	emptyEKU, err := ca.Sign(&x509.Certificate{
+		PublicKey: signer.Public(),
+		ExtraExtensions: []pkix.Extension{{
+			Id:    oidExtensionExtendedKeyUsage,
+			Value: []byte{0x30, 0x00}, // DER: empty SEQUENCE
+		}},
+	})
+	require.NoError(t, err)
+
+	tests := []struct {
+		name   string
+		c      *x509.Certificate
+		expErr error
+	}{
+		{"ok", ok, nil},
+		{"fail/wrong-eku", wrongEKU, errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")},
+		{"fail/empty-eku", emptyEKU, errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")},
+		{"fail/missing-eku", missingEKU, errors.New("AK certificate is missing Extended Key Usage extension")},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			err := validateAKCertificateExtendedKeyUsage(tt.c)
+			if tt.expErr != nil {
+				if assert.Error(t, err) {
+					assert.EqualError(t, err, tt.expErr.Error())
+				}
+				return
+			}
+
+			assert.NoError(t, err)
+		})
+	}
+}
+
+// createSubjectAltNameExtension will construct an Extension containing all
+// SubjectAlternativeNames held in a Certificate. It implements more types than
+// the golang x509 library, so it is used whenever OtherName or RegisteredID
+// type SANs are present in the certificate.
+//
+// See also https://datatracker.ietf.org/doc/html/rfc5280.html#section-4.2.1.6
+//
+// TODO(hs): this was copied from go.step.sm/crypto/x509util to make it easier
+// to create the SAN extension for testing purposes. Should it be exposed instead?
+func createSubjectAltNameExtension(dnsNames, emailAddresses x509util.MultiString, ipAddresses x509util.MultiIP, uris x509util.MultiURL, sans []x509util.SubjectAlternativeName, subjectIsEmpty bool) (x509util.Extension, error) {
+	var zero x509util.Extension
+
+	var rawValues []asn1.RawValue
+	for _, dnsName := range dnsNames {
+		rawValue, err := x509util.SubjectAlternativeName{
+			Type: x509util.DNSType, Value: dnsName,
+		}.RawValue()
+		if err != nil {
+			return zero, err
+		}
+
+		rawValues = append(rawValues, rawValue)
+	}
+
+	for _, emailAddress := range emailAddresses {
+		rawValue, err := x509util.SubjectAlternativeName{
+			Type: x509util.EmailType, Value: emailAddress,
+		}.RawValue()
+		if err != nil {
+			return zero, err
+		}
+
+		rawValues = append(rawValues, rawValue)
+	}
+
+	for _, ip := range ipAddresses {
+		rawValue, err := x509util.SubjectAlternativeName{
+			Type: x509util.IPType, Value: ip.String(),
+		}.RawValue()
+		if err != nil {
+			return zero, err
+		}
+
+		rawValues = append(rawValues, rawValue)
+	}
+
+	for _, uri := range uris {
+		rawValue, err := x509util.SubjectAlternativeName{
+			Type: x509util.URIType, Value: uri.String(),
+		}.RawValue()
+		if err != nil {
+			return zero, err
+		}
+
+		rawValues = append(rawValues, rawValue)
+	}
+
+	for _, san := range sans {
+		rawValue, err := san.RawValue()
+		if err != nil {
+			return zero, err
+		}
+
+		rawValues = append(rawValues, rawValue)
+	}
+
+	// Now marshal the rawValues into the ASN1 sequence, and create an Extension object to hold the extension
+	rawBytes, err := asn1.Marshal(rawValues)
+	if err != nil {
+		return zero, fmt.Errorf("error marshaling SubjectAlternativeName extension to ASN1: %w", err)
+	}
+
+	return x509util.Extension{
+		ID:       x509util.ObjectIdentifier(oidSubjectAlternativeName),
+		Critical: subjectIsEmpty,
+		Value:    rawBytes,
+	}, nil
+}

+ 398 - 0
attestation/tpm/tpm_tpmsimulator_test.go

@@ -0,0 +1,398 @@
+//go:build tpmsimulator
+
+package tpm
+
+import (
+	"context"
+	"crypto"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/asn1"
+	"encoding/base64"
+	"errors"
+	"fmt"
+	"net/url"
+	"testing"
+
+	"github.com/smallstep/go-attestation/attest"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"go.step.sm/crypto/keyutil"
+	"go.step.sm/crypto/minica"
+	steptpm "go.step.sm/crypto/tpm"
+	"go.step.sm/crypto/tpm/simulator"
+	tpmstorage "go.step.sm/crypto/tpm/storage"
+	"go.step.sm/crypto/x509util"
+
+	"github.com/smallstep/certificates/attestation"
+)
+
+// keyAuth is the key authorization the attested key certifies.
+var keyAuth = []byte("token.thumbprint")
+
+func invalidEvidence(msg string) error {
+	return attestation.Invalidf("%s", msg)
+}
+
+func newSimulatedTPM(t *testing.T) *steptpm.TPM {
+	t.Helper()
+	tmpDir := t.TempDir()
+	tpm, err := steptpm.New(withSimulator(t), steptpm.WithStore(tpmstorage.NewDirstore(tmpDir))) // TODO: provide in-memory storage implementation instead
+	require.NoError(t, err)
+	return tpm
+}
+
+func withSimulator(t *testing.T) steptpm.NewTPMOption {
+	t.Helper()
+	var sim simulator.Simulator
+	t.Cleanup(func() {
+		if sim == nil {
+			return
+		}
+		err := sim.Close()
+		require.NoError(t, err)
+	})
+	sim, err := simulator.New()
+	require.NoError(t, err)
+	err = sim.Open()
+	require.NoError(t, err)
+	return steptpm.WithSimulator(sim)
+}
+
+func generateKeyID(t *testing.T, pub crypto.PublicKey) []byte {
+	t.Helper()
+	b, err := x509.MarshalPKIXPublicKey(pub)
+	require.NoError(t, err)
+	hash := sha256.Sum256(b)
+	return hash[:]
+}
+
+func TestVerify(t *testing.T) {
+	aca, err := minica.New(
+		minica.WithName("TPM Testing"),
+		minica.WithGetSignerFunc(
+			func() (crypto.Signer, error) {
+				return keyutil.GenerateSigner("RSA", "", 2048)
+			},
+		),
+	)
+	require.NoError(t, err)
+	roots := x509.NewCertPool()
+	roots.AddCert(aca.Root)
+
+	// prepare simulated TPM and create an AK
+	stpm := newSimulatedTPM(t)
+	eks, err := stpm.GetEKs(context.Background())
+	require.NoError(t, err)
+	ak, err := stpm.CreateAK(context.Background(), "first-ak")
+	require.NoError(t, err)
+	require.NotNil(t, ak)
+
+	// extract the AK public key // TODO(hs): replace this when there's a simpler method to get the AK public key (e.g. ak.Public())
+	ap, err := ak.AttestationParameters(context.Background())
+	require.NoError(t, err)
+	akp, err := attest.ParseAKPublic(attest.TPMVersion20, ap.Public)
+	require.NoError(t, err)
+
+	// create template and sign certificate for the AK public key
+	keyID := generateKeyID(t, eks[0].Public())
+	template := &x509.Certificate{
+		PublicKey:          akp.Public,
+		IsCA:               false,
+		UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
+	}
+	sans := []x509util.SubjectAlternativeName{}
+	uris := []*url.URL{{Scheme: "urn", Opaque: "ek:sha256:" + base64.StdEncoding.EncodeToString(keyID)}}
+	asn1Value := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMModel, "SLB 9670 TPM2.0", oidTPMVersion, "7.55"))
+	sans = append(sans, x509util.SubjectAlternativeName{
+		Type:      x509util.DirectoryNameType,
+		ASN1Value: asn1Value,
+	})
+	ext, err := createSubjectAltNameExtension(nil, nil, nil, uris, sans, true)
+	require.NoError(t, err)
+	ext.Set(template)
+	akCert, err := aca.Sign(template)
+	require.NoError(t, err)
+	require.NotNil(t, akCert)
+
+	invalidTemplate := &x509.Certificate{
+		PublicKey:          akp.Public,
+		IsCA:               false,
+		UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
+	}
+	invalidAKCert, err := aca.Sign(invalidTemplate)
+	require.NoError(t, err)
+	require.NotNil(t, invalidAKCert)
+
+	// create a new key attested by the AK, while including
+	// the key authorization bytes as qualifying data.
+	keyAuthSum := sha256.Sum256(keyAuth)
+	config := steptpm.AttestKeyConfig{
+		Algorithm:      "RSA",
+		Size:           2048,
+		QualifyingData: keyAuthSum[:],
+	}
+	key, err := stpm.AttestKey(context.Background(), "first-ak", "first-key", config)
+	require.NoError(t, err)
+	require.NotNil(t, key)
+	params, err := key.CertificationParameters(context.Background())
+	require.NoError(t, err)
+
+	signer, err := key.Signer(context.Background())
+	require.NoError(t, err)
+	fingerprint, err := keyutil.Fingerprint(signer.Public())
+	require.NoError(t, err)
+
+	// attest another key and get its certification parameters
+	anotherKey, err := stpm.AttestKey(context.Background(), "first-ak", "another-key", config)
+	require.NoError(t, err)
+	require.NotNil(t, key)
+	anotherKeyParams, err := anotherKey.CertificationParameters(context.Background())
+	require.NoError(t, err)
+
+	type args struct {
+		roots   *x509.CertPool
+		keyAuth []byte
+		attStmt map[string]any
+	}
+	tests := []struct {
+		name   string
+		args   args
+		want   *Data
+		expErr error
+	}{
+		{"ok", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, nil},
+		{"fail ver not present", args{roots, keyAuth, map[string]any{
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("ver not present")},
+		{"fail ver type", args{roots, keyAuth, map[string]any{
+			"ver":      []any{},
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("ver not present")},
+		{"fail bogus ver", args{roots, keyAuth, map[string]any{
+			"ver":      "bogus",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence(`version "bogus" is not supported`)},
+		{"fail x5c not present", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("x5c not present")},
+		{"fail x5c type", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      [][]byte{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("x5c not present")},
+		{"fail x5c empty", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("x5c is empty")},
+		{"fail leaf type", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{"leaf", aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("x5c is malformed")},
+		{"fail leaf parse", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw[:100], aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("x5c is malformed: x509: malformed certificate")},
+		{"fail intermediate type", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, "intermediate"},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("x5c is malformed")},
+		{"fail intermediate parse", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw[:100]},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("x5c is malformed: x509: malformed certificate")},
+		{"fail roots", args{nil, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, errors.New("no root CA bundle available to verify the attestation certificate")},
+		{"fail verify", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("x5c is not valid: x509: certificate signed by unknown authority")},
+		{"fail validateAKCertificate", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{invalidAKCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("AK certificate is not valid: missing TPM manufacturer")},
+		{"fail pubArea not present", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+		}}, nil, invalidEvidence("invalid pubArea in attestation statement")},
+		{"fail pubArea type", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  []any{},
+		}}, nil, invalidEvidence("invalid pubArea in attestation statement")},
+		{"fail pubArea empty", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  []byte{},
+		}}, nil, invalidEvidence("pubArea is empty")},
+		{"fail sig not present", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("invalid sig in attestation statement")},
+		{"fail sig type", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      []any{},
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("invalid sig in attestation statement")},
+		{"fail sig empty", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      []byte{},
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("sig is empty")},
+		{"fail certInfo not present", args{roots, keyAuth, map[string]any{
+			"ver":     "2.0",
+			"x5c":     []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":     int64(-257), // RS256
+			"sig":     params.CreateSignature,
+			"pubArea": params.Public,
+		}}, nil, invalidEvidence("invalid certInfo in attestation statement")},
+		{"fail certInfo type", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": []any{},
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("invalid certInfo in attestation statement")},
+		{"fail certInfo empty", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": []byte{},
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("certInfo is empty")},
+		{"fail alg not present", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("invalid alg in attestation statement")},
+		{"fail alg type", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(0), // invalid alg
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("invalid alg 0 in attestation statement")},
+		{"fail attestation verification", args{roots, keyAuth, map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), // RS256
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  anotherKeyParams.Public,
+		}}, nil, invalidEvidence("invalid certification parameters: certification refers to a different key")},
+		{"fail different keyAuthorization", args{roots, []byte("aDifferentToken.thumbprint"), map[string]any{
+			"ver":      "2.0",
+			"x5c":      []any{akCert.Raw, aca.Intermediate.Raw},
+			"alg":      int64(-257), //
+			"sig":      params.CreateSignature,
+			"certInfo": params.CreateAttestation,
+			"pubArea":  params.Public,
+		}}, nil, invalidEvidence("key authorization invalid")},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := Verify(tt.args.attStmt, tt.args.roots, tt.args.keyAuth)
+			if tt.expErr != nil {
+				assert.EqualError(t, err, tt.expErr.Error())
+				assert.Equal(t, errors.Is(tt.expErr, attestation.ErrInvalidEvidence), errors.Is(err, attestation.ErrInvalidEvidence))
+				assert.Nil(t, got)
+				return
+			}
+
+			assert.NoError(t, err)
+			if assert.NotNil(t, got) {
+				assert.Equal(t, akCert, got.Certificate)
+				assert.Equal(t, [][]*x509.Certificate{
+					{
+						akCert, aca.Intermediate, aca.Root,
+					},
+				}, got.VerifiedChains)
+				assert.Equal(t, fingerprint, got.Fingerprint)
+				assert.Empty(t, got.PermanentIdentifiers) // currently expected to be always empty
+			}
+		})
+	}
+}