From e7ef63e0421df1497b49c96cf952394281358dde Mon Sep 17 00:00:00 2001 From: ROG-X57R Date: Tue, 8 Sep 2026 10:39:24 +0800 Subject: [PATCH] =?UTF-8?q?T4:=20crypto=20suite=20=E2=80=94=20GCM/CTR/etM/?= =?UTF-8?q?plain=20MAC=20packet=20ciphers,=20KDF=20expansion,=20DerUtils,?= =?UTF-8?q?=20KeyImport=20host-key=20verify,=20RFC=20vector=20self-test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- entry/src/main/ets/pages/DiagPage.ets | 292 +++++++++++- entry/src/main/ets/ssh/Ciphers.ts | 434 ++++++++++++++++++ entry/src/main/ets/ssh/PacketCodec.ts | 30 +- .../src/main/ets/ssh/crypto/CryptoAdapter.ts | 237 +++++++++- entry/src/main/ets/ssh/crypto/DerUtils.ts | 361 +++++++++++++++ entry/src/main/ets/ssh/crypto/KeyImport.ts | 172 +++++++ 6 files changed, 1511 insertions(+), 15 deletions(-) create mode 100644 entry/src/main/ets/ssh/Ciphers.ts create mode 100644 entry/src/main/ets/ssh/crypto/DerUtils.ts create mode 100644 entry/src/main/ets/ssh/crypto/KeyImport.ts diff --git a/entry/src/main/ets/pages/DiagPage.ets b/entry/src/main/ets/pages/DiagPage.ets index 8d17e9e..de4d196 100644 --- a/entry/src/main/ets/pages/DiagPage.ets +++ b/entry/src/main/ets/pages/DiagPage.ets @@ -9,11 +9,16 @@ import { SshTransport, KexInitInfo } from '../ssh/Transport'; import { TcpRawSocket } from '../ssh/OhosTcpSocket'; -import { packetCodecSelfTest } from '../ssh/PacketCodec'; +import { packetCodecSelfTest, PacketCodec } from '../ssh/PacketCodec'; +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 { ClientProposals } from '../ssh/Algorithms'; -import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual } from '../ssh/SshWire'; +import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual, concatBytes, SshWriter } from '../ssh/SshWire'; +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component @@ -93,6 +98,11 @@ struct DiagPage { .onClick(() => { this.runTest((): Promise => this.testPacketCodec()); }) + Button('8. 加密套件自测 (RFC 向量)') + .width('100%') + .onClick(() => { + this.runTest((): Promise => this.testCryptoSuite()); + }) } .width('100%') @@ -383,4 +393,282 @@ struct DiagPage { this.log('FAIL', 'PacketCodec 自测失败'); } } + + /** 8) Crypto suite self test: RFC vectors, packet ciphers, KDF, DER, KeyImport. */ + private async testCryptoSuite(): Promise { + let pass: number = 0; + let fail: number = 0; + const check = (ok: boolean, name: string): void => { + if (ok) { + this.log('PASS', name); + pass += 1; + } else { + this.log('FAIL', name); + fail += 1; + } + }; + + // 1) HMAC RFC 4231 test case 1 (key = 0x0b x20, data = "Hi There") + const hmacKey: Uint8Array = new Uint8Array(20); + for (let i = 0; i < hmacKey.length; i++) { + hmacKey[i] = 0x0b; + } + const hmacData: Uint8Array = utf8ToBytes('Hi There'); + const mac256: Uint8Array = CryptoAdapter.hmacSha256Sync(hmacKey, hmacData); + check(bytesToHex(mac256) === 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7', + 'HMAC-SHA-256 RFC 4231 TC1'); + const mac512: Uint8Array = CryptoAdapter.hmacSha512Sync(hmacKey, hmacData); + check(bytesToHex(mac512) === '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854', + 'HMAC-SHA-512 RFC 4231 TC1'); + + // 2) AES-128-CTR, NIST SP 800-38A F.5.5 (CTR-AES128.Encrypt) + const ctrKey: Uint8Array = hexToBytes('2b7e151628aed2a6abf7158809cf4f3c'); + const ctrIv: Uint8Array = hexToBytes('f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'); + const ctr1: Uint8Array = CryptoAdapter.aesCtrCryptSync(ctrKey, ctrIv, + hexToBytes('6bc1bee22e409f96e93d7e117393172a'), cryptoFramework.CryptoMode.ENCRYPT_MODE); + check(bytesEqual(ctr1, hexToBytes('874d6191b620e3261bef6864990db6ce')), + 'AES-128-CTR 单块 (NIST F.5.5)'); + const ctr4: Uint8Array = CryptoAdapter.aesCtrCryptSync(ctrKey, ctrIv, + hexToBytes('6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710'), + cryptoFramework.CryptoMode.ENCRYPT_MODE); + check(bytesEqual(ctr4, hexToBytes('874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee')), + 'AES-128-CTR 4 块连续 (NIST F.5.5)'); + + // 3) GCM packet cipher: framing + byte-at-a-time round trip + tamper + const gcmKey: Uint8Array = await CryptoAdapter.randomBytes(32); + const gcmIvMat: Uint8Array = await CryptoAdapter.randomBytes(16); + const gcmEnc: GcmPacketCipher = new GcmPacketCipher(gcmKey, gcmIvMat, 32); + const gcmDec: GcmPacketCipher = new GcmPacketCipher(gcmKey, gcmIvMat, 32); + const g1: Uint8Array = await CryptoAdapter.randomBytes(5); + const g2: Uint8Array = await CryptoAdapter.randomBytes(40); + const g3: Uint8Array = await CryptoAdapter.randomBytes(300); + const gw1: Uint8Array = gcmEnc.encryptToPacket(g1, 0); + const gw2: Uint8Array = gcmEnc.encryptToPacket(g2, 1); + const gw3: Uint8Array = gcmEnc.encryptToPacket(g3, 2); + let gcmFramingOk: boolean = true; + const gws: Uint8Array[] = [gw1, gw2, gw3]; + for (let gi = 0; gi < gws.length; gi++) { + const w: Uint8Array = gws[gi]; + const plen: number = ((w[0] * 256 + w[1]) * 256 + w[2]) * 256 + w[3]; + if (plen % 16 !== 0 || plen < 16 || plen > 1048576 || w.length !== 4 + plen + 16) { + gcmFramingOk = false; + } + } + check(gcmFramingOk, 'GCM 分帧: 明文长度字段 + packet_length%16==0 + 总长 4+len+16'); + const gcmCodec: PacketCodec = new PacketCodec(); + gcmCodec.setInCipher(gcmDec); + const gcmStream: Uint8Array = concatBytes(concatBytes(gw1, gw2), gw3); + let gcmCount: number = 0; + let gcmRoundOk: boolean = true; + for (let bi = 0; bi < gcmStream.length; bi++) { + gcmCodec.pushBytes(gcmStream.slice(bi, bi + 1)); + let draining: boolean = true; + while (draining) { + const p: Uint8Array | undefined = await gcmCodec.nextPacket(); + if (p === undefined) { + draining = false; + } else { + gcmCount += 1; + const want: Uint8Array = gcmCount === 1 ? g1 : (gcmCount === 2 ? g2 : g3); + if (!bytesEqual(p, want)) { + gcmRoundOk = false; + } + } + } + } + check(gcmRoundOk && gcmCount === 3, 'GCM 往返: 逐字节喂入 3 包, 调用计数器跨包连续'); + const gcmTampered: Uint8Array = gw1.slice(0); + gcmTampered[10] ^= 0xff; // ciphertext byte + const gcmDecT: GcmPacketCipher = new GcmPacketCipher(gcmKey, gcmIvMat, 32); + let gcmTamperThrew: boolean = false; + try { + await gcmDecT.tryDecryptPacket(gcmTampered); + } catch (e) { + gcmTamperThrew = true; + } + check(gcmTamperThrew, 'GCM 篡改密文 → 认证失败抛出'); + + // 4) CTR + hmac-sha2-256 (plain MAC): 7-byte chunk feeding + MAC tamper + const cKey: Uint8Array = await CryptoAdapter.randomBytes(16); + const cIv: Uint8Array = await CryptoAdapter.randomBytes(16); + const cMac: Uint8Array = await CryptoAdapter.randomBytes(32); + const cEnc: CtrMacPacketCipher = new CtrMacPacketCipher(cKey, cIv, cMac, 32, false); + const cDec: CtrMacPacketCipher = new CtrMacPacketCipher(cKey, cIv, cMac, 32, false); + const c1: Uint8Array = await CryptoAdapter.randomBytes(5); + const c2: Uint8Array = await CryptoAdapter.randomBytes(40); + const c3: Uint8Array = await CryptoAdapter.randomBytes(300); + const cw1: Uint8Array = cEnc.encryptToPacket(c1, 0); + const cw2: Uint8Array = cEnc.encryptToPacket(c2, 1); + const cw3: Uint8Array = cEnc.encryptToPacket(c3, 2); + const cCodec: PacketCodec = new PacketCodec(); + cCodec.setInCipher(cDec); + const cStream: Uint8Array = concatBytes(concatBytes(cw1, cw2), cw3); + let cCount: number = 0; + let cRoundOk: boolean = true; + let ci: number = 0; + while (ci < cStream.length) { + const cEnd: number = ci + 7 <= cStream.length ? ci + 7 : cStream.length; + cCodec.pushBytes(cStream.slice(ci, cEnd)); + ci = cEnd; + let draining2: boolean = true; + while (draining2) { + const p2: Uint8Array | undefined = await cCodec.nextPacket(); + if (p2 === undefined) { + draining2 = false; + } else { + cCount += 1; + const want2: Uint8Array = cCount === 1 ? c1 : (cCount === 2 ? c2 : c3); + if (!bytesEqual(p2, want2)) { + cRoundOk = false; + } + } + } + } + check(cRoundOk && cCount === 3, 'CTR+hmac-sha2-256 往返: 7 字节分块(试解密缓存) + 跨包计数器连续'); + const cTampered: Uint8Array = cw1.slice(0); + cTampered[cTampered.length - 1] ^= 0xff; // MAC byte + const cDecT: CtrMacPacketCipher = new CtrMacPacketCipher(cKey, cIv, cMac, 32, false); + let cTamperThrew: boolean = false; + try { + await cDecT.tryDecryptPacket(cTampered); + } catch (e) { + cTamperThrew = true; + } + check(cTamperThrew, 'CTR+plainMAC 篡改 MAC → 校验失败抛出'); + + // 5) CTR + hmac-sha2-512 etm variant + CT tamper + const eKey: Uint8Array = await CryptoAdapter.randomBytes(16); + const eIv: Uint8Array = await CryptoAdapter.randomBytes(16); + const eMac: Uint8Array = await CryptoAdapter.randomBytes(64); + const eEnc: CtrMacPacketCipher = new CtrMacPacketCipher(eKey, eIv, eMac, 64, true); + const eDec: CtrMacPacketCipher = new CtrMacPacketCipher(eKey, eIv, eMac, 64, true); + const e1: Uint8Array = await CryptoAdapter.randomBytes(9); + const e2: Uint8Array = await CryptoAdapter.randomBytes(70); + const e3: Uint8Array = await CryptoAdapter.randomBytes(256); + const ew1: Uint8Array = eEnc.encryptToPacket(e1, 0); + const ew2: Uint8Array = eEnc.encryptToPacket(e2, 1); + const ew3: Uint8Array = eEnc.encryptToPacket(e3, 2); + const eCodec: PacketCodec = new PacketCodec(); + eCodec.setInCipher(eDec); + const eStream: Uint8Array = concatBytes(concatBytes(ew1, ew2), ew3); + let eCount: number = 0; + let eRoundOk: boolean = true; + for (let ei = 0; ei < eStream.length; ei++) { + eCodec.pushBytes(eStream.slice(ei, ei + 1)); + let draining3: boolean = true; + while (draining3) { + const p3: Uint8Array | undefined = await eCodec.nextPacket(); + if (p3 === undefined) { + draining3 = false; + } else { + eCount += 1; + const want3: Uint8Array = eCount === 1 ? e1 : (eCount === 2 ? e2 : e3); + if (!bytesEqual(p3, want3)) { + eRoundOk = false; + } + } + } + } + check(eRoundOk && eCount === 3, 'CTR+hmac-sha2-512-etm 往返: 逐字节喂入 3 包'); + const eTampered: Uint8Array = ew1.slice(0); + eTampered[8] ^= 0xff; // ciphertext byte, MAC must catch it before decrypt + const eDecT: CtrMacPacketCipher = new CtrMacPacketCipher(eKey, eIv, eMac, 64, true); + let eTamperThrew: boolean = false; + try { + await eDecT.tryDecryptPacket(eTampered); + } catch (e) { + eTamperThrew = true; + } + check(eTamperThrew, 'CTR+etm 篡改密文 → MAC 优先校验抛出'); + + // 6) KDF expansion (RFC 4253 §7.2): determinism, length, chain structure + const kK: Uint8Array = await CryptoAdapter.randomBytes(32); + const kH: Uint8Array = await CryptoAdapter.randomBytes(32); + const kSid: Uint8Array = await CryptoAdapter.randomBytes(32); + const ex1: Uint8Array = CryptoAdapter.expandKey('SHA256', kK, kH, 'C', kSid, 80); + const ex2: Uint8Array = CryptoAdapter.expandKey('SHA256', kK, kH, 'C', kSid, 80); + check(ex1.length === 80 && bytesEqual(ex1, ex2), 'expandKey 确定性 + 截断至 80 字节'); + const k1: Uint8Array = CryptoAdapter.sha256Sync( + concatBytes(concatBytes(concatBytes(kK, kH), utf8ToBytes('C')), kSid)); + check(bytesEqual(ex1.slice(0, 32), k1), 'expandKey K1 = HASH(k||h||letter||sessionId)'); + const k2: Uint8Array = CryptoAdapter.sha256Sync(concatBytes(concatBytes(kK, kH), k1)); + check(bytesEqual(ex1.slice(32, 64), k2), 'expandKey K2 = HASH(k||h||K1) 链式正确'); + + // 7) RSA: SPKI parse/rebuild + sync sign/verify + ssh-rsa(SHA1) probe + const rsaPair: RawKeyPair = CryptoAdapter.rsaGenerateKeyPairSync(2048); + const rsaParts: RsaPublicKeyParts = DerUtils.parseRsaSpki(rsaPair.pub); + const rsaRebuilt: Uint8Array = DerUtils.buildRsaSpki(rsaParts.e, rsaParts.n); + check(bytesEqual(rsaRebuilt, rsaPair.pub) && rsaParts.n.length === 256, + 'RSA SPKI 解析→重建与原始 DER 一致 (modulus 256B)'); + const rsaData: Uint8Array = utf8ToBytes('haven-t4-rsa-pkcs1-roundtrip'); + const rsaSig: Uint8Array = CryptoAdapter.rsaSignPkcs1Sync(rsaPair.pri, rsaData, 'SHA256'); + const rsaOk: boolean = CryptoAdapter.rsaVerifyPkcs1Sync(rsaPair.pub, rsaData, rsaSig, 'SHA256'); + check(rsaOk && rsaSig.length === 256, 'RSA2048|PKCS1|SHA256 同步签名验签'); + try { + const sigSha1: Uint8Array = CryptoAdapter.rsaSignPkcs1Sync(rsaPair.pri, rsaData, 'SHA1'); + const okSha1: boolean = CryptoAdapter.rsaVerifyPkcs1Sync(rsaPair.pub, rsaData, sigSha1, 'SHA1'); + check(okSha1, 'RSA2048|PKCS1|SHA1 (ssh-rsa) 签名验签'); + } catch (e) { + const be: BusinessError = e as BusinessError; + if (be.code === 801) { + this.log('INFO', 'ssh-rsa(SHA1) 不受支持 (code 801),将在 T5 移除 ssh-rsa 提案'); + } else { + this.log('FAIL', `ssh-rsa(SHA1) 异常 code=${be.code}: ${be.message}(将在 T5 评估移除 ssh-rsa 提案)`); + fail += 1; + } + } + + // 8) ECDSA: sign → DER parse → rebuild → verify (validates OH sig format) + const ecPair: RawKeyPair = CryptoAdapter.ecdsaP256GenerateKeyPairSync(); + const ecData: Uint8Array = utf8ToBytes('haven-t4-ecdsa-roundtrip'); + const ecSig: Uint8Array = CryptoAdapter.ecdsaP256SignSync(ecPair.pri, ecData); + const ecParts: EcdsaParts = DerUtils.ecdsaPartsFromDer(ecSig); + const ecRebuilt: Uint8Array = DerUtils.ecdsaDerFromParts(ecParts.r, ecParts.s); + const ecOk: boolean = CryptoAdapter.ecdsaP256VerifySync(ecPair.pub, ecData, ecRebuilt); + check(ecOk, 'ECDSA-P256 签名 DER 解析→重建→验签 (验证 OH 输出格式假设)'); + const ecOk2: boolean = CryptoAdapter.ecdsaP256VerifySync(ecPair.pub, ecData, ecSig); + check(ecOk2, 'ECDSA-P256 原始签名直接验签'); + + // 9) KeyImport: SSH blob format + verifyHostKeySignature, all families + const edPub: Uint8Array = hexToBytes('d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a'); + const edPri: Uint8Array = hexToBytes('9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60'); + const hostData: Uint8Array = utf8ToBytes('haven-t4-hostkey-exchange-hash'); + const edSig: Uint8Array = await CryptoAdapter.ed25519Sign(edPri, hostData); + const edMat: PublicKeyMaterial = { algo: 'ssh-ed25519', ed25519Pub: edPub }; + const edBlob: Uint8Array = buildPublicKeyBlob('ssh-ed25519', edMat); + const edSigW: SshWriter = new SshWriter(96); + edSigW.writeString('ssh-ed25519'); + edSigW.writeStringBytes(edSig); + check(verifyHostKeySignature('ssh-ed25519', edBlob, hostData, edSigW.toBytes()), + 'KeyImport ssh-ed25519 主机密钥验签 (RFC 8032 TEST 1 密钥)'); + check(!verifyHostKeySignature('ssh-ed25519', edBlob, utf8ToBytes('tampered'), edSigW.toBytes()), + 'KeyImport ssh-ed25519 篡改 H → 验签拒绝'); + const ecSig2: Uint8Array = CryptoAdapter.ecdsaP256SignSync(ecPair.pri, hostData); + const ecParts2: EcdsaParts = DerUtils.ecdsaPartsFromDer(ecSig2); + const ecInner: SshWriter = new SshWriter(80); + ecInner.writeMpint(ecParts2.r); + ecInner.writeMpint(ecParts2.s); + const ecMat: PublicKeyMaterial = { algo: 'ecdsa-sha2-nistp256', ecPoint: ecPair.pub }; + const ecBlob: Uint8Array = buildPublicKeyBlob('ecdsa-sha2-nistp256', ecMat); + const ecSigW: SshWriter = new SshWriter(96); + ecSigW.writeString('ecdsa-sha2-nistp256'); + ecSigW.writeStringBytes(ecInner.toBytes()); + check(verifyHostKeySignature('ecdsa-sha2-nistp256', ecBlob, hostData, ecSigW.toBytes()), + 'KeyImport ecdsa-sha2-nistp256 主机密钥验签 (SSH mpint r||s)'); + const rsaMat: PublicKeyMaterial = { algo: 'ssh-rsa', rsaE: rsaParts.e, rsaN: rsaParts.n }; + const rsaBlob: Uint8Array = buildPublicKeyBlob('rsa-sha2-256', rsaMat); + const rsaSigW: SshWriter = new SshWriter(320); + rsaSigW.writeString('rsa-sha2-256'); + rsaSigW.writeStringBytes(rsaSig); + check(verifyHostKeySignature('rsa-sha2-256', rsaBlob, rsaData, rsaSigW.toBytes()), + 'KeyImport rsa-sha2-256 主机密钥验签 (blob 内名 ssh-rsa)'); + + // summary + const total: number = pass + fail; + if (fail === 0) { + this.log('PASS', `加密套件自测 ${pass}/${total}`); + } else { + this.log('FAIL', `加密套件自测 ${pass}/${total},${fail} 项失败`); + } + } } diff --git a/entry/src/main/ets/ssh/Ciphers.ts b/entry/src/main/ets/ssh/Ciphers.ts new file mode 100644 index 0000000..fa081d0 --- /dev/null +++ b/entry/src/main/ets/ssh/Ciphers.ts @@ -0,0 +1,434 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + */ + +/** + * SSH encrypted packet ciphers (T4): AES-GCM (RFC 5647), AES-CTR with a + * plain MAC (RFC 4253 §6 + RFC 6668) and AES-CTR with encrypt-then-MAC + * (*-etm@openssh.com). All crypto runs on the cryptoFramework *Sync APIs + * so the packet hot path stays synchronous (see the PacketCipher contract). + * + * Counter ownership: every cipher instance owns its own packet counter + * starting at 0 and is freshly installed right after NEWKEYS, so sequence + * numbers are implicitly reset (RFC 4253 §6.4 — strict-kex compatible). + * The `seq` argument of encryptToPacket is intentionally ignored. + */ + +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +import { PacketCipher, DecodedPacket } from './PacketCodec'; +import { CryptoAdapter } from './crypto/CryptoAdapter'; +import { concatBytes, bytesEqual } from './SshWire'; + +const MAX_PACKET_LEN: number = 1024 * 1024; +const GCM_TAG_LEN: number = 16; +const AES_BLOCK: number = 16; + +/** + * aes128-gcm@openssh.com / aes256-gcm@openssh.com (RFC 5647). + * + * Wire form: [packet_length(4), PLAINTEXT][CT = E(padLen||payload||pad)] + * [tag(16)] — the length field is authenticated as AAD, not encrypted + * (RFC 5647 §7.3). The encrypted portion is packet_length bytes and MUST + * be a multiple of 16 (RFC 5647 §7.2). + * + * IV (RFC 5647 §7.1, JSch-compatible): fixed field = ivMaterial[0..3], + * invocation counter = BE64 of ivMaterial[4..11], incremented per packet; + * the initial counter comes from the KDF (not zero); bytes 12..15 of the + * 16-byte IV material are unused. + */ +export class GcmPacketCipher implements PacketCipher { + private encKey: Uint8Array; + private fixedIv: Uint8Array; + /** 8-byte big-endian invocation counter (byte-wise: full 64-bit range). */ + private invCounter: Uint8Array; + + constructor(encKey: Uint8Array, ivMaterial: Uint8Array, keyLen: number) { + if (keyLen !== 16 && keyLen !== 32) { + throw new Error(`GcmPacketCipher: unsupported key length ${keyLen}`); + } + if (encKey.length !== keyLen) { + throw new Error(`GcmPacketCipher: key must be ${keyLen} bytes, got ${encKey.length}`); + } + if (ivMaterial.length !== 16) { + throw new Error(`GcmPacketCipher: IV material must be 16 bytes, got ${ivMaterial.length}`); + } + this.encKey = encKey; + this.fixedIv = ivMaterial.slice(0, 4); + this.invCounter = ivMaterial.slice(4, 12); + } + + private nextIv(): Uint8Array { + const iv: Uint8Array = new Uint8Array(12); + iv.set(this.fixedIv, 0); + iv.set(this.invCounter, 4); + return iv; + } + + /** Increment the 64-bit big-endian invocation counter (with carry). */ + private advanceCounter(): void { + for (let i = 7; i >= 0; i--) { + this.invCounter[i] = (this.invCounter[i] + 1) & 0xff; + if (this.invCounter[i] !== 0) { + return; // no carry out of this byte + } + } + // Full 2^64 wrap: keep the all-zero value (unreachable in practice). + } + + encryptToPacket(payload: Uint8Array, seq: number): Uint8Array { + // seq ignored: this cipher owns its packet counter. + let padLen: number = AES_BLOCK - ((1 + payload.length) % AES_BLOCK); + if (padLen < 4) { + padLen += AES_BLOCK; + } + const packetLen: number = 1 + payload.length + padLen; // multiple of 16 + const pt: Uint8Array = new Uint8Array(packetLen); + pt[0] = padLen; + pt.set(payload, 1); + // Padding bytes are zero: RFC 4253 §6 allows any bytes (random is only + // a recommendation) and the sync hot path cannot await randomBytes. + const aad: Uint8Array = new Uint8Array(4); + writeBe32(aad, 0, packetLen); + const sealed: Uint8Array = CryptoAdapter.aesGcmEncryptSync(this.encKey, this.nextIv(), pt, aad); + const wire: Uint8Array = new Uint8Array(4 + sealed.length); + wire.set(aad, 0); // plaintext packet_length (RFC 5647 §7.3) + wire.set(sealed, 4); // CT || tag(16) + this.advanceCounter(); + return wire; + } + + async tryDecryptPacket(input: Uint8Array): Promise { + if (input.length < 4) { + return undefined; + } + const packetLen: number = be32(input, 0); + if (packetLen < AES_BLOCK || packetLen > MAX_PACKET_LEN || packetLen % AES_BLOCK !== 0) { + throw new Error(`GcmPacketCipher: illegal packet_length ${packetLen}`); + } + const total: number = 4 + packetLen + GCM_TAG_LEN; + if (input.length < total) { + return undefined; // wait for the rest of the packet + } + const sealed: Uint8Array = input.slice(4, total); // CT || tag + const aad: Uint8Array = input.slice(0, 4); + // Throws on authentication failure; the transport closes the link. + const pt: Uint8Array = CryptoAdapter.aesGcmDecryptSync(this.encKey, this.nextIv(), sealed, aad); + const padLen: number = pt[0]; + if (padLen < 4 || padLen >= pt.length) { + throw new Error(`GcmPacketCipher: illegal padding_length ${padLen}`); + } + const payload: Uint8Array = pt.slice(1, pt.length - padLen); + this.advanceCounter(); // advance only after a fully consumed packet + const out: DecodedPacket = { payload: payload, wireLength: total }; + return out; + } +} + +/** + * AES-CTR + HMAC (RFC 4253 §6; hmac-sha2-* per RFC 6668), in plain-MAC or + * encrypt-then-MAC wiring (*-etm@openssh.com). + * + * The 16-byte big-endian CTR counter state persists ACROSS packets + * (starts at the KDF IV); the MAC sequence (packetIndex) is a separate + * 0-based packet counter that also starts fresh after NEWKEYS. + * + * Plain MAC wire: E( BE32(len) || padLen || payload || pad ) || MAC + * MAC = HMAC(macKey, BE32(packetIndex) || unencrypted packet) [RFC 4253 §6.4] + * EtM wire: BE32(len) || E(padLen||payload||pad) || MAC + * MAC = HMAC(macKey, BE32(packetIndex) || BE32(len) || ciphertext), verified + * BEFORE decryption. + */ +export class CtrMacPacketCipher implements PacketCipher { + private encKey: Uint8Array; + private macKey: Uint8Array; + private macLen: number; + private etm: boolean; + /** 16-byte big-endian CTR block counter state (persists across packets). */ + private counter: Uint8Array; + private packetIndex: number = 0; + /** + * Decrypted first 16 bytes of the next inbound packet (plain-MAC mode). + * The trial-decrypted block MUST be cached: re-decrypting it would + * consume the same CTR keystream block twice and corrupt the stream. + */ + private cachedHead: Uint8Array | undefined = undefined; + + constructor(encKey: Uint8Array, iv16: Uint8Array, macKey: Uint8Array, + macLen: number, encryptThenMac: boolean) { + if (encKey.length !== 16 && encKey.length !== 24 && encKey.length !== 32) { + throw new Error(`CtrMacPacketCipher: bad AES key length ${encKey.length}`); + } + if (iv16.length !== 16) { + throw new Error('CtrMacPacketCipher: IV/counter must be 16 bytes'); + } + if (macLen !== 32 && macLen !== 64) { + throw new Error(`CtrMacPacketCipher: bad MAC length ${macLen}`); + } + if (macKey.length !== macLen) { + throw new Error(`CtrMacPacketCipher: MAC key must be ${macLen} bytes, got ${macKey.length}`); + } + this.encKey = encKey; + this.macKey = macKey; + this.macLen = macLen; + this.etm = encryptThenMac; + this.counter = iv16.slice(0); + this.packetIndex = 0; + this.cachedHead = undefined; + } + + encryptToPacket(payload: Uint8Array, seq: number): Uint8Array { + // seq ignored: this cipher owns the MAC sequence counter. + let padLen: number = AES_BLOCK - ((5 + payload.length) % AES_BLOCK); + if (padLen < 4) { + padLen += AES_BLOCK; + } + const packetLen: number = 1 + payload.length + padLen; // (4+len) % 16 == 0 + const wire: Uint8Array = new Uint8Array(4 + packetLen + this.macLen); + if (this.etm) { + const body: Uint8Array = new Uint8Array(packetLen); + body[0] = padLen; + body.set(payload, 1); + // padding zero (RFC 4253 §6: any bytes legal; random needs async) + const ct: Uint8Array = CryptoAdapter.aesCtrCryptSync(this.encKey, this.counter, body, + cryptoFramework.CryptoMode.ENCRYPT_MODE); + this.advanceCounter(CtrMacPacketCipher.blocksOf(packetLen)); + writeBe32(wire, 0, packetLen); + wire.set(ct, 4); + const macInput: Uint8Array = concatBytes(seqBytes(this.packetIndex), wire.slice(0, 4 + packetLen)); + wire.set(this.computeMac(macInput), 4 + packetLen); + } else { + const pt: Uint8Array = new Uint8Array(4 + packetLen); + writeBe32(pt, 0, packetLen); + pt[4] = padLen; + pt.set(payload, 5); + const ct: Uint8Array = CryptoAdapter.aesCtrCryptSync(this.encKey, this.counter, pt, + cryptoFramework.CryptoMode.ENCRYPT_MODE); + this.advanceCounter(CtrMacPacketCipher.blocksOf(4 + packetLen)); + wire.set(ct, 0); + const macInput: Uint8Array = concatBytes(seqBytes(this.packetIndex), pt); + wire.set(this.computeMac(macInput), 4 + packetLen); + } + this.packetIndex = (this.packetIndex + 1) % 4294967296; + return wire; + } + + async tryDecryptPacket(input: Uint8Array): Promise { + if (this.etm) { + return this.tryDecryptEtm(input); + } + return this.tryDecryptPlain(input); + } + + /** Inbound plain-MAC (MAC over the unencrypted packet, RFC 4253 §6.4). */ + private async tryDecryptPlain(input: Uint8Array): Promise { + // The first 16 ciphertext bytes always cover the length field. + if (input.length < AES_BLOCK) { + return undefined; + } + let head: Uint8Array; + if (this.cachedHead === undefined) { + // Trial-decrypt the first block with the CURRENT counter state, then + // cache it — the keystream block must never be consumed twice. + head = CryptoAdapter.aesCtrCryptSync(this.encKey, this.counter, input.slice(0, AES_BLOCK), + cryptoFramework.CryptoMode.DECRYPT_MODE); + this.cachedHead = head; + } else { + head = this.cachedHead; + } + const packetLen: number = be32(head, 0); + if (packetLen < 12 || packetLen > MAX_PACKET_LEN || (4 + packetLen) % AES_BLOCK !== 0) { + throw new Error(`CtrMacPacketCipher: illegal packet_length ${packetLen}`); + } + const total: number = 4 + packetLen + this.macLen; + if (input.length < total) { + return undefined; // keep the cached head for the next call + } + // The remainder starts at byte offset 16 = block boundary 1: decrypt it + // with the counter advanced by exactly one block from the current state. + const ivRem: Uint8Array = this.counter.slice(0); + ivRem[15] = (ivRem[15] + 1) & 0xff; + let carry: boolean = ivRem[15] === 0; + for (let i = 14; i >= 0 && carry; i--) { + ivRem[i] = (ivRem[i] + 1) & 0xff; + carry = ivRem[i] === 0; + } + const ctRem: Uint8Array = input.slice(AES_BLOCK, 4 + packetLen); + const ptRem: Uint8Array = CryptoAdapter.aesCtrCryptSync(this.encKey, ivRem, ctRem, + cryptoFramework.CryptoMode.DECRYPT_MODE); + // Reassemble the full unencrypted packet: cached head || remainder. + const pt: Uint8Array = new Uint8Array(4 + packetLen); + pt.set(head, 0); + pt.set(ptRem, AES_BLOCK); + const expect: Uint8Array = this.computeMac(concatBytes(seqBytes(this.packetIndex), pt)); + const got: Uint8Array = input.slice(4 + packetLen, total); + if (!bytesEqual(expect, got)) { + throw new Error('CtrMacPacketCipher: MAC mismatch'); + } + const padLen: number = pt[4]; + if (padLen < 4 || 1 + padLen > packetLen) { + throw new Error(`CtrMacPacketCipher: illegal padding_length ${padLen}`); + } + const payload: Uint8Array = pt.slice(5, 4 + packetLen - padLen); + this.advanceCounter(CtrMacPacketCipher.blocksOf(4 + packetLen)); + this.packetIndex = (this.packetIndex + 1) % 4294967296; + this.cachedHead = undefined; + const out: DecodedPacket = { payload: payload, wireLength: total }; + return out; + } + + /** Inbound encrypt-then-MAC: verify the MAC before touching the CT. */ + private async tryDecryptEtm(input: Uint8Array): Promise { + if (input.length < 4) { + return undefined; + } + const packetLen: number = be32(input, 0); // plaintext length field + if (packetLen < 12 || packetLen > MAX_PACKET_LEN || (4 + packetLen) % AES_BLOCK !== 0) { + throw new Error(`CtrMacPacketCipher: illegal packet_length ${packetLen}`); + } + const total: number = 4 + packetLen + this.macLen; + if (input.length < total) { + return undefined; + } + const ct: Uint8Array = input.slice(4, 4 + packetLen); + const macInput: Uint8Array = concatBytes(seqBytes(this.packetIndex), input.slice(0, 4 + packetLen)); + const expect: Uint8Array = this.computeMac(macInput); + const got: Uint8Array = input.slice(4 + packetLen, total); + if (!bytesEqual(expect, got)) { + throw new Error('CtrMacPacketCipher: MAC mismatch (etm)'); + } + const pt: Uint8Array = CryptoAdapter.aesCtrCryptSync(this.encKey, this.counter, ct, + cryptoFramework.CryptoMode.DECRYPT_MODE); + const padLen: number = pt[0]; + if (padLen < 4 || 1 + padLen > pt.length) { + throw new Error(`CtrMacPacketCipher: illegal padding_length ${padLen}`); + } + const payload: Uint8Array = pt.slice(1, pt.length - padLen); + this.advanceCounter(CtrMacPacketCipher.blocksOf(packetLen)); + this.packetIndex = (this.packetIndex + 1) % 4294967296; + const out: DecodedPacket = { payload: payload, wireLength: total }; + return out; + } + + private computeMac(input: Uint8Array): Uint8Array { + return this.macLen === 64 + ? CryptoAdapter.hmacSha512Sync(this.macKey, input) + : CryptoAdapter.hmacSha256Sync(this.macKey, input); + } + + /** Advance the 128-bit big-endian counter by `blocks` blocks (with carry). */ + private advanceCounter(blocks: number): void { + let carry: number = blocks; + for (let i = 15; i >= 0 && carry > 0; i--) { + const add: number = carry & 0xff; + carry = Math.floor(carry / 256); + const sum: number = this.counter[i] + add; + this.counter[i] = sum & 0xff; + carry += sum > 255 ? 1 : 0; + } + // Carry out of bit 127 wraps to zero (CTR semantics; unreachable). + } + + /** ceil(n / 16). */ + private static blocksOf(n: number): number { + return Math.ceil(n / AES_BLOCK); + } +} + +/** Negotiated cipher parameters (sizes in bytes), for T5's KDF sizing. */ +export interface CipherInfo { + /** Encryption key length. */ + keyLen: number; + /** IV material length taken from the KDF (GCM: 16, first 12 used). */ + ivLen: number; + /** MAC key length; 0 for AEAD and for CTR (see macInfo of the negotiated MAC). */ + macKeyLen: number; + /** Cipher block size (padding alignment). */ + blockSize: number; + /** Minimum padding (RFC 4253 §6 mandates >= 4). */ + minPadding: number; + /** AEAD cipher: the effective MAC is "implicit none". */ + aead: boolean; + /** Encrypt-then-MAC wiring; actually a property of the negotiated MAC. */ + etm: boolean; +} + +/** Negotiated MAC parameters (RFC 6668 / OpenSSH etm extension). */ +export interface MacInfo { + /** MAC key length. */ + keyLen: number; + /** MAC tag length on the wire. */ + tagLen: number; + /** Whether this MAC variant is the encrypt-then-MAC wiring. */ + etm: boolean; +} + +/** + * Parameter table for the cipher names proposed in SshAlgoLists.CIPHER. + * For non-AEAD ciphers the MAC key/tag sizes come from macInfo() of the + * negotiated MAC algorithm. + */ +export function cipherInfo(name: string): CipherInfo { + if (name === 'aes128-gcm@openssh.com') { + const info: CipherInfo = { keyLen: 16, ivLen: 16, macKeyLen: 0, blockSize: 16, minPadding: 4, aead: true, etm: false }; + return info; + } + if (name === 'aes256-gcm@openssh.com') { + const info: CipherInfo = { keyLen: 32, ivLen: 16, macKeyLen: 0, blockSize: 16, minPadding: 4, aead: true, etm: false }; + return info; + } + if (name === 'aes128-ctr') { + const info: CipherInfo = { keyLen: 16, ivLen: 16, macKeyLen: 0, blockSize: 16, minPadding: 4, aead: false, etm: false }; + return info; + } + if (name === 'aes192-ctr') { + const info: CipherInfo = { keyLen: 24, ivLen: 16, macKeyLen: 0, blockSize: 16, minPadding: 4, aead: false, etm: false }; + return info; + } + if (name === 'aes256-ctr') { + const info: CipherInfo = { keyLen: 32, ivLen: 16, macKeyLen: 0, blockSize: 16, minPadding: 4, aead: false, etm: false }; + return info; + } + throw new Error(`Ciphers: unknown cipher '${name}'`); +} + +/** Parameter table for the MAC names proposed in SshAlgoLists.MAC. */ +export function macInfo(name: string): MacInfo { + if (name === 'hmac-sha2-256-etm@openssh.com') { + const info: MacInfo = { keyLen: 32, tagLen: 32, etm: true }; + return info; + } + if (name === 'hmac-sha2-512-etm@openssh.com') { + const info: MacInfo = { keyLen: 64, tagLen: 64, etm: true }; + return info; + } + if (name === 'hmac-sha2-256') { + const info: MacInfo = { keyLen: 32, tagLen: 32, etm: false }; + return info; + } + if (name === 'hmac-sha2-512') { + const info: MacInfo = { keyLen: 64, tagLen: 64, etm: false }; + return info; + } + throw new Error(`Ciphers: unknown MAC '${name}'`); +} + +// ------------------------------------------------------------ byte helpers + +function be32(b: Uint8Array, off: number): number { + return ((b[off] * 256 + b[off + 1]) * 256 + b[off + 2]) * 256 + b[off + 3]; +} + +function writeBe32(b: Uint8Array, off: number, v: number): void { + b[off] = (v >>> 24) & 0xff; + b[off + 1] = (v >>> 16) & 0xff; + b[off + 2] = (v >>> 8) & 0xff; + b[off + 3] = v & 0xff; +} + +/** BE32 of the MAC sequence number (RFC 4253 §6.4). */ +function seqBytes(seq: number): Uint8Array { + const out: Uint8Array = new Uint8Array(4); + writeBe32(out, 0, seq); + return out; +} diff --git a/entry/src/main/ets/ssh/PacketCodec.ts b/entry/src/main/ets/ssh/PacketCodec.ts index aa81589..ac01527 100644 --- a/entry/src/main/ets/ssh/PacketCodec.ts +++ b/entry/src/main/ets/ssh/PacketCodec.ts @@ -23,20 +23,26 @@ export interface DecodedPacket { /** * Encrypt/decrypt context installed after NEWKEYS (RFC 4253 §7.3). * - * Implementations own their sequence counter for inbound packets: the counter - * starts at 0 for a fresh context and increments per decoded packet. Since a - * NEWKEYS switch always installs a brand-new context, sequence numbers are - * implicitly reset (RFC 4253 §6.4), satisfying strict-kex as well. + * Implementations own their packet counters: a fresh instance starts + * counting from 0 right after NEWKEYS (so sequence numbers are implicitly + * reset per RFC 4253 §6.4, satisfying strict-kex as well). The `seq` + * parameter passed to encryptToPacket is the transport's outbound counter + * and MUST be ignored by implementations — they use their own. * - * GCM notes for the T4 implementation (RFC 5647): - * - wire form: E(4-byte packet_length) || E(padding_length||payload||padding) || tag(16) - * - IV = fixedIV(4 bytes from key derivation) || seq(8 bytes big endian) - * - the second GCM call uses AAD = the 4 encrypted length bytes - * - to peek the length before the full packet arrives, decrypt the first - * 4 bytes as AES-CTR with IV16 = fixedIV || seq || 0x00000001 (the GCM - * keystream for the length field starts at counter J0+1) - * - OpenHarmony GCM: doFinal(encrypt) output = ciphertext || 16-byte tag; + * GCM wire form (aes*-gcm@openssh.com, RFC 5647; impl: ssh/Ciphers.ts): + * - wire = BE32(packet_length) [PLAINTEXT] || CT || tag(16); the length + * is authenticated as AAD, not encrypted (RFC 5647 §7.3) + * - the encrypted portion (padding_length||payload||padding) is + * packet_length bytes and a multiple of 16 (RFC 5647 §7.2) + * - IV = fixed(4 bytes, KDF IV material[0..3]) || + * BE64(invocation counter) where the counter starts at the KDF IV + * material bytes 4..11 and increments once per packet (RFC 5647 §7.1; + * 16-byte IV material, last 4 bytes unused — JSch-compatible) + * - OpenHarmony GCM: encrypt doFinal() output = ciphertext || 16-byte tag; * on decrypt the tag must be split off and passed via GcmParamsSpec.authTag. + * + * CTR + MAC wire forms (RFC 4253 §6, RFC 6668) are documented on + * CtrMacPacketCipher in ssh/Ciphers.ts. */ export interface PacketCipher { /** Turn a payload into a complete encrypted wire packet. */ diff --git a/entry/src/main/ets/ssh/crypto/CryptoAdapter.ts b/entry/src/main/ets/ssh/crypto/CryptoAdapter.ts index 951ffbe..7557bed 100644 --- a/entry/src/main/ets/ssh/crypto/CryptoAdapter.ts +++ b/entry/src/main/ets/ssh/crypto/CryptoAdapter.ts @@ -8,7 +8,7 @@ */ import { cryptoFramework } from '@kit.CryptoArchitectureKit'; -import { hexToBytes, concatBytes } from '../SshWire'; +import { hexToBytes, concatBytes, utf8ToBytes } from '../SshWire'; /** Raw key material pair: semantics depend on the algorithm. */ export interface RawKeyPair { @@ -300,6 +300,241 @@ export class CryptoAdapter { return ok; } + // ------------------------------------------------- sync hot-path surface + // PacketCipher implementations must stay synchronous (PacketCodec hot + // path), so these mirror the async wrappers on the cryptoFramework *Sync + // APIs (verified present in @ohos.security.cryptoFramework). + + static sha256Sync(data: Uint8Array): Uint8Array { + const md: cryptoFramework.Md = cryptoFramework.createMd('SHA256'); + md.updateSync({ data: data }); + return md.digestSync().data; + } + + static sha512Sync(data: Uint8Array): Uint8Array { + const md: cryptoFramework.Md = cryptoFramework.createMd('SHA512'); + md.updateSync({ data: data }); + return md.digestSync().data; + } + + private static hmacSync(mdAlg: string, key: Uint8Array, data: Uint8Array): Uint8Array { + const keyGen: cryptoFramework.SymKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC'); + const symKey: cryptoFramework.SymKey = keyGen.convertKeySync({ data: key }); + const mac: cryptoFramework.Mac = cryptoFramework.createMac(mdAlg); + mac.initSync(symKey); + mac.updateSync({ data: data }); + return mac.doFinalSync().data; + } + + static hmacSha256Sync(key: Uint8Array, data: Uint8Array): Uint8Array { + return CryptoAdapter.hmacSync('SHA256', key, data); + } + + static hmacSha512Sync(key: Uint8Array, data: Uint8Array): Uint8Array { + return CryptoAdapter.hmacSync('SHA512', key, data); + } + + /** Sync GCM encrypt; output = ciphertext || tag(16) (SSH semantics). */ + static aesGcmEncryptSync(key: Uint8Array, iv: Uint8Array, plain: Uint8Array, + aad: Uint8Array): Uint8Array { + const alg: string = CryptoAdapter.aesAlgName(key.length); + const keyGen: cryptoFramework.SymKeyGenerator = cryptoFramework.createSymKeyGenerator(alg); + const symKey: cryptoFramework.SymKey = keyGen.convertKeySync({ data: key }); + const cipher: cryptoFramework.Cipher = cryptoFramework.createCipher(`${alg}|GCM|NoPadding`); + // authTag is an output on encryption; an empty blob is accepted here. + const params: cryptoFramework.GcmParamsSpec = { + algName: 'GcmParamsSpec', + iv: { data: iv }, + aad: { data: aad }, + authTag: { data: new Uint8Array(0) } + }; + cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, params); + return cipher.doFinalSync({ data: plain }).data; // ciphertext || tag(16) + } + + /** Sync GCM decrypt of ciphertext||tag(16); throws on auth failure. */ + static aesGcmDecryptSync(key: Uint8Array, iv: Uint8Array, sealed: Uint8Array, + aad: Uint8Array): Uint8Array { + if (sealed.length < CryptoAdapter.GCM_TAG_LEN) { + throw new Error('CryptoAdapter: GCM input shorter than tag'); + } + const alg: string = CryptoAdapter.aesAlgName(key.length); + const keyGen: cryptoFramework.SymKeyGenerator = cryptoFramework.createSymKeyGenerator(alg); + const symKey: cryptoFramework.SymKey = keyGen.convertKeySync({ data: key }); + const cipher: cryptoFramework.Cipher = cryptoFramework.createCipher(`${alg}|GCM|NoPadding`); + const tag: Uint8Array = sealed.slice(sealed.length - CryptoAdapter.GCM_TAG_LEN); + const body: Uint8Array = sealed.slice(0, sealed.length - CryptoAdapter.GCM_TAG_LEN); + const params: cryptoFramework.GcmParamsSpec = { + algName: 'GcmParamsSpec', + iv: { data: iv }, + aad: { data: aad }, + authTag: { data: tag } + }; + cipher.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, params); + return cipher.doFinalSync({ data: body }).data; + } + + /** + * Sync AES-CTR. CTR is a stream mode: any length is legal with NoPadding. + * The FULL 16-byte counter block is passed as the IV; advancing the + * counter across packets is the caller's job (RFC 4253 §6 semantics, the + * counter is explicitly allowed to persist between packets). + */ + static aesCtrCryptSync(key: Uint8Array, iv16: Uint8Array, data: Uint8Array, + mode: cryptoFramework.CryptoMode): Uint8Array { + if (iv16.length !== 16) { + throw new Error(`CryptoAdapter: CTR IV must be 16 bytes, got ${iv16.length}`); + } + const alg: string = CryptoAdapter.aesAlgName(key.length); + const keyGen: cryptoFramework.SymKeyGenerator = cryptoFramework.createSymKeyGenerator(alg); + const symKey: cryptoFramework.SymKey = keyGen.convertKeySync({ data: key }); + const cipher: cryptoFramework.Cipher = cryptoFramework.createCipher(`${alg}|CTR|NoPadding`); + const params: cryptoFramework.IvParamsSpec = { + algName: 'IvParamsSpec', + iv: { data: iv16 } + }; + cipher.initSync(mode, symKey, params); + if (data.length === 0) { + return new Uint8Array(0); + } + const mid: cryptoFramework.DataBlob = cipher.updateSync({ data: data }); + const tail: cryptoFramework.DataBlob = cipher.doFinalSync(null); + return concatBytes(mid.data, tail.data); + } + + /** Sync RSA PKCS#1 v1.5 sign; hash: 'SHA1' | 'SHA256' | 'SHA512'. */ + static rsaSignPkcs1Sync(priDer: Uint8Array, data: Uint8Array, hash: string): Uint8Array { + const bits: number = CryptoAdapter.rsaBitsFromDer(priDer); + const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator(`RSA${bits}`); + const kp: cryptoFramework.KeyPair = gen.convertKeySync(null, { data: priDer }); + const signer: cryptoFramework.Sign = cryptoFramework.createSign(`RSA${bits}|PKCS1|${hash}`); + signer.initSync(kp.priKey); + return signer.signSync({ data: data }).data; + } + + /** Sync RSA PKCS#1 v1.5 verify; hash: 'SHA1' | 'SHA256' | 'SHA512'. */ + static rsaVerifyPkcs1Sync(pubDer: Uint8Array, data: Uint8Array, sig: Uint8Array, + hash: string): boolean { + const bits: number = CryptoAdapter.rsaBitsFromDer(pubDer); + const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator(`RSA${bits}`); + const kp: cryptoFramework.KeyPair = gen.convertKeySync({ data: pubDer }, null); + const verifier: cryptoFramework.Verify = cryptoFramework.createVerify(`RSA${bits}|PKCS1|${hash}`); + verifier.initSync(kp.pubKey); + return verifier.verifySync({ data: data }, { data: sig }); + } + + /** Sync RSA key generation (full DER blobs, same shape as the async one). */ + static rsaGenerateKeyPairSync(bits: number): RawKeyPair { + let alg: string = ''; + if (bits === 2048) { + alg = 'RSA2048'; + } else if (bits === 3072) { + alg = 'RSA3072'; + } else if (bits === 4096) { + alg = 'RSA4096'; + } else { + throw new Error(`CryptoAdapter: unsupported RSA bits ${bits}`); + } + const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator(alg); + const kp: cryptoFramework.KeyPair = gen.generateKeyPairSync(); + const pair: RawKeyPair = { + pri: kp.priKey.getEncoded().data, + pub: kp.pubKey.getEncoded().data + }; + return pair; + } + + /** Sync Ed25519 verify (raw 32-byte key, raw 64-byte signature). */ + static ed25519VerifySync(pubRaw: Uint8Array, data: Uint8Array, sig: Uint8Array): boolean { + const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('Ed25519'); + const pubBlob: cryptoFramework.DataBlob = { data: CryptoAdapter.wrapSpki(pubRaw, DerPrefix.ED25519_SPKI) }; + const kp: cryptoFramework.KeyPair = gen.convertKeySync(pubBlob, null); + const verifier: cryptoFramework.Verify = cryptoFramework.createVerify('Ed25519'); + verifier.initSync(kp.pubKey); + return verifier.verifySync({ data: data }, { data: sig }); + } + + /** Sync P-256 key pair (pri = 32-byte scalar, pub = 04||X||Y). */ + static ecdsaP256GenerateKeyPairSync(): RawKeyPair { + const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); + const kp: cryptoFramework.KeyPair = gen.generateKeyPairSync(); + const priDer: Uint8Array = kp.priKey.getEncoded().data; + const pubDer: Uint8Array = kp.pubKey.getEncoded().data; + const point: Uint8Array = CryptoAdapter.unwrapSpki(pubDer, DerPrefix.P256_SPKI); + if (point.length !== 65 || point[0] !== 0x04) { + throw new Error(`CryptoAdapter: unexpected P-256 public point length ${point.length}`); + } + const pair: RawKeyPair = { + pri: CryptoAdapter.extractP256Scalar(priDer), + pub: point + }; + return pair; + } + + /** + * Sync ECDSA-P256 sign with the raw 32-byte scalar; returns the + * signature (expected DER SEQUENCE(r,s) — consumers use the defensive + * DerUtils.ecdsaPartsFromDer). + */ + static ecdsaP256SignSync(scalar: Uint8Array, data: Uint8Array): Uint8Array { + const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); + const priBlob: cryptoFramework.DataBlob = { data: CryptoAdapter.buildP256Pkcs8(scalar) }; + const kp: cryptoFramework.KeyPair = gen.convertKeySync(null, priBlob); + const signer: cryptoFramework.Sign = cryptoFramework.createSign('ECC256|SHA256'); + signer.initSync(kp.priKey); + return signer.signSync({ data: data }).data; + } + + /** Sync ECDSA-P256 verify (65-byte point, DER signature). */ + static ecdsaP256VerifySync(point65: Uint8Array, data: Uint8Array, derSig: Uint8Array): boolean { + if (point65.length !== 65 || point65[0] !== 0x04) { + throw new Error('CryptoAdapter: P-256 public key must be 04||X||Y (65 bytes)'); + } + const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); + const pubBlob: cryptoFramework.DataBlob = { data: concatBytes(DerPrefix.P256_SPKI, point65) }; + const kp: cryptoFramework.KeyPair = gen.convertKeySync(pubBlob, null); + const verifier: cryptoFramework.Verify = cryptoFramework.createVerify('ECC256|SHA256'); + verifier.initSync(kp.pubKey); + return verifier.verifySync({ data: data }, { data: derSig }); + } + + /** + * Key expansion per RFC 4253 §7.2: + * K1 = HASH(K || H || letter || session_id) + * Kn = HASH(K || H || K_{n-1}) for n >= 2 + * output = K1||...||Kn truncated to `need` bytes. + * @param hashAlg 'SHA256' | 'SHA512' (the KEX hash) + * @param k normalized mpint bytes of the shared secret K + */ + static expandKey(hashAlg: string, k: Uint8Array, h: Uint8Array, letter: string, + sessionId: Uint8Array, need: number): Uint8Array { + if (hashAlg !== 'SHA256' && hashAlg !== 'SHA512') { + throw new Error(`CryptoAdapter: expandKey unsupported hash '${hashAlg}'`); + } + if (need <= 0) { + throw new Error(`CryptoAdapter: expandKey need=${need}`); + } + const out: Uint8Array = new Uint8Array(need); + let filled: number = 0; + let prev: Uint8Array = new Uint8Array(0); + let first: boolean = true; + while (filled < need) { + const kh: Uint8Array = concatBytes(k, h); + const input: Uint8Array = first + ? concatBytes(concatBytes(kh, utf8ToBytes(letter)), sessionId) + : concatBytes(kh, prev); + const block: Uint8Array = hashAlg === 'SHA512' + ? CryptoAdapter.sha512Sync(input) + : CryptoAdapter.sha256Sync(input); + const take: number = need - filled < block.length ? need - filled : block.length; + out.set(block.subarray(0, take), filled); + filled += take; + prev = block; + first = false; + } + return out; + } + // ------------------------------------------------------------- DER helpers private static wrapSpki(raw: Uint8Array, prefix: Uint8Array): Uint8Array { diff --git a/entry/src/main/ets/ssh/crypto/DerUtils.ts b/entry/src/main/ets/ssh/crypto/DerUtils.ts new file mode 100644 index 0000000..cfd5325 --- /dev/null +++ b/entry/src/main/ets/ssh/crypto/DerUtils.ts @@ -0,0 +1,361 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + */ + +/** + * Byte-level DER helpers (X.690 subset): INTEGER / SEQUENCE / BIT STRING + * building and parsing for RSA SPKI & PKCS#8 (RFC 8017 App. A) and ECDSA + * signature conversion (RFC 5480 / SEC 1 §2.2.3). BigInt is used ONLY in + * this file, for the RSA CRT parameter math (modPowCrtParams); everything + * else is plain byte arithmetic per the project coding standard. + */ + +import { normalizeMagnitude, hexToBytes, concatBytes } from '../SshWire'; +import { SshWriter } from '../SshWire'; + +/** One parsed TLV element. */ +export interface DerTlv { + tag: number; + content: Uint8Array; + /** Offset just past this element, relative to the buffer passed in. */ + nextOffset: number; +} + +/** Result of reading one DER INTEGER. */ +export interface DerIntegerResult { + /** Unsigned magnitude (leading sign byte stripped). */ + magnitude: Uint8Array; + nextOffset: number; +} + +/** RSA public key parts (exponent, modulus). */ +export interface RsaPublicKeyParts { + e: Uint8Array; + n: Uint8Array; +} + +/** RSA CRT parameters needed by the PKCS#8 RSAPrivateKey structure. */ +export interface RsaCrtParams { + /** d mod (p-1) */ + dp: Uint8Array; + /** d mod (q-1) */ + dq: Uint8Array; + /** q^-1 mod p */ + iqmp: Uint8Array; +} + +/** ECDSA signature components as unsigned magnitudes. */ +export interface EcdsaParts { + r: Uint8Array; + s: Uint8Array; +} + +export class DerUtils { + /** OID rsaEncryption 1.2.840.113549.1.1.1 (RFC 8017 §9.2), DER encoded. */ + private static readonly RSA_OID: Uint8Array = hexToBytes('06092a864886f70d010101'); + /** DER NULL (algorithm parameters). */ + private static readonly DER_NULL: Uint8Array = hexToBytes('0500'); + /** DER INTEGER 0 (PKCS#8 / RSAPrivateKey version). */ + private static readonly DER_INT_ZERO: Uint8Array = hexToBytes('020100'); + + // --------------------------------------------------------------- building + + /** DER length octets for content of n bytes. */ + static derLen(n: number): Uint8Array { + if (n < 0x80) { + const short: Uint8Array = new Uint8Array(1); + short[0] = n; + return short; + } + if (n < 0x100) { + const mid: Uint8Array = new Uint8Array(2); + mid[0] = 0x81; + mid[1] = n; + return mid; + } + if (n < 0x10000) { + const long: Uint8Array = new Uint8Array(3); + long[0] = 0x82; + long[1] = (n >>> 8) & 0xff; + long[2] = n & 0xff; + return long; + } + throw new Error(`DerUtils: unsupported DER length ${n}`); + } + + /** TLV builder: tag + length octets + content. */ + static tlv(tag: number, content: Uint8Array): Uint8Array { + const len: Uint8Array = DerUtils.derLen(content.length); + const out: Uint8Array = new Uint8Array(1 + len.length + content.length); + out[0] = tag & 0xff; + out.set(len, 1); + out.set(content, 1 + len.length); + return out; + } + + /** Minimal two's-complement INTEGER content from an unsigned magnitude. */ + static integerContent(mag: Uint8Array): Uint8Array { + const m: Uint8Array = normalizeMagnitude(mag); + if (m.length === 1 && m[0] === 0) { + const zero: Uint8Array = new Uint8Array(1); + zero[0] = 0x00; + return zero; + } + if (m[0] >= 0x80) { + const padded: Uint8Array = new Uint8Array(m.length + 1); + padded[0] = 0x00; + padded.set(m, 1); + return padded; + } + return m.slice(); + } + + /** DER INTEGER (tag 0x02) from an unsigned magnitude. */ + static derInteger(mag: Uint8Array): Uint8Array { + return DerUtils.tlv(0x02, DerUtils.integerContent(mag)); + } + + /** SEQUENCE (tag 0x30) wrap. */ + static derSequence(content: Uint8Array): Uint8Array { + return DerUtils.tlv(0x30, content); + } + + /** SSH mpint wire encoding (RFC 4251 §5) of an unsigned magnitude. */ + static sshMpiFromMag(mag: Uint8Array): Uint8Array { + const w: SshWriter = new SshWriter(mag.length + 8); + w.writeMpint(mag); + return w.toBytes(); + } + + // --------------------------------------------------------------- parsing + + /** Read one TLV element at offset; throws on malformed input. */ + static readTlv(buf: Uint8Array, offset: number): DerTlv { + if (offset < 0 || offset + 2 > buf.length) { + throw new Error('DerUtils: truncated TLV header'); + } + const tag: number = buf[offset]; + const lenByte: number = buf[offset + 1]; + let len: number = 0; + let headerLen: number = 2; + if (lenByte < 0x80) { + len = lenByte; + } else if (lenByte === 0x81) { + if (offset + 3 > buf.length) { + throw new Error('DerUtils: truncated long-form length'); + } + len = buf[offset + 2]; + headerLen = 3; + } else if (lenByte === 0x82) { + if (offset + 4 > buf.length) { + throw new Error('DerUtils: truncated long-form length'); + } + len = buf[offset + 2] * 256 + buf[offset + 3]; + headerLen = 4; + } else { + throw new Error(`DerUtils: unsupported length form 0x${lenByte.toString(16)}`); + } + if (offset + headerLen + len > buf.length) { + throw new Error('DerUtils: TLV content exceeds buffer'); + } + const result: DerTlv = { + tag: tag, + content: buf.slice(offset + headerLen, offset + headerLen + len), + nextOffset: offset + headerLen + len + }; + return result; + } + + /** Read a DER INTEGER at offset; returns its unsigned magnitude. */ + static derIntegerRead(buf: Uint8Array, offset: number): DerIntegerResult { + const tlv: DerTlv = DerUtils.readTlv(buf, offset); + if (tlv.tag !== 0x02) { + throw new Error(`DerUtils: expected INTEGER, got tag 0x${tlv.tag.toString(16)}`); + } + let mag: Uint8Array = tlv.content; + if (mag.length > 1 && mag[0] === 0x00) { + mag = mag.slice(1); + } + const result: DerIntegerResult = { magnitude: mag, nextOffset: tlv.nextOffset }; + return result; + } + + // ------------------------------------------------------------------- RSA + + /** + * SubjectPublicKeyInfo for an RSA public key (RFC 8017 App. A.1): + * SEQUENCE{ SEQUENCE{ OID rsaEncryption, NULL }, + * BIT STRING( 0x00 || SEQUENCE{ INTEGER n, INTEGER e } ) } + */ + static buildRsaSpki(e: Uint8Array, n: Uint8Array): Uint8Array { + const algId: Uint8Array = DerUtils.derSequence(concatBytes(DerUtils.RSA_OID, DerUtils.DER_NULL)); + const rsaPub: Uint8Array = DerUtils.derSequence( + concatBytes(DerUtils.derInteger(n), DerUtils.derInteger(e))); + const unusedBits: Uint8Array = new Uint8Array(1); // 0x00: no unused bits + const bitString: Uint8Array = DerUtils.tlv(0x03, concatBytes(unusedBits, rsaPub)); + return DerUtils.derSequence(concatBytes(algId, bitString)); + } + + /** Parse an RSA SubjectPublicKeyInfo back into (e, n). Tolerates DER quirks. */ + static parseRsaSpki(der: Uint8Array): RsaPublicKeyParts { + const outer: DerTlv = DerUtils.readTlv(der, 0); + if (outer.tag !== 0x30) { + throw new Error('DerUtils: RSA SPKI must be a SEQUENCE'); + } + const algId: DerTlv = DerUtils.readTlv(outer.content, 0); + if (algId.tag !== 0x30) { + throw new Error('DerUtils: RSA SPKI AlgorithmIdentifier must be a SEQUENCE'); + } + const bitStr: DerTlv = DerUtils.readTlv(outer.content, algId.nextOffset); + if (bitStr.tag !== 0x03) { + throw new Error('DerUtils: RSA SPKI subjectPublicKey must be a BIT STRING'); + } + let inner: Uint8Array = bitStr.content; + if (inner.length > 0 && inner[0] === 0x00) { + inner = inner.slice(1); // strip the unused-bits octet + } + const seq: DerTlv = DerUtils.readTlv(inner, 0); + if (seq.tag !== 0x30) { + throw new Error('DerUtils: RSAPublicKey must be a SEQUENCE'); + } + const nRes: DerIntegerResult = DerUtils.derIntegerRead(seq.content, 0); + const eRes: DerIntegerResult = DerUtils.derIntegerRead(seq.content, nRes.nextOffset); + const parts: RsaPublicKeyParts = { e: eRes.magnitude, n: nRes.magnitude }; + return parts; + } + + /** + * PKCS#8 PrivateKeyInfo wrapping a full 9-INTEGER RSAPrivateKey + * (RFC 8017 App. A.1). `dp`/`dq`/`iqmp` come from modPowCrtParams when + * the source format does not carry them. + */ + static buildRsaPkcs8(n: Uint8Array, e: Uint8Array, d: Uint8Array, p: Uint8Array, q: Uint8Array, + dp: Uint8Array, dq: Uint8Array, iqmp: Uint8Array): Uint8Array { + const rsaPriv: Uint8Array = DerUtils.derSequence(DerUtils.concatAll([ + DerUtils.DER_INT_ZERO, + DerUtils.derInteger(n), + DerUtils.derInteger(e), + DerUtils.derInteger(d), + DerUtils.derInteger(p), + DerUtils.derInteger(q), + DerUtils.derInteger(dp), + DerUtils.derInteger(dq), + DerUtils.derInteger(iqmp) + ])); + const algId: Uint8Array = DerUtils.derSequence(concatBytes(DerUtils.RSA_OID, DerUtils.DER_NULL)); + const octetString: Uint8Array = DerUtils.tlv(0x04, rsaPriv); + return DerUtils.derSequence(DerUtils.concatAll([DerUtils.DER_INT_ZERO, algId, octetString])); + } + + /** + * CRT parameters for RSA private key import (the only BigInt site in the + * project): dp = d mod (p-1), dq = d mod (q-1), iqmp = q^-1 mod p via + * extended Euclid (RFC 8017 §3.2 uses the same definitions). + */ + static modPowCrtParams(d: Uint8Array, p: Uint8Array, q: Uint8Array): RsaCrtParams { + const dBig: bigint = DerUtils.bigFromBytes(d); + const pBig: bigint = DerUtils.bigFromBytes(p); + const qBig: bigint = DerUtils.bigFromBytes(q); + const params: RsaCrtParams = { + dp: DerUtils.bigToBytes(dBig % (pBig - BigInt(1))), + dq: DerUtils.bigToBytes(dBig % (qBig - BigInt(1))), + iqmp: DerUtils.bigToBytes(DerUtils.modInverse(qBig, pBig)) + }; + return params; + } + + // ----------------------------------------------------------------- ECDSA + + /** SEQUENCE{ INTEGER r, INTEGER s } with sign normalization (SEC 1 §2.2.3). */ + static ecdsaDerFromParts(r: Uint8Array, s: Uint8Array): Uint8Array { + return DerUtils.derSequence(concatBytes(DerUtils.derInteger(r), DerUtils.derInteger(s))); + } + + /** + * Parse an ECDSA signature into (r, s) magnitudes. Defensive per the T4 + * spec: if the buffer is exactly 64 bytes and does not parse as DER, it is + * treated as a raw r||s pair. + */ + static ecdsaPartsFromDer(der: Uint8Array): EcdsaParts { + let parts: EcdsaParts | undefined = undefined; + if (der.length > 0 && der[0] === 0x30) { + try { + const seq: DerTlv = DerUtils.readTlv(der, 0); + const rRes: DerIntegerResult = DerUtils.derIntegerRead(seq.content, 0); + const sRes: DerIntegerResult = DerUtils.derIntegerRead(seq.content, rRes.nextOffset); + const parsed: EcdsaParts = { r: rRes.magnitude, s: sRes.magnitude }; + parts = parsed; + } catch (e) { + parts = undefined; // fall through to the raw r||s reading + } + } + if (parts === undefined && der.length === 64) { + const raw: EcdsaParts = { r: der.slice(0, 32), s: der.slice(32, 64) }; + parts = raw; + } + if (parts === undefined) { + throw new Error('DerUtils: malformed ECDSA signature (neither DER nor raw r||s)'); + } + return parts; + } + + // -------------------------------------------------------------- internal + + private static concatAll(parts: Uint8Array[]): Uint8Array { + let total: number = 0; + for (let i = 0; i < parts.length; i++) { + total += parts[i].length; + } + const out: Uint8Array = new Uint8Array(total); + let off: number = 0; + for (let i = 0; i < parts.length; i++) { + out.set(parts[i], off); + off += parts[i].length; + } + return out; + } + + private static bigFromBytes(b: Uint8Array): bigint { + let v: bigint = BigInt(0); + for (let i = 0; i < b.length; i++) { + v = (v << BigInt(8)) | BigInt(b[i]); + } + return v; + } + + /** Minimal unsigned magnitude bytes for a non-negative bigint. */ + private static bigToBytes(v: bigint): Uint8Array { + if (v <= BigInt(0)) { + const zero: Uint8Array = new Uint8Array(1); + zero[0] = 0x00; + return zero; + } + let hex: string = v.toString(16); + if (hex.length % 2 !== 0) { + hex = '0' + hex; + } + return hexToBytes(hex); + } + + /** Modular inverse of a modulo m (extended Euclid); m > 1. */ + private static modInverse(a: bigint, m: bigint): bigint { + let oldR: bigint = ((a % m) + m) % m; + let r: bigint = m; + let oldS: bigint = BigInt(1); + let s: bigint = BigInt(0); + while (r !== BigInt(0)) { + const q: bigint = oldR / r; + const nextR: bigint = oldR - q * r; + oldR = r; + r = nextR; + const nextS: bigint = oldS - q * s; + oldS = s; + s = nextS; + } + if (oldR !== BigInt(1)) { + throw new Error('DerUtils: modular inverse does not exist'); + } + return ((oldS % m) + m) % m; + } +} diff --git a/entry/src/main/ets/ssh/crypto/KeyImport.ts b/entry/src/main/ets/ssh/crypto/KeyImport.ts new file mode 100644 index 0000000..e843237 --- /dev/null +++ b/entry/src/main/ets/ssh/crypto/KeyImport.ts @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + */ + +/** + * SSH public key blob parsing/building (RFC 4253 §6.6; Ed25519 RFC 8709, + * ECDSA RFC 5656 §3.1, RSA RFC 4253 §6.6) and host key signature + * verification for every host key algorithm we propose (RSA hash variants + * per RFC 8332 §3). All crypto goes through CryptoAdapter's sync API so + * the KEX hot path stays synchronous. + */ + +import { SshReader, SshWriter, bytesToBase64 } from '../SshWire'; +import { DerUtils, EcdsaParts } from './DerUtils'; +import { CryptoAdapter } from './CryptoAdapter'; + +/** Parsed contents of an SSH public key blob. */ +export interface PublicKeyMaterial { + /** Blob-internal name: ssh-ed25519 | ecdsa-sha2-nistp256 | ssh-rsa. */ + algo: string; + /** Ed25519: raw 32-byte public key. */ + ed25519Pub?: Uint8Array; + /** ECDSA P-256: uncompressed point 04||X||Y (65 bytes). */ + ecPoint?: Uint8Array; + /** RSA public exponent (magnitude). */ + rsaE?: Uint8Array; + /** RSA modulus (magnitude). */ + rsaN?: Uint8Array; +} + +/** + * Parse an SSH public key blob (RFC 4253 §6.6). For rsa-sha2-256/512 the + * blob-internal name is always "ssh-rsa" (RFC 8332 §3). + */ +export function parsePublicKeyBlob(blob: Uint8Array): PublicKeyMaterial { + const r: SshReader = new SshReader(blob); + const algo: string = r.readString(); + if (algo === 'ssh-ed25519') { + const pub: Uint8Array = r.readStringBytes(); + if (pub.length !== 32) { + throw new Error(`KeyImport: ed25519 public key must be 32 bytes, got ${pub.length}`); + } + const mat: PublicKeyMaterial = { algo: algo, ed25519Pub: pub }; + return mat; + } + if (algo === 'ecdsa-sha2-nistp256') { + const curveName: string = r.readString(); + if (curveName !== 'nistp256') { + throw new Error(`KeyImport: unexpected ECDSA curve '${curveName}'`); + } + const point: Uint8Array = r.readStringBytes(); + if (point.length !== 65 || point[0] !== 0x04) { + throw new Error('KeyImport: P-256 public key must be 04||X||Y (65 bytes)'); + } + const mat: PublicKeyMaterial = { algo: algo, ecPoint: point }; + return mat; + } + if (algo === 'ssh-rsa') { + const e: Uint8Array = r.readMpint(); + const n: Uint8Array = r.readMpint(); + const mat: PublicKeyMaterial = { algo: algo, rsaE: e, rsaN: n }; + return mat; + } + throw new Error(`KeyImport: unsupported public key algorithm '${algo}'`); +} + +/** + * Build an SSH public key blob. `algo` is the outward algorithm name; for + * rsa-sha2-256/512 the blob-internal name is written as "ssh-rsa". + */ +export function buildPublicKeyBlob(algo: string, mat: PublicKeyMaterial): Uint8Array { + const w: SshWriter = new SshWriter(64); + if (algo === 'ssh-ed25519') { + const pub: Uint8Array | undefined = mat.ed25519Pub; + if (pub === undefined) { + throw new Error('KeyImport: missing ed25519 public key material'); + } + w.writeString('ssh-ed25519'); + w.writeStringBytes(pub); + return w.toBytes(); + } + if (algo === 'ecdsa-sha2-nistp256') { + const point: Uint8Array | undefined = mat.ecPoint; + if (point === undefined) { + throw new Error('KeyImport: missing ECDSA point material'); + } + w.writeString('ecdsa-sha2-nistp256'); + w.writeString('nistp256'); + w.writeStringBytes(point); + return w.toBytes(); + } + if (algo === 'ssh-rsa' || algo === 'rsa-sha2-256' || algo === 'rsa-sha2-512') { + const e: Uint8Array | undefined = mat.rsaE; + const n: Uint8Array | undefined = mat.rsaN; + if (e === undefined || n === undefined) { + throw new Error('KeyImport: missing RSA key material'); + } + w.writeString('ssh-rsa'); + w.writeMpint(e); + w.writeMpint(n); + return w.toBytes(); + } + throw new Error(`KeyImport: cannot build public key blob for '${algo}'`); +} + +/** + * Verify a server host key signature over the exchange hash H. + * + * @param hostKeyAlgo negotiated algorithm: ssh-ed25519 | ecdsa-sha2-nistp256 + * | rsa-sha2-512 | rsa-sha2-256 | ssh-rsa + * @param hostKeyBlob the K_S blob from KEXDH_REPLY (RFC 4253 §8) + * @param signedData the exchange hash H + * @param sigBlob the signature blob: string algo, string signature + * @returns true when the signature is valid; false on any well-formed but + * unverifiable input. Throws on structural/protocol errors. + */ +export function verifyHostKeySignature(hostKeyAlgo: string, hostKeyBlob: Uint8Array, + signedData: Uint8Array, sigBlob: Uint8Array): boolean { + const mat: PublicKeyMaterial = parsePublicKeyBlob(hostKeyBlob); + const sr: SshReader = new SshReader(sigBlob); + const sigAlgo: string = sr.readString(); + const sig: Uint8Array = sr.readStringBytes(); + if (sigAlgo !== hostKeyAlgo) { + throw new Error(`KeyImport: signature algo '${sigAlgo}' != negotiated '${hostKeyAlgo}'`); + } + + if (hostKeyAlgo === 'ssh-ed25519') { + const pub: Uint8Array | undefined = mat.ed25519Pub; + if (pub === undefined || sig.length !== 64) { + return false; + } + return CryptoAdapter.ed25519VerifySync(pub, signedData, sig); + } + + if (hostKeyAlgo === 'ecdsa-sha2-nistp256') { + const point: Uint8Array | undefined = mat.ecPoint; + if (point === undefined) { + return false; + } + // signature string = mpint r || mpint s (RFC 5656 §3.1.2) + const er: SshReader = new SshReader(sig); + const rMag: Uint8Array = er.readMpint(); + const sMag: Uint8Array = er.readMpint(); + const parts: EcdsaParts = { r: rMag, s: sMag }; + const der: Uint8Array = DerUtils.ecdsaDerFromParts(parts.r, parts.s); + return CryptoAdapter.ecdsaP256VerifySync(point, signedData, der); + } + + if (hostKeyAlgo === 'rsa-sha2-512' || hostKeyAlgo === 'rsa-sha2-256' || hostKeyAlgo === 'ssh-rsa') { + const e: Uint8Array | undefined = mat.rsaE; + const n: Uint8Array | undefined = mat.rsaN; + if (e === undefined || n === undefined) { + return false; + } + const spki: Uint8Array = DerUtils.buildRsaSpki(e, n); + if (hostKeyAlgo === 'rsa-sha2-512') { + return CryptoAdapter.rsaVerifyPkcs1Sync(spki, signedData, sig, 'SHA512'); + } + if (hostKeyAlgo === 'rsa-sha2-256') { + return CryptoAdapter.rsaVerifyPkcs1Sync(spki, signedData, sig, 'SHA256'); + } + return CryptoAdapter.rsaVerifyPkcs1Sync(spki, signedData, sig, 'SHA1'); + } + + throw new Error(`KeyImport: unsupported host key algorithm '${hostKeyAlgo}'`); +} + +/** authorized_keys line: "algo base64(blob) comment" (RFC 4253 §6.6 note). */ +export function authorizedKeysLine(algo: string, blob: Uint8Array, comment: string): string { + return `${algo} ${bytesToBase64(blob)} ${comment}`; +}