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

Validate dns-persist-01 ACME challenges

Implement the dns-persist-01 validation method defined in
draft-ietf-acme-dns-persist-02. The validation looks up the TXT records
at _validation-persist.<domain>, ignores the ones for other issuers, and
succeeds if a record binds the domain to the account using the hashed
account URI. Wildcard identifiers require policy=wildcard.

The persistUntil parameter limits the expiration of the authorization,
and orders cannot be finalized once an authorization validated with
dns-persist-01 has expired.
Josh Drake 1 месяц назад
Родитель
Сommit
15d7244fdd
6 измененных файлов с 883 добавлено и 13 удалено
  1. 2 0
      acme/api/account_test.go
  2. 287 13
      acme/challenge.go
  3. 486 0
      acme/challenge_test.go
  4. 22 0
      acme/common.go
  5. 25 0
      acme/order.go
  6. 61 0
      acme/order_test.go

+ 2 - 0
acme/api/account_test.go

@@ -51,6 +51,8 @@ func (*fakeProvisioner) IsAttestationFormatEnabled(context.Context, provisioner.
 	return true
 	return true
 }
 }
 func (*fakeProvisioner) GetAttestationRoots() (*x509.CertPool, bool)   { return nil, false }
 func (*fakeProvisioner) GetAttestationRoots() (*x509.CertPool, bool)   { return nil, false }
+func (*fakeProvisioner) GetIssuerDomainNames() []string                { return nil }
+func (*fakeProvisioner) GetAccountHashPrefix() string                  { return "" }
 func (*fakeProvisioner) AuthorizeRevoke(context.Context, string) error { return nil }
 func (*fakeProvisioner) AuthorizeRevoke(context.Context, string) error { return nil }
 func (*fakeProvisioner) GetID() string                                 { return "" }
 func (*fakeProvisioner) GetID() string                                 { return "" }
 func (*fakeProvisioner) GetName() string                               { return "" }
 func (*fakeProvisioner) GetName() string                               { return "" }

+ 287 - 13
acme/challenge.go

@@ -60,6 +60,8 @@ const (
 	WIREOIDC01 ChallengeType = "wire-oidc-01"
 	WIREOIDC01 ChallengeType = "wire-oidc-01"
 	// WIREDPOP01 is the Wire DPoP challenge type
 	// WIREDPOP01 is the Wire DPoP challenge type
 	WIREDPOP01 ChallengeType = "wire-dpop-01"
 	WIREDPOP01 ChallengeType = "wire-dpop-01"
+	// DNSPERSIST01 is the dns-persist-01 ACME challenge type
+	DNSPERSIST01 ChallengeType = "dns-persist-01"
 )
 )
 
 
 var (
 var (
@@ -81,19 +83,20 @@ var (
 
 
 // Challenge represents an ACME response Challenge type.
 // Challenge represents an ACME response Challenge type.
 type Challenge struct {
 type Challenge struct {
-	ID              string        `json:"-"`
-	AccountID       string        `json:"-"`
-	AuthorizationID string        `json:"-"`
-	Value           string        `json:"-"`
-	Type            ChallengeType `json:"type"`
-	Status          Status        `json:"status"`
-	Token           string        `json:"token"`
-	ValidatedAt     string        `json:"validated,omitempty"`
-	URL             string        `json:"url"`
-	Target          string        `json:"target,omitempty"`
-	Error           *Error        `json:"error,omitempty"`
-	Payload         []byte        `json:"-"`
-	PayloadFormat   string        `json:"-"`
+	ID                string        `json:"-"`
+	AccountID         string        `json:"-"`
+	AuthorizationID   string        `json:"-"`
+	Value             string        `json:"-"`
+	Type              ChallengeType `json:"type"`
+	Status            Status        `json:"status"`
+	Token             string        `json:"token,omitempty"`
+	ValidatedAt       string        `json:"validated,omitempty"`
+	URL               string        `json:"url"`
+	Target            string        `json:"target,omitempty"`
+	IssuerDomainNames []string      `json:"issuerDomainNames,omitempty"`
+	Error             *Error        `json:"error,omitempty"`
+	Payload           []byte        `json:"-"`
+	PayloadFormat     string        `json:"-"`
 }
 }
 
 
 // ToLog enables response logging.
 // ToLog enables response logging.
@@ -118,6 +121,8 @@ func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey,
 		return http01Validate(ctx, ch, db, jwk)
 		return http01Validate(ctx, ch, db, jwk)
 	case DNS01:
 	case DNS01:
 		return dns01Validate(ctx, ch, db, jwk)
 		return dns01Validate(ctx, ch, db, jwk)
+	case DNSPERSIST01:
+		return dnsPersist01Validate(ctx, ch, db, jwk)
 	case TLSALPN01:
 	case TLSALPN01:
 		return tlsalpn01Validate(ctx, ch, db, jwk)
 		return tlsalpn01Validate(ctx, ch, db, jwk)
 	case DEVICEATTEST01:
 	case DEVICEATTEST01:
@@ -228,6 +233,12 @@ func dns01ChallengeHost(domain string) string {
 	return "_acme-challenge." + rootedName(domain)
 	return "_acme-challenge." + rootedName(domain)
 }
 }
 
 
+// dnsPersist01ChallengeHost returns the TXT record used in DNS-PERSIST-01
+// validations.
+func dnsPersist01ChallengeHost(domain string) string {
+	return "_validation-persist." + rootedName(domain)
+}
+
 func tlsAlert(err error) uint8 {
 func tlsAlert(err error) uint8 {
 	if opErr, ok := errors.AsType[*net.OpError](err); ok {
 	if opErr, ok := errors.AsType[*net.OpError](err); ok {
 		v := reflect.ValueOf(opErr.Err)
 		v := reflect.ValueOf(opErr.Err)
@@ -397,6 +408,269 @@ func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebK
 	return nil
 	return nil
 }
 }
 
 
+// dnsPersist01HashAlgorithm is the hash algorithm used in the hashed account
+// URIs of dns-persist-01 validation records. It is the only one supported.
+const dnsPersist01HashAlgorithm = "sha-256"
+
+// dnsPersist01Record contains the parameters of a dns-persist-01 validation
+// record.
+type dnsPersist01Record struct {
+	accountURI   string
+	wildcard     bool
+	persistUntil time.Time
+}
+
+// dnsPersist01Validate validates a dns-persist-01 challenge as defined in
+// draft-ietf-acme-dns-persist-02. Validation succeeds if one of the TXT
+// records at _validation-persist.<domain> contains one of the challenge issuer
+// domain names and a hashed account URI that binds the record to the account.
+func dnsPersist01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
+	// Load the authorization to check if it's for a wildcard identifier, and
+	// to limit its expiration to the persistUntil parameter of the record.
+	az, err := db.GetAuthorization(ctx, ch.AuthorizationID)
+	if err != nil {
+		return WrapErrorISE(err, "error loading authorization")
+	}
+
+	// The account status is checked on every request, but the draft requires
+	// to check it on every validation attempt too.
+	acc, err := db.GetAccount(ctx, ch.AccountID)
+	if err != nil {
+		return WrapErrorISE(err, "error loading account")
+	}
+	if !acc.IsValid() {
+		return storeError(ctx, db, ch, true, NewError(ErrorUnauthorizedType,
+			"account %s is not valid", acc.ID))
+	}
+
+	// The hashed account URI is computed over the account URL returned to the
+	// client, so use the stored location instead of one derived from the
+	// current request.
+	accountURL := acc.GetLocation()
+	if accountURL == "" {
+		return storeError(ctx, db, ch, true, NewError(ErrorUnauthorizedType,
+			"account %s does not have the stored location required by %s challenges", acc.ID, ch.Type))
+	}
+
+	// Normalize domain for wildcard DNS names, the validation record is always
+	// at the base domain.
+	domain, err := x509util.SanitizeName(strings.TrimSuffix(strings.TrimPrefix(ch.Value, "*."), "."))
+	if err != nil || len(domain) > 253 {
+		return storeError(ctx, db, ch, true, NewError(ErrorMalformedType,
+			"invalid DNS name %s", ch.Value))
+	}
+
+	// Key rollover is not supported, so the current account key is the only
+	// one that has been used by the account.
+	thumbprint, err := KeyToID(jwk)
+	if err != nil {
+		return err
+	}
+	prefix := MustProvisionerFromContext(ctx).GetAccountHashPrefix()
+	expected := []string{
+		dnsPersist01AccountURI(prefix, domain, thumbprint, accountURL),
+		dnsPersist01AccountURI(prefix, "*", thumbprint, accountURL),
+	}
+
+	host := dnsPersist01ChallengeHost(domain)
+	vc := MustClientFromContext(ctx)
+	txtRecords, err := vc.LookupTxt(host)
+	if err != nil {
+		return storeError(ctx, db, ch, false, WrapError(ErrorDNSType, err,
+			"error looking up TXT records for domain %s", domain))
+	}
+
+	// Validation succeeds if any of the records for the issuer domain names in
+	// the challenge is valid. Records for other CAs are ignored. If no record
+	// is valid, the error from the first one is reported.
+	var (
+		record    *dnsPersist01Record
+		recordErr *Error
+	)
+	now := clock.Now()
+	for _, txt := range txtRecords {
+		rec, ok, acmeErr := parseDNSPersist01Record(txt, ch.IssuerDomainNames, prefix)
+		if !ok {
+			continue
+		}
+		if acmeErr == nil {
+			acmeErr = verifyDNSPersist01Record(rec, now, expected, az.Wildcard, domain)
+		}
+		if acmeErr != nil {
+			if recordErr == nil {
+				recordErr = acmeErr
+			}
+			continue
+		}
+		record = rec
+		break
+	}
+	if record == nil {
+		if recordErr == nil {
+			recordErr = NewError(ErrorUnauthorizedType,
+				"no TXT record found at %s for issuer domain names %s", host, strings.Join(ch.IssuerDomainNames, ", "))
+		}
+		return storeError(ctx, db, ch, false, recordErr)
+	}
+
+	// The authorization cannot expire after the persistUntil timestamp.
+	//
+	// TODO: add method to update authorization and challenge atomically.
+	if !record.persistUntil.IsZero() && record.persistUntil.Before(az.ExpiresAt) {
+		az.ExpiresAt = record.persistUntil
+		if err := db.UpdateAuthorization(ctx, az); err != nil {
+			return WrapErrorISE(err, "error updating authorization")
+		}
+	}
+
+	// Update and store the challenge.
+	ch.Status = StatusValid
+	ch.Error = nil
+	ch.ValidatedAt = clock.Now().Format(time.RFC3339)
+
+	if err := db.UpdateChallenge(ctx, ch); err != nil {
+		return WrapErrorISE(err, "error updating challenge")
+	}
+	return nil
+}
+
+// dnsPersist01AccountURI returns the hashed account URI that binds a
+// dns-persist-01 validation record for the given domain to an account. The
+// domain can be "*" for records that are not bound to a domain. The domain must
+// not be longer than 255 octets.
+func dnsPersist01AccountURI(prefix, domain, thumbprint, accountURL string) string {
+	b := make([]byte, 0, 1+len(domain)+len(thumbprint)+len(accountURL))
+	b = append(b, cast.Uint8(len(domain)))
+	b = append(b, domain...)
+	b = append(b, thumbprint...)
+	b = append(b, accountURL...)
+	sum := sha256.Sum256(b)
+	return prefix + dnsPersist01HashAlgorithm + "/" + base64.RawURLEncoding.EncodeToString(sum[:])
+}
+
+// parseDNSPersist01Record parses a dns-persist-01 validation record, using the
+// issue-value syntax defined in RFC 8659, section 4.2. It returns false if the
+// issuer domain name of the record is not one of the given ones. Unknown
+// parameters are ignored.
+func parseDNSPersist01Record(txt string, issuerDomainNames []string, accountHashPrefix string) (*dnsPersist01Record, bool, *Error) {
+	issuer, params, _ := strings.Cut(txt, ";")
+	issuer = strings.ToLower(strings.TrimSuffix(strings.Trim(issuer, " \t"), "."))
+	if !slices.Contains(issuerDomainNames, issuer) {
+		return nil, false, nil
+	}
+
+	rec := new(dnsPersist01Record)
+	if strings.Trim(params, " \t") != "" {
+		seen := make(map[string]bool)
+		for param := range strings.SplitSeq(params, ";") {
+			tag, value, ok := strings.Cut(param, "=")
+			tag, value = strings.Trim(tag, " \t"), strings.Trim(value, " \t")
+			if !ok || !isDNSPersist01Tag(tag) || !isDNSPersist01Value(value) {
+				return nil, true, NewError(ErrorMalformedType,
+					"TXT record %q has an invalid parameter %q", txt, param)
+			}
+
+			// Tags are compared case-insensitively, so a constraint like
+			// persistUntil is never ignored because of its case.
+			tag = strings.ToLower(tag)
+			if seen[tag] {
+				return nil, true, NewError(ErrorMalformedType,
+					"TXT record %q has a duplicate parameter %q", txt, tag)
+			}
+			seen[tag] = true
+
+			switch tag {
+			case "accounturi":
+				if err := validateDNSPersist01AccountURI(value, accountHashPrefix); err != nil {
+					return nil, true, err
+				}
+				rec.accountURI = value
+			case "policy":
+				rec.wildcard = strings.EqualFold(value, "wildcard")
+			case "persistuntil":
+				ts, err := strconv.ParseInt(value, 10, 64)
+				if err != nil || strings.Trim(value, "0123456789") != "" {
+					return nil, true, NewError(ErrorMalformedType,
+						"TXT record %q has an invalid persistUntil value %q", txt, value)
+				}
+				rec.persistUntil = time.Unix(ts, 0).UTC()
+			}
+		}
+	}
+
+	if rec.accountURI == "" {
+		return nil, true, NewError(ErrorMalformedType,
+			"TXT record %q is missing the accounturi parameter", txt)
+	}
+	return rec, true, nil
+}
+
+// validateDNSPersist01AccountURI checks that the given value is a hashed
+// account URI with the format <accountHashPrefix>sha-256/<base64url hash>.
+func validateDNSPersist01AccountURI(value, accountHashPrefix string) *Error {
+	rest, ok := strings.CutPrefix(value, accountHashPrefix)
+	if !ok {
+		return NewError(ErrorMalformedType,
+			"accounturi %q does not start with %q", value, accountHashPrefix)
+	}
+	alg, hash, _ := strings.Cut(rest, "/")
+	if alg != dnsPersist01HashAlgorithm {
+		return NewError(ErrorMalformedType,
+			"accounturi %q does not use the %s hash algorithm", value, dnsPersist01HashAlgorithm)
+	}
+	if b, err := base64.RawURLEncoding.Strict().DecodeString(hash); err != nil || len(b) != sha256.Size {
+		return NewError(ErrorMalformedType,
+			"accounturi %q does not contain a valid %s hash value", value, dnsPersist01HashAlgorithm)
+	}
+	return nil
+}
+
+// verifyDNSPersist01Record checks that a dns-persist-01 validation record for
+// the given domain authorizes the account and has not expired.
+func verifyDNSPersist01Record(rec *dnsPersist01Record, now time.Time, expected []string, wildcard bool, domain string) *Error {
+	switch {
+	case !slices.Contains(expected, rec.accountURI):
+		return NewError(ErrorUnauthorizedType,
+			"accounturi does not match; expected %s, but got %s", expected[0], rec.accountURI)
+	case !rec.persistUntil.IsZero() && now.After(rec.persistUntil):
+		return NewError(ErrorUnauthorizedType,
+			"TXT record expired at %s", rec.persistUntil.Format(time.RFC3339))
+	case wildcard && !rec.wildcard:
+		return NewError(ErrorUnauthorizedType,
+			"TXT record does not have the policy=wildcard parameter required for *.%s", domain)
+	default:
+		return nil
+	}
+}
+
+// isDNSPersist01Tag returns true if the given string matches the tag syntax:
+//
+//	tag = (ALPHA / DIGIT) *( *("-") (ALPHA / DIGIT))
+func isDNSPersist01Tag(s string) bool {
+	if s == "" || s[0] == '-' || s[len(s)-1] == '-' {
+		return false
+	}
+	for _, c := range []byte(s) {
+		if c != '-' && (c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') {
+			return false
+		}
+	}
+	return true
+}
+
+// isDNSPersist01Value returns true if the given string matches the value
+// syntax:
+//
+//	value = *(%x21-3A / %x3C-7E)
+func isDNSPersist01Value(s string) bool {
+	for _, c := range []byte(s) {
+		if c < 0x21 || c > 0x7e || c == ';' {
+			return false
+		}
+	}
+	return true
+}
+
 type wireOidcPayload struct {
 type wireOidcPayload struct {
 	// IDToken contains the OIDC identity token
 	// IDToken contains the OIDC identity token
 	IDToken string `json:"id_token"`
 	IDToken string `json:"id_token"`

+ 486 - 0
acme/challenge_test.go

@@ -788,6 +788,57 @@ MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
 				},
 				},
 			}
 			}
 		},
 		},
+		"ok/dns-persist-01": func(t *testing.T) test {
+			ch := &Challenge{
+				ID:                "chID",
+				AccountID:         "accID",
+				AuthorizationID:   "azID",
+				Type:              "dns-persist-01",
+				Status:            StatusPending,
+				Value:             "zap.internal",
+				IssuerDomainNames: []string{"ca.example.com"},
+			}
+
+			return test{
+				ch:  ch,
+				jwk: dnsPersist01TestJWK(t),
+				ctx: NewProvisionerContext(context.Background(), &MockProvisioner{
+					MgetAccountHashPrefix: func() string { return "https://ca.example.com/account-hash/" },
+				}),
+				vc: &mockClient{
+					lookupTxt: func(name string) ([]string, error) {
+						assert.Equal(t, "_validation-persist.zap.internal", name)
+						return nil, errors.New("force")
+					},
+				},
+				db: &MockDB{
+					MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
+						assert.Equal(t, "azID", id)
+						return &Authorization{ID: id, Status: StatusPending}, nil
+					},
+					MockGetAccount: func(ctx context.Context, id string) (*Account, error) {
+						assert.Equal(t, "accID", id)
+						return &Account{ID: id, Status: StatusValid, LocationPrefix: "https://ca.example.com/acme/acme/account/"}, nil
+					},
+					MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
+						assert.Equal(t, "chID", updch.ID)
+						assert.Equal(t, ChallengeType("dns-persist-01"), updch.Type)
+						assert.Equal(t, "zap.internal", updch.Value)
+						assert.Equal(t, StatusPending, updch.Status)
+
+						err := NewError(ErrorDNSType, "error looking up TXT records for domain %s: force", ch.Value)
+
+						assert.EqualError(t, updch.Error.Err, err.Err.Error())
+						assert.Equal(t, err.Type, updch.Error.Type)
+						assert.Equal(t, err.Detail, updch.Error.Detail)
+						assert.Equal(t, err.Status, updch.Error.Status)
+						assert.Equal(t, err.Subproblems, updch.Error.Subproblems)
+
+						return nil
+					},
+				},
+			}
+		},
 		"fail/tls-alpn-01": func(t *testing.T) test {
 		"fail/tls-alpn-01": func(t *testing.T) test {
 			ch := &Challenge{
 			ch := &Challenge{
 				ID:     "chID",
 				ID:     "chID",
@@ -5452,3 +5503,438 @@ func Test_dns01ChallengeHost(t *testing.T) {
 		})
 		})
 	}
 	}
 }
 }
+
+func Test_dnsPersist01ChallengeHost(t *testing.T) {
+	tests := []struct {
+		name       string
+		strictFQDN bool
+		domain     string
+		want       string
+	}{
+		{"dns", false, "smallstep.com", "_validation-persist.smallstep.com"},
+		{"dns strict", true, "smallstep.com", "_validation-persist.smallstep.com."},
+		{"rooted dns", false, "smallstep.com.", "_validation-persist.smallstep.com."},
+		{"rooted dns strict", true, "smallstep.com.", "_validation-persist.smallstep.com."},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			tmp := StrictFQDN
+			t.Cleanup(func() {
+				StrictFQDN = tmp
+			})
+			StrictFQDN = tt.strictFQDN
+			assert.Equal(t, tt.want, dnsPersist01ChallengeHost(tt.domain))
+		})
+	}
+}
+
+// dnsPersist01TestJWK returns the example key from RFC 7638, section 3.1. It
+// is the key used in the examples of draft-ietf-acme-dns-persist-02.
+func dnsPersist01TestJWK(t *testing.T) *jose.JSONWebKey {
+	t.Helper()
+	jwk := new(jose.JSONWebKey)
+	require.NoError(t, json.Unmarshal([]byte(`{
+		"kty": "RSA",
+		"n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
+		"e": "AQAB",
+		"alg": "RS256",
+		"kid": "2011-04-29"
+	}`), jwk))
+	return jwk
+}
+
+func Test_dnsPersist01AccountURI(t *testing.T) {
+	// Test vectors from draft-ietf-acme-dns-persist-02, section 10.2.
+	thumbprint, err := KeyToID(dnsPersist01TestJWK(t))
+	require.NoError(t, err)
+	require.Equal(t, "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs", thumbprint)
+
+	const (
+		prefix     = "https://ca.example/account-hash/"
+		accountURL = "https://ca.example/acct/123"
+	)
+	tests := []struct {
+		name   string
+		domain string
+		want   string
+	}{
+		{"domain", "example.com", "https://ca.example/account-hash/sha-256/5SQm7n6tPh2-PlLbCKGnViTXX5z19SCN4cPGQHSk-kw"},
+		{"any domain", "*", "https://ca.example/account-hash/sha-256/NpDnSwUthQK8zCgFdefYxAdAVPnygMLbs9US6oO-5ug"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			assert.Equal(t, tt.want, dnsPersist01AccountURI(prefix, tt.domain, thumbprint, accountURL))
+		})
+	}
+}
+
+func TestDNSPersist01Validate(t *testing.T) {
+	// The key, account URL and hashed account URIs are the ones in
+	// draft-ietf-acme-dns-persist-02, section 10.2.
+	const (
+		prefix           = "https://ca.example/account-hash/"
+		accountURI       = prefix + "sha-256/5SQm7n6tPh2-PlLbCKGnViTXX5z19SCN4cPGQHSk-kw"
+		anyDomainURI     = prefix + "sha-256/NpDnSwUthQK8zCgFdefYxAdAVPnygMLbs9US6oO-5ug"
+		otherAccountURI  = prefix + "sha-256/Mpngr2LZCN9gPArggXqEu4pKtYZvLL5IxMStzyWrrXc"
+		validationDomain = "_validation-persist.example.com"
+	)
+	jwk := dnsPersist01TestJWK(t)
+	issuerDomainNames := []string{"authority.example", "ca.example.net"}
+	now := clock.Now()
+	expiresAt := now.Add(24 * time.Hour)
+	persistUntil := now.Add(time.Hour)
+	validAccount := &Account{ID: "123", Status: StatusValid, LocationPrefix: "https://ca.example/acct/"}
+	wwwAccountURI := dnsPersist01AccountURI(prefix, "www.example.com", "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs", "https://ca.example/acct/123")
+
+	tests := []struct {
+		name        string
+		value       string
+		wildcard    bool
+		account     *Account
+		accountErr  error
+		authzErr    error
+		txtRecords  []string
+		lookupErr   error
+		updChErr    error
+		updAzErr    error
+		wantStatus  Status
+		wantChErr   *Error
+		wantExpires time.Time
+		err         *Error
+	}{
+		{
+			name:       "ok",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI},
+			wantStatus: StatusValid,
+		},
+		{
+			name:       "ok/any-domain",
+			value:      "example.com",
+			txtRecords: []string{"ca.example.net; accounturi=" + anyDomainURI},
+			wantStatus: StatusValid,
+		},
+		{
+			name:       "ok/normalized-identifier",
+			value:      "Example.COM",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI},
+			wantStatus: StatusValid,
+		},
+		{
+			name:       "ok/case-insensitive",
+			value:      "example.com",
+			wildcard:   true,
+			txtRecords: []string{"Authority.Example.;AccountURI=" + accountURI + " ;\tPolicy=WILDCARD"},
+			wantStatus: StatusValid,
+		},
+		{
+			name:       "ok/wildcard",
+			value:      "example.com",
+			wildcard:   true,
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + "; policy=wildcard"},
+			wantStatus: StatusValid,
+		},
+		{
+			name:       "ok/unknown-parameters",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; foo=bar; accounturi=" + accountURI + "; policy=other; empty="},
+			wantStatus: StatusValid,
+		},
+		{
+			name:  "ok/multiple-records",
+			value: "example.com",
+			txtRecords: []string{
+				"ca1.example; accounturi=https://ca1.example/account-hash/sha-256/wjZNvLpIgf7zrr9KQo7zCLaG2Ea67KS4o4cAwSepsls; policy=wildcard",
+				"ca2.example; invalid record",
+				"authority.example; accounturi=" + otherAccountURI,
+				"ca.example.net; accounturi=" + accountURI,
+			},
+			wantStatus: StatusValid,
+		},
+		{
+			name:        "ok/persist-until",
+			value:       "example.com",
+			txtRecords:  []string{fmt.Sprintf("authority.example; accounturi=%s; persistUntil=%d", accountURI, persistUntil.Unix())},
+			wantStatus:  StatusValid,
+			wantExpires: persistUntil,
+		},
+		{
+			name:       "ok/persist-until-after-expiration",
+			value:      "example.com",
+			txtRecords: []string{fmt.Sprintf("authority.example; accounturi=%s; persistUntil=%d", accountURI, expiresAt.Add(time.Hour).Unix())},
+			wantStatus: StatusValid,
+		},
+		{
+			name:       "fail/get-authorization-error",
+			value:      "example.com",
+			authzErr:   errors.New("force"),
+			wantStatus: StatusPending,
+			err:        NewErrorISE("error loading authorization: force"),
+		},
+		{
+			name:       "fail/get-account-error",
+			value:      "example.com",
+			accountErr: errors.New("force"),
+			wantStatus: StatusPending,
+			err:        NewErrorISE("error loading account: force"),
+		},
+		{
+			name:       "fail/account-deactivated",
+			value:      "example.com",
+			account:    &Account{ID: "123", Status: StatusDeactivated, LocationPrefix: "https://ca.example/acct/"},
+			wantStatus: StatusInvalid,
+			wantChErr:  NewError(ErrorUnauthorizedType, "account 123 is not valid"),
+		},
+		{
+			name:       "fail/account-without-location",
+			value:      "example.com",
+			account:    &Account{ID: "123", Status: StatusValid},
+			wantStatus: StatusInvalid,
+			wantChErr:  NewError(ErrorUnauthorizedType, "account 123 does not have the stored location required by dns-persist-01 challenges"),
+		},
+		{
+			name:       "fail/invalid-domain",
+			value:      "exa mple.com",
+			wantStatus: StatusInvalid,
+			wantChErr:  NewError(ErrorMalformedType, "invalid DNS name exa mple.com"),
+		},
+		{
+			name:       "fail/lookup-error",
+			value:      "example.com",
+			lookupErr:  errors.New("force"),
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorDNSType, "error looking up TXT records for domain example.com: force"),
+		},
+		{
+			name:       "fail/no-records",
+			value:      "example.com",
+			txtRecords: []string{"ca1.example; accounturi=" + accountURI},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorUnauthorizedType, "no TXT record found at _validation-persist.example.com for issuer domain names authority.example, ca.example.net"),
+		},
+		{
+			name:       "fail/missing-account-uri",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; policy=wildcard"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `TXT record "authority.example; policy=wildcard" is missing the accounturi parameter`),
+		},
+		{
+			name:       "fail/missing-parameters",
+			value:      "example.com",
+			txtRecords: []string{"authority.example;"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `TXT record "authority.example;" is missing the accounturi parameter`),
+		},
+		{
+			name:       "fail/duplicate-parameter",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + "; persistUntil=1; persistuntil=2"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `TXT record "authority.example; accounturi=%s; persistUntil=1; persistuntil=2" has a duplicate parameter "persistuntil"`, accountURI),
+		},
+		{
+			name:       "fail/parameter-without-value",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + "; policy"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `TXT record "authority.example; accounturi=%s; policy" has an invalid parameter " policy"`, accountURI),
+		},
+		{
+			name:       "fail/empty-parameter",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + ";"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `TXT record "authority.example; accounturi=%s;" has an invalid parameter ""`, accountURI),
+		},
+		{
+			name:       "fail/invalid-tag",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + "; -policy=wildcard"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `TXT record "authority.example; accounturi=%s; -policy=wildcard" has an invalid parameter " -policy=wildcard"`, accountURI),
+		},
+		{
+			name:       "fail/invalid-value",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + "; policy=wild card"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `TXT record "authority.example; accounturi=%s; policy=wild card" has an invalid parameter " policy=wild card"`, accountURI),
+		},
+		{
+			name:       "fail/account-uri-prefix",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=https://ca.example/acct/123"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `accounturi "https://ca.example/acct/123" does not start with "https://ca.example/account-hash/"`),
+		},
+		{
+			name:       "fail/account-uri-algorithm",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + prefix + "sha-512/5SQm7n6tPh2-PlLbCKGnViTXX5z19SCN4cPGQHSk-kw"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `accounturi "https://ca.example/account-hash/sha-512/5SQm7n6tPh2-PlLbCKGnViTXX5z19SCN4cPGQHSk-kw" does not use the sha-256 hash algorithm`),
+		},
+		{
+			name:       "fail/account-uri-hash",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + prefix + "sha-256/5SQm7n6tPh2-PlLbCKGnViTXX5z19SCN4cPGQHSk"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `accounturi "https://ca.example/account-hash/sha-256/5SQm7n6tPh2-PlLbCKGnViTXX5z19SCN4cPGQHSk" does not contain a valid sha-256 hash value`),
+		},
+		{
+			name:       "fail/account-uri-mismatch",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + otherAccountURI},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorUnauthorizedType, "accounturi does not match; expected %s, but got %s", accountURI, otherAccountURI),
+		},
+		{
+			name:       "fail/account-uri-other-domain",
+			value:      "www.example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorUnauthorizedType, "accounturi does not match; expected %s, but got %s", wwwAccountURI, accountURI),
+		},
+		{
+			name:       "fail/persist-until-invalid",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + "; persistUntil=+1767225600"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorMalformedType, `TXT record "authority.example; accounturi=%s; persistUntil=+1767225600" has an invalid persistUntil value "+1767225600"`, accountURI),
+		},
+		{
+			name:       "fail/persist-until-expired",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + "; persistUntil=1721952000"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorUnauthorizedType, "TXT record expired at 2024-07-26T00:00:00Z"),
+		},
+		{
+			name:       "fail/wildcard-without-policy",
+			value:      "example.com",
+			wildcard:   true,
+			txtRecords: []string{"authority.example; accounturi=" + accountURI + "; policy=other"},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorUnauthorizedType, "TXT record does not have the policy=wildcard parameter required for *.example.com"),
+		},
+		{
+			name:  "fail/first-error",
+			value: "example.com",
+			txtRecords: []string{
+				"authority.example; accounturi=" + otherAccountURI,
+				"ca.example.net; policy=wildcard",
+			},
+			wantStatus: StatusPending,
+			wantChErr:  NewError(ErrorUnauthorizedType, "accounturi does not match; expected %s, but got %s", accountURI, otherAccountURI),
+		},
+		{
+			name:        "fail/update-authorization-error",
+			value:       "example.com",
+			txtRecords:  []string{fmt.Sprintf("authority.example; accounturi=%s; persistUntil=%d", accountURI, persistUntil.Unix())},
+			updAzErr:    errors.New("force"),
+			wantStatus:  StatusPending,
+			wantExpires: persistUntil,
+			err:         NewErrorISE("error updating authorization: force"),
+		},
+		{
+			name:       "fail/update-challenge-error",
+			value:      "example.com",
+			txtRecords: []string{"authority.example; accounturi=" + accountURI},
+			updChErr:   errors.New("force"),
+			wantStatus: StatusValid,
+			err:        NewErrorISE("error updating challenge: force"),
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ch := &Challenge{
+				ID:                "chID",
+				AccountID:         "123",
+				AuthorizationID:   "azID",
+				Type:              DNSPERSIST01,
+				Value:             tt.value,
+				Status:            StatusPending,
+				IssuerDomainNames: issuerDomainNames,
+			}
+			account := validAccount
+			if tt.account != nil {
+				account = tt.account
+			}
+
+			var (
+				updatedCh *Challenge
+				updatedAz *Authorization
+			)
+			db := &MockDB{
+				MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
+					assert.Equal(t, "azID", id)
+					if tt.authzErr != nil {
+						return nil, tt.authzErr
+					}
+					return &Authorization{ID: id, Wildcard: tt.wildcard, ExpiresAt: expiresAt, Status: StatusPending}, nil
+				},
+				MockGetAccount: func(ctx context.Context, id string) (*Account, error) {
+					assert.Equal(t, "123", id)
+					if tt.accountErr != nil {
+						return nil, tt.accountErr
+					}
+					return account, nil
+				},
+				MockUpdateAuthorization: func(ctx context.Context, az *Authorization) error {
+					updatedAz = az
+					return tt.updAzErr
+				},
+				MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
+					updatedCh = updch
+					return tt.updChErr
+				},
+			}
+			vc := &mockClient{
+				lookupTxt: func(name string) ([]string, error) {
+					assert.Equal(t, strings.Replace(validationDomain, "example.com", strings.ToLower(tt.value), 1), name)
+					return tt.txtRecords, tt.lookupErr
+				},
+			}
+			ctx := NewClientContext(context.Background(), vc)
+			ctx = NewProvisionerContext(ctx, &MockProvisioner{
+				MgetAccountHashPrefix: func() string { return prefix },
+			})
+
+			err := dnsPersist01Validate(ctx, ch, db, jwk)
+			if tt.err != nil {
+				var k *Error
+				if assert.ErrorAs(t, err, &k) {
+					assert.Equal(t, tt.err.Type, k.Type)
+					assert.Equal(t, tt.err.Status, k.Status)
+					assert.Equal(t, tt.err.Err.Error(), k.Err.Error())
+				}
+			} else {
+				assert.NoError(t, err)
+			}
+
+			assert.Equal(t, tt.wantStatus, ch.Status)
+			if tt.err == nil {
+				require.NotNil(t, updatedCh)
+			}
+			if tt.wantChErr != nil {
+				if assert.NotNil(t, ch.Error) {
+					assert.Equal(t, tt.wantChErr.Type, ch.Error.Type)
+					assert.Equal(t, tt.wantChErr.Status, ch.Error.Status)
+					assert.Equal(t, tt.wantChErr.Err.Error(), ch.Error.Err.Error())
+				}
+			} else {
+				assert.Nil(t, ch.Error)
+			}
+			if tt.wantStatus == StatusValid {
+				assert.NotEmpty(t, ch.ValidatedAt)
+			}
+
+			if tt.wantExpires.IsZero() {
+				assert.Nil(t, updatedAz)
+			} else if assert.NotNil(t, updatedAz) {
+				assert.True(t, tt.wantExpires.Equal(updatedAz.ExpiresAt))
+			}
+		})
+	}
+}

+ 22 - 0
acme/common.go

@@ -75,6 +75,8 @@ type Provisioner interface {
 	IsChallengeEnabled(ctx context.Context, challenge provisioner.ACMEChallenge) bool
 	IsChallengeEnabled(ctx context.Context, challenge provisioner.ACMEChallenge) bool
 	IsAttestationFormatEnabled(ctx context.Context, format provisioner.ACMEAttestationFormat) bool
 	IsAttestationFormatEnabled(ctx context.Context, format provisioner.ACMEAttestationFormat) bool
 	GetAttestationRoots() (*x509.CertPool, bool)
 	GetAttestationRoots() (*x509.CertPool, bool)
+	GetIssuerDomainNames() []string
+	GetAccountHashPrefix() string
 	GetID() string
 	GetID() string
 	GetName() string
 	GetName() string
 	DefaultTLSCertDuration() time.Duration
 	DefaultTLSCertDuration() time.Duration
@@ -119,6 +121,8 @@ type MockProvisioner struct {
 	MisChallengeEnabled       func(ctx context.Context, challenge provisioner.ACMEChallenge) bool
 	MisChallengeEnabled       func(ctx context.Context, challenge provisioner.ACMEChallenge) bool
 	MisAttFormatEnabled       func(ctx context.Context, format provisioner.ACMEAttestationFormat) bool
 	MisAttFormatEnabled       func(ctx context.Context, format provisioner.ACMEAttestationFormat) bool
 	MgetAttestationRoots      func() (*x509.CertPool, bool)
 	MgetAttestationRoots      func() (*x509.CertPool, bool)
+	MgetIssuerDomainNames     func() []string
+	MgetAccountHashPrefix     func() string
 	MdefaultTLSCertDuration   func() time.Duration
 	MdefaultTLSCertDuration   func() time.Duration
 	MgetOptions               func() *provisioner.Options
 	MgetOptions               func() *provisioner.Options
 }
 }
@@ -178,6 +182,24 @@ func (m *MockProvisioner) GetAttestationRoots() (*x509.CertPool, bool) {
 	return m.Mret1.(*x509.CertPool), m.Mret1 != nil
 	return m.Mret1.(*x509.CertPool), m.Mret1 != nil
 }
 }
 
 
+// GetIssuerDomainNames mock
+func (m *MockProvisioner) GetIssuerDomainNames() []string {
+	if m.MgetIssuerDomainNames != nil {
+		return m.MgetIssuerDomainNames()
+	}
+	names, _ := m.Mret1.([]string)
+	return names
+}
+
+// GetAccountHashPrefix mock
+func (m *MockProvisioner) GetAccountHashPrefix() string {
+	if m.MgetAccountHashPrefix != nil {
+		return m.MgetAccountHashPrefix()
+	}
+	prefix, _ := m.Mret1.(string)
+	return prefix
+}
+
 // DefaultTLSCertDuration mock
 // DefaultTLSCertDuration mock
 func (m *MockProvisioner) DefaultTLSCertDuration() time.Duration {
 func (m *MockProvisioner) DefaultTLSCertDuration() time.Duration {
 	if m.MdefaultTLSCertDuration != nil {
 	if m.MdefaultTLSCertDuration != nil {

+ 25 - 0
acme/order.go

@@ -161,6 +161,26 @@ func (o *Order) getAuthorizationFingerprint(ctx context.Context, db DB) (string,
 	return "", nil
 	return "", nil
 }
 }
 
 
+// checkPersistentAuthorizations returns an error if an authorization validated
+// with a dns-persist-01 challenge has expired. These authorizations can expire
+// before the order does, because their expiration is limited by the
+// persistUntil parameter of the validation record.
+func (o *Order) checkPersistentAuthorizations(ctx context.Context, db DB) error {
+	now := clock.Now()
+	for _, azID := range o.AuthorizationIDs {
+		az, err := db.GetAuthorization(ctx, azID)
+		if err != nil {
+			return WrapErrorISE(err, "error getting authorization %q", azID)
+		}
+		for _, ch := range az.Challenges {
+			if ch.Type == DNSPERSIST01 && ch.Status == StatusValid && now.After(az.ExpiresAt) {
+				return NewError(ErrorUnauthorizedType, "order %s authorization %s has expired", o.ID, az.ID)
+			}
+		}
+	}
+	return nil
+}
+
 // Finalize signs a certificate if the necessary conditions for Order completion
 // Finalize signs a certificate if the necessary conditions for Order completion
 // have been met.
 // have been met.
 //
 //
@@ -186,6 +206,11 @@ 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)
 	}
 	}
 
 
+	// Do not issue certificates using expired dns-persist-01 validations.
+	if err := o.checkPersistentAuthorizations(ctx, db); err != nil {
+		return err
+	}
+
 	// Get key fingerprint if any. And then compare it with the CSR fingerprint.
 	// 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
 	// In device-attest-01 challenges we should check that the keys in the CSR

+ 61 - 0
acme/order_test.go

@@ -404,6 +404,67 @@ func TestOrder_Finalize(t *testing.T) {
 				err: NewErrorISE("unrecognized order status: %s", o.Status),
 				err: NewErrorISE("unrecognized order status: %s", o.Status),
 			}
 			}
 		},
 		},
+		"fail/get-authorization-error": func(t *testing.T) test {
+			now := clock.Now()
+			o := &Order{
+				ID:               "oID",
+				AccountID:        "accID",
+				Status:           StatusReady,
+				ExpiresAt:        now.Add(5 * time.Minute),
+				AuthorizationIDs: []string{"a"},
+			}
+			return test{
+				o: o,
+				db: &MockDB{
+					MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: NewErrorISE(`error getting authorization "a": force`),
+			}
+		},
+		"fail/expired-dns-persist-01-authorization": func(t *testing.T) test {
+			now := clock.Now()
+			o := &Order{
+				ID:               "oID",
+				AccountID:        "accID",
+				Status:           StatusReady,
+				ExpiresAt:        now.Add(5 * time.Minute),
+				AuthorizationIDs: []string{"a", "b"},
+			}
+			return test{
+				o: o,
+				db: &MockDB{
+					MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
+						switch id {
+						case "a":
+							return &Authorization{
+								ID:        id,
+								Status:    StatusValid,
+								ExpiresAt: o.ExpiresAt,
+								Challenges: []*Challenge{
+									{Type: DNS01, Status: StatusValid},
+								},
+							}, nil
+						case "b":
+							return &Authorization{
+								ID:        id,
+								Status:    StatusValid,
+								ExpiresAt: now.Add(-time.Minute),
+								Challenges: []*Challenge{
+									{Type: DNS01, Status: StatusPending},
+									{Type: DNSPERSIST01, Status: StatusValid},
+								},
+							}, nil
+						default:
+							assert.FatalError(t, errors.Errorf("unexpected authorization %s", id))
+							return nil, errors.New("force")
+						}
+					},
+				},
+				err: NewError(ErrorUnauthorizedType, "order oID authorization b has expired"),
+			}
+		},
 		"fail/non-matching-permanent-identifier-common-name": func(t *testing.T) test {
 		"fail/non-matching-permanent-identifier-common-name": func(t *testing.T) test {
 			now := clock.Now()
 			now := clock.Now()
 			o := &Order{
 			o := &Order{