tlscert.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // Package tlscert — gestión del certificado autofirmado on-box (Fase 9 R2).
  2. //
  3. // En modo on-box el servidor escucha HTTPS con un cert autofirmado generado
  4. // en el primer arranque. El agente valida la conexión por pinning del SPKI
  5. // (SubjectPublicKeyInfo) hash, configurado durante el pairing — sin
  6. // InsecureSkipVerify.
  7. //
  8. // El fingerprint expuesto por GET /fingerprint es SHA-256 del DER del SPKI en
  9. // hex minúsculas (formato estándar de pinning, mismo que usa el agente en
  10. // VerifyPeerCertificate).
  11. package tlscert
  12. import (
  13. "crypto/ecdsa"
  14. "crypto/elliptic"
  15. "crypto/rand"
  16. "crypto/sha256"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "crypto/x509/pkix"
  20. "encoding/hex"
  21. "encoding/pem"
  22. "fmt"
  23. "math/big"
  24. "net"
  25. "os"
  26. "time"
  27. )
  28. // Ensure garantiza que existe un cert autofirmado en certPath/keyPath.
  29. // Si ya existe, lo carga; si no, lo genera. Devuelve el *tls.Config para el
  30. // listener y el fingerprint SPKI hex (SHA-256 del DER del SubjectPublicKeyInfo).
  31. func Ensure(certPath, keyPath string) (*tls.Config, string, error) {
  32. if fileExists(certPath) && fileExists(keyPath) {
  33. return loadExisting(certPath, keyPath)
  34. }
  35. return generate(certPath, keyPath)
  36. }
  37. // Load carga un par cert/clave existente SIN generar si falta. Es el caso de
  38. // "certificados del usuario" (NETPULSE_TLS_CERT/NETPULSE_TLS_KEY, #696): si
  39. // alguno no existe o no parsea, devuelve error en vez de generar un
  40. // autofirmado en las rutas configuradas.
  41. func Load(certPath, keyPath string) (*tls.Config, string, error) {
  42. if !fileExists(certPath) || !fileExists(keyPath) {
  43. return nil, "", fmt.Errorf("cert or key not found at %s / %s", certPath, keyPath)
  44. }
  45. return loadExisting(certPath, keyPath)
  46. }
  47. // Fingerprint calcula el SPKI hash hex de un certificado parsed.
  48. func Fingerprint(cert *x509.Certificate) string {
  49. sum := sha256.Sum256(cert.RawSubjectPublicKeyInfo)
  50. return hex.EncodeToString(sum[:])
  51. }
  52. func loadExisting(certPath, keyPath string) (*tls.Config, string, error) {
  53. cert, err := tls.LoadX509KeyPair(certPath, keyPath)
  54. if err != nil {
  55. return nil, "", fmt.Errorf("cargar cert existente: %w", err)
  56. }
  57. leaf, err := x509.ParseCertificate(cert.Certificate[0])
  58. if err != nil {
  59. return nil, "", fmt.Errorf("parsear leaf: %w", err)
  60. }
  61. return &tls.Config{
  62. Certificates: []tls.Certificate{cert},
  63. MinVersion: tls.VersionTLS12,
  64. }, Fingerprint(leaf), nil
  65. }
  66. func generate(certPath, keyPath string) (*tls.Config, string, error) {
  67. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  68. if err != nil {
  69. return nil, "", fmt.Errorf("generar clave ECDSA: %w", err)
  70. }
  71. serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
  72. if err != nil {
  73. return nil, "", fmt.Errorf("serial: %w", err)
  74. }
  75. template := x509.Certificate{
  76. SerialNumber: serial,
  77. Subject: pkix.Name{CommonName: "netpulse"},
  78. NotBefore: time.Now().Add(-time.Hour),
  79. NotAfter: time.Now().AddDate(10, 0, 0),
  80. KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
  81. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
  82. IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
  83. }
  84. der, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
  85. if err != nil {
  86. return nil, "", fmt.Errorf("crear cert: %w", err)
  87. }
  88. certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
  89. keyDER, err := x509.MarshalECPrivateKey(priv)
  90. if err != nil {
  91. return nil, "", fmt.Errorf("marshal clave: %w", err)
  92. }
  93. keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
  94. if err := os.WriteFile(certPath, certPEM, 0o644); err != nil {
  95. return nil, "", fmt.Errorf("escribir cert: %w", err)
  96. }
  97. if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil {
  98. return nil, "", fmt.Errorf("escribir key: %w", err)
  99. }
  100. leaf, _ := x509.ParseCertificate(der)
  101. tlsCert := tls.Certificate{Certificate: [][]byte{der}, PrivateKey: priv}
  102. return &tls.Config{
  103. Certificates: []tls.Certificate{tlsCert},
  104. MinVersion: tls.VersionTLS12,
  105. }, Fingerprint(leaf), nil
  106. }
  107. func fileExists(path string) bool {
  108. _, err := os.Stat(path)
  109. return err == nil
  110. }