Selaa lähdekoodia

Make Android Key Attestation CRL check (partially) configurable

Herman Slatman 4 kuukautta sitten
vanhempi
sitoutus
e3d6949bfc

+ 9 - 3
acme/challenge.go

@@ -1486,7 +1486,7 @@ func findAndroidAttestationCert(certs []*x509.Certificate) *x509.Certificate {
 //     See the section about the provisioning information extension for more details.
 //     See the section about the provisioning information extension for more details.
 //  6. Find the nearest certificate to the root that contains the key attestation certificate extension. If the provisioning information certificate extension was present, the key attestation certificate extension must be in the immediately subsequent certificate. Use the parser to extract the key attestation certificate extension data from that certificate.
 //  6. Find the nearest certificate to the root that contains the key attestation certificate extension. If the provisioning information certificate extension was present, the key attestation certificate extension must be in the immediately subsequent certificate. Use the parser to extract the key attestation certificate extension data from that certificate.
 //  7. 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.
 //  7. 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 doAndroidKeyAttestionFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*androidKeyAttestationData, error) {
+func doAndroidKeyAttestionFormat(ctx context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*androidKeyAttestationData, error) {
 	acmeProv := prov.(*provisioner.ACME)
 	acmeProv := prov.(*provisioner.ACME)
 
 
 	roots, ok := prov.GetAttestationRoots()
 	roots, ok := prov.GetAttestationRoots()
@@ -1536,10 +1536,16 @@ func doAndroidKeyAttestionFormat(_ context.Context, prov Provisioner, ch *Challe
 		if err != nil {
 		if err != nil {
 			return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing certificate at index %d", i+1)
 			return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing certificate at index %d", i+1)
 		}
 		}
-		// Verify CRL
-		if acmeProv.IsRootRevoked(cert.SerialNumber.String()) {
+
+		// 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")
 			return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c element contains a revoked certificate")
 		}
 		}
+
 		if i == len(x5c)-2 {
 		if i == len(x5c)-2 {
 			// Last cert = root
 			// Last cert = root
 			certs = append(certs, cert)
 			certs = append(certs, cert)

+ 19 - 9
acme/challenge_test.go

@@ -25,6 +25,7 @@ import (
 	"net/http"
 	"net/http"
 	"net/http/httptest"
 	"net/http/httptest"
 	"reflect"
 	"reflect"
+	"slices"
 	"strconv"
 	"strconv"
 	"strings"
 	"strings"
 	"testing"
 	"testing"
@@ -43,6 +44,7 @@ import (
 
 
 	"github.com/smallstep/certificates/authority/config"
 	"github.com/smallstep/certificates/authority/config"
 	"github.com/smallstep/certificates/authority/provisioner"
 	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/authority/provisioner/androidkey"
 	wireprovisioner "github.com/smallstep/certificates/authority/provisioner/wire"
 	wireprovisioner "github.com/smallstep/certificates/authority/provisioner/wire"
 )
 )
 
 
@@ -99,18 +101,25 @@ func mustAttestationProvisioner(t *testing.T, roots []byte) Provisioner {
 	return prov
 	return prov
 }
 }
 
 
-func mustNonCRLAttestationProvisioner(t *testing.T, roots []byte, CRLs []string) Provisioner {
+type fakeAndroidKeyCRLChecker []string
+
+func (p fakeAndroidKeyCRLChecker) IsRevoked(_ context.Context, cert *x509.Certificate) (bool, error) {
+	return slices.Contains(p, cert.SerialNumber.String()), nil
+}
+
+func mustAndroidAttestationProvisioner(t *testing.T, roots []byte, androidKeyCRLChecker androidkey.CRLChecker) Provisioner {
 	t.Helper()
 	t.Helper()
 
 
 	prov := &provisioner.ACME{
 	prov := &provisioner.ACME{
-		Type:             "ACME",
-		Name:             "acme",
-		Challenges:       []provisioner.ACMEChallenge{provisioner.DEVICE_ATTEST_01},
-		AttestationRoots: roots,
-		RootCRLs:         CRLs,
+		Type:               "ACME",
+		Name:               "acme",
+		Challenges:         []provisioner.ACMEChallenge{provisioner.DEVICE_ATTEST_01},
+		AttestationFormats: []provisioner.ACMEAttestationFormat{provisioner.ANDROID_KEY},
+		AttestationRoots:   roots,
 	}
 	}
 	if err := prov.Init(provisioner.Config{
 	if err := prov.Init(provisioner.Config{
-		Claims: config.GlobalProvisionerClaims,
+		Claims:               config.GlobalProvisionerClaims,
+		AndroidKeyCRLChecker: androidKeyCRLChecker,
 	}); err != nil {
 	}); err != nil {
 		t.Fatal(err)
 		t.Fatal(err)
 	}
 	}
@@ -4584,7 +4593,7 @@ func Test_deviceAttest01Validate(t *testing.T) {
 			payload, _, root := mustAttestAndroid(t, keyAuth)
 			payload, _, root := mustAttestAndroid(t, keyAuth)
 
 
 			caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
 			caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
-			ctx := NewProvisionerContext(context.Background(), mustAttestationProvisioner(t, caRoot))
+			ctx := NewProvisionerContext(context.Background(), mustAndroidAttestationProvisioner(t, caRoot, nil))
 			return test{
 			return test{
 				args: args{
 				args: args{
 					ctx: ctx,
 					ctx: ctx,
@@ -4624,7 +4633,8 @@ func Test_deviceAttest01Validate(t *testing.T) {
 			payload, _, root := mustAttestAndroid(t, keyAuth)
 			payload, _, root := mustAttestAndroid(t, keyAuth)
 
 
 			caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
 			caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
-			ctx := NewProvisionerContext(context.Background(), mustNonCRLAttestationProvisioner(t, caRoot, []string{root.SerialNumber.String()}))
+			androidKeyCRLChecker := fakeAndroidKeyCRLChecker([]string{root.SerialNumber.String()})
+			ctx := NewProvisionerContext(context.Background(), mustAndroidAttestationProvisioner(t, caRoot, androidKeyCRLChecker))
 			return test{
 			return test{
 				args: args{
 				args: args{
 					ctx: ctx,
 					ctx: ctx,

+ 44 - 27
authority/provisioner/acme.go

@@ -7,7 +7,6 @@ import (
 	"encoding/pem"
 	"encoding/pem"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
-	"log"
 	"net"
 	"net"
 	"net/http"
 	"net/http"
 	"slices"
 	"slices"
@@ -125,13 +124,13 @@ type ACME struct {
 	// AttestationRoots contains a bundle of root certificates in PEM format
 	// AttestationRoots contains a bundle of root certificates in PEM format
 	// that will be used to verify the attestation certificates. If provided,
 	// that will be used to verify the attestation certificates. If provided,
 	// this bundle will be used even for well-known CAs like Apple and Yubico.
 	// this bundle will be used even for well-known CAs like Apple and Yubico.
-	AttestationRoots    []byte   `json:"attestationRoots,omitempty"`
-	Claims              *Claims  `json:"claims,omitempty"`
-	Options             *Options `json:"options,omitempty"`
-	RootCRLs            []string `json:"rootCRLs,omitempty"`
-	androidCRLTimeout   time.Time
-	attestationRootPool *x509.CertPool
-	ctl                 *Controller
+	AttestationRoots      []byte   `json:"attestationRoots,omitempty"`
+	Claims                *Claims  `json:"claims,omitempty"`
+	Options               *Options `json:"options,omitempty"`
+	androidRevokedSerials []string
+	androidCRLFetchedAt   time.Time
+	attestationRootPool   *x509.CertPool
+	ctl                   *Controller
 }
 }
 
 
 // GetID returns the provisioner unique identifier.
 // GetID returns the provisioner unique identifier.
@@ -227,26 +226,22 @@ func (p *ACME) Init(config Config) (err error) {
 		return fmt.Errorf("failed initializing Wire options: %w", err)
 		return fmt.Errorf("failed initializing Wire options: %w", err)
 	}
 	}
 
 
-	if slices.Contains(p.AttestationFormats, "android-key") && len(p.RootCRLs) == 0 {
-		p.initializeAndroidCRL()
-	}
-
 	p.ctl, err = NewController(p, p.Claims, config, p.Options)
 	p.ctl, err = NewController(p, p.Claims, config, p.Options)
 	return
 	return
 }
 }
 
 
-const ANDROID_ATTESTATION_STATUS_URL = "https://android.googleapis.com/attestation/status"
+const androidAttestationStatusURL = "https://android.googleapis.com/attestation/status" // TODO: make configurable?
 
 
-// fetch CRL https://android.googleapis.com/attestation/status and build a list of serial number
-func (p *ACME) initializeAndroidCRL() error {
-	log.Printf("Updating Android CRL list for %s ACME provisioner", p.Name)
+// loadAndroidCRL fetches the CRL at https://android.googleapis.com/attestation/status
+// and builds a list of serial numbers for each certificate that has been revoked.
+func (p *ACME) loadAndroidCRL(ctx context.Context) error {
 	var CRLResponse struct {
 	var CRLResponse struct {
 		Entries map[string]struct {
 		Entries map[string]struct {
 			Status string `json:"status"`
 			Status string `json:"status"`
 			Reason string `json:"reason"`
 			Reason string `json:"reason"`
 		} `json:"entries"`
 		} `json:"entries"`
 	}
 	}
-	res, err := http.Get(ANDROID_ATTESTATION_STATUS_URL)
+	res, err := p.ctl.GetHTTPClient().Get(androidAttestationStatusURL)
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("client: error making Android CRL request: %s\n", err)
 		return fmt.Errorf("client: error making Android CRL request: %s\n", err)
 	}
 	}
@@ -262,12 +257,14 @@ func (p *ACME) initializeAndroidCRL() error {
 	}
 	}
 
 
 	// Extract keys into a slice
 	// Extract keys into a slice
-	keys := make([]string, 0, len(CRLResponse.Entries))
+	serials := make([]string, 0, len(CRLResponse.Entries))
 	for k := range CRLResponse.Entries {
 	for k := range CRLResponse.Entries {
-		keys = append(keys, k)
+		serials = append(serials, k)
 	}
 	}
-	p.RootCRLs = keys
-	p.androidCRLTimeout = time.Now().Add(24 * time.Hour)
+
+	p.androidRevokedSerials = serials
+	p.androidCRLFetchedAt = time.Now()
+
 	return nil
 	return nil
 }
 }
 
 
@@ -444,11 +441,31 @@ func (p *ACME) GetAttestationRoots() (*x509.CertPool, bool) {
 	return p.attestationRootPool, p.attestationRootPool != nil
 	return p.attestationRootPool, p.attestationRootPool != nil
 }
 }
 
 
-// IsRootRevoked return a true if the serialNumber is part of the list
-// It will also be in charge of updating the list periodically if no CRL list is provided at configuration.
-func (p *ACME) IsRootRevoked(serialNumber string) bool {
-	if slices.Contains(p.AttestationFormats, "android-key") && !p.androidCRLTimeout.IsZero() && time.Now().After(p.androidCRLTimeout) {
-		p.initializeAndroidCRL()
+// IsAndroidCertificateRevoked returns whether the serial number is
+// revoked or not.
+func (p *ACME) IsAndroidCertificateRevoked(ctx context.Context, cert *x509.Certificate) (bool, error) {
+	// the check only has to be performed when the "android-key" attestation
+	// format is enabled
+	if !slices.Contains(p.AttestationFormats, ANDROID_KEY) {
+		return false, nil
+	}
+
+	if p.ctl.androidKeyCRLChecker != nil {
+		revoked, err := p.ctl.androidKeyCRLChecker.IsRevoked(ctx, cert)
+		if err != nil {
+			return true, fmt.Errorf("failed checking certificate against Android CRL: %w", err)
+		}
+
+		return revoked, nil
+	}
+
+	// TODO(hs): refactor, so that the period between loads becomes configurable
+	if p.androidCRLFetchedAt.IsZero() || time.Now().After(p.androidCRLFetchedAt.Add(24*time.Hour)) {
+		// reinitialize the Android CRL
+		if err := p.loadAndroidCRL(ctx); err != nil {
+			return false, err
+		}
 	}
 	}
-	return len(p.RootCRLs) > 0 && slices.Contains(p.RootCRLs, serialNumber)
+
+	return slices.Contains(p.androidRevokedSerials, cert.SerialNumber.String()), nil
 }
 }

+ 10 - 0
authority/provisioner/androidkey/crl.go

@@ -0,0 +1,10 @@
+package androidkey
+
+import (
+	"context"
+	"crypto/x509"
+)
+
+type CRLChecker interface {
+	IsRevoked(ctx context.Context, cert *x509.Certificate) (bool, error)
+}

+ 3 - 0
authority/provisioner/controller.go

@@ -12,6 +12,7 @@ import (
 
 
 	"github.com/smallstep/linkedca"
 	"github.com/smallstep/linkedca"
 
 
+	"github.com/smallstep/certificates/authority/provisioner/androidkey"
 	"github.com/smallstep/certificates/errs"
 	"github.com/smallstep/certificates/errs"
 	"github.com/smallstep/certificates/internal/cast"
 	"github.com/smallstep/certificates/internal/cast"
 	"github.com/smallstep/certificates/internal/httptransport"
 	"github.com/smallstep/certificates/internal/httptransport"
@@ -32,6 +33,7 @@ type Controller struct {
 	webhookClient         HTTPClient
 	webhookClient         HTTPClient
 	webhooks              []*Webhook
 	webhooks              []*Webhook
 	wrapTransport         httptransport.Wrapper
 	wrapTransport         httptransport.Wrapper
+	androidKeyCRLChecker  androidkey.CRLChecker
 }
 }
 
 
 // NewController initializes a new provisioner controller.
 // NewController initializes a new provisioner controller.
@@ -66,6 +68,7 @@ func NewController(p Interface, claims *Claims, config Config, options *Options)
 		webhooks:              options.GetWebhooks(),
 		webhooks:              options.GetWebhooks(),
 		httpClient:            config.HTTPClient,
 		httpClient:            config.HTTPClient,
 		wrapTransport:         wt,
 		wrapTransport:         wt,
+		androidKeyCRLChecker:  config.AndroidKeyCRLChecker,
 	}, nil
 	}, nil
 }
 }
 
 

+ 5 - 0
authority/provisioner/provisioner.go

@@ -13,6 +13,7 @@ import (
 	kmsapi "go.step.sm/crypto/kms/apiv1"
 	kmsapi "go.step.sm/crypto/kms/apiv1"
 	"golang.org/x/crypto/ssh"
 	"golang.org/x/crypto/ssh"
 
 
+	"github.com/smallstep/certificates/authority/provisioner/androidkey"
 	"github.com/smallstep/certificates/errs"
 	"github.com/smallstep/certificates/errs"
 )
 )
 
 
@@ -281,6 +282,10 @@ type Config struct {
 	// WrapTransport references the function that should wrap any [http.Transport] initialized
 	// WrapTransport references the function that should wrap any [http.Transport] initialized
 	// down the Config's chain.
 	// down the Config's chain.
 	WrapTransport TransportWrapper
 	WrapTransport TransportWrapper
+	// AndroidKeyCRLProvider references an implementation of [androidkey.CRLProvider]
+	// that is responsible for resolving revoked Android Key Attestation certificate
+	// numbers.
+	AndroidKeyCRLChecker androidkey.CRLChecker
 }
 }
 
 
 type provisioner struct {
 type provisioner struct {