Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases.

## [Unreleased]

### Development

- Added live coverage for keyboard-interactive authentication on a nested hop
and for `abortOnSudoFailure`, plus deterministic tests that feed one PTY
transcript through `onData` at every chunk boundary.

## [4.0.4] - 2026-11-18

### Fixed
Expand Down
11 changes: 11 additions & 0 deletions scripts/run-live.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const server3 = env.SERVER3_HOST;
const defaultTests = [
'simple',
'keyboard-interactive',
'hop_keyboard_interactive',
'sudo_su',
'sudo_no_pass',
'prompt_response',
Expand Down Expand Up @@ -104,6 +105,11 @@ const checks = {
'keyboard-interactive': {
contains: [`\n${kbdUser}\n`],
},
hop_keyboard_interactive: {
contains: [`\n${kbdUser}\n`, 'hop-keyboard-interactive-marker'],
excludes: ['SSH failed'],
logContains: [`hop-keyboard-interactive-handler:${kbdUser}`],
},
fingerprint: {
contains: [`\n${user}\n`],
},
Expand Down Expand Up @@ -145,6 +151,11 @@ const checks = {
logContains: ['Sudo authentication failed for', 'sudo-failed:true'],
logExcludes: ['Stop requested'],
},
sudo_abort: {
logContains: ['Sudo authentication failed for', 'sudo-failed:true', 'Stop requested: sudo-failed'],
logExcludes: ['sudo-abort-follow-up-ran'],
excludes: ['sudo-abort-must-not-run'],
},
transport_drop: {
contains: ['transport-drop-before'],
excludes: ['transport-drop-after'],
Expand Down
64 changes: 64 additions & 0 deletions test/live/hop_keyboard_interactive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const dotenv = require('dotenv').config();
const { logFile, log } = require('../utils/logging.js');
logFile('hop_keyboard_interactive.js');

const SSH2Shell = require('../utils/module.js');
const { readPrivateKey } = require('../utils/private_key.js');

// Prove the README claim that keyboard-interactive works on nested hosts.
// The parent authenticates with the throwaway key over server2. The child is
// opened with forwardOut to server1's kbduser, whose password auth is disabled,
// so only the child's keyboard-interactive handler can complete the login.
const privateKey = readPrivateKey();
const kbdUser = process.env.KBD_USER || 'kbduser';
const kbdPassword = process.env.KBD_PASSWORD;

if (!kbdPassword) {
console.error('Set KBD_PASSWORD in .env for the keyboard-interactive user.');
process.exit(1);
}

const parent = {
server: {
host: process.env.SERVER2_HOST,
port: process.env.SERVER2_PORT || process.env.PORT,
userName: process.env.SERVER2_USER_NAME,
privateKey,
passPhrase: process.env.KEY_PASSPHRASE,
},
commands: ['hostname'],
debug: (process.env.DEBUG === 'true'),
verbose: (process.env.VERBOSE === 'true'),
};

const child = {
server: {
host: process.env.KBD_HOST || process.env.HOST,
port: process.env.KBD_PORT || process.env.PORT,
userName: kbdUser,
password: kbdPassword,
tryKeyboard: true,
},
commands: ['whoami', 'echo hop-keyboard-interactive-marker'],
// Host handlers are record-scoped. This one must be used for the child's
// challenge, not the parent's (the parent uses key authentication).
onKeyboardInteractive: function (name, instructions, instructionsLang, prompts, finish) {
log(`hop-keyboard-interactive-handler:${this.sshObj.server.userName}`);
finish([kbdPassword]);
},
debug: (process.env.DEBUG === 'true'),
verbose: (process.env.VERBOSE === 'true'),
};

parent.hosts = [child];
child.hosts = [];

const SSH = new SSH2Shell(parent);

SSH.on('msg', log);

SSH.connect((sessionText) => {
const text = `-----Callback session text:\n${sessionText}\n-----Callback end`;
log(text);
console.log(text);
});
47 changes: 47 additions & 0 deletions test/live/sudo_abort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const dotenv = require('dotenv').config();
const { logFile, log } = require('../utils/logging.js');
logFile('sudo_abort.js');

const SSH2Shell = require('../utils/module.js');

// Same rejection path as sudo_rejected.js, but the host opts into aborting.
// The run must stop at the failed prompt, send one Ctrl-C, and never start the
// follow-up command.
const host = {
server: {
host: process.env.HOST,
port: process.env.PORT,
userName: process.env.USER_NAME,
password: process.env.PASSWORD,
},
commands: [
'sudo -k',
'sudo id -u',
'echo sudo-abort-must-not-run',
],
abortOnSudoFailure: true,
onCommandProcessing: (command, response, sshObj) => {
if (command.includes('sudo id -u') && /password/i.test(response)) {
sshObj.server.password = 'definitely-not-the-sudo-password';
}
},
onCommandComplete: (command) => {
if (command.includes('sudo-abort-must-not-run')) {
log('sudo-abort-follow-up-ran');
}
},
debug: (process.env.DEBUG === 'true'),
verbose: (process.env.VERBOSE === 'true'),
};

const SSH = new SSH2Shell(host);

SSH.on('msg', log);

SSH.connect((sessionText) => {
const text = `-----Callback session text:\n${sessionText}\n-----Callback end`;
log(text);
log(`sudo-failed:${SSH.sshObj.sudoFailed}`);
console.log(text);
console.log(`sudo-failed:${SSH.sshObj.sudoFailed}`);
});
100 changes: 100 additions & 0 deletions test/unit/chunking.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');

const {
installFakeSsh2,
isBaseline,
loadSSH2Shell,
createHost,
waitFor,
waitForStream,
} = require('./helpers/harness');

installFakeSsh2();
const SSH2Shell = loadSSH2Shell();

// One PTY transcript containing a wrapped command echo, ANSI control sequences,
// CRLF line endings, and a final prompt. The shell can deliver this in any
// chunking; command completion must not depend on where the bytes are split.
const COMMAND = 'echo chunk-boundary-output';
const transcript = [
COMMAND.slice(0, 12),
'\r\n',
COMMAND.slice(12),
'\r\n',
'\x1b[?2004l',
'\x1b]3008;start=abc;type=command;cwd=/home/tester\x1b\\',
'\r\n',
'chunk-boundary-output',
'\r\n',
'\x1b[?2004h',
'tester@host:~$ ',
].join('');

async function run(chunks) {
const completed = [];
const host = createHost({
commands: [COMMAND],
onCommandComplete: (command, response) => {
completed.push({ command, response });
},
});

const ssh = new SSH2Shell(host);
let callbackText;
ssh.connect((text) => {
callbackText = text;
});

await waitForStream(ssh);
const stream = ssh._stream;
stream.onWrite = (data, target) => {
setTimeout(() => {
for (const chunk of chunks) {
target.receive(chunk);
}
}, 1);
};
stream.receive('$ ');

await waitFor(() => callbackText !== undefined, {
label: 'callback',
timeout: 2000,
});

assert.deepEqual(stream.writes, [`${COMMAND}\n`]);
assert.equal(completed.length, 1);
assert.equal(completed[0].command, COMMAND);
assert.ok(completed[0].response.includes('chunk-boundary-output'));
assert.ok(!completed[0].response.includes('3008;'));
assert.ok(!completed[0].response.includes('[?2004'));
assert.equal(stream.closed, true);

return { response: completed[0].response, sessionText: callbackText };
}

function splitAt(index) {
return [transcript.slice(0, index), transcript.slice(index)];
}

describe('onData chunk boundaries', () => {
it('produces the same result for every two-chunk split', async () => {
if (isBaseline()) return;

const expected = await run([transcript]);
for (let index = 1; index < transcript.length; index += 1) {
const actual = await run(splitAt(index));
assert.deepEqual(actual, expected, `split at byte ${index}`);
}
});

it('produces the same result for byte-at-a-time delivery', async () => {
if (isBaseline()) return;

const expected = await run([transcript]);
const actual = await run(Array.from(transcript, (byte) => byte));
assert.deepEqual(actual, expected);
});
});
52 changes: 52 additions & 0 deletions test/unit/host-hop.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,58 @@ describe('host hop transport', () => {
ssh.close();
});

newOnly('uses the child host keyboard-interactive handler on a hop', async () => {
let handled = null;
const hop = hopHost({
server: {
host: 'hop.test',
port: 2222,
userName: 'kbduser',
password: 'kbdpassword',
tryKeyboard: true,
},
// Keep a command pending so the hop shell stays open while the
// challenge is delivered.
commands: ['echo hop'],
onKeyboardInteractive: function (name, instructions, instructionsLang, prompts, finish) {
handled = {
user: this.sshObj.server.userName,
password: this.sshObj.server.password,
};
finish(['kbd-answer']);
},
});
const primary = createHost({
server: { host: 'primary.test' },
commands: [],
hosts: [hop],
});
const ssh = await connected(primary);
const parentConnection = ssh.connection;
ssh._nextHost();

await waitFor(
() => ssh._activeContext().host === hop && ssh.connection && ssh.connection !== parentConnection,
{ label: 'hop keyboard-interactive handler' }
);

const hopConnection = ssh.connection;
const responses = await new Promise((resolve) => {
hopConnection.emit(
'keyboard-interactive',
'sshd',
'',
'en',
[{ prompt: 'Password:' }],
resolve
);
});

assert.deepEqual(responses, ['kbd-answer']);
assert.deepEqual(handled, { user: 'kbduser', password: 'kbdpassword' });
ssh.close();
});

newOnly('terminates when _connectHop has no parent record', () => {
const ssh = new SSH2Shell(createHost());
let called = false;
Expand Down
Loading