est

package module
v1.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 36 Imported by: 0

README

go-pki-est

GitHub Release Go Reference License Tests Supply chain OpenSSF Scorecard

Go library for Enrollment over Secure Transport (EST), the certificate enrollment protocol defined in RFC 7030. It provides:

  • an EST client library
  • an http.Handler that serves EST in front of your CA (NewRouter and the CA interface)
  • estclient, a command line client built on the library
  • estserver, a server with a mock CA for testing and development

Contents

Install

go get github.com/misiektoja/go-pki-est

The package name is est. Requires Go 1.27.3 or newer.

The command line tools install with:

go install github.com/misiektoja/go-pki-est/cmd/estclient@latest
go install github.com/misiektoja/go-pki-est/cmd/estserver@latest

Scope

Standard Coverage Enabled by
RFC 7030 EST /cacerts, /csrattrs, /simpleenroll, /simplereenroll and /serverkeygen, with or without an additional path segment Always
RFC 7030 section 3.5 tls-unique proof of possession over TLS 1.2 Client.SigningKey. The CA checks the value
RFC 7030 section 2.3 Renewal with a password or token instead of the certificate ServerConfig.PasswordRenewal
RFC 7030 section 3.3.3 and RFC 5054 TLS-SRP sign-in without certificates Client.SRPUsername and a go-tls-srp listener
RFC 6750 Bearer tokens Client.BearerToken and ServerConfig.CheckBearerToken
RFC 8951 Whitespace in base64 and the Content-Transfer-Encoding header ignored Always
TPM 2.0 credential protection /tpmenroll, an operation outside RFC 7030 CA.TPMEnroll

ML-DSA keys work for enrollment, renewal over TLS 1.3 and server-generated keys. Composite ML-DSA and SLH-DSA requests need a signature hook, because Go cannot verify them. /fullcmc is not implemented.

Getting started

Enroll a key with an EST server that asks for a password:

client := &est.Client{
	Host:           "est.example.com:8443",
	ExplicitAnchor: anchor, // *x509.CertPool with the root of the EST server
	Username:       "device-1",
	Password:       "one-time-secret",
}
cert, err := client.Enroll(ctx, csr) // csr is a parsed *x509.CertificateRequest
if err != nil {
	log.Fatal(err)
}

To serve EST, implement the CA interface and pass it to est.NewRouter, which returns an http.Handler for your TLS server.

Getting started runs estserver and enrolls, renews and gets a server-generated key with estclient, then shows the same from Go.

Documentation

Full documentation is at misiektoja.github.io/go-pki-est.

The package documentation on pkg.go.dev describes every exported type.

Limitations

  • No /fullcmc and no CMS error responses.
  • The router does not check the tls-unique value or revocation. The CA does.
  • TLS 1.3 has no tls-unique value, so ML-DSA renewals carry no binding.
  • Composite ML-DSA and SLH-DSA need host hooks and cannot renew over TLS.
  • estserver issues to anyone and is for testing only.

Known limitations explains each gap.

Credits

This project began as a fork of globalsign/est by GMO GlobalSign. The protocol implementation, both command line tools and the test server come from that project. The first fixes made here were offered upstream in globalsign/est#59 to globalsign/est#66.

This fork is maintained separately so fixes and new features ship in its own releases without waiting for upstream review. Changes that suit upstream are still offered there. NOTICE records the attribution.

Support

SUPPORT.md says where to ask questions and what to include in a bug report. Check Troubleshooting first. Report vulnerabilities privately as SECURITY.md describes. The Contributing Guide lists the development checks and the Code of conduct applies to every project space. CHANGELOG.md records the changes in each release and DEPENDENCIES.md lists the third-party modules and their licenses.

License

MIT License. See LICENSE and NOTICE.

Documentation

Overview

Package est provides an EST client and server as defined by RFC7030.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewRouter

func NewRouter(cfg *ServerConfig) (http.Handler, error)

NewRouter creates a new EST server mux. The additional path segment of a request may be at most 255 bytes, a longer one answers 414. The CA certificates of at most 1024 segments are kept for client certificate checks.

Example

ExampleNewRouter serves EST in front of a CA. The listener requests a client certificate without requiring one, so the same port serves first enrollments with a password and renewals with the certificate being renewed.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/subtle"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"errors"
	"log"
	"math/big"
	"net/http"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}

	// --8<-- [start:router]
	// One-time enrollment passwords, as an operator would issue them.
	passwords := map[string]string{"device-1": "one-time-secret"}

	router, err := est.NewRouter(&est.ServerConfig{
		CA:        ca,
		RateLimit: 50,
		CheckBasicAuth: func(ctx context.Context, r *http.Request, aps, username, password string) error {
			// A client certificate that crypto/tls verified needs no password.
			if r.TLS != nil && len(r.TLS.VerifiedChains) > 0 {
				return nil
			}
			want, ok := passwords[username]
			if !ok || subtle.ConstantTimeCompare([]byte(password), []byte(want)) != 1 {
				return errors.New("unknown user or wrong password")
			}
			return nil
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(ca.root)

	srv := &http.Server{
		Addr:    ":8443",
		Handler: router,
		TLSConfig: &tls.Config{
			MinVersion: tls.VersionTLS12,
			ClientAuth: tls.VerifyClientCertIfGiven,
			ClientCAs:  clientCAs,
		},
		ReadHeaderTimeout: 30 * time.Second,
	}
	log.Fatal(srv.ListenAndServeTLS("server-chain.pem", "server-key.pem"))
	// --8<-- [end:router]
}

func SRPUsernameFromContext

func SRPUsernameFromContext(ctx context.Context) string

SRPUsernameFromContext returns the username set by WithSRPUsername, or an empty string if the request did not sign in with TLS-SRP.

func WithSRPUsername

func WithSRPUsername(ctx context.Context, username string) context.Context

WithSRPUsername returns a copy of ctx that carries the username a client proved in a TLS-SRP handshake (RFC 5054). A server that terminates TLS-SRP sets it on each request before the router handles it. The router then accepts /simplereenroll without a client certificate, as libest does. An empty username returns ctx unchanged.

Example

ExampleWithSRPUsername serves EST over TLS-SRP and enrolls and renews with a username and password instead of certificates.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"errors"
	"fmt"
	"log"
	"math/big"
	"net"
	"net/http"
	"time"

	srptls "github.com/misiektoja/go-tls-srp"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// newCSR returns a certificate request for key with the given common name.
func newCSR(key crypto.Signer, commonName string) (*x509.CertificateRequest, error) {
	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: commonName}}, key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificateRequest(der)
}

// srpConnKey is the request context key of the TLS-SRP connection.
type srpConnKey struct{}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}

	// --8<-- [start:srp-server]
	// A real host stores the salt and verifier when it registers the device, never the password.
	group, err := srptls.GroupByBits(3072)
	if err != nil {
		log.Fatal(err)
	}
	salt, err := srptls.NewSalt(rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	verifier, err := srptls.NewVerifier(group, []byte("device-5"), []byte("srp-secret"), salt)
	if err != nil {
		log.Fatal(err)
	}

	ln, err := srptls.Listen("tcp", "127.0.0.1:0", &srptls.Config{
		GetVerifier: func(info *srptls.ClientHelloInfo) (*srptls.Verifier, error) {
			if info.Username != "device-5" {
				return nil, srptls.ErrUnknownUsername
			}
			return verifier, nil
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	router, err := est.NewRouter(&est.ServerConfig{
		CA: ca,
		CheckBasicAuth: func(ctx context.Context, r *http.Request, aps, username, password string) error {
			if est.SRPUsernameFromContext(ctx) == "" {
				return errors.New("sign in with TLS-SRP")
			}
			return nil
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	srv := &http.Server{
		// net/http sets Request.TLS only for crypto/tls, so the handler reads the TLS-SRP
		// connection from the context and passes the username to the router.
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			conn, ok := r.Context().Value(srpConnKey{}).(*srptls.Conn)
			if !ok {
				http.Error(w, "no TLS-SRP connection", http.StatusInternalServerError)
				return
			}
			ctx := est.WithSRPUsername(r.Context(), conn.ConnectionState().SRPUsername)
			router.ServeHTTP(w, r.WithContext(ctx))
		}),
		ConnContext: func(ctx context.Context, c net.Conn) context.Context {
			return context.WithValue(ctx, srpConnKey{}, c)
		},
		// net/http logs handshake failures only for crypto/tls. Handshake returns the stored
		// error of a failed handshake.
		ConnState: func(c net.Conn, state http.ConnState) {
			conn, ok := c.(*srptls.Conn)
			if !ok || state != http.StateClosed || conn.ConnectionState().HandshakeComplete {
				return
			}
			if err := conn.Handshake(); err != nil {
				log.Printf("TLS-SRP handshake from %s failed: %v", c.RemoteAddr(), err)
			}
		},
		// The handshake runs in the first read, so this also bounds it.
		ReadHeaderTimeout: 30 * time.Second,
	}
	go func() { _ = srv.Serve(ln) }()
	// --8<-- [end:srp-server]

	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	csr, err := newCSR(key, "device-5")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	// --8<-- [start:srp-client]
	client := &est.Client{
		Host:        ln.Addr().String(),
		SRPUsername: "device-5",
		SRPPassword: "srp-secret",
	}

	cert, err := client.Enroll(ctx, csr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("enrolled:", cert.Subject.CommonName)

	// The password signs the client in, so no client certificate is needed.
	renewed, err := client.Reenroll(ctx, csr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("renewed:", renewed.Subject.CommonName)
	// --8<-- [end:srp-client]

	_ = srv.Close()

}
Output:
enrolled: device-5
renewed: device-5

Types

type Attribute

type Attribute struct {
	Type   asn1.ObjectIdentifier
	Values AttributeValueSET
}

Attribute is a CSR Attribute type, as defined by RFC7030 4.5.2.

type AttributeValueSET

type AttributeValueSET []interface{}

AttributeValueSET is an ASN.1 SET of CSR attribute values.

type CA

type CA interface {
	// CACerts requests a copy of the current CA certificates. See RFC7030 4.1.
	CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error)

	// CSRAttrs requests a list of CA-desired CSR attributes. The returned list
	// may be empty. See RFC7030 4.5.
	CSRAttrs(ctx context.Context, aps string, r *http.Request) (CSRAttrs, error)

	// Enroll requests a new certificate. See RFC7030 4.2.
	Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error)

	// Reenroll requests renewal/rekey of an existing certificate. See RFC7030
	// 4.2. cert is the TLS client certificate being renewed. The server has
	// checked that it chains to the certificates CACerts returned, is within
	// its validity period and allows client authentication or has let
	// ServerConfig.VerifyClientCertificate decide. It does not check
	// revocation, so a CA that revokes certificates must refuse a revoked
	// one here. cert is nil when the client sent no certificate and signed
	// in with TLS-SRP or, with ServerConfig.PasswordRenewal, with HTTP Basic
	// credentials or a bearer token. Then the CA decides which certificate
	// is renewed and must choose it by the signed-in identity, not by the
	// Subject of csr, which any user could name. SRPUsernameFromContext
	// returns the TLS-SRP username, r.BasicAuth the HTTP Basic one and the
	// Authorization header the bearer token.
	Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error)

	// ServerKeyGen requests a new certificate and a private key. The key must
	// be returned as a DER-encoded PKCS8 PrivateKeyInfo structure if additional
	// encryption is not being employed, or returned inside a CMS SignedData
	// structure which itself is inside a CMS EnvelopedData structure. See
	// RFC7030 4.4.
	ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error)

	// TPMEnroll requests a new certificate using the TPM 2.0 privacy-preserving
	// protocol. An EK certificate chain with a length of at least one must be
	// provided, along with the EK and AK public areas. The return values are an
	// encrypted credential blob, an encrypted seed, and the certificate itself
	// inside a CMS EnvelopedData encrypted with the credential as a pre-shared
	// key.
	TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error)
}

CA is a Certificate Authority backing an EST server. The server can be connected to any backing CA by providing an implementation of this interface.

All operations receive:

  • a context, from which the EST server logger can be retrieved by calling LoggerFromContext
  • the optional URI additional path segment (RFC7030 3.2.2)
  • the HTTP request object from the server, from which the HTTP headers passed by the client (including the Host header, to support virtual servers) can be obtained

Any error object returned from these functions which implements Error will be used by the EST server to determine the HTTP response code, human-readable error description, and Retry-After header value, if applicable. Any other error will be treated as an internal server error.

type CSRAttrs

type CSRAttrs struct {
	OIDs       []asn1.ObjectIdentifier
	Attributes []Attribute
}

CSRAttrs contains CSR attributes as defined by RFC7030 4.5.

CSR attributes are defined by RFC7030 as a sequence of AttrOrOID, where AttrOrOID is a CHOICE of Object Identifier or Attribute. For ease of use, CRSAttrs provides separately a list of Object Identifiers, and a list of Attributes.

When the EST client retrieves and parses CSR attributes from an EST server, attribute values of the ASN.1 types: - OBJECT IDENTIFIER - BOOLEAN - INTEGER - most STRING types

will be unmarshalled into the Attribute.Values field as standard Go asn1.ObjectIdentifier, bool, *big.Int and string types where possible, and they can be retrieved via a type assertion. Other types will be unmarshalled into an asn1.RawValue structure and must be interpreted by the caller.

func (CSRAttrs) Marshal

func (a CSRAttrs) Marshal() ([]byte, error)

Marshal returns the ASN.1 DER-encoding of a value.

func (*CSRAttrs) Unmarshal

func (a *CSRAttrs) Unmarshal(b []byte) error

Unmarshal parses an DER-encoded ASN.1 data structure and stores the result in the object. Attribute values of the ASN.1 types: - OBJECT IDENTIFIER - BOOLEAN - INTEGER - most STRING types

will be unmarshalled into standard Go asn1.ObjectIdentifier, bool, *big.Int and string types where possible, and can be retrieved via a type assertion. Other types will be unmarshalled into an asn1.RawValue structure and must be interpreted by the caller.

type Client

type Client struct {
	// Host is the host:path of the EST server excluding any URL path
	// component, e.g. est.server.com:8443
	Host string

	// AdditionalPathSegment is an optional label for EST servers to provide
	// service for multiple CAs. See RFC7030 3.2.2.
	AdditionalPathSegment string

	// ExplicitAnchor is the optional Explicit TA database. See RFC7030 3.6.1.
	ExplicitAnchor *x509.CertPool

	// ImplicitAnchor is an optional Implicit TA database. If nil, the system
	// certificate pool will be used. See RFC7030 3.6.2.
	ImplicitAnchor *x509.CertPool

	// Certificates are the client certificates to present to the EST server
	// during the handshake. If more than one certificate is provided, they
	// should be provided in order, with the end-entity certificate first, and
	// the root CA (or last intermediate CA) certificate last.
	Certificates []*x509.Certificate

	// PrivateKey is the private key associated with the end-entity TLS
	// certificate. Any object implementing crypto.Signer may be used, to
	// support private keys resident on a hardware security module (HSM),
	// Trusted Platform Module (TPM) or other hardware device.
	PrivateKey interface{}

	// SigningKey is an optional private key to use for signing CSRs during initial enrollment.
	//
	// If not set, the challenge password field will not be included in the CSR.
	SigningKey interface{}

	// AdditionalHeaders are additional HTTP headers to include with the
	// request to the EST server.
	AdditionalHeaders map[string]string

	// HostHeader overrides the default Host header for the HTTP request to the
	// EST server, and is mostly useful for testing.
	HostHeader string

	// Username is an optional HTTP Basic Authentication username.
	Username string

	// Password is an optional HTTP Basic Authentication password.
	Password string

	// BearerToken is an optional HTTP Bearer authentication token (RFC
	// 6750). It is sent as "Authorization: Bearer <token>" when Username is
	// empty, so Basic authentication takes precedence.
	BearerToken string

	// DisableKeepAlives disables HTTP keep-alives if set.
	DisableKeepAlives bool

	// Proxy returns the proxy for the connection to the EST server, as
	// http.Transport.Proxy does, or nil for a direct connection. If Proxy
	// is nil, http.ProxyFromEnvironment applies, so the HTTPS_PROXY and
	// NO_PROXY environment variables choose the proxy. The client reaches
	// the server through an http or https proxy with a CONNECT tunnel, so
	// the TLS handshake, OnConnect and the tls-unique value work as without
	// a proxy. The user information of the proxy URL is sent as Basic
	// Proxy-Authorization. An https proxy is checked against the system
	// roots.
	Proxy func(*http.Request) (*url.URL, error)

	// InsecureSkipVerify controls whether the client verifies the EST server's
	// certificate chain and host name. If true, the client accepts any
	// certificate presented by the server and any host name in that certificate.
	// In this mode, TLS is susceptible to man-in-the-middle attacks. This should
	// be used only for testing. If used to obtain the CA certificates from an
	// otherwise untrusted EST server, those certificates must be manually
	// verified in some out-of-band manner before any further EST operations with
	// that server are performed.
	InsecureSkipVerify bool

	// WrapTransport, if set, wraps the HTTP transport of every request. The
	// wrapper sees each request and response, for example to record a
	// protocol trace, and must pass every request on to the transport it
	// wraps. The transport it wraps already bounds response bodies with
	// MaxResponseBody.
	WrapTransport func(http.RoundTripper) http.RoundTripper

	// OnConnect, if set, is called with the connection of each operation
	// after the TLS handshake and before the request is sent. The connection
	// is a *tls.Conn, or a *srptls.Conn with TLS-SRP. OnConnect must not read
	// from, write to or close it.
	OnConnect func(net.Conn)

	// AllowCertificateChain accepts an enroll, reenroll or serverkeygen
	// response that carries CA certificates besides the issued certificate.
	// RFC 7030 section 4.2.3 allows only the issued certificate, but some
	// servers add its chain. The client then returns the one certificate
	// that issued none of the others.
	AllowCertificateChain bool

	// MaxResponseBody bounds the size of a response body in bytes, including
	// an error message and all parts of a multipart response. A larger
	// response fails the operation. If zero, 1 MiB is used. A chain of large
	// post-quantum CA certificates can exceed that, such as SLH-DSA-SHA2-256f
	// certificates at about 67 KB each in base64. A negative value fails
	// every operation.
	MaxResponseBody int64

	// SRPUsername, if set, signs in with TLS-SRP (RFC 5054) as this user
	// with SRPPassword, as RFC 7030 section 3.3.3 allows. The password also
	// authenticates the server, so ExplicitAnchor, ImplicitAnchor,
	// InsecureSkipVerify and Certificates are not used. TLS-SRP runs over
	// TLS 1.2 only. OnConnect then receives a *srptls.Conn from
	// github.com/misiektoja/go-tls-srp.
	SRPUsername string

	// SRPPassword is the TLS-SRP password of SRPUsername.
	SRPPassword string

	// SRPMinGroupBits is the size of the smallest SRP group the client
	// accepts from the server. If zero, 2048 bits.
	SRPMinGroupBits int
}

Client is an EST client implementing the Enrollment over Secure Transport protocol as defined in RFC7030.

All EST client operations will return an error object implementing Error when the EST server returns any status other than 200 OK. The status code, description and, if applicable, retry-after seconds can be extracted from that object. In order to make the retry-after seconds available through this mechanism, note that a 202 Accepted response to enroll and reenroll operations is returned as an error for this purpose, even though 2** status codes indicate success.

Example

ExampleClient fetches the CA certificates, enrolls a new key and renews the certificate over a connection that the certificate being renewed authenticates.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"fmt"
	"log"
	"math/big"
	"net/http"
	"net/http/httptest"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// startExampleServer serves the router for cfg over TLS on a local port. Clients may present a
// certificate that chains to the example CA root.
func startExampleServer(ca *exampleCA, cfg *est.ServerConfig) (*httptest.Server, error) {
	cfg.CA = ca
	router, err := est.NewRouter(cfg)
	if err != nil {
		return nil, err
	}
	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(ca.root)
	srv := httptest.NewUnstartedServer(router)
	srv.TLS = &tls.Config{ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: clientCAs}
	srv.StartTLS()
	return srv, nil
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}
	srv, err := startExampleServer(ca, &est.ServerConfig{})
	if err != nil {
		log.Fatal(err)
	}
	anchor := x509.NewCertPool()
	anchor.AddCert(srv.Certificate())
	host := srv.Listener.Addr().String()

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)

	// --8<-- [start:client-enroll]
	client := &est.Client{
		Host:           host,
		ExplicitAnchor: anchor,
	}

	cacerts, err := client.CACerts(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("CA:", cacerts[0].Subject.CommonName)

	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
		Subject:  pkix.Name{CommonName: "device-1"},
		DNSNames: []string{"device-1.example.com"},
	}, key)
	if err != nil {
		log.Fatal(err)
	}
	csr, err := x509.ParseCertificateRequest(der)
	if err != nil {
		log.Fatal(err)
	}

	cert, err := client.Enroll(ctx, csr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("enrolled:", cert.Subject.CommonName, cert.DNSNames)
	// --8<-- [end:client-enroll]

	// --8<-- [start:client-reenroll]
	// The certificate being renewed authenticates the TLS connection.
	client.Certificates = []*x509.Certificate{cert}
	client.PrivateKey = key

	// The request repeats the Subject and SubjectAltName of the certificate.
	der, err = x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
		RawSubject: cert.RawSubject,
		DNSNames:   cert.DNSNames,
	}, key)
	if err != nil {
		log.Fatal(err)
	}
	csr, err = x509.ParseCertificateRequest(der)
	if err != nil {
		log.Fatal(err)
	}

	renewed, err := client.Reenroll(ctx, csr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("renewed:", renewed.Subject.CommonName, renewed.SerialNumber.Cmp(cert.SerialNumber) != 0)
	// --8<-- [end:client-reenroll]

	cancel()
	srv.Close()

}
Output:
CA: Example EST CA
enrolled: device-1 [device-1.example.com]
renewed: device-1 true
Example (Hooks)

ExampleClient_hooks traces each request and reports the TLS version of each connection.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"fmt"
	"log"
	"math/big"
	"net"
	"net/http"
	"net/http/httptest"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// startExampleServer serves the router for cfg over TLS on a local port. Clients may present a
// certificate that chains to the example CA root.
func startExampleServer(ca *exampleCA, cfg *est.ServerConfig) (*httptest.Server, error) {
	cfg.CA = ca
	router, err := est.NewRouter(cfg)
	if err != nil {
		return nil, err
	}
	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(ca.root)
	srv := httptest.NewUnstartedServer(router)
	srv.TLS = &tls.Config{ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: clientCAs}
	srv.StartTLS()
	return srv, nil
}

// exampleClient returns a client for srv that trusts the test server certificate.
func exampleClient(srv *httptest.Server) *est.Client {
	anchor := x509.NewCertPool()
	anchor.AddCert(srv.Certificate())
	return &est.Client{Host: srv.Listener.Addr().String(), ExplicitAnchor: anchor}
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}
	srv, err := startExampleServer(ca, &est.ServerConfig{})
	if err != nil {
		log.Fatal(err)
	}
	client := exampleClient(srv)

	// --8<-- [start:hooks]
	client.OnConnect = func(conn net.Conn) {
		if c, ok := conn.(*tls.Conn); ok {
			fmt.Println("connected with", tls.VersionName(c.ConnectionState().Version))
		}
	}
	client.WrapTransport = func(next http.RoundTripper) http.RoundTripper {
		return roundTripFunc(func(r *http.Request) (*http.Response, error) {
			resp, err := next.RoundTrip(r)
			if err == nil {
				fmt.Println(r.Method, r.URL.Path, resp.Status)
			}
			return resp, err
		})
	}
	// --8<-- [end:hooks]

	if _, err := client.CACerts(context.Background()); err != nil {
		log.Fatal(err)
	}

	srv.Close()

}

// roundTripFunc adapts a function to http.RoundTripper.
type roundTripFunc func(*http.Request) (*http.Response, error)

// RoundTrip calls f.
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
Output:
connected with TLS 1.3
GET /.well-known/est/cacerts 200 OK
Example (Mldsa)

ExampleClient_mldsa enrolls an ML-DSA-65 key and renews the certificate over TLS 1.3, which accepts an ML-DSA client certificate.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/mldsa"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"fmt"
	"log"
	"math/big"
	"net"
	"net/http"
	"net/http/httptest"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// startExampleServer serves the router for cfg over TLS on a local port. Clients may present a
// certificate that chains to the example CA root.
func startExampleServer(ca *exampleCA, cfg *est.ServerConfig) (*httptest.Server, error) {
	cfg.CA = ca
	router, err := est.NewRouter(cfg)
	if err != nil {
		return nil, err
	}
	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(ca.root)
	srv := httptest.NewUnstartedServer(router)
	srv.TLS = &tls.Config{ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: clientCAs}
	srv.StartTLS()
	return srv, nil
}

// exampleClient returns a client for srv that trusts the test server certificate.
func exampleClient(srv *httptest.Server) *est.Client {
	anchor := x509.NewCertPool()
	anchor.AddCert(srv.Certificate())
	return &est.Client{Host: srv.Listener.Addr().String(), ExplicitAnchor: anchor}
}

// newCSR returns a certificate request for key with the given common name.
func newCSR(key crypto.Signer, commonName string) (*x509.CertificateRequest, error) {
	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: commonName}}, key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificateRequest(der)
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}
	srv, err := startExampleServer(ca, &est.ServerConfig{})
	if err != nil {
		log.Fatal(err)
	}
	client := exampleClient(srv)
	ctx := context.Background()

	// --8<-- [start:mldsa]
	key, err := mldsa.GenerateKey(mldsa.MLDSA65())
	if err != nil {
		log.Fatal(err)
	}
	csr, err := newCSR(key, "device-8")
	if err != nil {
		log.Fatal(err)
	}
	cert, err := client.Enroll(ctx, csr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("enrolled: %s with %T\n", cert.Subject.CommonName, cert.PublicKey)

	// The ML-DSA certificate authenticates the renewal.
	client.Certificates = []*x509.Certificate{cert}
	client.PrivateKey = key
	client.OnConnect = func(conn net.Conn) {
		fmt.Println("renewing over", tls.VersionName(conn.(*tls.Conn).ConnectionState().Version))
	}
	renewed, err := client.Reenroll(ctx, csr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("renewed:", renewed.Subject.CommonName)
	// --8<-- [end:mldsa]

	srv.Close()

}
Output:
enrolled: device-8 with *mldsa.PublicKey
renewing over TLS 1.3
renewed: device-8
Example (Proxy)

ExampleClient_proxy configures a client that reaches the server through an HTTP proxy and signs in with a bearer token. It is compiled but not run.

package main

import (
	"log"
	"net/http"
	"net/url"

	est "github.com/misiektoja/go-pki-est"
)

func main() {
	// --8<-- [start:proxy]
	proxyURL, err := url.Parse("http://proxy-user:proxy-secret@proxy.example.com:3128")
	if err != nil {
		log.Fatal(err)
	}
	client := &est.Client{
		Host:        "est.example.com:8443",
		Proxy:       http.ProxyURL(proxyURL),
		BearerToken: "token-from-the-identity-provider",
	}
	// --8<-- [end:proxy]
	_ = client
}

func (*Client) CACerts

func (c *Client) CACerts(ctx context.Context) ([]*x509.Certificate, error)

CACerts requests a copy of the current CA certificates.

func (*Client) CSRAttrs

func (c *Client) CSRAttrs(ctx context.Context) (CSRAttrs, error)

CSRAttrs requests a list of CA-desired CSR attributes.

Example

ExampleClient_CSRAttrs asks the server which attributes it wants in a request.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"fmt"
	"log"
	"math/big"
	"net/http"
	"net/http/httptest"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// startExampleServer serves the router for cfg over TLS on a local port. Clients may present a
// certificate that chains to the example CA root.
func startExampleServer(ca *exampleCA, cfg *est.ServerConfig) (*httptest.Server, error) {
	cfg.CA = ca
	router, err := est.NewRouter(cfg)
	if err != nil {
		return nil, err
	}
	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(ca.root)
	srv := httptest.NewUnstartedServer(router)
	srv.TLS = &tls.Config{ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: clientCAs}
	srv.StartTLS()
	return srv, nil
}

// exampleClient returns a client for srv that trusts the test server certificate.
func exampleClient(srv *httptest.Server) *est.Client {
	anchor := x509.NewCertPool()
	anchor.AddCert(srv.Certificate())
	return &est.Client{Host: srv.Listener.Addr().String(), ExplicitAnchor: anchor}
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}
	srv, err := startExampleServer(ca, &est.ServerConfig{})
	if err != nil {
		log.Fatal(err)
	}
	client := exampleClient(srv)
	ctx := context.Background()

	// --8<-- [start:csrattrs]
	attrs, err := client.CSRAttrs(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, oid := range attrs.OIDs {
		fmt.Println("OID:", oid)
	}
	for _, attr := range attrs.Attributes {
		fmt.Println("attribute:", attr.Type, attr.Values)
	}
	// --8<-- [end:csrattrs]

	srv.Close()

}
Output:
attribute: 1.2.840.10045.2.1 [1.3.132.0.34]

func (*Client) Enroll

Enroll requests a new certificate.

func (*Client) Reenroll

Reenroll renews an existing certificate.

func (*Client) ServerKeyGen

func (c *Client) ServerKeyGen(ctx context.Context, r *x509.CertificateRequest) (*x509.Certificate, []byte, error)

ServerKeyGen requests a new certificate and a server-generated private key.

Example

ExampleClient_ServerKeyGen asks the server to generate the private key.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"fmt"
	"log"
	"math/big"
	"net/http"
	"net/http/httptest"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// startExampleServer serves the router for cfg over TLS on a local port. Clients may present a
// certificate that chains to the example CA root.
func startExampleServer(ca *exampleCA, cfg *est.ServerConfig) (*httptest.Server, error) {
	cfg.CA = ca
	router, err := est.NewRouter(cfg)
	if err != nil {
		return nil, err
	}
	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(ca.root)
	srv := httptest.NewUnstartedServer(router)
	srv.TLS = &tls.Config{ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: clientCAs}
	srv.StartTLS()
	return srv, nil
}

// exampleClient returns a client for srv that trusts the test server certificate.
func exampleClient(srv *httptest.Server) *est.Client {
	anchor := x509.NewCertPool()
	anchor.AddCert(srv.Certificate())
	return &est.Client{Host: srv.Listener.Addr().String(), ExplicitAnchor: anchor}
}

// newCSR returns a certificate request for key with the given common name.
func newCSR(key crypto.Signer, commonName string) (*x509.CertificateRequest, error) {
	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: commonName}}, key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificateRequest(der)
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}
	srv, err := startExampleServer(ca, &est.ServerConfig{})
	if err != nil {
		log.Fatal(err)
	}
	client := exampleClient(srv)
	ctx := context.Background()

	// --8<-- [start:serverkeygen]
	// The request carries the names. The server ignores its key, so a throwaway key signs it.
	throwaway, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	csr, err := newCSR(throwaway, "device-2")
	if err != nil {
		log.Fatal(err)
	}

	cert, keyDER, err := client.ServerKeyGen(ctx, csr)
	if err != nil {
		log.Fatal(err)
	}
	// Without additional encryption the key is PKCS #8.
	key, err := x509.ParsePKCS8PrivateKey(keyDER)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("certificate: %s\nkey: %T\n", cert.Subject.CommonName, key)
	// --8<-- [end:serverkeygen]

	srv.Close()

}
Output:
certificate: device-2
key: *ecdsa.PrivateKey

func (*Client) TPMEnroll

func (c *Client) TPMEnroll(
	ctx context.Context,
	r *x509.CertificateRequest,
	ekCerts []*x509.Certificate,
	ekPub []byte,
	akPub []byte,
) ([]byte, []byte, []byte, error)

TPMEnroll requests a certificate using the TPM 2.0 privacy preserving protocol for distributing credentials for keys on a TPM.

type Error

type Error interface {
	// StatusCode returns the HTTP status code.
	StatusCode() int

	// Error returns a human-readable description of the error.
	Error() string

	// RetryAfter returns the value in seconds after which the client should
	// retry the request.
	RetryAfter() int
}

Error represents an error which can be translated into an HTTP status code and message, and optionally specify a Retry-After period.

Example

ExampleError reads the status and the Retry-After value of a deferred enrollment.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"errors"
	"fmt"
	"log"
	"math/big"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// exampleClient returns a client for srv that trusts the test server certificate.
func exampleClient(srv *httptest.Server) *est.Client {
	anchor := x509.NewCertPool()
	anchor.AddCert(srv.Certificate())
	return &est.Client{Host: srv.Listener.Addr().String(), ExplicitAnchor: anchor}
}

// newCSR returns a certificate request for key with the given common name.
func newCSR(key crypto.Signer, commonName string) (*x509.CertificateRequest, error) {
	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: commonName}}, key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificateRequest(der)
}

// approvalCA defers every enrollment until an operator approves it.
type approvalCA struct {
	*exampleCA
}

// Enroll answers 202 Accepted and asks the client to retry in ten minutes.
func (ca approvalCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return nil, caError{status: http.StatusAccepted, msg: "waiting for approval", retryAfter: 600}
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}
	router, err := est.NewRouter(&est.ServerConfig{CA: approvalCA{ca}})
	if err != nil {
		log.Fatal(err)
	}
	srv := httptest.NewTLSServer(router)
	client := exampleClient(srv)
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	csr, err := newCSR(key, "device-6")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	// --8<-- [start:error]
	_, err = client.Enroll(ctx, csr)
	if estErr, ok := errors.AsType[est.Error](err); ok {
		fmt.Println("status:", estErr.StatusCode())
		fmt.Println("retry after:", estErr.RetryAfter())
		fmt.Println("message:", strings.TrimSpace(estErr.Error()))
	}
	// --8<-- [end:error]

	srv.Close()

}
Output:
status: 202
retry after: 600
message: 202 waiting for approval

type Logger

type Logger interface {
	// Errorf uses fmt.Sprintf to log a formatted message.
	Errorf(format string, args ...interface{})

	// Errorw logs a message with some additional context. The variadic
	// key-value pairs are treated as they are in With.
	Errorw(format string, keysAndValues ...interface{})

	// Infof uses fmt.Sprintf to log a formatted message.
	Infof(format string, args ...interface{})

	// Infow logs a message with some additional context. The variadic
	// key-value pairs are treated as they are in With.
	Infow(format string, keysAndValues ...interface{})

	// With adds a variadic number of key-values pairs to the logging context.
	// The first element of the pair is used as the field key and should be a
	// string. Passing a non-string key or passing an orphaned key panics.
	With(keysAndValues ...interface{}) Logger
}

Logger is an interface for an EST server logger.

func LoggerFromContext

func LoggerFromContext(ctx context.Context) Logger

LoggerFromContext returns a logger included in a context.

type Refusal

type Refusal struct {
	// Operation is the last segment of the request path, such as
	// "simpleenroll" or "simplereenroll".
	Operation string

	// AdditionalPathSegment is the optional label from the request path.
	AdditionalPathSegment string

	// Status is the HTTP status code sent to the client.
	Status int

	// Reason is the error text sent to the client.
	Reason string

	// Request is the refused request. Its body may already have been read.
	Request *http.Request
}

Refusal describes a request the server refused without asking the CA.

type RefusalRecorder

type RefusalRecorder interface {
	RecordRefusal(ctx context.Context, refusal Refusal) error
}

RefusalRecorder records the requests the server refuses without asking the CA, such as a malformed request, an unsupported content type or a renewal whose subject changed. Authentication failures from CheckBasicAuth and errors returned by the CA are not reported, because the host made those decisions. Server faults are not reported either.

RecordRefusal runs before the response is written, with a context that is not cancelled when the client disconnects, so it must bound its own work. A returned error is logged and does not change the response.

Example

ExampleRefusalRecorder records a renewal that the server refuses because the client sent no certificate.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"fmt"
	"log"
	"math/big"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// startExampleServer serves the router for cfg over TLS on a local port. Clients may present a
// certificate that chains to the example CA root.
func startExampleServer(ca *exampleCA, cfg *est.ServerConfig) (*httptest.Server, error) {
	cfg.CA = ca
	router, err := est.NewRouter(cfg)
	if err != nil {
		return nil, err
	}
	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(ca.root)
	srv := httptest.NewUnstartedServer(router)
	srv.TLS = &tls.Config{ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: clientCAs}
	srv.StartTLS()
	return srv, nil
}

// exampleClient returns a client for srv that trusts the test server certificate.
func exampleClient(srv *httptest.Server) *est.Client {
	anchor := x509.NewCertPool()
	anchor.AddCert(srv.Certificate())
	return &est.Client{Host: srv.Listener.Addr().String(), ExplicitAnchor: anchor}
}

// newCSR returns a certificate request for key with the given common name.
func newCSR(key crypto.Signer, commonName string) (*x509.CertificateRequest, error) {
	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: commonName}}, key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificateRequest(der)
}

// --8<-- [start:refusals]
// printRefusals prints each request the server refuses without asking the CA.
type printRefusals struct{}

// RecordRefusal prints the operation, the status and the reason.
func (printRefusals) RecordRefusal(ctx context.Context, refusal est.Refusal) error {
	fmt.Printf("refused %s: %d %s\n", refusal.Operation, refusal.Status, refusal.Reason)
	return nil
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}
	srv, err := startExampleServer(ca, &est.ServerConfig{Refusals: printRefusals{}})
	if err != nil {
		log.Fatal(err)
	}
	client := exampleClient(srv)
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	csr, err := newCSR(key, "device-7")
	if err != nil {
		log.Fatal(err)
	}

	if _, err := client.Reenroll(context.Background(), csr); err != nil {
		fmt.Println("client:", strings.TrimSpace(err.Error()))
	}

	srv.Close()

}
Output:
refused simplereenroll: 403 client certificate must be provided for /simplereenroll
client: 403 client certificate must be provided for /simplereenroll

type ServerConfig

type ServerConfig struct {
	// CA is an interface to the Certificate Authority backing the EST server.
	CA CA

	// Logger is an optional logger. The logger can be retrieved by the backing
	// CA from the HTTP request context using LoggerFromContext.
	Logger Logger

	// Timeout sets a request timeout. If zero, a reasonable default will be
	// used.
	Timeout time.Duration

	// AllowedHosts is an optional list of fully-qualified domain names
	// representing hosts which are allowed to serve the EST service.
	AllowedHosts []string

	// RateLimit is an optional rate limit expressed in requests per second.
	// If zero, no rate limit will be applied. NewRouter refuses a negative
	// value.
	RateLimit int

	// CheckBasicAuth is an optional callback function to check HTTP Basic
	// Authentication credentials. It runs for every enrollment request that
	// CheckBearerToken does not check, with empty credentials when the
	// request carries no HTTP Basic credentials, so it can also accept a TLS
	// client certificate from the request. A nil error means that
	// authentication was successful. An error that implements Error with a
	// status other than 401, such as 403 or 429, is sent as is with its
	// Retry-After value. Any other error answers 401 with a Basic challenge.
	// On a TLS-SRP connection, SRPUsernameFromContext(ctx) returns the
	// username the client signed in with. If CheckBasicAuth is nil, then HTTP
	// Basic Authentication is not required for any EST operation. The
	// /healthcheck endpoint then only answers a request CheckBearerToken
	// accepts.
	CheckBasicAuth func(ctx context.Context, r *http.Request, aps, username, password string) error

	// CheckBearerToken is an optional callback function to check the token of
	// an "Authorization: Bearer" header (RFC 6750). It runs in place of
	// CheckBasicAuth for every request that carries one. Its errors are
	// handled like those of CheckBasicAuth. The 401 answer also carries a
	// Bearer challenge. If CheckBearerToken is nil, a bearer token is not
	// checked: CheckBasicAuth runs with empty credentials, as for a request
	// without an Authorization header. The token then does not sign the
	// client in for PasswordRenewal.
	CheckBearerToken func(ctx context.Context, r *http.Request, aps, token string) error

	// PasswordRenewal lets /simplereenroll accept a request without a TLS
	// client certificate when it carries HTTP Basic credentials with a
	// username that CheckBasicAuth accepted or a bearer token that
	// CheckBearerToken accepted. RFC 7030 section 2.3 allows this when the
	// certificate being renewed cannot be used for TLS client authentication,
	// such as a composite ML-DSA certificate. The CA receives a nil
	// certificate and decides which certificate is renewed. NewRouter refuses
	// it without CheckBasicAuth or CheckBearerToken. It defaults to false.
	PasswordRenewal bool

	// CheckCSRSignature optionally verifies the signature of each PKCS#10
	// request to /simpleenroll and /simplereenroll. /serverkeygen ignores the
	// signature, as RFC 7030 section 4.4.1 requires. If nil, the server uses
	// (*x509.CertificateRequest).CheckSignature, which refuses algorithms
	// crypto/x509 cannot verify, such as composite ML-DSA. crypto/x509 leaves
	// PublicKey nil for keys it does not know. An error that implements Error
	// is sent as is. Any other error answers 400.
	CheckCSRSignature func(csr *x509.CertificateRequest) error

	// VerifyClientCertificate optionally checks the TLS client certificate of
	// a /simplereenroll request in place of the built-in check, which verifies
	// it with crypto/x509 against the certificates CACerts returns. crypto/x509
	// cannot verify a certificate signed by some post-quantum CAs, such as an
	// SLH-DSA or composite ML-DSA CA. The Subject and SubjectAltName
	// comparison with the request runs first. A nil error accepts the
	// certificate. An error that implements Error is sent as is. Any other
	// error answers 403. The TLS listener must request the certificate
	// without verifying it, for example with tls.RequestClientCert, because
	// crypto/tls would otherwise refuse the handshake first.
	VerifyClientCertificate func(ctx context.Context, r *http.Request, aps string, cert *x509.Certificate) error

	// Refusals optionally receives the requests the server refuses itself,
	// before or instead of calling the CA.
	Refusals RefusalRecorder

	// OmitTransferEncoding leaves the Content-Transfer-Encoding header out of
	// responses and their multipart parts. Bodies stay base64 encoded. RFC 8951
	// tells receivers to ignore the header. Some clients fail when it is
	// present.
	OmitTransferEncoding bool

	// OmitStrictTransportSecurity leaves the Strict-Transport-Security header
	// out of responses, so the host can send its own value or none. A browser
	// that has stored the header refuses certificate warnings for the host
	// name on every port. It defaults to false, which sends max-age=31536000.
	OmitStrictTransportSecurity bool

	// MaxRequestBody bounds the size of a request body in bytes. Larger
	// requests are refused with 413. If zero, 64 KiB is used. A CSR for a
	// large post-quantum key can exceed that, such as an SLH-DSA-SHA2-256f
	// request at about 67 KB in base64. NewRouter refuses a negative value.
	// Keep it below 4 MiB: /tpmenroll decodes its PKCS#7 part with a parser
	// that recurses once per nested structure. A structure nested about
	// 10 MB deep exhausts the stack and ends the process.
	MaxRequestBody int64

	// TrustProxyHeaders sets the request's RemoteAddr from the X-Real-IP or
	// X-Forwarded-For header. It defaults to false. Enable it only when every
	// request passes through a trusted proxy that removes or overwrites both
	// headers. Proxy source addresses are not checked.
	TrustProxyHeaders bool
}

ServerConfig contains EST server configuration options.

Example (PasswordRenewal)

ExampleServerConfig_passwordRenewal renews a certificate with HTTP Basic credentials instead of a TLS client certificate.

package main

import (
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/subtle"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"errors"
	"fmt"
	"log"
	"math/big"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	est "github.com/misiektoja/go-pki-est"
)

// exampleCA is a minimal in-memory CA with a self-signed root that signs every certificate.
type exampleCA struct {
	root *x509.Certificate
	key  crypto.Signer
}

// newExampleCA creates an exampleCA with a new P-256 root.
func newExampleCA() (*exampleCA, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example EST CA"},
		NotBefore:             time.Now().Add(-time.Minute),
		NotAfter:              time.Now().Add(24 * time.Hour),
		KeyUsage:              x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
	if err != nil {
		return nil, err
	}
	root, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, err
	}
	return &exampleCA{root: root, key: key}, nil
}

// --8<-- [start:ca]
// caError is an error with an HTTP status. The server sends its status, message and Retry-After
// value to the client.
type caError struct {
	status     int
	msg        string
	retryAfter int
}

// Error returns the message sent to the client.
func (e caError) Error() string { return e.msg }

// StatusCode returns the HTTP status of the response.
func (e caError) StatusCode() int { return e.status }

// RetryAfter returns the Retry-After value in seconds, or 0 for none.
func (e caError) RetryAfter() int { return e.retryAfter }

// CACerts returns the certificates clients use as trust anchors.
func (ca *exampleCA) CACerts(ctx context.Context, aps string, r *http.Request) ([]*x509.Certificate, error) {
	return []*x509.Certificate{ca.root}, nil
}

// CSRAttrs asks clients for a P-384 key, using the example of RFC 7030 section 4.5.2.
func (ca *exampleCA) CSRAttrs(ctx context.Context, aps string, r *http.Request) (est.CSRAttrs, error) {
	return est.CSRAttrs{
		Attributes: []est.Attribute{{
			Type:   asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1},
			Values: est.AttributeValueSET{asn1.ObjectIdentifier{1, 3, 132, 0, 34}},
		}},
	}, nil
}

// Enroll issues a certificate for the key in the request.
func (ca *exampleCA) Enroll(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	return ca.issue(csr, csr.PublicKey)
}

// Reenroll renews a certificate. cert is nil when the client signed in with TLS-SRP or, with
// PasswordRenewal, with a password or bearer token instead of the certificate being renewed.
func (ca *exampleCA) Reenroll(ctx context.Context, cert *x509.Certificate, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, error) {
	if cert == nil {

		user := est.SRPUsernameFromContext(ctx)
		if user == "" {
			user, _, _ = r.BasicAuth()
		}
		if user == "" || csr.Subject.CommonName != user {
			return nil, caError{status: http.StatusForbidden, msg: "renewal is limited to the signed-in user"}
		}
	}
	return ca.issue(csr, csr.PublicKey)
}

// ServerKeyGen generates a key for the client and returns it unencrypted as PKCS #8.
func (ca *exampleCA) ServerKeyGen(ctx context.Context, csr *x509.CertificateRequest, aps string, r *http.Request) (*x509.Certificate, []byte, error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}

	cert, err := ca.issue(csr, key.Public())
	if err != nil {
		return nil, nil, err
	}
	der, err := x509.MarshalPKCS8PrivateKey(key)
	if err != nil {
		return nil, nil, err
	}
	return cert, der, nil
}

// TPMEnroll refuses TPM enrollment, which this CA does not offer.
func (ca *exampleCA) TPMEnroll(ctx context.Context, csr *x509.CertificateRequest, ekcerts []*x509.Certificate, ekPub, akPub []byte, aps string, r *http.Request) ([]byte, []byte, []byte, error) {
	return nil, nil, nil, caError{status: http.StatusNotImplemented, msg: "TPM enrollment is not offered"}
}

// issue signs a certificate for pub with the Subject and SubjectAltName of csr. It copies both
// unchanged, because a renewal request must repeat them byte for byte.
func (ca *exampleCA) issue(csr *x509.CertificateRequest, pub crypto.PublicKey) (*x509.Certificate, error) {
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
	if err != nil {
		return nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		RawSubject:   csr.RawSubject,
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(12 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 17}) {
			tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, ext)
		}
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, pub, ca.key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(der)
}

// startExampleServer serves the router for cfg over TLS on a local port. Clients may present a
// certificate that chains to the example CA root.
func startExampleServer(ca *exampleCA, cfg *est.ServerConfig) (*httptest.Server, error) {
	cfg.CA = ca
	router, err := est.NewRouter(cfg)
	if err != nil {
		return nil, err
	}
	clientCAs := x509.NewCertPool()
	clientCAs.AddCert(ca.root)
	srv := httptest.NewUnstartedServer(router)
	srv.TLS = &tls.Config{ClientAuth: tls.VerifyClientCertIfGiven, ClientCAs: clientCAs}
	srv.StartTLS()
	return srv, nil
}

// exampleClient returns a client for srv that trusts the test server certificate.
func exampleClient(srv *httptest.Server) *est.Client {
	anchor := x509.NewCertPool()
	anchor.AddCert(srv.Certificate())
	return &est.Client{Host: srv.Listener.Addr().String(), ExplicitAnchor: anchor}
}

// newCSR returns a certificate request for key with the given common name.
func newCSR(key crypto.Signer, commonName string) (*x509.CertificateRequest, error) {
	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: commonName}}, key)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificateRequest(der)
}

func main() {
	ca, err := newExampleCA()
	if err != nil {
		log.Fatal(err)
	}
	passwords := map[string]string{"device-3": "renewal-secret"}

	// --8<-- [start:password-renewal-server]
	cfg := &est.ServerConfig{
		CheckBasicAuth: func(ctx context.Context, r *http.Request, aps, username, password string) error {
			want, ok := passwords[username]
			if !ok || subtle.ConstantTimeCompare([]byte(password), []byte(want)) != 1 {
				return errors.New("unknown user or wrong password")
			}
			return nil
		},
		PasswordRenewal: true,
	}
	// --8<-- [end:password-renewal-server]
	srv, err := startExampleServer(ca, cfg)
	if err != nil {
		log.Fatal(err)
	}
	client := exampleClient(srv)
	ctx := context.Background()
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		log.Fatal(err)
	}

	// --8<-- [start:password-renewal-client]
	client.Username = "device-3"
	client.Password = "renewal-secret"

	csr, err := newCSR(key, "device-3")
	if err != nil {
		log.Fatal(err)
	}
	renewed, err := client.Reenroll(ctx, csr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("renewed without a client certificate:", renewed.Subject.CommonName)

	// The CA refuses a request that names another subject.
	other, err := newCSR(key, "device-4")
	if err != nil {
		log.Fatal(err)
	}
	_, err = client.Reenroll(ctx, other)
	fmt.Println(strings.TrimSpace(err.Error()))
	// --8<-- [end:password-renewal-client]

	srv.Close()

}
Output:
renewed without a client certificate: device-3
403 renewal is limited to the signed-in user

Directories

Path Synopsis
cmd
estclient command
Application estclient is an EST client.
Application estclient is an EST client.
estserver command
Application estserver is a basic EST server for testing purposes.
Application estserver is a basic EST server for testing purposes.
internal
basiclogger
Package basiclogger provides a basic logger implementing est.Logger, for demonstration and testing purposes.
Package basiclogger provides a basic logger implementing est.Logger, for demonstration and testing purposes.
mockca
Package mockca provides a mock certificate authority for testing purposes.
Package mockca provides a mock certificate authority for testing purposes.
tpm
Package tpm provides TPM 2.0 credential-related functionality.
Package tpm provides TPM 2.0 credential-related functionality.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL