diff --git a/entry/src/main/ets/common/Fingerprint.ts b/entry/src/main/ets/common/Fingerprint.ts new file mode 100644 index 0000000..3333412 --- /dev/null +++ b/entry/src/main/ets/common/Fingerprint.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + */ + +import { CryptoAdapter } from '../ssh/crypto/CryptoAdapter'; +import { bytesToBase64 } from '../ssh/SshWire'; + +/** Trailing base64 padding chars ('=') — stripped per OpenSSH convention. */ +const B64_PADDING: RegExp = new RegExp('=+$'); + +/** + * OpenSSH-style SHA256 fingerprint of a host key blob: + * "SHA256:" + base64(SHA256(blob)) with trailing '=' padding stripped + * (matches `ssh-keygen -l -E sha256` / known_hosts fingerprint output). + */ +export function sha256Fingerprint(blob: Uint8Array): string { + const digest: Uint8Array = CryptoAdapter.sha256Sync(blob); + return `SHA256:${bytesToBase64(digest).replace(B64_PADDING, '')}`; +} diff --git a/entry/src/main/ets/pages/DiagPage.ets b/entry/src/main/ets/pages/DiagPage.ets index de4d196..baa963d 100644 --- a/entry/src/main/ets/pages/DiagPage.ets +++ b/entry/src/main/ets/pages/DiagPage.ets @@ -14,9 +14,13 @@ import { GcmPacketCipher, CtrMacPacketCipher } from '../ssh/Ciphers'; import { CryptoAdapter, RawKeyPair } from '../ssh/crypto/CryptoAdapter'; import { DerUtils, RsaPublicKeyParts, EcdsaParts } from '../ssh/crypto/DerUtils'; import { buildPublicKeyBlob, verifyHostKeySignature, PublicKeyMaterial } from '../ssh/crypto/KeyImport'; -import { SshVersion } from '../ssh/SshTypes'; +import { SshVersion, SshMsg } from '../ssh/SshTypes'; import { ClientProposals } from '../ssh/Algorithms'; -import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual, concatBytes, SshWriter } from '../ssh/SshWire'; +import { KexEngine, KexResult } from '../ssh/Kex'; +import { verifyHostKeyTofu, InMemoryKnownHostStore, HostKeyDecider, HostKeyPrompt, + HostKeyDecision } from '../ssh/HostKeyVerifier'; +import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual, concatBytes, SshWriter, + SshReader } from '../ssh/SshWire'; import { cryptoFramework } from '@kit.CryptoArchitectureKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -103,6 +107,11 @@ struct DiagPage { .onClick(() => { this.runTest((): Promise => this.testCryptoSuite()); }) + Button('9. 完整 KEX 密钥交换 (真实服务器)') + .width('100%') + .onClick(() => { + this.runTest((): Promise => this.testLiveKex()); + }) } .width('100%') @@ -671,4 +680,80 @@ struct DiagPage { this.log('FAIL', `加密套件自测 ${pass}/${total},${fail} 项失败`); } } + + /** 9) Full KEX against a live server: negotiate → agree → verify → NEWKEYS. */ + private async testLiveKex(): Promise { + const host: string = this.host.trim(); + if (host.length === 0) { + this.log('FAIL', '请先输入 SSH 服务器地址'); + return; + } + const port: number = this.parsePort(); + this.log('INFO', `连接 ${host}:${port} 进行完整 KEX 密钥交换 ...`); + const socket: TcpRawSocket = new TcpRawSocket(); + const transport: SshTransport = new SshTransport(socket); + try { + await socket.connect(host, port, 10000); + const serverBanner: string = await transport.start(SshVersion.CLIENT_BANNER, 15000); + this.log('INFO', `服务器版本: ${serverBanner}`); + + // Fresh in-memory store per run → every test sees status 'new'. + const store: InMemoryKnownHostStore = new InMemoryKnownHostStore(); + const decider: HostKeyDecider = { + decide: async (prompt: HostKeyPrompt): Promise => { + this.log('INFO', `主机密钥 [${prompt.status}] ${prompt.hostPort} (${prompt.keyAlgo})`); + this.log('INFO', `本次指纹: ${prompt.fingerprint}`); + if (prompt.status === 'changed') { + for (let i = 0; i < prompt.knownFingerprints.length; i++) { + this.log('INFO', `已知指纹 ${i + 1}: ${prompt.knownFingerprints[i]}`); + } + } + return 'accept-once'; + } + }; + const engine: KexEngine = new KexEngine(transport, + (algo: string, blob: Uint8Array, fp: string): Promise => { + this.log('INFO', `校验主机密钥: ${algo} / ${fp}`); + // Rejection rejects this promise → run() aborts with the reason. + return verifyHostKeyTofu(store, decider, host, port, algo, blob) + .then((): boolean => true); + }); + + const result: KexResult = await engine.run(SshVersion.CLIENT_BANNER, serverBanner, 20000); + this.log('INFO', `kex: ${result.negotiated.kex}`); + this.log('INFO', `hostKeyAlgo: ${result.negotiated.hostKeyAlgo}`); + this.log('INFO', `cipherC2s: ${result.negotiated.cipherC2s}`); + this.log('INFO', `cipherS2c: ${result.negotiated.cipherS2c}`); + this.log('INFO', `macC2s: ${result.negotiated.macC2s.length > 0 ? result.negotiated.macC2s : 'implicit (AEAD)'}`); + this.log('INFO', `macS2c: ${result.negotiated.macS2c.length > 0 ? result.negotiated.macS2c : 'implicit (AEAD)'}`); + this.log('INFO', `strictKex: ${result.strictKex}`); + this.log('INFO', `extInfoExpected: ${result.extInfoExpected}`); + this.log('INFO', `hostKeyFingerprint: ${result.hostKeyFingerprint}`); + this.log('INFO', `sessionId: ${bytesToHex(result.sessionId)}`); + + if (result.extInfoExpected) { + try { + const p: Uint8Array = await transport.waitPacket(2000); + if (p[0] === SshMsg.EXT_INFO) { + const er: SshReader = new SshReader(p); + er.readByte(); + const count: number = er.readUint32(); + this.log('INFO', `EXT_INFO (${count} 项扩展):`); + for (let i = 0; i < count; i++) { + const name: string = er.readString(); + const value: string = er.readString(); + this.log('INFO', ` ${name} = ${this.trunc(value, 80)}`); + } + } else { + this.log('INFO', `KEX 后消息 ${p[0]} 忽略`); + } + } catch (e) { + this.log('INFO', '2 秒内未收到 EXT_INFO (ok)'); + } + } + this.log('PASS', 'KEX 完成 ✓'); + } finally { + transport.close(); + } + } } diff --git a/entry/src/main/ets/ssh/HostKeyVerifier.ts b/entry/src/main/ets/ssh/HostKeyVerifier.ts new file mode 100644 index 0000000..1abaec1 --- /dev/null +++ b/entry/src/main/ets/ssh/HostKeyVerifier.ts @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * TOFU (trust-on-first-use) host key decision engine: pure logic, no UI and + * no database — persistence and user prompting are injected interfaces, so + * the diagnostics page and the future connection layer can share the policy. + */ + +import { bytesEqual } from './SshWire'; +import { sha256Fingerprint } from '../common/Fingerprint'; + +/** Outcome of comparing the presented key against stored records. */ +export type HostKeyStatus = 'new' | 'changed' | 'trusted'; + +/** User/policy decision for a 'new' or 'changed' host key. */ +export type HostKeyDecision = 'accept-save' | 'accept-once' | 'reject'; + +/** One known-hosts entry: host spec + algorithm + key blob. */ +export interface KnownHostRecord { + hostPort: string; + keyAlgo: string; + keyBlob: Uint8Array; +} + +/** Persistence surface injected into the TOFU engine. */ +export interface KnownHostStore { + lookup(hostPort: string): Promise; + /** Insert or replace the entry of the same hostPort + keyAlgo. */ + save(record: KnownHostRecord): Promise; +} + +/** What a HostKeyDecider sees when making its decision. */ +export interface HostKeyPrompt { + /** 'new' or 'changed' ('trusted' never prompts). */ + status: HostKeyStatus; + hostPort: string; + keyAlgo: string; + /** SHA256:... fingerprint of the presented key. */ + fingerprint: string; + /** For 'changed': fingerprints of every stored key for this host. */ + knownFingerprints: string[]; +} + +/** UI/policy callback that resolves a host key prompt. */ +export interface HostKeyDecider { + decide(prompt: HostKeyPrompt): Promise; +} + +/** known_hosts style host spec: "host" for port 22, "[host]:port" otherwise. */ +export function hostPortString(host: string, port: number): string { + return port === 22 ? host : `[${host}]:${port}`; +} + +/** + * TOFU host key verification: + * 1. the blob equals any stored record's blob -> trusted, return silently; + * 2. records exist but none matches -> status 'changed'; + * 3. no records at all -> status 'new'; + * then ask the decider and honor its decision. 'reject' throws, so callers + * see the failure reason; 'accept-save' persists the key; 'accept-once' + * continues without saving. + */ +export async function verifyHostKeyTofu(store: KnownHostStore, decider: HostKeyDecider, + host: string, port: number, keyAlgo: string, keyBlob: Uint8Array): Promise { + const hostPort: string = hostPortString(host, port); + const records: KnownHostRecord[] = await store.lookup(hostPort); + for (let i = 0; i < records.length; i++) { + if (bytesEqual(records[i].keyBlob, keyBlob)) { + return; // trusted: exact key already on file + } + } + const knownFps: string[] = []; + for (let i = 0; i < records.length; i++) { + knownFps.push(sha256Fingerprint(records[i].keyBlob)); + } + const prompt: HostKeyPrompt = { + status: records.length > 0 ? 'changed' : 'new', + hostPort: hostPort, + keyAlgo: keyAlgo, + fingerprint: sha256Fingerprint(keyBlob), + knownFingerprints: knownFps + }; + const decision: HostKeyDecision = await decider.decide(prompt); + if (decision === 'reject') { + throw new Error(`host key rejected: ${hostPortString(host, port)}`); + } + if (decision === 'accept-save') { + const record: KnownHostRecord = { + hostPort: hostPort, + keyAlgo: keyAlgo, + keyBlob: keyBlob + }; + await store.save(record); + } + // 'accept-once': continue without persisting. +} + +/** + * Map-backed KnownHostStore for tests and diagnostics; save() replaces the + * entry with the same hostPort + keyAlgo. A fresh instance per run makes + * every live test see status 'new'. + */ +export class InMemoryKnownHostStore implements KnownHostStore { + private records: Map = new Map(); + + async lookup(hostPort: string): Promise { + const out: KnownHostRecord[] = []; + this.records.forEach((rec: KnownHostRecord): void => { + if (rec.hostPort === hostPort) { + out.push(rec); + } + }); + return out; + } + + async save(record: KnownHostRecord): Promise { + this.records.set(`${record.hostPort}|${record.keyAlgo}`, record); + } +} diff --git a/entry/src/main/ets/ssh/Kex.ts b/entry/src/main/ets/ssh/Kex.ts new file mode 100644 index 0000000..144aec8 --- /dev/null +++ b/entry/src/main/ets/ssh/Kex.ts @@ -0,0 +1,410 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * SSH key exchange engine (T5): ECDH-only KEX over SshTransport — + * curve25519-sha256[/@libssh.org] (RFC 8731) and ecdh-sha2-nistp256 + * (RFC 5656 §4) — with the RFC 4253 §7.2 KDF, RFC 8308 ext-info awareness + * and OpenSSH strict-kex (Terrapin) enforcement. + */ + +import { Log } from '../common/Log'; +import { SshMsg, disconnectReason } from './SshTypes'; +import { SshReader, SshWriter } from './SshWire'; +import { ClientProposals, negotiate } from './Algorithms'; +import { SshTransport, KexInitInfo } from './Transport'; +import { GcmPacketCipher, CtrMacPacketCipher, cipherInfo, macInfo, CipherInfo, MacInfo } from './Ciphers'; +import { PacketCipher } from './PacketCodec'; +import { CryptoAdapter, RawKeyPair } from './crypto/CryptoAdapter'; +import { verifyHostKeySignature } from './crypto/KeyImport'; +import { sha256Fingerprint } from '../common/Fingerprint'; + +/** Algorithms negotiated from the two KEXINIT payloads (RFC 4253 §7.1). */ +export interface NegotiatedAlgos { + kex: string; + hostKeyAlgo: string; + cipherC2s: string; + cipherS2c: string; + /** '' when the negotiated cipher is AEAD (effective MAC "implicit none"). */ + macC2s: string; + /** '' when the negotiated cipher is AEAD (effective MAC "implicit none"). */ + macS2c: string; +} + +/** Everything callers need after a successful key exchange. */ +export interface KexResult { + negotiated: NegotiatedAlgos; + /** Exchange hash H = SHA256(V_C..K_S..Q_C..Q_S..K) per RFC 4253 §8. */ + exchangeHash: Uint8Array; + /** Session id: H from the first KEX, fixed for the connection lifetime. */ + sessionId: Uint8Array; + hostKeyAlgo: string; + hostKeyBlob: Uint8Array; + /** SHA256:... OpenSSH-style fingerprint of hostKeyBlob. */ + hostKeyFingerprint: string; + /** Server version banner, without \r\n. */ + serverBanner: string; + /** Client version banner, without \r\n. */ + clientBanner: string; + /** Server advertised kex-strict-s-v00@openssh.com. */ + strictKex: boolean; + /** Server advertised ext-info-s (EXT_INFO follows NEWKEYS, RFC 8308). */ + extInfoExpected: boolean; +} + +/** Host key policy hook: resolve true to proceed; false (or throw) aborts. */ +export type HostKeyCallback = (algo: string, blob: Uint8Array, fingerprint: string) => Promise; + +/** KEX name-list entries that are protocol markers, never real algorithms. */ +const KEX_MARKERS: string[] = [ + 'ext-info-c', + 'ext-info-s', + 'kex-strict-c-v00@openssh.com', + 'kex-strict-s-v00@openssh.com' +]; + +/** Remove RFC 8308 / OpenSSH strict-kex marker names from a kex name-list. */ +function stripKexMarkers(list: string[]): string[] { + const out: string[] = []; + for (let i = 0; i < list.length; i++) { + if (KEX_MARKERS.indexOf(list[i]) < 0) { + out.push(list[i]); + } + } + return out; +} + +export class KexEngine { + private static readonly TAG: string = 'KexEngine'; + + private transport: SshTransport; + private onHostKey: HostKeyCallback; + + constructor(transport: SshTransport, onHostKey: HostKeyCallback) { + this.transport = transport; + this.onHostKey = onHostKey; + } + + /** + * Run one full key exchange over the transport (banner exchange must have + * completed). Both banners are the identification strings WITHOUT the + * trailing \r\n — exactly as SshVersion.CLIENT_BANNER is defined and as + * SshTransport.start() returns them (matching the exchange-hash inputs + * used by OpenSSH kex_gen_hash / JSch). + * + * On success the transport is switched into the negotiated encrypted mode + * with sequence numbers reset (RFC 4253 §6.4). + * + * @param sessionId session id of an earlier KEX (rekey); omit on the first + * KEX, where H becomes the session id (RFC 4253 §7.2). + */ + async run(clientBanner: string, serverBanner: string, timeoutMs: number, + sessionId?: Uint8Array): Promise { + // 1) KEXINIT (RFC 4253 §7.1): random cookie + our proposal lists. + const cookie: Uint8Array = await CryptoAdapter.randomBytes(16); + const iC: Uint8Array = this.transport.buildKexInit(cookie); + await this.transport.sendPacket(iC); + + // 2) + 3) wait for the server KEXINIT and parse it. + const iS: Uint8Array = await this.expectMessage(SshMsg.KEXINIT, timeoutMs); + const serverInfo: KexInitInfo = this.transport.parseKexInit(iS); + + // 4) negotiate every field in client preference order. + const clientKex: string[] = stripKexMarkers(ClientProposals.kexAlgos); + const serverKex: string[] = stripKexMarkers(serverInfo.kexAlgos); + const kex: string | undefined = negotiate(clientKex, serverKex); + if (kex === undefined) { + throw new Error(`KEX: no common key exchange algorithm (client: ${clientKex.join(',')} / ` + + `server: ${serverKex.join(',')})`); + } + if (kex !== 'curve25519-sha256' && kex !== 'curve25519-sha256@libssh.org' && + kex !== 'ecdh-sha2-nistp256') { + throw new Error(`KEX: unsupported key exchange algorithm '${kex}'`); + } + + const hostKeyAlgo: string | undefined = negotiate(ClientProposals.hostKeyAlgos, + serverInfo.serverHostKeyAlgos); + if (hostKeyAlgo === undefined) { + let msg: string = `KEX: no common host key algorithm (client: ${ClientProposals.hostKeyAlgos.join(',')} / ` + + `server: ${serverInfo.serverHostKeyAlgos.join(',')})`; + if (serverInfo.serverHostKeyAlgos.indexOf('ssh-rsa') >= 0) { + msg += '; the server only offers ssh-rsa, which we no longer support'; + } + throw new Error(msg); + } + + const cipherC2s: string | undefined = negotiate(ClientProposals.ciphersC2s, + serverInfo.encryptionC2s); + if (cipherC2s === undefined) { + throw new Error(`KEX: no common encryption algorithm c2s (client: ${ClientProposals.ciphersC2s.join(',')} / ` + + `server: ${serverInfo.encryptionC2s.join(',')})`); + } + const cipherS2c: string | undefined = negotiate(ClientProposals.ciphersS2c, + serverInfo.encryptionS2c); + if (cipherS2c === undefined) { + throw new Error(`KEX: no common encryption algorithm s2c (client: ${ClientProposals.ciphersS2c.join(',')} / ` + + `server: ${serverInfo.encryptionS2c.join(',')})`); + } + + const cipherInfoC2s: CipherInfo = cipherInfo(cipherC2s); + const cipherInfoS2c: CipherInfo = cipherInfo(cipherS2c); + + let macC2s: string = ''; + if (!cipherInfoC2s.aead) { + const m: string | undefined = negotiate(ClientProposals.macsC2s, serverInfo.macC2s); + if (m === undefined) { + throw new Error(`KEX: no common MAC algorithm c2s (client: ${ClientProposals.macsC2s.join(',')} / ` + + `server: ${serverInfo.macC2s.join(',')})`); + } + macC2s = m; + } + let macS2c: string = ''; + if (!cipherInfoS2c.aead) { + const m: string | undefined = negotiate(ClientProposals.macsS2c, serverInfo.macS2c); + if (m === undefined) { + throw new Error(`KEX: no common MAC algorithm s2c (client: ${ClientProposals.macsS2c.join(',')} / ` + + `server: ${serverInfo.macS2c.join(',')})`); + } + macS2c = m; + } + + const noneOnly: string[] = ['none']; + const compressionC2s: string | undefined = negotiate(noneOnly, serverInfo.compressionC2s); + if (compressionC2s !== 'none') { + throw new Error(`KEX: no common compression algorithm c2s (client: none / ` + + `server: ${serverInfo.compressionC2s.join(',')})`); + } + const compressionS2c: string | undefined = negotiate(noneOnly, serverInfo.compressionS2c); + if (compressionS2c !== 'none') { + throw new Error(`KEX: no common compression algorithm s2c (client: none / ` + + `server: ${serverInfo.compressionS2c.join(',')})`); + } + + const strictKex: boolean = serverInfo.kexAlgos.indexOf('kex-strict-s-v00@openssh.com') >= 0; + const extInfoExpected: boolean = serverInfo.kexAlgos.indexOf('ext-info-s') >= 0; + Log.info(KexEngine.TAG, `negotiated: kex=${kex} hostKey=${hostKeyAlgo} cipher=${cipherC2s}/${cipherS2c} ` + + `mac=${macC2s.length > 0 ? macC2s : '(aead)'}/${macS2c.length > 0 ? macS2c : '(aead)'} ` + + `strictKex=${strictKex} extInfo=${extInfoExpected}`); + + // 5) strict-kex: the server KEXINIT must have been its first packet. + if (strictKex && this.transport.getInSeq() !== 1) { + throw new Error('strict KEX: KEXINIT was not the first packet from server'); + } + + // 6) wrong first_kex_packet_follows guess (RFC 4253 §7.1): the server's + // guessed kex/host-key pair must match ours, else it discards one + // packet — fatal under strict-kex. + if (serverInfo.firstKexPacketFollows) { + const strippedServerKex: string[] = stripKexMarkers(serverInfo.kexAlgos); + const guessKex: string = strippedServerKex.length > 0 ? strippedServerKex[0] : ''; + const guessHostKey: string = serverInfo.serverHostKeyAlgos.length > 0 + ? serverInfo.serverHostKeyAlgos[0] : ''; + if (guessKex !== kex || guessHostKey !== hostKeyAlgo) { + if (strictKex) { + throw new Error('strict KEX: wrong first_kex_packet_follows guess'); + } + Log.warn(KexEngine.TAG, 'discarding wrong guess packet'); + await this.expectMessage(-1, timeoutMs); + } + } + + // 7) ephemeral key pair + KEXDH_INIT / KEX_ECDH_INIT. + let kp: RawKeyPair; + let qc: Uint8Array; + if (kex === 'ecdh-sha2-nistp256') { + kp = await CryptoAdapter.ecdhP256GenerateKeyPair(); + qc = kp.pub; // uncompressed point 04||X||Y (65 bytes, RFC 5656 §3.1) + } else { + kp = await CryptoAdapter.x25519GenerateKeyPair(); + qc = kp.pub; // raw 32 bytes (RFC 8731) + } + const init: SshWriter = new SshWriter(64); + init.writeByte(SshMsg.KEXDH_INIT); + init.writeStringBytes(qc); + await this.transport.sendPacket(init.toBytes()); + + // 8) KEXDH_REPLY: K_S, Q_S, signature. + const reply: Uint8Array = await this.expectMessage(SshMsg.KEXDH_REPLY, timeoutMs); + const rr: SshReader = new SshReader(reply); + rr.readByte(); // message number + const hostKeyBlob: Uint8Array = rr.readStringBytes(); + const qs: Uint8Array = rr.readStringBytes(); + const sigBlob: Uint8Array = rr.readStringBytes(); + + // 9) shared secret K. + let k: Uint8Array; + if (kex === 'ecdh-sha2-nistp256') { + if (qs.length !== 65 || qs[0] !== 0x04) { + throw new Error(`KEX: bad ECDH server public key (${qs.length} bytes)`); + } + const raw: Uint8Array = await CryptoAdapter.ecdhP256Agreement(kp.pri, qs); + if (raw.length === 32) { + k = raw; + } else if (raw.length === 64) { + k = raw.slice(0, 32); + } else if (raw.length === 65) { + k = raw.slice(1, 33); + } else { + throw new Error(`KEX: unexpected ECDH shared secret length ${raw.length}`); + } + } else { + if (qs.length !== 32) { + throw new Error(`KEX: X25519 server public key must be 32 bytes, got ${qs.length}`); + } + k = await CryptoAdapter.x25519Agreement(kp.pri, qs); + let allZero: boolean = true; + for (let i = 0; i < k.length; i++) { + if (k[i] !== 0) { + allZero = false; + break; + } + } + if (allZero) { + throw new Error('KEX: all-zero X25519 shared secret'); + } + } + + // 10) exchange hash H = SHA256 of V_C, V_S, I_C, I_S, K_S, Q_C, Q_S, K + // (banners without \r\n; KEXINIT payloads include their msg byte 20; + // K as canonical mpint) — exactly OpenSSH kex_gen_hash's input order. + const hw: SshWriter = new SshWriter(256); + hw.writeString(clientBanner); + hw.writeString(serverBanner); + hw.writeStringBytes(iC); + hw.writeStringBytes(iS); + hw.writeStringBytes(hostKeyBlob); + hw.writeStringBytes(qc); + hw.writeStringBytes(qs); + hw.writeMpint(k); + const h: Uint8Array = CryptoAdapter.sha256Sync(hw.toBytes()); + + // 11) verify the server's host key signature over H. + if (!verifyHostKeySignature(hostKeyAlgo, hostKeyBlob, h, sigBlob)) { + throw new Error('host key signature verification failed'); + } + + // 12) session id: carried over on rekey, else H from this first KEX. + const sid: Uint8Array = sessionId !== undefined ? sessionId : h.slice(0); + + // 13) full mpint wire form of K (BE32 length + canonical magnitude) as + // the KDF seed — expandKey expects exactly these bytes. + const kw: SshWriter = new SshWriter(64); + kw.writeMpint(k); + const kWire: Uint8Array = kw.toBytes(); + + // 14) derive keys per RFC 4253 §7.2 — each key independently from + // expandKey(SHA256, kWire, H, letter, sessionId, need); MAC keys + // are skipped entirely for AEAD ciphers. + const ivC2s: Uint8Array = CryptoAdapter.expandKey('SHA256', kWire, h, 'A', sid, 16); + const ivS2c: Uint8Array = CryptoAdapter.expandKey('SHA256', kWire, h, 'B', sid, 16); + const keyC2s: Uint8Array = CryptoAdapter.expandKey('SHA256', kWire, h, 'C', sid, cipherInfoC2s.keyLen); + const keyS2c: Uint8Array = CryptoAdapter.expandKey('SHA256', kWire, h, 'D', sid, cipherInfoS2c.keyLen); + let macKeyC2s: Uint8Array = new Uint8Array(0); + if (!cipherInfoC2s.aead) { + macKeyC2s = CryptoAdapter.expandKey('SHA256', kWire, h, 'E', sid, macInfo(macC2s).keyLen); + } + let macKeyS2c: Uint8Array = new Uint8Array(0); + if (!cipherInfoS2c.aead) { + macKeyS2c = CryptoAdapter.expandKey('SHA256', kWire, h, 'F', sid, macInfo(macS2c).keyLen); + } + + // 15) host key policy decision (TOFU or any other policy, injected). + const fingerprint: string = sha256Fingerprint(hostKeyBlob); + const ok: boolean = await this.onHostKey(hostKeyAlgo, hostKeyBlob, fingerprint); + if (!ok) { + throw new Error('host key rejected'); + } + + // 16) NEWKEYS, then IMMEDIATELY install the outbound cipher (RFC 4253 + // §7.3 order: everything after our NEWKEYS goes out encrypted). + const nk: SshWriter = new SshWriter(8); + nk.writeByte(SshMsg.NEWKEYS); + await this.transport.sendPacket(nk.toBytes()); + let outCipher: PacketCipher; + if (cipherInfoC2s.aead) { + outCipher = new GcmPacketCipher(keyC2s, ivC2s, keyC2s.length); + } else { + const miC2s: MacInfo = macInfo(macC2s); + outCipher = new CtrMacPacketCipher(keyC2s, ivC2s, macKeyC2s, miC2s.tagLen, miC2s.etm); + } + this.transport.setOutCipher(outCipher, cipherInfoC2s.blockSize, cipherInfoC2s.minPadding); + + // 17) server NEWKEYS, then install the inbound cipher and reset the + // sequence numbers (RFC 4253 §6.4). + await this.expectMessage(SshMsg.NEWKEYS, timeoutMs); + let inCipher: PacketCipher; + if (cipherInfoS2c.aead) { + inCipher = new GcmPacketCipher(keyS2c, ivS2c, keyS2c.length); + } else { + const miS2c: MacInfo = macInfo(macS2c); + inCipher = new CtrMacPacketCipher(keyS2c, ivS2c, macKeyS2c, miS2c.tagLen, miS2c.etm); + } + this.transport.setInCipher(inCipher); + this.transport.resetSequenceNumbers(); + + // 18) done. + const negotiated: NegotiatedAlgos = { + kex: kex, + hostKeyAlgo: hostKeyAlgo, + cipherC2s: cipherC2s, + cipherS2c: cipherS2c, + macC2s: macC2s, + macS2c: macS2c + }; + const result: KexResult = { + negotiated: negotiated, + exchangeHash: h, + sessionId: sid, + hostKeyAlgo: hostKeyAlgo, + hostKeyBlob: hostKeyBlob, + hostKeyFingerprint: fingerprint, + serverBanner: serverBanner, + clientBanner: clientBanner, + strictKex: strictKex, + extInfoExpected: extInfoExpected + }; + return result; + } + + /** + * Wait for the next protocol message, transparently consuming DISCONNECT + * (fatal — parsed and rethrown), IGNORE / UNIMPLEMENTED / DEBUG + * (informational). A `want` below 0 means "return the next + * non-informational message, whatever it is" — used to discard exactly + * one wrong first_kex_packet_follows guess. + */ + private async expectMessage(want: number, timeoutMs: number): Promise { + while (true) { + const p: Uint8Array = await this.transport.waitPacket(timeoutMs); + const msg: number = p[0]; + if (msg === SshMsg.DISCONNECT) { + const r: SshReader = new SshReader(p); + r.readByte(); + const code: number = r.readUint32(); + const desc: string = r.readString(); + r.readString(); // language tag + throw new Error(`server disconnected: ${disconnectReason(code)} (${desc})`); + } + if (msg === SshMsg.IGNORE) { + continue; + } + if (msg === SshMsg.UNIMPLEMENTED) { + Log.warn(KexEngine.TAG, 'KEX: server sent UNIMPLEMENTED, continuing'); + continue; + } + if (msg === SshMsg.DEBUG_MSG) { + const r: SshReader = new SshReader(p); + r.readByte(); + const alwaysDisplay: boolean = r.readBoolean(); + const dbg: string = r.readString(); + r.readString(); // language tag + Log.debug(KexEngine.TAG, `server debug (alwaysDisplay=${alwaysDisplay}): ${dbg}`); + continue; + } + if (want < 0 || msg === want) { + return p; + } + throw new Error(`KEX: unexpected message ${msg} (expected ${want})`); + } + } +} diff --git a/entry/src/main/ets/ssh/SshTypes.ts b/entry/src/main/ets/ssh/SshTypes.ts index 92030cd..430f172 100644 --- a/entry/src/main/ets/ssh/SshTypes.ts +++ b/entry/src/main/ets/ssh/SshTypes.ts @@ -39,6 +39,12 @@ export class SshMsg { static readonly USERAUTH_BANNER: number = 53; /** SSH_MSG_USERAUTH_INFO_REQUEST (RFC 4256, keyboard-interactive) */ static readonly USERAUTH_INFO_REQUEST: number = 60; + /** + * SSH_MSG_USERAUTH_PK_OK (RFC 4252 §7, publickey "query" ack). Shares the + * value 60 with USERAUTH_INFO_REQUEST: the meaning is context-dependent + * (determined by the auth phase, RFC 4252 §7 / RFC 4256). + */ + static readonly USERAUTH_PK_OK: number = 60; /** SSH_MSG_USERAUTH_INFO_RESPONSE */ static readonly USERAUTH_INFO_RESPONSE: number = 61; /** SSH_MSG_GLOBAL_REQUEST (RFC 4254 §4) */ @@ -65,6 +71,10 @@ export class SshMsg { static readonly CHANNEL_CLOSE: number = 97; /** SSH_MSG_CHANNEL_REQUEST (§5.4) */ static readonly CHANNEL_REQUEST: number = 98; + /** SSH_MSG_CHANNEL_SUCCESS (§5.4) */ + static readonly CHANNEL_SUCCESS: number = 99; + /** SSH_MSG_CHANNEL_FAILURE (§5.4) */ + static readonly CHANNEL_FAILURE: number = 100; } /** @@ -118,6 +128,9 @@ export class SshVersion { * Mirrors JSch defaults trimmed to what cryptoFramework can implement. * Per RFC 8308, ext-info-c signals server-sent EXT_INFO support; per OpenSSH * strict KEX, kex-strict-c-v00@openssh.com must be the LAST kex entry. + * ssh-rsa (RSA-SHA1) is NOT proposed: the platform crypto lacks a reliable + * SHA1 sign/verify spec string, and OpenSSH 8.8+ disables ssh-rsa by + * default; rsa-sha2-* still cover OpenSSH 7.4+ servers. */ export class SshAlgoLists { static readonly KEX: string[] = [ @@ -131,8 +144,7 @@ export class SshAlgoLists { 'ssh-ed25519', 'ecdsa-sha2-nistp256', 'rsa-sha2-512', - 'rsa-sha2-256', - 'ssh-rsa' + 'rsa-sha2-256' ]; static readonly CIPHER: string[] = [ 'aes128-gcm@openssh.com', diff --git a/entry/src/main/ets/ssh/Transport.ts b/entry/src/main/ets/ssh/Transport.ts index 8978b48..8d9fda0 100644 --- a/entry/src/main/ets/ssh/Transport.ts +++ b/entry/src/main/ets/ssh/Transport.ts @@ -105,9 +105,12 @@ export class SshTransport { return banner; } - /** Persistent packet handler (waitPacket takes precedence when armed). */ - onPacket(cb: (payload: Uint8Array) => void): void { - this.packetCallback = cb; + /** + * Persistent packet handler (waitPacket takes precedence when armed). + * Pass null to clear the dispatcher (phase transitions stop consuming). + */ + onPacket(cb: ((payload: Uint8Array) => void) | null): void { + this.packetCallback = cb === null ? undefined : cb; } /** Connection loss notification. */