ソースを参照

add EST provisioner

Implementation of [RFC 7030] (https://datatracker.ietf.org/doc/html/rfc7030).
Support TLS client certificate authentication and basic auth.   Support webhook for authentication, notification and data.
Not covered :
* full CMC
* server-side key generation
Jean-Baptiste Pin 8 ヶ月 前
親
コミット
7804f0b93b

+ 1 - 0
.gitignore

@@ -15,6 +15,7 @@ go.work.sum
 
 # Output of the go coverage tool, specifically when used with LiteIDE
 *.out
+.gocache
 
 # Others
 *.swp

+ 16 - 6
api/api.go

@@ -257,22 +257,32 @@ func scepFromProvisioner(p *provisioner.SCEP) *models.SCEP {
 	}
 }
 
+func estFromProvisioner(p *provisioner.EST) *provisioner.EST {
+	prov := *p
+	prov.ClientCertificateRoots = []byte(redacted)
+	prov.BasicAuthUsername = redacted
+	prov.BasicAuthPassword = redacted
+	return &prov
+}
+
 // MarshalJSON implements json.Marshaler. It marshals the ProvisionersResponse
 // into a byte slice.
 //
 // Special treatment is given to the SCEP provisioner, as it contains a
 // challenge secret that MUST NOT be leaked in (public) HTTP responses. The
-// challenge value is thus redacted in HTTP responses.
+// challenge value is thus redacted in HTTP responses. EST provisioners also
+// contain a shared secret and are redacted in responses.
 func (p ProvisionersResponse) MarshalJSON() ([]byte, error) {
 	var responseProvisioners provisioner.List
 	for _, item := range p.Provisioners {
-		scepProv, ok := item.(*provisioner.SCEP)
-		if !ok {
+		switch prov := item.(type) {
+		case *provisioner.SCEP:
+			responseProvisioners = append(responseProvisioners, scepFromProvisioner(prov))
+		case *provisioner.EST:
+			responseProvisioners = append(responseProvisioners, estFromProvisioner(prov))
+		default:
 			responseProvisioners = append(responseProvisioners, item)
-			continue
 		}
-
-		responseProvisioners = append(responseProvisioners, scepFromProvisioner(scepProv))
 	}
 
 	var list = struct {

+ 79 - 3
authority/authority.go

@@ -34,6 +34,7 @@ import (
 	"github.com/smallstep/certificates/cas"
 	casapi "github.com/smallstep/certificates/cas/apiv1"
 	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/certificates/est"
 	"github.com/smallstep/certificates/internal/httptransport"
 	"github.com/smallstep/certificates/scep"
 	"github.com/smallstep/certificates/templates"
@@ -72,6 +73,11 @@ type Authority struct {
 	scepAuthority  *scep.Authority
 	scepKeyManager provisioner.SCEPKeyManager
 
+	// EST CA
+	estOptions   *est.Options
+	validateEST  bool
+	estAuthority *est.Authority
+
 	// SSH CA
 	sshHostPassword         []byte
 	sshUserPassword         []byte
@@ -135,6 +141,7 @@ func New(cfg *config.Config, opts ...Option) (*Authority, error) {
 		config:        cfg,
 		certificates:  new(sync.Map),
 		validateSCEP:  true,
+		validateEST:   true,
 		meter:         noopMeter{},
 		wrapTransport: httptransport.NoopWrapper(),
 	}
@@ -172,6 +179,7 @@ func NewEmbedded(opts ...Option) (*Authority, error) {
 		certificates:  new(sync.Map),
 		meter:         noopMeter{},
 		wrapTransport: httptransport.NoopWrapper(),
+		validateEST:   true,
 	}
 
 	// Apply options.
@@ -316,6 +324,11 @@ func (a *Authority) ReloadAdminResources(ctx context.Context) error {
 		// TODO(hs): don't remove the authority if we can't also
 		// reload it.
 		//a.scepAuthority = nil
+	case a.requiresEST() && a.GetEST() != nil:
+		a.estAuthority.UpdateProvisioners(a.getESTProvisionerNames())
+		if err := a.estAuthority.Validate(); err != nil {
+			log.Printf("failed validating EST authority: %v\n", err)
+		}
 	}
 
 	return nil
@@ -816,6 +829,51 @@ func (a *Authority) init() error {
 		}
 	}
 
+	// EST functionality is provided through an instance of est.Authority.
+	switch {
+	case a.requiresEST() && a.GetEST() == nil:
+		if a.estOptions == nil {
+			options := &est.Options{
+				Roots:         a.rootX509Certs,
+				Intermediates: a.intermediateX509Certs,
+			}
+			if len(a.intermediateX509Certs) > 0 {
+				options.SignerCert = a.intermediateX509Certs[0]
+			}
+			if a.config.IntermediateKey != "" {
+				if signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
+					SigningKey: a.config.IntermediateKey,
+					Password:   a.password,
+				}); err == nil {
+					options.Signer = signer
+				}
+			}
+			a.estOptions = options
+		}
+
+		a.estOptions.ESTProvisionerNames = a.getESTProvisionerNames()
+
+		estAuthority, err := est.New(a, *a.estOptions)
+		if err != nil {
+			return err
+		}
+
+		if a.validateEST {
+			if err := estAuthority.Validate(); err != nil {
+				a.initLogf("failed validating EST authority: %v", err)
+			}
+		}
+
+		a.estAuthority = estAuthority
+	case !a.requiresEST() && a.GetEST() != nil:
+		a.estAuthority = nil
+	case a.requiresEST() && a.GetEST() != nil:
+		a.estAuthority.UpdateProvisioners(a.getESTProvisionerNames())
+		if err := a.estAuthority.Validate(); err != nil {
+			log.Printf("failed validating EST authority: %v\n", err)
+		}
+	}
+
 	// Load X509 constraints engine.
 	//
 	// This is currently only available in CA mode.
@@ -1004,16 +1062,34 @@ func (a *Authority) GetSCEP() *scep.Authority {
 	return a.scepAuthority
 }
 
-// HasACMEProvisioner returns true if at least one ACME provisioner is configured.
-func (a *Authority) HasACMEProvisioner() bool {
+// requiresEST iterates over the configured provisioners
+// and determines if at least one of them is an EST provisioner.
+func (a *Authority) requiresEST() bool {
 	for _, p := range a.config.AuthorityConfig.Provisioners {
-		if p.GetType() == provisioner.TypeACME {
+		if p.GetType() == provisioner.TypeEST {
 			return true
 		}
 	}
 	return false
 }
 
+// getESTProvisionerNames returns the names of the EST provisioners
+// that are currently available in the CA.
+func (a *Authority) getESTProvisionerNames() (names []string) {
+	for _, p := range a.config.AuthorityConfig.Provisioners {
+		if p.GetType() == provisioner.TypeEST {
+			names = append(names, p.GetName())
+		}
+	}
+
+	return
+}
+
+// GetEST returns the configured EST Authority
+func (a *Authority) GetEST() *est.Authority {
+	return a.estAuthority
+}
+
 func (a *Authority) startCRLGenerator() error {
 	if !a.config.CRL.IsEnabled() {
 		return nil

+ 12 - 0
authority/options.go

@@ -19,6 +19,7 @@ import (
 	casapi "github.com/smallstep/certificates/cas/apiv1"
 	"github.com/smallstep/certificates/db"
 	"github.com/smallstep/certificates/internal/httptransport"
+	"github.com/smallstep/certificates/est"
 	"github.com/smallstep/certificates/scep"
 )
 
@@ -252,6 +253,17 @@ func WithFullSCEPOptions(options *scep.Options) Option {
 	}
 }
 
+// WithFullESTOptions defines the options used for EST support.
+//
+// This feature is EXPERIMENTAL and might change at any time.
+func WithFullESTOptions(options *est.Options) Option {
+	return func(a *Authority) error {
+		a.estOptions = options
+		a.validateEST = false
+		return nil
+	}
+}
+
 // WithSCEPKeyManager defines the key manager used on SCEP provisioners.
 //
 // This feature is EXPERIMENTAL and might change at any time.

+ 195 - 0
authority/provisioner/est.go

@@ -0,0 +1,195 @@
+package provisioner
+
+import (
+	"context"
+	"crypto"
+	"crypto/x509"
+	"fmt"
+	"time"
+
+	"github.com/pkg/errors"
+
+	"github.com/smallstep/certificates/internal/httptransport"
+	"github.com/smallstep/linkedca"
+)
+
+// EST is the EST provisioner type, an entity that can authorize the EST flow.
+type EST struct {
+	*base
+	ID                                 string   `json:"-"`
+	Type                               string   `json:"type"`
+	Name                               string   `json:"name"`
+	EnableTLSClientCertificate         *bool    `json:"enableTLSClientCertificate,omitempty"`
+	EnableHTTPBasicAuth                *bool    `json:"enableHTTPBasicAuth,omitempty"`
+	BasicAuthUsername                  string   `json:"basicAuthUsername,omitempty"`
+	BasicAuthPassword                  string   `json:"basicAuthPassword,omitempty"`
+	ClientCertificateRoots             []byte   `json:"clientCertificateRoots,omitempty"`
+	ForceCN                            bool     `json:"forceCN,omitempty"`
+	Capabilities                       []string `json:"capabilities,omitempty"`
+	IncludeRoot                        bool     `json:"includeRoot,omitempty"`
+	ExcludeIntermediate                bool     `json:"excludeIntermediate,omitempty"`
+	MinimumPublicKeyLength             int      `json:"minimumPublicKeyLength,omitempty"`
+	CSRAttrs                           []byte   `json:"csrAttrs,omitempty"`
+	Options                            *Options `json:"options,omitempty"`
+	Claims                             *Claims  `json:"claims,omitempty"`
+	ctl                                *Controller
+	signer                             crypto.Signer
+	signerCertificate                  *x509.Certificate
+	challengeValidationController      *challengeValidationController
+	notificationController             *notificationController
+	clientCertificateRootPool          *x509.CertPool
+}
+
+// GetID returns the provisioner unique identifier.
+func (s *EST) GetID() string {
+	if s.ID != "" {
+		return s.ID
+	}
+	return s.GetIDForToken()
+}
+
+// GetIDForToken returns an identifier that will be used to load the provisioner from a token.
+func (s *EST) GetIDForToken() string {
+	return "est/" + s.Name
+}
+
+// GetName returns the name of the provisioner.
+func (s *EST) GetName() string {
+	return s.Name
+}
+
+// GetType returns the type of provisioner.
+func (s *EST) GetType() Type {
+	return TypeEST
+}
+
+// GetEncryptedKey returns the base provisioner encrypted key if it's defined.
+func (s *EST) GetEncryptedKey() (string, string, bool) {
+	return "", "", false
+}
+
+// GetTokenID returns the identifier of the token. This provisioner does not support tokens.
+func (s *EST) GetTokenID(string) (string, error) {
+	return "", ErrTokenFlowNotSupported
+}
+
+// GetOptions returns the configured provisioner options.
+func (s *EST) GetOptions() *Options {
+	return s.Options
+}
+
+// DefaultTLSCertDuration returns the default TLS cert duration enforced by the provisioner.
+func (s *EST) DefaultTLSCertDuration() time.Duration {
+	return s.ctl.Claimer.DefaultTLSCertDuration()
+}
+
+// newChallengeValidationController creates a new challengeValidationController
+// that performs challenge validation through webhooks.
+func newESTChallengeValidationController(client HTTPClient, tw httptransport.Wrapper, webhooks []*Webhook) *challengeValidationController {
+	scepHooks := []*Webhook{}
+	for _, wh := range webhooks {
+		// if wh.Kind != linkedca.Webhook_ESTCHALLENGE.String() {
+		if wh.Kind != "ESTCHALLENGE" {
+			continue
+		}
+		if !isCertTypeOK(wh) {
+			continue
+		}
+		scepHooks = append(scepHooks, wh)
+	}
+	return &challengeValidationController{
+		client:        client,
+		wrapTransport: tw,
+		webhooks:      scepHooks,
+	}
+}
+
+// Init initializes and validates the fields of an EST type.
+func (s *EST) Init(config Config) (err error) {
+	switch {
+	case s.Type == "":
+		return errors.New("provisioner type cannot be empty")
+	case s.Name == "":
+		return errors.New("provisioner name cannot be empty")
+	}
+
+	if s.MinimumPublicKeyLength == 0 {
+		s.MinimumPublicKeyLength = 2048
+	}
+	if s.MinimumPublicKeyLength%8 != 0 {
+		return errors.Errorf("%d bits is not exactly divisible by 8", s.MinimumPublicKeyLength)
+	}
+
+	// Prepare the EST challenge validator
+	s.challengeValidationController = newESTChallengeValidationController(
+		config.WebhookClient,
+		config.WrapTransport,
+		s.GetOptions().GetWebhooks(),
+	)
+
+	// Prepare the EST notification controller
+	s.notificationController = newNotificationController(
+		config.WebhookClient,
+		config.WrapTransport,
+		s.GetOptions().GetWebhooks(),
+	)
+
+	if err := s.parseClientCertificateRoots(); err != nil {
+		return err
+	}
+
+	if err := s.normalizeAuthConfig(); err != nil {
+		return err
+	}
+
+	s.ctl, err = NewController(s, s.Claims, config, s.Options)
+	return err
+}
+
+// AuthorizeSign does not do any verification; main validation is in the EST protocol.
+func (s *EST) AuthorizeSign(context.Context, string) ([]SignOption, error) {
+	return []SignOption{
+		s,
+		newProvisionerExtensionOption(TypeEST, s.Name, "").WithControllerOptions(s.ctl),
+		newForceCNOption(s.ForceCN),
+		profileDefaultDuration(s.ctl.Claimer.DefaultTLSCertDuration()),
+		newPublicKeyMinimumLengthValidator(s.MinimumPublicKeyLength),
+		newValidityValidator(s.ctl.Claimer.MinTLSCertDuration(), s.ctl.Claimer.MaxTLSCertDuration()),
+		newX509NamePolicyValidator(s.ctl.getPolicy().getX509()),
+		s.ctl.newWebhookController(nil, linkedca.Webhook_X509),
+	}, nil
+}
+
+// ShouldIncludeRootInChain indicates if the CA should return its root in the chain.
+func (s *EST) ShouldIncludeRootInChain() bool {
+	return s.IncludeRoot
+}
+
+// ShouldIncludeIntermediateInChain indicates if the CA should include the intermediate CA certificate.
+func (s *EST) ShouldIncludeIntermediateInChain() bool {
+	return !s.ExcludeIntermediate
+}
+
+// GetSigner returns the provisioner specific signer, used to sign EST responses.
+func (s *EST) GetSigner() (*x509.Certificate, crypto.Signer) {
+	return s.signerCertificate, s.signer
+}
+
+// GetCSRAttributes returns the CSR attributes to signal to clients.
+func (s *EST) GetCSRAttributes(context.Context) ([]byte, error) {
+	return s.CSRAttrs, nil
+}
+
+func (s *EST) NotifySuccess(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, transactionID string) error {
+	if s.notificationController == nil {
+		return fmt.Errorf("provisioner %q wasn't initialized", s.Name)
+	}
+	return s.notificationController.Success(ctx, csr, cert, transactionID)
+}
+
+func (s *EST) NotifyFailure(ctx context.Context, csr *x509.CertificateRequest, transactionID string, errorCode int, errorDescription string) error {
+	if s.notificationController == nil {
+		return fmt.Errorf("provisioner %q wasn't initialized", s.Name)
+	}
+	return s.notificationController.Failure(ctx, csr, transactionID, errorCode, errorDescription)
+}

+ 378 - 0
authority/provisioner/est_auth.go

@@ -0,0 +1,378 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/subtle"
+	"crypto/x509"
+	"encoding/pem"
+	"errors"
+	"fmt"
+
+	"github.com/smallstep/certificates/webhook"
+)
+
+var (
+	ErrESTAuthMethodDisabled = errors.New("est authentication method disabled")
+	ErrESTAuthDenied         = errors.New("est authentication denied")
+)
+
+// ESTAuthMethod identifies the EST authentication method used.
+type ESTAuthMethod string
+
+const (
+	ESTAuthMethodTLSClientCertificate         ESTAuthMethod = "tls-client-certificate"
+	ESTAuthMethodTLSExternalClientCertificate ESTAuthMethod = "tls-external-client-certificate"
+	ESTAuthMethodHTTPBasicAuth                ESTAuthMethod = "http-basic-auth"
+)
+
+// ESTAuthRequest contains authentication material extracted from the request.
+type ESTAuthRequest struct {
+	CSR                    *x509.CertificateRequest
+	ClientCertificate      *x509.Certificate
+	ClientCertificateChain []*x509.Certificate
+	CARoots                []*x509.Certificate
+	CAIntermediates        []*x509.Certificate
+	BasicAuthUsername      string
+	BasicAuthPassword      string
+}
+
+// AuthorizeRequest validates the request against configured EST auth methods.
+func (s *EST) AuthorizeRequest(ctx context.Context, req ESTAuthRequest) (ESTAuthMethod, error) {
+	if s.hasAuthWebhooks() {
+		return s.authorizeRequestWithWebhook(ctx, req)
+	}
+	return s.authorizeRequestLocal(ctx, req)
+}
+
+// AuthorizeTLSClientCertificate validates a CA-issued client certificate.
+func (s *EST) AuthorizeTLSClientCertificate(ctx context.Context, cert *x509.Certificate, chain, roots, intermediates []*x509.Certificate) error {
+	method, err := s.AuthorizeRequest(ctx, ESTAuthRequest{
+		ClientCertificate:      cert,
+		ClientCertificateChain: chain,
+		CARoots:                roots,
+		CAIntermediates:        intermediates,
+	})
+	if err != nil {
+		return err
+	}
+	if method != ESTAuthMethodTLSClientCertificate {
+		return ErrESTAuthDenied
+	}
+	return nil
+}
+
+// AuthorizeTLSExternalClientCertificate validates a client certificate against external roots.
+func (s *EST) AuthorizeTLSExternalClientCertificate(ctx context.Context, cert *x509.Certificate, chain []*x509.Certificate) error {
+	method, err := s.AuthorizeRequest(ctx, ESTAuthRequest{
+		ClientCertificate:      cert,
+		ClientCertificateChain: chain,
+	})
+	if err != nil {
+		return err
+	}
+	if method != ESTAuthMethodTLSExternalClientCertificate {
+		return ErrESTAuthDenied
+	}
+	return nil
+}
+
+// AuthorizeHTTPBasicAuth validates a username/password pair for EST.
+func (s *EST) AuthorizeHTTPBasicAuth(ctx context.Context, csr *x509.CertificateRequest, username, password string) error {
+	method, err := s.AuthorizeRequest(ctx, ESTAuthRequest{
+		CSR:               csr,
+		BasicAuthUsername: username,
+		BasicAuthPassword: password,
+	})
+	if err != nil {
+		return err
+	}
+	if method != ESTAuthMethodHTTPBasicAuth {
+		return ErrESTAuthDenied
+	}
+	return nil
+}
+
+// authorizeRequestWithWebhook delegates authentication to EST webhooks.
+func (s *EST) authorizeRequestWithWebhook(ctx context.Context, req ESTAuthRequest) (ESTAuthMethod, error) {
+	if req.ClientCertificate != nil {
+		method, err := s.preferredCertAuthMethod()
+		if err != nil {
+			return "", err
+		}
+		if err := s.authorizeWithWebhook(ctx, req.ClientCertificate, req.CSR, ""); err != nil {
+			return "", err
+		}
+		return method, nil
+	}
+
+	if req.hasBasicAuth() {
+		method, err := s.preferredBasicAuthMethod()
+		if err != nil {
+			return "", err
+		}
+		if method == ESTAuthMethodHTTPBasicAuth {
+			if req.BasicAuthPassword == "" {
+				return "", errors.New("missing basic auth credentials")
+			}
+		}
+		if req.CSR == nil {
+			return "", errors.New("missing CSR for basic auth validation")
+		}
+		opts := []webhook.RequestBodyOption{}
+		if req.BasicAuthUsername != "" {
+			opts = append(opts, webhook.WithAuthorizationPrincipal(req.BasicAuthUsername))
+		}
+		if err := s.authorizeWithWebhook(ctx, nil, req.CSR, req.BasicAuthPassword, opts...); err != nil {
+			return "", err
+		}
+		return method, nil
+	}
+
+	return "", errors.New("missing client certificate or basic auth")
+}
+
+// authorizeRequestLocal validates the request using provisioner configuration.
+func (s *EST) authorizeRequestLocal(ctx context.Context, req ESTAuthRequest) (ESTAuthMethod, error) {
+	if req.ClientCertificate != nil {
+		var lastErr error
+		if boolValue(s.EnableTLSClientCertificate, false) {
+			if err := verifyCertificate(req.ClientCertificate, req.ClientCertificateChain, req.CARoots, req.CAIntermediates); err == nil {
+				return ESTAuthMethodTLSClientCertificate, nil
+			} else {
+				lastErr = err
+			}
+		}
+		if s.hasClientCertificateRoots() {
+			if s.clientCertificateRootPool == nil {
+				lastErr = ErrESTAuthMethodDisabled
+			} else if err := verifyCertificateWithPool(req.ClientCertificate, req.ClientCertificateChain, s.clientCertificateRootPool, nil); err == nil {
+				return ESTAuthMethodTLSExternalClientCertificate, nil
+			} else {
+				lastErr = err
+			}
+		}
+		if lastErr != nil {
+			return "", lastErr
+		}
+		return "", ErrESTAuthMethodDisabled
+	}
+
+	if req.hasBasicAuth() {
+		if boolValue(s.EnableHTTPBasicAuth, false) {
+			if req.BasicAuthPassword == "" {
+				return "", errors.New("missing basic auth credentials")
+			}
+			if s.BasicAuthUsername != "" && req.BasicAuthUsername != s.BasicAuthUsername {
+				return "", errors.New("invalid basic auth username")
+			}
+			if err := s.validateBasicAuthPassword(req.BasicAuthPassword); err != nil {
+				return "", err
+			}
+			return ESTAuthMethodHTTPBasicAuth, nil
+		}
+		return "", ErrESTAuthMethodDisabled
+	}
+
+	return "", errors.New("missing client certificate or basic auth")
+}
+
+// preferredCertAuthMethod selects the enabled certificate-based auth method.
+func (s *EST) preferredCertAuthMethod() (ESTAuthMethod, error) {
+	switch {
+	case boolValue(s.EnableTLSClientCertificate, false):
+		return ESTAuthMethodTLSClientCertificate, nil
+	case s.hasClientCertificateRoots():
+		return ESTAuthMethodTLSExternalClientCertificate, nil
+	default:
+		return "", ErrESTAuthMethodDisabled
+	}
+}
+
+// preferredBasicAuthMethod selects the enabled basic-auth-based method.
+func (s *EST) preferredBasicAuthMethod() (ESTAuthMethod, error) {
+	switch {
+	case boolValue(s.EnableHTTPBasicAuth, false):
+		return ESTAuthMethodHTTPBasicAuth, nil
+	default:
+		return "", ErrESTAuthMethodDisabled
+	}
+}
+
+// validateBasicAuthPassword verifies the configured basic auth password.
+func (s *EST) validateBasicAuthPassword(password string) error {
+	if s.BasicAuthPassword == "" {
+		return errors.New("basic auth password is not configured")
+	}
+	if subtleCompare(s.BasicAuthPassword, password) {
+		return nil
+	}
+	return errors.New("invalid basic auth password")
+}
+
+// authorizeWithWebhook executes configured webhooks for auth decisions.
+func (s *EST) authorizeWithWebhook(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, secret string, opts ...webhook.RequestBodyOption) error {
+	if !s.hasAuthWebhooks() {
+		return nil
+	}
+
+	var (
+		req *webhook.RequestBody
+		err error
+	)
+	switch {
+	case cert != nil:
+		req, err = webhook.NewRequestBody(append(opts, webhook.WithX509Certificate(nil, cert))...)
+		if err != nil {
+			return fmt.Errorf("failed creating webhook request: %w", err)
+		}
+		if req.X509Certificate != nil {
+			req.X509Certificate.Raw = cert.Raw
+		}
+	case csr != nil:
+		req, err = webhook.NewRequestBody(append(opts, webhook.WithX509CertificateRequest(csr))...)
+		if err != nil {
+			return fmt.Errorf("failed creating webhook request: %w", err)
+		}
+	default:
+		return errors.New("missing certificate or CSR for webhook validation")
+	}
+
+	req.ProvisionerName = s.Name
+	if secret != "" {
+		// TODO: change this to add a dedicated field in the webhook request body (or rename it but can broken existing webhooks)
+		req.SCEPChallenge = secret
+	}
+
+	for _, wh := range s.challengeValidationController.webhooks {
+		resp, err := wh.DoWithContext(ctx, s.challengeValidationController.client, s.challengeValidationController.wrapTransport, req, nil)
+		if err != nil {
+			return fmt.Errorf("failed executing webhook request: %w", err)
+		}
+		if resp.Allow {
+			return nil
+		}
+	}
+
+	return ErrESTAuthDenied
+}
+
+// hasBasicAuth reports whether any basic auth data is present.
+func (r ESTAuthRequest) hasBasicAuth() bool {
+	return r.BasicAuthUsername != "" || r.BasicAuthPassword != ""
+}
+
+// hasAuthWebhooks reports whether auth webhooks are configured.
+func (s *EST) hasAuthWebhooks() bool {
+	return s.challengeValidationController != nil && len(s.challengeValidationController.webhooks) > 0
+}
+
+// normalizeAuthConfig applies defaults and validates auth configuration.
+func (s *EST) normalizeAuthConfig() error {
+	if !s.authMethodsConfigured() {
+		enable := true
+		s.EnableHTTPBasicAuth = &enable
+	}
+	if s.EnableHTTPBasicAuth == nil && (s.BasicAuthUsername != "" || s.BasicAuthPassword != "") {
+		enable := true
+		s.EnableHTTPBasicAuth = &enable
+	}
+	if boolValue(s.EnableHTTPBasicAuth, false) && s.BasicAuthPassword == "" && !s.hasAuthWebhooks() {
+		return errors.New("basic auth password cannot be empty")
+	}
+	return nil
+}
+
+// authMethodsConfigured reports whether any auth method is explicitly configured.
+func (s *EST) authMethodsConfigured() bool {
+	return s.EnableTLSClientCertificate != nil ||
+		s.hasClientCertificateRoots() ||
+		s.EnableHTTPBasicAuth != nil
+}
+
+// parseClientCertificateRoots loads external client certificate roots.
+func (s *EST) parseClientCertificateRoots() error {
+	if len(s.ClientCertificateRoots) == 0 {
+		return nil
+	}
+	var (
+		block   *pem.Block
+		hasCert bool
+		rest    = s.ClientCertificateRoots
+	)
+	s.clientCertificateRootPool = x509.NewCertPool()
+	for rest != nil {
+		block, rest = pem.Decode(rest)
+		if block == nil {
+			break
+		}
+		cert, err := x509.ParseCertificate(block.Bytes)
+		if err != nil {
+			return errors.New("error parsing clientCertificateRoots: malformed certificate")
+		}
+		s.clientCertificateRootPool.AddCert(cert)
+		hasCert = true
+	}
+	if !hasCert {
+		return errors.New("error parsing clientCertificateRoots: no certificates found")
+	}
+	return nil
+}
+
+func (s *EST) hasClientCertificateRoots() bool {
+	return len(s.ClientCertificateRoots) > 0
+}
+
+// verifyCertificate validates the client certificate against CA roots.
+func verifyCertificate(cert *x509.Certificate, chain, roots, intermediates []*x509.Certificate) error {
+	rootPool := x509.NewCertPool()
+	for _, root := range roots {
+		if root != nil {
+			rootPool.AddCert(root)
+		}
+	}
+	intermediatePool := x509.NewCertPool()
+	for _, intermediate := range intermediates {
+		if intermediate != nil {
+			intermediatePool.AddCert(intermediate)
+		}
+	}
+	return verifyCertificateWithPool(cert, chain, rootPool, intermediatePool)
+}
+
+// verifyCertificateWithPool validates the client certificate using explicit pools.
+func verifyCertificateWithPool(cert *x509.Certificate, chain []*x509.Certificate, roots, intermediates *x509.CertPool) error {
+	if intermediates == nil {
+		intermediates = x509.NewCertPool()
+	}
+	for i, intermediate := range chain {
+		if i == 0 || intermediate == nil {
+			continue
+		}
+		intermediates.AddCert(intermediate)
+	}
+	_, err := cert.Verify(x509.VerifyOptions{
+		Roots:         roots,
+		Intermediates: intermediates,
+		KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
+	})
+	if err != nil {
+		return fmt.Errorf("invalid client certificate: %w", err)
+	}
+	return nil
+}
+
+// boolValue returns the dereferenced value or a default.
+func boolValue(value *bool, defaultValue bool) bool {
+	if value == nil {
+		return defaultValue
+	}
+	return *value
+}
+
+// subtleCompare compares secrets in constant time.
+func subtleCompare(expected, actual string) bool {
+	if len(expected) != len(actual) {
+		return false
+	}
+	return subtle.ConstantTimeCompare([]byte(expected), []byte(actual)) == 1
+}

+ 6 - 0
authority/provisioner/provisioner.go

@@ -209,6 +209,8 @@ const (
 	TypeSCEP Type = 10
 	// TypeNebula is used to indicate the Nebula provisioners
 	TypeNebula Type = 11
+	// TypeEST is used to indicate the EST provisioners
+	TypeEST Type = 12
 )
 
 // String returns the string representation of the type.
@@ -236,6 +238,8 @@ func (t Type) String() string {
 		return "SCEP"
 	case TypeNebula:
 		return "Nebula"
+	case TypeEST:
+		return "EST"
 	default:
 		return ""
 	}
@@ -333,6 +337,8 @@ func (l *List) UnmarshalJSON(data []byte) error {
 			p = &SCEP{}
 		case "nebula":
 			p = &Nebula{}
+		case "est":
+			p = &EST{}
 		default:
 			// Skip unsupported provisioners. A client using this method may be
 			// compiled with a version of smallstep/certificates that does not

+ 1 - 1
ca/bootstrap_test.go

@@ -54,7 +54,7 @@ func startCABootstrapServer() *httptest.Server {
 	if err != nil {
 		panic(err)
 	}
-	baseContext := buildContext(ca.auth, nil, nil, nil)
+	baseContext := buildContext(ca.auth, nil, nil, nil, nil)
 	srv.Config.Handler = ca.srv.Handler
 	srv.Config.BaseContext = func(net.Listener) context.Context {
 		return baseContext

+ 17 - 2
ca/ca.go

@@ -39,6 +39,8 @@ import (
 	"github.com/smallstep/certificates/logging"
 	"github.com/smallstep/certificates/middleware/requestid"
 	"github.com/smallstep/certificates/monitoring"
+	"github.com/smallstep/certificates/est"
+	estAPI "github.com/smallstep/certificates/est/api"
 	"github.com/smallstep/certificates/scep"
 	scepAPI "github.com/smallstep/certificates/scep/api"
 	"github.com/smallstep/certificates/server"
@@ -300,6 +302,7 @@ func (ca *CA) Init(cfg *config.Config) (*CA, error) {
 	}
 
 	var scepAuthority *scep.Authority
+	var estAuthority *est.Authority
 	if ca.shouldServeSCEPEndpoints() {
 		// get the SCEP authority configuration. Validation is
 		// performed within the authority instantiation process.
@@ -328,6 +331,15 @@ func (ca *CA) Init(cfg *config.Config) (*CA, error) {
 	//dumpRoutes(mux)
 	//dumpRoutes(insecureMux)
 
+	// EST endpoints (HTTPS only)
+	estPrefix := ".well-known/est"
+	if estAuth := auth.GetEST(); estAuth != nil {
+		estAuthority = estAuth
+		mux.Route("/"+estPrefix, func(r chi.Router) {
+			estAPI.Route(r)
+		})
+	}
+
 	// Add monitoring if configured
 	if len(cfg.Monitoring) > 0 {
 		m, err := monitoring.New(cfg.Monitoring)
@@ -355,7 +367,7 @@ func (ca *CA) Init(cfg *config.Config) (*CA, error) {
 	insecureHandler = requestid.New(legacyTraceHeader).Middleware(insecureHandler)
 
 	// Create context with all the necessary values.
-	baseContext := buildContext(auth, scepAuthority, acmeDB, acmeLinker)
+	baseContext := buildContext(auth, scepAuthority, estAuthority, acmeDB, acmeLinker)
 
 	ca.srv = server.New(cfg.Address, handler, tlsConfig)
 	ca.srv.BaseContext = func(net.Listener) context.Context {
@@ -403,7 +415,7 @@ func (ca *CA) shouldServeInsecureServer() bool {
 }
 
 // buildContext builds the server base context.
-func buildContext(a *authority.Authority, scepAuthority *scep.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
+func buildContext(a *authority.Authority, scepAuthority *scep.Authority, estAuthority *est.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
 	ctx := authority.NewContext(context.Background(), a)
 	if authDB := a.GetDatabase(); authDB != nil {
 		ctx = db.NewContext(ctx, authDB)
@@ -414,6 +426,9 @@ func buildContext(a *authority.Authority, scepAuthority *scep.Authority, acmeDB
 	if scepAuthority != nil {
 		ctx = scep.NewContext(ctx, scepAuthority)
 	}
+	if estAuthority != nil {
+		ctx = est.NewContext(ctx, estAuthority)
+	}
 	if acmeDB != nil {
 		ctx = acme.NewContext(ctx, acmeDB, acme.NewClient(), acmeLinker, nil)
 	}

+ 1 - 1
ca/tls_test.go

@@ -78,7 +78,7 @@ func startCATestServer(t *testing.T) *httptest.Server {
 	ca, err := New(config)
 	require.NoError(t, err)
 	// Use a httptest.Server instead
-	baseContext := buildContext(ca.auth, nil, nil, nil)
+	baseContext := buildContext(ca.auth, nil, nil, nil, nil)
 	srv := startTestServer(baseContext, ca.srv.TLSConfig, ca.srv.Handler)
 	return srv
 }

+ 304 - 0
est/api/api.go

@@ -0,0 +1,304 @@
+// Package api implements an EST HTTP server.
+package api
+
+import (
+	"context"
+	"crypto/x509"
+	"encoding/base64"
+	"errors"
+	"fmt"
+	"io"
+	"mime"
+	"net/http"
+	"net/url"
+	"strings"
+
+	"github.com/go-chi/chi/v5"
+
+	"github.com/smallstep/certificates/api"
+	"github.com/smallstep/certificates/api/log"
+	"github.com/smallstep/certificates/authority"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/est"
+)
+
+const (
+	maxPayloadSize = 2 << 20
+)
+
+// Route configures the EST routes under the provided router.
+func Route(r api.Router) {
+	r.MethodFunc(http.MethodGet, "/{provisionerName}/cacerts", getCACerts)
+	r.MethodFunc(http.MethodGet, "/{provisionerName}/csrattrs", getCSRAttrs)
+	r.MethodFunc(http.MethodPost, "/{provisionerName}/simpleenroll", enroll)
+	r.MethodFunc(http.MethodPost, "/{provisionerName}/simplereenroll", enroll)
+}
+
+func lookupProvisioner(next http.HandlerFunc) http.HandlerFunc {
+	return func(w http.ResponseWriter, r *http.Request) {
+		name := chi.URLParam(r, "provisionerName")
+		if name == "" || name == "/" {
+			name = r.URL.Query().Get("provisioner")
+		}
+		if name == "" {
+			fail(w, r, errors.New("missing provisioner name"))
+			return
+		}
+		provisionerName, err := url.PathUnescape(name)
+		if err != nil {
+			fail(w, r, fmt.Errorf("error url unescaping provisioner name '%s'", name))
+			return
+		}
+
+		ctx := r.Context()
+		auth := authority.MustFromContext(ctx)
+		p, err := auth.LoadProvisionerByName(provisionerName)
+		if err != nil {
+			fail(w, r, err)
+			return
+		}
+
+		prov, ok := p.(*provisioner.EST)
+		if !ok {
+			fail(w, r, errors.New("provisioner must be of type EST"))
+			return
+		}
+
+		ctx = est.NewProvisionerContext(ctx, est.Provisioner(prov))
+		next(w, r.WithContext(ctx))
+	}
+}
+
+func getCACerts(w http.ResponseWriter, r *http.Request) {
+	lookupProvisioner(getCACertsHandler)(w, r)
+}
+
+func getCACertsHandler(w http.ResponseWriter, r *http.Request) {
+	ctx := r.Context()
+	auth := est.MustFromContext(ctx)
+
+	certs, err := auth.GetCACertificates(ctx)
+	if err != nil {
+		fail(w, r, fmt.Errorf("failed to get CA certificates: %w", err))
+		return
+	}
+
+	data, err := auth.BuildResponse(ctx, certs)
+	if err != nil {
+		fail(w, r, fmt.Errorf("failed to encode CA certificates: %w", err))
+		return
+	}
+
+	writeResponse(w, r, data, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
+}
+
+func getCSRAttrs(w http.ResponseWriter, r *http.Request) {
+	lookupProvisioner(getCSRAttrsHandler)(w, r)
+}
+
+func getCSRAttrsHandler(w http.ResponseWriter, r *http.Request) {
+	ctx := r.Context()
+	prov := est.ProvisionerFromContext(ctx)
+
+	attrs, err := prov.GetCSRAttributes(ctx)
+	if err != nil {
+		fail(w, r, fmt.Errorf("failed to get CSR attributes: %w", err))
+		return
+	}
+	if attrs == nil {
+		attrs = []byte{}
+	}
+	// Minimal implementation: allow provisioner to return nil/empty for "no attributes".
+	writeResponse(w, r, attrs, "application/csrattrs", http.StatusOK)
+}
+
+func enroll(w http.ResponseWriter, r *http.Request) {
+	lookupProvisioner(enrollHandler)(w, r)
+}
+
+func enrollHandler(w http.ResponseWriter, r *http.Request) {
+	ctx := r.Context()
+	ctx, err := authContextFromRequest(ctx, r)
+	if err != nil {
+		if errors.Is(err, errMissingClientCertificateOrBasicAuth) {
+			w.Header().Set("WWW-Authenticate", `Basic realm="EST"`)
+		}
+		failWithStatus(w, r, http.StatusUnauthorized, err)
+		return
+	}
+
+	body, err := io.ReadAll(io.LimitReader(r.Body, maxPayloadSize))
+	if err != nil {
+		failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("failed reading request body: %w", err))
+		return
+	}
+
+	if err := requireContentType(r, "application/pkcs10"); err != nil {
+		failWithStatus(w, r, http.StatusUnsupportedMediaType, err)
+		return
+	}
+
+	der, err := decodeBase64Payload(body)
+	if err != nil {
+		failWithStatus(w, r, http.StatusBadRequest, err)
+		return
+	}
+
+	csr, err := parseCSR(der)
+	if err != nil {
+		failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("failed parsing CSR: %w", err))
+		return
+	}
+	if err := csr.CheckSignature(); err != nil {
+		failWithStatus(w, r, http.StatusBadRequest, fmt.Errorf("invalid CSR signature: %w", err))
+		return
+	}
+
+	ctx, err = authorizeEnrollRequest(ctx, csr)
+	if err != nil {
+		failWithStatus(w, r, http.StatusUnauthorized, err)
+		return
+	}
+
+	r = r.WithContext(ctx)
+	auth := est.MustFromContext(ctx)
+
+	issued, err := auth.SignCSR(ctx, csr)
+	if err != nil {
+		failWithStatus(w, r, http.StatusInternalServerError, fmt.Errorf("failed issuing certificate: %w", err))
+		return
+	}
+
+	signed, err := auth.BuildResponse(ctx, []*x509.Certificate{issued})
+	if err != nil {
+		failWithStatus(w, r, http.StatusInternalServerError, fmt.Errorf("failed encoding issued certificate: %w", err))
+		return
+	}
+
+	writeResponse(w, r, signed, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
+}
+
+var errMissingClientCertificateOrBasicAuth = errors.New("missing client certificate or basic auth")
+
+// authContextFromRequest extracts auth material from the request into the context.
+func authContextFromRequest(ctx context.Context, r *http.Request) (context.Context, error) {
+	if r.TLS == nil {
+		return ctx, errors.New("missing TLS connection")
+	}
+
+	if len(r.TLS.PeerCertificates) > 0 {
+		ctx = est.NewClientCertificateContext(ctx, r.TLS.PeerCertificates[0])
+		ctx = est.NewClientCertificateChainContext(ctx, r.TLS.PeerCertificates)
+	}
+
+	if username, password, ok := r.BasicAuth(); ok {
+		ctx = est.NewBasicAuthContext(ctx, est.BasicAuth{
+			Username: username,
+			Password: password,
+		})
+	}
+
+	if _, ok := est.ClientCertificateFromContext(ctx); !ok {
+		if _, ok := est.BasicAuthFromContext(ctx); !ok {
+			return ctx, errMissingClientCertificateOrBasicAuth
+		}
+	}
+	return ctx, nil
+}
+
+// authorizeEnrollRequest validates the request against provisioner-configured auth methods.
+func authorizeEnrollRequest(ctx context.Context, csr *x509.CertificateRequest) (context.Context, error) {
+	prov := est.ProvisionerFromContext(ctx)
+	ca := authority.MustFromContext(ctx)
+
+	req := provisioner.ESTAuthRequest{
+		CSR:             csr,
+		CARoots:         ca.GetRootCertificates(),
+		CAIntermediates: ca.GetIntermediateCertificates(),
+	}
+	if cert, ok := est.ClientCertificateFromContext(ctx); ok {
+		req.ClientCertificate = cert
+		req.ClientCertificateChain, _ = est.ClientCertificateChainFromContext(ctx)
+	}
+	if auth, ok := est.BasicAuthFromContext(ctx); ok {
+		req.BasicAuthUsername = auth.Username
+		req.BasicAuthPassword = auth.Password
+	}
+
+	method, err := prov.AuthorizeRequest(ctx, req)
+	if err != nil {
+		return ctx, err
+	}
+	ctx = est.NewAuthMethodContext(ctx, est.AuthMethod(method))
+	return ctx, nil
+}
+
+func parseCSR(body []byte) (*x509.CertificateRequest, error) {
+	if len(body) == 0 {
+		return nil, errors.New("empty body")
+	}
+
+	return x509.ParseCertificateRequest(body)
+}
+
+func decodeBase64Payload(body []byte) ([]byte, error) {
+	if len(body) == 0 {
+		return nil, errors.New("empty body")
+	}
+
+	trimmed := strings.Map(func(r rune) rune {
+		switch r {
+		case ' ', '\n', '\r', '\t':
+			return -1
+		default:
+			return r
+		}
+	}, string(body))
+
+	if trimmed == "" {
+		return nil, errors.New("empty base64 payload")
+	}
+
+	decoded := make([]byte, base64.StdEncoding.DecodedLen(len(trimmed)))
+	n, err := base64.StdEncoding.Decode(decoded, []byte(trimmed))
+	if err != nil {
+		return nil, fmt.Errorf("invalid base64 payload: %w", err)
+	}
+
+	return decoded[:n], nil
+}
+
+func requireContentType(r *http.Request, want string) error {
+	ct := r.Header.Get("Content-Type")
+	if ct == "" {
+		return errors.New("missing Content-Type header")
+	}
+	mt, _, err := mime.ParseMediaType(ct)
+	if err != nil {
+		return fmt.Errorf("invalid Content-Type header: %w", err)
+	}
+	if mt != want {
+		return fmt.Errorf("unsupported Content-Type %q", mt)
+	}
+	return nil
+}
+
+func writeResponse(w http.ResponseWriter, r *http.Request, data []byte, contentType string, status int) {
+	w.Header().Set("Content-Type", contentType)
+	w.Header().Set("Content-Transfer-Encoding", "base64")
+	w.WriteHeader(status)
+
+	encoder := base64.NewEncoder(base64.StdEncoding, w)
+	_, _ = encoder.Write(data)
+	_ = encoder.Close()
+}
+
+func fail(w http.ResponseWriter, r *http.Request, err error) {
+	log.Error(w, r, err)
+	http.Error(w, err.Error(), http.StatusInternalServerError)
+}
+
+func failWithStatus(w http.ResponseWriter, r *http.Request, status int, err error) {
+	log.Error(w, r, err)
+	http.Error(w, err.Error(), status)
+}

+ 71 - 0
est/api/api_test.go

@@ -0,0 +1,71 @@
+package api
+
+import (
+	"encoding/base64"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func Test_writeResponse(t *testing.T) {
+	type args struct {
+		w           http.ResponseWriter
+		r           *http.Request
+		data        []byte
+		contentType string
+		status      int
+	}
+	tests := []struct {
+		name        string
+		args        args
+		wantBody    string
+		wantHeaders map[string]string
+	}{
+		{
+			name: "ok",
+			args: args{
+				w:           httptest.NewRecorder(),
+				r:           httptest.NewRequest("GET", "/", nil),
+				data:        []byte("hello world"),
+				contentType: "application/pkcs7-mime; smime-type=certs-only",
+				status:      http.StatusOK,
+			},
+			wantBody: base64.StdEncoding.EncodeToString([]byte("hello world")),
+			wantHeaders: map[string]string{
+				"Content-Type":              "application/pkcs7-mime; smime-type=certs-only",
+				"Content-Transfer-Encoding": "base64",
+			},
+		},
+		{
+			name: "ok/csrattrs",
+			args: args{
+				w:           httptest.NewRecorder(),
+				r:           httptest.NewRequest("GET", "/", nil),
+				data:        []byte("attribute data"),
+				contentType: "application/csrattrs",
+				status:      http.StatusOK,
+			},
+			wantBody: base64.StdEncoding.EncodeToString([]byte("attribute data")),
+			wantHeaders: map[string]string{
+				"Content-Type":              "application/csrattrs",
+				"Content-Transfer-Encoding": "base64",
+			},
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			writeResponse(tt.args.w, tt.args.r, tt.args.data, tt.args.contentType, tt.args.status)
+			resp := tt.args.w.(*httptest.ResponseRecorder)
+
+			assert.Equal(t, tt.args.status, resp.Code)
+			assert.Equal(t, tt.wantBody, resp.Body.String())
+
+			for k, v := range tt.wantHeaders {
+				assert.Equal(t, v, resp.Header().Get(k))
+			}
+		})
+	}
+}

+ 50 - 0
est/auth_context.go

@@ -0,0 +1,50 @@
+package est
+
+import "context"
+
+// AuthMethod describes the authentication method used for an EST request.
+type AuthMethod string
+
+const (
+	AuthMethodTLSClientCertificate         AuthMethod = "tls-client-certificate"
+	AuthMethodTLSExternalClientCertificate AuthMethod = "tls-external-client-certificate"
+	AuthMethodHTTPBasicAuth                AuthMethod = "http-basic-auth"
+)
+
+type authMethodKey struct{}
+
+// NewAuthMethodContext stores the EST authentication method in the context.
+func NewAuthMethodContext(ctx context.Context, method AuthMethod) context.Context {
+	if method == "" {
+		return ctx
+	}
+	return context.WithValue(ctx, authMethodKey{}, method)
+}
+
+// AuthMethodFromContext returns the EST authentication method stored in the context.
+func AuthMethodFromContext(ctx context.Context) (AuthMethod, bool) {
+	method, ok := ctx.Value(authMethodKey{}).(AuthMethod)
+	return method, ok
+}
+
+// BasicAuth holds the HTTP basic auth credentials for an EST request.
+type BasicAuth struct {
+	Username string
+	Password string
+}
+
+type basicAuthKey struct{}
+
+// NewBasicAuthContext stores the HTTP basic auth credentials in the context.
+func NewBasicAuthContext(ctx context.Context, auth BasicAuth) context.Context {
+	if auth.Username == "" && auth.Password == "" {
+		return ctx
+	}
+	return context.WithValue(ctx, basicAuthKey{}, auth)
+}
+
+// BasicAuthFromContext returns the HTTP basic auth credentials stored in the context.
+func BasicAuthFromContext(ctx context.Context) (BasicAuth, bool) {
+	auth, ok := ctx.Value(basicAuthKey{}).(BasicAuth)
+	return auth, ok
+}

+ 238 - 0
est/authority.go

@@ -0,0 +1,238 @@
+package est
+
+import (
+	"bytes"
+	"context"
+	"crypto"
+	"crypto/x509"
+	"fmt"
+	"sync"
+
+	"github.com/smallstep/pkcs7"
+
+	"go.step.sm/crypto/x509util"
+
+	"github.com/smallstep/certificates/authority/provisioner"
+)
+
+// Authority handles EST interactions.
+type Authority struct {
+	signAuth            SignAuthority
+	roots               []*x509.Certificate
+	intermediates       []*x509.Certificate
+	defaultSigner       crypto.Signer
+	signerCertificate   *x509.Certificate
+	estProvisionerNames []string
+	provisionersMutex   sync.RWMutex
+}
+
+type authorityKey struct{}
+
+// NewContext adds the given authority to the context.
+func NewContext(ctx context.Context, a *Authority) context.Context {
+	return context.WithValue(ctx, authorityKey{}, a)
+}
+
+// FromContext returns the current authority from the given context.
+func FromContext(ctx context.Context) (a *Authority, ok bool) {
+	a, ok = ctx.Value(authorityKey{}).(*Authority)
+	return
+}
+
+// MustFromContext returns the current authority from the given context. It will
+// panic if the authority is not in the context.
+func MustFromContext(ctx context.Context) *Authority {
+	var (
+		a  *Authority
+		ok bool
+	)
+	if a, ok = FromContext(ctx); !ok {
+		panic("est authority is not in the context")
+	}
+	return a
+}
+
+// SignAuthority is the interface for a signing authority.
+type SignAuthority interface {
+	SignWithContext(ctx context.Context, cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
+	LoadProvisionerByName(string) (provisioner.Interface, error)
+}
+
+// New returns a new Authority that implements the EST interface.
+func New(signAuth SignAuthority, opts Options) (*Authority, error) {
+	if err := opts.Validate(); err != nil {
+		return nil, err
+	}
+
+	return &Authority{
+		signAuth:            signAuth,
+		roots:               opts.Roots,
+		intermediates:       opts.Intermediates,
+		defaultSigner:       opts.Signer,
+		signerCertificate:   opts.SignerCert,
+		estProvisionerNames: opts.ESTProvisionerNames,
+	}, nil
+}
+
+// validates if the EST Authority has a valid configuration.
+func (a *Authority) Validate() error {
+	if a == nil {
+		return nil
+	}
+
+	a.provisionersMutex.RLock()
+	defer a.provisionersMutex.RUnlock()
+
+	noDefaultSignerAvailable := a.defaultSigner == nil || a.signerCertificate == nil
+	for _, name := range a.estProvisionerNames {
+		p, err := a.LoadProvisionerByName(name)
+		if err != nil {
+			return fmt.Errorf("failed loading provisioner %q: %w", name, err)
+		}
+		if estProv, ok := p.(*provisioner.EST); ok {
+			cert, signer := estProv.GetSigner()
+			if cert == nil && noDefaultSignerAvailable {
+				return fmt.Errorf("EST provisioner %q does not have a signer certificate", name)
+			}
+			if signer == nil && noDefaultSignerAvailable {
+				return fmt.Errorf("EST provisioner %q does not have a signer", name)
+			}
+		}
+	}
+
+	return nil
+}
+
+// UpdateProvisioners updates the EST Authority with the new, and hopefully
+// current EST provisioners configured. This allows the Authority to be
+// validated with the latest data.
+func (a *Authority) UpdateProvisioners(estProvisionerNames []string) {
+	if a == nil {
+		return
+	}
+
+	a.provisionersMutex.Lock()
+	defer a.provisionersMutex.Unlock()
+
+	a.estProvisionerNames = estProvisionerNames
+}
+
+// LoadProvisionerByName calls out to the SignAuthority interface to load a
+// provisioner by name.
+func (a *Authority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
+	return a.signAuth.LoadProvisionerByName(name)
+}
+
+// GetCACertificates returns the certificate chain for the CA.
+func (a *Authority) GetCACertificates(ctx context.Context) (certs []*x509.Certificate, err error) {
+	p := provisionerFromContext(ctx)
+
+	if signerCert, _ := p.GetSigner(); signerCert != nil {
+		certs = append(certs, signerCert)
+	}
+
+	if p.ShouldIncludeIntermediateInChain() || len(certs) == 0 {
+		certs = append(certs, a.intermediates...)
+	}
+
+	if p.ShouldIncludeRootInChain() {
+		certs = append(certs, a.roots...)
+	}
+
+	return certs, nil
+}
+
+// SignCSR signs the CSR using the provisioner and returns the issued chain.
+func (a *Authority) SignCSR(ctx context.Context, csr *x509.CertificateRequest, signCSROpts ...provisioner.SignCSROption) (*x509.Certificate, error) {
+	// TODO: intermediate storage of the request? In EST it's possible to request a csr/certificate
+	// to be signed, which can be performed asynchronously / out-of-band. In that case a client can
+	// poll for the status. It seems to be similar as what can happen in ACME and SCEP, so might want to model
+	// the implementation after the one in the ACME authority. Requires storage, etc.
+	// ref: https://datatracker.ietf.org/doc/html/rfc7030#section-4.2.3
+	p := provisionerFromContext(ctx)
+
+	// Template data
+	sans := []string{}
+	sans = append(sans, csr.DNSNames...)
+	sans = append(sans, csr.EmailAddresses...)
+	for _, v := range csr.IPAddresses {
+		sans = append(sans, v.String())
+	}
+	for _, v := range csr.URIs {
+		sans = append(sans, v.String())
+	}
+	if len(sans) == 0 {
+		sans = append(sans, csr.Subject.CommonName)
+	}
+	data := x509util.CreateTemplateData(csr.Subject.CommonName, sans)
+	data.SetCertificateRequest(csr)
+	data.SetSubject(x509util.Subject{
+		Country:            csr.Subject.Country,
+		Organization:       csr.Subject.Organization,
+		OrganizationalUnit: csr.Subject.OrganizationalUnit,
+		Locality:           csr.Subject.Locality,
+		Province:           csr.Subject.Province,
+		StreetAddress:      csr.Subject.StreetAddress,
+		PostalCode:         csr.Subject.PostalCode,
+		SerialNumber:       csr.Subject.SerialNumber,
+		CommonName:         csr.Subject.CommonName,
+	})
+
+	for _, o := range signCSROpts {
+		if m, ok := o.(provisioner.TemplateDataModifier); ok {
+			m.Modify(data)
+		}
+	}
+
+	ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
+	signOps, err := p.AuthorizeSign(ctx, "")
+	if err != nil {
+		return nil, fmt.Errorf("error retrieving authorization options from EST provisioner: %w", err)
+	}
+	for _, signOp := range signOps {
+		if wc, ok := signOp.(*provisioner.WebhookController); ok {
+			wc.TemplateData = data
+		}
+	}
+
+	opts := provisioner.SignOptions{}
+	templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
+	if err != nil {
+		return nil, fmt.Errorf("error creating template options from EST provisioner: %w", err)
+	}
+	signOps = append(signOps, templateOptions)
+
+	certChain, err := a.signAuth.SignWithContext(ctx, csr, opts, signOps...)
+	if err != nil {
+		return nil, fmt.Errorf("error generating certificate: %w", err)
+	}
+	// return leaf certificate (only): https://datatracker.ietf.org/doc/html/rfc7030#section-4.2.3
+	return certChain[0], nil
+}
+
+// BuildResponse returns a certs-only PKCS7 SignedData for the given certs.
+func (a *Authority) BuildResponse(ctx context.Context, certs []*x509.Certificate) ([]byte, error) {
+	if len(certs) == 0 {
+		return nil, fmt.Errorf("no certificates to encode")
+	}
+	// Build degenerate PKCS7: SignedData with no encapsulated content or signer infos.
+	var buf bytes.Buffer
+	for _, cert := range certs {
+		buf.Write(cert.Raw)
+	}
+	degenerate, err := pkcs7.DegenerateCertificate(buf.Bytes())
+	if err != nil {
+		return nil, err
+	}
+	return degenerate, nil
+}
+
+func (a *Authority) NotifySuccess(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, transactionID string) error {
+	p := provisionerFromContext(ctx)
+	return p.NotifySuccess(ctx, csr, cert, transactionID)
+}
+
+func (a *Authority) NotifyFailure(ctx context.Context, csr *x509.CertificateRequest, transactionID string, errorCode int, errorDescription string) error {
+	p := provisionerFromContext(ctx)
+	return p.NotifyFailure(ctx, csr, transactionID, errorCode, errorDescription)
+}

+ 37 - 0
est/client_cert.go

@@ -0,0 +1,37 @@
+package est
+
+import (
+	"context"
+	"crypto/x509"
+)
+
+type clientCertificateKey struct{}
+type clientCertificateChainKey struct{}
+
+// NewClientCertificateContext stores the TLS client certificate in the context.
+func NewClientCertificateContext(ctx context.Context, cert *x509.Certificate) context.Context {
+	if cert == nil {
+		return ctx
+	}
+	return context.WithValue(ctx, clientCertificateKey{}, cert)
+}
+
+// ClientCertificateFromContext returns the TLS client certificate stored in the context.
+func ClientCertificateFromContext(ctx context.Context) (*x509.Certificate, bool) {
+	cert, ok := ctx.Value(clientCertificateKey{}).(*x509.Certificate)
+	return cert, ok
+}
+
+// NewClientCertificateChainContext stores the TLS client certificate chain in the context.
+func NewClientCertificateChainContext(ctx context.Context, chain []*x509.Certificate) context.Context {
+	if len(chain) == 0 {
+		return ctx
+	}
+	return context.WithValue(ctx, clientCertificateChainKey{}, chain)
+}
+
+// ClientCertificateChainFromContext returns the TLS client certificate chain stored in the context.
+func ClientCertificateChainFromContext(ctx context.Context) ([]*x509.Certificate, bool) {
+	chain, ok := ctx.Value(clientCertificateChainKey{}).([]*x509.Certificate)
+	return chain, ok
+}

+ 40 - 0
est/options.go

@@ -0,0 +1,40 @@
+package est
+
+import (
+	"crypto"
+	"crypto/x509"
+	"errors"
+)
+
+// Options configures the EST authority instance.
+type Options struct {
+	Roots         []*x509.Certificate `json:"-"`
+	Intermediates []*x509.Certificate `json:"-"`
+	SignerCert    *x509.Certificate   `json:"-"`
+	Signer        crypto.Signer       `json:"-"`
+
+	ESTProvisionerNames []string
+}
+
+type comparablePublicKey interface {
+	Equal(crypto.PublicKey) bool
+}
+
+// Validate checks the fields in Options.
+func (o *Options) Validate() error {
+	switch {
+	case len(o.Intermediates) == 0:
+		return errors.New("no intermediate certificate available for EST authority")
+	case o.SignerCert == nil:
+		return errors.New("no signer certificate available for EST authority")
+	}
+
+	if o.Signer != nil {
+		signerPublicKey := o.Signer.Public().(comparablePublicKey)
+		if !signerPublicKey.Equal(o.SignerCert.PublicKey) {
+			return errors.New("mismatch between signer certificate and public key")
+		}
+	}
+
+	return nil
+}

+ 46 - 0
est/provisioner.go

@@ -0,0 +1,46 @@
+package est
+
+import (
+	"context"
+	"crypto"
+	"crypto/x509"
+
+	"github.com/smallstep/certificates/authority/provisioner"
+)
+
+// Provisioner is an interface that embeds the generic provisioner.Interface and
+// adds EST-specific helpers.
+type Provisioner interface {
+	provisioner.Interface
+	GetOptions() *provisioner.Options
+	ShouldIncludeRootInChain() bool
+	ShouldIncludeIntermediateInChain() bool
+	GetSigner() (*x509.Certificate, crypto.Signer)
+	AuthorizeRequest(ctx context.Context, req provisioner.ESTAuthRequest) (provisioner.ESTAuthMethod, error)
+	NotifySuccess(ctx context.Context, csr *x509.CertificateRequest, cert *x509.Certificate, transactionID string) error
+	NotifyFailure(ctx context.Context, csr *x509.CertificateRequest, transactionID string, errorCode int, errorDescription string) error
+	GetCSRAttributes(ctx context.Context) ([]byte, error)
+}
+
+// provisionerKey is the key type for storing and searching an EST provisioner in the context.
+type provisionerKey struct{}
+
+// provisionerFromContext searches the context for an EST provisioner.
+// Returns the provisioner or panics if no EST provisioner is found.
+func provisionerFromContext(ctx context.Context) Provisioner {
+	p, ok := ctx.Value(provisionerKey{}).(Provisioner)
+	if !ok {
+		panic("EST provisioner expected in request context")
+	}
+	return p
+}
+
+// NewProvisionerContext returns a new context with the EST provisioner set.
+func NewProvisionerContext(ctx context.Context, p Provisioner) context.Context {
+	return context.WithValue(ctx, provisionerKey{}, p)
+}
+
+// ProvisionerFromContext returns the EST provisioner stored in the context.
+func ProvisionerFromContext(ctx context.Context) Provisioner {
+	return provisionerFromContext(ctx)
+}