generated from ali/HarmonyTemplate
T6: user auth (none/publickey/password), session channel, keepalive, SshSession facade
- Auth.ts: SERVICE_REQUEST handshake, none probe, publickey query + signed request (sig over string(session_id) || payload-without-signature; Ed25519 raw / ECDSA DER->mpint r||s / RSA PKCS1 SHA256/512), password fallback; skip-list wait loop (DISCONNECT/IGNORE/UNIMPLEMENTED/DEBUG/ EXT_INFO/BANNER); msg60 dual meaning handled per phase - Channel.ts: open/confirm, pty-req/shell/exec/window-change, chunked flow-controlled write, WINDOW_ADJUST at half local window, stderr via EXTENDED_DATA, exit-status, EOF/CLOSE lifecycle, per-channel promise slots (never overlaps transport.waitPacket) - KeepAlive.ts: keepalive@openssh.com global request every 15s, dead after 3 unanswered probes - SshSession.ts: state machine (IDLE..CLOSED), KEX with TOFU host key verify, post-auth dispatcher routes keepalive replies + channel packets, server channels/global requests refused, execCommand collects stdout/stderr/exitStatus - Transport.ts: fix stale waitPacket timer rejecting a fresh waiter (clear timer on resolve/reject/re-arm) - latent since T3, amplified by the T6 auth loop - DiagPage: username/password inputs + button 10 (connect -> auth -> exec 'echo haven-ok && uname -a')
This commit is contained in:
@@ -19,6 +19,8 @@ import { ClientProposals } from '../ssh/Algorithms';
|
|||||||
import { KexEngine, KexResult, parseExtInfo } from '../ssh/Kex';
|
import { KexEngine, KexResult, parseExtInfo } from '../ssh/Kex';
|
||||||
import { verifyHostKeyTofu, InMemoryKnownHostStore, HostKeyDecider, HostKeyPrompt,
|
import { verifyHostKeyTofu, InMemoryKnownHostStore, HostKeyDecider, HostKeyPrompt,
|
||||||
HostKeyDecision, HostKeyStatus } from '../ssh/HostKeyVerifier';
|
HostKeyDecision, HostKeyStatus } from '../ssh/HostKeyVerifier';
|
||||||
|
import { SshSession, SshSessionOptions, ExecResult } from '../ssh/SshSession';
|
||||||
|
import { AuthResult } from '../ssh/Auth';
|
||||||
import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual, concatBytes, SshWriter } from '../ssh/SshWire';
|
import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual, concatBytes, SshWriter } from '../ssh/SshWire';
|
||||||
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
|
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
|
||||||
import { BusinessError } from '@kit.BasicServicesKit';
|
import { BusinessError } from '@kit.BasicServicesKit';
|
||||||
@@ -28,6 +30,8 @@ import { BusinessError } from '@kit.BasicServicesKit';
|
|||||||
struct DiagPage {
|
struct DiagPage {
|
||||||
@State host: string = '';
|
@State host: string = '';
|
||||||
@State port: string = '22';
|
@State port: string = '22';
|
||||||
|
@State username: string = '';
|
||||||
|
@State password: string = '';
|
||||||
@State logText: string = '';
|
@State logText: string = '';
|
||||||
@State busy: boolean = false;
|
@State busy: boolean = false;
|
||||||
private scroller: Scroller = new Scroller();
|
private scroller: Scroller = new Scroller();
|
||||||
@@ -65,6 +69,23 @@ struct DiagPage {
|
|||||||
}
|
}
|
||||||
.width('100%')
|
.width('100%')
|
||||||
|
|
||||||
|
Row({ space: 8 }) {
|
||||||
|
TextInput({ placeholder: '用户名', text: this.username })
|
||||||
|
.layoutWeight(1)
|
||||||
|
.height(44)
|
||||||
|
.onChange((value: string) => {
|
||||||
|
this.username = value;
|
||||||
|
})
|
||||||
|
TextInput({ placeholder: '密码', text: this.password })
|
||||||
|
.layoutWeight(1)
|
||||||
|
.height(44)
|
||||||
|
.type(InputType.Password)
|
||||||
|
.onChange((value: string) => {
|
||||||
|
this.password = value;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
.width('100%')
|
||||||
|
|
||||||
Column({ space: 8 }) {
|
Column({ space: 8 }) {
|
||||||
Button('1. TCP 连接与 SSH Banner')
|
Button('1. TCP 连接与 SSH Banner')
|
||||||
.width('100%')
|
.width('100%')
|
||||||
@@ -111,6 +132,11 @@ struct DiagPage {
|
|||||||
.onClick(() => {
|
.onClick(() => {
|
||||||
this.runTest((): Promise<void> => this.testLiveKex());
|
this.runTest((): Promise<void> => this.testLiveKex());
|
||||||
})
|
})
|
||||||
|
Button('10. 认证 + 执行命令 (用户名/密码)')
|
||||||
|
.width('100%')
|
||||||
|
.onClick(() => {
|
||||||
|
this.runTest((): Promise<void> => this.testLiveAuth());
|
||||||
|
})
|
||||||
}
|
}
|
||||||
.width('100%')
|
.width('100%')
|
||||||
|
|
||||||
@@ -751,4 +777,48 @@ struct DiagPage {
|
|||||||
transport.close();
|
transport.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 10) Full session: connect → KEX (TOFU) → password auth → exec. */
|
||||||
|
private async testLiveAuth(): Promise<void> {
|
||||||
|
const host: string = this.host.trim();
|
||||||
|
if (host.length === 0) {
|
||||||
|
this.log('FAIL', '请先输入 SSH 服务器地址');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const username: string = this.username.trim();
|
||||||
|
if (username.length === 0) {
|
||||||
|
this.log('FAIL', '请先输入用户名');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const port: number = this.parsePort();
|
||||||
|
this.log('INFO', `连接 ${host}:${port} → KEX → 认证 → exec ...`);
|
||||||
|
const store: InMemoryKnownHostStore = new InMemoryKnownHostStore();
|
||||||
|
const decider: HostKeyDecider = {
|
||||||
|
decide: async (prompt: HostKeyPrompt): Promise<HostKeyDecision> => {
|
||||||
|
this.log('INFO', `主机密钥 [${prompt.status}] ${prompt.hostPort} (${prompt.keyAlgo})`);
|
||||||
|
this.log('INFO', `指纹: ${prompt.fingerprint}`);
|
||||||
|
return HostKeyDecision.ACCEPT_ONCE;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const options: SshSessionOptions = {
|
||||||
|
knownHostStore: store,
|
||||||
|
hostKeyDecider: decider
|
||||||
|
};
|
||||||
|
const session: SshSession = new SshSession(options);
|
||||||
|
try {
|
||||||
|
await session.connect(host, port);
|
||||||
|
this.log('INFO', 'KEX 完成,开始认证 ...');
|
||||||
|
const auth: AuthResult = await session.authenticate(username, this.password, null);
|
||||||
|
this.log('INFO', `认证成功 (方式: ${auth.method})`);
|
||||||
|
const result: ExecResult = await session.execCommand('echo haven-ok && uname -a', 15000);
|
||||||
|
this.log('INFO', `exitStatus: ${result.exitStatus}`);
|
||||||
|
this.log('INFO', `stdout: ${this.trunc(result.stdout, 200)}`);
|
||||||
|
if (result.stderr.length > 0) {
|
||||||
|
this.log('INFO', `stderr: ${this.trunc(result.stderr, 200)}`);
|
||||||
|
}
|
||||||
|
this.log('PASS', '完整会话流程通过 ✓');
|
||||||
|
} finally {
|
||||||
|
session.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,284 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2026 Haven for HarmonyOS contributors.
|
||||||
|
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SSH user authentication (RFC 4252): service request, "none" probe,
|
||||||
|
* publickey (server query + signed request, §7) and password (§8).
|
||||||
|
* Runs before the session dispatcher is installed: every inbound wait goes
|
||||||
|
* through SshTransport.waitPacket with a skip list for connection
|
||||||
|
* management messages (DISCONNECT/IGNORE/UNIMPLEMENTED/DEBUG/EXT_INFO);
|
||||||
|
* USERAUTH_BANNER texts are forwarded to the caller.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { SshTransport } from './Transport';
|
||||||
|
import { SshMsg, SshServiceName, disconnectReason } from './SshTypes';
|
||||||
|
import { SshReader, SshWriter } from './SshWire';
|
||||||
|
import { parseExtInfo } from './Kex';
|
||||||
|
import { CryptoAdapter } from './crypto/CryptoAdapter';
|
||||||
|
import { DerUtils, EcdsaParts } from './crypto/DerUtils';
|
||||||
|
import { buildPublicKeyBlob, PublicKeyMaterial } from './crypto/KeyImport';
|
||||||
|
import { Log } from '../common/Log';
|
||||||
|
|
||||||
|
/** Skip-list round cap so a hostile server cannot loop the auth wait. */
|
||||||
|
const MAX_SKIP_ROUNDS: number = 64;
|
||||||
|
|
||||||
|
/** Client private key material ready for USERAUTH_REQUEST signing. */
|
||||||
|
export interface ClientPrivateKey {
|
||||||
|
/** Outward name: ssh-ed25519 | ecdsa-sha2-nistp256 | rsa-sha2-256 | rsa-sha2-512. */
|
||||||
|
algo: string;
|
||||||
|
/** Ed25519: raw 32 bytes; ECDSA P-256: 32-byte scalar; RSA: PKCS#8 DER. */
|
||||||
|
pri: Uint8Array;
|
||||||
|
/** SSH public key blob as sent on the wire (RFC 4253 §6.6). */
|
||||||
|
pubBlob: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Result of a successful authentication. */
|
||||||
|
export interface AuthResult {
|
||||||
|
/** Method the server accepted: 'none' | 'publickey' | 'password'. */
|
||||||
|
method: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wrap raw key material as a ClientPrivateKey. `algo` is the outward
|
||||||
|
* algorithm name; `pub` holds the parsed public parts (see KeyImport).
|
||||||
|
*/
|
||||||
|
export function buildClientPrivateKey(algo: string, pri: Uint8Array,
|
||||||
|
pub: PublicKeyMaterial): ClientPrivateKey {
|
||||||
|
const key: ClientPrivateKey = {
|
||||||
|
algo: algo,
|
||||||
|
pri: pri,
|
||||||
|
pubBlob: buildPublicKeyBlob(algo, pub)
|
||||||
|
};
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UserAuthEngine {
|
||||||
|
private static readonly TAG: string = 'UserAuth';
|
||||||
|
|
||||||
|
private readonly transport: SshTransport;
|
||||||
|
private readonly sessionId: Uint8Array;
|
||||||
|
|
||||||
|
constructor(transport: SshTransport, sessionId: Uint8Array) {
|
||||||
|
this.transport = transport;
|
||||||
|
this.sessionId = sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate `username`: "none" probe, then publickey (when a key is
|
||||||
|
* supplied and offered), then password. `onBanner` receives
|
||||||
|
* USERAUTH_BANNER texts. Throws on rejection, disconnect or timeout.
|
||||||
|
*/
|
||||||
|
async authenticate(username: string, password: string, privateKey: ClientPrivateKey | null,
|
||||||
|
timeoutMs: number, onBanner: ((message: string) => void) | null): Promise<AuthResult> {
|
||||||
|
await this.requestService(timeoutMs);
|
||||||
|
|
||||||
|
// "none" probe (RFC 4252 §5.2): either a surprise success or the
|
||||||
|
// server's list of acceptable methods.
|
||||||
|
const none: SshWriter = this.authHeader(username, 'none');
|
||||||
|
await this.transport.sendPacket(none.toBytes());
|
||||||
|
let reply: Uint8Array = await this.waitAuthReply(timeoutMs, onBanner);
|
||||||
|
if (reply[0] === SshMsg.USERAUTH_SUCCESS) {
|
||||||
|
const byNone: AuthResult = { method: 'none' };
|
||||||
|
return byNone;
|
||||||
|
}
|
||||||
|
if (reply[0] !== SshMsg.USERAUTH_FAILURE) {
|
||||||
|
throw new Error(`UserAuth: unexpected msg ${reply[0]} after none probe`);
|
||||||
|
}
|
||||||
|
let methods: string[] = this.parseFailureMethods(reply);
|
||||||
|
Log.debug(UserAuthEngine.TAG, `server auth methods: ${methods.join(',')}`);
|
||||||
|
|
||||||
|
// publickey (RFC 4252 §7): server query, then the signed request.
|
||||||
|
if (privateKey !== null && methods.indexOf('publickey') >= 0) {
|
||||||
|
const query: SshWriter = this.authHeader(username, 'publickey');
|
||||||
|
query.writeBoolean(false);
|
||||||
|
query.writeString(privateKey.algo);
|
||||||
|
query.writeStringBytes(privateKey.pubBlob);
|
||||||
|
await this.transport.sendPacket(query.toBytes());
|
||||||
|
reply = await this.waitAuthReply(timeoutMs, onBanner);
|
||||||
|
if (reply[0] === SshMsg.USERAUTH_PK_OK) {
|
||||||
|
// Signed bytes = string(session_id) || the whole request payload
|
||||||
|
// without the trailing signature string (RFC 4252 §7).
|
||||||
|
const request: SshWriter = this.authHeader(username, 'publickey');
|
||||||
|
request.writeBoolean(true);
|
||||||
|
request.writeString(privateKey.algo);
|
||||||
|
request.writeStringBytes(privateKey.pubBlob);
|
||||||
|
const signedData: Uint8Array = this.buildSignedData(request.toBytes());
|
||||||
|
const sigBlob: Uint8Array = await this.signRequest(privateKey, signedData);
|
||||||
|
request.writeStringBytes(sigBlob);
|
||||||
|
await this.transport.sendPacket(request.toBytes());
|
||||||
|
reply = await this.waitAuthReply(timeoutMs, onBanner);
|
||||||
|
if (reply[0] === SshMsg.USERAUTH_SUCCESS) {
|
||||||
|
const byKey: AuthResult = { method: 'publickey' };
|
||||||
|
return byKey;
|
||||||
|
}
|
||||||
|
if (reply[0] !== SshMsg.USERAUTH_FAILURE) {
|
||||||
|
throw new Error(`UserAuth: unexpected msg ${reply[0]} after publickey request`);
|
||||||
|
}
|
||||||
|
methods = this.parseFailureMethods(reply);
|
||||||
|
Log.info(UserAuthEngine.TAG, `publickey rejected; methods left: ${methods.join(',')}`);
|
||||||
|
} else if (reply[0] === SshMsg.USERAUTH_FAILURE) {
|
||||||
|
methods = this.parseFailureMethods(reply);
|
||||||
|
Log.info(UserAuthEngine.TAG, `publickey query refused; methods: ${methods.join(',')}`);
|
||||||
|
} else {
|
||||||
|
throw new Error(`UserAuth: unexpected msg ${reply[0]} after publickey query`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// password (RFC 4252 §8). Value 60 in this phase is
|
||||||
|
// SSH_MSG_USERAUTH_PASSWD_CHANGEREQ (§8), not PK_OK.
|
||||||
|
if (password.length > 0 && methods.indexOf('password') >= 0) {
|
||||||
|
const pw: SshWriter = this.authHeader(username, 'password');
|
||||||
|
pw.writeBoolean(false);
|
||||||
|
pw.writeString(password);
|
||||||
|
await this.transport.sendPacket(pw.toBytes());
|
||||||
|
reply = await this.waitAuthReply(timeoutMs, onBanner);
|
||||||
|
if (reply[0] === SshMsg.USERAUTH_SUCCESS) {
|
||||||
|
const byPassword: AuthResult = { method: 'password' };
|
||||||
|
return byPassword;
|
||||||
|
}
|
||||||
|
if (reply[0] === SshMsg.USERAUTH_INFO_REQUEST) {
|
||||||
|
throw new Error('UserAuth: server requires a password change (unsupported)');
|
||||||
|
}
|
||||||
|
if (reply[0] === SshMsg.USERAUTH_FAILURE) {
|
||||||
|
throw new Error('UserAuth: password rejected');
|
||||||
|
}
|
||||||
|
throw new Error(`UserAuth: unexpected msg ${reply[0]} after password`);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`UserAuth: no usable auth method (server offers: ${methods.join(',')})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** SSH_MSG_SERVICE_REQUEST 'ssh-userauth' → SSH_MSG_SERVICE_ACCEPT. */
|
||||||
|
private async requestService(timeoutMs: number): Promise<void> {
|
||||||
|
const w: SshWriter = new SshWriter(32);
|
||||||
|
w.writeByte(SshMsg.SERVICE_REQUEST);
|
||||||
|
w.writeString(SshServiceName.USER_AUTH);
|
||||||
|
await this.transport.sendPacket(w.toBytes());
|
||||||
|
for (let round: number = 0; round < MAX_SKIP_ROUNDS; round++) {
|
||||||
|
const payload: Uint8Array = await this.transport.waitPacket(timeoutMs);
|
||||||
|
const msg: number = payload[0];
|
||||||
|
if (msg === SshMsg.DISCONNECT) {
|
||||||
|
throw this.parseDisconnect(payload);
|
||||||
|
}
|
||||||
|
if (msg === SshMsg.IGNORE || msg === SshMsg.UNIMPLEMENTED ||
|
||||||
|
msg === SshMsg.DEBUG_MSG || msg === SshMsg.EXT_INFO) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (msg === SshMsg.SERVICE_ACCEPT) {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
const svc: string = r.readString();
|
||||||
|
if (svc !== SshServiceName.USER_AUTH) {
|
||||||
|
throw new Error(`UserAuth: service accepted '${svc}' != '${SshServiceName.USER_AUTH}'`);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new Error(`UserAuth: unexpected msg ${msg} after SERVICE_REQUEST`);
|
||||||
|
}
|
||||||
|
throw new Error('UserAuth: too many skipped packets waiting for SERVICE_ACCEPT');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Next auth-phase reply, skipping connection management messages.
|
||||||
|
* DISCONNECT aborts; USERAUTH_BANNER goes to onBanner; EXT_INFO is
|
||||||
|
* informational only (RFC 8308).
|
||||||
|
*/
|
||||||
|
private async waitAuthReply(timeoutMs: number,
|
||||||
|
onBanner: ((message: string) => void) | null): Promise<Uint8Array> {
|
||||||
|
for (let round: number = 0; round < MAX_SKIP_ROUNDS; round++) {
|
||||||
|
const payload: Uint8Array = await this.transport.waitPacket(timeoutMs);
|
||||||
|
const msg: number = payload[0];
|
||||||
|
if (msg === SshMsg.DISCONNECT) {
|
||||||
|
throw this.parseDisconnect(payload);
|
||||||
|
}
|
||||||
|
if (msg === SshMsg.IGNORE || msg === SshMsg.UNIMPLEMENTED || msg === SshMsg.DEBUG_MSG) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (msg === SshMsg.EXT_INFO) {
|
||||||
|
const ext: Map<string, string> = parseExtInfo(payload);
|
||||||
|
Log.debug(UserAuthEngine.TAG, `EXT_INFO during auth: ${ext.size} entries`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (msg === SshMsg.USERAUTH_BANNER) {
|
||||||
|
if (onBanner !== null) {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
onBanner(r.readString());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
throw new Error('UserAuth: too many skipped packets during auth');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Common USERAUTH_REQUEST prefix: msg, user, service, method name. */
|
||||||
|
private authHeader(username: string, method: string): SshWriter {
|
||||||
|
const w: SshWriter = new SshWriter(64);
|
||||||
|
w.writeByte(SshMsg.USERAUTH_REQUEST);
|
||||||
|
w.writeString(username);
|
||||||
|
w.writeString(SshServiceName.CONNECTION);
|
||||||
|
w.writeString(method);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** string(session_id) || request payload (RFC 4252 §7 signature input). */
|
||||||
|
private buildSignedData(payloadWithoutSig: Uint8Array): Uint8Array {
|
||||||
|
const w: SshWriter = new SshWriter(this.sessionId.length + payloadWithoutSig.length + 8);
|
||||||
|
w.writeStringBytes(this.sessionId);
|
||||||
|
w.writeRaw(payloadWithoutSig);
|
||||||
|
return w.toBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signature blob for USERAUTH_REQUEST: string(sigAlgo) + string(sig).
|
||||||
|
* Ed25519 yields raw 64 bytes; ECDSA converts the platform DER output to
|
||||||
|
* mpint r||s (RFC 5656 §3.1.2); RSA uses PKCS#1 v1.5 with the hash
|
||||||
|
* matching the rsa-sha2-* name (RFC 8332 §3).
|
||||||
|
*/
|
||||||
|
private async signRequest(key: ClientPrivateKey, signedData: Uint8Array): Promise<Uint8Array> {
|
||||||
|
let sig: Uint8Array = new Uint8Array(0);
|
||||||
|
if (key.algo === 'ssh-ed25519') {
|
||||||
|
sig = await CryptoAdapter.ed25519Sign(key.pri, signedData);
|
||||||
|
} else if (key.algo === 'ecdsa-sha2-nistp256') {
|
||||||
|
const der: Uint8Array = CryptoAdapter.ecdsaP256SignSync(key.pri, signedData);
|
||||||
|
const parts: EcdsaParts = DerUtils.ecdsaPartsFromDer(der);
|
||||||
|
const w: SshWriter = new SshWriter(72);
|
||||||
|
w.writeMpint(parts.r);
|
||||||
|
w.writeMpint(parts.s);
|
||||||
|
sig = w.toBytes();
|
||||||
|
} else if (key.algo === 'rsa-sha2-256' || key.algo === 'rsa-sha2-512') {
|
||||||
|
const hash: string = key.algo === 'rsa-sha2-512' ? 'SHA512' : 'SHA256';
|
||||||
|
sig = CryptoAdapter.rsaSignPkcs1Sync(key.pri, signedData, hash);
|
||||||
|
} else {
|
||||||
|
throw new Error(`UserAuth: unsupported private key algorithm '${key.algo}'`);
|
||||||
|
}
|
||||||
|
const blob: SshWriter = new SshWriter(sig.length + key.algo.length + 12);
|
||||||
|
blob.writeString(key.algo);
|
||||||
|
blob.writeStringBytes(sig);
|
||||||
|
return blob.toBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** USERAUTH_FAILURE → method name list; logs partial success. */
|
||||||
|
private parseFailureMethods(payload: Uint8Array): string[] {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
const list: string = r.readString();
|
||||||
|
const partial: boolean = r.readBoolean();
|
||||||
|
if (partial) {
|
||||||
|
Log.info(UserAuthEngine.TAG, 'server reports partial success');
|
||||||
|
}
|
||||||
|
return list.length === 0 ? [] : list.split(',');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** DISCONNECT → Error with the reason code and description. */
|
||||||
|
private parseDisconnect(payload: Uint8Array): Error {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
const code: number = r.readUint32();
|
||||||
|
const reason: string = r.readString();
|
||||||
|
return new Error(`server disconnected: ${disconnectReason(code)} (${reason})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,477 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2026 Haven for HarmonyOS contributors.
|
||||||
|
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SSH "session" channel (RFC 4254 §5): open/confirmation, flow-controlled
|
||||||
|
* DATA both ways, channel requests (pty-req / shell / exec /
|
||||||
|
* window-change, §5.4/§6) and the EOF/CLOSE lifecycle. Inbound packets are
|
||||||
|
* routed here by SshSession's dispatcher; replies are awaited through
|
||||||
|
* per-channel promise slots, never through SshTransport.waitPacket (the
|
||||||
|
* dispatcher is already installed while channels are live).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { SshTransport } from './Transport';
|
||||||
|
import { SshMsg } from './SshTypes';
|
||||||
|
import { SshReader, SshWriter } from './SshWire';
|
||||||
|
import { Log } from '../common/Log';
|
||||||
|
|
||||||
|
/** Local receive window and max packet we advertise (2 MiB / 32 KiB). */
|
||||||
|
const LOCAL_WINDOW: number = 2097152;
|
||||||
|
const LOCAL_MAX_PACKET: number = 32768;
|
||||||
|
/** Send WINDOW_ADJUST once half the local window has been consumed. */
|
||||||
|
const ADJUST_THRESHOLD: number = LOCAL_WINDOW / 2;
|
||||||
|
|
||||||
|
/** Inbound callbacks for one channel. */
|
||||||
|
export interface ChannelCallbacks {
|
||||||
|
onData: (data: Uint8Array) => void;
|
||||||
|
onExtendedData: (data: Uint8Array) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SshChannel {
|
||||||
|
private static readonly TAG: string = 'SshChannel';
|
||||||
|
|
||||||
|
readonly localId: number;
|
||||||
|
private readonly transport: SshTransport;
|
||||||
|
private readonly callbacks: ChannelCallbacks;
|
||||||
|
|
||||||
|
private remoteId: number = -1;
|
||||||
|
private remoteWindow: number = 0;
|
||||||
|
private remoteMaxPacket: number = 0;
|
||||||
|
private localWindowConsumed: number = 0;
|
||||||
|
private exitStatus: number = -1;
|
||||||
|
|
||||||
|
private closed: boolean = false;
|
||||||
|
private sentClose: boolean = false;
|
||||||
|
private eof: boolean = false;
|
||||||
|
|
||||||
|
private openResolve: (() => void) | undefined = undefined;
|
||||||
|
private openReject: ((err: Error) => void) | undefined = undefined;
|
||||||
|
private openTimerId: number = -1;
|
||||||
|
|
||||||
|
private replyResolve: ((ok: boolean) => void) | undefined = undefined;
|
||||||
|
private replyReject: ((err: Error) => void) | undefined = undefined;
|
||||||
|
private replyTimerId: number = -1;
|
||||||
|
|
||||||
|
private readonly windowWaiters: Array<() => void> = [];
|
||||||
|
private readonly closedWaiters: Array<(v: boolean) => void> = [];
|
||||||
|
|
||||||
|
constructor(transport: SshTransport, localId: number, callbacks: ChannelCallbacks) {
|
||||||
|
this.transport = transport;
|
||||||
|
this.localId = localId;
|
||||||
|
this.callbacks = callbacks;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Open the channel and wait for the server's confirmation. */
|
||||||
|
async open(timeoutMs: number): Promise<void> {
|
||||||
|
const w: SshWriter = new SshWriter(48);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_OPEN);
|
||||||
|
w.writeString('session');
|
||||||
|
w.writeUint32(this.localId);
|
||||||
|
w.writeUint32(LOCAL_WINDOW);
|
||||||
|
w.writeUint32(LOCAL_MAX_PACKET);
|
||||||
|
const opened: Promise<void> = new Promise<void>((resolve: () => void,
|
||||||
|
reject: (err: Error) => void): void => {
|
||||||
|
this.openResolve = resolve;
|
||||||
|
this.openReject = reject;
|
||||||
|
this.openTimerId = setTimeout((): void => {
|
||||||
|
if (this.openReject !== undefined) {
|
||||||
|
this.openReject(new Error('SshChannel: open confirmation timeout'));
|
||||||
|
this.openResolve = undefined;
|
||||||
|
this.openReject = undefined;
|
||||||
|
}
|
||||||
|
}, timeoutMs);
|
||||||
|
});
|
||||||
|
await this.transport.sendPacket(w.toBytes());
|
||||||
|
await opened;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** pty-req (RFC 4254 §6.2), want_reply = true. */
|
||||||
|
async requestPty(cols: number, rows: number, timeoutMs: number): Promise<boolean> {
|
||||||
|
const w: SshWriter = new SshWriter(80);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_REQUEST);
|
||||||
|
w.writeUint32(this.remoteId);
|
||||||
|
w.writeString('pty-req');
|
||||||
|
w.writeBoolean(true);
|
||||||
|
w.writeString('xterm-256color');
|
||||||
|
w.writeUint32(cols);
|
||||||
|
w.writeUint32(rows);
|
||||||
|
w.writeUint32(0); // pixel width
|
||||||
|
w.writeUint32(0); // pixel height
|
||||||
|
w.writeString(''); // no terminal modes
|
||||||
|
await this.transport.sendPacket(w.toBytes());
|
||||||
|
return this.waitReply('pty-req', timeoutMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** shell request (RFC 4254 §6.1), want_reply = true. */
|
||||||
|
async requestShell(timeoutMs: number): Promise<boolean> {
|
||||||
|
const w: SshWriter = new SshWriter(32);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_REQUEST);
|
||||||
|
w.writeUint32(this.remoteId);
|
||||||
|
w.writeString('shell');
|
||||||
|
w.writeBoolean(true);
|
||||||
|
await this.transport.sendPacket(w.toBytes());
|
||||||
|
return this.waitReply('shell', timeoutMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** exec request (RFC 4254 §6.5), want_reply = true. */
|
||||||
|
async exec(command: string, timeoutMs: number): Promise<boolean> {
|
||||||
|
const w: SshWriter = new SshWriter(command.length + 32);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_REQUEST);
|
||||||
|
w.writeUint32(this.remoteId);
|
||||||
|
w.writeString('exec');
|
||||||
|
w.writeBoolean(true);
|
||||||
|
w.writeString(command);
|
||||||
|
await this.transport.sendPacket(w.toBytes());
|
||||||
|
return this.waitReply('exec', timeoutMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** window-change (RFC 4254 §6.7), fire and forget. */
|
||||||
|
async resize(cols: number, rows: number): Promise<void> {
|
||||||
|
if (this.closed || this.remoteId < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const w: SshWriter = new SshWriter(40);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_REQUEST);
|
||||||
|
w.writeUint32(this.remoteId);
|
||||||
|
w.writeString('window-change');
|
||||||
|
w.writeBoolean(false);
|
||||||
|
w.writeUint32(cols);
|
||||||
|
w.writeUint32(rows);
|
||||||
|
w.writeUint32(0);
|
||||||
|
w.writeUint32(0);
|
||||||
|
await this.transport.sendPacket(w.toBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flow-controlled write: chunks to min(remoteMaxPacket, LOCAL_MAX_PACKET,
|
||||||
|
* remoteWindow) and awaits while the remote window is exhausted.
|
||||||
|
*/
|
||||||
|
async write(data: Uint8Array): Promise<void> {
|
||||||
|
let offset: number = 0;
|
||||||
|
while (offset < data.length) {
|
||||||
|
if (this.closed) {
|
||||||
|
throw new Error('SshChannel: channel closed while writing');
|
||||||
|
}
|
||||||
|
if (this.remoteWindow <= 0) {
|
||||||
|
await this.waitForWindow();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const room: number = Math.min(this.remoteMaxPacket, LOCAL_MAX_PACKET,
|
||||||
|
this.remoteWindow, data.length - offset);
|
||||||
|
const chunk: Uint8Array = data.slice(offset, offset + room);
|
||||||
|
const w: SshWriter = new SshWriter(chunk.length + 16);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_DATA);
|
||||||
|
w.writeUint32(this.remoteId);
|
||||||
|
w.writeStringBytes(chunk);
|
||||||
|
await this.transport.sendPacket(w.toBytes());
|
||||||
|
this.remoteWindow -= room;
|
||||||
|
offset += room;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve once the peer sends CLOSE (immediately when already closed). */
|
||||||
|
async waitClosed(timeoutMs: number): Promise<void> {
|
||||||
|
if (this.closed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const closedPromise: Promise<boolean> = new Promise<boolean>((resolve: (v: boolean) => void): void => {
|
||||||
|
this.closedWaiters.push(resolve);
|
||||||
|
});
|
||||||
|
const timerPromise: Promise<boolean> = new Promise<boolean>((resolve: (v: boolean) => void): void => {
|
||||||
|
setTimeout((): void => {
|
||||||
|
resolve(false);
|
||||||
|
}, timeoutMs);
|
||||||
|
});
|
||||||
|
const first: boolean = await Promise.race([closedPromise, timerPromise]);
|
||||||
|
if (!first) {
|
||||||
|
throw new Error('SshChannel: timed out waiting for channel close');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Send CHANNEL_CLOSE and mark the channel dead (idempotent). */
|
||||||
|
async close(): Promise<void> {
|
||||||
|
if (this.sentClose) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.sentClose = true;
|
||||||
|
if (this.remoteId >= 0 && !this.transport.isClosed()) {
|
||||||
|
const w: SshWriter = new SshWriter(16);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_CLOSE);
|
||||||
|
w.writeUint32(this.remoteId);
|
||||||
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
||||||
|
sent.catch((e: Object): void => {
|
||||||
|
const err = e as Error;
|
||||||
|
Log.debug(SshChannel.TAG, `CHANNEL_CLOSE send failed: ${err.message}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.markClosed();
|
||||||
|
}
|
||||||
|
|
||||||
|
isClosed(): boolean {
|
||||||
|
return this.closed;
|
||||||
|
}
|
||||||
|
|
||||||
|
hasEof(): boolean {
|
||||||
|
return this.eof;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** exit-status from the server, or -1 when none arrived. */
|
||||||
|
getExitStatus(): number {
|
||||||
|
return this.exitStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Route one inbound packet (msg 91..100 with recipient == localId);
|
||||||
|
* called by SshSession's dispatcher only.
|
||||||
|
*/
|
||||||
|
handlePacket(payload: Uint8Array): void {
|
||||||
|
const msg: number = payload[0];
|
||||||
|
switch (msg) {
|
||||||
|
case SshMsg.CHANNEL_OPEN_CONFIRMATION:
|
||||||
|
this.onOpenConfirmation(payload);
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_OPEN_FAILURE:
|
||||||
|
this.onOpenFailure(payload);
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_WINDOW_ADJUST:
|
||||||
|
this.onWindowAdjust(payload);
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_DATA:
|
||||||
|
this.onData(payload, false);
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_EXTENDED_DATA:
|
||||||
|
this.onData(payload, true);
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_EOF:
|
||||||
|
this.eof = true;
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_CLOSE:
|
||||||
|
this.onPeerClose();
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_REQUEST:
|
||||||
|
this.onChannelRequest(payload);
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_SUCCESS:
|
||||||
|
this.onReply(true);
|
||||||
|
return;
|
||||||
|
case SshMsg.CHANNEL_FAILURE:
|
||||||
|
this.onReply(false);
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
Log.warn(SshChannel.TAG, `channel ${this.localId}: unexpected msg ${msg}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The transport died: mark dead without sending anything. */
|
||||||
|
handleSessionClosing(): void {
|
||||||
|
this.markClosed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- private
|
||||||
|
|
||||||
|
private onOpenConfirmation(payload: Uint8Array): void {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
r.readUint32(); // recipient = localId
|
||||||
|
this.remoteId = r.readUint32();
|
||||||
|
this.remoteWindow = r.readUint32();
|
||||||
|
this.remoteMaxPacket = r.readUint32();
|
||||||
|
if (this.openTimerId >= 0) {
|
||||||
|
clearTimeout(this.openTimerId);
|
||||||
|
this.openTimerId = -1;
|
||||||
|
}
|
||||||
|
const resolve: (() => void) | undefined = this.openResolve;
|
||||||
|
this.openResolve = undefined;
|
||||||
|
this.openReject = undefined;
|
||||||
|
if (resolve !== undefined) {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
Log.debug(SshChannel.TAG,
|
||||||
|
`channel ${this.localId} open (remote ${this.remoteId}, window ${this.remoteWindow})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private onOpenFailure(payload: Uint8Array): void {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
r.readUint32();
|
||||||
|
const code: number = r.readUint32();
|
||||||
|
const desc: string = r.readString();
|
||||||
|
if (this.openTimerId >= 0) {
|
||||||
|
clearTimeout(this.openTimerId);
|
||||||
|
this.openTimerId = -1;
|
||||||
|
}
|
||||||
|
const reject: ((err: Error) => void) | undefined = this.openReject;
|
||||||
|
this.openResolve = undefined;
|
||||||
|
this.openReject = undefined;
|
||||||
|
if (reject !== undefined) {
|
||||||
|
reject(new Error(`SshChannel: open failed (code ${code}: ${desc})`));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private onWindowAdjust(payload: Uint8Array): void {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
r.readUint32();
|
||||||
|
const inc: number = r.readUint32();
|
||||||
|
this.remoteWindow = Math.min(this.remoteWindow + inc, 4294967295);
|
||||||
|
this.flushWindowWaiters();
|
||||||
|
}
|
||||||
|
|
||||||
|
private onData(payload: Uint8Array, extended: boolean): void {
|
||||||
|
if (this.closed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
r.readUint32(); // recipient
|
||||||
|
if (extended) {
|
||||||
|
r.readUint32(); // data type code (1 = stderr)
|
||||||
|
}
|
||||||
|
const data: Uint8Array = r.readStringBytes();
|
||||||
|
this.localWindowConsumed += data.length;
|
||||||
|
if (this.localWindowConsumed >= ADJUST_THRESHOLD) {
|
||||||
|
this.sendWindowAdjust(this.localWindowConsumed);
|
||||||
|
this.localWindowConsumed = 0;
|
||||||
|
}
|
||||||
|
if (extended) {
|
||||||
|
this.callbacks.onExtendedData(data);
|
||||||
|
} else {
|
||||||
|
this.callbacks.onData(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private onPeerClose(): void {
|
||||||
|
if (!this.sentClose && !this.transport.isClosed()) {
|
||||||
|
this.sentClose = true;
|
||||||
|
const w: SshWriter = new SshWriter(16);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_CLOSE);
|
||||||
|
w.writeUint32(this.remoteId);
|
||||||
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
||||||
|
sent.catch((e: Object): void => {
|
||||||
|
const err = e as Error;
|
||||||
|
Log.debug(SshChannel.TAG, `CHANNEL_CLOSE reply failed: ${err.message}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.markClosed();
|
||||||
|
}
|
||||||
|
|
||||||
|
private onChannelRequest(payload: Uint8Array): void {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
r.readUint32(); // recipient
|
||||||
|
const type: string = r.readString();
|
||||||
|
const wantReply: boolean = r.readBoolean();
|
||||||
|
if (type === 'exit-status') {
|
||||||
|
this.exitStatus = r.readUint32();
|
||||||
|
Log.debug(SshChannel.TAG, `channel ${this.localId} exit-status ${this.exitStatus}`);
|
||||||
|
if (wantReply) {
|
||||||
|
this.sendChannelResult(true);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Log.debug(SshChannel.TAG, `channel ${this.localId}: request '${type}' ignored`);
|
||||||
|
if (wantReply) {
|
||||||
|
this.sendChannelResult(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private onReply(ok: boolean): void {
|
||||||
|
if (this.replyTimerId >= 0) {
|
||||||
|
clearTimeout(this.replyTimerId);
|
||||||
|
this.replyTimerId = -1;
|
||||||
|
}
|
||||||
|
const resolve: ((ok: boolean) => void) | undefined = this.replyResolve;
|
||||||
|
this.replyResolve = undefined;
|
||||||
|
this.replyReject = undefined;
|
||||||
|
if (resolve !== undefined) {
|
||||||
|
resolve(ok);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private waitReply(what: string, timeoutMs: number): Promise<boolean> {
|
||||||
|
return new Promise<boolean>((resolve: (ok: boolean) => void,
|
||||||
|
reject: (err: Error) => void): void => {
|
||||||
|
if (this.replyTimerId >= 0) {
|
||||||
|
clearTimeout(this.replyTimerId);
|
||||||
|
this.replyTimerId = -1;
|
||||||
|
}
|
||||||
|
this.replyResolve = resolve;
|
||||||
|
this.replyReject = reject;
|
||||||
|
this.replyTimerId = setTimeout((): void => {
|
||||||
|
if (this.replyReject !== undefined) {
|
||||||
|
this.replyReject(new Error(`SshChannel: '${what}' reply timeout`));
|
||||||
|
this.replyResolve = undefined;
|
||||||
|
this.replyReject = undefined;
|
||||||
|
}
|
||||||
|
}, timeoutMs);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private markClosed(): void {
|
||||||
|
if (this.closed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.closed = true;
|
||||||
|
if (this.openTimerId >= 0) {
|
||||||
|
clearTimeout(this.openTimerId);
|
||||||
|
this.openTimerId = -1;
|
||||||
|
}
|
||||||
|
const openReject: ((err: Error) => void) | undefined = this.openReject;
|
||||||
|
this.openResolve = undefined;
|
||||||
|
this.openReject = undefined;
|
||||||
|
if (openReject !== undefined) {
|
||||||
|
openReject(new Error('SshChannel: channel closed before confirmation'));
|
||||||
|
}
|
||||||
|
// Pending channel requests die with the channel (reply slot cleared
|
||||||
|
// by onReply; a stale timer can no longer reject anything).
|
||||||
|
this.onReply(false);
|
||||||
|
this.flushWindowWaiters();
|
||||||
|
const waiters: Array<(v: boolean) => void> = this.closedWaiters.slice();
|
||||||
|
this.closedWaiters.splice(0, this.closedWaiters.length);
|
||||||
|
for (let i: number = 0; i < waiters.length; i++) {
|
||||||
|
waiters[i](true);
|
||||||
|
}
|
||||||
|
this.callbacks.onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
private waitForWindow(): Promise<void> {
|
||||||
|
return new Promise<void>((resolve: () => void): void => {
|
||||||
|
this.windowWaiters.push(resolve);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private flushWindowWaiters(): void {
|
||||||
|
const waiters: Array<() => void> = this.windowWaiters.slice();
|
||||||
|
this.windowWaiters.splice(0, this.windowWaiters.length);
|
||||||
|
for (let i: number = 0; i < waiters.length; i++) {
|
||||||
|
waiters[i]();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendWindowAdjust(delta: number): void {
|
||||||
|
const w: SshWriter = new SshWriter(16);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_WINDOW_ADJUST);
|
||||||
|
w.writeUint32(this.localId);
|
||||||
|
w.writeUint32(delta);
|
||||||
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
||||||
|
sent.catch((e: Object): void => {
|
||||||
|
const err = e as Error;
|
||||||
|
Log.debug(SshChannel.TAG, `WINDOW_ADJUST send failed: ${err.message}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendChannelResult(ok: boolean): void {
|
||||||
|
const w: SshWriter = new SshWriter(16);
|
||||||
|
w.writeByte(ok ? SshMsg.CHANNEL_SUCCESS : SshMsg.CHANNEL_FAILURE);
|
||||||
|
w.writeUint32(this.remoteId);
|
||||||
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
||||||
|
sent.catch((e: Object): void => {
|
||||||
|
const err = e as Error;
|
||||||
|
Log.debug(SshChannel.TAG, `channel result send failed: ${err.message}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2026 Haven for HarmonyOS contributors.
|
||||||
|
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Server liveness probe (RFC 4254 §4): sends a "keepalive@openssh.com"
|
||||||
|
* global request with want_reply every `intervalMs`; once
|
||||||
|
* `maxUnanswered` probes have gone unanswered the connection is presumed
|
||||||
|
* dead and `onDead` fires. Replies (REQUEST_SUCCESS/REQUEST_FAILURE) are
|
||||||
|
* routed here by SshSession's dispatcher.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { SshTransport } from './Transport';
|
||||||
|
import { SshMsg } from './SshTypes';
|
||||||
|
import { SshWriter } from './SshWire';
|
||||||
|
import { Log } from '../common/Log';
|
||||||
|
|
||||||
|
export class KeepAlive {
|
||||||
|
private static readonly TAG: string = 'KeepAlive';
|
||||||
|
static readonly REQUEST_NAME: string = 'keepalive@openssh.com';
|
||||||
|
|
||||||
|
private readonly transport: SshTransport;
|
||||||
|
private readonly intervalMs: number;
|
||||||
|
private readonly maxUnanswered: number;
|
||||||
|
private readonly onDead: (reason: string) => void;
|
||||||
|
|
||||||
|
private timerId: number = -1;
|
||||||
|
private unanswered: number = 0;
|
||||||
|
|
||||||
|
constructor(transport: SshTransport, intervalMs: number, maxUnanswered: number,
|
||||||
|
onDead: (reason: string) => void) {
|
||||||
|
this.transport = transport;
|
||||||
|
this.intervalMs = intervalMs;
|
||||||
|
this.maxUnanswered = maxUnanswered;
|
||||||
|
this.onDead = onDead;
|
||||||
|
}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
if (this.timerId >= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.unanswered = 0;
|
||||||
|
this.timerId = setInterval((): void => {
|
||||||
|
this.tick();
|
||||||
|
}, this.intervalMs);
|
||||||
|
Log.debug(KeepAlive.TAG, `started (${this.intervalMs} ms interval)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.timerId >= 0) {
|
||||||
|
clearInterval(this.timerId);
|
||||||
|
this.timerId = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Called by the dispatcher on REQUEST_SUCCESS / REQUEST_FAILURE. */
|
||||||
|
onReply(): void {
|
||||||
|
this.unanswered = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private tick(): void {
|
||||||
|
if (this.unanswered >= this.maxUnanswered) {
|
||||||
|
Log.warn(KeepAlive.TAG,
|
||||||
|
`no reply to ${this.unanswered} keepalives; connection presumed dead`);
|
||||||
|
this.stop();
|
||||||
|
this.onDead(`no reply to ${this.unanswered} keepalives`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.unanswered += 1;
|
||||||
|
const w: SshWriter = new SshWriter(48);
|
||||||
|
w.writeByte(SshMsg.GLOBAL_REQUEST);
|
||||||
|
w.writeString(KeepAlive.REQUEST_NAME);
|
||||||
|
w.writeBoolean(true);
|
||||||
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
||||||
|
sent.catch((e: Object): void => {
|
||||||
|
const err = e as Error;
|
||||||
|
Log.warn(KeepAlive.TAG, `keepalive send failed: ${err.message}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,412 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2026 Haven for HarmonyOS contributors.
|
||||||
|
* Port of Haven by GlassHaven (AGPL-3.0). See LICENSE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One SSH connection lifecycle: TCP → transport → KEX (host key TOFU) →
|
||||||
|
* user authentication → channel multiplexing. After authentication a
|
||||||
|
* single dispatcher routes every inbound packet (keepalive replies,
|
||||||
|
* channel traffic); SshTransport.waitPacket is never armed again once the
|
||||||
|
* dispatcher is installed, so the two consumers never overlap (see
|
||||||
|
* Transport.drainLoop, which delivers to both when both are set).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { TcpRawSocket } from './OhosTcpSocket';
|
||||||
|
import { SshTransport } from './Transport';
|
||||||
|
import { SshVersion, SshMsg, SshChannelFailureCode, disconnectReason } from './SshTypes';
|
||||||
|
import { KexEngine, KexResult, parseExtInfo } from './Kex';
|
||||||
|
import { KnownHostStore, HostKeyDecider, verifyHostKeyTofu } from './HostKeyVerifier';
|
||||||
|
import { UserAuthEngine, ClientPrivateKey, AuthResult } from './Auth';
|
||||||
|
import { SshChannel, ChannelCallbacks } from './Channel';
|
||||||
|
import { KeepAlive } from './KeepAlive';
|
||||||
|
import { SshReader, SshWriter, bytesToUtf8 } from './SshWire';
|
||||||
|
import { Log } from '../common/Log';
|
||||||
|
|
||||||
|
export enum SshSessionState {
|
||||||
|
IDLE = 'idle',
|
||||||
|
CONNECTING = 'connecting',
|
||||||
|
KEX = 'kex',
|
||||||
|
AUTHENTICATING = 'authenticating',
|
||||||
|
READY = 'ready',
|
||||||
|
CLOSED = 'closed',
|
||||||
|
ERROR = 'error'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SshSessionOptions {
|
||||||
|
knownHostStore: KnownHostStore;
|
||||||
|
hostKeyDecider: HostKeyDecider;
|
||||||
|
/** TCP + banner timeout (default 10000 ms). */
|
||||||
|
connectTimeoutMs?: number;
|
||||||
|
/** KEX timeout (default 20000 ms). */
|
||||||
|
kexTimeoutMs?: number;
|
||||||
|
/** Auth / channel handshake timeout (default 20000 ms). */
|
||||||
|
authTimeoutMs?: number;
|
||||||
|
/** Keepalive probe interval (default 15000 ms). */
|
||||||
|
keepAliveIntervalMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExecResult {
|
||||||
|
stdout: string;
|
||||||
|
stderr: string;
|
||||||
|
/** exit-status from the server, or -1 when none arrived. */
|
||||||
|
exitStatus: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SshSession {
|
||||||
|
private static readonly TAG: string = 'SshSession';
|
||||||
|
private static readonly DEFAULT_CONNECT_TIMEOUT: number = 10000;
|
||||||
|
private static readonly DEFAULT_KEX_TIMEOUT: number = 20000;
|
||||||
|
private static readonly DEFAULT_AUTH_TIMEOUT: number = 20000;
|
||||||
|
private static readonly DEFAULT_KEEPALIVE_INTERVAL: number = 15000;
|
||||||
|
private static readonly KEEPALIVE_MAX_UNANSWERED: number = 3;
|
||||||
|
|
||||||
|
private readonly options: SshSessionOptions;
|
||||||
|
private readonly socket: TcpRawSocket;
|
||||||
|
private readonly transport: SshTransport;
|
||||||
|
private readonly channels: SshChannel[] = [];
|
||||||
|
private readonly connectTimeoutMs: number;
|
||||||
|
private readonly kexTimeoutMs: number;
|
||||||
|
private readonly authTimeoutMs: number;
|
||||||
|
private readonly keepAliveIntervalMs: number;
|
||||||
|
|
||||||
|
private state: SshSessionState = SshSessionState.IDLE;
|
||||||
|
private sessionId: Uint8Array = new Uint8Array(0);
|
||||||
|
private keepAlive: KeepAlive | null = null;
|
||||||
|
private nextLocalId: number = 0;
|
||||||
|
private closed: boolean = false;
|
||||||
|
|
||||||
|
constructor(options: SshSessionOptions) {
|
||||||
|
this.options = options;
|
||||||
|
this.connectTimeoutMs = options.connectTimeoutMs === undefined ?
|
||||||
|
SshSession.DEFAULT_CONNECT_TIMEOUT : options.connectTimeoutMs;
|
||||||
|
this.kexTimeoutMs = options.kexTimeoutMs === undefined ?
|
||||||
|
SshSession.DEFAULT_KEX_TIMEOUT : options.kexTimeoutMs;
|
||||||
|
this.authTimeoutMs = options.authTimeoutMs === undefined ?
|
||||||
|
SshSession.DEFAULT_AUTH_TIMEOUT : options.authTimeoutMs;
|
||||||
|
this.keepAliveIntervalMs = options.keepAliveIntervalMs === undefined ?
|
||||||
|
SshSession.DEFAULT_KEEPALIVE_INTERVAL : options.keepAliveIntervalMs;
|
||||||
|
this.socket = new TcpRawSocket();
|
||||||
|
this.transport = new SshTransport(this.socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
getState(): SshSessionState {
|
||||||
|
return this.state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TCP + banner + full KEX with host key verification (TOFU). */
|
||||||
|
async connect(host: string, port: number): Promise<void> {
|
||||||
|
if (this.state !== SshSessionState.IDLE) {
|
||||||
|
throw new Error(`SshSession: connect() requires IDLE state (got ${this.state})`);
|
||||||
|
}
|
||||||
|
this.setState(SshSessionState.CONNECTING);
|
||||||
|
try {
|
||||||
|
await this.socket.connect(host, port, this.connectTimeoutMs);
|
||||||
|
const serverBanner: string =
|
||||||
|
await this.transport.start(SshVersion.CLIENT_BANNER, this.connectTimeoutMs);
|
||||||
|
this.setState(SshSessionState.KEX);
|
||||||
|
const engine: KexEngine = new KexEngine(this.transport,
|
||||||
|
(algo: string, blob: Uint8Array, fp: string): Promise<boolean> => {
|
||||||
|
return verifyHostKeyTofu(this.options.knownHostStore, this.options.hostKeyDecider,
|
||||||
|
host, port, algo, blob).then((): boolean => true);
|
||||||
|
});
|
||||||
|
const result: KexResult =
|
||||||
|
await engine.run(SshVersion.CLIENT_BANNER, serverBanner, this.kexTimeoutMs);
|
||||||
|
this.sessionId = result.sessionId;
|
||||||
|
this.transport.onClose((reason: string): void => {
|
||||||
|
this.handleTransportClosed(reason);
|
||||||
|
});
|
||||||
|
Log.info(SshSession.TAG, `connected to ${host}:${port} (kex ${result.negotiated.kex})`);
|
||||||
|
} catch (e) {
|
||||||
|
this.setState(SshSessionState.ERROR);
|
||||||
|
this.transport.close();
|
||||||
|
throw e as Error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* User authentication; on success installs the packet dispatcher and
|
||||||
|
* starts the keepalive probe.
|
||||||
|
*/
|
||||||
|
async authenticate(username: string, password: string,
|
||||||
|
privateKey: ClientPrivateKey | null): Promise<AuthResult> {
|
||||||
|
if (this.state !== SshSessionState.KEX) {
|
||||||
|
throw new Error(`SshSession: authenticate() requires KEX-complete state (got ${this.state})`);
|
||||||
|
}
|
||||||
|
this.setState(SshSessionState.AUTHENTICATING);
|
||||||
|
try {
|
||||||
|
const engine: UserAuthEngine = new UserAuthEngine(this.transport, this.sessionId);
|
||||||
|
const result: AuthResult = await engine.authenticate(username, password, privateKey,
|
||||||
|
this.authTimeoutMs,
|
||||||
|
(message: string): void => {
|
||||||
|
Log.info(SshSession.TAG, `auth banner: ${message}`);
|
||||||
|
});
|
||||||
|
// From here on every packet is routed by the dispatcher; waitPacket
|
||||||
|
// is never armed again while the dispatcher is installed.
|
||||||
|
this.transport.onPacket((payload: Uint8Array): void => {
|
||||||
|
this.dispatch(payload);
|
||||||
|
});
|
||||||
|
this.keepAlive = new KeepAlive(this.transport, this.keepAliveIntervalMs,
|
||||||
|
SshSession.KEEPALIVE_MAX_UNANSWERED,
|
||||||
|
(reason: string): void => {
|
||||||
|
Log.warn(SshSession.TAG, `keepalive dead: ${reason}`);
|
||||||
|
this.transport.close();
|
||||||
|
});
|
||||||
|
this.keepAlive.start();
|
||||||
|
this.setState(SshSessionState.READY);
|
||||||
|
Log.info(SshSession.TAG, `authenticated as '${username}' via ${result.method}`);
|
||||||
|
return result;
|
||||||
|
} catch (e) {
|
||||||
|
this.setState(SshSessionState.ERROR);
|
||||||
|
throw e as Error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Open a channel, request a PTY and an interactive shell. */
|
||||||
|
async openShell(cols: number, rows: number, onData: (data: Uint8Array) => void,
|
||||||
|
onExtendedData: (data: Uint8Array) => void,
|
||||||
|
onClose: (() => void) | null): Promise<SshChannel> {
|
||||||
|
this.requireReady('openShell');
|
||||||
|
const ch: SshChannel = this.newChannel(onData, onExtendedData, onClose);
|
||||||
|
await ch.open(this.authTimeoutMs);
|
||||||
|
const ptyOk: boolean = await ch.requestPty(cols, rows, this.authTimeoutMs);
|
||||||
|
if (!ptyOk) {
|
||||||
|
await ch.close();
|
||||||
|
throw new Error('SshSession: server rejected pty-req');
|
||||||
|
}
|
||||||
|
const shellOk: boolean = await ch.requestShell(this.authTimeoutMs);
|
||||||
|
if (!shellOk) {
|
||||||
|
await ch.close();
|
||||||
|
throw new Error('SshSession: server rejected shell request');
|
||||||
|
}
|
||||||
|
return ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run one command over a fresh channel and collect its output. */
|
||||||
|
async execCommand(command: string, timeoutMs: number): Promise<ExecResult> {
|
||||||
|
this.requireReady('execCommand');
|
||||||
|
const stdoutChunks: Uint8Array[] = [];
|
||||||
|
const stderrChunks: Uint8Array[] = [];
|
||||||
|
const ch: SshChannel = this.newChannel(
|
||||||
|
(data: Uint8Array): void => {
|
||||||
|
stdoutChunks.push(data);
|
||||||
|
},
|
||||||
|
(data: Uint8Array): void => {
|
||||||
|
stderrChunks.push(data);
|
||||||
|
},
|
||||||
|
null);
|
||||||
|
try {
|
||||||
|
await ch.open(this.authTimeoutMs);
|
||||||
|
const ok: boolean = await ch.exec(command, timeoutMs);
|
||||||
|
if (!ok) {
|
||||||
|
throw new Error('SshSession: server rejected exec request');
|
||||||
|
}
|
||||||
|
await ch.waitClosed(timeoutMs);
|
||||||
|
const result: ExecResult = {
|
||||||
|
stdout: bytesToUtf8(concatAll(stdoutChunks)),
|
||||||
|
stderr: bytesToUtf8(concatAll(stderrChunks)),
|
||||||
|
exitStatus: ch.getExitStatus()
|
||||||
|
};
|
||||||
|
return result;
|
||||||
|
} finally {
|
||||||
|
await ch.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Idempotent teardown: keepalive, channels, transport. */
|
||||||
|
close(): void {
|
||||||
|
if (this.closed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.closed = true;
|
||||||
|
const ka: KeepAlive | null = this.keepAlive;
|
||||||
|
if (ka !== null) {
|
||||||
|
ka.stop();
|
||||||
|
}
|
||||||
|
this.closeAllChannels();
|
||||||
|
this.transport.close();
|
||||||
|
this.setState(SshSessionState.CLOSED);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- private
|
||||||
|
|
||||||
|
private requireReady(what: string): void {
|
||||||
|
if (this.state !== SshSessionState.READY) {
|
||||||
|
throw new Error(`SshSession: ${what}() requires READY state (got ${this.state})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private newChannel(onData: (data: Uint8Array) => void, onExtendedData: (data: Uint8Array) => void,
|
||||||
|
onClose: (() => void) | null): SshChannel {
|
||||||
|
const localId: number = this.nextLocalId;
|
||||||
|
this.nextLocalId += 1;
|
||||||
|
const cbs: ChannelCallbacks = {
|
||||||
|
onData: onData,
|
||||||
|
onExtendedData: onExtendedData,
|
||||||
|
onClose: (): void => {
|
||||||
|
this.removeChannel(localId);
|
||||||
|
if (onClose !== null) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const ch: SshChannel = new SshChannel(this.transport, localId, cbs);
|
||||||
|
this.channels.push(ch);
|
||||||
|
return ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
private removeChannel(localId: number): void {
|
||||||
|
for (let i: number = 0; i < this.channels.length; i++) {
|
||||||
|
if (this.channels[i].localId === localId) {
|
||||||
|
this.channels.splice(i, 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private findChannel(localId: number): SshChannel | undefined {
|
||||||
|
for (let i: number = 0; i < this.channels.length; i++) {
|
||||||
|
if (this.channels[i].localId === localId) {
|
||||||
|
return this.channels[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
private setState(next: SshSessionState): void {
|
||||||
|
this.state = next;
|
||||||
|
Log.debug(SshSession.TAG, `state -> ${next}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private closeAllChannels(): void {
|
||||||
|
const snapshot: SshChannel[] = this.channels.slice();
|
||||||
|
this.channels.splice(0, this.channels.length);
|
||||||
|
for (let i: number = 0; i < snapshot.length; i++) {
|
||||||
|
snapshot[i].handleSessionClosing();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleTransportClosed(reason: string): void {
|
||||||
|
if (this.closed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.closed = true;
|
||||||
|
Log.warn(SshSession.TAG, `transport closed: ${reason}`);
|
||||||
|
const ka: KeepAlive | null = this.keepAlive;
|
||||||
|
if (ka !== null) {
|
||||||
|
ka.stop();
|
||||||
|
}
|
||||||
|
this.closeAllChannels();
|
||||||
|
this.setState(SshSessionState.CLOSED);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single inbound packet router (installed after auth success):
|
||||||
|
* DISCONNECT closes the session; GLOBAL_REQUEST is always refused;
|
||||||
|
* keepalive replies reset the probe counter; everything in the channel
|
||||||
|
* range (91..100) goes to the channel owning the recipient id.
|
||||||
|
*/
|
||||||
|
private dispatch(payload: Uint8Array): void {
|
||||||
|
if (payload.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const msg: number = payload[0];
|
||||||
|
switch (msg) {
|
||||||
|
case SshMsg.DISCONNECT: {
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
const code: number = r.readUint32();
|
||||||
|
const reason: string = r.readString();
|
||||||
|
Log.warn(SshSession.TAG, `server disconnect: ${disconnectReason(code)} (${reason})`);
|
||||||
|
this.transport.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SshMsg.IGNORE:
|
||||||
|
case SshMsg.UNIMPLEMENTED:
|
||||||
|
case SshMsg.DEBUG_MSG:
|
||||||
|
return;
|
||||||
|
case SshMsg.EXT_INFO: {
|
||||||
|
const ext: Map<string, string> = parseExtInfo(payload);
|
||||||
|
ext.forEach((value: string, name: string): void => {
|
||||||
|
Log.debug(SshSession.TAG, `ext-info: ${name}=${value}`);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SshMsg.GLOBAL_REQUEST: {
|
||||||
|
// We accept no server-initiated global requests.
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
const name: string = r.readString();
|
||||||
|
const wantReply: boolean = r.readBoolean();
|
||||||
|
Log.debug(SshSession.TAG, `global request '${name}' refused`);
|
||||||
|
if (wantReply) {
|
||||||
|
const w: SshWriter = new SshWriter(16);
|
||||||
|
w.writeByte(SshMsg.REQUEST_FAILURE);
|
||||||
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
||||||
|
sent.catch((e: Object): void => {
|
||||||
|
const err = e as Error;
|
||||||
|
Log.debug(SshSession.TAG, `REQUEST_FAILURE send failed: ${err.message}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SshMsg.REQUEST_SUCCESS:
|
||||||
|
case SshMsg.REQUEST_FAILURE: {
|
||||||
|
const ka: KeepAlive | null = this.keepAlive;
|
||||||
|
if (ka !== null) {
|
||||||
|
ka.onReply();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SshMsg.CHANNEL_OPEN: {
|
||||||
|
// Refuse server-initiated channels.
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
const chanType: string = r.readString();
|
||||||
|
const senderId: number = r.readUint32();
|
||||||
|
Log.debug(SshSession.TAG, `refusing server channel '${chanType}'`);
|
||||||
|
const w: SshWriter = new SshWriter(64);
|
||||||
|
w.writeByte(SshMsg.CHANNEL_OPEN_FAILURE);
|
||||||
|
w.writeUint32(senderId);
|
||||||
|
w.writeUint32(SshChannelFailureCode.UNKNOWN_CHANNEL_TYPE);
|
||||||
|
w.writeString('client does not accept incoming channels');
|
||||||
|
w.writeString('');
|
||||||
|
const sent: Promise<void> = this.transport.sendPacket(w.toBytes());
|
||||||
|
sent.catch((e: Object): void => {
|
||||||
|
const err = e as Error;
|
||||||
|
Log.debug(SshSession.TAG, `CHANNEL_OPEN_FAILURE send failed: ${err.message}`);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (msg < SshMsg.CHANNEL_OPEN_CONFIRMATION || msg > SshMsg.CHANNEL_FAILURE) {
|
||||||
|
Log.debug(SshSession.TAG, `unrouted msg ${msg} ignored`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const r: SshReader = new SshReader(payload);
|
||||||
|
r.readByte();
|
||||||
|
const recipient: number = r.readUint32();
|
||||||
|
const ch: SshChannel | undefined = this.findChannel(recipient);
|
||||||
|
if (ch === undefined) {
|
||||||
|
Log.warn(SshSession.TAG, `packet for unknown channel ${recipient} (msg ${msg})`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ch.handlePacket(payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function concatAll(chunks: Uint8Array[]): Uint8Array {
|
||||||
|
let total: number = 0;
|
||||||
|
for (let i: number = 0; i < chunks.length; i++) {
|
||||||
|
total += chunks[i].length;
|
||||||
|
}
|
||||||
|
const out: Uint8Array = new Uint8Array(total);
|
||||||
|
let offset: number = 0;
|
||||||
|
for (let i: number = 0; i < chunks.length; i++) {
|
||||||
|
out.set(chunks[i], offset);
|
||||||
|
offset += chunks[i].length;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -63,6 +63,7 @@ export class SshTransport {
|
|||||||
private packetCallback: ((payload: Uint8Array) => void) | undefined = undefined;
|
private packetCallback: ((payload: Uint8Array) => void) | undefined = undefined;
|
||||||
private packetWaiter: ((payload: Uint8Array) => void) | undefined = undefined;
|
private packetWaiter: ((payload: Uint8Array) => void) | undefined = undefined;
|
||||||
private packetWaiterRejecter: ((err: Error) => void) | undefined = undefined;
|
private packetWaiterRejecter: ((err: Error) => void) | undefined = undefined;
|
||||||
|
private packetWaiterTimerId: number = -1;
|
||||||
private outSeq: number = 0;
|
private outSeq: number = 0;
|
||||||
private inSeq: number = 0;
|
private inSeq: number = 0;
|
||||||
private sentBytes: number = 0;
|
private sentBytes: number = 0;
|
||||||
@@ -118,16 +119,26 @@ export class SshTransport {
|
|||||||
this.closeCallback = cb;
|
this.closeCallback = cb;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Resolve with the next received packet payload, or reject on close/timeout. */
|
/**
|
||||||
|
* Resolve with the next received packet payload, or reject on
|
||||||
|
* close/timeout. Only one waiter may be armed at a time; re-arming
|
||||||
|
* clears the previous (already settled) timer so a stale timeout can
|
||||||
|
* never reject the new waiter.
|
||||||
|
*/
|
||||||
async waitPacket(timeoutMs: number): Promise<Uint8Array> {
|
async waitPacket(timeoutMs: number): Promise<Uint8Array> {
|
||||||
return new Promise<Uint8Array>((resolve: (p: Uint8Array) => void, reject: (e: Error) => void): void => {
|
return new Promise<Uint8Array>((resolve: (p: Uint8Array) => void, reject: (e: Error) => void): void => {
|
||||||
|
if (this.packetWaiterTimerId >= 0) {
|
||||||
|
clearTimeout(this.packetWaiterTimerId);
|
||||||
|
this.packetWaiterTimerId = -1;
|
||||||
|
}
|
||||||
this.packetWaiter = resolve;
|
this.packetWaiter = resolve;
|
||||||
this.packetWaiterRejecter = reject;
|
this.packetWaiterRejecter = reject;
|
||||||
setTimeout((): void => {
|
this.packetWaiterTimerId = setTimeout((): void => {
|
||||||
if (this.packetWaiterRejecter !== undefined) {
|
if (this.packetWaiterRejecter !== undefined) {
|
||||||
this.packetWaiterRejecter(new Error(`timeout waiting for packet after ${timeoutMs} ms`));
|
this.packetWaiterRejecter(new Error(`timeout waiting for packet after ${timeoutMs} ms`));
|
||||||
this.packetWaiter = undefined;
|
this.packetWaiter = undefined;
|
||||||
this.packetWaiterRejecter = undefined;
|
this.packetWaiterRejecter = undefined;
|
||||||
|
this.packetWaiterTimerId = -1;
|
||||||
}
|
}
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
});
|
});
|
||||||
@@ -333,6 +344,10 @@ export class SshTransport {
|
|||||||
this.packetWaiterRejecter(err);
|
this.packetWaiterRejecter(err);
|
||||||
this.packetWaiter = undefined;
|
this.packetWaiter = undefined;
|
||||||
this.packetWaiterRejecter = undefined;
|
this.packetWaiterRejecter = undefined;
|
||||||
|
if (this.packetWaiterTimerId >= 0) {
|
||||||
|
clearTimeout(this.packetWaiterTimerId);
|
||||||
|
this.packetWaiterTimerId = -1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -363,6 +378,10 @@ export class SshTransport {
|
|||||||
if (waiter !== undefined) {
|
if (waiter !== undefined) {
|
||||||
this.packetWaiter = undefined;
|
this.packetWaiter = undefined;
|
||||||
this.packetWaiterRejecter = undefined;
|
this.packetWaiterRejecter = undefined;
|
||||||
|
if (this.packetWaiterTimerId >= 0) {
|
||||||
|
clearTimeout(this.packetWaiterTimerId);
|
||||||
|
this.packetWaiterTimerId = -1;
|
||||||
|
}
|
||||||
waiter(payload);
|
waiter(payload);
|
||||||
}
|
}
|
||||||
const cb: ((payload: Uint8Array) => void) | undefined = this.packetCallback;
|
const cb: ((payload: Uint8Array) => void) | undefined = this.packetCallback;
|
||||||
|
|||||||
Reference in New Issue
Block a user