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,84 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { listSpecFiles } from "../spec.js"
|
|
3
|
+
|
|
4
|
+
// leftover versions and environments: /v1 next to /v2, /dev, /beta, /old (debug and internal are BFLA's)
|
|
5
|
+
// environment names only, near the top of the path: /dev/csrf, /api/test/x. "/stage", "/temp" and
|
|
6
|
+
// "/flush/old" are usually feature names
|
|
7
|
+
const NON_PROD = /^(dev|develop|development|test|testing|staging|sandbox|deprecated)$/i
|
|
8
|
+
const VERSION = /^v\d+$/i
|
|
9
|
+
|
|
10
|
+
const strength = route => (route.role ? 2 : route.auth ? 1 : 0)
|
|
11
|
+
const STRENGTH = ["no auth", "auth", "auth and a role"]
|
|
12
|
+
// /api/v1/users/:id and /api/v2/users/:userId are the same endpoint
|
|
13
|
+
// one app's /x and another app's /x in the same monorepo are not copies of each other
|
|
14
|
+
const shape = route => `${route.rootFile ?? ""} ${shapePath(route)}`
|
|
15
|
+
const shapePath = route => `${route.method} ${route.path.split("/").filter(s => !VERSION.test(s)).map(s => (/^[:{]/.test(s) ? ":p" : s.toLowerCase())).join("/")}`
|
|
16
|
+
|
|
17
|
+
// API9: endpoints nobody tracks, which keep old or weaker rules
|
|
18
|
+
export function inventory(routes, root) {
|
|
19
|
+
const findings = []
|
|
20
|
+
|
|
21
|
+
// the same endpoint registered more than once, one copy guarded less than another
|
|
22
|
+
const byShape = new Map()
|
|
23
|
+
// only routes whose full path is known: a router mounted inside a function (mountMcp(app)) has no prefix here
|
|
24
|
+
// catch-alls (/{*any}, *) exist in most apps and are not copies of one endpoint
|
|
25
|
+
for (const r of routes.filter(r => r.anchored && !/[*]/.test(r.path))) {
|
|
26
|
+
if (!byShape.has(shape(r))) byShape.set(shape(r), [])
|
|
27
|
+
byShape.get(shape(r)).push(r)
|
|
28
|
+
}
|
|
29
|
+
for (const copies of byShape.values()) {
|
|
30
|
+
const distinct = [...new Map(copies.map(r => [`${r.file}:${r.line}`, r])).values()]
|
|
31
|
+
if (distinct.length < 2) continue
|
|
32
|
+
const strongest = distinct.reduce((a, b) => (strength(b) > strength(a) ? b : a))
|
|
33
|
+
for (const weaker of distinct.filter(r => strength(r) < strength(strongest))) {
|
|
34
|
+
findings.push({
|
|
35
|
+
rule: "SHADOW_ROUTE",
|
|
36
|
+
owasp: "API9:2023 Improper Inventory Management",
|
|
37
|
+
severity: "HIGH",
|
|
38
|
+
route: `${weaker.method} ${weaker.path}`,
|
|
39
|
+
where: `${weaker.file}:${weaker.line}`,
|
|
40
|
+
message: `Another copy of this endpoint (${strongest.file}:${strongest.line}) requires ${STRENGTH[strength(strongest)]}; this one requires ${STRENGTH[strength(weaker)]}, so callers can go around the check.`,
|
|
41
|
+
fix: "Remove the older or development copy, or give it the same middleware."
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// /dev/..., /beta/..., /old/...
|
|
47
|
+
for (const r of routes) {
|
|
48
|
+
const segment = r.path.split("/").filter(s => s && !/^(api|v\d+)$/i.test(s)).slice(0, 2).find(s => NON_PROD.test(s))
|
|
49
|
+
if (!segment) continue
|
|
50
|
+
findings.push({
|
|
51
|
+
rule: "NON_PROD_ROUTE",
|
|
52
|
+
owasp: "API9:2023 Improper Inventory Management",
|
|
53
|
+
severity: r.auth ? "LOW" : "MEDIUM",
|
|
54
|
+
route: `${r.method} ${r.path}`,
|
|
55
|
+
where: `${r.file}:${r.line}`,
|
|
56
|
+
message: `"/${segment}" looks like a development or retired endpoint that is still mounted.`,
|
|
57
|
+
fix: "Remove it from production builds, or mount it only when NODE_ENV is development."
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// routes the API's own OpenAPI spec does not list
|
|
62
|
+
const spec = listSpecFiles(root)
|
|
63
|
+
if (spec.paths.size > 0) {
|
|
64
|
+
const documented = p => spec.paths.has(p.replace(/:(\w+)/g, ":p").replace(/\{\w+\}/g, ":p").toLowerCase())
|
|
65
|
+
// a spec served under /b2b/v2 describes that API only, not the whole app
|
|
66
|
+
const inScope = r => !spec.basePath || r.path.toLowerCase().startsWith(spec.basePath.toLowerCase())
|
|
67
|
+
const missing = routes.filter(r => inScope(r) && !documented(r.path) && !documented(r.path.slice(spec.basePath.length)))
|
|
68
|
+
const unique = [...new Map(missing.map(r => [`${r.method} ${r.path}`, r])).values()]
|
|
69
|
+
if (unique.length) {
|
|
70
|
+
const [first] = unique
|
|
71
|
+
findings.push({
|
|
72
|
+
rule: "UNDOCUMENTED",
|
|
73
|
+
owasp: "API9:2023 Improper Inventory Management",
|
|
74
|
+
severity: "LOW",
|
|
75
|
+
route: `${unique.length} route${unique.length > 1 ? "s" : ""}`,
|
|
76
|
+
where: `${first.file}:${first.line}`,
|
|
77
|
+
message: `Not in ${spec.files.map(f => path.relative(root, f)).join(", ")}: ${unique.slice(0, 8).map(r => `${r.method} ${r.path}`).join(", ")}${unique.length > 8 ? ", …" : ""}.`,
|
|
78
|
+
fix: "Document the routes or remove them; an endpoint nobody knows about is one nobody reviews.",
|
|
79
|
+
undocumented: unique.map(r => `${r.method} ${r.path}`)
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return findings
|
|
84
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { walk, isMemberNode, isCallNode } from "../mapper.js"
|
|
2
|
+
import { handlerParams, hasRole, isMember, whereOf } from "./handler.js"
|
|
3
|
+
|
|
4
|
+
const WRITE_CALL =
|
|
5
|
+
/^(create|insert|insertOne|insertMany|upsert|build|bulkCreate|update|updateOne|updateMany|findByIdAndUpdate|findOneAndUpdate|replaceOne|set|assign)$/
|
|
6
|
+
|
|
7
|
+
// models and routes where an extra field like role or isAdmin means privilege escalation
|
|
8
|
+
const PRIVILEGED = /user|account|member|profile|admin|register|signup/i
|
|
9
|
+
|
|
10
|
+
// names bound to the whole body: const data = req.body
|
|
11
|
+
function bodyAliases(fn, req) {
|
|
12
|
+
const names = new Set()
|
|
13
|
+
walk(fn.body, n => {
|
|
14
|
+
if (n.type === "VariableDeclarator" && n.id.type === "Identifier" && isMember(n.init, req, "body"))
|
|
15
|
+
names.add(n.id.name)
|
|
16
|
+
})
|
|
17
|
+
return names
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// req.body itself, an alias of it, or { ...req.body } / { $set: req.body }
|
|
21
|
+
function isWholeBody(node, req, aliases) {
|
|
22
|
+
if (isMember(node, req, "body")) return true
|
|
23
|
+
if (node?.type === "Identifier" && aliases.has(node.name)) return true
|
|
24
|
+
if (node?.type === "ObjectExpression")
|
|
25
|
+
return node.properties.some(p =>
|
|
26
|
+
p.type === "SpreadElement" ? isWholeBody(p.argument, req, aliases) : isWholeBody(p.value, req, aliases)
|
|
27
|
+
)
|
|
28
|
+
return false
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// fields a client must never choose
|
|
32
|
+
const SENSITIVE_FIELD = /^(is_?admin|admin|role|roles|permissions?|is_?verified|verified|credit|balance|owner|owner_?id|user_?id|tenant_?id|org_?id)$/i
|
|
33
|
+
|
|
34
|
+
// { isAdmin: req.body.isAdmin }: a privileged field copied from the body by name
|
|
35
|
+
function sensitiveFieldsFromBody(node, req) {
|
|
36
|
+
if (node?.type !== "ObjectExpression") return []
|
|
37
|
+
return node.properties
|
|
38
|
+
.filter(p => p.type === "ObjectProperty" && SENSITIVE_FIELD.test(p.key.name ?? p.key.value ?? ""))
|
|
39
|
+
.filter(p => isMemberNode(p.value) && isMember(p.value.object, req, "body"))
|
|
40
|
+
.map(p => p.key.name ?? p.key.value)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function calleeName(node) {
|
|
44
|
+
if (node.callee.type === "Identifier") return node.callee.name
|
|
45
|
+
if (isMemberNode(node.callee)) return node.callee.property.name
|
|
46
|
+
return ""
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// API3: the whole request body is written to a record, so a client can set fields the
|
|
50
|
+
// form never offered (role, isAdmin, credit, owner)
|
|
51
|
+
export function massAssignment(route) {
|
|
52
|
+
if (!route.fn || route.method === "GET") return null
|
|
53
|
+
const { req } = handlerParams(route.fn)
|
|
54
|
+
const aliases = bodyAliases(route.fn, req)
|
|
55
|
+
|
|
56
|
+
const sinks = []
|
|
57
|
+
const fields = []
|
|
58
|
+
walk(route.fn.body, node => {
|
|
59
|
+
if (node.type === "NewExpression" || (isCallNode(node) && WRITE_CALL.test(calleeName(node)))) {
|
|
60
|
+
for (const arg of node.arguments) {
|
|
61
|
+
const found = sensitiveFieldsFromBody(arg, req)
|
|
62
|
+
if (found.length) fields.push({ names: found, line: node.loc.start.line })
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (node.type === "NewExpression" && node.arguments.some(a => isWholeBody(a, req, aliases)))
|
|
66
|
+
sinks.push({ what: `new ${calleeName(node)}(…)`, model: calleeName(node), line: node.loc.start.line })
|
|
67
|
+
if (isCallNode(node) && WRITE_CALL.test(calleeName(node))) {
|
|
68
|
+
if (node.arguments.some(a => isWholeBody(a, req, aliases))) {
|
|
69
|
+
const object = isMemberNode(node.callee) ? (node.callee.object.name ?? "") : ""
|
|
70
|
+
sinks.push({ what: `${object ? object + "." : ""}${calleeName(node)}(…)`, model: object, line: node.loc.start.line })
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
})
|
|
74
|
+
if (sinks.length === 0 && fields.length > 0) {
|
|
75
|
+
const names = [...new Set(fields.flatMap(f => f.names))]
|
|
76
|
+
return {
|
|
77
|
+
rule: "MASS_ASSIGNMENT",
|
|
78
|
+
owasp: "API3:2023 Broken Object Property Level Authorization",
|
|
79
|
+
severity: "HIGH",
|
|
80
|
+
route: `${route.method} ${route.path}`,
|
|
81
|
+
where: whereOf(route, fields[0].line),
|
|
82
|
+
message: `${names.join(", ")} is taken straight from the request body, so a client chooses its own privileges.`,
|
|
83
|
+
fix: `Set ${names.join(", ")} on the server (a default, or from req.user), never from req.body.`
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (sinks.length === 0) return null
|
|
87
|
+
|
|
88
|
+
const privileged = sinks.some(s => PRIVILEGED.test(s.model)) || PRIVILEGED.test(route.path)
|
|
89
|
+
return {
|
|
90
|
+
rule: "MASS_ASSIGNMENT",
|
|
91
|
+
owasp: "API3:2023 Broken Object Property Level Authorization (mass assignment)",
|
|
92
|
+
// behind a role check the caller is trusted more, but extra fields still deserve a look
|
|
93
|
+
severity: hasRole(route) ? "LOW" : privileged ? "HIGH" : "MEDIUM",
|
|
94
|
+
route: `${route.method} ${route.path}`,
|
|
95
|
+
where: whereOf(route, sinks[0].line),
|
|
96
|
+
message: `${sinks.map(s => s.what).join(", ")} receives the whole request body, so a client can set any field${privileged ? ", including role or admin flags" : ""}.`,
|
|
97
|
+
fix: "Copy only the fields the client may set: _.pick(req.body, ['name', 'email']) or a validator schema that strips unknown keys."
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { listSourceFiles, parseFile, walk, isCallNode, isMemberNode } from "../mapper.js"
|
|
3
|
+
import { calleeName, calleeObject } from "./handler.js"
|
|
4
|
+
|
|
5
|
+
const ASYMMETRIC = /^(RS|ES|PS)\d{3}$|^EdDSA$/
|
|
6
|
+
const SYMMETRIC = /^HS\d{3}$/
|
|
7
|
+
const FUNCTION = /^(FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod|ClassMethod)$/
|
|
8
|
+
const ERROR_NAME = /^(e|err|error|ex|exception)$/
|
|
9
|
+
const SECURITY_HEADERS = /^(helmet|lusca|xssProtection|hidePoweredBy|frameguard|hsts|contentSecurityPolicy)$/
|
|
10
|
+
|
|
11
|
+
const prop = (object, key) =>
|
|
12
|
+
object?.type === "ObjectExpression" ? object.properties.find(p => (p.key?.name ?? p.key?.value) === key)?.value : undefined
|
|
13
|
+
const stringsIn = node => (node?.type === "ArrayExpression" ? node.elements.filter(e => e?.type === "StringLiteral").map(e => e.value) : [])
|
|
14
|
+
const isTrue = node => node?.type === "BooleanLiteral" && node.value
|
|
15
|
+
|
|
16
|
+
// reflects the caller's origin: origin: true, origin: "*", or (origin, cb) => cb(null, true)
|
|
17
|
+
function anyOrigin(origin) {
|
|
18
|
+
if (!origin) return false
|
|
19
|
+
if (isTrue(origin) || (origin.type === "StringLiteral" && origin.value === "*")) return true
|
|
20
|
+
if (["ArrowFunctionExpression", "FunctionExpression"].includes(origin.type)) {
|
|
21
|
+
let allowsAll = false
|
|
22
|
+
walk(origin.body, n => {
|
|
23
|
+
if (isCallNode(n) && n.arguments.length === 2 && isTrue(n.arguments[1]) && n.arguments[0].type === "NullLiteral") allowsAll = true
|
|
24
|
+
})
|
|
25
|
+
// a callback that only ever says yes, with no list or check in front of it
|
|
26
|
+
let checks = false
|
|
27
|
+
walk(origin.body, n => {
|
|
28
|
+
if (n.type === "IfStatement" || n.type === "ConditionalExpression" || (isCallNode(n) && /includes|indexOf|test|has|match/.test(calleeName(n)))) checks = true
|
|
29
|
+
})
|
|
30
|
+
return allowsAll && !checks
|
|
31
|
+
}
|
|
32
|
+
return false
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// API8 (and API2 for tokens): settings that hold for the whole app, read once per file
|
|
36
|
+
export function misconfig(root) {
|
|
37
|
+
const findings = []
|
|
38
|
+
let createsApp = null
|
|
39
|
+
let hasSecurityHeaders = false
|
|
40
|
+
const add = (file, node, finding) =>
|
|
41
|
+
findings.push({ ...finding, route: "(app-wide)", where: `${path.relative(root, file)}:${node.loc.start.line}` })
|
|
42
|
+
|
|
43
|
+
for (const file of listSourceFiles(root)) {
|
|
44
|
+
const ast = parseFile(file)
|
|
45
|
+
if (!ast) continue
|
|
46
|
+
let rawErrors = 0
|
|
47
|
+
let firstRawError = null
|
|
48
|
+
// CORS headers, grouped by the function that sets them
|
|
49
|
+
const corsByFunction = new Map()
|
|
50
|
+
let corsNoOptions = false
|
|
51
|
+
|
|
52
|
+
// the walk visits a function before its body, so this stack holds the nearest one
|
|
53
|
+
const enclosing = []
|
|
54
|
+
walk(ast, n => {
|
|
55
|
+
if (FUNCTION.test(n.type)) {
|
|
56
|
+
while (enclosing.length && !(enclosing.at(-1).start <= n.start && n.end <= enclosing.at(-1).end)) enclosing.pop()
|
|
57
|
+
enclosing.push(n)
|
|
58
|
+
return
|
|
59
|
+
}
|
|
60
|
+
while (enclosing.length && !(enclosing.at(-1).start <= n.start && n.end <= enclosing.at(-1).end)) enclosing.pop()
|
|
61
|
+
if (!isCallNode(n)) return
|
|
62
|
+
const name = calleeName(n)
|
|
63
|
+
const object = calleeObject(n)
|
|
64
|
+
|
|
65
|
+
if (n.callee.type === "Identifier" && name === "express" && !createsApp) createsApp = { file, node: n }
|
|
66
|
+
if (SECURITY_HEADERS.test(name) || SECURITY_HEADERS.test(object)) hasSecurityHeaders = true
|
|
67
|
+
if (name === "disable" && n.arguments[0]?.value === "x-powered-by") hasSecurityHeaders = true
|
|
68
|
+
|
|
69
|
+
// cors() and cors({ origin, credentials })
|
|
70
|
+
if (name === "cors" && n.callee.type === "Identifier") {
|
|
71
|
+
const options = n.arguments[0]
|
|
72
|
+
if (!options) {
|
|
73
|
+
if (corsNoOptions) return
|
|
74
|
+
corsNoOptions = true
|
|
75
|
+
add(file, n, {
|
|
76
|
+
rule: "CORS",
|
|
77
|
+
owasp: "API8:2023 Security Misconfiguration",
|
|
78
|
+
severity: "LOW",
|
|
79
|
+
message: "cors() with no options answers every origin. Fine for a public, token-only API; not with cookies or for internal APIs.",
|
|
80
|
+
fix: "Pass the origins that may call the API: cors({ origin: ['https://app.example.com'] })."
|
|
81
|
+
})
|
|
82
|
+
} else if (anyOrigin(prop(options, "origin")) && isTrue(prop(options, "credentials"))) {
|
|
83
|
+
add(file, n, {
|
|
84
|
+
rule: "CORS",
|
|
85
|
+
owasp: "API8:2023 Security Misconfiguration",
|
|
86
|
+
severity: "HIGH",
|
|
87
|
+
message: "CORS reflects any origin and allows credentials, so any website can make signed-in requests and read the answers.",
|
|
88
|
+
fix: "List the allowed origins explicitly; never combine credentials: true with a reflected or * origin."
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// res.setHeader("Access-Control-Allow-Origin", "*" or req.headers.origin)
|
|
94
|
+
if (/^(setHeader|header|set)$/.test(name) && /^access-control-allow-(origin|credentials)$/i.test(n.arguments[0]?.value ?? "")) {
|
|
95
|
+
const header = n.arguments[0].value.toLowerCase()
|
|
96
|
+
const value = n.arguments[1]
|
|
97
|
+
const fn = enclosing.at(-1) ?? ast
|
|
98
|
+
if (!corsByFunction.has(fn)) corsByFunction.set(fn, { credentials: false, wildcard: null })
|
|
99
|
+
const group = corsByFunction.get(fn)
|
|
100
|
+
if (header.endsWith("credentials") && (isTrue(value) || value?.value === "true")) group.credentials = true
|
|
101
|
+
const reflected = isMemberNode(value) && /origin/i.test(value.property?.name ?? value.property?.value ?? "")
|
|
102
|
+
if (header.endsWith("origin") && (value?.value === "*" || reflected)) group.wildcard ??= { node: n, reflected }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// jwt.verify(token, key, { algorithms, ignoreExpiration }) and jwt.sign(payload, "literal")
|
|
106
|
+
if (object === "jwt" || object === "jsonwebtoken") {
|
|
107
|
+
const secret = n.arguments[1]
|
|
108
|
+
if (/^(sign|verify)$/.test(name) && (secret?.type === "StringLiteral" || (secret?.type === "TemplateLiteral" && secret.expressions.length === 0))) {
|
|
109
|
+
add(file, n, {
|
|
110
|
+
rule: "JWT",
|
|
111
|
+
owasp: "API2:2023 Broken Authentication",
|
|
112
|
+
severity: "HIGH",
|
|
113
|
+
message: `jwt.${name}() uses a key written in the code, so anyone with the source can mint tokens.`,
|
|
114
|
+
fix: "Load the key from the environment or a secret store, and rotate the one in the code."
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
const options = n.arguments[2]
|
|
118
|
+
const algorithms = stringsIn(prop(options, "algorithms"))
|
|
119
|
+
if (name === "verify" && algorithms.some(a => ASYMMETRIC.test(a)) && algorithms.some(a => SYMMETRIC.test(a))) {
|
|
120
|
+
add(file, n, {
|
|
121
|
+
rule: "JWT",
|
|
122
|
+
owasp: "API2:2023 Broken Authentication",
|
|
123
|
+
severity: "HIGH",
|
|
124
|
+
message: `jwt.verify() accepts both ${algorithms.join(" and ")}: a token signed with HS256 using the public key as the secret passes (algorithm confusion).`,
|
|
125
|
+
fix: "Accept exactly the algorithm you sign with, e.g. { algorithms: ['RS256'] }."
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
if (name === "verify" && algorithms.some(a => a.toLowerCase() === "none")) {
|
|
129
|
+
add(file, n, {
|
|
130
|
+
rule: "JWT",
|
|
131
|
+
owasp: "API2:2023 Broken Authentication",
|
|
132
|
+
severity: "HIGH",
|
|
133
|
+
message: "jwt.verify() accepts alg none, so an unsigned token passes.",
|
|
134
|
+
fix: "Remove 'none' from algorithms."
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
if (name === "verify" && isTrue(prop(options, "ignoreExpiration"))) {
|
|
138
|
+
add(file, n, {
|
|
139
|
+
rule: "JWT",
|
|
140
|
+
owasp: "API2:2023 Broken Authentication",
|
|
141
|
+
severity: "MEDIUM",
|
|
142
|
+
message: "jwt.verify() ignores expiry, so a stolen token works forever.",
|
|
143
|
+
fix: "Drop ignoreExpiration and keep access tokens short-lived."
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// res.json({ err }) / res.send(err.stack): internals in the answer
|
|
149
|
+
if (/^(send|json)$/.test(name)) {
|
|
150
|
+
let stack = null
|
|
151
|
+
let raw = false
|
|
152
|
+
for (const arg of n.arguments) {
|
|
153
|
+
walk(arg, a => {
|
|
154
|
+
if (isMemberNode(a) && a.property?.name === "stack") stack = a
|
|
155
|
+
})
|
|
156
|
+
if (arg.type === "Identifier" && ERROR_NAME.test(arg.name)) raw = true
|
|
157
|
+
if (arg.type === "ObjectExpression" && arg.properties.some(p => p.value?.type === "Identifier" && ERROR_NAME.test(p.value.name))) raw = true
|
|
158
|
+
}
|
|
159
|
+
if (stack) {
|
|
160
|
+
add(file, n, {
|
|
161
|
+
rule: "ERROR_LEAK",
|
|
162
|
+
owasp: "API8:2023 Security Misconfiguration",
|
|
163
|
+
severity: "MEDIUM",
|
|
164
|
+
message: "A stack trace goes back to the client, showing file paths, library versions and code structure.",
|
|
165
|
+
fix: "Log the stack on the server and answer with a generic message and an error id."
|
|
166
|
+
})
|
|
167
|
+
} else if (raw) {
|
|
168
|
+
rawErrors++
|
|
169
|
+
firstRawError ??= n
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
for (const { wildcard, credentials } of corsByFunction.values()) {
|
|
175
|
+
if (!wildcard) continue
|
|
176
|
+
add(file, wildcard.node, {
|
|
177
|
+
rule: "CORS",
|
|
178
|
+
owasp: "API8:2023 Security Misconfiguration",
|
|
179
|
+
severity: credentials ? "HIGH" : "LOW",
|
|
180
|
+
message: `Access-Control-Allow-Origin is ${wildcard.reflected ? "copied from the request" : "*"}${credentials ? ", with Allow-Credentials true, so any website can act as the signed-in user" : ""}.`,
|
|
181
|
+
fix: "Answer only the origins you trust."
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
if (rawErrors) {
|
|
185
|
+
add(file, firstRawError, {
|
|
186
|
+
rule: "ERROR_LEAK",
|
|
187
|
+
owasp: "API8:2023 Security Misconfiguration",
|
|
188
|
+
severity: "LOW",
|
|
189
|
+
message: `${rawErrors} response${rawErrors > 1 ? "s" : ""} in this file send a raw error object, which can carry query details, driver messages and paths.`,
|
|
190
|
+
fix: "Map errors to a fixed code and message before answering."
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (createsApp && !hasSecurityHeaders) {
|
|
196
|
+
add(createsApp.file, createsApp.node, {
|
|
197
|
+
rule: "SECURITY_HEADERS",
|
|
198
|
+
owasp: "API8:2023 Security Misconfiguration",
|
|
199
|
+
severity: "LOW",
|
|
200
|
+
message: "No helmet() or equivalent: no HSTS, nosniff or frame protection, and X-Powered-By names the framework.",
|
|
201
|
+
fix: "app.use(helmet()), or at least app.disable('x-powered-by') and the headers your clients need."
|
|
202
|
+
})
|
|
203
|
+
}
|
|
204
|
+
return findings
|
|
205
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { walk, isCallNode } from "../mapper.js"
|
|
2
|
+
import { calleeName } from "./handler.js"
|
|
3
|
+
|
|
4
|
+
// endpoints worth brute-forcing, judged on the last path segment: /auth/login, /forgot-password, /otp
|
|
5
|
+
const GUESSABLE = new Set(["login", "signin", "otp", "2fa", "mfa", "totp", "verify", "forgot", "reset", "password", "register", "signup", "auth"])
|
|
6
|
+
// "flushProjectToTpds" has "otp" in it, "loginLimit" has "login": split into words first
|
|
7
|
+
const words = segment =>
|
|
8
|
+
segment
|
|
9
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
10
|
+
.split(/[\s_.-]+/)
|
|
11
|
+
.map(w => w.toLowerCase())
|
|
12
|
+
.flatMap((w, i, all) => (all[i + 1] && ["log", "sign"].includes(w) && ["in", "up"].includes(all[i + 1]) ? [w + all[i + 1]] : [w]))
|
|
13
|
+
const CODE_CHECK = { test: segment => words(segment).some(w => ["otp", "2fa", "mfa", "totp", "verify", "code"].includes(w)) }
|
|
14
|
+
const LIMITER = /limit|throttle|slow.?down|brute|pace|lockout/i
|
|
15
|
+
// throttling done in code: signInPace.check(...), recordFailedAttempt(user)
|
|
16
|
+
const LIMITER_CALL = /rate.?limit|throttle|pace|lockout|attempts?|brute|penalt|cooldown/i
|
|
17
|
+
const DEPTH = 2
|
|
18
|
+
|
|
19
|
+
function throttlesInCode(route, fn, file, depth = 0, seen = new Set()) {
|
|
20
|
+
if (!fn || depth > DEPTH || seen.has(fn)) return false
|
|
21
|
+
seen.add(fn)
|
|
22
|
+
let found = false
|
|
23
|
+
walk(fn.body, n => {
|
|
24
|
+
if (found || !isCallNode(n)) return
|
|
25
|
+
if (LIMITER_CALL.test(calleeName(n))) found = true
|
|
26
|
+
else {
|
|
27
|
+
const target = route.resolve?.(file, n.callee)
|
|
28
|
+
if (target && throttlesInCode(route, target.fn, target.file, depth + 1, seen)) found = true
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
return found
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// API4 and API2: a credential or code can be guessed as fast as the client can send requests
|
|
35
|
+
export function rateLimit(route) {
|
|
36
|
+
if (route.method !== "POST") return null
|
|
37
|
+
const segment = route.path.split("/").filter(s => s && !/^[:{]/.test(s)).at(-1) ?? ""
|
|
38
|
+
if (!words(segment).some(w => GUESSABLE.has(w))) return null
|
|
39
|
+
// a signed-in caller setting a password is not guessing one; a code check behind a session still is
|
|
40
|
+
if (route.auth && !CODE_CHECK.test(segment)) return null
|
|
41
|
+
if (route.middleware.some(m => LIMITER.test(m))) return null
|
|
42
|
+
if (throttlesInCode(route, route.fn, route.fnPath)) return null
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
rule: "RATE_LIMIT",
|
|
46
|
+
owasp: "API4:2023 Unrestricted Resource Consumption / API2:2023 Broken Authentication",
|
|
47
|
+
severity: "MEDIUM",
|
|
48
|
+
route: `${route.method} ${route.path}`,
|
|
49
|
+
where: `${route.file}:${route.line}`,
|
|
50
|
+
message: `"${segment}" takes a password or code, and neither its middleware nor its handler limits how often it can be tried.`,
|
|
51
|
+
fix: "Add a limiter keyed on the caller and the account, e.g. express-rate-limit: router.post(path, rateLimit({ windowMs: 15 * 60 * 1000, max: 10 }), handler)."
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { walk, isCallNode } from "../mapper.js"
|
|
2
|
+
import { calleeName, calleeObject, userInput, whereOf } from "./handler.js"
|
|
3
|
+
|
|
4
|
+
const CLIENT_FN = new Set(["fetch", "axios", "got", "needle", "request", "superagent"])
|
|
5
|
+
const CLIENT_OBJ = new Set(["axios", "got", "needle", "request", "superagent", "http", "https", "undici", "ky"])
|
|
6
|
+
const CLIENT_METHOD = /^(get|post|put|patch|delete|head|request|stream)$/
|
|
7
|
+
// a check on the URL before the request: isAllowedHost(url), validateUrl(url)
|
|
8
|
+
const URL_CHECK = /allow|whitelist|safe.?url|is.?safe|validate.?url|is.?allowed|trusted|permitted/i
|
|
9
|
+
// `https://api.example.com/x?q=${input}`: the host is fixed, the client only fills a parameter
|
|
10
|
+
const FIXED_HOST = /^https?:\/\/[^/${}]+\//i
|
|
11
|
+
|
|
12
|
+
const isClientCall = n =>
|
|
13
|
+
CLIENT_FN.has(n.callee.name) || (CLIENT_OBJ.has(calleeObject(n)) && CLIENT_METHOD.test(calleeName(n)))
|
|
14
|
+
|
|
15
|
+
const isFunction = n => ["ArrowFunctionExpression", "FunctionExpression"].includes(n?.type)
|
|
16
|
+
|
|
17
|
+
function fixedHost(node, inits) {
|
|
18
|
+
const value = node?.type === "Identifier" ? inits.get(node.name) : node
|
|
19
|
+
if (value?.type === "TemplateLiteral") return FIXED_HOST.test(value.quasis[0].value.cooked)
|
|
20
|
+
if (value?.type === "BinaryExpression") return value.left.type === "StringLiteral" ? FIXED_HOST.test(value.left.value) : fixedHost(value.left, inits)
|
|
21
|
+
return false
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// API7: the server fetches a URL the client chose, so it can be pointed at internal services
|
|
25
|
+
// or the cloud metadata endpoint
|
|
26
|
+
export function ssrf(route) {
|
|
27
|
+
if (!route.fn) return null
|
|
28
|
+
const { reads, inits } = userInput(route.fn)
|
|
29
|
+
|
|
30
|
+
const hits = []
|
|
31
|
+
let checked = false
|
|
32
|
+
walk(route.fn.body, n => {
|
|
33
|
+
if (!isCallNode(n)) return
|
|
34
|
+
if (URL_CHECK.test(calleeName(n)) && n.arguments.some(reads)) checked = true
|
|
35
|
+
if (!isClientCall(n)) return
|
|
36
|
+
const tainted = n.arguments.find(a => !isFunction(a) && reads(a))
|
|
37
|
+
if (tainted) hits.push({ call: n, arg: tainted })
|
|
38
|
+
})
|
|
39
|
+
if (hits.length === 0 || checked) return null
|
|
40
|
+
|
|
41
|
+
const [hit] = hits
|
|
42
|
+
const fixed = fixedHost(hit.arg, inits)
|
|
43
|
+
const client = `${calleeObject(hit.call) ? calleeObject(hit.call) + "." : ""}${calleeName(hit.call)}`
|
|
44
|
+
return {
|
|
45
|
+
rule: "SSRF",
|
|
46
|
+
owasp: "API7:2023 Server Side Request Forgery",
|
|
47
|
+
severity: fixed ? "MEDIUM" : "HIGH",
|
|
48
|
+
route: `${route.method} ${route.path}`,
|
|
49
|
+
where: whereOf(route, hit.call.loc.start.line),
|
|
50
|
+
message: fixed
|
|
51
|
+
? `${client}() puts client input into a fixed host's URL, so the client can change the path or add parameters.`
|
|
52
|
+
: `${client}() requests a URL the client controls, so the server can be sent to internal hosts or 169.254.169.254.`,
|
|
53
|
+
fix: fixed
|
|
54
|
+
? "Encode the value (encodeURIComponent) and validate it against what the API expects."
|
|
55
|
+
: "Allow only known hosts: parse with new URL(), check url.hostname against an allow-list, and block private and link-local addresses."
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/sarif.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// SARIF 2.1.0, the format GitHub code scanning reads
|
|
2
|
+
const LEVEL = { HIGH: "error", MEDIUM: "warning", LOW: "note" }
|
|
3
|
+
// GitHub ranks alerts by this score: 7.0+ is high, 4.0+ medium
|
|
4
|
+
const SCORE = { HIGH: "8.0", MEDIUM: "5.0", LOW: "2.0" }
|
|
5
|
+
|
|
6
|
+
export function toSarif(findings, version) {
|
|
7
|
+
const rules = [...new Map(findings.map(f => [f.rule, f])).values()].map(f => ({
|
|
8
|
+
id: f.rule,
|
|
9
|
+
name: f.rule,
|
|
10
|
+
shortDescription: { text: f.owasp },
|
|
11
|
+
helpUri: "https://owasp.org/API-Security/editions/2023/en/0x11-t10/",
|
|
12
|
+
properties: { tags: ["security", "owasp-api-top-10"] }
|
|
13
|
+
}))
|
|
14
|
+
|
|
15
|
+
const results = findings.map(f => {
|
|
16
|
+
const at = f.where.lastIndexOf(":")
|
|
17
|
+
return {
|
|
18
|
+
ruleId: f.rule,
|
|
19
|
+
level: LEVEL[f.severity] ?? "warning",
|
|
20
|
+
message: { text: `${f.route}: ${f.message} Fix: ${f.fix}` },
|
|
21
|
+
locations: [
|
|
22
|
+
{
|
|
23
|
+
physicalLocation: {
|
|
24
|
+
artifactLocation: { uri: f.where.slice(0, at), uriBaseId: "%SRCROOT%" },
|
|
25
|
+
region: { startLine: Number(f.where.slice(at + 1)) }
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
],
|
|
29
|
+
// the route identifies a finding even when lines move between commits
|
|
30
|
+
partialFingerprints: { routeguardRoute: `${f.rule}:${f.route}` },
|
|
31
|
+
properties: { "security-severity": SCORE[f.severity] ?? "5.0" }
|
|
32
|
+
}
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
$schema: "https://json.schemastore.org/sarif-2.1.0.json",
|
|
37
|
+
version: "2.1.0",
|
|
38
|
+
runs: [
|
|
39
|
+
{
|
|
40
|
+
tool: { driver: { name: "routeguard", version, informationUri: "https://github.com/12keerti21/routeguard", rules } },
|
|
41
|
+
results
|
|
42
|
+
}
|
|
43
|
+
]
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/spec.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from "node:fs"
|
|
2
|
+
import path from "node:path"
|
|
3
|
+
|
|
4
|
+
const SPEC_FILE = /^(openapi|swagger)[\w.-]*\.(json|ya?ml)$/i
|
|
5
|
+
const SKIP = new Set(["node_modules", ".git", "dist", "build", "coverage"])
|
|
6
|
+
|
|
7
|
+
function findSpecs(dir, out = []) {
|
|
8
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
9
|
+
if (SKIP.has(entry.name)) continue
|
|
10
|
+
const full = path.join(dir, entry.name)
|
|
11
|
+
if (entry.isDirectory()) findSpecs(full, out)
|
|
12
|
+
else if (SPEC_FILE.test(entry.name)) out.push(full)
|
|
13
|
+
}
|
|
14
|
+
return out
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const normalise = p => p.replace(/\{\w+\}/g, ":p").replace(/:(\w+)/g, ":p").replace(/\/$/, "").toLowerCase() || "/"
|
|
18
|
+
|
|
19
|
+
// the paths an OpenAPI or Swagger file documents, read without a YAML parser:
|
|
20
|
+
// JSON through JSON.parse, YAML through the " /path:" keys under "paths:"
|
|
21
|
+
export function listSpecFiles(root) {
|
|
22
|
+
const files = findSpecs(root)
|
|
23
|
+
const paths = new Set()
|
|
24
|
+
let basePath = ""
|
|
25
|
+
for (const file of files) {
|
|
26
|
+
const text = readFileSync(file, "utf8")
|
|
27
|
+
if (file.endsWith(".json")) {
|
|
28
|
+
try {
|
|
29
|
+
const spec = JSON.parse(text)
|
|
30
|
+
Object.keys(spec.paths ?? {}).forEach(p => paths.add(normalise(p)))
|
|
31
|
+
basePath ||= spec.basePath ?? new URL(spec.servers?.[0]?.url ?? "http://x/", "http://x").pathname.replace(/\/$/, "")
|
|
32
|
+
} catch {}
|
|
33
|
+
continue
|
|
34
|
+
}
|
|
35
|
+
const block = text.split(/^paths:\s*$/m)[1]?.split(/^\S/m)[0] ?? ""
|
|
36
|
+
for (const match of block.matchAll(/^ {2}['"]?(\/[^'":\s]*)['"]?:\s*$/gm)) paths.add(normalise(match[1]))
|
|
37
|
+
basePath ||=
|
|
38
|
+
text.match(/^basePath:\s*['"]?(\/\S*?)['"]?\s*$/m)?.[1] ??
|
|
39
|
+
text.match(/^servers:\s*\n\s*-\s*url:\s*['"]?([^'"\s]+)/m)?.[1]?.replace(/^https?:\/\/[^/]+/, "") ??
|
|
40
|
+
""
|
|
41
|
+
}
|
|
42
|
+
return { files, paths, basePath }
|
|
43
|
+
}
|