mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-13 07:28:51 +00:00
feat(M46): Windows Certificate Store + Java Keystore target connectors, shared certutil package
Extract shared certutil helpers (CreatePFX, ParsePrivateKey, ComputeThumbprint, GenerateRandomPassword, ParseCertificatePEM) from IIS connector for reuse. Add WinCertStore connector (PowerShell Import-PfxCertificate, dual local/WinRM mode, configurable store/location, expired cert cleanup) and JavaKeystore connector (PEM→PKCS#12→keytool pipeline, JKS/PKCS12 support, shell injection prevention, path traversal protection). 53 new tests, all passing. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
// Package certutil provides shared certificate utility functions for target connectors.
|
||||
// These functions handle PEM/PFX conversion, key parsing, thumbprint computation,
|
||||
// and random password generation. Extracted from the IIS connector (M39) to enable
|
||||
// reuse by Windows Certificate Store (M46) and Java Keystore (M46) connectors.
|
||||
package certutil
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
pkcs12 "software.sslmate.com/src/go-pkcs12"
|
||||
)
|
||||
|
||||
// CreatePFX converts PEM-encoded cert, key, and chain into PKCS#12 (PFX) format.
|
||||
// Uses go-pkcs12 Modern encoder with strong encryption.
|
||||
func CreatePFX(certPEM, keyPEM, chainPEM string, password string) ([]byte, error) {
|
||||
// Parse leaf certificate
|
||||
certBlock, _ := pem.Decode([]byte(certPEM))
|
||||
if certBlock == nil || certBlock.Type != "CERTIFICATE" {
|
||||
return nil, fmt.Errorf("failed to decode certificate PEM")
|
||||
}
|
||||
leafCert, err := x509.ParseCertificate(certBlock.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse leaf certificate: %w", err)
|
||||
}
|
||||
|
||||
// Parse private key (supports PKCS#8, PKCS#1 RSA, and EC)
|
||||
keyBlock, _ := pem.Decode([]byte(keyPEM))
|
||||
if keyBlock == nil {
|
||||
return nil, fmt.Errorf("failed to decode private key PEM")
|
||||
}
|
||||
privateKey, err := ParsePrivateKey(keyBlock.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse private key: %w", err)
|
||||
}
|
||||
|
||||
// Parse CA chain certificates (optional)
|
||||
var caCerts []*x509.Certificate
|
||||
if chainPEM != "" {
|
||||
rest := []byte(chainPEM)
|
||||
for {
|
||||
var block *pem.Block
|
||||
block, rest = pem.Decode(rest)
|
||||
if block == nil {
|
||||
break
|
||||
}
|
||||
if block.Type != "CERTIFICATE" {
|
||||
continue
|
||||
}
|
||||
caCert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse CA certificate: %w", err)
|
||||
}
|
||||
caCerts = append(caCerts, caCert)
|
||||
}
|
||||
}
|
||||
|
||||
// Encode as PKCS#12 with Modern encryption
|
||||
pfxData, err := pkcs12.Modern.Encode(privateKey, leafCert, caCerts, password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to encode PKCS#12: %w", err)
|
||||
}
|
||||
|
||||
return pfxData, nil
|
||||
}
|
||||
|
||||
// ParsePrivateKey attempts to parse a DER-encoded private key.
|
||||
// Tries PKCS#8, PKCS#1 RSA, and EC formats in order.
|
||||
func ParsePrivateKey(der []byte) (interface{}, error) {
|
||||
if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
|
||||
return key, nil
|
||||
}
|
||||
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
|
||||
return key, nil
|
||||
}
|
||||
if key, err := x509.ParseECPrivateKey(der); err == nil {
|
||||
return key, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unsupported private key format")
|
||||
}
|
||||
|
||||
// ComputeThumbprint calculates the SHA-1 thumbprint of a PEM-encoded certificate.
|
||||
// Windows uses SHA-1 thumbprints as the primary certificate identifier.
|
||||
// Returns uppercase hex string matching Windows certutil output.
|
||||
func ComputeThumbprint(certPEM string) (string, error) {
|
||||
block, _ := pem.Decode([]byte(certPEM))
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
return "", fmt.Errorf("failed to decode certificate PEM for thumbprint")
|
||||
}
|
||||
hash := sha1.Sum(block.Bytes)
|
||||
return strings.ToUpper(hex.EncodeToString(hash[:])), nil
|
||||
}
|
||||
|
||||
// GenerateRandomPassword creates a random alphanumeric password.
|
||||
// Typically used for transient PFX encryption — the password is only used
|
||||
// between PFX creation and import, it never persists.
|
||||
func GenerateRandomPassword(length int) (string, error) {
|
||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
b := make([]byte, length)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("failed to read random bytes: %w", err)
|
||||
}
|
||||
for i := range b {
|
||||
b[i] = charset[int(b[i])%len(charset)]
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// ParseCertificatePEM parses a PEM-encoded certificate and returns the x509.Certificate.
|
||||
func ParseCertificatePEM(certPEM string) (*x509.Certificate, error) {
|
||||
block, _ := pem.Decode([]byte(certPEM))
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
return nil, fmt.Errorf("failed to decode certificate PEM")
|
||||
}
|
||||
cert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse certificate: %w", err)
|
||||
}
|
||||
return cert, nil
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package certutil
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// generateTestCertAndKey creates a self-signed certificate and key for testing.
|
||||
func generateTestCertAndKey() (string, string, error) {
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "test.example.com"},
|
||||
NotBefore: time.Now().Add(-1 * time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
}
|
||||
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||
|
||||
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
|
||||
|
||||
return string(certPEM), string(keyPEM), nil
|
||||
}
|
||||
|
||||
func TestCreatePFX_Success(t *testing.T) {
|
||||
certPEM, keyPEM, err := generateTestCertAndKey()
|
||||
if err != nil {
|
||||
t.Fatalf("generate test cert: %v", err)
|
||||
}
|
||||
|
||||
pfx, err := CreatePFX(certPEM, keyPEM, "", "test-password")
|
||||
if err != nil {
|
||||
t.Fatalf("CreatePFX failed: %v", err)
|
||||
}
|
||||
if len(pfx) == 0 {
|
||||
t.Error("expected non-empty PFX data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatePFX_WithChain(t *testing.T) {
|
||||
certPEM, keyPEM, err := generateTestCertAndKey()
|
||||
if err != nil {
|
||||
t.Fatalf("generate test cert: %v", err)
|
||||
}
|
||||
// Use the same cert as chain for testing purposes
|
||||
pfx, err := CreatePFX(certPEM, keyPEM, certPEM, "test-password")
|
||||
if err != nil {
|
||||
t.Fatalf("CreatePFX with chain failed: %v", err)
|
||||
}
|
||||
if len(pfx) == 0 {
|
||||
t.Error("expected non-empty PFX data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatePFX_InvalidCert(t *testing.T) {
|
||||
_, err := CreatePFX("not-a-cert", "not-a-key", "", "pw")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid cert PEM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatePFX_InvalidKey(t *testing.T) {
|
||||
certPEM, _, err := generateTestCertAndKey()
|
||||
if err != nil {
|
||||
t.Fatalf("generate test cert: %v", err)
|
||||
}
|
||||
_, err = CreatePFX(certPEM, "not-a-key", "", "pw")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid key PEM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePrivateKey_PKCS8(t *testing.T) {
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
der, _ := x509.MarshalPKCS8PrivateKey(key)
|
||||
parsed, err := ParsePrivateKey(der)
|
||||
if err != nil {
|
||||
t.Fatalf("ParsePrivateKey failed: %v", err)
|
||||
}
|
||||
if parsed == nil {
|
||||
t.Fatal("expected non-nil key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePrivateKey_EC(t *testing.T) {
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
der, _ := x509.MarshalECPrivateKey(key)
|
||||
parsed, err := ParsePrivateKey(der)
|
||||
if err != nil {
|
||||
t.Fatalf("ParsePrivateKey failed: %v", err)
|
||||
}
|
||||
if parsed == nil {
|
||||
t.Fatal("expected non-nil key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePrivateKey_Invalid(t *testing.T) {
|
||||
_, err := ParsePrivateKey([]byte("garbage"))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid key bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeThumbprint_Success(t *testing.T) {
|
||||
certPEM, _, err := generateTestCertAndKey()
|
||||
if err != nil {
|
||||
t.Fatalf("generate test cert: %v", err)
|
||||
}
|
||||
thumb, err := ComputeThumbprint(certPEM)
|
||||
if err != nil {
|
||||
t.Fatalf("ComputeThumbprint failed: %v", err)
|
||||
}
|
||||
if len(thumb) != 40 {
|
||||
t.Errorf("expected 40-char hex thumbprint, got %d chars", len(thumb))
|
||||
}
|
||||
// Verify uppercase hex
|
||||
for _, c := range thumb {
|
||||
if !((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
|
||||
t.Errorf("thumbprint contains non-uppercase-hex char: %c", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputeThumbprint_InvalidPEM(t *testing.T) {
|
||||
_, err := ComputeThumbprint("not a cert")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid PEM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateRandomPassword(t *testing.T) {
|
||||
pw, err := GenerateRandomPassword(32)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateRandomPassword failed: %v", err)
|
||||
}
|
||||
if len(pw) != 32 {
|
||||
t.Errorf("expected 32-char password, got %d", len(pw))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateRandomPassword_Uniqueness(t *testing.T) {
|
||||
pw1, _ := GenerateRandomPassword(32)
|
||||
pw2, _ := GenerateRandomPassword(32)
|
||||
if pw1 == pw2 {
|
||||
t.Error("two generated passwords should not be identical")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseCertificatePEM_Success(t *testing.T) {
|
||||
certPEM, _, err := generateTestCertAndKey()
|
||||
if err != nil {
|
||||
t.Fatalf("generate test cert: %v", err)
|
||||
}
|
||||
cert, err := ParseCertificatePEM(certPEM)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseCertificatePEM failed: %v", err)
|
||||
}
|
||||
if cert.Subject.CommonName != "test.example.com" {
|
||||
t.Errorf("expected CN test.example.com, got %s", cert.Subject.CommonName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseCertificatePEM_Invalid(t *testing.T) {
|
||||
_, err := ParseCertificatePEM("not a cert")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid PEM")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user