Refactor CA management and certificate generation
/ test-bash (push) Failing after 3s
/ test-python (push) Successful in 18s
/ test-go (push) Successful in 9m50s

- Removed the legacy simple-ca.sh script, consolidating functionality into Go code.
- Introduced a JSON configuration file (simple-ca.json) to manage CA settings, including validity periods and AIA base URLs.
- Enhanced the makeCA function to utilize configuration values for CA creation and AIA URL management.
- Updated makeCert and makePFX functions to support configuration-driven behavior.
- Improved error handling and user feedback throughout the CA and certificate generation processes.
- Added support for using Apple's OpenSSL for PKCS#12 file generation.
This commit is contained in:
slawek committed 2026-05-24 14:39:47 +02:00
1 parent 93fc382f9a
commit 16c228d2b1
4 files changed
+391 -617

No files matched your search

+248 -78
View File
@@ -27,22 +27,26 @@ import (
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"github.com/spf13/cobra"
"math/big"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/spf13/cobra"
"software.sslmate.com/src/go-pkcs12"
)
// ---- helpers ----------------------------------------------------------------
func dirExists(path string) bool {
info, err := os.Stat(path)
return err == nil && info.IsDir()
@@ -109,11 +113,84 @@ func loadKey(path string) (*rsa.PrivateKey, error) {
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
func rebuildCABundle(caDir string) error {
entries, err := os.ReadDir(caDir)
// ---- Config -----------------------------------------------------------------
type daysConfig struct {
CA int `json:"ca,omitempty"`
Cert int `json:"cert,omitempty"`
}
type configData struct {
OpenSSL string `json:"openssl,omitempty"`
AIABaseURL string `json:"aia_base_url,omitempty"`
IssuingCA string `json:"issuing_ca,omitempty"`
Days *daysConfig `json:"days,omitempty"`
Subordinates []string `json:"subordinates,omitempty"`
}
type Config struct {
path string
data configData
// isNew is true when the file did not exist at load time,
// so the first mutation always creates it.
isNew bool
}
func loadConfig(caDir string) *Config {
cfg := &Config{path: filepath.Join(caDir, "simple-ca.json")}
b, err := os.ReadFile(cfg.path)
if err != nil {
cfg.isNew = true
return cfg
}
if err := json.Unmarshal(b, &cfg.data); err != nil {
fmt.Fprintf(os.Stderr, "WARNING: could not read %s: %v\n", cfg.path, err)
cfg.isNew = true
}
return cfg
}
func (c *Config) save() error {
b, err := json.MarshalIndent(c.data, "", " ")
if err != nil {
return err
}
c.isNew = false
return os.WriteFile(c.path, append(b, '\n'), 0o644)
}
// ensure writes the file if it did not exist at load time.
func (c *Config) ensure() error {
if c.isNew {
return c.save()
}
return nil
}
// setAIABaseURL updates the stored URL (if changed) and persists.
func (c *Config) setAIABaseURL(url string) error {
if url != "" && c.data.AIABaseURL != url {
c.data.AIABaseURL = url
return c.save()
}
return c.ensure()
}
// addSubordinate registers name in the subordinates list (if absent) and persists.
func (c *Config) addSubordinate(name string) error {
for _, s := range c.data.Subordinates {
if s == name {
return c.ensure()
}
}
c.data.Subordinates = append(c.data.Subordinates, name)
sort.Strings(c.data.Subordinates)
return c.save()
}
// ---- CA bundle --------------------------------------------------------------
func rebuildCABundle(caDir string, cfg *Config) error {
var bundle []byte
rootPath := filepath.Join(caDir, "ca_cert.pem")
if fileExists(rootPath) {
@@ -123,12 +200,14 @@ func rebuildCABundle(caDir string) error {
}
bundle = append(bundle, data...)
}
for _, e := range entries {
name := e.Name()
if e.IsDir() || name == "ca_cert.pem" || !strings.HasSuffix(name, "_cert.pem") {
subs := append([]string(nil), cfg.data.Subordinates...)
sort.Strings(subs)
for _, name := range subs {
subCert := filepath.Join(caDir, name, "ca_cert.pem")
if !fileExists(subCert) {
continue
}
data, err := os.ReadFile(filepath.Join(caDir, name))
data, err := os.ReadFile(subCert)
if err != nil {
return err
}
@@ -137,7 +216,9 @@ func rebuildCABundle(caDir string) error {
return os.WriteFile(filepath.Join(caDir, "ca_bundle.pem"), bundle, 0o644)
}
func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string) error {
// ---- makeCA -----------------------------------------------------------------
func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string, cfg *Config) error {
if issuingCA == "ca" {
return errors.New("--issuing-ca cannot be 'ca' as it is reserved for the root CA")
}
@@ -148,26 +229,20 @@ func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string) error
return errors.New("CA name is required")
}
aiaFile := filepath.Join(caDir, "aia_base_url.txt")
// Inherit AIA URL from config when not provided on CLI.
if aiaBaseURL == "" {
if data, err := os.ReadFile(aiaFile); err == nil {
aiaBaseURL = strings.TrimSpace(string(data))
}
aiaBaseURL = cfg.data.AIABaseURL
}
prefix := issuingCA
if prefix == "" {
prefix = "ca"
}
rootCertPath := filepath.Join(caDir, "ca_cert.pem")
rootKeyPath := filepath.Join(caDir, "ca_key.pem")
caCertPath := filepath.Join(caDir, prefix+"_cert.pem")
caKeyPath := filepath.Join(caDir, prefix+"_key.pem")
isRoot := prefix == "ca"
// ---- root CA ----
if !fileExists(rootCertPath) || !fileExists(rootKeyPath) {
if !isRoot {
return fmt.Errorf("cannot create issuing CA '%s' without existing root CA certificate and key. Please create the root CA first", caName)
if issuingCA != "" {
return fmt.Errorf(
"cannot create issuing CA '%s' without existing root CA certificate and key. "+
"Please create the root CA first", caName)
}
fmt.Printf("Generating CA certificate '%s' and key...\n", caName)
key, err := rsa.GenerateKey(rand.Reader, 4096)
@@ -199,19 +274,22 @@ func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string) error
if err := writeCert(der, rootCertPath); err != nil {
return err
}
if err := rebuildCABundle(caDir); err != nil {
if err := rebuildCABundle(caDir, cfg); err != nil {
return err
}
if aiaBaseURL != "" {
if err := os.WriteFile(aiaFile, []byte(aiaBaseURL), 0o644); err != nil {
return err
}
}
return nil
return cfg.setAIABaseURL(aiaBaseURL)
}
if !fileExists(caCertPath) || !fileExists(caKeyPath) {
// ---- issuing CA ----
issuingCADir := filepath.Join(caDir, issuingCA)
issuingCACert := filepath.Join(issuingCADir, "ca_cert.pem")
issuingCAKey := filepath.Join(issuingCADir, "ca_key.pem")
if !fileExists(issuingCACert) || !fileExists(issuingCAKey) {
fmt.Printf("Generating issuing CA certificate '%s' and key...\n", caName)
if err := os.MkdirAll(issuingCADir, 0o755); err != nil {
return err
}
rootCert, err := loadCert(rootCertPath)
if err != nil {
return err
@@ -247,38 +325,37 @@ func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string) error
if err != nil {
return err
}
if err := writeKey(key, caKeyPath); err != nil {
if err := writeKey(key, issuingCAKey); err != nil {
return err
}
if err := writeCert(der, caCertPath); err != nil {
if err := writeCert(der, issuingCACert); err != nil {
return err
}
}
if err := rebuildCABundle(caDir); err != nil {
if err := cfg.addSubordinate(issuingCA); err != nil {
return err
}
if aiaBaseURL != "" {
if err := os.WriteFile(aiaFile, []byte(aiaBaseURL), 0o644); err != nil {
if aiaBaseURL != "" && aiaBaseURL != cfg.data.AIABaseURL {
cfg.data.AIABaseURL = aiaBaseURL
if err := cfg.save(); err != nil {
return err
}
}
return nil
return rebuildCABundle(caDir, cfg)
}
// ---- makeCert ---------------------------------------------------------------
var (
ipRE = regexp.MustCompile(`^[0-9]{1,3}(\.[0-9]{1,3}){3}$`)
dnsRE = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)*$`)
)
func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA string, days int) error {
func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA string, days int, cfg *Config) error {
if issuingCA == "ca" {
return errors.New("--issuing-ca cannot be 'ca' as it is reserved for the root CA")
}
prefix := issuingCA
if prefix == "" {
prefix = "ca"
}
if certDir == "" || !dirExists(certDir) {
return fmt.Errorf("certificate directory %s does not exist", certDir)
}
@@ -292,16 +369,25 @@ func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA strin
return fmt.Errorf("invalid subject name '%s'. Must be a valid DNS name", subjectName)
}
aiaFile := filepath.Join(caDir, "aia_base_url.txt")
aiaURL := ""
if data, err := os.ReadFile(aiaFile); err == nil {
aiaURL = strings.TrimSpace(string(data)) + "/" + prefix + "_cert.crt"
signingDir := caDir
if issuingCA != "" {
signingDir = filepath.Join(caDir, issuingCA)
}
caCertPath := filepath.Join(signingDir, "ca_cert.pem")
caKeyPath := filepath.Join(signingDir, "ca_key.pem")
if !fileExists(caCertPath) || !fileExists(caKeyPath) {
return fmt.Errorf(
"signing CA certificate and key not found in %s. Please set up a signing CA first",
signingDir)
}
caCertPath := filepath.Join(caDir, prefix+"_cert.pem")
caKeyPath := filepath.Join(caDir, prefix+"_key.pem")
if !fileExists(caCertPath) || !fileExists(caKeyPath) {
return fmt.Errorf("signing CA certificate and key not found in %s. Please call setup a signing CA first", caDir)
aiaURL := ""
if base := cfg.data.AIABaseURL; base != "" {
if issuingCA != "" {
aiaURL = base + "/" + issuingCA + "/ca_cert.crt"
} else {
aiaURL = base + "/ca_cert.crt"
}
}
certName := subjectName
@@ -379,22 +465,18 @@ func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA strin
return writeCert(der, certOut)
}
func makePFX(certPath, caDir, issuingCA, password string) error {
// ---- makePFX ----------------------------------------------------------------
func makePFX(certPath, caDir, issuingCA, password string, appleOpenSSL bool) error {
if issuingCA == "ca" {
return errors.New("--issuing-ca cannot be 'ca' as it is reserved for the root CA")
}
prefix := issuingCA
if prefix == "" {
prefix = "ca"
}
rootCertPath := filepath.Join(caDir, "ca_cert.pem")
rootKeyPath := filepath.Join(caDir, "ca_key.pem")
caCertPath := filepath.Join(caDir, prefix+"_cert.pem")
caKeyPath := filepath.Join(caDir, prefix+"_key.pem")
certDir := filepath.Dir(certPath)
certName := strings.TrimSuffix(filepath.Base(certPath), "_cert.pem")
keyPath := filepath.Join(certDir, certName+"_key.pem")
pfxPath := filepath.Join(certDir, certName+".pfx")
rootCertPath := filepath.Join(caDir, "ca_cert.pem")
if !dirExists(certDir) {
return fmt.Errorf("certificate directory %s does not exist", certDir)
@@ -405,12 +487,15 @@ func makePFX(certPath, caDir, issuingCA, password string) error {
if !fileExists(certPath) || !fileExists(keyPath) {
return errors.New("server certificate or key not found")
}
if !fileExists(rootCertPath) || !fileExists(rootKeyPath) {
return fmt.Errorf("CA certificate or key not found in %s", caDir)
if !fileExists(rootCertPath) {
return fmt.Errorf("CA certificate not found in %s", caDir)
}
var issuingCACertPath string
if issuingCA != "" {
if !fileExists(caCertPath) || !fileExists(caKeyPath) {
return fmt.Errorf("issuing CA certificate or key not found in %s", caDir)
issuingCACertPath = filepath.Join(caDir, issuingCA, "ca_cert.pem")
if !fileExists(issuingCACertPath) {
return fmt.Errorf("issuing CA certificate not found: %s", issuingCACertPath)
}
}
@@ -418,7 +503,6 @@ func makePFX(certPath, caDir, issuingCA, password string) error {
password = "changeit"
}
pfxPath := filepath.Join(certDir, certName+".pfx")
if fileExists(pfxPath) {
fmt.Println("PKCS#12 (PFX) file already exists, aborting generation.")
return errors.New("PFX file already exists")
@@ -426,6 +510,10 @@ func makePFX(certPath, caDir, issuingCA, password string) error {
fmt.Print("Generating PKCS#12 (PFX) file...")
if appleOpenSSL {
return makePFXViaAppleOpenSSL(certPath, keyPath, rootCertPath, issuingCACertPath, pfxPath, password)
}
cert, err := loadCert(certPath)
if err != nil {
return err
@@ -434,14 +522,13 @@ func makePFX(certPath, caDir, issuingCA, password string) error {
if err != nil {
return err
}
chain := []*x509.Certificate{}
root, err := loadCert(rootCertPath)
if err != nil {
return err
}
chain = append(chain, root)
chain := []*x509.Certificate{root}
if issuingCA != "" {
issuing, err := loadCert(caCertPath)
issuing, err := loadCert(issuingCACertPath)
if err != nil {
return err
}
@@ -459,6 +546,53 @@ func makePFX(certPath, caDir, issuingCA, password string) error {
return nil
}
func makePFXViaAppleOpenSSL(certPath, keyPath, rootCertPath, issuingCACertPath, pfxPath, password string) error {
chainFile, err := os.CreateTemp("", "chain-*.pem")
if err != nil {
return err
}
defer os.Remove(chainFile.Name())
rootData, err := os.ReadFile(rootCertPath)
if err != nil {
chainFile.Close()
return err
}
if _, err := chainFile.Write(rootData); err != nil {
chainFile.Close()
return err
}
if issuingCACertPath != "" {
issuingData, err := os.ReadFile(issuingCACertPath)
if err != nil {
chainFile.Close()
return err
}
if _, err := chainFile.Write(issuingData); err != nil {
chainFile.Close()
return err
}
}
chainFile.Close()
cmd := exec.Command("/usr/bin/openssl", "pkcs12",
"-export", "-out", pfxPath,
"-inkey", keyPath,
"-in", certPath,
"-certfile", chainFile.Name(),
"-password", "pass:"+password,
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("apple openssl pkcs12 failed: %w", err)
}
fmt.Println("done.")
return nil
}
// ---- CLI --------------------------------------------------------------------
func resolveCADir(flagVal string) string {
if flagVal != "" {
return flagVal
@@ -492,12 +626,26 @@ func newMakeCACmd() *cobra.Command {
Use: "make-ca CA_NAME",
Short: "Create a root or issuing CA.",
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
return makeCA(resolveCADir(caDir), args[0], days, issuingCA, aiaBaseURL)
RunE: func(c *cobra.Command, args []string) error {
dir := resolveCADir(caDir)
cfg := loadConfig(dir)
effectiveDays := days
if !c.Flags().Changed("days") {
if cfg.data.Days != nil && cfg.data.Days.CA > 0 {
effectiveDays = cfg.data.Days.CA
} else {
effectiveDays = 3650
}
}
effectiveIssuingCA := issuingCA
if !c.Flags().Changed("issuing-ca") && cfg.data.IssuingCA != "" {
effectiveIssuingCA = cfg.data.IssuingCA
}
return makeCA(dir, args[0], effectiveDays, effectiveIssuingCA, aiaBaseURL, cfg)
},
}
cmd.Flags().IntVar(&days, "days", 3650, "validity period in days")
cmd.Flags().StringVar(&issuingCA, "issuing-ca", "", "issuing CA file prefix (creates an issuing CA signed by the root)")
cmd.Flags().StringVar(&issuingCA, "issuing-ca", "", "issuing CA directory name (creates an issuing CA signed by the root)")
cmd.Flags().StringVar(&aiaBaseURL, "aia-base-url", "", "base URL for the AIA caIssuers extension")
cmd.Flags().StringVar(&caDir, "ca-dir", "", "directory for CA files")
return cmd
@@ -514,34 +662,56 @@ func newMakeCertCmd() *cobra.Command {
Use: "make-cert SUBJECT [SAN...]",
Short: "Create a server/client certificate signed by the CA.",
Args: cobra.MinimumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
return makeCert(certDir, args[0], args[1:], resolveCADir(caDir), issuingCA, days)
RunE: func(c *cobra.Command, args []string) error {
dir := resolveCADir(caDir)
cfg := loadConfig(dir)
effectiveDays := days
if !c.Flags().Changed("days") {
if cfg.data.Days != nil && cfg.data.Days.Cert > 0 {
effectiveDays = cfg.data.Days.Cert
} else {
effectiveDays = 365
}
}
effectiveIssuingCA := issuingCA
if !c.Flags().Changed("issuing-ca") && cfg.data.IssuingCA != "" {
effectiveIssuingCA = cfg.data.IssuingCA
}
return makeCert(certDir, args[0], args[1:], dir, effectiveIssuingCA, effectiveDays, cfg)
},
}
cmd.Flags().StringVar(&certDir, "cert-dir", "", "directory to store the certificate files")
cmd.Flags().StringVar(&caDir, "ca-dir", "", "CA directory")
cmd.Flags().StringVar(&issuingCA, "issuing-ca", "", "issuing CA file prefix")
cmd.Flags().StringVar(&issuingCA, "issuing-ca", "", "issuing CA directory name")
cmd.Flags().IntVar(&days, "days", 365, "validity period in days")
return cmd
}
func newMakePFXCmd() *cobra.Command {
var (
caDir string
issuingCA string
password string
caDir string
issuingCA string
password string
appleOpenSSL bool
)
cmd := &cobra.Command{
Use: "make-pfx CERT_PATH",
Short: "Create a PKCS#12 (PFX) bundle for a leaf certificate.",
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
return makePFX(args[0], resolveCADir(caDir), issuingCA, password)
RunE: func(c *cobra.Command, args []string) error {
dir := resolveCADir(caDir)
cfg := loadConfig(dir)
effectiveIssuingCA := issuingCA
if !c.Flags().Changed("issuing-ca") && cfg.data.IssuingCA != "" {
effectiveIssuingCA = cfg.data.IssuingCA
}
return makePFX(args[0], dir, effectiveIssuingCA, password, appleOpenSSL)
},
}
cmd.Flags().StringVar(&caDir, "ca-dir", "", "CA directory")
cmd.Flags().StringVar(&issuingCA, "issuing-ca", "", "issuing CA file prefix")
cmd.Flags().StringVar(&issuingCA, "issuing-ca", "", "issuing CA directory name")
cmd.Flags().StringVar(&password, "password", "", "PFX password (default: changeit)")
cmd.Flags().BoolVar(&appleOpenSSL, "apple-openssl", false, "use Apple's bundled /usr/bin/openssl for PKCS12 generation")
return cmd
}