ai-secure-audit 0.0.9 → 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 +8 -4
- package/config/targets.example.yml +9 -0
- package/package.json +2 -1
- package/src/cli.js +27 -2
- package/src/coverage.js +12 -1
- package/src/dockerignore.js +107 -0
- 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/report.js +9 -3
- package/src/scan.js +7 -2
- package/src/scanners/trivy.js +40 -0
- package/src/targets.js +80 -0
- package/src/tools.js +50 -3
- package/tools.lock.json +78 -0
package/README.md
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
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
|
-
> name such as `constructor` passes.
|
|
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, 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.
|
|
6
7
|
>
|
|
7
8
|
> **มือใหม่เริ่มตรงนี้:** [learn/](learn/) ควรตรวจอะไรก่อน เพราะอะไร และแก้ยังไง (ภาษาไทย)
|
|
8
9
|
>
|
|
@@ -57,8 +58,11 @@ node ai-secure-audit/bin/ai-secure-audit.js /tmp/demo-app
|
|
|
57
58
|
Or ask your AI assistant: *"Run `node <path-to>/ai-secure-audit/bin/ai-secure-audit.js` on this project, explain the
|
|
58
59
|
results in simple words, and help me fix the most serious ones first."*
|
|
59
60
|
|
|
60
|
-
Results go to `.audit/out/` in your project (`report.md` for people, `findings.json` for tools and AI). That folder
|
|
61
|
-
ignores itself in git, so results are not committed by accident.
|
|
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
|
+
ignores itself in git, so results are not committed by accident. Git is not the only way out, though: a `Dockerfile`
|
|
63
|
+
with `COPY . .` puts every file in the folder into the image. From 0.0.11 the report warns (under "About these
|
|
64
|
+
results") when a `Dockerfile` at the top of the project copies the whole folder and `.dockerignore` does not leave out
|
|
65
|
+
`.audit`.
|
|
62
66
|
|
|
63
67
|
## Repository layout
|
|
64
68
|
|
|
@@ -88,7 +92,7 @@ SHA-256 checksums. The check reads only your project folder and never uploads yo
|
|
|
88
92
|
|---|---|---|
|
|
89
93
|
| Passwords, API keys and tokens in the code, in files not committed yet, in git history and in build output (v0.1) | gitleaks | MIT |
|
|
90
94
|
| Libraries with known vulnerabilities (v0.2) | osv-scanner (offline database) | Apache-2.0 |
|
|
91
|
-
| Dockerfile and config mistakes (
|
|
95
|
+
| Dockerfile and config mistakes (0.0.10): Dockerfile, Kubernetes, Helm, Terraform, CloudFormation, Azure ARM, Ansible. trivy does not read Docker Compose files; the report names any it found as not checked | trivy config | Apache-2.0 |
|
|
92
96
|
| Code mistakes AI-generated apps often make (see below), one rule at a time: sign-in, sign-up and join routes with no limit on repeats (Express 0.0.5, NestJS 0.0.6), vote and like routes that never check who is voting (0.0.6), session, token or admin checks that a built-in name like `constructor` passes (0.0.9); the rest planned | opengrep + this kit's own rules | LGPL-2.1 (rules: Apache-2.0) |
|
|
93
97
|
|
|
94
98
|
Common mistakes the kit's own rules look for: sign-in, sign-up and join routes that anyone can call without limit
|
|
@@ -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/coverage.js
CHANGED
|
@@ -27,6 +27,10 @@ const LANGUAGES = {
|
|
|
27
27
|
vue: ['.vue'],
|
|
28
28
|
svelte: ['.svelte'],
|
|
29
29
|
};
|
|
30
|
+
// Docker Compose files: trivy (the config checker) does not read them, so the report must say they were not checked.
|
|
31
|
+
// compose.yaml, compose.yml, docker-compose.yml, docker-compose.prod.yaml and the like.
|
|
32
|
+
export const isComposeFile = (name) => /^(docker-)?compose(\.[\w-]+)?\.ya?ml$/i.test(name);
|
|
33
|
+
|
|
30
34
|
const BY_EXT = new Map(Object.entries(LANGUAGES).flatMap(([lang, exts]) => exts.map((e) => [e, lang])));
|
|
31
35
|
|
|
32
36
|
// Lockfiles osv-scanner reads, and whether this kit has tested that ecosystem with known-answer cases.
|
|
@@ -81,16 +85,18 @@ export function projectCoverage(root, { rulesDir, limit = 200_000 } = {}) {
|
|
|
81
85
|
const covered = ruleLanguages(rulesDir);
|
|
82
86
|
const counts = new Map();
|
|
83
87
|
const lockfiles = [];
|
|
88
|
+
const compose = [];
|
|
84
89
|
for (const f of files) {
|
|
85
90
|
const name = basename(f);
|
|
86
91
|
const ext = name.includes('.') ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
|
|
87
92
|
const lang = BY_EXT.get(ext);
|
|
88
93
|
if (lang) counts.set(lang, (counts.get(lang) ?? 0) + 1);
|
|
89
94
|
if (LOCKFILES[name]) lockfiles.push({ file: f, ...LOCKFILES[name] });
|
|
95
|
+
if (isComposeFile(name)) compose.push(f);
|
|
90
96
|
}
|
|
91
97
|
const languages = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
|
92
98
|
.map(([language, n]) => ({ language, files: n, code_rules: covered.has(language) }));
|
|
93
|
-
return { languages, lockfiles, truncated: files.length >= limit };
|
|
99
|
+
return { languages, lockfiles, compose, truncated: files.length >= limit };
|
|
94
100
|
}
|
|
95
101
|
|
|
96
102
|
// Plain sentences for the report and for the AI assistant. Empty when everything found is covered.
|
|
@@ -108,6 +114,11 @@ export function coverageGaps(cov) {
|
|
|
108
114
|
gaps.push(`Libraries: ${untested.map((l) => `${l.file} (${l.ecosystem})`).join(', ')} ` +
|
|
109
115
|
'were read by osv-scanner, but this kit has not tested that ecosystem with known answers yet.');
|
|
110
116
|
}
|
|
117
|
+
if (cov.compose?.length) {
|
|
118
|
+
gaps.push(`Docker Compose: ${cov.compose.join(', ')} ${cov.compose.length === 1 ? 'was' : 'were'} not checked. trivy reads ` +
|
|
119
|
+
'Dockerfiles but not Compose files, so settings such as privileged: true, network_mode: host, a mounted ' +
|
|
120
|
+
'docker.sock or a database port open to every network were not looked at; "0 findings" says nothing about them.');
|
|
121
|
+
}
|
|
111
122
|
if (cov.truncated) gaps.push('The project has more files than this check counts; the lists above may be incomplete.');
|
|
112
123
|
return gaps;
|
|
113
124
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Does a Docker build of the scanned folder take this tool's own results (.audit/) into the image?
|
|
2
|
+
// trivy only reads Dockerfile instructions, so nothing else notices: .audit/ appears on the first scan, and a
|
|
3
|
+
// Dockerfile with COPY . . then ships the list of the app's weak points in every image.
|
|
4
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { join, posix } from 'node:path';
|
|
6
|
+
|
|
7
|
+
// The files a scan writes; if any of them gets into the build context, the results do.
|
|
8
|
+
const AUDIT_FILES = ['.audit/out/findings.json', '.audit/out/report.md', '.audit/out/raw/x.json'];
|
|
9
|
+
|
|
10
|
+
const DOCKERFILE = /^(Dockerfile|Containerfile)(\.[\w.-]+)?$|^[\w.-]+\.(Dockerfile|dockerfile)$/;
|
|
11
|
+
|
|
12
|
+
function patternToRegex(p) {
|
|
13
|
+
let re = '';
|
|
14
|
+
for (let i = 0; i < p.length; i++) {
|
|
15
|
+
const c = p[i];
|
|
16
|
+
if (c === '*') {
|
|
17
|
+
if (p[i + 1] === '*') {
|
|
18
|
+
i++;
|
|
19
|
+
if (p[i + 1] === '/') { i++; re += '(?:.*/)?'; } else re += '.*';
|
|
20
|
+
} else re += '[^/]*';
|
|
21
|
+
} else if (c === '?') re += '[^/]';
|
|
22
|
+
else if (c === '[') {
|
|
23
|
+
const end = p.indexOf(']', i + 1);
|
|
24
|
+
if (end < 0) { re += '\\['; continue; }
|
|
25
|
+
re += '[' + p.slice(i + 1, end).replace(/^!/, '^').replace(/\\/g, '\\\\') + ']';
|
|
26
|
+
i = end;
|
|
27
|
+
} else if (c === '\\' && i + 1 < p.length) re += '\\' + p[++i];
|
|
28
|
+
else re += c.replace(/[.+^${}()|]/g, '\\$&');
|
|
29
|
+
}
|
|
30
|
+
return new RegExp(`^${re}$`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// .dockerignore rules as Docker reads them: one pattern per line, # comments, surrounding space trimmed, a leading
|
|
34
|
+
// ! re-includes, paths cleaned (leading /, ./ and trailing / dropped). The last matching line wins.
|
|
35
|
+
export function parseDockerignore(text) {
|
|
36
|
+
const rules = [];
|
|
37
|
+
for (let line of text.split(/\r?\n/)) {
|
|
38
|
+
line = line.trim();
|
|
39
|
+
if (!line || line.startsWith('#')) continue;
|
|
40
|
+
const negate = line.startsWith('!');
|
|
41
|
+
if (negate) line = line.slice(1).trim();
|
|
42
|
+
let p = posix.normalize(line).replace(/^\/+/, '').replace(/\/+$/, '');
|
|
43
|
+
if (!p || p === '.') continue;
|
|
44
|
+
rules.push({ negate, re: patternToRegex(p) });
|
|
45
|
+
}
|
|
46
|
+
return rules;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// A path is excluded when a pattern matches it or one of its parent folders.
|
|
50
|
+
export function isExcluded(rules, file) {
|
|
51
|
+
const parts = file.split('/');
|
|
52
|
+
const paths = parts.map((_, i) => parts.slice(0, i + 1).join('/'));
|
|
53
|
+
let excluded = false;
|
|
54
|
+
for (const r of rules) if (paths.some((p) => r.re.test(p))) excluded = !r.negate;
|
|
55
|
+
return excluded;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// COPY or ADD whose sources include the whole context: ".", "./", "*" or "./*" (shell or JSON form).
|
|
59
|
+
export function copiesWholeFolder(dockerfile) {
|
|
60
|
+
const text = dockerfile.replace(/\\\r?\n/g, ' ');
|
|
61
|
+
for (const line of text.split(/\r?\n/)) {
|
|
62
|
+
const m = /^\s*(?:COPY|ADD)\s+(.*)$/i.exec(line);
|
|
63
|
+
if (!m) continue;
|
|
64
|
+
let rest = m[1].trim();
|
|
65
|
+
while (/^--\S+/.test(rest)) rest = rest.replace(/^--\S+\s*/, '');
|
|
66
|
+
if (/--from=/i.test(m[1])) continue; // copies from another stage, not from the folder
|
|
67
|
+
let args;
|
|
68
|
+
if (rest.startsWith('[')) {
|
|
69
|
+
try { args = JSON.parse(rest); } catch { continue; }
|
|
70
|
+
} else args = rest.split(/\s+/);
|
|
71
|
+
if (args.slice(0, -1).some((a) => ['.', './', '*', './*'].includes(a))) return true;
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// One notice per Dockerfile at the top of the scanned folder (the usual build context) that would ship .audit/.
|
|
77
|
+
// Not checked: Dockerfiles in subfolders built with a context above them (compose build.context: ..).
|
|
78
|
+
export function dockerignoreNotices(root) {
|
|
79
|
+
let names;
|
|
80
|
+
try { names = readdirSync(root); } catch { return []; }
|
|
81
|
+
const notices = [];
|
|
82
|
+
for (const name of names.filter((n) => DOCKERFILE.test(n)).sort()) {
|
|
83
|
+
let text;
|
|
84
|
+
try { text = readFileSync(join(root, name), 'utf8'); } catch { continue; }
|
|
85
|
+
if (!copiesWholeFolder(text)) continue;
|
|
86
|
+
// BuildKit reads <Dockerfile>.dockerignore next to the Dockerfile first, then .dockerignore.
|
|
87
|
+
const own = `${name}.dockerignore`;
|
|
88
|
+
const ignoreFile = existsSync(join(root, own)) ? own : existsSync(join(root, '.dockerignore')) ? '.dockerignore' : null;
|
|
89
|
+
if (!ignoreFile) {
|
|
90
|
+
notices.push({
|
|
91
|
+
id: 'dockerignore-audit', file: name,
|
|
92
|
+
message: `${name} copies the whole folder and there is no .dockerignore, so this check's results in .audit/ ` +
|
|
93
|
+
'(a list of the app\'s weak points) go into the image, together with .env, .git and anything else in the ' +
|
|
94
|
+
'folder. Add a .dockerignore with at least these lines: .audit, .env, .git',
|
|
95
|
+
});
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const rules = parseDockerignore(readFileSync(join(root, ignoreFile), 'utf8'));
|
|
99
|
+
if (AUDIT_FILES.every((f) => isExcluded(rules, f))) continue;
|
|
100
|
+
notices.push({
|
|
101
|
+
id: 'dockerignore-audit', file: name,
|
|
102
|
+
message: `${name} copies the whole folder and ${ignoreFile} does not exclude .audit/, so this check's results ` +
|
|
103
|
+
`(a list of the app's weak points) go into the image. Add the line .audit to ${ignoreFile}.`,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return notices;
|
|
107
|
+
}
|
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/report.js
CHANGED
|
@@ -108,13 +108,19 @@ export function reportMarkdown(result, date) {
|
|
|
108
108
|
lines.push('');
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
if (result.notices?.length) {
|
|
112
|
+
lines.push('## About these results');
|
|
113
|
+
lines.push('');
|
|
114
|
+
for (const n of result.notices) lines.push(`- ${n.message}`);
|
|
115
|
+
lines.push('');
|
|
116
|
+
}
|
|
117
|
+
|
|
111
118
|
lines.push('## What this check could not see');
|
|
112
119
|
lines.push('');
|
|
113
120
|
lines.push('- Whether one user can open or change another user\'s data (for example by changing an id in the URL)');
|
|
114
121
|
lines.push('- Business rules: prices, coupons, approvals, payments');
|
|
115
122
|
lines.push('- Database rules such as Supabase row-level security or Firebase security rules (planned)');
|
|
116
123
|
lines.push('- Anything about the live server or website');
|
|
117
|
-
lines.push('- Docker/config mistakes: not in this version yet (coming in v0.3)');
|
|
118
124
|
for (const g of result.coverage?.gaps ?? []) lines.push(`- ${g}`);
|
|
119
125
|
lines.push('');
|
|
120
126
|
lines.push('## Tools');
|
|
@@ -142,9 +148,9 @@ export function consoleSummary(result, outRel) {
|
|
|
142
148
|
'- A finding marked not_committed can be moved out of the code without rotating, unless the key was shared or pasted somewhere else.',
|
|
143
149
|
'- Findings of type code come from pattern rules and can be wrong. Read the code at that location and tell the user',
|
|
144
150
|
' if a limit or check exists somewhere the rule cannot see (another file, the proxy) before changing anything.',
|
|
145
|
-
'- Not checked: whether one user can reach another user\'s data, business rules
|
|
146
|
-
' Docker/config files. Say so.',
|
|
151
|
+
'- Not checked: whether one user can reach another user\'s data, and business rules. Say so.',
|
|
147
152
|
...(result.coverage?.gaps ?? []).map((g) => `- ${g} Tell the user.`),
|
|
153
|
+
...(result.notices ?? []).map((n) => `- ${n.message} Tell the user, and ask before editing the file.`),
|
|
148
154
|
...(failed.length ? ['- Some tools did not run (see NOT RUN above). Tell the user the check is incomplete.'] : []),
|
|
149
155
|
].join('\n');
|
|
150
156
|
}
|
package/src/scan.js
CHANGED
|
@@ -4,13 +4,15 @@ import { join, resolve } from 'node:path';
|
|
|
4
4
|
import { cacheDir, ensureTool, lockedTools } from './tools.js';
|
|
5
5
|
import { sortAndNumber } from './findings.js';
|
|
6
6
|
import { coverageGaps, projectCoverage } from './coverage.js';
|
|
7
|
+
import { dockerignoreNotices } from './dockerignore.js';
|
|
7
8
|
import gitleaks from './scanners/gitleaks.js';
|
|
8
9
|
import osv from './scanners/osv.js';
|
|
9
10
|
import opengrep from './scanners/opengrep.js';
|
|
11
|
+
import trivy from './scanners/trivy.js';
|
|
10
12
|
|
|
11
13
|
// Scanners are released one at a time, each after passing its own tests (see CLAUDE.md).
|
|
12
14
|
// Scanners still in development are kept outside this repository until they pass.
|
|
13
|
-
export const BASIC_SCANNERS = [gitleaks, osv, opengrep];
|
|
15
|
+
export const BASIC_SCANNERS = [gitleaks, osv, opengrep, trivy];
|
|
14
16
|
|
|
15
17
|
function git(root, args) {
|
|
16
18
|
const r = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' });
|
|
@@ -86,10 +88,13 @@ export async function scan(target, { log = () => {}, version }) {
|
|
|
86
88
|
target: { git: isGit, commit: ctx.commit, uncommitted_changes: ctx.dirty },
|
|
87
89
|
tools: runs,
|
|
88
90
|
coverage: { ...coverage, gaps: coverageGaps(coverage) },
|
|
91
|
+
// About this tool's own output, not a weakness of the app: kept apart from findings so it is never rated.
|
|
92
|
+
notices: dockerignoreNotices(root),
|
|
89
93
|
notes: [
|
|
90
94
|
'Not checked by this tool: whether one user can reach another user\'s data, business rules, and anything running on a server.',
|
|
91
95
|
'Code rules (category code) are this kit\'s own opengrep rules. They can be wrong: check the location before changing code.',
|
|
92
|
-
|
|
96
|
+
'Config files are checked by trivy: Dockerfiles, Kubernetes, Helm, Terraform, CloudFormation, Azure ARM and Ansible files. ' +
|
|
97
|
+
'trivy does not read Docker Compose files; coverage.gaps names any that were not checked.',
|
|
93
98
|
],
|
|
94
99
|
findings: sortAndNumber(findings),
|
|
95
100
|
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { rel } from '../paths.js';
|
|
3
|
+
|
|
4
|
+
export default {
|
|
5
|
+
id: 'trivy',
|
|
6
|
+
category: 'config',
|
|
7
|
+
|
|
8
|
+
// --skip-check-update keeps the checks built into the pinned trivy version, so results do not drift.
|
|
9
|
+
args(ctx, out) {
|
|
10
|
+
return ['config', '--format', 'json', '--output', out, '--skip-check-update', '--quiet',
|
|
11
|
+
'--cache-dir', join(ctx.cache, 'trivy'),
|
|
12
|
+
'--skip-dirs', '**/node_modules', '--skip-dirs', '**/.git', ctx.root];
|
|
13
|
+
},
|
|
14
|
+
|
|
15
|
+
okExit: [0],
|
|
16
|
+
|
|
17
|
+
parse(json, ctx) {
|
|
18
|
+
const findings = [];
|
|
19
|
+
for (const result of json?.Results ?? []) {
|
|
20
|
+
const file = rel(ctx.root, result.Target);
|
|
21
|
+
for (const m of result.Misconfigurations ?? []) {
|
|
22
|
+
if (m.Status !== 'FAIL') continue;
|
|
23
|
+
const line = m.CauseMetadata?.StartLine;
|
|
24
|
+
const location = line ? `${file}:${line}` : file;
|
|
25
|
+
const sev = (m.Severity ?? 'UNKNOWN').toLowerCase();
|
|
26
|
+
findings.push({
|
|
27
|
+
fingerprint: `trivy:${m.ID}:${location}`,
|
|
28
|
+
category: 'config',
|
|
29
|
+
title: m.Title,
|
|
30
|
+
severity: { tool: m.Severity, normalized: ['critical', 'high', 'medium', 'low'].includes(sev) ? sev : 'medium' },
|
|
31
|
+
source: { kind: 'tool', tool: 'trivy', rule_id: m.ID },
|
|
32
|
+
evidence: [{ location, detail: m.Message }],
|
|
33
|
+
fix: m.Resolution,
|
|
34
|
+
references: { urls: m.PrimaryURL ? [m.PrimaryURL] : [] },
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return findings;
|
|
39
|
+
},
|
|
40
|
+
};
|
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",
|
|
@@ -166,5 +221,28 @@
|
|
|
166
221
|
}
|
|
167
222
|
}
|
|
168
223
|
}
|
|
224
|
+
},
|
|
225
|
+
"live_tools": {
|
|
226
|
+
"zap": {
|
|
227
|
+
"kind": "docker",
|
|
228
|
+
"version": "2.17.0",
|
|
229
|
+
"license": "Apache-2.0",
|
|
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
|
+
]
|
|
246
|
+
}
|
|
169
247
|
}
|
|
170
248
|
}
|