sshkey.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. // Package sshkey — clave SSH propia de NetPulse (paridad src/sshkey.js):
  2. // par ed25519 en DATA_DIR/.ssh generado la primera vez, pública expuesta vía
  3. // /api/config/sshkey para autorizarla a mano en cada router. known_hosts
  4. // JUNTO a la clave (imprescindible con systemd ProtectSystem=strict).
  5. package sshkey
  6. import (
  7. "fmt"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "strings"
  13. "time"
  14. )
  15. // BaseArgs replica sshBaseArgs (src/sshkey.js:16-24): los args SSH comunes.
  16. // known_hosts junto a la clave (dentro de DATA_DIR).
  17. func BaseArgs(keyPath string) []string {
  18. return []string{
  19. "-i", keyPath,
  20. "-o", "BatchMode=yes",
  21. "-o", "ConnectTimeout=4",
  22. "-o", "StrictHostKeyChecking=accept-new",
  23. "-o", "UserKnownHostsFile=" + filepath.Join(filepath.Dir(keyPath), "known_hosts"),
  24. }
  25. }
  26. // KnownHostsPath devuelve la ruta del known_hosts propio (junto a la clave).
  27. func KnownHostsPath(keyPath string) string {
  28. return filepath.Join(filepath.Dir(keyPath), "known_hosts")
  29. }
  30. // EnsureKeypair garantiza que existe el par de claves en keyPath
  31. // (ssh-keygen -t ed25519 -N ” -C netpulse); best-effort en permisos.
  32. func EnsureKeypair(keyPath string) error {
  33. if _, err := os.Stat(keyPath); err == nil {
  34. if _, err := os.Stat(keyPath + ".pub"); err == nil {
  35. return nil
  36. }
  37. }
  38. if err := os.MkdirAll(filepath.Dir(keyPath), 0o700); err != nil {
  39. return err
  40. }
  41. cmd := exec.Command("ssh-keygen", "-t", "ed25519", "-f", keyPath, "-N", "", "-C", "netpulse", "-q")
  42. if out, err := cmd.CombinedOutput(); err != nil {
  43. return &ExecError{What: "ssh-keygen", Err: err, Out: string(out)}
  44. }
  45. _ = os.Chmod(filepath.Dir(keyPath), 0o700)
  46. _ = os.Chmod(keyPath, 0o600)
  47. return nil
  48. }
  49. // ExecError envuelve un fallo de proceso externo.
  50. type ExecError struct {
  51. What string
  52. Err error
  53. Out string
  54. }
  55. func (e *ExecError) Error() string {
  56. return e.What + ": " + e.Err.Error() + " " + strings.TrimSpace(e.Out)
  57. }
  58. func (e *ExecError) Unwrap() error { return e.Err }
  59. // PublicKey es la respuesta de /api/config/sshkey.
  60. type PublicKey struct {
  61. PublicKey string `json:"publicKey"`
  62. Fingerprint string `json:"fingerprint"`
  63. }
  64. var fpRe = regexp.MustCompile(`^\d+\s+(\S+)`)
  65. // GetPublicKey lee la clave pública y su fingerprint (ssh-keygen -lf, 2º
  66. // campo). Devuelve (nil, nil) si no se puede leer (→ 500 no_key).
  67. func GetPublicKey(keyPath string) *PublicKey {
  68. data, err := os.ReadFile(keyPath + ".pub")
  69. if err != nil {
  70. return nil
  71. }
  72. pub := strings.TrimSpace(string(data))
  73. out, err := exec.Command("ssh-keygen", "-lf", keyPath+".pub").Output()
  74. fp := ""
  75. if err == nil {
  76. if m := fpRe.FindStringSubmatch(strings.TrimSpace(string(out))); m != nil {
  77. fp = m[1]
  78. }
  79. }
  80. return &PublicKey{PublicKey: pub, Fingerprint: fp}
  81. }
  82. // RotateKeypair regenera el par de claves (issue #242): respalda el par actual
  83. // como <keyPath>.bak.<epoch> y genera uno nuevo. known_hosts NO se toca (las
  84. // host keys de los routers son independientes del par del cliente). Devuelve
  85. // la nueva clave pública para reautorizarla en los routers. Si el par actual
  86. // no existe, simplemente genera uno (sin backup).
  87. func RotateKeypair(keyPath string) (*PublicKey, error) {
  88. // Backup del par actual si existe.
  89. if _, err := os.Stat(keyPath); err == nil {
  90. bak := fmt.Sprintf("%s.bak.%d", keyPath, time.Now().Unix())
  91. if err := os.Rename(keyPath, bak); err != nil {
  92. return nil, &ExecError{What: "rotate-backup", Err: err}
  93. }
  94. if _, err := os.Stat(keyPath + ".pub"); err == nil {
  95. _ = os.Rename(keyPath+".pub", bak+".pub")
  96. }
  97. }
  98. if err := EnsureKeypair(keyPath); err != nil {
  99. return nil, err
  100. }
  101. key := GetPublicKey(keyPath)
  102. if key == nil {
  103. return nil, &ExecError{What: "rotate-public-key", Err: os.ErrNotExist}
  104. }
  105. return key, nil
  106. }