Help us shape the future of Go! Take the 2026 Go Developer Survey

enterprise

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

Keppin-OSS Enterprise TLS

Keppin-OSS Enterprise TLS is a Windows Enterprise CA provider. It requests, independently validates, and installs a localhost certificate from an Active Directory Certificate Services (AD CS) Enterprise CA using the native certreq.exe workflow, and returns structured status, key-state, and cleanup metadata to the caller.

The supported and verified target is Windows/amd64.

Scope

Use this module when you need to:

  • request a certificate for the expected localhost identity (localhost, 127.0.0.1, and ::1) from an AD CS Enterprise CA on Windows;
  • obtain structured status, error, and key-state information instead of parsing tool output.

Non-scope

This module does not own local-CA creation, TLS serving/runtime configuration, or general certificate management. It validates the expected localhost certificate properties; it is not a general-purpose certificate validator.

Resources

License

Apache License 2.0. See LICENSE.

Documentation

Overview

Package enterprise is a standalone Windows Enterprise CA provider for Keppin localhost HTTPS. It requests and independently validates a machine/computer certificate from an Active Directory Certificate Services (AD CS) Enterprise CA using the native certreq.exe workflow.

This module is deliberately narrow: it does not implement a local-TLS fallback, it does not create or install any local CA, and it contains no fallback/orchestration policy. Those concerns are external to this module.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotConfigured indicates required Enterprise CA configuration is missing.
	ErrNotConfigured = errors.New("enterprise enrollment is not configured")
	// ErrUnavailable indicates certreq.exe or the Enterprise CA infrastructure
	// could not be reached.
	ErrUnavailable = errors.New("enterprise CA infrastructure or tool is unavailable")
	// ErrEnrollmentFailed indicates enrollment was attempted but failed.
	ErrEnrollmentFailed = errors.New("enterprise enrollment was attempted but failed")
	// ErrInvalidCertificate indicates the returned certificate material is
	// invalid, untrusted, or mismatched.
	ErrInvalidCertificate = errors.New("returned certificate is invalid, untrusted, or mismatched")
	// ErrEnrollmentIncomplete indicates a valid certificate was installed but
	// the cleanup metadata required for later safe removal is missing.
	ErrEnrollmentIncomplete = errors.New("enrollment installed a certificate but cleanup metadata is incomplete")
)

Sentinel errors allow callers to classify outcomes by matching the sentinels with errors.Is; the concrete *Result type can be extracted with errors.As.

View Source
var ErrCleanupFailed = errors.New("enterprise cleanup failed")

ErrCleanupFailed wraps any failure to complete cleanup of owned material.

View Source
var ErrOwnershipMismatch = errors.New("ownership could not be verified; refusing to delete")

ErrOwnershipMismatch indicates one or more ownership guards did not match the persisted enrollment metadata. Cleanup refuses to delete either artifact.

Functions

func BuildRequestINF

func BuildRequestINF(cfg Config, keyContainer string) string

BuildRequestINF renders the certreq.exe request (INF) content for a machine-scoped, localhost-only server-authentication certificate.

keyContainer, when non-empty, is the CNG key container name that certreq -new must generate the key into. It is fixed for the enrollment attempt (a randomly generated, module-namespaced name) so the key identity is known before key creation.

The INF requires a machine-scoped private key in the Microsoft Software Key Storage Provider (MachineKeySet = TRUE) that is not exportable (Exportable = FALSE). The module does not subsequently verify either the resulting key export policy or the actual machine-scope ownership of the key, and it never writes private-key material as PEM or PFX.

func Uninstall

func Uninstall(info CleanupInfo) error

Uninstall removes the leaf certificate and private key described by info. info must originate from an enrollment result and be treated as trusted, integrity-protected administrative data: when the certificate is not found, the provider and container name from info are used to attempt key deletion without re-verifying ownership. Cleanup is best-effort and not transactional; it deletes only the artifacts this module manages and does not roll back every side effect of certreq.exe.

Uninstall is idempotent: it also returns nil when CNG reports the key as not found, which covers a key that is absent and one that could not be opened or is not accessible to the caller. A nil return therefore does not certify that the key was deleted.

func ValidateCertificate

func ValidateCertificate(data []byte, opts ValidateOptions) (*x509.Certificate, error)

ValidateCertificate independently validates certificate material returned by the CA. A nil error means the certificate is acceptable. It performs, at minimum: parse, validity window, localhost SAN policy, Server Authentication EKU/key usage, public-key match against the requested key, and chain/trust verification against the platform/system trust available to the calling process.

Types

type CleanupInfo

type CleanupInfo struct {
	Issuer       string // RFC2253 string of the issuer name
	SerialNumber string // hex of the serial number (big-endian)
	LeafSHA256   string // hex SHA-256 of the leaf certificate DER
	SPKISHA256   string // hex SHA-256 of the SubjectPublicKeyInfo DER

	Provider      string // key storage provider name
	ContainerName string // key container name
	ProviderType  uint32
	KeySpec       uint32
}

CleanupInfo is the enrollment metadata used to later remove the leaf certificate and its associated private key without broad discovery.

Treat CleanupInfo as privileged input: Uninstall trusts the values it contains. Its provenance and integrity must be protected by the caller.

The certificate-identity fields (Issuer, SerialNumber, LeafSHA256, SPKISHA256) are computed from the validated leaf. The key-association fields (Provider, ContainerName, ProviderType, KeySpec) are read from the installed certificate's CERT_KEY_PROV_INFO_PROP_ID.

type Config

type Config struct {
	// CA identifies the Enterprise CA in certreq.exe "-config" format:
	// "CAHostName\CAName" (the host and common name of the CA).
	CA string

	// Template is the certificate template name to request. When empty, the
	// template directive is omitted from the generated INF; the module makes
	// no claim about which template (if any) the CA then applies.
	Template string
}

Config supplies the Enterprise CA/template identifiers required for machine certificate enrollment. None of these values are hardcoded; they must be provided by the caller (or a future orchestration layer).

type KeyState

type KeyState int

KeyState classifies what is known about the key container generated for an enrollment attempt.

const (
	// KeyStateNone is the zero/unclassified state, also used on success. It does
	// not imply that no key container was allocated or that no key exists.
	KeyStateNone KeyState = iota
	// KeyStateRemoved means the owned key was created and successfully removed.
	KeyStateRemoved
	// KeyStatePresent means the owned key may remain and can be retried using
	// Result.KeyContainer.
	KeyStatePresent
	// KeyStateUnproven means key ownership could not be proven; the caller must
	// not attempt to delete the key.
	KeyStateUnproven
)

func (KeyState) String

func (s KeyState) String() string

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider enrolls and validates a machine-scoped localhost certificate from an Enterprise CA using certreq.exe. It is a standalone provider and contains no fallback/orchestration logic.

func New

func New(cfg Config) *Provider

New creates a Provider using the real certreq.exe runner and the native Windows machine certificate store and CNG key providers.

func (*Provider) Enroll

func (p *Provider) Enroll(ctx context.Context) (*Result, error)

Enroll performs the full enterprise enrollment workflow and returns a structured Result. On success, Result.Status is StatusSuccess and Result.Certificate holds the validated certificate.

The result classification is: not-configured, unavailable, enrollment-failed, invalid-certificate, enrollment-incomplete, or success (see Status). Result.KeyContainer and Result.KeyState describe the state of the key container generated for this attempt across the failure and success paths.

type Result

type Result struct {
	Status      Status
	Certificate *x509.Certificate
	Err         error

	// Diagnostics (populated where available).
	Tool       string // e.g. "certreq.exe"
	ExitCode   int    // raw process exit code when a tool returned non-zero
	Stderr     string // tool stderr, when non-empty
	Thumbprint string // SHA-1 thumbprint of the validated certificate (hex)

	// Cleanup holds the enrollment metadata used to later remove the leaf
	// certificate and its private key. It is populated on success and, on a
	// failed attempt where retry cleanup is possible, as best-effort metadata.
	Cleanup *CleanupInfo

	// KeyContainer is the key container name generated for this attempt and
	// selected before certreq -new. It is populated whenever a container name
	// was allocated, including failure paths, so the key identity is not lost
	// when the module can determine it.
	KeyContainer string
	// KeyState describes the state of the owned key after the attempt.
	KeyState KeyState
	// KeyCleanupErr, when non-nil, records a key-removal failure so it is not
	// hidden behind the primary enrollment error.
	KeyCleanupErr error
}

Result is the structured outcome of an enrollment attempt. Status is the canonical classification; Err carries a wrapped sentinel error that errors.Is can match, while errors.As extracts the *Result type itself.

func (*Result) Error

func (r *Result) Error() string

Error implements error, allowing a Result to be returned directly as the error of an enrollment attempt.

func (*Result) Unwrap

func (r *Result) Unwrap() error

Unwrap exposes the underlying error so errors.Is can match the sentinel.

type Status

type Status int

Status classifies the outcome of an enrollment attempt so a future orchestration layer can reason about it without string matching.

const (
	// StatusUnknown is the zero value; it indicates no attempt was made.
	StatusUnknown Status = iota
	// StatusNotConfigured means the required CA configuration is missing.
	StatusNotConfigured
	// StatusUnavailable means certreq.exe or the Enterprise CA infrastructure
	// could not be reached.
	StatusUnavailable
	// StatusEnrollmentFailed means enrollment failed. This includes local errors
	// that occur before or around the tool run (for example file or request
	// handling), as well as the CA rejecting the request or certreq.exe failing.
	StatusEnrollmentFailed
	// StatusInvalidCertificate means material was returned but failed
	// independent validation (malformed, wrong identity, wrong EKU/key usage,
	// key mismatch, or untrusted chain).
	StatusInvalidCertificate
	// StatusSuccess means enrollment succeeded and the certificate passed
	// independent validation.
	StatusSuccess
	// StatusEnrollmentIncomplete means a valid certificate was installed but
	// the cleanup metadata required for later safe removal could not be
	// captured. The caller must treat this as an observable orphan state.
	StatusEnrollmentIncomplete
)

func (Status) String

func (s Status) String() string

type ValidateOptions

type ValidateOptions struct {
	// Roots and Intermediates default to the platform/system trust available to
	// the calling process and an empty pool respectively when nil. Callers can
	// supply explicit pools when they must control the trust set.
	Roots         *x509.CertPool
	Intermediates *x509.CertPool
	// ExpectedPublicKey, when set, must match the certificate's public key
	// (the key generated for the enrollment request).
	ExpectedPublicKey any
	// Now is the reference time for validity checks; defaults to time.Now.
	Now time.Time
}

ValidateOptions controls independent certificate validation and allows the caller to inject trust roots, intermediates, a reference clock, and the expected public key.

Directories

Path Synopsis
examples
classification command
Command classification demonstrates caller-side classification of structured enrollment statuses and sentinel errors through the public API, without any production changes or machine-state mutation.
Command classification demonstrates caller-side classification of structured enrollment statuses and sentinel errors through the public API, without any production changes or machine-state mutation.
enroll command
Command enroll demonstrates the Enterprise CA enrollment flow for a machine/computer certificate.
Command enroll demonstrates the Enterprise CA enrollment flow for a machine/computer certificate.
uninstall command
Command uninstall demonstrates the cleanup boundary: it removes the leaf certificate and associated machine key described by a CleanupInfo previously persisted from an enrollment result.
Command uninstall demonstrates the cleanup boundary: it removes the leaf certificate and associated machine key described by a CleanupInfo previously persisted from an enrollment result.
validate command
Command validate demonstrates the strict localhost certificate validation policy using synthetic in-memory fixtures (a self-signed root CA and a matching localhost leaf certificate).
Command validate demonstrates the strict localhost certificate validation policy using synthetic in-memory fixtures (a self-signed root CA and a matching localhost leaf certificate).

Jump to

Keyboard shortcuts

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