Refactor simple-ca: Remove JSON config and streamline AIA URL handling
- Removed the JSON configuration structure and related functions. - Introduced plain text file for AIA base URL management. - Updated CA and certificate creation functions to directly read/write AIA URL. - Simplified CA bundle rebuilding logic by directly reading subdirectories. - Enhanced test coverage for CA and certificate creation, including PFX generation. - Adjusted test cases to reflect changes in directory structure and file handling.
This commit is contained in:
1 parent
04d8dab9bc
commit
935167ca8c
7 files changed
+440
-316
No files matched your search
+114
-219
@@ -27,7 +27,6 @@ import (
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -37,7 +36,6 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -113,85 +111,27 @@ func loadKey(path string) (*rsa.PrivateKey, error) {
|
||||
return x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
}
|
||||
|
||||
// ---- Config -----------------------------------------------------------------
|
||||
// ---- AIA base URL -----------------------------------------------------------
|
||||
|
||||
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)
|
||||
func readAIABaseURL(caDir string) string {
|
||||
b, err := os.ReadFile(filepath.Join(caDir, "aia_base_url.txt"))
|
||||
if err != nil {
|
||||
cfg.isNew = true
|
||||
return cfg
|
||||
return ""
|
||||
}
|
||||
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
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
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()
|
||||
func writeAIABaseURL(caDir, url string) error {
|
||||
return os.WriteFile(filepath.Join(caDir, "aia_base_url.txt"), []byte(url+"\n"), 0o644)
|
||||
}
|
||||
|
||||
// ---- CA bundle --------------------------------------------------------------
|
||||
|
||||
func rebuildCABundle(caDir string, cfg *Config) error {
|
||||
// rebuildCABundle writes ca_bundle.pem containing the root CA cert followed by
|
||||
// all issuing CA certs found in immediate subdirectories.
|
||||
func rebuildCABundle(caDir string) error {
|
||||
var bundle []byte
|
||||
|
||||
rootPath := filepath.Join(caDir, "ca_cert.pem")
|
||||
if fileExists(rootPath) {
|
||||
data, err := os.ReadFile(rootPath)
|
||||
@@ -200,10 +140,13 @@ func rebuildCABundle(caDir string, cfg *Config) error {
|
||||
}
|
||||
bundle = append(bundle, data...)
|
||||
}
|
||||
subs := append([]string(nil), cfg.data.Subordinates...)
|
||||
sort.Strings(subs)
|
||||
for _, name := range subs {
|
||||
subCert := filepath.Join(caDir, name, "ca_cert.pem")
|
||||
|
||||
entries, _ := os.ReadDir(caDir)
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
subCert := filepath.Join(caDir, e.Name(), "ca_cert.pem")
|
||||
if !fileExists(subCert) {
|
||||
continue
|
||||
}
|
||||
@@ -213,25 +156,25 @@ func rebuildCABundle(caDir string, cfg *Config) error {
|
||||
}
|
||||
bundle = append(bundle, data...)
|
||||
}
|
||||
|
||||
return os.WriteFile(filepath.Join(caDir, "ca_bundle.pem"), bundle, 0o644)
|
||||
}
|
||||
|
||||
// ---- makeCA -----------------------------------------------------------------
|
||||
|
||||
func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string, cfg *Config) error {
|
||||
func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string) error {
|
||||
if issuingCA == "ca" {
|
||||
return errors.New("--issuing-ca cannot be 'ca' as it is reserved for the root CA")
|
||||
return errors.New("--issuing-ca cannot be 'ca'")
|
||||
}
|
||||
if caDir == "" || !dirExists(caDir) {
|
||||
return fmt.Errorf("certificate directory %s does not exist", caDir)
|
||||
if !dirExists(caDir) {
|
||||
return fmt.Errorf("CA directory %s does not exist", caDir)
|
||||
}
|
||||
if caName == "" {
|
||||
return errors.New("CA name is required")
|
||||
}
|
||||
|
||||
// Inherit AIA URL from config when not provided on CLI.
|
||||
if aiaBaseURL == "" {
|
||||
aiaBaseURL = cfg.data.AIABaseURL
|
||||
aiaBaseURL = readAIABaseURL(caDir)
|
||||
}
|
||||
|
||||
rootCertPath := filepath.Join(caDir, "ca_cert.pem")
|
||||
@@ -241,10 +184,10 @@ func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string, cfg *C
|
||||
if !fileExists(rootCertPath) || !fileExists(rootKeyPath) {
|
||||
if issuingCA != "" {
|
||||
return fmt.Errorf(
|
||||
"cannot create issuing CA '%s' without existing root CA certificate and key. "+
|
||||
"cannot create issuing CA '%s' without existing root CA. "+
|
||||
"Please create the root CA first", caName)
|
||||
}
|
||||
fmt.Printf("Generating CA certificate '%s' and key...\n", caName)
|
||||
fmt.Printf("Generating root CA certificate '%s' and key...\n", caName)
|
||||
key, err := rsa.GenerateKey(rand.Reader, 4096)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -274,10 +217,12 @@ func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string, cfg *C
|
||||
if err := writeCert(der, rootCertPath); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rebuildCABundle(caDir, cfg); err != nil {
|
||||
return err
|
||||
if aiaBaseURL != "" {
|
||||
if err := writeAIABaseURL(caDir, aiaBaseURL); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return cfg.setAIABaseURL(aiaBaseURL)
|
||||
return rebuildCABundle(caDir)
|
||||
}
|
||||
|
||||
// ---- issuing CA ----
|
||||
@@ -285,64 +230,57 @@ func makeCA(caDir, caName string, days int, issuingCA, aiaBaseURL string, cfg *C
|
||||
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
|
||||
}
|
||||
rootKey, err := loadKey(rootKeyPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := rsa.GenerateKey(rand.Reader, 4096)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serial, err := randomSerial()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{CommonName: caName},
|
||||
NotBefore: now,
|
||||
NotAfter: now.AddDate(0, 0, days),
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
MaxPathLen: 0,
|
||||
MaxPathLenZero: true,
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
}
|
||||
if aiaBaseURL != "" {
|
||||
tmpl.IssuingCertificateURL = []string{aiaBaseURL + "/ca_cert.crt"}
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, rootCert, &key.PublicKey, rootKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeKey(key, issuingCAKey); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeCert(der, issuingCACert); err != nil {
|
||||
return err
|
||||
}
|
||||
if fileExists(issuingCACert) && fileExists(issuingCAKey) {
|
||||
fmt.Printf("Issuing CA '%s' already exists in %s, skipping.\n", issuingCA, issuingCADir)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := cfg.addSubordinate(issuingCA); err != nil {
|
||||
fmt.Printf("Generating issuing CA certificate '%s' and key...\n", caName)
|
||||
if err := os.MkdirAll(issuingCADir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if aiaBaseURL != "" && aiaBaseURL != cfg.data.AIABaseURL {
|
||||
cfg.data.AIABaseURL = aiaBaseURL
|
||||
if err := cfg.save(); err != nil {
|
||||
return err
|
||||
}
|
||||
rootCert, err := loadCert(rootCertPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return rebuildCABundle(caDir, cfg)
|
||||
rootKey, err := loadKey(rootKeyPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := rsa.GenerateKey(rand.Reader, 4096)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serial, err := randomSerial()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{CommonName: caName},
|
||||
NotBefore: now,
|
||||
NotAfter: now.AddDate(0, 0, days),
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
MaxPathLen: 0,
|
||||
MaxPathLenZero: true,
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
}
|
||||
if aiaBaseURL != "" {
|
||||
tmpl.IssuingCertificateURL = []string{aiaBaseURL + "/ca_cert.crt"}
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, rootCert, &key.PublicKey, rootKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeKey(key, issuingCAKey); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeCert(der, issuingCACert); err != nil {
|
||||
return err
|
||||
}
|
||||
return rebuildCABundle(caDir)
|
||||
}
|
||||
|
||||
// ---- makeCert ---------------------------------------------------------------
|
||||
@@ -352,12 +290,9 @@ var (
|
||||
dnsRE = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)*$`)
|
||||
)
|
||||
|
||||
func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA string, days int, cfg *Config) error {
|
||||
func makeCert(subjectName string, sans []string, caDir, certDir, issuingCA string, days int) error {
|
||||
if issuingCA == "ca" {
|
||||
return errors.New("--issuing-ca cannot be 'ca' as it is reserved for the root CA")
|
||||
}
|
||||
if certDir == "" || !dirExists(certDir) {
|
||||
return fmt.Errorf("certificate directory %s does not exist", certDir)
|
||||
return errors.New("--issuing-ca cannot be 'ca'")
|
||||
}
|
||||
if !dirExists(caDir) {
|
||||
return fmt.Errorf("CA directory %s does not exist", caDir)
|
||||
@@ -373,6 +308,13 @@ func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA strin
|
||||
if issuingCA != "" {
|
||||
signingDir = filepath.Join(caDir, issuingCA)
|
||||
}
|
||||
if certDir == "" {
|
||||
certDir = signingDir
|
||||
}
|
||||
if !dirExists(certDir) {
|
||||
return fmt.Errorf("certificate directory %s does not exist", certDir)
|
||||
}
|
||||
|
||||
caCertPath := filepath.Join(signingDir, "ca_cert.pem")
|
||||
caKeyPath := filepath.Join(signingDir, "ca_key.pem")
|
||||
if !fileExists(caCertPath) || !fileExists(caKeyPath) {
|
||||
@@ -382,7 +324,7 @@ func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA strin
|
||||
}
|
||||
|
||||
aiaURL := ""
|
||||
if base := cfg.data.AIABaseURL; base != "" {
|
||||
if base := readAIABaseURL(caDir); base != "" {
|
||||
if issuingCA != "" {
|
||||
aiaURL = base + "/" + issuingCA + "/ca_cert.crt"
|
||||
} else {
|
||||
@@ -419,6 +361,7 @@ func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA strin
|
||||
certOut := filepath.Join(certDir, certName+"_cert.pem")
|
||||
keyOut := filepath.Join(certDir, certName+"_key.pem")
|
||||
if fileExists(certOut) && fileExists(keyOut) {
|
||||
fmt.Printf("Certificate already exists in %s, skipping.\n", certDir)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -469,7 +412,7 @@ func makeCert(certDir, subjectName string, sans []string, caDir, issuingCA strin
|
||||
|
||||
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")
|
||||
return errors.New("--issuing-ca cannot be 'ca'")
|
||||
}
|
||||
|
||||
certDir := filepath.Dir(certPath)
|
||||
@@ -488,7 +431,7 @@ func makePFX(certPath, caDir, issuingCA, password string, appleOpenSSL bool) err
|
||||
return errors.New("server certificate or key not found")
|
||||
}
|
||||
if !fileExists(rootCertPath) {
|
||||
return fmt.Errorf("CA certificate not found in %s", caDir)
|
||||
return fmt.Errorf("root CA certificate not found in %s", caDir)
|
||||
}
|
||||
|
||||
var issuingCACertPath string
|
||||
@@ -502,16 +445,14 @@ func makePFX(certPath, caDir, issuingCA, password string, appleOpenSSL bool) err
|
||||
if password == "" {
|
||||
password = "changeit"
|
||||
}
|
||||
|
||||
if fileExists(pfxPath) {
|
||||
fmt.Println("PKCS#12 (PFX) file already exists, aborting generation.")
|
||||
return errors.New("PFX file already exists")
|
||||
return errors.New("PKCS#12 (PFX) file already exists, aborting generation")
|
||||
}
|
||||
|
||||
fmt.Print("Generating PKCS#12 (PFX) file...")
|
||||
|
||||
if appleOpenSSL {
|
||||
return makePFXViaAppleOpenSSL(certPath, keyPath, rootCertPath, issuingCACertPath, pfxPath, password)
|
||||
return makePFXViaOpenSSL("/usr/bin/openssl", certPath, keyPath, rootCertPath, issuingCACertPath, pfxPath, password)
|
||||
}
|
||||
|
||||
cert, err := loadCert(certPath)
|
||||
@@ -546,7 +487,7 @@ func makePFX(certPath, caDir, issuingCA, password string, appleOpenSSL bool) err
|
||||
return nil
|
||||
}
|
||||
|
||||
func makePFXViaAppleOpenSSL(certPath, keyPath, rootCertPath, issuingCACertPath, pfxPath, password string) error {
|
||||
func makePFXViaOpenSSL(opensslBin, certPath, keyPath, rootCertPath, issuingCACertPath, pfxPath, password string) error {
|
||||
chainFile, err := os.CreateTemp("", "chain-*.pem")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -575,7 +516,7 @@ func makePFXViaAppleOpenSSL(certPath, keyPath, rootCertPath, issuingCACertPath,
|
||||
}
|
||||
chainFile.Close()
|
||||
|
||||
cmd := exec.Command("/usr/bin/openssl", "pkcs12",
|
||||
cmd := exec.Command(opensslBin, "pkcs12",
|
||||
"-export", "-out", pfxPath,
|
||||
"-inkey", keyPath,
|
||||
"-in", certPath,
|
||||
@@ -585,7 +526,7 @@ func makePFXViaAppleOpenSSL(certPath, keyPath, rootCertPath, issuingCACertPath,
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("apple openssl pkcs12 failed: %w", err)
|
||||
return fmt.Errorf("openssl pkcs12 failed: %w", err)
|
||||
}
|
||||
fmt.Println("done.")
|
||||
return nil
|
||||
@@ -616,102 +557,56 @@ func newRootCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
func newMakeCACmd() *cobra.Command {
|
||||
var (
|
||||
days int
|
||||
issuingCA string
|
||||
aiaBaseURL string
|
||||
caDir string
|
||||
)
|
||||
var days int
|
||||
var issuingCA, aiaBaseURL, caDir string
|
||||
cmd := &cobra.Command{
|
||||
Use: "make-ca CA_NAME",
|
||||
Short: "Create a root or issuing CA.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
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)
|
||||
RunE: func(_ *cobra.Command, args []string) error {
|
||||
return makeCA(resolveCADir(caDir), args[0], days, issuingCA, aiaBaseURL)
|
||||
},
|
||||
}
|
||||
cmd.Flags().IntVar(&days, "days", 3650, "validity period in days")
|
||||
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")
|
||||
cmd.Flags().StringVar(&issuingCA, "issuing-ca", "", "create an issuing CA with this directory name")
|
||||
cmd.Flags().StringVar(&aiaBaseURL, "aia-base-url", "", "base URL for AIA caIssuers extension")
|
||||
cmd.Flags().StringVar(&caDir, "ca-dir", "", "CA root directory")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newMakeCertCmd() *cobra.Command {
|
||||
var (
|
||||
certDir string
|
||||
caDir string
|
||||
issuingCA string
|
||||
days int
|
||||
)
|
||||
var certDir, caDir, issuingCA string
|
||||
var days int
|
||||
cmd := &cobra.Command{
|
||||
Use: "make-cert SUBJECT [SAN...]",
|
||||
Short: "Create a server/client certificate signed by the CA.",
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
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)
|
||||
RunE: func(_ *cobra.Command, args []string) error {
|
||||
return makeCert(args[0], args[1:], resolveCADir(caDir), certDir, issuingCA, days)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&certDir, "cert-dir", "", "directory to store the certificate files")
|
||||
cmd.Flags().StringVar(&caDir, "ca-dir", "", "CA directory")
|
||||
cmd.Flags().StringVar(&certDir, "cert-dir", "", "output directory (default: signing CA directory)")
|
||||
cmd.Flags().StringVar(&caDir, "ca-dir", "", "CA root directory")
|
||||
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
|
||||
appleOpenSSL bool
|
||||
)
|
||||
var caDir, issuingCA, password string
|
||||
var 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(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)
|
||||
RunE: func(_ *cobra.Command, args []string) error {
|
||||
return makePFX(args[0], resolveCADir(caDir), issuingCA, password, appleOpenSSL)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&caDir, "ca-dir", "", "CA directory")
|
||||
cmd.Flags().StringVar(&caDir, "ca-dir", "", "CA root directory")
|
||||
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")
|
||||
cmd.Flags().BoolVar(&appleOpenSSL, "apple-openssl", false, "use /usr/bin/openssl for PKCS12 (Apple-compatible format)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func verifyCert(t *testing.T, bundle, cert string) {
|
||||
t.Helper()
|
||||
out, err := exec.Command("openssl", "verify", "-CAfile", bundle, cert).CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("certificate verification failed for %s:\n%s", cert, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStandaloneCA(t *testing.T) {
|
||||
caDir := t.TempDir()
|
||||
|
||||
if err := makeCA(caDir, "Test CA", 3650, "", ""); err != nil {
|
||||
t.Fatalf("makeCA: %v", err)
|
||||
}
|
||||
if !fileExists(filepath.Join(caDir, "ca_cert.pem")) {
|
||||
t.Fatal("ca_cert.pem not created")
|
||||
}
|
||||
if !fileExists(filepath.Join(caDir, "ca_bundle.pem")) {
|
||||
t.Fatal("ca_bundle.pem not created")
|
||||
}
|
||||
verifyCert(t, filepath.Join(caDir, "ca_bundle.pem"), filepath.Join(caDir, "ca_cert.pem"))
|
||||
|
||||
if err := makeCert("test", []string{"test.example.com", "127.0.0.1"}, caDir, "", "", 365); err != nil {
|
||||
t.Fatalf("makeCert: %v", err)
|
||||
}
|
||||
certPath := filepath.Join(caDir, "test_cert.pem")
|
||||
if !fileExists(certPath) {
|
||||
t.Fatal("test_cert.pem not created in caDir")
|
||||
}
|
||||
verifyCert(t, filepath.Join(caDir, "ca_bundle.pem"), certPath)
|
||||
}
|
||||
|
||||
func TestTwoLevelCA(t *testing.T) {
|
||||
caDir := t.TempDir()
|
||||
|
||||
if err := makeCA(caDir, "Test Root CA", 3650, "", ""); err != nil {
|
||||
t.Fatalf("makeCA root: %v", err)
|
||||
}
|
||||
verifyCert(t, filepath.Join(caDir, "ca_bundle.pem"), filepath.Join(caDir, "ca_cert.pem"))
|
||||
|
||||
if err := makeCA(caDir, "Issuing CA", 3650, "issuing_ca", ""); err != nil {
|
||||
t.Fatalf("makeCA issuing: %v", err)
|
||||
}
|
||||
issuingCert := filepath.Join(caDir, "issuing_ca", "ca_cert.pem")
|
||||
if !fileExists(issuingCert) {
|
||||
t.Fatal("issuing_ca/ca_cert.pem not created")
|
||||
}
|
||||
verifyCert(t, filepath.Join(caDir, "ca_bundle.pem"), issuingCert)
|
||||
|
||||
if err := makeCert("test", []string{"test.example.com", "127.0.0.1"}, caDir, "", "issuing_ca", 365); err != nil {
|
||||
t.Fatalf("makeCert: %v", err)
|
||||
}
|
||||
certPath := filepath.Join(caDir, "issuing_ca", "test_cert.pem")
|
||||
if !fileExists(certPath) {
|
||||
t.Fatal("issuing_ca/test_cert.pem not created")
|
||||
}
|
||||
verifyCert(t, filepath.Join(caDir, "ca_bundle.pem"), certPath)
|
||||
|
||||
if err := makePFX(certPath, caDir, "issuing_ca", "s3cr3t", false); err != nil {
|
||||
t.Fatalf("makePFX: %v", err)
|
||||
}
|
||||
pfxPath := filepath.Join(caDir, "issuing_ca", "test.pfx")
|
||||
if !fileExists(pfxPath) {
|
||||
t.Fatal("issuing_ca/test.pfx not created")
|
||||
}
|
||||
out, err := exec.Command("openssl", "pkcs12", "-in", pfxPath, "-noout", "-info",
|
||||
"-password", "pass:s3cr3t").CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("PFX verification failed:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertDirOverride(t *testing.T) {
|
||||
caDir := t.TempDir()
|
||||
certDir := t.TempDir()
|
||||
|
||||
if err := makeCA(caDir, "Test CA", 3650, "", ""); err != nil {
|
||||
t.Fatalf("makeCA: %v", err)
|
||||
}
|
||||
if err := makeCert("test", []string{"test.example.com"}, caDir, certDir, "", 365); err != nil {
|
||||
t.Fatalf("makeCert: %v", err)
|
||||
}
|
||||
certPath := filepath.Join(certDir, "test_cert.pem")
|
||||
if !fileExists(certPath) {
|
||||
t.Fatal("test_cert.pem not created in certDir override")
|
||||
}
|
||||
verifyCert(t, filepath.Join(caDir, "ca_bundle.pem"), certPath)
|
||||
}
|
||||
|
||||
func TestAppleOpenSSL(t *testing.T) {
|
||||
if _, err := os.Stat("/usr/bin/openssl"); err != nil {
|
||||
t.Skip("/usr/bin/openssl not available")
|
||||
}
|
||||
|
||||
caDir := t.TempDir()
|
||||
|
||||
if err := makeCA(caDir, "Test CA", 3650, "", ""); err != nil {
|
||||
t.Fatalf("makeCA: %v", err)
|
||||
}
|
||||
if err := makeCA(caDir, "Issuing CA", 3650, "issuing_ca", ""); err != nil {
|
||||
t.Fatalf("makeCA issuing: %v", err)
|
||||
}
|
||||
if err := makeCert("test", []string{"test.example.com"}, caDir, "", "issuing_ca", 365); err != nil {
|
||||
t.Fatalf("makeCert: %v", err)
|
||||
}
|
||||
certPath := filepath.Join(caDir, "issuing_ca", "test_cert.pem")
|
||||
|
||||
if err := makePFX(certPath, caDir, "issuing_ca", "s3cr3t", true); err != nil {
|
||||
t.Fatalf("makePFX --apple-openssl: %v", err)
|
||||
}
|
||||
pfxPath := filepath.Join(caDir, "issuing_ca", "test.pfx")
|
||||
out, err := exec.Command("/usr/bin/openssl", "pkcs12", "-in", pfxPath, "-noout", "-info",
|
||||
"-password", "pass:s3cr3t").CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("Apple openssl PFX verification failed:\n%s", out)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user