File size: 9,696 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Tries to get past the local-only API. node t_security.js <port> <cfgdir> <project root> <Linux|Windows>
// Uses the scratch config (local1 online, ssh1 unreachable). Commands are built for the unreachable server (never executed) or are
// read-only (service logs) on the local one.
const fs = require('fs'), net = require('net'), path = require('path'), { sleep, client, check, done } = require('./lib');
const [port, cfg, root, os] = process.argv.slice(2), win = os === 'Windows', { req, post, state } = client(port), dir = path.join(cfg, 'ServerMonitorWeb');
const raw = text => new Promise(resolve => { // a request exactly as written
    const s = net.connect(port, '127.0.0.1', () => s.write(text)); let d = '';
    s.setEncoding('utf8').on('data', x => d += x).on('close', () => resolve(d)).on('error', () => resolve(d)); setTimeout(() => s.destroy(), 1500);
});
(async () => {
    const src = fs.readFileSync(path.join(root, 'server.js'), 'utf8'), routes = [...src.slice(src.indexOf('const POST')).matchAll(/'(\/api\/[a-z/.]+)':/g)].map(m => m[1]);
    const before = JSON.stringify((await state()).servers.map(s => [s.cfg, s.status === 'Disabled', s.paused])), file = fs.readFileSync(path.join(dir, 'servers.json'), 'utf8');
    // 1. Host / Origin
    const hosts = ['evil.example', `evil.example:${port}`, `127.0.0.1:${port}.evil.example`, `127.0.0.1.evil.example:${port}`, `LOCALHOST:${port}`, `localhost.:${port}`, `[::1]:${port}`, `0.0.0.0:${port}`, `127.0.0.1`, `127.0.0.1:${+port + 1}`, `127.1:${port}`];
    let bad = [];
    for (const h of hosts) for (const [m, p, b] of [['GET', '/'], ['GET', '/api/state'], ['GET', '/app.js'], ['POST', '/api/alerts/clear', {}]]) { const r = await req(m, p, b, { Host: h }); if (r.status !== 403) bad.push(`${h} ${p} -> ${r.status}`); }
    check(`${hosts.length} foreign or malformed Host values are refused on pages, files and API`, !bad.length, bad.join('; '));
    const noHost = await raw(`GET /api/state HTTP/1.0\r\n\r\n`), twoHosts = await raw(`GET /api/state HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nHost: evil.example\r\n\r\n`);
    check('no Host header is refused (a second Host header is ignored by Node: reported)', /^HTTP\/1\.1 40[03]/.test(noHost), noHost.split('\r\n')[0] + ' / ' + twoHosts.split('\r\n')[0]);
    bad = [];
    for (const o of ['http://evil.example', 'null', `https://127.0.0.1:${port}`, `http://127.0.0.1:${+port + 1}`, `http://127.0.0.1:${port}.evil.example`, `http://evil.example/http://127.0.0.1:${port}`, `http://localhost`, 'file://', `http://http://127.0.0.1:${port}`])
        for (const [m, p, b] of [['GET', '/api/state'], ['GET', '/api/events'], ['POST', '/api/alerts/clear', {}], ['POST', '/api/exec', { id: 'local1', cmd: 'echo x' }]]) { const r = await req(m, p, b, { Origin: o }); if (r.status !== 403) bad.push(`${o} ${p} -> ${r.status}`); }
    check('9 foreign Origin values are refused (also for GET and the event stream)', !bad.length, bad.join('; '));
    const same = await req('POST', '/api/server/analyze', { id: 'local1' }, { Origin: `http://127.0.0.1:${port}` }), sameL = await req('GET', '/api/state', undefined, { Origin: `http://localhost:${port}`, Host: `localhost:${port}` });
    check('the page\'s own Origin is accepted', same.status === 200 && sameL.status === 200);
    // 2. custom header rule on every state-changing route; other methods
    bad = [];
    for (const r of routes) {
        for (const [what, h] of [['no X-SM', { 'X-SM': '' }], ['X-SM: 0', { 'X-SM': '0' }], ['text/plain', { 'Content-Type': 'text/plain' }], ['form', { 'Content-Type': 'application/x-www-form-urlencoded' }], ['application/jsonx', { 'Content-Type': 'application/jsonx' }]]) {
            const x = await req('POST', r, { id: 'local1', cmd: 'echo x', paused: true, delta: 1, deleteHistory: true, name: 'n', transport: 0 }, h);
            if (x.status !== 403) bad.push(`${r} ${what} -> ${x.status}`);
        }
        for (const m of ['GET', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD']) { const x = await req(m, r, m === 'GET' || m === 'HEAD' ? undefined : { id: 'local1' }); if (x.status !== 404) bad.push(`${m} ${r} -> ${x.status}`); }
    }
    check(`all ${routes.length} POST routes: 403 without the custom header or JSON type; no other method reaches them`, routes.length >= 14 && !bad.length, bad.join('; ') || routes.join(' '));
    check('nothing changed by the refused requests', JSON.stringify((await state()).servers.map(s => [s.cfg, s.status === 'Disabled', s.paused])) === before && fs.readFileSync(path.join(dir, 'servers.json'), 'utf8') === file);
    const all = [await req('GET', '/'), await req('GET', '/api/state'), await req('POST', '/api/alerts/clear', {}), await req('OPTIONS', '/api/exec', undefined, { Origin: 'http://evil.example', 'Access-Control-Request-Method': 'POST' }), await req('GET', '/nope')];
    check('no CORS header on any reply; security headers on all', all.every(r => !Object.keys(r.headers).some(h => h.startsWith('access-control')) && r.headers['x-content-type-options'] === 'nosniff' && /frame-ancestors 'none'/.test(r.headers['content-security-policy']) && r.headers['cross-origin-resource-policy'] === 'same-origin'));
    // 3. static files
    bad = [];
    for (const p of ['/../server.js', '/..%2fserver.js', '/%2e%2e/server.js', '/%2e%2e%2fserver.js', '//server.js', '/public/../server.js', '/app.js/../../server.js', '/..\\server.js', '/%5c..%5cserver.js', '/core/platform.js', '/server.js', '/README.md', '/app.js%00', '/app.js/', '/./app.js/.', '/.', '/index.html/..', '/%00', '/__proto__', '/constructor', '/api/__proto__', '/api/../server.js']) {
        const r = await raw(`GET ${p} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\n\r\n`), status = +r.split(' ')[1];
        if (/require\(|createServer|Server Monitor \(web/.test(r) && !/<!doctype html>/i.test(r) || ![200, 400, 404].includes(status) || (status === 200 && !/<!doctype html>|Server Monitor page/i.test(r))) bad.push(`${p} -> ${status}`);
    }
    check('22 traversal and odd paths serve nothing outside public/', !bad.length, bad.join('; '));
    // 4. bodies
    bad = [];
    for (const b of ['null', '[]', '"x"', '123', 'true', '{"id":{"$ne":1}}', '{"id":["local1"]}', '{"__proto__":{"polluted":1},"id":"x"}', '{"constructor":{"prototype":{"polluted":1}}}']) for (const r of routes) {
        const x = await req('POST', r, b);
        if (x.status >= 500 || ({}).polluted) bad.push(`${r} ${b} -> ${x.status} ${x.text.slice(0, 60)}`);
    }
    check('odd JSON bodies on every route: no server error', !bad.length, bad.slice(0, 6).join('; '));
    const s1 = await state();
    check('odd bodies changed nothing but the event list', s1.servers.length === 2 || s1.servers.every(s => s.cfg.id), s1.servers.map(s => s.cfg.name).join());
    for (const s of s1.servers.filter(s => !['local1', 'ssh1'].includes(s.cfg.id))) await post('server/remove', { id: s.cfg.id, deleteHistory: true }); // "add" accepted {name?}: none expected
    const run = await req('POST', '/api/run', { id: 'ssh1', list: '__proto__', i: 0, arg: 1 }), run2 = await req('POST', '/api/run', { id: 'ssh1', list: 'procActions', i: '__proto__', arg: 1 }), run3 = await req('POST', '/api/run', { id: 'ssh1', list: 'diagnostics', i: 0, arg: 1 });
    check('command tables cannot be addressed through prototype keys or other lists', [run, run2, run3].every(r => r.status === 400), [run, run2, run3].map(r => r.status).join());
    const big = await req('POST', '/api/exec', JSON.stringify({ id: 'ssh1', cmd: 'x'.repeat(3 << 20) })).catch(e => ({ status: 0, text: e.code }));
    check('a 3 MB body is cut off', big.status === 0 || big.status >= 400, `${big.status} ${big.text}`);
    check('the server still answers', (await req('GET', '/api/state')).status === 200);
    // 5. quoting of names (commands for the unreachable server are returned, not run)
    const nasty = `a'b"c$(touch ${cfg}.pwned)\`touch ${cfg}.pwned\`;touch ${cfg}.pwned|&\n$HOME %PATH% -rf`;
    const svc = (await post('run', { id: 'ssh1', list: 'serviceActions', i: 0, arg: nasty })).cmd;
    const expect = win ? `Start-Service -Name '${nasty.replace(/'/g, "''")}'` : `systemctl start '${nasty.replace(/'/g, "'\\''")}'`;
    check('service name is one quoted argument in the command', svc === expect, JSON.stringify(svc));
    const logs = await post('logs', { id: 'local1', unit: nasty, lines: '50; touch ' + cfg + '.pwned' });
    await sleep(500);
    check('service logs with a hostile name and line count: nothing is injected', !fs.existsSync(cfg + '.pwned') && typeof logs.out === 'string', JSON.stringify(logs.out.slice(0, 120)));
    if (win) { const l = fs.readFileSync(cfg + '.log', 'utf8'); check('PowerShell: the name arrives single-quoted with doubled quotes, lines as a number', l.includes(`Where-Object Name -eq '${nasty.replace(/'/g, "''").split('\n')[0]}`) && /Select-Object -First 50 \|/.test(l)); }
    const pid = (await post('run', { id: 'ssh1', list: 'procActions', i: 1, arg: '4242' })).cmd, prio = (await post('run', { id: 'ssh1', list: 'priorities', i: 0, arg: 77 })).cmd;
    check('pid commands take digits only', pid === (win ? 'taskkill /F /PID 4242' : 'kill -KILL 4242') && prio === (win ? "(Get-Process -Id 77).PriorityClass = 'Idle'" : 'renice -n -20 -p 77') && (await req('POST', '/api/run', { id: 'ssh1', list: 'procActions', i: 1, arg: '1 2' })).status === 400, `${pid} | ${prio}`);
    // 6. file modes
    const mode = f => (fs.statSync(f).mode & 0o777).toString(8);
    await post('server/update', { id: 'ssh1', notes: 'saved' });
    check('servers.json is 600 after a save (whatever it was before)', mode(path.join(dir, 'servers.json')) === '600');
    done();
})();