certificates/acme/challenge.go

271 lines
8.5 KiB
Go
Raw Normal View History

2021-02-28 18:09:06 +00:00
package acme
2021-02-28 01:05:37 +00:00
import (
"context"
"crypto"
"crypto/sha256"
"crypto/subtle"
"crypto/tls"
"encoding/asn1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
"go.step.sm/crypto/jose"
)
// Challenge represents an ACME response Challenge type.
type Challenge struct {
Type string `json:"type"`
Status Status `json:"status"`
Token string `json:"token"`
ValidatedAt string `json:"validated,omitempty"`
URL string `json:"url"`
Error *Error `json:"error,omitempty"`
ID string `json:"-"`
AccountID string `json:"-"`
Value string `json:"-"`
2021-02-28 01:05:37 +00:00
}
// ToLog enables response logging.
func (ch *Challenge) ToLog() (interface{}, error) {
b, err := json.Marshal(ch)
if err != nil {
2021-03-05 07:10:46 +00:00
return nil, WrapErrorISE(err, "error marshaling challenge for logging")
2021-02-28 01:05:37 +00:00
}
return string(b), nil
}
// Validate attempts to validate the challenge. Stores changes to the Challenge
// type using the DB interface.
// satisfactorily validated, the 'status' and 'validated' attributes are
// updated.
func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey, vo *ValidateChallengeOptions) error {
2021-02-28 01:05:37 +00:00
// If already valid or invalid then return without performing validation.
if ch.Status == StatusValid || ch.Status == StatusInvalid {
return nil
}
switch ch.Type {
case "http-01":
return http01Validate(ctx, ch, db, jwk, vo)
case "dns-01":
return dns01Validate(ctx, ch, db, jwk, vo)
case "tls-alpn-01":
return tlsalpn01Validate(ctx, ch, db, jwk, vo)
default:
2021-03-05 07:10:46 +00:00
return NewErrorISE("unexpected challenge type '%s'", ch.Type)
2021-02-28 01:05:37 +00:00
}
}
func http01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, vo *ValidateChallengeOptions) error {
2021-02-28 01:05:37 +00:00
url := fmt.Sprintf("http://%s/.well-known/acme-challenge/%s", ch.Value, ch.Token)
2021-03-05 07:10:46 +00:00
resp, err := vo.HTTPGet(url)
2021-02-28 01:05:37 +00:00
if err != nil {
2021-03-05 07:10:46 +00:00
return storeError(ctx, ch, db, WrapError(ErrorConnectionType, err,
2021-03-01 07:33:18 +00:00
"error doing http GET for url %s", url))
2021-02-28 01:05:37 +00:00
}
if resp.StatusCode >= 400 {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorConnectionType,
"error doing http GET for url %s with status code %d", url, resp.StatusCode))
2021-02-28 01:05:37 +00:00
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
2021-03-05 07:10:46 +00:00
return WrapErrorISE(err, "error reading "+
2021-03-01 07:33:18 +00:00
"response body for url %s", url)
2021-02-28 01:05:37 +00:00
}
keyAuth := strings.Trim(string(body), "\r\n")
expected, err := KeyAuthorization(ch.Token, jwk)
if err != nil {
return err
}
if keyAuth != expected {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"keyAuthorization does not match; expected %s, but got %s", expected, keyAuth))
2021-02-28 01:05:37 +00:00
}
// Update and store the challenge.
ch.Status = StatusValid
ch.Error = nil
ch.ValidatedAt = clock.Now().Format(time.RFC3339)
2021-02-28 01:05:37 +00:00
2021-03-01 07:33:18 +00:00
if err = db.UpdateChallenge(ctx, ch); err != nil {
2021-03-05 07:10:46 +00:00
return WrapErrorISE(err, "error updating challenge")
2021-03-01 07:33:18 +00:00
}
return nil
2021-02-28 01:05:37 +00:00
}
func tlsalpn01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, vo *ValidateChallengeOptions) error {
2021-02-28 01:05:37 +00:00
config := &tls.Config{
NextProtos: []string{"acme-tls/1"},
2021-03-01 06:49:20 +00:00
ServerName: ch.Value,
2021-02-28 01:05:37 +00:00
InsecureSkipVerify: true, // we expect a self-signed challenge certificate
}
2021-03-01 06:49:20 +00:00
hostPort := net.JoinHostPort(ch.Value, "443")
2021-02-28 01:05:37 +00:00
2021-03-05 07:10:46 +00:00
conn, err := vo.TLSDial("tcp", hostPort, config)
2021-02-28 01:05:37 +00:00
if err != nil {
2021-03-05 07:10:46 +00:00
return storeError(ctx, ch, db, WrapError(ErrorConnectionType, err,
2021-03-01 07:33:18 +00:00
"error doing TLS dial for %s", hostPort))
2021-02-28 01:05:37 +00:00
}
defer conn.Close()
cs := conn.ConnectionState()
certs := cs.PeerCertificates
if len(certs) == 0 {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"%s challenge for %s resulted in no certificates", ch.Type, ch.Value))
2021-02-28 01:05:37 +00:00
}
if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != "acme-tls/1" {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
2021-02-28 01:05:37 +00:00
}
leafCert := certs[0]
2021-03-01 06:49:20 +00:00
if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], ch.Value) {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single DNS name, %v", ch.Value))
2021-02-28 01:05:37 +00:00
}
idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
foundIDPeAcmeIdentifierV1Obsolete := false
2021-03-01 06:49:20 +00:00
keyAuth, err := KeyAuthorization(ch.Token, jwk)
2021-02-28 01:05:37 +00:00
if err != nil {
2021-03-01 06:49:20 +00:00
return err
2021-02-28 01:05:37 +00:00
}
hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
for _, ext := range leafCert.Extensions {
if idPeAcmeIdentifier.Equal(ext.Id) {
if !ext.Critical {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"incorrect certificate for tls-alpn-01 challenge: acmeValidationV1 extension not critical"))
2021-02-28 01:05:37 +00:00
}
var extValue []byte
rest, err := asn1.Unmarshal(ext.Value, &extValue)
if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"incorrect certificate for tls-alpn-01 challenge: malformed acmeValidationV1 extension value"))
2021-02-28 01:05:37 +00:00
}
if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"incorrect certificate for tls-alpn-01 challenge: "+
"expected acmeValidationV1 extension value %s for this challenge but got %s",
hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))
2021-02-28 01:05:37 +00:00
}
ch.Status = StatusValid
ch.Error = nil
ch.ValidatedAt = clock.Now().Format(time.RFC3339)
2021-02-28 01:05:37 +00:00
2021-03-01 06:49:20 +00:00
if err = db.UpdateChallenge(ctx, ch); err != nil {
2021-03-05 07:10:46 +00:00
return WrapErrorISE(err, "tlsalpn01ValidateChallenge - error updating challenge")
2021-03-01 06:49:20 +00:00
}
return nil
2021-02-28 01:05:37 +00:00
}
if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
foundIDPeAcmeIdentifierV1Obsolete = true
}
}
if foundIDPeAcmeIdentifierV1Obsolete {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"incorrect certificate for tls-alpn-01 challenge: obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))
2021-02-28 01:05:37 +00:00
}
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"incorrect certificate for tls-alpn-01 challenge: missing acmeValidationV1 extension"))
2021-02-28 01:05:37 +00:00
}
func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, vo *ValidateChallengeOptions) error {
2021-02-28 01:05:37 +00:00
// Normalize domain for wildcard DNS names
// This is done to avoid making TXT lookups for domains like
// _acme-challenge.*.example.com
// Instead perform txt lookup for _acme-challenge.example.com
2021-03-01 06:49:20 +00:00
domain := strings.TrimPrefix(ch.Value, "*.")
2021-02-28 01:05:37 +00:00
2021-03-05 07:10:46 +00:00
txtRecords, err := vo.LookupTxt("_acme-challenge." + domain)
2021-02-28 01:05:37 +00:00
if err != nil {
2021-03-05 07:10:46 +00:00
return storeError(ctx, ch, db, WrapError(ErrorDNSType, err,
2021-03-01 07:33:18 +00:00
"error looking up TXT records for domain %s", domain))
2021-02-28 01:05:37 +00:00
}
2021-03-01 06:49:20 +00:00
expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
2021-02-28 01:05:37 +00:00
if err != nil {
2021-03-01 06:49:20 +00:00
return err
2021-02-28 01:05:37 +00:00
}
h := sha256.Sum256([]byte(expectedKeyAuth))
expected := base64.RawURLEncoding.EncodeToString(h[:])
var found bool
for _, r := range txtRecords {
if r == expected {
found = true
break
}
}
if !found {
2021-03-01 07:33:18 +00:00
return storeError(ctx, ch, db, NewError(ErrorRejectedIdentifierType,
"keyAuthorization does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))
2021-02-28 01:05:37 +00:00
}
// Update and store the challenge.
ch.Status = StatusValid
ch.Error = nil
ch.ValidatedAt = clock.Now().Format(time.RFC3339)
2021-02-28 01:05:37 +00:00
2021-03-01 07:33:18 +00:00
if err = db.UpdateChallenge(ctx, ch); err != nil {
2021-03-05 07:10:46 +00:00
return WrapErrorISE(err, "error updating challenge")
2021-03-01 07:33:18 +00:00
}
return nil
2021-02-28 01:05:37 +00:00
}
// KeyAuthorization creates the ACME key authorization value from a token
// and a jwk.
func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
thumbprint, err := jwk.Thumbprint(crypto.SHA256)
if err != nil {
2021-03-05 07:10:46 +00:00
return "", WrapErrorISE(err, "error generating JWK thumbprint")
2021-02-28 01:05:37 +00:00
}
encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
return fmt.Sprintf("%s.%s", token, encPrint), nil
}
// storeError the given error to an ACME error and saves using the DB interface.
2021-03-01 06:49:20 +00:00
func storeError(ctx context.Context, ch *Challenge, db DB, err *Error) error {
2021-03-01 07:33:18 +00:00
ch.Error = err
2021-02-28 01:05:37 +00:00
if err := db.UpdateChallenge(ctx, ch); err != nil {
2021-03-05 07:10:46 +00:00
return WrapErrorISE(err, "failure saving error to acme challenge")
2021-02-28 01:05:37 +00:00
}
return nil
}
type httpGetter func(string) (*http.Response, error)
type lookupTxt func(string) ([]string, error)
type tlsDialer func(network, addr string, config *tls.Config) (*tls.Conn, error)
// ValidateChallengeOptions are ACME challenge validator functions.
type ValidateChallengeOptions struct {
2021-03-05 07:10:46 +00:00
HTTPGet httpGetter
LookupTxt lookupTxt
TLSDial tlsDialer
2021-02-28 01:05:37 +00:00
}