Răsfoiți Sursa

Validate remote-attest-01 and bind the attested key at finalize

remoteAttest01Validate parses the payload as a CMW record and verifies
it through the provisioner. step-ca's profile of draft-ietf-acme-rats-03,
which defines no binding, requires the evidence to bind two digests:
SHA-256 of the challenge's key authorization (freshnessNonce, ".",
account key thumbprint), for freshness and the account; and SHA-256 of
the DER SubjectPublicKeyInfo of the key the order will be finalized
with. The challenge comes before the CSR exists, so the key digest is
stored on the authorization with the verified attestation.

Rules:
- An empty payload or {} leaves the challenge unchanged.
- A malformed CMW is a malformed error and does not invalidate the
  challenge.
- Evidence that fails verification or does not bind the key
  authorization is badAttestationStatement and invalidates the
  challenge.
- A collateral fetch failure is an internal error.

At finalize, checkAttestedKeys replaces getAuthorizationFingerprint. It
checks the CSR's key against every authorization's attested key: the
fingerprint a device-attest-01 challenge stored, and the key digest a
remote-attest-01 challenge stored, the latter computed over the CSR's
RawSubjectPublicKeyInfo. This changes device-attest-01: an order whose
two authorizations attested different keys used to pass if the first
one matched, and is now refused.

The order's attestation goes to templates as .Attestation and to
enriching and authorizing webhooks as the attestation object.
remote-attestation identifiers add no SANs, so the CSR of an order that
has only one must name nothing; the template and webhooks name the
certificate.

Claude-Session: https://claude.ai/code/session_01CjfEMLGpnHQaWsmxe1zmLF
Josh Drake 1 lună în urmă
părinte
comite
674bd222ae

+ 15 - 10
acme/authorization.go

@@ -4,20 +4,25 @@ import (
 	"context"
 	"context"
 	"encoding/json"
 	"encoding/json"
 	"time"
 	"time"
+
+	"github.com/smallstep/certificates/webhook"
 )
 )
 
 
 // Authorization representst an ACME Authorization.
 // Authorization representst an ACME Authorization.
 type Authorization struct {
 type Authorization struct {
-	ID          string       `json:"-"`
-	AccountID   string       `json:"-"`
-	Token       string       `json:"-"`
-	Fingerprint string       `json:"-"`
-	Identifier  Identifier   `json:"identifier"`
-	Status      Status       `json:"status"`
-	Challenges  []*Challenge `json:"challenges"`
-	Wildcard    bool         `json:"wildcard"`
-	ExpiresAt   time.Time    `json:"expires"`
-	Error       *Error       `json:"error,omitempty"`
+	ID          string `json:"-"`
+	AccountID   string `json:"-"`
+	Token       string `json:"-"`
+	Fingerprint string `json:"-"`
+	// Attestation is the evidence a remote-attest-01 challenge of the
+	// authorization verified.
+	Attestation *webhook.Attestation `json:"-"`
+	Identifier  Identifier           `json:"identifier"`
+	Status      Status               `json:"status"`
+	Challenges  []*Challenge         `json:"challenges"`
+	Wildcard    bool                 `json:"wildcard"`
+	ExpiresAt   time.Time            `json:"expires"`
+	Error       *Error               `json:"error,omitempty"`
 }
 }
 
 
 // ToLog enables response logging.
 // ToLog enables response logging.

+ 1 - 1
acme/challenge.go

@@ -144,7 +144,7 @@ func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey,
 		}
 		}
 		return wireDPOP01Validate(ctx, ch, wireDB, jwk, payload)
 		return wireDPOP01Validate(ctx, ch, wireDB, jwk, payload)
 	case REMOTEATTEST01:
 	case REMOTEATTEST01:
-		return NewError(ErrorMalformedType, "remote-attest-01 is not implemented yet")
+		return remoteAttest01Validate(ctx, ch, db, jwk, payload)
 	default:
 	default:
 		return NewErrorISE("unexpected challenge type %q", ch.Type)
 		return NewErrorISE("unexpected challenge type %q", ch.Type)
 	}
 	}

+ 111 - 0
acme/challenge_remote_attestation.go

@@ -0,0 +1,111 @@
+package acme
+
+import (
+	"bytes"
+	"context"
+	"crypto/sha256"
+	"crypto/subtle"
+	"crypto/x509"
+	"encoding/hex"
+	"errors"
+	"time"
+
+	"go.step.sm/crypto/jose"
+
+	"github.com/smallstep/certificates/attestation"
+	"github.com/smallstep/certificates/attestation/cmw"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/webhook"
+)
+
+// remoteAttest01Validate validates a remote-attest-01 challenge
+// (draft-ietf-acme-rats-03). The payload is a CMW record (RFC 9999) holding the
+// evidence: a TDX quote or an SEV-SNP report in a configfs-tsm report, or a
+// Confidential Space token. step-ca profiles the draft, which defines no
+// binding, by requiring the evidence to bind 64 bytes:
+//
+//   - The SHA-256 digest of the key authorization of the challenge, computed
+//     over its freshnessNonce: freshnessNonce || '.' || base64url(JWK
+//     thumbprint of the account key). It makes the evidence fresh and binds it
+//     to the account.
+//   - The SHA-256 digest of the DER SubjectPublicKeyInfo of the key the order
+//     will be finalized with. The CSR has not been sent yet, so the digest is
+//     stored on the authorization and finalize compares it with the CSR's key.
+//
+// A TDX quote or SEV-SNP report carries the 64 bytes as its report data; a
+// Confidential Space token carries each digest, base64url encoded without
+// padding, as its first two eat_nonce values.
+//
+// An empty payload, or an empty JSON object, leaves the challenge unchanged.
+func remoteAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
+	if p := bytes.TrimSpace(payload); len(p) == 0 || bytes.Equal(p, []byte("{}")) {
+		return nil
+	}
+	if ch.FreshnessNonce == "" {
+		return NewErrorISE("remote-attest-01 challenge %s has no freshness nonce", ch.ID)
+	}
+
+	record, err := cmw.Parse(payload)
+	if err != nil {
+		return WrapError(ErrorMalformedType, err, "error parsing remote attestation")
+	}
+
+	prov := MustProvisionerFromContext(ctx)
+	var audience string
+	if linker, ok := LinkerFromContext(ctx); ok {
+		audience = linker.GetLink(ctx, DirectoryLinkType)
+	}
+	result, bound, err := prov.VerifyRemoteAttestation(ctx, record, audience)
+	switch {
+	case errors.Is(err, attestation.ErrInvalidEvidence):
+		return storeError(ctx, db, ch, true, WrapDetailedError(ErrorBadAttestationStatementType, err, "%s", err))
+	case err != nil:
+		return WrapErrorISE(err, "error verifying remote attestation")
+	case len(bound) != provisioner.RemoteAttestationBoundSize:
+		return NewErrorISE("remote attestation binds %d bytes, not %d", len(bound), provisioner.RemoteAttestationBoundSize)
+	}
+
+	keyAuth, err := KeyAuthorization(ch.FreshnessNonce, jwk)
+	if err != nil {
+		return err
+	}
+	keyAuthDigest := sha256.Sum256([]byte(keyAuth))
+	if subtle.ConstantTimeCompare(bound[:sha256.Size], keyAuthDigest[:]) != 1 {
+		return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType,
+			"the evidence does not bind the key authorization of the challenge"))
+	}
+
+	az, err := db.GetAuthorization(ctx, ch.AuthorizationID)
+	if err != nil {
+		return WrapErrorISE(err, "error loading authorization")
+	}
+	az.Attestation = &webhook.Attestation{
+		Challenge:              string(REMOTEATTEST01),
+		Hint:                   az.Identifier.Value,
+		FreshnessNonce:         ch.FreshnessNonce,
+		KeyAuthorizationDigest: hex.EncodeToString(keyAuthDigest[:]),
+		KeyDigest:              hex.EncodeToString(bound[sha256.Size:]),
+		Result:                 result,
+	}
+
+	ch.Status = StatusValid
+	ch.Error = nil
+	ch.ValidatedAt = clock.Now().Format(time.RFC3339)
+	ch.PayloadFormat = string(result.Format)
+
+	// TODO: add method to update authorization and challenge atomically.
+	if err := db.UpdateAuthorization(ctx, az); err != nil {
+		return WrapErrorISE(err, "error updating authorization")
+	}
+	if err := db.UpdateChallenge(ctx, ch); err != nil {
+		return WrapErrorISE(err, "error updating challenge")
+	}
+	return nil
+}
+
+// remoteAttestationKeyDigest returns the hex encoded SHA-256 digest of the DER
+// SubjectPublicKeyInfo of the CSR's key, which remote-attest-01 evidence binds.
+func remoteAttestationKeyDigest(csr *x509.CertificateRequest) string {
+	sum := sha256.Sum256(csr.RawSubjectPublicKeyInfo)
+	return hex.EncodeToString(sum[:])
+}

+ 331 - 0
acme/challenge_remote_attestation_test.go

@@ -0,0 +1,331 @@
+package acme
+
+import (
+	"context"
+	"crypto"
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/sha256"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/hex"
+	"errors"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"go.step.sm/crypto/jose"
+	"go.step.sm/crypto/keyutil"
+	"go.step.sm/crypto/x509util"
+
+	"github.com/smallstep/certificates/attestation"
+	"github.com/smallstep/certificates/attestation/cmw"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/webhook"
+)
+
+const testFreshnessNonce = "yoW1RL2zPBzYEHBQ06Jy"
+
+// testRemoteAttestationCMW is a valid CMW record; the provisioner mocks decide
+// what it verifies to.
+var testRemoteAttestationCMW = []byte(`["application/eat+jwt", "ZXlKaGJHY2lPaUpTVXpJMU5pSjku", 8]`)
+
+func mustCSR(t *testing.T, cn string) (*x509.CertificateRequest, crypto.Signer) {
+	t.Helper()
+	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	require.NoError(t, err)
+	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
+		Subject: pkix.Name{CommonName: cn},
+	}, key)
+	require.NoError(t, err)
+	csr, err := x509.ParseCertificateRequest(der)
+	require.NoError(t, err)
+	return csr, key
+}
+
+// testBoundData returns the data the evidence of a challenge with the given
+// account key binds, for the given CSR's key.
+func testBoundData(t *testing.T, jwk *jose.JSONWebKey, csr *x509.CertificateRequest) []byte {
+	t.Helper()
+	keyAuth, err := KeyAuthorization(testFreshnessNonce, jwk)
+	require.NoError(t, err)
+	ka := sha256.Sum256([]byte(keyAuth))
+	key := sha256.Sum256(csr.RawSubjectPublicKeyInfo)
+	return append(ka[:], key[:]...)
+}
+
+func TestRemoteAttest01Validate(t *testing.T) {
+	jwk, _ := mustAccountAndKeyAuthorization(t, testFreshnessNonce)
+	csr, _ := mustCSR(t, "")
+	bound := testBoundData(t, jwk, csr)
+	result := &attestation.Result{
+		Format:            attestation.FormatConfidentialSpace,
+		MediaType:         "application/eat+jwt",
+		Evidence:          []byte("token"),
+		ConfidentialSpace: &attestation.ConfidentialSpace{Claims: map[string]any{"hwmodel": "GCP_INTEL_TDX"}},
+	}
+
+	type want struct {
+		status    Status
+		errType   string
+		errDetail string
+		err       string
+		stored    bool
+	}
+	tests := []struct {
+		name    string
+		payload []byte
+		nonce   string
+		verify  func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error)
+		want    want
+	}{
+		{"ok", testRemoteAttestationCMW, testFreshnessNonce,
+			func(_ context.Context, r *cmw.Record, aud string) (*attestation.Result, []byte, error) {
+				assert.Equal(t, "application/eat+jwt", r.MediaType)
+				assert.Equal(t, "https://ca.example.com/acme/acme/directory", aud)
+				return result, bound, nil
+			}, want{status: StatusValid, stored: true}},
+		{"ok empty payload", nil, testFreshnessNonce, nil, want{status: StatusPending}},
+		{"ok empty object", []byte(" {} "), testFreshnessNonce, nil, want{status: StatusPending}},
+		{"fail no nonce", testRemoteAttestationCMW, "", nil, want{status: StatusPending, err: "has no freshness nonce"}},
+		{"fail malformed", []byte(`["application/eat+jwt"]`), testFreshnessNonce, nil,
+			want{status: StatusPending, err: "must have 2 or 3 elements"}},
+		{"fail invalid evidence", testRemoteAttestationCMW, testFreshnessNonce,
+			func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
+				return nil, nil, attestation.Invalidf("attestation token dbgstat is %q", "enabled")
+			}, want{status: StatusInvalid, errType: "badAttestationStatement", errDetail: `attestation token dbgstat is "enabled"`}},
+		{"fail verifier", testRemoteAttestationCMW, testFreshnessNonce,
+			func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
+				return nil, nil, errors.New("error fetching tdx collateral")
+			}, want{status: StatusPending, err: "error verifying remote attestation"}},
+		{"fail bound size", testRemoteAttestationCMW, testFreshnessNonce,
+			func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
+				return result, bound[:32], nil
+			}, want{status: StatusPending, err: "binds 32 bytes"}},
+		{"fail key authorization", testRemoteAttestationCMW, testFreshnessNonce,
+			func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
+				other := append([]byte(nil), bound...)
+				other[0] ^= 1
+				return result, other, nil
+			}, want{status: StatusInvalid, errType: "badAttestationStatement", errDetail: "does not bind the key authorization"}},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			var (
+				updatedAz *Authorization
+				updatedCh *Challenge
+			)
+			db := &MockDB{
+				MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
+					assert.Equal(t, "azID", id)
+					return &Authorization{ID: id, Identifier: Identifier{Type: RemoteAttestation, Value: "measured_boot"}}, nil
+				},
+				MockUpdateAuthorization: func(_ context.Context, az *Authorization) error {
+					updatedAz = az
+					return nil
+				},
+				MockUpdateChallenge: func(_ context.Context, ch *Challenge) error {
+					updatedCh = ch
+					return nil
+				},
+			}
+			prov := &MockProvisioner{
+				MgetName:                 func() string { return "acme" },
+				MverifyRemoteAttestation: tt.verify,
+			}
+			ctx := NewProvisionerContext(context.Background(), prov)
+			ctx = NewLinkerContext(ctx, NewLinker("ca.example.com", "acme"))
+			ch := &Challenge{
+				ID:              "chID",
+				AuthorizationID: "azID",
+				Type:            REMOTEATTEST01,
+				Status:          StatusPending,
+				Token:           "token",
+				FreshnessNonce:  tt.nonce,
+			}
+
+			err := ch.Validate(ctx, db, jwk, tt.payload)
+			if tt.want.err != "" {
+				assert.ErrorContains(t, err, tt.want.err)
+			} else {
+				require.NoError(t, err)
+			}
+			assert.Equal(t, tt.want.status, ch.Status)
+
+			if tt.want.errType != "" {
+				require.NotNil(t, updatedCh)
+				require.NotNil(t, ch.Error)
+				assert.Equal(t, "urn:ietf:params:acme:error:"+tt.want.errType, ch.Error.Type)
+				assert.Contains(t, ch.Error.Detail, tt.want.errDetail)
+				assert.Nil(t, updatedAz)
+				return
+			}
+			if !tt.want.stored {
+				assert.Nil(t, updatedAz)
+				assert.Nil(t, updatedCh)
+				return
+			}
+
+			require.NotNil(t, updatedCh)
+			assert.Nil(t, ch.Error)
+			assert.NotEmpty(t, ch.ValidatedAt)
+			assert.Equal(t, "confidential-space", ch.PayloadFormat)
+			require.NotNil(t, updatedAz)
+			require.NotNil(t, updatedAz.Attestation)
+			att := updatedAz.Attestation
+			assert.Equal(t, "remote-attest-01", att.Challenge)
+			assert.Equal(t, "measured_boot", att.Hint)
+			assert.Equal(t, testFreshnessNonce, att.FreshnessNonce)
+			assert.Equal(t, hex.EncodeToString(bound[:32]), att.KeyAuthorizationDigest)
+			assert.Equal(t, remoteAttestationKeyDigest(csr), att.KeyDigest)
+			assert.Equal(t, result, att.Result)
+		})
+	}
+}
+
+func TestOrder_checkAttestedKeys(t *testing.T) {
+	csr, _ := mustCSR(t, "")
+	otherCSR, _ := mustCSR(t, "")
+	fp, err := keyutil.Fingerprint(csr.PublicKey)
+	require.NoError(t, err)
+	otherFP, err := keyutil.Fingerprint(otherCSR.PublicKey)
+	require.NoError(t, err)
+	att := &webhook.Attestation{Challenge: "remote-attest-01", KeyDigest: remoteAttestationKeyDigest(csr)}
+	otherAtt := &webhook.Attestation{Challenge: "remote-attest-01", KeyDigest: remoteAttestationKeyDigest(otherCSR)}
+
+	tests := []struct {
+		name    string
+		azs     map[string]*Authorization
+		want    *webhook.Attestation
+		wantErr string
+	}{
+		{"ok none", map[string]*Authorization{"az1": {}, "az2": {}}, nil, ""},
+		{"ok fingerprint", map[string]*Authorization{"az1": {}, "az2": {Fingerprint: fp}}, nil, ""},
+		{"ok attestation", map[string]*Authorization{"az1": {}, "az2": {Attestation: att}}, att, ""},
+		{"ok both", map[string]*Authorization{"az1": {Fingerprint: fp}, "az2": {Attestation: att}}, att, ""},
+		{"fail fingerprint", map[string]*Authorization{"az1": {Fingerprint: otherFP}, "az2": {}}, nil, "csr does not match the attested key"},
+		{"fail attestation", map[string]*Authorization{"az1": {}, "az2": {Attestation: otherAtt}}, nil, "csr does not match the attested key"},
+		{"fail attestation without digest", map[string]*Authorization{"az1": {Attestation: &webhook.Attestation{}}, "az2": {}}, nil,
+			"csr does not match the attested key"},
+		// Every attested key is checked, not only the first one found.
+		{"fail second fingerprint", map[string]*Authorization{"az1": {Fingerprint: fp}, "az2": {Fingerprint: otherFP}}, nil,
+			"csr does not match the attested key"},
+		{"fail attestation after fingerprint", map[string]*Authorization{"az1": {Fingerprint: fp}, "az2": {Attestation: otherAtt}}, nil,
+			"csr does not match the attested key"},
+		{"fail db", map[string]*Authorization{"az1": nil}, nil, "error getting authorization"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			o := &Order{ID: "orderID", AuthorizationIDs: []string{"az1", "az2"}}
+			db := &MockDB{
+				MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
+					az, ok := tt.azs[id]
+					if !ok || az == nil {
+						return nil, errors.New("force")
+					}
+					return az, nil
+				},
+			}
+			got, err := o.checkAttestedKeys(context.Background(), db, csr)
+			if tt.wantErr != "" {
+				assert.ErrorContains(t, err, tt.wantErr)
+				return
+			}
+			require.NoError(t, err)
+			assert.Equal(t, tt.want, got)
+		})
+	}
+}
+
+// TestOrder_Finalize_remoteAttestation finalizes an order whose only
+// identifier is remote-attestation: the CSR names nothing, and the attestation
+// reaches the template data and the bodies of the webhook requests.
+func TestOrder_Finalize_remoteAttestation(t *testing.T) {
+	csr, _ := mustCSR(t, "")
+	att := &webhook.Attestation{
+		Challenge: "remote-attest-01",
+		KeyDigest: remoteAttestationKeyDigest(csr),
+		Result:    &attestation.Result{Format: attestation.FormatTDX, TDX: &attestation.TDX{MRTD: "aa"}},
+	}
+
+	newOrder := func() *Order {
+		return &Order{
+			ID:               "orderID",
+			AccountID:        "accID",
+			Status:           StatusReady,
+			ExpiresAt:        time.Now().Add(time.Hour),
+			Identifiers:      []Identifier{{Type: RemoteAttestation}},
+			AuthorizationIDs: []string{"azID"},
+		}
+	}
+	db := &MockDB{
+		MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
+			return &Authorization{ID: id, Status: StatusValid, Attestation: att}, nil
+		},
+		MockCreateCertificate: func(_ context.Context, cert *Certificate) error {
+			cert.ID = "certID"
+			return nil
+		},
+		MockUpdateOrder: func(context.Context, *Order) error { return nil },
+	}
+	prov := &MockProvisioner{
+		MauthorizeSign: func(context.Context, string) ([]provisioner.SignOption, error) {
+			return []provisioner.SignOption{&provisioner.WebhookController{}}, nil
+		},
+		MgetOptions: func() *provisioner.Options { return nil },
+	}
+
+	t.Run("ok", func(t *testing.T) {
+		leaf, intermediate := &x509.Certificate{Raw: []byte("leaf")}, &x509.Certificate{Raw: []byte("intermediate")}
+		ca := &mockSignAuth{
+			signWithContext: func(ctx context.Context, _ *x509.CertificateRequest, _ provisioner.SignOptions, opts ...provisioner.SignOption) ([]*x509.Certificate, error) {
+				var wc *provisioner.WebhookController
+				for _, o := range opts {
+					if c, ok := o.(*provisioner.WebhookController); ok {
+						wc = c
+					}
+				}
+				require.NotNil(t, wc)
+				data, ok := wc.TemplateData.(x509util.TemplateData)
+				require.True(t, ok)
+				assert.Equal(t, att, data["Attestation"])
+				assert.Empty(t, data[x509util.SANsKey])
+
+				req := &webhook.RequestBody{}
+				require.NoError(t, wc.Enrich(ctx, req))
+				assert.Equal(t, att, req.Attestation)
+				return []*x509.Certificate{leaf, intermediate}, nil
+			},
+		}
+		o := newOrder()
+		require.NoError(t, o.Finalize(context.Background(), db, csr, ca, prov))
+		assert.Equal(t, StatusValid, o.Status)
+		assert.Equal(t, "certID", o.CertificateID)
+	})
+
+	t.Run("fail other key", func(t *testing.T) {
+		other, _ := mustCSR(t, "")
+		err := newOrder().Finalize(context.Background(), db, other, &mockSignAuth{}, prov)
+		assert.ErrorContains(t, err, "csr does not match the attested key")
+	})
+
+	t.Run("fail common name", func(t *testing.T) {
+		// The order names nothing, so the CSR cannot name anything either.
+		named := mustCSRWithKeyOf(t, csr, "workload.example.com")
+		err := newOrder().Finalize(context.Background(), db, named, &mockSignAuth{}, prov)
+		var acmeErr *Error
+		require.ErrorAs(t, err, &acmeErr)
+		assert.Equal(t, "urn:ietf:params:acme:error:badCSR", acmeErr.Type)
+	})
+}
+
+// mustCSRWithKeyOf returns a CSR whose public key is the one of csr, with the
+// given common name. Its signature is not valid, which Finalize does not check.
+func mustCSRWithKeyOf(t *testing.T, csr *x509.CertificateRequest, cn string) *x509.CertificateRequest {
+	t.Helper()
+	named := *csr
+	named.Subject = pkix.Name{CommonName: cn}
+	return &named
+}

+ 18 - 11
acme/db/nosql/authz.go

@@ -7,22 +7,25 @@ import (
 
 
 	"github.com/pkg/errors"
 	"github.com/pkg/errors"
 	"github.com/smallstep/certificates/acme"
 	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/webhook"
 	"github.com/smallstep/nosql"
 	"github.com/smallstep/nosql"
 )
 )
 
 
 // dbAuthz is the base authz type that others build from.
 // dbAuthz is the base authz type that others build from.
 type dbAuthz struct {
 type dbAuthz struct {
-	ID           string          `json:"id"`
-	AccountID    string          `json:"accountID"`
-	Identifier   acme.Identifier `json:"identifier"`
-	Status       acme.Status     `json:"status"`
-	Token        string          `json:"token"`
-	Fingerprint  string          `json:"fingerprint,omitempty"`
-	ChallengeIDs []string        `json:"challengeIDs"`
-	Wildcard     bool            `json:"wildcard"`
-	CreatedAt    time.Time       `json:"createdAt"`
-	ExpiresAt    time.Time       `json:"expiresAt"`
-	Error        *acme.Error     `json:"error"`
+	ID          string          `json:"id"`
+	AccountID   string          `json:"accountID"`
+	Identifier  acme.Identifier `json:"identifier"`
+	Status      acme.Status     `json:"status"`
+	Token       string          `json:"token"`
+	Fingerprint string          `json:"fingerprint,omitempty"`
+	// Attestation is set by a valid remote-attest-01 challenge.
+	Attestation  *webhook.Attestation `json:"attestation,omitempty"`
+	ChallengeIDs []string             `json:"challengeIDs"`
+	Wildcard     bool                 `json:"wildcard"`
+	CreatedAt    time.Time            `json:"createdAt"`
+	ExpiresAt    time.Time            `json:"expiresAt"`
+	Error        *acme.Error          `json:"error"`
 }
 }
 
 
 func (ba *dbAuthz) clone() *dbAuthz {
 func (ba *dbAuthz) clone() *dbAuthz {
@@ -71,6 +74,7 @@ func (db *DB) GetAuthorization(ctx context.Context, id string) (*acme.Authorizat
 		ExpiresAt:   dbaz.ExpiresAt,
 		ExpiresAt:   dbaz.ExpiresAt,
 		Token:       dbaz.Token,
 		Token:       dbaz.Token,
 		Fingerprint: dbaz.Fingerprint,
 		Fingerprint: dbaz.Fingerprint,
+		Attestation: dbaz.Attestation,
 		Error:       dbaz.Error,
 		Error:       dbaz.Error,
 	}, nil
 	}, nil
 }
 }
@@ -100,6 +104,7 @@ func (db *DB) CreateAuthorization(ctx context.Context, az *acme.Authorization) e
 		ChallengeIDs: chIDs,
 		ChallengeIDs: chIDs,
 		Token:        az.Token,
 		Token:        az.Token,
 		Fingerprint:  az.Fingerprint,
 		Fingerprint:  az.Fingerprint,
+		Attestation:  az.Attestation,
 		Wildcard:     az.Wildcard,
 		Wildcard:     az.Wildcard,
 	}
 	}
 
 
@@ -116,6 +121,7 @@ func (db *DB) UpdateAuthorization(ctx context.Context, az *acme.Authorization) e
 	nu := old.clone()
 	nu := old.clone()
 	nu.Status = az.Status
 	nu.Status = az.Status
 	nu.Fingerprint = az.Fingerprint
 	nu.Fingerprint = az.Fingerprint
+	nu.Attestation = az.Attestation
 	nu.Error = az.Error
 	nu.Error = az.Error
 	return db.save(ctx, old.ID, nu, old, "authz", authzTable)
 	return db.save(ctx, old.ID, nu, old, "authz", authzTable)
 }
 }
@@ -148,6 +154,7 @@ func (db *DB) GetAuthorizationsByAccountID(_ context.Context, accountID string)
 			ExpiresAt:   dbaz.ExpiresAt,
 			ExpiresAt:   dbaz.ExpiresAt,
 			Token:       dbaz.Token,
 			Token:       dbaz.Token,
 			Fingerprint: dbaz.Fingerprint,
 			Fingerprint: dbaz.Fingerprint,
+			Attestation: dbaz.Attestation,
 			Error:       dbaz.Error,
 			Error:       dbaz.Error,
 		})
 		})
 	}
 	}

+ 45 - 0
acme/db/nosql/challenge_remote_attestation_test.go

@@ -8,7 +8,9 @@ import (
 	"github.com/stretchr/testify/require"
 	"github.com/stretchr/testify/require"
 
 
 	"github.com/smallstep/certificates/acme"
 	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/attestation"
 	"github.com/smallstep/certificates/db"
 	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/certificates/webhook"
 )
 )
 
 
 // TestDB_Challenge_remoteAttestation checks that the fields of a
 // TestDB_Challenge_remoteAttestation checks that the fields of a
@@ -48,3 +50,46 @@ func TestDB_Challenge_remoteAttestation(t *testing.T) {
 	assert.NotContains(t, string(stored), "freshnessNonce")
 	assert.NotContains(t, string(stored), "freshnessNonce")
 	assert.NotContains(t, string(stored), "attestClaimsHint")
 	assert.NotContains(t, string(stored), "attestClaimsHint")
 }
 }
+
+// TestDB_Authorization_remoteAttestation checks that the attestation a
+// remote-attest-01 challenge verified is stored with the authorization and
+// read back.
+func TestDB_Authorization_remoteAttestation(t *testing.T) {
+	var stored []byte
+	d := DB{db: &db.MockNoSQLDB{
+		MCmpAndSwap: func(_, _, _, nu []byte) ([]byte, bool, error) {
+			stored = nu
+			return nu, true, nil
+		},
+		MGet: func(bucket, key []byte) ([]byte, error) {
+			assert.Equal(t, authzTable, bucket)
+			return stored, nil
+		},
+	}}
+	att := &webhook.Attestation{
+		Challenge:      "remote-attest-01",
+		FreshnessNonce: "nonce",
+		KeyDigest:      "01",
+		Result: &attestation.Result{
+			Format:   attestation.FormatSEVSNP,
+			SEVSNP:   &attestation.SEVSNP{Measurement: "aa", GuestSVN: 2},
+			Evidence: []byte("report"),
+		},
+	}
+	az := &acme.Authorization{
+		AccountID:  "accountID",
+		Identifier: acme.Identifier{Type: acme.RemoteAttestation},
+		Status:     acme.StatusPending,
+		Challenges: []*acme.Challenge{},
+	}
+	require.NoError(t, d.CreateAuthorization(context.Background(), az))
+	assert.NotContains(t, string(stored), `"attestation"`)
+
+	az.Status = acme.StatusValid
+	az.Attestation = att
+	require.NoError(t, d.UpdateAuthorization(context.Background(), az))
+
+	got, err := d.GetAuthorization(context.Background(), az.ID)
+	require.NoError(t, err)
+	assert.Equal(t, att, got.Attestation)
+}

+ 42 - 26
acme/order.go

@@ -145,25 +145,43 @@ func (o *Order) UpdateStatus(ctx context.Context, db DB) error {
 	return nil
 	return nil
 }
 }
 
 
-// getAuthorizationFingerprint returns a fingerprint from the list of authorizations. This
-// fingerprint is used on the device-attest-01 flow to verify the attestation
-// certificate public key with the CSR public key.
-//
-// There's no point on reading all the authorizations as there will be only one
-// for a permanent identifier.
-func (o *Order) getAuthorizationFingerprint(ctx context.Context, db DB) (string, error) {
+// checkAttestedKeys checks the CSR's key against every key an authorization of
+// the order attested: the fingerprint of the key a device-attest-01 challenge
+// verified, and the digest of the key the evidence of a remote-attest-01
+// challenge bound. It returns the attestation of the order's remote-attest-01
+// challenge, if there is one.
+func (o *Order) checkAttestedKeys(ctx context.Context, db DB, csr *x509.CertificateRequest) (*webhook.Attestation, error) {
+	var (
+		att         *webhook.Attestation
+		fingerprint string
+		keyDigest   string
+	)
 	for _, azID := range o.AuthorizationIDs {
 	for _, azID := range o.AuthorizationIDs {
 		az, err := db.GetAuthorization(ctx, azID)
 		az, err := db.GetAuthorization(ctx, azID)
 		if err != nil {
 		if err != nil {
-			return "", WrapErrorISE(err, "error getting authorization %q", azID)
+			return nil, WrapErrorISE(err, "error getting authorization %q", azID)
 		}
 		}
-		// There's no point on reading all the authorizations as there will
-		// be only one for a permanent identifier.
 		if az.Fingerprint != "" {
 		if az.Fingerprint != "" {
-			return az.Fingerprint, nil
+			if fingerprint == "" {
+				if fingerprint, err = keyutil.Fingerprint(csr.PublicKey); err != nil {
+					return nil, WrapErrorISE(err, "error calculating key fingerprint")
+				}
+			}
+			if subtle.ConstantTimeCompare([]byte(az.Fingerprint), []byte(fingerprint)) == 0 {
+				return nil, NewError(ErrorUnauthorizedType, "order %s csr does not match the attested key", o.ID)
+			}
+		}
+		if az.Attestation != nil {
+			if keyDigest == "" {
+				keyDigest = remoteAttestationKeyDigest(csr)
+			}
+			if subtle.ConstantTimeCompare([]byte(az.Attestation.KeyDigest), []byte(keyDigest)) == 0 {
+				return nil, NewError(ErrorUnauthorizedType, "order %s csr does not match the attested key", o.ID)
+			}
+			att = az.Attestation
 		}
 		}
 	}
 	}
-	return "", nil
+	return att, nil
 }
 }
 
 
 // Finalize signs a certificate if the necessary conditions for Order completion
 // Finalize signs a certificate if the necessary conditions for Order completion
@@ -191,23 +209,12 @@ func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateReques
 		return NewErrorISE("unexpected status %s for order %s", o.Status, o.ID)
 		return NewErrorISE("unexpected status %s for order %s", o.Status, o.ID)
 	}
 	}
 
 
-	// Get key fingerprint if any. And then compare it with the CSR fingerprint.
-	//
-	// In device-attest-01 challenges we should check that the keys in the CSR
-	// and the attestation certificate are the same.
-	fingerprint, err := o.getAuthorizationFingerprint(ctx, db)
+	// In device-attest-01 and remote-attest-01 challenges, the key in the CSR
+	// must be the attested one.
+	att, err := o.checkAttestedKeys(ctx, db, csr)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
-	if fingerprint != "" {
-		fp, err := keyutil.Fingerprint(csr.PublicKey)
-		if err != nil {
-			return WrapErrorISE(err, "error calculating key fingerprint")
-		}
-		if subtle.ConstantTimeCompare([]byte(fingerprint), []byte(fp)) == 0 {
-			return NewError(ErrorUnauthorizedType, "order %s csr does not match the attested key", o.ID)
-		}
-	}
 
 
 	// canonicalize the CSR to allow for comparison
 	// canonicalize the CSR to allow for comparison
 	csr = canonicalize(csr)
 	csr = canonicalize(csr)
@@ -240,6 +247,9 @@ func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateReques
 	} else {
 	} else {
 		data.SetCommonName(csr.Subject.CommonName)
 		data.SetCommonName(csr.Subject.CommonName)
 	}
 	}
+	if att != nil {
+		data.Set("Attestation", att)
+	}
 
 
 	// Custom sign options passed to authority.Sign
 	// Custom sign options passed to authority.Sign
 	var extraOptions []provisioner.SignOption
 	var extraOptions []provisioner.SignOption
@@ -293,6 +303,9 @@ func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateReques
 	for _, signOp := range signOps {
 	for _, signOp := range signOps {
 		if wc, ok := signOp.(*provisioner.WebhookController); ok {
 		if wc, ok := signOp.(*provisioner.WebhookController); ok {
 			wc.TemplateData = data
 			wc.TemplateData = data
+			if att != nil {
+				wc.AppendRequestBodyOptions(webhook.WithAttestation(att))
+			}
 		}
 		}
 	}
 	}
 
 
@@ -448,6 +461,9 @@ func (o *Order) sans(csr *x509.CertificateRequest) ([]x509util.SubjectAlternativ
 			}
 			}
 			tmpOrderURIs[indexURI] = clientID
 			tmpOrderURIs[indexURI] = clientID
 			indexURI++
 			indexURI++
+		case RemoteAttestation:
+			// It names nothing in the certificate.
+			continue
 		default:
 		default:
 			return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
 			return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
 		}
 		}

+ 0 - 52
acme/order_test.go

@@ -2589,55 +2589,3 @@ func TestOrder_sans(t *testing.T) {
 		})
 		})
 	}
 	}
 }
 }
-
-func TestOrder_getAuthorizationFingerprint(t *testing.T) {
-	ctx := context.Background()
-	type fields struct {
-		AuthorizationIDs []string
-	}
-	type args struct {
-		ctx context.Context
-		db  DB
-	}
-	tests := []struct {
-		name    string
-		fields  fields
-		args    args
-		want    string
-		wantErr bool
-	}{
-		{"ok", fields{[]string{"az1", "az2"}}, args{ctx, &MockDB{
-			MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
-				return &Authorization{ID: id, Status: StatusValid}, nil
-			},
-		}}, "", false},
-		{"ok fingerprint", fields{[]string{"az1", "az2"}}, args{ctx, &MockDB{
-			MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
-				if id == "az1" {
-					return &Authorization{ID: id, Status: StatusValid}, nil
-				}
-				return &Authorization{ID: id, Fingerprint: "fingerprint", Status: StatusValid}, nil
-			},
-		}}, "fingerprint", false},
-		{"fail", fields{[]string{"az1", "az2"}}, args{ctx, &MockDB{
-			MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
-				return nil, errors.New("force")
-			},
-		}}, "", true},
-	}
-	for _, tt := range tests {
-		t.Run(tt.name, func(t *testing.T) {
-			o := &Order{
-				AuthorizationIDs: tt.fields.AuthorizationIDs,
-			}
-			got, err := o.getAuthorizationFingerprint(tt.args.ctx, tt.args.db)
-			if (err != nil) != tt.wantErr {
-				t.Errorf("Order.getAuthorizationFingerprint() error = %v, wantErr %v", err, tt.wantErr)
-				return
-			}
-			if got != tt.want {
-				t.Errorf("Order.getAuthorizationFingerprint() = %v, want %v", got, tt.want)
-			}
-		})
-	}
-}