Added certificate revocation and CRL generation code.
This commit is contained in:
240
ca.go
240
ca.go
@@ -12,6 +12,7 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
@@ -40,6 +41,10 @@ type _CAConfig struct {
|
||||
Paths Paths `hcl:"paths,block"`
|
||||
}
|
||||
|
||||
func (c *_CAConfig) StateName() string {
|
||||
return c.Label + "_state.json"
|
||||
}
|
||||
|
||||
type Configuration struct {
|
||||
Current _CAConfig `hcl:"ca,block"`
|
||||
}
|
||||
@@ -70,10 +75,11 @@ var CAConfig *_CAConfig
|
||||
var CAKey *rsa.PrivateKey
|
||||
var CACert *x509.Certificate
|
||||
|
||||
// LoadCA loads the CA config and sets the global CAConfig variable
|
||||
func LoadCA(path string) error {
|
||||
// LoadCAConfig parses and validates the CA config from the given path and stores it in the CAConfig global variable
|
||||
func LoadCAConfig() error {
|
||||
fmt.Printf("Loading CA config from %s\n", configPath)
|
||||
parser := hclparse.NewParser()
|
||||
file, diags := parser.ParseHCLFile(path)
|
||||
file, diags := parser.ParseHCLFile(configPath)
|
||||
if diags.HasErrors() {
|
||||
return fmt.Errorf("failed to parse HCL: %s", diags.Error())
|
||||
}
|
||||
@@ -91,9 +97,18 @@ func LoadCA(path string) error {
|
||||
if err := config.Current.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
CAConfig = &config.Current
|
||||
err := error(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadCA loads the CA config, certificate, key, and state
|
||||
func LoadCA() error {
|
||||
var err error
|
||||
|
||||
err = LoadCAConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Load CA key and certificate
|
||||
caCertPath := filepath.Join(CAConfig.Paths.Certificates, "ca_cert.pem")
|
||||
@@ -125,11 +140,7 @@ func LoadCA(path string) error {
|
||||
return fmt.Errorf("failed to parse CA private key: %v", err)
|
||||
}
|
||||
|
||||
// Derive caStatePath from caConfig label and config file path
|
||||
caDir := filepath.Dir(path)
|
||||
caLabel := config.Current.Label
|
||||
caStatePath := filepath.Join(caDir, caLabel+"_state.json")
|
||||
CAState, err = LoadCAState(caStatePath)
|
||||
err = LoadCAState()
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("failed to load CA state: %w", err)
|
||||
}
|
||||
@@ -178,58 +189,6 @@ func parseValidity(validity string) (time.Duration, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func GenerateCA() ([]byte, []byte, error) {
|
||||
// Use global CAConfig directly
|
||||
keySize := CAConfig.KeySize
|
||||
if keySize == 0 {
|
||||
keySize = 4096
|
||||
}
|
||||
priv, err := rsa.GenerateKey(rand.Reader, keySize)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
||||
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to generate serial number: %v", err)
|
||||
}
|
||||
validity, err := parseValidity(CAConfig.Validity)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
now := time.Now()
|
||||
tmpl := x509.Certificate{
|
||||
SerialNumber: serialNumber,
|
||||
Subject: pkix.Name{
|
||||
Country: []string{CAConfig.Country},
|
||||
Organization: []string{CAConfig.Organization},
|
||||
OrganizationalUnit: optionalSlice(CAConfig.OrganizationalUnit),
|
||||
Locality: optionalSlice(CAConfig.Locality),
|
||||
Province: optionalSlice(CAConfig.Province),
|
||||
CommonName: CAConfig.Name,
|
||||
},
|
||||
NotBefore: now,
|
||||
NotAfter: now.Add(validity),
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
BasicConstraintsValid: true,
|
||||
IsCA: true,
|
||||
}
|
||||
// Add email if present
|
||||
if CAConfig.Email != "" {
|
||||
tmpl.Subject.ExtraNames = append(tmpl.Subject.ExtraNames, pkix.AttributeTypeAndValue{
|
||||
Type: []int{1, 2, 840, 113549, 1, 9, 1}, // emailAddress OID
|
||||
Value: CAConfig.Email,
|
||||
})
|
||||
}
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &priv.PublicKey, priv)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
|
||||
return certPEM, keyPEM, nil
|
||||
}
|
||||
|
||||
func SavePEM(filename string, data []byte, secure bool, overwrite bool) error {
|
||||
if !overwrite {
|
||||
if _, err := os.Stat(filename); err == nil {
|
||||
@@ -280,43 +239,123 @@ func (c *_CAConfig) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func InitCA(configPath string, overwrite bool) {
|
||||
if err := LoadCA(configPath); err != nil {
|
||||
fmt.Println("Error loading config:", err)
|
||||
return
|
||||
func InitCA(overwrite bool) error {
|
||||
|
||||
var err error
|
||||
|
||||
err = LoadCAConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create certificates directory with 0755, private keys with 0700
|
||||
if CAConfig.Paths.Certificates != "" {
|
||||
if err := os.MkdirAll(CAConfig.Paths.Certificates, 0755); err != nil {
|
||||
fmt.Printf("Error creating certificates directory '%s': %v\n", CAConfig.Paths.Certificates, err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
}
|
||||
if CAConfig.Paths.PrivateKeys != "" {
|
||||
if err := os.MkdirAll(CAConfig.Paths.PrivateKeys, 0700); err != nil {
|
||||
fmt.Printf("Error creating private keys directory '%s': %v\n", CAConfig.Paths.PrivateKeys, err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
}
|
||||
certPEM, keyPEM, err := GenerateCA()
|
||||
if err != nil {
|
||||
fmt.Println("Error generating CA:", err)
|
||||
return
|
||||
|
||||
// Initialize CAState empty state with serial starting from 1
|
||||
CAState = &_CAState{
|
||||
Serial: 1, // Start serial from 1
|
||||
CreatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
UpdatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
Certificates: []CertificateRecord{},
|
||||
}
|
||||
|
||||
keySize := CAConfig.KeySize
|
||||
if keySize == 0 {
|
||||
keySize = 4096
|
||||
}
|
||||
priv, err := rsa.GenerateKey(rand.Reader, keySize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
||||
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate serial number: %v", err)
|
||||
}
|
||||
validity, err := parseValidity(CAConfig.Validity)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
// Store CA certificate creation time
|
||||
CAState.CreatedAt = now.UTC().Format(time.RFC3339)
|
||||
|
||||
tmpl := x509.Certificate{
|
||||
SerialNumber: serialNumber,
|
||||
Subject: pkix.Name{
|
||||
Country: []string{CAConfig.Country},
|
||||
Organization: []string{CAConfig.Organization},
|
||||
OrganizationalUnit: optionalSlice(CAConfig.OrganizationalUnit),
|
||||
Locality: optionalSlice(CAConfig.Locality),
|
||||
Province: optionalSlice(CAConfig.Province),
|
||||
CommonName: CAConfig.Name,
|
||||
},
|
||||
NotBefore: now,
|
||||
NotAfter: now.Add(validity),
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
BasicConstraintsValid: true,
|
||||
IsCA: true,
|
||||
}
|
||||
// Add email if present
|
||||
if CAConfig.Email != "" {
|
||||
tmpl.Subject.ExtraNames = append(tmpl.Subject.ExtraNames, pkix.AttributeTypeAndValue{
|
||||
Type: []int{1, 2, 840, 113549, 1, 9, 1}, // emailAddress OID
|
||||
Value: CAConfig.Email,
|
||||
})
|
||||
}
|
||||
certDER, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &priv.PublicKey, priv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
|
||||
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
|
||||
|
||||
if err := SavePEM(filepath.Join(CAConfig.Paths.Certificates, "ca_cert.pem"), certPEM, false, overwrite); err != nil {
|
||||
fmt.Println("Error saving CA certificate:", err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
if err := SavePEM(filepath.Join(CAConfig.Paths.PrivateKeys, "ca_key.pem"), keyPEM, true, overwrite); err != nil {
|
||||
fmt.Println("Error saving CA key:", err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
|
||||
// set last updated time in the CAState
|
||||
CAState.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
|
||||
// Save the state
|
||||
|
||||
err = SaveCAState()
|
||||
if err != nil {
|
||||
fmt.Println("Error saving CA state:", err)
|
||||
return err
|
||||
}
|
||||
fmt.Println("CA certificate and key generated.")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Helper: issue a single certificate and key, save to files, return error if any
|
||||
func issueSingleCertificate(def CertificateDefinition, overwrite, verbose bool) error {
|
||||
// Use global CAConfig directly
|
||||
// Validate Name
|
||||
if !isValidName(def.Name) {
|
||||
return fmt.Errorf("certificate name must be specified and contain only letters, numbers, dash, or underscore")
|
||||
}
|
||||
// Initialize Subject if not specified
|
||||
if def.Subject == "" {
|
||||
def.Subject = def.Name
|
||||
}
|
||||
|
||||
// Add default dns SAN for server/server-only if none specified
|
||||
if (def.Type == "server" || def.Type == "server-only") && len(def.SAN) == 0 {
|
||||
def.SAN = append(def.SAN, "dns:"+def.Subject)
|
||||
@@ -349,11 +388,14 @@ func issueSingleCertificate(def CertificateDefinition, overwrite, verbose bool)
|
||||
subjectPKIX = pkix.Name{CommonName: def.Subject}
|
||||
}
|
||||
|
||||
dateIssued := time.Now()
|
||||
expires := dateIssued.Add(validityDur)
|
||||
|
||||
certTmpl := x509.Certificate{
|
||||
SerialNumber: serialNumber,
|
||||
Subject: subjectPKIX,
|
||||
NotBefore: time.Now(),
|
||||
NotAfter: time.Now().Add(validityDur),
|
||||
NotBefore: dateIssued,
|
||||
NotAfter: expires,
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
}
|
||||
|
||||
@@ -397,8 +439,8 @@ func issueSingleCertificate(def CertificateDefinition, overwrite, verbose bool)
|
||||
if basename == "" {
|
||||
basename = def.Subject
|
||||
}
|
||||
certFile := filepath.Join(CAConfig.Paths.Certificates, basename+"."+def.Type+".crt.pem")
|
||||
keyFile := filepath.Join(CAConfig.Paths.PrivateKeys, basename+"."+def.Type+".key.pem")
|
||||
certFile := filepath.Join(CAConfig.Paths.Certificates, basename+".crt.pem")
|
||||
keyFile := filepath.Join(CAConfig.Paths.PrivateKeys, basename+".key.pem")
|
||||
if err := SavePEM(certFile, certPEM, false, overwrite); err != nil {
|
||||
return fmt.Errorf("error saving certificate: %v", err)
|
||||
}
|
||||
@@ -421,15 +463,20 @@ Certificate:
|
||||
def.SAN,
|
||||
)
|
||||
}
|
||||
CAState.UpdateCAStateAfterIssue(
|
||||
CAConfig.SerialType,
|
||||
basename,
|
||||
serialNumber,
|
||||
validityDur,
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
func IssueCertificate(configPath, subject, certType, validity string, san []string, name, fromFile string, overwrite, dryRun, verbose bool) {
|
||||
func IssueCertificate(configPath, subject, certType, validity string, san []string, name, fromFile string, overwrite, dryRun, verbose bool) error {
|
||||
if fromFile != "" {
|
||||
certDefs, defaults, err := LoadCertificatesFile(fromFile)
|
||||
if err != nil {
|
||||
fmt.Printf("Error loading certificates file: %v\n", err)
|
||||
return
|
||||
return fmt.Errorf("Error loading certificates file: %v", err)
|
||||
}
|
||||
successes := 0
|
||||
errors := 0
|
||||
@@ -464,34 +511,29 @@ func IssueCertificate(configPath, subject, certType, validity string, san []stri
|
||||
}
|
||||
}
|
||||
fmt.Printf("Batch complete: %d succeeded, %d failed.\n", successes, errors)
|
||||
// Save CA state after batch issuance
|
||||
caDir := filepath.Dir(configPath)
|
||||
caLabel := CAConfig.Label
|
||||
caStatePath := filepath.Join(caDir, caLabel+"_state.json")
|
||||
if err := SaveCAState(caStatePath, CAState); err != nil {
|
||||
if err := SaveCAState(); err != nil {
|
||||
fmt.Printf("Error saving CA state: %v\n", err)
|
||||
}
|
||||
return
|
||||
if errors > 0 {
|
||||
return fmt.Errorf("%d certificate(s) failed to issue", errors)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Single mode
|
||||
finalDef := renderCertificateDefTemplates(CertificateDefinition{Name: name, Subject: subject, Type: certType, Validity: validity, SAN: san}, nil)
|
||||
if dryRun {
|
||||
fmt.Printf("Would issue %s certificate for '%s' (dry run)\n", finalDef.Type, finalDef.Subject)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
err := issueSingleCertificate(finalDef, overwrite, verbose)
|
||||
if err != nil {
|
||||
fmt.Printf("Error: %v\n", err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
fmt.Printf("%s certificate and key for '%s' generated.\n", finalDef.Type, finalDef.Subject)
|
||||
// Save CA state after single issuance
|
||||
caDir := filepath.Dir(configPath)
|
||||
caLabel := CAConfig.Label
|
||||
caStatePath := filepath.Join(caDir, caLabel+"_state.json")
|
||||
if err := SaveCAState(caStatePath, CAState); err != nil {
|
||||
if err := SaveCAState(); err != nil {
|
||||
fmt.Printf("Error saving CA state: %v\n", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Extract defaults from certificates.hcl (now using new LoadCertificatesFile signature)
|
||||
@@ -616,3 +658,9 @@ func optionalSlice(s string) []string {
|
||||
}
|
||||
return []string{s}
|
||||
}
|
||||
|
||||
// Helper: validate certificate name using regex
|
||||
func isValidName(name string) bool {
|
||||
matched, _ := regexp.MatchString(`^[A-Za-z0-9_-]+$`, name)
|
||||
return matched
|
||||
}
|
||||
|
Reference in New Issue
Block a user