certificates/acme/api/order.go

408 lines
12 KiB
Go
Raw Normal View History

2019-05-27 00:41:10 +00:00
package api
import (
2021-03-05 07:10:46 +00:00
"context"
2019-05-27 00:41:10 +00:00
"crypto/x509"
"encoding/base64"
"encoding/json"
2021-06-03 20:02:13 +00:00
"net"
2019-05-27 00:41:10 +00:00
"net/http"
2021-03-05 07:10:46 +00:00
"strings"
2019-05-27 00:41:10 +00:00
"time"
"github.com/go-chi/chi"
2021-03-05 07:10:46 +00:00
"go.step.sm/crypto/randutil"
2022-08-16 06:03:18 +00:00
"go.step.sm/crypto/x509util"
"github.com/smallstep/certificates/acme"
"github.com/smallstep/certificates/api/render"
2022-04-11 13:25:55 +00:00
"github.com/smallstep/certificates/authority/policy"
"github.com/smallstep/certificates/authority/provisioner"
2019-05-27 00:41:10 +00:00
)
// NewOrderRequest represents the body for a NewOrder request.
type NewOrderRequest struct {
Identifiers []acme.Identifier `json:"identifiers"`
NotBefore time.Time `json:"notBefore,omitempty"`
NotAfter time.Time `json:"notAfter,omitempty"`
}
// Validate validates a new-order request body.
func (n *NewOrderRequest) Validate() error {
if len(n.Identifiers) == 0 {
2021-03-05 07:10:46 +00:00
return acme.NewError(acme.ErrorMalformedType, "identifiers list cannot be empty")
2019-05-27 00:41:10 +00:00
}
for _, id := range n.Identifiers {
2022-08-16 06:03:18 +00:00
switch id.Type {
case acme.IP:
if net.ParseIP(id.Value) == nil {
return acme.NewError(acme.ErrorMalformedType, "invalid IP address: %s", id.Value)
}
case acme.DNS:
value, _ := trimIfWildcard(id.Value)
if _, err := x509util.SanitizeName(value); err != nil {
return acme.NewError(acme.ErrorMalformedType, "invalid DNS name: %s", id.Value)
}
case acme.PermanentIdentifier:
if id.Value == "" {
return acme.NewError(acme.ErrorMalformedType, "permanent identifier cannot be empty")
}
2022-08-16 06:03:18 +00:00
default:
2021-03-05 07:10:46 +00:00
return acme.NewError(acme.ErrorMalformedType, "identifier type unsupported: %s", id.Type)
2019-05-27 00:41:10 +00:00
}
2022-08-16 06:03:18 +00:00
// TODO(hs): add some validations for DNS domains?
// TODO(hs): combine the errors from this with allow/deny policy, like example error in https://datatracker.ietf.org/doc/html/rfc8555#section-6.7.1
2019-05-27 00:41:10 +00:00
}
return nil
}
// FinalizeRequest captures the body for a Finalize order request.
type FinalizeRequest struct {
CSR string `json:"csr"`
csr *x509.CertificateRequest
}
// Validate validates a finalize request body.
func (f *FinalizeRequest) Validate() error {
var err error
// RFC 8555 isn't 100% conclusive about using raw base64-url encoding for the
// CSR specifically, instead of "normal" base64-url encoding (incl. padding).
// By trimming the padding from CSRs submitted by ACME clients that use
// base64-url encoding instead of raw base64-url encoding, these are also
// supported. This was reported in https://github.com/smallstep/certificates/issues/939
// to be the case for a Synology DSM NAS system.
csrBytes, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(f.CSR, "="))
2019-05-27 00:41:10 +00:00
if err != nil {
2021-03-05 07:10:46 +00:00
return acme.WrapError(acme.ErrorMalformedType, err, "error base64url decoding csr")
2019-05-27 00:41:10 +00:00
}
f.csr, err = x509.ParseCertificateRequest(csrBytes)
if err != nil {
2021-03-05 07:10:46 +00:00
return acme.WrapError(acme.ErrorMalformedType, err, "unable to parse csr")
2019-05-27 00:41:10 +00:00
}
if err = f.csr.CheckSignature(); err != nil {
2021-03-05 07:10:46 +00:00
return acme.WrapError(acme.ErrorMalformedType, err, "csr failed signature check")
2019-05-27 00:41:10 +00:00
}
return nil
}
2021-03-05 07:10:46 +00:00
var defaultOrderExpiry = time.Hour * 24
2021-03-25 07:23:57 +00:00
var defaultOrderBackdate = time.Minute
2021-03-05 07:10:46 +00:00
2019-05-27 00:41:10 +00:00
// NewOrder ACME api for creating a new order.
2022-04-27 22:42:26 +00:00
func NewOrder(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ca := mustAuthority(ctx)
2022-04-29 02:15:18 +00:00
db := acme.MustDatabaseFromContext(ctx)
linker := acme.MustLinkerFromContext(ctx)
2021-03-05 07:10:46 +00:00
acc, err := accountFromContext(ctx)
if err != nil {
render.Error(w, err)
2021-03-05 07:10:46 +00:00
return
}
2022-05-03 00:35:35 +00:00
prov, err := provisionerFromContext(ctx)
if err != nil {
render.Error(w, err)
return
}
payload, err := payloadFromContext(ctx)
2019-05-27 00:41:10 +00:00
if err != nil {
render.Error(w, err)
2019-05-27 00:41:10 +00:00
return
}
2019-05-27 00:41:10 +00:00
var nor NewOrderRequest
if err := json.Unmarshal(payload.value, &nor); err != nil {
render.Error(w, acme.WrapError(acme.ErrorMalformedType, err,
2021-03-05 07:10:46 +00:00
"failed to unmarshal new-order request payload"))
2019-05-27 00:41:10 +00:00
return
}
2021-06-03 20:02:13 +00:00
2019-05-27 00:41:10 +00:00
if err := nor.Validate(); err != nil {
render.Error(w, err)
2019-05-27 00:41:10 +00:00
return
}
2022-04-21 11:21:06 +00:00
// TODO(hs): gather all errors, so that we can build one response with ACME subproblems
// include the nor.Validate() error here too, like in the example in the ACME RFC?
2022-04-21 11:21:06 +00:00
acmeProv, err := acmeProvisionerFromContext(ctx)
2022-04-11 13:25:55 +00:00
if err != nil {
2022-04-21 11:21:06 +00:00
render.Error(w, err)
2022-04-11 13:25:55 +00:00
return
}
2022-04-21 11:21:06 +00:00
var eak *acme.ExternalAccountKey
if acmeProv.RequireEAB {
if eak, err = db.GetExternalAccountKeyByAccountID(ctx, prov.GetID(), acc.ID); err != nil {
2022-04-21 11:21:06 +00:00
render.Error(w, acme.WrapErrorISE(err, "error retrieving external account binding key"))
return
}
}
2022-04-11 13:25:55 +00:00
acmePolicy, err := newACMEPolicyEngine(eak)
if err != nil {
render.Error(w, acme.WrapErrorISE(err, "error creating ACME policy engine"))
return
}
2022-04-07 12:11:53 +00:00
for _, identifier := range nor.Identifiers {
2022-04-15 08:58:29 +00:00
// evaluate the ACME account level policy
2022-04-11 13:25:55 +00:00
if err = isIdentifierAllowed(acmePolicy, identifier); err != nil {
render.Error(w, acme.WrapError(acme.ErrorRejectedIdentifierType, err, "not authorized"))
return
}
// evaluate the provisioner level policy
orderIdentifier := provisioner.ACMEIdentifier{Type: provisioner.ACMEIdentifierType(identifier.Type), Value: identifier.Value}
2022-04-11 13:25:55 +00:00
if err = prov.AuthorizeOrderIdentifier(ctx, orderIdentifier); err != nil {
render.Error(w, acme.WrapError(acme.ErrorRejectedIdentifierType, err, "not authorized"))
return
}
// evaluate the authority level policy
if err = ca.AreSANsAllowed(ctx, []string{identifier.Value}); err != nil {
render.Error(w, acme.WrapError(acme.ErrorRejectedIdentifierType, err, "not authorized"))
return
}
}
now := clock.Now()
2021-03-05 07:10:46 +00:00
// New order.
o := &acme.Order{
2021-03-25 07:23:57 +00:00
AccountID: acc.ID,
ProvisionerID: prov.GetID(),
Status: acme.StatusPending,
Identifiers: nor.Identifiers,
ExpiresAt: now.Add(defaultOrderExpiry),
AuthorizationIDs: make([]string, len(nor.Identifiers)),
NotBefore: nor.NotBefore,
NotAfter: nor.NotAfter,
}
2021-03-05 07:10:46 +00:00
for i, identifier := range o.Identifiers {
az := &acme.Authorization{
AccountID: acc.ID,
Identifier: identifier,
2021-03-25 07:23:57 +00:00
ExpiresAt: o.ExpiresAt,
Status: acme.StatusPending,
2021-03-05 07:10:46 +00:00
}
2022-04-27 22:42:26 +00:00
if err := newAuthorization(ctx, az); err != nil {
render.Error(w, err)
2021-03-05 07:10:46 +00:00
return
}
o.AuthorizationIDs[i] = az.ID
}
if o.NotBefore.IsZero() {
o.NotBefore = now
}
if o.NotAfter.IsZero() {
o.NotAfter = o.NotBefore.Add(prov.DefaultTLSCertDuration())
}
// If request NotBefore was empty then backdate the order.NotBefore (now)
// to avoid timing issues.
2021-03-25 07:23:57 +00:00
if nor.NotBefore.IsZero() {
o.NotBefore = o.NotBefore.Add(-defaultOrderBackdate)
2021-03-25 07:23:57 +00:00
}
2021-03-05 07:10:46 +00:00
2022-04-27 22:42:26 +00:00
if err := db.CreateOrder(ctx, o); err != nil {
render.Error(w, acme.WrapErrorISE(err, "error creating order"))
2019-05-27 00:41:10 +00:00
return
}
2022-04-29 02:15:18 +00:00
linker.LinkOrder(ctx, o)
2021-03-05 07:10:46 +00:00
2022-04-29 02:15:18 +00:00
w.Header().Set("Location", linker.GetLink(ctx, acme.OrderLinkType, o.ID))
render.JSONStatus(w, o, http.StatusCreated)
2019-05-27 00:41:10 +00:00
}
2022-04-11 13:25:55 +00:00
func isIdentifierAllowed(acmePolicy policy.X509Policy, identifier acme.Identifier) error {
if acmePolicy == nil {
return nil
}
2022-04-26 11:12:16 +00:00
return acmePolicy.AreSANsAllowed([]string{identifier.Value})
2022-04-11 13:25:55 +00:00
}
func newACMEPolicyEngine(eak *acme.ExternalAccountKey) (policy.X509Policy, error) {
if eak == nil {
return nil, nil
}
return policy.NewX509PolicyEngine(eak.Policy)
}
2022-08-16 06:03:18 +00:00
func trimIfWildcard(value string) (string, bool) {
if strings.HasPrefix(value, "*.") {
return strings.TrimPrefix(value, "*."), true
}
return value, false
}
2022-04-27 22:42:26 +00:00
func newAuthorization(ctx context.Context, az *acme.Authorization) error {
2022-08-16 06:03:18 +00:00
value, isWildcard := trimIfWildcard(az.Identifier.Value)
az.Wildcard = isWildcard
az.Identifier = acme.Identifier{
Value: value,
Type: az.Identifier.Type,
2021-03-05 07:10:46 +00:00
}
chTypes := challengeTypes(az)
2021-03-05 07:10:46 +00:00
var err error
2021-03-05 07:10:46 +00:00
az.Token, err = randutil.Alphanumeric(32)
if err != nil {
return acme.WrapErrorISE(err, "error generating random alphanumeric ID")
}
2022-04-27 22:42:26 +00:00
2022-04-29 02:15:18 +00:00
db := acme.MustDatabaseFromContext(ctx)
prov := acme.MustProvisionerFromContext(ctx)
az.Challenges = make([]*acme.Challenge, 0, len(chTypes))
for _, typ := range chTypes {
2022-09-08 20:22:35 +00:00
if !prov.IsChallengeEnabled(ctx, provisioner.ACMEChallenge(typ)) {
continue
}
2021-03-05 07:10:46 +00:00
ch := &acme.Challenge{
AccountID: az.AccountID,
Value: az.Identifier.Value,
Type: typ,
Token: az.Token,
Status: acme.StatusPending,
2021-03-05 07:10:46 +00:00
}
2022-04-27 22:42:26 +00:00
if err := db.CreateChallenge(ctx, ch); err != nil {
2021-03-25 07:23:57 +00:00
return acme.WrapErrorISE(err, "error creating challenge")
2021-03-05 07:10:46 +00:00
}
az.Challenges = append(az.Challenges, ch)
2021-03-05 07:10:46 +00:00
}
2022-04-27 22:42:26 +00:00
if err = db.CreateAuthorization(ctx, az); err != nil {
2021-03-05 07:10:46 +00:00
return acme.WrapErrorISE(err, "error creating authorization")
}
return nil
}
2019-05-27 00:41:10 +00:00
// GetOrder ACME api for retrieving an order.
2022-04-27 22:42:26 +00:00
func GetOrder(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
2022-04-29 02:15:18 +00:00
db := acme.MustDatabaseFromContext(ctx)
linker := acme.MustLinkerFromContext(ctx)
2021-03-05 07:10:46 +00:00
acc, err := accountFromContext(ctx)
2019-05-27 00:41:10 +00:00
if err != nil {
render.Error(w, err)
2019-05-27 00:41:10 +00:00
return
}
2022-05-03 00:35:35 +00:00
prov, err := provisionerFromContext(ctx)
if err != nil {
render.Error(w, err)
return
}
2022-04-27 22:42:26 +00:00
o, err := db.GetOrder(ctx, chi.URLParam(r, "ordID"))
2021-03-05 07:10:46 +00:00
if err != nil {
render.Error(w, acme.WrapErrorISE(err, "error retrieving order"))
2021-03-05 07:10:46 +00:00
return
}
if acc.ID != o.AccountID {
render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
2021-03-05 07:10:46 +00:00
"account '%s' does not own order '%s'", acc.ID, o.ID))
return
}
if prov.GetID() != o.ProvisionerID {
render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
2021-03-05 07:10:46 +00:00
"provisioner '%s' does not own order '%s'", prov.GetID(), o.ID))
return
}
2022-04-27 22:42:26 +00:00
if err = o.UpdateStatus(ctx, db); err != nil {
render.Error(w, acme.WrapErrorISE(err, "error updating order status"))
2021-03-05 07:10:46 +00:00
return
}
2019-05-27 00:41:10 +00:00
2022-04-29 02:15:18 +00:00
linker.LinkOrder(ctx, o)
2021-03-05 07:10:46 +00:00
2022-04-29 02:15:18 +00:00
w.Header().Set("Location", linker.GetLink(ctx, acme.OrderLinkType, o.ID))
render.JSON(w, o)
2019-05-27 00:41:10 +00:00
}
// FinalizeOrder attempts to finalize an order and create a certificate.
2022-04-27 22:42:26 +00:00
func FinalizeOrder(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
2022-04-29 02:15:18 +00:00
db := acme.MustDatabaseFromContext(ctx)
linker := acme.MustLinkerFromContext(ctx)
2021-03-05 07:10:46 +00:00
acc, err := accountFromContext(ctx)
if err != nil {
render.Error(w, err)
2021-03-05 07:10:46 +00:00
return
}
2022-05-03 00:35:35 +00:00
prov, err := provisionerFromContext(ctx)
if err != nil {
render.Error(w, err)
return
}
payload, err := payloadFromContext(ctx)
2019-05-27 00:41:10 +00:00
if err != nil {
render.Error(w, err)
2019-05-27 00:41:10 +00:00
return
}
var fr FinalizeRequest
if err := json.Unmarshal(payload.value, &fr); err != nil {
render.Error(w, acme.WrapError(acme.ErrorMalformedType, err,
2021-03-05 07:10:46 +00:00
"failed to unmarshal finalize-order request payload"))
2019-05-27 00:41:10 +00:00
return
}
if err := fr.Validate(); err != nil {
render.Error(w, err)
2019-05-27 00:41:10 +00:00
return
}
2022-04-27 22:42:26 +00:00
o, err := db.GetOrder(ctx, chi.URLParam(r, "ordID"))
2019-05-27 00:41:10 +00:00
if err != nil {
render.Error(w, acme.WrapErrorISE(err, "error retrieving order"))
2019-05-27 00:41:10 +00:00
return
}
2021-03-05 07:10:46 +00:00
if acc.ID != o.AccountID {
render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
2021-03-05 07:10:46 +00:00
"account '%s' does not own order '%s'", acc.ID, o.ID))
return
}
if prov.GetID() != o.ProvisionerID {
render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
2021-03-05 07:10:46 +00:00
"provisioner '%s' does not own order '%s'", prov.GetID(), o.ID))
return
}
2022-04-27 22:42:26 +00:00
ca := mustAuthority(ctx)
if err = o.Finalize(ctx, db, fr.csr, ca, prov); err != nil {
render.Error(w, acme.WrapErrorISE(err, "error finalizing order"))
2021-03-05 07:10:46 +00:00
return
}
2022-04-29 02:15:18 +00:00
linker.LinkOrder(ctx, o)
2019-05-27 00:41:10 +00:00
2022-04-29 02:15:18 +00:00
w.Header().Set("Location", linker.GetLink(ctx, acme.OrderLinkType, o.ID))
render.JSON(w, o)
2019-05-27 00:41:10 +00:00
}
// challengeTypes determines the types of challenges that should be used
// for the ACME authorization request.
func challengeTypes(az *acme.Authorization) []acme.ChallengeType {
var chTypes []acme.ChallengeType
switch az.Identifier.Type {
case acme.IP:
chTypes = []acme.ChallengeType{acme.HTTP01, acme.TLSALPN01}
case acme.DNS:
chTypes = []acme.ChallengeType{acme.DNS01}
// HTTP and TLS challenges can only be used for identifiers without wildcards.
if !az.Wildcard {
chTypes = append(chTypes, []acme.ChallengeType{acme.HTTP01, acme.TLSALPN01}...)
}
case acme.PermanentIdentifier:
chTypes = []acme.ChallengeType{acme.DEVICEATTEST01}
default:
chTypes = []acme.ChallengeType{}
}
return chTypes
}