T2+T3: platform spike diag page + SSH wire/transport

This commit is contained in:
ROG-X57R
2026-09-08 08:06:10 +08:00
parent e2e79a1d1a
commit f8eefa702b
13 changed files with 2308 additions and 27 deletions
+386
View File
@@ -0,0 +1,386 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*
* T2 platform spike: verifies every platform capability the SSH stack needs
* (TCPSocket binary I/O, cryptoFramework algorithms, packet codec) against
* real servers and RFC test vectors.
*/
import { SshTransport, KexInitInfo } from '../ssh/Transport';
import { TcpRawSocket } from '../ssh/OhosTcpSocket';
import { packetCodecSelfTest } from '../ssh/PacketCodec';
import { CryptoAdapter, RawKeyPair } from '../ssh/crypto/CryptoAdapter';
import { SshVersion } from '../ssh/SshTypes';
import { ClientProposals } from '../ssh/Algorithms';
import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual } from '../ssh/SshWire';
@Entry
@Component
struct DiagPage {
@State host: string = '';
@State port: string = '22';
@State logText: string = '';
@State busy: boolean = false;
private scroller: Scroller = new Scroller();
build() {
Column({ space: 10 }) {
Row({ space: 10 }) {
Text('平台能力诊断')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.layoutWeight(1)
Button('返回')
.fontSize(14)
.height(36)
.onClick(() => {
this.getUIContext().getRouter().back();
})
}
.width('100%')
Row({ space: 8 }) {
TextInput({ placeholder: 'SSH 服务器地址', text: this.host })
.layoutWeight(1)
.height(44)
.onChange((value: string) => {
this.host = value;
})
TextInput({ placeholder: '端口', text: this.port })
.width(90)
.height(44)
.type(InputType.Number)
.onChange((value: string) => {
this.port = value;
})
}
.width('100%')
Column({ space: 8 }) {
Button('1. TCP 连接与 SSH Banner')
.width('100%')
.onClick(() => {
this.runTest((): Promise<void> => this.testTcpBanner());
})
Button('2. AES-256-GCM 加解密往返')
.width('100%')
.onClick(() => {
this.runTest((): Promise<void> => this.testAesGcm());
})
Button('3. X25519 (RFC 7748 向量)')
.width('100%')
.onClick(() => {
this.runTest((): Promise<void> => this.testX25519());
})
Button('4. ECDH-P256 双向协商')
.width('100%')
.onClick(() => {
this.runTest((): Promise<void> => this.testEcdhP256());
})
Button('5. Ed25519 (RFC 8032) + RSA2048 签名')
.width('100%')
.onClick(() => {
this.runTest((): Promise<void> => this.testEd25519Rsa());
})
Button('6. SSH 版本交换 + KEXINIT 握手')
.width('100%')
.onClick(() => {
this.runTest((): Promise<void> => this.testKexInit());
})
Button('7. 二进制包编解码自测')
.width('100%')
.onClick(() => {
this.runTest((): Promise<void> => this.testPacketCodec());
})
}
.width('100%')
Scroll(this.scroller) {
Text(this.logText)
.fontSize(12)
.fontFamily('monospace')
.textAlign(TextAlign.Start)
.width('100%')
}
.layoutWeight(1)
.width('100%')
.backgroundColor('#f2f2f2')
.borderRadius(8)
.padding(8)
.edgeEffect(EdgeEffect.None)
}
.width('100%')
.height('100%')
.padding(14)
}
aboutToAppear(): void {
this.log('INFO', '诊断页就绪。填入服务器地址后逐项点击测试。');
}
private log(level: string, msg: string): void {
this.logText += `[${level}] ${msg}\n`;
if (this.logText.length > 16000) {
this.logText = this.logText.substring(this.logText.length - 12000);
}
this.scroller.scrollEdge(Edge.Bottom);
}
private runTest(test: () => Promise<void>): void {
if (this.busy) {
this.log('INFO', '有测试正在执行,请稍候…');
return;
}
this.busy = true;
const run: Promise<void> = test();
run.then((): void => {
this.busy = false;
}).catch((e: Object): void => {
const err = e as Error;
this.log('FAIL', `异常: ${err.message}`);
this.busy = false;
});
}
private parsePort(): number {
const p: number = parseInt(this.port);
if (isNaN(p) || p < 1 || p > 65535) {
return 22;
}
return p;
}
private trunc(s: string, max: number): string {
if (s.length <= max) {
return s;
}
return `${s.substring(0, max)}…`;
}
/** 1) TCP connect + first SSH banner line, binary-safe. */
private async testTcpBanner(): Promise<void> {
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} ...`);
const sock: TcpRawSocket = new TcpRawSocket();
try {
await sock.connect(host, port, 10000);
const banner: string = await this.readUntilNewline(sock, 8000);
const nl: number = banner.indexOf('\n');
const line: string = (nl >= 0 ? banner.substring(0, nl) : banner).replace('\r', '');
if (line.startsWith('SSH-')) {
this.log('PASS', `服务器 banner: ${line}`);
} else {
this.log('FAIL', `首行不是 SSH 版本串: ${this.trunc(line, 60)}`);
}
} finally {
sock.close();
}
}
private readUntilNewline(sock: TcpRawSocket, timeoutMs: number): Promise<string> {
return new Promise<string>((resolve: (s: string) => void, reject: (e: Error) => void): void => {
let acc: Uint8Array = new Uint8Array(0);
let settled: boolean = false;
sock.onData((chunk: Uint8Array): void => {
if (settled) {
return;
}
const merged: Uint8Array = new Uint8Array(acc.length + chunk.length);
merged.set(acc, 0);
merged.set(chunk, acc.length);
acc = merged;
for (let i = 0; i < acc.length; i++) {
if (acc[i] === 0x0a) {
settled = true;
resolve(bytesToUtf8(acc));
return;
}
}
if (acc.length > 4096) {
settled = true;
resolve(bytesToUtf8(acc));
}
});
sock.onClose((): void => {
if (!settled) {
settled = true;
reject(new Error('连接在收到 banner 前被关闭'));
}
});
setTimeout((): void => {
if (!settled) {
settled = true;
if (acc.length > 0) {
resolve(bytesToUtf8(acc));
} else {
reject(new Error('超时未收到任何数据'));
}
}
}, timeoutMs);
});
}
/** 2) AES-256-GCM round trip + tamper detection. */
private async testAesGcm(): Promise<void> {
const key: Uint8Array = await CryptoAdapter.randomBytes(32);
const iv: Uint8Array = await CryptoAdapter.randomBytes(12);
const plain: Uint8Array = utf8ToBytes('Haven AES-256-GCM round trip 0123456789 中文');
const aad: Uint8Array = utf8ToBytes('haven-diag-aad');
const sealed: Uint8Array = await CryptoAdapter.aesGcmEncrypt(key, iv, plain, aad);
if (sealed.length !== plain.length + 16) {
this.log('FAIL', `密文长度异常: ${sealed.length} (明文 ${plain.length} + 16 tag)`);
return;
}
this.log('INFO', `密文+tag ${bytesToHex(sealed.slice(0, 12))}...`);
const back: Uint8Array = await CryptoAdapter.aesGcmDecrypt(key, iv, sealed, aad);
if (!bytesEqual(back, plain)) {
this.log('FAIL', '解密结果与明文不一致');
return;
}
const tampered: Uint8Array = sealed.slice(0);
tampered[0] ^= 0xff;
let tamperDetected: boolean = false;
try {
await CryptoAdapter.aesGcmDecrypt(key, iv, tampered, aad);
} catch (e) {
tamperDetected = true;
}
if (!tamperDetected) {
this.log('FAIL', '篡改密文未被 GCM tag 校验拒绝');
return;
}
this.log('PASS', 'AES-256-GCM 往返一致,篡改被拒绝');
}
/** 3) X25519 agreement against RFC 7748 §6.1 test vectors. */
private async testX25519(): Promise<void> {
const alicePri: Uint8Array =
hexToBytes('77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a');
const bobPub: Uint8Array =
hexToBytes('de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f');
const bobPri: Uint8Array =
hexToBytes('5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb');
const alicePub: Uint8Array =
hexToBytes('8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a');
const want: Uint8Array =
hexToBytes('4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742');
const k1: Uint8Array = await CryptoAdapter.x25519Agreement(alicePri, bobPub);
const k2: Uint8Array = await CryptoAdapter.x25519Agreement(bobPri, alicePub);
if (!bytesEqual(k1, want) || !bytesEqual(k2, want)) {
this.log('FAIL', `X25519 共享密钥与向量不符: ${bytesToHex(k1)}`);
return;
}
this.log('PASS', `X25519 双向协商 = ${bytesToHex(k1.slice(0, 16))}...`);
}
/** 4) ECDH P-256: generate two pairs, cross-agree, expect equality. */
private async testEcdhP256(): Promise<void> {
const a: RawKeyPair = await CryptoAdapter.ecdhP256GenerateKeyPair();
const b: RawKeyPair = await CryptoAdapter.ecdhP256GenerateKeyPair();
if (a.pub.length !== 65 || a.pub[0] !== 0x04 || b.pub.length !== 65) {
this.log('FAIL', `公钥点格式异常 (len=${a.pub.length})`);
return;
}
const k1: Uint8Array = await CryptoAdapter.ecdhP256Agreement(a.pri, b.pub);
const k2: Uint8Array = await CryptoAdapter.ecdhP256Agreement(b.pri, a.pub);
if (!bytesEqual(k1, k2)) {
this.log('FAIL', 'ECDH-P256 双向协商结果不一致');
return;
}
this.log('PASS', `ECDH-P256 协商一致 (${k1.length}B): ${bytesToHex(k1.slice(0, 12))}...`);
}
/** 5) Ed25519 RFC 8032 TEST 1 + RSA2048 PKCS1-SHA256 round trip. */
private async testEd25519Rsa(): Promise<void> {
const pri: Uint8Array =
hexToBytes('9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
const pub: Uint8Array =
hexToBytes('d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a');
const wantSig: Uint8Array =
hexToBytes('e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b');
const empty: Uint8Array = new Uint8Array(0);
const sig: Uint8Array = await CryptoAdapter.ed25519Sign(pri, empty);
if (!bytesEqual(sig, wantSig)) {
this.log('FAIL', `Ed25519 签名与 RFC 8032 向量不符: ${bytesToHex(sig)}`);
return;
}
const ok: boolean = await CryptoAdapter.ed25519Verify(pub, empty, wantSig);
if (!ok) {
this.log('FAIL', 'Ed25519 向量验签失败');
return;
}
const badOk: boolean = await CryptoAdapter.ed25519Verify(pub, utf8ToBytes('x'), wantSig);
if (badOk) {
this.log('FAIL', 'Ed25519 对被篡改数据验签通过(不应发生)');
return;
}
this.log('PASS', 'Ed25519 签名=向量, 验签通过, 篡改被拒绝');
const pair: RawKeyPair = await CryptoAdapter.rsaGenerateKeyPair(2048);
this.log('INFO', `RSA2048 密钥 DER: pri ${pair.pri.length}B / pub ${pair.pub.length}B`);
const data: Uint8Array = utf8ToBytes('haven-rsa-pkcs1-sha256-roundtrip');
const rsig: Uint8Array = await CryptoAdapter.rsaSignPkcs1Sha256(pair.pri, data);
if (rsig.length !== 256) {
this.log('FAIL', `RSA 签名长度异常: ${rsig.length}`);
return;
}
const rok: boolean = await CryptoAdapter.rsaVerifyPkcs1Sha256(pair.pub, data, rsig);
if (!rok) {
this.log('FAIL', 'RSA 验签失败');
return;
}
this.log('PASS', 'RSA2048|PKCS1|SHA256 签名验签往返通过');
}
/** 6) Version exchange + KEXINIT with a real server (T3 acceptance). */
private async testKexInit(): Promise<void> {
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} 进行版本交换与 KEXINIT ...`);
const sock: TcpRawSocket = new TcpRawSocket();
const transport: SshTransport = new SshTransport(sock);
try {
await sock.connect(host, port, 10000);
const banner: string = await transport.start(SshVersion.CLIENT_BANNER, 15000);
this.log('INFO', `服务器版本: ${banner}`);
if (!banner.startsWith('SSH-2.0')) {
this.log('INFO', '注意: 对端未声明 SSH-2.0(老服务器可能无法继续)');
}
const cookie: Uint8Array = await CryptoAdapter.randomBytes(16);
await transport.sendPacket(transport.buildKexInit(cookie));
this.log('INFO', '已发送我方 KEXINIT');
const payload: Uint8Array = await transport.waitPacket(15000);
const info: KexInitInfo = transport.parseKexInit(payload);
this.log('INFO', `客户端 KEX: ${this.trunc(ClientProposals.kexAlgos.join(','), 64)}`);
this.log('INFO', `服务器 KEX: ${this.trunc(info.kexAlgos.join(','), 64)}`);
this.log('INFO', `服务器 HostKey: ${this.trunc(info.serverHostKeyAlgos.join(','), 64)}`);
this.log('INFO', `服务器 Cipher: ${this.trunc(info.encryptionC2s.join(','), 64)}`);
this.log('INFO', `服务器 MAC: ${this.trunc(info.macC2s.join(','), 64)}`);
this.log('INFO', `firstKexPacketFollows=${info.firstKexPacketFollows}, 出向序号=${transport.getOutSeq()}`);
this.log('PASS', '版本交换与 KEXINIT 解析完成');
} finally {
transport.close();
}
}
/** 7) Binary packet codec self test (sync logic wrapped for runTest). */
private async testPacketCodec(): Promise<void> {
const ok: boolean = packetCodecSelfTest();
if (ok) {
this.log('PASS', 'PacketCodec 自测通过(填充/分块/往返/GCM 分帧参数)');
} else {
this.log('FAIL', 'PacketCodec 自测失败');
}
}
}