eslint-plugin-node-security 5.4.2 → 5.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.
- package/README.md +2 -2
- package/package.json +1 -1
- package/src/index.js +1 -1
- package/src/rules/detect-child-process/index.js +1 -1
- package/src/rules/detect-non-literal-fs-filename/index.js +1 -1
- package/src/rules/no-deprecated-buffer/index.js +1 -1
- package/src/rules/no-insecure-key-derivation/index.js +1 -1
- package/src/rules/no-insecure-rsa-padding/index.js +1 -1
- package/src/rules/no-self-signed-certs/index.js +1 -1
- package/src/rules/no-unbounded-decompression/index.js +1 -1
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<a href="https://eslint.interlace.tools
|
|
2
|
+
<a href="https://eslint.interlace.tools/docs/security/plugin-node-security?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security" target="blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://eslint.interlace.tools/logos/interlace-dark.svg"><img src="https://eslint.interlace.tools/logos/interlace-light.svg" alt="Interlace" height="90" /></picture></a>
|
|
3
3
|
|
|
4
4
|
<a href="https://nodejs.org" target="_blank"><img src="https://eslint.interlace.tools/logos/node.svg" alt="Node.js" height="90" /></a>
|
|
5
5
|
|
|
@@ -202,5 +202,5 @@ MIT © [Ofri Peretz](https://github.com/ofri-peretz)
|
|
|
202
202
|
</p>
|
|
203
203
|
|
|
204
204
|
<p align="center">
|
|
205
|
-
<a href="https://eslint.interlace.tools
|
|
205
|
+
<a href="https://eslint.interlace.tools/docs/security/plugin-node-security?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security" target="blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://eslint.interlace.tools/logos/interlace-dark.svg"><img src="https://eslint.interlace.tools/logos/interlace-light.svg" alt="Interlace" height="70" /></picture></a>
|
|
206
206
|
</p>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-node-security",
|
|
3
|
-
"version": "5.4.
|
|
3
|
+
"version": "5.4.4",
|
|
4
4
|
"description": "ESLint plugin for Node.js security — detects command injection, path traversal, SSRF, zip slip, and weak crypto (MD5/SHA-1, ECB, static IV) in fs, child_process, vm, and crypto.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
package/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"detect-child-process"(){return require("./rules/detect-child-process").detectChildProcess},get"detect-eval-with-expression"(){return require("./rules/detect-eval-with-expression").detectEvalWithExpression},get"detect-non-literal-fs-filename"(){return require("./rules/detect-non-literal-fs-filename").detectNonLiteralFsFilename},get"no-unsafe-dynamic-require"(){return require("./rules/no-unsafe-dynamic-require").noUnsafeDynamicRequire},get"no-buffer-overread"(){return require("./rules/no-buffer-overread").noBufferOverread},get"no-deprecated-buffer"(){return require("./rules/no-deprecated-buffer").noDeprecatedBuffer},get"no-unsafe-buffer-alloc"(){return require("./rules/no-unsafe-buffer-alloc").noUnsafeBufferAlloc},get"no-toctou-vulnerability"(){return require("./rules/no-toctou-vulnerability").noToctouVulnerability},get"no-zip-slip"(){return require("./rules/no-zip-slip").noZipSlip},get"no-arbitrary-file-access"(){return require("./rules/no-arbitrary-file-access").noArbitraryFileAccess},get"no-data-in-temp-storage"(){return require("./rules/no-data-in-temp-storage").noDataInTempStorage},get"no-ssrf"(){return require("./rules/no-ssrf").noSsrf},get"no-shell-injection"(){return require("./rules/no-shell-injection").noShellInjection},get"no-dynamic-command-string"(){return require("./rules/no-dynamic-command-string").noDynamicCommandString},get"no-env-injection"(){return require("./rules/no-env-injection").noEnvInjection},get"no-dynamic-algorithm-selection"(){return require("./rules/no-dynamic-algorithm-selection").noDynamicAlgorithmSelection},get"detect-suspicious-dependencies"(){return require("./rules/detect-suspicious-dependencies").detectSuspiciousDependencies},get"lock-file"(){return require("./rules/lock-file").lockFile},get"no-dynamic-dependency-loading"(){return require("./rules/no-dynamic-dependency-loading").noDynamicDependencyLoading},get"require-dependency-integrity"(){return require("./rules/require-dependency-integrity").requireDependencyIntegrity},get"require-secure-credential-storage"(){return require("./rules/require-secure-credential-storage").requireSecureCredentialStorage},get"require-secure-deletion"(){return require("./rules/require-secure-deletion").requireSecureDeletion},get"require-storage-encryption"(){return require("./rules/require-storage-encryption").requireStorageEncryption},get"no-dynamic-require"(){return require("./rules/no-dynamic-require").noDynamicRequire},get"no-cryptojs"(){return require("./rules/no-cryptojs").noCryptojs},get"no-cryptojs-weak-random"(){return require("./rules/no-cryptojs-weak-random").noCryptojsWeakRandom},get"no-deprecated-cipher-method"(){return require("./rules/no-deprecated-cipher-method").noDeprecatedCipherMethod},get"no-ecb-mode"(){return require("./rules/no-ecb-mode").noEcbMode},get"no-insecure-key-derivation"(){return require("./rules/no-insecure-key-derivation").noInsecureKeyDerivation},get"no-insecure-rsa-padding"(){return require("./rules/no-insecure-rsa-padding").noInsecureRsaPadding},get"no-math-random-crypto"(){return require("./rules/no-math-random-crypto").noMathRandomCrypto},get"no-self-signed-certs"(){return require("./rules/no-self-signed-certs").noSelfSignedCerts},get"no-sha1-hash"(){return require("./rules/no-sha1-hash").noSha1Hash},get"no-static-iv"(){return require("./rules/no-static-iv").noStaticIv},get"no-timing-unsafe-compare"(){return require("./rules/no-timing-unsafe-compare").noTimingUnsafeCompare},get"no-weak-cipher-algorithm"(){return require("./rules/no-weak-cipher-algorithm").noWeakCipherAlgorithm},get"no-weak-hash-algorithm"(){return require("./rules/no-weak-hash-algorithm").noWeakHashAlgorithm},get"prefer-native-crypto"(){return require("./rules/prefer-native-crypto").preferNativeCrypto},get"require-aead-tag-verification"(){return require("./rules/require-aead-tag-verification").requireAeadTagVerification},get"no-unbounded-decompression"(){return require("./rules/no-unbounded-decompression").noUnboundedDecompression},get"no-insecure-http-parser"(){return require("./rules/no-insecure-http-parser").noInsecureHttpParser},get"require-stream-error-handler"(){return require("./rules/require-stream-error-handler").requireStreamErrorHandler}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-node-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-node-security",version:"5.4.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"detect-child-process"(){return require("./rules/detect-child-process").detectChildProcess},get"detect-eval-with-expression"(){return require("./rules/detect-eval-with-expression").detectEvalWithExpression},get"detect-non-literal-fs-filename"(){return require("./rules/detect-non-literal-fs-filename").detectNonLiteralFsFilename},get"no-unsafe-dynamic-require"(){return require("./rules/no-unsafe-dynamic-require").noUnsafeDynamicRequire},get"no-buffer-overread"(){return require("./rules/no-buffer-overread").noBufferOverread},get"no-deprecated-buffer"(){return require("./rules/no-deprecated-buffer").noDeprecatedBuffer},get"no-unsafe-buffer-alloc"(){return require("./rules/no-unsafe-buffer-alloc").noUnsafeBufferAlloc},get"no-toctou-vulnerability"(){return require("./rules/no-toctou-vulnerability").noToctouVulnerability},get"no-zip-slip"(){return require("./rules/no-zip-slip").noZipSlip},get"no-arbitrary-file-access"(){return require("./rules/no-arbitrary-file-access").noArbitraryFileAccess},get"no-data-in-temp-storage"(){return require("./rules/no-data-in-temp-storage").noDataInTempStorage},get"no-ssrf"(){return require("./rules/no-ssrf").noSsrf},get"no-shell-injection"(){return require("./rules/no-shell-injection").noShellInjection},get"no-dynamic-command-string"(){return require("./rules/no-dynamic-command-string").noDynamicCommandString},get"no-env-injection"(){return require("./rules/no-env-injection").noEnvInjection},get"no-dynamic-algorithm-selection"(){return require("./rules/no-dynamic-algorithm-selection").noDynamicAlgorithmSelection},get"detect-suspicious-dependencies"(){return require("./rules/detect-suspicious-dependencies").detectSuspiciousDependencies},get"lock-file"(){return require("./rules/lock-file").lockFile},get"no-dynamic-dependency-loading"(){return require("./rules/no-dynamic-dependency-loading").noDynamicDependencyLoading},get"require-dependency-integrity"(){return require("./rules/require-dependency-integrity").requireDependencyIntegrity},get"require-secure-credential-storage"(){return require("./rules/require-secure-credential-storage").requireSecureCredentialStorage},get"require-secure-deletion"(){return require("./rules/require-secure-deletion").requireSecureDeletion},get"require-storage-encryption"(){return require("./rules/require-storage-encryption").requireStorageEncryption},get"no-dynamic-require"(){return require("./rules/no-dynamic-require").noDynamicRequire},get"no-cryptojs"(){return require("./rules/no-cryptojs").noCryptojs},get"no-cryptojs-weak-random"(){return require("./rules/no-cryptojs-weak-random").noCryptojsWeakRandom},get"no-deprecated-cipher-method"(){return require("./rules/no-deprecated-cipher-method").noDeprecatedCipherMethod},get"no-ecb-mode"(){return require("./rules/no-ecb-mode").noEcbMode},get"no-insecure-key-derivation"(){return require("./rules/no-insecure-key-derivation").noInsecureKeyDerivation},get"no-insecure-rsa-padding"(){return require("./rules/no-insecure-rsa-padding").noInsecureRsaPadding},get"no-math-random-crypto"(){return require("./rules/no-math-random-crypto").noMathRandomCrypto},get"no-self-signed-certs"(){return require("./rules/no-self-signed-certs").noSelfSignedCerts},get"no-sha1-hash"(){return require("./rules/no-sha1-hash").noSha1Hash},get"no-static-iv"(){return require("./rules/no-static-iv").noStaticIv},get"no-timing-unsafe-compare"(){return require("./rules/no-timing-unsafe-compare").noTimingUnsafeCompare},get"no-weak-cipher-algorithm"(){return require("./rules/no-weak-cipher-algorithm").noWeakCipherAlgorithm},get"no-weak-hash-algorithm"(){return require("./rules/no-weak-hash-algorithm").noWeakHashAlgorithm},get"prefer-native-crypto"(){return require("./rules/prefer-native-crypto").preferNativeCrypto},get"require-aead-tag-verification"(){return require("./rules/require-aead-tag-verification").requireAeadTagVerification},get"no-unbounded-decompression"(){return require("./rules/no-unbounded-decompression").noUnboundedDecompression},get"no-insecure-http-parser"(){return require("./rules/no-insecure-http-parser").noInsecureHttpParser},get"require-stream-error-handler"(){return require("./rules/require-stream-error-handler").requireStreamErrorHandler}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-node-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-node-security",version:"5.4.4"},rules:exports.rules};const recommendedRules={"node-security/detect-child-process":"error","node-security/detect-eval-with-expression":"error","node-security/detect-non-literal-fs-filename":"warn","node-security/no-unsafe-dynamic-require":"error","node-security/no-buffer-overread":"warn","node-security/no-deprecated-buffer":"error","node-security/no-unsafe-buffer-alloc":"warn","node-security/no-toctou-vulnerability":"error","node-security/no-zip-slip":"error","node-security/no-arbitrary-file-access":"error","node-security/no-data-in-temp-storage":"error","node-security/no-ssrf":"warn","node-security/no-shell-injection":"error","node-security/no-dynamic-command-string":"error","node-security/no-env-injection":"error","node-security/no-dynamic-algorithm-selection":"error","node-security/no-timing-unsafe-compare":"warn","node-security/detect-suspicious-dependencies":"warn","node-security/require-dependency-integrity":"error","node-security/no-weak-hash-algorithm":"error","node-security/no-weak-cipher-algorithm":"error","node-security/no-static-iv":"error","node-security/no-ecb-mode":"error","node-security/no-math-random-crypto":"error","node-security/no-cryptojs":"error","node-security/no-self-signed-certs":"error","node-security/require-aead-tag-verification":"error","node-security/no-unbounded-decompression":"error","node-security/no-insecure-http-parser":"error","node-security/require-stream-error-handler":"error"};exports.configs={recommended:{plugins:{"node-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"node-security":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`node-security/${ruleName}`,"error"]))}};exports.default=exports.plugin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectChildProcess=exports.generateRefactoringSteps=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const DEFAULT_TAINT_SOURCES=["req","request","ctx","event","process"];const LOCAL_TAINT_ROOT="process";const SHELL_BINARIES=new Set(["sh","bash","zsh","dash","ksh","csh","tcsh","fish","ash","busybox","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe","env"]);const EVAL_INVOCATIONS=new Map([["node",new Set(["-e","--eval","-p","--print"])],["nodejs",new Set(["-e","--eval","-p","--print"])],["bun",new Set(["-e","--eval","-p","--print"])],["deno",new Set(["eval"])],["python",new Set(["-c"])],["python2",new Set(["-c"])],["python3",new Set(["-c"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])],["php",new Set(["-r"])],["osascript",new Set(["-e"])]]);const NO_EVAL_TOKENS=new Set;const EVAL_FLAGS=new Set(["-c","-e","--eval","-e:","/c","/k","-command","-encodedcommand","-p","--print","-e","-r","eval"]);const COMMAND_PATTERNS=[{method:"exec",dangerous:true,vulnerability:"command-injection",safeAlternatives:["execFile","spawn"],example:{bad:"exec(`git clone ${repoUrl}`)",good:["execFile('git', ['clone', repoUrl], {shell: false})","spawn('git', ['clone', repoUrl], {shell: false})"]},effort:"15-25 minutes"},{method:"execSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["execFileSync","spawnSync"],example:{bad:"execSync(`npm install ${packageName}`)",good:["execFileSync('npm', ['install', packageName], {shell: false})","spawnSync('npm', ['install', packageName], {shell: false})"]},effort:"15-25 minutes"},{method:"spawn",dangerous:false,vulnerability:"argument-injection",safeAlternatives:["spawn with validation"],example:{bad:"spawn('bash', ['-c', userCommand])",good:["spawn(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"20-30 minutes"},{method:"execFile",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawn"],example:{bad:"execFile(userCommand, userArgs, callback)",good:["spawn(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"10-15 minutes"},{method:"execFileSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawnSync"],example:{bad:"execFileSync(userCommand, userArgs)",good:["spawnSync(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"10-15 minutes"},{method:"spawnSync",dangerous:false,vulnerability:"argument-injection",safeAlternatives:["spawnSync with validation"],example:{bad:"spawnSync('bash', ['-c', userCommand])",good:["spawnSync(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"15-20 minutes"},{method:"fork",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawn"],example:{bad:"fork(userScript)",good:["spawn('node', [validatedScript], {shell: false})","// Validate script path first"]},effort:"15-20 minutes"},{method:"forkSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawnSync"],example:{bad:"forkSync(userScript)",good:["spawnSync('node', [validatedScript], {shell: false, stdio: 'inherit'})","// Validate script path first"]},effort:"15-20 minutes"}];const generateRefactoringSteps=pattern=>{switch(pattern.method){case"exec":case"execSync":return[" 1. Replace exec() with execFile() or spawn()"," 2. Split command and arguments into separate array elements"," 3. Use {shell: false} option to prevent shell interpretation"," 4. Validate and sanitize all user inputs"," 5. Consider using execa library for better security"].join("\n");case"spawn":return[" 1. Ensure first argument is a safe, validated command path"," 2. Pass arguments as separate array elements"," 3. Use {shell: false} to prevent shell injection"," 4. Validate command exists and is executable"," 5. Consider using cross-spawn for cross-platform safety"].join("\n");case"execFile":return[" 1. Replace execFile() with spawn() for better security"," 2. Validate command path before execution"," 3. Ensure arguments are properly sanitized"," 4. Use {shell: false} option"," 5. Consider using execa library"].join("\n");case"execFileSync":return[" 1. Replace execFileSync() with spawnSync() for better security"," 2. Validate command path before execution"," 3. Ensure arguments are properly sanitized"," 4. Use {shell: false} option"," 5. Consider using execa library"].join("\n");case"spawnSync":return[" 1. Ensure first argument is a safe, validated command path"," 2. Pass arguments as separate array elements"," 3. Use {shell: false} to prevent shell injection"," 4. Validate command exists and is executable"," 5. Handle synchronous execution properly"].join("\n");case"fork":return[" 1. Replace fork() with spawn() for Node.js scripts"," 2. Validate script path exists and is readable"," 3. Use spawn('node', [scriptPath], options) instead"," 4. Add proper error handling"," 5. Consider using child_process.execFile() for simple scripts"].join("\n");case"forkSync":return[" 1. Replace forkSync() with spawnSync() for Node.js scripts"," 2. Validate script path exists and is readable"," 3. Use spawnSync('node', [scriptPath], options) instead"," 4. Add proper error handling and synchronous waiting"," 5. Consider using child_process.execFileSync() for simple scripts"].join("\n");default:return[" 1. Identify the specific command execution need"," 2. Choose appropriate child_process method"," 3. Use argument arrays instead of string interpolation"," 4. Add comprehensive input validation"," 5. Test with malicious inputs"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;exports.detectChildProcess=(0,eslint_devkit_2.createRule)({name:"detect-child-process",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-child-process.md",description:"Detects child_process usage that may allow command injection",cwe:"CWE-78",cvss:9.8,confidence:"medium"},messages:{childProcessCommandInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Command injection",cwe:"CWE-78",description:"Command injection detected",severity:"CRITICAL",fix:"Use execFile/spawn with {shell: false} and array args",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"}),untrustedProgram:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Untrusted program",cwe:"CWE-114",description:"The executable name is attacker-steerable. No shell runs here, so metacharacters are inert \u2014 but the caller still chooses which program executes.",severity:"HIGH",fix:"Resolve the name against a fixed allowlist of permitted executables before spawning it.",documentationLink:"https://cwe.mitre.org/data/definitions/114.html"}),argumentInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Argument injection",cwe:"CWE-88",description:"An attacker-steered value sits in the argv vector with no `--` before it. There is no shell here, but the callee still parses a leading `-` as an option \u2014 `--upload-pack=` (git), `--to-command=` (tar), `-o ProxyCommand=` (ssh) all execute arbitrary programs.",severity:"HIGH",fix:"Insert a literal '--' before the first attacker-controlled element, or reject values beginning with '-'.",documentationLink:"https://cwe.mitre.org/data/definitions/88.html"})},schema:[{type:"object",properties:{allowLiteralStrings:{type:"boolean",default:false,description:"Allow exec() with literal strings"},allowLiteralSpawn:{type:"boolean",default:false,description:"Allow spawn() with literal arguments"},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional child_process methods to check"},taintSources:{type:"array",items:{type:"string"},default:DEFAULT_TAINT_SOURCES,description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},reportUnresolvedCommands:{type:"boolean",default:false,description:'Report a command whose provenance cannot be resolved. Restores the pre-inversion "any dynamic argument is dangerous" behaviour.'}},additionalProperties:false}]},defaultOptions:[{allowLiteralStrings:false,allowLiteralSpawn:false,additionalMethods:[]}],create(context){const options=context.options[0]||{};const{allowLiteralStrings=false,allowLiteralSpawn=false,additionalMethods=[]}=options;const taintRoots=new Set((options.taintSources??DEFAULT_TAINT_SOURCES).map(source=>source.toLowerCase()));const readsTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,taintRoots);const readsRemoteTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,new Set([...taintRoots].filter(root=>root!==LOCAL_TAINT_ROOT)));const reportUnresolvedCommands=options.reportUnresolvedCommands??false;const dangerousMethodsSet=new Set(["exec","execSync","execFile","execFileSync","spawn","spawnSync","fork","forkSync",...additionalMethods]);const isChildProcessSpecifier=value=>value==="child_process"||value==="node:child_process";const moduleAliases=new Set(["child_process"]);const importedMethods=new Set;const containsDynamicStrings=node=>!(0,eslint_devkit_2.isStaticExpression)({node,scope:context.sourceCode.getScope(node)});const isFreeReference=node=>{const name=node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node:node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.callee:null;if(!name)return false;return context.sourceCode.getScope(name).through.some(ref=>ref.identifier===name&&ref.resolved===null)};const isStaticArg=argument=>(0,eslint_devkit_2.isStaticExpression)({node:argument,scope:context.sourceCode.getScope(argument)});const hasOnlyLiteralArgs=args=>{if(args.length===0)return false;if(!isStaticArg(args[0])){return false}if(args.length>=2){const argsArray=args[1];if(argsArray.type==="ArrayExpression"){const allLiteralElements=argsArray.elements.every(el=>el!==null&&isStaticArg(el));if(!allLiteralElements){return false}}else if(!isStaticArg(argsArray)){return false}}return true};const usesShell=(node,method)=>{if(method==="exec"||method==="execSync")return true;const command=node.arguments[0];if(command!==void 0&&command.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof command.value==="string"&&SHELL_BINARIES.has(command.value.replace(/^.*[/\\]/,"").toLowerCase())){return true}const namedBinary=command!==void 0&&command.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof command.value==="string"?command.value.replace(/^.*[/\\]/,"").toLowerCase():null;const evalTokens=namedBinary===null?EVAL_FLAGS:EVAL_INVOCATIONS.get(namedBinary)??NO_EVAL_TOKENS;const argv=node.arguments[1];if(argv?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of argv.elements){if(element?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof element.value==="string"&&evalTokens.has(element.value.toLowerCase())){return true}}}for(const candidate of[node.arguments[1],node.arguments[2]]){if(!candidate||candidate.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)continue;for(const property of candidate.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||property.key.name!=="shell"){continue}return!(property.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value.value===false)}}return false};const cannotStartWithDash=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const first=node.quasis[0].value.raw;return first.length>0&&!first.startsWith("-")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=node.left;return left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof left.value==="string"&&left.value.length>0&&!left.value.startsWith("-")}return false};const argumentInjectionSite=node=>{const argv=node.arguments[1];if(argv?.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;for(const element of argv.elements){if(element===null)continue;if(element.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&element.value==="--"){return null}if(!readsRemoteTaintSource(element))continue;const target=element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement?element.argument:element;if(cannotStartWithDash(target))continue;return element}return null};const hasShellFalseOption=node=>{const optionsArg=node.arguments[2];if(!optionsArg||optionsArg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return true}for(const prop of optionsArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="shell"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===false){return true}return false}}return true};const hasPrecedingAllowlistValidation=node=>{const makeArgChecker=validatedVarNames=>{const check=argNode=>{if(argNode.type==="Identifier"&&validatedVarNames.has(argNode.name))return true;if(argNode.type==="TemplateLiteral"){return argNode.expressions.some(e=>e.type==="Identifier"&&validatedVarNames.has(e.name))}if(argNode.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return argNode.elements.some(el=>el!==null&&check(el))}return false};return check};const checkGuardClause=ifNode=>{const test=ifNode.test;if(test.type==="CallExpression"&&test.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(test.callee)==="includes"){const validatedVarNames=new Set;for(const testArg of test.arguments){if(testArg.type==="Identifier")validatedVarNames.add(testArg.name)}const check=makeArgChecker(validatedVarNames);for(const arg of node.arguments){if(check(arg))return true}}if(test.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&test.operator==="!"&&test.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&test.argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(test.argument.callee)==="includes"){const consequent=ifNode.consequent;const isGuardBody=consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&consequent.body.length>0&&(consequent.body[0].type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||consequent.body[0].type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement);if(isGuardBody){const validatedVarNames=new Set;for(const testArg of test.argument.arguments){if(testArg.type==="Identifier")validatedVarNames.add(testArg.name)}const check=makeArgChecker(validatedVarNames.size>0?validatedVarNames:new Set(["*"]));if(validatedVarNames.size>0){for(const arg of node.arguments){if(check(arg))return true}}else{for(const arg of node.arguments){if(arg.type==="Identifier"||arg.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&arg.elements.some(el=>el?.type==="Identifier")){return true}}}}}return false};let current=node.parent;while(current){if(current.type==="IfStatement"){if(checkGuardClause(current))return true}current=current.parent}let stmt=node.parent;while(stmt&&stmt.parent&&stmt.parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement){stmt=stmt.parent}if(stmt&&stmt.parent&&stmt.parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const block=stmt.parent;const callIndex=block.body.indexOf(stmt);if(callIndex>0){for(let i=0;i<callIndex;i++){const sibling=block.body[i];if(sibling.type==="IfStatement"){if(checkGuardClause(sibling))return true}}}}return false};const extractCommandInfo=(node,method)=>{const sourceCode=context.sourceCode;const args=node.arguments.map(arg=>sourceCode.getText(arg)).join(", ");const pattern=COMMAND_PATTERNS.find(p=>p.method===method)||null;const injectableArgs=node.arguments.slice(0,1);const argvArray=node.arguments[1];if(argvArray?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){injectableArgs.push(...argvArray.elements.filter(el=>el!==null))}const isDynamic=injectableArgs.some(arg=>containsDynamicStrings(arg));return{args,pattern,isDynamic}};const determineRiskLevel=(pattern,isDynamic)=>{if(pattern?.dangerous&&isDynamic){return"critical"}if(pattern?.dangerous||isDynamic){return"high"}return"medium"};const isChildProcessRequire=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&isChildProcessSpecifier(node.arguments[0].value);const childProcessMemberName=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;for(let scope=context.sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const[def]=variable.defs;if(def?.type==="ImportBinding"){const declaration=def.parent;if(declaration?.type!==eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration||!isChildProcessSpecifier(declaration.source.value)||def.node.type!==eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){return null}return def.node.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?def.node.imported.name:String(def.node.imported.value)}if(def?.type==="Variable"){const declarator=def.node;if(declarator.init==null||!isChildProcessRequire(declarator.init)||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern){return null}for(const property of declarator.id.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===node.name&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return property.key.name}}}return null}return null};const resolvesToChildProcess=(node,fallback)=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let scope=context.sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const[def]=variable.defs;if(def?.type==="ImportBinding"){const declaration=def.parent;return declaration?.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&isChildProcessSpecifier(declaration.source.value)}if(def?.type==="Variable"){return def.node.init!=null&&isChildProcessRequire(def.node.init)}return false}return fallback.has(node.name)};const getChildProcessCall=node=>{if(node.callee.type==="MemberExpression"){const methodName=(0,eslint_devkit_1.propertyName)(node.callee);if(methodName===null||!dangerousMethodsSet.has(methodName)){return null}if(resolvesToChildProcess(node.callee.object,moduleAliases)){return{method:methodName,calleeNode:node.callee}}if(isChildProcessRequire(node.callee.object)){return{method:methodName,calleeNode:node.callee}}}const member=childProcessMemberName(node.callee);if(member!==null&&dangerousMethodsSet.has(member)){return{method:member,calleeNode:node.callee}}if(node.callee.type==="Identifier"&&dangerousMethodsSet.has(node.callee.name)){if(resolvesToChildProcess(node.callee,importedMethods)){return{method:node.callee.name,calleeNode:node.callee}}}return null};const checkChildProcessCall=node=>{const detected=getChildProcessCall(node);if(!detected){return}const{method}=detected;const{args,pattern,isDynamic}=extractCommandInfo(node,method);if((method==="exec"||method==="execSync")&&!isDynamic&&hasOnlyLiteralArgs(node.arguments)){return}if(allowLiteralStrings&&method==="exec"&&!isDynamic){return}const saferMethods=new Set(["spawn","spawnSync","execFile","execFileSync"]);if(allowLiteralSpawn&&saferMethods.has(method)&&hasOnlyLiteralArgs(node.arguments)){return}if(saferMethods.has(method)&&hasOnlyLiteralArgs(node.arguments)){const isExecFile=method==="execFile"||method==="execFileSync";if(isExecFile||hasShellFalseOption(node)){return}}const allSafeMethods=["execFile","execFileSync","spawn","spawnSync"];if(allSafeMethods.includes(method)&&hasPrecedingAllowlistValidation(node)){return}const command=node.arguments[0];const commandIsSteerable=command===void 0||isFreeReference(command)||readsRemoteTaintSource(command);if(!usesShell(node,method)&&!commandIsSteerable){const injected=argumentInjectionSite(node);if(injected===null)return;context.report({node:injected,messageId:"argumentInjection"});return}const injectablePositions=node.arguments.slice(0,1);const argvVector=node.arguments[1];if(argvVector?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){injectablePositions.push(...argvVector.elements.filter(el=>el!==null))}const unknowable=injectablePositions.some(argument=>isFreeReference(argument));if(!reportUnresolvedCommands&&!unknowable&&!node.arguments.some(argument=>readsTaintSource(argument))){return}const riskLevel=determineRiskLevel(pattern,isDynamic);const steps=pattern?(0,exports.generateRefactoringSteps)(pattern):"Review and secure command execution";const alternatives=pattern?.safeAlternatives.join(", ")||"execFile, spawn with validation";context.report({node,messageId:usesShell(node,method)?"childProcessCommandInjection":"untrustedProgram",data:{method,args,riskLevel,vulnerability:pattern?.vulnerability||"command injection",alternatives,steps,effort:pattern?.effort||"15-30 minutes"}})};const trackChildProcessImport=node=>{if(!isChildProcessSpecifier(node.source.value)){return}for(const specifier of node.specifiers){if(specifier.type==="ImportDefaultSpecifier"||specifier.type==="ImportNamespaceSpecifier"){moduleAliases.add(specifier.local.name)}if(specifier.type==="ImportSpecifier"){importedMethods.add(specifier.local.name)}}};const trackChildProcessRequire=node=>{if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]&&node.init.arguments[0].type==="Literal"&&isChildProcessSpecifier(node.init.arguments[0].value)){moduleAliases.add(node.id.name);return}if(node.id.type==="ObjectPattern"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]&&node.init.arguments[0].type==="Literal"&&isChildProcessSpecifier(node.init.arguments[0].value)){for(const prop of node.id.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){importedMethods.add(prop.value.type==="Identifier"?prop.value.name:prop.key.name)}}}};const checkBareChildProcessRequire=node=>{if(!isChildProcessRequire(node))return;const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===node)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===node)return;context.report({node,messageId:"childProcessCommandInjection",data:{method:"require",riskLevel:"MEDIUM",vulnerability:"command-injection",safeAlternatives:"execFile, spawn",refactoringSteps:" 1. Avoid importing child_process where it is not needed\n 2. If required, prefer execFile()/spawn() with {shell: false}\n 3. Validate any command or argument that is not a literal",effort:"10-15 minutes",badExample:"require('child_process')",goodExample:"const { execFile } = require('node:child_process')"}})};return{CallExpression(node){checkChildProcessCall(node);checkBareChildProcessRequire(node)},ImportDeclaration:trackChildProcessImport,VariableDeclarator:trackChildProcessRequire}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectChildProcess=exports.generateRefactoringSteps=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const DEFAULT_TAINT_SOURCES=["req","request","ctx","event","process"];const LOCAL_TAINT_ROOT="process";const SHELL_BINARIES=new Set(["sh","bash","zsh","dash","ksh","csh","tcsh","fish","ash","busybox","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe","env"]);const EVAL_INVOCATIONS=new Map([["node",new Set(["-e","--eval","-p","--print"])],["nodejs",new Set(["-e","--eval","-p","--print"])],["bun",new Set(["-e","--eval","-p","--print"])],["deno",new Set(["eval"])],["python",new Set(["-c"])],["python2",new Set(["-c"])],["python3",new Set(["-c"])],["ruby",new Set(["-e"])],["perl",new Set(["-e","-E"])],["php",new Set(["-r"])],["osascript",new Set(["-e"])]]);const NO_EVAL_TOKENS=new Set;const EVAL_FLAGS=new Set(["-c","-e","--eval","-e:","/c","/k","-command","-encodedcommand","-p","--print","-e","-r","eval"]);const COMMAND_PATTERNS=[{method:"exec",dangerous:true,vulnerability:"command-injection",safeAlternatives:["execFile","spawn"],example:{bad:"exec(`git clone ${repoUrl}`)",good:["execFile('git', ['clone', repoUrl], {shell: false})","spawn('git', ['clone', repoUrl], {shell: false})"]},effort:"15-25 minutes"},{method:"execSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["execFileSync","spawnSync"],example:{bad:"execSync(`npm install ${packageName}`)",good:["execFileSync('npm', ['install', packageName], {shell: false})","spawnSync('npm', ['install', packageName], {shell: false})"]},effort:"15-25 minutes"},{method:"spawn",dangerous:false,vulnerability:"argument-injection",safeAlternatives:["spawn with validation"],example:{bad:"spawn('bash', ['-c', userCommand])",good:["spawn(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"20-30 minutes"},{method:"execFile",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawn"],example:{bad:"execFile(userCommand, userArgs, callback)",good:["spawn(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"10-15 minutes"},{method:"execFileSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawnSync"],example:{bad:"execFileSync(userCommand, userArgs)",good:["spawnSync(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"10-15 minutes"},{method:"spawnSync",dangerous:false,vulnerability:"argument-injection",safeAlternatives:["spawnSync with validation"],example:{bad:"spawnSync('bash', ['-c', userCommand])",good:["spawnSync(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"15-20 minutes"},{method:"fork",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawn"],example:{bad:"fork(userScript)",good:["spawn('node', [validatedScript], {shell: false})","// Validate script path first"]},effort:"15-20 minutes"},{method:"forkSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawnSync"],example:{bad:"forkSync(userScript)",good:["spawnSync('node', [validatedScript], {shell: false, stdio: 'inherit'})","// Validate script path first"]},effort:"15-20 minutes"}];const generateRefactoringSteps=pattern=>{switch(pattern.method){case"exec":case"execSync":return[" 1. Replace exec() with execFile() or spawn()"," 2. Split command and arguments into separate array elements"," 3. Use {shell: false} option to prevent shell interpretation"," 4. Validate and sanitize all user inputs"," 5. Consider using execa library for better security"].join("\n");case"spawn":return[" 1. Ensure first argument is a safe, validated command path"," 2. Pass arguments as separate array elements"," 3. Use {shell: false} to prevent shell injection"," 4. Validate command exists and is executable"," 5. Consider using cross-spawn for cross-platform safety"].join("\n");case"execFile":return[" 1. Replace execFile() with spawn() for better security"," 2. Validate command path before execution"," 3. Ensure arguments are properly sanitized"," 4. Use {shell: false} option"," 5. Consider using execa library"].join("\n");case"execFileSync":return[" 1. Replace execFileSync() with spawnSync() for better security"," 2. Validate command path before execution"," 3. Ensure arguments are properly sanitized"," 4. Use {shell: false} option"," 5. Consider using execa library"].join("\n");case"spawnSync":return[" 1. Ensure first argument is a safe, validated command path"," 2. Pass arguments as separate array elements"," 3. Use {shell: false} to prevent shell injection"," 4. Validate command exists and is executable"," 5. Handle synchronous execution properly"].join("\n");case"fork":return[" 1. Replace fork() with spawn() for Node.js scripts"," 2. Validate script path exists and is readable"," 3. Use spawn('node', [scriptPath], options) instead"," 4. Add proper error handling"," 5. Consider using child_process.execFile() for simple scripts"].join("\n");case"forkSync":return[" 1. Replace forkSync() with spawnSync() for Node.js scripts"," 2. Validate script path exists and is readable"," 3. Use spawnSync('node', [scriptPath], options) instead"," 4. Add proper error handling and synchronous waiting"," 5. Consider using child_process.execFileSync() for simple scripts"].join("\n");default:return[" 1. Identify the specific command execution need"," 2. Choose appropriate child_process method"," 3. Use argument arrays instead of string interpolation"," 4. Add comprehensive input validation"," 5. Test with malicious inputs"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;exports.detectChildProcess=(0,eslint_devkit_2.createRule)({name:"detect-child-process",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-child-process.md",description:"Detects child_process usage that may allow command injection",cwe:"CWE-78",cvss:9.8,confidence:"medium"},messages:{childProcessCommandInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Command injection",cwe:"CWE-78",description:"Command injection detected",severity:"CRITICAL",fix:"Use execFile/spawn with {shell: false} and array args",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"}),untrustedProgram:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Untrusted program",cwe:"CWE-114",description:"The executable name is attacker-steerable. No shell runs here, so metacharacters are inert \u2014 but the caller still chooses which program executes.",severity:"HIGH",fix:"Resolve the name against a fixed allowlist of permitted executables before spawning it.",documentationLink:"https://cwe.mitre.org/data/definitions/114.html"}),argumentInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Argument injection",cwe:"CWE-88",description:"An attacker-steered value sits in the argv vector with no `--` before it. There is no shell here, but the callee still parses a leading `-` as an option \u2014 `--upload-pack=` (git), `--to-command=` (tar), `-o ProxyCommand=` (ssh) all execute arbitrary programs.",severity:"HIGH",fix:"Insert a literal '--' before the first attacker-controlled element, or reject values beginning with '-'.",documentationLink:"https://cwe.mitre.org/data/definitions/88.html"})},schema:[{type:"object",properties:{allowLiteralStrings:{type:"boolean",default:false,description:"Allow exec() with literal strings"},allowLiteralSpawn:{type:"boolean",default:false,description:"Allow spawn() with literal arguments"},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional child_process methods to check"},taintSources:{type:"array",items:{type:"string"},default:DEFAULT_TAINT_SOURCES,description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},reportUnresolvedCommands:{type:"boolean",default:false,description:'Report a command whose provenance cannot be resolved. Restores the pre-inversion "any dynamic argument is dangerous" behaviour.'}},additionalProperties:false}]},defaultOptions:[{allowLiteralStrings:false,allowLiteralSpawn:false,additionalMethods:[]}],create(context){const options=context.options[0]||{};const{allowLiteralStrings=false,allowLiteralSpawn=false,additionalMethods=[]}=options;const taintRoots=new Set((options.taintSources??DEFAULT_TAINT_SOURCES).map(source=>source.toLowerCase()));const readsTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,taintRoots);const readsRemoteTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,new Set([...taintRoots].filter(root=>root!==LOCAL_TAINT_ROOT)));const reportUnresolvedCommands=options.reportUnresolvedCommands??false;const dangerousMethodsSet=new Set(["exec","execSync","execFile","execFileSync","spawn","spawnSync","fork","forkSync",...additionalMethods]);const isChildProcessSpecifier=value=>value==="child_process"||value==="node:child_process";const moduleAliases=new Set(["child_process"]);const importedMethods=new Set;const containsDynamicStrings=node=>!(0,eslint_devkit_2.isStaticExpression)({node,scope:context.sourceCode.getScope(node)});const isFreeReference=node=>{const name=node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node:node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.callee:null;if(!name)return false;return context.sourceCode.getScope(name).through.some(ref=>ref.identifier===name&&ref.resolved===null)};const isStaticArg=argument=>(0,eslint_devkit_2.isStaticExpression)({node:argument,scope:context.sourceCode.getScope(argument)});const hasOnlyLiteralArgs=args=>{if(args.length===0)return false;if(!isStaticArg(args[0])){return false}if(args.length>=2){const argsArray=args[1];if(argsArray.type==="ArrayExpression"){const allLiteralElements=argsArray.elements.every(el=>el!==null&&isStaticArg(el));if(!allLiteralElements){return false}}else if(!isStaticArg(argsArray)){return false}}return true};const usesShell=(node,method)=>{if(method==="exec"||method==="execSync")return true;const command=node.arguments[0];if(command!==void 0&&command.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof command.value==="string"&&SHELL_BINARIES.has(command.value.replace(/^.*[/\\]/,"").toLowerCase())){return true}const namedBinary=command!==void 0&&command.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof command.value==="string"?command.value.replace(/^.*[/\\]/,"").toLowerCase():null;const evalTokens=namedBinary===null?EVAL_FLAGS:EVAL_INVOCATIONS.get(namedBinary)??NO_EVAL_TOKENS;const argv=node.arguments[1];if(argv?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of argv.elements){if(element?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof element.value==="string"&&evalTokens.has(element.value.toLowerCase())){return true}}}for(const candidate of[node.arguments[1],node.arguments[2]]){if(!candidate||candidate.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)continue;for(const property of candidate.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||(0,eslint_devkit_1.objectKeyName)(property)!=="shell"){continue}return!(property.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value.value===false)}}return false};const cannotStartWithDash=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const first=node.quasis[0].value.raw;return first.length>0&&!first.startsWith("-")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=node.left;return left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof left.value==="string"&&left.value.length>0&&!left.value.startsWith("-")}return false};const argumentInjectionSite=node=>{const argv=node.arguments[1];if(argv?.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;for(const element of argv.elements){if(element===null)continue;if((0,eslint_devkit_1.staticString)(element)==="--"){return null}if(!readsRemoteTaintSource(element))continue;const target=element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement?element.argument:element;if(cannotStartWithDash(target))continue;return element}return null};const hasShellFalseOption=node=>{const optionsArg=node.arguments[2];if(!optionsArg||optionsArg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return true}for(const prop of optionsArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(prop)==="shell"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===false){return true}return false}}return true};const hasPrecedingAllowlistValidation=node=>{const makeArgChecker=validatedVarNames=>{const check=argNode=>{if(argNode.type==="Identifier"&&validatedVarNames.has(argNode.name))return true;if(argNode.type==="TemplateLiteral"){return argNode.expressions.some(e=>e.type==="Identifier"&&validatedVarNames.has(e.name))}if(argNode.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return argNode.elements.some(el=>el!==null&&check(el))}return false};return check};const checkGuardClause=ifNode=>{const test=ifNode.test;if(test.type==="CallExpression"&&test.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(test.callee)==="includes"){const validatedVarNames=new Set;for(const testArg of test.arguments){if(testArg.type==="Identifier")validatedVarNames.add(testArg.name)}const check=makeArgChecker(validatedVarNames);for(const arg of node.arguments){if(check(arg))return true}}if(test.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&test.operator==="!"&&test.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&test.argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(test.argument.callee)==="includes"){const consequent=ifNode.consequent;const isGuardBody=consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&consequent.body.length>0&&(consequent.body[0].type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||consequent.body[0].type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement);if(isGuardBody){const validatedVarNames=new Set;for(const testArg of test.argument.arguments){if(testArg.type==="Identifier")validatedVarNames.add(testArg.name)}const check=makeArgChecker(validatedVarNames.size>0?validatedVarNames:new Set(["*"]));if(validatedVarNames.size>0){for(const arg of node.arguments){if(check(arg))return true}}else{for(const arg of node.arguments){if(arg.type==="Identifier"||arg.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&arg.elements.some(el=>el?.type==="Identifier")){return true}}}}}return false};let current=node.parent;while(current){if(current.type==="IfStatement"){if(checkGuardClause(current))return true}current=current.parent}let stmt=node.parent;while(stmt&&stmt.parent&&stmt.parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement){stmt=stmt.parent}if(stmt&&stmt.parent&&stmt.parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const block=stmt.parent;const callIndex=block.body.indexOf(stmt);if(callIndex>0){for(let i=0;i<callIndex;i++){const sibling=block.body[i];if(sibling.type==="IfStatement"){if(checkGuardClause(sibling))return true}}}}return false};const extractCommandInfo=(node,method)=>{const sourceCode=context.sourceCode;const args=node.arguments.map(arg=>sourceCode.getText(arg)).join(", ");const pattern=COMMAND_PATTERNS.find(p=>p.method===method)||null;const injectableArgs=node.arguments.slice(0,1);const argvArray=node.arguments[1];if(argvArray?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){injectableArgs.push(...argvArray.elements.filter(el=>el!==null))}const isDynamic=injectableArgs.some(arg=>containsDynamicStrings(arg));return{args,pattern,isDynamic}};const determineRiskLevel=(pattern,isDynamic)=>{if(pattern?.dangerous&&isDynamic){return"critical"}if(pattern?.dangerous||isDynamic){return"high"}return"medium"};const isChildProcessRequire=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&isChildProcessSpecifier(node.arguments[0].value);const childProcessMemberName=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;for(let scope=context.sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const[def]=variable.defs;if(def?.type==="ImportBinding"){const declaration=def.parent;if(declaration?.type!==eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration||!isChildProcessSpecifier(declaration.source.value)||def.node.type!==eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){return null}return def.node.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?def.node.imported.name:String(def.node.imported.value)}if(def?.type==="Variable"){const declarator=def.node;if(declarator.init==null||!isChildProcessRequire(declarator.init)||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern){return null}for(const property of declarator.id.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===node.name&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return property.key.name}}}return null}return null};const resolvesToChildProcess=(node,fallback)=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let scope=context.sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const[def]=variable.defs;if(def?.type==="ImportBinding"){const declaration=def.parent;return declaration?.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&isChildProcessSpecifier(declaration.source.value)}if(def?.type==="Variable"){return def.node.init!=null&&isChildProcessRequire(def.node.init)}return false}return fallback.has(node.name)};const getChildProcessCall=node=>{if(node.callee.type==="MemberExpression"){const methodName=(0,eslint_devkit_1.propertyName)(node.callee);if(methodName===null||!dangerousMethodsSet.has(methodName)){return null}if(resolvesToChildProcess(node.callee.object,moduleAliases)){return{method:methodName,calleeNode:node.callee}}if(isChildProcessRequire(node.callee.object)){return{method:methodName,calleeNode:node.callee}}}const member=childProcessMemberName(node.callee);if(member!==null&&dangerousMethodsSet.has(member)){return{method:member,calleeNode:node.callee}}if(node.callee.type==="Identifier"&&dangerousMethodsSet.has(node.callee.name)){if(resolvesToChildProcess(node.callee,importedMethods)){return{method:node.callee.name,calleeNode:node.callee}}}return null};const checkChildProcessCall=node=>{const detected=getChildProcessCall(node);if(!detected){return}const{method}=detected;const{args,pattern,isDynamic}=extractCommandInfo(node,method);if((method==="exec"||method==="execSync")&&!isDynamic&&hasOnlyLiteralArgs(node.arguments)){return}if(allowLiteralStrings&&method==="exec"&&!isDynamic){return}const saferMethods=new Set(["spawn","spawnSync","execFile","execFileSync"]);if(allowLiteralSpawn&&saferMethods.has(method)&&hasOnlyLiteralArgs(node.arguments)){return}if(saferMethods.has(method)&&hasOnlyLiteralArgs(node.arguments)){const isExecFile=method==="execFile"||method==="execFileSync";if(isExecFile||hasShellFalseOption(node)){return}}const allSafeMethods=["execFile","execFileSync","spawn","spawnSync"];if(allSafeMethods.includes(method)&&hasPrecedingAllowlistValidation(node)){return}const command=node.arguments[0];const commandIsSteerable=command===void 0||isFreeReference(command)||readsRemoteTaintSource(command);if(!usesShell(node,method)&&!commandIsSteerable){const injected=argumentInjectionSite(node);if(injected===null)return;context.report({node:injected,messageId:"argumentInjection"});return}const injectablePositions=node.arguments.slice(0,1);const argvVector=node.arguments[1];if(argvVector?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){injectablePositions.push(...argvVector.elements.filter(el=>el!==null))}const unknowable=injectablePositions.some(argument=>isFreeReference(argument));if(!reportUnresolvedCommands&&!unknowable&&!node.arguments.some(argument=>readsTaintSource(argument))){return}const riskLevel=determineRiskLevel(pattern,isDynamic);const steps=pattern?(0,exports.generateRefactoringSteps)(pattern):"Review and secure command execution";const alternatives=pattern?.safeAlternatives.join(", ")||"execFile, spawn with validation";context.report({node,messageId:usesShell(node,method)?"childProcessCommandInjection":"untrustedProgram",data:{method,args,riskLevel,vulnerability:pattern?.vulnerability||"command injection",alternatives,steps,effort:pattern?.effort||"15-30 minutes"}})};const trackChildProcessImport=node=>{if(!isChildProcessSpecifier(node.source.value)){return}for(const specifier of node.specifiers){if(specifier.type==="ImportDefaultSpecifier"||specifier.type==="ImportNamespaceSpecifier"){moduleAliases.add(specifier.local.name)}if(specifier.type==="ImportSpecifier"){importedMethods.add(specifier.local.name)}}};const trackChildProcessRequire=node=>{if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]&&node.init.arguments[0].type==="Literal"&&isChildProcessSpecifier(node.init.arguments[0].value)){moduleAliases.add(node.id.name);return}if(node.id.type==="ObjectPattern"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]&&node.init.arguments[0].type==="Literal"&&isChildProcessSpecifier(node.init.arguments[0].value)){for(const prop of node.id.properties){if(prop.type!=="Property")continue;const imported=prop.value.type==="Identifier"?prop.value.name:(0,eslint_devkit_1.objectKeyName)(prop);if(imported!==null)importedMethods.add(imported)}}};const checkBareChildProcessRequire=node=>{if(!isChildProcessRequire(node))return;const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===node)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===node)return;context.report({node,messageId:"childProcessCommandInjection",data:{method:"require",riskLevel:"MEDIUM",vulnerability:"command-injection",safeAlternatives:"execFile, spawn",refactoringSteps:" 1. Avoid importing child_process where it is not needed\n 2. If required, prefer execFile()/spawn() with {shell: false}\n 3. Validate any command or argument that is not a literal",effort:"10-15 minutes",badExample:"require('child_process')",goodExample:"const { execFile } = require('node:child_process')"}})};return{CallExpression(node){checkChildProcessCall(node);checkBareChildProcessRequire(node)},ImportDeclaration:trackChildProcessImport,VariableDeclarator:trackChildProcessRequire}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectNonLiteralFsFilename=exports.determineRiskLevel=exports.isFsModule=exports.generateRefactoringSteps=void 0;exports.fsMethodName=fsMethodName;exports.isFsRequire=isFsRequire;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const FS_OPERATIONS=[{method:"readFile",dangerous:true,vulnerability:"file-access",safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))",example:{bad:"fs.readFile(userPath, callback)",good:"const safePath = path.join(SAFE_UPLOADS_DIR, path.basename(userPath)); fs.readFile(safePath, callback)"},effort:"10-15 minutes"},{method:"writeFile",dangerous:true,vulnerability:"file-access",safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))",example:{bad:"fs.writeFile(userPath, data, callback)",good:"const safePath = path.join(SAFE_WRITES_DIR, path.basename(userPath)); fs.writeFile(safePath, data, callback)"},effort:"10-15 minutes"},{method:"stat",dangerous:true,vulnerability:"path-traversal",safePattern:"path.resolve(baseDir, userInput) with validation",example:{bad:"fs.stat(userPath, callback)",good:"const resolvedPath = path.resolve(SAFE_DIR, userPath);\nif (!resolvedPath.startsWith(SAFE_DIR + path.sep)) return;\nfs.stat(resolvedPath, callback)"},effort:"15-20 minutes"},{method:"readdir",dangerous:true,vulnerability:"directory-traversal",safePattern:"Validate directory is within allowed paths",example:{bad:"fs.readdir(userDir, callback)",good:"const resolvedDir = path.resolve(ALLOWED_DIRS, userDir);\nif (!resolvedDir.startsWith(ALLOWED_DIRS + path.sep)) return;\nfs.readdir(resolvedDir, callback)"},effort:"15-20 minutes"}];const hasTraversalPatterns=pathStr=>{return/\.\.[/\\]/.test(pathStr)||/^\.\.[/\\]/.test(pathStr)};const PROCESS_INPUT_MEMBERS=new Set(["env","argv","argv0","execArgv","stdin"]);const SENSITIVE_SEGMENTS=["etc/passwd","etc/shadow","etc/hosts","etc/sudoers","proc/self",".ssh/id_rsa",".ssh/id_dsa",".ssh/authorized_keys",".aws/credentials",".npmrc",".git/config","windows/system32/config/sam"];const targetsSensitiveLocation=pathStr=>{const unquoted=pathStr.replace(/^['"`]|['"`]$/g,"");const normalised=unquoted.replace(/\\/g,"/").toLowerCase();if(!/(^|\/)\.\.(\/|$)/.test(normalised)){return false}const withoutPrefix=normalised.replace(/^(?:\.{1,2}\/)+/,"");return SENSITIVE_SEGMENTS.some(seg=>withoutPrefix===seg||withoutPrefix.endsWith(`/${seg}`)||withoutPrefix.startsWith(`${seg}/`))};const generateRefactoringSteps=operation=>{switch(operation.method){case"readFile":case"writeFile":return[" 1. Define a SAFE_DIR constant for allowed operations"," 2. Use path.basename() to strip directory components"," 3. Combine with SAFE_DIR: path.join(SAFE_DIR, path.basename(userPath))"," 4. Optionally validate file extensions"," 5. Add error handling for invalid paths"].join("\n");case"stat":return[" 1. Use path.resolve() to normalize the path"," 2. Check the resolved path starts with the base PLUS path.sep \u2014 a bare"," prefix lets /safebad through a /safe check"," 3. Reject requests that escape the allowed directory"," 4. Use path.relative() for additional validation"," 5. Log security events for monitoring"].join("\n");case"readdir":return[" 1. Resolve the directory path: path.resolve(ALLOWED_DIRS, userDir)"," 2. Validate resolved path starts with ALLOWED_DIRS"," 3. Check directory exists and is readable"," 4. Consider whitelisting allowed directories"," 5. Add rate limiting to prevent enumeration attacks"].join("\n");default:return[" 1. Identify the specific file operation needed"," 2. Define safe base directories for operations"," 3. Use path.resolve() and validate containment"," 4. Sanitize user input (basename, extension validation)"," 5. Add comprehensive error handling"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;const FS_MODULE_EQUIVALENTS={"fs-extra":"fs","graceful-fs":"fs","fs/promises":"fs"};const FS_MODULES=new Set(["fs","node:fs","fs/promises","node:fs/promises","fs-extra","graceful-fs"]);const isFsModule=source=>typeof source==="string"&&FS_MODULES.has(source);exports.isFsModule=isFsModule;function fsMethodName(callee,namespaces,named){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return named.get(callee.name);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return void 0}const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null){return void 0}const object=callee.object;if(object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&namespaces.has(object.name)){return method}if(object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&namespaces.has(object.object.name)&&(0,eslint_devkit_1.propertyName)(object)==="promises"){return method}return void 0}function isFsRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments.length>0&&node.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(0,exports.isFsModule)(node.arguments[0].value)}const determineRiskLevel=(operation,pathStr)=>{if(hasTraversalPatterns(pathStr)){return"CRITICAL"}if(operation.dangerous){return"HIGH"}return"MEDIUM"};exports.determineRiskLevel=determineRiskLevel;exports.detectNonLiteralFsFilename=(0,eslint_devkit_2.createRule)({name:"detect-non-literal-fs-filename",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-non-literal-fs-filename.md",description:"Detects variable in filename argument of fs calls, which might allow an attacker to access anything on your system",cwe:"CWE-22",confidence:"medium"},messages:{fsPathTraversal:(0,eslint_devkit_1.formatLLMMessage)({icon:"\u{1F511}",issueName:"Path traversal",cwe:"CWE-22",description:"Path traversal vulnerability",severity:"{{riskLevel}}",fix:"{{safePattern}} \u2014 Not a finding when the value is path.basename()d, checked against an allowlist, or resolved and then prefix-checked WITH a trailing separator",documentationLink:"https://owasp.org/www-community/attacks/Path_Traversal"})},schema:[{type:"object",properties:{taintSources:{type:"array",items:{type:"string"},default:["process"],description:"Identifier roots treated as attacker-reachable. Default: ['process'] (process.argv and process.env). Request roots (req/request/ctx/event) are deliberately NOT included \u2014 no-arbitrary-file-access owns those, and listing them here would double-report one line at two severities. Add them only if you run this rule without that one."},reportUnresolvedPaths:{type:"boolean",default:false,description:"Report paths whose provenance cannot be resolved. Restores the pre-inversion behaviour; measured at 7% precision on real code."},allowLiterals:{type:"boolean",default:false,description:`Allow literal string paths. Default true: a rule named "non-literal" reporting a literal contradicts its contract. Set false to also flag hardcoded paths containing "../" \u2014 measured as this rule's largest FP class on real code.`},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional fs methods to check"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowLiterals:false,additionalMethods:[]}],create(context){const options=context.options[0]||{};const{allowLiterals=false,additionalMethods=[]}=options;const DEFAULT_TAINT_ROOTS=["process","req","request","ctx","context","event"];const WHOLE_VALUE_TRUSTED_ROOTS=new Set(["process"]);const AMBIGUOUS_ROOTS=new Set(["ctx","context"]);const REQUEST_SURFACE=new Set(["query","params","body","request","req","headers","cookies","searchParams","originalUrl"]);const resolvesInFile=id=>context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved!=null;const readsRequestSurface=node=>node?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);const hasRequestEvidence=id=>{if(readsRequestSurface(id.parent))return true;const variable=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id).resolved;return variable.references.some(ref=>readsRequestSurface(ref.identifier.parent))};const taintRoots=new Set(options.taintSources??DEFAULT_TAINT_ROOTS);const reportUnresolvedPaths=options.reportUnresolvedPaths??false;const PATH_ARGUMENT_INDICES=new Map([["copyFile",[0,1]],["copyFileSync",[0,1]],["cp",[0,1]],["cpSync",[0,1]],["rename",[0,1]],["renameSync",[0,1]],["link",[0,1]],["linkSync",[0,1]],["symlink",[0,1]],["symlinkSync",[0,1]]]);const dangerousMethods=new Set(["readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","stat","statSync","lstat","lstatSync","readdir","readdirSync","unlink","unlinkSync","mkdir","mkdirSync","rmdir","rmdirSync","access","accessSync","createReadStream","createWriteStream","open","openSync","rm","rmSync","rename","renameSync","copyFile","copyFileSync","cp","cpSync","truncate","truncateSync","chmod","chmodSync","chown","chownSync","lchown","lchownSync","utimes","utimesSync","readlink","readlinkSync","symlink","symlinkSync","link","linkSync","opendir","opendirSync",...additionalMethods]);const isLiteralString=node=>{return(0,eslint_devkit_1.staticString)(node)!==null};const isLocallyConstructed=id=>{const variable=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved;if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression};const readsTaintSource=(node,depth=0)=>{if(depth>6)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name)){if(AMBIGUOUS_ROOTS.has(node.name)&&resolvesInFile(node)&&!hasRequestEvidence(node)){return false}return!isLocallyConstructed(node)}const bound=constBindings.get(node.name);return bound!==void 0&&readsTaintSource(bound,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="process"&&!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PROCESS_INPUT_MEMBERS)){return false}return readsTaintSource(node.object,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>readsTaintSource(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsTaintSource(node.left,depth+1)||readsTaintSource(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&(0,eslint_devkit_1.propertyName)(callee)==="basename"){return false}return node.arguments.some(arg=>arg.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&readsTaintSource(arg,depth+1))}default:return false}};const containsUntrustedRoot=(node,depth=0)=>{if(depth>6)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return!WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);const bound=constBindings.get(node.name);return bound!==void 0&&containsUntrustedRoot(bound,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return containsUntrustedRoot(node.object,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsUntrustedRoot(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return containsUntrustedRoot(node.left,depth+1)||containsUntrustedRoot(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&containsUntrustedRoot(a,depth+1));default:return false}};const isWholeTaintValue=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);const bound=constBindings.get(node.name);return bound!==void 0&&isWholeTaintValue(bound)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isWholeTaintValue(node.object);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;const isPathCall=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"||(0,eslint_devkit_1.resolveModuleBinding)(callee,context.sourceCode.getScope(callee),{})?.module==="path";if(!isPathCall)return false;if(node.arguments.length===1)return isWholeTaintValue(node.arguments[0]);return isWholeTaintValue(node.arguments[0])&&!containsUntrustedRoot(node)}default:return false}};const isDangerousPath=(pathNode,pathStr)=>{if(!pathNode)return reportUnresolvedPaths;if(isLiteralString(pathNode)){return!allowLiterals&&targetsSensitiveLocation(pathStr)}if(hasPathValidation(pathNode))return false;if(readsTaintSource(pathNode))return!isWholeTaintValue(pathNode);if(isBuildTimeConstant(pathNode))return false;if(isFreeVariable(pathNode))return true;if(containsFreeVariable(pathNode))return true;return reportUnresolvedPaths};function isFreeVariable(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const through=context.sourceCode.getScope(node).through;return through.some(ref=>ref.identifier===node&&ref.resolved===null)}const containsFreeVariable=(node,depth=0)=>{if(depth>4)return false;if(isBuildTimeConstant(node,depth))return false;if(isFreeVariable(node))return true;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsFreeVariable(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&containsFreeVariable(a,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return node.operator==="+"&&(containsFreeVariable(node.left,depth+1)||containsFreeVariable(node.right,depth+1));case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return node.computed&&containsFreeVariable(node.property,depth+1);default:return false}};const isBuildTimeConstant=(node,depth=0)=>{if(depth>4)return false;if(isLiteralString(node)){return!hasTraversalPatterns(node.value)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(node.name==="__dirname"||node.name==="__filename")return true;const bound=constBindings.get(node.name);return bound!==void 0&&isBuildTimeConstant(bound,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const literalText=node.quasis.map(q=>q.value.raw).join("");if(hasTraversalPatterns(literalText))return false;return node.expressions.every(e=>isBuildTimeConstant(e,depth+1))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="process"&&(0,eslint_devkit_1.propertyName)(callee)==="cwd"){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["join","resolve"].includes(callee.property.name)){return node.arguments.length>0&&node.arguments.every(arg=>isBuildTimeConstant(arg,depth+1))}return false}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return isBuildTimeConstant(node.left,depth+1)&&isBuildTimeConstant(node.right,depth+1)}return false};const isSeparatorAnchored=arg=>{if(arg===void 0)return false;const endsWithSep=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&n.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.object.name==="path"&&(0,eslint_devkit_1.propertyName)(n)==="sep"){return true}const staticText=(0,eslint_devkit_1.staticString)(n);if(staticText!==null){return staticText.endsWith("/")||staticText.endsWith("\\")}return false};if(endsWithSep(arg))return true;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){return endsWithSep(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const last=arg.quasis[arg.quasis.length-1].value.cooked;if(last.endsWith("/")||last.endsWith("\\"))return true;if(last===""){const tail=arg.expressions[arg.expressions.length-1];return tail!==void 0&&endsWithSep(tail)}return false}return false};const hasPathValidation=pathNode=>{if(pathNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){const parts=[];const collect=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="+"){collect(n.left);collect(n.right);return}if(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){n.expressions.forEach(e=>collect(e));return}if(n.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){n.arguments.forEach(a=>{if(a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement)collect(a)});return}if(readsTaintSource(n))parts.push(n)};collect(pathNode);return parts.length>0&&parts.every(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&hasPathValidation(p))}const varName=pathNode.name;const isValidationCall=testNode=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"&&testNode.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){testNode=testNode.argument}if(testNode.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression){return false}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&testNode.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.callee.object.name===varName&&((0,eslint_devkit_1.propertyName)(testNode.callee)==="startsWith"||(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes")){return(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"?true:isSeparatorAnchored(testNode.arguments[0])}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"){for(const arg of testNode.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name===varName){return true}}}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="test"){for(const arg of testNode.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name===varName){return true}}}return false};const hasEarlyExit=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};let current=pathNode.parent;let foundFunctionBody=false;while(current&&!foundFunctionBody){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(isValidationCall(current.test)){return true}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&¤t.parent&&(current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)){foundFunctionBody=true;const blockBody=current.body;const nodeIndex=blockBody.findIndex(stmt=>{let check=pathNode;while(check){if(check===stmt)return true;check=check.parent}return false});for(let i=0;i<nodeIndex;i++){const stmt=blockBody[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&isValidationCall(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}current=current.parent}return false};const fsNamespaces=new Set(["fs"]);const fsNamedMethods=new Map;const pendingCalls=[];const constBindings=new Map;function bindFsName(local,imported){if(imported==="promises")fsNamespaces.add(local);else fsNamedMethods.set(local,imported)}const checkFsCall=node=>{let methodName=fsMethodName(node.callee,fsNamespaces,fsNamedMethods);if(methodName===void 0){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,context.sourceCode.getScope(node),{equivalents:FS_MODULE_EQUIVALENTS});if(binding?.module!=="fs")return;const[first,second]=binding.path;methodName=binding.path.length===1?first:binding.path.length===2&&first==="promises"?second:void 0;if(methodName===void 0)return}if(!dangerousMethods.has(methodName)){return}const method=methodName;const indices=PATH_ARGUMENT_INDICES.get(method)??[0];const sourceCode=context.sourceCode;let pathNode=null;let path="";for(const index of indices){const candidate=node.arguments[index];if(candidate===void 0||candidate.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;if(isDangerousPath(candidate,sourceCode.getText(candidate))){pathNode=candidate;path=sourceCode.getText(candidate);break}}if(pathNode===null){const present=indices.some(index=>node.arguments[index]!==void 0);if(!present&&isDangerousPath(null,"")){context.report({node,messageId:"fsPathTraversal",data:{method,path:"",riskLevel:"MEDIUM",vulnerability:"path traversal",safePattern:"Use path.resolve() with validation",steps:"Review file system access patterns"}})}return}const operation=FS_OPERATIONS.find(op=>op.method===method)??null;const riskLevel=(0,exports.determineRiskLevel)(operation||FS_OPERATIONS[0],path);const steps=operation?(0,exports.generateRefactoringSteps)(operation):"Review file system access patterns";const safePattern=operation?.safePattern||"Use path.resolve() with validation";context.report({node,messageId:"fsPathTraversal",data:{method,path,riskLevel,vulnerability:operation?.vulnerability||"path traversal",safePattern,steps,effort:operation?.effort||"15-20 minutes"}})};return{ImportDeclaration(node){if(!(0,exports.isFsModule)(node.source.value))return;for(const spec of node.specifiers){if(spec.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){const imported=spec.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?spec.imported.name:spec.imported.value;bindFsName(spec.local.name,imported);continue}fsNamespaces.add(spec.local.name)}},VariableDeclarator(node){if(node.init!==null&&node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&node.parent.kind==="const"){constBindings.set(node.id.name,node.init)}if(node.init===null||!isFsRequire(node.init))return;if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){fsNamespaces.add(node.id.name);return}if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return;for(const prop of node.id.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property||prop.computed)continue;if(prop.value.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;const key=prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.key.name:(0,eslint_devkit_1.staticString)(prop.key)??void 0;if(key===void 0)continue;bindFsName(prop.value.name,key)}},CallExpression(node){pendingCalls.push(node)},"Program:exit"(){for(const call of pendingCalls)checkFsCall(call)}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectNonLiteralFsFilename=exports.determineRiskLevel=exports.isFsModule=exports.generateRefactoringSteps=void 0;exports.fsMethodName=fsMethodName;exports.isFsRequire=isFsRequire;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const FS_OPERATIONS=[{method:"readFile",dangerous:true,vulnerability:"file-access",safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))",example:{bad:"fs.readFile(userPath, callback)",good:"const safePath = path.join(SAFE_UPLOADS_DIR, path.basename(userPath)); fs.readFile(safePath, callback)"},effort:"10-15 minutes"},{method:"writeFile",dangerous:true,vulnerability:"file-access",safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))",example:{bad:"fs.writeFile(userPath, data, callback)",good:"const safePath = path.join(SAFE_WRITES_DIR, path.basename(userPath)); fs.writeFile(safePath, data, callback)"},effort:"10-15 minutes"},{method:"stat",dangerous:true,vulnerability:"path-traversal",safePattern:"path.resolve(baseDir, userInput) with validation",example:{bad:"fs.stat(userPath, callback)",good:"const resolvedPath = path.resolve(SAFE_DIR, userPath);\nif (!resolvedPath.startsWith(SAFE_DIR + path.sep)) return;\nfs.stat(resolvedPath, callback)"},effort:"15-20 minutes"},{method:"readdir",dangerous:true,vulnerability:"directory-traversal",safePattern:"Validate directory is within allowed paths",example:{bad:"fs.readdir(userDir, callback)",good:"const resolvedDir = path.resolve(ALLOWED_DIRS, userDir);\nif (!resolvedDir.startsWith(ALLOWED_DIRS + path.sep)) return;\nfs.readdir(resolvedDir, callback)"},effort:"15-20 minutes"}];const hasTraversalPatterns=pathStr=>{return/\.\.[/\\]/.test(pathStr)||/^\.\.[/\\]/.test(pathStr)};const PROCESS_INPUT_MEMBERS=new Set(["env","argv","argv0","execArgv","stdin"]);const SENSITIVE_SEGMENTS=["etc/passwd","etc/shadow","etc/hosts","etc/sudoers","proc/self",".ssh/id_rsa",".ssh/id_dsa",".ssh/authorized_keys",".aws/credentials",".npmrc",".git/config","windows/system32/config/sam"];const targetsSensitiveLocation=pathStr=>{const unquoted=pathStr.replace(/^['"`]|['"`]$/g,"");const normalised=unquoted.replace(/\\/g,"/").toLowerCase();if(!/(^|\/)\.\.(\/|$)/.test(normalised)){return false}const withoutPrefix=normalised.replace(/^(?:\.{1,2}\/)+/,"");return SENSITIVE_SEGMENTS.some(seg=>withoutPrefix===seg||withoutPrefix.endsWith(`/${seg}`)||withoutPrefix.startsWith(`${seg}/`))};const generateRefactoringSteps=operation=>{switch(operation.method){case"readFile":case"writeFile":return[" 1. Define a SAFE_DIR constant for allowed operations"," 2. Use path.basename() to strip directory components"," 3. Combine with SAFE_DIR: path.join(SAFE_DIR, path.basename(userPath))"," 4. Optionally validate file extensions"," 5. Add error handling for invalid paths"].join("\n");case"stat":return[" 1. Use path.resolve() to normalize the path"," 2. Check the resolved path starts with the base PLUS path.sep \u2014 a bare"," prefix lets /safebad through a /safe check"," 3. Reject requests that escape the allowed directory"," 4. Use path.relative() for additional validation"," 5. Log security events for monitoring"].join("\n");case"readdir":return[" 1. Resolve the directory path: path.resolve(ALLOWED_DIRS, userDir)"," 2. Validate resolved path starts with ALLOWED_DIRS"," 3. Check directory exists and is readable"," 4. Consider whitelisting allowed directories"," 5. Add rate limiting to prevent enumeration attacks"].join("\n");default:return[" 1. Identify the specific file operation needed"," 2. Define safe base directories for operations"," 3. Use path.resolve() and validate containment"," 4. Sanitize user input (basename, extension validation)"," 5. Add comprehensive error handling"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;const FS_MODULE_EQUIVALENTS={"fs-extra":"fs","graceful-fs":"fs","fs/promises":"fs"};const FS_MODULES=new Set(["fs","node:fs","fs/promises","node:fs/promises","fs-extra","graceful-fs"]);const isFsModule=source=>typeof source==="string"&&FS_MODULES.has(source);exports.isFsModule=isFsModule;function fsMethodName(callee,namespaces,named){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return named.get(callee.name);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return void 0}const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null){return void 0}const object=callee.object;if(object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&namespaces.has(object.name)){return method}if(object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&namespaces.has(object.object.name)&&(0,eslint_devkit_1.propertyName)(object)==="promises"){return method}return void 0}function isFsRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments.length>0&&node.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(0,exports.isFsModule)(node.arguments[0].value)}const determineRiskLevel=(operation,pathStr)=>{if(hasTraversalPatterns(pathStr)){return"CRITICAL"}if(operation.dangerous){return"HIGH"}return"MEDIUM"};exports.determineRiskLevel=determineRiskLevel;exports.detectNonLiteralFsFilename=(0,eslint_devkit_2.createRule)({name:"detect-non-literal-fs-filename",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-non-literal-fs-filename.md",description:"Detects variable in filename argument of fs calls, which might allow an attacker to access anything on your system",cwe:"CWE-22",confidence:"medium"},messages:{fsPathTraversal:(0,eslint_devkit_1.formatLLMMessage)({icon:"\u{1F511}",issueName:"Path traversal",cwe:"CWE-22",description:"Path traversal vulnerability",severity:"{{riskLevel}}",fix:"{{safePattern}} \u2014 Not a finding when the value is path.basename()d, checked against an allowlist, or resolved and then prefix-checked WITH a trailing separator",documentationLink:"https://owasp.org/www-community/attacks/Path_Traversal"})},schema:[{type:"object",properties:{taintSources:{type:"array",items:{type:"string"},default:["process"],description:"Identifier roots treated as attacker-reachable. Default: ['process'] (process.argv and process.env). Request roots (req/request/ctx/event) are deliberately NOT included \u2014 no-arbitrary-file-access owns those, and listing them here would double-report one line at two severities. Add them only if you run this rule without that one."},reportUnresolvedPaths:{type:"boolean",default:false,description:"Report paths whose provenance cannot be resolved. Restores the pre-inversion behaviour; measured at 7% precision on real code."},allowLiterals:{type:"boolean",default:false,description:`Allow literal string paths. Default true: a rule named "non-literal" reporting a literal contradicts its contract. Set false to also flag hardcoded paths containing "../" \u2014 measured as this rule's largest FP class on real code.`},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional fs methods to check"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowLiterals:false,additionalMethods:[]}],create(context){const options=context.options[0]||{};const{allowLiterals=false,additionalMethods=[]}=options;const DEFAULT_TAINT_ROOTS=["process","req","request","ctx","context","event"];const WHOLE_VALUE_TRUSTED_ROOTS=new Set(["process"]);const AMBIGUOUS_ROOTS=new Set(["ctx","context"]);const REQUEST_SURFACE=new Set(["query","params","body","request","req","headers","cookies","searchParams","originalUrl"]);const resolvesInFile=id=>context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved!=null;const readsRequestSurface=node=>node?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);const hasRequestEvidence=id=>{if(readsRequestSurface(id.parent))return true;const variable=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id).resolved;return variable.references.some(ref=>readsRequestSurface(ref.identifier.parent))};const taintRoots=new Set(options.taintSources??DEFAULT_TAINT_ROOTS);const reportUnresolvedPaths=options.reportUnresolvedPaths??false;const PATH_ARGUMENT_INDICES=new Map([["copyFile",[0,1]],["copyFileSync",[0,1]],["cp",[0,1]],["cpSync",[0,1]],["rename",[0,1]],["renameSync",[0,1]],["link",[0,1]],["linkSync",[0,1]],["symlink",[0,1]],["symlinkSync",[0,1]]]);const dangerousMethods=new Set(["readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","stat","statSync","lstat","lstatSync","readdir","readdirSync","unlink","unlinkSync","mkdir","mkdirSync","rmdir","rmdirSync","access","accessSync","createReadStream","createWriteStream","open","openSync","rm","rmSync","rename","renameSync","copyFile","copyFileSync","cp","cpSync","truncate","truncateSync","chmod","chmodSync","chown","chownSync","lchown","lchownSync","utimes","utimesSync","readlink","readlinkSync","symlink","symlinkSync","link","linkSync","opendir","opendirSync",...additionalMethods]);const isLiteralString=node=>{return(0,eslint_devkit_1.staticString)(node)!==null};const isLocallyConstructed=id=>{const variable=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved;if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression};const readsTaintSource=(node,depth=0)=>{if(depth>6)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name)){if(AMBIGUOUS_ROOTS.has(node.name)&&resolvesInFile(node)&&!hasRequestEvidence(node)){return false}return!isLocallyConstructed(node)}const bound=constBindings.get(node.name);return bound!==void 0&&readsTaintSource(bound,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="process"&&!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PROCESS_INPUT_MEMBERS)){return false}return readsTaintSource(node.object,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>readsTaintSource(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsTaintSource(node.left,depth+1)||readsTaintSource(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&(0,eslint_devkit_1.propertyName)(callee)==="basename"){return false}return node.arguments.some(arg=>arg.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&readsTaintSource(arg,depth+1))}default:return false}};const containsUntrustedRoot=(node,depth=0)=>{if(depth>6)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return!WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);const bound=constBindings.get(node.name);return bound!==void 0&&containsUntrustedRoot(bound,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return containsUntrustedRoot(node.object,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsUntrustedRoot(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return containsUntrustedRoot(node.left,depth+1)||containsUntrustedRoot(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&containsUntrustedRoot(a,depth+1));default:return false}};const isWholeTaintValue=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);const bound=constBindings.get(node.name);return bound!==void 0&&isWholeTaintValue(bound)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isWholeTaintValue(node.object);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;const isPathCall=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"||(0,eslint_devkit_1.resolveModuleBinding)(callee,context.sourceCode.getScope(callee),{})?.module==="path";if(!isPathCall)return false;if(node.arguments.length===1)return isWholeTaintValue(node.arguments[0]);return isWholeTaintValue(node.arguments[0])&&!containsUntrustedRoot(node)}default:return false}};const isDangerousPath=(pathNode,pathStr)=>{if(!pathNode)return reportUnresolvedPaths;if(isLiteralString(pathNode)){return!allowLiterals&&targetsSensitiveLocation(pathStr)}if(hasPathValidation(pathNode))return false;if(readsTaintSource(pathNode))return!isWholeTaintValue(pathNode);if(isBuildTimeConstant(pathNode))return false;if(isFreeVariable(pathNode))return true;if(containsFreeVariable(pathNode))return true;return reportUnresolvedPaths};function isFreeVariable(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const through=context.sourceCode.getScope(node).through;return through.some(ref=>ref.identifier===node&&ref.resolved===null)}const containsFreeVariable=(node,depth=0)=>{if(depth>4)return false;if(isBuildTimeConstant(node,depth))return false;if(isFreeVariable(node))return true;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsFreeVariable(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&containsFreeVariable(a,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return node.operator==="+"&&(containsFreeVariable(node.left,depth+1)||containsFreeVariable(node.right,depth+1));case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return node.computed&&containsFreeVariable(node.property,depth+1);default:return false}};const isBuildTimeConstant=(node,depth=0)=>{if(depth>4)return false;if(isLiteralString(node)){return!hasTraversalPatterns(node.value)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(node.name==="__dirname"||node.name==="__filename")return true;const bound=constBindings.get(node.name);return bound!==void 0&&isBuildTimeConstant(bound,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const literalText=node.quasis.map(q=>q.value.raw).join("");if(hasTraversalPatterns(literalText))return false;return node.expressions.every(e=>isBuildTimeConstant(e,depth+1))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="process"&&(0,eslint_devkit_1.propertyName)(callee)==="cwd"){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["join","resolve"].includes(callee.property.name)){return node.arguments.length>0&&node.arguments.every(arg=>isBuildTimeConstant(arg,depth+1))}return false}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return isBuildTimeConstant(node.left,depth+1)&&isBuildTimeConstant(node.right,depth+1)}return false};const isSeparatorAnchored=arg=>{if(arg===void 0)return false;const endsWithSep=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&n.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.object.name==="path"&&(0,eslint_devkit_1.propertyName)(n)==="sep"){return true}const staticText=(0,eslint_devkit_1.staticString)(n);if(staticText!==null){return staticText.endsWith("/")||staticText.endsWith("\\")}return false};if(endsWithSep(arg))return true;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){return endsWithSep(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const last=arg.quasis[arg.quasis.length-1].value.cooked;if(last.endsWith("/")||last.endsWith("\\"))return true;if(last===""){const tail=arg.expressions[arg.expressions.length-1];return tail!==void 0&&endsWithSep(tail)}return false}return false};const hasPathValidation=pathNode=>{if(pathNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){const parts=[];const collect=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="+"){collect(n.left);collect(n.right);return}if(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){n.expressions.forEach(e=>collect(e));return}if(n.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){n.arguments.forEach(a=>{if(a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement)collect(a)});return}if(readsTaintSource(n))parts.push(n)};collect(pathNode);return parts.length>0&&parts.every(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&hasPathValidation(p))}const varName=pathNode.name;const isValidationCall=testNode=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"&&testNode.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){testNode=testNode.argument}if(testNode.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression){return false}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&testNode.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.callee.object.name===varName&&((0,eslint_devkit_1.propertyName)(testNode.callee)==="startsWith"||(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes")){return(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"?true:isSeparatorAnchored(testNode.arguments[0])}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"){for(const arg of testNode.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name===varName){return true}}}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="test"){for(const arg of testNode.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name===varName){return true}}}return false};const hasEarlyExit=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};let current=pathNode.parent;let foundFunctionBody=false;while(current&&!foundFunctionBody){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(isValidationCall(current.test)){return true}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&¤t.parent&&(current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)){foundFunctionBody=true;const blockBody=current.body;const nodeIndex=blockBody.findIndex(stmt=>{let check=pathNode;while(check){if(check===stmt)return true;check=check.parent}return false});for(let i=0;i<nodeIndex;i++){const stmt=blockBody[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&isValidationCall(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}current=current.parent}return false};const fsNamespaces=new Set(["fs"]);const fsNamedMethods=new Map;const pendingCalls=[];const constBindings=new Map;function bindFsName(local,imported){if(imported==="promises")fsNamespaces.add(local);else fsNamedMethods.set(local,imported)}const checkFsCall=node=>{let methodName=fsMethodName(node.callee,fsNamespaces,fsNamedMethods);if(methodName===void 0){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,context.sourceCode.getScope(node),{equivalents:FS_MODULE_EQUIVALENTS});if(binding?.module!=="fs")return;const[first,second]=binding.path;methodName=binding.path.length===1?first:binding.path.length===2&&first==="promises"?second:void 0;if(methodName===void 0)return}if(!dangerousMethods.has(methodName)){return}const method=methodName;const indices=PATH_ARGUMENT_INDICES.get(method)??[0];const sourceCode=context.sourceCode;let pathNode=null;let path="";for(const index of indices){const candidate=node.arguments[index];if(candidate===void 0||candidate.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;if(isDangerousPath(candidate,sourceCode.getText(candidate))){pathNode=candidate;path=sourceCode.getText(candidate);break}}if(pathNode===null){const present=indices.some(index=>node.arguments[index]!==void 0);if(!present&&isDangerousPath(null,"")){context.report({node,messageId:"fsPathTraversal",data:{method,path:"",riskLevel:"MEDIUM",vulnerability:"path traversal",safePattern:"Use path.resolve() with validation",steps:"Review file system access patterns"}})}return}const operation=FS_OPERATIONS.find(op=>op.method===method)??null;const riskLevel=(0,exports.determineRiskLevel)(operation||FS_OPERATIONS[0],path);const steps=operation?(0,exports.generateRefactoringSteps)(operation):"Review file system access patterns";const safePattern=operation?.safePattern||"Use path.resolve() with validation";context.report({node,messageId:"fsPathTraversal",data:{method,path,riskLevel,vulnerability:operation?.vulnerability||"path traversal",safePattern,steps,effort:operation?.effort||"15-20 minutes"}})};return{ImportDeclaration(node){if(!(0,exports.isFsModule)(node.source.value))return;for(const spec of node.specifiers){if(spec.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){const imported=spec.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?spec.imported.name:spec.imported.value;bindFsName(spec.local.name,imported);continue}fsNamespaces.add(spec.local.name)}},VariableDeclarator(node){if(node.init!==null&&node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&node.parent.kind==="const"){constBindings.set(node.id.name,node.init)}if(node.init===null||!isFsRequire(node.init))return;if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){fsNamespaces.add(node.id.name);return}if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return;for(const prop of node.id.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(prop.value.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;const key=(0,eslint_devkit_1.objectKeyName)(prop);if(key===null)continue;bindFsName(prop.value.name,key)}},CallExpression(node){pendingCalls.push(node)},"Program:exit"(){for(const call of pendingCalls)checkFsCall(call)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDeprecatedBuffer=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const BUFFER_MODULES=new Set(["buffer","node:buffer"]);function isBufferModuleRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.arguments[0].value==="string"&&BUFFER_MODULES.has(node.arguments[0].value)}function fromBufferModule(def){const declaration=def.parent;return declaration.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&BUFFER_MODULES.has(declaration.source.value)}exports.noDeprecatedBuffer=(0,eslint_devkit_1.createRule)({name:"no-deprecated-buffer",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-deprecated-buffer.md",description:"Disallow the deprecated `new Buffer()` constructor and `Buffer()` factory call.",cwe:"CWE-676",cvss:7.5},fixable:"code",messages:{deprecatedBufferConstructor:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Deprecated Buffer Constructor",cwe:"CWE-676",cvss:7.5,description:"`new Buffer()` is deprecated since Node 10 and unsafe \u2014 when called with a number it returns uninitialized memory (CVE-2018-7166).",severity:"HIGH",fix:"Use `Buffer.alloc(size)` (zero-filled), `Buffer.allocUnsafe(size)` (only when you immediately overwrite the buffer), or `Buffer.from(value)` (for strings/arrays/buffers).",documentationLink:"https://nodejs.org/api/buffer.html#bufnew-buffersize"}),deprecatedBufferCall:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Deprecated Buffer() Factory Call",cwe:"CWE-676",cvss:7.5,description:"`Buffer()` (without `new`) is deprecated since Node 10 and unsafe \u2014 when called with a number it returns uninitialized memory.",severity:"HIGH",fix:"Use `Buffer.alloc(size)`, `Buffer.allocUnsafe(size)`, or `Buffer.from(value)`.",documentationLink:"https://nodejs.org/api/buffer.html#bufnew-buffersize"})},schema:[]},defaultOptions:[],create(context){const sourceCode=context.sourceCode;function resolvesToNodeBuffer(id){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(variable===null||variable.defs.length===0)return id.name==="Buffer";const def=variable.defs[0];if(def.type==="ImportBinding"){return fromBufferModule(def)&&def.node.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier&&def.node.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&def.node.imported.name==="Buffer"}if(def.type!=="Variable")return false;const init=def.node.init;if(init===null)return false;if(init.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(init)==="Buffer"){return isBufferModuleRequire(init.object)}if(!isBufferModuleRequire(init))return false;const property=def.name.parent;return property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDeprecatedBuffer=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const BUFFER_MODULES=new Set(["buffer","node:buffer"]);function isBufferModuleRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.arguments[0].value==="string"&&BUFFER_MODULES.has(node.arguments[0].value)}function fromBufferModule(def){const declaration=def.parent;return declaration.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&BUFFER_MODULES.has(declaration.source.value)}exports.noDeprecatedBuffer=(0,eslint_devkit_1.createRule)({name:"no-deprecated-buffer",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-deprecated-buffer.md",description:"Disallow the deprecated `new Buffer()` constructor and `Buffer()` factory call.",cwe:"CWE-676",cvss:7.5},fixable:"code",messages:{deprecatedBufferConstructor:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Deprecated Buffer Constructor",cwe:"CWE-676",cvss:7.5,description:"`new Buffer()` is deprecated since Node 10 and unsafe \u2014 when called with a number it returns uninitialized memory (CVE-2018-7166).",severity:"HIGH",fix:"Use `Buffer.alloc(size)` (zero-filled), `Buffer.allocUnsafe(size)` (only when you immediately overwrite the buffer), or `Buffer.from(value)` (for strings/arrays/buffers).",documentationLink:"https://nodejs.org/api/buffer.html#bufnew-buffersize"}),deprecatedBufferCall:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Deprecated Buffer() Factory Call",cwe:"CWE-676",cvss:7.5,description:"`Buffer()` (without `new`) is deprecated since Node 10 and unsafe \u2014 when called with a number it returns uninitialized memory.",severity:"HIGH",fix:"Use `Buffer.alloc(size)`, `Buffer.allocUnsafe(size)`, or `Buffer.from(value)`.",documentationLink:"https://nodejs.org/api/buffer.html#bufnew-buffersize"})},schema:[]},defaultOptions:[],create(context){const sourceCode=context.sourceCode;function resolvesToNodeBuffer(id){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(variable===null||variable.defs.length===0)return id.name==="Buffer";const def=variable.defs[0];if(def.type==="ImportBinding"){return fromBufferModule(def)&&def.node.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier&&def.node.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&def.node.imported.name==="Buffer"}if(def.type!=="Variable")return false;const init=def.node.init;if(init===null)return false;if(init.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(init)==="Buffer"){return isBufferModuleRequire(init.object)}if(!isBufferModuleRequire(init))return false;const property=def.name.parent;return property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&(0,eslint_devkit_1.objectKeyName)(property)==="Buffer"}function isBufferNamespace(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,provenance_1.findVariable)(sourceCode,node);if(variable===null||variable.defs.length===0){return node.name==="global"||node.name==="globalThis"}const def=variable.defs[0];if(def.type==="ImportBinding"){return fromBufferModule(def)&&def.node.type===eslint_devkit_1.AST_NODE_TYPES.ImportNamespaceSpecifier}return def.type==="Variable"&&def.node.init!==null&&isBufferModuleRequire(def.node.init)}function deprecatedCallee(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return resolvesToNodeBuffer(callee)?callee:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee)==="Buffer"&&isBufferNamespace(callee.object)){return callee}return null}function replacementMethod(args){if(args.length!==1)return args.length===0?null:".from";const argument=args[0];if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return null;if(argument.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||argument.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return".from"}const resolved=(0,const_value_1.resolveConstant)(sourceCode,argument);if(resolved===null)return null;return typeof resolved.value==="number"?".alloc":".from"}function fixTo(node,callee,method){return fixer=>{const start=node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression?sourceCode.getFirstToken(node).range[0]:callee.range[0];return fixer.replaceTextRange([start,callee.range[1]],`${sourceCode.getText(callee)}${method}`)}}return{NewExpression(node){const callee=deprecatedCallee(node.callee);if(callee===null)return;const method=replacementMethod(node.arguments);context.report({node,messageId:"deprecatedBufferConstructor",...method===null?{}:{fix:fixTo(node,callee,method)}})},CallExpression(node){const callee=deprecatedCallee(node.callee);if(callee===null)return;const method=replacementMethod(node.arguments);context.report({node,messageId:"deprecatedBufferCall",...method===null?{}:{fix:fixTo(node,callee,method)}})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureKeyDerivation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const PBKDF2_EXPORTS=new Set(["pbkdf2","pbkdf2Sync"]);const SUBTLE_DERIVE_METHODS=new Set(["deriveBits","deriveKey"]);function foldNumber(sourceCode,node,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return foldNumber(sourceCode,bare,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="number"?{value:node.value,source:node}:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&node.operator==="-"){const inner=foldNumber(sourceCode,node.argument,depth+1);return inner===null?null:{value:-inner.value,source:node}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const left=foldNumber(sourceCode,node.left,depth+1);const right=foldNumber(sourceCode,node.right,depth+1);if(left===null||right===null)return null;switch(node.operator){case"*":return{value:left.value*right.value,source:node};case"+":return{value:left.value+right.value,source:node};case"-":return{value:left.value-right.value,source:node};case"**":return{value:left.value**right.value,source:node};default:return null}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,const_value_1.constInitializerOf)(sourceCode,node);return init===null?null:foldNumber(sourceCode,init,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const value=objectPropertyValue(sourceCode,node.object,propertyKey(sourceCode,node));return value===null?null:foldNumber(sourceCode,value,depth+1)}return null}function propertyKey(sourceCode,node){if(node.computed)return(0,const_value_1.resolveConstantString)(sourceCode,node.property)?.value??null;return node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:null}function objectPropertyValue(sourceCode,node,key){if(key===null)return null;let object=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,const_value_1.constInitializerOf)(sourceCode,object);if(init===null)return null;object=(0,eslint_devkit_1.unwrapTypeSyntax)(init)}if(object.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return null;for(const property of object.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const name=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureKeyDerivation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const PBKDF2_EXPORTS=new Set(["pbkdf2","pbkdf2Sync"]);const SUBTLE_DERIVE_METHODS=new Set(["deriveBits","deriveKey"]);function foldNumber(sourceCode,node,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return foldNumber(sourceCode,bare,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="number"?{value:node.value,source:node}:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&node.operator==="-"){const inner=foldNumber(sourceCode,node.argument,depth+1);return inner===null?null:{value:-inner.value,source:node}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const left=foldNumber(sourceCode,node.left,depth+1);const right=foldNumber(sourceCode,node.right,depth+1);if(left===null||right===null)return null;switch(node.operator){case"*":return{value:left.value*right.value,source:node};case"+":return{value:left.value+right.value,source:node};case"-":return{value:left.value-right.value,source:node};case"**":return{value:left.value**right.value,source:node};default:return null}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,const_value_1.constInitializerOf)(sourceCode,node);return init===null?null:foldNumber(sourceCode,init,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const value=objectPropertyValue(sourceCode,node.object,propertyKey(sourceCode,node));return value===null?null:foldNumber(sourceCode,value,depth+1)}return null}function propertyKey(sourceCode,node){if(node.computed)return(0,const_value_1.resolveConstantString)(sourceCode,node.property)?.value??null;return node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:null}function objectPropertyValue(sourceCode,node,key){if(key===null)return null;let object=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,const_value_1.constInitializerOf)(sourceCode,object);if(init===null)return null;object=(0,eslint_devkit_1.unwrapTypeSyntax)(init)}if(object.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return null;for(const property of object.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const name=(0,eslint_devkit_1.objectKeyName)(property);if(name===key)return property.value}return null}function isPromisifyCall(sourceCode,node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node));return binding?.module==="util"&&binding.path.at(-1)==="promisify"}function isPbkdf2Callee(sourceCode,callee,depth=0){if(depth>4)return false;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),PBKDF2_EXPORTS)){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&PBKDF2_EXPORTS.has(callee.name))return true;const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));if(binding!==void 0&&PBKDF2_EXPORTS.has(binding.path.at(-1)??""))return true;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isPromisifyCall(sourceCode,callee)&&callee.arguments.length>0&&isPbkdf2Callee(sourceCode,callee.arguments[0],depth+1)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,const_value_1.constInitializerOf)(sourceCode,callee);return init!==null&&isPromisifyCall(sourceCode,init)&&init.arguments.length>0&&isPbkdf2Callee(sourceCode,init.arguments[0],depth+1)}return false}const DEFAULT_MIN_ITERATIONS=1e5;exports.noInsecureKeyDerivation=(0,eslint_devkit_1.createRule)({name:"no-insecure-key-derivation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-insecure-key-derivation.md",description:"Disallow PBKDF2 with insufficient iterations (< 100,000)",cwe:"CWE-916",cvss:7.5},hasSuggestions:true,messages:{insufficientIterations:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insufficient PBKDF2 iterations",cwe:"CWE-916",description:"PBKDF2 with {{actual}} iterations is too low. Minimum recommended: {{minimum}} iterations (OWASP 2023).",severity:"HIGH",fix:"Increase iterations to at least {{minimum}}, or use scrypt/Argon2",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html"}),useMinIterations:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use minimum iterations",description:"Use at least {{minimum}} iterations for PBKDF2",severity:"LOW",fix:"crypto.pbkdf2(password, salt, {{minimum}}, keylen, digest)",documentationLink:"https://nodejs.org/api/crypto.html#cryptopbkdf2password-salt-iterations-keylen-digest-callback"})},schema:[{type:"object",properties:{minIterations:{type:"number",default:DEFAULT_MIN_ITERATIONS,description:"Minimum required PBKDF2 iterations"}},additionalProperties:false}]},defaultOptions:[{minIterations:DEFAULT_MIN_ITERATIONS}],create(context,[options={}]){const{minIterations=DEFAULT_MIN_ITERATIONS}=options;const sourceCode=context.sourceCode;function judgeIterations(iterationsArg){if(iterationsArg===void 0||iterationsArg===null)return;const folded=foldNumber(sourceCode,iterationsArg);if(folded===null||folded.value>=minIterations)return;context.report({node:iterationsArg,messageId:"insufficientIterations",data:{actual:String(folded.value),minimum:String(minIterations)},suggest:[{messageId:"useMinIterations",data:{minimum:String(minIterations)},fix:fixer=>{return fixer.replaceText(folded.source,String(minIterations))}}]})}function checkCallExpression(node){if(isPbkdf2Callee(sourceCode,node.callee)){judgeIterations(node.arguments[2]);return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="PBKDF2"||node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="PBKDF2"){const options2=node.arguments[2];if(options2!==void 0){judgeIterations(objectPropertyValue(sourceCode,options2,"iterations"))}return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),SUBTLE_DERIVE_METHODS)){const params=node.arguments[0];if(params===void 0)return;const algorithm=objectPropertyValue(sourceCode,params,"name");if(algorithm===null)return;if((0,const_value_1.resolveConstantString)(sourceCode,algorithm)?.value!=="PBKDF2")return;judgeIterations(objectPropertyValue(sourceCode,params,"iterations"))}}return{CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureRsaPadding=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const PKCS1_PADDING_NAMES=new Set(["RSA_PKCS1_PADDING","constants.RSA_PKCS1_PADDING","crypto.constants.RSA_PKCS1_PADDING"]);exports.noInsecureRsaPadding=(0,eslint_devkit_1.createRule)({name:"no-insecure-rsa-padding",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-insecure-rsa-padding.md",description:"Disallow RSA PKCS#1 v1.5 padding (CVE-2023-46809 Marvin Attack)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{insecureRsaPadding:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure RSA padding",cwe:"CWE-327",description:"RSA PKCS#1 v1.5 padding is vulnerable to the Marvin Attack (CVE-2023-46809). Timing side-channels allow attackers to decrypt ciphertexts or forge signatures.",severity:"HIGH",fix:"Use RSA_PKCS1_OAEP_PADDING instead",documentationLink:"https://people.redhat.com/~hkario/marvin/"}),useOaep:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use OAEP padding",description:"Use RSA-OAEP which is not vulnerable to padding oracle attacks",severity:"LOW",fix:"padding: crypto.constants.RSA_PKCS1_OAEP_PADDING",documentationLink:"https://nodejs.org/api/crypto.html#cryptopublicdecryptkey-buffer"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options={}]){const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);const sourceCode=context.sourceCode;function checkCallExpression(node){if(isTestFile)return;const rsaMethods=new Set(["privateDecrypt","publicDecrypt","privateEncrypt","publicEncrypt"]);const isRsaCall=node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),rsaMethods)||node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&rsaMethods.has(node.callee.name);if(isRsaCall&&node.arguments.length>=1){const keyArg=node.arguments[0];if(keyArg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of keyArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureRsaPadding=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const PKCS1_PADDING_NAMES=new Set(["RSA_PKCS1_PADDING","constants.RSA_PKCS1_PADDING","crypto.constants.RSA_PKCS1_PADDING"]);exports.noInsecureRsaPadding=(0,eslint_devkit_1.createRule)({name:"no-insecure-rsa-padding",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-insecure-rsa-padding.md",description:"Disallow RSA PKCS#1 v1.5 padding (CVE-2023-46809 Marvin Attack)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{insecureRsaPadding:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure RSA padding",cwe:"CWE-327",description:"RSA PKCS#1 v1.5 padding is vulnerable to the Marvin Attack (CVE-2023-46809). Timing side-channels allow attackers to decrypt ciphertexts or forge signatures.",severity:"HIGH",fix:"Use RSA_PKCS1_OAEP_PADDING instead",documentationLink:"https://people.redhat.com/~hkario/marvin/"}),useOaep:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use OAEP padding",description:"Use RSA-OAEP which is not vulnerable to padding oracle attacks",severity:"LOW",fix:"padding: crypto.constants.RSA_PKCS1_OAEP_PADDING",documentationLink:"https://nodejs.org/api/crypto.html#cryptopublicdecryptkey-buffer"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options={}]){const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);const sourceCode=context.sourceCode;function checkCallExpression(node){if(isTestFile)return;const rsaMethods=new Set(["privateDecrypt","publicDecrypt","privateEncrypt","publicEncrypt"]);const isRsaCall=node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),rsaMethods)||node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&rsaMethods.has(node.callee.name);if(isRsaCall&&node.arguments.length>=1){const keyArg=node.arguments[0];if(keyArg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of keyArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(prop)==="padding"){const paddingText=sourceCode.getText(prop.value);if(PKCS1_PADDING_NAMES.has(paddingText)||paddingText.includes("RSA_PKCS1_PADDING")){context.report({node:prop,messageId:"insecureRsaPadding",suggest:[{messageId:"useOaep",fix:fixer=>{return fixer.replaceText(prop.value,"crypto.constants.RSA_PKCS1_OAEP_PADDING")}}]})}}}}}}return{CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSelfSignedCerts=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noSelfSignedCerts=(0,eslint_devkit_1.createRule)({name:"no-self-signed-certs",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-self-signed-certs.md",description:"Disallow rejectUnauthorized: false in TLS options",cwe:"CWE-295",cvss:7.4},hasSuggestions:true,messages:{insecureTls:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"TLS certificate validation disabled",cwe:"CWE-295",description:"rejectUnauthorized: false disables TLS certificate validation, enabling man-in-the-middle attacks. Any certificate will be accepted, including self-signed and expired ones.",severity:"CRITICAL",fix:"Remove rejectUnauthorized: false or set it to true",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Security_Cheat_Sheet.html"}),enableValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Enable certificate validation",description:"Enable proper TLS certificate validation",severity:"LOW",fix:"rejectUnauthorized: true (or remove the property)",documentationLink:"https://nodejs.org/api/tls.html#tlsconnectoptions-callback"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options={}]){const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);function checkProperty(node){if(isTestFile)return;if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSelfSignedCerts=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noSelfSignedCerts=(0,eslint_devkit_1.createRule)({name:"no-self-signed-certs",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-self-signed-certs.md",description:"Disallow rejectUnauthorized: false in TLS options",cwe:"CWE-295",cvss:7.4},hasSuggestions:true,messages:{insecureTls:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"TLS certificate validation disabled",cwe:"CWE-295",description:"rejectUnauthorized: false disables TLS certificate validation, enabling man-in-the-middle attacks. Any certificate will be accepted, including self-signed and expired ones.",severity:"CRITICAL",fix:"Remove rejectUnauthorized: false or set it to true",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Security_Cheat_Sheet.html"}),enableValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Enable certificate validation",description:"Enable proper TLS certificate validation",severity:"LOW",fix:"rejectUnauthorized: true (or remove the property)",documentationLink:"https://nodejs.org/api/tls.html#tlsconnectoptions-callback"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options={}]){const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);function checkProperty(node){if(isTestFile)return;if((0,eslint_devkit_1.objectKeyName)(node)==="rejectUnauthorized"&&node.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&node.value.value===false){context.report({node,messageId:"insecureTls",suggest:[{messageId:"enableValidation",fix:fixer=>{return fixer.replaceText(node.value,"true")}}]})}}function checkAssignmentExpression(node){if(isTestFile)return;if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.left.object.object.name==="process"&&(0,eslint_devkit_1.propertyName)(node.left.object)==="env"&&(0,eslint_devkit_1.propertyName)(node.left)==="NODE_TLS_REJECT_UNAUTHORIZED"){if(node.right.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(node.right.value==="0"||node.right.value===0)){context.report({node,messageId:"insecureTls"})}}}return{Property:checkProperty,AssignmentExpression:checkAssignmentExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnboundedDecompression=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const ZLIB_MODULE=/^(node:)?zlib$/;const ASYNC_DECOMPRESSORS=new Set(["gunzip","inflate","inflateRaw","unzip","brotliDecompress","zstdDecompress"]);const SYNC_DECOMPRESSORS=new Set(["gunzipSync","inflateSync","inflateRawSync","unzipSync","brotliDecompressSync","zstdDecompressSync"]);exports.noUnboundedDecompression=(0,eslint_devkit_1.createRule)({name:"no-unbounded-decompression",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unbounded-decompression.md",description:"Require a maxOutputLength ceiling on zlib one-shot decompression",cwe:"CWE-409",cvss:7.5},hasSuggestions:false,messages:{unboundedDecompression:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unbounded decompression",cwe:"CWE-409",description:"zlib.{{fn}}() buffers the whole decompressed result in memory with no maxOutputLength cap. A few KB of crafted input can expand to gigabytes and exhaust the heap (decompression bomb).",severity:"HIGH",fix:"Pass an explicit ceiling: zlib.{{fn}}(input, { maxOutputLength: 10 * 1024 * 1024 }, \u2026)",documentationLink:"https://nodejs.org/api/zlib.html#class-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unbounded decompression in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options={}]){const{allowInTests=false}=options;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename);const namespaceBindings=new Set;const directBindings=new Map;const pending=[];function noteDirect(local,imported){if(ASYNC_DECOMPRESSORS.has(imported)||SYNC_DECOMPRESSORS.has(imported)){directBindings.set(local,imported)}}function requiredModule(init){if(init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="require"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof init.arguments[0].value==="string"){return init.arguments[0].value}return null}function decompressorName(node){const callee=node.callee;const name=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&name!==null&&namespaceBindings.has(callee.object.name)){return ASYNC_DECOMPRESSORS.has(name)||SYNC_DECOMPRESSORS.has(name)?name:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return directBindings.get(callee.name)??null}return null}function isLiteralPayload(argument){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;return argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&argument.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&argument.callee.object.name==="Buffer"&&argument.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal}function outputCap(options_){let capped=false;for(const property of options_.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return"unknown";
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnboundedDecompression=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const ZLIB_MODULE=/^(node:)?zlib$/;const ASYNC_DECOMPRESSORS=new Set(["gunzip","inflate","inflateRaw","unzip","brotliDecompress","zstdDecompress"]);const SYNC_DECOMPRESSORS=new Set(["gunzipSync","inflateSync","inflateRawSync","unzipSync","brotliDecompressSync","zstdDecompressSync"]);exports.noUnboundedDecompression=(0,eslint_devkit_1.createRule)({name:"no-unbounded-decompression",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unbounded-decompression.md",description:"Require a maxOutputLength ceiling on zlib one-shot decompression",cwe:"CWE-409",cvss:7.5},hasSuggestions:false,messages:{unboundedDecompression:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unbounded decompression",cwe:"CWE-409",description:"zlib.{{fn}}() buffers the whole decompressed result in memory with no maxOutputLength cap. A few KB of crafted input can expand to gigabytes and exhaust the heap (decompression bomb).",severity:"HIGH",fix:"Pass an explicit ceiling: zlib.{{fn}}(input, { maxOutputLength: 10 * 1024 * 1024 }, \u2026)",documentationLink:"https://nodejs.org/api/zlib.html#class-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unbounded decompression in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options={}]){const{allowInTests=false}=options;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename);const namespaceBindings=new Set;const directBindings=new Map;const pending=[];function noteDirect(local,imported){if(ASYNC_DECOMPRESSORS.has(imported)||SYNC_DECOMPRESSORS.has(imported)){directBindings.set(local,imported)}}function requiredModule(init){if(init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="require"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof init.arguments[0].value==="string"){return init.arguments[0].value}return null}function decompressorName(node){const callee=node.callee;const name=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&name!==null&&namespaceBindings.has(callee.object.name)){return ASYNC_DECOMPRESSORS.has(name)||SYNC_DECOMPRESSORS.has(name)?name:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return directBindings.get(callee.name)??null}return null}function isLiteralPayload(argument){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;return argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&argument.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&argument.callee.object.name==="Buffer"&&argument.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal}function outputCap(options_){let capped=false;for(const property of options_.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return"unknown";const named=(0,eslint_devkit_1.objectKeyName)(property);if(named==="maxOutputLength")capped=true}return capped?"capped":"uncapped"}function judge(node){const fn=decompressorName(node);if(fn===null)return;const args=node.arguments;const payload=args[0];if(payload===void 0)return;if(isLiteralPayload(payload))return;const isAsync=ASYNC_DECOMPRESSORS.has(fn);if(isAsync&&args.length<2)return;const candidates=isAsync?args.slice(1,args.length-1):args.slice(1);if(candidates.length>1)return;const optionsArgument=candidates[0];if(optionsArgument!==void 0){if(optionsArgument.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;if(outputCap(optionsArgument)!=="uncapped")return}context.report({node,messageId:"unboundedDecompression",data:{fn}})}return{ImportDeclaration(node){if(!ZLIB_MODULE.test(node.source.value))return;for(const specifier of node.specifiers){if(specifier.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){const imported=specifier.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?specifier.imported.name:specifier.imported.value;noteDirect(specifier.local.name,imported);continue}namespaceBindings.add(specifier.local.name)}},VariableDeclarator(node){if(!node.init)return;const source=requiredModule(node.init);if(source===null||!ZLIB_MODULE.test(source))return;if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){namespaceBindings.add(node.id.name);return}if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return;for(const property of node.id.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){noteDirect(property.value.name,property.key.name)}}},CallExpression(node){if(isTestFile)return;pending.push({node})},"Program:exit"(){for(const{node}of pending)judge(node)}}}});
|