mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 16:11:29 +00:00
43075a1b5c
+ 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.
172 lines
5.3 KiB
Go
172 lines
5.3 KiB
Go
package pkcs7
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/ecdsa"
|
|
"crypto/elliptic"
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"crypto/x509/pkix"
|
|
"math/big"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// freshRSARecipient produces a self-signed RSA-2048 cert + matching key
|
|
// usable as both EnvelopedData recipient (BUILDER input) and EnvelopedData
|
|
// decryptor (Decrypt input). RSA-2048 is the minimum the parser supports
|
|
// for keyTrans.
|
|
func freshRSARecipient(t *testing.T) (*x509.Certificate, *rsa.PrivateKey) {
|
|
t.Helper()
|
|
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
if err != nil {
|
|
t.Fatalf("rsa.GenerateKey: %v", err)
|
|
}
|
|
tmpl := &x509.Certificate{
|
|
SerialNumber: big.NewInt(time.Now().UnixNano()),
|
|
Subject: pkix.Name{CommonName: "envelopeddata-builder-test"},
|
|
Issuer: pkix.Name{CommonName: "envelopeddata-builder-test-issuer"},
|
|
NotBefore: time.Now().Add(-1 * time.Hour),
|
|
NotAfter: time.Now().Add(24 * time.Hour),
|
|
KeyUsage: x509.KeyUsageKeyEncipherment,
|
|
}
|
|
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
|
if err != nil {
|
|
t.Fatalf("CreateCertificate: %v", err)
|
|
}
|
|
cert, err := x509.ParseCertificate(der)
|
|
if err != nil {
|
|
t.Fatalf("ParseCertificate: %v", err)
|
|
}
|
|
return cert, key
|
|
}
|
|
|
|
func TestBuildEnvelopedData_RoundTrip(t *testing.T) {
|
|
cert, key := freshRSARecipient(t)
|
|
plaintext := []byte("the eagle has landed at coordinate 47.6062N 122.3321W; key zeroize at exit")
|
|
|
|
wire, err := BuildEnvelopedData(plaintext, cert, nil)
|
|
if err != nil {
|
|
t.Fatalf("BuildEnvelopedData: %v", err)
|
|
}
|
|
if len(wire) == 0 {
|
|
t.Fatal("empty wire bytes")
|
|
}
|
|
|
|
parsed, err := ParseEnvelopedData(wire)
|
|
if err != nil {
|
|
t.Fatalf("ParseEnvelopedData: %v", err)
|
|
}
|
|
got, err := parsed.Decrypt(key, cert)
|
|
if err != nil {
|
|
t.Fatalf("Decrypt: %v", err)
|
|
}
|
|
if !bytes.Equal(got, plaintext) {
|
|
t.Errorf("round-trip mismatch:\n got = %q\nwant = %q", got, plaintext)
|
|
}
|
|
}
|
|
|
|
func TestBuildEnvelopedData_AlgorithmIsAES256CBC(t *testing.T) {
|
|
cert, _ := freshRSARecipient(t)
|
|
wire, err := BuildEnvelopedData([]byte("alg-id pin"), cert, nil)
|
|
if err != nil {
|
|
t.Fatalf("BuildEnvelopedData: %v", err)
|
|
}
|
|
parsed, err := ParseEnvelopedData(wire)
|
|
if err != nil {
|
|
t.Fatalf("ParseEnvelopedData: %v", err)
|
|
}
|
|
if !parsed.ContentEncryptionAlg.Algorithm.Equal(OIDAES256CBC) {
|
|
t.Errorf("alg = %v, want OIDAES256CBC %v", parsed.ContentEncryptionAlg.Algorithm, OIDAES256CBC)
|
|
}
|
|
}
|
|
|
|
func TestBuildEnvelopedData_RecipientMatchesIssuerAndSerial(t *testing.T) {
|
|
cert, _ := freshRSARecipient(t)
|
|
wire, err := BuildEnvelopedData([]byte("rid pin"), cert, nil)
|
|
if err != nil {
|
|
t.Fatalf("BuildEnvelopedData: %v", err)
|
|
}
|
|
parsed, err := ParseEnvelopedData(wire)
|
|
if err != nil {
|
|
t.Fatalf("ParseEnvelopedData: %v", err)
|
|
}
|
|
if len(parsed.RecipientInfos) != 1 {
|
|
t.Fatalf("recipient count = %d, want 1", len(parsed.RecipientInfos))
|
|
}
|
|
rid := parsed.RecipientInfos[0].IssuerAndSerial
|
|
if !bytes.Equal(rid.IssuerRaw.FullBytes, cert.RawIssuer) {
|
|
t.Errorf("issuer mismatch:\n got = %x\nwant = %x", rid.IssuerRaw.FullBytes, cert.RawIssuer)
|
|
}
|
|
if rid.SerialNumber == nil || rid.SerialNumber.Cmp(cert.SerialNumber) != 0 {
|
|
t.Errorf("serial mismatch: got %v, want %v", rid.SerialNumber, cert.SerialNumber)
|
|
}
|
|
}
|
|
|
|
func TestBuildEnvelopedData_RejectsNonRSARecipient(t *testing.T) {
|
|
// EnvelopedData keyTrans requires RSA per the parser's contract; ECDSA
|
|
// recipient certs MUST be rejected at build time so an operator never
|
|
// ships a serverkeygen response that no client can decrypt.
|
|
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
if err != nil {
|
|
t.Fatalf("ecdsa.GenerateKey: %v", err)
|
|
}
|
|
tmpl := &x509.Certificate{
|
|
SerialNumber: big.NewInt(99),
|
|
Subject: pkix.Name{CommonName: "ecdsa-recipient-reject-test"},
|
|
Issuer: pkix.Name{CommonName: "ecdsa-recipient-reject-test-issuer"},
|
|
NotBefore: time.Now().Add(-1 * time.Hour),
|
|
NotAfter: time.Now().Add(24 * time.Hour),
|
|
}
|
|
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &ecKey.PublicKey, ecKey)
|
|
if err != nil {
|
|
t.Fatalf("CreateCertificate: %v", err)
|
|
}
|
|
cert, err := x509.ParseCertificate(der)
|
|
if err != nil {
|
|
t.Fatalf("ParseCertificate: %v", err)
|
|
}
|
|
if _, err := BuildEnvelopedData([]byte("test"), cert, nil); err == nil {
|
|
t.Fatal("expected error for non-RSA recipient cert")
|
|
}
|
|
}
|
|
|
|
func TestBuildEnvelopedData_RejectsEmptyPlaintext(t *testing.T) {
|
|
cert, _ := freshRSARecipient(t)
|
|
_, err := BuildEnvelopedData(nil, cert, nil)
|
|
if err == nil {
|
|
t.Fatal("expected error for empty plaintext")
|
|
}
|
|
}
|
|
|
|
func TestBuildEnvelopedData_RejectsNilCert(t *testing.T) {
|
|
_, err := BuildEnvelopedData([]byte("x"), nil, nil)
|
|
if err == nil {
|
|
t.Fatal("expected error for nil recipient cert")
|
|
}
|
|
}
|
|
|
|
func TestBuildEnvelopedData_LargePlaintextRoundTrip(t *testing.T) {
|
|
// PKCS#7 padding + AES-256-CBC works for arbitrary plaintext lengths.
|
|
// Pin the contract for a 4KiB-aligned key blob (typical PKCS#8 RSA-2048
|
|
// is ~1.2KB; ECDSA P-384 is ~250B).
|
|
cert, key := freshRSARecipient(t)
|
|
big := bytes.Repeat([]byte("ABCDEFGH"), 512) // 4 KiB
|
|
wire, err := BuildEnvelopedData(big, cert, nil)
|
|
if err != nil {
|
|
t.Fatalf("BuildEnvelopedData: %v", err)
|
|
}
|
|
parsed, err := ParseEnvelopedData(wire)
|
|
if err != nil {
|
|
t.Fatalf("ParseEnvelopedData: %v", err)
|
|
}
|
|
got, err := parsed.Decrypt(key, cert)
|
|
if err != nil {
|
|
t.Fatalf("Decrypt: %v", err)
|
|
}
|
|
if !bytes.Equal(got, big) {
|
|
t.Errorf("4KiB round-trip mismatch")
|
|
}
|
|
}
|