ai-secure-audit 0.0.14 → 0.0.16
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/package.json +1 -1
- package/rules/express-route-no-rate-limit.yml +2 -0
- package/rules/express-session-lookup-plain-object.yml +2 -0
- package/rules/express-vote-route-no-identity.yml +2 -0
- package/rules/js-code-from-text.js +136 -0
- package/rules/js-code-from-text.yml +81 -0
- package/rules/js-html-from-user-text.js +206 -0
- package/rules/js-html-from-user-text.yml +143 -0
- package/rules/nestjs-route-no-throttle.yml +2 -0
- package/rules/sql-built-from-parameter.js +115 -0
- package/rules/sql-built-from-parameter.yml +81 -0
- package/rules/sql-built-from-request.ts +196 -0
- package/rules/sql-built-from-request.yml +103 -0
- package/src/cli.js +6 -2
- package/src/coverage.js +100 -5
- package/src/findings.js +1 -1
- package/src/live/ports.js +136 -0
- package/src/live.js +30 -7
- package/src/report-simple.js +1 -0
- package/src/report.js +2 -1
- package/src/scan.js +4 -1
- package/src/scanners/opengrep.js +44 -1
package/src/coverage.js
CHANGED
|
@@ -23,6 +23,11 @@ const LANGUAGES = {
|
|
|
23
23
|
cpp: ['.cpp', '.cc', '.cxx', '.hpp', '.hh'],
|
|
24
24
|
dart: ['.dart'],
|
|
25
25
|
swift: ['.swift'],
|
|
26
|
+
scala: ['.scala'],
|
|
27
|
+
elixir: ['.ex', '.exs'],
|
|
28
|
+
lua: ['.lua'],
|
|
29
|
+
// Smart contracts: a language this kit does not read must still be named, or its files look checked.
|
|
30
|
+
solidity: ['.sol'],
|
|
26
31
|
// Single-file components: the JavaScript rules do not read the <script> block inside them.
|
|
27
32
|
vue: ['.vue'],
|
|
28
33
|
svelte: ['.svelte'],
|
|
@@ -131,7 +136,9 @@ const named = (files) => `${files.slice(0, 5).join(', ')}${files.length > 5 ? `
|
|
|
131
136
|
export const NO_LIBRARY_CHECK = 'Libraries not checked:';
|
|
132
137
|
|
|
133
138
|
// Languages the kit's own code rules read, taken from the rule files so the list cannot fall behind them.
|
|
134
|
-
|
|
139
|
+
const RULES_DIR = fileURLToPath(new URL('../rules/', import.meta.url));
|
|
140
|
+
|
|
141
|
+
export function ruleLanguages(rulesDir = RULES_DIR) {
|
|
135
142
|
const langs = new Set();
|
|
136
143
|
for (const f of readdirSync(rulesDir).filter((n) => /\.ya?ml$/.test(n)).sort()) {
|
|
137
144
|
for (const m of readFileSync(join(rulesDir, f), 'utf8').matchAll(/languages:\s*\[([^\]]*)\]/g)) {
|
|
@@ -141,6 +148,33 @@ export function ruleLanguages(rulesDir = fileURLToPath(new URL('../rules/', impo
|
|
|
141
148
|
return langs;
|
|
142
149
|
}
|
|
143
150
|
|
|
151
|
+
// The rules a user sees findings from, with the one-line summary the report lists. Helper rules marked
|
|
152
|
+
// `internal: true` only filter other findings, so they are left out.
|
|
153
|
+
export function ruleSummaries(rulesDir = RULES_DIR) {
|
|
154
|
+
const rules = [];
|
|
155
|
+
for (const f of readdirSync(rulesDir).filter((n) => /\.ya?ml$/.test(n)).sort()) {
|
|
156
|
+
for (const block of readFileSync(join(rulesDir, f), 'utf8').split(/^ {2}- id:/m).slice(1)) {
|
|
157
|
+
if (/^\s+internal:\s*true\b/m.test(block)) continue;
|
|
158
|
+
const id = block.slice(0, block.indexOf('\n')).trim();
|
|
159
|
+
const languages = (/languages:\s*\[([^\]]*)\]/.exec(block)?.[1] ?? '').split(',').map((l) => l.trim()).filter(Boolean);
|
|
160
|
+
const summary = /^\s+summary:\s*'([^']*)'/m.exec(block)?.[1] ?? /^\s+summary:\s*"([^"]*)"/m.exec(block)?.[1] ?? null;
|
|
161
|
+
rules.push({ id, languages, summary });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return rules;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Common mistakes that no code rule of this kit looks for yet. Keep this list true: drop an item once a rule covers it.
|
|
168
|
+
export const NOT_LOOKED_FOR = [
|
|
169
|
+
'NoSQL queries or shell commands built from user input',
|
|
170
|
+
'HTML put on the page from values whose names do not look like text people type, or through other variables (XSS)',
|
|
171
|
+
'redirects or server-side requests to a URL the user chose',
|
|
172
|
+
'folders served as file lists',
|
|
173
|
+
'passwords stored with a fast hash such as MD5 or SHA-1',
|
|
174
|
+
];
|
|
175
|
+
|
|
176
|
+
const extOf = (name) => (name.includes('.') ? name.slice(name.lastIndexOf('.')).toLowerCase() : '');
|
|
177
|
+
|
|
144
178
|
function walk(dir, rel, out, limit) {
|
|
145
179
|
let entries;
|
|
146
180
|
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
@@ -152,26 +186,38 @@ function walk(dir, rel, out, limit) {
|
|
|
152
186
|
}
|
|
153
187
|
}
|
|
154
188
|
|
|
155
|
-
export function projectCoverage(root, { rulesDir, limit = 200_000 } = {}) {
|
|
189
|
+
export function projectCoverage(root, { rulesDir = RULES_DIR, limit = 200_000 } = {}) {
|
|
156
190
|
const files = [];
|
|
157
191
|
walk(root, '', files, limit);
|
|
158
192
|
const covered = ruleLanguages(rulesDir);
|
|
193
|
+
const rules = ruleSummaries(rulesDir);
|
|
159
194
|
const counts = new Map();
|
|
160
195
|
const lockfiles = [];
|
|
161
196
|
const compose = [];
|
|
162
197
|
for (const f of files) {
|
|
163
198
|
const name = basename(f);
|
|
164
|
-
const
|
|
165
|
-
const lang = BY_EXT.get(ext);
|
|
199
|
+
const lang = BY_EXT.get(extOf(name));
|
|
166
200
|
if (lang) counts.set(lang, (counts.get(lang) ?? 0) + 1);
|
|
167
201
|
if (LOCKFILES[name]) lockfiles.push({ file: f, ...LOCKFILES[name] });
|
|
168
202
|
if (isComposeFile(name)) compose.push(f);
|
|
169
203
|
}
|
|
170
204
|
const languages = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
|
171
205
|
.map(([language, n]) => ({ language, files: n, code_rules: covered.has(language) }));
|
|
172
|
-
|
|
206
|
+
// Only the rules that can match a language found here: a NestJS rule says nothing about a PHP project.
|
|
207
|
+
const present = new Set(languages.filter((l) => l.code_rules).map((l) => l.language));
|
|
208
|
+
// opengrep's built-in ignore list leaves out folders named test or tests at any depth, and *.min.js files, so the
|
|
209
|
+
// code rules never read them. Files in a language with no rules are already named above.
|
|
210
|
+
const ruled = (f) => present.has(BY_EXT.get(extOf(basename(f))));
|
|
211
|
+
const code_skipped = {
|
|
212
|
+
test_folders: files.filter((f) => ruled(f) && /(?:^|\/)tests?\//.test(f)),
|
|
213
|
+
minified: files.filter((f) => ruled(f) && /\.min\.js$/i.test(f) && !/(?:^|\/)tests?\//.test(f)),
|
|
214
|
+
};
|
|
215
|
+
const code_rules = rules.filter((r) => r.languages.some((l) => present.has(l))).map(({ id, summary }) => ({ id, summary }));
|
|
216
|
+
return { languages, code_rules, code_skipped, lockfiles, compose, unlocked: manifestsWithoutLockfile(root, files), truncated: files.length >= limit };
|
|
173
217
|
}
|
|
174
218
|
|
|
219
|
+
const list = (items) => (items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`);
|
|
220
|
+
|
|
175
221
|
// Plain sentences for the report and for the AI assistant. Empty when everything found is covered.
|
|
176
222
|
export function coverageGaps(cov) {
|
|
177
223
|
const gaps = [];
|
|
@@ -182,6 +228,55 @@ export function coverageGaps(cov) {
|
|
|
182
228
|
'AI assistant with the prompt in https://github.com/surapas3022/ai-secure-audit/blob/main/docs/ai-review-prompt.md ' +
|
|
183
229
|
'(its results are leads to check, not findings).');
|
|
184
230
|
}
|
|
231
|
+
// Languages that do have rules: say how few, so "code rules: yes" is not read as "the code was checked".
|
|
232
|
+
const withRules = cov.languages.filter((l) => l.code_rules).map((l) => l.language);
|
|
233
|
+
if (withRules.length && cov.code_rules) {
|
|
234
|
+
const n = cov.code_rules.length;
|
|
235
|
+
gaps.push(`Code rules: ${list(withRules)} code was checked with only ${n} rule${n === 1 ? '' : 's'} from this kit` +
|
|
236
|
+
(n ? `: ${cov.code_rules.map((r) => r.summary ?? r.id).join('; ')}` : '') + '. ' +
|
|
237
|
+
`Other mistakes were not looked for, such as ${list(NOT_LOOKED_FOR)}; "0 findings" says nothing about them. ` +
|
|
238
|
+
'To review them, ask an AI assistant with the prompt in ' +
|
|
239
|
+
'https://github.com/surapas3022/ai-secure-audit/blob/main/docs/ai-review-prompt.md (its results are leads to check, not findings).');
|
|
240
|
+
}
|
|
241
|
+
const skipped = cov.code_skipped ?? { test_folders: [], minified: [] };
|
|
242
|
+
const parts = [];
|
|
243
|
+
const files = (n) => `${n} ${n === 1 ? 'file' : 'files'}`;
|
|
244
|
+
if (skipped.test_folders.length) parts.push(`${files(skipped.test_folders.length)} in test or tests folders (${named(skipped.test_folders)})`);
|
|
245
|
+
if (skipped.minified.length) {
|
|
246
|
+
const n = skipped.minified.length;
|
|
247
|
+
parts.push(`${n} minified ${n === 1 ? 'file' : 'files'} (${named(skipped.minified)})`);
|
|
248
|
+
}
|
|
249
|
+
if (parts.length) {
|
|
250
|
+
const total = skipped.test_folders.length + skipped.minified.length;
|
|
251
|
+
const what = [skipped.test_folders.length && 'folders named test or tests', skipped.minified.length && '*.min.js files'].filter(Boolean);
|
|
252
|
+
const why = [
|
|
253
|
+
skipped.test_folders.length && 'Test code usually does not run as the app; if a folder named test or tests holds code that does, review it by hand.',
|
|
254
|
+
skipped.minified.length && 'A minified file does run, but it is usually a library copied in or build output whose source is elsewhere; if it is code you wrote, check the source instead.',
|
|
255
|
+
].filter(Boolean);
|
|
256
|
+
gaps.push(`Code rules: ${parts.join(' and ')} ${total === 1 ? 'was' : 'were'} not checked by the code rules: opengrep ` +
|
|
257
|
+
`leaves ${what.join(' and ')} out on its own. ${why.join(' ')} The secret check still read these files.`);
|
|
258
|
+
}
|
|
259
|
+
const read = cov.code_read ?? { not_read: [], read_in_part: [], stopped: [] };
|
|
260
|
+
const n = (k, one, many) => `${k} ${k === 1 ? one : many}`;
|
|
261
|
+
if (read.not_read.length) {
|
|
262
|
+
const list = named(read.not_read.map((x) => (x.line ? `${x.file} (syntax error at line ${x.line})` : x.file)));
|
|
263
|
+
gaps.push(`Code rules: ${n(read.not_read.length, 'file', 'files')} could not be read by the code checker (${list}), so ` +
|
|
264
|
+
`${read.not_read.length === 1 ? 'it was' : 'they were'} not checked by the code rules at all. This happens with syntax ` +
|
|
265
|
+
'the checker does not know, or a file that is only part of a program. If one of them is app code, review it by hand ' +
|
|
266
|
+
'(full list in findings.json under coverage.code_read).');
|
|
267
|
+
}
|
|
268
|
+
if (read.read_in_part.length) {
|
|
269
|
+
const list = named(read.read_in_part.map((x) => (x.lines.length ? `${x.file} (${x.lines.length === 1 ? 'line' : 'lines'} ${x.lines.join(', ')})` : x.file)));
|
|
270
|
+
gaps.push(`Code rules: ${n(read.read_in_part.length, 'file was', 'files were')} read only in part (${list}): the code ` +
|
|
271
|
+
'checker skipped the code around those lines, so a finding there can be missing. Review those parts by hand ' +
|
|
272
|
+
'(full list in findings.json under coverage.code_read).');
|
|
273
|
+
}
|
|
274
|
+
if (read.stopped.length) {
|
|
275
|
+
const list = named(read.stopped.map((x) => (x.rules.length ? `${x.file} (${x.rules.join(', ')})` : x.file)));
|
|
276
|
+
gaps.push(`Code rules: the check stopped on ${n(read.stopped.length, 'file', 'files')} before it finished (${list}), ` +
|
|
277
|
+
'because a rule took too long; those rules did not finish on that file. Large or generated files cause this ' +
|
|
278
|
+
'(full list in findings.json under coverage.code_read).');
|
|
279
|
+
}
|
|
185
280
|
if (cov.unlocked?.length) {
|
|
186
281
|
gaps.push(`${NO_LIBRARY_CHECK} no lockfile (the file that records exact library versions) was found for ${named(cov.unlocked)}, ` +
|
|
187
282
|
'so the libraries listed there were not looked at; "0 findings" says nothing about them. Create the lockfile with your ' +
|
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', 'tls', 'web'];
|
|
2
|
+
const CATEGORY_ORDER = ['secret', 'dependency', 'config', 'code', 'tls', 'web', 'network'];
|
|
3
3
|
|
|
4
4
|
// Stable order: same inputs give byte-identical findings.json.
|
|
5
5
|
export function sortAndNumber(findings) {
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { BlockList, connect } from 'node:net';
|
|
2
|
+
import { lookup } from 'node:dns/promises';
|
|
3
|
+
|
|
4
|
+
// Port check: which well-known risky ports accept a connection from here.
|
|
5
|
+
// It connects and closes at once. It sends no data, reads no banner, and tries only the list below, never a range.
|
|
6
|
+
// "Not open" means closed, filtered by a firewall, or not reachable from where this ran: it cannot tell which.
|
|
7
|
+
|
|
8
|
+
// Where an address sits decides what an open port proves. The check only ever connects from the computer that ran it,
|
|
9
|
+
// so a port that is open on a public address proves it is reachable from here, and on a loopback or private address
|
|
10
|
+
// it proves only that something is listening there, not that anyone on the internet can reach it.
|
|
11
|
+
const SCOPES = new BlockList();
|
|
12
|
+
for (const [net, prefix] of [['127.0.0.0', 8], ['0.0.0.0', 8]]) SCOPES.addSubnet(net, prefix, 'ipv4');
|
|
13
|
+
SCOPES.addAddress('::1', 'ipv6'); SCOPES.addAddress('::', 'ipv6');
|
|
14
|
+
const PRIVATE = new BlockList();
|
|
15
|
+
for (const [net, prefix] of [['10.0.0.0', 8], ['172.16.0.0', 12], ['192.168.0.0', 16], ['169.254.0.0', 16], ['100.64.0.0', 10]]) PRIVATE.addSubnet(net, prefix, 'ipv4');
|
|
16
|
+
PRIVATE.addSubnet('fc00::', 7, 'ipv6'); PRIVATE.addSubnet('fe80::', 10, 'ipv6');
|
|
17
|
+
|
|
18
|
+
export function addressScope(ip) {
|
|
19
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip); // an IPv4 address written in IPv6 form
|
|
20
|
+
const addr = mapped ? mapped[1] : ip;
|
|
21
|
+
const family = addr.includes(':') ? 'ipv6' : 'ipv4';
|
|
22
|
+
if (SCOPES.check(addr, family)) return 'loopback';
|
|
23
|
+
if (PRIVATE.check(addr, family)) return 'private';
|
|
24
|
+
return 'public';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const SEEN = {
|
|
28
|
+
public: 'If you ran this from outside your own network, anyone on the internet can do the same.',
|
|
29
|
+
loopback: 'This address is this computer itself, so it shows the service is listening here, not that it can be reached from outside.',
|
|
30
|
+
private: 'This is a private network address, so it shows the service can be reached from inside that network, not from the internet.',
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const DB = 'Do not expose a database to the internet. Make it listen only on 127.0.0.1 or a private network, and block the port in the firewall. Reach it through an SSH tunnel or VPN. If it was open for a while, assume the data could have been read: change its passwords and check its logs.';
|
|
34
|
+
const ADMIN = 'Block this port in the firewall and reach the machine through a VPN or SSH instead. Remote-control services on the open internet are attacked all day.';
|
|
35
|
+
const DEV = 'This is a common development-server port. If it is a dev server, stop it or make it listen only on 127.0.0.1 (for example `--host 127.0.0.1`), and put the real site behind a proxy on ports 80 and 443. If it is meant to be public, ignore this.';
|
|
36
|
+
|
|
37
|
+
// port -> [name, severity, fix]. No SSH here: an open SSH port is normal; it is listed as information only.
|
|
38
|
+
export const RISKY_PORTS = {
|
|
39
|
+
2375: ['Docker remote API (no login)', 'critical', 'Anyone who can reach this can start containers as root on the machine. Close it now: remove `-H tcp://0.0.0.0:2375` from the Docker settings, or bind it to 127.0.0.1, and treat the machine as possibly compromised.'],
|
|
40
|
+
4243: ['Docker remote API (no login)', 'critical', 'Anyone who can reach this can start containers as root on the machine. Close it now and treat the machine as possibly compromised.'],
|
|
41
|
+
10250: ['Kubernetes kubelet', 'high', 'Block this port from the internet; the kubelet API can run commands in pods.'],
|
|
42
|
+
2379: ['etcd', 'high', 'etcd holds cluster secrets. Block it from the internet and require client certificates.'],
|
|
43
|
+
6379: ['Redis', 'high', DB], 27017: ['MongoDB', 'high', DB], 5432: ['PostgreSQL', 'high', DB], 3306: ['MySQL / MariaDB', 'high', DB],
|
|
44
|
+
1433: ['Microsoft SQL Server', 'high', DB], 9200: ['Elasticsearch', 'high', DB], 11211: ['Memcached', 'high', DB], 5984: ['CouchDB', 'high', DB],
|
|
45
|
+
3389: ['Remote Desktop (RDP)', 'high', ADMIN], 5900: ['VNC', 'high', ADMIN], 445: ['Windows file sharing (SMB)', 'high', ADMIN], 23: ['Telnet', 'high', ADMIN],
|
|
46
|
+
21: ['FTP', 'medium', 'FTP sends passwords in plain text. Use SFTP (over SSH) instead and close this port.'],
|
|
47
|
+
111: ['rpcbind', 'medium', ADMIN], 6443: ['Kubernetes API', 'medium', 'Limit the Kubernetes API to your own addresses (firewall or private network).'],
|
|
48
|
+
5601: ['Kibana', 'medium', 'Put it behind a login and a VPN, or block the port.'], 15672: ['RabbitMQ management', 'medium', 'Put it behind a VPN or block the port, and change the default guest login.'],
|
|
49
|
+
5672: ['RabbitMQ', 'medium', DB], 9090: ['Prometheus', 'medium', 'Put it behind a login and a VPN, or block the port. Metrics often reveal internals.'],
|
|
50
|
+
3000: ['Development server (port 3000)', 'low', DEV], 5173: ['Vite dev server', 'low', DEV], 4200: ['Angular dev server', 'low', DEV],
|
|
51
|
+
5000: ['Development server (port 5000)', 'low', DEV], 8000: ['Development server (port 8000)', 'low', DEV],
|
|
52
|
+
8080: ['Alternate web port (8080)', 'low', DEV], 8888: ['Development server (port 8888)', 'low', DEV],
|
|
53
|
+
};
|
|
54
|
+
export const INFO_PORTS = { 22: 'SSH', 25: 'SMTP (mail)', 80: 'HTTP', 443: 'HTTPS' };
|
|
55
|
+
|
|
56
|
+
export const PORT_LIST = [...Object.keys(RISKY_PORTS), ...Object.keys(INFO_PORTS)].map(Number).sort((a, b) => a - b);
|
|
57
|
+
|
|
58
|
+
// 'open' | 'closed' | 'filtered' (no answer in time) | `error:<code>`. Never writes to the socket.
|
|
59
|
+
export function probe(ip, port, timeoutMs = 3000) {
|
|
60
|
+
return new Promise((done) => {
|
|
61
|
+
const s = connect({ host: ip, port });
|
|
62
|
+
let settled = false;
|
|
63
|
+
const end = (v) => { if (!settled) { settled = true; s.destroy(); done(v); } };
|
|
64
|
+
s.setTimeout(timeoutMs, () => end('filtered'));
|
|
65
|
+
s.once('connect', () => end('open'));
|
|
66
|
+
s.once('error', (e) => end(e.code === 'ECONNREFUSED' ? 'closed' : `error:${e.code ?? 'unknown'}`));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Both address families are tried (the first IPv4 and the first IPv6 address): a firewall rule is often set for
|
|
71
|
+
// one and forgotten for the other. A family that cannot be reached at all (no IPv6 route here) is reported as such;
|
|
72
|
+
// the check fails only if no address could be tried.
|
|
73
|
+
export async function scanPorts(host, { probeFn = probe, resolve = (h) => lookup(h, { all: true }), concurrency = 10, ports = PORT_LIST } = {}) {
|
|
74
|
+
let all;
|
|
75
|
+
try { all = await resolve(host); } catch (e) { throw new Error(`could not resolve ${host} (${e.code ?? e.message})`); }
|
|
76
|
+
const list = Array.isArray(all) ? all : [all];
|
|
77
|
+
const picked = [4, 6].map((f) => list.find((a) => a.family === f)).filter(Boolean);
|
|
78
|
+
if (!picked.length) throw new Error(`could not resolve ${host} (no address)`);
|
|
79
|
+
const addrs = [];
|
|
80
|
+
for (const { address: ip, family } of picked) {
|
|
81
|
+
const results = {};
|
|
82
|
+
const queue = [...ports];
|
|
83
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
|
|
84
|
+
for (let p = queue.shift(); p !== undefined; p = queue.shift()) results[p] = await probeFn(ip, p);
|
|
85
|
+
}));
|
|
86
|
+
const states = Object.values(results);
|
|
87
|
+
// Every probe failed in a way that is not "closed" or "no answer": the network is the problem, not the host.
|
|
88
|
+
const unreachable = states.every((st) => st.startsWith('error:')) ? [...new Set(states)].join(', ') : null;
|
|
89
|
+
addrs.push({ ip, family, results, unreachable });
|
|
90
|
+
}
|
|
91
|
+
if (addrs.every((a) => a.unreachable)) {
|
|
92
|
+
throw new Error(`no connection could be tried from this computer (${addrs.map((a) => a.unreachable).join('; ')}): the result would say nothing about ${host}`);
|
|
93
|
+
}
|
|
94
|
+
return { addrs };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function parsePorts({ addrs }, { host }) {
|
|
98
|
+
const byPort = new Map();
|
|
99
|
+
const info = new Set();
|
|
100
|
+
const notices = [];
|
|
101
|
+
for (const a of addrs) {
|
|
102
|
+
if (a.unreachable) {
|
|
103
|
+
notices.push({ id: `ports-ipv${a.family}`, message: `IPv${a.family} address ${a.ip} could not be tried from this computer (${a.unreachable}), so its ports are not counted as closed.` });
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const unclear = Object.values(a.results).filter((st) => st.startsWith('error:')).length;
|
|
107
|
+
if (unclear) notices.push({ id: `ports-ipv${a.family}`, message: `${unclear} of ${Object.keys(a.results).length} ports on ${a.ip} could not be tried (network error), so they are not counted as closed.` });
|
|
108
|
+
for (const [port, state] of Object.entries(a.results)) {
|
|
109
|
+
if (state !== 'open') continue;
|
|
110
|
+
if (!RISKY_PORTS[port]) { info.add(`${port} (${INFO_PORTS[port] ?? 'open'}) on IPv${a.family}`); continue; }
|
|
111
|
+
byPort.set(port, [...(byPort.get(port) ?? []), a]);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const findings = [...byPort].map(([port, hits]) => {
|
|
115
|
+
const risky = RISKY_PORTS[port];
|
|
116
|
+
return {
|
|
117
|
+
fingerprint: `ports:${port}:${host}`,
|
|
118
|
+
category: 'network',
|
|
119
|
+
title: `${risky[0]} accepts connections`,
|
|
120
|
+
severity: { tool: 'port-check', normalized: risky[1] },
|
|
121
|
+
source: { kind: 'tool', tool: 'port-check', rule_id: String(port) },
|
|
122
|
+
evidence: hits.map((a) => ({
|
|
123
|
+
location: a.family === 6 ? `[${a.ip}]:${port}` : `${a.ip}:${port}`,
|
|
124
|
+
detail: `A connection over IPv${a.family} was accepted from the computer that ran this check. Nothing was sent. ${SEEN[addressScope(a.ip)]}`,
|
|
125
|
+
})),
|
|
126
|
+
fix: risky[2],
|
|
127
|
+
references: {},
|
|
128
|
+
};
|
|
129
|
+
});
|
|
130
|
+
return {
|
|
131
|
+
findings,
|
|
132
|
+
notices,
|
|
133
|
+
info: [...info].sort((x, y) => parseInt(x) - parseInt(y)),
|
|
134
|
+
addresses: addrs.map((a) => `${a.ip} (IPv${a.family}${a.unreachable ? ', not reachable from here' : ''})`),
|
|
135
|
+
};
|
|
136
|
+
}
|
package/src/live.js
CHANGED
|
@@ -5,6 +5,7 @@ import { ensureFolderTool, liveTools } from './tools.js';
|
|
|
5
5
|
import { sortAndNumber, countBySeverity } from './findings.js';
|
|
6
6
|
import { loadTargets, resolveTarget } from './targets.js';
|
|
7
7
|
import { parseTestssl, testsslArgs } from './live/testssl.js';
|
|
8
|
+
import { scanPorts, parsePorts, PORT_LIST } from './live/ports.js';
|
|
8
9
|
import { parseZap, zapDockerArgs, zapUrl, ZAP_NOT_CHECKED } from './live/zap.js';
|
|
9
10
|
|
|
10
11
|
// `live` checks one host from the targets file. It is a different kind of check from `scan`:
|
|
@@ -49,25 +50,35 @@ function zapStep({ target, out, log }) {
|
|
|
49
50
|
return parseZap(JSON.parse(readFileSync(rawFile, 'utf8') || 'null'), { url });
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
|
|
53
|
+
async function portsStep({ target, log }) {
|
|
54
|
+
log(`checking ${PORT_LIST.length} well-known risky ports on ${target.host} (connect and close, nothing is sent; about 10 seconds) ...`);
|
|
55
|
+
return parsePorts(await scanPorts(target.host), { host: target.host });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function live(arg, { targetsFile, allowProd, zap = false, ports = false, noTls = false, log = () => {}, version, cwd = process.cwd() }) {
|
|
53
59
|
const target = resolveTarget(arg, loadTargets(resolve(cwd, targetsFile)), { allowProd });
|
|
54
60
|
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.`);
|
|
61
|
+
if (target.scheme === 'http' && !zap && !ports) {
|
|
62
|
+
throw new Error(`${host}:${port} is plain http, so there is no TLS to check. Add --zap to check the web site itself, or --ports to check open ports.`);
|
|
57
63
|
}
|
|
64
|
+
if (noTls && !zap && !ports) throw new Error('--no-tls leaves nothing to check: add --zap or --ports');
|
|
58
65
|
|
|
59
66
|
const out = join(cwd, '.audit', 'out', 'live', `${host}-${port}`);
|
|
60
67
|
mkdirSync(out, { recursive: true });
|
|
61
68
|
writeFileSync(join(cwd, '.audit', 'out', '.gitignore'), '*\n');
|
|
62
69
|
|
|
63
70
|
const steps = [];
|
|
64
|
-
if (target.scheme
|
|
65
|
-
else steps.push({ id: 'testssl', skip: '
|
|
71
|
+
if (target.scheme !== 'https') steps.push({ id: 'testssl', skip: 'plain http: there is no TLS to check', tool: liveTools().testssl });
|
|
72
|
+
else if (noTls) steps.push({ id: 'testssl', skip: 'left out with --no-tls', tool: liveTools().testssl });
|
|
73
|
+
else steps.push({ id: 'testssl', run: tlsStep, tool: liveTools().testssl });
|
|
66
74
|
if (zap) steps.push({ id: 'zap-baseline', run: zapStep, tool: liveTools().zap });
|
|
75
|
+
if (ports) steps.push({ id: 'port-check', run: portsStep, tool: { version: 'built-in', license: 'Apache-2.0' } });
|
|
67
76
|
|
|
68
77
|
const runs = [];
|
|
69
78
|
let findings = [];
|
|
70
79
|
let notices = [];
|
|
80
|
+
const openNotRated = [];
|
|
81
|
+
const addresses = [];
|
|
71
82
|
for (const s of steps) {
|
|
72
83
|
const run = { id: s.id, version: s.tool.version, license: s.tool.license, status: 'ok' };
|
|
73
84
|
runs.push(run);
|
|
@@ -77,6 +88,8 @@ export async function live(arg, { targetsFile, allowProd, zap = false, log = ()
|
|
|
77
88
|
const found = parsed.findings.map((f) => ({ ...f, source: { ...f.source, tool_version: s.tool.version } }));
|
|
78
89
|
findings = findings.concat(found);
|
|
79
90
|
notices = notices.concat(parsed.notices);
|
|
91
|
+
if (parsed.info) openNotRated.push(...parsed.info);
|
|
92
|
+
if (parsed.addresses) addresses.push(...parsed.addresses);
|
|
80
93
|
run.findings = found.length;
|
|
81
94
|
} catch (err) {
|
|
82
95
|
run.status = 'failed';
|
|
@@ -88,15 +101,21 @@ export async function live(arg, { targetsFile, allowProd, zap = false, log = ()
|
|
|
88
101
|
if (steps.some((s) => s.id === 'testssl' && !s.skip)) {
|
|
89
102
|
notes.push('TLS check: only this one host and port: protocols, ciphers, the certificate, HSTS and known TLS weaknesses.');
|
|
90
103
|
}
|
|
104
|
+
if (ports) {
|
|
105
|
+
notes.push('Port check: only a fixed list of well-known risky ports was tried, from the computer that ran this, by connecting and closing at once. ' +
|
|
106
|
+
'"Not open" means closed, blocked by a firewall, or not reachable from here: it cannot tell which, and it says nothing about ports outside the list or about what runs behind an open port.');
|
|
107
|
+
}
|
|
91
108
|
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
109
|
notes.push('Not checked: the app\'s own logic (who may see or change what), other hosts and ports.');
|
|
93
110
|
|
|
94
111
|
const result = {
|
|
95
112
|
generator: `ai-secure-audit ${version}`,
|
|
96
|
-
check: zap ? '
|
|
113
|
+
check: ['live', noTls || target.scheme !== 'https' ? null : 'tls', zap ? 'web' : null, ports ? 'ports' : null].filter(Boolean).join('-'),
|
|
97
114
|
target: { host, port, scheme: target.scheme, env: target.env },
|
|
98
115
|
tools: runs,
|
|
99
116
|
notices,
|
|
117
|
+
...(addresses.length ? { addresses_tried: addresses } : {}),
|
|
118
|
+
open_not_rated: openNotRated,
|
|
100
119
|
notes,
|
|
101
120
|
findings: sortAndNumber(findings),
|
|
102
121
|
};
|
|
@@ -120,7 +139,7 @@ export function liveReport(result, date) {
|
|
|
120
139
|
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
140
|
for (const f of findings) {
|
|
122
141
|
L.push(`### ${f.id}: ${f.title} (${f.severity.normalized})`, '');
|
|
123
|
-
L.push(`**Found by:** ${
|
|
142
|
+
L.push(`**Found by:** ${{ web: 'ZAP baseline (web)', network: 'port check', tls: 'testssl (TLS)' }[f.category] ?? f.category}`, '');
|
|
124
143
|
L.push(`**Where / what was seen:** ${f.evidence.map((e) => `\`${e.location}\`${e.detail ? ` (${e.detail})` : ''}`).join('; ')}`, '');
|
|
125
144
|
L.push(`**How to fix it:** ${f.fix}`, '');
|
|
126
145
|
}
|
|
@@ -129,6 +148,10 @@ export function liveReport(result, date) {
|
|
|
129
148
|
for (const n of notices) L.push(`- ${n.message}`);
|
|
130
149
|
L.push('');
|
|
131
150
|
}
|
|
151
|
+
if (result.addresses_tried?.length) L.push('## Addresses tried by the port check', '', ...result.addresses_tried.map((a) => `- ${a}`), '');
|
|
152
|
+
if (result.open_not_rated?.length) {
|
|
153
|
+
L.push('## Open ports that are not rated', '', `Seen open: ${result.open_not_rated.join(', ')}. These are normal on many servers; they are listed so you know they answer.`, '');
|
|
154
|
+
}
|
|
132
155
|
L.push('## What this check did not see', '');
|
|
133
156
|
for (const n of result.notes) L.push(`- ${n}`);
|
|
134
157
|
L.push('', '## Tools', '', '| Tool | Version | License | Result |', '|---|---|---|---|');
|
package/src/report-simple.js
CHANGED
|
@@ -104,6 +104,7 @@ export function reportSimple(result, date) {
|
|
|
104
104
|
lines.push('These tools cannot see the following, so "nothing found" does not cover them:', '');
|
|
105
105
|
lines.push('- Whether one user can open or change another user\'s data');
|
|
106
106
|
lines.push('- Rules of your business: prices, coupons, payments, approvals');
|
|
107
|
+
lines.push('- How signing in, signing up and resetting a password work, for example whether someone can make themselves an admin when signing up, or guess the answer to a reset question');
|
|
107
108
|
lines.push('- Anything about your live website or server');
|
|
108
109
|
for (const g of result.coverage?.gaps ?? []) lines.push(`- ${g}`);
|
|
109
110
|
lines.push('');
|
package/src/report.js
CHANGED
|
@@ -125,6 +125,7 @@ export function reportMarkdown(result, date) {
|
|
|
125
125
|
lines.push('');
|
|
126
126
|
lines.push('- Whether one user can open or change another user\'s data (for example by changing an id in the URL)');
|
|
127
127
|
lines.push('- Business rules: prices, coupons, approvals, payments');
|
|
128
|
+
lines.push('- How sign-in, sign-up and password reset work (for example a role the sign-up form can set, a reset question anyone can guess, or a login that skips a check)');
|
|
128
129
|
lines.push('- Database rules such as Supabase row-level security or Firebase security rules (planned)');
|
|
129
130
|
lines.push('- Anything about the live server or website');
|
|
130
131
|
for (const g of result.coverage?.gaps ?? []) lines.push(`- ${g}`);
|
|
@@ -154,7 +155,7 @@ export function consoleSummary(result, outRel) {
|
|
|
154
155
|
'- A finding marked not_committed can be moved out of the code without rotating, unless the key was shared or pasted somewhere else.',
|
|
155
156
|
'- Findings of type code come from pattern rules and can be wrong. Read the code at that location and tell the user',
|
|
156
157
|
' if a limit or check exists somewhere the rule cannot see (another file, the proxy) before changing anything.',
|
|
157
|
-
'- Not checked: whether one user can reach another user\'s data, and
|
|
158
|
+
'- Not checked: whether one user can reach another user\'s data, business rules, and how sign-in, sign-up and password reset work. Say so.',
|
|
158
159
|
...(result.coverage?.gaps ?? []).map((g) => `- ${g} Tell the user.`),
|
|
159
160
|
...(result.notices ?? []).map((n) => `- ${n.message} Tell the user, and ask before editing the file.`),
|
|
160
161
|
...(failed.length ? ['- Some tools did not run (see NOT RUN above). Tell the user the check is incomplete.'] : []),
|
package/src/scan.js
CHANGED
|
@@ -59,6 +59,7 @@ export async function scan(target, { log = () => {}, version }) {
|
|
|
59
59
|
const runs = [];
|
|
60
60
|
let findings = [];
|
|
61
61
|
let librariesRead = null; // stays null when the library scanner did not run: the report says that already
|
|
62
|
+
let codeRead = null; // files the code checker could not read fully; null when it did not run
|
|
62
63
|
for (const s of BASIC_SCANNERS) {
|
|
63
64
|
const run = { id: s.id, version: tools[s.id].version, license: tools[s.id].license, status: 'ok' };
|
|
64
65
|
runs.push(run);
|
|
@@ -84,6 +85,7 @@ export async function scan(target, { log = () => {}, version }) {
|
|
|
84
85
|
json = pass.name ? [...(json ?? []), ...(data ?? []).map((item) => ({ ...item, pass: pass.name }))] : data;
|
|
85
86
|
}
|
|
86
87
|
if (s.filesRead) librariesRead = new Set(s.filesRead(json, ctx));
|
|
88
|
+
if (s.codeRead) codeRead = s.codeRead(json, ctx);
|
|
87
89
|
const found = s.parse(json, ctx).map((f) => ({ ...f, source: { ...f.source, tool_version: run.version } }));
|
|
88
90
|
run.findings = found.length;
|
|
89
91
|
findings = findings.concat(found);
|
|
@@ -94,6 +96,7 @@ export async function scan(target, { log = () => {}, version }) {
|
|
|
94
96
|
}
|
|
95
97
|
|
|
96
98
|
const coverage = projectCoverage(root);
|
|
99
|
+
if (codeRead) coverage.code_read = codeRead;
|
|
97
100
|
coverage.unread = librariesRead ? coverage.lockfiles.map((l) => l.file).filter((f) => !librariesRead.has(f)) : [];
|
|
98
101
|
const result = {
|
|
99
102
|
generator: `ai-secure-audit ${version}`,
|
|
@@ -104,7 +107,7 @@ export async function scan(target, { log = () => {}, version }) {
|
|
|
104
107
|
// About this tool's own output, not a weakness of the app: kept apart from findings so it is never rated.
|
|
105
108
|
notices: dockerignoreNotices(root),
|
|
106
109
|
notes: [
|
|
107
|
-
'Not checked by this tool: whether one user can reach another user\'s data, business rules, and anything running on a server.',
|
|
110
|
+
'Not checked by this tool: whether one user can reach another user\'s data, business rules, how sign-in, sign-up and password reset work, and anything running on a server.',
|
|
108
111
|
'Code rules (category code) are this kit\'s own opengrep rules. They can be wrong: check the location before changing code.',
|
|
109
112
|
'Config files are checked by trivy: Dockerfiles, Kubernetes, Helm, Terraform, CloudFormation, Azure ARM and Ansible files. ' +
|
|
110
113
|
'trivy does not read Docker Compose files; coverage.gaps names any that were not checked.',
|
package/src/scanners/opengrep.js
CHANGED
|
@@ -22,25 +22,68 @@ export default {
|
|
|
22
22
|
|
|
23
23
|
// Local rules only, no version check: nothing about the project leaves the machine.
|
|
24
24
|
// --no-git-ignore: code that is not committed yet is still code that will run.
|
|
25
|
+
// --taint-intrafile: follow a request value into a helper function in the same file (sql-built-from-request).
|
|
25
26
|
args(ctx, out) {
|
|
26
27
|
return ['scan', '--config', RULES, '--json', '--output', out, '--disable-version-check', '--quiet',
|
|
27
|
-
'--no-git-ignore', ...[...EXCLUDE, ...RULE_TESTS].flatMap((d) => ['--exclude', d]), ctx.root];
|
|
28
|
+
'--no-git-ignore', '--taint-intrafile', ...[...EXCLUDE, ...RULE_TESTS].flatMap((d) => ['--exclude', d]), ctx.root];
|
|
28
29
|
},
|
|
29
30
|
|
|
30
31
|
okExit: [0],
|
|
31
32
|
|
|
33
|
+
// Files opengrep could not check fully, from its errors list: a syntax error means the whole file was skipped, a
|
|
34
|
+
// partial parse means some lines were skipped (a finding there can be missing), a timeout means a rule gave up on
|
|
35
|
+
// the file. Errors with no file (about a rule) are left out: those make the run fail instead.
|
|
36
|
+
codeRead(json, ctx) {
|
|
37
|
+
const notRead = new Map();
|
|
38
|
+
const inPart = new Map();
|
|
39
|
+
const stopped = new Map();
|
|
40
|
+
for (const e of json?.errors ?? []) {
|
|
41
|
+
if (!e?.path) continue;
|
|
42
|
+
const file = rel(ctx.root, e.path);
|
|
43
|
+
const kind = Array.isArray(e.type) ? e.type[0] : e.type;
|
|
44
|
+
const lines = (e.spans ?? []).map((s) => s?.start?.line).filter((n) => Number.isInteger(n));
|
|
45
|
+
// A syntax error that stops the whole file has no spans; its message names the line: "...at line <path>:7:".
|
|
46
|
+
const inMessage = Number(String(e.message ?? '').split(`${e.path}:`)[1]?.match(/^(\d+):/)?.[1]);
|
|
47
|
+
if (!lines.length && Number.isInteger(inMessage) && inMessage > 0) lines.push(inMessage);
|
|
48
|
+
if (kind === 'PartialParsing') {
|
|
49
|
+
inPart.set(file, [...new Set([...(inPart.get(file) ?? []), ...lines])].sort((a, b) => a - b));
|
|
50
|
+
} else if (kind === 'Timeout') {
|
|
51
|
+
const rule = String(e.rule_id ?? '').split('.').at(-1);
|
|
52
|
+
stopped.set(file, [...new Set([...(stopped.get(file) ?? []), ...(rule ? [rule] : [])])].sort());
|
|
53
|
+
} else if (!notRead.has(file)) {
|
|
54
|
+
notRead.set(file, lines[0] ?? null);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const sorted = (m) => [...m].sort((a, b) => (a[0] < b[0] ? -1 : 1));
|
|
58
|
+
return {
|
|
59
|
+
not_read: sorted(notRead).map(([file, line]) => ({ file, line })),
|
|
60
|
+
read_in_part: sorted(inPart).filter(([file]) => !notRead.has(file)).map(([file, lines]) => ({ file, lines })),
|
|
61
|
+
stopped: sorted(stopped).map(([file, rules]) => ({ file, rules })),
|
|
62
|
+
};
|
|
63
|
+
},
|
|
64
|
+
|
|
32
65
|
parse(json, ctx) {
|
|
33
66
|
// opengrep prefixes the rule id with the config path, joined by dots; our rule ids have no dots.
|
|
34
67
|
const results = (json?.results ?? []).map((r) => ({ ...r, ruleId: r.check_id.split('.').at(-1) }));
|
|
35
68
|
// Internal rules are never shown: they only record that something exists anywhere in the project (for example a
|
|
36
69
|
// throttle registered for the whole app), and a rule with suppressed-by: <id> is dropped when that rule matched.
|
|
37
70
|
const seen = new Set(results.filter((r) => r.extra?.metadata?.internal).map((r) => r.ruleId));
|
|
71
|
+
// A rule with suppressed-on-same-line-by: <id> is dropped where that rule reported the same file and line (a
|
|
72
|
+
// medium "check the callers" finding is not needed next to the high one that already sees the request).
|
|
73
|
+
const lineOf = (r) => `${rel(ctx.root, r.path)}:${r.start.line}`;
|
|
74
|
+
const reported = new Set(results.map((r) => `${r.ruleId}@${lineOf(r)}`));
|
|
38
75
|
const findings = [];
|
|
76
|
+
// A taint rule reports one result per path from a source to the same line (three request values in one query
|
|
77
|
+
// give three results): one line is one finding.
|
|
78
|
+
const done = new Set();
|
|
39
79
|
for (const r of results) {
|
|
40
80
|
const meta = r.extra?.metadata ?? {};
|
|
41
81
|
if (meta.internal || (meta['suppressed-by'] && seen.has(meta['suppressed-by']))) continue;
|
|
82
|
+
if (meta['suppressed-on-same-line-by'] && reported.has(`${meta['suppressed-on-same-line-by']}@${lineOf(r)}`)) continue;
|
|
42
83
|
const ruleId = r.ruleId;
|
|
43
84
|
const location = `${rel(ctx.root, r.path)}:${r.start.line}`;
|
|
85
|
+
if (done.has(`${ruleId}:${location}`)) continue;
|
|
86
|
+
done.add(`${ruleId}:${location}`);
|
|
44
87
|
const [title, ...rest] = (r.extra?.message ?? ruleId).split('. ');
|
|
45
88
|
findings.push({
|
|
46
89
|
fingerprint: `opengrep:${ruleId}:${location}`,
|