Просмотр исходного кода

fix(ssh): serialize known_hosts writes and drop unreadable lines (#2014)

Three writers touched the shared known_hosts without coordination, and the re-onboard path rewrote it in place after truncating, so an append landing in that window left a half-written line that made the host key parser reject the whole file. Writes now go through one lock and an atomic rename, and unreadable lines are dropped before loading.

Closes #2014
Nacho 3 недель назад
Родитель
Сommit
aa3449b12b

+ 2 - 0
CHANGELOG.md

@@ -43,6 +43,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 - A node drag in the topology no longer turns into a pan or opens the tagging panel on touch screens (#1983). A second pointer could arm a pan or a pinch during a drag, and the click that ends a chip drag opened the tagging sheet.
 
+- SSH to the whole fleet survives a corrupt known_hosts entry (#2014). Three writers touched the file without a shared lock, and the re-onboard path rewrote it in place after truncating, so an append landing inside that window left a half-written line. One malformed line makes the host key parser reject the entire file, which took out install, rearm, config backup and polling for every unit while agent pushes kept working. Writes are now serialized and the file is replaced with an atomic rename, so a reader never sees a partial file, and unreadable lines are dropped before loading with a log entry instead of being fatal. A test reproduces the corrupt file and checks that the connection path recovers.
+
 ## [2.51.5] - 2026-11-07
 
 ### Added

+ 24 - 10
server-go/internal/adapters/sshpool.go

@@ -158,6 +158,15 @@ func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
 			_ = os.WriteFile(p.khPath, nil, 0o600)
 		}
 	}
+	// #2014: una sola línea ilegible hace que knownhosts.New rechace el
+	// fichero entero, y con él el SSH a TODAS las unidades. Se descarta antes
+	// de cargarlo: el fichero también lo escriben procesos ssh externos, que
+	// no pueden tomar el lock del paquete.
+	if dropped, serr := sshkey.SanitizeKnownHosts(p.khPath); serr != nil {
+		log.Printf("ssh: saneando %s: %v", p.khPath, serr)
+	} else if dropped > 0 {
+		log.Printf("ssh: %d entrada(s) ilegible(s) descartada(s) de %s (#2014)", dropped, p.khPath)
+	}
 	checker, err := knownhosts.New(p.khPath)
 	if err != nil {
 		return nil, err
@@ -184,13 +193,7 @@ func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
 		}
 		// Host desconocido → accept-new
 		line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
-		f, ferr := os.OpenFile(p.khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
-		if ferr != nil {
-			return ferr
-		}
-		defer f.Close()
-		_, ferr = f.WriteString(line + "\n")
-		return ferr
+		return sshkey.AppendKnownHosts(p.khPath, []string{line})
 	}, nil
 }
 
@@ -247,7 +250,12 @@ func (p *SSHPool) RemoveHostKey(hostnames ...string) error {
 		norms[knownhosts.Normalize(h)] = true
 	}
 	var keep []string
-	if data, err := os.ReadFile(p.khPath); err == nil {
+	dropped := 0
+	// #2014: lectura y reescritura bajo el lock del paquete y con rename
+	// atómico. Antes era ReadFile + os.WriteFile (truncate en sitio): un
+	// append concurrente caía entre el truncate y la escritura y dejaba una
+	// línea a medias, que tumbaba el SSH de toda la flota.
+	err := sshkey.UpdateKnownHosts(p.khPath, func(data []byte) ([]byte, error) {
 		for _, ln := range strings.Split(string(data), "\n") {
 			if strings.TrimSpace(ln) == "" {
 				continue
@@ -265,10 +273,16 @@ func (p *SSHPool) RemoveHostKey(hostnames ...string) error {
 			}
 			if !drop {
 				keep = append(keep, ln)
+				continue
 			}
+			dropped++
 		}
-	}
-	return os.WriteFile(p.khPath, []byte(strings.Join(keep, "\n")+"\n"), 0o600)
+		if dropped == 0 {
+			return data, nil
+		}
+		return []byte(strings.Join(keep, "\n") + "\n"), nil
+	})
+	return err
 }
 
 // dial abre (o reabre) la conexión a un host respetando el backoff.

+ 117 - 0
server-go/internal/adapters/sshpool_2014_test.go

@@ -0,0 +1,117 @@
+package adapters
+
+import (
+	"fmt"
+	"os"
+	"strings"
+	"sync"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/sshkey"
+	"golang.org/x/crypto/ssh/knownhosts"
+)
+
+// TestHostKeyCallbackRecoversFromCorruptKnownHosts: una línea corrupta en el
+// known_hosts deja hoy sin SSH a TODAS las unidades, porque knownhosts.New
+// rechaza el fichero entero (#2014). El callback debe sanear antes de cargar.
+func TestHostKeyCallbackRecoversFromCorruptKnownHosts(t *testing.T) {
+	pool := newTestPool(t)
+	_, pub := genTestKey(t)
+	good := knownhosts.Line([]string{knownhosts.Normalize("host-a")}, pub)
+	content := good + "\nhost-corrupt ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAbc\n"
+	if err := os.WriteFile(pool.khPath, []byte(content), 0o600); err != nil {
+		t.Fatal(err)
+	}
+
+	// Premisa: el fichero de partida es inválido para la librería.
+	if _, err := knownhosts.New(pool.khPath); err == nil {
+		t.Fatal("premisa rota: el fichero de partida debería ser inválido")
+	}
+
+	cb, err := pool.hostKeyCallback()
+	if err != nil {
+		t.Fatalf("el callback debería recuperarse de una línea corrupta, obtuve: %v", err)
+	}
+	if cb == nil {
+		t.Fatal("callback nil")
+	}
+	data, _ := os.ReadFile(pool.khPath)
+	if strings.Contains(string(data), "host-corrupt") {
+		t.Fatal("la línea corrupta sigue en el fichero")
+	}
+	if !strings.Contains(string(data), good) {
+		t.Fatal("el saneado se comió la entrada válida")
+	}
+}
+
+// TestRemoveHostKeyConcurrentWithAppends: la carrera del issue consistía en
+// reescribir el fichero (truncate en sitio) mientras otro escritor hacía
+// append. Con la reescritura atómica el fichero siempre queda legible.
+func TestRemoveHostKeyConcurrentWithAppends(t *testing.T) {
+	pool := newTestPool(t)
+	const n = 40
+	lines := make([]string, n)
+	for i := 0; i < n; i++ {
+		_, pub := genTestKey(t)
+		lines[i] = knownhosts.Line([]string{knownhosts.Normalize(fmt.Sprintf("host-%d", i))}, pub)
+	}
+	if err := os.WriteFile(pool.khPath, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
+		t.Fatal(err)
+	}
+
+	var wg sync.WaitGroup
+	for i := 0; i < n; i++ {
+		wg.Add(2)
+		go func(i int) {
+			defer wg.Done()
+			if err := sshkey.AppendKnownHosts(pool.khPath, []string{lines[i]}); err != nil {
+				t.Errorf("append %d: %v", i, err)
+			}
+		}(i)
+		go func(i int) {
+			defer wg.Done()
+			if err := pool.RemoveHostKey(fmt.Sprintf("host-%d", i)); err != nil {
+				t.Errorf("remove %d: %v", i, err)
+			}
+		}(i)
+	}
+	wg.Wait()
+
+	if _, err := knownhosts.New(pool.khPath); err != nil {
+		t.Fatalf("known_hosts ilegible tras la concurrencia: %v", err)
+	}
+}
+
+// TestRemoveHostKeyKeepsOtherHostsAndSkipsNoop: sin coincidencias no se
+// reescribe; con coincidencias se quita solo ese host.
+func TestRemoveHostKeyKeepsOtherHostsAndSkipsNoop(t *testing.T) {
+	pool := newTestPool(t)
+	_, pubA := genTestKey(t)
+	_, pubB := genTestKey(t)
+	a := knownhosts.Line([]string{knownhosts.Normalize("host-a")}, pubA)
+	b := knownhosts.Line([]string{knownhosts.Normalize("host-b")}, pubB)
+	if err := os.WriteFile(pool.khPath, []byte(a+"\n"+b+"\n"), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	before, _ := os.Stat(pool.khPath)
+
+	if err := pool.RemoveHostKey("host-inexistente"); err != nil {
+		t.Fatal(err)
+	}
+	after, _ := os.Stat(pool.khPath)
+	if !os.SameFile(before, after) {
+		t.Fatal("un RemoveHostKey sin coincidencias no debería reescribir el fichero")
+	}
+
+	if err := pool.RemoveHostKey("host-a"); err != nil {
+		t.Fatal(err)
+	}
+	data, _ := os.ReadFile(pool.khPath)
+	s := string(data)
+	if strings.Contains(s, "host-a") {
+		t.Fatal("no se quitó host-a")
+	}
+	if !strings.Contains(s, b) {
+		t.Fatal("se perdió host-b")
+	}
+}

+ 169 - 0
server-go/internal/sshkey/knownhosts.go

@@ -0,0 +1,169 @@
+// knownhosts.go — acceso sincronizado al known_hosts propio (#2014).
+//
+// Tres escritores de Go trabajan sobre el mismo fichero: el callback
+// accept-new del pool (append), PinHostKeys (append de ssh-keyscan) y
+// RemoveHostKey (re-onboard, que reescribe el fichero entero). Sin coordinación,
+// un append que caía entre el truncate y la reescritura dejaba una línea a
+// medias, y como golang.org/x/crypto/ssh/knownhosts rechaza el fichero COMPLETO
+// con la primera línea ilegible, el SSH a todas las unidades se caía de golpe.
+//
+// Hay un cuarto escritor que no puede tomar este lock: los procesos ssh y
+// ssh-keyscan externos, que OpenSSH lanza con UserKnownHostsFile apuntando al
+// mismo fichero (BaseArgs). Por eso la garantía no es el mutex sino el rename
+// atómico: quien lee ve siempre un fichero completo, y una entrada que se
+// pierda en el relevo se vuelve a añadir por TOFU en el siguiente dial. El
+// mutex solo evita que los tres escritores de Go se pisen entre ellos.
+package sshkey
+
+import (
+	"bytes"
+	"encoding/base64"
+	"log"
+	"os"
+	"path/filepath"
+	"strings"
+	"sync"
+
+	"golang.org/x/crypto/ssh"
+)
+
+// khMu serializa lecturas-modificación-escritura sobre el known_hosts.
+var khMu sync.Mutex
+
+// AppendKnownHosts añade líneas al known_hosts. Van en un único write con
+// O_APPEND, así que un lector nunca ve media línea.
+func AppendKnownHosts(khPath string, lines []string) error {
+	if len(lines) == 0 {
+		return nil
+	}
+	khMu.Lock()
+	defer khMu.Unlock()
+	return appendKnownHostsLocked(khPath, lines)
+}
+
+func appendKnownHostsLocked(khPath string, lines []string) error {
+	f, err := os.OpenFile(khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
+	if err != nil {
+		return err
+	}
+	if _, err := f.WriteString(strings.Join(lines, "\n") + "\n"); err != nil {
+		f.Close()
+		return err
+	}
+	if err := f.Sync(); err != nil {
+		f.Close()
+		return err
+	}
+	return f.Close()
+}
+
+// UpdateKnownHosts aplica fn al contenido actual del fichero y lo reemplaza de
+// forma atómica, todo bajo el lock del paquete. Si fn devuelve el contenido
+// sin cambios no se reescribe nada, para no pisar un append ajeno.
+func UpdateKnownHosts(khPath string, fn func(data []byte) ([]byte, error)) error {
+	khMu.Lock()
+	defer khMu.Unlock()
+	data, err := os.ReadFile(khPath)
+	if err != nil && !os.IsNotExist(err) {
+		return err
+	}
+	out, err := fn(data)
+	if err != nil {
+		return err
+	}
+	if bytes.Equal(out, data) {
+		return nil
+	}
+	return replaceKnownHostsLocked(khPath, out)
+}
+
+// replaceKnownHostsLocked escribe el fichero entero en un temporal de la misma
+// carpeta, lo sincroniza y lo renombra encima: nunca trunca en sitio.
+func replaceKnownHostsLocked(khPath string, data []byte) error {
+	tmp, err := os.CreateTemp(filepath.Dir(khPath), ".known_hosts.tmp-*")
+	if err != nil {
+		return err
+	}
+	tmpName := tmp.Name()
+	fail := func(err error) error {
+		tmp.Close()
+		os.Remove(tmpName)
+		return err
+	}
+	if _, err := tmp.Write(data); err != nil {
+		return fail(err)
+	}
+	if err := tmp.Sync(); err != nil {
+		return fail(err)
+	}
+	if err := tmp.Close(); err != nil {
+		os.Remove(tmpName)
+		return err
+	}
+	if err := os.Rename(tmpName, khPath); err != nil {
+		os.Remove(tmpName)
+		return err
+	}
+	return nil
+}
+
+// SanitizeKnownHosts descarta las líneas que knownhosts.New rechazaría y
+// devuelve cuántas quitó. Es la red de seguridad: una sola entrada corrupta no
+// puede dejar sin SSH a toda la flota. Sin cambios en el fichero, no lo toca.
+func SanitizeKnownHosts(khPath string) (int, error) {
+	khMu.Lock()
+	defer khMu.Unlock()
+	data, err := os.ReadFile(khPath)
+	if err != nil {
+		if os.IsNotExist(err) {
+			return 0, nil
+		}
+		return 0, err
+	}
+	var keep []string
+	dropped := 0
+	firstBad := 0
+	for i, ln := range strings.Split(string(data), "\n") {
+		if strings.TrimSpace(ln) == "" {
+			continue
+		}
+		if !validKnownHostsLine(ln) {
+			dropped++
+			if firstBad == 0 {
+				firstBad = i + 1
+			}
+			continue
+		}
+		keep = append(keep, ln)
+	}
+	if dropped == 0 {
+		return 0, nil
+	}
+	log.Printf("[netpulse:ssh] known_hosts %s: %d línea(s) ilegible(s) descartada(s), la primera en la %d (#2014)", khPath, dropped, firstBad)
+	if err := replaceKnownHostsLocked(khPath, []byte(strings.Join(keep, "\n")+"\n")); err != nil {
+		return 0, err
+	}
+	return dropped, nil
+}
+
+// validKnownHostsLine aplica el criterio de knownhosts: "<marcador opcional>
+// <hosts> <tipo> <base64>". Un comentario se conserva.
+func validKnownHostsLine(line string) bool {
+	fields := strings.Fields(line)
+	if len(fields) == 0 || strings.HasPrefix(fields[0], "#") {
+		return true
+	}
+	if strings.HasPrefix(fields[0], "@") {
+		// @cert-authority y @revoked anteponen un marcador.
+		fields = fields[1:]
+	}
+	if len(fields) < 3 {
+		return false
+	}
+	blob, err := base64.StdEncoding.DecodeString(fields[2])
+	if err != nil {
+		return false
+	}
+	_, err = ssh.ParsePublicKey(blob)
+	return err == nil
+}

+ 219 - 0
server-go/internal/sshkey/knownhosts_2014_test.go

@@ -0,0 +1,219 @@
+package sshkey
+
+import (
+	"fmt"
+	"os"
+	"path/filepath"
+	"strings"
+	"sync"
+	"testing"
+
+	"golang.org/x/crypto/ssh/knownhosts"
+)
+
+// corruptLine replica la forma que deja un append a medias sobre una
+// reescritura: base64 truncado, que es lo que rechaza knownhosts.New.
+const corruptLine = "host-corrupt ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAbc"
+
+func writeKH(t *testing.T, dir, content string) string {
+	t.Helper()
+	path := filepath.Join(dir, "known_hosts")
+	if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	return path
+}
+
+func tmpLeftovers(t *testing.T, dir string) []string {
+	t.Helper()
+	ents, err := os.ReadDir(dir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	var out []string
+	for _, e := range ents {
+		if strings.HasPrefix(e.Name(), ".known_hosts.tmp") {
+			out = append(out, e.Name())
+		}
+	}
+	return out
+}
+
+// TestSanitizeKnownHostsDropsMalformedLines: una línea corrupta no puede
+// tumbar la carga del fichero. Premisa comprobada (el fichero de partida es
+// inválido para la librería) y resultado comprobado tras el saneado.
+func TestSanitizeKnownHostsDropsMalformedLines(t *testing.T) {
+	dir := t.TempDir()
+	good1 := lineFor(t, "host-a", genPubKey(t, "ed25519"))
+	good2 := lineFor(t, "host-b", genPubKey(t, "ecdsa"))
+	path := writeKH(t, dir, "# comentario\n"+good1+"\n"+corruptLine+"\n"+good2+"\n")
+
+	if _, err := knownhosts.New(path); err == nil {
+		t.Fatal("premisa rota: el fichero de partida debería ser inválido para knownhosts.New")
+	}
+
+	dropped, err := SanitizeKnownHosts(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if dropped != 1 {
+		t.Fatalf("esperaba 1 línea descartada, got=%d", dropped)
+	}
+	if _, err := knownhosts.New(path); err != nil {
+		t.Fatalf("knownhosts.New sigue fallando tras el saneado: %v", err)
+	}
+	data, _ := os.ReadFile(path)
+	s := string(data)
+	if !strings.Contains(s, good1) || !strings.Contains(s, good2) {
+		t.Fatal("el saneado se comió entradas válidas")
+	}
+	if !strings.Contains(s, "# comentario") {
+		t.Fatal("el saneado se comió un comentario")
+	}
+	if strings.Contains(s, "host-corrupt") {
+		t.Fatal("la línea corrupta sigue en el fichero")
+	}
+	if st, _ := os.Stat(path); st.Mode().Perm() != 0o600 {
+		t.Fatalf("permisos tras el saneado = %v, esperaba 0600", st.Mode().Perm())
+	}
+	if left := tmpLeftovers(t, dir); len(left) != 0 {
+		t.Fatalf("temporales sin limpiar: %v", left)
+	}
+}
+
+// TestSanitizeKnownHostsLeavesHealthyFileUntouched: sin líneas malas no se
+// reescribe nada (ni siquiera se toca el inodo).
+func TestSanitizeKnownHostsLeavesHealthyFileUntouched(t *testing.T) {
+	dir := t.TempDir()
+	good := lineFor(t, "host-a", genPubKey(t, "ed25519")) + "\n"
+	path := writeKH(t, dir, good)
+	before, err := os.Stat(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	dropped, err := SanitizeKnownHosts(path)
+	if err != nil || dropped != 0 {
+		t.Fatalf("dropped=%d err=%v, esperaba 0/nil", dropped, err)
+	}
+	after, _ := os.Stat(path)
+	if !os.SameFile(before, after) {
+		t.Fatal("un fichero sano no debería reescribirse")
+	}
+	data, _ := os.ReadFile(path)
+	if string(data) != good {
+		t.Fatalf("contenido alterado: %q", string(data))
+	}
+}
+
+// TestSanitizeKnownHostsKeepsMarkers: @revoked y @cert-authority son formato
+// válido de known_hosts y no se descartan.
+func TestSanitizeKnownHostsKeepsMarkers(t *testing.T) {
+	dir := t.TempDir()
+	revoked := "@revoked " + lineFor(t, "host-a", genPubKey(t, "ed25519")) + "\n"
+	path := writeKH(t, dir, revoked)
+
+	dropped, err := SanitizeKnownHosts(path)
+	if err != nil || dropped != 0 {
+		t.Fatalf("dropped=%d err=%v, esperaba 0/nil para una línea con marcador", dropped, err)
+	}
+	data, _ := os.ReadFile(path)
+	if string(data) != revoked {
+		t.Fatalf("se alteró una línea con marcador: %q", string(data))
+	}
+}
+
+// TestReplaceUsesRenameNotTruncate: la reescritura cambia el inodo, prueba de
+// que no trunca en sitio (un append concurrente no puede caer "en medio").
+func TestReplaceUsesRenameNotTruncate(t *testing.T) {
+	dir := t.TempDir()
+	path := writeKH(t, dir, lineFor(t, "host-a", genPubKey(t, "ed25519"))+"\n")
+	before, err := os.Stat(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	newLine := lineFor(t, "host-b", genPubKey(t, "ed25519"))
+	if err := UpdateKnownHosts(path, func([]byte) ([]byte, error) {
+		return []byte(newLine + "\n"), nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	after, err := os.Stat(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if os.SameFile(before, after) {
+		t.Fatal("la reescritura fue en sitio (truncate); debería haber sido un rename")
+	}
+	if after.Mode().Perm() != 0o600 {
+		t.Fatalf("permisos = %v, esperaba 0600", after.Mode().Perm())
+	}
+	if _, err := knownhosts.New(path); err != nil {
+		t.Fatalf("knownhosts.New falla tras la reescritura: %v", err)
+	}
+	if left := tmpLeftovers(t, dir); len(left) != 0 {
+		t.Fatalf("temporales sin limpiar: %v", left)
+	}
+}
+
+// TestUpdateKnownHostsNoOpKeepsInode: si fn no cambia el contenido, no se
+// reescribe (no se pisa un append que acabe de entrar).
+func TestUpdateKnownHostsNoOpKeepsInode(t *testing.T) {
+	dir := t.TempDir()
+	path := writeKH(t, dir, lineFor(t, "host-a", genPubKey(t, "ed25519"))+"\n")
+	before, _ := os.Stat(path)
+
+	if err := UpdateKnownHosts(path, func(data []byte) ([]byte, error) {
+		return data, nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	after, _ := os.Stat(path)
+	if !os.SameFile(before, after) {
+		t.Fatal("un update sin cambios no debería reescribir el fichero")
+	}
+}
+
+// TestAppendAndUpdateAreSerialized: appends y reescrituras en paralelo dejan
+// siempre un fichero que la librería acepta. Es la carrera del issue.
+func TestAppendAndUpdateAreSerialized(t *testing.T) {
+	dir := t.TempDir()
+	path := filepath.Join(dir, "known_hosts")
+	if err := os.WriteFile(path, nil, 0o600); err != nil {
+		t.Fatal(err)
+	}
+	const n = 40
+	lines := make([]string, n)
+	for i := 0; i < n; i++ {
+		lines[i] = lineFor(t, fmt.Sprintf("host-%d", i), genPubKey(t, "ed25519"))
+	}
+
+	var wg sync.WaitGroup
+	for i := 0; i < n; i++ {
+		wg.Add(2)
+		go func(i int) {
+			defer wg.Done()
+			if err := AppendKnownHosts(path, []string{lines[i]}); err != nil {
+				t.Errorf("append %d: %v", i, err)
+			}
+		}(i)
+		go func(i int) {
+			defer wg.Done()
+			// Reescribe el fichero entero mientras otros hacen append.
+			if err := UpdateKnownHosts(path, func(data []byte) ([]byte, error) {
+				return append(data, []byte(lines[(i+1)%n]+"\n")...), nil
+			}); err != nil {
+				t.Errorf("update %d: %v", i, err)
+			}
+		}(i)
+	}
+	wg.Wait()
+
+	if _, err := knownhosts.New(path); err != nil {
+		t.Fatalf("known_hosts ilegible tras la concurrencia: %v", err)
+	}
+	if left := tmpLeftovers(t, dir); len(left) != 0 {
+		t.Fatalf("temporales sin limpiar: %v", left)
+	}
+}

+ 3 - 7
server-go/internal/sshkey/sshkey.go

@@ -300,13 +300,9 @@ func PinHostKeys(host, keyPath string) error {
 		return nil
 	}
 
-	f, err := os.OpenFile(khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
-	if err != nil {
-		return err
-	}
-	defer f.Close()
-	_, err = f.WriteString(strings.Join(toAdd, "\n") + "\n")
-	return err
+	// #2014: el append va por el lock del paquete, compartido con el pool y
+	// con RemoveHostKey.
+	return AppendKnownHosts(khPath, toAdd)
 }
 
 // pinHostKeysMerge devuelve las líneas de claves escaneadas que faltan para