certificates/acme/order.go

420 lines
14 KiB
Go
Raw Normal View History

package acme
2019-05-27 00:41:10 +00:00
import (
"bytes"
2019-05-27 00:41:10 +00:00
"context"
"crypto/x509"
"encoding/json"
"net"
"sort"
"strings"
2019-05-27 00:41:10 +00:00
"time"
"github.com/smallstep/certificates/authority/provisioner"
"go.step.sm/crypto/x509util"
2019-05-27 00:41:10 +00:00
)
2021-06-18 10:03:46 +00:00
type IdentifierType string
const (
2021-11-12 16:13:10 +00:00
// IP is the ACME ip identifier type
IP IdentifierType = "ip"
// DNS is the ACME dns identifier type
2021-06-18 10:03:46 +00:00
DNS IdentifierType = "dns"
// PermanentIdentifier is the ACME permanent-identifier identifier type
// defined in https://datatracker.ietf.org/doc/html/draft-bweeks-acme-device-attest-00
PermanentIdentifier IdentifierType = "permanent-identifier"
2021-06-18 10:03:46 +00:00
)
2021-03-01 06:49:20 +00:00
// Identifier encodes the type that an order pertains to.
type Identifier struct {
2021-06-18 10:03:46 +00:00
Type IdentifierType `json:"type"`
Value string `json:"value"`
2021-03-01 06:49:20 +00:00
}
2019-05-27 00:41:10 +00:00
// Order contains order metadata for the ACME protocol order type.
type Order struct {
ID string `json:"id"`
2021-03-29 19:04:14 +00:00
AccountID string `json:"-"`
ProvisionerID string `json:"-"`
Status Status `json:"status"`
ExpiresAt time.Time `json:"expires"`
Identifiers []Identifier `json:"identifiers"`
NotBefore time.Time `json:"notBefore"`
NotAfter time.Time `json:"notAfter"`
Error *Error `json:"error,omitempty"`
AuthorizationIDs []string `json:"-"`
AuthorizationURLs []string `json:"authorizations"`
FinalizeURL string `json:"finalize"`
CertificateID string `json:"-"`
CertificateURL string `json:"certificate,omitempty"`
2019-05-27 00:41:10 +00:00
}
// ToLog enables response logging.
func (o *Order) ToLog() (interface{}, error) {
b, err := json.Marshal(o)
if err != nil {
2021-03-05 07:10:46 +00:00
return nil, WrapErrorISE(err, "error marshaling order for logging")
2019-05-27 00:41:10 +00:00
}
return string(b), nil
}
2021-02-28 01:05:37 +00:00
// UpdateStatus updates the ACME Order Status if necessary.
// Changes to the order are saved using the database interface.
func (o *Order) UpdateStatus(ctx context.Context, db DB) error {
2021-03-12 08:16:48 +00:00
now := clock.Now()
2019-05-27 00:41:10 +00:00
switch o.Status {
case StatusInvalid:
2021-02-28 01:05:37 +00:00
return nil
2019-05-27 00:41:10 +00:00
case StatusValid:
2021-02-28 01:05:37 +00:00
return nil
2019-05-27 00:41:10 +00:00
case StatusReady:
2021-02-28 01:05:37 +00:00
// Check expiry
if now.After(o.ExpiresAt) {
2021-02-28 01:05:37 +00:00
o.Status = StatusInvalid
2021-03-01 07:33:18 +00:00
o.Error = NewError(ErrorMalformedType, "order has expired")
2019-05-27 00:41:10 +00:00
break
}
2021-02-28 01:05:37 +00:00
return nil
2019-05-27 00:41:10 +00:00
case StatusPending:
2021-02-28 01:05:37 +00:00
// Check expiry
if now.After(o.ExpiresAt) {
2021-02-28 01:05:37 +00:00
o.Status = StatusInvalid
2021-03-01 07:33:18 +00:00
o.Error = NewError(ErrorMalformedType, "order has expired")
2019-05-27 00:41:10 +00:00
break
}
2021-03-01 06:49:20 +00:00
var count = map[Status]int{
2019-05-27 00:41:10 +00:00
StatusValid: 0,
StatusInvalid: 0,
StatusPending: 0,
}
2021-03-03 23:16:25 +00:00
for _, azID := range o.AuthorizationIDs {
2021-02-28 01:05:37 +00:00
az, err := db.GetAuthorization(ctx, azID)
2019-05-27 00:41:10 +00:00
if err != nil {
2021-03-24 23:50:35 +00:00
return WrapErrorISE(err, "error getting authorization ID %s", azID)
2019-05-27 00:41:10 +00:00
}
2021-03-01 06:49:20 +00:00
if err = az.UpdateStatus(ctx, db); err != nil {
2021-03-24 23:50:35 +00:00
return WrapErrorISE(err, "error updating authorization ID %s", azID)
2019-05-27 00:41:10 +00:00
}
2021-02-28 01:05:37 +00:00
st := az.Status
2019-05-27 00:41:10 +00:00
count[st]++
}
switch {
case count[StatusInvalid] > 0:
2021-02-28 01:05:37 +00:00
o.Status = StatusInvalid
// No change in the order status, so just return the order as is -
// without writing any changes.
2019-05-27 00:41:10 +00:00
case count[StatusPending] > 0:
2021-02-28 01:05:37 +00:00
return nil
2021-03-03 23:16:25 +00:00
case count[StatusValid] == len(o.AuthorizationIDs):
2021-02-28 01:05:37 +00:00
o.Status = StatusReady
2019-05-27 00:41:10 +00:00
default:
2021-03-03 23:16:25 +00:00
return NewErrorISE("unexpected authz status")
2019-05-27 00:41:10 +00:00
}
default:
2021-03-03 23:16:25 +00:00
return NewErrorISE("unrecognized order status: %s", o.Status)
2019-05-27 00:41:10 +00:00
}
2021-03-24 23:50:35 +00:00
if err := db.UpdateOrder(ctx, o); err != nil {
return WrapErrorISE(err, "error updating order")
}
return nil
2019-05-27 00:41:10 +00:00
}
2021-03-01 06:49:20 +00:00
// Finalize signs a certificate if the necessary conditions for Order completion
2019-05-27 00:41:10 +00:00
// have been met.
//
// TODO(mariano): Here or in the challenge validation we should perform some
// external validation using the identifier value and the attestation data. From
// a validation service we can get the list of SANs to set in the final
// certificate.
2021-03-05 07:10:46 +00:00
func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateRequest, auth CertificateAuthority, p Provisioner) error {
2021-03-01 06:49:20 +00:00
if err := o.UpdateStatus(ctx, db); err != nil {
return err
2019-05-27 00:41:10 +00:00
}
2019-05-27 00:41:10 +00:00
switch o.Status {
case StatusInvalid:
2021-03-01 07:33:18 +00:00
return NewError(ErrorOrderNotReadyType, "order %s has been abandoned", o.ID)
2019-05-27 00:41:10 +00:00
case StatusValid:
2021-02-28 01:05:37 +00:00
return nil
2019-05-27 00:41:10 +00:00
case StatusPending:
2021-03-01 07:33:18 +00:00
return NewError(ErrorOrderNotReadyType, "order %s is not ready", o.ID)
2019-05-27 00:41:10 +00:00
case StatusReady:
break
default:
2021-03-03 23:16:25 +00:00
return NewErrorISE("unexpected status %s for order %s", o.Status, o.ID)
2019-05-27 00:41:10 +00:00
}
// canonicalize the CSR to allow for comparison
csr = canonicalize(csr)
// Template data
data := x509util.NewTemplateData()
data.SetCommonName(csr.Subject.CommonName)
// Custom sign options passed to authority.Sign
var extraOptions []provisioner.SignOption
// TODO: support for multiple identifiers?
var permanentIdentifier string
for i := range o.Identifiers {
if o.Identifiers[i].Type == PermanentIdentifier {
permanentIdentifier = o.Identifiers[i].Value
// the first (and only) Permanent Identifier that gets added to the certificate
// should be equal to the Subject Common Name if it's set. If not equal, the CSR
// is rejected, because the Common Name hasn't been challenged in that case. This
// could result in unauthorized access if a relying system relies on the Common
// Name in its authorization logic.
if csr.Subject.CommonName != "" && csr.Subject.CommonName != permanentIdentifier {
return NewError(ErrorBadCSRType, "CSR Subject Common Name does not match identifiers exactly: "+
"CSR Subject Common Name = %s, Order Permanent Identifier = %s", csr.Subject.CommonName, permanentIdentifier)
}
break
}
2020-06-23 18:10:45 +00:00
}
var defaultTemplate string
if permanentIdentifier != "" {
defaultTemplate = x509util.DefaultAttestedLeafTemplate
data.SetSubjectAlternativeNames(x509util.SubjectAlternativeName{
Type: x509util.PermanentIdentifierType,
Value: permanentIdentifier,
})
extraOptions = append(extraOptions, provisioner.AttestationData{
PermanentIdentifier: permanentIdentifier,
})
} else {
defaultTemplate = x509util.DefaultLeafTemplate
sans, err := o.sans(csr)
if err != nil {
return err
}
data.SetSubjectAlternativeNames(sans...)
}
2019-05-27 00:41:10 +00:00
// Get authorizations from the ACME provisioner.
2021-03-01 06:49:20 +00:00
ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
2019-05-27 00:41:10 +00:00
signOps, err := p.AuthorizeSign(ctx, "")
if err != nil {
2021-03-05 07:10:46 +00:00
return WrapErrorISE(err, "error retrieving authorization options from ACME provisioner")
2019-05-27 00:41:10 +00:00
}
2022-09-30 00:16:26 +00:00
// Unlike most of the provisioners, ACME's AuthorizeSign method doesn't
// define the templates, and the template data used in WebHooks is not
// available.
for _, signOp := range signOps {
if wc, ok := signOp.(*provisioner.WebhookController); ok {
wc.TemplateData = data
}
}
2019-05-27 00:41:10 +00:00
templateOptions, err := provisioner.CustomTemplateOptions(p.GetOptions(), data, defaultTemplate)
if err != nil {
2021-03-05 07:10:46 +00:00
return WrapErrorISE(err, "error creating template options from ACME provisioner")
}
// Build extra signing options.
signOps = append(signOps, templateOptions)
signOps = append(signOps, extraOptions...)
2021-03-01 06:49:20 +00:00
// Sign a new certificate.
certChain, err := auth.Sign(csr, provisioner.SignOptions{
2021-03-03 23:16:25 +00:00
NotBefore: provisioner.NewTimeDuration(o.NotBefore),
NotAfter: provisioner.NewTimeDuration(o.NotAfter),
2019-05-27 00:41:10 +00:00
}, signOps...)
if err != nil {
2021-03-05 07:10:46 +00:00
return WrapErrorISE(err, "error signing certificate for order %s", o.ID)
2019-05-27 00:41:10 +00:00
}
2021-03-01 06:49:20 +00:00
cert := &Certificate{
2019-05-27 00:41:10 +00:00
AccountID: o.AccountID,
OrderID: o.ID,
Leaf: certChain[0],
Intermediates: certChain[1:],
2021-03-01 06:49:20 +00:00
}
if err := db.CreateCertificate(ctx, cert); err != nil {
2021-03-25 03:07:21 +00:00
return WrapErrorISE(err, "error creating certificate for order %s", o.ID)
2019-05-27 00:41:10 +00:00
}
2021-03-05 07:10:46 +00:00
o.CertificateID = cert.ID
2021-02-28 01:05:37 +00:00
o.Status = StatusValid
2021-03-25 03:07:21 +00:00
if err = db.UpdateOrder(ctx, o); err != nil {
return WrapErrorISE(err, "error updating order %s", o.ID)
}
return nil
2019-05-27 00:41:10 +00:00
}
func (o *Order) sans(csr *x509.CertificateRequest) ([]x509util.SubjectAlternativeName, error) {
var sans []x509util.SubjectAlternativeName
if len(csr.EmailAddresses) > 0 || len(csr.URIs) > 0 {
return sans, NewError(ErrorBadCSRType, "Only DNS names and IP addresses are allowed")
}
// order the DNS names and IP addresses, so that they can be compared against the canonicalized CSR
2021-06-18 14:09:48 +00:00
orderNames := make([]string, numberOfIdentifierType(DNS, o.Identifiers))
orderIPs := make([]net.IP, numberOfIdentifierType(IP, o.Identifiers))
orderPIDs := make([]string, numberOfIdentifierType(PermanentIdentifier, o.Identifiers))
indexDNS, indexIP, indexPID := 0, 0, 0
2021-06-03 20:45:24 +00:00
for _, n := range o.Identifiers {
switch n.Type {
2021-06-18 14:09:48 +00:00
case DNS:
2021-06-03 20:45:24 +00:00
orderNames[indexDNS] = n.Value
indexDNS++
2021-06-18 14:09:48 +00:00
case IP:
2021-06-03 20:45:24 +00:00
orderIPs[indexIP] = net.ParseIP(n.Value) // NOTE: this assumes are all valid IPs at this time; or will result in nil entries
indexIP++
case PermanentIdentifier:
orderPIDs[indexPID] = n.Value
indexPID++
default:
return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
}
}
orderNames = uniqueSortedLowerNames(orderNames)
orderIPs = uniqueSortedIPs(orderIPs)
totalNumberOfSANs := len(csr.DNSNames) + len(csr.IPAddresses)
sans = make([]x509util.SubjectAlternativeName, totalNumberOfSANs)
2021-06-03 20:45:24 +00:00
index := 0
// Validate identifier names against CSR alternative names.
//
// Note that with certificate templates we are not going to check for the
2021-06-18 10:03:46 +00:00
// absence of other SANs as they will only be set if the template allows
// them.
2021-06-03 20:45:24 +00:00
if len(csr.DNSNames) != len(orderNames) {
return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
"CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
}
for i := range csr.DNSNames {
if csr.DNSNames[i] != orderNames[i] {
return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
"CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
}
sans[index] = x509util.SubjectAlternativeName{
Type: x509util.DNSType,
Value: csr.DNSNames[i],
}
index++
}
if len(csr.IPAddresses) != len(orderIPs) {
2021-06-04 06:42:24 +00:00
return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
"CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
}
for i := range csr.IPAddresses {
if !ipsAreEqual(csr.IPAddresses[i], orderIPs[i]) {
return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
"CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
}
2021-06-03 20:45:24 +00:00
sans[index] = x509util.SubjectAlternativeName{
Type: x509util.IPType,
Value: csr.IPAddresses[i].String(),
}
2021-06-03 20:45:24 +00:00
index++
}
2021-06-03 20:45:24 +00:00
return sans, nil
}
2021-06-03 20:45:24 +00:00
// numberOfIdentifierType returns the number of Identifiers that
// are of type typ.
2021-06-18 10:03:46 +00:00
func numberOfIdentifierType(typ IdentifierType, ids []Identifier) int {
2021-06-03 20:45:24 +00:00
c := 0
for _, id := range ids {
if id.Type == typ {
c++
}
}
2021-06-03 20:45:24 +00:00
return c
}
2021-06-03 20:45:24 +00:00
// canonicalize canonicalizes a CSR so that it can be compared against an Order
// NOTE: this effectively changes the order of SANs in the CSR, which may be OK,
// but may not be expected. It also adds a Subject Common Name to either the IP
// addresses or DNS names slice, depending on whether it can be parsed as an IP
// or not. This might result in an additional SAN in the final certificate.
func canonicalize(csr *x509.CertificateRequest) (canonicalized *x509.CertificateRequest) {
// for clarity only; we're operating on the same object by pointer
canonicalized = csr
// RFC8555: The CSR MUST indicate the exact same set of requested
// identifiers as the initial newOrder request. Identifiers of type "dns"
// MUST appear either in the commonName portion of the requested subject
// name or in an extensionRequest attribute [RFC2985] requesting a
// subjectAltName extension, or both. Subject Common Names that can be
// parsed as an IP are included as an IP address for the equality check.
// If these were excluded, a certificate could contain an IP as the
// common name without having been challenged.
if csr.Subject.CommonName != "" {
2021-12-20 12:40:17 +00:00
if ip := net.ParseIP(csr.Subject.CommonName); ip != nil {
canonicalized.IPAddresses = append(canonicalized.IPAddresses, ip)
} else {
2021-12-20 12:40:17 +00:00
canonicalized.DNSNames = append(canonicalized.DNSNames, csr.Subject.CommonName)
}
}
2021-12-20 12:40:17 +00:00
canonicalized.DNSNames = uniqueSortedLowerNames(canonicalized.DNSNames)
canonicalized.IPAddresses = uniqueSortedIPs(canonicalized.IPAddresses)
return canonicalized
}
// ipsAreEqual compares IPs to be equal. Nil values (i.e. invalid IPs) are
// not considered equal. IPv6 representations of IPv4 addresses are
// considered equal to the IPv4 address in this implementation, which is
// standard Go behavior. An example is "::ffff:192.168.42.42", which
// is equal to "192.168.42.42". This is considered a known issue within
// step and is tracked here too: https://github.com/golang/go/issues/37921.
func ipsAreEqual(x, y net.IP) bool {
if x == nil || y == nil {
return false
}
return x.Equal(y)
}
2021-02-28 01:05:37 +00:00
// uniqueSortedLowerNames returns the set of all unique names in the input after all
// of them are lowercased. The returned names will be in their lowercased form
// and sorted alphabetically.
2021-02-28 01:05:37 +00:00
func uniqueSortedLowerNames(names []string) (unique []string) {
nameMap := make(map[string]int, len(names))
for _, name := range names {
nameMap[strings.ToLower(name)] = 1
}
unique = make([]string, 0, len(nameMap))
for name := range nameMap {
unique = append(unique, name)
}
sort.Strings(unique)
return
}
// uniqueSortedIPs returns the set of all unique net.IPs in the input. They
// are sorted by their bytes (octet) representation.
func uniqueSortedIPs(ips []net.IP) (unique []net.IP) {
type entry struct {
ip net.IP
}
ipEntryMap := make(map[string]entry, len(ips))
for _, ip := range ips {
// reparsing the IP results in the IP being represented using 16 bytes
// for both IPv4 as well as IPv6, even when the ips slice contains IPs that
// are represented by 4 bytes. This ensures a fair comparison and thus ordering.
ipEntryMap[ip.String()] = entry{ip: net.ParseIP(ip.String())}
}
unique = make([]net.IP, 0, len(ipEntryMap))
for _, entry := range ipEntryMap {
unique = append(unique, entry.ip)
}
sort.Slice(unique, func(i, j int) bool {
return bytes.Compare(unique[i], unique[j]) < 0
})
return
}