Security suites from the 2026-12 audit: static rules, attack probes, per-class tests, gate
- doctor: code-patterns (unescaped HTML/JSON-LD, eval, shell, NEXT_PUBLIC_ secrets, overrideAccess / Local API user, where from the request, redirects and fetches to a request address) and config-dangerous; live-probes runs the safe attack probes on --url - ATTACK_PROBES / runAttackProbes / createProbeContext exported from /doctor; the reference site runs all of them in pnpm e2e:built (both bundlers) plus CSRF and cookie flags; project template iapl-audit/resources/attack-probes.spec.template.ts - test/securityPatterns.test.ts gates every hit against test/security-patterns.allow.json; test/securityClasses.test.ts covers XSS, redirects, pollution, logs, DoS, cache poisoning - pnpm security:gate (pnpm audit --prod, the two suites, optional offline ZAP) in prepublishOnly - audit findings F1, F3, F4, F5 reproduced as expected-to-fail tests/probes; no fix built - docs: security.md threat list + Security suites, doctor.md, AGENT.md, CHANGELOG, skills Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a416411f01
commit
d2f19095dc
@@ -18,6 +18,8 @@ export { DEFAULT_SRC_ALLOW, findFrontend } from '../modules/doctor/rules/layout.
|
||||
export type { FrontendLayout } from '../modules/doctor/rules/layout.js'
|
||||
export { createLiveFetcher } from '../modules/doctor/rules/live.js'
|
||||
export { performanceRules } from '../modules/doctor/rules/performance.js'
|
||||
export { codeFindings, listCodeFiles, LIVE_PROBE_IDS, scanCode, scanConfigs, SECURITY_OK_MARKER, securityCodeRules } from '../modules/doctor/rules/securityCode.js'
|
||||
export type { CodeHit, CodePatternId } from '../modules/doctor/rules/securityCode.js'
|
||||
export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling.js'
|
||||
export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js'
|
||||
export type { RunDoctorOptions } from '../modules/doctor/run.js'
|
||||
@@ -38,6 +40,9 @@ export type { GrowthThresholds } from '../modules/doctor/types.js'
|
||||
// Performance budgets (docs/performance.md): the defaults, a project's own on top, and the check the gate runs
|
||||
export { IMAGE_RULES, overBudget, PERF_BUDGETS, perfBudgets, SERVER_BUDGET } from '../modules/performance/budgets.js'
|
||||
export type { PerfBudget, PerfMeasurement, PerfProfile, ServerBudget } from '../modules/performance/budgets.js'
|
||||
// HTTP attack probes (docs/security.md "Security suites")
|
||||
export { ATTACK_PROBES, createProbeContext, runAttackProbes } from '../modules/security/attackProbes.js'
|
||||
export type { AttackProbe, ProbeAnswer, ProbeContext, ProbeResult } from '../modules/security/attackProbes.js'
|
||||
// routes:check — the site's public routes against the judged snapshot (docs/security.md "Routes nobody has judged")
|
||||
export { runRouteCheck } from '../modules/security/routeCheck.js'
|
||||
export type { RunRouteCheckOptions } from '../modules/security/routeCheck.js'
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
import { readdirSync, statSync } from 'node:fs'
|
||||
import { join, relative } from 'node:path'
|
||||
|
||||
import type { DoctorContext } from '../project.js'
|
||||
import type { DoctorRule, DoctorSeverity, RuleFinding } from '../types.js'
|
||||
|
||||
import { ATTACK_PROBES, createProbeContext, runAttackProbes } from '../../security/attackProbes.js'
|
||||
import { configFile, nextConfigFile } from '../project.js'
|
||||
import { stripComments } from '../util.js'
|
||||
|
||||
/**
|
||||
* Static security rules over the project's own code (security.md → "Security suites"). Each pattern is a class that
|
||||
* hits Payload / Next.js sites again and again: HTML or JSON printed into the page without escaping, the Local API
|
||||
* run with access switched off where a visitor reaches it, a query built from what the request sent, code built from
|
||||
* strings, secrets in the browser bundle, redirects and server-side fetches to an address the request chose.
|
||||
*
|
||||
* Patterns, not proof: a finding is a place to look. A place that is right on purpose carries a comment on the same
|
||||
* line or the line above — `// iapl-security-ok: <why>` — and the finding goes; a whole file or rule is silenced in
|
||||
* iapl-doctor.json (`rules: { "code-override-access": { files: ["src/lib/admin/**"], off: true, reason: "…" } }`).
|
||||
*/
|
||||
|
||||
/** The marker that accepts one place, with its reason: `// iapl-security-ok: the value is a number`. */
|
||||
export const SECURITY_OK_MARKER = 'iapl-security-ok'
|
||||
|
||||
const CODE_EXT = /\.[cm]?[jt]sx?$/
|
||||
/** Never scanned: generated, built or vendored code, and the project's tests. */
|
||||
const SKIP_DIR = new Set(['.agents', '.git', '.next', '.turbo', 'build', 'coverage', 'dist', 'node_modules', 'out'])
|
||||
const SKIP_FILE = /(?:^|\/)(?:payload-types\.ts|importMap\.js|next-env\.d\.ts)$|\.(?:test|spec)\.[cm]?[jt]sx?$|\.d\.ts$/
|
||||
/** Code no visitor reaches: seeds, migrations, scripts, tests. Rules about request input and access skip it. */
|
||||
const OFFLINE_PATH = /(?:^|\/)(?:seed|seeds|migrations|scripts|e2e|tests?|__tests__|fixtures)(?:\/|$)/
|
||||
|
||||
export type CodePatternId =
|
||||
| 'code-eval'
|
||||
| 'code-inner-html'
|
||||
| 'code-local-api-user'
|
||||
| 'code-open-redirect'
|
||||
| 'code-override-access'
|
||||
| 'code-public-secret'
|
||||
| 'code-raw-where'
|
||||
| 'code-shell'
|
||||
| 'code-ssrf'
|
||||
|
||||
export type CodeHit = { file: string; line: number; message: string; rule: CodePatternId; severity: DoctorSeverity; text: string }
|
||||
|
||||
/** Files to scan, relative to the project root: `src/` (or the root's app, lib, components… when there is none). */
|
||||
export function listCodeFiles(root: string, start: string): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (dir: string) => {
|
||||
let names: string[]
|
||||
try {
|
||||
names = readdirSync(dir)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const name of names) {
|
||||
if (SKIP_DIR.has(name)) {continue}
|
||||
const full = join(dir, name)
|
||||
let isDir = false
|
||||
try {
|
||||
isDir = statSync(full).isDirectory()
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const rel = relative(root, full).split('\\').join('/')
|
||||
if (isDir) {walk(full)} else if (CODE_EXT.test(name) && !SKIP_FILE.test(rel)) {out.push(rel)}
|
||||
}
|
||||
}
|
||||
walk(join(root, start))
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
/** The text of the `{ … }` (or `( … )`) that opens at `open`, up to `max` characters. */
|
||||
function balanced(code: string, open: number, max = 1500): string {
|
||||
const pairs: Record<string, string> = { '(': ')', '[': ']', '{': '}' }
|
||||
const stack: string[] = []
|
||||
let quote: null | string = null
|
||||
for (let i = open; i < code.length && i < open + max; i++) {
|
||||
const c = code[i]
|
||||
if (quote) {
|
||||
if (c === '\\') {i++; continue}
|
||||
if (c === quote) {quote = null}
|
||||
continue
|
||||
}
|
||||
if (c === '"' || c === "'" || c === '`') {quote = c; continue}
|
||||
if (pairs[c]) {stack.push(pairs[c])} else if (c === stack.at(-1)) {
|
||||
stack.pop()
|
||||
if (!stack.length) {return code.slice(open, i + 1)}
|
||||
}
|
||||
}
|
||||
return code.slice(open, open + max)
|
||||
}
|
||||
|
||||
const lineOf = (code: string, index: number) => code.slice(0, index).split('\n').length
|
||||
|
||||
/** True when the line, or the line above, carries `iapl-security-ok`. Read from the raw text (comments kept). */
|
||||
function accepted(raw: string[], line: number): boolean {
|
||||
return [raw[line - 1], raw[line - 2]].some((l) => l?.includes(SECURITY_OK_MARKER))
|
||||
}
|
||||
|
||||
/** What a request handed in: query, body, params, headers, search params. */
|
||||
const REQUEST_INPUT = String.raw`(?:req|request)\s*\.\s*(?:query|body|data|params|headers|json\s*\(|formData\s*\(|text\s*\()|searchParams\b|\bparams\s*\.|\bbody\s*\.|\bformData\s*\.\s*get\s*\(|nextUrl\s*\.\s*searchParams|routeParams\b`
|
||||
const FROM_REQUEST = new RegExp(REQUEST_INPUT)
|
||||
|
||||
/** __html values the plugin and common sanitizers make safe. */
|
||||
const SAFE_HTML = /\.replace\(\s*\/<\/g|sanitize|DOMPurify|xss\(|consentBannerScript|consentDecidedScript|themeScript|cookieButtonSpaceScript|jsonLdScript|serializeJsonLd|escapeHtml|escapeJson/
|
||||
|
||||
/** Secrets whose name says so; the public keys of browser tools are not secrets. */
|
||||
const SECRET_NAME = /NEXT_PUBLIC_[A-Z0-9_]*(?:SECRET|PASSWORD|PASSWD|PRIVATE|_TOKEN|DATABASE|DB_URI|MONGO|POSTGRES|SMTP_PASS|API_KEY_SECRET)[A-Z0-9_]*/g
|
||||
const SERVER_ONLY_ENV = /process\.env\.(?:PAYLOAD_SECRET|DATABASE_URI|DATABASE_URL|POSTGRES_URL|MONGODB_URI|R2_SECRET_ACCESS_KEY|R2_ACCESS_KEY_ID|TURNSTILE_SECRET_KEY|CRON_SECRET|IAPL_DOCTOR_TOKEN|IAPL_COOKIE_SCAN_TOKEN|SMTP_PASS(?:WORD)?|GRAPH_CLIENT_SECRET|RESEND_API_KEY)\b/g
|
||||
|
||||
/**
|
||||
* Every pattern hit in one file's code. `path` decides whether the file is reachable from the web (seeds, migrations,
|
||||
* scripts and tests are not). Exported for a project's own test or another scanner.
|
||||
*/
|
||||
export function scanCode(path: string, rawCode: string): CodeHit[] {
|
||||
const raw = rawCode.split('\n')
|
||||
// comments out, line count kept (block comments keep their newlines)
|
||||
const code = rawCode.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:'"`\\])\/\/.*$/gm, '$1')
|
||||
const web = !OFFLINE_PATH.test(path)
|
||||
const client = /^\s*['"]use client['"]/m.test(code)
|
||||
const hits: CodeHit[] = []
|
||||
const add = (rule: CodePatternId, index: number, severity: DoctorSeverity, message: string) => {
|
||||
const line = lineOf(code, index)
|
||||
if (accepted(raw, line)) {return}
|
||||
hits.push({ file: path, line, message, rule, severity, text: (raw[line - 1] ?? '').trim().slice(0, 160) })
|
||||
}
|
||||
|
||||
// 1. HTML into the page: dangerouslySetInnerHTML / innerHTML with a value nothing escaped
|
||||
for (const m of code.matchAll(/dangerouslySetInnerHTML\s*=\s*\{/g)) {
|
||||
const value = balanced(code, m.index + m[0].length - 1, 800)
|
||||
if (SAFE_HTML.test(value)) {continue}
|
||||
const json = /JSON\.stringify/.test(value)
|
||||
add('code-inner-html', m.index, 'error', json
|
||||
? 'JSON printed into a <script> without escaping "<": a value with </script> ends the script (JsonLdGraph, or .replace(/</g, "\\\\u003c"))'
|
||||
: 'dangerouslySetInnerHTML with a value that no sanitizer passed (RenderRichText, or a sanitizer such as DOMPurify)')
|
||||
}
|
||||
for (const m of code.matchAll(/\.(?:innerHTML|outerHTML)\s*=(?!=)|\.insertAdjacentHTML\s*\(|document\.write(?:ln)?\s*\(/g)) {
|
||||
const rest = code.slice(m.index, m.index + 300).split('\n')[0]
|
||||
if (SAFE_HTML.test(rest) || /=\s*(?:''|""|``)\s*;?$/.test(rest)) {continue}
|
||||
add('code-inner-html', m.index, 'error', 'HTML written into the DOM from a string (innerHTML / insertAdjacentHTML / document.write)')
|
||||
}
|
||||
|
||||
// 2. code built from strings
|
||||
for (const m of code.matchAll(/(?<![\w.])eval\s*\(|new\s+Function\s*\(|\bvm\s*\.\s*(?:runInNewContext|runInThisContext|runInContext|compileFunction)\s*\(|\bset(?:Timeout|Interval)\s*\(\s*['"`]/g)) {
|
||||
add('code-eval', m.index, 'error', 'code built from a string (eval / new Function / vm / setTimeout with a string)')
|
||||
}
|
||||
for (const m of code.matchAll(/\b(?:exec|execSync)\s*\(\s*`[^`]*\$\{/g)) {
|
||||
add('code-shell', m.index, web ? 'error' : 'warning', 'a shell command built from a template string: pass arguments with execFile / spawn instead')
|
||||
}
|
||||
|
||||
// 3. secrets that reach the browser
|
||||
for (const m of code.matchAll(SECRET_NAME)) {
|
||||
add('code-public-secret', m.index, 'error', `${m[0]}: a NEXT_PUBLIC_ variable is copied into the browser bundle; a secret must never have that prefix`)
|
||||
}
|
||||
if (client) {
|
||||
for (const m of code.matchAll(SERVER_ONLY_ENV)) {
|
||||
add('code-public-secret', m.index, 'error', `${m[0]} read in a 'use client' file: rendered on the server, the value can end up in the HTML`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!web) {return hits}
|
||||
|
||||
// 4. the Local API with access off where a visitor reaches it
|
||||
for (const m of code.matchAll(/overrideAccess\s*:\s*true\b/g)) {
|
||||
add('code-override-access', m.index, 'warning', 'overrideAccess: true in code a request reaches: every access rule is skipped; pass the user and overrideAccess: false, or say why with iapl-security-ok')
|
||||
}
|
||||
for (const m of code.matchAll(/\bpayload\s*\.\s*(?:find|findByID|findGlobal|count|create|update|updateGlobal|delete|duplicate|findVersions|findVersionByID|findGlobalVersions)\s*\(\s*\{/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1)
|
||||
if (/\buser\s*[:,}]/.test(args) && !/overrideAccess\s*:/.test(args)) {
|
||||
add('code-local-api-user', m.index, 'warning', "the Local API gets a user but no overrideAccess: false — Payload then IGNORES the user's rules (overrideAccess defaults to true)")
|
||||
}
|
||||
}
|
||||
|
||||
// 5. a query built from what the request sent (operators, other fields, other people's records)
|
||||
for (const m of code.matchAll(/\bwhere\s*:\s*/g)) {
|
||||
const start = m.index + m[0].length
|
||||
const value = code[start] === '{' ? balanced(code, start, 600) : code.slice(start, start + 200).split(/[,\n})]/)[0]
|
||||
const direct = code[start] !== '{'
|
||||
if ((direct && (FROM_REQUEST.test(value) || /^(?:JSON\.parse|qs\.parse|parse)\s*\(/.test(value))) || (!direct && /:\s*(?:req|request)\s*\.\s*(?:query|body)\s*(?:[,}\n]|\.where)/.test(value))) {
|
||||
add('code-raw-where', m.index, 'error', 'a where clause taken from the request: the visitor picks operators and fields ($ne, exists, other users\' records). Build it from checked values')
|
||||
}
|
||||
}
|
||||
|
||||
// 6. redirects and server-side fetches to an address the request chose
|
||||
for (const m of code.matchAll(/\b(?:redirect|permanentRedirect|NextResponse\s*\.\s*redirect|Response\s*\.\s*redirect)\s*\(/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1, 300)
|
||||
if (FROM_REQUEST.test(args) || /\.get\(\s*['"](?:next|redirect|redirectTo|returnTo|return|back|url|to|callbackUrl)['"]\s*\)/.test(args)) {
|
||||
if (/safeAdminBack|safeRedirect|isSafe|startsWith\(\s*['"]\/['"]\s*\)/.test(args)) {continue}
|
||||
add('code-open-redirect', m.index, 'warning', 'a redirect to an address from the request: accept a path of this site only (one leading "/", not "//" or "/\\\\")')
|
||||
}
|
||||
}
|
||||
for (const m of code.matchAll(/\bfetch\s*\(/g)) {
|
||||
const args = balanced(code, m.index + m[0].length - 1, 300)
|
||||
const target = args.slice(1).split(/,(?![^(]*\))/)[0] ?? ''
|
||||
if (FROM_REQUEST.test(target) || /\b(?:body|data|input|args)\s*\.\s*(?:url|href|endpoint|webhook|callback)\b/.test(target)) {
|
||||
add('code-ssrf', m.index, 'warning', 'a server-side fetch of an address the request chose (SSRF): allow a fixed list of hosts, refuse private addresses')
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
/** next.config / payload.config settings that open a known door. */
|
||||
export function scanConfigs(next: { code: string; file: string } | null, payload: { code: string; file: string } | null): RuleFinding[] {
|
||||
const out: RuleFinding[] = []
|
||||
if (next) {
|
||||
const c = stripComments(next.code)
|
||||
if (/dangerouslyAllowSVG\s*:\s*true/.test(c) && !/contentSecurityPolicy\s*:/.test(c)) {
|
||||
out.push({ file: next.file, fix: "images.contentSecurityPolicy: \"default-src 'self'; script-src 'none'; sandbox;\" and contentDispositionType: 'attachment'", message: 'images.dangerouslyAllowSVG without images.contentSecurityPolicy: an uploaded SVG runs script on the site\'s domain through /_next/image', severity: 'error' })
|
||||
}
|
||||
if (/hostname\s*:\s*['"]\*\*?['"]/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'list the media hosts (buildImagesConfig)', message: 'images.remotePatterns allows every host: /_next/image fetches and resizes any image on the internet for anyone (cost, SSRF to inner addresses on old Next)', severity: 'warning' })
|
||||
}
|
||||
if (/allowedOrigins\s*:\s*\[[^\]]*['"]\*['"]/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'name the origins', message: 'serverActions.allowedOrigins contains "*": Server Actions accept posts from any site (CSRF)', severity: 'error' })
|
||||
}
|
||||
if (/productionBrowserSourceMaps\s*:\s*true/.test(c)) {
|
||||
out.push({ file: next.file, fix: 'productionBrowserSourceMaps: false (upload maps to the error tracker instead)', message: 'productionBrowserSourceMaps: true publishes the source of every client file', severity: 'warning' })
|
||||
}
|
||||
}
|
||||
if (payload) {
|
||||
const c = stripComments(payload.code)
|
||||
if (/\bcors\s*:\s*['"]\*['"]/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'cors: [process.env.NEXT_PUBLIC_SERVER_URL]', message: "cors: '*': any site may call the API from a visitor's browser", severity: 'warning' })
|
||||
}
|
||||
if (/\bdebug\s*:\s*true/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'debug: process.env.NODE_ENV !== "production"', message: 'debug: true: Payload answers errors with their stack traces', severity: 'warning' })
|
||||
}
|
||||
if (/disablePlaygroundInProduction\s*:\s*false|disableIntrospectionInProduction\s*:\s*false/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'leave the GraphQL defaults on', message: 'the GraphQL playground or introspection is switched on in production: the whole schema is public', severity: 'warning' })
|
||||
}
|
||||
if (/maxDepth\s*:\s*(?:[2-9]\d|\d{3,})/.test(c)) {
|
||||
out.push({ file: payload.file, fix: 'maxDepth: 10 or less', message: 'maxDepth above 20: one request can populate a very deep tree (memory, time)', severity: 'warning' })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const RULE_TEXT: Record<CodePatternId, string> = {
|
||||
'code-eval': 'Code built from strings',
|
||||
'code-inner-html': 'HTML or JSON printed without escaping (XSS)',
|
||||
'code-local-api-user': 'Local API given a user without overrideAccess: false',
|
||||
'code-open-redirect': 'Redirect to an address from the request',
|
||||
'code-override-access': 'overrideAccess: true where a request reaches', // iapl-security-ok: the rule's own title
|
||||
'code-public-secret': 'A secret that can reach the browser',
|
||||
'code-raw-where': 'A query (where) taken from the request',
|
||||
'code-shell': 'A shell command built from a string',
|
||||
'code-ssrf': 'A server-side fetch of an address the request chose',
|
||||
}
|
||||
|
||||
/** Every hit of a project, grouped as doctor findings (one per rule and file). */
|
||||
export function codeFindings(ctx: Pick<DoctorContext, 'read' | 'root' | 'src'>): RuleFinding[] {
|
||||
const start = ctx.src ? ctx.src.replace(/\/$/, '') : '.'
|
||||
const files = listCodeFiles(ctx.root, start).filter((f) => ctx.src || /^(?:app|lib|components|blocks|collections|globals|hooks|endpoints|utilities|access|fields|plugins)\//.test(f) || /^(?:payload\.config|proxy|middleware)\.[cm]?[jt]s$/.test(f))
|
||||
const byKey = new Map<string, CodeHit[]>()
|
||||
for (const file of files) {
|
||||
for (const hit of scanCode(file, ctx.read(file))) {
|
||||
const key = `${hit.rule}\u0000${hit.file}`
|
||||
byKey.set(key, [...(byKey.get(key) ?? []), hit])
|
||||
}
|
||||
}
|
||||
return [...byKey.values()].map((hits) => ({
|
||||
file: hits[0].file,
|
||||
fix: `${RULE_TEXT[hits[0].rule]} — fix it, or mark a correct place with // ${SECURITY_OK_MARKER}: <why> (security.md → Security suites)`,
|
||||
message: `${hits[0].message}: ${hits.slice(0, 3).map((h) => `${h.file}:${h.line}`).join(', ')}${hits.length > 3 ? ` … +${hits.length - 3}` : ''}`,
|
||||
rule: hits[0].rule,
|
||||
severity: hits.some((h) => h.severity === 'error') ? 'error' : hits[0].severity,
|
||||
}))
|
||||
}
|
||||
|
||||
export const securityCodeRules: DoctorRule[] = [
|
||||
{
|
||||
id: 'code-patterns',
|
||||
check: (ctx) => codeFindings(ctx),
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
id: 'config-dangerous',
|
||||
check: (ctx) => {
|
||||
const n = nextConfigFile(ctx)
|
||||
const p = configFile(ctx)
|
||||
return scanConfigs(n ? { code: ctx.read(n), file: n } : null, p ? { code: ctx.read(p), file: p } : null)
|
||||
},
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// The HTTP attack probes safe on a live site (security/attackProbes.ts): `iapl-doctor --url https://site --only live-probes`
|
||||
id: 'live-probes',
|
||||
check: async (ctx) => {
|
||||
if (!ctx.live) {return []}
|
||||
const severe = new Set(['bundle-secrets', 'graphql', 'login-operators', 'middleware-subrequest', 'rest-where', 'secret-files'])
|
||||
const results = await runAttackProbes(createProbeContext(ctx.live.url))
|
||||
return results.filter(({ result }) => !result.ok).map(({ probe, result }) => ({
|
||||
fix: `${probe.title}${probe.finding ? ` (a known IAPL issue, ${probe.finding} of the 2026-12 audit: see the changelog)` : ''} — security.md → Security suites`,
|
||||
message: `${probe.class}: ${result.detail}`,
|
||||
rule: `live-probes:${probe.id}`,
|
||||
severity: severe.has(probe.id) ? 'error' : 'warning',
|
||||
}))
|
||||
},
|
||||
docs: 'docs/security.md',
|
||||
group: 'security',
|
||||
source: 'live',
|
||||
},
|
||||
]
|
||||
|
||||
/** Probe ids, for `--skip live-probes:<id>` style settings in iapl-doctor.json. */
|
||||
export const LIVE_PROBE_IDS = ATTACK_PROBES.filter((p) => p.live).map((p) => p.id)
|
||||
@@ -17,6 +17,7 @@ import { createLiveFetcher, liveRules } from './rules/live.js'
|
||||
import { mailRules } from './rules/mail.js'
|
||||
import { performanceRules } from './rules/performance.js'
|
||||
import { securityRules } from './rules/security.js'
|
||||
import { securityCodeRules } from './rules/securityCode.js'
|
||||
import { seedRules } from './rules/seeds.js'
|
||||
import { toolingRules } from './rules/tooling.js'
|
||||
import { versionRules } from './rules/versions.js'
|
||||
@@ -37,6 +38,7 @@ export const doctorRules: DoctorRule[] = [
|
||||
...layoutRules,
|
||||
...envRules,
|
||||
...securityRules,
|
||||
...securityCodeRules,
|
||||
...consentRules,
|
||||
...mailRules,
|
||||
...agentRules,
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
/**
|
||||
* HTTP attack probes (security audit 2026-12): the requests attackers send to Payload / Next.js sites, each with the
|
||||
* answer a safe site gives. One list, two users:
|
||||
* - `iapl-doctor --url https://site --only live-probes` runs the probes marked `live` against a project's own site:
|
||||
* GET requests, plus requests that change nothing (a refused sign-in with operators in it);
|
||||
* - the plugin's reference site runs every probe on a production build in both bundlers
|
||||
* (reference/e2e/attack-probes.spec.ts, part of `pnpm e2e:built`); a project copies
|
||||
* `.agents/skills/iapl-audit/resources/attack-probes.spec.template.ts`.
|
||||
* Exported (`@intecion/ipal-kit/doctor`) so a project adds its own probes or runs a subset in its CI.
|
||||
*
|
||||
* A probe answers on STATUS CODES and headers first: a 500 page is never counted as "closed" (a test that passes on
|
||||
* an error page proves nothing).
|
||||
*/
|
||||
|
||||
export type ProbeAnswer = { error?: string; headers: Headers; ms: number; status: number; text: string }
|
||||
|
||||
export type ProbeContext = {
|
||||
/** Site origin, no trailing slash. */
|
||||
base: string
|
||||
/** One request; never follows redirects unless asked. */
|
||||
fetch: (path: string, init?: { body?: string; follow?: boolean; headers?: Record<string, string>; method?: string }) => Promise<ProbeAnswer>
|
||||
/** A public page path of the site (default `/`), e.g. `/pl`. */
|
||||
page?: string
|
||||
/** Values that must never appear in a public file (the test knows the real secrets; a live run passes none). */
|
||||
secrets?: string[]
|
||||
}
|
||||
|
||||
export type ProbeResult = { detail: string; ok: boolean; skipped?: string }
|
||||
|
||||
export type AttackProbe = {
|
||||
/** The vulnerability class (security.md → "Threat list"). */
|
||||
class: string
|
||||
/** A finding of the audit that is not fixed yet (security-audit-2026-12-findings.md): expected to fail until it is. */
|
||||
finding?: string
|
||||
id: string
|
||||
/** Safe on a live site: reads only, or a request the site refuses without writing. */
|
||||
live: boolean
|
||||
run: (ctx: ProbeContext) => Promise<ProbeResult>
|
||||
title: string
|
||||
}
|
||||
|
||||
const ok = (detail = ''): ProbeResult => ({ detail, ok: true })
|
||||
const bad = (detail: string): ProbeResult => ({ detail, ok: false })
|
||||
const skip = (why: string): ProbeResult => ({ detail: '', ok: true, skipped: why })
|
||||
|
||||
/** A stack trace or a server path in an answer. */
|
||||
const LEAK = /\n\s+at [\w$.<>]+ \(|\bat (?:async )?[\w$.]+ \((?:\/|[A-Z]:\\|file:)|\/node_modules\/|webpack-internal:|\/\.next\/server\//
|
||||
/** What a secret looks like, without knowing it. */
|
||||
const SECRET_SHAPES: Array<[string, RegExp]> = [
|
||||
['a private key', /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/],
|
||||
['a database URL with a password', /\b(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql):\/\/[^\s"'`:@/]+:[^\s"'`@/]+@/],
|
||||
['a live Stripe key', /\bsk_live_[0-9a-zA-Z]{10,}/],
|
||||
['an AWS secret', /\baws_secret_access_key\b|\bAKIA[0-9A-Z]{16}\b/],
|
||||
['a variable assignment of a server secret', /\b(?:PAYLOAD_SECRET|DATABASE_URI|R2_SECRET_ACCESS_KEY|TURNSTILE_SECRET_KEY|CRON_SECRET|SMTP_PASS(?:WORD)?)\s*[=:]\s*["'`][^"'`]{8,}/],
|
||||
]
|
||||
const EVIL = 'evil.example'
|
||||
const sameHost = (location: null | string, base: string) => {
|
||||
if (!location) {return true}
|
||||
try {
|
||||
return new URL(location, base).host === new URL(base).host
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
const describe = (a: ProbeAnswer) => (a.error ? `no answer (${a.error})` : `${a.status}`)
|
||||
const scriptSrcs = (html: string) => [...html.matchAll(/<script[^>]+src="([^"]+)"/g)].map((m) => m[1].replace(/&/g, '&'))
|
||||
|
||||
export const ATTACK_PROBES: AttackProbe[] = [
|
||||
{
|
||||
id: 'secret-files',
|
||||
class: 'secrets in public files',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const paths = ['/.env', '/.env.local', '/.env.production', '/.git/config', '/.git/HEAD', '/package.json', '/pnpm-lock.yaml', '/next.config.ts', '/payload.config.ts', '/src/payload.config.ts', '/Dockerfile', '/docker-compose.yml', '/.DS_Store', '/api/media/file/..%2F..%2F.env', '/api/media/file/%2e%2e%2f%2e%2e%2fpackage.json', '/_next/static/..%2F..%2F.env', '/_next/../package.json']
|
||||
const open: string[] = []
|
||||
for (const path of paths) {
|
||||
const a = await fetch(path)
|
||||
if (a.status === 200 && /PAYLOAD_SECRET|DATABASE_URI|"dependencies"\s*:|\[core\]|^ref: refs\/|lockfileVersion|FROM node|buildConfig\(/m.test(a.text)) {open.push(path)}
|
||||
if (a.status >= 500) {open.push(`${path} → ${a.status}`)}
|
||||
}
|
||||
return open.length ? bad(`served: ${open.join(', ')}`) : ok(`${paths.length} paths refused`)
|
||||
},
|
||||
title: 'source, env and git files are not served (also through ../ in a file route)',
|
||||
},
|
||||
{
|
||||
id: 'bundle-secrets',
|
||||
class: 'secrets in client bundles',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/', secrets = [] }) => {
|
||||
const pages = [page, '/admin/login']
|
||||
const files = new Set<string>()
|
||||
for (const p of pages) {
|
||||
const a = await fetch(p, { follow: true })
|
||||
for (const src of scriptSrcs(a.text)) {if (src.startsWith('/') && !src.startsWith('//')) {files.add(src)}}
|
||||
}
|
||||
if (!files.size) {return skip('no script files found on the pages')}
|
||||
const found: string[] = []
|
||||
let maps = 0
|
||||
for (const file of files) {
|
||||
const a = await fetch(file)
|
||||
for (const [what, re] of SECRET_SHAPES) {if (re.test(a.text)) {found.push(`${file}: ${what}`)}}
|
||||
for (const s of secrets) {if (s && s.length >= 8 && a.text.includes(s)) {found.push(`${file}: a server secret's value`)}}
|
||||
if (maps < 3 && /\/_next\/static\/.+\.js$/.test(file)) {
|
||||
maps++
|
||||
const map = await fetch(`${file.split('?')[0]}.map`)
|
||||
if (map.status === 200 && /"sources"\s*:/.test(map.text)) {found.push(`${file}.map: source map is public (productionBrowserSourceMaps)`)}
|
||||
}
|
||||
}
|
||||
return found.length ? bad(found.join('; ')) : ok(`${files.size} script files clean`)
|
||||
},
|
||||
title: 'no secret (or a secret-shaped value) in the JavaScript the pages load; no public source maps',
|
||||
},
|
||||
{
|
||||
id: 'middleware-subrequest',
|
||||
class: 'middleware / proxy bypass',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const plain = await fetch('/')
|
||||
if (plain.status < 300 || plain.status >= 400) {return skip(`/ answers ${describe(plain)} without the proxy redirecting (single locale?): nothing to compare`)}
|
||||
const values = ['middleware:middleware:middleware:middleware:middleware', 'src/middleware:src/middleware:src/middleware:src/middleware:src/middleware', 'proxy:proxy:proxy:proxy:proxy', 'src/proxy:src/proxy:src/proxy:src/proxy:src/proxy', 'pages/_middleware']
|
||||
for (const v of values) {
|
||||
const a = await fetch('/', { headers: { 'x-middleware-subrequest': v } })
|
||||
if (a.status !== plain.status) {return bad(`x-middleware-subrequest: ${v} changed / from ${plain.status} to ${describe(a)}: the proxy was skipped (CVE-2025-29927 class — upgrade Next)`)}
|
||||
}
|
||||
return ok(`the proxy ran for all ${values.length} header values`)
|
||||
},
|
||||
title: 'x-middleware-subrequest does not skip the proxy (CVE-2025-29927 class)',
|
||||
},
|
||||
{
|
||||
id: 'open-redirect',
|
||||
class: 'open redirect',
|
||||
live: true,
|
||||
run: async ({ base, fetch }) => {
|
||||
const paths = [`//${EVIL}/`, `/%2F%2F${EVIL}`, `/\\${EVIL}`, `/%5C${EVIL}`, `/%09/${EVIL}`, `/admin/login?redirect=https://${EVIL}/`, `/admin?redirect=//${EVIL}`, `/api/ipal/admin-language?lng=en`]
|
||||
const away: string[] = []
|
||||
for (const path of paths) {
|
||||
const a = await fetch(path, { headers: path.includes('admin-language') ? { referer: `https://${EVIL}/admin` } : {} })
|
||||
const location = a.headers.get('location')
|
||||
if (a.status >= 300 && a.status < 400 && !sameHost(location, base)) {away.push(`${path} → ${location}`)}
|
||||
if (a.status >= 500) {away.push(`${path} → ${a.status}`)}
|
||||
}
|
||||
return away.length ? bad(away.join('; ')) : ok(`${paths.length} paths stay on the site`)
|
||||
},
|
||||
title: 'no path, parameter or Referer sends the browser to another host',
|
||||
},
|
||||
{
|
||||
id: 'host-header',
|
||||
class: 'cache poisoning (host headers)',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const headers = { forwarded: `host=${EVIL}`, 'x-forwarded-host': EVIL, 'x-host': EVIL, 'x-original-host': EVIL }
|
||||
const redirect = await fetch('/', { headers })
|
||||
const location = redirect.headers.get('location') ?? ''
|
||||
if (location.includes(EVIL)) {return bad(`/ redirects to ${location}: the redirect trusts X-Forwarded-Host`)}
|
||||
const html = await fetch(page, { follow: true, headers })
|
||||
if (html.text.includes(EVIL)) {return bad(`${page} prints ${EVIL} (canonical, og:url, hreflang or a link): a cached page would carry it for everyone`)}
|
||||
return ok('neither the redirect nor the page uses a host the request named')
|
||||
},
|
||||
title: 'X-Forwarded-Host / Forwarded do not reach redirects or links in the page',
|
||||
},
|
||||
{
|
||||
id: 'markdown-vary',
|
||||
class: 'cache poisoning (content negotiation)',
|
||||
finding: 'F3',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const a = await fetch(page, { follow: true, headers: { accept: 'text/markdown' } })
|
||||
if (!/text\/markdown/.test(a.headers.get('content-type') ?? '')) {return skip(`${page} with Accept: text/markdown answers ${a.headers.get('content-type') ?? describe(a)} (no Markdown negotiation)`)}
|
||||
const cc = a.headers.get('cache-control') ?? ''
|
||||
const shared = /s-maxage|public/.test(cc) && !/private|no-store/.test(cc)
|
||||
const vary = (a.headers.get('vary') ?? '').split(',').map((v) => v.trim().toLowerCase())
|
||||
if (shared && !vary.includes('accept') && !vary.includes('*')) {return bad(`${page} answers Markdown to Accept: text/markdown with "${cc}" and no Vary: Accept: a shared cache stores it under the HTML URL`)}
|
||||
return ok('the Markdown answer at the HTML URL varies by Accept or is not shared')
|
||||
},
|
||||
title: 'the Markdown copy at an HTML URL cannot be cached as the page',
|
||||
},
|
||||
{
|
||||
id: 'rsc-vary',
|
||||
class: 'cache poisoning (RSC)',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const a = await fetch(page, { follow: true, headers: { rsc: '1' } })
|
||||
if (!/text\/x-component/.test(a.headers.get('content-type') ?? '')) {return skip(`${page} with RSC: 1 is not a flight answer`)}
|
||||
return /\brsc\b/i.test(a.headers.get('vary') ?? '') ? ok() : bad(`the flight answer of ${page} has no Vary: RSC (vary: ${a.headers.get('vary') ?? 'none'})`)
|
||||
},
|
||||
title: 'the RSC (flight) answer of a page varies by the RSC header',
|
||||
},
|
||||
{
|
||||
id: 'login-operators',
|
||||
class: 'injection (NoSQL operators)',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const bodies = [{ email: { $ne: null }, password: { $ne: null } }, { email: { $gt: '' }, password: 'x' }, { email: '[email protected]', password: { $ne: 'x' } }]
|
||||
for (const body of bodies) {
|
||||
const a = await fetch('/api/users/login', { body: JSON.stringify(body), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
if (a.status === 200 || /"token"\s*:\s*"/.test(a.text)) {return bad(`login with ${JSON.stringify(body)} answered ${a.status} with a token`)}
|
||||
if (a.status >= 500) {return bad(`login with ${JSON.stringify(body)} answered ${a.status}`)}
|
||||
if (LEAK.test(a.text)) {return bad('the refused login answer carries a stack trace or a server path')}
|
||||
}
|
||||
return ok('operators in the e-mail or password are refused')
|
||||
},
|
||||
title: 'a sign-in with $ne / $gt in it is refused (no account, no 500)',
|
||||
},
|
||||
{
|
||||
id: 'rest-where',
|
||||
class: 'access control (REST where / drafts)',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const problems: string[] = []
|
||||
for (const path of ['/api/users?where[email][exists]=true&limit=1', '/api/users?where[password][exists]=true&limit=1', '/api/users?where[or][0][roles][equals]=admin&limit=1', '/api/form-submissions?limit=1', '/api/payload-preferences?limit=1', '/api/payload-kv?limit=1']) {
|
||||
const a = await fetch(path)
|
||||
if (a.status === 404) {continue}
|
||||
if (a.status >= 500) {problems.push(`${path} → ${a.status}`); continue}
|
||||
if (a.status === 200 && /"docs"\s*:\s*\[\s*\{/.test(a.text)) {problems.push(`${path} → 200 with documents`)}
|
||||
}
|
||||
const drafts = await fetch('/api/pages?draft=true&where[_status][equals]=draft&limit=5&depth=0')
|
||||
if (drafts.status === 200 && /"_status"\s*:\s*"draft"/.test(drafts.text)) {problems.push('/api/pages?draft=true returns drafts to an anonymous visitor')}
|
||||
if (drafts.status >= 500) {problems.push(`/api/pages?draft=true… → ${drafts.status}`)}
|
||||
const versions = await fetch('/api/pages/versions?limit=1&depth=0')
|
||||
if (versions.status === 200 && /"docs"\s*:\s*\[\s*\{/.test(versions.text)) {problems.push('/api/pages/versions lists versions to an anonymous visitor')}
|
||||
return problems.length ? bad(problems.join('; ')) : ok('accounts, submissions, preferences, drafts and versions stay closed to a where query')
|
||||
},
|
||||
title: 'an anonymous where / draft / versions query reads no accounts, submissions or drafts',
|
||||
},
|
||||
{
|
||||
id: 'graphql',
|
||||
class: 'access control (GraphQL)',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const post = (query: string) => fetch('/api/graphql', { body: JSON.stringify({ query }), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
const intro = await post('{ __schema { types { name } } }')
|
||||
if (intro.status === 404) {return skip('no GraphQL route')}
|
||||
if (intro.status === 200 && /"__schema"\s*:\s*\{/.test(intro.text)) {return bad('introspection answers in production: the whole schema is public')}
|
||||
const syntax = await post('{ Pages(where: { ')
|
||||
if (syntax.status >= 500 || LEAK.test(syntax.text)) {return bad(`a broken query answers ${syntax.status}${LEAK.test(syntax.text) ? ' with a stack trace' : ''}`)}
|
||||
const get = await fetch(`/api/graphql?query=${encodeURIComponent('mutation { __typename }')}`)
|
||||
if (get.status === 200 && /"data"\s*:\s*\{\s*"__typename"/.test(get.text)) {return bad('a mutation runs over GET (CSRF: a link or <img> can run it with the visitor\'s cookie)')}
|
||||
const users = await post('{ Users(limit: 1) { docs { email } } }')
|
||||
if (users.status === 200 && /"email"\s*:\s*"/.test(users.text)) {return bad('an anonymous GraphQL query lists account e-mails')}
|
||||
return ok('no introspection, no stack traces, no mutation over GET, no accounts')
|
||||
},
|
||||
title: 'GraphQL: no introspection in production, no mutation over GET, no accounts, no stack traces',
|
||||
},
|
||||
{
|
||||
id: 'error-leak',
|
||||
class: 'information disclosure (errors)',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const paths = ['/api/pages/%27%22%3C%3E', '/api/pages?where[id][equals]=not-an-id', '/api/pages?depth=abc&limit=-1', '/api/pages?where[title][like][$regex]=.*', '/api/users/me', '/api/globals/does-not-exist', '/does-not-exist-%00']
|
||||
const problems: string[] = []
|
||||
for (const path of paths) {
|
||||
const a = await fetch(path)
|
||||
if (a.status >= 500) {problems.push(`${path} → ${a.status}`)}
|
||||
if (LEAK.test(a.text)) {problems.push(`${path}: stack trace or server path in the answer`)}
|
||||
}
|
||||
return problems.length ? bad(problems.join('; ')) : ok(`${paths.length} malformed requests answered without a 500 or a stack trace`)
|
||||
},
|
||||
title: 'malformed ids, sorts, depths and operators give a 4xx without a stack trace',
|
||||
},
|
||||
{
|
||||
id: 'sort-operator',
|
||||
class: 'injection (operators in sort)',
|
||||
finding: 'F5',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const problems: string[] = []
|
||||
for (const sort of ['%24where', '-%24where', '%24natural', 'title.%24ne']) {
|
||||
const a = await fetch(`/api/pages?sort=${sort}&limit=1&depth=0`)
|
||||
if (a.status >= 500 || LEAK.test(a.text)) {problems.push(`sort=${decodeURIComponent(sort)} → ${a.status}`)}
|
||||
}
|
||||
return problems.length ? bad(`${problems.join('; ')}: an operator name reaches the database as a sort field (an error and a logged stack trace per request)`) : ok('operator names in sort are refused with a 4xx')
|
||||
},
|
||||
title: 'an operator name in ?sort= is refused, not passed to the database',
|
||||
},
|
||||
{
|
||||
id: 'unbounded-list',
|
||||
class: 'denial of service (unbounded queries)',
|
||||
finding: 'F4',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const a = await fetch('/api/pages?limit=100000&depth=50')
|
||||
if (a.status !== 200) {return skip(`/api/pages answers ${describe(a)}`)}
|
||||
let body: { limit?: number } = {}
|
||||
try {
|
||||
body = JSON.parse(a.text) as typeof body
|
||||
} catch {
|
||||
return skip('not JSON')
|
||||
}
|
||||
return (body.limit ?? 0) > 1000 ? bad(`/api/pages?limit=100000 is honoured (limit ${body.limit}, ${a.ms} ms, ${a.text.length} bytes): one anonymous request reads a whole collection`) : ok(`limit capped at ${body.limit}`)
|
||||
},
|
||||
title: 'a public list caps limit (and depth) so one request cannot read a whole collection',
|
||||
},
|
||||
{
|
||||
id: 'image-optimizer',
|
||||
class: 'SSRF / image optimizer',
|
||||
live: true,
|
||||
run: async ({ fetch }) => {
|
||||
const problems: string[] = []
|
||||
for (const url of ['http://169.254.169.254/latest/meta-data/', 'http://127.0.0.1:22/', `https://${EVIL}/x.png`, '//evil.example/x.png', '/api/media/file/x.svg']) {
|
||||
const a = await fetch(`/_next/image?url=${encodeURIComponent(url)}&w=64&q=75`)
|
||||
if (a.status === 200 && !/^image\/(?:png|jpe?g|webp|avif|gif)/.test(a.headers.get('content-type') ?? '')) {problems.push(`${url} → 200 ${a.headers.get('content-type')}`)}
|
||||
if (a.status === 200 && /169\.254|127\.0\.0\.1|evil\.example/.test(url)) {problems.push(`${url} → 200: the optimizer fetched it`)}
|
||||
// a missing local file is a 500 from Next's optimizer (it reports the upstream 404 so): not a door
|
||||
if (a.status >= 500 && !url.startsWith('/api/media/')) {problems.push(`${url} → ${a.status}`)}
|
||||
}
|
||||
return problems.length ? bad(problems.join('; ')) : ok('inner addresses, foreign hosts and SVG are refused')
|
||||
},
|
||||
title: '/_next/image refuses inner addresses, unlisted hosts and SVG',
|
||||
},
|
||||
{
|
||||
id: 'headers-everywhere',
|
||||
class: 'security headers',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const missing: string[] = []
|
||||
for (const path of [page, '/this-page-does-not-exist-iapl', '/api/health', '/api/pages?limit=1', '/admin/login']) {
|
||||
const a = await fetch(path, { follow: true })
|
||||
if (!a.status) {continue}
|
||||
const h = a.headers
|
||||
const lacks = [
|
||||
...(/nosniff/i.test(h.get('x-content-type-options') ?? '') ? [] : ['nosniff']),
|
||||
...(h.get('x-frame-options') || /frame-ancestors/.test(h.get('content-security-policy') ?? '') ? [] : ['frame protection']),
|
||||
...(h.get('x-powered-by') ? [`X-Powered-By: ${h.get('x-powered-by')}`] : []),
|
||||
]
|
||||
if (lacks.length) {missing.push(`${path}: ${lacks.join(', ')}`)}
|
||||
}
|
||||
return missing.length ? bad(missing.join('; ')) : ok()
|
||||
},
|
||||
title: 'pages, the 404 page, the API and the admin all carry nosniff and frame protection, no X-Powered-By',
|
||||
},
|
||||
{
|
||||
id: 'methods',
|
||||
class: 'unexpected methods',
|
||||
live: true,
|
||||
run: async ({ fetch, page = '/' }) => {
|
||||
const problems: string[] = []
|
||||
for (const method of ['TRACE', 'PUT', 'DELETE', 'PATCH']) {
|
||||
const a = await fetch(page, { method })
|
||||
if (a.status >= 500) {problems.push(`${method} ${page} → ${a.status}`)}
|
||||
if (method === 'TRACE' && a.status === 200 && /TRACE \//.test(a.text)) {problems.push('TRACE echoes the request')}
|
||||
}
|
||||
const action = await fetch(page, { body: '[]', headers: { 'content-type': 'text/plain;charset=UTF-8', 'next-action': '0'.repeat(42) }, method: 'POST' })
|
||||
if (action.status >= 500 || LEAK.test(action.text)) {problems.push(`an unknown Server Action id → ${action.status}`)}
|
||||
return problems.length ? bad(problems.join('; ')) : ok()
|
||||
},
|
||||
title: 'TRACE / PUT / DELETE on a page and an unknown Server Action id give no 500',
|
||||
},
|
||||
{
|
||||
id: 'body-size',
|
||||
class: 'denial of service (body size)',
|
||||
live: false,
|
||||
run: async ({ fetch }) => {
|
||||
const problems: string[] = []
|
||||
const big = JSON.stringify({ email: '[email protected]', pad: 'x'.repeat(8 * 1024 * 1024), password: 'x' })
|
||||
for (const path of ['/api/ipal/consent', '/api/csp-report', '/api/mcp', '/api/users/login', '/api/graphql']) {
|
||||
const a = await fetch(path, { body: big, headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
if (a.status === 404 || a.status === 405) {continue}
|
||||
if (a.status >= 500 || a.status === 0) {problems.push(`${path} → ${describe(a)} after ${a.ms} ms`)}
|
||||
else if (a.ms > 5000) {problems.push(`${path} took ${a.ms} ms for an 8 MB body`)}
|
||||
}
|
||||
return problems.length ? bad(problems.join('; ')) : ok('8 MB bodies refused or answered quickly')
|
||||
},
|
||||
title: 'an 8 MB body to the public POST routes is refused quickly, never a 500',
|
||||
},
|
||||
]
|
||||
|
||||
/** Plain-fetch context for a site. */
|
||||
export function createProbeContext(base: string, options: { page?: string; secrets?: string[]; timeoutMs?: number; userAgent?: string } = {}): ProbeContext {
|
||||
const origin = base.replace(/\/+$/, '')
|
||||
return {
|
||||
base: origin,
|
||||
fetch: async (path, init = {}) => {
|
||||
const started = Date.now()
|
||||
try {
|
||||
const res = await fetch(origin + path, {
|
||||
body: init.body,
|
||||
headers: { 'user-agent': options.userAgent ?? 'iapl-doctor probes (read-only)', ...init.headers },
|
||||
method: init.method ?? 'GET',
|
||||
redirect: init.follow ? 'follow' : 'manual',
|
||||
signal: AbortSignal.timeout(options.timeoutMs ?? 20_000),
|
||||
})
|
||||
const text = init.method === 'HEAD' ? '' : await res.text()
|
||||
return { headers: res.headers, ms: Date.now() - started, status: res.status, text }
|
||||
} catch (err) {
|
||||
const e = err as { cause?: { code?: string }; message?: string }
|
||||
return { error: e.cause?.code ?? e.message ?? 'unreachable', headers: new Headers(), ms: Date.now() - started, status: 0, text: '' }
|
||||
}
|
||||
},
|
||||
page: options.page,
|
||||
secrets: options.secrets,
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the probes (default: those safe on a live site) and returns each result. */
|
||||
export async function runAttackProbes(ctx: ProbeContext, probes: AttackProbe[] = ATTACK_PROBES.filter((p) => p.live)): Promise<Array<{ probe: AttackProbe; result: ProbeResult }>> {
|
||||
const out: Array<{ probe: AttackProbe; result: ProbeResult }> = []
|
||||
for (const probe of probes) {
|
||||
let result: ProbeResult
|
||||
try {
|
||||
result = await probe.run(ctx)
|
||||
} catch (err) {
|
||||
result = bad(`probe crashed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
out.push({ probe, result })
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user