eslint-plugin-express-security 1.3.4 → 1.4.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/CHANGELOG.md +43 -0
- package/README.md +39 -27
- package/package.json +24 -12
- package/src/index.js +26 -1
- package/src/rules/no-error-details-in-response/index.d.ts +57 -0
- package/src/rules/no-error-details-in-response/index.js +202 -0
- package/src/rules/no-exposed-debug-endpoints/index.js +36 -22
- package/src/rules/no-host-header-in-links/index.d.ts +56 -0
- package/src/rules/no-host-header-in-links/index.js +266 -0
- package/src/rules/no-missing-security-headers/index.js +64 -43
- package/src/rules/no-sensitive-data-in-query/index.d.ts +51 -0
- package/src/rules/no-sensitive-data-in-query/index.js +207 -0
- package/src/rules/no-static-root-exposure/index.d.ts +45 -0
- package/src/rules/no-static-root-exposure/index.js +288 -0
- package/src/rules/no-user-controlled-render-locals/index.d.ts +49 -0
- package/src/rules/no-user-controlled-render-locals/index.js +313 -0
- package/src/rules/require-case-insensitive-path-guard/index.d.ts +59 -0
- package/src/rules/require-case-insensitive-path-guard/index.js +201 -0
- package/src/rules/require-query-type-guard/index.d.ts +54 -0
- package/src/rules/require-query-type-guard/index.js +278 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
4
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
5
|
+
* MIT license that can be found in the LICENSE file.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.noUserControlledRenderLocals = void 0;
|
|
9
|
+
const eslint_devkit_1 = require("@interlace/eslint-devkit");
|
|
10
|
+
/** Request properties that carry whole user-controlled objects. */
|
|
11
|
+
const USER_SOURCE_PROPS = new Set(['body', 'query', 'params']);
|
|
12
|
+
/** Response object names (matched case-insensitively). */
|
|
13
|
+
const RESPONSE_NAMES = new Set(['res', 'response', 'reply']);
|
|
14
|
+
/** Request object names (matched case-insensitively). */
|
|
15
|
+
const REQUEST_NAMES = new Set(['req', 'request', 'ctx']);
|
|
16
|
+
exports.noUserControlledRenderLocals = (0, eslint_devkit_1.createRule)({
|
|
17
|
+
name: 'no-user-controlled-render-locals',
|
|
18
|
+
meta: {
|
|
19
|
+
type: 'problem',
|
|
20
|
+
hasSuggestions: true,
|
|
21
|
+
docs: {
|
|
22
|
+
url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-user-controlled-render-locals.md',
|
|
23
|
+
description: 'Disallow res.render() with locals or view names sourced wholesale from req.body / req.query / req.params',
|
|
24
|
+
cwe: 'CWE-73',
|
|
25
|
+
cvss: 7.3,
|
|
26
|
+
},
|
|
27
|
+
messages: {
|
|
28
|
+
unsafeRenderLocals: (0, eslint_devkit_1.formatLLMMessage)({
|
|
29
|
+
icon: eslint_devkit_1.MessageIcons.SECURITY,
|
|
30
|
+
issueName: 'Template Object Injection (CWE-73)',
|
|
31
|
+
cwe: 'CWE-73',
|
|
32
|
+
description: 'res.render() receives locals wholly controlled by {{source}}. Express merges locals into the view-engine options, so keys like "layout", "settings" or "cache" can point the engine at an attacker-chosen file.',
|
|
33
|
+
severity: 'HIGH',
|
|
34
|
+
fix: 'Pick only the fields the template needs into an explicit object literal ({ title: req.body.title }) instead of forwarding the whole request object.',
|
|
35
|
+
documentationLink: 'https://cwe.mitre.org/data/definitions/73.html',
|
|
36
|
+
}),
|
|
37
|
+
userControlledView: (0, eslint_devkit_1.formatLLMMessage)({
|
|
38
|
+
icon: eslint_devkit_1.MessageIcons.SECURITY,
|
|
39
|
+
issueName: 'User-Controlled View Path (CWE-73)',
|
|
40
|
+
cwe: 'CWE-73',
|
|
41
|
+
description: 'The view name passed to res.render() derives from {{source}}. An attacker can traverse into unintended templates or files within the views directory.',
|
|
42
|
+
severity: 'HIGH',
|
|
43
|
+
fix: 'Map user input to a fixed set of view names via an allowlist; never build the template path from request data.',
|
|
44
|
+
documentationLink: 'https://cwe.mitre.org/data/definitions/73.html',
|
|
45
|
+
}),
|
|
46
|
+
pickFieldsExplicitly: 'Remove the request-object spread and pick the required fields explicitly',
|
|
47
|
+
},
|
|
48
|
+
schema: [
|
|
49
|
+
{
|
|
50
|
+
type: 'object',
|
|
51
|
+
properties: {
|
|
52
|
+
allowSanitizers: {
|
|
53
|
+
type: 'array',
|
|
54
|
+
items: { type: 'string' },
|
|
55
|
+
description: 'Callee names that sanitize locals (e.g. ["pick", "sanitizeLocals"]); calls to them are not flagged',
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
additionalProperties: false,
|
|
59
|
+
},
|
|
60
|
+
],
|
|
61
|
+
},
|
|
62
|
+
defaultOptions: [{}],
|
|
63
|
+
create(context, [options]) {
|
|
64
|
+
const { allowSanitizers } = options;
|
|
65
|
+
const sanitizers = new Set(allowSanitizers ?? []);
|
|
66
|
+
/**
|
|
67
|
+
* Single-assignment tracking keyed by the RESOLVED scope variable, not by
|
|
68
|
+
* name — two handlers in the same file can each declare `locals`, and a
|
|
69
|
+
* name-keyed map would leak the first one's origin into the second.
|
|
70
|
+
*/
|
|
71
|
+
const trackedVars = new Map();
|
|
72
|
+
/** The scope variable an identifier resolves to, or null if unresolved. */
|
|
73
|
+
function resolveVariable(node) {
|
|
74
|
+
let scope = context.sourceCode.getScope(node);
|
|
75
|
+
while (scope) {
|
|
76
|
+
const found = scope.variables.find((v) => v.name === node.name);
|
|
77
|
+
if (found)
|
|
78
|
+
return found;
|
|
79
|
+
scope = scope.upper;
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
/** Tracked origin for an identifier, resolved through scope. */
|
|
84
|
+
function getTracked(node) {
|
|
85
|
+
const variable = resolveVariable(node);
|
|
86
|
+
return variable ? trackedVars.get(variable) : undefined;
|
|
87
|
+
}
|
|
88
|
+
function isRequestName(name) {
|
|
89
|
+
return REQUEST_NAMES.has(name.toLowerCase());
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Returns "req.<prop>" when `node` is a WHOLE user-source object access —
|
|
93
|
+
* exactly `<req>.body`, `<req>.query` or `<req>.params` (two levels).
|
|
94
|
+
* Field accesses like req.body.title are NOT whole objects.
|
|
95
|
+
*/
|
|
96
|
+
function getWholeSource(node) {
|
|
97
|
+
if (node.type !== eslint_devkit_1.AST_NODE_TYPES.MemberExpression)
|
|
98
|
+
return null;
|
|
99
|
+
const { object, property } = node;
|
|
100
|
+
if (object.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
|
|
101
|
+
return null;
|
|
102
|
+
if (property.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
|
|
103
|
+
return null;
|
|
104
|
+
// req[body] reads whatever `body` holds — not the request body.
|
|
105
|
+
if (node.computed)
|
|
106
|
+
return null;
|
|
107
|
+
if (!USER_SOURCE_PROPS.has(property.name))
|
|
108
|
+
return null;
|
|
109
|
+
if (!isRequestName(object.name))
|
|
110
|
+
return null;
|
|
111
|
+
return `req.${property.name}`;
|
|
112
|
+
}
|
|
113
|
+
/** True when the call's callee name is in the allowSanitizers option. */
|
|
114
|
+
function isSanitizerCall(node) {
|
|
115
|
+
const callee = node.callee;
|
|
116
|
+
if (callee.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
|
|
117
|
+
return sanitizers.has(callee.name);
|
|
118
|
+
}
|
|
119
|
+
if (callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
|
|
120
|
+
callee.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
|
|
121
|
+
return sanitizers.has(callee.property.name);
|
|
122
|
+
}
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Returns the origin when `node` would flow a WHOLE user-controlled
|
|
127
|
+
* object into render locals: a direct req.body/query/params access, an
|
|
128
|
+
* identifier tracked as whole, or a non-sanitizer call that forwards a
|
|
129
|
+
* whole source (transform(req.body)).
|
|
130
|
+
*/
|
|
131
|
+
function getUnsafeLocalsSource(node) {
|
|
132
|
+
const direct = getWholeSource(node);
|
|
133
|
+
if (direct)
|
|
134
|
+
return direct;
|
|
135
|
+
if (node.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
|
|
136
|
+
const tracked = getTracked(node);
|
|
137
|
+
if (tracked && tracked.whole)
|
|
138
|
+
return tracked.source;
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
if (node.type === eslint_devkit_1.AST_NODE_TYPES.CallExpression) {
|
|
142
|
+
if (isSanitizerCall(node))
|
|
143
|
+
return null;
|
|
144
|
+
for (const arg of node.arguments) {
|
|
145
|
+
const argSource = getWholeSource(arg);
|
|
146
|
+
if (argSource)
|
|
147
|
+
return argSource;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Returns the origin when `node` DERIVES from user input in any way —
|
|
154
|
+
* used for the view-name argument, where even a single field
|
|
155
|
+
* (req.params.page) enables path traversal.
|
|
156
|
+
*/
|
|
157
|
+
function getDerivedSource(node) {
|
|
158
|
+
const whole = getWholeSource(node);
|
|
159
|
+
if (whole)
|
|
160
|
+
return whole;
|
|
161
|
+
if (node.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression) {
|
|
162
|
+
return getDerivedSource(node.object);
|
|
163
|
+
}
|
|
164
|
+
if (node.type === eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral) {
|
|
165
|
+
for (const expr of node.expressions) {
|
|
166
|
+
const inner = getDerivedSource(expr);
|
|
167
|
+
if (inner)
|
|
168
|
+
return inner;
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
if (node.type === eslint_devkit_1.AST_NODE_TYPES.BinaryExpression) {
|
|
173
|
+
if (node.operator !== '+')
|
|
174
|
+
return null;
|
|
175
|
+
const left = getDerivedSource(node.left);
|
|
176
|
+
if (left)
|
|
177
|
+
return left;
|
|
178
|
+
return getDerivedSource(node.right);
|
|
179
|
+
}
|
|
180
|
+
if (node.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
|
|
181
|
+
const tracked = getTracked(node);
|
|
182
|
+
if (tracked)
|
|
183
|
+
return tracked.source;
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
/** True when `<res>.render(...)` — response ident + literal .render. */
|
|
189
|
+
function isRenderCall(node) {
|
|
190
|
+
const callee = node.callee;
|
|
191
|
+
if (callee.type !== eslint_devkit_1.AST_NODE_TYPES.MemberExpression)
|
|
192
|
+
return false;
|
|
193
|
+
if (callee.property.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
|
|
194
|
+
return false;
|
|
195
|
+
if (callee.property.name !== 'render')
|
|
196
|
+
return false;
|
|
197
|
+
const obj = callee.object;
|
|
198
|
+
if (obj.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
|
|
199
|
+
return false;
|
|
200
|
+
return RESPONSE_NAMES.has(obj.name.toLowerCase());
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Suggestion fix: delete a `...req.x` spread element (and its adjoining
|
|
204
|
+
* comma) from an object literal.
|
|
205
|
+
*/
|
|
206
|
+
function buildRemoveSpreadFix(spread) {
|
|
207
|
+
return (fixer) => {
|
|
208
|
+
const sourceCode = context.sourceCode;
|
|
209
|
+
// Inside an ObjectExpression a spread always has a token on each side
|
|
210
|
+
// ('{' or ',' before; ',' or '}' after), so these casts are safe.
|
|
211
|
+
const tokenAfter = sourceCode.getTokenAfter(spread);
|
|
212
|
+
const tokenBefore = sourceCode.getTokenBefore(spread);
|
|
213
|
+
if (tokenAfter.value === ',') {
|
|
214
|
+
return fixer.removeRange([spread.range[0], tokenAfter.range[1]]);
|
|
215
|
+
}
|
|
216
|
+
if (tokenBefore.value === ',') {
|
|
217
|
+
return fixer.removeRange([tokenBefore.range[0], spread.range[1]]);
|
|
218
|
+
}
|
|
219
|
+
return fixer.remove(spread);
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
function checkLocalsArg(node) {
|
|
223
|
+
const source = getUnsafeLocalsSource(node);
|
|
224
|
+
if (source) {
|
|
225
|
+
context.report({
|
|
226
|
+
node,
|
|
227
|
+
messageId: 'unsafeRenderLocals',
|
|
228
|
+
data: { source },
|
|
229
|
+
});
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (node.type !== eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)
|
|
233
|
+
return;
|
|
234
|
+
for (const prop of node.properties) {
|
|
235
|
+
if (prop.type !== eslint_devkit_1.AST_NODE_TYPES.SpreadElement)
|
|
236
|
+
continue;
|
|
237
|
+
const spreadSource = getUnsafeLocalsSource(prop.argument);
|
|
238
|
+
if (!spreadSource)
|
|
239
|
+
continue;
|
|
240
|
+
context.report({
|
|
241
|
+
node: prop,
|
|
242
|
+
messageId: 'unsafeRenderLocals',
|
|
243
|
+
data: { source: spreadSource },
|
|
244
|
+
suggest: [
|
|
245
|
+
{
|
|
246
|
+
messageId: 'pickFieldsExplicitly',
|
|
247
|
+
fix: buildRemoveSpreadFix(prop),
|
|
248
|
+
},
|
|
249
|
+
],
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** Records the origin of a single-assignment declaration. */
|
|
254
|
+
function trackDeclarator(declared, init) {
|
|
255
|
+
const unsafe = getUnsafeLocalsSource(init);
|
|
256
|
+
if (unsafe) {
|
|
257
|
+
trackedVars.set(declared, { source: unsafe, whole: true });
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
// const locals = { ...req.body } still carries the whole object
|
|
261
|
+
if (init.type === eslint_devkit_1.AST_NODE_TYPES.ObjectExpression) {
|
|
262
|
+
for (const prop of init.properties) {
|
|
263
|
+
if (prop.type !== eslint_devkit_1.AST_NODE_TYPES.SpreadElement)
|
|
264
|
+
continue;
|
|
265
|
+
const spreadSource = getUnsafeLocalsSource(prop.argument);
|
|
266
|
+
if (spreadSource) {
|
|
267
|
+
trackedVars.set(declared, { source: spreadSource, whole: true });
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
const derived = getDerivedSource(init);
|
|
274
|
+
if (derived) {
|
|
275
|
+
trackedVars.set(declared, { source: derived, whole: false });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
VariableDeclarator(node) {
|
|
280
|
+
// Destructuring (const { title } = req.body) IS field-picking — safe.
|
|
281
|
+
if (node.id.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
|
|
282
|
+
return;
|
|
283
|
+
const init = node.init;
|
|
284
|
+
if (!init)
|
|
285
|
+
return;
|
|
286
|
+
// Exactly one variable for an Identifier id — the loop keeps the
|
|
287
|
+
// lookup total, with no unreachable null-guard to cover.
|
|
288
|
+
for (const declared of context.sourceCode.getDeclaredVariables(node)) {
|
|
289
|
+
trackDeclarator(declared, init);
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
CallExpression(node) {
|
|
293
|
+
if (!isRenderCall(node))
|
|
294
|
+
return;
|
|
295
|
+
const viewArg = node.arguments[0];
|
|
296
|
+
if (!viewArg)
|
|
297
|
+
return;
|
|
298
|
+
const viewSource = getDerivedSource(viewArg);
|
|
299
|
+
if (viewSource) {
|
|
300
|
+
context.report({
|
|
301
|
+
node: viewArg,
|
|
302
|
+
messageId: 'userControlledView',
|
|
303
|
+
data: { source: viewSource },
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
const localsArg = node.arguments[1];
|
|
307
|
+
if (!localsArg)
|
|
308
|
+
return;
|
|
309
|
+
checkLocalsArg(localsArg);
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
},
|
|
313
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* ESLint Rule: require-case-insensitive-path-guard
|
|
8
|
+
*
|
|
9
|
+
* Detects path-based authorization guards that compare req.path / req.url /
|
|
10
|
+
* req.originalUrl case-SENSITIVELY against a protected-looking path. Express
|
|
11
|
+
* routers can match case-insensitively (`caseSensitive` defaults to false on
|
|
12
|
+
* Router, and regex routes often carry the `i` flag), so a guard that only
|
|
13
|
+
* checks `req.path.startsWith('/admin')` is bypassed by `GET /Admin/users` —
|
|
14
|
+
* the route still fires, but the authorization check never does.
|
|
15
|
+
*
|
|
16
|
+
* CWE-178: Improper Handling of Case Sensitivity
|
|
17
|
+
* OWASP A01:2021 – Broken Access Control
|
|
18
|
+
*
|
|
19
|
+
* ## Detection method: structural-api
|
|
20
|
+
*
|
|
21
|
+
* The rule fires on the AST shape of a case-sensitive comparison against a
|
|
22
|
+
* `<reqIdent>.(path|url|originalUrl)` member access:
|
|
23
|
+
*
|
|
24
|
+
* req.path.startsWith('/admin') — prefix guard
|
|
25
|
+
* req.url === '/admin' — equality guard (===, ==, !==, !=)
|
|
26
|
+
* req.path.indexOf('/admin') — index guard
|
|
27
|
+
* req.path.includes('/admin') — containment guard
|
|
28
|
+
* req.path.match(/^\/admin/) — regex guard without the `i` flag
|
|
29
|
+
*
|
|
30
|
+
* ...but ONLY when the compared value looks like a protected path (default
|
|
31
|
+
* patterns: admin, api, dashboard, internal, private — configurable via
|
|
32
|
+
* `protectedPaths`, or `checkAllPaths: true` to flag every path guard).
|
|
33
|
+
*
|
|
34
|
+
* Patterns that are NOT flagged:
|
|
35
|
+
* - `req.path.toLowerCase().startsWith('/admin')` — normalized first
|
|
36
|
+
* - `req.path.match(/^\/admin/i)` — regex already case-insensitive
|
|
37
|
+
* - `app.get('/admin', handler)` — route REGISTRATION, not a guard
|
|
38
|
+
* - `const p = req.path; p.startsWith('/admin')` — indirect via a variable
|
|
39
|
+
* (no data-flow analysis; documented false negative)
|
|
40
|
+
*
|
|
41
|
+
* @see https://cwe.mitre.org/data/definitions/178.html
|
|
42
|
+
* @see https://owasp.org/Top10/A01_2021-Broken_Access_Control/
|
|
43
|
+
*/
|
|
44
|
+
import type { TSESLint } from '@interlace/eslint-devkit';
|
|
45
|
+
type MessageIds = 'caseSensitivePathGuard' | 'addToLowerCase' | 'addIgnoreCaseFlag';
|
|
46
|
+
export interface Options {
|
|
47
|
+
/**
|
|
48
|
+
* Substrings that mark a compared value as a protected path.
|
|
49
|
+
* Default: ['admin', 'api', 'dashboard', 'internal', 'private']
|
|
50
|
+
*/
|
|
51
|
+
protectedPaths?: string[];
|
|
52
|
+
/** Flag EVERY case-sensitive path guard regardless of the compared value. Default: false */
|
|
53
|
+
checkAllPaths?: boolean;
|
|
54
|
+
}
|
|
55
|
+
type RuleOptions = [Options?];
|
|
56
|
+
export declare const requireCaseInsensitivePathGuard: TSESLint.RuleModule<MessageIds, RuleOptions, unknown, TSESLint.RuleListener> & {
|
|
57
|
+
name: string;
|
|
58
|
+
};
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
4
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
5
|
+
* MIT license that can be found in the LICENSE file.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.requireCaseInsensitivePathGuard = void 0;
|
|
9
|
+
const eslint_devkit_1 = require("@interlace/eslint-devkit");
|
|
10
|
+
/** Request properties that carry the incoming path. */
|
|
11
|
+
const PATH_PROPS = new Set(['path', 'url', 'originalUrl']);
|
|
12
|
+
/** String methods used as path guards. */
|
|
13
|
+
const GUARD_METHODS = new Set([
|
|
14
|
+
'startsWith',
|
|
15
|
+
'endsWith',
|
|
16
|
+
'includes',
|
|
17
|
+
'indexOf',
|
|
18
|
+
'match',
|
|
19
|
+
]);
|
|
20
|
+
/** Equality operators used as path guards. */
|
|
21
|
+
const EQUALITY_OPS = new Set(['===', '==', '!==', '!=']);
|
|
22
|
+
/**
|
|
23
|
+
* Lower-cases a path literal and re-quotes it for source output. Prefers the
|
|
24
|
+
* repo-idiomatic single quotes, but falls back to `JSON.stringify`'s
|
|
25
|
+
* double-quoted, fully-escaped form when the value contains a quote or
|
|
26
|
+
* backslash — naive `'${value}'` interpolation emits a syntax error there.
|
|
27
|
+
*/
|
|
28
|
+
function quoteLiteral(value) {
|
|
29
|
+
const json = JSON.stringify(value.toLowerCase());
|
|
30
|
+
const inner = json.slice(1, -1);
|
|
31
|
+
return /['\\]/.test(inner) ? json : `'${inner}'`;
|
|
32
|
+
}
|
|
33
|
+
const DEFAULT_PROTECTED_PATHS = [
|
|
34
|
+
'admin',
|
|
35
|
+
'api',
|
|
36
|
+
'dashboard',
|
|
37
|
+
'internal',
|
|
38
|
+
'private',
|
|
39
|
+
];
|
|
40
|
+
exports.requireCaseInsensitivePathGuard = (0, eslint_devkit_1.createRule)({
|
|
41
|
+
name: 'require-case-insensitive-path-guard',
|
|
42
|
+
meta: {
|
|
43
|
+
type: 'problem',
|
|
44
|
+
hasSuggestions: true,
|
|
45
|
+
docs: {
|
|
46
|
+
url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-case-insensitive-path-guard.md',
|
|
47
|
+
description: 'Require case-insensitive comparison when guarding protected paths via req.path / req.url / req.originalUrl',
|
|
48
|
+
cwe: 'CWE-178',
|
|
49
|
+
cvss: 7.3,
|
|
50
|
+
},
|
|
51
|
+
messages: {
|
|
52
|
+
caseSensitivePathGuard: (0, eslint_devkit_1.formatLLMMessage)({
|
|
53
|
+
icon: eslint_devkit_1.MessageIcons.SECURITY,
|
|
54
|
+
issueName: 'Case-Sensitive Path Guard (CWE-178)',
|
|
55
|
+
cwe: 'CWE-178',
|
|
56
|
+
description: "{{pathExpr}} is compared case-sensitively against '{{value}}', but Express routes can match case-insensitively. A request to an upper-cased variant (e.g. /Admin) reaches the handler without ever hitting this guard.",
|
|
57
|
+
severity: 'HIGH',
|
|
58
|
+
fix: 'Normalize the path with .toLowerCase() before comparing (and lower-case the compared literal), or add the /i flag to the guard regex.',
|
|
59
|
+
documentationLink: 'https://cwe.mitre.org/data/definitions/178.html',
|
|
60
|
+
}),
|
|
61
|
+
addToLowerCase: 'Normalize with .toLowerCase() before comparing',
|
|
62
|
+
addIgnoreCaseFlag: 'Add the i flag to the guard regex',
|
|
63
|
+
},
|
|
64
|
+
schema: [
|
|
65
|
+
{
|
|
66
|
+
type: 'object',
|
|
67
|
+
properties: {
|
|
68
|
+
protectedPaths: {
|
|
69
|
+
type: 'array',
|
|
70
|
+
items: { type: 'string' },
|
|
71
|
+
description: 'Substrings that mark a compared value as a protected path',
|
|
72
|
+
},
|
|
73
|
+
checkAllPaths: {
|
|
74
|
+
type: 'boolean',
|
|
75
|
+
description: 'Flag every case-sensitive path guard regardless of the compared value',
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
additionalProperties: false,
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
},
|
|
82
|
+
defaultOptions: [{}],
|
|
83
|
+
create(context, [options]) {
|
|
84
|
+
const { protectedPaths, checkAllPaths } = options;
|
|
85
|
+
const patterns = (protectedPaths ?? DEFAULT_PROTECTED_PATHS).map((p) => p.toLowerCase());
|
|
86
|
+
const flagAll = checkAllPaths ?? false;
|
|
87
|
+
const sourceCode = context.sourceCode;
|
|
88
|
+
function isRequestIdent(name) {
|
|
89
|
+
const lower = name.toLowerCase();
|
|
90
|
+
return lower === 'req' || lower === 'request';
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* `req.path`, `request.url`, `req.originalUrl` — a direct, non-computed
|
|
94
|
+
* member access on a request identifier.
|
|
95
|
+
*/
|
|
96
|
+
function isPathAccess(node) {
|
|
97
|
+
return (node.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
|
|
98
|
+
!node.computed &&
|
|
99
|
+
node.object.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
|
|
100
|
+
isRequestIdent(node.object.name) &&
|
|
101
|
+
node.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
|
|
102
|
+
PATH_PROPS.has(node.property.name));
|
|
103
|
+
}
|
|
104
|
+
function isProtectedValue(value) {
|
|
105
|
+
if (flagAll)
|
|
106
|
+
return true;
|
|
107
|
+
const lower = value.toLowerCase();
|
|
108
|
+
return patterns.some((p) => lower.includes(p));
|
|
109
|
+
}
|
|
110
|
+
function isStringLiteral(node) {
|
|
111
|
+
return (node.type === eslint_devkit_1.AST_NODE_TYPES.Literal && typeof node.value === 'string');
|
|
112
|
+
}
|
|
113
|
+
function reportWithLowerCaseSuggestion(node, pathNode, literalNode) {
|
|
114
|
+
const value = literalNode.value;
|
|
115
|
+
context.report({
|
|
116
|
+
node,
|
|
117
|
+
messageId: 'caseSensitivePathGuard',
|
|
118
|
+
data: { pathExpr: sourceCode.getText(pathNode), value },
|
|
119
|
+
suggest: [
|
|
120
|
+
{
|
|
121
|
+
messageId: 'addToLowerCase',
|
|
122
|
+
fix(fixer) {
|
|
123
|
+
const fixes = [fixer.insertTextAfter(pathNode, '.toLowerCase()')];
|
|
124
|
+
if (/[A-Z]/.test(value)) {
|
|
125
|
+
fixes.push(fixer.replaceText(literalNode, quoteLiteral(value)));
|
|
126
|
+
}
|
|
127
|
+
return fixes;
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
],
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
CallExpression(node) {
|
|
135
|
+
const callee = node.callee;
|
|
136
|
+
if (callee.type !== eslint_devkit_1.AST_NODE_TYPES.MemberExpression)
|
|
137
|
+
return;
|
|
138
|
+
if (callee.property.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
|
|
139
|
+
return;
|
|
140
|
+
if (!GUARD_METHODS.has(callee.property.name))
|
|
141
|
+
return;
|
|
142
|
+
// Route registrations (app.get('/admin', ...)) never match here:
|
|
143
|
+
// the object must be a req.path-style access, not an app/router object.
|
|
144
|
+
if (!isPathAccess(callee.object))
|
|
145
|
+
return;
|
|
146
|
+
const arg = node.arguments[0];
|
|
147
|
+
if (!arg)
|
|
148
|
+
return;
|
|
149
|
+
if (arg.type !== eslint_devkit_1.AST_NODE_TYPES.Literal)
|
|
150
|
+
return;
|
|
151
|
+
// req.path.match(/^\/admin/) — regex literal guard
|
|
152
|
+
if ('regex' in arg) {
|
|
153
|
+
if (arg.regex.flags.includes('i'))
|
|
154
|
+
return;
|
|
155
|
+
if (!isProtectedValue(arg.regex.pattern))
|
|
156
|
+
return;
|
|
157
|
+
context.report({
|
|
158
|
+
node,
|
|
159
|
+
messageId: 'caseSensitivePathGuard',
|
|
160
|
+
data: {
|
|
161
|
+
pathExpr: sourceCode.getText(callee.object),
|
|
162
|
+
value: arg.regex.pattern,
|
|
163
|
+
},
|
|
164
|
+
suggest: [
|
|
165
|
+
{
|
|
166
|
+
messageId: 'addIgnoreCaseFlag',
|
|
167
|
+
fix: (fixer) => fixer.insertTextAfter(arg, 'i'),
|
|
168
|
+
},
|
|
169
|
+
],
|
|
170
|
+
});
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (typeof arg.value !== 'string')
|
|
174
|
+
return;
|
|
175
|
+
if (!isProtectedValue(arg.value))
|
|
176
|
+
return;
|
|
177
|
+
reportWithLowerCaseSuggestion(node, callee.object, arg);
|
|
178
|
+
},
|
|
179
|
+
BinaryExpression(node) {
|
|
180
|
+
if (!EQUALITY_OPS.has(node.operator))
|
|
181
|
+
return;
|
|
182
|
+
let pathNode;
|
|
183
|
+
let literalNode;
|
|
184
|
+
if (isPathAccess(node.left) && isStringLiteral(node.right)) {
|
|
185
|
+
pathNode = node.left;
|
|
186
|
+
literalNode = node.right;
|
|
187
|
+
}
|
|
188
|
+
else if (isPathAccess(node.right) && isStringLiteral(node.left)) {
|
|
189
|
+
pathNode = node.right;
|
|
190
|
+
literalNode = node.left;
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (!isProtectedValue(literalNode.value))
|
|
196
|
+
return;
|
|
197
|
+
reportWithLowerCaseSuggestion(node, pathNode, literalNode);
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
},
|
|
201
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* ESLint Rule: require-query-type-guard
|
|
8
|
+
*
|
|
9
|
+
* Detects string methods called on `req.query` values without a preceding
|
|
10
|
+
* type guard. Express's qs parser yields `string | string[] | ParsedQs`:
|
|
11
|
+
* `?name=a&name=b` produces an array and `?name[$ne]=` produces an object,
|
|
12
|
+
* so `req.query.name.replace(...)` throws (DoS) or silently bypasses
|
|
13
|
+
* sanitization when an attacker shapes the query string.
|
|
14
|
+
*
|
|
15
|
+
* CWE-843: Access of Resource Using Incompatible Type ('Type Confusion')
|
|
16
|
+
* OWASP A03:2021 – Injection
|
|
17
|
+
*
|
|
18
|
+
* ## Detection method: structural-api
|
|
19
|
+
*
|
|
20
|
+
* Two shapes are flagged:
|
|
21
|
+
*
|
|
22
|
+
* 1. Direct member calls — `req.query.name.replace(...)`,
|
|
23
|
+
* `req.query['x'].trim()`.
|
|
24
|
+
* 2. Calls on identifiers whose most recent assignment was a raw
|
|
25
|
+
* `req.query` member — `const term = req.query.name; term.trim()`.
|
|
26
|
+
*
|
|
27
|
+
* A value is considered guarded (NOT flagged) after any of:
|
|
28
|
+
* - `typeof v === 'string'` (any of === / == / !== / !=, either operand order)
|
|
29
|
+
* - `Array.isArray(v)`
|
|
30
|
+
* - coercion at the source: `const v = String(req.query.name)` (never
|
|
31
|
+
* tracked — the coercer call is the init, not the raw member)
|
|
32
|
+
* - re-assignment through a coercer/validator: `v = String(v)`,
|
|
33
|
+
* `v = schema.parse(v)` (configurable via `coercers` / `validators`)
|
|
34
|
+
*
|
|
35
|
+
* Guards are scoped per enclosing function (nested closures see outer
|
|
36
|
+
* guards). The rule does no cross-function data-flow: query values passed
|
|
37
|
+
* as call arguments are a documented false negative.
|
|
38
|
+
*
|
|
39
|
+
* @see https://cwe.mitre.org/data/definitions/843.html
|
|
40
|
+
* @see https://owasp.org/Top10/A03_2021-Injection/
|
|
41
|
+
*/
|
|
42
|
+
import type { TSESLint } from '@interlace/eslint-devkit';
|
|
43
|
+
type MessageIds = 'unguardedQueryStringMethod' | 'wrapString' | 'coerceAtAssignment';
|
|
44
|
+
export interface Options {
|
|
45
|
+
/** Callee names whose result is a safe string coercion. Default: ['String'] */
|
|
46
|
+
coercers?: string[];
|
|
47
|
+
/** Callee / method names treated as type-safe sources. Default: ['parse', 'safeParse'] */
|
|
48
|
+
validators?: string[];
|
|
49
|
+
}
|
|
50
|
+
type RuleOptions = [Options?];
|
|
51
|
+
export declare const requireQueryTypeGuard: TSESLint.RuleModule<MessageIds, RuleOptions, unknown, TSESLint.RuleListener> & {
|
|
52
|
+
name: string;
|
|
53
|
+
};
|
|
54
|
+
export {};
|