ai-secure-audit 0.0.11 → 0.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/config/targets.example.yml +9 -0
- package/package.json +2 -1
- package/src/cli.js +27 -2
- package/src/extract.js +31 -0
- package/src/findings.js +1 -1
- package/src/live/testssl.js +84 -0
- package/src/live/zap.js +91 -0
- package/src/live.js +161 -0
- package/src/report-simple.js +105 -0
- package/src/targets.js +80 -0
- package/src/tools.js +50 -3
- package/tools.lock.json +77 -54
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
> Status: 0.0.x on npm runs the basic check with `npx ai-secure-audit`: secrets, libraries with known holes and, from
|
|
4
4
|
> 0.0.5, code rules for routes anyone can repeat without limit and, from 0.0.9, for session checks that a built-in
|
|
5
5
|
> name such as `constructor` passes. From 0.0.10 it also checks Dockerfiles with trivy (Compose files are not read yet,
|
|
6
|
-
> and the report says so), and from 0.0.11 it warns when a Docker build would copy these results into the image. v0.1 is not released yet.
|
|
6
|
+
> and the report says so), and from 0.0.11 it warns when a Docker build would copy these results into the image, and from 0.0.13 `--report simple` writes a short to-do list in plain words (`report-simple.md`) and `live` checks one host you list in `targets.yml`: its TLS with testssl.sh, and with `--zap` its web headers and cookies with OWASP ZAP in Docker. `live` has only been tried on servers on the same machine and a GitHub test runner, never on a real remote site, and it does not run on Windows (TLS part) or without Docker (ZAP part). v0.1 is not released yet.
|
|
7
7
|
>
|
|
8
8
|
> **มือใหม่เริ่มตรงนี้:** [learn/](learn/) ควรตรวจอะไรก่อน เพราะอะไร และแก้ยังไง (ภาษาไทย)
|
|
9
9
|
>
|
|
@@ -58,7 +58,7 @@ node ai-secure-audit/bin/ai-secure-audit.js /tmp/demo-app
|
|
|
58
58
|
Or ask your AI assistant: *"Run `node <path-to>/ai-secure-audit/bin/ai-secure-audit.js` on this project, explain the
|
|
59
59
|
results in simple words, and help me fix the most serious ones first."*
|
|
60
60
|
|
|
61
|
-
Results go to `.audit/out/` in your project (`report.md` for people, `findings.json` for tools and AI). That folder
|
|
61
|
+
Results go to `.audit/out/` in your project (`report.md` for people, `report-simple.md` too if you add `--report simple`: a short to-do list for someone who does not know security words, `findings.json` for tools and AI). That folder
|
|
62
62
|
ignores itself in git, so results are not committed by accident. Git is not the only way out, though: a `Dockerfile`
|
|
63
63
|
with `COPY . .` puts every file in the folder into the image. From 0.0.11 the report warns (under "About these
|
|
64
64
|
results") when a `Dockerfile` at the top of the project copies the whole folder and `.dockerignore` does not leave out
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# targets.yml: the hosts you own or have permission to test.
|
|
2
|
+
# `ai-secure-audit live` refuses any host that is not listed here. Keep this file out of git (add it to .gitignore).
|
|
3
|
+
targets:
|
|
4
|
+
- host: dev.example.com
|
|
5
|
+
scheme: https # https (default) or http. http has no TLS to check; use it with --zap for a plain-http dev server.
|
|
6
|
+
env: dev # dev (default) or prod. prod also needs --allow-prod on the command line.
|
|
7
|
+
- host: www.example.com
|
|
8
|
+
port: 443 # optional, default 443
|
|
9
|
+
env: prod
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-secure-audit",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.13",
|
|
4
4
|
"description": "Free, open-source security check for apps built with AI. Runs pinned open-source scanners; no AI needed to run.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"bin/",
|
|
20
20
|
"src/",
|
|
21
21
|
"rules/",
|
|
22
|
+
"config/targets.example.yml",
|
|
22
23
|
"tools.lock.json"
|
|
23
24
|
],
|
|
24
25
|
"engines": {
|
package/src/cli.js
CHANGED
|
@@ -2,6 +2,8 @@ import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
|
2
2
|
import { join, relative } from 'node:path';
|
|
3
3
|
import { scan, outDir } from './scan.js';
|
|
4
4
|
import { reportMarkdown, consoleSummary } from './report.js';
|
|
5
|
+
import { live, liveSummary } from './live.js';
|
|
6
|
+
import { reportSimple } from './report-simple.js';
|
|
5
7
|
import { atOrAbove, SEVERITY_ORDER } from './findings.js';
|
|
6
8
|
import { cacheDir, lockedTools, platformKey } from './tools.js';
|
|
7
9
|
|
|
@@ -14,12 +16,17 @@ Usage: npx ai-secure-audit [command] [path] [options]
|
|
|
14
16
|
Commands
|
|
15
17
|
scan [path] basic check of a project folder (default command, default path ".")
|
|
16
18
|
retest [path] run the check again and compare with the last result
|
|
19
|
+
live <host> check the TLS of one host from your targets file (about 2 minutes; see docs/cli.md)
|
|
17
20
|
tools list pinned tool versions, licenses and the cache folder
|
|
18
21
|
init install the AI skills into this project (not available yet)
|
|
19
22
|
mcp run as an MCP server (not available yet)
|
|
20
23
|
|
|
21
24
|
Options
|
|
22
25
|
--json print findings.json to stdout instead of the summary
|
|
26
|
+
--report simple also write report-simple.md: a short to-do list in plain words
|
|
27
|
+
--targets <file> for live: the list of hosts you may check (default: targets.yml)
|
|
28
|
+
--zap for live: also run the ZAP baseline web check in Docker (passive: reads responses only)
|
|
29
|
+
--allow-prod for live: also allow hosts marked prod in the targets file
|
|
23
30
|
--fail-on <level> exit 1 if a finding is at or above: ${SEVERITY_ORDER.slice(0, 4).join(', ')}
|
|
24
31
|
--advanced add the Docker-based advanced tools (not available yet)
|
|
25
32
|
-h, --help show this help
|
|
@@ -28,12 +35,17 @@ Options
|
|
|
28
35
|
Results are written to <path>/.audit/out/ (git-ignored automatically).`;
|
|
29
36
|
|
|
30
37
|
function parseArgs(argv) {
|
|
31
|
-
const opts = { command: 'scan', path: '.', json: false, failOn: null, advanced: false };
|
|
38
|
+
const opts = { command: 'scan', path: '.', json: false, failOn: null, advanced: false, report: null, targets: 'targets.yml', allowProd: false, zap: false };
|
|
32
39
|
const rest = [];
|
|
33
40
|
for (let i = 0; i < argv.length; i++) {
|
|
34
41
|
const a = argv[i];
|
|
35
42
|
if (a === '--json') opts.json = true;
|
|
36
43
|
else if (a === '--advanced') opts.advanced = true;
|
|
44
|
+
else if (a === '--allow-prod') opts.allowProd = true;
|
|
45
|
+
else if (a === '--zap') opts.zap = true;
|
|
46
|
+
else if (a === '--targets') opts.targets = argv[++i];
|
|
47
|
+
else if (a === '--report') opts.report = argv[++i];
|
|
48
|
+
else if (a.startsWith('--report=')) opts.report = a.slice(9);
|
|
37
49
|
else if (a === '--fail-on') opts.failOn = argv[++i];
|
|
38
50
|
else if (a.startsWith('--fail-on=')) opts.failOn = a.slice(10);
|
|
39
51
|
else if (a === '-h' || a === '--help') opts.command = 'help';
|
|
@@ -41,8 +53,9 @@ function parseArgs(argv) {
|
|
|
41
53
|
else if (a.startsWith('-')) throw new Error(`unknown option: ${a}`);
|
|
42
54
|
else rest.push(a);
|
|
43
55
|
}
|
|
44
|
-
if (opts.command === 'scan' && ['scan', 'retest', 'tools', 'init', 'mcp', 'help'].includes(rest[0])) opts.command = rest.shift();
|
|
56
|
+
if (opts.command === 'scan' && ['scan', 'retest', 'live', 'tools', 'init', 'mcp', 'help'].includes(rest[0])) opts.command = rest.shift();
|
|
45
57
|
if (rest[0]) opts.path = rest[0];
|
|
58
|
+
if (opts.report && opts.report !== 'simple') throw new Error('--report must be: simple');
|
|
46
59
|
if (opts.failOn && !SEVERITY_ORDER.slice(0, 4).includes(opts.failOn)) throw new Error(`--fail-on must be one of ${SEVERITY_ORDER.slice(0, 4).join(', ')}`);
|
|
47
60
|
return opts;
|
|
48
61
|
}
|
|
@@ -69,12 +82,15 @@ async function runScan(opts, { retest }) {
|
|
|
69
82
|
|
|
70
83
|
const { root, out, result } = await scan(opts.path, { log, version: pkg.version });
|
|
71
84
|
writeFileSync(join(out, 'report.md'), reportMarkdown(result, new Date().toISOString().slice(0, 10)));
|
|
85
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
86
|
+
if (opts.report === 'simple') writeFileSync(join(out, 'report-simple.md'), reportSimple(result, date));
|
|
72
87
|
const r = relative(process.cwd(), out);
|
|
73
88
|
const outRel = (r && !r.startsWith('..') ? r : out).split('\\').join('/');
|
|
74
89
|
|
|
75
90
|
if (opts.json) process.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
|
76
91
|
else {
|
|
77
92
|
process.stdout.write(consoleSummary(result, outRel) + '\n');
|
|
93
|
+
if (opts.report === 'simple') process.stdout.write(`\nPlain to-do list: ${outRel}/report-simple.md\n`);
|
|
78
94
|
if (prev) {
|
|
79
95
|
const d = compare(prev, result);
|
|
80
96
|
writeFileSync(join(out, 'retest.json'), JSON.stringify({
|
|
@@ -108,6 +124,15 @@ export async function main(argv) {
|
|
|
108
124
|
process.stdout.write(`\nplatform: ${platformKey()}\ncache: ${cacheDir()}\n`);
|
|
109
125
|
return 0;
|
|
110
126
|
}
|
|
127
|
+
case 'live': {
|
|
128
|
+
if (opts.path === '.') throw new Error('live needs a host: npx ai-secure-audit live <host[:port]>');
|
|
129
|
+
const log = opts.json ? () => {} : (m) => process.stderr.write(`${m}\n`);
|
|
130
|
+
const { out, result } = await live(opts.path, { targetsFile: opts.targets, allowProd: opts.allowProd, zap: opts.zap, log, version: pkg.version });
|
|
131
|
+
const r = relative(process.cwd(), out).split('\\').join('/');
|
|
132
|
+
process.stdout.write(opts.json ? JSON.stringify(result, null, 2) + '\n' : liveSummary(result, r) + '\n');
|
|
133
|
+
if (result.tools.some((t) => t.status === 'failed')) return 2;
|
|
134
|
+
return opts.failOn && atOrAbove(result.findings, opts.failOn).length ? 1 : 0;
|
|
135
|
+
}
|
|
111
136
|
case 'init':
|
|
112
137
|
case 'mcp':
|
|
113
138
|
process.stderr.write(`\`${opts.command}\` is not available yet. See docs/cli.md.\n`);
|
package/src/extract.js
CHANGED
|
@@ -51,3 +51,34 @@ export function fromZip(buf, name) {
|
|
|
51
51
|
}
|
|
52
52
|
throw new Error(`${name} not found in archive`);
|
|
53
53
|
}
|
|
54
|
+
|
|
55
|
+
// Whole-folder reader for tools that ship as a folder (testssl.sh). Returns [{ path, mode, data }] in memory, so the
|
|
56
|
+
// content can be checked against the pinned hash before anything is written to disk.
|
|
57
|
+
// Only plain files and folders are accepted; an entry that would land outside the target is an error.
|
|
58
|
+
export function treeFromTarGz(buf, strip = 1) {
|
|
59
|
+
const tar = gunzipSync(buf);
|
|
60
|
+
const files = [];
|
|
61
|
+
let longName = null;
|
|
62
|
+
for (let off = 0; off + 512 <= tar.length; ) {
|
|
63
|
+
const header = tar.subarray(off, off + 512);
|
|
64
|
+
if (header.every((b) => b === 0)) break;
|
|
65
|
+
const field = (start, len) => header.subarray(start, start + len).toString('utf8').replace(/\0.*$/s, '');
|
|
66
|
+
const size = parseInt(field(124, 12).trim() || '0', 8);
|
|
67
|
+
const type = field(156, 1);
|
|
68
|
+
const data = tar.subarray(off + 512, off + 512 + size);
|
|
69
|
+
const rawPath = longName ?? (field(345, 155) ? `${field(345, 155)}/${field(0, 100)}` : field(0, 100));
|
|
70
|
+
longName = null;
|
|
71
|
+
if (type === 'L') longName = data.toString('utf8').replace(/\0.*$/s, '');
|
|
72
|
+
else if (type === '0' || type === '') {
|
|
73
|
+
const parts = rawPath.split('/').filter(Boolean).slice(strip);
|
|
74
|
+
if (parts.some((p) => p === '..' || p === '.') || rawPath.startsWith('/') || rawPath.includes('\\')) {
|
|
75
|
+
throw new Error(`unsafe path in archive: ${rawPath}`);
|
|
76
|
+
}
|
|
77
|
+
if (parts.length) files.push({ path: parts.join('/'), mode: parseInt(field(100, 8).trim() || '644', 8) & 0o777, data: Buffer.from(data) });
|
|
78
|
+
} else if (!['5', 'g', 'x'].includes(type)) {
|
|
79
|
+
throw new Error(`unsupported entry type "${type}" in archive: ${rawPath}`);
|
|
80
|
+
}
|
|
81
|
+
off += 512 + Math.ceil(size / 512) * 512;
|
|
82
|
+
}
|
|
83
|
+
return files;
|
|
84
|
+
}
|
package/src/findings.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export const SEVERITY_ORDER = ['critical', 'high', 'medium', 'low', 'info'];
|
|
2
|
-
const CATEGORY_ORDER = ['secret', 'dependency', 'config', 'code'];
|
|
2
|
+
const CATEGORY_ORDER = ['secret', 'dependency', 'config', 'code', 'tls', 'web'];
|
|
3
3
|
|
|
4
4
|
// Stable order: same inputs give byte-identical findings.json.
|
|
5
5
|
export function sortAndNumber(findings) {
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// testssl.sh: TLS check of one live host. Turns its flat list into a few findings.
|
|
2
|
+
// testssl reports ~170 lines for one host (one per cipher, grades, hints). Only the ids below can become a finding;
|
|
3
|
+
// the rest stays in the raw file. A line about testssl itself (engine, deprecated flags) is never a finding.
|
|
4
|
+
|
|
5
|
+
const SEVERITY = { CRITICAL: 'critical', HIGH: 'high', MEDIUM: 'medium', LOW: 'low' };
|
|
6
|
+
|
|
7
|
+
const FIX = {
|
|
8
|
+
protocol: 'Turn off this old TLS/SSL version on the server or proxy. Keep TLS 1.2 and TLS 1.3 only. Browsers that need less are gone.',
|
|
9
|
+
cipher: 'Remove this group of weak ciphers from the server or proxy cipher list. Use the "modern" or "intermediate" list from the Mozilla SSL Configuration Generator.',
|
|
10
|
+
cert_trust: 'Install a certificate from a trusted authority (Let\'s Encrypt is free) that includes this exact host name, with the full chain.',
|
|
11
|
+
cert_expiry: 'Renew the certificate now and set up automatic renewal (certbot, Caddy and most hosting panels do this).',
|
|
12
|
+
cert_key: 'Issue a new certificate with a modern key (RSA 2048 or more, or ECDSA P-256) and a SHA-256 signature.',
|
|
13
|
+
hsts: 'Send the header `Strict-Transport-Security: max-age=31536000` from the HTTPS site, after you are sure every sub-page works on HTTPS.',
|
|
14
|
+
vuln: 'Update the server software (OpenSSL, nginx, Apache or the proxy in front) and its TLS settings, then run the check again.',
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// id -> [title, fix, category of the problem]. cert_* are capped at high: a self-signed cert on a dev host is not critical.
|
|
18
|
+
const CURATED = {
|
|
19
|
+
SSLv2: ['SSLv2 is offered', FIX.protocol],
|
|
20
|
+
SSLv3: ['SSLv3 is offered', FIX.protocol],
|
|
21
|
+
TLS1: ['TLS 1.0 is offered', FIX.protocol],
|
|
22
|
+
TLS1_1: ['TLS 1.1 is offered', FIX.protocol],
|
|
23
|
+
cipherlist_NULL: ['Ciphers with no encryption are offered', FIX.cipher],
|
|
24
|
+
cipherlist_aNULL: ['Ciphers with no authentication are offered', FIX.cipher],
|
|
25
|
+
cipherlist_EXPORT: ['Export-grade (deliberately weak) ciphers are offered', FIX.cipher],
|
|
26
|
+
cipherlist_LOW: ['Weak ciphers (64-bit, DES, RC2, RC4, MD5) are offered', FIX.cipher],
|
|
27
|
+
cipherlist_3DES_IDEA: ['Triple-DES / IDEA ciphers are offered', FIX.cipher],
|
|
28
|
+
cert_chain_of_trust: ['The certificate is not trusted', FIX.cert_trust],
|
|
29
|
+
cert_trust: ['The certificate does not match the host name', FIX.cert_trust],
|
|
30
|
+
cert_subjectAltName: ['The certificate has no Subject Alternative Name', FIX.cert_trust],
|
|
31
|
+
cert_expirationStatus: ['The certificate is expired or about to expire', FIX.cert_expiry],
|
|
32
|
+
cert_signatureAlgorithm: ['The certificate uses a weak signature', FIX.cert_key],
|
|
33
|
+
cert_keySize: ['The certificate key is weak', FIX.cert_key],
|
|
34
|
+
HSTS: ['HSTS is not sent', FIX.hsts],
|
|
35
|
+
heartbleed: ['Heartbleed', FIX.vuln], CCS: ['CCS injection', FIX.vuln], ticketbleed: ['Ticketbleed', FIX.vuln],
|
|
36
|
+
ROBOT: ['ROBOT', FIX.vuln], secure_renego: ['Insecure renegotiation', FIX.vuln],
|
|
37
|
+
secure_client_renego: ['Client-initiated renegotiation (denial of service)', FIX.vuln],
|
|
38
|
+
CRIME_TLS: ['CRIME', FIX.vuln], POODLE_SSL: ['POODLE', FIX.vuln], SWEET32: ['SWEET32', FIX.vuln],
|
|
39
|
+
FREAK: ['FREAK', FIX.vuln], DROWN: ['DROWN', FIX.vuln], LOGJAM: ['LOGJAM', FIX.vuln], BEAST: ['BEAST', FIX.vuln],
|
|
40
|
+
RC4: ['RC4 ciphers are offered', FIX.cipher], winshock: ['Winshock', FIX.vuln],
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// The result is only trusted if testssl reached the host and spoke TLS to it.
|
|
44
|
+
const PROOF_OF_TLS = ['SSLv3', 'TLS1', 'TLS1_1', 'TLS1_2', 'TLS1_3'];
|
|
45
|
+
|
|
46
|
+
export function parseTestssl(json, { host, port }) {
|
|
47
|
+
const rows = Array.isArray(json) ? json : [];
|
|
48
|
+
if (!rows.some((r) => PROOF_OF_TLS.includes(r.id))) {
|
|
49
|
+
throw new Error(`testssl could not talk TLS to ${host}:${port} (no TLS answer: wrong port, no HTTPS, or blocked)`);
|
|
50
|
+
}
|
|
51
|
+
const findings = [];
|
|
52
|
+
const notices = [];
|
|
53
|
+
for (const r of rows) {
|
|
54
|
+
const c = CURATED[r.id];
|
|
55
|
+
if (!c) continue;
|
|
56
|
+
if (r.severity === 'WARN') {
|
|
57
|
+
// The test did not run (e.g. the local OpenSSL has no RC4): "no finding" would read as a pass. Say so.
|
|
58
|
+
notices.push({ id: r.id, message: `testssl could not check "${c[0]}": ${r.finding}` });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
let sev = SEVERITY[r.severity];
|
|
62
|
+
if (!sev) continue; // OK and INFO are not problems
|
|
63
|
+
if (r.id.startsWith('cert_') && (sev === 'critical')) sev = 'high';
|
|
64
|
+
findings.push({
|
|
65
|
+
fingerprint: `testssl:${r.id}:${host}:${port}`,
|
|
66
|
+
category: 'tls',
|
|
67
|
+
title: c[0],
|
|
68
|
+
severity: { tool: r.severity, normalized: sev },
|
|
69
|
+
source: { kind: 'tool', tool: 'testssl', rule_id: r.id },
|
|
70
|
+
evidence: [{ location: `${host}:${port}`, detail: String(r.finding).slice(0, 300) }],
|
|
71
|
+
fix: c[1],
|
|
72
|
+
references: r.cwe ? { cwe: [r.cwe] } : {},
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return { findings, notices };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function testsslArgs(host, port, rawFile) {
|
|
79
|
+
// --ip one: test a single address, so a host behind many addresses is not hit many times.
|
|
80
|
+
// No --connect-timeout: testssl needs a `timeout` command for it and macOS has none. `live` stops the run after 15 minutes.
|
|
81
|
+
// No --fast (not recommended by testssl) and nothing that sends attack traffic beyond testssl's own TLS probes.
|
|
82
|
+
return ['--quiet', '--warnings', 'off', '--color', '0', '--ip', 'one',
|
|
83
|
+
'--jsonfile', rawFile, `${host}:${port}`];
|
|
84
|
+
}
|
package/src/live/zap.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// OWASP ZAP baseline: a passive check of one live web site, run in Docker.
|
|
2
|
+
// "Baseline" = spider for about a minute, then read every response with ZAP's passive rules. It sends ordinary GET
|
|
3
|
+
// requests and nothing that attacks. This tool never runs ZAP's active or full scan.
|
|
4
|
+
//
|
|
5
|
+
// What it finds: header, cookie and information-leak mistakes. What it cannot find (say so in every report):
|
|
6
|
+
// XSS, injection, broken login, access control. Those need an active scan or a person.
|
|
7
|
+
|
|
8
|
+
export const ZAP_NOT_CHECKED =
|
|
9
|
+
'ZAP baseline only reads responses. It does not find XSS, injection, broken login or access control: ' +
|
|
10
|
+
'a clean result here says nothing about them.';
|
|
11
|
+
|
|
12
|
+
const RISK = { 3: 'high', 2: 'medium', 1: 'low' };
|
|
13
|
+
|
|
14
|
+
// pluginid -> true when the alert is only as good as a banner the server sends about itself.
|
|
15
|
+
// Everything not listed here is left out (ids 10019, 10049, 10027, 10109, 10063, 90004 ... are advice or noise).
|
|
16
|
+
const CURATED = {
|
|
17
|
+
10003: false, // vulnerable JavaScript library
|
|
18
|
+
10010: false, // cookie without HttpOnly
|
|
19
|
+
10011: false, // cookie without Secure
|
|
20
|
+
10020: false, // missing anti-clickjacking header
|
|
21
|
+
10021: false, // X-Content-Type-Options missing
|
|
22
|
+
10023: false, // debug error messages
|
|
23
|
+
10024: false, // sensitive information in URL
|
|
24
|
+
10035: false, // HSTS missing (https)
|
|
25
|
+
10036: true, // Server header leaks version
|
|
26
|
+
10037: true, // X-Powered-By leaks
|
|
27
|
+
10038: false, // CSP not set
|
|
28
|
+
10054: false, // cookie without SameSite
|
|
29
|
+
10061: true, // X-AspNet-Version leaks
|
|
30
|
+
10062: false, // PII disclosure
|
|
31
|
+
10098: false, // cross-domain misconfiguration (CORS)
|
|
32
|
+
10105: false, // weak authentication method
|
|
33
|
+
10202: false, // absence of anti-CSRF tokens
|
|
34
|
+
20020: true, // server version with known vulnerabilities (from the banner)
|
|
35
|
+
90003: false, // subresource integrity missing
|
|
36
|
+
90022: false, // application error disclosure
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function plain(html) {
|
|
40
|
+
return String(html ?? '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 400);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function parseZap(json, { url }) {
|
|
44
|
+
const site = json?.site?.[0];
|
|
45
|
+
if (!site) throw new Error(`ZAP found no site at ${url} (not reachable from Docker, or nothing answered)`);
|
|
46
|
+
const findings = [];
|
|
47
|
+
for (const a of site.alerts ?? []) {
|
|
48
|
+
const id = Number(a.pluginid);
|
|
49
|
+
if (!(id in CURATED)) continue;
|
|
50
|
+
let sev = RISK[Number(a.riskcode)];
|
|
51
|
+
if (!sev) continue;
|
|
52
|
+
const banner = CURATED[id];
|
|
53
|
+
// ZAP trusts what the server says about itself: it can rate "Apache 2.2 with known holes" high for a lie.
|
|
54
|
+
if (banner && sev === 'high') sev = 'medium';
|
|
55
|
+
const inst = a.instances ?? [];
|
|
56
|
+
const total = Number(a.count) || inst.length;
|
|
57
|
+
findings.push({
|
|
58
|
+
fingerprint: `zap:${a.alertRef ?? id}:${url}`,
|
|
59
|
+
category: 'web',
|
|
60
|
+
title: a.name,
|
|
61
|
+
severity: { tool: `ZAP risk ${a.riskcode}`, normalized: sev },
|
|
62
|
+
source: { kind: 'tool', tool: 'zap-baseline', rule_id: String(a.alertRef ?? id) },
|
|
63
|
+
evidence: inst.slice(0, 3).map((i, n) => ({
|
|
64
|
+
location: `${i.method ?? 'GET'} ${i.uri}`,
|
|
65
|
+
detail: [
|
|
66
|
+
n === 0 && total > 3 ? `${total} places in total, first 3 shown.` : '',
|
|
67
|
+
i.evidence ? `Seen: ${String(i.evidence).slice(0, 80)}` : '',
|
|
68
|
+
banner ? 'Based on what the server says about itself; it may not be true.' : '',
|
|
69
|
+
].filter(Boolean).join(' ') || a.name,
|
|
70
|
+
})),
|
|
71
|
+
fix: plain(a.solution) || 'See the ZAP alert for this check.',
|
|
72
|
+
references: a.cweid && Number(a.cweid) > 0 ? { cwe: [`CWE-${a.cweid}`] } : {},
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return { findings, notices: [] };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// docker arguments. The URL is the only thing taken from the target; the scan type is fixed.
|
|
79
|
+
// -m 1: spider for one minute. -I: do not make the exit code depend on warnings (we read the JSON).
|
|
80
|
+
export function zapDockerArgs({ image, dir, url }) {
|
|
81
|
+
return ['run', '--rm', '--security-opt', 'no-new-privileges', '--add-host', 'host.docker.internal:host-gateway',
|
|
82
|
+
'-v', `${dir}:/zap/wrk:rw`, image, 'zap-baseline.py', '-t', url, '-J', 'report.json', '-m', '1', '-I'];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// A server on this machine is reached from the container through host.docker.internal.
|
|
86
|
+
export function zapUrl({ scheme, host, port }) {
|
|
87
|
+
const local = ['localhost', '127.0.0.1', '::1'].includes(host);
|
|
88
|
+
const h = local ? 'host.docker.internal' : host;
|
|
89
|
+
const dflt = scheme === 'http' ? 80 : 443;
|
|
90
|
+
return `${scheme}://${h}${port === dflt ? '' : `:${port}`}`;
|
|
91
|
+
}
|
package/src/live.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { ensureFolderTool, liveTools } from './tools.js';
|
|
5
|
+
import { sortAndNumber, countBySeverity } from './findings.js';
|
|
6
|
+
import { loadTargets, resolveTarget } from './targets.js';
|
|
7
|
+
import { parseTestssl, testsslArgs } from './live/testssl.js';
|
|
8
|
+
import { parseZap, zapDockerArgs, zapUrl, ZAP_NOT_CHECKED } from './live/zap.js';
|
|
9
|
+
|
|
10
|
+
// `live` checks one host from the targets file. It is a different kind of check from `scan`:
|
|
11
|
+
// it talks to a server, so it only runs against a host the owner listed, and production needs --allow-prod.
|
|
12
|
+
// Each step ends as ok, skipped (does not apply, said so) or failed (did not run: never read as a pass).
|
|
13
|
+
|
|
14
|
+
function ok(cmd, args) {
|
|
15
|
+
const r = spawnSync(cmd, args, { encoding: 'utf8' });
|
|
16
|
+
return !r.error && r.status === 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function tlsStep({ target, out, log }) {
|
|
20
|
+
const { host, port } = target;
|
|
21
|
+
const lock = liveTools().testssl;
|
|
22
|
+
if (process.platform === 'win32') throw new Error('not supported on Windows (it needs bash): use WSL or Docker');
|
|
23
|
+
if (!ok('bash', ['--version'])) throw new Error('bash was not found');
|
|
24
|
+
if (!ok('openssl', ['version'])) throw new Error('openssl was not found');
|
|
25
|
+
const script = await ensureFolderTool('testssl', log);
|
|
26
|
+
const rawFile = join(out, 'testssl.json');
|
|
27
|
+
rmSync(rawFile, { force: true });
|
|
28
|
+
log(`checking TLS on ${host}:${port} with testssl ${lock.version} (about 2 minutes) ...`);
|
|
29
|
+
const r = spawnSync('bash', [script, ...testsslArgs(host, port, rawFile)], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 15 * 60 * 1000 });
|
|
30
|
+
if (r.error) throw r.error;
|
|
31
|
+
if (!existsSync(rawFile)) throw new Error(`testssl wrote no result: ${(r.stdout || r.stderr || '').trim().split('\n').slice(-2).join(' ')}`);
|
|
32
|
+
return parseTestssl(JSON.parse(readFileSync(rawFile, 'utf8') || 'null'), { host, port });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function zapStep({ target, out, log }) {
|
|
36
|
+
const lock = liveTools().zap;
|
|
37
|
+
if (!ok('docker', ['version', '--format', '{{.Server.Version}}'])) throw new Error('Docker is not installed or not running');
|
|
38
|
+
const url = zapUrl(target);
|
|
39
|
+
// The container writes its report here as a different user, so the folder must be writable by anyone.
|
|
40
|
+
const dir = join(out, 'zap');
|
|
41
|
+
rmSync(dir, { recursive: true, force: true });
|
|
42
|
+
mkdirSync(dir, { recursive: true });
|
|
43
|
+
chmodSync(dir, 0o777);
|
|
44
|
+
log(`checking ${url} with ZAP ${lock.version} baseline in Docker (about 1 to 2 minutes; the first time it downloads the image) ...`);
|
|
45
|
+
const r = spawnSync('docker', zapDockerArgs({ image: lock.image, dir, url }), { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 15 * 60 * 1000 });
|
|
46
|
+
if (r.error) throw r.error;
|
|
47
|
+
const rawFile = join(dir, 'report.json');
|
|
48
|
+
if (!existsSync(rawFile)) throw new Error(`ZAP wrote no result: ${(r.stdout || r.stderr || '').trim().split('\n').slice(-2).join(' ')}`);
|
|
49
|
+
return parseZap(JSON.parse(readFileSync(rawFile, 'utf8') || 'null'), { url });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function live(arg, { targetsFile, allowProd, zap = false, log = () => {}, version, cwd = process.cwd() }) {
|
|
53
|
+
const target = resolveTarget(arg, loadTargets(resolve(cwd, targetsFile)), { allowProd });
|
|
54
|
+
const { host, port } = target;
|
|
55
|
+
if (target.scheme === 'http' && !zap) {
|
|
56
|
+
throw new Error(`${host}:${port} is plain http, so there is no TLS to check. Add --zap to check the web site itself.`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const out = join(cwd, '.audit', 'out', 'live', `${host}-${port}`);
|
|
60
|
+
mkdirSync(out, { recursive: true });
|
|
61
|
+
writeFileSync(join(cwd, '.audit', 'out', '.gitignore'), '*\n');
|
|
62
|
+
|
|
63
|
+
const steps = [];
|
|
64
|
+
if (target.scheme === 'https') steps.push({ id: 'testssl', run: tlsStep, tool: liveTools().testssl });
|
|
65
|
+
else steps.push({ id: 'testssl', skip: 'plain http: there is no TLS to check', tool: liveTools().testssl });
|
|
66
|
+
if (zap) steps.push({ id: 'zap-baseline', run: zapStep, tool: liveTools().zap });
|
|
67
|
+
|
|
68
|
+
const runs = [];
|
|
69
|
+
let findings = [];
|
|
70
|
+
let notices = [];
|
|
71
|
+
for (const s of steps) {
|
|
72
|
+
const run = { id: s.id, version: s.tool.version, license: s.tool.license, status: 'ok' };
|
|
73
|
+
runs.push(run);
|
|
74
|
+
if (s.skip) { run.status = 'skipped'; run.note = s.skip; continue; }
|
|
75
|
+
try {
|
|
76
|
+
const parsed = await s.run({ target, out, log });
|
|
77
|
+
const found = parsed.findings.map((f) => ({ ...f, source: { ...f.source, tool_version: s.tool.version } }));
|
|
78
|
+
findings = findings.concat(found);
|
|
79
|
+
notices = notices.concat(parsed.notices);
|
|
80
|
+
run.findings = found.length;
|
|
81
|
+
} catch (err) {
|
|
82
|
+
run.status = 'failed';
|
|
83
|
+
run.error = err.message;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const notes = [];
|
|
88
|
+
if (steps.some((s) => s.id === 'testssl' && !s.skip)) {
|
|
89
|
+
notes.push('TLS check: only this one host and port: protocols, ciphers, the certificate, HSTS and known TLS weaknesses.');
|
|
90
|
+
}
|
|
91
|
+
if (zap) notes.push(`Web check: ${ZAP_NOT_CHECKED} It also trusts what the server says about itself (a made-up Server header is believed).`);
|
|
92
|
+
notes.push('Not checked: the app\'s own logic (who may see or change what), other hosts and ports.');
|
|
93
|
+
|
|
94
|
+
const result = {
|
|
95
|
+
generator: `ai-secure-audit ${version}`,
|
|
96
|
+
check: zap ? 'live-tls-web' : 'live-tls',
|
|
97
|
+
target: { host, port, scheme: target.scheme, env: target.env },
|
|
98
|
+
tools: runs,
|
|
99
|
+
notices,
|
|
100
|
+
notes,
|
|
101
|
+
findings: sortAndNumber(findings),
|
|
102
|
+
};
|
|
103
|
+
writeFileSync(join(out, 'findings.json'), JSON.stringify(result, null, 2) + '\n');
|
|
104
|
+
writeFileSync(join(out, 'report.md'), liveReport(result, new Date().toISOString().slice(0, 10)));
|
|
105
|
+
return { out, result };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function liveReport(result, date) {
|
|
109
|
+
const { findings, tools, target, notices } = result;
|
|
110
|
+
const c = countBySeverity(findings);
|
|
111
|
+
const L = [`# Live check: ${target.host}:${target.port}`, ''];
|
|
112
|
+
L.push(`${result.generator} · ${result.check} · ${date} · ${target.env}`, '');
|
|
113
|
+
L.push('This is a self-check with free open-source tools. It is not a certification and does not prove the site is secure.', '');
|
|
114
|
+
const failed = tools.filter((t) => t.status === 'failed');
|
|
115
|
+
if (failed.length) {
|
|
116
|
+
L.push('> **Some checks did not run:** ' + failed.map((t) => `${t.id} (${t.error})`).join('; '), '');
|
|
117
|
+
L.push('Do not read this as "no problems" for the parts that did not run.', '');
|
|
118
|
+
}
|
|
119
|
+
L.push(`**${c.critical} critical · ${c.high} high · ${c.medium} medium · ${c.low} low**`, '');
|
|
120
|
+
if (!findings.length && !failed.length) L.push('No problems found by these tools. That does not cover what is listed under "What this check did not see".', '');
|
|
121
|
+
for (const f of findings) {
|
|
122
|
+
L.push(`### ${f.id}: ${f.title} (${f.severity.normalized})`, '');
|
|
123
|
+
L.push(`**Found by:** ${f.category === 'web' ? 'ZAP baseline (web)' : 'testssl (TLS)'}`, '');
|
|
124
|
+
L.push(`**Where / what was seen:** ${f.evidence.map((e) => `\`${e.location}\`${e.detail ? ` (${e.detail})` : ''}`).join('; ')}`, '');
|
|
125
|
+
L.push(`**How to fix it:** ${f.fix}`, '');
|
|
126
|
+
}
|
|
127
|
+
if (notices?.length) {
|
|
128
|
+
L.push('## Tests that could not run', '');
|
|
129
|
+
for (const n of notices) L.push(`- ${n.message}`);
|
|
130
|
+
L.push('');
|
|
131
|
+
}
|
|
132
|
+
L.push('## What this check did not see', '');
|
|
133
|
+
for (const n of result.notes) L.push(`- ${n}`);
|
|
134
|
+
L.push('', '## Tools', '', '| Tool | Version | License | Result |', '|---|---|---|---|');
|
|
135
|
+
for (const t of tools) {
|
|
136
|
+
const res = t.status === 'ok' ? `${t.findings} findings` : t.status === 'skipped' ? `skipped: ${t.note}` : `did not run: ${t.error}`;
|
|
137
|
+
L.push(`| ${t.id} | ${t.version} | ${t.license} | ${res} |`);
|
|
138
|
+
}
|
|
139
|
+
L.push('');
|
|
140
|
+
return L.join('\n');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function liveSummary(result, outRel) {
|
|
144
|
+
const c = countBySeverity(result.findings);
|
|
145
|
+
const failed = result.tools.filter((t) => t.status === 'failed');
|
|
146
|
+
return [
|
|
147
|
+
`${result.generator} · ${result.check} · ${result.target.host}:${result.target.port}`,
|
|
148
|
+
`${c.critical} critical · ${c.high} high · ${c.medium} medium · ${c.low} low report: ${outRel}/report.md`,
|
|
149
|
+
...result.tools.filter((t) => t.status === 'skipped').map((t) => `SKIPPED: ${t.id}: ${t.note}`),
|
|
150
|
+
...failed.map((t) => `NOT RUN: ${t.id}: ${t.error}`),
|
|
151
|
+
...(result.notices ?? []).map((n) => `NOTE: ${n.message}`),
|
|
152
|
+
'',
|
|
153
|
+
'For the AI assistant reading this:',
|
|
154
|
+
`- Findings are in ${outRel}/findings.json. Do not add, remove or re-rate findings.`,
|
|
155
|
+
'- Explain them in plain language, most serious first. Ask before changing any server, proxy or app setting.',
|
|
156
|
+
...result.notes.map((n) => `- ${n} Say so.`),
|
|
157
|
+
'- Never run this against a host the user did not list in targets.yml, and never against production without --allow-prod.',
|
|
158
|
+
'- Never run ZAP\'s active or full scan against anything: this tool does not, and you should not add it.',
|
|
159
|
+
...(failed.length ? ['- Some checks did not run. Tell the user the check is incomplete; do not report it as clean.'] : []),
|
|
160
|
+
].join('\n');
|
|
161
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { countBySeverity } from './findings.js';
|
|
2
|
+
|
|
3
|
+
// Plain report for someone who does not know security words.
|
|
4
|
+
// Rules: no tool names, no commit hashes, no CWE ids, no severity jargon.
|
|
5
|
+
// Every item says what is wrong, where, and what to do, in that order.
|
|
6
|
+
|
|
7
|
+
const WHAT = {
|
|
8
|
+
secret: 'A password or key is written in your code.',
|
|
9
|
+
dependency: 'A library your app uses has a known security hole.',
|
|
10
|
+
config: 'A setting in your Docker or server files is unsafe.',
|
|
11
|
+
code: 'Your code has a pattern that apps built with AI often get wrong.',
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const HEAD = {
|
|
15
|
+
secret: 'A password or key is in your code',
|
|
16
|
+
dependency: 'A library has a known security hole',
|
|
17
|
+
config: 'An unsafe setting in your Docker or server files',
|
|
18
|
+
code: 'A risky pattern in your code',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const GROUPS = [
|
|
22
|
+
{ title: 'Do these today', levels: ['critical', 'high'] },
|
|
23
|
+
{ title: 'Do these this week', levels: ['medium'] },
|
|
24
|
+
{ title: 'When you have time', levels: ['low'] },
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
const MAX_DETAILED = 10;
|
|
28
|
+
|
|
29
|
+
// One line per library, not one per advisory: a non-expert cannot act on 13 lines that all say "multer".
|
|
30
|
+
function mergeDependencies(findings) {
|
|
31
|
+
const order = ['critical', 'high', 'medium', 'low'];
|
|
32
|
+
const out = [];
|
|
33
|
+
const byPkg = new Map();
|
|
34
|
+
for (const f of findings) {
|
|
35
|
+
const pkg = f.category === 'dependency' ? /^(\S+ \S+):/.exec(f.title)?.[1] : null;
|
|
36
|
+
if (!pkg) { out.push(f); continue; }
|
|
37
|
+
const key = `${pkg}|${f.evidence[0]?.location}`;
|
|
38
|
+
const m = byPkg.get(key);
|
|
39
|
+
if (!m) { const g = { ...f, pkg, count: 1, fixes: new Set(f.fix ? [f.fix] : []) }; byPkg.set(key, g); out.push(g); continue; }
|
|
40
|
+
m.count++;
|
|
41
|
+
if (f.fix) m.fixes.add(f.fix);
|
|
42
|
+
if (order.indexOf(f.severity.normalized) < order.indexOf(m.severity.normalized)) m.severity = f.severity;
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function place(f) {
|
|
48
|
+
const e = f.evidence[0];
|
|
49
|
+
if (!e) return '';
|
|
50
|
+
const more = f.evidence.length > 1 ? ` (and ${f.evidence.length - 1} more place${f.evidence.length > 2 ? 's' : ''})` : '';
|
|
51
|
+
let note = '';
|
|
52
|
+
if (e.history_only) note = ' It is no longer in your files, but it is still in your git history, so anyone with a copy of the project can read it.';
|
|
53
|
+
else if (e.not_committed) note = ' It is not in git yet, so you can still keep it out.';
|
|
54
|
+
return `In \`${e.location}\`${more}.${note}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function reportSimple(result, date) {
|
|
58
|
+
const findings = mergeDependencies(result.findings);
|
|
59
|
+
const c = countBySeverity(findings);
|
|
60
|
+
const failed = result.tools.filter((t) => t.status !== 'ok');
|
|
61
|
+
const lines = ['# Your security to-do list', ''];
|
|
62
|
+
lines.push(`Checked on ${date}. This is a self-check with free tools. It is not a certification and does not prove your app is safe.`, '');
|
|
63
|
+
|
|
64
|
+
if (failed.length) {
|
|
65
|
+
lines.push('> **The check is incomplete:** some parts did not run. Do not treat "nothing found" as safe until they do.', '');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const total = c.critical + c.high + c.medium + c.low;
|
|
69
|
+
if (total === 0) {
|
|
70
|
+
lines.push(failed.length ? 'Nothing found by the parts that ran.' : '**Nothing found by these tools.** That is good, but read "What was not checked" below.', '');
|
|
71
|
+
} else {
|
|
72
|
+
lines.push(`**${total} thing${total === 1 ? '' : 's'} to fix.** Start at number 1 and work down. After each fix, run \`npx ai-secure-audit retest\` to see it disappear from the list.`, '');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let n = 0;
|
|
76
|
+
for (const g of GROUPS) {
|
|
77
|
+
const items = findings.filter((f) => g.levels.includes(f.severity.normalized));
|
|
78
|
+
if (!items.length) continue;
|
|
79
|
+
lines.push(`## ${g.title}`, '');
|
|
80
|
+
for (const f of items) {
|
|
81
|
+
n++;
|
|
82
|
+
lines.push(`### ${n}. ${f.pkg ? `The library ${f.pkg} has ${f.count} known security hole${f.count === 1 ? '' : 's'}` : (HEAD[f.category] ?? f.title)}`, '');
|
|
83
|
+
if (n <= MAX_DETAILED) {
|
|
84
|
+
lines.push(`**What is wrong:** ${WHAT[f.category] ?? f.title}`, '');
|
|
85
|
+
lines.push(`**Where:** ${place(f)}`, '');
|
|
86
|
+
const fix = f.fixes ? [...f.fixes].join(' Also: ') : f.fix;
|
|
87
|
+
if (fix) lines.push(`**What to do:** ${fix}`, '');
|
|
88
|
+
if (f.category === 'code') lines.push('**Look first:** this comes from a pattern rule and can be wrong. Read the code before you change it.', '');
|
|
89
|
+
} else {
|
|
90
|
+
lines.push(`**Where:** ${place(f)}`, '');
|
|
91
|
+
lines.push('The full report (`report.md`) has the fix for this one.');
|
|
92
|
+
}
|
|
93
|
+
lines.push('');
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
lines.push('## What was not checked', '');
|
|
98
|
+
lines.push('These tools cannot see the following, so "nothing found" does not cover them:', '');
|
|
99
|
+
lines.push('- Whether one user can open or change another user\'s data');
|
|
100
|
+
lines.push('- Rules of your business: prices, coupons, payments, approvals');
|
|
101
|
+
lines.push('- Anything about your live website or server');
|
|
102
|
+
for (const g of result.coverage?.gaps ?? []) lines.push(`- ${g}`);
|
|
103
|
+
lines.push('');
|
|
104
|
+
return lines.join('\n');
|
|
105
|
+
}
|
package/src/targets.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
// The allowlist for `live`. A line this reader does not understand is an error, never skipped:
|
|
4
|
+
// a typo must not turn into "no limits".
|
|
5
|
+
|
|
6
|
+
const HOST = /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/;
|
|
7
|
+
|
|
8
|
+
export function parseTargets(text) {
|
|
9
|
+
const targets = [];
|
|
10
|
+
let seenHeader = false;
|
|
11
|
+
let cur = null;
|
|
12
|
+
const bad = (n, why) => { throw new Error(`targets file, line ${n}: ${why}`); };
|
|
13
|
+
const finish = (n) => {
|
|
14
|
+
if (!cur) return;
|
|
15
|
+
if (!cur.host) bad(n, 'an entry has no host');
|
|
16
|
+
// The default port follows the scheme: https 443, http 80.
|
|
17
|
+
if (cur.port === null) cur.port = cur.scheme === 'http' ? 80 : 443;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
text.split(/\r?\n/).forEach((raw, i) => {
|
|
21
|
+
const n = i + 1;
|
|
22
|
+
const line = raw.replace(/(^|\s)#.*$/, '').trimEnd();
|
|
23
|
+
if (!line.trim()) return;
|
|
24
|
+
if (!seenHeader) {
|
|
25
|
+
if (line.trim() !== 'targets:') bad(n, 'expected "targets:" first');
|
|
26
|
+
seenHeader = true;
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const m = /^(\s+)(- )?([a-z]+):\s*(\S+)\s*$/.exec(line);
|
|
30
|
+
if (!m) bad(n, `cannot read "${raw.trim()}"`);
|
|
31
|
+
const [, , dash, key, value] = m;
|
|
32
|
+
if (dash) {
|
|
33
|
+
finish(n);
|
|
34
|
+
cur = { host: null, port: null, scheme: 'https', env: 'dev' };
|
|
35
|
+
targets.push(cur);
|
|
36
|
+
} else if (!cur) bad(n, 'a setting before any "- host:" entry');
|
|
37
|
+
if (key === 'host') {
|
|
38
|
+
if (!HOST.test(value) || value.includes('..')) bad(n, `"${value}" is not a plain host name (no scheme, path, port or wildcard)`);
|
|
39
|
+
if (cur.host) bad(n, 'two hosts in one entry');
|
|
40
|
+
cur.host = value.toLowerCase();
|
|
41
|
+
} else if (key === 'port') {
|
|
42
|
+
if (!/^\d{1,5}$/.test(value) || +value < 1 || +value > 65535) bad(n, `"${value}" is not a port`);
|
|
43
|
+
cur.port = +value;
|
|
44
|
+
} else if (key === 'scheme') {
|
|
45
|
+
if (!['https', 'http'].includes(value)) bad(n, 'scheme must be https or http');
|
|
46
|
+
cur.scheme = value;
|
|
47
|
+
} else if (key === 'env') {
|
|
48
|
+
if (!['dev', 'prod'].includes(value)) bad(n, 'env must be dev or prod');
|
|
49
|
+
cur.env = value;
|
|
50
|
+
} else bad(n, `unknown setting "${key}"`);
|
|
51
|
+
if (dash && key !== 'host') bad(n, 'an entry must start with "- host:"');
|
|
52
|
+
});
|
|
53
|
+
finish(text.split('\n').length);
|
|
54
|
+
if (!seenHeader || !targets.length) throw new Error('targets file has no targets');
|
|
55
|
+
return targets;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function loadTargets(file) {
|
|
59
|
+
if (!existsSync(file)) {
|
|
60
|
+
throw new Error(`no targets file at ${file}. \`live\` only checks hosts you list there. ` +
|
|
61
|
+
'Copy config/targets.example.yml to targets.yml, list your own hosts, and keep it out of git.');
|
|
62
|
+
}
|
|
63
|
+
return parseTargets(readFileSync(file, 'utf8'));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// "host" or "host:port" only. Anything that looks like a URL, a path, a wildcard or an address range is refused.
|
|
67
|
+
export function resolveTarget(arg, targets, { allowProd = false } = {}) {
|
|
68
|
+
const m = /^([A-Za-z0-9.-]+)(?::(\d{1,5}))?$/.exec(arg ?? '');
|
|
69
|
+
if (!m || !HOST.test(m[1])) throw new Error(`"${arg}" is not host or host:port (no scheme, path, wildcard or range)`);
|
|
70
|
+
const host = m[1].toLowerCase();
|
|
71
|
+
// Without a port, only an entry on its scheme's default port (https 443, http 80) can match.
|
|
72
|
+
const isDefault = (t) => t.port === (t.scheme === 'http' ? 80 : 443);
|
|
73
|
+
const hit = targets.find((t) => t.host === host && (m[2] ? t.port === +m[2] : isDefault(t)));
|
|
74
|
+
const port = m[2] ? +m[2] : 443;
|
|
75
|
+
if (!hit) throw new Error(`${host}:${port} is not in the targets file: refusing to check it`);
|
|
76
|
+
if (hit.env === 'prod' && !allowProd) {
|
|
77
|
+
throw new Error(`${host}:${hit.port} is marked prod: add --allow-prod only when the owner has told you to check production`);
|
|
78
|
+
}
|
|
79
|
+
return hit;
|
|
80
|
+
}
|
package/src/tools.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync } from 'node:fs';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync, rmSync } from 'node:fs';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
|
-
import { join } from 'node:path';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
5
|
import { get } from './http.js';
|
|
6
|
-
import { fromTarGz, fromZip } from './extract.js';
|
|
6
|
+
import { fromTarGz, fromZip, treeFromTarGz } from './extract.js';
|
|
7
7
|
|
|
8
8
|
const lock = JSON.parse(readFileSync(new URL('../tools.lock.json', import.meta.url), 'utf8'));
|
|
9
9
|
|
|
@@ -54,3 +54,50 @@ export async function ensureTool(id, log = () => {}) {
|
|
|
54
54
|
renameSync(tmp, target);
|
|
55
55
|
return target;
|
|
56
56
|
}
|
|
57
|
+
|
|
58
|
+
// Hash of a folder's content that does not depend on how the archive was compressed (GitHub does not promise that
|
|
59
|
+
// a source archive keeps the same bytes): path, mode and content of every file, in path order.
|
|
60
|
+
export function treeHash(files) {
|
|
61
|
+
const h = createHash('sha256');
|
|
62
|
+
for (const f of [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
|
|
63
|
+
h.update(`${f.path}\0${f.mode & 0o111 ? 'x' : '-'}\0${f.data.length}\0`);
|
|
64
|
+
h.update(f.data);
|
|
65
|
+
}
|
|
66
|
+
return h.digest('hex');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function liveTools() {
|
|
70
|
+
return lock.live_tools ?? {};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Tools for checking a live host. They ship as a folder, so the pin is a content hash of the whole folder.
|
|
74
|
+
// Returns the path to the entry script, downloading and verifying it on first use.
|
|
75
|
+
export async function ensureFolderTool(id, log = () => {}) {
|
|
76
|
+
const tool = liveTools()[id];
|
|
77
|
+
if (!tool) throw new Error(`unknown tool: ${id}`);
|
|
78
|
+
if (!tool.platforms.includes(platformKey())) throw new Error(`${id} has no build for ${platformKey()}`);
|
|
79
|
+
|
|
80
|
+
const dir = join(cacheDir(), 'live', id, tool.version);
|
|
81
|
+
const entry = join(dir, tool.entry);
|
|
82
|
+
if (existsSync(join(dir, '.verified'))) return entry;
|
|
83
|
+
|
|
84
|
+
log(`downloading ${id} ${tool.version} ...`);
|
|
85
|
+
const files = treeFromTarGz(await get(tool.url), 1);
|
|
86
|
+
const got = treeHash(files);
|
|
87
|
+
if (got !== tool.tree_sha256) {
|
|
88
|
+
throw new Error(`${id}: content hash mismatch for ${tool.url}\n expected ${tool.tree_sha256}\n got ${got}`);
|
|
89
|
+
}
|
|
90
|
+
const tmp = `${dir}.${process.pid}.tmp`;
|
|
91
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
92
|
+
for (const f of files) {
|
|
93
|
+
const dest = join(tmp, f.path);
|
|
94
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
95
|
+
writeFileSync(dest, f.data);
|
|
96
|
+
chmodSync(dest, f.mode);
|
|
97
|
+
}
|
|
98
|
+
writeFileSync(join(tmp, '.verified'), `${got}\n`);
|
|
99
|
+
rmSync(dir, { recursive: true, force: true });
|
|
100
|
+
mkdirSync(dirname(dir), { recursive: true });
|
|
101
|
+
renameSync(tmp, dir);
|
|
102
|
+
return entry;
|
|
103
|
+
}
|
package/tools.lock.json
CHANGED
|
@@ -111,6 +111,61 @@
|
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
113
|
},
|
|
114
|
+
"trivy": {
|
|
115
|
+
"version": "0.76.1",
|
|
116
|
+
"license": "Apache-2.0",
|
|
117
|
+
"repo": "https://github.com/aquasecurity/trivy",
|
|
118
|
+
"platforms": {
|
|
119
|
+
"darwin-arm64": {
|
|
120
|
+
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_macOS-ARM64.tar.gz",
|
|
121
|
+
"sha256": "11a9b6cd2752011b54f01ea4bd0dbfa9f0c41dc6538d5a3f9d23955f471bf4e5",
|
|
122
|
+
"archive": "tar.gz",
|
|
123
|
+
"binary": "trivy"
|
|
124
|
+
},
|
|
125
|
+
"darwin-x64": {
|
|
126
|
+
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_macOS-64bit.tar.gz",
|
|
127
|
+
"sha256": "7aa762eacd582052d053b62dcf972a1ab058abe39a57ccae234ed8894945b6b7",
|
|
128
|
+
"archive": "tar.gz",
|
|
129
|
+
"binary": "trivy"
|
|
130
|
+
},
|
|
131
|
+
"linux-arm64": {
|
|
132
|
+
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-ARM64.tar.gz",
|
|
133
|
+
"sha256": "e174dff2a6dba5e3ae41f8d0537a6324405bd08132497340304c6b20e0f16a1f",
|
|
134
|
+
"archive": "tar.gz",
|
|
135
|
+
"binary": "trivy"
|
|
136
|
+
},
|
|
137
|
+
"linux-x64": {
|
|
138
|
+
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-64bit.tar.gz",
|
|
139
|
+
"sha256": "c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0",
|
|
140
|
+
"archive": "tar.gz",
|
|
141
|
+
"binary": "trivy"
|
|
142
|
+
},
|
|
143
|
+
"linux-arm64-musl": {
|
|
144
|
+
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-ARM64.tar.gz",
|
|
145
|
+
"sha256": "e174dff2a6dba5e3ae41f8d0537a6324405bd08132497340304c6b20e0f16a1f",
|
|
146
|
+
"archive": "tar.gz",
|
|
147
|
+
"binary": "trivy"
|
|
148
|
+
},
|
|
149
|
+
"linux-x64-musl": {
|
|
150
|
+
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-64bit.tar.gz",
|
|
151
|
+
"sha256": "c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0",
|
|
152
|
+
"archive": "tar.gz",
|
|
153
|
+
"binary": "trivy"
|
|
154
|
+
},
|
|
155
|
+
"win32-arm64": {
|
|
156
|
+
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_windows-64bit.zip",
|
|
157
|
+
"sha256": "1051f49cb22d5284f43425f72aad9cda63ca12ceb92e7caa06903490c82dc9bf",
|
|
158
|
+
"archive": "zip",
|
|
159
|
+
"binary": "trivy.exe"
|
|
160
|
+
},
|
|
161
|
+
"win32-x64": {
|
|
162
|
+
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_windows-64bit.zip",
|
|
163
|
+
"sha256": "1051f49cb22d5284f43425f72aad9cda63ca12ceb92e7caa06903490c82dc9bf",
|
|
164
|
+
"archive": "zip",
|
|
165
|
+
"binary": "trivy.exe"
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
},
|
|
114
169
|
"opengrep": {
|
|
115
170
|
"version": "1.33.1",
|
|
116
171
|
"license": "LGPL-2.1",
|
|
@@ -165,61 +220,29 @@
|
|
|
165
220
|
"binary": "opengrep_windows_x86.exe"
|
|
166
221
|
}
|
|
167
222
|
}
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
"live_tools": {
|
|
226
|
+
"zap": {
|
|
227
|
+
"kind": "docker",
|
|
228
|
+
"version": "2.17.0",
|
|
171
229
|
"license": "Apache-2.0",
|
|
172
|
-
"repo": "https://github.com/
|
|
173
|
-
"
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
"linux-
|
|
187
|
-
|
|
188
|
-
"sha256": "e174dff2a6dba5e3ae41f8d0537a6324405bd08132497340304c6b20e0f16a1f",
|
|
189
|
-
"archive": "tar.gz",
|
|
190
|
-
"binary": "trivy"
|
|
191
|
-
},
|
|
192
|
-
"linux-x64": {
|
|
193
|
-
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-64bit.tar.gz",
|
|
194
|
-
"sha256": "c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0",
|
|
195
|
-
"archive": "tar.gz",
|
|
196
|
-
"binary": "trivy"
|
|
197
|
-
},
|
|
198
|
-
"linux-arm64-musl": {
|
|
199
|
-
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-ARM64.tar.gz",
|
|
200
|
-
"sha256": "e174dff2a6dba5e3ae41f8d0537a6324405bd08132497340304c6b20e0f16a1f",
|
|
201
|
-
"archive": "tar.gz",
|
|
202
|
-
"binary": "trivy"
|
|
203
|
-
},
|
|
204
|
-
"linux-x64-musl": {
|
|
205
|
-
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_Linux-64bit.tar.gz",
|
|
206
|
-
"sha256": "c7cbe3137fb8a48a17574bede3dd6beb16742d1e9772929940fc90082c39d9c0",
|
|
207
|
-
"archive": "tar.gz",
|
|
208
|
-
"binary": "trivy"
|
|
209
|
-
},
|
|
210
|
-
"win32-arm64": {
|
|
211
|
-
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_windows-64bit.zip",
|
|
212
|
-
"sha256": "1051f49cb22d5284f43425f72aad9cda63ca12ceb92e7caa06903490c82dc9bf",
|
|
213
|
-
"archive": "zip",
|
|
214
|
-
"binary": "trivy.exe"
|
|
215
|
-
},
|
|
216
|
-
"win32-x64": {
|
|
217
|
-
"url": "https://github.com/aquasecurity/trivy/releases/download/v0.76.1/trivy_0.76.1_windows-64bit.zip",
|
|
218
|
-
"sha256": "1051f49cb22d5284f43425f72aad9cda63ca12ceb92e7caa06903490c82dc9bf",
|
|
219
|
-
"archive": "zip",
|
|
220
|
-
"binary": "trivy.exe"
|
|
221
|
-
}
|
|
222
|
-
}
|
|
230
|
+
"repo": "https://github.com/zaproxy/zaproxy",
|
|
231
|
+
"image": "ghcr.io/zaproxy/zaproxy@sha256:9624669db72f54d86c4b46a7064518bd9bf79d8c61a4c31befa9923489f328af"
|
|
232
|
+
},
|
|
233
|
+
"testssl": {
|
|
234
|
+
"version": "3.2.5",
|
|
235
|
+
"license": "GPL-2.0",
|
|
236
|
+
"repo": "https://github.com/testssl/testssl.sh",
|
|
237
|
+
"entry": "testssl.sh",
|
|
238
|
+
"url": "https://github.com/testssl/testssl.sh/archive/refs/tags/v3.2.5.tar.gz",
|
|
239
|
+
"tree_sha256": "acd99ec1375601207940682bbd595c18ef9299295ad6dfc74c59d1e7d297c6ee",
|
|
240
|
+
"platforms": [
|
|
241
|
+
"darwin-arm64",
|
|
242
|
+
"darwin-x64",
|
|
243
|
+
"linux-arm64",
|
|
244
|
+
"linux-x64"
|
|
245
|
+
]
|
|
223
246
|
}
|
|
224
247
|
}
|
|
225
248
|
}
|