File size: 7,630 Bytes
bad179a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | // ssh transport with a stand-in ssh that logs its arguments and runs the command line on this machine (read-only collector; dry run on).
// node t_ssh.js <port> <cfgdir> <Linux|Windows>
const fs = require('fs'), path = require('path'), { sleep, client, check, done } = require('./lib');
const [port, cfg, os] = process.argv.slice(2), win = os === 'Windows', { req, post, state } = client(port), dir = path.join(cfg, 'ServerMonitorWeb');
const calls = () => fs.readFileSync(cfg + '.sshlog', 'utf8').split('\n').filter(Boolean).map(JSON.parse);
const until = async (fn, ms) => { for (const t0 = Date.now(); Date.now() - t0 < ms; await sleep(250)) { const v = await fn(); if (v) return v; } return false; };
const SECRET = "S3cr3t'pw \"$HOME\" & %PATH% !x! ^<>|", OPTS = ['-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=3', '-o', 'StrictHostKeyChecking=accept-new', '-o', 'LogLevel=ERROR'];
(async () => {
let s = await state();
check('first start: "This computer" (local) is created', s.servers.length === 1 && s.servers[0].cfg.name === 'This computer' && s.servers[0].cfg.transport === 0 && s.servers[0].cfg.group === 'Local' && s.servers[0].cfg.interval === (win ? 3 : 2));
const mode = f => (fs.statSync(f).mode & 0o777).toString(8);
check('config folder 700, servers.json 600', mode(dir) === '700' && mode(path.join(dir, 'servers.json')) === '600', `${mode(dir)} ${mode(path.join(dir, 'servers.json'))}`);
await post('server/update', { id: s.servers[0].cfg.id, autopilot: { ...s.servers[0].cfg.autopilot, dryRun: true } });
for (const [what, b] of [['host starting with "-"', { host: '-oProxyCommand=touch /tmp/pwn' }], ['host " -o…" (spaces are trimmed first)', { host: ' -oProxyCommand=x' }], ['user starting with "-"', { host: 'h', user: '-oProxyCommand=x' }]]) {
const r = await req('POST', '/api/server/add', { name: 'x', transport: 1, ...b }), t = await req('POST', '/api/server/test', { name: 'x', transport: 1, ...b });
check(`${what} is refused (add and test)`, r.status === 400 && t.status === 400, r.text);
}
check('nothing was started for the refused servers', !fs.existsSync(cfg + '.sshlog') && (await state()).servers.length === 1);
// key login: BatchMode, no askpass
const key = await post('server/add', { name: 'key box', transport: 1, host: 'fakehost', user: 'me', keyFile: '~/.ssh/-oProxyCommand=evil key', port: 22, interval: 1, autopilot: { dryRun: true } });
await until(() => fs.existsSync(cfg + '.sshlog'), 5000);
let c = calls()[0], home = require('os').homedir();
const shell = win ? 'powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA' : 'sh -s -- 1';
check('ssh argv with a key: options, BatchMode, -i <expanded key as one argument>, -T user@host, command line', JSON.stringify(c.argv) === JSON.stringify([...OPTS, '-o', 'BatchMode=yes', '-i', home + '/.ssh/-oProxyCommand=evil key', '-T', 'me@fakehost', shell]), JSON.stringify(c.argv));
check('no askpass environment without a password', !c.env.SSH_ASKPASS && !c.env.SERVERMONITOR_ASKPASS);
// password login
const pw = await post('server/add', { name: 'pw box', transport: 1, host: 'fake host;$(id)', user: '', port: 2222, password: SECRET, interval: 1, useSudo: true, autopilot: { dryRun: true } });
c = await until(() => calls().find(x => x.argv.includes('2222')), 5000);
check('ssh argv with a password: NumberOfPasswordPrompts=1, -p, host kept as one argument', JSON.stringify(c.argv) === JSON.stringify([...OPTS, '-o', 'NumberOfPasswordPrompts=1', '-p', '2222', '-T', 'fake host;$(id)', shell]), JSON.stringify(c.argv));
check('askpass environment: helper, force, password, DISPLAY', c.env.SSH_ASKPASS_REQUIRE === 'force' && c.env.SERVERMONITOR_ASKPASS === SECRET && !!c.env.DISPLAY && path.basename(c.env.SSH_ASKPASS) === (win ? 'askpass.cmd' : 'askpass.sh'), JSON.stringify({ ...c.env, SERVERMONITOR_ASKPASS: '…' }));
if (!win) check('askpass helper prints exactly the password; helper 700 in a 700 folder', c.askpass_answer === SECRET + '\n' && c.askpass_mode === '0o700 in 0o700', JSON.stringify(c.askpass_answer) + ' ' + c.askpass_mode);
else check('askpass.cmd: CRLF batch file that echoes the variable with delayed expansion', c.askpass_text === '@echo off\r\nsetlocal EnableDelayedExpansion\r\necho(!SERVERMONITOR_ASKPASS!\r\n', JSON.stringify(c.askpass_text));
check('the password is in no argument', calls().every(x => !x.argv.join(' ').includes('S3cr3t')));
// the stored password never reaches the browser
const b64 = JSON.parse(fs.readFileSync(path.join(dir, 'servers.json'))).servers.find(x => x.id === pw.id).password;
const texts = [(await req('GET', '/api/state')).text, (await req('GET', '/api/history?id=' + pw.id + '&range=3600')).text, (await req('GET', '/api/alerts.log')).text, fs.readFileSync(cfg + '.out', 'utf8') + fs.readFileSync(cfg + '.err', 'utf8')];
const sse = p => new Promise(res => require('http').get({ host: '127.0.0.1', port, path: p }, r => { let b = ''; r.on('data', d => b += d); setTimeout(() => (r.destroy(), res(b)), 2500); }));
texts.push(await sse('/api/events'), await sse('/api/events?id=' + pw.id));
check('stored password: obfuscated in servers.json, absent from every reply, stream and log', b64.length > 8 && !fs.readFileSync(path.join(dir, 'servers.json'), 'utf8').includes('S3cr3t') && texts.every(t => t.length > 0 || t === '') && texts.slice(0, 2).concat(texts.slice(4)).every(t => t.length > 50) && !texts.some(t => t.includes('S3cr3t') || t.includes(b64)), `${texts.map(t => t.length).join('/')} bytes searched`);
s = (await state()).servers.find(x => x.cfg.id === pw.id);
check('page gets hasPassword only', s.cfg.hasPassword === true && !('password' in s.cfg));
if (!win) {
check('server over (stand-in) ssh comes online', await until(async () => (await state()).servers.find(x => x.cfg.id === pw.id).online, 8000));
let r = await post('exec', { id: pw.id, cmd: 'echo "$0 over ssh"; echo err >&2; exit 4', privileged: false });
check('one-shot command over ssh: stdin script, merged output, exit code', r.code === 4 && /over ssh\nerr\n/.test(r.out), JSON.stringify(r));
const one = calls().at(-1);
check('one-shot ssh call runs "sh -s"', one.argv.at(-1) === 'sh -s', one.argv.at(-1));
const t = await post('server/test', { id: pw.id, name: 'pw box', transport: 1, host: 'fake host;$(id)', port: 2222, password: '' });
check('test connection of an edited server uses the stored password', t.ok && calls().at(-1).env.SERVERMONITOR_ASKPASS === SECRET && /Connected in \d+ ms — .+ · \d+ cores · .+ RAM · CPU \d+%/.test(t.text), t.text);
}
const dead = await post('server/test', { name: 'd', transport: 1, host: 'deadhost' });
check('test connection: failure text is ssh\'s last error line', dead.ok === false && dead.text === '✗ ssh: connect to host deadhost port 22: Connection refused', dead.text);
await post('server/update', { id: pw.id, password: '', clearPassword: true, enabled: false });
check('"remove stored" clears the password', JSON.parse(fs.readFileSync(path.join(dir, 'servers.json'))).servers.find(x => x.id === pw.id).password === '' && !(await state()).servers.find(x => x.cfg.id === pw.id).cfg.hasPassword);
await post('server/remove', { id: key.id, deleteHistory: true }), await post('server/remove', { id: pw.id, deleteHistory: true });
done();
})();
|