certificates/acme/authority.go

332 lines
11 KiB
Go
Raw Normal View History

2019-05-27 00:41:10 +00:00
package acme
import (
"context"
2019-05-27 00:41:10 +00:00
"crypto"
2020-02-07 14:50:22 +00:00
"crypto/tls"
2019-05-27 00:41:10 +00:00
"crypto/x509"
"encoding/base64"
"net"
"net/http"
"net/url"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/authority/provisioner"
database "github.com/smallstep/certificates/db"
2019-05-27 00:41:10 +00:00
"github.com/smallstep/nosql"
"go.step.sm/crypto/jose"
2019-05-27 00:41:10 +00:00
)
// Interface is the acme authority interface.
type Interface interface {
GetDirectory(ctx context.Context) (*Directory, error)
2019-05-27 00:41:10 +00:00
NewNonce() (string, error)
UseNonce(string) error
DeactivateAccount(ctx context.Context, accID string) (*Account, error)
GetAccount(ctx context.Context, accID string) (*Account, error)
GetAccountByKey(ctx context.Context, key *jose.JSONWebKey) (*Account, error)
NewAccount(ctx context.Context, ao AccountOptions) (*Account, error)
UpdateAccount(context.Context, string, []string) (*Account, error)
GetAuthz(ctx context.Context, accID string, authzID string) (*Authz, error)
ValidateChallenge(ctx context.Context, accID string, chID string, key *jose.JSONWebKey) (*Challenge, error)
FinalizeOrder(ctx context.Context, accID string, orderID string, csr *x509.CertificateRequest) (*Order, error)
GetOrder(ctx context.Context, accID string, orderID string) (*Order, error)
GetOrdersByAccount(ctx context.Context, accID string) ([]string, error)
NewOrder(ctx context.Context, oo OrderOptions) (*Order, error)
GetCertificate(string, string) ([]byte, error)
LoadProvisionerByID(string) (provisioner.Interface, error)
GetLink(ctx context.Context, linkType Link, absoluteLink bool, inputs ...string) string
GetLinkExplicit(linkType Link, provName string, absoluteLink bool, baseURL *url.URL, inputs ...string) string
2019-05-27 00:41:10 +00:00
}
// Authority is the layer that handles all ACME interactions.
type Authority struct {
backdate provisioner.Duration
2019-05-27 00:41:10 +00:00
db nosql.DB
dir *directory
signAuth SignAuthority
}
// AuthorityOptions required to create a new ACME Authority.
type AuthorityOptions struct {
Backdate provisioner.Duration
// DB is the database used by nosql.
DB nosql.DB
// DNS the host used to generate accurate ACME links. By default the authority
// will use the Host from the request, so this value will only be used if
// request.Host is empty.
DNS string
// Prefix is a URL path prefix under which the ACME api is served. This
// prefix is required to generate accurate ACME links.
// E.g. https://ca.smallstep.com/acme/my-acme-provisioner/new-account --
// "acme" is the prefix from which the ACME api is accessed.
Prefix string
}
var (
accountTable = []byte("acme_accounts")
accountByKeyIDTable = []byte("acme_keyID_accountID_index")
authzTable = []byte("acme_authzs")
challengeTable = []byte("acme_challenges")
nonceTable = []byte("nonces")
orderTable = []byte("acme_orders")
2020-01-28 21:17:10 +00:00
ordersByAccountIDTable = []byte("acme_account_orders_index")
certTable = []byte("acme_certs")
)
2019-05-27 00:41:10 +00:00
// NewAuthority returns a new Authority that implements the ACME interface.
//
// Deprecated: NewAuthority exists for hitorical compatibility and should not
// be used. Use acme.New() instead.
func NewAuthority(db nosql.DB, dns, prefix string, signAuth SignAuthority) (*Authority, error) {
return New(signAuth, AuthorityOptions{
DB: db,
DNS: dns,
Prefix: prefix,
})
}
2021-02-25 18:23:11 +00:00
// New returns a new Authority that implements the ACME interface.
func New(signAuth SignAuthority, ops AuthorityOptions) (*Authority, error) {
if _, ok := ops.DB.(*database.SimpleDB); !ok {
// If it's not a SimpleDB then go ahead and bootstrap the DB with the
// necessary ACME tables. SimpleDB should ONLY be used for testing.
tables := [][]byte{accountTable, accountByKeyIDTable, authzTable,
challengeTable, nonceTable, orderTable, ordersByAccountIDTable,
certTable}
for _, b := range tables {
if err := ops.DB.CreateTable(b); err != nil {
return nil, errors.Wrapf(err, "error creating table %s",
string(b))
}
}
}
2019-05-27 00:41:10 +00:00
return &Authority{
backdate: ops.Backdate, db: ops.DB, dir: newDirectory(ops.DNS, ops.Prefix), signAuth: signAuth,
}, nil
2019-05-27 00:41:10 +00:00
}
// GetLink returns the requested link from the directory.
func (a *Authority) GetLink(ctx context.Context, typ Link, abs bool, inputs ...string) string {
return a.dir.getLink(ctx, typ, abs, inputs...)
}
// GetLinkExplicit returns the requested link from the directory.
func (a *Authority) GetLinkExplicit(typ Link, provName string, abs bool, baseURL *url.URL, inputs ...string) string {
return a.dir.getLinkExplicit(typ, provName, abs, baseURL, inputs...)
2019-05-27 00:41:10 +00:00
}
// GetDirectory returns the ACME directory object.
func (a *Authority) GetDirectory(ctx context.Context) (*Directory, error) {
2019-05-27 00:41:10 +00:00
return &Directory{
NewNonce: a.dir.getLink(ctx, NewNonceLink, true),
NewAccount: a.dir.getLink(ctx, NewAccountLink, true),
NewOrder: a.dir.getLink(ctx, NewOrderLink, true),
RevokeCert: a.dir.getLink(ctx, RevokeCertLink, true),
KeyChange: a.dir.getLink(ctx, KeyChangeLink, true),
}, nil
2019-05-27 00:41:10 +00:00
}
// LoadProvisionerByID calls out to the SignAuthority interface to load a
// provisioner by ID.
func (a *Authority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
return a.signAuth.LoadProvisionerByID(id)
}
// NewNonce generates, stores, and returns a new ACME nonce.
2021-02-25 18:23:11 +00:00
func (a *Authority) NewNonce(ctx context.Context) (string, error) {
return a.db.CreateNonce(ctx)
2019-05-27 00:41:10 +00:00
}
// UseNonce consumes the given nonce if it is valid, returns error otherwise.
2021-02-25 18:23:11 +00:00
func (a *Authority) UseNonce(ctx context.Context, nonce string) error {
return a.db.DeleteNonce(ctx, nonce)
2019-05-27 00:41:10 +00:00
}
// NewAccount creates, stores, and returns a new ACME account.
func (a *Authority) NewAccount(ctx context.Context, ao AccountOptions) (*Account, error) {
2021-02-25 18:23:11 +00:00
a := NewAccount(ao)
if err := a.db.CreateAccount(ctx, a); err != nil {
return ServerInternalErr(err)
2019-05-27 00:41:10 +00:00
}
2021-02-25 18:23:11 +00:00
return a, nil
2019-05-27 00:41:10 +00:00
}
// UpdateAccount updates an ACME account.
2021-02-25 18:23:11 +00:00
func (a *Authority) UpdateAccount(ctx context.Context, auo AccountUpdateOptions) (*Account, error) {
acc, err := a.db.GetAccount(ctx, auo.ID)
2019-05-27 00:41:10 +00:00
if err != nil {
2021-02-25 18:23:11 +00:00
return ServerInternalErr(err)
2019-05-27 00:41:10 +00:00
}
2021-02-25 18:23:11 +00:00
acc.Contact = auo.Contact
acc.Status = auo.Status
if err = a.db.UpdateAccount(ctx, acc); err != nil {
return ServerInternalErr(err)
2019-05-27 00:41:10 +00:00
}
2021-02-25 18:23:11 +00:00
return acc, nil
2019-05-27 00:41:10 +00:00
}
// GetAccount returns an ACME account.
func (a *Authority) GetAccount(ctx context.Context, id string) (*Account, error) {
2021-02-25 18:23:11 +00:00
return a.db.GetAccount(ctx, id)
2019-05-27 00:41:10 +00:00
}
func keyToID(jwk *jose.JSONWebKey) (string, error) {
kid, err := jwk.Thumbprint(crypto.SHA256)
if err != nil {
return "", ServerInternalErr(errors.Wrap(err, "error generating jwk thumbprint"))
}
return base64.RawURLEncoding.EncodeToString(kid), nil
}
// GetAccountByKey returns the ACME associated with the jwk id.
func (a *Authority) GetAccountByKey(ctx context.Context, jwk *jose.JSONWebKey) (*Account, error) {
2019-05-27 00:41:10 +00:00
kid, err := keyToID(jwk)
if err != nil {
return nil, err
}
2021-02-25 18:23:11 +00:00
acc, err := a.db.GetAccountByKeyID(ctx, kid)
return acc, err
2019-05-27 00:41:10 +00:00
}
// GetOrder returns an ACME order.
func (a *Authority) GetOrder(ctx context.Context, accID, orderID string) (*Order, error) {
2019-05-27 00:41:10 +00:00
o, err := getOrder(a.db, orderID)
if err != nil {
return nil, err
}
if accID != o.AccountID {
return nil, UnauthorizedErr(errors.New("account does not own order"))
}
if o, err = o.updateStatus(a.db); err != nil {
return nil, err
}
return o.toACME(ctx, a.db, a.dir)
2019-05-27 00:41:10 +00:00
}
// GetOrdersByAccount returns the list of order urls owned by the account.
func (a *Authority) GetOrdersByAccount(ctx context.Context, id string) ([]string, error) {
2020-10-21 00:18:20 +00:00
ordersByAccountMux.Lock()
defer ordersByAccountMux.Unlock()
var oiba = orderIDsByAccount{}
2020-10-21 00:18:20 +00:00
oids, err := oiba.unsafeGetOrderIDsByAccount(a.db, id)
2019-05-27 00:41:10 +00:00
if err != nil {
return nil, err
}
var ret = []string{}
for _, oid := range oids {
ret = append(ret, a.dir.getLink(ctx, OrderLink, true, oid))
2019-05-27 00:41:10 +00:00
}
return ret, nil
}
// NewOrder generates, stores, and returns a new ACME order.
func (a *Authority) NewOrder(ctx context.Context, ops OrderOptions) (*Order, error) {
prov, err := ProvisionerFromContext(ctx)
if err != nil {
return nil, err
}
ops.backdate = a.backdate.Duration
ops.defaultDuration = prov.DefaultTLSCertDuration()
2019-05-27 00:41:10 +00:00
order, err := newOrder(a.db, ops)
if err != nil {
return nil, Wrap(err, "error creating order")
}
return order.toACME(ctx, a.db, a.dir)
2019-05-27 00:41:10 +00:00
}
// FinalizeOrder attempts to finalize an order and generate a new certificate.
func (a *Authority) FinalizeOrder(ctx context.Context, accID, orderID string, csr *x509.CertificateRequest) (*Order, error) {
prov, err := ProvisionerFromContext(ctx)
if err != nil {
return nil, err
}
2019-05-27 00:41:10 +00:00
o, err := getOrder(a.db, orderID)
if err != nil {
return nil, err
}
if accID != o.AccountID {
return nil, UnauthorizedErr(errors.New("account does not own order"))
}
o, err = o.finalize(a.db, csr, a.signAuth, prov)
2019-05-27 00:41:10 +00:00
if err != nil {
return nil, Wrap(err, "error finalizing order")
}
return o.toACME(ctx, a.db, a.dir)
2019-05-27 00:41:10 +00:00
}
// GetAuthz retrieves and attempts to update the status on an ACME authz
// before returning.
func (a *Authority) GetAuthz(ctx context.Context, accID, authzID string) (*Authz, error) {
2019-09-19 20:17:23 +00:00
az, err := getAuthz(a.db, authzID)
2019-05-27 00:41:10 +00:00
if err != nil {
return nil, err
}
2019-09-19 20:17:23 +00:00
if accID != az.getAccountID() {
2019-05-27 00:41:10 +00:00
return nil, UnauthorizedErr(errors.New("account does not own authz"))
}
2019-09-19 20:17:23 +00:00
az, err = az.updateStatus(a.db)
2019-05-27 00:41:10 +00:00
if err != nil {
return nil, Wrap(err, "error updating authz status")
}
return az.toACME(ctx, a.db, a.dir)
2019-05-27 00:41:10 +00:00
}
// ValidateChallenge attempts to validate the challenge.
func (a *Authority) ValidateChallenge(ctx context.Context, accID, chID string, jwk *jose.JSONWebKey) (*Challenge, error) {
2019-05-27 00:41:10 +00:00
ch, err := getChallenge(a.db, chID)
if err != nil {
return nil, err
}
if accID != ch.getAccountID() {
return nil, UnauthorizedErr(errors.New("account does not own challenge"))
}
client := http.Client{
Timeout: time.Duration(30 * time.Second),
}
2020-02-07 14:50:22 +00:00
dialer := &net.Dialer{
Timeout: 30 * time.Second,
}
2019-05-27 00:41:10 +00:00
ch, err = ch.validate(a.db, jwk, validateOptions{
httpGet: client.Get,
lookupTxt: net.LookupTXT,
2020-02-07 14:50:22 +00:00
tlsDial: func(network, addr string, config *tls.Config) (*tls.Conn, error) {
return tls.DialWithDialer(dialer, network, addr, config)
},
2019-05-27 00:41:10 +00:00
})
if err != nil {
return nil, Wrap(err, "error attempting challenge validation")
}
return ch.toACME(ctx, a.db, a.dir)
2019-05-27 00:41:10 +00:00
}
// GetCertificate retrieves the Certificate by ID.
func (a *Authority) GetCertificate(accID, certID string) ([]byte, error) {
cert, err := getCert(a.db, certID)
if err != nil {
return nil, err
}
if accID != cert.AccountID {
return nil, UnauthorizedErr(errors.New("account does not own certificate"))
}
return cert.toACME(a.db, a.dir)
}
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)
type validateOptions struct {
httpGet httpGetter
lookupTxt lookupTxt
tlsDial tlsDialer
}