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

Move the android-key device attestation verifier to attestation/androidkey

The verifier of the "android-key" format of device-attest-01 moves from
acme/challenge.go to attestation/androidkey, with Google's roots, and
uses the signature check in attestation/internal/keyauth, so acme's copy
goes. androidkey.Verify takes the attestation statement, the roots, nil
for Google's, the key authorization and a revocation checker, and
returns the attestation certificate, its key's fingerprint and its key
description. acme builds the checker from the provisioner's
IsAndroidCertificateRevoked, so the CRL cache stays in
authority/provisioner, and keeps the provisioner type check, the
security level and device serial checks. With every format moved, the
TODO to move attestation verification to a shared package goes too.

acme maps the verifier's errors back to the ACME errors it returned
before: androidkey.ErrEmptyX5C keeps an empty x5c a rejectedIdentifier,
androidkey.ErrKeyDescription keeps an unparsable key attestation
extension a bad attestation statement without detail, and a revocation
check failure stays an internal error. androidkey.Verify refuses a nil
revocation checker, which acme never passes. There were no verifier
tests to move; the package gets its own.

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 месяц назад
Родитель
Сommit
56e7c348ca
4 измененных файлов с 464 добавлено и 298 удалено
  1. 20 298
      acme/challenge.go
  2. 10 0
      acme/challenge_test.go
  3. 277 0
      attestation/androidkey/androidkey.go
  4. 157 0
      attestation/androidkey/androidkey_test.go

+ 20 - 298
acme/challenge.go

@@ -4,10 +4,6 @@ import (
 	"bytes"
 	"context"
 	"crypto"
-	"crypto/ecdsa"
-	"crypto/ed25519"
-	"crypto/elliptic"
-	"crypto/rsa"
 	"crypto/sha256"
 	"crypto/subtle"
 	"crypto/tls"
@@ -29,15 +25,11 @@ import (
 
 	"github.com/coreos/go-oidc/v3/oidc"
 	"github.com/fxamacker/cbor/v2"
-
-	androidattestation "github.com/smallstep/android-attestation"
 	"go.step.sm/crypto/jose"
-	"go.step.sm/crypto/keyutil"
-	"go.step.sm/crypto/mldsa"
-	"go.step.sm/crypto/pemutil"
 
 	"github.com/smallstep/certificates/acme/wire"
 	"github.com/smallstep/certificates/attestation"
+	"github.com/smallstep/certificates/attestation/androidkey"
 	"github.com/smallstep/certificates/attestation/apple"
 	"github.com/smallstep/certificates/attestation/tpm"
 	"github.com/smallstep/certificates/attestation/yubikey"
@@ -800,7 +792,6 @@ type attestationObject struct {
 	AttStatement map[string]any `json:"attStmt,omitempty"`
 }
 
-// TODO(bweeks): move attestation verification to a shared package.
 func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
 	// Update challenge with the payload
 	ch.Payload = payload
@@ -858,28 +849,30 @@ func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose
 
 	switch format {
 	case "android-key":
-		data, err := doAndroidKeyAttestationFormat(ctx, prov, ch, jwk, &att)
+		acmeProv, ok := prov.(*provisioner.ACME)
+		if !ok {
+			return NewErrorISE("provisioner in context is not an ACME provisioner")
+		}
+		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 err
+		}
+		data, err := androidkey.Verify(ctx, att.AttStatement, attestationRoots(prov), []byte(keyAuth), acmeProv.IsAndroidCertificateRevoked)
+		if err != nil {
+			return storeAttestationError(ctx, db, ch, err)
 		}
 
 		// Enforce hardware security level (TrustedEnvironment or StrongBox; Software not allowed)
-		if data.Attestation.AttestationSecurityLevel < 1 {
-			return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "insufficient security level: %d", data.Attestation.AttestationSecurityLevel))
+		if data.KeyDescription.AttestationSecurityLevel < 1 {
+			return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "insufficient security level: %d", data.KeyDescription.AttestationSecurityLevel))
 		}
 
 		// Enforce hardware backed device serial
-		if ch.Value != string(data.Attestation.TeeEnforced.AttestationIdSerial) {
+		if ch.Value != string(data.KeyDescription.TeeEnforced.AttestationIdSerial) {
 			subproblem := NewSubproblemWithIdentifier(
 				ErrorRejectedIdentifierType,
 				Identifier{Type: "permanent-identifier", Value: ch.Value},
-				"challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, []string{string(data.Attestation.TeeEnforced.AttestationIdSerial)},
+				"challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, []string{string(data.KeyDescription.TeeEnforced.AttestationIdSerial)},
 			)
 			return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
 		}
@@ -1006,16 +999,17 @@ func attestationRoots(prov Provisioner) *x509.CertPool {
 // invalid, as a bad attestation statement with the error in its detail. Any
 // other error is returned as an internal error.
 //
-// The exceptions keep the errors the step format has always returned: an empty
-// x5c is a rejected identifier, and a malformed serial number has no detail.
+// The exceptions keep the errors the step and android-key formats have always
+// returned: an empty x5c is a rejected identifier, and a malformed serial number
+// or key description has no detail.
 func storeAttestationError(ctx context.Context, db DB, ch *Challenge, err error) error {
 	var acmeErr *Error
 	switch {
 	case !errors.Is(err, attestation.ErrInvalidEvidence):
 		return newError(ErrorServerInternalType, err)
-	case errors.Is(err, yubikey.ErrEmptyX5C):
+	case errors.Is(err, yubikey.ErrEmptyX5C), errors.Is(err, androidkey.ErrEmptyX5C):
 		acmeErr = newError(ErrorRejectedIdentifierType, err).withDetail()
-	case errors.Is(err, yubikey.ErrSerialNumber):
+	case errors.Is(err, yubikey.ErrSerialNumber), errors.Is(err, androidkey.ErrKeyDescription):
 		acmeErr = newError(ErrorBadAttestationStatementType, err)
 	default:
 		acmeErr = newError(ErrorBadAttestationStatementType, err).withDetail()
@@ -1023,278 +1017,6 @@ func storeAttestationError(ctx context.Context, db DB, ch *Challenge, err error)
 	return storeError(ctx, db, ch, true, acmeErr)
 }
 
-// Android RSA Root CA
-// https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate
-var androidRSARootC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8GA1UdEwEB/wQFMAMBAf8wDgYD
-VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7
-174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC
-W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G
-tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx
-oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG
-1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF
-mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
-lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
-n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
-zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
-vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
-w1IdYIg2Wxg7yHcQZemFQg==
------END CERTIFICATE-----`
-
-// Android ECDSA (secp384r1) Root CA
-var androidECDSARootCA = `-----BEGIN CERTIFICATE-----
-MIICIjCCAaigAwIBAgIRAISp0Cl7DrWK5/8OgN52BgUwCgYIKoZIzj0EAwMwUjEc
-MBoGA1UEAwwTS2V5IEF0dGVzdGF0aW9uIENBMTEQMA4GA1UECwwHQW5kcm9pZDET
-MBEGA1UECgwKR29vZ2xlIExMQzELMAkGA1UEBhMCVVMwHhcNMjUwNzE3MjIzMjE4
-WhcNMzUwNzE1MjIzMjE4WjBSMRwwGgYDVQQDDBNLZXkgQXR0ZXN0YXRpb24gQ0Ex
-MRAwDgYDVQQLDAdBbmRyb2lkMRMwEQYDVQQKDApHb29nbGUgTExDMQswCQYDVQQG
-EwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABCPaI3FO3z5bBQo8cuiEas4HjqCt
-G/mLFfRT0MsIssPBEEU5Cfbt6sH5yOAxqEi5QagpU1yX4HwnGb7OtBYpDTB57uH5
-Eczm34A5FNijV3s0/f0UPl7zbJcTx6xwqMIRq6NCMEAwDwYDVR0TAQH/BAUwAwEB
-/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFFIyuyz7RkOb3NaBqQ5lZuA0QepA
-MAoGCCqGSM49BAMDA2gAMGUCMETfjPO/HwqReR2CS7p0ZWoD/LHs6hDi422opifH
-EUaYLxwGlT9SLdjkVpz0UUOR5wIxAIoGyxGKRHVTpqpGRFiJtQEOOTp/+s1GcxeY
-uR2zh/80lQyu9vAFCj6E4AXc+osmRg==
------END CERTIFICATE-----`
-
-// OID for Android Key Attestation
-// https://source.android.com/docs/security/features/keystore/attestation#id-attestation
-var oidAndroidAttestation = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 1, 17}
-
-type androidKeyAttestationData struct {
-	Certificate *x509.Certificate
-	Fingerprint string
-	Attestation *androidattestation.KeyDescription
-}
-
-// findAndroidAttestationCert traverses the slice of [*x509.Certificate] from
-// end to start (root -> intermediate -> leaf) to locate the certificate closest
-// to the root carrying an Android Key Attestation extension.
-//
-// TODO(hs): implement the optional step of locating the provisioning information
-// extension? That should immediately precede the cert with the key attestation
-// extension.
-func findAndroidAttestationCert(certs []*x509.Certificate) *x509.Certificate {
-	for _, cert := range slices.Backward(certs) {
-		for _, ext := range cert.Extensions {
-			if ext.Id.Equal(oidAndroidAttestation) {
-				return cert
-			}
-		}
-	}
-
-	return nil
-}
-
-// doAndroidKeyAttestationFormat handles ACME Device Attestation requests for
-// the "android-key" attestation format. Its verification logic is based on
-// the documentation at https://developer.android.com/privacy-and-security/security-key-attestation
-//
-// This function performs the below steps:
-//   - Verifies that the root public certificate is trustworthy and that each certificate signs
-//     the next certificate in the chain.
-//   - Checks each certificate's revocation status to ensure that none of the certificates have
-//     been revoked.
-//   - Find the nearest certificate to the root that contains the key attestation certificate
-//     extension.
-//   - Check the extension data that you've retrieved in the previous steps for consistency and
-//     compare with the set of values that you expect the hardware-backed key to contain.
-func doAndroidKeyAttestationFormat(ctx context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*androidKeyAttestationData, error) {
-	acmeProv, ok := prov.(*provisioner.ACME)
-	if !ok {
-		return nil, NewErrorISE("provisioner in context is not an ACME provisioner")
-	}
-
-	roots, ok := prov.GetAttestationRoots()
-	if !ok {
-		rsaRoot, err := pemutil.ParseCertificate([]byte(androidRSARootCA))
-		if err != nil {
-			return nil, WrapErrorISE(err, "error parsing Android RSA root CA")
-		}
-		ecdsaRoot, err := pemutil.ParseCertificate([]byte(androidECDSARootCA))
-		if err != nil {
-			return nil, WrapErrorISE(err, "error parsing Android ECDSA root CA")
-		}
-		roots = x509.NewCertPool()
-		roots.AddCert(rsaRoot)
-		roots.AddCert(ecdsaRoot)
-	}
-
-	// extract x5c and verify certificate
-	x5c, ok := att.AttStatement["x5c"].([]any)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
-	}
-	if len(x5c) == 0 {
-		return nil, NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty")
-	}
-
-	// Parse leaf, intermediates and root
-	intermediates := x509.NewCertPool()
-	var leaf, root *x509.Certificate
-	for i, v := range x5c {
-		der, dok := v.([]byte)
-		if !dok {
-			return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c element is malformed")
-		}
-		cert, err := x509.ParseCertificate(der)
-		if err != nil {
-			return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing certificate at index %d", i)
-		}
-
-		// Verify certificate serial number against CRL
-		revoked, err := acmeProv.IsAndroidCertificateRevoked(ctx, cert)
-		if err != nil {
-			return nil, WrapDetailedError(ErrorServerInternalType, err, "failed checking certificate revocation status")
-		}
-		if revoked {
-			return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c element contains a revoked certificate")
-		}
-
-		switch i {
-		case 0: // leaf
-			leaf = cert
-		case len(x5c) - 1: // root
-			root = cert
-		default: // intermediates
-			intermediates.AddCert(cert)
-		}
-	}
-
-	// Require a leaf in the chain
-	if leaf == nil {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "missing leaf certificate in x5c chain")
-	}
-
-	// Require a root in the chain
-	if root == nil {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "missing root certificate in x5c chain")
-	}
-
-	// Verify the root is one of the trusted roots
-	_, err := root.Verify(x509.VerifyOptions{
-		Roots:       roots,
-		CurrentTime: time.Now().Truncate(time.Second),
-	})
-	if err != nil {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "root certificate in chain is not trusted")
-	}
-
-	// Validate the full chain including root as trust anchor
-	chains, err := leaf.Verify(x509.VerifyOptions{
-		Intermediates: intermediates,
-		Roots:         roots,
-		CurrentTime:   time.Now().Truncate(time.Second),
-		KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
-	})
-	if err != nil {
-		return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c chain verification failed")
-	}
-
-	switch {
-	case len(chains) == 0:
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c does not contain a valid certificate chain")
-	case len(chains) > 1:
-		// currently we strictly prohibit multiple valid signing chains
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c contains multiple (%d) valid certificate chains", len(chains))
-	}
-
-	// Get signature
-	sig, ok := att.AttStatement["sig"].([]byte)
-	if !ok {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig not present")
-	}
-
-	keyAuth, err := KeyAuthorization(ch.Token, jwk)
-	if err != nil {
-		return nil, err
-	}
-
-	// Find the attestation certificate
-	attCert := findAndroidAttestationCert(chains[0])
-	if attCert == nil {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "no attestation certificate with OID 1.3.6.1.4.1.11129.2.1.17 found in the cert chain")
-	}
-
-	// Verify attestation statement sig
-	if err := validateAttestationSignature(attCert, keyAuth, sig); err != nil {
-		return nil, err
-	}
-
-	data := &androidKeyAttestationData{
-		Certificate: attCert,
-	}
-	if data.Fingerprint, err = keyutil.Fingerprint(attCert.PublicKey); err != nil {
-		return nil, WrapErrorISE(err, "error calculating key fingerprint")
-	}
-
-	for _, ext := range attCert.Extensions {
-		if !ext.Id.Equal(oidAndroidAttestation) {
-			continue
-		}
-		keyDesc, err := androidattestation.ParseExtension(ext.Value)
-		if err != nil {
-			return nil, WrapError(ErrorBadAttestationStatementType, err, "error parsing attestation")
-		}
-		data.Attestation = keyDesc
-		break
-	}
-
-	// Validate key authorization
-	if string(data.Attestation.AttestationChallenge) != keyAuth {
-		return nil, NewDetailedError(ErrorBadAttestationStatementType, "challenge mismatch; expected %q, got %q", keyAuth, string(data.Attestation.AttestationChallenge))
-	}
-
-	return data, nil
-}
-
-// validateAttestationSignature verifies that sig is a signature of the key
-// authorization made with the private key of the given attestation certificate.
-func validateAttestationSignature(cert *x509.Certificate, keyAuth string, sig []byte) error {
-	switch pub := cert.PublicKey.(type) {
-	case *ecdsa.PublicKey:
-		if pub.Curve != elliptic.P256() {
-			return NewDetailedError(ErrorBadAttestationStatementType, "unsupported elliptic curve %s", pub.Curve)
-		}
-		sum := sha256.Sum256([]byte(keyAuth))
-		if !ecdsa.VerifyASN1(pub, sum[:], sig) {
-			return NewDetailedError(ErrorBadAttestationStatementType, "failed validating signature")
-		}
-	case *rsa.PublicKey:
-		sum := sha256.Sum256([]byte(keyAuth))
-		if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil {
-			return NewDetailedError(ErrorBadAttestationStatementType, "failed validating signature")
-		}
-	case ed25519.PublicKey:
-		if !ed25519.Verify(pub, []byte(keyAuth), sig) {
-			return NewDetailedError(ErrorBadAttestationStatementType, "failed validating signature")
-		}
-	case *mldsa.PublicKey:
-		if err := mldsa.Verify(pub, []byte(keyAuth), sig, nil); err != nil {
-			return NewDetailedError(ErrorBadAttestationStatementType, "failed validating signature")
-		}
-	default:
-		return NewDetailedError(ErrorBadAttestationStatementType, "unsupported public key type %T", pub)
-	}
-
-	return nil
-}
-
 // serverName determines the SNI HostName to set based on an acme.Challenge
 // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
 // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.

+ 10 - 0
acme/challenge_test.go

@@ -41,6 +41,7 @@ import (
 	"go.step.sm/crypto/pemutil"
 
 	"github.com/smallstep/certificates/attestation"
+	attandroidkey "github.com/smallstep/certificates/attestation/androidkey"
 	"github.com/smallstep/certificates/attestation/yubikey"
 	"github.com/smallstep/certificates/authority/config"
 	"github.com/smallstep/certificates/authority/provisioner"
@@ -137,6 +138,8 @@ func mustAccountAndKeyAuthorization(t *testing.T, token string) (*jose.JSONWebKe
 	return jwk, keyAuth
 }
 
+var oidAndroidAttestation = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 1, 17}
+
 func mustAttestAndroid(t *testing.T, keyAuthorization string) ([]byte, *x509.Certificate, *x509.Certificate) {
 	t.Helper()
 
@@ -375,6 +378,7 @@ func newWireProvisionerWithOptions(t *testing.T, options *provisioner.Options) *
 func Test_storeAttestationError(t *testing.T) {
 	asn1Err := asn1.StructuralError{Msg: "tags don't match"}
 	verifyErr := errors.New("x509: certificate signed by unknown authority")
+	crlErr := errors.New("failed checking certificate against Android CRL: unavailable")
 	// The errors expected are made as acme made them before the verifiers
 	// moved to the attestation packages.
 	tests := []struct {
@@ -389,6 +393,12 @@ func Test_storeAttestationError(t *testing.T) {
 			NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty"), nil},
 		{"step serial number", attestation.Invalid(fmt.Errorf("error finding serial number: %w: %w", yubikey.ErrSerialNumber, asn1Err)),
 			WrapErrorISE(WrapError(ErrorBadAttestationStatementType, asn1Err, "error parsing serial number"), "error finding serial number"), nil},
+		{"android-key empty x5c", attestation.Invalid(attandroidkey.ErrEmptyX5C),
+			NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty"), nil},
+		{"android-key key description", attestation.Invalid(fmt.Errorf("%w: %w", attandroidkey.ErrKeyDescription, asn1Err)),
+			WrapError(ErrorBadAttestationStatementType, asn1Err, "error parsing attestation"), nil},
+		{"android-key revocation", fmt.Errorf("failed checking certificate revocation status: %w", crlErr), nil,
+			WrapDetailedError(ErrorServerInternalType, crlErr, "failed checking certificate revocation status")},
 		{"internal", errors.New("error calculating key fingerprint: unsupported key"), nil,
 			WrapErrorISE(errors.New("unsupported key"), "error calculating key fingerprint")},
 	}

+ 277 - 0
attestation/androidkey/androidkey.go

@@ -0,0 +1,277 @@
+// Package androidkey verifies attestation statements of the "android-key"
+// format of ACME device-attest-01 challenges, made by Android Key Attestation.
+package androidkey
+
+import (
+	"bytes"
+	"context"
+	"crypto/x509"
+	"encoding/asn1"
+	"errors"
+	"fmt"
+	"slices"
+	"time"
+
+	keyattestation "github.com/smallstep/android-attestation"
+	"go.step.sm/crypto/keyutil"
+	"go.step.sm/crypto/pemutil"
+
+	"github.com/smallstep/certificates/attestation"
+	"github.com/smallstep/certificates/attestation/internal/keyauth"
+)
+
+// Android RSA Root CA
+// https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate
+const androidRSARootCA = `-----BEGIN CERTIFICATE-----
+MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
+BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw
+NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
+AQEFAAOCAg8AMIICCgKCAgEAr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RCp/lM0PKvmxYN10RYsK631jrleGdcdkx
+oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG
+1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF
+mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
+lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
+n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
+zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
+vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
+w1IdYIg2Wxg7yHcQZemFQg==
+-----END CERTIFICATE-----`
+
+// Android ECDSA (secp384r1) Root CA
+const androidECDSARootCA = `-----BEGIN CERTIFICATE-----
+MIICIjCCAaigAwIBAgIRAISp0Cl7DrWK5/8OgN52BgUwCgYIKoZIzj0EAwMwUjEc
+MBoGA1UEAwwTS2V5IEF0dGVzdGF0aW9uIENBMTEQMA4GA1UECwwHQW5kcm9pZDET
+MBEGA1UECgwKR29vZ2xlIExMQzELMAkGA1UEBhMCVVMwHhcNMjUwNzE3MjIzMjE4
+WhcNMzUwNzE1MjIzMjE4WjBSMRwwGgYDVQQDDBNLZXkgQXR0ZXN0YXRpb24gQ0Ex
+MRAwDgYDVQQLDAdBbmRyb2lkMRMwEQYDVQQKDApHb29nbGUgTExDMQswCQYDVQQG
+EwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABCPaI3FO3z5bBQo8cuiEas4HjqCt
+G/mLFfRT0MsIssPBEEU5Cfbt6sH5yOAxqEi5QagpU1yX4HwnGb7OtBYpDTB57uH5
+Eczm34A5FNijV3s0/f0UPl7zbJcTx6xwqMIRq6NCMEAwDwYDVR0TAQH/BAUwAwEB
+/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFFIyuyz7RkOb3NaBqQ5lZuA0QepA
+MAoGCCqGSM49BAMDA2gAMGUCMETfjPO/HwqReR2CS7p0ZWoD/LHs6hDi422opifH
+EUaYLxwGlT9SLdjkVpz0UUOR5wIxAIoGyxGKRHVTpqpGRFiJtQEOOTp/+s1GcxeY
+uR2zh/80lQyu9vAFCj6E4AXc+osmRg==
+-----END CERTIFICATE-----`
+
+// OID for Android Key Attestation
+// https://source.android.com/docs/security/features/keystore/attestation#id-attestation
+var oidAndroidAttestation = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 1, 17}
+
+var (
+	// ErrEmptyX5C is matched by the error of an attestation statement whose
+	// x5c holds no certificates.
+	ErrEmptyX5C = errors.New("x5c is empty")
+
+	// ErrKeyDescription is matched by the error of a key attestation
+	// extension that cannot be parsed.
+	ErrKeyDescription = errors.New("error parsing attestation")
+)
+
+// RevocationChecker reports whether a certificate of an x5c chain is revoked.
+type RevocationChecker func(ctx context.Context, cert *x509.Certificate) (bool, error)
+
+// Data is what a verified "android-key" attestation statement attests.
+type Data struct {
+	// Certificate is the attestation certificate, the certificate closest to
+	// the root that carries a key attestation extension. It holds the
+	// attested key.
+	Certificate *x509.Certificate
+	// Fingerprint is the fingerprint of the attested key.
+	Fingerprint string
+	// KeyDescription is the key attestation extension of the attestation
+	// certificate.
+	KeyDescription *keyattestation.KeyDescription
+}
+
+// findAndroidAttestationCert traverses the slice of [*x509.Certificate] from
+// end to start (root -> intermediate -> leaf) to locate the certificate closest
+// to the root carrying an Android Key Attestation extension.
+//
+// TODO(hs): implement the optional step of locating the provisioning information
+// extension? That should immediately precede the cert with the key attestation
+// extension.
+func findAndroidAttestationCert(certs []*x509.Certificate) *x509.Certificate {
+	for _, cert := range slices.Backward(certs) {
+		for _, ext := range cert.Extensions {
+			if ext.Id.Equal(oidAndroidAttestation) {
+				return cert
+			}
+		}
+	}
+
+	return nil
+}
+
+// Verify verifies an "android-key" attestation statement, following
+// https://developer.android.com/privacy-and-security/security-key-attestation,
+// against roots, or against Google's roots if roots is nil, and keyAuth, the
+// key authorization of the challenge. It performs the below steps:
+//   - Verifies that the root public certificate is trustworthy and that each certificate signs
+//     the next certificate in the chain.
+//   - Checks each certificate's revocation status with isRevoked to ensure that none of the
+//     certificates have been revoked.
+//   - Finds the nearest certificate to the root that contains the key attestation certificate
+//     extension, and verifies the statement's signature over keyAuth with its key.
+//   - Checks that the attestation challenge of the extension is keyAuth.
+//
+// It returns the attestation certificate and its key description, whose
+// values the caller compares with the ones it expects the hardware-backed key
+// to have. Errors of the statement match attestation.ErrInvalidEvidence; errors
+// of isRevoked do not.
+func Verify(ctx context.Context, attStmt map[string]any, roots *x509.CertPool, keyAuth []byte, isRevoked RevocationChecker) (*Data, error) {
+	if isRevoked == nil {
+		return nil, errors.New("android-key attestation requires a revocation checker")
+	}
+
+	if roots == nil {
+		rsaRoot, err := pemutil.ParseCertificate([]byte(androidRSARootCA))
+		if err != nil {
+			return nil, fmt.Errorf("error parsing Android RSA root CA: %w", err)
+		}
+		ecdsaRoot, err := pemutil.ParseCertificate([]byte(androidECDSARootCA))
+		if err != nil {
+			return nil, fmt.Errorf("error parsing Android ECDSA root CA: %w", err)
+		}
+		roots = x509.NewCertPool()
+		roots.AddCert(rsaRoot)
+		roots.AddCert(ecdsaRoot)
+	}
+
+	// extract x5c and verify certificate
+	x5c, ok := attStmt["x5c"].([]any)
+	if !ok {
+		return nil, attestation.Invalidf("x5c not present")
+	}
+	if len(x5c) == 0 {
+		return nil, attestation.Invalid(ErrEmptyX5C)
+	}
+
+	// Parse leaf, intermediates and root
+	intermediates := x509.NewCertPool()
+	var leaf, root *x509.Certificate
+	for i, v := range x5c {
+		der, dok := v.([]byte)
+		if !dok {
+			return nil, attestation.Invalidf("x5c element is malformed")
+		}
+		cert, err := x509.ParseCertificate(der)
+		if err != nil {
+			return nil, attestation.Invalidf("failed parsing certificate at index %d: %w", i, err)
+		}
+
+		// Verify certificate serial number against CRL
+		revoked, err := isRevoked(ctx, cert)
+		if err != nil {
+			return nil, fmt.Errorf("failed checking certificate revocation status: %w", err)
+		}
+		if revoked {
+			return nil, attestation.Invalidf("x5c element contains a revoked certificate")
+		}
+
+		switch i {
+		case 0: // leaf
+			leaf = cert
+		case len(x5c) - 1: // root
+			root = cert
+		default: // intermediates
+			intermediates.AddCert(cert)
+		}
+	}
+
+	// Require a leaf in the chain
+	if leaf == nil {
+		return nil, attestation.Invalidf("missing leaf certificate in x5c chain")
+	}
+
+	// Require a root in the chain
+	if root == nil {
+		return nil, attestation.Invalidf("missing root certificate in x5c chain")
+	}
+
+	// Verify the root is one of the trusted roots
+	_, err := root.Verify(x509.VerifyOptions{
+		Roots:       roots,
+		CurrentTime: time.Now().Truncate(time.Second),
+	})
+	if err != nil {
+		return nil, attestation.Invalidf("root certificate in chain is not trusted")
+	}
+
+	// Validate the full chain including root as trust anchor
+	chains, err := leaf.Verify(x509.VerifyOptions{
+		Intermediates: intermediates,
+		Roots:         roots,
+		CurrentTime:   time.Now().Truncate(time.Second),
+		KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
+	})
+	if err != nil {
+		return nil, attestation.Invalidf("x5c chain verification failed: %w", err)
+	}
+
+	switch {
+	case len(chains) == 0:
+		return nil, attestation.Invalidf("x5c does not contain a valid certificate chain")
+	case len(chains) > 1:
+		// currently we strictly prohibit multiple valid signing chains
+		return nil, attestation.Invalidf("x5c contains multiple (%d) valid certificate chains", len(chains))
+	}
+
+	// Get signature
+	sig, ok := attStmt["sig"].([]byte)
+	if !ok {
+		return nil, attestation.Invalidf("sig not present")
+	}
+
+	// Find the attestation certificate
+	attCert := findAndroidAttestationCert(chains[0])
+	if attCert == nil {
+		return nil, attestation.Invalidf("no attestation certificate with OID 1.3.6.1.4.1.11129.2.1.17 found in the cert chain")
+	}
+
+	// Verify attestation statement sig
+	if err := keyauth.Verify(attCert, keyAuth, sig); err != nil {
+		return nil, err
+	}
+
+	data := &Data{
+		Certificate: attCert,
+	}
+	if data.Fingerprint, err = keyutil.Fingerprint(attCert.PublicKey); err != nil {
+		return nil, fmt.Errorf("error calculating key fingerprint: %w", err)
+	}
+
+	for _, ext := range attCert.Extensions {
+		if !ext.Id.Equal(oidAndroidAttestation) {
+			continue
+		}
+		keyDesc, err := keyattestation.ParseExtension(ext.Value)
+		if err != nil {
+			return nil, attestation.Invalid(fmt.Errorf("%w: %w", ErrKeyDescription, err))
+		}
+		data.KeyDescription = keyDesc
+		break
+	}
+
+	// Validate key authorization
+	if !bytes.Equal(data.KeyDescription.AttestationChallenge, keyAuth) {
+		return nil, attestation.Invalidf("challenge mismatch; expected %q, got %q", keyAuth, data.KeyDescription.AttestationChallenge)
+	}
+
+	return data, nil
+}

+ 157 - 0
attestation/androidkey/androidkey_test.go

@@ -0,0 +1,157 @@
+package androidkey
+
+import (
+	"context"
+	"crypto"
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/sha256"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"errors"
+	"testing"
+
+	keyattestation "github.com/smallstep/android-attestation"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"go.step.sm/crypto/keyutil"
+	"go.step.sm/crypto/minica"
+
+	"github.com/smallstep/certificates/attestation"
+)
+
+// keyAuth is the key authorization the attestation statements sign.
+var keyAuth = []byte("token.thumbprint")
+
+func notRevoked(context.Context, *x509.Certificate) (bool, error) {
+	return false, nil
+}
+
+func TestVerify(t *testing.T) {
+	ca, err := minica.New()
+	require.NoError(t, err)
+	roots := x509.NewCertPool()
+	roots.AddCert(ca.Root)
+
+	signer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	require.NoError(t, err)
+	fingerprint, err := keyutil.Fingerprint(signer.Public())
+	require.NoError(t, err)
+
+	keyDescription, err := keyattestation.CreateKeyDescription(&keyattestation.KeyDescription{
+		AttestationVersion:       300,
+		AttestationSecurityLevel: 1,
+		AttestationChallenge:     keyAuth,
+		TeeEnforced: keyattestation.AuthorizationList{
+			AttestationIdSerial: []byte("serial-number"),
+		},
+	})
+	require.NoError(t, err)
+
+	makeLeaf := func(exts ...pkix.Extension) *x509.Certificate {
+		leaf, err := ca.Sign(&x509.Certificate{
+			Subject:         pkix.Name{CommonName: "attestation cert"},
+			PublicKey:       signer.Public(),
+			ExtraExtensions: exts,
+		})
+		require.NoError(t, err)
+		return leaf
+	}
+	leaf := makeLeaf(pkix.Extension{Id: oidAndroidAttestation, Value: keyDescription})
+	leafWithoutExtension := makeLeaf()
+	leafWithBadExtension := makeLeaf(pkix.Extension{Id: oidAndroidAttestation, Value: []byte("bad")})
+
+	keyAuthSum := sha256.Sum256(keyAuth)
+	sig, err := signer.Sign(rand.Reader, keyAuthSum[:], crypto.SHA256)
+	require.NoError(t, err)
+
+	otherSigner, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	require.NoError(t, err)
+	otherSig, err := otherSigner.Sign(rand.Reader, keyAuthSum[:], crypto.SHA256)
+	require.NoError(t, err)
+
+	otherKeyAuth := []byte("other.thumbprint")
+	otherKeyAuthSum := sha256.Sum256(otherKeyAuth)
+	otherKeyAuthSig, err := signer.Sign(rand.Reader, otherKeyAuthSum[:], crypto.SHA256)
+	require.NoError(t, err)
+
+	x5c := []any{leaf.Raw, ca.Intermediate.Raw, ca.Root.Raw}
+	errCRL := errors.New("crl unavailable")
+
+	t.Run("ok", func(t *testing.T) {
+		got, err := Verify(context.Background(), map[string]any{"x5c": x5c, "sig": sig}, roots, keyAuth, notRevoked)
+		require.NoError(t, err)
+		assert.Equal(t, leaf, got.Certificate)
+		assert.Equal(t, fingerprint, got.Fingerprint)
+		if assert.NotNil(t, got.KeyDescription) {
+			assert.Equal(t, keyAuth, got.KeyDescription.AttestationChallenge)
+			assert.Equal(t, keyattestation.SecurityLevel(1), got.KeyDescription.AttestationSecurityLevel)
+			assert.Equal(t, []byte("serial-number"), got.KeyDescription.TeeEnforced.AttestationIdSerial)
+		}
+	})
+
+	revokedRoot := func(_ context.Context, cert *x509.Certificate) (bool, error) {
+		return cert.SerialNumber.Cmp(ca.Root.SerialNumber) == 0, nil
+	}
+	failingCRL := func(context.Context, *x509.Certificate) (bool, error) {
+		return true, errCRL
+	}
+
+	type args struct {
+		attStmt   map[string]any
+		roots     *x509.CertPool
+		keyAuth   []byte
+		isRevoked RevocationChecker
+	}
+	tests := []struct {
+		name    string
+		args    args
+		invalid bool
+		wantErr error
+		msg     string
+	}{
+		{"fail no revocation checker", args{map[string]any{"x5c": x5c, "sig": sig}, roots, keyAuth, nil},
+			false, nil, "requires a revocation checker"},
+		{"fail google roots", args{map[string]any{"x5c": x5c, "sig": sig}, nil, keyAuth, notRevoked},
+			true, nil, "root certificate in chain is not trusted"},
+		{"fail x5c not present", args{map[string]any{"sig": sig}, roots, keyAuth, notRevoked},
+			true, nil, "x5c not present"},
+		{"fail x5c empty", args{map[string]any{"x5c": []any{}, "sig": sig}, roots, keyAuth, notRevoked},
+			true, ErrEmptyX5C, "x5c is empty"},
+		{"fail x5c element type", args{map[string]any{"x5c": []any{"leaf", ca.Intermediate.Raw, ca.Root.Raw}, "sig": sig}, roots, keyAuth, notRevoked},
+			true, nil, "x5c element is malformed"},
+		{"fail x5c element parse", args{map[string]any{"x5c": []any{leaf.Raw[:100], ca.Intermediate.Raw, ca.Root.Raw}, "sig": sig}, roots, keyAuth, notRevoked},
+			true, nil, "failed parsing certificate at index 0"},
+		{"fail revoked", args{map[string]any{"x5c": x5c, "sig": sig}, roots, keyAuth, revokedRoot},
+			true, nil, "x5c element contains a revoked certificate"},
+		{"fail revocation check", args{map[string]any{"x5c": x5c, "sig": sig}, roots, keyAuth, failingCRL},
+			false, errCRL, "failed checking certificate revocation status"},
+		{"fail missing root", args{map[string]any{"x5c": []any{leaf.Raw}, "sig": sig}, roots, keyAuth, notRevoked},
+			true, nil, "missing root certificate in x5c chain"},
+		{"fail chain verification", args{map[string]any{"x5c": []any{leaf.Raw, ca.Root.Raw}, "sig": sig}, roots, keyAuth, notRevoked},
+			true, nil, "x5c chain verification failed"},
+		{"fail sig not present", args{map[string]any{"x5c": x5c}, roots, keyAuth, notRevoked},
+			true, nil, "sig not present"},
+		{"fail sig verify", args{map[string]any{"x5c": x5c, "sig": otherSig}, roots, keyAuth, notRevoked},
+			true, nil, "failed validating signature"},
+		{"fail no attestation certificate", args{map[string]any{"x5c": []any{leafWithoutExtension.Raw, ca.Intermediate.Raw, ca.Root.Raw}, "sig": sig}, roots, keyAuth, notRevoked},
+			true, nil, "no attestation certificate with OID 1.3.6.1.4.1.11129.2.1.17 found"},
+		{"fail key description", args{map[string]any{"x5c": []any{leafWithBadExtension.Raw, ca.Intermediate.Raw, ca.Root.Raw}, "sig": sig}, roots, keyAuth, notRevoked},
+			true, ErrKeyDescription, "error parsing attestation"},
+		{"fail challenge mismatch", args{map[string]any{"x5c": x5c, "sig": otherKeyAuthSig}, roots, otherKeyAuth, notRevoked},
+			true, nil, `challenge mismatch; expected "other.thumbprint", got "token.thumbprint"`},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := Verify(context.Background(), tt.args.attStmt, tt.args.roots, tt.args.keyAuth, tt.args.isRevoked)
+			require.Error(t, err)
+			assert.ErrorContains(t, err, tt.msg)
+			assert.Equal(t, tt.invalid, errors.Is(err, attestation.ErrInvalidEvidence), "errors.Is(%v, attestation.ErrInvalidEvidence)", err)
+			if tt.wantErr != nil {
+				assert.ErrorIs(t, err, tt.wantErr)
+			}
+			assert.Nil(t, got)
+		})
+	}
+}