Files
ssw-mvp/scard/code/cmd/gen-pki/main.go
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

308 lines
8.9 KiB
Go

// gen-pki generates a software PKI hierarchy for the security connector.
//
// It is the "soft root of trust" used before the FPGA/TPM-backed root key is
// available: a self-signed root CA, a server certificate for the security
// server, and optionally a device certificate for a connector.
//
// This mirrors the hardware layout described in the design document, where the
// root key lives in the FPGA and never leaves it. Here the root key is an
// ordinary file, so this mode is for development and integration only.
//
// Usage:
//
// go run ./cmd/gen-pki --out ./bin/tls --server-host 198.19.249.3 --server-dns host.orb.internal
// go run ./cmd/gen-pki --out ./bin/tls --device-id connector-001 # additionally issue a device cert
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"flag"
"fmt"
"math/big"
"net"
"os"
"path/filepath"
"strings"
"time"
)
func main() {
var (
outDir string
serverHosts string
serverDNS string
deviceID string
validDays int
force bool
)
flag.StringVar(&outDir, "out", "./bin/tls", "output directory for the generated PKI")
flag.StringVar(&serverHosts, "server-host", "127.0.0.1", "comma-separated IP SANs for the server certificate")
flag.StringVar(&serverDNS, "server-dns", "localhost", "comma-separated DNS SANs for the server certificate")
flag.StringVar(&deviceID, "device-id", "", "if set, also issue a client certificate for this device")
flag.IntVar(&validDays, "days", 825, "certificate validity in days")
flag.BoolVar(&force, "force", false, "overwrite an existing root CA instead of reusing it")
flag.Parse()
if err := run(outDir, serverHosts, serverDNS, deviceID, validDays, force); err != nil {
fmt.Fprintf(os.Stderr, "gen-pki: %v\n", err)
os.Exit(1)
}
}
func run(outDir, serverHosts, serverDNS, deviceID string, validDays int, force bool) error {
if err := os.MkdirAll(outDir, 0o755); err != nil {
return fmt.Errorf("failed to create output directory: %w", err)
}
caCertPath := filepath.Join(outDir, "ca-cert.pem")
caKeyPath := filepath.Join(outDir, "ca-key.pem")
// Reuse an existing root CA when possible, so that re-running the tool to
// add a device certificate does not invalidate everything issued so far.
caCert, caKey, reused, err := loadOrCreateCA(caCertPath, caKeyPath, validDays, force)
if err != nil {
return err
}
if reused {
fmt.Printf("root CA : reusing %s\n", caCertPath)
} else {
fmt.Printf("root CA : %s\n", caCertPath)
fmt.Printf("root CA key : %s (KEEP THIS SECRET)\n", caKeyPath)
}
// Server certificate.
ips, dnsNames := parseSANs(serverHosts, serverDNS)
serverTmpl := &x509.Certificate{
SerialNumber: mustSerial(),
Subject: pkix.Name{
Organization: []string{"security-connector"},
CommonName: "security-server",
},
NotBefore: time.Now().Add(-5 * time.Minute),
NotAfter: time.Now().AddDate(0, 0, validDays),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IPAddresses: ips,
DNSNames: dnsNames,
}
serverCertPath := filepath.Join(outDir, "server-cert.pem")
serverKeyPath := filepath.Join(outDir, "server-key.pem")
if err := issue(serverTmpl, caCert, caKey, serverCertPath, serverKeyPath); err != nil {
return fmt.Errorf("failed to issue server certificate: %w", err)
}
fmt.Printf("server cert : %s\n", serverCertPath)
fmt.Printf(" IP SANs : %v\n", ips)
fmt.Printf(" DNS SANs : %v\n", dnsNames)
// Optional device (client) certificate.
if deviceID != "" {
deviceTmpl := &x509.Certificate{
SerialNumber: mustSerial(),
Subject: pkix.Name{
Organization: []string{"security-connector"},
CommonName: deviceID,
},
NotBefore: time.Now().Add(-5 * time.Minute),
NotAfter: time.Now().AddDate(0, 0, validDays),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
}
devCertPath := filepath.Join(outDir, fmt.Sprintf("%s-cert.pem", deviceID))
devKeyPath := filepath.Join(outDir, fmt.Sprintf("%s-key.pem", deviceID))
if err := issue(deviceTmpl, caCert, caKey, devCertPath, devKeyPath); err != nil {
return fmt.Errorf("failed to issue device certificate: %w", err)
}
fmt.Printf("device cert : %s\n", devCertPath)
}
return nil
}
// loadOrCreateCA returns an existing root CA if one is present, otherwise it
// creates a new self-signed root.
func loadOrCreateCA(certPath, keyPath string, validDays int, force bool) (*x509.Certificate, *ecdsa.PrivateKey, bool, error) {
if !force {
cert, key, err := loadCA(certPath, keyPath)
if err == nil {
return cert, key, true, nil
}
if !os.IsNotExist(err) && !strings.Contains(err.Error(), "no such file") {
// A malformed existing CA is a hard error; silently replacing it
// would invalidate previously issued certificates.
if _, statErr := os.Stat(certPath); statErr == nil {
return nil, nil, false, fmt.Errorf("existing CA at %s is unusable (%v); pass --force to replace it", certPath, err)
}
}
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, false, err
}
tmpl := &x509.Certificate{
SerialNumber: mustSerial(),
Subject: pkix.Name{
Organization: []string{"security-connector"},
CommonName: "security-connector Root CA (software)",
},
NotBefore: time.Now().Add(-5 * time.Minute),
NotAfter: time.Now().AddDate(0, 0, validDays*2),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
IsCA: true,
MaxPathLen: 1,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
return nil, nil, false, err
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, nil, false, err
}
if err := writeCert(certPath, der); err != nil {
return nil, nil, false, err
}
if err := writeKey(keyPath, key); err != nil {
return nil, nil, false, err
}
return cert, key, false, nil
}
func loadCA(certPath, keyPath string) (*x509.Certificate, *ecdsa.PrivateKey, error) {
certPEM, err := os.ReadFile(certPath)
if err != nil {
return nil, nil, err
}
keyPEM, err := os.ReadFile(keyPath)
if err != nil {
return nil, nil, err
}
certBlock, _ := pem.Decode(certPEM)
if certBlock == nil {
return nil, nil, fmt.Errorf("failed to decode CA certificate PEM")
}
cert, err := x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return nil, nil, err
}
if !cert.IsCA {
return nil, nil, fmt.Errorf("certificate at %s is not a CA", certPath)
}
keyBlock, _ := pem.Decode(keyPEM)
if keyBlock == nil {
return nil, nil, fmt.Errorf("failed to decode CA key PEM")
}
key, err := x509.ParseECPrivateKey(keyBlock.Bytes)
if err != nil {
return nil, nil, err
}
return cert, key, nil
}
// issue creates a leaf certificate signed by the CA and writes the key pair.
func issue(tmpl, caCert *x509.Certificate, caKey *ecdsa.PrivateKey, certPath, keyPath string) error {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, caCert, &key.PublicKey, caKey)
if err != nil {
return err
}
if err := writeCert(certPath, der); err != nil {
return err
}
return writeKey(keyPath, key)
}
func writeCert(path string, der []byte) error {
buf := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
return os.WriteFile(path, buf, 0o644)
}
func writeKey(path string, key *ecdsa.PrivateKey) error {
der, err := x509.MarshalECPrivateKey(key)
if err != nil {
return err
}
buf := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})
// Private keys must not be world-readable.
return os.WriteFile(path, buf, 0o600)
}
func parseSANs(hosts, dns string) ([]net.IP, []string) {
var ips []net.IP
for _, h := range strings.Split(hosts, ",") {
h = strings.TrimSpace(h)
if h == "" {
continue
}
if ip := net.ParseIP(h); ip != nil {
ips = append(ips, ip)
}
}
// Always include loopback so local smoke tests work.
if !containsIP(ips, net.ParseIP("127.0.0.1")) {
ips = append(ips, net.ParseIP("127.0.0.1"))
}
var names []string
for _, d := range strings.Split(dns, ",") {
d = strings.TrimSpace(d)
if d != "" {
names = append(names, d)
}
}
if !containsStr(names, "localhost") {
names = append(names, "localhost")
}
return ips, names
}
func containsIP(list []net.IP, ip net.IP) bool {
for _, v := range list {
if v.Equal(ip) {
return true
}
}
return false
}
func containsStr(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}
func mustSerial() *big.Int {
limit := new(big.Int).Lsh(big.NewInt(1), 128)
n, err := rand.Int(rand.Reader, limit)
if err != nil {
panic(fmt.Sprintf("gen-pki: failed to generate serial number: %v", err))
}
return n
}