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
+29
View File
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*/
import { hilog } from '@kit.PerformanceAnalysisKit';
/**
* Thin wrapper over hilog with a fixed application domain (0x0500).
*/
export class Log {
private static readonly DOMAIN: number = 0x0500;
static debug(tag: string, msg: string): void {
hilog.debug(Log.DOMAIN, tag, '%{public}s', msg);
}
static info(tag: string, msg: string): void {
hilog.info(Log.DOMAIN, tag, '%{public}s', msg);
}
static warn(tag: string, msg: string): void {
hilog.warn(Log.DOMAIN, tag, '%{public}s', msg);
}
static error(tag: string, msg: string): void {
hilog.error(Log.DOMAIN, tag, '%{public}s', msg);
}
}
+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 自测失败');
}
}
}
+16 -25
View File
@@ -1,38 +1,29 @@
/*
* Copyright (c) 2026 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*/
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
Column({ space: 12 }) {
Text('Haven')
.fontSize(26)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
Text('HarmonyOS port · SSH client')
.fontSize(14)
.fontColor('#666666')
Button('打开诊断页')
.width('60%')
.height(44)
.margin({ top: 16 })
.onClick(() => {
this.message = 'Welcome';
this.getUIContext().getRouter().pushUrl({ url: 'pages/DiagPage' });
})
}
.height('100%')
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
}
}
}
+52
View File
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*/
import { SshAlgoLists } from './SshTypes';
/**
* Client-side KEXINIT proposals (the same lists as SshAlgoLists, spelled out
* per KEXINIT field). T5's Kex state machine consumes these when building
* the KEXINIT payload.
*/
export class ClientProposals {
static readonly kexAlgos: string[] = SshAlgoLists.KEX;
static readonly hostKeyAlgos: string[] = SshAlgoLists.HOST_KEY;
static readonly ciphersC2s: string[] = SshAlgoLists.CIPHER;
static readonly ciphersS2c: string[] = SshAlgoLists.CIPHER;
static readonly macsC2s: string[] = SshAlgoLists.MAC;
static readonly macsS2c: string[] = SshAlgoLists.MAC;
static readonly compressionC2s: string[] = SshAlgoLists.COMPRESSION;
static readonly compressionS2c: string[] = SshAlgoLists.COMPRESSION;
static readonly languagesC2s: string[] = [];
static readonly languagesS2c: string[] = [];
static readonly firstKexPacketFollows: boolean = false;
}
/**
* RFC 4251 §7.1 algorithm negotiation: pick the first client algorithm that
* the server also offers. Returns undefined when there is no match.
*/
export function negotiate(client: string[], server: string[]): string | undefined {
for (let i = 0; i < client.length; i++) {
const name: string = client[i];
if (server.indexOf(name) >= 0) {
return name;
}
}
return undefined;
}
/** Split an SSH comma-separated name-list; empty list yields []. */
export function splitNameList(s: string): string[] {
if (s.length === 0) {
return [];
}
return s.split(',');
}
/** Join a name-list back into its wire form. */
export function joinNameList(list: string[]): string {
return list.join(',');
}
+91
View File
@@ -0,0 +1,91 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*/
import { socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { RawSocket } from './Transport';
import { Log } from '../common/Log';
/**
* RawSocket adapter over @ohos.net.socket TCPSocket.
* Event handlers are registered in the constructor, so chunks that arrive
* between connect() resolution and SshTransport.start() are queued in
* `pending` and flushed when the transport installs its callback.
*/
export class TcpRawSocket implements RawSocket {
private static readonly TAG: string = 'TcpRawSocket';
private sock: socket.TCPSocket = socket.constructTCPSocketInstance();
private pending: Uint8Array[] = [];
private dataCb: ((chunk: Uint8Array) => void) | undefined = undefined;
private closeCb: (() => void) | undefined = undefined;
private closed: boolean = false;
constructor() {
this.sock.on('message', (info: socket.SocketMessageInfo): void => {
const chunk: Uint8Array = new Uint8Array(info.message);
if (this.dataCb !== undefined) {
this.dataCb(chunk);
} else {
this.pending.push(chunk);
}
});
this.sock.on('close', (): void => {
this.closed = true;
if (this.closeCb !== undefined) {
this.closeCb();
}
});
this.sock.on('error', (err: BusinessError): void => {
Log.error(TcpRawSocket.TAG, `socket error: ${err.message}`);
});
}
connect(host: string, port: number, timeoutMs: number): Promise<void> {
const addr: socket.NetAddress = { address: host, port: port };
const opts: socket.TCPConnectOptions = { address: addr, timeout: timeoutMs };
return this.sock.connect(opts);
}
send(bytes: Uint8Array): Promise<void> {
return this.sock.send(u8ToArrayBuffer(bytes));
}
onData(cb: (chunk: Uint8Array) => void): void {
this.dataCb = cb;
const queued: Uint8Array[] = this.pending;
this.pending = [];
for (let i = 0; i < queued.length; i++) {
cb(queued[i]);
}
}
onClose(cb: () => void): void {
this.closeCb = cb;
if (this.closed) {
cb();
}
}
close(): void {
if (this.closed) {
return;
}
this.closed = true;
const done: Promise<void> = this.sock.close();
done.catch((e: Object): void => {
const err = e as BusinessError;
Log.warn(TcpRawSocket.TAG, `close: ${err.message}`);
});
}
}
/** Copy a Uint8Array into a standalone ArrayBuffer (TCPSocket.send takes ArrayBuffer). */
export function u8ToArrayBuffer(b: Uint8Array): ArrayBuffer {
const out: ArrayBuffer = new ArrayBuffer(b.length);
const view: Uint8Array = new Uint8Array(out);
view.set(b);
return out;
}
+339
View File
@@ -0,0 +1,339 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*/
/**
* SSH binary packet protocol codec (RFC 4253 §6), with mounting points for
* encrypted modes (RFC 5647 GCM, encrypt-then-MAC) that T4 fills in.
*
* Outbound plaintext framing:
* [packet_length(4)][padding_length(1)][payload][padding]
* with (4 + packet_length) a multiple of blockSize and padding >= minPadding.
*/
/** Result of a successful inbound decode. */
export interface DecodedPacket {
/** Decrypted payload with padding stripped. */
payload: Uint8Array;
/** Total wire bytes this packet consumed (4 + packet_length, +tag for AEAD). */
wireLength: number;
}
/**
* 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.
*
* 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;
* on decrypt the tag must be split off and passed via GcmParamsSpec.authTag.
*/
export interface PacketCipher {
/** Turn a payload into a complete encrypted wire packet. */
encryptToPacket(payload: Uint8Array, seq: number): Uint8Array;
/**
* Try to decrypt one packet from the front of `input`.
* Returns undefined when more bytes are needed; throws on MAC/tag mismatch.
*/
tryDecryptPacket(input: Uint8Array): Promise<DecodedPacket | undefined>;
}
export class PacketCodec {
/** Conservative upper bound on a single packet (1 MiB). */
static readonly MAX_PACKET_LEN: number = 1024 * 1024;
private buffer: Uint8Array = new Uint8Array(4096);
private bufferLen: number = 0;
private outCipher: PacketCipher | undefined = undefined;
private inCipher: PacketCipher | undefined = undefined;
private blockSize: number = 8;
private minPadding: number = 4;
/** Install the outbound cipher and its framing parameters after NEWKEYS. */
setOutCipher(cipher: PacketCipher, blockSize: number, minPadding: number): void {
this.outCipher = cipher;
this.blockSize = blockSize;
this.minPadding = minPadding;
}
/** Install the inbound cipher after NEWKEYS (fresh context resets its seq). */
setInCipher(cipher: PacketCipher): void {
this.inCipher = cipher;
}
/** Drop ciphers (used by tests / connection teardown). */
clearCiphers(): void {
this.outCipher = undefined;
this.inCipher = undefined;
this.blockSize = 8;
this.minPadding = 4;
}
/** Encode a payload into a full wire packet (plaintext or via cipher). */
encodePacket(payload: Uint8Array, seq: number): Uint8Array {
const cipher: PacketCipher | undefined = this.outCipher;
if (cipher !== undefined) {
return cipher.encryptToPacket(payload, seq);
}
return PacketCodec.encodePlain(payload, this.blockSize, this.minPadding);
}
/**
* Plaintext framing. padding >= max(4, minPadding), total length a multiple
* of blockSize. Padding bytes are zero (plaintext mode only; encrypted
* modes build their own framing inside PacketCipher).
*/
static encodePlain(payload: Uint8Array, blockSize: number, minPadding: number): Uint8Array {
const minPad: number = minPadding < 4 ? 4 : minPadding;
let padLen: number = blockSize - ((5 + payload.length) % blockSize);
if (padLen < minPad) {
padLen += blockSize;
}
const packetLen: number = 1 + payload.length + padLen;
const out: Uint8Array = new Uint8Array(4 + packetLen);
out[0] = (packetLen >>> 24) & 0xff;
out[1] = (packetLen >>> 16) & 0xff;
out[2] = (packetLen >>> 8) & 0xff;
out[3] = packetLen & 0xff;
out[4] = padLen;
out.set(payload, 5);
// padding already zero-filled
return out;
}
/** Feed received bytes in arbitrary chunks. */
pushBytes(chunk: Uint8Array): void {
if (chunk.length === 0) {
return;
}
this.ensureCapacity(this.bufferLen + chunk.length);
this.buffer.set(chunk, this.bufferLen);
this.bufferLen += chunk.length;
}
/** Bytes currently buffered awaiting framing. */
buffered(): number {
return this.bufferLen;
}
/**
* Try to pull the next packet. Returns undefined when more bytes are needed.
* Async because cipher decryption may be async; plaintext mode resolves
* immediately.
*/
async nextPacket(): Promise<Uint8Array | undefined> {
const cipher: PacketCipher | undefined = this.inCipher;
if (cipher !== undefined) {
if (this.bufferLen === 0) {
return undefined;
}
const view: Uint8Array = this.buffer.subarray(0, this.bufferLen);
const decoded: DecodedPacket | undefined = await cipher.tryDecryptPacket(view);
if (decoded === undefined) {
return undefined;
}
if (decoded.wireLength > this.bufferLen) {
throw new Error(`PacketCodec: cipher consumed ${decoded.wireLength} > buffered ${this.bufferLen}`);
}
this.consume(decoded.wireLength);
return decoded.payload;
}
return this.tryNextPlainPacket();
}
/** Synchronous plaintext decode (also used by the self test). */
tryNextPlainPacket(): Uint8Array | undefined {
if (this.bufferLen < 4) {
return undefined;
}
const packetLen: number = ((this.buffer[0] * 256 + this.buffer[1]) * 256 + this.buffer[2]) * 256 + this.buffer[3];
if (packetLen < 12) {
throw new Error(`PacketCodec: packet_length ${packetLen} below minimum 12`);
}
if (packetLen > PacketCodec.MAX_PACKET_LEN) {
throw new Error(`PacketCodec: packet_length ${packetLen} exceeds limit`);
}
// Unencrypted packets are multiples of the 8-byte block (RFC 4253 §6).
if ((4 + packetLen) % 8 !== 0) {
throw new Error(`PacketCodec: total length ${4 + packetLen} not a multiple of 8`);
}
if (this.bufferLen < 4 + packetLen) {
return undefined;
}
const padLen: number = this.buffer[4];
if (padLen < 4) {
throw new Error(`PacketCodec: padding_length ${padLen} below 4`);
}
const payloadLen: number = packetLen - 1 - padLen;
if (payloadLen < 0) {
throw new Error('PacketCodec: negative payload length');
}
const payload: Uint8Array = this.buffer.slice(5, 5 + payloadLen);
this.consume(4 + packetLen);
return payload;
}
private ensureCapacity(need: number): void {
if (need <= this.buffer.length) {
return;
}
let cap: number = this.buffer.length * 2;
while (cap < need) {
cap *= 2;
}
const grown: Uint8Array = new Uint8Array(cap);
for (let i = 0; i < this.bufferLen; i++) {
grown[i] = this.buffer[i];
}
this.buffer = grown;
}
private consume(n: number): void {
const remain: number = this.bufferLen - n;
for (let i = 0; i < remain; i++) {
this.buffer[i] = this.buffer[n + i];
}
this.bufferLen = remain;
}
}
/**
* Self test for the plaintext codec: round-trip over several payload sizes,
* byte-at-a-time and multi-byte chunked feeding, back-to-back packets, and
* GCM-style framing parameters (blockSize 16 / minPadding 8).
*/
export function packetCodecSelfTest(): boolean {
const sizes: number[] = [0, 1, 3, 7, 8, 11, 20, 64, 100, 301];
// 1) framing legality + byte-at-a-time reassembly (blockSize 8)
for (let s = 0; s < sizes.length; s++) {
const size: number = sizes[s];
const payload: Uint8Array = testPattern(size);
const packet: Uint8Array = PacketCodec.encodePlain(payload, 8, 4);
const packetLen: number = be32(packet, 0);
if (packet.length !== 4 + packetLen) {
return false;
}
if ((4 + packetLen) % 8 !== 0) {
return false;
}
const padLen: number = packet[4];
if (padLen < 4 || 1 + size + padLen !== packetLen) {
return false;
}
const codec: PacketCodec = new PacketCodec();
for (let i = 0; i < packet.length; i++) {
const one: Uint8Array = packet.slice(i, i + 1);
codec.pushBytes(one);
}
const got: Uint8Array | undefined = codec.tryNextPlainPacket();
if (got === undefined || !bytesMatch(got, payload)) {
return false;
}
if (codec.tryNextPlainPacket() !== undefined) {
return false;
}
}
// 2) chunked feeding with 3-byte chunks
for (let s = 0; s < sizes.length; s++) {
const size: number = sizes[s];
const payload: Uint8Array = testPattern(size);
const packet: Uint8Array = PacketCodec.encodePlain(payload, 8, 4);
const codec: PacketCodec = new PacketCodec();
let i: number = 0;
while (i < packet.length) {
const end: number = i + 3 <= packet.length ? i + 3 : packet.length;
codec.pushBytes(packet.slice(i, end));
i = end;
}
const got: Uint8Array | undefined = codec.tryNextPlainPacket();
if (got === undefined || !bytesMatch(got, payload)) {
return false;
}
}
// 3) two packets back-to-back in one buffer, decoded in order
const p1: Uint8Array = testPattern(10);
const p2: Uint8Array = testPattern(70);
const wire: Uint8Array = concatU8(PacketCodec.encodePlain(p1, 8, 4), PacketCodec.encodePlain(p2, 8, 4));
const codec2: PacketCodec = new PacketCodec();
codec2.pushBytes(wire);
const g1: Uint8Array | undefined = codec2.tryNextPlainPacket();
const g2: Uint8Array | undefined = codec2.tryNextPlainPacket();
if (g1 === undefined || g2 === undefined || !bytesMatch(g1, p1) || !bytesMatch(g2, p2)) {
return false;
}
// 4) partial buffer must not decode early
const big: Uint8Array = PacketCodec.encodePlain(testPattern(200), 8, 4);
const codec3: PacketCodec = new PacketCodec();
codec3.pushBytes(big.slice(0, big.length - 1));
if (codec3.tryNextPlainPacket() !== undefined) {
return false;
}
codec3.pushBytes(big.slice(big.length - 1, big.length));
if (codec3.tryNextPlainPacket() === undefined) {
return false;
}
// 5) GCM-style framing: blockSize 16, minPadding 8
for (let s = 0; s < sizes.length; s++) {
const size: number = sizes[s];
const payload: Uint8Array = testPattern(size);
const packet: Uint8Array = PacketCodec.encodePlain(payload, 16, 8);
const packetLen: number = be32(packet, 0);
if ((4 + packetLen) % 16 !== 0) {
return false;
}
if (packet[4] < 8) {
return false;
}
if (packet.length !== 4 + packetLen) {
return false;
}
}
return true;
}
function be32(b: Uint8Array, off: number): number {
return ((b[off] * 256 + b[off + 1]) * 256 + b[off + 2]) * 256 + b[off + 3];
}
function concatU8(a: Uint8Array, b: Uint8Array): Uint8Array {
const out: Uint8Array = new Uint8Array(a.length + b.length);
out.set(a, 0);
out.set(b, a.length);
return out;
}
function bytesMatch(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function testPattern(size: number): Uint8Array {
const out: Uint8Array = new Uint8Array(size);
for (let i = 0; i < size; i++) {
out[i] = (i * 31 + 7) & 0xff;
}
return out;
}
+190
View File
@@ -0,0 +1,190 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*/
/**
* SSH message numbers, RFC 4251-4254 (+ RFC 8308 EXT_INFO).
*/
export class SshMsg {
/** SSH_MSG_DISCONNECT (RFC 4253 §11.4) */
static readonly DISCONNECT: number = 1;
/** SSH_MSG_IGNORE */
static readonly IGNORE: number = 2;
/** SSH_MSG_UNIMPLEMENTED */
static readonly UNIMPLEMENTED: number = 3;
/** SSH_MSG_DEBUG */
static readonly DEBUG_MSG: number = 4;
/** SSH_MSG_SERVICE_REQUEST (RFC 4254 §10) */
static readonly SERVICE_REQUEST: number = 5;
/** SSH_MSG_SERVICE_ACCEPT */
static readonly SERVICE_ACCEPT: number = 6;
/** SSH_MSG_EXT_INFO (RFC 8308 §2.3) */
static readonly EXT_INFO: number = 7;
/** SSH_MSG_KEXINIT (RFC 4253 §7.1) */
static readonly KEXINIT: number = 20;
/** SSH_MSG_NEWKEYS (RFC 4253 §7.3) */
static readonly NEWKEYS: number = 21;
/** SSH_MSG_KEXDH_INIT / SSH_MSG_KEX_ECDH_INIT (RFC 4253 §8 / RFC 5656 §4) */
static readonly KEXDH_INIT: number = 30;
/** SSH_MSG_KEXDH_REPLY / SSH_MSG_KEX_ECDH_REPLY */
static readonly KEXDH_REPLY: number = 31;
/** SSH_MSG_USERAUTH_REQUEST (RFC 4252 §5) */
static readonly USERAUTH_REQUEST: number = 50;
/** SSH_MSG_USERAUTH_FAILURE */
static readonly USERAUTH_FAILURE: number = 51;
/** SSH_MSG_USERAUTH_SUCCESS */
static readonly USERAUTH_SUCCESS: number = 52;
/** SSH_MSG_USERAUTH_BANNER */
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_INFO_RESPONSE */
static readonly USERAUTH_INFO_RESPONSE: number = 61;
/** SSH_MSG_GLOBAL_REQUEST (RFC 4254 §4) */
static readonly GLOBAL_REQUEST: number = 80;
/** SSH_MSG_REQUEST_SUCCESS */
static readonly REQUEST_SUCCESS: number = 81;
/** SSH_MSG_REQUEST_FAILURE */
static readonly REQUEST_FAILURE: number = 82;
/** SSH_MSG_CHANNEL_OPEN (RFC 4254 §5.1) */
static readonly CHANNEL_OPEN: number = 90;
/** SSH_MSG_CHANNEL_OPEN_CONFIRMATION */
static readonly CHANNEL_OPEN_CONFIRMATION: number = 91;
/** SSH_MSG_CHANNEL_OPEN_FAILURE */
static readonly CHANNEL_OPEN_FAILURE: number = 92;
/** SSH_MSG_CHANNEL_WINDOW_ADJUST (§5.2) */
static readonly CHANNEL_WINDOW_ADJUST: number = 93;
/** SSH_MSG_CHANNEL_DATA (§5.2) */
static readonly CHANNEL_DATA: number = 94;
/** SSH_MSG_CHANNEL_EXTENDED_DATA */
static readonly CHANNEL_EXTENDED_DATA: number = 95;
/** SSH_MSG_CHANNEL_EOF (§5.3) */
static readonly CHANNEL_EOF: number = 96;
/** SSH_MSG_CHANNEL_CLOSE (§5.3) */
static readonly CHANNEL_CLOSE: number = 97;
/** SSH_MSG_CHANNEL_REQUEST (§5.4) */
static readonly CHANNEL_REQUEST: number = 98;
}
/**
* SSH disconnect reason codes, RFC 4253 §11.1.
*/
export class SshDisconnectCode {
static readonly HOST_NOT_ALLOWED_TO_CONNECT: number = 1;
static readonly PROTOCOL_ERROR: number = 2;
static readonly KEY_EXCHANGE_FAILED: number = 3;
static readonly RESERVED: number = 4;
static readonly MAC_ERROR: number = 5;
static readonly COMPRESSION_ERROR: number = 6;
static readonly SERVICE_NOT_AVAILABLE: number = 7;
static readonly PROTOCOL_VERSION_NOT_SUPPORTED: number = 8;
static readonly HOST_KEY_NOT_VERIFIABLE: number = 9;
static readonly CONNECTION_LOST: number = 10;
static readonly BY_APPLICATION: number = 11;
static readonly TOO_MANY_CONNECTIONS: number = 12;
static readonly AUTH_CANCELLED_BY_USER: number = 13;
static readonly NO_MORE_AUTH_METHODS_AVAILABLE: number = 14;
static readonly ILLEGAL_USER_NAME: number = 15;
}
/**
* Channel open failure reason codes, RFC 4254 §5.1.
*/
export class SshChannelFailureCode {
static readonly ADMINISTRATIVELY_PROHIBITED: number = 1;
static readonly CONNECT_FAILED: number = 2;
static readonly UNKNOWN_CHANNEL_TYPE: number = 3;
static readonly RESOURCE_SHORTAGE: number = 4;
}
/**
* Service names (RFC 4252 §5 / RFC 4254 §4).
*/
export class SshServiceName {
static readonly USER_AUTH: string = 'ssh-userauth';
static readonly CONNECTION: string = 'ssh-connection';
}
/**
* Our client identification string (RFC 4253 §4.6: no trailing CR/LF here).
*/
export class SshVersion {
static readonly CLIENT_BANNER: string = 'SSH-2.0-HavenOH_0.1.0';
}
/**
* Algorithm proposal lists (client side, in preference order).
* 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.
*/
export class SshAlgoLists {
static readonly KEX: string[] = [
'curve25519-sha256',
'curve25519-sha256@libssh.org',
'ecdh-sha2-nistp256',
'ext-info-c',
'kex-strict-c-v00@openssh.com'
];
static readonly HOST_KEY: string[] = [
'ssh-ed25519',
'ecdsa-sha2-nistp256',
'rsa-sha2-512',
'rsa-sha2-256',
'ssh-rsa'
];
static readonly CIPHER: string[] = [
'aes128-gcm@openssh.com',
'aes256-gcm@openssh.com',
'aes128-ctr',
'aes192-ctr',
'aes256-ctr'
];
/** With a GCM cipher negotiated the effective MAC is "implicit none". */
static readonly MAC: string[] = [
'hmac-sha2-256-etm@openssh.com',
'hmac-sha2-512-etm@openssh.com',
'hmac-sha2-256',
'hmac-sha2-512'
];
static readonly COMPRESSION: string[] = ['none'];
}
/**
* Human-readable text for a disconnect reason code.
*/
export function disconnectReason(code: number): string {
switch (code) {
case SshDisconnectCode.HOST_NOT_ALLOWED_TO_CONNECT:
return 'host not allowed to connect';
case SshDisconnectCode.PROTOCOL_ERROR:
return 'protocol error';
case SshDisconnectCode.KEY_EXCHANGE_FAILED:
return 'key exchange failed';
case SshDisconnectCode.MAC_ERROR:
return 'MAC error';
case SshDisconnectCode.COMPRESSION_ERROR:
return 'compression error';
case SshDisconnectCode.SERVICE_NOT_AVAILABLE:
return 'service not available';
case SshDisconnectCode.PROTOCOL_VERSION_NOT_SUPPORTED:
return 'protocol version not supported';
case SshDisconnectCode.HOST_KEY_NOT_VERIFIABLE:
return 'host key not verifiable';
case SshDisconnectCode.CONNECTION_LOST:
return 'connection lost';
case SshDisconnectCode.BY_APPLICATION:
return 'disconnected by application';
case SshDisconnectCode.TOO_MANY_CONNECTIONS:
return 'too many connections';
case SshDisconnectCode.AUTH_CANCELLED_BY_USER:
return 'auth cancelled by user';
case SshDisconnectCode.NO_MORE_AUTH_METHODS_AVAILABLE:
return 'no more auth methods available';
case SshDisconnectCode.ILLEGAL_USER_NAME:
return 'illegal user name';
default:
return `disconnect code ${code}`;
}
}
+411
View File
@@ -0,0 +1,411 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*/
/**
* Byte-level SSH wire format reader (RFC 4251 §5).
* All multi-byte integers are big endian. Reads past the end throw Error.
*/
export class SshReader {
private buf: Uint8Array;
private pos: number = 0;
constructor(buf: Uint8Array) {
this.buf = buf;
}
/** Bytes not yet consumed. */
remaining(): number {
return this.buf.length - this.pos;
}
/** Current read offset (for callers that need to reslice). */
position(): number {
return this.pos;
}
private need(n: number): void {
if (this.remaining() < n) {
throw new Error(`SshReader: out of bounds, need ${n} bytes, have ${this.remaining()}`);
}
}
readByte(): number {
this.need(1);
const v: number = this.buf[this.pos];
this.pos += 1;
return v;
}
readBoolean(): boolean {
return this.readByte() !== 0;
}
readUint32(): number {
this.need(4);
const v: number = ((this.buf[this.pos] * 256 + this.buf[this.pos + 1]) * 256 + this.buf[this.pos + 2]) * 256 +
this.buf[this.pos + 3];
this.pos += 4;
return v;
}
/** uint64 read as a JS number (safe below 2^53, enough for SSH counters). */
readUint64(): number {
const hi: number = this.readUint32();
const lo: number = this.readUint32();
return hi * 4294967296 + lo;
}
/** length-prefixed (uint32) byte string; returns a copy. */
readStringBytes(): Uint8Array {
const len: number = this.readUint32();
this.need(len);
const out: Uint8Array = this.buf.slice(this.pos, this.pos + len);
this.pos += len;
return out;
}
/** length-prefixed string decoded as UTF-8. */
readString(): string {
return bytesToUtf8(this.readStringBytes());
}
/**
* mpint per RFC 4251 §5, normalized to the minimal unsigned magnitude:
* the sign byte (0x00 prefix) and redundant leading zeros are stripped,
* keeping at least one byte. Zero is returned as a single 0x00 byte.
*/
readMpint(): Uint8Array {
const raw: Uint8Array = this.readStringBytes();
return normalizeMagnitude(raw);
}
/** Consume n raw bytes, returned as a copy. */
readRaw(n: number): Uint8Array {
this.need(n);
const out: Uint8Array = this.buf.slice(this.pos, this.pos + n);
this.pos += n;
return out;
}
}
/**
* Byte-level SSH wire format writer with a growable internal buffer.
*/
export class SshWriter {
private buf: Uint8Array;
private len: number = 0;
constructor(capacity: number = 64) {
const cap: number = capacity < 16 ? 16 : capacity;
this.buf = new Uint8Array(cap);
}
private ensure(extra: number): void {
const need: number = this.len + extra;
if (need <= this.buf.length) {
return;
}
let cap: number = this.buf.length * 2;
while (cap < need) {
cap *= 2;
}
const grown: Uint8Array = new Uint8Array(cap);
grown.set(this.buf);
this.buf = grown;
}
writeByte(v: number): void {
this.ensure(1);
this.buf[this.len] = v & 0xff;
this.len += 1;
}
writeBoolean(v: boolean): void {
this.writeByte(v ? 1 : 0);
}
writeUint32(v: number): void {
this.ensure(4);
this.buf[this.len] = (v >>> 24) & 0xff;
this.buf[this.len + 1] = (v >>> 16) & 0xff;
this.buf[this.len + 2] = (v >>> 8) & 0xff;
this.buf[this.len + 3] = v & 0xff;
this.len += 4;
}
/** uint64 written from a JS number (must be below 2^53). */
writeUint64(v: number): void {
const hi: number = Math.floor(v / 4294967296);
const lo: number = v % 4294967296;
this.writeUint32(hi);
this.writeUint32(lo);
}
/** uint32 length prefix + raw bytes. */
writeStringBytes(b: Uint8Array): void {
this.writeUint32(b.length);
this.writeRaw(b);
}
/** uint32 length prefix + UTF-8 encoded string. */
writeString(s: string): void {
this.writeStringBytes(utf8ToBytes(s));
}
/**
* mpint per RFC 4251 §5 from an unsigned magnitude:
* - all-zero encodes as a single 0x00 byte
* - a 0x00 sign byte is prepended when the MSB would otherwise read as negative
* - redundant leading zero bytes are stripped (canonical form)
*/
writeMpint(b: Uint8Array): void {
const mag: Uint8Array = normalizeMagnitude(b);
if (mag.length === 1 && mag[0] === 0) {
this.writeUint32(1);
this.writeByte(0);
return;
}
if (mag[0] >= 0x80) {
this.writeUint32(mag.length + 1);
this.writeByte(0);
this.writeRaw(mag);
} else {
this.writeUint32(mag.length);
this.writeRaw(mag);
}
}
writeRaw(b: Uint8Array): void {
this.ensure(b.length);
this.buf.set(b, this.len);
this.len += b.length;
}
/** Current number of written bytes. */
length(): number {
return this.len;
}
/** Copy of the written region. */
toBytes(): Uint8Array {
return this.buf.slice(0, this.len);
}
}
/**
* Normalize an unsigned magnitude: strip the sign byte / redundant leading
* zeros, keep at least one byte. Zero -> single 0x00.
*/
export function normalizeMagnitude(b: Uint8Array): Uint8Array {
let i: number = 0;
while (i < b.length - 1 && b[i] === 0) {
i += 1;
}
return b.slice(i);
}
/** Concatenate two byte arrays. */
export function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
const out: Uint8Array = new Uint8Array(a.length + b.length);
out.set(a, 0);
out.set(b, a.length);
return out;
}
/** Constant-time-ish byte comparison. */
export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) {
return false;
}
let diff: number = 0;
for (let i = 0; i < a.length; i++) {
diff |= a[i] ^ b[i];
}
return diff === 0;
}
const HEX_CHARS: string = '0123456789abcdef';
export function bytesToHex(b: Uint8Array): string {
let out: string = '';
for (let i = 0; i < b.length; i++) {
const v: number = b[i];
out += HEX_CHARS[(v >>> 4) & 0xf];
out += HEX_CHARS[v & 0xf];
}
return out;
}
export function hexToBytes(s: string): Uint8Array {
if (s.length % 2 !== 0) {
throw new Error(`hexToBytes: odd length ${s.length}`);
}
const out: Uint8Array = new Uint8Array(s.length / 2);
for (let i = 0; i < out.length; i++) {
const hi: number = hexDigit(s.charCodeAt(i * 2));
const lo: number = hexDigit(s.charCodeAt(i * 2 + 1));
out[i] = (hi << 4) | lo;
}
return out;
}
function hexDigit(c: number): number {
if (c >= 48 && c <= 57) {
return c - 48;
}
if (c >= 97 && c <= 102) {
return c - 87;
}
if (c >= 65 && c <= 70) {
return c - 55;
}
throw new Error(`hexToBytes: invalid hex char ${c}`);
}
const B64_ALPHABET: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
export function bytesToBase64(b: Uint8Array): string {
let out: string = '';
const full: number = Math.floor(b.length / 3) * 3;
for (let i = 0; i < full; i += 3) {
const n: number = (b[i] << 16) | (b[i + 1] << 8) | b[i + 2];
out += B64_ALPHABET[(n >>> 18) & 0x3f];
out += B64_ALPHABET[(n >>> 12) & 0x3f];
out += B64_ALPHABET[(n >>> 6) & 0x3f];
out += B64_ALPHABET[n & 0x3f];
}
const rest: number = b.length - full;
if (rest === 1) {
const n: number = b[full] << 16;
out += B64_ALPHABET[(n >>> 18) & 0x3f];
out += B64_ALPHABET[(n >>> 12) & 0x3f];
out += '==';
} else if (rest === 2) {
const n: number = (b[full] << 16) | (b[full + 1] << 8);
out += B64_ALPHABET[(n >>> 18) & 0x3f];
out += B64_ALPHABET[(n >>> 12) & 0x3f];
out += B64_ALPHABET[(n >>> 6) & 0x3f];
out += '=';
}
return out;
}
export function base64ToBytes(s: string): Uint8Array {
const clean: string[] = [];
for (let i = 0; i < s.length; i++) {
const ch: string = s[i];
if (ch === '=' || ch === '\n' || ch === '\r' || ch === ' ' || ch === '\t') {
continue;
}
const idx: number = B64_ALPHABET.indexOf(ch);
if (idx < 0) {
throw new Error(`base64ToBytes: invalid char '${ch}'`);
}
clean.push(B64_ALPHABET[idx]);
}
const outLen: number = Math.floor(clean.length / 4) * 3;
const rem: number = clean.length % 4;
let total: number = outLen;
if (rem === 2) {
total += 1;
} else if (rem === 3) {
total += 2;
} else if (rem === 1) {
throw new Error('base64ToBytes: invalid length');
}
const out: Uint8Array = new Uint8Array(total);
let o: number = 0;
let i: number = 0;
while (i + 4 <= clean.length) {
const n: number = (b64Val(clean[i]) << 18) | (b64Val(clean[i + 1]) << 12) | (b64Val(clean[i + 2]) << 6) |
b64Val(clean[i + 3]);
out[o] = (n >>> 16) & 0xff;
out[o + 1] = (n >>> 8) & 0xff;
out[o + 2] = n & 0xff;
o += 3;
i += 4;
}
if (rem === 2) {
const n: number = (b64Val(clean[i]) << 18) | (b64Val(clean[i + 1]) << 12);
out[o] = (n >>> 16) & 0xff;
} else if (rem === 3) {
const n: number = (b64Val(clean[i]) << 18) | (b64Val(clean[i + 1]) << 12) | (b64Val(clean[i + 2]) << 6);
out[o] = (n >>> 16) & 0xff;
out[o + 1] = (n >>> 8) & 0xff;
}
return out;
}
function b64Val(ch: string): number {
const idx: number = B64_ALPHABET.indexOf(ch);
if (idx < 0) {
throw new Error(`base64ToBytes: invalid char '${ch}'`);
}
return idx;
}
/** Minimal UTF-8 decoder (RFC 3629), rejects overlong/surrogate encodings. */
export function bytesToUtf8(b: Uint8Array): string {
let out: string = '';
let i: number = 0;
while (i < b.length) {
const c: number = b[i];
if (c < 0x80) {
out += String.fromCharCode(c);
i += 1;
continue;
}
let cp: number = 0;
let extra: number = 0;
if (c >= 0xc2 && c <= 0xdf) {
cp = c & 0x1f;
extra = 1;
} else if (c >= 0xe0 && c <= 0xef) {
cp = c & 0x0f;
extra = 2;
} else if (c >= 0xf0 && c <= 0xf4) {
cp = c & 0x07;
extra = 3;
} else {
throw new Error(`bytesToUtf8: invalid byte 0x${HEX_CHARS[(c >>> 4) & 0xf]}${HEX_CHARS[c & 0xf]}`);
}
if (i + extra >= b.length) {
throw new Error('bytesToUtf8: truncated sequence');
}
for (let j = 1; j <= extra; j++) {
const cc: number = b[i + j];
if ((cc & 0xc0) !== 0x80) {
throw new Error('bytesToUtf8: invalid continuation byte');
}
cp = (cp << 6) | (cc & 0x3f);
}
out += String.fromCharCode(cp);
i += extra + 1;
}
return out;
}
/** Minimal UTF-8 encoder (BMP range via charCodeAt; sufficient for SSH). */
export function utf8ToBytes(s: string): Uint8Array {
const out: number[] = [];
for (let i = 0; i < s.length; i++) {
const c: number = s.charCodeAt(i);
if (c < 0x80) {
out.push(c);
} else if (c < 0x800) {
out.push(0xc0 | (c >>> 6));
out.push(0x80 | (c & 0x3f));
} else {
out.push(0xe0 | (c >>> 12));
out.push(0x80 | ((c >>> 6) & 0x3f));
out.push(0x80 | (c & 0x3f));
}
}
const bytes: Uint8Array = new Uint8Array(out.length);
for (let i = 0; i < out.length; i++) {
bytes[i] = out[i];
}
return bytes;
}
+387
View File
@@ -0,0 +1,387 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*
* SSH transport layer over an injected raw socket:
* version banner exchange (RFC 4253 §4), binary packet framing, sequence
* number management, cipher mounting points around NEWKEYS and rekey byte
* counters. Algorithm KEX lives in T5; this layer only moves bytes.
*/
import { Log } from '../common/Log';
import { BusinessError } from '@kit.BasicServicesKit';
import { PacketCodec, PacketCipher } from './PacketCodec';
import { SshReader, SshWriter, bytesToUtf8, utf8ToBytes } from './SshWire';
import { ClientProposals, splitNameList, joinNameList } from './Algorithms';
import { SshMsg } from './SshTypes';
/**
* Socket abstraction so the protocol stack stays testable. Implementations
* MUST buffer data events that fire before onData() registers its callback
* (a TCP server can send the banner immediately after connect).
*/
export interface RawSocket {
connect(host: string, port: number, timeoutMs: number): Promise<void>;
send(bytes: Uint8Array): Promise<void>;
/** Install the (single) data callback; queued chunks are flushed to it. */
onData(cb: (chunk: Uint8Array) => void): void;
/** Install the (single) close callback; called immediately if already closed. */
onClose(cb: () => void): void;
close(): void;
}
/** Parsed KEXINIT payload (RFC 4253 §7.1). */
export interface KexInitInfo {
msgType: number;
cookie: Uint8Array;
kexAlgos: string[];
serverHostKeyAlgos: string[];
encryptionC2s: string[];
encryptionS2c: string[];
macC2s: string[];
macS2c: string[];
compressionC2s: string[];
compressionS2c: string[];
languagesC2s: string[];
languagesS2c: string[];
firstKexPacketFollows: boolean;
reserved: number;
}
const MAX_BANNER_BYTES: number = 8192;
export class SshTransport {
private static readonly TAG: string = 'SshTransport';
private socket: RawSocket;
private codec: PacketCodec = new PacketCodec();
private bannerBuffer: Uint8Array = new Uint8Array(0);
private bannerDone: boolean = false;
private closed: boolean = false;
private bannerResolver: ((banner: string) => void) | undefined = undefined;
private bannerRejecter: ((err: Error) => void) | undefined = undefined;
private packetCallback: ((payload: Uint8Array) => void) | undefined = undefined;
private packetWaiter: ((payload: Uint8Array) => void) | undefined = undefined;
private packetWaiterRejecter: ((err: Error) => void) | undefined = undefined;
private outSeq: number = 0;
private inSeq: number = 0;
private sentBytes: number = 0;
private receivedBytes: number = 0;
private dispatching: boolean = false;
private sendChain: Promise<void> = Promise.resolve();
private closeCallback: ((reason: string) => void) | undefined = undefined;
constructor(socket: RawSocket) {
this.socket = socket;
}
/**
* Send our identification string, then read the server's banner.
* RFC 4253 §4.2: lines not starting with "SSH-" sent before the version
* line are legal and skipped; CR, LF and CRLF line endings tolerated.
* Returns the server banner without its line terminator.
*/
async start(clientVersion: string, timeoutMs: number = 15000): Promise<string> {
const version: string = clientVersion.replace('\r', '').replace('\n', '');
this.socket.onData((chunk: Uint8Array): void => {
this.handleData(chunk);
});
this.socket.onClose((): void => {
this.handleClose('socket closed');
});
await this.sendRaw(utf8ToBytes(`${version}\r\n`));
const banner: string = await new Promise<string>((resolve: (b: string) => void,
reject: (e: Error) => void): void => {
this.bannerResolver = resolve;
this.bannerRejecter = reject;
setTimeout((): void => {
if (this.bannerRejecter !== undefined) {
this.bannerRejecter(new Error(`timeout waiting for server banner after ${timeoutMs} ms`));
this.bannerRejecter = undefined;
this.bannerResolver = undefined;
}
}, timeoutMs);
});
return banner;
}
/** Persistent packet handler (waitPacket takes precedence when armed). */
onPacket(cb: (payload: Uint8Array) => void): void {
this.packetCallback = cb;
}
/** Connection loss notification. */
onClose(cb: (reason: string) => void): void {
this.closeCallback = cb;
}
/** Resolve with the next received packet payload, or reject on close/timeout. */
async waitPacket(timeoutMs: number): Promise<Uint8Array> {
return new Promise<Uint8Array>((resolve: (p: Uint8Array) => void, reject: (e: Error) => void): void => {
this.packetWaiter = resolve;
this.packetWaiterRejecter = reject;
setTimeout((): void => {
if (this.packetWaiterRejecter !== undefined) {
this.packetWaiterRejecter(new Error(`timeout waiting for packet after ${timeoutMs} ms`));
this.packetWaiter = undefined;
this.packetWaiterRejecter = undefined;
}
}, timeoutMs);
});
}
/** Build our KEXINIT payload (unframed; pass to sendPacket). */
buildKexInit(cookie: Uint8Array): Uint8Array {
const w: SshWriter = new SshWriter(512);
w.writeByte(SshMsg.KEXINIT);
w.writeRaw(cookie);
w.writeString(joinNameList(ClientProposals.kexAlgos));
w.writeString(joinNameList(ClientProposals.hostKeyAlgos));
w.writeString(joinNameList(ClientProposals.ciphersC2s));
w.writeString(joinNameList(ClientProposals.ciphersS2c));
w.writeString(joinNameList(ClientProposals.macsC2s));
w.writeString(joinNameList(ClientProposals.macsS2c));
w.writeString(joinNameList(ClientProposals.compressionC2s));
w.writeString(joinNameList(ClientProposals.compressionS2c));
w.writeString(joinNameList(ClientProposals.languagesC2s));
w.writeString(joinNameList(ClientProposals.languagesS2c));
w.writeBoolean(ClientProposals.firstKexPacketFollows);
w.writeUint32(0);
return w.toBytes();
}
/** Parse a KEXINIT payload (throws if the message number mismatches). */
parseKexInit(payload: Uint8Array): KexInitInfo {
const r: SshReader = new SshReader(payload);
const msgType: number = r.readByte();
if (msgType !== SshMsg.KEXINIT) {
throw new Error(`parseKexInit: expected msg ${SshMsg.KEXINIT}, got ${msgType}`);
}
const cookie: Uint8Array = r.readRaw(16);
const info: KexInitInfo = {
msgType: msgType,
cookie: cookie,
kexAlgos: splitNameList(r.readString()),
serverHostKeyAlgos: splitNameList(r.readString()),
encryptionC2s: splitNameList(r.readString()),
encryptionS2c: splitNameList(r.readString()),
macC2s: splitNameList(r.readString()),
macS2c: splitNameList(r.readString()),
compressionC2s: splitNameList(r.readString()),
compressionS2c: splitNameList(r.readString()),
languagesC2s: splitNameList(r.readString()),
languagesS2c: splitNameList(r.readString()),
firstKexPacketFollows: r.readBoolean(),
reserved: r.readUint32()
};
return info;
}
/** Frame and send one packet; outbound sequence number increments on success. */
sendPacket(payload: Uint8Array): Promise<void> {
const seq: number = this.outSeq;
this.outSeq = (this.outSeq + 1) % 4294967296;
const wire: Uint8Array = this.codec.encodePacket(payload, seq);
const send: Promise<void> = this.sendChain.then((): Promise<void> => {
if (this.closed) {
throw new Error('SshTransport: connection already closed');
}
return this.sendRaw(wire);
});
this.sendChain = send.catch((): void => {});
return send;
}
/** Install the outbound cipher after sending NEWKEYS (T5 wires this). */
setOutCipher(cipher: PacketCipher, blockSize: number, minPadding: number): void {
this.codec.setOutCipher(cipher, blockSize, minPadding);
}
/** Install the inbound cipher after receiving NEWKEYS (T5 wires this). */
setInCipher(cipher: PacketCipher): void {
this.codec.setInCipher(cipher);
}
/**
* Zero both sequence counters. Called after the NEWKEYS exchange completes
* (RFC 4253 §6.4); with strict-kex the KEXINIT guess check happens before.
*/
resetSequenceNumbers(): void {
this.outSeq = 0;
this.inSeq = 0;
}
/** Bytes sent since connect (rekey trigger at 2^30, plan Design §2). */
getSentBytes(): number {
return this.sentBytes;
}
/** Bytes received since connect. */
getReceivedBytes(): number {
return this.receivedBytes;
}
getOutSeq(): number {
return this.outSeq;
}
getInSeq(): number {
return this.inSeq;
}
isClosed(): boolean {
return this.closed;
}
close(): void {
if (this.closed) {
return;
}
this.closed = true;
this.rejectPending(new Error('SshTransport: closed'));
try {
this.socket.close();
} catch (e) {
const err = e as BusinessError;
Log.warn(SshTransport.TAG, `socket close error: ${err.message}`);
}
}
private async sendRaw(bytes: Uint8Array): Promise<void> {
this.sentBytes += bytes.length;
await this.socket.send(bytes);
}
private handleData(chunk: Uint8Array): void {
if (this.closed) {
return;
}
this.receivedBytes += chunk.length;
if (this.bannerDone) {
this.codec.pushBytes(chunk);
this.drainPackets();
return;
}
this.bannerBuffer = concatU8(this.bannerBuffer, chunk);
if (this.bannerBuffer.length > MAX_BANNER_BYTES) {
this.failBanner(new Error('server sent too much data without an SSH version line'));
return;
}
while (!this.bannerDone) {
const nl: number = indexOfByte(this.bannerBuffer, 0x0a);
if (nl < 0) {
return;
}
const lineBytes: Uint8Array = this.bannerBuffer.slice(0, nl);
this.bannerBuffer = this.bannerBuffer.slice(nl + 1);
let line: string = bytesToUtf8(lineBytes);
if (line.length > 0 && line[line.length - 1] === '\r') {
line = line.substring(0, line.length - 1);
}
if (line.startsWith('SSH-')) {
this.bannerDone = true;
Log.info(SshTransport.TAG, `server banner: ${line}`);
const resolver: ((b: string) => void) | undefined = this.bannerResolver;
this.bannerResolver = undefined;
this.bannerRejecter = undefined;
if (resolver !== undefined) {
resolver(line);
}
const leftover: Uint8Array = this.bannerBuffer;
this.bannerBuffer = new Uint8Array(0);
if (leftover.length > 0) {
this.codec.pushBytes(leftover);
this.drainPackets();
}
return;
}
Log.debug(SshTransport.TAG, `ignoring pre-banner line: ${line}`);
}
}
private failBanner(err: Error): void {
const rejecter: ((e: Error) => void) | undefined = this.bannerRejecter;
this.bannerResolver = undefined;
this.bannerRejecter = undefined;
if (rejecter !== undefined) {
rejecter(err);
}
}
private handleClose(reason: string): void {
if (this.closed) {
return;
}
this.closed = true;
this.rejectPending(new Error(`SshTransport: ${reason}`));
const cb: ((reason: string) => void) | undefined = this.closeCallback;
if (cb !== undefined) {
cb(reason);
}
}
private rejectPending(err: Error): void {
if (this.bannerRejecter !== undefined) {
this.bannerRejecter(err);
this.bannerResolver = undefined;
this.bannerRejecter = undefined;
}
if (this.packetWaiterRejecter !== undefined) {
this.packetWaiterRejecter(err);
this.packetWaiter = undefined;
this.packetWaiterRejecter = undefined;
}
}
private drainPackets(): void {
if (this.dispatching) {
return;
}
this.dispatching = true;
const step: Promise<void> = this.drainLoop();
step.then((): void => {
this.dispatching = false;
}).catch((e: Object): void => {
this.dispatching = false;
const err = e as Error;
Log.error(SshTransport.TAG, `packet decode failed: ${err.message}`);
this.handleClose(`packet decode error: ${err.message}`);
});
}
private async drainLoop(): Promise<void> {
while (!this.closed) {
const payload: Uint8Array | undefined = await this.codec.nextPacket();
if (payload === undefined) {
return;
}
this.inSeq = (this.inSeq + 1) % 4294967296;
const waiter: ((p: Uint8Array) => void) | undefined = this.packetWaiter;
if (waiter !== undefined) {
this.packetWaiter = undefined;
this.packetWaiterRejecter = undefined;
waiter(payload);
}
const cb: ((payload: Uint8Array) => void) | undefined = this.packetCallback;
if (cb !== undefined) {
cb(payload);
}
}
}
}
function concatU8(a: Uint8Array, b: Uint8Array): Uint8Array {
const out: Uint8Array = new Uint8Array(a.length + b.length);
out.set(a, 0);
out.set(b, a.length);
return out;
}
function indexOfByte(b: Uint8Array, v: number): number {
for (let i = 0; i < b.length; i++) {
if (b[i] === v) {
return i;
}
}
return -1;
}
@@ -0,0 +1,375 @@
/*
* Copyright (c) 2026 Haven for HarmonyOS contributors.
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
*
* Async wrapper over @ohos.security.cryptoFramework. T4 extends this with
* CTR streaming, key derivation expansion and DerUtils; the T2 surface
* below is what the diagnostics page and the SSH stack need first.
*/
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { hexToBytes, concatBytes } from '../SshWire';
/** Raw key material pair: semantics depend on the algorithm. */
export interface RawKeyPair {
/** X25519/Ed25519: raw 32 bytes. ECC-P256: 32-byte scalar. RSA: PKCS#8 DER. */
pri: Uint8Array;
/** X25519/Ed25519: raw 32 bytes. ECC-P256: 04||X||Y (65 bytes). RSA: SPKI DER. */
pub: Uint8Array;
}
/**
* Fixed DER prefixes for raw-key wrapping (confirmed against the official
* CryptoArchitectureKit samples; RFC 8410 / RFC 5480 structures).
*/
export class DerPrefix {
/** X25519 SubjectPublicKeyInfo header (12 bytes) + raw 32-byte public key. */
static readonly X25519_SPKI: Uint8Array = hexToBytes('302a300506032b656e032100');
/** X25519 PKCS#8 header (16 bytes) + raw 32-byte private key. */
static readonly X25519_PKCS8: Uint8Array = hexToBytes('302e020100300506032b656e04220420');
/** Ed25519 SubjectPublicKeyInfo header (12 bytes) + raw 32-byte public key. */
static readonly ED25519_SPKI: Uint8Array = hexToBytes('302a300506032b6570032100');
/** Ed25519 PKCS#8 header (16 bytes) + raw 32-byte private key. */
static readonly ED25519_PKCS8: Uint8Array = hexToBytes('302e020100300506032b657004220420');
/** EC P-256 SubjectPublicKeyInfo header (26 bytes) + 04||X||Y (65 bytes). */
static readonly P256_SPKI: Uint8Array =
hexToBytes('3059301306072a8648ce3d020106082a8648ce3d030107034200');
/** EC P-256 PKCS#8 trailing attributes (12 bytes). */
static readonly P256_PKCS8_TAIL: Uint8Array = hexToBytes('a00a06082a8648ce3d030107');
}
export class CryptoAdapter {
private static readonly TAG: string = 'CryptoAdapter';
private static readonly GCM_TAG_LEN: number = 16;
// ---------------------------------------------------------------- random
static async randomBytes(n: number): Promise<Uint8Array> {
const rand: cryptoFramework.Random = cryptoFramework.createRandom();
const out: cryptoFramework.DataBlob = await rand.generateRandom(n);
return out.data;
}
// --------------------------------------------------------------- digests
private static async digest(alg: string, data: Uint8Array): Promise<Uint8Array> {
const md: cryptoFramework.Md = cryptoFramework.createMd(alg);
await md.update({ data: data });
const out: cryptoFramework.DataBlob = await md.digest();
return out.data;
}
static async sha256(data: Uint8Array): Promise<Uint8Array> {
return CryptoAdapter.digest('SHA256', data);
}
static async sha512(data: Uint8Array): Promise<Uint8Array> {
return CryptoAdapter.digest('SHA512', data);
}
// ------------------------------------------------------------------ MAC
private static async hmac(mdAlg: string, key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {
const keyGen: cryptoFramework.SymKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC');
const symKey: cryptoFramework.SymKey = await keyGen.convertKey({ data: key });
const mac: cryptoFramework.Mac = cryptoFramework.createMac(mdAlg);
await mac.init(symKey);
await mac.update({ data: data });
const out: cryptoFramework.DataBlob = await mac.doFinal();
return out.data;
}
static async hmacSha256(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {
return CryptoAdapter.hmac('SHA256', key, data);
}
static async hmacSha512(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {
return CryptoAdapter.hmac('SHA512', key, data);
}
// --------------------------------------------------------------- AES-GCM
// SSH semantics: encrypt output = ciphertext || 16-byte tag.
// OpenHarmony: encrypt doFinal() output = ciphertext || tag (take the last
// 16 bytes); decrypt requires the tag in GcmParamsSpec.authTag and the
// ciphertext WITHOUT the tag in doFinal().
private static aesAlgName(keyLen: number): string {
if (keyLen === 16) {
return 'AES128';
}
if (keyLen === 24) {
return 'AES192';
}
if (keyLen === 32) {
return 'AES256';
}
throw new Error(`CryptoAdapter: unsupported AES key length ${keyLen}`);
}
static async aesGcmEncrypt(key: Uint8Array, iv: Uint8Array, plain: Uint8Array,
aad: Uint8Array): Promise<Uint8Array> {
const alg: string = CryptoAdapter.aesAlgName(key.length);
const keyGen: cryptoFramework.SymKeyGenerator = cryptoFramework.createSymKeyGenerator(alg);
const symKey: cryptoFramework.SymKey = await keyGen.convertKey({ 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) }
};
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, params);
const out: cryptoFramework.DataBlob = await cipher.doFinal({ data: plain });
return out.data; // ciphertext || tag(16)
}
static async aesGcmDecrypt(key: Uint8Array, iv: Uint8Array, sealed: Uint8Array,
aad: Uint8Array): Promise<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 = await keyGen.convertKey({ 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 }
};
await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, params);
const out: cryptoFramework.DataBlob = await cipher.doFinal({ data: body });
return out.data;
}
// --------------------------------------------------------------- X25519
// raw 32-byte keys in and out; DER wrapping is internal.
static async x25519GenerateKeyPair(): Promise<RawKeyPair> {
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('X25519');
const kp: cryptoFramework.KeyPair = await gen.generateKeyPair();
const priDer: Uint8Array = kp.priKey.getEncoded().data;
const pubDer: Uint8Array = kp.pubKey.getEncoded().data;
const pair: RawKeyPair = {
pri: CryptoAdapter.unwrapPkcs8(priDer, DerPrefix.X25519_PKCS8),
pub: CryptoAdapter.unwrapSpki(pubDer, DerPrefix.X25519_SPKI)
};
return pair;
}
static async x25519Agreement(priRaw: Uint8Array, peerPubRaw: Uint8Array): Promise<Uint8Array> {
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('X25519');
const priBlob: cryptoFramework.DataBlob = { data: CryptoAdapter.wrapPkcs8(priRaw, DerPrefix.X25519_PKCS8) };
const pubBlob: cryptoFramework.DataBlob = { data: CryptoAdapter.wrapSpki(peerPubRaw, DerPrefix.X25519_SPKI) };
const priKp: cryptoFramework.KeyPair = await gen.convertKey(null, priBlob);
const pubKp: cryptoFramework.KeyPair = await gen.convertKey(pubBlob, null);
const agreement: cryptoFramework.KeyAgreement = cryptoFramework.createKeyAgreement('X25519');
const secret: cryptoFramework.DataBlob = await agreement.generateSecret(priKp.priKey, pubKp.pubKey);
return secret.data;
}
// -------------------------------------------------------------- ECDH P-256
// pub = uncompressed point 04||X||Y (65 bytes); pri = 32-byte scalar.
static async ecdhP256GenerateKeyPair(): Promise<RawKeyPair> {
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256');
const kp: cryptoFramework.KeyPair = await gen.generateKeyPair();
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;
}
static async ecdhP256Agreement(pri: Uint8Array, peerPubPoint: Uint8Array): Promise<Uint8Array> {
if (peerPubPoint.length !== 65 || peerPubPoint[0] !== 0x04) {
throw new Error('CryptoAdapter: P-256 peer public key must be 04||X||Y');
}
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256');
const priBlob: cryptoFramework.DataBlob = { data: CryptoAdapter.buildP256Pkcs8(pri) };
const pubBlob: cryptoFramework.DataBlob = { data: concatBytes(DerPrefix.P256_SPKI, peerPubPoint) };
const priKp: cryptoFramework.KeyPair = await gen.convertKey(null, priBlob);
const pubKp: cryptoFramework.KeyPair = await gen.convertKey(pubBlob, null);
const agreement: cryptoFramework.KeyAgreement = cryptoFramework.createKeyAgreement('ECC256');
const secret: cryptoFramework.DataBlob = await agreement.generateSecret(priKp.priKey, pubKp.pubKey);
return secret.data;
}
// --------------------------------------------------------------- Ed25519
// raw 32-byte keys; signatures are raw 64 bytes (RFC 8032).
static async ed25519GenerateKeyPair(): Promise<RawKeyPair> {
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('Ed25519');
const kp: cryptoFramework.KeyPair = await gen.generateKeyPair();
const priDer: Uint8Array = kp.priKey.getEncoded().data;
const pubDer: Uint8Array = kp.pubKey.getEncoded().data;
const pair: RawKeyPair = {
pri: CryptoAdapter.unwrapPkcs8(priDer, DerPrefix.ED25519_PKCS8),
pub: CryptoAdapter.unwrapSpki(pubDer, DerPrefix.ED25519_SPKI)
};
return pair;
}
static async ed25519Sign(priRaw: Uint8Array, data: Uint8Array): Promise<Uint8Array> {
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('Ed25519');
const priBlob: cryptoFramework.DataBlob = { data: CryptoAdapter.wrapPkcs8(priRaw, DerPrefix.ED25519_PKCS8) };
const kp: cryptoFramework.KeyPair = await gen.convertKey(null, priBlob);
const signer: cryptoFramework.Sign = cryptoFramework.createSign('Ed25519');
await signer.init(kp.priKey);
const sig: cryptoFramework.DataBlob = await signer.sign({ data: data });
return sig.data;
}
static async ed25519Verify(pubRaw: Uint8Array, data: Uint8Array, sig: Uint8Array): Promise<boolean> {
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator('Ed25519');
const pubBlob: cryptoFramework.DataBlob = { data: CryptoAdapter.wrapSpki(pubRaw, DerPrefix.ED25519_SPKI) };
const kp: cryptoFramework.KeyPair = await gen.convertKey(pubBlob, null);
const verifier: cryptoFramework.Verify = cryptoFramework.createVerify('Ed25519');
await verifier.init(kp.pubKey);
const ok: boolean = await verifier.verify({ data: data }, { data: sig });
return ok;
}
// ------------------------------------------------------------------- RSA
// Keys are full DER blobs (SPKI public / PKCS#8 private, as exported by
// generateKeyPair). 2048/3072/4096 bits, PKCS#1 v1.5 + SHA-256.
static async rsaGenerateKeyPair(bits: number): Promise<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 = await gen.generateKeyPair();
const pair: RawKeyPair = {
pri: kp.priKey.getEncoded().data,
pub: kp.pubKey.getEncoded().data
};
return pair;
}
private static rsaBitsFromDer(der: Uint8Array): number {
// First INTEGER with a 2-byte DER length (>=256 content bytes) is the
// modulus; version (len 1) and exponent (len 3) never match.
for (let i = 0; i + 4 < der.length; i++) {
if (der[i] === 0x02 && der[i + 1] === 0x82) {
const intLen: number = der[i + 2] * 256 + der[i + 3];
let magLen: number = intLen;
if (der[i + 4] === 0x00) {
magLen -= 1;
}
return magLen * 8;
}
}
throw new Error('CryptoAdapter: cannot locate RSA modulus in DER');
}
static async rsaSignPkcs1Sha256(priDer: Uint8Array, data: Uint8Array): Promise<Uint8Array> {
const bits: number = CryptoAdapter.rsaBitsFromDer(priDer);
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator(`RSA${bits}`);
const kp: cryptoFramework.KeyPair = await gen.convertKey(null, { data: priDer });
const signer: cryptoFramework.Sign = cryptoFramework.createSign(`RSA${bits}|PKCS1|SHA256`);
await signer.init(kp.priKey);
const sig: cryptoFramework.DataBlob = await signer.sign({ data: data });
return sig.data;
}
static async rsaVerifyPkcs1Sha256(pubDer: Uint8Array, data: Uint8Array, sig: Uint8Array): Promise<boolean> {
const bits: number = CryptoAdapter.rsaBitsFromDer(pubDer);
const gen: cryptoFramework.AsyKeyGenerator = cryptoFramework.createAsyKeyGenerator(`RSA${bits}`);
const kp: cryptoFramework.KeyPair = await gen.convertKey({ data: pubDer }, null);
const verifier: cryptoFramework.Verify = cryptoFramework.createVerify(`RSA${bits}|PKCS1|SHA256`);
await verifier.init(kp.pubKey);
const ok: boolean = await verifier.verify({ data: data }, { data: sig });
return ok;
}
// ------------------------------------------------------------- DER helpers
private static wrapSpki(raw: Uint8Array, prefix: Uint8Array): Uint8Array {
return concatBytes(prefix, raw);
}
private static unwrapSpki(der: Uint8Array, prefix: Uint8Array): Uint8Array {
if (der.length <= prefix.length) {
throw new Error('CryptoAdapter: SPKI DER too short');
}
for (let i = 0; i < prefix.length; i++) {
if (der[i] !== prefix[i]) {
throw new Error(`CryptoAdapter: unexpected SPKI prefix at byte ${i}`);
}
}
return der.slice(prefix.length);
}
private static wrapPkcs8(raw: Uint8Array, prefix: Uint8Array): Uint8Array {
return concatBytes(prefix, raw);
}
private static unwrapPkcs8(der: Uint8Array, prefix: Uint8Array): Uint8Array {
if (der.length <= prefix.length) {
throw new Error('CryptoAdapter: PKCS8 DER too short');
}
for (let i = 0; i < prefix.length; i++) {
if (der[i] !== prefix[i]) {
throw new Error(`CryptoAdapter: unexpected PKCS8 prefix at byte ${i}`);
}
}
return der.slice(prefix.length);
}
/**
* P-256 PKCS#8 has a variable-length layout: the private key INTEGER gets
* a 0x00 sign byte when the scalar's MSB is set, shifting the outer SEQUENCE
* length. Build it dynamically instead of using a fixed prefix.
*/
private static buildP256Pkcs8(scalar: Uint8Array): Uint8Array {
const content: Uint8Array = scalar[0] >= 0x80 ? concatBytes(new Uint8Array([0]), scalar) : scalar;
// inner = 02 01 01 || 04 <len> content || tail ; len < 128 guaranteed
const innerLen: number = 3 + 2 + content.length + DerPrefix.P256_PKCS8_TAIL.length;
const out: Uint8Array = new Uint8Array(2 + innerLen);
out[0] = 0x30;
out[1] = innerLen;
out[2] = 0x02;
out[3] = 0x01;
out[4] = 0x01;
out[5] = 0x04;
out[6] = content.length;
out.set(content, 7);
out.set(DerPrefix.P256_PKCS8_TAIL, 7 + content.length);
return out;
}
/** Extract the 32-byte scalar from a P-256 PKCS#8 DER blob. */
private static extractP256Scalar(der: Uint8Array): Uint8Array {
// 30 <len> 02 01 01 04 <octLen> <scalar...> a0 0a ...
if (der.length < 8 || der[0] !== 0x30 || der[2] !== 0x02 || der[5] !== 0x04) {
throw new Error('CryptoAdapter: unrecognized P-256 PKCS8');
}
const octLen: number = der[6];
let scalar: Uint8Array = der.slice(7, 7 + octLen);
if (octLen === 33 && scalar[0] === 0x00) {
scalar = scalar.slice(1);
}
if (scalar.length !== 32) {
throw new Error(`CryptoAdapter: P-256 scalar length ${scalar.length}`);
}
return scalar;
}
}
@@ -1,5 +1,6 @@
{
"src": [
"pages/Index"
"pages/Index",
"pages/DiagPage"
]
}