|
| 1 | +// Copyright 2025 Blindspot Software |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package tlsutil |
| 6 | + |
| 7 | +import ( |
| 8 | + "crypto/ed25519" |
| 9 | + "crypto/rand" |
| 10 | + "crypto/tls" |
| 11 | + "crypto/x509" |
| 12 | + "crypto/x509/pkix" |
| 13 | + "encoding/pem" |
| 14 | + "fmt" |
| 15 | + "log" |
| 16 | + "math/big" |
| 17 | + "net" |
| 18 | + "os" |
| 19 | + "path/filepath" |
| 20 | + "time" |
| 21 | +) |
| 22 | + |
| 23 | +const ( |
| 24 | + // File and directory permissions. |
| 25 | + certFileMode = 0644 // Public read, owner write. |
| 26 | + keyFileMode = 0600 // Owner read/write only |
| 27 | + dirMode = 0755 // Standard directory permissions. |
| 28 | + |
| 29 | + // Certificate serial number bit size. |
| 30 | + serialNumberBits = 128 |
| 31 | +) |
| 32 | + |
| 33 | +// GenerateSelfSignedCert creates a new self-signed TLS certificate and private key. |
| 34 | +// The certificate is valid for 10 years and includes localhost and system hostname in SANs. |
| 35 | +// Uses Ed25519 for better performance and security compared to RSA. |
| 36 | +func GenerateSelfSignedCert(certPath, keyPath string) error { |
| 37 | + // Generate Ed25519 private key (much faster than RSA) |
| 38 | + publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) |
| 39 | + if err != nil { |
| 40 | + return fmt.Errorf("failed to generate keys: %w", err) |
| 41 | + } |
| 42 | + |
| 43 | + // Create self-signed certificate |
| 44 | + derBytes, err := createSelfSignedCertificate(publicKey, privateKey) |
| 45 | + if err != nil { |
| 46 | + return err |
| 47 | + } |
| 48 | + |
| 49 | + err = writeCertificate(certPath, derBytes) |
| 50 | + if err != nil { |
| 51 | + return err |
| 52 | + } |
| 53 | + |
| 54 | + err = writePrivateKey(keyPath, privateKey) |
| 55 | + if err != nil { |
| 56 | + return err |
| 57 | + } |
| 58 | + |
| 59 | + log.Printf("Generated self-signed TLS certificate: %s", certPath) |
| 60 | + log.Printf("Generated private key: %s", keyPath) |
| 61 | + |
| 62 | + return nil |
| 63 | +} |
| 64 | + |
| 65 | +func createSelfSignedCertificate(publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey) ([]byte, error) { |
| 66 | + // Generate a random serial number |
| 67 | + serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), serialNumberBits) |
| 68 | + |
| 69 | + serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) |
| 70 | + if err != nil { |
| 71 | + return nil, fmt.Errorf("failed to generate serial number: %w", err) |
| 72 | + } |
| 73 | + |
| 74 | + // Get system hostname for SANs |
| 75 | + hostname, err := os.Hostname() |
| 76 | + if err != nil { |
| 77 | + hostname = "localhost" // Fallback if hostname detection fails |
| 78 | + } |
| 79 | + |
| 80 | + template := &x509.Certificate{ |
| 81 | + SerialNumber: serialNumber, |
| 82 | + Subject: pkix.Name{ |
| 83 | + Organization: []string{"Blindspot Software"}, |
| 84 | + CommonName: "dutagent", |
| 85 | + }, |
| 86 | + NotBefore: time.Now(), |
| 87 | + NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), // 10 years |
| 88 | + KeyUsage: x509.KeyUsageDigitalSignature, |
| 89 | + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 90 | + BasicConstraintsValid: true, |
| 91 | + DNSNames: []string{"localhost", hostname}, |
| 92 | + IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, |
| 93 | + } |
| 94 | + |
| 95 | + derBytes, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey) |
| 96 | + if err != nil { |
| 97 | + return nil, fmt.Errorf("failed to create certificate: %w", err) |
| 98 | + } |
| 99 | + |
| 100 | + return derBytes, nil |
| 101 | +} |
| 102 | + |
| 103 | +func writeCertificate(certPath string, derBytes []byte) error { |
| 104 | + certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, certFileMode) |
| 105 | + if err != nil { |
| 106 | + return fmt.Errorf("failed to create certificate file: %w", err) |
| 107 | + } |
| 108 | + defer certOut.Close() |
| 109 | + |
| 110 | + err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) |
| 111 | + if err != nil { |
| 112 | + return fmt.Errorf("failed to write certificate: %w", err) |
| 113 | + } |
| 114 | + |
| 115 | + return nil |
| 116 | +} |
| 117 | + |
| 118 | +func writePrivateKey(keyPath string, privateKey ed25519.PrivateKey) error { |
| 119 | + // Marshal Ed25519 private key in PKCS8 format |
| 120 | + privBytes, err := x509.MarshalPKCS8PrivateKey(privateKey) |
| 121 | + if err != nil { |
| 122 | + return fmt.Errorf("failed to marshal private key: %w", err) |
| 123 | + } |
| 124 | + |
| 125 | + keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, keyFileMode) |
| 126 | + if err != nil { |
| 127 | + return fmt.Errorf("failed to create key file: %w", err) |
| 128 | + } |
| 129 | + defer keyOut.Close() |
| 130 | + |
| 131 | + err = pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) |
| 132 | + if err != nil { |
| 133 | + return fmt.Errorf("failed to write private key: %w", err) |
| 134 | + } |
| 135 | + |
| 136 | + return nil |
| 137 | +} |
| 138 | + |
| 139 | +// LoadOrGenerateCert attempts to load an existing TLS certificate/key pair. |
| 140 | +// If the files don't exist, it generates a new self-signed certificate. |
| 141 | +// If the files exist but cannot be loaded, it returns an error without overwriting them. |
| 142 | +func LoadOrGenerateCert(certPath, keyPath string) (tls.Certificate, error) { |
| 143 | + // Check if certificate and key files exist |
| 144 | + certExists := fileExists(certPath) |
| 145 | + keyExists := fileExists(keyPath) |
| 146 | + |
| 147 | + // If either file exists, we must load them (don't auto-generate) |
| 148 | + if certExists || keyExists { |
| 149 | + cert, err := tls.LoadX509KeyPair(certPath, keyPath) |
| 150 | + if err != nil { |
| 151 | + return tls.Certificate{}, fmt.Errorf("certificate/key files exist but failed to load (cert exists: %v, key exists: %v): %w", |
| 152 | + certExists, keyExists, err) |
| 153 | + } |
| 154 | + |
| 155 | + log.Printf("Loaded existing TLS certificate from: %s", certPath) |
| 156 | + |
| 157 | + return cert, nil |
| 158 | + } |
| 159 | + |
| 160 | + // Neither file exists, generate new certificate |
| 161 | + log.Printf("TLS certificate not found, generating new self-signed certificate...") |
| 162 | + |
| 163 | + // Derive directory from cert path |
| 164 | + certDir := filepath.Dir(certPath) |
| 165 | + keyDir := filepath.Dir(keyPath) |
| 166 | + |
| 167 | + // Ensure directories exist |
| 168 | + err := os.MkdirAll(certDir, dirMode) |
| 169 | + if err != nil { |
| 170 | + return tls.Certificate{}, fmt.Errorf("failed to create certificate directory: %w", err) |
| 171 | + } |
| 172 | + |
| 173 | + if certDir != keyDir { |
| 174 | + err := os.MkdirAll(keyDir, dirMode) |
| 175 | + if err != nil { |
| 176 | + return tls.Certificate{}, fmt.Errorf("failed to create key directory: %w", err) |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + // Generate certificate |
| 181 | + err = GenerateSelfSignedCert(certPath, keyPath) |
| 182 | + if err != nil { |
| 183 | + return tls.Certificate{}, err |
| 184 | + } |
| 185 | + |
| 186 | + // Load the newly generated certificate |
| 187 | + cert, err := tls.LoadX509KeyPair(certPath, keyPath) |
| 188 | + if err != nil { |
| 189 | + return tls.Certificate{}, fmt.Errorf("failed to load generated certificate: %w", err) |
| 190 | + } |
| 191 | + |
| 192 | + return cert, nil |
| 193 | +} |
| 194 | + |
| 195 | +// fileExists checks if a file exists and is not a directory. |
| 196 | +func fileExists(path string) bool { |
| 197 | + info, err := os.Stat(path) |
| 198 | + if err != nil { |
| 199 | + return false |
| 200 | + } |
| 201 | + |
| 202 | + return !info.IsDir() |
| 203 | +} |
0 commit comments