routeguard-cli 0.0.0-stage → 1.1.0
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/LICENSE +21 -0
- package/README.md +164 -2
- package/bin/cli.js +116 -0
- package/package.json +45 -4
- package/src/flow.js +217 -0
- package/src/mapper.js +714 -0
- package/src/rules/bfla.js +51 -0
- package/src/rules/bola.js +69 -0
- package/src/rules/businessFlow.js +50 -0
- package/src/rules/consumption.js +164 -0
- package/src/rules/dataExposure.js +107 -0
- package/src/rules/handler.js +159 -0
- package/src/rules/inventory.js +84 -0
- package/src/rules/massAssignment.js +99 -0
- package/src/rules/misconfig.js +205 -0
- package/src/rules/rateLimit.js +53 -0
- package/src/rules/ssrf.js +57 -0
- package/src/sarif.js +45 -0
- package/src/spec.js +43 -0
- package/src/verify.js +142 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { DB_CALL, DB_WRITE, checksBodyCredential, dbCalls, hasRole, readsIdentity, whereOf } from "./handler.js"
|
|
2
|
+
|
|
3
|
+
// res.sendFile(adminIndex): the admin page itself is public, its actions need the check
|
|
4
|
+
const PAGE_ONLY = /^(sendFile|render|redirect|download|readFile|createReadStream)$/
|
|
5
|
+
|
|
6
|
+
// path segments that name operator-only functions
|
|
7
|
+
const SENSITIVE = /(^|\/)(admin|internal|manage|system|config|debug|metrics|logs?|secrets?|backup)(\/|$)/i
|
|
8
|
+
|
|
9
|
+
// an API key or basic auth is usually issued to operators only; a user login is not
|
|
10
|
+
function sensitiveSeverity(route) {
|
|
11
|
+
// the handler looks at the caller itself (empty answer for anonymous users), so the gap is narrower
|
|
12
|
+
if (route.fn && readsIdentity(route.fn)) return "LOW"
|
|
13
|
+
if (route.middleware.some(m => /api.?(key|auth)|basic/i.test(m))) return "LOW"
|
|
14
|
+
if (route.fn && dbCalls(route.fn, DB_CALL).length === 0 && dbCalls(route.fn, PAGE_ONLY).length > 0) return "LOW"
|
|
15
|
+
return "HIGH"
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// API5: a function meant for privileged users is reachable by anyone signed in, or by anyone
|
|
19
|
+
export function bfla(route) {
|
|
20
|
+
if (hasRole(route)) return null
|
|
21
|
+
|
|
22
|
+
const sensitive = route.path.match(SENSITIVE)
|
|
23
|
+
if (sensitive) {
|
|
24
|
+
return {
|
|
25
|
+
rule: "BFLA",
|
|
26
|
+
owasp: "API5:2023 Broken Function Level Authorization",
|
|
27
|
+
severity: sensitiveSeverity(route),
|
|
28
|
+
route: `${route.method} ${route.path}`,
|
|
29
|
+
where: `${route.file}:${route.line}`,
|
|
30
|
+
message: `"${sensitive[2]}" names an operator function, but the route has ${route.auth ? "no role check" : "no auth or role check"}.`,
|
|
31
|
+
fix: "Add a role check, e.g. router.get(path, [auth, admin], handler), or remove the route from production."
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// a signed-in user creates a record that is not tied to them, so it is shared data,
|
|
36
|
+
// and changing shared data is usually an admin's job (catalogue items, settings)
|
|
37
|
+
// routes with an id in the path are covered by the BOLA rule
|
|
38
|
+
if (!route.auth || route.method === "GET" || /[:{]/.test(route.path) || !route.fn) return null
|
|
39
|
+
const writes = dbCalls(route.fn, DB_WRITE)
|
|
40
|
+
if (writes.length === 0 || readsIdentity(route.fn) || checksBodyCredential(route.fn)) return null
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
rule: "BFLA",
|
|
44
|
+
owasp: "API5:2023 Broken Function Level Authorization",
|
|
45
|
+
severity: "MEDIUM",
|
|
46
|
+
route: `${route.method} ${route.path}`,
|
|
47
|
+
where: whereOf(route, writes[0].line),
|
|
48
|
+
message: `Any signed-in user can ${writes.map(w => w.method).join(", ")} here, and the new record is not tied to them, so this looks like shared data with no role check.`,
|
|
49
|
+
fix: "Add a role check such as [auth, admin], or store the caller as owner (owner: req.user._id) if users should own these records."
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { walk, isMemberNode } from "../mapper.js"
|
|
3
|
+
import { traceRoute } from "../flow.js"
|
|
4
|
+
import { RECORD_ACCESS, checksBodyCredential, dbCalls, handlerParams, hasRole, isMember, whereOf } from "./handler.js"
|
|
5
|
+
|
|
6
|
+
const SECRET_PARAM = /token|code|hash|secret|otp|nonce|signature|key|session/i
|
|
7
|
+
|
|
8
|
+
// names that carry a value from req.params: const id = req.params.id, const { id } = req.params
|
|
9
|
+
function paramDerivedNames(fn, req) {
|
|
10
|
+
const names = new Set()
|
|
11
|
+
walk(fn.body, node => {
|
|
12
|
+
if (node.type !== "VariableDeclarator" || !node.init) return
|
|
13
|
+
const fromParams =
|
|
14
|
+
isMember(node.init, req, "params") ||
|
|
15
|
+
(isMemberNode(node.init) && isMember(node.init.object, req, "params"))
|
|
16
|
+
if (!fromParams) return
|
|
17
|
+
if (node.id.type === "Identifier") names.add(node.id.name)
|
|
18
|
+
if (node.id.type === "ObjectPattern")
|
|
19
|
+
node.id.properties.forEach(p => p.value?.type === "Identifier" && names.add(p.value.name))
|
|
20
|
+
})
|
|
21
|
+
return names
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function usesParam(node, req, derived) {
|
|
25
|
+
let found = false
|
|
26
|
+
walk(node, n => {
|
|
27
|
+
if (isMemberNode(n) && isMember(n.object, req, "params")) found = true
|
|
28
|
+
if (n.type === "Identifier" && derived.has(n.name)) found = true
|
|
29
|
+
})
|
|
30
|
+
return found
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// API1: a record is fetched or changed by a client-supplied id, and the handler never
|
|
34
|
+
// compares it with the caller, so any signed-in user can reach anyone's record
|
|
35
|
+
export function bola(route) {
|
|
36
|
+
if (!/[:{]/.test(route.path) || !route.fn || hasRole(route)) return null
|
|
37
|
+
// an unauthenticated read is usually a public catalogue on purpose (books, products)
|
|
38
|
+
if (!route.auth && route.method === "GET") return null
|
|
39
|
+
// /reset/:token, /verify/:code: an unguessable secret in the URL is the authorisation
|
|
40
|
+
const params = route.path.match(/[:{](\w+)/g)?.map(p => p.slice(1)) ?? []
|
|
41
|
+
if (params.length && params.every(p => SECRET_PARAM.test(p))) return null
|
|
42
|
+
|
|
43
|
+
const { req } = handlerParams(route.fn)
|
|
44
|
+
const derived = paramDerivedNames(route.fn, req)
|
|
45
|
+
const calls = dbCalls(route.fn, RECORD_ACCESS).filter(c => c.node.arguments.some(a => usesParam(a, req, derived)))
|
|
46
|
+
if (checksBodyCredential(route.fn)) return null
|
|
47
|
+
|
|
48
|
+
// follow the id into the services it reaches; the caller must limit it somewhere on the way
|
|
49
|
+
const trace = traceRoute(route)
|
|
50
|
+
if (trace.scoped === true || (trace.scoped === null && trace.trusted)) return null
|
|
51
|
+
if (trace.scoped === null && calls.length === 0) return null
|
|
52
|
+
const at = trace.at
|
|
53
|
+
const via = at?.chain.length ? ` via ${at.chain.join(" → ")}` : ""
|
|
54
|
+
|
|
55
|
+
const write = ["PUT", "PATCH", "DELETE"].includes(route.method)
|
|
56
|
+
return {
|
|
57
|
+
rule: "BOLA",
|
|
58
|
+
owasp: !route.auth
|
|
59
|
+
? "API1/API2: no auth at all"
|
|
60
|
+
: write
|
|
61
|
+
? "API1:2023 BOLA, or API5:2023 BFLA if this is a shared record only admins should change"
|
|
62
|
+
: "API1:2023 Broken Object Level Authorization",
|
|
63
|
+
severity: !route.auth || write ? "HIGH" : "MEDIUM",
|
|
64
|
+
route: `${route.method} ${route.path}`,
|
|
65
|
+
where: at ? `${path.relative(route.root, at.file)}:${at.line}` : whereOf(route, calls[0].line),
|
|
66
|
+
message: `${at?.method ?? calls.map(c => c.method).join(", ")}${via} uses an id from the URL, and nothing on the way checks it against the caller.`,
|
|
67
|
+
fix: "If the record has an owner, scope the query to the caller: findOne({ _id: id, owner: req.user._id }). If it is shared, add a role check such as [auth, admin]."
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { walk, isCallNode } from "../mapper.js"
|
|
2
|
+
import { calleeName, hasRole } from "./handler.js"
|
|
3
|
+
|
|
4
|
+
// flows a bot profits from automating: buying out stock, farming referrals, mass reviews
|
|
5
|
+
// matched against whole path segments: "books" is a catalogue and "tokenTransfer" a session hand-off
|
|
6
|
+
const MONEY = /^(checkout|orders?|purchases?|buy|redeem|coupons?|vouchers?|promos?|promo-?codes?|referrals?|refer|withdraw\w*|payouts?|gift-?cards?|credits?|rewards?)$/i
|
|
7
|
+
const ABUSE = /^(book|bookings?|reserv\w*|seats?|tickets?|votes?|likes?|reviews?|comments?|invites?|invitations?)$/i
|
|
8
|
+
// anti-automation: a limiter, a captcha, a proof of work, a queue
|
|
9
|
+
// robots(…) serves robots.txt; bot only counts as botProtection, botGuard, botDetect
|
|
10
|
+
const GUARD = /limit|throttle|slow.?down|captcha|turnstile|bot.?(guard|protect|check|detect)|antiAutomation|proof.?of.?work|queue/i
|
|
11
|
+
const DEPTH = 2
|
|
12
|
+
|
|
13
|
+
function guardedInCode(route, fn, file, depth = 0, seen = new Set()) {
|
|
14
|
+
if (!fn || depth > DEPTH || seen.has(fn)) return false
|
|
15
|
+
seen.add(fn)
|
|
16
|
+
let found = false
|
|
17
|
+
walk(fn.body, n => {
|
|
18
|
+
if (found || !isCallNode(n)) return
|
|
19
|
+
if (GUARD.test(calleeName(n))) found = true
|
|
20
|
+
else {
|
|
21
|
+
const target = route.resolve?.(file, n.callee)
|
|
22
|
+
if (target && guardedInCode(route, target.fn, target.file, depth + 1, seen)) found = true
|
|
23
|
+
}
|
|
24
|
+
})
|
|
25
|
+
return found
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// API6: a business flow can be run by a script as fast as it likes
|
|
29
|
+
export function businessFlow(route) {
|
|
30
|
+
if (!["POST", "PUT", "PATCH"].includes(route.method)) return null
|
|
31
|
+
const segments = route.path.split("/").filter(s => s && !/^[:{]/.test(s))
|
|
32
|
+
// a transfer is money only next to money words: /wallet/transfer, not /labels/transfer
|
|
33
|
+
const moneyTransfer = segments.some(s => /^transfers?$/i.test(s)) && segments.some(s => /wallet|fund|balance|payment|account|money|credit/i.test(s))
|
|
34
|
+
const segment = (moneyTransfer && "transfer") || segments.find(s => MONEY.test(s)) || segments.find(s => ABUSE.test(s))
|
|
35
|
+
if (!segment || hasRole(route)) return null
|
|
36
|
+
// /invites/:token/accept: the token gates it, one use per token
|
|
37
|
+
if (/[:{]\w*(token|code|secret|hash)/i.test(route.path)) return null
|
|
38
|
+
if (route.middleware.some(m => GUARD.test(m)) || guardedInCode(route, route.fn, route.fnPath)) return null
|
|
39
|
+
|
|
40
|
+
const money = MONEY.test(segment)
|
|
41
|
+
return {
|
|
42
|
+
rule: "BUSINESS_FLOW",
|
|
43
|
+
owasp: "API6:2023 Unrestricted Access to Sensitive Business Flows",
|
|
44
|
+
severity: money ? "MEDIUM" : "LOW",
|
|
45
|
+
route: `${route.method} ${route.path}`,
|
|
46
|
+
where: `${route.file}:${route.line}`,
|
|
47
|
+
message: `"${segment}" is a ${money ? "money or stock" : "reputation or capacity"} flow with no limiter, captcha or other anti-automation, so a script can ${money ? "buy out, redeem or transfer at scale" : "flood it"}.`,
|
|
48
|
+
fix: "Limit per account and per device (express-rate-limit keyed on the user), add a captcha or a queue for the flow, and alert on bursts."
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { listSourceFiles, parseFile, walk, isCallNode, isMemberNode } from "../mapper.js"
|
|
3
|
+
import { DB_WRITE, calleeName, calleeObject } from "./handler.js"
|
|
4
|
+
|
|
5
|
+
const CLIENT_FN = new Set(["fetch", "axios", "got", "needle", "request", "superagent"])
|
|
6
|
+
const CLIENT_OBJ = new Set(["axios", "got", "needle", "request", "superagent", "http", "https", "undici", "ky"])
|
|
7
|
+
const CLIENT_METHOD = /^(get|post|put|patch|delete|head|request|stream)$/
|
|
8
|
+
// schema.parse(data), validate(data), Joi, zod, ajv: the response is checked before use
|
|
9
|
+
const VALIDATE = /validat|parse|safeParse|schema|assert|sanitiz|check|verify|decode|joi|zod|ajv|yup/i
|
|
10
|
+
const CODE_SINK = /^(eval|Function|runInContext|runInNewContext|runInThisContext|exec|execSync|spawn|spawnSync|execFile)$/
|
|
11
|
+
// a key in a literal URL: ?appid=2ee846af…, &api_key=…
|
|
12
|
+
const KEY_IN_URL = /[?&](app_?id|api_?key|key|token|access_token|secret|client_secret)=([A-Za-z0-9_\-]{16,})/i
|
|
13
|
+
const LOCAL = /^http:\/\/(localhost|127\.|0\.0\.0\.0|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[::1\]|[\w-]+:\d+\/?$|[\w-]+\/)/i
|
|
14
|
+
|
|
15
|
+
const isClientCall = n =>
|
|
16
|
+
isCallNode(n) && (CLIENT_FN.has(n.callee.name) || (CLIENT_OBJ.has(calleeObject(n)) && CLIENT_METHOD.test(calleeName(n))))
|
|
17
|
+
const isFunction = n => ["ArrowFunctionExpression", "FunctionExpression"].includes(n?.type)
|
|
18
|
+
const literalText = n =>
|
|
19
|
+
n?.type === "StringLiteral" ? n.value : n?.type === "TemplateLiteral" ? n.quasis.map(q => q.value.cooked).join("…") : null
|
|
20
|
+
|
|
21
|
+
// each outermost function is its own scope, so two functions' "message" never mix
|
|
22
|
+
function scopes(ast) {
|
|
23
|
+
const out = []
|
|
24
|
+
const visit = node => {
|
|
25
|
+
if (!node || typeof node.type !== "string") return
|
|
26
|
+
if (["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression", "ObjectMethod", "ClassMethod"].includes(node.type)) {
|
|
27
|
+
out.push(node)
|
|
28
|
+
return
|
|
29
|
+
}
|
|
30
|
+
for (const key of Object.keys(node)) {
|
|
31
|
+
if (key === "loc" || key === "start" || key === "end") continue
|
|
32
|
+
const child = node[key]
|
|
33
|
+
if (Array.isArray(child)) child.forEach(visit)
|
|
34
|
+
else if (child && typeof child.type === "string") visit(child)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
visit(ast.program)
|
|
38
|
+
return out
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// reads third-party data, unless it went through a validator: schema.parse(res.data) is clean
|
|
42
|
+
function reads(node, names) {
|
|
43
|
+
if (!node || typeof node.type !== "string") return false
|
|
44
|
+
if (isCallNode(node) && VALIDATE.test(calleeName(node))) return false
|
|
45
|
+
if (node.type === "Identifier") return names.has(node.name)
|
|
46
|
+
if (isClientCall(node)) return true
|
|
47
|
+
for (const key of Object.keys(node)) {
|
|
48
|
+
if (key === "loc" || key === "start" || key === "end") continue
|
|
49
|
+
const child = node[key]
|
|
50
|
+
if (Array.isArray(child) ? child.some(c => reads(c, names)) : child && typeof child.type === "string" && reads(child, names)) return true
|
|
51
|
+
}
|
|
52
|
+
return false
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// API10: data from another API is trusted as if it were our own
|
|
56
|
+
export function consumption(root) {
|
|
57
|
+
const findings = []
|
|
58
|
+
const add = (file, node, finding) =>
|
|
59
|
+
findings.push({ ...finding, route: "(app-wide)", where: `${path.relative(root, file)}:${node.loc.start.line}` })
|
|
60
|
+
|
|
61
|
+
for (const file of listSourceFiles(root)) {
|
|
62
|
+
const ast = parseFile(file)
|
|
63
|
+
if (!ast) continue
|
|
64
|
+
|
|
65
|
+
// literal values of variables in the file: const url = `https://…?appid=…`
|
|
66
|
+
const inits = new Map()
|
|
67
|
+
walk(ast, n => {
|
|
68
|
+
if (n.type === "VariableDeclarator" && n.id.type === "Identifier" && n.init) inits.set(n.id.name, n.init)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
for (const scope of scopes(ast)) {
|
|
72
|
+
// what came back from a third party: const r = await axios.get(…), .then(r => …),
|
|
73
|
+
// https.get(url, res => res.on("data", chunk => body += chunk)), and values built from those
|
|
74
|
+
const external = new Set()
|
|
75
|
+
const taintParams = fn => fn?.params?.forEach(p => p.type === "Identifier" && external.add(p.name))
|
|
76
|
+
for (let pass = 0; pass < 3; pass++) {
|
|
77
|
+
walk(scope, n => {
|
|
78
|
+
if (n.type === "VariableDeclarator" && n.id.type === "Identifier" && n.init && reads(n.init, external)) external.add(n.id.name)
|
|
79
|
+
if (n.type === "AssignmentExpression" && n.left.type === "Identifier" && reads(n.right, external)) external.add(n.left.name)
|
|
80
|
+
if (isClientCall(n)) n.arguments.filter(isFunction).forEach(taintParams)
|
|
81
|
+
if (isCallNode(n) && isMemberNode(n.callee) && /^(then|on|once)$/.test(calleeName(n))) {
|
|
82
|
+
const source = n.callee.object
|
|
83
|
+
if (isClientCall(source) || (source.type === "Identifier" && external.has(source.name)) || reads(source, external))
|
|
84
|
+
n.arguments.filter(isFunction).forEach(taintParams)
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const validated = new Set()
|
|
90
|
+
walk(scope, n => {
|
|
91
|
+
if (isCallNode(n) && VALIDATE.test(calleeName(n)))
|
|
92
|
+
n.arguments.forEach(a => walk(a, x => x.type === "Identifier" && external.has(x.name) && validated.add(x.name)))
|
|
93
|
+
})
|
|
94
|
+
const unchecked = new Set([...external].filter(name => !validated.has(name)))
|
|
95
|
+
|
|
96
|
+
let relayed = null
|
|
97
|
+
let stored = null
|
|
98
|
+
walk(scope, n => {
|
|
99
|
+
if (!isCallNode(n)) return
|
|
100
|
+
const name = calleeName(n)
|
|
101
|
+
const args = n.arguments.filter(a => !isFunction(a))
|
|
102
|
+
|
|
103
|
+
if (isClientCall(n)) {
|
|
104
|
+
const first = n.arguments[0]
|
|
105
|
+
const url = literalText(first?.type === "Identifier" ? inits.get(first.name) : first)
|
|
106
|
+
const key = url?.match(KEY_IN_URL)
|
|
107
|
+
if (key)
|
|
108
|
+
add(file, n, {
|
|
109
|
+
rule: "SECRET_IN_URL",
|
|
110
|
+
owasp: "API8:2023 Security Misconfiguration",
|
|
111
|
+
severity: "HIGH",
|
|
112
|
+
message: `The "${key[1]}" key for a third-party API is written into the URL in the code.`,
|
|
113
|
+
fix: "Load the key from the environment or a secret store, and rotate the one in the code."
|
|
114
|
+
})
|
|
115
|
+
if (url?.startsWith("http://") && !LOCAL.test(url))
|
|
116
|
+
add(file, n, {
|
|
117
|
+
rule: "UNSAFE_CONSUMPTION",
|
|
118
|
+
owasp: "API10:2023 Unsafe Consumption of APIs",
|
|
119
|
+
severity: "LOW",
|
|
120
|
+
message: `A third-party API is called over plain http (${url.slice(0, 60)}), so its answers can be changed in transit.`,
|
|
121
|
+
fix: "Use https, and verify certificates."
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
if (unchecked.size === 0 || !args.some(a => reads(a, unchecked))) return
|
|
125
|
+
|
|
126
|
+
if (CODE_SINK.test(name) || (n.callee.type === "Identifier" && name === "Function")) {
|
|
127
|
+
add(file, n, {
|
|
128
|
+
rule: "UNSAFE_CONSUMPTION",
|
|
129
|
+
owasp: "API10:2023 Unsafe Consumption of APIs",
|
|
130
|
+
severity: "HIGH",
|
|
131
|
+
message: `${name}() runs data that came from another API, so whoever controls that API runs code here.`,
|
|
132
|
+
fix: "Never evaluate third-party data; parse it as data and validate it against a schema."
|
|
133
|
+
})
|
|
134
|
+
} else if (name === "redirect") {
|
|
135
|
+
add(file, n, {
|
|
136
|
+
rule: "UNSAFE_CONSUMPTION",
|
|
137
|
+
owasp: "API10:2023 Unsafe Consumption of APIs",
|
|
138
|
+
severity: "MEDIUM",
|
|
139
|
+
message: "The client is redirected to a URL another API returned, which that API can point anywhere.",
|
|
140
|
+
fix: "Redirect only to URLs on an allow-list."
|
|
141
|
+
})
|
|
142
|
+
} else if (DB_WRITE.test(name)) stored ??= n
|
|
143
|
+
else if (/^(send|write|end)$/.test(name) && isMemberNode(n.callee)) relayed ??= n
|
|
144
|
+
})
|
|
145
|
+
if (stored)
|
|
146
|
+
add(file, stored, {
|
|
147
|
+
rule: "UNSAFE_CONSUMPTION",
|
|
148
|
+
owasp: "API10:2023 Unsafe Consumption of APIs",
|
|
149
|
+
severity: "MEDIUM",
|
|
150
|
+
message: `${calleeName(stored)}() stores data from another API without validating it, so a compromised or buggy provider writes into our database.`,
|
|
151
|
+
fix: "Validate the response against a schema (zod, Joi, ajv) and copy only the fields you need."
|
|
152
|
+
})
|
|
153
|
+
if (relayed)
|
|
154
|
+
add(file, relayed, {
|
|
155
|
+
rule: "UNSAFE_CONSUMPTION",
|
|
156
|
+
owasp: "API10:2023 Unsafe Consumption of APIs",
|
|
157
|
+
severity: "LOW",
|
|
158
|
+
message: "A third-party response is passed to our clients as is, so its content (HTML, scripts, extra fields) reaches them under our origin.",
|
|
159
|
+
fix: "Parse the response, pick the fields you need and send those as JSON."
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return findings
|
|
164
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs"
|
|
2
|
+
import { walk, isCallNode, isMemberNode } from "../mapper.js"
|
|
3
|
+
import { DB_CALL, calleeName, handlerParams, hasRole, isMember, whereOf } from "./handler.js"
|
|
4
|
+
|
|
5
|
+
// models whose documents carry password hashes, tokens and personal data
|
|
6
|
+
const PERSON_MODEL = /^(user|users|account|accounts|member|members|customer|customers|profile|profiles|employee|employees|person|people)$/i
|
|
7
|
+
// field selection on the query: .select("name email"), { attributes: [...] }, { select: {...} }
|
|
8
|
+
const PROJECTION_CALL = /^(select|project|projection|attributes|pick|omit|lean)$/
|
|
9
|
+
const PROJECTION_KEY = /^(select|attributes|projection|fields)$/
|
|
10
|
+
// shaping before the response: toJSON, a DTO, a serializer, _.pick
|
|
11
|
+
const SHAPED = /pick|omit|serial|sanitiz|transform|toJSON|toDTO|dto|format|present|public|safe|strip|without/i
|
|
12
|
+
// the model hides fields itself: select: false on a field, a toJSON transform
|
|
13
|
+
const MODEL_HIDES = /select:\s*false|toJSON|transform\s*[:(]|defaultScope|hidden/
|
|
14
|
+
|
|
15
|
+
function modelFrom(call) {
|
|
16
|
+
let node = call.callee
|
|
17
|
+
while (isMemberNode(node) || isCallNode(node)) node = isMemberNode(node) ? node.object : node.callee
|
|
18
|
+
return node?.type === "Identifier" ? node.name : null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// User.findById(id) and User.find().select("name"): the query, and whether it picks fields
|
|
22
|
+
function personQuery(node) {
|
|
23
|
+
let query = null
|
|
24
|
+
let projected = false
|
|
25
|
+
walk(node, n => {
|
|
26
|
+
if (!isCallNode(n)) return
|
|
27
|
+
const name = calleeName(n)
|
|
28
|
+
if (PROJECTION_CALL.test(name)) projected = true
|
|
29
|
+
if (DB_CALL.test(name) && PERSON_MODEL.test(modelFrom(n) ?? "")) {
|
|
30
|
+
query = n
|
|
31
|
+
// findById(id, "name email") or findOne(filter, { password: 0 }) or { attributes: [...] }
|
|
32
|
+
const options = n.arguments.slice(1)
|
|
33
|
+
if (options.some(a => a.type === "StringLiteral" || a.type === "ObjectExpression")) projected = true
|
|
34
|
+
for (const arg of n.arguments)
|
|
35
|
+
if (arg.type === "ObjectExpression" && arg.properties.some(p => PROJECTION_KEY.test(p.key?.name ?? ""))) projected = true
|
|
36
|
+
}
|
|
37
|
+
})
|
|
38
|
+
return query ? { query, projected } : null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function modelHidesFields(route, model) {
|
|
42
|
+
const file = route.importedFile?.(route.fnPath, model)
|
|
43
|
+
try {
|
|
44
|
+
return file ? MODEL_HIDES.test(readFileSync(file, "utf8")) : false
|
|
45
|
+
} catch {
|
|
46
|
+
return false
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const isResponse = (n, res) =>
|
|
51
|
+
isCallNode(n) &&
|
|
52
|
+
isMemberNode(n.callee) &&
|
|
53
|
+
/^(send|json|jsonp)$/.test(n.callee.property.name) &&
|
|
54
|
+
(isMember(n.callee, res) || isCallNode(n.callee.object))
|
|
55
|
+
|
|
56
|
+
// the record itself, not one of its fields: user, { user }, { ...user }, JSON.stringify(user)
|
|
57
|
+
function sendsWhole(node, names) {
|
|
58
|
+
if (!node) return false
|
|
59
|
+
if (node.type === "Identifier") return names.has(node.name)
|
|
60
|
+
if (node.type === "ObjectExpression")
|
|
61
|
+
return node.properties.some(p => (p.type === "SpreadElement" ? sendsWhole(p.argument, names) : sendsWhole(p.value, names)))
|
|
62
|
+
if (node.type === "ArrayExpression") return node.elements.some(e => sendsWhole(e, names))
|
|
63
|
+
if (isCallNode(node)) return !SHAPED.test(calleeName(node)) && calleeName(node) === "stringify" && node.arguments.some(a => sendsWhole(a, names))
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// API3: a person's whole record goes back to the client, password hash and tokens included
|
|
68
|
+
export function dataExposure(route) {
|
|
69
|
+
if (!route.fn) return null
|
|
70
|
+
const { res } = handlerParams(route.fn)
|
|
71
|
+
|
|
72
|
+
const records = new Map()
|
|
73
|
+
walk(route.fn.body, n => {
|
|
74
|
+
// const user = await User.findById(id)
|
|
75
|
+
if (n.type === "VariableDeclarator" && n.id.type === "Identifier" && n.init) {
|
|
76
|
+
const found = personQuery(n.init)
|
|
77
|
+
if (found && !found.projected) records.set(n.id.name, found)
|
|
78
|
+
}
|
|
79
|
+
// User.findById(id).then(user => res.json({ user }))
|
|
80
|
+
if (isCallNode(n) && calleeName(n) === "then" && isMemberNode(n.callee)) {
|
|
81
|
+
const found = personQuery(n.callee.object)
|
|
82
|
+
const param = n.arguments[0]?.params?.[0]
|
|
83
|
+
if (found && !found.projected && param?.type === "Identifier") records.set(param.name, found)
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
if (records.size === 0) return null
|
|
87
|
+
|
|
88
|
+
let sent = null
|
|
89
|
+
walk(route.fn.body, n => {
|
|
90
|
+
if (!sent && isResponse(n, res) && n.arguments.some(a => sendsWhole(a, new Set(records.keys())))) sent = n
|
|
91
|
+
})
|
|
92
|
+
if (!sent) return null
|
|
93
|
+
|
|
94
|
+
const [record] = [...records.values()]
|
|
95
|
+
const model = modelFrom(record.query)
|
|
96
|
+
if (modelHidesFields(route, model)) return null
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
rule: "DATA_EXPOSURE",
|
|
100
|
+
owasp: "API3:2023 Broken Object Property Level Authorization (excessive data exposure)",
|
|
101
|
+
severity: !route.auth ? "HIGH" : hasRole(route) ? "LOW" : "MEDIUM",
|
|
102
|
+
route: `${route.method} ${route.path}`,
|
|
103
|
+
where: whereOf(route, sent.loc.start.line),
|
|
104
|
+
message: `The whole ${model} record from ${calleeName(record.query)} is sent to the client, with no field selection, so hashes, tokens and private fields go too.`,
|
|
105
|
+
fix: `Select only what the client needs: ${model}.${calleeName(record.query)}(…).select("name email"), _.pick(user, [...]), or mark secret fields select: false in the schema.`
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { walk, isMemberNode, isCallNode } from "../mapper.js"
|
|
2
|
+
|
|
3
|
+
// Mongoose, Sequelize, Prisma and raw query calls that load or change a record
|
|
4
|
+
export const DB_CALL =
|
|
5
|
+
/^(find|findOne|findById|findByPk|findUnique|findFirst|findByIdAnd(Update|Delete|Remove)|findOneAnd(Update|Delete|Remove|Replace)|update|updateOne|updateMany|delete|deleteOne|deleteMany|destroy|remove|replaceOne|query|execute)$/
|
|
6
|
+
|
|
7
|
+
// service calls such as userService.getUserById(id) or updateArticle(slug, body)
|
|
8
|
+
export const RECORD_ACCESS = new RegExp(
|
|
9
|
+
`${DB_CALL.source}|^(get|find|fetch|load|read|update|edit|patch|delete|remove|destroy|archive)[A-Z_]`
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
export const DB_WRITE =
|
|
13
|
+
/^(save|create|insert|insertOne|insertMany|upsert|bulkCreate|update|updateOne|updateMany|findByIdAnd(Update|Delete|Remove)|findOneAnd(Update|Delete|Remove|Replace)|delete|deleteOne|deleteMany|destroy|remove|replaceOne)$/
|
|
14
|
+
|
|
15
|
+
// where the signed-in caller's identity usually lives
|
|
16
|
+
const IDENTITY_KEYS = new Set(["user", "auth", "session", "userId", "currentUser"])
|
|
17
|
+
|
|
18
|
+
export const isMember = (node, objectName, propertyName) =>
|
|
19
|
+
isMemberNode(node) &&
|
|
20
|
+
node.object.type === "Identifier" &&
|
|
21
|
+
node.object.name === objectName &&
|
|
22
|
+
(propertyName === undefined || node.property.name === propertyName)
|
|
23
|
+
|
|
24
|
+
// the names the handler gives req and res: (request, response) => {} works too
|
|
25
|
+
export function handlerParams(fn) {
|
|
26
|
+
const [reqParam, resParam] = fn.params
|
|
27
|
+
return {
|
|
28
|
+
req: reqParam?.type === "Identifier" ? reqParam.name : "req",
|
|
29
|
+
res: resParam?.type === "Identifier" ? resParam.name : "res"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function dbCalls(fn, pattern) {
|
|
34
|
+
const calls = []
|
|
35
|
+
walk(fn.body, node => {
|
|
36
|
+
if (!isCallNode(node)) return
|
|
37
|
+
const method = isMemberNode(node.callee) ? node.callee.property.name : node.callee.name
|
|
38
|
+
if (method && pattern.test(method)) calls.push({ node, method, line: node.loc.start.line })
|
|
39
|
+
})
|
|
40
|
+
return calls
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// helpers that turn the request into the caller: authenticatedUsers.from(req), jwtFrom(req), getUser(req)
|
|
44
|
+
const IDENTITY_FN = /user|auth|jwt|token|session|identity|principal|caller/i
|
|
45
|
+
|
|
46
|
+
function boundNames(id) {
|
|
47
|
+
if (id.type === "Identifier") return [id.name]
|
|
48
|
+
if (id.type === "ObjectPattern") return id.properties.flatMap(p => (p.value ? boundNames(p.value) : p.argument ? boundNames(p.argument) : []))
|
|
49
|
+
return []
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// what in this handler stands for the caller: req.user, res.locals, a helper's result,
|
|
53
|
+
// and every variable built from those (const data = auth.from(req), const filter = { owner: req.user.id })
|
|
54
|
+
// appendUserId() copies the caller into req.body, so req.body.UserId is the caller there
|
|
55
|
+
const APPENDS_USER = /(append|set|attach|inject|add)_?user/i
|
|
56
|
+
const BODY_USER_FIELD = /^(user_?id|owner_?id|owner)$/i
|
|
57
|
+
|
|
58
|
+
function identity(fn, route) {
|
|
59
|
+
const { req, res } = handlerParams(fn)
|
|
60
|
+
const names = new Set()
|
|
61
|
+
const bodyIsCaller = route?.middleware.some(m => APPENDS_USER.test(m)) ?? false
|
|
62
|
+
const isIdentity = n =>
|
|
63
|
+
(isMember(n, req) && IDENTITY_KEYS.has(n.property.name)) ||
|
|
64
|
+
(bodyIsCaller && isMemberNode(n) && isMember(n.object, req, "body") && BODY_USER_FIELD.test(n.property.name ?? "")) ||
|
|
65
|
+
isMember(n, res, "locals") ||
|
|
66
|
+
(n.type === "Identifier" && names.has(n.name)) ||
|
|
67
|
+
(isCallNode(n) &&
|
|
68
|
+
n.arguments.some(a => a.type === "Identifier" && a.name === req) &&
|
|
69
|
+
IDENTITY_FN.test((isMemberNode(n.callee) ? `${n.callee.object.name ?? n.callee.object.property?.name ?? ""}.${n.callee.property.name}` : n.callee.name) ?? ""))
|
|
70
|
+
const contains = node => {
|
|
71
|
+
let found = false
|
|
72
|
+
walk(node, n => {
|
|
73
|
+
if (isIdentity(n)) found = true
|
|
74
|
+
})
|
|
75
|
+
return found
|
|
76
|
+
}
|
|
77
|
+
// twice, so a variable built from another identity variable is caught too
|
|
78
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
79
|
+
walk(fn.body, n => {
|
|
80
|
+
if (n.type !== "VariableDeclarator" || !n.init) return
|
|
81
|
+
// const { user } = req
|
|
82
|
+
const fromReq =
|
|
83
|
+
n.id.type === "ObjectPattern" &&
|
|
84
|
+
n.init.type === "Identifier" &&
|
|
85
|
+
n.init.name === req &&
|
|
86
|
+
n.id.properties.some(p => IDENTITY_KEYS.has(p.key?.name))
|
|
87
|
+
if (fromReq || contains(n.init)) boundNames(n.id).forEach(name => names.add(name))
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
return { names, contains }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function readsIdentity(fn) {
|
|
94
|
+
const { names, contains } = identity(fn)
|
|
95
|
+
return names.size > 0 || contains(fn.body)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const ROLE_CALL = /^(require|assert|ensure|check|verify)_?(admin|role|permission|staff|owner)|^is_?(admin|staff|owner)$|^has_?(role|permission)|^authori[sz]e$|^can[A-Z]/i
|
|
99
|
+
const ROLE_FIELD = /^(is_?admin|admin|role|roles|permissions?|is_?staff)$/i
|
|
100
|
+
|
|
101
|
+
// a role checked inside the handler: requireAdmin(req, res), if (req.user.role !== "admin")
|
|
102
|
+
export function checksRoleInline(fn) {
|
|
103
|
+
if (!fn) return false
|
|
104
|
+
let found = false
|
|
105
|
+
walk(fn.body, n => {
|
|
106
|
+
if (isCallNode(n)) {
|
|
107
|
+
const name = isMemberNode(n.callee) ? n.callee.property.name : n.callee.name
|
|
108
|
+
if (name && ROLE_CALL.test(name)) found = true
|
|
109
|
+
}
|
|
110
|
+
if (isMemberNode(n) && ROLE_FIELD.test(n.property.name ?? "")) found = true
|
|
111
|
+
})
|
|
112
|
+
return found
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// a credential in the body guards the action: a link password, a reset code
|
|
116
|
+
const CREDENTIAL_FIELD = /^(password|passcode|pin|code|otp|token|secret)$/i
|
|
117
|
+
|
|
118
|
+
export function checksBodyCredential(fn) {
|
|
119
|
+
const { req } = handlerParams(fn)
|
|
120
|
+
let found = false
|
|
121
|
+
walk(fn.body, n => {
|
|
122
|
+
if (isMemberNode(n) && isMember(n.object, req, "body") && CREDENTIAL_FIELD.test(n.property.name ?? "")) found = true
|
|
123
|
+
})
|
|
124
|
+
return found
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export const hasRole = route => route.role || checksRoleInline(route.fn)
|
|
128
|
+
|
|
129
|
+
// findings point at the line in the handler, which may live in a controller file
|
|
130
|
+
export const whereOf = (route, line) => `${route.fnFile ?? route.file}:${line}`
|
|
131
|
+
|
|
132
|
+
const INPUT_KEYS = new Set(["body", "query", "params", "headers", "cookies"])
|
|
133
|
+
|
|
134
|
+
// what in the handler the client controls: req.body.url, req.query, and variables built from them
|
|
135
|
+
export function userInput(fn) {
|
|
136
|
+
const { req } = handlerParams(fn)
|
|
137
|
+
const names = new Set()
|
|
138
|
+
const direct = n => isMember(n, req) && INPUT_KEYS.has(n.property.name)
|
|
139
|
+
const reads = node => {
|
|
140
|
+
let found = false
|
|
141
|
+
walk(node, n => {
|
|
142
|
+
if (direct(n) || (n.type === "Identifier" && names.has(n.name))) found = true
|
|
143
|
+
})
|
|
144
|
+
return found
|
|
145
|
+
}
|
|
146
|
+
const inits = new Map()
|
|
147
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
148
|
+
walk(fn.body, n => {
|
|
149
|
+
if (n.type !== "VariableDeclarator" || !n.init || n.id.type !== "Identifier") return
|
|
150
|
+
inits.set(n.id.name, n.init)
|
|
151
|
+
if (reads(n.init)) names.add(n.id.name)
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
return { reads, inits }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export const calleeName = call => (isMemberNode(call.callee) ? call.callee.property.name : call.callee.name) ?? ""
|
|
158
|
+
export const calleeObject = call =>
|
|
159
|
+
isMemberNode(call.callee) ? (call.callee.object.name ?? call.callee.object.property?.name ?? "") : ""
|