Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(native-ssh): pin the recorded host key type

review5469c50f2866
diff --git a/src/core/remote-ssh/native/known-hosts.test.ts b/src/core/remote-ssh/native/known-hosts.test.ts
index aede590d0..bf7a2063a 100644
--- a/src/core/remote-ssh/native/known-hosts.test.ts
+++ b/src/core/remote-ssh/native/known-hosts.test.ts
@@ -3,11 +3,16 @@ import { createHmac, randomBytes } from 'crypto'
import fs from 'fs'
import os from 'os'
import path from 'path'
+import { createRequire } from 'module'
import {
acceptNewHostKey,
+ hostKeyAlgorithmsFor,
hostPatternsMatch,
keyTypeOfBlob,
knownHostsName,
+ orderHostKeyAlgorithms,
+ recordedHostKeyTypes,
+ SSH2_DEFAULT_SERVER_HOST_KEY,
verifyHostKey
} from './known-hosts'
import { parseSshG, expandHomePath } from './ssh-config'
@@ -22,6 +27,7 @@ function blob(type: string, fill: number): Buffer {
const ED_A = blob('ssh-ed25519', 1)
const ED_B = blob('ssh-ed25519', 2)
const RSA = blob('ssh-rsa', 3)
+const ECDSA = blob('ecdsa-sha2-nistp256', 4)
const line = (hosts: string, b: Buffer, marker = ''): string =>
`${marker ? marker + ' ' : ''}${hosts} ${keyTypeOfBlob(b)} ${b.toString('base64')}`
const hashed = (name: string): string => {
@@ -47,8 +53,11 @@ describe('known_hosts matching (OpenSSH semantics)', () => {
const file = [line('h', ED_A), line(hashed('[k]:22022'), RSA)].join('\n')
expect(verifyHostKey([file], 'h', ED_A)).toBe('match')
expect(verifyHostKey([file], 'h', ED_B)).toBe('mismatch')
- // A different key TYPE for a known host is not a mismatch (hosts serve several types).
- expect(verifyHostKey([file], 'h', RSA)).toBe('unknown')
+ // A different key TYPE for a host that already has a recorded key is a mismatch too: the
+ // transport offers the recorded types first (hostKeyAlgorithmsFor), so a host that still has
+ // its recorded key always presents it — only a host that lost it, or a MITM holding just
+ // another type, presents something else.
+ expect(verifyHostKey([file], 'h', RSA)).toBe('mismatch')
expect(verifyHostKey([file], 'other', ED_A)).toBe('unknown')
expect(verifyHostKey([file], '[k]:22022', RSA)).toBe('match')
const revoked = [file, line('*', ED_A, '@revoked')].join('\n')
@@ -57,6 +66,71 @@ describe('known_hosts matching (OpenSSH semantics)', () => {
it('ignores @cert-authority lines — they can only leave a host unknown', () => {
expect(verifyHostKey([line('*', ED_A, '@cert-authority')], 'h', ED_A)).toBe('unknown')
+ // ...and they never count as a recorded key that would refuse a first-seen one.
+ expect(verifyHostKey([line('*', RSA, '@cert-authority')], 'h', ED_A)).toBe('unknown')
+ })
+
+ it('a @revoked line is not a recorded key: another type is still first-seen', () => {
+ expect(verifyHostKey([line('h', RSA, '@revoked')], 'h', ED_A)).toBe('unknown')
+ })
+
+ it('a host serving several types, each recorded, matches whichever it presents', () => {
+ const file = [line('h', ED_A), line('h', RSA)].join('\n')
+ expect(verifyHostKey([file], 'h', ED_A)).toBe('match')
+ expect(verifyHostKey([file], 'h', RSA)).toBe('match')
+ expect(verifyHostKey([file], 'h', ECDSA)).toBe('mismatch')
+ })
+
+ it('the recorded keys in a GLOBAL file count as well', () => {
+ expect(verifyHostKey(['', line('h', RSA)], 'h', ED_A)).toBe('mismatch')
+ })
+})
+
+describe('host key algorithm order (OpenSSH order_hostkeyalgs)', () => {
+ it("pins ssh2's own default list, so the order we hand it is one it accepts", () => {
+ const require = createRequire(import.meta.url)
+ const constants = require('ssh2/lib/protocol/constants.js') as { DEFAULT_SERVER_HOST_KEY: string[] }
+ expect([...SSH2_DEFAULT_SERVER_HOST_KEY]).toEqual(constants.DEFAULT_SERVER_HOST_KEY)
+ })
+
+ it('lists the recorded key types for a host, revoked and CA lines excluded', () => {
+ const file = [line('h', RSA), line('h', ECDSA, '@revoked'), line('*', ED_A, '@cert-authority'), line('other', ED_B)].join('\n')
+ expect(recordedHostKeyTypes([file], 'h')).toEqual(['ssh-rsa'])
+ expect(recordedHostKeyTypes([file], 'nowhere')).toEqual([])
+ })
+
+ it('moves the algorithms of the recorded types to the front, keeping the default order otherwise', () => {
+ const d = [...SSH2_DEFAULT_SERVER_HOST_KEY]
+ expect(orderHostKeyAlgorithms([])).toBeUndefined()
+ expect(orderHostKeyAlgorithms(['ssh-rsa'])).toEqual([
+ 'rsa-sha2-512',
+ 'rsa-sha2-256',
+ 'ssh-rsa',
+ ...d.filter((a) => !['rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa'].includes(a))
+ ])
+ expect(orderHostKeyAlgorithms(['ecdsa-sha2-nistp384', 'ssh-ed25519'])).toEqual([
+ 'ssh-ed25519',
+ 'ecdsa-sha2-nistp384',
+ ...d.filter((a) => a !== 'ssh-ed25519' && a !== 'ecdsa-sha2-nistp384')
+ ])
+ // A recorded type no algorithm of ours speaks changes nothing (ssh2 would throw on it).
+ expect(orderHostKeyAlgorithms(['ssh-dss'])).toBeUndefined()
+ expect(orderHostKeyAlgorithms(['[email protected]'])).toBeUndefined()
+ // Nothing is dropped and nothing is added: the same set, reordered.
+ expect([...(orderHostKeyAlgorithms(['ssh-rsa']) ?? [])].sort()).toEqual([...d].sort())
+ })
+
+ it('reads the policy files for a host:port the way the verifier does', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-kh-order-'))
+ try {
+ const user = path.join(dir, 'known_hosts')
+ fs.writeFileSync(user, line('[h]:2222', ECDSA) + '\n')
+ const policy = { userFiles: [user, path.join(dir, 'missing')], globalFiles: [] }
+ expect(hostKeyAlgorithmsFor(policy, 'h', 2222)?.[0]).toBe('ecdsa-sha2-nistp256')
+ expect(hostKeyAlgorithmsFor(policy, 'h', 22)).toBeUndefined()
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
})
})
@@ -71,10 +145,23 @@ describe('acceptNewHostKey (StrictHostKeyChecking=accept-new)', () => {
it('records a first-seen host and accepts it; a changed key is then refused', () => {
const policy = { userFiles: [user], globalFiles: [] }
- expect(acceptNewHostKey(policy, 'h', 2222, ED_A)).toEqual({ accept: true, verdict: 'unknown' })
+ expect(acceptNewHostKey(policy, 'h', 2222, ED_A)).toMatchObject({ accept: true, verdict: 'unknown' })
expect(fs.readFileSync(user, 'utf8')).toBe(`[h]:2222 ssh-ed25519 ${ED_A.toString('base64')}\n`)
- expect(acceptNewHostKey(policy, 'h', 2222, ED_A)).toEqual({ accept: true, verdict: 'match' })
- expect(acceptNewHostKey(policy, 'h', 2222, ED_B)).toEqual({ accept: false, verdict: 'mismatch' })
+ expect(acceptNewHostKey(policy, 'h', 2222, ED_A)).toMatchObject({ accept: true, verdict: 'match' })
+ expect(acceptNewHostKey(policy, 'h', 2222, ED_B)).toMatchObject({ accept: false, verdict: 'mismatch' })
+ })
+
+ it('refuses a key of ANOTHER type for a recorded host, and records nothing', () => {
+ const policy = { userFiles: [user], globalFiles: [] }
+ acceptNewHostKey(policy, 'h', 22, ED_A)
+ const before = fs.readFileSync(user, 'utf8')
+ expect(acceptNewHostKey(policy, 'h', 22, RSA)).toEqual({
+ accept: false,
+ verdict: 'mismatch',
+ presentedType: 'ssh-rsa',
+ recordedTypes: ['ssh-ed25519']
+ })
+ expect(fs.readFileSync(user, 'utf8')).toBe(before)
})
it('appends without rewriting what another ssh wrote', () => {
diff --git a/src/core/remote-ssh/native/known-hosts.ts b/src/core/remote-ssh/native/known-hosts.ts
index fe034db22..9803d6a33 100644
--- a/src/core/remote-ssh/native/known-hosts.ts
+++ b/src/core/remote-ssh/native/known-hosts.ts
@@ -2,6 +2,14 @@
// `StrictHostKeyChecking=accept-new` — a host never seen before is recorded and accepted; a host
// whose recorded key CHANGED is refused (the MITM case), and so is a key marked @revoked.
//
+// A host that has a recorded key is never "first seen" again, whatever key TYPE it presents.
+// The transport offers the recorded types first (`hostKeyAlgorithmsFor`, OpenSSH's
+// order_hostkeyalgs), so a host that still holds its recorded key always presents it; one that
+// presents another type has either dropped that key or is not the host — a MITM that holds only an
+// RSA key against a host recorded under ed25519. Recording that key as new (what a type-blind
+// accept-new did) let the swap through silently. It is refused like a changed key, with the remedy
+// named; this is stricter than OpenSSH's accept-new, which records a new type for a known host.
+//
// The file format is OpenSSH's (sshd(8) "SSH_KNOWN_HOSTS FILE FORMAT"), read from the same files
// `ssh -G` reports (userknownhostsfile + globalknownhostsfile), so a host the user already trusts
// with their own ssh is trusted here, and one we record is trusted by their ssh too:
@@ -106,16 +114,32 @@ export function parseKnownHosts(text: string): Entry[] {
return out
}
+/**
+ * The key types recorded for `name` across all files, in file order, deduplicated. @revoked and
+ * @cert-authority lines are not recorded keys: a revoked key says which key to refuse, and the
+ * native transport does not do host certificates.
+ */
+export function recordedHostKeyTypes(texts: string[], name: string): string[] {
+ const types: string[] = []
+ for (const text of texts) {
+ for (const e of parseKnownHosts(text)) {
+ if (e.marker === '@cert-authority' || e.marker === '@revoked') continue
+ if (!hostPatternsMatch(e.hosts, name)) continue
+ if (!types.includes(e.keyType)) types.push(e.keyType)
+ }
+ }
+ return types
+}
+
/**
* The verdict for `blob` presented by `name` (already in knownHostsName form), across all files.
* Order of precedence follows OpenSSH: a matching @revoked key refuses; a matching key accepts;
- * a recorded key of the SAME type that differs is a mismatch; otherwise the host is unknown.
- * A different key TYPE for a known host is "unknown", not a mismatch — OpenSSH offers the types it
- * has on record first, and a host that genuinely serves several types records each separately.
+ * otherwise, a host with ANY recorded key is a mismatch — the same type with different bytes (a
+ * changed key) and another type alike (see the file header); only a host with no recorded key at
+ * all is unknown.
*/
export function verifyHostKey(texts: string[], name: string, blob: Buffer): HostKeyVerdict {
- const type = keyTypeOfBlob(blob)
- let sawSameTypeDifferent = false
+ let recorded = false
let matched = false
for (const text of texts) {
for (const e of parseKnownHosts(text)) {
@@ -125,12 +149,49 @@ export function verifyHostKey(texts: string[], name: string, blob: Buffer): Host
if (e.key.equals(blob)) return 'revoked'
continue
}
+ recorded = true
if (e.key.equals(blob)) matched = true
- else if (e.keyType === type) sawSameTypeDifferent = true
}
}
if (matched) return 'match'
- return sawSameTypeDifferent ? 'mismatch' : 'unknown'
+ return recorded ? 'mismatch' : 'unknown'
+}
+
+/**
+ * ssh2 1.17's own default server host key algorithms, in its order (pinned against the package by
+ * known-hosts.test.ts). The list handed to ssh2 is always a reordering of exactly these: an exact
+ * list naming anything ssh2 does not support makes `connect()` throw.
+ */
+export const SSH2_DEFAULT_SERVER_HOST_KEY = [
+ 'ssh-ed25519',
+ 'ecdsa-sha2-nistp256',
+ 'ecdsa-sha2-nistp384',
+ 'ecdsa-sha2-nistp521',
+ 'rsa-sha2-512',
+ 'rsa-sha2-256',
+ 'ssh-rsa'
+] as const
+
+/** The known_hosts KEY type an algorithm's key is recorded under: RSA's SHA-2 signature
+ * algorithms all use an `ssh-rsa` key; every other algorithm is named after its key type. */
+function keyTypeOfAlgorithm(alg: string): string {
+ return alg === 'rsa-sha2-512' || alg === 'rsa-sha2-256' ? 'ssh-rsa' : alg
+}
+
+/**
+ * OpenSSH's order_hostkeyalgs over ssh2's defaults: the algorithms whose key type is recorded for
+ * the host first, everything else after, each half in the default order. `undefined` (= ssh2's
+ * default) when nothing recorded maps to an algorithm we offer — a host recorded only under
+ * `ssh-dss` or a security-key type keeps the default order, and the verifier still refuses the
+ * key it then presents.
+ */
+export function orderHostKeyAlgorithms(recordedTypes: string[]): string[] | undefined {
+ const first: string[] = []
+ const last: string[] = []
+ for (const alg of SSH2_DEFAULT_SERVER_HOST_KEY) {
+ ;(recordedTypes.includes(keyTypeOfAlgorithm(alg)) ? first : last).push(alg)
+ }
+ return first.length ? [...first, ...last] : undefined
}
function readIfPresent(p: string): string {
@@ -153,6 +214,22 @@ export interface HostKeyPolicy {
globalFiles: string[]
}
+/** The `algorithms.serverHostKey` list for a connection to `host:port`, or undefined for ssh2's
+ * default. Read from the same files, under the same name, the verifier reads. */
+export function hostKeyAlgorithmsFor(policy: HostKeyPolicy, host: string, port: number): string[] | undefined {
+ const texts = [...policy.userFiles, ...policy.globalFiles].map(readIfPresent)
+ return orderHostKeyAlgorithms(recordedHostKeyTypes(texts, knownHostsName(host, port)))
+}
+
+export interface HostKeyDecision {
+ accept: boolean
+ verdict: HostKeyVerdict
+ /** The presented key's type, and the types on record for the host — so a refusal can say
+ * "recorded ssh-ed25519, presented ssh-rsa" instead of only "changed". */
+ presentedType?: string
+ recordedTypes?: string[]
+}
+
/**
* The accept-new decision, with the file side effects: an unknown key is appended to the FIRST
* user known_hosts file (created with its directory, 0600/0700 — ssh's own modes) and accepted;
@@ -164,11 +241,19 @@ export function acceptNewHostKey(
host: string,
port: number,
blob: Buffer
-): { accept: boolean; verdict: HostKeyVerdict } {
+): HostKeyDecision {
const name = knownHostsName(host, port)
const texts = [...policy.userFiles, ...policy.globalFiles].map(readIfPresent)
const verdict = verifyHostKey(texts, name, blob)
if (verdict === 'match') return { accept: true, verdict }
+ if (verdict === 'mismatch') {
+ return {
+ accept: false,
+ verdict,
+ presentedType: keyTypeOfBlob(blob) ?? 'unknown',
+ recordedTypes: recordedHostKeyTypes(texts, name)
+ }
+ }
if (verdict !== 'unknown') return { accept: false, verdict }
const line = knownHostsLine(name, blob)
const file = policy.userFiles[0]
@@ -187,3 +272,16 @@ export function acceptNewHostKey(
}
return { accept: true, verdict }
}
+
+/** The refusal sentence for a mismatch: OpenSSH's banner (callers and users match on it), plus
+ * what differed and the remedy when the TYPE changed — a rotation the user must confirm. */
+export function hostKeyMismatchMessage(knownAs: string, port: number, d: HostKeyDecision): string {
+ const head = `@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@ Host key verification failed for ${knownAs}.`
+ const recorded = d.recordedTypes ?? []
+ if (!d.presentedType || !recorded.length || recorded.includes(d.presentedType)) return head
+ return (
+ `${head} known_hosts records a ${recorded.join(' / ')} key for this host, and it presented a ` +
+ `${d.presentedType} key instead. If the host's keys really changed, remove the old entry ` +
+ `(ssh-keygen -R ${knownHostsName(knownAs, port)}) and connect again.`
+ )
+}
diff --git a/src/core/remote-ssh/native/native-hostkey-type.test.ts b/src/core/remote-ssh/native/native-hostkey-type.test.ts
new file mode 100644
index 000000000..d001d9c12
--- /dev/null
+++ b/src/core/remote-ssh/native/native-hostkey-type.test.ts
@@ -0,0 +1,134 @@
+// The native transport pins the host key TYPE on record, against a REAL SSH protocol peer (ssh2's
+// own Server, in-process, on loopback — runs the same on every CI leg).
+//
+// Before: ssh2 negotiated host keys in its own default order (ed25519 first) and the verifier read
+// a key of a type known_hosts did not hold for that host as "first seen", recorded it and
+// connected. So a man in the middle holding only an ed25519 key, against a host recorded under
+// ECDSA (or RSA), was silently trusted — the changed-key check never ran, because no recorded key
+// of the presented type existed to differ from.
+import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { AddressInfo } from 'net'
+import { Server, utils, type Connection } from 'ssh2'
+import { NativeMux } from './native-mux'
+import { parseSshArgv } from './ssh-argv'
+import { childArgs } from '../control-master'
+import type { ResolvedHost } from './ssh-config'
+import { ed25519KeyPair } from './test-keys'
+
+const edKey = ed25519KeyPair()
+const ecdsaKey = utils.generateKeyPairSync('ecdsa', { bits: 256 })
+const clientKey = ed25519KeyPair()
+
+let dir: string
+const servers: Server[] = []
+const live: Connection[] = []
+const muxes: NativeMux[] = []
+
+/** A server holding `hostKeys`, answering every exec with `ran`. Resolves its port. */
+function startServer(hostKeys: string[]): Promise<number> {
+ const server = new Server({ hostKeys }, (client) => {
+ live.push(client)
+ client.on('authentication', (ctx) => {
+ if (ctx.method !== 'publickey') return ctx.reject(['publickey'])
+ const k = utils.parseKey(clientKey.public)
+ const one = Array.isArray(k) ? k[0] : k
+ if (one instanceof Error || ctx.key.algo !== one.type || !ctx.key.data.equals(one.getPublicSSH())) {
+ return ctx.reject(['publickey'])
+ }
+ ctx.accept()
+ })
+ client.on('ready', () => {
+ client.on('session', (accept) => {
+ accept().on('exec', (acceptExec) => {
+ const ch = acceptExec()
+ ch.write('ran\n')
+ ch.exit(0)
+ ch.end()
+ })
+ })
+ })
+ client.on('error', () => {})
+ })
+ servers.push(server)
+ return new Promise((r) => server.listen(0, '127.0.0.1', () => r((server.address() as AddressInfo).port)))
+}
+
+const knownHosts = (): string => path.join(dir, 'known_hosts')
+const kh = (port: number, key: string): string => {
+ const k = utils.parseKey(key)
+ const one = Array.isArray(k) ? k[0] : k
+ if (one instanceof Error) throw one
+ return `[127.0.0.1]:${port} ${one.type} ${one.getPublicSSH().toString('base64')}\n`
+}
+
+function mux(port: number): NativeMux {
+ const host: ResolvedHost = {
+ hostname: '127.0.0.1',
+ port,
+ user: 'dev',
+ identityFiles: [path.join(dir, 'id')],
+ identitiesOnly: true,
+ userKnownHostsFiles: [knownHosts()],
+ globalKnownHostsFiles: [],
+ strictHostKeyChecking: 'ask'
+ }
+ const m = new NativeMux({ resolveHost: async () => host, defaultAgent: () => undefined })
+ muxes.push(m)
+ return m
+}
+
+async function run(port: number) {
+ const p = parseSshArgv(
+ childArgs({ user: 'dev', host: '127.0.0.1', port, identityFile: path.join(dir, 'id') }, path.join(dir, `cm-${port}.sock`), 'echo')
+ )
+ if (p.kind !== 'exec') throw new Error('not exec')
+ return mux(port).exec(p)
+}
+
+beforeAll(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-native-hktype-'))
+ fs.writeFileSync(path.join(dir, 'id'), clientKey.private)
+})
+afterEach(() => {
+ for (const m of muxes.splice(0)) m.exitAll()
+ for (const c of live.splice(0)) c.end()
+ for (const s of servers.splice(0)) s.close()
+ fs.rmSync(knownHosts(), { force: true })
+})
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }))
+
+describe('native ssh: the recorded host key type is pinned', () => {
+ it('a host serving several types presents the RECORDED one (order_hostkeyalgs), and nothing new is recorded', async () => {
+ const port = await startServer([edKey.private, ecdsaKey.private])
+ // Recorded under ECDSA only; ssh2's default order would have asked for ed25519 first.
+ fs.writeFileSync(knownHosts(), kh(port, ecdsaKey.private))
+ const r = await run(port)
+ expect(r.stderr.toString()).toBe('')
+ expect(r.code).toBe(0)
+ expect(r.stdout.toString()).toBe('ran\n')
+ expect(fs.readFileSync(knownHosts(), 'utf8')).toBe(kh(port, ecdsaKey.private))
+ })
+
+ it('a peer holding only ANOTHER type (the MITM) is refused, and its key is not recorded', async () => {
+ const port = await startServer([edKey.private])
+ fs.writeFileSync(knownHosts(), kh(port, ecdsaKey.private))
+ const r = await run(port)
+ expect(r.code).toBe(255)
+ const err = r.stderr.toString()
+ expect(err).toMatch(/REMOTE HOST IDENTIFICATION HAS CHANGED/)
+ expect(err).toContain('ecdsa-sha2-nistp256')
+ expect(err).toContain('ssh-ed25519')
+ expect(err).toContain(`ssh-keygen -R [127.0.0.1]:${port}`)
+ expect(fs.readFileSync(knownHosts(), 'utf8')).toBe(kh(port, ecdsaKey.private))
+ })
+
+ it('a host never seen before is still recorded and accepted (accept-new is unchanged)', async () => {
+ const port = await startServer([edKey.private, ecdsaKey.private])
+ const r = await run(port)
+ expect(r.code).toBe(0)
+ expect(fs.readFileSync(knownHosts(), 'utf8')).toBe(kh(port, edKey.private))
+ })
+})
diff --git a/src/core/remote-ssh/native/native-mux.ts b/src/core/remote-ssh/native/native-mux.ts
index d17fbe18f..9e98c3ad8 100644
--- a/src/core/remote-ssh/native/native-mux.ts
+++ b/src/core/remote-ssh/native/native-mux.ts
@@ -42,7 +42,7 @@ import type { LocalForward, ParsedSsh, ReverseForward, SshOptions, SshTarget } f
import { parseProxyJump, resolveForwardAgent, type HostQuery, type JumpSpec, type ResolvedHost } from './ssh-config'
import { WINDOWS_OPENSSH_AGENT_PIPE, resolveWindowsIdentityAgent } from './windows-agent-discovery'
import { expandProxyTokens, proxyCommandSocket, type ProxySpawn } from './proxy-command'
-import { acceptNewHostKey } from './known-hosts'
+import { acceptNewHostKey, hostKeyAlgorithmsFor, hostKeyMismatchMessage } from './known-hosts'
import { addKeyToAgent, type AgentAddResult } from './agent-add'
/**
@@ -842,27 +842,28 @@ export class NativeMux {
let hostKeyRefusal = ''
const cancelled = { value: false }
const auth = this.authPlan(target, host, options, mode, cancelled)
+ const keyPolicy = { userFiles: host.userKnownHostsFiles, globalFiles: host.globalKnownHostsFiles }
+ // OpenSSH's order_hostkeyalgs: offer the key types on record for this host first, so a host
+ // that still holds its recorded key presents it — and any other type it presents is refused as
+ // a changed key (known-hosts.ts), never recorded as a new one. Undefined = ssh2's default order.
+ const serverHostKey = hostKeyAlgorithmsFor(keyPolicy, knownAs, host.port)
const cfg: ConnectConfig = {
sock,
username: host.user,
readyTimeout: AUTH_WAIT_MS,
keepaliveInterval: (options.serverAliveInterval ?? 0) * 1000,
keepaliveCountMax: options.serverAliveCountMax ?? 3,
+ ...(serverHostKey ? { algorithms: { serverHostKey } } : {}),
hostVerifier: (key: Buffer): boolean => {
// accept-new is the only policy the builders ask for; `ask`/`yes` from the user's config
// are overridden by the command line exactly as they are for OpenSSH.
- const v = acceptNewHostKey(
- { userFiles: host.userKnownHostsFiles, globalFiles: host.globalKnownHostsFiles },
- knownAs,
- host.port,
- key
- )
+ const v = acceptNewHostKey(keyPolicy, knownAs, host.port, key)
if (!v.accept) {
hostKeyRefusal =
prefix +
(v.verdict === 'revoked'
? `@@@ WARNING: REVOKED HOST KEY DETECTED FOR ${knownAs} @@@`
- : `@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@ Host key verification failed for ${knownAs}.`)
+ : hostKeyMismatchMessage(knownAs, host.port, v))
}
return v.accept
},