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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-secure-coding",
3
- "version": "3.4.3",
3
+ "version": "3.4.4",
4
4
  "description": "ESLint plugin for secure coding — detects LDAP, XPath, XXE, GraphQL and template injection, unsafe deserialization, ReDoS, missing authentication, and PII in logs.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -77,7 +77,7 @@
77
77
  "node": ">=18.0.0"
78
78
  },
79
79
  "dependencies": {
80
- "@interlace/eslint-devkit": "^1.8.0",
80
+ "@interlace/eslint-devkit": "^1.10.0",
81
81
  "scslre": "^0.3.0",
82
82
  "@eslint-community/regexpp": "^4.10.0"
83
83
  },
package/src/index.js CHANGED
@@ -1,107 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.configs = exports.plugin = exports.rules = void 0;
4
- exports.rules = {
5
- get 'no-graphql-injection'() { return require("./rules/no-graphql-injection").noGraphqlInjection; },
6
- get 'no-xxe-injection'() { return require("./rules/no-xxe-injection").noXxeInjection; },
7
- get 'no-xpath-injection'() { return require("./rules/no-xpath-injection").noXpathInjection; },
8
- get 'no-ldap-injection'() { return require("./rules/no-ldap-injection").noLdapInjection; },
9
- get 'no-directive-injection'() { return require("./rules/no-directive-injection").noDirectiveInjection; },
10
- get 'no-format-string-injection'() { return require("./rules/no-format-string-injection").noFormatStringInjection; },
11
- get 'no-template-injection'() { return require("./rules/no-template-injection").noTemplateInjection; },
12
- get 'detect-non-literal-regexp'() { return require("./rules/detect-non-literal-regexp").detectNonLiteralRegexp; },
13
- get 'no-redos-vulnerable-regex'() { return require("./rules/no-redos-vulnerable-regex").noRedosVulnerableRegex; },
14
- get 'no-unsafe-regex-construction'() { return require("./rules/no-unsafe-regex-construction").noUnsafeRegexConstruction; },
15
- get 'detect-object-injection'() { return require("./rules/detect-object-injection").detectObjectInjection; },
16
- get 'no-unsafe-deserialization'() { return require("./rules/no-unsafe-deserialization").noUnsafeDeserialization; },
17
- get 'no-insecure-comparison'() { return require("./rules/no-insecure-comparison").noInsecureComparison; },
18
- get 'no-improper-sanitization'() { return require("./rules/no-improper-sanitization").noImproperSanitization; },
19
- get 'no-improper-type-validation'() { return require("./rules/no-improper-type-validation").noImproperTypeValidation; },
20
- get 'no-missing-authentication'() { return require("./rules/no-missing-authentication").noMissingAuthentication; },
21
- get 'no-privilege-escalation'() { return require("./rules/no-privilege-escalation").noPrivilegeEscalation; },
22
- get 'no-weak-password-recovery'() { return require("./rules/no-weak-password-recovery").noWeakPasswordRecovery; },
23
- get 'require-backend-authorization'() { return require("./rules/require-backend-authorization").requireBackendAuthorization; },
24
- get 'no-hardcoded-credentials'() { return require("./rules/no-hardcoded-credentials").noHardcodedCredentials; },
25
- get 'no-sensitive-data-exposure'() { return require("./rules/no-sensitive-data-exposure").noSensitiveDataExposure; },
26
- get 'no-pii-in-logs'() { return require("./rules/no-pii-in-logs").noPiiInLogs; },
27
- get 'no-unlimited-resource-allocation'() { return require("./rules/no-unlimited-resource-allocation").noUnlimitedResourceAllocation; },
28
- get 'no-unchecked-loop-condition'() { return require("./rules/no-unchecked-loop-condition").noUncheckedLoopCondition; },
29
- get 'detect-weak-password-validation'() { return require("./rules/detect-weak-password-validation").detectWeakPasswordValidation; },
30
- get 'no-electron-security-issues'() { return require("./rules/no-electron-security-issues").noElectronSecurityIssues; },
31
- get 'no-hardcoded-session-tokens'() { return require("./rules/no-hardcoded-session-tokens").noHardcodedSessionTokens; },
32
- get 'require-secure-defaults'() { return require("./rules/require-secure-defaults").requireSecureDefaults; },
33
-
34
- };
35
- exports.plugin = {
36
- meta: {
37
- name: 'eslint-plugin-secure-coding',
38
- version: '3.4.3',
39
- },
40
- rules: exports.rules,
41
- };
42
- const recommendedRules = {
43
- 'secure-coding/no-graphql-injection': 'warn',
44
- 'secure-coding/no-xxe-injection': 'error',
45
- 'secure-coding/no-xpath-injection': 'error',
46
- 'secure-coding/no-ldap-injection': 'error',
47
- 'secure-coding/no-unsafe-deserialization': 'warn',
48
- 'secure-coding/detect-non-literal-regexp': 'warn',
49
- 'secure-coding/no-redos-vulnerable-regex': 'error',
50
- 'secure-coding/no-unsafe-regex-construction': 'error',
51
- 'secure-coding/detect-object-injection': 'warn',
52
- 'secure-coding/no-hardcoded-credentials': 'error',
53
- 'secure-coding/no-template-injection': 'error',
54
- 'secure-coding/no-improper-sanitization': 'error',
55
- 'secure-coding/no-privilege-escalation': 'warn',
56
- 'secure-coding/no-weak-password-recovery': 'warn',
57
- 'secure-coding/no-sensitive-data-exposure': 'warn',
58
- 'secure-coding/no-unlimited-resource-allocation': 'warn',
59
- 'secure-coding/no-unchecked-loop-condition': 'warn',
60
- };
61
- exports.configs = {
62
- flagship: {
63
- plugins: {
64
- 'secure-coding': exports.plugin,
65
- },
66
- rules: {
67
- 'secure-coding/no-hardcoded-credentials': 'error',
68
- 'secure-coding/no-redos-vulnerable-regex': 'error',
69
- },
70
- },
71
- recommended: {
72
- plugins: {
73
- 'secure-coding': exports.plugin,
74
- },
75
- rules: recommendedRules,
76
- },
77
- 'recommended-strict': {
78
- plugins: {
79
- 'secure-coding': exports.plugin,
80
- },
81
- rules: Object.fromEntries(Object.keys(recommendedRules).map((rule) => [rule, 'error'])),
82
- },
83
- strict: {
84
- plugins: {
85
- 'secure-coding': exports.plugin,
86
- },
87
- rules: Object.fromEntries(Object.keys(exports.rules).map(ruleName => [`secure-coding/${ruleName}`, 'error'])),
88
- },
89
- 'owasp-top-10': {
90
- plugins: {
91
- 'secure-coding': exports.plugin,
92
- },
93
- rules: {
94
- 'secure-coding/no-privilege-escalation': 'warn',
95
- 'secure-coding/no-hardcoded-credentials': 'error',
96
- 'secure-coding/no-sensitive-data-exposure': 'warn',
97
- 'secure-coding/no-graphql-injection': 'error',
98
- 'secure-coding/no-xxe-injection': 'error',
99
- 'secure-coding/no-xpath-injection': 'error',
100
- 'secure-coding/no-ldap-injection': 'error',
101
- 'secure-coding/no-weak-password-recovery': 'error',
102
- 'secure-coding/no-improper-type-validation': 'error',
103
- 'secure-coding/no-unsafe-deserialization': 'error',
104
- },
105
- },
106
- };
107
- exports.default = exports.plugin;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;exports.rules={get"no-graphql-injection"(){return require("./rules/no-graphql-injection").noGraphqlInjection},get"no-xxe-injection"(){return require("./rules/no-xxe-injection").noXxeInjection},get"no-xpath-injection"(){return require("./rules/no-xpath-injection").noXpathInjection},get"no-ldap-injection"(){return require("./rules/no-ldap-injection").noLdapInjection},get"no-directive-injection"(){return require("./rules/no-directive-injection").noDirectiveInjection},get"no-format-string-injection"(){return require("./rules/no-format-string-injection").noFormatStringInjection},get"no-template-injection"(){return require("./rules/no-template-injection").noTemplateInjection},get"detect-non-literal-regexp"(){return require("./rules/detect-non-literal-regexp").detectNonLiteralRegexp},get"no-redos-vulnerable-regex"(){return require("./rules/no-redos-vulnerable-regex").noRedosVulnerableRegex},get"no-unsafe-regex-construction"(){return require("./rules/no-unsafe-regex-construction").noUnsafeRegexConstruction},get"detect-object-injection"(){return require("./rules/detect-object-injection").detectObjectInjection},get"no-unsafe-deserialization"(){return require("./rules/no-unsafe-deserialization").noUnsafeDeserialization},get"no-insecure-comparison"(){return require("./rules/no-insecure-comparison").noInsecureComparison},get"no-improper-sanitization"(){return require("./rules/no-improper-sanitization").noImproperSanitization},get"no-improper-type-validation"(){return require("./rules/no-improper-type-validation").noImproperTypeValidation},get"no-missing-authentication"(){return require("./rules/no-missing-authentication").noMissingAuthentication},get"no-privilege-escalation"(){return require("./rules/no-privilege-escalation").noPrivilegeEscalation},get"no-weak-password-recovery"(){return require("./rules/no-weak-password-recovery").noWeakPasswordRecovery},get"require-backend-authorization"(){return require("./rules/require-backend-authorization").requireBackendAuthorization},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"no-sensitive-data-exposure"(){return require("./rules/no-sensitive-data-exposure").noSensitiveDataExposure},get"no-pii-in-logs"(){return require("./rules/no-pii-in-logs").noPiiInLogs},get"no-unlimited-resource-allocation"(){return require("./rules/no-unlimited-resource-allocation").noUnlimitedResourceAllocation},get"no-unchecked-loop-condition"(){return require("./rules/no-unchecked-loop-condition").noUncheckedLoopCondition},get"detect-weak-password-validation"(){return require("./rules/detect-weak-password-validation").detectWeakPasswordValidation},get"no-electron-security-issues"(){return require("./rules/no-electron-security-issues").noElectronSecurityIssues},get"no-hardcoded-session-tokens"(){return require("./rules/no-hardcoded-session-tokens").noHardcodedSessionTokens},get"require-secure-defaults"(){return require("./rules/require-secure-defaults").requireSecureDefaults}};exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"3.4.4"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-unsafe-deserialization":"warn","secure-coding/detect-non-literal-regexp":"warn","secure-coding/no-redos-vulnerable-regex":"error","secure-coding/no-unsafe-regex-construction":"error","secure-coding/detect-object-injection":"warn","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-template-injection":"error","secure-coding/no-improper-sanitization":"error","secure-coding/no-privilege-escalation":"warn","secure-coding/no-weak-password-recovery":"warn","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-unlimited-resource-allocation":"warn","secure-coding/no-unchecked-loop-condition":"warn"};exports.configs={flagship:{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-hardcoded-credentials":"error","secure-coding/no-redos-vulnerable-regex":"error"}},recommended:{plugins:{"secure-coding":exports.plugin},rules:recommendedRules},"recommended-strict":{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(recommendedRules).map(rule=>[rule,"error"]))},strict:{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`secure-coding/${ruleName}`,"error"]))},"owasp-top-10":{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-privilege-escalation":"warn","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-graphql-injection":"error","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-weak-password-recovery":"error","secure-coding/no-improper-type-validation":"error","secure-coding/no-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
package/src/oxlint.js CHANGED
@@ -1,3 +1 @@
1
- "use strict";
2
- const index_1 = require("./index");
3
- module.exports = index_1.plugin;
1
+ "use strict";const index_1=require("./index");module.exports=index_1.plugin;
@@ -1,329 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.detectNonLiteralRegexp = void 0;
4
- const eslint_devkit_1 = require("@interlace/eslint-devkit");
5
- const eslint_devkit_2 = require("@interlace/eslint-devkit");
6
- const isRegExpLiteral = (node) => {
7
- return node.type === 'Literal' && Object.prototype.hasOwnProperty.call(node, 'regex');
8
- };
9
- const REGEXP_PATTERNS = [
10
- {
11
- pattern: 'new RegExp\\(.*\\)',
12
- dangerous: true,
13
- vulnerability: 'redos',
14
- safeAlternative: 'Pre-defined RegExp constants',
15
- example: {
16
- bad: 'new RegExp(userInput)',
17
- good: 'const PATTERNS = { email: /^[a-zA-Z0-9]+$/ }; PATTERNS[userChoice]'
18
- },
19
- effort: '10-15 minutes',
20
- riskLevel: 'high'
21
- },
22
- {
23
- pattern: 'RegExp\\(.*\\)',
24
- dangerous: true,
25
- vulnerability: 'redos',
26
- safeAlternative: 'Static RegExp literals or validated patterns',
27
- example: {
28
- bad: 'RegExp(userPattern)',
29
- good: 'const safePattern = userPattern.replace(/[.*+?^${}()|[\\]\\\\]/g, \'\\\\$&\'); new RegExp(`^${safePattern}$`)'
30
- },
31
- effort: '15-20 minutes',
32
- riskLevel: 'high'
33
- },
34
- {
35
- pattern: '/.*\\*\\*.*|.*\\+\\+.*|.*\\?\\?/',
36
- dangerous: true,
37
- vulnerability: 'redos',
38
- safeAlternative: 'Avoid nested quantifiers, use atomic groups',
39
- example: {
40
- bad: '/(a+)+b/',
41
- good: '/(?>a+)b/',
42
- },
43
- effort: '20-30 minutes',
44
- riskLevel: 'critical'
45
- }
46
- ];
47
- exports.detectNonLiteralRegexp = (0, eslint_devkit_2.createRule)({
48
- name: 'detect-non-literal-regexp',
49
- meta: {
50
- type: 'problem',
51
- docs: {
52
- url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-non-literal-regexp.md',
53
- description: 'Detects RegExp(variable), which might allow an attacker to DOS your server with a long-running regular expression',
54
- cwe: 'CWE-400',
55
- },
56
- messages: {
57
- regexpReDoS: (0, eslint_devkit_1.formatLLMMessage)({
58
- icon: eslint_devkit_1.MessageIcons.WARNING,
59
- issueName: 'ReDoS vulnerability',
60
- cwe: 'CWE-400',
61
- description: 'ReDoS vulnerability detected',
62
- severity: '{{riskLevel}}',
63
- fix: '{{safeAlternative}}',
64
- documentationLink: 'https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS',
65
- }),
66
- useStaticRegex: (0, eslint_devkit_1.formatLLMMessage)({
67
- icon: eslint_devkit_1.MessageIcons.INFO,
68
- issueName: 'Use Static Regex',
69
- description: 'Use pre-defined RegExp constants',
70
- severity: 'LOW',
71
- fix: 'const PATTERN = /^[a-z]+$/; // Define at module level',
72
- documentationLink: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp',
73
- }),
74
- validateInput: (0, eslint_devkit_1.formatLLMMessage)({
75
- icon: eslint_devkit_1.MessageIcons.INFO,
76
- issueName: 'Validate Input',
77
- description: 'Validate and escape user input',
78
- severity: 'LOW',
79
- fix: 'Validate input length and characters before RegExp',
80
- documentationLink: 'https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS',
81
- }),
82
- useRegexLibrary: (0, eslint_devkit_1.formatLLMMessage)({
83
- icon: eslint_devkit_1.MessageIcons.INFO,
84
- issueName: 'Use Safe Library',
85
- description: 'Use safe-regex library or re2',
86
- severity: 'LOW',
87
- fix: 'import { isSafe } from "safe-regex"; if (isSafe(pattern)) ...',
88
- documentationLink: 'https://github.com/substack/safe-regex',
89
- }),
90
- addTimeout: (0, eslint_devkit_1.formatLLMMessage)({
91
- icon: eslint_devkit_1.MessageIcons.INFO,
92
- issueName: 'Add Timeout',
93
- description: 'Add timeout to regex operations',
94
- severity: 'LOW',
95
- fix: 'Use timeout wrapper for regex operations',
96
- documentationLink: 'https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS',
97
- }),
98
- escapeUserInput: (0, eslint_devkit_1.formatLLMMessage)({
99
- icon: eslint_devkit_1.MessageIcons.INFO,
100
- issueName: 'Escape Input',
101
- description: 'Escape special regex characters',
102
- severity: 'LOW',
103
- fix: 'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',
104
- documentationLink: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping',
105
- })
106
- },
107
- schema: [
108
- {
109
- type: 'object',
110
- properties: {
111
- allowLiterals: {
112
- type: 'boolean',
113
- default: false,
114
- description: 'Allow literal string regex patterns'
115
- },
116
- additionalPatterns: {
117
- type: 'array',
118
- items: { type: 'string' },
119
- default: [],
120
- description: 'Additional RegExp creation patterns to check'
121
- },
122
- maxPatternLength: {
123
- type: 'number',
124
- default: 100,
125
- minimum: 1,
126
- description: 'Maximum allowed pattern length for dynamic regex'
127
- }
128
- },
129
- additionalProperties: false,
130
- },
131
- ],
132
- },
133
- defaultOptions: [
134
- {
135
- allowLiterals: false,
136
- additionalPatterns: [],
137
- maxPatternLength: 100
138
- },
139
- ],
140
- create(context) {
141
- const options = context.options[0] || {};
142
- const { allowLiterals = false, maxPatternLength = 100, } = options;
143
- const isLiteralString = (node) => {
144
- if (node.type === 'Literal' && typeof node.value === 'string') {
145
- return true;
146
- }
147
- if (node.type === 'TemplateLiteral' && node.expressions.length === 0) {
148
- return true;
149
- }
150
- return false;
151
- };
152
- const hasReDoSPatterns = (pattern) => {
153
- const nestedQuantifierPatterns = [
154
- /\([^)]*[+*]\)[+*]/,
155
- /\([^)]*[+*]\)\{[0-9,]+\}/,
156
- ];
157
- for (const dangerousPattern of nestedQuantifierPatterns) {
158
- if (dangerousPattern.test(pattern)) {
159
- return true;
160
- }
161
- }
162
- return false;
163
- };
164
- const extractPattern = (node) => {
165
- const sourceCode = context.sourceCode;
166
- let constructor = 'RegExp';
167
- if (node.type === 'NewExpression' && node.callee.type === 'Identifier') {
168
- constructor = `new ${node.callee.name}`;
169
- }
170
- const patternNode = node.arguments.length > 0 ? node.arguments[0] : null;
171
- const pattern = patternNode ? sourceCode.getText(patternNode) : '';
172
- const isDynamic = patternNode ? !isLiteralString(patternNode) : false;
173
- const length = patternNode && isLiteralString(patternNode) ?
174
- String(patternNode.value).length : pattern.length;
175
- return { pattern, patternNode, constructor, isDynamic, length };
176
- };
177
- const detectVulnerability = (pattern, isDynamic) => {
178
- if (isDynamic) {
179
- for (const vuln of REGEXP_PATTERNS) {
180
- if (new RegExp(vuln.pattern, 'i').test(pattern)) {
181
- return vuln;
182
- }
183
- }
184
- return {
185
- pattern: 'dynamic',
186
- dangerous: true,
187
- vulnerability: 'redos',
188
- safeAlternative: 'Pre-defined RegExp constants',
189
- example: {
190
- bad: pattern,
191
- good: 'const PATTERNS = { email: /^[a-zA-Z0-9]+$/ }; PATTERNS[type]'
192
- },
193
- effort: '10-15 minutes',
194
- riskLevel: 'high'
195
- };
196
- }
197
- if (hasReDoSPatterns(pattern)) {
198
- return {
199
- pattern: 'redos-literal',
200
- dangerous: true,
201
- vulnerability: 'redos',
202
- safeAlternative: 'Restructure regex to avoid nested quantifiers',
203
- example: {
204
- bad: pattern,
205
- good: pattern.replace(/(a+)\+/g, '$1')
206
- },
207
- effort: '20-30 minutes',
208
- riskLevel: 'high'
209
- };
210
- }
211
- return null;
212
- };
213
- const generateRefactoringSteps = (vulnerability) => {
214
- if (vulnerability.pattern === 'dynamic') {
215
- return [
216
- ' 1. Create a whitelist of allowed regex patterns',
217
- ' 2. Use object lookup: PATTERNS[userChoice]',
218
- ' 3. If dynamic needed: escape input with regex escaping function',
219
- ' 4. Add pattern length validation',
220
- ' 5. Consider using a safe regex library'
221
- ].join('\n');
222
- }
223
- if (vulnerability.pattern === 'redos-literal') {
224
- return [
225
- ' 1. Identify nested quantifiers (*+, ++, ?+)',
226
- ' 2. Restructure regex to avoid exponential backtracking',
227
- ' 3. Use atomic groups if supported: (?>...)',
228
- ' 4. Test regex performance with long inputs',
229
- ' 5. Consider alternatives like string methods'
230
- ].join('\n');
231
- }
232
- return [
233
- ' 1. Avoid nested quantifiers and backreferences',
234
- ' 2. Use possessive quantifiers: *+, ++, ?+',
235
- ' 3. Restructure regex to be more specific',
236
- ' 4. Test with potentially malicious inputs',
237
- ' 5. Consider safe-regex library validation'
238
- ].join('\n');
239
- };
240
- const determineRiskLevel = (vulnerability, pattern) => {
241
- if (vulnerability.riskLevel === 'critical' || hasReDoSPatterns(pattern)) {
242
- return 'CRITICAL';
243
- }
244
- return 'HIGH';
245
- };
246
- const checkRegExpCall = (node) => {
247
- const isRegExpCall = node.callee.type === 'Identifier' && node.callee.name === 'RegExp';
248
- const isNewRegExp = node.type === 'NewExpression' && node.callee.type === 'Identifier' && node.callee.name === 'RegExp';
249
- if (!isRegExpCall && !isNewRegExp) {
250
- return;
251
- }
252
- const { pattern, patternNode, isDynamic, length } = extractPattern(node);
253
- if (allowLiterals && patternNode && isLiteralString(patternNode) && length <= maxPatternLength) {
254
- if (!hasReDoSPatterns(pattern)) {
255
- return;
256
- }
257
- }
258
- const vulnerability = detectVulnerability(pattern, isDynamic);
259
- const effectiveVulnerability = vulnerability;
260
- if (!effectiveVulnerability) {
261
- return;
262
- }
263
- const riskLevel = determineRiskLevel(effectiveVulnerability, pattern);
264
- const steps = generateRefactoringSteps(effectiveVulnerability);
265
- context.report({
266
- node,
267
- messageId: 'regexpReDoS',
268
- data: {
269
- pattern: pattern.substring(0, 30) + (pattern.length > 30 ? '...' : ''),
270
- riskLevel,
271
- vulnerability: effectiveVulnerability.vulnerability,
272
- safeAlternative: effectiveVulnerability.safeAlternative,
273
- steps,
274
- effort: effectiveVulnerability.effort
275
- },
276
- suggest: [
277
- {
278
- messageId: 'useStaticRegex',
279
- fix: () => null
280
- },
281
- {
282
- messageId: 'validateInput',
283
- fix: () => null
284
- },
285
- {
286
- messageId: 'useRegexLibrary',
287
- fix: () => null
288
- },
289
- {
290
- messageId: 'addTimeout',
291
- fix: () => null
292
- },
293
- {
294
- messageId: 'escapeUserInput',
295
- fix: () => null
296
- }
297
- ]
298
- });
299
- };
300
- const checkLiteralRegExp = (node) => {
301
- if (!isRegExpLiteral(node)) {
302
- return;
303
- }
304
- const pattern = node.regex.pattern;
305
- if (hasReDoSPatterns(pattern)) {
306
- const vulnerability = detectVulnerability(pattern, false);
307
- const riskLevel = determineRiskLevel(vulnerability, pattern);
308
- const steps = generateRefactoringSteps(vulnerability);
309
- context.report({
310
- node,
311
- messageId: 'regexpReDoS',
312
- data: {
313
- pattern: pattern.substring(0, 30) + (pattern.length > 30 ? '...' : ''),
314
- riskLevel,
315
- vulnerability: vulnerability.vulnerability,
316
- safeAlternative: vulnerability.safeAlternative,
317
- steps,
318
- effort: vulnerability.effort
319
- }
320
- });
321
- }
322
- };
323
- return {
324
- CallExpression: checkRegExpCall,
325
- NewExpression: checkRegExpCall,
326
- Literal: checkLiteralRegExp
327
- };
328
- },
329
- });
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectNonLiteralRegexp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const isRegExpLiteral=node=>{return node.type==="Literal"&&Object.prototype.hasOwnProperty.call(node,"regex")};const REGEXP_PATTERNS=[{pattern:"new RegExp\\(.*\\)",dangerous:true,vulnerability:"redos",safeAlternative:"Pre-defined RegExp constants",example:{bad:"new RegExp(userInput)",good:"const PATTERNS = { email: /^[a-zA-Z0-9]+$/ }; PATTERNS[userChoice]"},effort:"10-15 minutes",riskLevel:"high"},{pattern:"RegExp\\(.*\\)",dangerous:true,vulnerability:"redos",safeAlternative:"Static RegExp literals or validated patterns",example:{bad:"RegExp(userPattern)",good:"const safePattern = userPattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); new RegExp(`^${safePattern}$`)"},effort:"15-20 minutes",riskLevel:"high"},{pattern:"/.*\\*\\*.*|.*\\+\\+.*|.*\\?\\?/",dangerous:true,vulnerability:"redos",safeAlternative:"Avoid nested quantifiers, use atomic groups",example:{bad:"/(a+)+b/",good:"/(?>a+)b/"},effort:"20-30 minutes",riskLevel:"critical"}];exports.detectNonLiteralRegexp=(0,eslint_devkit_2.createRule)({name:"detect-non-literal-regexp",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-non-literal-regexp.md",description:"Detects RegExp(variable), which might allow an attacker to DOS your server with a long-running regular expression",cwe:"CWE-400"},messages:{regexpReDoS:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"ReDoS vulnerability",cwe:"CWE-400",description:"ReDoS vulnerability detected",severity:"{{riskLevel}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),useStaticRegex:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Static Regex",description:"Use pre-defined RegExp constants",severity:"LOW",fix:"const PATTERN = /^[a-z]+$/; // Define at module level",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"}),validateInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Validate Input",description:"Validate and escape user input",severity:"LOW",fix:"Validate input length and characters before RegExp",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),useRegexLibrary:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Safe Library",description:"Use safe-regex library or re2",severity:"LOW",fix:'import { isSafe } from "safe-regex"; if (isSafe(pattern)) ...',documentationLink:"https://github.com/substack/safe-regex"}),addTimeout:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Timeout",description:"Add timeout to regex operations",severity:"LOW",fix:"Use timeout wrapper for regex operations",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),escapeUserInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Escape Input",description:"Escape special regex characters",severity:"LOW",fix:'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:false,description:"Allow literal string regex patterns"},additionalPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional RegExp creation patterns to check"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum allowed pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:false,additionalPatterns:[],maxPatternLength:100}],create(context){const options=context.options[0]||{};const{allowLiterals=false,maxPatternLength=100}=options;const isLiteralString=node=>{if(node.type==="Literal"&&typeof node.value==="string"){return true}if(node.type==="TemplateLiteral"&&node.expressions.length===0){return true}return false};const hasReDoSPatterns=pattern=>{const nestedQuantifierPatterns=[/\([^)]*[+*]\)[+*]/,/\([^)]*[+*]\)\{[0-9,]+\}/];for(const dangerousPattern of nestedQuantifierPatterns){if(dangerousPattern.test(pattern)){return true}}return false};const extractPattern=node=>{const sourceCode=context.sourceCode;let constructor="RegExp";if(node.type==="NewExpression"&&node.callee.type==="Identifier"){constructor=`new ${node.callee.name}`}const patternNode=node.arguments.length>0?node.arguments[0]:null;const pattern=patternNode?sourceCode.getText(patternNode):"";const isDynamic=patternNode?!isLiteralString(patternNode):false;const length=patternNode&&isLiteralString(patternNode)?String(patternNode.value).length:pattern.length;return{pattern,patternNode,constructor,isDynamic,length}};const detectVulnerability=(pattern,isDynamic)=>{if(isDynamic){for(const vuln of REGEXP_PATTERNS){if(new RegExp(vuln.pattern,"i").test(pattern)){return vuln}}return{pattern:"dynamic",dangerous:true,vulnerability:"redos",safeAlternative:"Pre-defined RegExp constants",example:{bad:pattern,good:"const PATTERNS = { email: /^[a-zA-Z0-9]+$/ }; PATTERNS[type]"},effort:"10-15 minutes",riskLevel:"high"}}if(hasReDoSPatterns(pattern)){return{pattern:"redos-literal",dangerous:true,vulnerability:"redos",safeAlternative:"Restructure regex to avoid nested quantifiers",example:{bad:pattern,good:pattern.replace(/(a+)\+/g,"$1")},effort:"20-30 minutes",riskLevel:"high"}}return null};const generateRefactoringSteps=vulnerability=>{if(vulnerability.pattern==="dynamic"){return[" 1. Create a whitelist of allowed regex patterns"," 2. Use object lookup: PATTERNS[userChoice]"," 3. If dynamic needed: escape input with regex escaping function"," 4. Add pattern length validation"," 5. Consider using a safe regex library"].join("\n")}if(vulnerability.pattern==="redos-literal"){return[" 1. Identify nested quantifiers (*+, ++, ?+)"," 2. Restructure regex to avoid exponential backtracking"," 3. Use atomic groups if supported: (?>...)"," 4. Test regex performance with long inputs"," 5. Consider alternatives like string methods"].join("\n")}return[" 1. Avoid nested quantifiers and backreferences"," 2. Use possessive quantifiers: *+, ++, ?+"," 3. Restructure regex to be more specific"," 4. Test with potentially malicious inputs"," 5. Consider safe-regex library validation"].join("\n")};const determineRiskLevel=(vulnerability,pattern)=>{if(vulnerability.riskLevel==="critical"||hasReDoSPatterns(pattern)){return"CRITICAL"}return"HIGH"};const checkRegExpCall=node=>{const isRegExpCall=node.callee.type==="Identifier"&&node.callee.name==="RegExp";const isNewRegExp=node.type==="NewExpression"&&node.callee.type==="Identifier"&&node.callee.name==="RegExp";if(!isRegExpCall&&!isNewRegExp){return}const{pattern,patternNode,isDynamic,length}=extractPattern(node);if(allowLiterals&&patternNode&&isLiteralString(patternNode)&&length<=maxPatternLength){if(!hasReDoSPatterns(pattern)){return}}const vulnerability=detectVulnerability(pattern,isDynamic);const effectiveVulnerability=vulnerability;if(!effectiveVulnerability){return}const riskLevel=determineRiskLevel(effectiveVulnerability,pattern);const steps=generateRefactoringSteps(effectiveVulnerability);context.report({node,messageId:"regexpReDoS",data:{pattern:pattern.substring(0,30)+(pattern.length>30?"...":""),riskLevel,vulnerability:effectiveVulnerability.vulnerability,safeAlternative:effectiveVulnerability.safeAlternative,steps,effort:effectiveVulnerability.effort},suggest:[{messageId:"useStaticRegex",fix:()=>null},{messageId:"validateInput",fix:()=>null},{messageId:"useRegexLibrary",fix:()=>null},{messageId:"addTimeout",fix:()=>null},{messageId:"escapeUserInput",fix:()=>null}]})};const checkLiteralRegExp=node=>{if(!isRegExpLiteral(node)){return}const pattern=node.regex.pattern;if(hasReDoSPatterns(pattern)){const vulnerability=detectVulnerability(pattern,false);const riskLevel=determineRiskLevel(vulnerability,pattern);const steps=generateRefactoringSteps(vulnerability);context.report({node,messageId:"regexpReDoS",data:{pattern:pattern.substring(0,30)+(pattern.length>30?"...":""),riskLevel,vulnerability:vulnerability.vulnerability,safeAlternative:vulnerability.safeAlternative,steps,effort:vulnerability.effort}})}};return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall,Literal:checkLiteralRegExp}}});