scep

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 14 Imported by: 0

README

go-pki-scep

GitHub Release Go Reference License Tests Interop Supply chain OpenSSF Scorecard

go-pki-scep is a Go implementation of the Simple Certificate Enrollment Protocol (SCEP, RFC 8894). Routers, VPN gateways, mobile device managers and other network devices use SCEP to request certificates from a CA. The module has three packages:

  • scep builds and parses SCEP messages and answers requests without any transport.
  • scepserver is an http.Handler that serves SCEP for a CA you implement.
  • scepclient enrolls, renews, polls and queries a SCEP server over HTTP.

The library handles message signatures and encryption, nonces, transaction IDs and the HTTP operations. Your code decides who may enroll, issues the certificates and keeps the state of the CA. The CMS layer comes from go-pkcs7.

Contents

Install

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

The module needs Go 1.27.4 or newer. Its only dependency is go-pkcs7.

Scope

Operation Server handler Client
GetCACaps and GetCACert Yes Yes
PKCSReq and RenewalReq Passed to the CA, which issues, keeps the request pending or refuses it Enroll and EnrollAndWait
UpdateReq Passed to the CA Message layer only
CertPoll Passed to the CA Poll
GetCert and GetCRL When the CA implements them GetCert and GetCRL
GetNextCACert and GetCACertChain When the CA implements them GetNextCACert and GetCACertChain

The scep package builds, parses and answers every RFC 8894 message type. sscep, the micromdm/scep client and server and EJBCA run against the module in CI, see Tested implementations. The API may still change before v1.0.0 as described in the Compatibility policy.

Getting started

A server implements scepserver.CA and mounts the handler. The CA decides who may enroll, for example by checking the challenge password of a PKCSReq:

handler, err := scepserver.NewHandler(myCA, scepserver.Options{Logger: slog.Default()})
if err != nil {
	log.Fatal(err)
}
http.Handle("/scep", handler)

A device fetches the CA certificates with GetCACert, checks them against a fingerprint it trusts and enrolls with EnrollAndWait from scepclient.

Getting started builds a local server and client in one file, enrolls and renews a certificate and names what to replace before production. That program is in examples/quickstart and runs with go run ./examples/quickstart. The package example in example_test.go shows the message layer without HTTP.

Documentation

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

The package documentation on pkg.go.dev describes every exported type and option. Repository files:

Limitations

  • Requests and answers use RSA key transport, so a requester signs with an RSA key and a CA without an RSA key needs an RSA RA certificate. A CSR may still carry an ECDSA key. Password-based encryption of answers (PasswordRecipientInfo) is not supported.
  • No storage. The CA keeps pending requests, issued certificates and CRLs.
  • The client makes no trust decision about the GetCACert answer. The caller checks it, for example against a pinned fingerprint.
  • No automatic CA rollover, AES-GCM or AuthEnvelopedData.

Known limitations explains each gap.

Credits

go-pki-scep continues the work of these projects and their contributors:

  • micromdm/scep, the original implementation by Victor Vrantchan and the MicroMDM contributors.
  • smallstep/scep, the Smallstep fork of the message layer this repository started from.

Both are MIT licensed. NOTICE records the origins of the code, including the Go standard library code in x509util.

Support

SUPPORT.md directs usage questions, bug reports, feature requests and security reports. Check Troubleshooting and gather the versions, the failInfo or HTTP status and the server log before posting.

License

Licensed under the MIT License. The Go code in x509util keeps the Go BSD-style license in its file header, as NOTICE describes.

Documentation

Overview

Package scep encodes and decodes the pkiMessage structures of the Simple Certificate Enrollment Protocol (SCEP, RFC 8894).

A pkiMessage is a CMS SignedData whose content is an EnvelopedData. The signed attributes carry the message type, the transaction identifier and the nonces. The envelope carries a CSR, a certificate query or the certificates of a response.

Requesters build PKCSReq, RenewalReq, CertPoll, GetCert and GetCRL messages with the New functions. Responders parse them with ParsePKIMessage, decrypt them with DecryptPKIEnvelope and answer with Success, SuccessCRL, Pending or Fail. Algorithm choices are made per call. The HTTP transport lives in the scepserver and scepclient packages.

Example

Example builds a PKCSReq as a requester, answers it as a CA and reads the answer as the requester again. The HTTP transport is left out.

package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"log"
	"math/big"
	"time"

	"github.com/misiektoja/go-pkcs7"

	scep "github.com/misiektoja/go-pki-scep"
	"github.com/misiektoja/go-pki-scep/x509util"
)

// Example builds a PKCSReq as a requester, answers it as a CA and reads the answer as the requester
// again. The HTTP transport is left out.
func main() {
	caCert, caKey := newExampleCA()
	deviceCert, deviceKey, csr := newExampleDevice("device-1", "secret")

	// --8<-- [start:request]
	req, err := scep.NewCSRRequest(scep.PKCSReq, csr, scep.RequestOptions{
		Recipients:        []*x509.Certificate{caCert},
		SignerCertificate: deviceCert,
		SignerKey:         deviceKey,
	})
	if err != nil {
		log.Fatal(err)
	}
	// --8<-- [end:request]

	// --8<-- [start:respond]
	msg, err := scep.ParsePKIMessage(req.Raw, scep.ParseOptions{})
	if err != nil {
		log.Fatal(err)
	}
	if err := msg.DecryptPKIEnvelope(caCert, caKey, pkcs7.DecryptOptions{}); err != nil {
		log.Fatal(err)
	}
	opts := scep.ResponseOptions{SignerCertificate: caCert, SignerKey: caKey}
	var rep *scep.PKIMessage
	if msg.ChallengePassword != "secret" {
		rep, err = msg.Fail(scep.BadRequest, opts)
	} else {
		rep, err = msg.Success([]*x509.Certificate{issueExample(caCert, caKey, msg.CSR), caCert}, opts)
	}
	if err != nil {
		log.Fatal(err)
	}
	// --8<-- [end:respond]

	// --8<-- [start:answer]
	answer, err := scep.ParsePKIMessage(rep.Raw, scep.ParseOptions{Signers: []*x509.Certificate{caCert}})
	if err != nil {
		log.Fatal(err)
	}
	if err := answer.MatchesRequest(req); err != nil {
		log.Fatal(err)
	}
	if answer.PKIStatus == scep.SUCCESS {
		if err := answer.DecryptPKIEnvelope(deviceCert, deviceKey, pkcs7.DecryptOptions{}); err != nil {
			log.Fatal(err)
		}
		fmt.Println(answer.PKIStatus, answer.CertRepMessage.Certificates[0].Subject)
	}
	// --8<-- [end:answer]

}

// newExampleCA returns a self-signed RSA CA certificate and its key.
func newExampleCA() (*x509.Certificate, *rsa.PrivateKey) {
	key := newExampleKey()
	template := &x509.Certificate{
		SerialNumber:          big.NewInt(1),
		Subject:               pkix.Name{CommonName: "Example CA"},
		NotBefore:             time.Now().Add(-time.Hour),
		NotAfter:              time.Now().Add(time.Hour),
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		IsCA:                  true,
		BasicConstraintsValid: true,
	}
	return createExample(template, template, key, key), key
}

// newExampleDevice returns a self-signed certificate, an RSA key and a CSR with the challenge
// password, which a requester signs its PKCSReq with.
func newExampleDevice(name, password string) (*x509.Certificate, *rsa.PrivateKey, *x509.CertificateRequest) {
	key := newExampleKey()
	der, err := x509util.CreateCertificateRequest(rand.Reader, &x509util.CertificateRequest{
		Subject:           pkix.Name{CommonName: name},
		ChallengePassword: password,
	}, key)
	if err != nil {
		log.Fatal(err)
	}
	csr, err := x509.ParseCertificateRequest(der)
	if err != nil {
		log.Fatal(err)
	}
	template := &x509.Certificate{
		SerialNumber: big.NewInt(2),
		Subject:      csr.Subject,
		NotBefore:    time.Now().Add(-time.Hour),
		NotAfter:     time.Now().Add(time.Hour),
	}
	return createExample(template, template, key, key), key, csr
}

// issueExample signs a certificate for the CSR key.
func issueExample(caCert *x509.Certificate, caKey *rsa.PrivateKey, csr *x509.CertificateRequest) *x509.Certificate {
	der, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{
		SerialNumber: big.NewInt(3),
		Subject:      csr.Subject,
		NotBefore:    time.Now().Add(-time.Hour),
		NotAfter:     time.Now().Add(time.Hour),
	}, caCert, csr.PublicKey, caKey)
	if err != nil {
		log.Fatal(err)
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		log.Fatal(err)
	}
	return cert
}

// createExample signs template with the issuer key and parses the result.
func createExample(template, issuer *x509.Certificate, key, issuerKey *rsa.PrivateKey) *x509.Certificate {
	der, err := x509.CreateCertificate(rand.Reader, template, issuer, &key.PublicKey, issuerKey)
	if err != nil {
		log.Fatal(err)
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		log.Fatal(err)
	}
	return cert
}

// newExampleKey returns a 2048-bit RSA key.
func newExampleKey() *rsa.PrivateKey {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal(err)
	}
	return key
}
Output:
SUCCESS (0) CN=device-1

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CACerts

func CACerts(data []byte) ([]*x509.Certificate, error)

CACerts returns the certificates of a certificate-only SignedData, such as a GetCACert or GetNextCACert response body.

func DegenerateCertificates

func DegenerateCertificates(certs []*x509.Certificate) ([]byte, error)

DegenerateCertificates encodes certificates as a certificate-only SignedData, the body of a GetCACert response that carries more than one certificate.

func ParseSignedCertificates

func ParseSignedCertificates(data []byte, signers []*x509.Certificate) ([]*x509.Certificate, error)

ParseSignedCertificates verifies a GetNextCACert response against signers, the current CA or RA certificates from GetCACert, and returns the certificates it announces.

func SignedCertificates

func SignedCertificates(certs []*x509.Certificate, signerCert *x509.Certificate, signerKey crypto.Signer, digest crypto.Hash) ([]byte, error)

SignedCertificates encodes certs as a SignedData that the current CA or RA signs, the body of a GetNextCACert response (RFC 8894 section 4.7). The message carries certs only. The requester already holds the signer certificate from GetCACert. A zero digest selects SHA-256.

Types

type CSRReqMessage

type CSRReqMessage struct {
	// RawDecrypted is the decrypted pkiEnvelope, the DER encoded CSR.
	RawDecrypted []byte

	// CSR is the parsed certificate request.
	CSR *x509.CertificateRequest

	// ChallengePassword is the challengePassword attribute of the CSR, or empty.
	ChallengePassword string
}

CSRReqMessage holds the CSR of a PKCSReq, RenewalReq or UpdateReq.

type CertRepMessage

type CertRepMessage struct {
	PKIStatus
	RecipientNonce
	FailInfo

	// Certificates are the certificates of a SUCCESS response, such as the issued certificate and
	// its chain. Their order is the order the responder sent.
	Certificates []*x509.Certificate

	// CRL is the DER encoded CRL of a SUCCESS response to GetCRL.
	CRL []byte
}

CertRepMessage holds the CertRep attributes and, once the pkiEnvelope of a SUCCESS response is decrypted, its certificates or CRL.

type CertsSelector

type CertsSelector interface {
	SelectCerts([]*x509.Certificate) []*x509.Certificate
}

A CertsSelector filters certificates.

type CertsSelectorFunc

type CertsSelectorFunc func([]*x509.Certificate) []*x509.Certificate

CertsSelectorFunc is a type of function that filters certificates.

func EnciphermentCertsSelector

func EnciphermentCertsSelector() CertsSelectorFunc

EnciphermentCertsSelector returns a CertsSelectorFunc that selects certificates eligible for key encipherment. This certsSelector can be used to filter PKCSReq recipients.

func FingerprintCertsSelector

func FingerprintCertsSelector(hashType crypto.Hash, hash []byte) CertsSelectorFunc

FingerprintCertsSelector selects a certificate that matches hash using hashType against the digest of the raw certificate DER bytes

func NopCertsSelector

func NopCertsSelector() CertsSelectorFunc

NopCertsSelector returns a CertsSelectorFunc that does not do anything.

func (CertsSelectorFunc) SelectCerts

func (f CertsSelectorFunc) SelectCerts(certs []*x509.Certificate) []*x509.Certificate

type FailInfo

type FailInfo string

FailInfo is the SCEP failInfo attribute of a CertRep with status FAILURE.

const (
	BadAlg          FailInfo = "0"
	BadMessageCheck FailInfo = "1"
	BadRequest      FailInfo = "2"
	BadTime         FailInfo = "3"
	BadCertID       FailInfo = "4"
)

Failure reasons from RFC 8894 section 3.2.1.4.

func (FailInfo) String

func (info FailInfo) String() string

String returns the failure reason name and number.

type IssuerAndSerial

type IssuerAndSerial struct {
	// Issuer is the DER encoded name of the issuing CA.
	Issuer []byte
	// SerialNumber is the certificate serial number.
	SerialNumber *big.Int
}

IssuerAndSerial is the content of GetCert and GetCRL: a certificate identified by its issuer name and serial number (RFC 8894 sections 3.3.4 and 3.3.5).

type IssuerAndSubject

type IssuerAndSubject struct {
	// Issuer is the DER encoded name of the CA.
	Issuer []byte
	// Subject is the DER encoded subject of the CSR.
	Subject []byte
}

IssuerAndSubject is the content of a CertPoll: the name of the CA and the subject of the CSR whose certificate the requester waits for (RFC 8894 section 3.3.3).

type MessageType

type MessageType string

MessageType is the SCEP messageType attribute, a decimal number in a PrintableString.

const (
	CertRep    MessageType = "3"
	RenewalReq MessageType = "17"
	UpdateReq  MessageType = "18"
	PKCSReq    MessageType = "19"
	CertPoll   MessageType = "20"
	GetCert    MessageType = "21"
	GetCRL     MessageType = "22"
)

Message types from RFC 8894 section 3.2.1.2. UpdateReq comes from earlier drafts and is parsed like RenewalReq.

func (MessageType) String

func (msg MessageType) String() string

String returns the message type name and number.

type PKIMessage

type PKIMessage struct {
	TransactionID TransactionID
	MessageType   MessageType

	// SenderNonce is required in requests. Some CA products leave it out of CertRep messages.
	SenderNonce SenderNonce

	// CertRepMessage is set on CertRep messages.
	*CertRepMessage

	// CSRReqMessage is set on PKCSReq, RenewalReq and UpdateReq messages once their pkiEnvelope
	// is decrypted, and on built requests.
	*CSRReqMessage

	// PollRequest is set on CertPoll messages once their pkiEnvelope is decrypted.
	PollRequest *IssuerAndSubject

	// CertificateID is set on GetCert and GetCRL messages once their pkiEnvelope is decrypted.
	CertificateID *IssuerAndSerial

	// Raw is the DER encoded pkiMessage.
	Raw []byte

	// SignerCertificate is the certificate that signed the message. A responder encrypts its
	// answer for it.
	SignerCertificate *x509.Certificate

	// Certificates are the certificates carried in the SignedData, which usually include the
	// signer certificate.
	Certificates []*x509.Certificate

	// Digest is the digest algorithm of the signature.
	Digest crypto.Hash

	// ContentEncryption is the content cipher of the pkiEnvelope once it is decrypted. A responder
	// answers with the same cipher.
	ContentEncryption pkcs7.ContentEncryptionAlgorithm

	// Recipients are the CA or RA certificates a built request is encrypted for.
	Recipients []*x509.Certificate
	// contains filtered or unexported fields
}

PKIMessage is a parsed or built SCEP pkiMessage.

func NewCSRRequest

func NewCSRRequest(messageType MessageType, csr *x509.CertificateRequest, opts RequestOptions) (*PKIMessage, error)

NewCSRRequest builds a PKCSReq, RenewalReq or UpdateReq message for csr.

func NewCertPollRequest

func NewCertPollRequest(issuer, subject []byte, opts RequestOptions) (*PKIMessage, error)

NewCertPollRequest builds a CertPoll for the enrollment opts.TransactionID names. issuer is the DER encoded subject of the CA, subject the DER encoded subject of the CSR.

func NewGetCRLRequest

func NewGetCRLRequest(issuer []byte, serial *big.Int, opts RequestOptions) (*PKIMessage, error)

NewGetCRLRequest builds a GetCRL for the CRL that covers the certificate issuer issued with serial.

func NewGetCertRequest

func NewGetCertRequest(issuer []byte, serial *big.Int, opts RequestOptions) (*PKIMessage, error)

NewGetCertRequest builds a GetCert for the certificate that issuer issued with serial.

func ParsePKIMessage

func ParsePKIMessage(data []byte, opts ParseOptions) (*PKIMessage, error)

ParsePKIMessage parses a DER or BER encoded pkiMessage, verifies its signature and reads its attributes. The signature proves possession of the signer key only. Whether the signer is authorized is up to the caller, through ParseOptions.Signers for a response or the challenge password or existing certificate of a request.

func (*PKIMessage) DecryptPKIEnvelope

func (msg *PKIMessage) DecryptPKIEnvelope(cert *x509.Certificate, key crypto.Decrypter, opts pkcs7.DecryptOptions) error

DecryptPKIEnvelope decrypts the pkiEnvelope with the recipient certificate and its RSA key and parses its content: the CSR of an enrollment request, the query of CertPoll, GetCert and GetCRL, or the certificates or CRL of a SUCCESS CertRep. opts lists the content ciphers to accept.

func (*PKIMessage) EnvelopeRecipients

func (msg *PKIMessage) EnvelopeRecipients() ([]IssuerAndSerial, error)

EnvelopeRecipients lists the certificates the pkiEnvelope of a parsed message is encrypted for, so a server that holds several CA or RA keys can pick the one that decrypts it.

func (*PKIMessage) Fail

func (msg *PKIMessage) Fail(info FailInfo, opts ResponseOptions) (*PKIMessage, error)

Fail answers any request with a FAILURE and the reason info.

func (*PKIMessage) MatchesRequest

func (msg *PKIMessage) MatchesRequest(req *PKIMessage) error

MatchesRequest checks that a CertRep answers req: the transaction identifiers are equal and the recipientNonce repeats the senderNonce of req.

func (*PKIMessage) Pending

func (msg *PKIMessage) Pending(opts ResponseOptions) (*PKIMessage, error)

Pending answers an enrollment or CertPoll whose certificate is not issued yet, for example while an operator approves it. The requester then polls with CertPoll.

func (*PKIMessage) Success

func (msg *PKIMessage) Success(certs []*x509.Certificate, opts ResponseOptions) (*PKIMessage, error)

Success answers an enrollment, CertPoll or GetCert with certificates. certs holds the issued or requested certificate first and may add its chain. The certificates are encrypted for the request signer certificate.

func (*PKIMessage) SuccessCRL

func (msg *PKIMessage) SuccessCRL(crl []byte, opts ResponseOptions) (*PKIMessage, error)

SuccessCRL answers a GetCRL with a DER encoded CRL, encrypted for the request signer certificate.

type PKIStatus

type PKIStatus string

PKIStatus is the SCEP pkiStatus attribute of a CertRep.

const (
	SUCCESS PKIStatus = "0"
	FAILURE PKIStatus = "2"
	PENDING PKIStatus = "3"
)

Statuses from RFC 8894 section 3.2.1.3.

func (PKIStatus) String

func (status PKIStatus) String() string

String returns the status name and number.

type ParseOptions

type ParseOptions struct {
	// Signers restricts who may sign the message to these certificates, which are then the only
	// certificates the signature is checked against. A requester sets the CA and RA certificates
	// from GetCACert, so a CertRep that omits its signer certificate still verifies and a CertRep
	// signed by any other key is refused. A responder leaves it empty, because requests are signed
	// with the requester's own certificate.
	Signers []*x509.Certificate

	// AllowMD5 accepts messages signed with the MD5 digest. Some network devices still send them.
	AllowMD5 bool

	// LegacyCertificateParser accepts certificates that mark the authority key identifier
	// critical, which some Windows SCEP clients send.
	LegacyCertificateParser bool
}

ParseOptions controls how ParsePKIMessage reads a message.

type RecipientNonce

type RecipientNonce []byte

RecipientNonce is the recipientNonce of a CertRep. It repeats the senderNonce of the request.

type RequestOptions

type RequestOptions struct {
	// Recipients are the CA or RA certificates the pkiEnvelope is encrypted for, usually the
	// encryption certificate from GetCACert.
	Recipients []*x509.Certificate

	// SignerCertificate and SignerKey sign the request. A PKCSReq is signed with a self-signed
	// certificate for the CSR key, a RenewalReq with the certificate being renewed. CertPoll,
	// GetCert and GetCRL use the same certificate as the enrollment they follow.
	SignerCertificate *x509.Certificate
	SignerKey         crypto.Signer

	// TransactionID identifies the transaction. CertPoll needs the identifier of the enrollment
	// it polls for. When empty, NewCSRRequest derives one from the CSR key and the other
	// functions pick a random one.
	TransactionID TransactionID

	// Digest is the signature digest. The zero value selects SHA-256.
	Digest crypto.Hash

	// Encryption selects the content cipher and the key transport. The zero value selects
	// AES-128-CBC with PKCS #1 v1.5 key transport.
	Encryption pkcs7.EncryptOptions
}

RequestOptions holds what every request needs: who signs it, who it is encrypted for and the algorithms.

type ResponseOptions

type ResponseOptions struct {
	// SignerCertificate and SignerKey sign the response. They belong to the CA or to its RA, the
	// certificate a requester trusts from GetCACert.
	SignerCertificate *x509.Certificate
	SignerKey         crypto.Signer

	// Certificates are carried next to the signer certificate, such as the CA certificate when an
	// RA signs.
	Certificates []*x509.Certificate

	// Digest is the signature digest. The zero value follows the request when it used SHA-1,
	// SHA-256, SHA-384 or SHA-512, or MD5 when the request was signed with MD5, and selects SHA-256
	// otherwise, so a requester gets a digest it can check.
	Digest crypto.Hash

	// ContentEncryption is the cipher of the response pkiEnvelope. The zero value follows the
	// request, or AES-128-CBC when the request envelope was not decrypted.
	ContentEncryption pkcs7.ContentEncryptionAlgorithm
}

ResponseOptions holds what a CertRep needs: who signs it and the algorithms.

type SenderNonce

type SenderNonce []byte

SenderNonce is the random senderNonce of a message, 16 bytes in messages built by this package.

type TransactionID

type TransactionID string

TransactionID identifies an enrollment across its PKCSReq or RenewalReq, its CertPoll messages and their responses. It is a PrintableString.

func CSRTransactionID

func CSRTransactionID(csr *x509.CertificateRequest) (TransactionID, error)

CSRTransactionID derives the transactionID that NewCSRRequest uses when none is set: the hex encoded key identifier of the CSR public key. A requester that polls later can derive it again.

Directories

Path Synopsis
Package cryptoutil derives key identifiers for SCEP transaction identifiers.
Package cryptoutil derives key identifiers for SCEP transaction identifiers.
examples
quickstart command
A local SCEP server for trying go-pki-scep.
A local SCEP server for trying go-pki-scep.
internal
testca
Package testca is an in-memory SCEP CA for the tests of the server and client packages.
Package testca is an in-memory SCEP CA for the tests of the server and client packages.
Package scepclient is a SCEP (RFC 8894) client over HTTP.
Package scepclient is a SCEP (RFC 8894) client over HTTP.
Package scepserver serves SCEP (RFC 8894) over HTTP for a CA that the caller implements.
Package scepserver serves SCEP (RFC 8894) over HTTP for a CA that the caller implements.
Package x509util creates certificate requests that carry a challengePassword attribute and reads that attribute back.
Package x509util creates certificate requests that carry a challengePassword attribute and reads that attribute back.

Jump to

Keyboard shortcuts

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