knownhosts_2014_test.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. package sshkey
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "sync"
  8. "testing"
  9. "golang.org/x/crypto/ssh/knownhosts"
  10. )
  11. // corruptLine replica la forma que deja un append a medias sobre una
  12. // reescritura: base64 truncado, que es lo que rechaza knownhosts.New.
  13. const corruptLine = "host-corrupt ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAbc"
  14. func writeKH(t *testing.T, dir, content string) string {
  15. t.Helper()
  16. path := filepath.Join(dir, "known_hosts")
  17. if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
  18. t.Fatal(err)
  19. }
  20. return path
  21. }
  22. func tmpLeftovers(t *testing.T, dir string) []string {
  23. t.Helper()
  24. ents, err := os.ReadDir(dir)
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. var out []string
  29. for _, e := range ents {
  30. if strings.HasPrefix(e.Name(), ".known_hosts.tmp") {
  31. out = append(out, e.Name())
  32. }
  33. }
  34. return out
  35. }
  36. // TestSanitizeKnownHostsDropsMalformedLines: una línea corrupta no puede
  37. // tumbar la carga del fichero. Premisa comprobada (el fichero de partida es
  38. // inválido para la librería) y resultado comprobado tras el saneado.
  39. func TestSanitizeKnownHostsDropsMalformedLines(t *testing.T) {
  40. dir := t.TempDir()
  41. good1 := lineFor(t, "host-a", genPubKey(t, "ed25519"))
  42. good2 := lineFor(t, "host-b", genPubKey(t, "ecdsa"))
  43. path := writeKH(t, dir, "# comentario\n"+good1+"\n"+corruptLine+"\n"+good2+"\n")
  44. if _, err := knownhosts.New(path); err == nil {
  45. t.Fatal("premisa rota: el fichero de partida debería ser inválido para knownhosts.New")
  46. }
  47. dropped, err := SanitizeKnownHosts(path)
  48. if err != nil {
  49. t.Fatal(err)
  50. }
  51. if dropped != 1 {
  52. t.Fatalf("esperaba 1 línea descartada, got=%d", dropped)
  53. }
  54. if _, err := knownhosts.New(path); err != nil {
  55. t.Fatalf("knownhosts.New sigue fallando tras el saneado: %v", err)
  56. }
  57. data, _ := os.ReadFile(path)
  58. s := string(data)
  59. if !strings.Contains(s, good1) || !strings.Contains(s, good2) {
  60. t.Fatal("el saneado se comió entradas válidas")
  61. }
  62. if !strings.Contains(s, "# comentario") {
  63. t.Fatal("el saneado se comió un comentario")
  64. }
  65. if strings.Contains(s, "host-corrupt") {
  66. t.Fatal("la línea corrupta sigue en el fichero")
  67. }
  68. if st, _ := os.Stat(path); st.Mode().Perm() != 0o600 {
  69. t.Fatalf("permisos tras el saneado = %v, esperaba 0600", st.Mode().Perm())
  70. }
  71. if left := tmpLeftovers(t, dir); len(left) != 0 {
  72. t.Fatalf("temporales sin limpiar: %v", left)
  73. }
  74. }
  75. // TestSanitizeKnownHostsLeavesHealthyFileUntouched: sin líneas malas no se
  76. // reescribe nada (ni siquiera se toca el inodo).
  77. func TestSanitizeKnownHostsLeavesHealthyFileUntouched(t *testing.T) {
  78. dir := t.TempDir()
  79. good := lineFor(t, "host-a", genPubKey(t, "ed25519")) + "\n"
  80. path := writeKH(t, dir, good)
  81. before, err := os.Stat(path)
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. dropped, err := SanitizeKnownHosts(path)
  86. if err != nil || dropped != 0 {
  87. t.Fatalf("dropped=%d err=%v, esperaba 0/nil", dropped, err)
  88. }
  89. after, _ := os.Stat(path)
  90. if !os.SameFile(before, after) {
  91. t.Fatal("un fichero sano no debería reescribirse")
  92. }
  93. data, _ := os.ReadFile(path)
  94. if string(data) != good {
  95. t.Fatalf("contenido alterado: %q", string(data))
  96. }
  97. }
  98. // TestSanitizeKnownHostsKeepsMarkers: @revoked y @cert-authority son formato
  99. // válido de known_hosts y no se descartan.
  100. func TestSanitizeKnownHostsKeepsMarkers(t *testing.T) {
  101. dir := t.TempDir()
  102. revoked := "@revoked " + lineFor(t, "host-a", genPubKey(t, "ed25519")) + "\n"
  103. path := writeKH(t, dir, revoked)
  104. dropped, err := SanitizeKnownHosts(path)
  105. if err != nil || dropped != 0 {
  106. t.Fatalf("dropped=%d err=%v, esperaba 0/nil para una línea con marcador", dropped, err)
  107. }
  108. data, _ := os.ReadFile(path)
  109. if string(data) != revoked {
  110. t.Fatalf("se alteró una línea con marcador: %q", string(data))
  111. }
  112. }
  113. // TestReplaceUsesRenameNotTruncate: la reescritura cambia el inodo, prueba de
  114. // que no trunca en sitio (un append concurrente no puede caer "en medio").
  115. func TestReplaceUsesRenameNotTruncate(t *testing.T) {
  116. dir := t.TempDir()
  117. path := writeKH(t, dir, lineFor(t, "host-a", genPubKey(t, "ed25519"))+"\n")
  118. before, err := os.Stat(path)
  119. if err != nil {
  120. t.Fatal(err)
  121. }
  122. newLine := lineFor(t, "host-b", genPubKey(t, "ed25519"))
  123. if err := UpdateKnownHosts(path, func([]byte) ([]byte, error) {
  124. return []byte(newLine + "\n"), nil
  125. }); err != nil {
  126. t.Fatal(err)
  127. }
  128. after, err := os.Stat(path)
  129. if err != nil {
  130. t.Fatal(err)
  131. }
  132. if os.SameFile(before, after) {
  133. t.Fatal("la reescritura fue en sitio (truncate); debería haber sido un rename")
  134. }
  135. if after.Mode().Perm() != 0o600 {
  136. t.Fatalf("permisos = %v, esperaba 0600", after.Mode().Perm())
  137. }
  138. if _, err := knownhosts.New(path); err != nil {
  139. t.Fatalf("knownhosts.New falla tras la reescritura: %v", err)
  140. }
  141. if left := tmpLeftovers(t, dir); len(left) != 0 {
  142. t.Fatalf("temporales sin limpiar: %v", left)
  143. }
  144. }
  145. // TestUpdateKnownHostsNoOpKeepsInode: si fn no cambia el contenido, no se
  146. // reescribe (no se pisa un append que acabe de entrar).
  147. func TestUpdateKnownHostsNoOpKeepsInode(t *testing.T) {
  148. dir := t.TempDir()
  149. path := writeKH(t, dir, lineFor(t, "host-a", genPubKey(t, "ed25519"))+"\n")
  150. before, _ := os.Stat(path)
  151. if err := UpdateKnownHosts(path, func(data []byte) ([]byte, error) {
  152. return data, nil
  153. }); err != nil {
  154. t.Fatal(err)
  155. }
  156. after, _ := os.Stat(path)
  157. if !os.SameFile(before, after) {
  158. t.Fatal("un update sin cambios no debería reescribir el fichero")
  159. }
  160. }
  161. // TestAppendAndUpdateAreSerialized: appends y reescrituras en paralelo dejan
  162. // siempre un fichero que la librería acepta. Es la carrera del issue.
  163. func TestAppendAndUpdateAreSerialized(t *testing.T) {
  164. dir := t.TempDir()
  165. path := filepath.Join(dir, "known_hosts")
  166. if err := os.WriteFile(path, nil, 0o600); err != nil {
  167. t.Fatal(err)
  168. }
  169. const n = 40
  170. lines := make([]string, n)
  171. for i := 0; i < n; i++ {
  172. lines[i] = lineFor(t, fmt.Sprintf("host-%d", i), genPubKey(t, "ed25519"))
  173. }
  174. var wg sync.WaitGroup
  175. for i := 0; i < n; i++ {
  176. wg.Add(2)
  177. go func(i int) {
  178. defer wg.Done()
  179. if err := AppendKnownHosts(path, []string{lines[i]}); err != nil {
  180. t.Errorf("append %d: %v", i, err)
  181. }
  182. }(i)
  183. go func(i int) {
  184. defer wg.Done()
  185. // Reescribe el fichero entero mientras otros hacen append.
  186. if err := UpdateKnownHosts(path, func(data []byte) ([]byte, error) {
  187. return append(data, []byte(lines[(i+1)%n]+"\n")...), nil
  188. }); err != nil {
  189. t.Errorf("update %d: %v", i, err)
  190. }
  191. }(i)
  192. }
  193. wg.Wait()
  194. if _, err := knownhosts.New(path); err != nil {
  195. t.Fatalf("known_hosts ilegible tras la concurrencia: %v", err)
  196. }
  197. if left := tmpLeftovers(t, dir); len(left) != 0 {
  198. t.Fatalf("temporales sin limpiar: %v", left)
  199. }
  200. }