sshkey.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. "io"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "regexp"
  13. "strings"
  14. "time"
  15. )
  16. // BaseArgs replica sshBaseArgs (src/sshkey.js:16-24): los args SSH comunes.
  17. // known_hosts junto a la clave (dentro de DATA_DIR).
  18. func BaseArgs(keyPath string) []string {
  19. return []string{
  20. "-i", keyPath,
  21. "-o", "BatchMode=yes",
  22. "-o", "ConnectTimeout=4",
  23. "-o", "StrictHostKeyChecking=accept-new",
  24. "-o", "UserKnownHostsFile=" + filepath.Join(filepath.Dir(keyPath), "known_hosts"),
  25. }
  26. }
  27. // KnownHostsPath devuelve la ruta del known_hosts propio (junto a la clave).
  28. func KnownHostsPath(keyPath string) string {
  29. return filepath.Join(filepath.Dir(keyPath), "known_hosts")
  30. }
  31. // EnsureKeypair garantiza que existe el par de claves en keyPath
  32. // (ssh-keygen -t ed25519 -N ” -C netpulse); best-effort en permisos.
  33. // Si no existe y hay un backup previo (<keyPath>.bak.<epoch>), lo restaura
  34. // en lugar de generar un par nuevo (defensa contra perdida accidental de
  35. // .ssh/ durante updates, issue #425).
  36. func EnsureKeypair(keyPath string) error {
  37. if keyExists(keyPath) {
  38. return nil
  39. }
  40. // Intentar restaurar desde backup antes de generar clave nueva.
  41. if restored, _ := restoreLatestBackup(keyPath); restored {
  42. return nil
  43. }
  44. return generateKeypair(keyPath)
  45. }
  46. func keyExists(keyPath string) bool {
  47. if _, err := os.Stat(keyPath); err != nil {
  48. return false
  49. }
  50. if _, err := os.Stat(keyPath + ".pub"); err != nil {
  51. return false
  52. }
  53. return true
  54. }
  55. // restoreLatestBackup busca backups <keyPath>.bak.<epoch> y restaura el mas
  56. // reciente. Devuelve true si restauro algo.
  57. func restoreLatestBackup(keyPath string) (bool, error) {
  58. dir := filepath.Dir(keyPath)
  59. base := filepath.Base(keyPath)
  60. entries, err := os.ReadDir(dir)
  61. if err != nil {
  62. return false, err
  63. }
  64. var latest string
  65. for _, e := range entries {
  66. name := e.Name()
  67. if strings.HasPrefix(name, base+".bak.") && !strings.HasSuffix(name, ".pub") {
  68. if latest == "" || name > latest {
  69. latest = name
  70. }
  71. }
  72. }
  73. if latest == "" {
  74. return false, nil
  75. }
  76. bakKey := filepath.Join(dir, latest)
  77. bakPub := bakKey + ".pub"
  78. if _, err := os.Stat(bakPub); err != nil {
  79. return false, err
  80. }
  81. if err := copyFile(bakKey, keyPath); err != nil {
  82. return false, err
  83. }
  84. if err := copyFile(bakPub, keyPath+".pub"); err != nil {
  85. return false, err
  86. }
  87. _ = os.Chmod(keyPath, 0o600)
  88. return true, nil
  89. }
  90. func copyFile(src, dst string) error {
  91. in, err := os.Open(src)
  92. if err != nil {
  93. return err
  94. }
  95. defer in.Close()
  96. out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
  97. if err != nil {
  98. return err
  99. }
  100. _, err = io.Copy(out, in)
  101. cerr := out.Close()
  102. if err != nil {
  103. return err
  104. }
  105. return cerr
  106. }
  107. // ExecError envuelve un fallo de proceso externo.
  108. type ExecError struct {
  109. What string
  110. Err error
  111. Out string
  112. }
  113. func (e *ExecError) Error() string {
  114. return e.What + ": " + e.Err.Error() + " " + strings.TrimSpace(e.Out)
  115. }
  116. func (e *ExecError) Unwrap() error { return e.Err }
  117. // PublicKey es la respuesta de /api/config/sshkey.
  118. type PublicKey struct {
  119. PublicKey string `json:"publicKey"`
  120. Fingerprint string `json:"fingerprint"`
  121. }
  122. var fpRe = regexp.MustCompile(`^\d+\s+(\S+)`)
  123. // GetPublicKey lee la clave pública y su fingerprint (ssh-keygen -lf, 2º
  124. // campo). Devuelve (nil, nil) si no se puede leer (→ 500 no_key).
  125. func GetPublicKey(keyPath string) *PublicKey {
  126. data, err := os.ReadFile(keyPath + ".pub")
  127. if err != nil {
  128. return nil
  129. }
  130. pub := strings.TrimSpace(string(data))
  131. out, err := exec.Command("ssh-keygen", "-lf", keyPath+".pub").Output()
  132. fp := ""
  133. if err == nil {
  134. if m := fpRe.FindStringSubmatch(strings.TrimSpace(string(out))); m != nil {
  135. fp = m[1]
  136. }
  137. }
  138. return &PublicKey{PublicKey: pub, Fingerprint: fp}
  139. }
  140. // RotateKeypair regenera el par de claves (issue #242): respalda el par actual
  141. // como <keyPath>.bak.<epoch> y genera uno nuevo. known_hosts NO se toca (las
  142. // host keys de los routers son independientes del par del cliente). Devuelve
  143. // la nueva clave pública para reautorizarla en los routers. Si el par actual
  144. // no existe, simplemente genera uno (sin backup).
  145. func RotateKeypair(keyPath string) (*PublicKey, error) {
  146. // Backup del par actual si existe.
  147. if keyExists(keyPath) {
  148. bak := fmt.Sprintf("%s.bak.%d", keyPath, time.Now().Unix())
  149. if err := os.Rename(keyPath, bak); err != nil {
  150. return nil, &ExecError{What: "rotate-backup", Err: err}
  151. }
  152. if _, err := os.Stat(keyPath + ".pub"); err == nil {
  153. _ = os.Rename(keyPath+".pub", bak+".pub")
  154. }
  155. }
  156. // Generar directamente, sin pasar por EnsureKeypair, para evitar que
  157. // restaure el backup que acabamos de crear (issue #425).
  158. if err := generateKeypair(keyPath); err != nil {
  159. return nil, err
  160. }
  161. key := GetPublicKey(keyPath)
  162. if key == nil {
  163. return nil, &ExecError{What: "rotate-public-key", Err: os.ErrNotExist}
  164. }
  165. return key, nil
  166. }
  167. func generateKeypair(keyPath string) error {
  168. if err := os.MkdirAll(filepath.Dir(keyPath), 0o700); err != nil {
  169. return err
  170. }
  171. cmd := exec.Command("ssh-keygen", "-t", "ed25519", "-f", keyPath, "-N", "", "-C", "netpulse", "-q")
  172. if out, err := cmd.CombinedOutput(); err != nil {
  173. return &ExecError{What: "ssh-keygen", Err: err, Out: string(out)}
  174. }
  175. _ = os.Chmod(filepath.Dir(keyPath), 0o700)
  176. _ = os.Chmod(keyPath, 0o600)
  177. return nil
  178. }