ai-secure-audit 0.0.14 → 0.0.15

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 CHANGED
@@ -3,7 +3,7 @@
3
3
  > Status: 0.0.x on npm runs the basic check with `npx ai-secure-audit`: secrets, libraries with known holes and, from
4
4
  > 0.0.5, code rules for routes anyone can repeat without limit and, from 0.0.9, for session checks that a built-in
5
5
  > name such as `constructor` passes. From 0.0.10 it also checks Dockerfiles with trivy (Compose files are not read yet,
6
- > and the report says so), and from 0.0.11 it warns when a Docker build would copy these results into the image, 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). From 0.0.14 a secret in a file that was moved with `git mv` is no longer called "not committed yet" (that wording told people they could skip rotating a key that is already in git). v0.1 is not released yet.
6
+ > and the report says so), and from 0.0.11 it warns when a Docker build would copy these results into the image, and from 0.0.13 `--report simple` writes a short to-do list in plain words (`report-simple.md`) and `live` checks one host you list in `targets.yml`: its TLS with testssl.sh, and with `--zap` its web headers and cookies with OWASP ZAP in Docker. `live` has only been tried on servers on the same machine and a GitHub test runner, never on a real remote site, and it does not run on Windows (TLS part) or without Docker (ZAP part). From 0.0.15 `live --ports` also checks which of 34 well-known risky ports (databases, Docker API, RDP, SMB, dev ports) accept a connection from the computer that runs it, and says what the address shows (a loopback or private address is not the internet). From 0.0.14 a secret in a file that was moved with `git mv` is no longer called "not committed yet" (that wording told people they could skip rotating a key that is already in git). v0.1 is not released yet.
7
7
  >
8
8
  > **มือใหม่เริ่มตรงนี้:** [learn/](learn/) ควรตรวจอะไรก่อน เพราะอะไร และแก้ยังไง (ภาษาไทย)
9
9
  >
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-secure-audit",
3
- "version": "0.0.14",
3
+ "version": "0.0.15",
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": {
package/src/cli.js CHANGED
@@ -26,6 +26,8 @@ Options
26
26
  --report simple also write report-simple.md: a short to-do list in plain words
27
27
  --targets <file> for live: the list of hosts you may check (default: targets.yml)
28
28
  --zap for live: also run the ZAP baseline web check in Docker (passive: reads responses only)
29
+ --ports for live: also check well-known risky ports (databases, Docker, remote desktop, dev servers): connect and close, nothing is sent
30
+ --no-tls for live: skip the TLS check (it takes about 2 minutes), for example when you only want --ports
29
31
  --allow-prod for live: also allow hosts marked prod in the targets file
30
32
  --fail-on <level> exit 1 if a finding is at or above: ${SEVERITY_ORDER.slice(0, 4).join(', ')}
31
33
  --advanced add the Docker-based advanced tools (not available yet)
@@ -35,7 +37,7 @@ Options
35
37
  Results are written to <path>/.audit/out/ (git-ignored automatically).`;
36
38
 
37
39
  function parseArgs(argv) {
38
- const opts = { command: 'scan', path: '.', json: false, failOn: null, advanced: false, report: null, targets: 'targets.yml', allowProd: false, zap: false };
40
+ const opts = { command: 'scan', path: '.', json: false, failOn: null, advanced: false, report: null, targets: 'targets.yml', allowProd: false, zap: false, ports: false, noTls: false };
39
41
  const rest = [];
40
42
  for (let i = 0; i < argv.length; i++) {
41
43
  const a = argv[i];
@@ -43,6 +45,8 @@ function parseArgs(argv) {
43
45
  else if (a === '--advanced') opts.advanced = true;
44
46
  else if (a === '--allow-prod') opts.allowProd = true;
45
47
  else if (a === '--zap') opts.zap = true;
48
+ else if (a === '--ports') opts.ports = true;
49
+ else if (a === '--no-tls') opts.noTls = true;
46
50
  else if (a === '--targets') opts.targets = argv[++i];
47
51
  else if (a === '--report') opts.report = argv[++i];
48
52
  else if (a.startsWith('--report=')) opts.report = a.slice(9);
@@ -127,7 +131,7 @@ export async function main(argv) {
127
131
  case 'live': {
128
132
  if (opts.path === '.') throw new Error('live needs a host: npx ai-secure-audit live <host[:port]>');
129
133
  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 });
134
+ const { out, result } = await live(opts.path, { targetsFile: opts.targets, allowProd: opts.allowProd, zap: opts.zap, ports: opts.ports, noTls: opts.noTls, log, version: pkg.version });
131
135
  const r = relative(process.cwd(), out).split('\\').join('/');
132
136
  process.stdout.write(opts.json ? JSON.stringify(result, null, 2) + '\n' : liveSummary(result, r) + '\n');
133
137
  if (result.tools.some((t) => t.status === 'failed')) return 2;
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
- export async function live(arg, { targetsFile, allowProd, zap = false, log = () => {}, version, cwd = process.cwd() }) {
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 === '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 });
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 ? 'live-tls-web' : 'live-tls',
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:** ${f.category === 'web' ? 'ZAP baseline (web)' : 'testssl (TLS)'}`, '');
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 |', '|---|---|---|---|');