eslint-plugin-secure-coding 3.4.3 → 3.4.4

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.
Files changed (32) hide show
  1. package/package.json +2 -2
  2. package/src/index.js +1 -107
  3. package/src/oxlint.js +1 -3
  4. package/src/rules/detect-non-literal-regexp/index.js +1 -329
  5. package/src/rules/detect-object-injection/index.js +1 -691
  6. package/src/rules/detect-weak-password-validation/index.js +1 -54
  7. package/src/rules/no-directive-injection/index.js +1 -416
  8. package/src/rules/no-electron-security-issues/index.js +1 -385
  9. package/src/rules/no-format-string-injection/index.js +1 -565
  10. package/src/rules/no-graphql-injection/index.js +1 -612
  11. package/src/rules/no-hardcoded-credentials/index.js +1 -658
  12. package/src/rules/no-hardcoded-session-tokens/index.js +1 -56
  13. package/src/rules/no-improper-sanitization/index.js +1 -391
  14. package/src/rules/no-improper-type-validation/index.js +1 -422
  15. package/src/rules/no-insecure-comparison/index.js +1 -249
  16. package/src/rules/no-ldap-injection/index.js +1 -403
  17. package/src/rules/no-missing-authentication/index.js +1 -282
  18. package/src/rules/no-pii-in-logs/index.js +1 -63
  19. package/src/rules/no-privilege-escalation/index.js +1 -282
  20. package/src/rules/no-redos-vulnerable-regex/index.js +0 -0
  21. package/src/rules/no-sensitive-data-exposure/index.js +1 -249
  22. package/src/rules/no-template-injection/index.js +1 -84
  23. package/src/rules/no-unchecked-loop-condition/index.js +1 -541
  24. package/src/rules/no-unlimited-resource-allocation/index.js +1 -555
  25. package/src/rules/no-unsafe-deserialization/index.js +1 -497
  26. package/src/rules/no-unsafe-regex-construction/index.js +1 -275
  27. package/src/rules/no-weak-password-recovery/index.js +1 -382
  28. package/src/rules/no-xpath-injection/index.js +1 -431
  29. package/src/rules/no-xxe-injection/index.js +1 -230
  30. package/src/rules/require-backend-authorization/index.js +1 -58
  31. package/src/rules/require-secure-defaults/index.js +1 -41
  32. package/src/types/index.js +1 -2
@@ -1,565 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.noFormatStringInjection = void 0;
4
- const eslint_devkit_1 = require("@interlace/eslint-devkit");
5
- const eslint_devkit_2 = require("@interlace/eslint-devkit");
6
- exports.noFormatStringInjection = (0, eslint_devkit_1.createRule)({
7
- name: 'no-format-string-injection',
8
- meta: {
9
- type: 'problem',
10
- docs: {
11
- url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-format-string-injection.md',
12
- description: 'Detects format string injection vulnerabilities',
13
- cwe: 'CWE-134',
14
- },
15
- fixable: 'code',
16
- hasSuggestions: true,
17
- messages: {
18
- formatStringInjection: (0, eslint_devkit_2.formatLLMMessage)({
19
- icon: eslint_devkit_2.MessageIcons.SECURITY,
20
- issueName: 'Format String Injection',
21
- cwe: 'CWE-134',
22
- description: 'Format string controlled by user input',
23
- severity: '{{severity}}',
24
- fix: '{{safeAlternative}}',
25
- documentationLink: 'https://cwe.mitre.org/data/definitions/134.html',
26
- }),
27
- unsafeFormatSpecifier: (0, eslint_devkit_2.formatLLMMessage)({
28
- icon: eslint_devkit_2.MessageIcons.SECURITY,
29
- issueName: 'Unsafe Format Specifier',
30
- cwe: 'CWE-134',
31
- description: 'User input may contain format specifiers',
32
- severity: 'MEDIUM',
33
- fix: 'Escape or validate user input before formatting',
34
- documentationLink: 'https://cwe.mitre.org/data/definitions/134.html',
35
- }),
36
- userControlledFormatString: (0, eslint_devkit_2.formatLLMMessage)({
37
- icon: eslint_devkit_2.MessageIcons.SECURITY,
38
- issueName: 'User Controlled Format String',
39
- cwe: 'CWE-134',
40
- description: 'Format string parameter comes from user input',
41
- severity: 'CRITICAL',
42
- fix: 'Use hardcoded format strings or validate user formats',
43
- documentationLink: 'https://cwe.mitre.org/data/definitions/134.html',
44
- }),
45
- missingFormatValidation: (0, eslint_devkit_2.formatLLMMessage)({
46
- icon: eslint_devkit_2.MessageIcons.SECURITY,
47
- issueName: 'Missing Format Validation',
48
- cwe: 'CWE-134',
49
- description: 'Format string not validated before use',
50
- severity: 'HIGH',
51
- fix: 'Validate format strings against allowed patterns',
52
- documentationLink: 'https://cwe.mitre.org/data/definitions/134.html',
53
- }),
54
- escapeFormatString: (0, eslint_devkit_2.formatLLMMessage)({
55
- icon: eslint_devkit_2.MessageIcons.INFO,
56
- issueName: 'Escape Format String',
57
- description: 'Escape format specifiers in user input',
58
- severity: 'LOW',
59
- fix: 'Replace % with %% in user input',
60
- documentationLink: 'https://nodejs.org/api/util.html#utilformatformat-args',
61
- }),
62
- useSafeFormatting: (0, eslint_devkit_2.formatLLMMessage)({
63
- icon: eslint_devkit_2.MessageIcons.INFO,
64
- issueName: 'Use Safe Formatting',
65
- description: 'Use safe string formatting methods',
66
- severity: 'LOW',
67
- fix: 'Use template literals or safe format libraries',
68
- documentationLink: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals',
69
- })
70
- },
71
- schema: [
72
- {
73
- type: 'object',
74
- properties: {
75
- formatFunctions: {
76
- type: 'array',
77
- items: { type: 'string' },
78
- default: ['util.format', 'console.log', 'console.error', 'console.warn', 'sprintf', 'printf', 'vsprintf'], description: 'Functions whose first argument is a format string'
79
- },
80
- formatSpecifiers: {
81
- type: 'array',
82
- items: { type: 'string' },
83
- default: ['%s', '%d', '%i', '%f', '%j', '%o', '%O', '%c', '%%'], description: 'Format specifiers recognised in a format string'
84
- },
85
- userInputVariables: {
86
- type: 'array',
87
- items: { type: 'string' },
88
- default: ['req', 'request', 'body', 'query', 'params', 'input', 'data', 'userInput'], description: 'Variable names treated as user-controlled input'
89
- },
90
- safeFormatLibraries: {
91
- type: 'array',
92
- items: { type: 'string' },
93
- default: ['mustache', 'handlebars', 'ejs', 'pug'], description: 'Templating libraries that escape their own input'
94
- },
95
- trustedSanitizers: {
96
- type: 'array',
97
- items: { type: 'string' },
98
- default: [],
99
- description: 'Additional function names to consider as format string sanitizers',
100
- },
101
- trustedAnnotations: {
102
- type: 'array',
103
- items: { type: 'string' },
104
- default: [],
105
- description: 'Additional JSDoc annotations to consider as safe markers',
106
- },
107
- strictMode: {
108
- type: 'boolean',
109
- default: false,
110
- description: 'Disable all false positive detection (strict mode)',
111
- },
112
- },
113
- additionalProperties: false,
114
- },
115
- ],
116
- },
117
- defaultOptions: [
118
- {
119
- formatFunctions: ['util.format', 'console.log', 'console.error', 'console.warn', 'sprintf', 'printf', 'vsprintf'],
120
- formatSpecifiers: ['%s', '%d', '%i', '%f', '%j', '%o', '%O', '%c', '%%'],
121
- userInputVariables: ['req', 'request', 'body', 'query', 'params', 'input', 'data', 'userInput'],
122
- safeFormatLibraries: ['mustache', 'handlebars', 'ejs', 'pug'],
123
- trustedSanitizers: ['validateFormat', 'sanitizeFormat', 'escapeFormat', 'cleanFormat', 'sanitizeFormatString', 'validate', 'sanitize', 'escape', 'clean'],
124
- trustedAnnotations: [],
125
- strictMode: false,
126
- },
127
- ],
128
- create(context) {
129
- const defaultOptions = {
130
- formatFunctions: ['util.format', 'console.log', 'console.error', 'console.warn', 'sprintf', 'printf', 'vsprintf'],
131
- formatSpecifiers: ['%s', '%d', '%i', '%f', '%j', '%o', '%O', '%c', '%%'],
132
- userInputVariables: ['req', 'request', 'body', 'query', 'params', 'input', 'data', 'userInput'],
133
- safeFormatLibraries: ['mustache', 'handlebars', 'ejs', 'pug'],
134
- trustedSanitizers: ['validateFormat', 'sanitizeFormat', 'escapeFormat', 'cleanFormat', 'sanitizeFormatString', 'validate', 'sanitize', 'escape', 'clean'],
135
- trustedAnnotations: [],
136
- strictMode: false,
137
- };
138
- const options = { ...defaultOptions, ...context.options[0] };
139
- const { formatSpecifiers, userInputVariables, trustedSanitizers, } = options;
140
- const filename = context.filename;
141
- const safetyChecker = {
142
- isSafe: (safeNode, ruleCtx) => {
143
- const comments = ruleCtx.sourceCode.getCommentsBefore(safeNode);
144
- for (const comment of comments) {
145
- if (comment.type === 'Block' && comment.value.includes('@safe-format')) {
146
- return true;
147
- }
148
- }
149
- if (safeNode.type === 'CallExpression' && safeNode.arguments.length > 0) {
150
- const firstArg = safeNode.arguments[0];
151
- if (firstArg.type === 'Identifier' && validatedVariables.has(firstArg.name)) {
152
- return true;
153
- }
154
- }
155
- return false;
156
- }
157
- };
158
- const isUserInput = (varName) => {
159
- const lowerName = varName.toLowerCase();
160
- return userInputVariables.some(input => lowerName.includes(input.toLowerCase())) ||
161
- lowerName === 'user' ||
162
- lowerName.includes('userinput') ||
163
- lowerName.includes('userdata') ||
164
- lowerName.includes('userparam') ||
165
- lowerName.includes('usermessage') ||
166
- lowerName.includes('usertemplate') ||
167
- lowerName.includes('userformat') ||
168
- lowerName.includes('uservar');
169
- };
170
- const isUserInputNode = (node) => {
171
- if (node.type === 'Identifier') {
172
- return isUserInput(node.name) || dangerousVariables.has(node.name);
173
- }
174
- if (node.type === 'MemberExpression') {
175
- if (node.object.type === 'MemberExpression' &&
176
- node.object.object.type === 'Identifier' &&
177
- node.object.object.name === 'req' &&
178
- node.object.property.type === 'Identifier' &&
179
- ['query', 'body', 'params', 'param'].includes(node.object.property.name)) {
180
- return true;
181
- }
182
- if (node.object.type === 'Identifier' && node.object.name === 'req') {
183
- return true;
184
- }
185
- const fullName = getMemberExpressionName(node);
186
- return isUserInput(fullName);
187
- }
188
- return false;
189
- };
190
- const getMemberExpressionName = (node) => {
191
- if (node.object.type === 'Identifier') {
192
- if (node.property.type === 'Identifier') {
193
- return `${node.object.name}.${node.property.name}`;
194
- }
195
- }
196
- else if (node.object.type === 'MemberExpression') {
197
- const objectName = getMemberExpressionName(node.object);
198
- if (node.property.type === 'Identifier') {
199
- return `${objectName}.${node.property.name}`;
200
- }
201
- }
202
- return '';
203
- };
204
- const containsFormatSpecifiers = (text) => {
205
- return formatSpecifiers.some(specifier => text.includes(specifier));
206
- };
207
- const isConsoleMethod = (node) => {
208
- const callee = node.callee;
209
- return callee.type === 'MemberExpression' &&
210
- callee.object.type === 'Identifier' &&
211
- callee.object.name === 'console' &&
212
- callee.property.type === 'Identifier' &&
213
- ['log', 'error', 'warn', 'info', 'debug'].includes(callee.property.name);
214
- };
215
- const isFormatFunctionCall = (node) => {
216
- const callee = node.callee;
217
- if (callee.type === 'MemberExpression' &&
218
- callee.object.type === 'Identifier' &&
219
- callee.object.name === 'util' &&
220
- callee.property.type === 'Identifier' &&
221
- callee.property.name === 'format') {
222
- return true;
223
- }
224
- if (callee.type === 'MemberExpression' &&
225
- callee.object.type === 'Identifier' &&
226
- callee.object.name === 'console' &&
227
- callee.property.type === 'Identifier' &&
228
- ['log', 'error', 'warn', 'info', 'debug'].includes(callee.property.name)) {
229
- return true;
230
- }
231
- if (callee.type === 'Identifier' &&
232
- ['sprintf', 'printf', 'vsprintf'].includes(callee.name)) {
233
- return true;
234
- }
235
- return false;
236
- };
237
- const validatedVariables = new Set();
238
- const dangerousVariables = new Set();
239
- const isInputValidated = (inputNode) => {
240
- if (inputNode.type === 'Identifier' && validatedVariables.has(inputNode.name)) {
241
- return true;
242
- }
243
- let current = inputNode;
244
- while (current) {
245
- if (current.type === 'CallExpression' &&
246
- current.callee.type === 'Identifier' &&
247
- trustedSanitizers.includes(current.callee.name)) {
248
- return true;
249
- }
250
- current = current.parent;
251
- }
252
- return false;
253
- };
254
- const hasFormatSpecifiers = (node) => {
255
- if (typeof node.value !== 'string') {
256
- return false;
257
- }
258
- return containsFormatSpecifiers(node.value);
259
- };
260
- function containsFormatSpecifiersInExpression(expr) {
261
- if (expr.left.type === 'Literal' && typeof expr.left.value === 'string' && containsFormatSpecifiers(expr.left.value)) {
262
- return true;
263
- }
264
- if (expr.right.type === 'Literal' && typeof expr.right.value === 'string' && containsFormatSpecifiers(expr.right.value)) {
265
- return true;
266
- }
267
- if (expr.left.type === 'BinaryExpression' && containsFormatSpecifiersInExpression(expr.left)) {
268
- return true;
269
- }
270
- if (expr.right.type === 'BinaryExpression' && containsFormatSpecifiersInExpression(expr.right)) {
271
- return true;
272
- }
273
- return false;
274
- }
275
- function hasUserInputInExpression(expr) {
276
- if (isUserInputNode(expr.left)) {
277
- return true;
278
- }
279
- if (isUserInputNode(expr.right)) {
280
- return true;
281
- }
282
- if (expr.left.type === 'BinaryExpression' && hasUserInputInExpression(expr.left)) {
283
- return true;
284
- }
285
- if (expr.right.type === 'BinaryExpression' && hasUserInputInExpression(expr.right)) {
286
- return true;
287
- }
288
- return false;
289
- }
290
- return {
291
- CallExpression: function (node) {
292
- if (!isFormatFunctionCall(node)) {
293
- return;
294
- }
295
- const args = node.arguments;
296
- if (args.length === 0) {
297
- return;
298
- }
299
- const formatArg = args[0];
300
- const isFormatFromUserInput = isUserInputNode(formatArg) ||
301
- (formatArg.type === 'Identifier' && dangerousVariables.has(formatArg.name)) ||
302
- (formatArg.type === 'BinaryExpression' && hasUserInputInExpression(formatArg));
303
- if (isFormatFromUserInput && !isConsoleMethod(node)) {
304
- if (safetyChecker.isSafe(node, context)) {
305
- return;
306
- }
307
- context.report({
308
- node: formatArg,
309
- messageId: 'userControlledFormatString',
310
- data: {
311
- filePath: filename,
312
- line: String(node.loc?.start.line ?? 0),
313
- },
314
- });
315
- return;
316
- }
317
- if (formatArg.type === 'TemplateLiteral') {
318
- const hasUserInput = formatArg.expressions.some((expr) => isUserInputNode(expr));
319
- if (hasUserInput) {
320
- if (safetyChecker.isSafe(node, context)) {
321
- return;
322
- }
323
- context.report({
324
- node: formatArg,
325
- messageId: 'formatStringInjection',
326
- data: {
327
- filePath: filename,
328
- line: String(node.loc?.start.line ?? 0),
329
- severity: 'HIGH',
330
- safeAlternative: 'Use hardcoded format strings or validate template input',
331
- },
332
- });
333
- return;
334
- }
335
- }
336
- else if (formatArg.type === 'BinaryExpression' && formatArg.operator === '+') {
337
- const hasUserInput = hasUserInputInExpression(formatArg);
338
- if (hasUserInput) {
339
- if (safetyChecker.isSafe(node, context)) {
340
- return;
341
- }
342
- context.report({
343
- node: formatArg,
344
- messageId: 'formatStringInjection',
345
- data: {
346
- filePath: filename,
347
- line: String(node.loc?.start.line ?? 0),
348
- severity: 'HIGH',
349
- safeAlternative: 'Separate user input from format strings',
350
- },
351
- });
352
- return;
353
- }
354
- }
355
- const fmtArg = args[0];
356
- const isFormatSafe = isInputValidated(fmtArg) ||
357
- (fmtArg.type === 'Identifier' && validatedVariables.has(fmtArg.name));
358
- if (!isFormatSafe) {
359
- let hasUserInputInArgs = false;
360
- let hasSpecifiersInFormat = false;
361
- for (let i = 1; i < args.length; i++) {
362
- const arg = args[i];
363
- if (isUserInputNode(arg) && !isInputValidated(arg)) {
364
- hasUserInputInArgs = true;
365
- break;
366
- }
367
- }
368
- const firstArg = args[0];
369
- if (firstArg.type === 'Literal' && typeof firstArg.value === 'string') {
370
- if (containsFormatSpecifiers(firstArg.value)) {
371
- hasSpecifiersInFormat = true;
372
- }
373
- }
374
- else if (firstArg.type === 'Identifier') {
375
- const varName = firstArg.name.toLowerCase();
376
- if (varName.includes('format') || varName.includes('template') || varName.includes('pattern')) {
377
- hasSpecifiersInFormat = true;
378
- }
379
- }
380
- if (!hasSpecifiersInFormat && args.length === 2 && isConsoleMethod(node)) {
381
- }
382
- else if (hasSpecifiersInFormat && hasUserInputInArgs) {
383
- if (safetyChecker.isSafe(node, context)) {
384
- return;
385
- }
386
- const messageId = firstArg.type === 'Literal' ? 'unsafeFormatSpecifier' : 'missingFormatValidation';
387
- context.report({
388
- node: node,
389
- messageId,
390
- data: {
391
- filePath: filename,
392
- line: String(node.loc?.start.line ?? 0),
393
- },
394
- suggest: [
395
- {
396
- messageId: 'escapeFormatString',
397
- fix: (fixer) => {
398
- const arg = node.arguments.slice(1).find(a => isUserInputNode(a));
399
- return fixer.insertTextAfter(arg, '.replace(/%/g, "%%")');
400
- },
401
- },
402
- ],
403
- });
404
- }
405
- }
406
- },
407
- Literal: function (node) {
408
- if (!hasFormatSpecifiers(node)) {
409
- return;
410
- }
411
- const text = node.value;
412
- let current = node;
413
- let isFromUserInput = false;
414
- while (current) {
415
- if (current.type === 'BinaryExpression' &&
416
- current.operator === '+' &&
417
- (current.left === node || current.right === node)) {
418
- const otherSide = current.left === node ? current.right : current.left;
419
- if (otherSide.type === 'Identifier' && isUserInput(otherSide.name)) {
420
- isFromUserInput = true;
421
- break;
422
- }
423
- }
424
- if (current.type === 'VariableDeclarator' &&
425
- current.init === node.parent &&
426
- current.id.type === 'Identifier') {
427
- if (isUserInput(current.id.name)) {
428
- isFromUserInput = true;
429
- break;
430
- }
431
- }
432
- current = current.parent;
433
- }
434
- if (!isFromUserInput) {
435
- return;
436
- }
437
- current = node;
438
- let isInDangerousContext = false;
439
- while (current) {
440
- if (current.type === 'CallExpression' && isFormatFunctionCall(current)) {
441
- const args = current.arguments;
442
- if (args.length > 0 && args[0] === node) {
443
- isInDangerousContext = true;
444
- break;
445
- }
446
- }
447
- current = current.parent;
448
- }
449
- if (isInDangerousContext && containsFormatSpecifiers(text)) {
450
- if (safetyChecker.isSafe(node, context)) {
451
- return;
452
- }
453
- context.report({
454
- node,
455
- messageId: 'missingFormatValidation',
456
- data: {
457
- filePath: filename,
458
- line: String(node.loc?.start.line ?? 0),
459
- },
460
- });
461
- }
462
- },
463
- TemplateLiteral: function (node) {
464
- let templateCurrent = node;
465
- let isFormatString = false;
466
- while (templateCurrent) {
467
- if (templateCurrent.type === 'CallExpression' && isFormatFunctionCall(templateCurrent)) {
468
- const args = templateCurrent.arguments;
469
- if (args.length > 0 && args[0] === node) {
470
- isFormatString = true;
471
- break;
472
- }
473
- }
474
- templateCurrent = templateCurrent.parent;
475
- }
476
- if (isFormatString) {
477
- return;
478
- }
479
- const hasUserInput = node.expressions.some((expr) => isUserInputNode(expr));
480
- if (hasUserInput) {
481
- let assignCurrent = node;
482
- let isAssignedToVariable = false;
483
- while (assignCurrent) {
484
- if (assignCurrent.type === 'VariableDeclarator') {
485
- isAssignedToVariable = true;
486
- break;
487
- }
488
- assignCurrent = assignCurrent.parent;
489
- }
490
- if (isAssignedToVariable) {
491
- if (safetyChecker.isSafe(node, context)) {
492
- return;
493
- }
494
- context.report({
495
- node,
496
- messageId: 'formatStringInjection',
497
- data: {
498
- filePath: filename,
499
- line: String(node.loc?.start.line ?? 0),
500
- severity: 'HIGH',
501
- safeAlternative: 'Extract user input from template and validate separately',
502
- },
503
- });
504
- }
505
- }
506
- },
507
- VariableDeclarator: function (node) {
508
- if (!node.init || node.id.type !== 'Identifier') {
509
- return;
510
- }
511
- const varName = node.id.name;
512
- if (node.init.type === 'CallExpression' &&
513
- node.init.callee.type === 'Identifier' &&
514
- trustedSanitizers.includes(node.init.callee.name)) {
515
- validatedVariables.add(varName);
516
- }
517
- if (isUserInputNode(node.init) || (node.init.type === 'BinaryExpression' && hasUserInputInExpression(node.init))) {
518
- dangerousVariables.add(varName);
519
- }
520
- const varNameLower = varName.toLowerCase();
521
- if (!varNameLower.includes('format') && !varNameLower.includes('template') && !varNameLower.includes('fmt') && !varNameLower.includes('str')) {
522
- return;
523
- }
524
- if (node.init.type === 'TemplateLiteral') {
525
- const hasSpecifiers = node.init.quasis.some((quasi) => containsFormatSpecifiers(quasi.value.raw));
526
- const hasUserInput = node.init.expressions.some((expr) => isUserInputNode(expr));
527
- if (hasSpecifiers && hasUserInput) {
528
- if (safetyChecker.isSafe(node, context)) {
529
- return;
530
- }
531
- context.report({
532
- node: node.init,
533
- messageId: 'formatStringInjection',
534
- data: {
535
- filePath: filename,
536
- line: String(node.loc?.start.line ?? 0),
537
- severity: 'MEDIUM',
538
- safeAlternative: 'Separate format string from user data',
539
- },
540
- });
541
- }
542
- }
543
- if (node.init.type === 'BinaryExpression' && node.init.operator === '+') {
544
- const hasSpecifiers = containsFormatSpecifiersInExpression(node.init);
545
- const hasUserInput = hasUserInputInExpression(node.init);
546
- if (hasSpecifiers && hasUserInput) {
547
- if (safetyChecker.isSafe(node, context)) {
548
- return;
549
- }
550
- context.report({
551
- node: node.init,
552
- messageId: 'formatStringInjection',
553
- data: {
554
- filePath: filename,
555
- line: String(node.loc?.start.line ?? 0),
556
- severity: 'MEDIUM',
557
- safeAlternative: 'Separate format string from user data',
558
- },
559
- });
560
- }
561
- }
562
- }
563
- };
564
- },
565
- });
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFormatStringInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");exports.noFormatStringInjection=(0,eslint_devkit_1.createRule)({name:"no-format-string-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-format-string-injection.md",description:"Detects format string injection vulnerabilities",cwe:"CWE-134"},fixable:"code",hasSuggestions:true,messages:{formatStringInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Format String Injection",cwe:"CWE-134",description:"Format string controlled by user input",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),unsafeFormatSpecifier:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Format Specifier",cwe:"CWE-134",description:"User input may contain format specifiers",severity:"MEDIUM",fix:"Escape or validate user input before formatting",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),userControlledFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Format String",cwe:"CWE-134",description:"Format string parameter comes from user input",severity:"CRITICAL",fix:"Use hardcoded format strings or validate user formats",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),missingFormatValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Format Validation",cwe:"CWE-134",description:"Format string not validated before use",severity:"HIGH",fix:"Validate format strings against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),escapeFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Escape Format String",description:"Escape format specifiers in user input",severity:"LOW",fix:"Replace % with %% in user input",documentationLink:"https://nodejs.org/api/util.html#utilformatformat-args"}),useSafeFormatting:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Safe Formatting",description:"Use safe string formatting methods",severity:"LOW",fix:"Use template literals or safe format libraries",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals"})},schema:[{type:"object",properties:{formatFunctions:{type:"array",items:{type:"string"},default:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],description:"Functions whose first argument is a format string"},formatSpecifiers:{type:"array",items:{type:"string"},default:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],description:"Format specifiers recognised in a format string"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},safeFormatLibraries:{type:"array",items:{type:"string"},default:["mustache","handlebars","ejs","pug"],description:"Templating libraries that escape their own input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as format string sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],safeFormatLibraries:["mustache","handlebars","ejs","pug"],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"],trustedAnnotations:[],strictMode:false}],create(context){const defaultOptions={formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],safeFormatLibraries:["mustache","handlebars","ejs","pug"],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"],trustedAnnotations:[],strictMode:false};const options={...defaultOptions,...context.options[0]};const{formatSpecifiers,userInputVariables,trustedSanitizers}=options;const filename=context.filename;const safetyChecker={isSafe:(safeNode,ruleCtx)=>{const comments=ruleCtx.sourceCode.getCommentsBefore(safeNode);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@safe-format")){return true}}if(safeNode.type==="CallExpression"&&safeNode.arguments.length>0){const firstArg=safeNode.arguments[0];if(firstArg.type==="Identifier"&&validatedVariables.has(firstArg.name)){return true}}return false}};const isUserInput=varName=>{const lowerName=varName.toLowerCase();return userInputVariables.some(input=>lowerName.includes(input.toLowerCase()))||lowerName==="user"||lowerName.includes("userinput")||lowerName.includes("userdata")||lowerName.includes("userparam")||lowerName.includes("usermessage")||lowerName.includes("usertemplate")||lowerName.includes("userformat")||lowerName.includes("uservar")};const isUserInputNode=node=>{if(node.type==="Identifier"){return isUserInput(node.name)||dangerousVariables.has(node.name)}if(node.type==="MemberExpression"){if(node.object.type==="MemberExpression"&&node.object.object.type==="Identifier"&&node.object.object.name==="req"&&node.object.property.type==="Identifier"&&["query","body","params","param"].includes(node.object.property.name)){return true}if(node.object.type==="Identifier"&&node.object.name==="req"){return true}const fullName=getMemberExpressionName(node);return isUserInput(fullName)}return false};const getMemberExpressionName=node=>{if(node.object.type==="Identifier"){if(node.property.type==="Identifier"){return`${node.object.name}.${node.property.name}`}}else if(node.object.type==="MemberExpression"){const objectName=getMemberExpressionName(node.object);if(node.property.type==="Identifier"){return`${objectName}.${node.property.name}`}}return""};const containsFormatSpecifiers=text=>{return formatSpecifiers.some(specifier=>text.includes(specifier))};const isConsoleMethod=node=>{const callee=node.callee;return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&callee.property.type==="Identifier"&&["log","error","warn","info","debug"].includes(callee.property.name)};const isFormatFunctionCall=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="util"&&callee.property.type==="Identifier"&&callee.property.name==="format"){return true}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&callee.property.type==="Identifier"&&["log","error","warn","info","debug"].includes(callee.property.name)){return true}if(callee.type==="Identifier"&&["sprintf","printf","vsprintf"].includes(callee.name)){return true}return false};const validatedVariables=new Set;const dangerousVariables=new Set;const isInputValidated=inputNode=>{if(inputNode.type==="Identifier"&&validatedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&trustedSanitizers.includes(current.callee.name)){return true}current=current.parent}return false};const hasFormatSpecifiers=node=>{if(typeof node.value!=="string"){return false}return containsFormatSpecifiers(node.value)};function containsFormatSpecifiersInExpression(expr){if(expr.left.type==="Literal"&&typeof expr.left.value==="string"&&containsFormatSpecifiers(expr.left.value)){return true}if(expr.right.type==="Literal"&&typeof expr.right.value==="string"&&containsFormatSpecifiers(expr.right.value)){return true}if(expr.left.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.right)){return true}return false}function hasUserInputInExpression(expr){if(isUserInputNode(expr.left)){return true}if(isUserInputNode(expr.right)){return true}if(expr.left.type==="BinaryExpression"&&hasUserInputInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&hasUserInputInExpression(expr.right)){return true}return false}return{CallExpression:function(node){if(!isFormatFunctionCall(node)){return}const args=node.arguments;if(args.length===0){return}const formatArg=args[0];const isFormatFromUserInput=isUserInputNode(formatArg)||formatArg.type==="Identifier"&&dangerousVariables.has(formatArg.name)||formatArg.type==="BinaryExpression"&&hasUserInputInExpression(formatArg);if(isFormatFromUserInput&&!isConsoleMethod(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"userControlledFormatString",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(formatArg.type==="TemplateLiteral"){const hasUserInput=formatArg.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded format strings or validate template input"}});return}}else if(formatArg.type==="BinaryExpression"&&formatArg.operator==="+"){const hasUserInput=hasUserInputInExpression(formatArg);if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Separate user input from format strings"}});return}}const fmtArg=args[0];const isFormatSafe=isInputValidated(fmtArg)||fmtArg.type==="Identifier"&&validatedVariables.has(fmtArg.name);if(!isFormatSafe){let hasUserInputInArgs=false;let hasSpecifiersInFormat=false;for(let i=1;i<args.length;i++){const arg=args[i];if(isUserInputNode(arg)&&!isInputValidated(arg)){hasUserInputInArgs=true;break}}const firstArg=args[0];if(firstArg.type==="Literal"&&typeof firstArg.value==="string"){if(containsFormatSpecifiers(firstArg.value)){hasSpecifiersInFormat=true}}else if(firstArg.type==="Identifier"){const varName=firstArg.name.toLowerCase();if(varName.includes("format")||varName.includes("template")||varName.includes("pattern")){hasSpecifiersInFormat=true}}if(!hasSpecifiersInFormat&&args.length===2&&isConsoleMethod(node)){}else if(hasSpecifiersInFormat&&hasUserInputInArgs){if(safetyChecker.isSafe(node,context)){return}const messageId=firstArg.type==="Literal"?"unsafeFormatSpecifier":"missingFormatValidation";context.report({node,messageId,data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"escapeFormatString",fix:fixer=>{const arg=node.arguments.slice(1).find(a=>isUserInputNode(a));return fixer.insertTextAfter(arg,'.replace(/%/g, "%%")')}}]})}}},Literal:function(node){if(!hasFormatSpecifiers(node)){return}const text=node.value;let current=node;let isFromUserInput=false;while(current){if(current.type==="BinaryExpression"&&current.operator==="+"&&(current.left===node||current.right===node)){const otherSide=current.left===node?current.right:current.left;if(otherSide.type==="Identifier"&&isUserInput(otherSide.name)){isFromUserInput=true;break}}if(current.type==="VariableDeclarator"&&current.init===node.parent&&current.id.type==="Identifier"){if(isUserInput(current.id.name)){isFromUserInput=true;break}}current=current.parent}if(!isFromUserInput){return}current=node;let isInDangerousContext=false;while(current){if(current.type==="CallExpression"&&isFormatFunctionCall(current)){const args=current.arguments;if(args.length>0&&args[0]===node){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext&&containsFormatSpecifiers(text)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingFormatValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},TemplateLiteral:function(node){let templateCurrent=node;let isFormatString=false;while(templateCurrent){if(templateCurrent.type==="CallExpression"&&isFormatFunctionCall(templateCurrent)){const args=templateCurrent.arguments;if(args.length>0&&args[0]===node){isFormatString=true;break}}templateCurrent=templateCurrent.parent}if(isFormatString){return}const hasUserInput=node.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){let assignCurrent=node;let isAssignedToVariable=false;while(assignCurrent){if(assignCurrent.type==="VariableDeclarator"){isAssignedToVariable=true;break}assignCurrent=assignCurrent.parent}if(isAssignedToVariable){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Extract user input from template and validate separately"}})}}},VariableDeclarator:function(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&trustedSanitizers.includes(node.init.callee.name)){validatedVariables.add(varName)}if(isUserInputNode(node.init)||node.init.type==="BinaryExpression"&&hasUserInputInExpression(node.init)){dangerousVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("format")&&!varNameLower.includes("template")&&!varNameLower.includes("fmt")&&!varNameLower.includes("str")){return}if(node.init.type==="TemplateLiteral"){const hasSpecifiers=node.init.quasis.some(quasi=>containsFormatSpecifiers(quasi.value.raw));const hasUserInput=node.init.expressions.some(expr=>isUserInputNode(expr));if(hasSpecifiers&&hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}if(node.init.type==="BinaryExpression"&&node.init.operator==="+"){const hasSpecifiers=containsFormatSpecifiersInExpression(node.init);const hasUserInput=hasUserInputInExpression(node.init);if(hasSpecifiers&&hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}}}}});