Files
certctl/internal/domain/profile.go
T
shankar0123 8bc9f4eed8 EST RFC 7030 hardening master bundle Phases 5-7: end-to-end serverkeygen
+ profile-driven csrattrs + admin observability with per-status
counters + reload-trust endpoint.

Phase 5 — RFC 7030 §4.4 server-driven key generation:
- internal/pkcs7/envelopeddata_builder.go is the inverse of the
  existing parser/decryptor: AES-256-CBC content cipher + RSA PKCS#1
  v1.5 keyTrans + per-call random IV. Round-trip pinned in test
  (BuildEnvelopedData → ParseEnvelopedData → Decrypt returns the
  original plaintext byte-for-byte).
- ESTService.SimpleServerKeygen runs the full §4.4 flow: parse client
  CSR → require RSA pubkey for keyTrans → resolve per-profile
  algorithm (RSA-2048 default; honors AllowedKeyAlgorithms) → in-
  memory keygen → re-build CSR with server pubkey → run existing
  issuer pipeline → marshal PKCS#8 → CMS-EnvelopedData wrap to a
  synthetic recipient cert wrapping the device's CSR-supplied pubkey
  → zeroize plaintext + PKCS#8 bytes → return CertPEM + ChainPEM
  + EncryptedKey. Typed sentinels ErrServerKeygenRequiresKey-
  Encipherment / ErrServerKeygenUnsupportedAlgorithm /
  ErrServerKeygenDisabled.
- ESTHandler.ServerKeygen + ServerKeygenMTLS emit RFC 7030 §4.4.2
  multipart/mixed with random per-response boundary; per-profile
  SetServerKeygenEnabled gate returns 404 when off (defense in depth
  even if the route was registered).
- New routes POST /.well-known/est/[<PathID>/]serverkeygen +
  /.well-known/est-mtls/<PathID>/serverkeygen; openapi.yaml +
  openapi-parity guard updated.

Phase 6 — Real csrattrs implementation:
- New CertificateProfile.RequiredCSRAttributes []string + migration
  000022_certificate_profiles_csrattrs.up.sql. The migration also
  lands the previously-unwired must_staple column (closes the 5.6
  follow-up loop where the field shipped at the domain + service
  layer but the postgres scan/insert/update never persisted it).
- domain.EKUStringToOID + AttributeStringToOID lookup tables: id-kp-*
  EKUs (RFC 5280 §4.2.1.12) + RFC 5280 DN attributes + RFC 2985
  PKCS#10 attributes + Microsoft Intune device-serial OID.
- ESTService.GetCSRAttrs replaces the v2.0.x nil/204 stub with a
  profile-derived SEQUENCE OF OID ASN.1 marshal. Unknown EKU /
  attribute strings dropped + warning-logged so a typo doesn't take
  down the entire endpoint.

Phase 7 — Admin observability + counters + reload-trust:
- internal/service/est_counters.go: estCounterTab (sync/atomic; 12
  named labels) + ESTStatsSnapshot per-profile shape +
  ESTService.Stats(now) zero-allocation accessor + ReloadTrust()
  SIGHUP-equivalent + SetESTAdminMetadata setter.
- Counter ticks wired into processEnrollment + SimpleServerKeygen at
  every success/failure leg.
- internal/api/handler/admin_est.go mirrors AdminSCEPIntune verbatim:
  Profiles + ReloadTrust handlers + AdminESTServiceImpl. Both
  endpoints admin-gated (M-008 triplet pinned + admin_est.go added
  to AdminGatedHandlers).
- New routes GET /api/v1/admin/est/profiles + POST /api/v1/admin/
  est/reload-trust; openapi.yaml documented; openapi-parity guard
  reproduced clean.
- cmd/server/main.go grows estServices map populated by the per-
  profile EST loop + handed to AdminEST. New MTLSTrust() +
  HasMTLSTrust() accessors on ESTHandler so main.go can pull the
  trust holder for the admin-metadata wire-up.
- Per-profile counter isolation regression test
  (internal/service/est_profile_counter_isolation_test.go) proves
  a future shared-counter refactor would fail at compile-time
  pointer-identity check.

Pre-commit verification (sandbox): gofmt clean, go vet clean
(excluding repository/postgres which the sandbox can't build —
disk-space testcontainers download), staticcheck clean across
cms/trustanchor/api/handler/api/router/scep/intune/ratelimit/
service/pkcs7/domain/cmd/server, go test -short -count=1 green
for every non-postgres package. G-3 docs-drift guard reproduced
locally clean (Phases 5-7 added zero new env vars; Phase 1
already documented per-profile SERVER_KEYGEN_ENABLED).

Spec preserved at cowork/est-rfc7030-hardening-prompt.md. Phases
8-13 (GUI ESTAdminPage / CLI+MCP / libest e2e / bulk revocation /
docs/est.md / release prep) remain — post-2.1.0 work.
2026-04-29 23:57:45 +00:00

191 lines
8.2 KiB
Go

package domain
import (
"encoding/asn1"
"time"
)
// CertificateProfile defines an enrollment profile that controls what kinds of
// certificates can be issued: allowed key algorithms, maximum TTL, permitted EKUs,
// required SAN patterns, and optional SPIFFE URI SANs for workload identity.
type CertificateProfile struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
AllowedKeyAlgorithms []KeyAlgorithmRule `json:"allowed_key_algorithms"`
MaxTTLSeconds int `json:"max_ttl_seconds"`
AllowedEKUs []string `json:"allowed_ekus"`
RequiredSANPatterns []string `json:"required_san_patterns"`
SPIFFEURIPattern string `json:"spiffe_uri_pattern"`
AllowShortLived bool `json:"allow_short_lived"`
// MustStaple, when true, causes the local issuer to add the RFC 7633
// must-staple extension (id-pe-tlsfeature, OID 1.3.6.1.5.5.7.1.24) to
// every certificate issued under this profile. Browsers + modern TLS
// libraries that see this extension MUST fail-closed on missing OCSP
// stapling responses — defense against revocation-bypass via OCSP
// blackholing.
//
// Default: false. Operators opt in once they've confirmed their TLS
// reverse proxy / load balancer staples OCSP responses (NGINX,
// HAProxy, Envoy, etc. all support stapling but it requires explicit
// config). Setting must-staple by default would break customer
// deployments where the TLS path doesn't staple — browsers hard-fail.
//
// Recommended for: Intune-deployed device certs (modern TLS clients);
// SCEP profiles serving general/legacy clients (ChromeOS, IoT) should
// stay false until the TLS path is verified.
MustStaple bool `json:"must_staple"`
// RequiredCSRAttributes is the per-profile hint list the EST `csrattrs`
// endpoint (RFC 7030 §4.5) returns to enrolling clients. Values are
// short string keys that map to ASN.1 ObjectIdentifiers via
// AttributeStringToOID — example: ["serialNumber", "deviceSerialNumber"]
// to push the device serial into the issued cert's Subject DN for
// IoT bootstrapping. Defaults empty (the EST handler then returns
// 204-No-Content per RFC 7030 §4.5.2 — the legacy stub behavior).
//
// EKU strings already live in AllowedEKUs above and are added to the
// csrattrs response automatically — RequiredCSRAttributes covers the
// non-EKU attribute hints (RFC 5280 distinguished-name attributes,
// RFC 5912 CMC attributes, etc.). Keeping the two concept slices
// separate matches how operators think: "what EKUs do I need" vs
// "what extra subject attributes do I need".
//
// Unknown keys are tolerated at marshal time (logged + dropped) so a
// new key on a forward-version certctl doesn't force every profile
// edit to round-trip through the validator.
//
// EST RFC 7030 hardening master bundle Phase 6.
RequiredCSRAttributes []string `json:"required_csr_attributes,omitempty"`
Enabled bool `json:"enabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// KeyAlgorithmRule defines an allowed key algorithm and its minimum key size.
type KeyAlgorithmRule struct {
Algorithm string `json:"algorithm"` // "RSA", "ECDSA", "Ed25519"
MinSize int `json:"min_size"` // RSA: 2048/4096, ECDSA: 256/384, Ed25519: 0 (fixed)
}
// IsShortLived returns true if this profile's max TTL is under 1 hour (3600 seconds).
// Short-lived certs use expiry as revocation — no CRL/OCSP needed.
func (p *CertificateProfile) IsShortLived() bool {
return p.AllowShortLived && p.MaxTTLSeconds > 0 && p.MaxTTLSeconds < 3600
}
// DefaultKeyAlgorithms returns sensible defaults for profiles without explicit rules.
func DefaultKeyAlgorithms() []KeyAlgorithmRule {
return []KeyAlgorithmRule{
{Algorithm: "ECDSA", MinSize: 256},
{Algorithm: "RSA", MinSize: 2048},
}
}
// DefaultEKUs returns the default extended key usages.
func DefaultEKUs() []string {
return []string{"serverAuth"}
}
// Supported key algorithm constants for validation.
const (
KeyAlgorithmRSA = "RSA"
KeyAlgorithmECDSA = "ECDSA"
KeyAlgorithmEd25519 = "Ed25519"
)
// ValidKeyAlgorithms is the set of recognized key algorithm names.
var ValidKeyAlgorithms = map[string]bool{
KeyAlgorithmRSA: true,
KeyAlgorithmECDSA: true,
KeyAlgorithmEd25519: true,
}
// ValidEKUs is the set of recognized extended key usage names.
var ValidEKUs = map[string]bool{
"serverAuth": true,
"clientAuth": true,
"codeSigning": true,
"emailProtection": true,
"timeStamping": true,
}
// EKUStringToOID maps an EKU short-name (as used in
// CertificateProfile.AllowedEKUs) to the corresponding RFC 5280 §4.2.1.12
// id-kp-* OID. Returns ok=false for unknown names so the EST csrattrs
// path can drop unrecognized hints rather than emit garbage OIDs.
//
// EST RFC 7030 hardening master bundle Phase 6.2.
func EKUStringToOID(name string) (asn1.ObjectIdentifier, bool) {
oid, ok := ekuOIDByName[name]
return oid, ok
}
// AttributeStringToOID maps a Subject DN / CMC attribute short-name
// (as used in CertificateProfile.RequiredCSRAttributes) to the
// corresponding ASN.1 OID. Returns ok=false for unknown names. The
// known set is intentionally small at GA — operators add new keys via
// PR review rather than free-form strings, so a typo trips a validator
// + the EST csrattrs response stays self-describing.
//
// EST RFC 7030 hardening master bundle Phase 6.2.
func AttributeStringToOID(name string) (asn1.ObjectIdentifier, bool) {
oid, ok := attributeOIDByName[name]
return oid, ok
}
// ekuOIDByName is the lookup table EKUStringToOID consults. OIDs
// registered in RFC 5280 §4.2.1.12 + RFC 3280 + Microsoft.
var ekuOIDByName = map[string]asn1.ObjectIdentifier{
"serverAuth": {1, 3, 6, 1, 5, 5, 7, 3, 1},
"clientAuth": {1, 3, 6, 1, 5, 5, 7, 3, 2},
"codeSigning": {1, 3, 6, 1, 5, 5, 7, 3, 3},
"emailProtection": {1, 3, 6, 1, 5, 5, 7, 3, 4},
"timeStamping": {1, 3, 6, 1, 5, 5, 7, 3, 8},
"ocspSigning": {1, 3, 6, 1, 5, 5, 7, 3, 9},
// Microsoft EKUs commonly required for AD smartcard / Intune device
// auth. Not in ValidEKUs above (which only enumerates the broadly
// portable names), but devices enrolling for these targets need
// csrattrs to advertise them.
"smartCardLogon": {1, 3, 6, 1, 4, 1, 311, 20, 2, 2},
"documentSigning": {1, 3, 6, 1, 4, 1, 311, 10, 3, 12},
"encryptingFileSystem": {1, 3, 6, 1, 4, 1, 311, 10, 3, 4},
"keyRecoveryAgent": {1, 3, 6, 1, 4, 1, 311, 21, 6},
"ocspNoCheck": {1, 3, 6, 1, 5, 5, 7, 48, 1, 5},
"anyExtendedKeyUsage": {2, 5, 29, 37, 0},
"ipsecIKE": {1, 3, 6, 1, 5, 5, 7, 3, 17},
"machineEAP": {1, 3, 6, 1, 5, 5, 7, 3, 13},
"kerberosClientAuth": {1, 3, 6, 1, 5, 2, 3, 4},
"kerberosKeyDistribution": {1, 3, 6, 1, 5, 2, 3, 5},
}
// attributeOIDByName covers the Subject DN / CMC attribute hints the
// EST csrattrs endpoint can advertise. Sourced from RFC 5280
// §4.1.2.6 + RFC 5912 (CMC) + RFC 5280 §4.1.2.4. Limited surface on
// purpose; PRs can extend.
var attributeOIDByName = map[string]asn1.ObjectIdentifier{
// RFC 5280 §4.1.2.6 — distinguished-name attributes commonly
// requested for IoT bootstrap.
"commonName": {2, 5, 4, 3},
"surname": {2, 5, 4, 4},
"serialNumber": {2, 5, 4, 5},
"countryName": {2, 5, 4, 6},
"localityName": {2, 5, 4, 7},
"stateOrProvinceName": {2, 5, 4, 8},
"organizationName": {2, 5, 4, 10},
"organizationalUnitName": {2, 5, 4, 11},
"title": {2, 5, 4, 12},
// CSR attributes from RFC 2985 §5.4 — challengePassword is
// already used by SCEP profiles; emailAddress + extensionRequest
// are the standard PKCS#10 carriers.
"challengePassword": {1, 2, 840, 113549, 1, 9, 7},
"emailAddress": {1, 2, 840, 113549, 1, 9, 1},
"extensionRequest": {1, 2, 840, 113549, 1, 9, 14},
// Device-identity attributes that show up in IoT / MDM
// enrollment flows.
"deviceSerialNumber": {1, 3, 6, 1, 4, 1, 311, 21, 14}, // Microsoft Intune device serial
"unstructuredName": {1, 2, 840, 113549, 1, 9, 2},
"unstructuredAddress": {1, 2, 840, 113549, 1, 9, 8},
}