knownhosts_2014_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. // Premisa: la línea corrupta sigue siendo inválida. Desde x/crypto 0.59
  44. // knownhosts.New salta las líneas malas de un fichero mixto y solo falla
  45. // si no queda ninguna válida, así que se comprueba con un fichero que
  46. // solo tiene la corrupta.
  47. onlyBad := writeKH(t, dir, corruptLine+"\n")
  48. if _, err := knownhosts.New(onlyBad); err == nil {
  49. t.Fatal("premisa rota: un known_hosts solo con la línea corrupta debería fallar")
  50. }
  51. path := writeKH(t, dir, "# comentario\n"+good1+"\n"+corruptLine+"\n"+good2+"\n")
  52. dropped, err := SanitizeKnownHosts(path)
  53. if err != nil {
  54. t.Fatal(err)
  55. }
  56. if dropped != 1 {
  57. t.Fatalf("esperaba 1 línea descartada, got=%d", dropped)
  58. }
  59. if _, err := knownhosts.New(path); err != nil {
  60. t.Fatalf("knownhosts.New sigue fallando tras el saneado: %v", err)
  61. }
  62. data, _ := os.ReadFile(path)
  63. s := string(data)
  64. if !strings.Contains(s, good1) || !strings.Contains(s, good2) {
  65. t.Fatal("el saneado se comió entradas válidas")
  66. }
  67. if !strings.Contains(s, "# comentario") {
  68. t.Fatal("el saneado se comió un comentario")
  69. }
  70. if strings.Contains(s, "host-corrupt") {
  71. t.Fatal("la línea corrupta sigue en el fichero")
  72. }
  73. if st, _ := os.Stat(path); st.Mode().Perm() != 0o600 {
  74. t.Fatalf("permisos tras el saneado = %v, esperaba 0600", st.Mode().Perm())
  75. }
  76. if left := tmpLeftovers(t, dir); len(left) != 0 {
  77. t.Fatalf("temporales sin limpiar: %v", left)
  78. }
  79. }
  80. // TestSanitizeKnownHostsLeavesHealthyFileUntouched: sin líneas malas no se
  81. // reescribe nada (ni siquiera se toca el inodo).
  82. func TestSanitizeKnownHostsLeavesHealthyFileUntouched(t *testing.T) {
  83. dir := t.TempDir()
  84. good := lineFor(t, "host-a", genPubKey(t, "ed25519")) + "\n"
  85. path := writeKH(t, dir, good)
  86. before, err := os.Stat(path)
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. dropped, err := SanitizeKnownHosts(path)
  91. if err != nil || dropped != 0 {
  92. t.Fatalf("dropped=%d err=%v, esperaba 0/nil", dropped, err)
  93. }
  94. after, _ := os.Stat(path)
  95. if !os.SameFile(before, after) {
  96. t.Fatal("un fichero sano no debería reescribirse")
  97. }
  98. data, _ := os.ReadFile(path)
  99. if string(data) != good {
  100. t.Fatalf("contenido alterado: %q", string(data))
  101. }
  102. }
  103. // TestSanitizeKnownHostsKeepsMarkers: @revoked y @cert-authority son formato
  104. // válido de known_hosts y no se descartan.
  105. func TestSanitizeKnownHostsKeepsMarkers(t *testing.T) {
  106. dir := t.TempDir()
  107. revoked := "@revoked " + lineFor(t, "host-a", genPubKey(t, "ed25519")) + "\n"
  108. path := writeKH(t, dir, revoked)
  109. dropped, err := SanitizeKnownHosts(path)
  110. if err != nil || dropped != 0 {
  111. t.Fatalf("dropped=%d err=%v, esperaba 0/nil para una línea con marcador", dropped, err)
  112. }
  113. data, _ := os.ReadFile(path)
  114. if string(data) != revoked {
  115. t.Fatalf("se alteró una línea con marcador: %q", string(data))
  116. }
  117. }
  118. // TestReplaceUsesRenameNotTruncate: la reescritura cambia el inodo, prueba de
  119. // que no trunca en sitio (un append concurrente no puede caer "en medio").
  120. func TestReplaceUsesRenameNotTruncate(t *testing.T) {
  121. dir := t.TempDir()
  122. path := writeKH(t, dir, lineFor(t, "host-a", genPubKey(t, "ed25519"))+"\n")
  123. before, err := os.Stat(path)
  124. if err != nil {
  125. t.Fatal(err)
  126. }
  127. newLine := lineFor(t, "host-b", genPubKey(t, "ed25519"))
  128. if err := UpdateKnownHosts(path, func([]byte) ([]byte, error) {
  129. return []byte(newLine + "\n"), nil
  130. }); err != nil {
  131. t.Fatal(err)
  132. }
  133. after, err := os.Stat(path)
  134. if err != nil {
  135. t.Fatal(err)
  136. }
  137. if os.SameFile(before, after) {
  138. t.Fatal("la reescritura fue en sitio (truncate); debería haber sido un rename")
  139. }
  140. if after.Mode().Perm() != 0o600 {
  141. t.Fatalf("permisos = %v, esperaba 0600", after.Mode().Perm())
  142. }
  143. if _, err := knownhosts.New(path); err != nil {
  144. t.Fatalf("knownhosts.New falla tras la reescritura: %v", err)
  145. }
  146. if left := tmpLeftovers(t, dir); len(left) != 0 {
  147. t.Fatalf("temporales sin limpiar: %v", left)
  148. }
  149. }
  150. // TestUpdateKnownHostsNoOpKeepsInode: si fn no cambia el contenido, no se
  151. // reescribe (no se pisa un append que acabe de entrar).
  152. func TestUpdateKnownHostsNoOpKeepsInode(t *testing.T) {
  153. dir := t.TempDir()
  154. path := writeKH(t, dir, lineFor(t, "host-a", genPubKey(t, "ed25519"))+"\n")
  155. before, _ := os.Stat(path)
  156. if err := UpdateKnownHosts(path, func(data []byte) ([]byte, error) {
  157. return data, nil
  158. }); err != nil {
  159. t.Fatal(err)
  160. }
  161. after, _ := os.Stat(path)
  162. if !os.SameFile(before, after) {
  163. t.Fatal("un update sin cambios no debería reescribir el fichero")
  164. }
  165. }
  166. // TestAppendAndUpdateAreSerialized: appends y reescrituras en paralelo dejan
  167. // siempre un fichero que la librería acepta. Es la carrera del issue.
  168. func TestAppendAndUpdateAreSerialized(t *testing.T) {
  169. dir := t.TempDir()
  170. path := filepath.Join(dir, "known_hosts")
  171. if err := os.WriteFile(path, nil, 0o600); err != nil {
  172. t.Fatal(err)
  173. }
  174. const n = 40
  175. lines := make([]string, n)
  176. for i := 0; i < n; i++ {
  177. lines[i] = lineFor(t, fmt.Sprintf("host-%d", i), genPubKey(t, "ed25519"))
  178. }
  179. var wg sync.WaitGroup
  180. for i := 0; i < n; i++ {
  181. wg.Add(2)
  182. go func(i int) {
  183. defer wg.Done()
  184. if err := AppendKnownHosts(path, []string{lines[i]}); err != nil {
  185. t.Errorf("append %d: %v", i, err)
  186. }
  187. }(i)
  188. go func(i int) {
  189. defer wg.Done()
  190. // Reescribe el fichero entero mientras otros hacen append.
  191. if err := UpdateKnownHosts(path, func(data []byte) ([]byte, error) {
  192. return append(data, []byte(lines[(i+1)%n]+"\n")...), nil
  193. }); err != nil {
  194. t.Errorf("update %d: %v", i, err)
  195. }
  196. }(i)
  197. }
  198. wg.Wait()
  199. if _, err := knownhosts.New(path); err != nil {
  200. t.Fatalf("known_hosts ilegible tras la concurrencia: %v", err)
  201. }
  202. if left := tmpLeftovers(t, dir); len(left) != 0 {
  203. t.Fatalf("temporales sin limpiar: %v", left)
  204. }
  205. }