eslint-plugin-node-security 5.8.1 → 5.8.3
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/package.json +1 -1
- package/src/index.js +1 -1
- package/src/rules/detect-child-process/index.js +1 -1
- package/src/rules/detect-eval-with-expression/index.js +1 -1
- package/src/rules/detect-non-literal-fs-filename/index.js +1 -1
- package/src/rules/detect-suspicious-dependencies/index.js +1 -1
- package/src/rules/lock-file/index.js +1 -1
- package/src/rules/no-arbitrary-file-access/index.js +1 -1
- package/src/rules/no-buffer-overread/index.js +1 -1
- package/src/rules/no-cryptojs/index.js +1 -1
- package/src/rules/no-cryptojs-weak-random/index.js +1 -1
- package/src/rules/no-data-in-temp-storage/index.js +1 -1
- package/src/rules/no-deprecated-buffer/index.js +1 -1
- package/src/rules/no-deprecated-cipher-method/index.js +1 -1
- package/src/rules/no-dynamic-algorithm-selection/index.js +1 -1
- package/src/rules/no-dynamic-command-string/index.js +1 -1
- package/src/rules/no-dynamic-require/index.js +1 -1
- package/src/rules/no-ecb-mode/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-math-random-crypto/index.js +1 -1
- package/src/rules/no-self-signed-certs/index.js +1 -1
- package/src/rules/no-sha1-hash/index.js +1 -1
- package/src/rules/no-shell-injection/index.js +1 -1
- package/src/rules/no-ssrf/index.js +1 -1
- package/src/rules/no-static-iv/index.js +1 -1
- package/src/rules/no-timing-unsafe-compare/index.js +1 -1
- package/src/rules/no-toctou-vulnerability/index.js +1 -1
- package/src/rules/no-unbounded-decompression/index.js +1 -1
- package/src/rules/no-unsafe-buffer-alloc/index.js +1 -1
- package/src/rules/no-unsafe-dynamic-require/index.js +1 -1
- package/src/rules/no-weak-cipher-algorithm/index.js +1 -1
- package/src/rules/no-weak-dh-parameters/index.js +1 -1
- package/src/rules/no-weak-hash-algorithm/index.js +1 -1
- package/src/rules/no-zip-slip/index.js +1 -1
- package/src/rules/prefer-native-crypto/index.js +1 -1
- package/src/rules/require-aead-tag-verification/index.js +1 -1
- package/src/rules/require-dependency-integrity/index.js +1 -1
- package/src/rules/require-secure-deletion/index.js +1 -1
- package/src/rules/require-storage-encryption/index.js +1 -1
- package/src/rules/require-stream-error-handler/index.js +1 -1
- package/src/utils/const-value.js +1 -1
- package/src/utils/credential-evidence.js +1 -1
- package/src/utils/module-binding.js +1 -0
- package/src/utils/provenance.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCryptojsWeakRandom=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 WEAK_RANDOM_PATH=["lib","WordArray","random"];function isCryptoJs(module){return module==="crypto-js"||module.startsWith("crypto-js/")}function endsWithWordArrayRandom(path){return path.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCryptojsWeakRandom=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 WEAK_RANDOM_PATH=["lib","WordArray","random"];function isCryptoJs(module){return module==="crypto-js"||module.startsWith("crypto-js/")}function cryptoJsPath(binding){return binding.module==="crypto-js/lib-typedarrays"?["lib","WordArray",...binding.path]:binding.path}function endsWithWordArrayRandom(path){return path.at(-2)==="WordArray"&&path.at(-1)==="random"}function resolveBinding(sourceCode,node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const key=node.computed?(0,const_value_1.resolveConstantString)(sourceCode,node.property)?.value:node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:void 0;if(key===void 0)return void 0;const base=resolveBinding(sourceCode,node.object);return base&&{module:base.module,path:[...base.path,key]}}return(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node))}function syntacticPath(sourceCode,node){const path=[];let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const key=current.computed?(0,const_value_1.resolveConstantString)(sourceCode,current.property)?.value:current.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?current.property.name:void 0;if(key===void 0)return null;path.unshift(key);current=current.object}return{root:current,path}}function isWeakRandomCall(sourceCode,callee){const binding=resolveBinding(sourceCode,callee);if(binding!==void 0){return isCryptoJs(binding.module)&&endsWithWordArrayRandom(cryptoJsPath(binding))}const spelled=syntacticPath(sourceCode,callee);if(spelled===null||spelled.root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(((0,provenance_1.findVariable)(sourceCode,spelled.root)?.defs.length??0)>0)return false;return spelled.path.length===WEAK_RANDOM_PATH.length&&WEAK_RANDOM_PATH.every((segment,i)=>spelled.path[i]===segment)}exports.noCryptojsWeakRandom=(0,eslint_devkit_1.createRule)({name:"no-cryptojs-weak-random",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-cryptojs-weak-random.md",description:"Disallow crypto-js WordArray.random() (CVE-2020-36732)",cwe:"CWE-338",cvss:5.3},messages:{weakRandom:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak random in crypto-js",cwe:"CWE-338",description:"CryptoJS.lib.WordArray.random() was insecure in versions < 3.2.1 (CVE-2020-36732). Used Math.random() instead of CSPRNG.",severity:"CRITICAL",fix:"Use crypto.randomBytes() from Node.js or crypto.getRandomValues() in browsers",documentationLink:"https://nvd.nist.gov/vuln/detail/CVE-2020-36732"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function checkCallExpression(node){if(isTestFile)return;if(!isWeakRandomCall(context.sourceCode,node.callee))return;context.report({node,messageId:"weakRandom"})}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDataInTempStorage=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const DEFAULT_TEMP_PATHS=["/tmp","/var/tmp","temp/","/temp"];
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDataInTempStorage=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const module_binding_1=require("../../utils/module-binding");const DEFAULT_TEMP_PATHS=["/tmp","/var/tmp","temp/","/temp"];function fsEntryPoints(fns){return new Set(fns.flatMap(fn=>[`fs:${fn}`,`fs:promises.${fn}`,`fs/promises:${fn}`]))}const FS_WRITE_FUNCTIONS=fsEntryPoints(["writeFile","writeFileSync","appendFile","appendFileSync","createWriteStream","outputFile","outputFileSync"]);const FS_MKDTEMP_FUNCTIONS=fsEntryPoints(["mkdtemp","mkdtempSync"]);const FS_EQUIVALENTS={"fs-extra":"fs","graceful-fs":"fs"};function containsPathSegments(haystack,needle){const split=value=>value.split(/[/\\]/).filter(segment=>segment.length>0);const target=split(needle);if(target.length===0)return false;const segments=split(haystack);return segments.some((_,start)=>target.every((segment,offset)=>segments[start+offset]===segment))}function isTmpdirCall(node){return node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="os"&&(0,eslint_devkit_1.propertyName)(node.callee)==="tmpdir"}function isStaticTmpdirJoin(node){const{callee}=node;if(callee.type!=="MemberExpression")return false;const method=(0,eslint_devkit_1.propertyName)(callee);if(method!=="join"&&method!=="resolve"){return false}if(callee.object.type!=="Identifier"||callee.object.name!=="path"){return false}if(node.arguments.length<2)return false;if(!isTmpdirCall(node.arguments[0]))return false;return node.arguments.slice(1).every(arg=>(0,eslint_devkit_1.staticString)(arg)!==null)}function isStaticTmpdirTemplate(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return false;return node.expressions.some(isTmpdirCall)&&node.expressions.every(expression=>isTmpdirCall(expression)||expression.type===eslint_devkit_1.AST_NODE_TYPES.Literal)}function isStaticTmpdirConcat(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||node.operator!=="+")return false;const side=part=>{if(isTmpdirCall(part))return"tmpdir";if((0,eslint_devkit_1.staticString)(part)!==null)return"static";if(isStaticTmpdirConcat(part))return"tmpdir";return"other"};const sides=new Set([side(node.left),side(node.right)]);return!sides.has("other")&&sides.has("tmpdir")}function isPredictableTempPath(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isStaticTmpdirJoin(node)||isStaticTmpdirTemplate(node)||isStaticTmpdirConcat(node)}exports.noDataInTempStorage=(0,eslint_devkit_1.createRule)({name:"no-data-in-temp-storage",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-data-in-temp-storage.md",description:"Prevent sensitive data in temp directories",cwe:"CWE-312",cvss:5.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Temp Storage Data",cwe:"CWE-312",description:"Sensitive data written to temp directory - not secure",severity:"HIGH",fix:"Use secure storage location or encrypt data before writing",documentationLink:"https://cwe.mitre.org/data/definitions/312.html"}),predictableTempPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Predictable Temp File Name (CWE-377)",cwe:"CWE-377",cvss:7.5,description:"path.join(os.tmpdir(), \u2026) with a constant name resolves to the same path on every run, in a directory every local user can write. An attacker who pre-creates that name \u2014 or symlinks it at a file they want clobbered \u2014 wins the race before the write happens.",severity:"HIGH",fix:"Create the file inside a fresh directory from fs.mkdtemp/mkdtempSync, or add a crypto.randomUUID() segment to the name.",documentationLink:"https://cwe.mitre.org/data/definitions/377.html"})},schema:[{type:"object",properties:{tempPaths:{type:"array",items:{type:"string"},default:DEFAULT_TEMP_PATHS,description:"Temporary path prefixes to flag. Replaces the built-in list rather than extending it."},ignoreFiles:{type:"array",items:{type:"string"},default:[],description:"List of files or patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{}],createOnce(context){let tempPaths;function report(node){context.report({node,messageId:"violationDetected"})}function callsFs(node,names){const scope=context.sourceCode.getScope(node);const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope,{equivalents:FS_EQUIVALENTS})??(0,module_binding_1.undeclaredFsBinding)(node.callee,scope);if(!binding)return false;return names.has(`${binding.module}:${binding.path.join(".")}`)}function passedAsPathTo(variable,names){return variable.references.some(reference=>{const parent=reference.identifier.parent;return parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===reference.identifier&&callsFs(parent,names)})}function reportIfPredictable(candidate,bound){if(!candidate)return;if(!isPredictableTempPath(candidate))return;if(bound!==null){const variable=bound.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?(0,provenance_1.findVariable)(context.sourceCode,bound):null;if(!variable||passedAsPathTo(variable,FS_MKDTEMP_FUNCTIONS)||!passedAsPathTo(variable,FS_WRITE_FUNCTIONS)){return}}context.report({node:candidate,messageId:"predictableTempPath"})}function staticPathRuns(node){const text=(0,eslint_devkit_1.staticString)(node);if(text!==null)return[text];if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(quasi=>quasi.value.raw)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(node.callee)==="join"||(0,eslint_devkit_1.propertyName)(node.callee)==="resolve")){return node.arguments.map(arg=>(0,eslint_devkit_1.staticString)(arg)).filter(text2=>text2!==null)}return[]}function resolvedPathRuns(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return staticPathRuns(node);const lastWrite=(0,provenance_1.findVariable)(context.sourceCode,node)?.references.map(reference=>reference.writeExpr).filter(write=>write!=null).filter(write=>write.range[1]<=node.range[0]).sort((a,b)=>a.range[1]-b.range[1]).at(-1);return lastWrite?staticPathRuns(lastWrite):[]}return{before(){const options=context.options[0]||{};tempPaths=options.tempPaths||DEFAULT_TEMP_PATHS;const ignoreFiles=options.ignoreFiles||[];const filename=context.filename;if(ignoreFiles.some(pattern=>filename.includes(pattern))){return false}return true},CallExpression(node){if(!callsFs(node,FS_WRITE_FUNCTIONS))return;const pathArg=node.arguments[0];if(pathArg){const runs=resolvedPathRuns(pathArg);if(runs.some(run=>tempPaths.some(tp=>containsPathSegments(run,tp)))){report(pathArg);return}}reportIfPredictable(pathArg,null)},VariableDeclarator(node){reportIfPredictable(node.init,node.id)},AssignmentExpression(node){reportIfPredictable(node.right,node.left)}}}});
|
|
@@ -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:{interop:{runtimes:["eslint","oxlint"]},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:[],createOnce(context){let 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
|
|
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:{interop:{runtimes:["eslint","oxlint"]},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:[],createOnce(context){let sourceCode;function resolvesToNodeBuffer(id,seen=new Set){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(variable===null||variable.defs.length===0)return id.name==="Buffer";if(seen.has(variable))return false;seen.add(variable);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.Identifier){return def.node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&variable.references.every(ref=>!ref.isWrite()||ref.init)&&resolvesToNodeBuffer(init,seen)}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.ImportSpecifier}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.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{before(){sourceCode=context.sourceCode},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.noDeprecatedCipherMethod=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEPRECATED_METHODS=new Set(["createCipher","createDecipher"]);exports.noDeprecatedCipherMethod=(0,eslint_devkit_1.createRule)({name:"no-deprecated-cipher-method",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-deprecated-cipher-method.md",description:"Disallow deprecated crypto.createCipher/createDecipher methods (use createCipheriv/createDecipheriv instead)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{deprecatedCipherMethod:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Deprecated cipher method",cwe:"CWE-327",description:"crypto.{{method}}() is deprecated. It derives key from password without salt and uses no IV, making encryption deterministic and vulnerable.",severity:"HIGH",fix:"Use crypto.{{replacement}}() with explicit key and random IV",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"}),useCipheriv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use createCipheriv",description:"Use createCipheriv with explicit key derivation and random IV",severity:"LOW",fix:"const key = crypto.scryptSync(password, salt, 32);\nconst iv = crypto.randomBytes(16);\nconst cipher = crypto.createCipheriv(algorithm, key, iv);",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow deprecated methods in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function checkCallExpression(node){if(isTestFile)return;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDeprecatedCipherMethod=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const module_binding_1=require("../../utils/module-binding");const DEPRECATED_METHODS=new Set(["createCipher","createDecipher"]);exports.noDeprecatedCipherMethod=(0,eslint_devkit_1.createRule)({name:"no-deprecated-cipher-method",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-deprecated-cipher-method.md",description:"Disallow deprecated crypto.createCipher/createDecipher methods (use createCipheriv/createDecipheriv instead)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{deprecatedCipherMethod:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Deprecated cipher method",cwe:"CWE-327",description:"crypto.{{method}}() is deprecated. It derives key from password without salt and uses no IV, making encryption deterministic and vulnerable.",severity:"HIGH",fix:"Use crypto.{{replacement}}() with explicit key and random IV",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"}),useCipheriv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use createCipheriv",description:"Use createCipheriv with explicit key derivation and random IV",severity:"LOW",fix:"const key = crypto.scryptSync(password, salt, 32);\nconst iv = crypto.randomBytes(16);\nconst cipher = crypto.createCipheriv(algorithm, key, iv);",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow deprecated methods in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function checkCallExpression(node){if(isTestFile)return;const methodName=(0,module_binding_1.calleeNameOn)(node.callee,context.sourceCode.getScope(node),"crypto");if(methodName===null||!DEPRECATED_METHODS.has(methodName))return;const replacementName=methodName==="createCipher"?"createCipheriv":"createDecipheriv";if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const callee=node.callee;const propertyNode=callee.property;context.report({node:propertyNode,messageId:"deprecatedCipherMethod",data:{method:methodName,replacement:replacementName},suggest:[{messageId:"useCipheriv",fix:fixer=>{const raw=context.sourceCode.getText(propertyNode);const quote=raw.startsWith('"')?'"':"'";return fixer.replaceText(propertyNode,callee.computed?`${quote}${replacementName}${quote}`:replacementName)}}]})}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const spelledAsExport=node.callee.name===methodName;context.report({node:node.callee,messageId:"deprecatedCipherMethod",data:{method:methodName,replacement:replacementName},suggest:spelledAsExport?[{messageId:"useCipheriv",fix:fixer=>fixer.replaceText(node.callee,replacementName)}]:[]})}}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDynamicAlgorithmSelection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const constant_folding_1=require("../../utils/constant-folding");const CRYPTO_ALGORITHM_FUNCTIONS=new Set(["createHash","createHmac","createSign","createVerify","createCipher","createCipheriv","createDecipher","createDecipheriv"]);exports.noDynamicAlgorithmSelection=(0,eslint_devkit_1.createRule)({name:"no-dynamic-algorithm-selection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-dynamic-algorithm-selection.md",description:"Disallow dynamic algorithm names in Node.js crypto functions (CWE-327)",cwe:"CWE-327",cvss:7.5},messages:{dynamicAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic Cryptographic Algorithm (CWE-327)",cwe:"CWE-327",description:"`crypto.{{method}}()` receives a dynamic algorithm name. An attacker who controls this value can downgrade to a weak algorithm (MD5, SHA1, RC4) or cause a crash.",severity:"HIGH",fix:'Hard-code the algorithm name as a literal string (e.g. "sha256", "aes-256-gcm"). Use an allowlist if the algorithm must vary at runtime.',documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html"})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let isLiteralConstant;const resolvesToLiteral=node=>{if(isLiteralConstant(node))return true;return node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,constant_folding_1.parameterIsAlwaysDefault)(sourceCode,node,isLiteralConstant)};return{before(){sourceCode=context.sourceCode;isLiteralConstant=(0,constant_folding_1.makeIsLiteralConstant)(sourceCode)},CallExpression(node){const{callee,arguments:args}=node;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDynamicAlgorithmSelection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const constant_folding_1=require("../../utils/constant-folding");const const_value_1=require("../../utils/const-value");const module_binding_1=require("../../utils/module-binding");const CRYPTO_ALGORITHM_FUNCTIONS=new Set(["createHash","createHmac","createSign","createVerify","createCipher","createCipheriv","createDecipher","createDecipheriv"]);exports.noDynamicAlgorithmSelection=(0,eslint_devkit_1.createRule)({name:"no-dynamic-algorithm-selection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-dynamic-algorithm-selection.md",description:"Disallow dynamic algorithm names in Node.js crypto functions (CWE-327)",cwe:"CWE-327",cvss:7.5},messages:{dynamicAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic Cryptographic Algorithm (CWE-327)",cwe:"CWE-327",description:"`crypto.{{method}}()` receives a dynamic algorithm name. An attacker who controls this value can downgrade to a weak algorithm (MD5, SHA1, RC4) or cause a crash.",severity:"HIGH",fix:'Hard-code the algorithm name as a literal string (e.g. "sha256", "aes-256-gcm"). Use an allowlist if the algorithm must vary at runtime.',documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html"})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let isLiteralConstant;const resolvesToLiteral=node=>{if(isLiteralConstant(node))return true;if((0,const_value_1.isClosedStringTableLookup)(sourceCode,node))return true;return node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,constant_folding_1.parameterIsAlwaysDefault)(sourceCode,node,isLiteralConstant)};return{before(){sourceCode=context.sourceCode;isLiteralConstant=(0,constant_folding_1.makeIsLiteralConstant)(sourceCode)},CallExpression(node){const{callee,arguments:args}=node;const methodName=(0,module_binding_1.moduleExportName)(callee,sourceCode.getScope(node),"crypto");if(methodName===null)return;if(!CRYPTO_ALGORITHM_FUNCTIONS.has(methodName))return;const firstArg=args[0];if(!firstArg)return;if(resolvesToLiteral(firstArg))return;context.report({node:firstArg,messageId:"dynamicAlgorithm",data:{method:methodName}})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDynamicCommandString=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const ARGV_FUNCTIONS=new Set(["spawn","spawnSync","execFile","execFileSync","fork","execa","execaSync"]);const POSIX_COMMAND_FLAGS=new Set(["-c"]);const CMD_COMMAND_FLAGS=new Set(["/c","/C","/k","/K"]);const POWERSHELL_COMMAND_FLAGS=new Set(["-Command","-command","-c","-EncodedCommand","-encodedcommand","-e","-ec"]);const SHELL_COMMAND_FLAGS={sh:POSIX_COMMAND_FLAGS,bash:POSIX_COMMAND_FLAGS,zsh:POSIX_COMMAND_FLAGS,dash:POSIX_COMMAND_FLAGS,ksh:POSIX_COMMAND_FLAGS,busybox:POSIX_COMMAND_FLAGS,cmd:CMD_COMMAND_FLAGS,"cmd.exe":CMD_COMMAND_FLAGS,powershell:POWERSHELL_COMMAND_FLAGS,"powershell.exe":POWERSHELL_COMMAND_FLAGS,pwsh:POWERSHELL_COMMAND_FLAGS};const COMMAND_RUNNERS=new Set(["execaCommand","execaCommandSync","$.raw"]);const POSIX_COMMAND_CLUSTER=/^-[a-zA-Z]*c
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDynamicCommandString=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const ARGV_FUNCTIONS=new Set(["spawn","spawnSync","execFile","execFileSync","fork","execa","execaSync"]);const POSIX_COMMAND_FLAGS=new Set(["-c"]);const CMD_COMMAND_FLAGS=new Set(["/c","/C","/k","/K"]);const POWERSHELL_COMMAND_FLAGS=new Set(["-Command","-command","-c","-EncodedCommand","-encodedcommand","-e","-ec"]);const SHELL_COMMAND_FLAGS={sh:POSIX_COMMAND_FLAGS,bash:POSIX_COMMAND_FLAGS,zsh:POSIX_COMMAND_FLAGS,dash:POSIX_COMMAND_FLAGS,ksh:POSIX_COMMAND_FLAGS,busybox:POSIX_COMMAND_FLAGS,cmd:CMD_COMMAND_FLAGS,"cmd.exe":CMD_COMMAND_FLAGS,powershell:POWERSHELL_COMMAND_FLAGS,"powershell.exe":POWERSHELL_COMMAND_FLAGS,pwsh:POWERSHELL_COMMAND_FLAGS};const COMMAND_RUNNERS=new Set(["execaCommand","execaCommandSync","$.raw"]);const POSIX_COMMAND_CLUSTER=/^-[a-zA-Z]*c[a-zA-Z]*$/;function isCommandFlag(commandFlags,flag){if(commandFlags.has(flag))return true;return commandFlags===POSIX_COMMAND_FLAGS&&POSIX_COMMAND_CLUSTER.test(flag)}function basename(command){const segments=command.split(/[\\/]/);return segments[segments.length-1]}function shellDialect(command){const shell=basename(command);const flags=SHELL_COMMAND_FLAGS[shell.toLowerCase()];return flags?{shell,flags}:null}function isAssembledString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return node.operator==="+"}return node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier||node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression}function calleeName(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return callee.name;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return null;if(callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="$"){return`$.${method}`}return method}exports.noDynamicCommandString=(0,eslint_devkit_1.createRule)({name:"no-dynamic-command-string",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-dynamic-command-string.md",description:"Disallow dynamically assembled command strings passed to a shell flag or to a command-runner that does not escape (CWE-77)",cwe:"CWE-77",cvss:9.8,confidence:"high"},messages:{shellFlagInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Command Injection Through Shell Flag (CWE-77)",cwe:"CWE-77",cvss:9.8,description:'{{fn}}("{{shell}}", ["{{flag}}", \u2026]) hands a dynamically built string to {{shell}}, which parses it as a command line. The argument array looks parameterized but everything after {{flag}} is re-parsed \u2014 `;`, `&&`, backticks and `$()` all execute.',severity:"CRITICAL",fix:'Invoke the target program directly with its own argument array \u2014 spawn("kill", [String(pid)]) \u2014 instead of routing it through a shell.',documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html"}),commandStringInterpolation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Interpolated Command Line (CWE-77)",cwe:"CWE-77",cvss:9.8,description:"{{fn}}() takes a whole command line and does NOT escape interpolated values (unlike the execa/zx tagged-template forms). Any special character in the interpolated value changes which command runs.",severity:"CRITICAL",fix:'Use the tagged-template or array form that escapes for you: execa("git", ["clone", url]) or await $`git clone ${url}`.',documentationLink:"https://cwe.mitre.org/data/definitions/77.html"})},schema:[{type:"object",properties:{extraCommandRunners:{type:"array",items:{type:"string"},default:[],description:"Extra functions that accept a full command line without escaping. Added to the built-in runners, not a replacement for them."}},additionalProperties:false}]},defaultOptions:[{}],createOnce(context,currentOptions){let runners;let sourceCode;function staticStringOf(node){const resolved=(0,const_value_1.resolveConstantString)(sourceCode,node);if(resolved)return resolved.value;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;if(node.computed)return null;if(node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(node.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const init=(0,const_value_1.constInitializerOf)(sourceCode,node.object);if(!init)return null;const literal=init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&calleeName(init.callee)==="freeze"&&init.arguments[0]?init.arguments[0]:init;if(literal.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return null;for(const property of[...literal.properties].reverse()){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)return null;const key=(0,eslint_devkit_1.objectKeyName)(property);if(key===null)return null;if(key!==node.property.name)continue;return(0,const_value_1.resolveConstantString)(sourceCode,property.value)?.value??null}return null}function isAssembled(node){if(staticStringOf(node)!==null)return false;return isAssembledString(node)}function canonicalName(callee){const direct=calleeName(callee);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return direct;const init=(0,const_value_1.constInitializerOf)(sourceCode,callee);if(!init)return direct;const target=init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&calleeName(init.callee)==="promisify"?init.arguments[0]:init;if(!target)return direct;const resolved=calleeName(target);if(resolved===null)return direct;return ARGV_FUNCTIONS.has(resolved)||runners.has(resolved)?resolved:direct}function shellPositions(command,argv){const positions=[];const commandText=staticStringOf(command);const outer=commandText===null?null:shellDialect(commandText);if(outer)positions.push({...outer,from:0});argv.elements.forEach((element,index)=>{if(!element)return;const text=staticStringOf(element);if(text===null)return;const nested=shellDialect(text);if(nested)positions.push({...nested,from:index+1})});return positions}function checkShellFlag(node,fn){const argvNode=node.arguments[1];const argv=argvNode?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?(0,const_value_1.constInitializerOf)(sourceCode,argvNode):argvNode;if(!argv||argv.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return;const command=node.arguments[0];for(const{shell,flags,from}of shellPositions(command,argv)){for(let i=from;i<argv.elements.length-1;i+=1){const flag=argv.elements[i];if(!flag)continue;const flagText=staticStringOf(flag);if(flagText===null)continue;if(!isCommandFlag(flags,flagText))continue;const commandString=argv.elements[i+1];if(!commandString)continue;if(!isAssembled(commandString))continue;context.report({node:commandString,messageId:"shellFlagInjection",data:{fn,shell,flag:flagText}});return}}}function checkCommandRunner(node,fn){const commandLine=node.arguments[0];if(!commandLine)return;if(!isAssembled(commandLine))return;context.report({node:commandLine,messageId:"commandStringInterpolation",data:{fn}})}return{before(){const[options]=currentOptions();const{extraCommandRunners}=options;runners=new Set([...COMMAND_RUNNERS,...extraCommandRunners??[]]);({sourceCode}=context)},CallExpression(node){const fn=canonicalName(node.callee);if(!fn)return;if(ARGV_FUNCTIONS.has(fn)){checkShellFlag(node,fn);return}if(runners.has(fn)){checkCommandRunner(node,fn)}},TaggedTemplateExpression(node){const fn=calleeName(node.tag);if(!fn||!runners.has(fn))return;if(node.quasi.expressions.length===0)return;context.report({node:node.quasi,messageId:"commandStringInterpolation",data:{fn}})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDynamicRequire=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const module_loader_1=require("./module-loader");exports.noDynamicRequire=(0,eslint_devkit_1.createRule)({name:"no-dynamic-require",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-dynamic-require.md",description:"Forbid `require()` calls with expressions",cwe:"CWE-94",cweJustification:"CWE-94 (Improper Control of Generation of Code) \u2014 dynamic require with attacker-influenced path can load arbitrary modules, equivalent to remote code execution.",confidence:"high"},hasSuggestions:false,messages:{dynamicRequire:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Dynamic Require",cwe:"CWE-94",description:"Require call uses dynamic expression",severity:"HIGH",fix:"Use static string literals for require() calls",documentationLink:"https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-dynamic-require.md"})},schema:[{type:"object",properties:{allowContexts:{type:"array",items:{type:"string",enum:["test","config","build","runtime"]},default:[],description:"Allow dynamic requires in
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDynamicRequire=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const module_loader_1=require("./module-loader");exports.noDynamicRequire=(0,eslint_devkit_1.createRule)({name:"no-dynamic-require",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-dynamic-require.md",description:"Forbid `require()` calls with expressions",cwe:"CWE-94",cweJustification:"CWE-94 (Improper Control of Generation of Code) \u2014 dynamic require with attacker-influenced path can load arbitrary modules, equivalent to remote code execution.",confidence:"high"},hasSuggestions:false,messages:{dynamicRequire:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Dynamic Require",cwe:"CWE-94",description:"Require call uses dynamic expression",severity:"HIGH",fix:"Use static string literals for require() calls",documentationLink:"https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-dynamic-require.md"})},schema:[{type:"object",properties:{allowContexts:{type:"array",items:{type:"string",enum:["test","config","build","runtime"]},default:[],description:"Allow dynamic requires in files whose path marks a context \u2014 a substring test on the linted file path: test (.test., .spec., /__tests__/), config (config, webpack, rollup), build (build, scripts, tools), runtime (runtime, dynamic)."},allowPatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns matched against the source text of the require argument; a match suppresses the report."}},additionalProperties:false}]},defaultOptions:[{allowContexts:[],allowPatterns:[]}],createOnce(context){let allowContexts;let allowPatterns;let filename;let allowed;function isInAllowedContext(){if(allowContexts.includes("test")&&(filename.includes(".test.")||filename.includes(".spec.")||filename.includes("/__tests__/"))){return true}if(allowContexts.includes("config")&&(filename.includes("config")||filename.includes("webpack")||filename.includes("rollup"))){return true}if(allowContexts.includes("build")&&(filename.includes("build")||filename.includes("scripts")||filename.includes("tools"))){return true}if(allowContexts.includes("runtime")&&(filename.includes("runtime")||filename.includes("dynamic"))){return true}return false}function isFixedSpecifier(node){return(0,eslint_devkit_1.isStaticExpression)({node,scope:context.sourceCode.getScope(node)})}return{before(){const[options]=context.options;({allowContexts=[],allowPatterns=[]}=options||{});filename=context.filename||"";allowed=(0,eslint_devkit_1.compileUserPatterns)(allowPatterns,"")},CallExpression(node){const[requireArg]=node.arguments;if(requireArg!==void 0&&(0,module_loader_1.isModuleLoader)(node.callee,context.sourceCode)){if(isInAllowedContext()){return}if(isFixedSpecifier(requireArg)){return}if((0,eslint_devkit_1.matchesAnyUserPattern)(allowed,context.sourceCode.getText(requireArg))){return}context.report({node:requireArg,messageId:"dynamicRequire"})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noEcbMode=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");exports.noEcbMode=(0,eslint_devkit_1.createRule)({name:"no-ecb-mode",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-ecb-mode.md",description:"Disallow ECB encryption mode (use GCM or CBC instead)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{ecbMode:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ECB mode detected",cwe:"CWE-327",description:'ECB mode encrypts identical plaintext blocks to identical ciphertext, leaking data patterns. Famous example: the "ECB penguin".',severity:"HIGH",fix:'Use GCM mode for authenticated encryption: crypto.createCipheriv("aes-256-gcm", key, iv)',documentationLink:"https://blog.cloudflare.com/why-are-some-images-more-secure-than-others/"}),useGcm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use GCM mode",description:"GCM provides authenticated encryption (confidentiality + integrity)",severity:"LOW",fix:'crypto.createCipheriv("aes-256-gcm", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"}),useCbc:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use CBC mode",description:"CBC with HMAC provides confidentiality (add separate MAC for integrity)",severity:"LOW",fix:'crypto.createCipheriv("aes-256-cbc", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow ECB mode in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function checkCallExpression(node){if(isTestFile)return;const cipherMethods=new Set(["createCipher","createCipheriv","createDecipher","createDecipheriv"]);const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noEcbMode=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const module_binding_1=require("../../utils/module-binding");exports.noEcbMode=(0,eslint_devkit_1.createRule)({name:"no-ecb-mode",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-ecb-mode.md",description:"Disallow ECB encryption mode (use GCM or CBC instead)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{ecbMode:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ECB mode detected",cwe:"CWE-327",description:'ECB mode encrypts identical plaintext blocks to identical ciphertext, leaking data patterns. Famous example: the "ECB penguin".',severity:"HIGH",fix:'Use GCM mode for authenticated encryption: crypto.createCipheriv("aes-256-gcm", key, iv)',documentationLink:"https://blog.cloudflare.com/why-are-some-images-more-secure-than-others/"}),useGcm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use GCM mode",description:"GCM provides authenticated encryption (confidentiality + integrity)",severity:"LOW",fix:'crypto.createCipheriv("aes-256-gcm", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"}),useCbc:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use CBC mode",description:"CBC with HMAC provides confidentiality (add separate MAC for integrity)",severity:"LOW",fix:'crypto.createCipheriv("aes-256-cbc", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow ECB mode in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function checkCallExpression(node){if(isTestFile)return;const cipherMethods=new Set(["createCipher","createCipheriv","createDecipher","createDecipheriv"]);const calleeName=(0,module_binding_1.calleeNameOn)(node.callee,context.sourceCode.getScope(node),"crypto");const isCipherCall=calleeName!==null&&cipherMethods.has(calleeName);if(isCipherCall&&node.arguments.length>=1){const algorithmArg=node.arguments[0];const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,algorithmArg);if(resolved===null)return;const algorithm=resolved.value.toLowerCase();if(algorithm.includes("-ecb")){const gcmReplacement=algorithm.replace(/-?ecb$/,"-gcm");const target=resolved.source;context.report({node:algorithmArg,messageId:"ecbMode",suggest:[{messageId:"useGcm",fix:fixer=>{return fixer.replaceText(target,`"${gcmReplacement}"`)}},{messageId:"useCbc",fix:fixer=>{const cbcReplacement=algorithm.replace(/-?ecb$/,"-cbc");return fixer.replaceText(target,`"${cbcReplacement}"`)}}]})}}}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
|
|
@@ -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,
|
|
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,resolving=new Set){const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return foldNumber(sourceCode,bare,resolving);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,resolving);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,resolving);const right=foldNumber(sourceCode,node.right,resolving);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){return foldBinding(sourceCode,(0,const_value_1.constInitializerOf)(sourceCode,node),resolving)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const value=objectPropertyValue(sourceCode,node.object,propertyKey(sourceCode,node));return foldBinding(sourceCode,value,resolving)}return null}function foldBinding(sourceCode,value,resolving){if(value===null||resolving.has(value))return null;resolving.add(value);const folded=foldNumber(sourceCode,value,resolving);resolving.delete(value);return folded}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){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,seen=new Set){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],seen)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,const_value_1.constInitializerOf)(sourceCode,callee);if(init===null||seen.has(init))return false;seen.add(init);return isPromisifyCall(sourceCode,init)&&init.arguments.length>0&&isPbkdf2Callee(sourceCode,init.arguments[0],seen)}return false}const DEFAULT_MIN_ITERATIONS=1e5;exports.noInsecureKeyDerivation=(0,eslint_devkit_1.createRule)({name:"no-insecure-key-derivation",meta:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context,currentOptions){let minIterations;let 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 options=node.arguments[2];if(options!==void 0){judgeIterations(objectPropertyValue(sourceCode,options,"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{before(){const[options={}]=currentOptions();({minIterations=DEFAULT_MIN_ITERATIONS}=options);sourceCode=context.sourceCode},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
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureRsaPadding=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const module_binding_1=require("../../utils/module-binding");const RSA_PKCS1_PADDING_VALUE=1;exports.noInsecureRsaPadding=(0,eslint_devkit_1.createRule)({name:"no-insecure-rsa-padding",meta:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context,currentOptions){let isTestFile;let sourceCode;function checkCallExpression(node){if(isTestFile)return;const rsaMethods=new Set(["privateDecrypt","publicDecrypt","privateEncrypt","publicEncrypt"]);const calleeName=(0,module_binding_1.calleeNameOn)(node.callee,sourceCode.getScope(node),"crypto");const isRsaCall=calleeName!==null&&rsaMethods.has(calleeName);if(isRsaCall&&node.arguments.length>=1){const written=node.arguments[0];const keyArg=written.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?(0,const_value_1.constInitializerOf)(sourceCode,written)??written:written;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 padding=prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?(0,const_value_1.constInitializerOf)(sourceCode,prop.value)??prop.value:prop.value;const paddingText=sourceCode.getText(padding);if(paddingText.includes("RSA_PKCS1_PADDING")||padding.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&padding.value===RSA_PKCS1_PADDING_VALUE){context.report({node:prop,messageId:"insecureRsaPadding",suggest:[{messageId:"useOaep",fix:fixer=>prop.shorthand?fixer.replaceText(prop,"padding: crypto.constants.RSA_PKCS1_OAEP_PADDING"):fixer.replaceText(prop.value,"crypto.constants.RSA_PKCS1_OAEP_PADDING")}]})}}}}}}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);sourceCode=context.sourceCode},CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMathRandomCrypto=void 0;const names_1=require("../../utils/names");const provenance_1=require("../../utils/provenance");const eslint_devkit_1=require("@interlace/eslint-devkit");const CSPRNG_CALLS=new Set(["getRandomValues","randomBytes","randomUUID","randomFillSync","randomFill","generateKey","subtle"]);const CRYPTO_WORDS=["token","tokens","key","keys","secret","secrets","password","passwd","salt","iv","nonce","seed","hash","cipher","auth","session","csrf","otp","pin","code","codes","verify","signature","credential","jwt","encryption","apikey","passphrase","mnemonic"];const DURATION_TAILS=new Set(["delay","timeout","interval","jitter","backoff","ms","millis","milliseconds","seconds","duration","wait","sleep","ttl","deadline","elapsed","latency","budget"]);const QUANTITY_TAILS=new Set(["count","counts","length","size","total","limit","quota","offset","index","rank","score","percent","ratio","rate","version","page"]);const NON_SECURITY_QUALIFIERS=new Map([["code",new Set(["http","status","error","err","exit","country","zip","postal","area","language","lang","locale","currency","promo","coupon","discount","color","colour","qr","bar","region","iso","mime","media","sort","source","char","unicode","ascii","airport"])],["key",new Set(["cache","map","object","row","index","partition","primary","foreign","sort","storage","translation","locale","i18n","react","idempotency","shortcut","keyboard","press","modifier"])]]);function nameSuggestsCrypto(name,vocab){if(!vocab.suggestsCrypto(name))return false;const words=(0,names_1.identifierWords)(name);const tail=words[words.length-1];if(DURATION_TAILS.has(tail)||QUANTITY_TAILS.has(tail))return false;const matched=words.filter(word=>vocab.words.has(word));if(matched.length===0)return true;return!matched.every(word=>{const qualifiers=NON_SECURITY_QUALIFIERS.get(word);return qualifiers!==void 0&&words.some(other=>qualifiers.has(other))})}function isMathRandomProperty(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(node.object.name!=="Math")return false;const property=node.property;if(!node.computed){return property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.name==="random"}return property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value==="random"}const NON_SECURITY_ID_QUALIFIERS=new Set(["request","req","correlation","trace","span","transaction","txn","message","msg","event","job","run","task","batch","element","node","row","record","instance","component","widget","dom","operation","call","invocation","frame","render"]);function isCorrelationIdFactory(name,vocab){const words=(0,names_1.identifierWords)(name);if(words[words.length-1]!=="id")return false;if(words.some(word=>vocab.words.has(word)))return false;return words.some(word=>vocab.correlationWords.has(word))}function functionNameSuggestsCrypto(name,vocab){if(!CRYPTO_FUNCTION_PATTERNS.some(pattern=>pattern.test(name)))return false;return!isCorrelationIdFactory(name,vocab)}const CRYPTO_FUNCTION_PATTERNS=[/generate.*token/i,/generate.*key/i,/generate.*id/i,/create.*secret/i,/create.*token/i,/random.*string/i,/get.*random.*(string|bytes|token|key|secret|value|id)/i,/make.*salt/i,/gen.*password/i];exports.noMathRandomCrypto=(0,eslint_devkit_1.createRule)({name:"no-math-random-crypto",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-math-random-crypto.md",description:"Disallow Math.random() for cryptographic purposes",cwe:"CWE-338",cvss:7.5,confidence:"medium"},messages:{pseudoRandomBytes:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Non-cryptographic random bytes",cwe:"CWE-338",owasp:"A02:2021",cvss:7.5,description:"crypto.pseudoRandomBytes() is not cryptographically secure. The name is the API's own warning: it was deprecated in Node 4 precisely because callers assumed otherwise.",severity:"HIGH",compliance:["SOC2","PCI-DSS","ISO27001"],fix:"Use crypto.randomBytes(n), or crypto.randomUUID() for identifiers.",documentationLink:"https://cwe.mitre.org/data/definitions/338.html"}),mathRandomCrypto:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Math.random() used for crypto",cwe:"CWE-338",description:"Math.random() is not cryptographically secure. It uses a PRNG that can be predicted. Never use it for tokens, keys, passwords, or any security-sensitive values.",severity:"CRITICAL",fix:"Use crypto.randomBytes() or crypto.randomUUID() instead",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#secure-random-number-generation"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow Math.random() in test files. Default: true"},secretWords:{type:"array",items:{type:"string"},default:[...CRYPTO_WORDS],description:"Words that name a security value in this codebase. Replaces the default list."},correlationIdWords:{type:"array",items:{type:"string"},default:[...NON_SECURITY_ID_QUALIFIERS],description:"Words that mark a trailing `id` as a correlation id rather than a credential. Replaces the default list."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,secretWords:[...CRYPTO_WORDS],correlationIdWords:[...NON_SECURITY_ID_QUALIFIERS]}],createOnce(context,currentOptions){let vocab;let sourceCode;let isTestFile;const MAX_BINDING_HOPS=2;function stableDeclarator(id){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(!variable||variable.defs.length!==1)return void 0;const def=variable.defs[0];if(def.type!=="Variable")return void 0;const reassigned=variable.references.some(reference=>reference.writeExpr!=null&&!reference.init);return reassigned?void 0:def.node}function isCsprngFallback(node){let scope=node.parent;while(scope!==void 0&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.Program){scope=scope.parent}let found=false;const stack=[scope];while(stack.length>0&&!found){const current=stack.pop();if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&¤t.range[1]<=node.range[0]){const callee=current.callee;const name=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee)??"":callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:"";if(CSPRNG_CALLS.has(name))found=true}for(const key of Object.keys(current)){if(key==="parent")continue;const value=current[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){stack.push(child)}}}}return found}function isMathRandomCallee(callee){if(isMathRandomProperty(callee))return true;const wanted=(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&&wanted!==null){const init2=stableDeclarator(callee.object)?.init;if(!init2||init2.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return false;return init2.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)===wanted&&isMathRandomProperty(property.value))}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const declarator=stableDeclarator(callee);const init=declarator?.init;if(!declarator||!init)return false;if(declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isMathRandomProperty(init)}if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return false;if(init.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||init.name!=="Math")return false;return declarator.id.properties.some(property=>{if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)return false;if(property.value.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(property.value.name!==callee.name)return false;const key=property.key;if(key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return key.name==="random";return key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&key.value==="random"})}function usedInCryptoContext(id,depth){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(!variable)return false;return variable.references.some(reference=>!reference.init&&isCryptoContext(reference.identifier,depth))}function escapesFunction(fn,cameFrom,passedReturn){if(fn.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.expression&&fn.body===cameFrom){return true}return passedReturn}function isCryptoContext(node,depth=0){let child=node;let current=node.parent;let namesThisValue=true;let passedReturn=false;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){if(!escapesFunction(current,child,passedReturn))namesThisValue=false;passedReturn=false}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)passedReturn=true;if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){if(current.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const varName=current.id.name;if(nameSuggestsCrypto(varName,vocab)){return true}if(depth<MAX_BINDING_HOPS&&usedInCryptoContext(current.id,depth+1)){return true}}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&¤t.id){const funcName=current.id.name;if(functionNameSuggestsCrypto(funcName,vocab)){return true}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){const propName=(0,eslint_devkit_1.memberPropertyName)(current.left);if(current.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&propName!==null){if(nameSuggestsCrypto(propName,vocab)){return true}}if(current.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(nameSuggestsCrypto(current.left.name,vocab)){return true}}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.Property){if(current.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const propName=current.key.name;if(nameSuggestsCrypto(propName,vocab)){return true}}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){const func=findContainingFunction(current);if(func){if((func.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||func.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)&&func.id?.name){const funcName=func.id.name;if(functionNameSuggestsCrypto(funcName,vocab)||nameSuggestsCrypto(funcName,vocab)){return true}}}}child=current;current=current.parent}return false}function findContainingFunction(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return current}current=current.parent}return null}return{before(){const[options={}]=currentOptions();const{allowInTests=true,secretWords=CRYPTO_WORDS,correlationIdWords=[...NON_SECURITY_ID_QUALIFIERS]}=options;vocab={words:new Set(secretWords),correlationWords:new Set(correlationIdWords),suggestsCrypto:(0,names_1.makeNameTest)(secretWords)};sourceCode=context.sourceCode;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression(node){if(isTestFile)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="pseudoRandomBytes"){context.report({node,messageId:"pseudoRandomBytes"});return}if(isMathRandomCallee(node.callee)){if(isCryptoContext(node)&&!isCsprngFallback(node)){context.report({node,messageId:"mathRandomCrypto"})}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMathRandomCrypto=void 0;const names_1=require("../../utils/names");const provenance_1=require("../../utils/provenance");const eslint_devkit_1=require("@interlace/eslint-devkit");const CSPRNG_CALLS=new Set(["getRandomValues","randomBytes","randomUUID","randomFillSync","randomFill","generateKey","subtle"]);const CRYPTO_WORDS=["token","tokens","key","keys","secret","secrets","password","passwd","salt","iv","nonce","seed","hash","cipher","auth","session","csrf","otp","pin","code","codes","verify","signature","credential","jwt","encryption","apikey","passphrase","mnemonic"];const DURATION_TAILS=new Set(["delay","timeout","interval","jitter","backoff","ms","millis","milliseconds","seconds","duration","wait","sleep","ttl","deadline","elapsed","latency","budget"]);const QUANTITY_TAILS=new Set(["count","counts","length","size","total","limit","quota","offset","index","rank","score","percent","ratio","rate","version","page"]);const NON_SECURITY_QUALIFIERS=new Map([["code",new Set(["http","status","error","err","exit","country","zip","postal","area","language","lang","locale","currency","promo","coupon","discount","color","colour","qr","bar","region","iso","mime","media","sort","source","char","unicode","ascii","airport"])],["key",new Set(["cache","map","object","row","index","partition","primary","foreign","sort","storage","translation","locale","i18n","react","idempotency","shortcut","keyboard","press","modifier"])]]);function nameSuggestsCrypto(name,vocab){if(!vocab.suggestsCrypto(name))return false;const words=(0,names_1.identifierWords)(name);const tail=words[words.length-1];if(DURATION_TAILS.has(tail)||QUANTITY_TAILS.has(tail))return false;const matched=words.filter(word=>vocab.words.has(word));if(matched.length===0)return true;return!matched.every(word=>{const qualifiers=NON_SECURITY_QUALIFIERS.get(word);return qualifiers!==void 0&&words.some(other=>qualifiers.has(other))})}const GLOBAL_OBJECTS=new Set(["globalThis","global","window","self"]);function isMathObject(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="Math";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&GLOBAL_OBJECTS.has(node.object.name)&&(0,eslint_devkit_1.propertyName)(node)==="Math"}function isMathRandomProperty(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&isMathObject(node.object)&&(0,eslint_devkit_1.propertyName)(node)==="random"}const NON_SECURITY_ID_QUALIFIERS=new Set(["request","req","correlation","trace","span","transaction","txn","message","msg","event","job","run","task","batch","element","node","row","record","instance","component","widget","dom","operation","call","invocation","frame","render"]);function isCorrelationIdFactory(name,vocab){const words=(0,names_1.identifierWords)(name);if(words[words.length-1]!=="id")return false;if(words.some(word=>vocab.words.has(word)))return false;return words.some(word=>vocab.correlationWords.has(word))}function functionNameSuggestsCrypto(name,vocab){if(!CRYPTO_FUNCTION_PATTERNS.some(pattern=>pattern.test(name)))return false;return!isCorrelationIdFactory(name,vocab)}const CRYPTO_FUNCTION_PATTERNS=[/generate.*token/i,/generate.*key/i,/generate.*id/i,/create.*secret/i,/create.*token/i,/random.*string/i,/get.*random.*(string|bytes|token|key|secret|value|id)/i,/make.*salt/i,/gen.*password/i];exports.noMathRandomCrypto=(0,eslint_devkit_1.createRule)({name:"no-math-random-crypto",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-math-random-crypto.md",description:"Disallow Math.random() for cryptographic purposes",cwe:"CWE-338",cvss:7.5,confidence:"medium"},messages:{pseudoRandomBytes:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Non-cryptographic random bytes",cwe:"CWE-338",owasp:"A02:2021",cvss:7.5,description:"crypto.pseudoRandomBytes() is not cryptographically secure. The name is the API's own warning: it was deprecated in Node 4 precisely because callers assumed otherwise.",severity:"HIGH",compliance:["SOC2","PCI-DSS","ISO27001"],fix:"Use crypto.randomBytes(n), or crypto.randomUUID() for identifiers.",documentationLink:"https://cwe.mitre.org/data/definitions/338.html"}),mathRandomCrypto:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Math.random() used for crypto",cwe:"CWE-338",description:"Math.random() is not cryptographically secure. It uses a PRNG that can be predicted. Never use it for tokens, keys, passwords, or any security-sensitive values.",severity:"CRITICAL",fix:"Use crypto.randomBytes() or crypto.randomUUID() instead",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#secure-random-number-generation"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow Math.random() in test files. Default: true"},secretWords:{type:"array",items:{type:"string"},default:[...CRYPTO_WORDS],description:"Words that name a security value in this codebase. Replaces the default list."},correlationIdWords:{type:"array",items:{type:"string"},default:[...NON_SECURITY_ID_QUALIFIERS],description:"Words that mark a trailing `id` as a correlation id rather than a credential. Replaces the default list."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,secretWords:[...CRYPTO_WORDS],correlationIdWords:[...NON_SECURITY_ID_QUALIFIERS]}],createOnce(context,currentOptions){let vocab;let sourceCode;let isTestFile;function stableDeclarator(id){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(!variable||variable.defs.length!==1)return void 0;const def=variable.defs[0];if(def.type!=="Variable")return void 0;const reassigned=variable.references.some(reference=>reference.writeExpr!=null&&!reference.init);return reassigned?void 0:def.node}function isCsprngFallback(node){let scope=node.parent;while(scope.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&scope.type!==eslint_devkit_1.AST_NODE_TYPES.Program){scope=scope.parent}let found=false;const stack=[scope];while(stack.length>0&&!found){const current=stack.pop();if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&¤t.range[1]<=node.range[0]){const callee=current.callee;const name=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee)??"":callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:"";if(CSPRNG_CALLS.has(name))found=true}for(const key of Object.keys(current)){if(key==="parent")continue;const value=current[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){stack.push(child)}}}}return found}function isMathRandomCallee(callee){if(isMathRandomProperty(callee))return true;const wanted=(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&&wanted!==null){const init2=stableDeclarator(callee.object)?.init;if(!init2||init2.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return false;return init2.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)===wanted&&isMathRandomProperty(property.value))}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const declarator=stableDeclarator(callee);const init=declarator?.init;if(!declarator||!init)return false;if(declarator.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isMathRandomProperty(init)}if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return false;if(!isMathObject(init))return false;return declarator.id.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===callee.name&&(0,eslint_devkit_1.objectKeyName)(property)==="random")}function usedInCryptoContext(id,followed){const variable=(0,provenance_1.findVariable)(sourceCode,id);if(!variable||followed.has(variable))return false;followed.add(variable);return variable.references.some(reference=>!reference.init&&isCryptoContext(reference.identifier,followed))}function escapesFunction(fn,cameFrom,passedReturn){if(fn.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.expression&&fn.body===cameFrom){return true}return passedReturn}function isCryptoContext(node,followed=new Set){let child=node;let current=node.parent;let namesThisValue=true;let passedReturn=false;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){if(!escapesFunction(current,child,passedReturn))namesThisValue=false;passedReturn=false}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)passedReturn=true;if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){if(current.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const varName=current.id.name;if(nameSuggestsCrypto(varName,vocab)){return true}if(usedInCryptoContext(current.id,followed)){return true}}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&¤t.id){const funcName=current.id.name;if(functionNameSuggestsCrypto(funcName,vocab)){return true}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){const propName=(0,eslint_devkit_1.memberPropertyName)(current.left);if(propName!==null){if(nameSuggestsCrypto(propName,vocab)){return true}}if(current.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(nameSuggestsCrypto(current.left.name,vocab)){return true}}}if(namesThisValue&¤t.type===eslint_devkit_1.AST_NODE_TYPES.Property){if(current.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const propName=current.key.name;if(nameSuggestsCrypto(propName,vocab)){return true}}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){const funcName=findContainingFunction(current)?.id?.name;if(funcName!==void 0&&(functionNameSuggestsCrypto(funcName,vocab)||nameSuggestsCrypto(funcName,vocab))){return true}}child=current;current=current.parent}return false}function findContainingFunction(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return current}current=current.parent}return null}return{before(){const[options={}]=currentOptions();const{allowInTests=true,secretWords=CRYPTO_WORDS,correlationIdWords=[...NON_SECURITY_ID_QUALIFIERS]}=options;vocab={words:new Set(secretWords),correlationWords:new Set(correlationIdWords),suggestsCrypto:(0,names_1.makeNameTest)(secretWords)};sourceCode=context.sourceCode;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression(node){if(isTestFile)return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="pseudoRandomBytes"){context.report({node,messageId:"pseudoRandomBytes"});return}if(isMathRandomCallee(node.callee)){if(isCryptoContext(node)&&!isCsprngFallback(node)){context.report({node,messageId:"mathRandomCrypto"})}}}}}});
|
|
@@ -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:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context,currentOptions){let isTestFile;function checkProperty(node){if(isTestFile)return;if((0,eslint_devkit_1.objectKeyName)(node)==="rejectUnauthorized"&&node.value
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSelfSignedCerts=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");exports.noSelfSignedCerts=(0,eslint_devkit_1.createRule)({name:"no-self-signed-certs",meta:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context,currentOptions){let isTestFile;function checkProperty(node){if(isTestFile)return;if((0,eslint_devkit_1.objectKeyName)(node)==="rejectUnauthorized"&&isFalse(node.value)){context.report({node,messageId:"insecureTls",suggest:[{messageId:"enableValidation",fix:fixer=>{return fixer.replaceText(node.value,"true")}}]})}}function isFalse(value){const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(value);const resolved=bare.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?(0,const_value_1.constInitializerOf)(context.sourceCode,bare):bare;if(resolved===null)return false;const literal=(0,eslint_devkit_1.unwrapTypeSyntax)(resolved);return literal.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&literal.value===false}function isProcess(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="process";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="globalThis"&&(0,eslint_devkit_1.propertyName)(node)==="process"}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&&isProcess(node.left.object.object)&&(0,eslint_devkit_1.propertyName)(node.left.object)==="env"&&(0,eslint_devkit_1.propertyName)(node.left)==="NODE_TLS_REJECT_UNAUTHORIZED"){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node.right);if((0,eslint_devkit_1.staticString)(value)==="0"||value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&value.value===0){context.report({node,messageId:"insecureTls"})}}}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},Property:checkProperty,AssignmentExpression:checkAssignmentExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSha1Hash=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noSha1Hash=(0,eslint_devkit_1.createRule)({name:"no-sha1-hash",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-sha1-hash.md",description:"Disallow sha1() from crypto-hash package (use sha256 or sha512)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{sha1Deprecated:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SHA-1 hash detected",cwe:"CWE-327",description:"SHA-1 is cryptographically broken and should not be used. The crypto-hash package itself warns against using sha1().",severity:"HIGH",fix:"Use sha256() or sha512() instead",documentationLink:"https://shattered.io/"}),useSha256:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use sha256",description:"SHA-256 provides adequate security for most use cases",severity:"LOW",fix:"import { sha256 } from 'crypto-hash'; await sha256(data)",documentationLink:"https://www.npmjs.com/package/crypto-hash"}),useSha512:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use sha512",description:"SHA-512 provides stronger security with longer hash",severity:"LOW",fix:"import { sha512 } from 'crypto-hash'; await sha512(data)",documentationLink:"https://www.npmjs.com/package/crypto-hash"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow SHA1 in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSha1Hash=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noSha1Hash=(0,eslint_devkit_1.createRule)({name:"no-sha1-hash",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-sha1-hash.md",description:"Disallow sha1() from crypto-hash package (use sha256 or sha512)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{sha1Deprecated:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SHA-1 hash detected",cwe:"CWE-327",description:"SHA-1 is cryptographically broken and should not be used. The crypto-hash package itself warns against using sha1().",severity:"HIGH",fix:"Use sha256() or sha512() instead",documentationLink:"https://shattered.io/"}),useSha256:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use sha256",description:"SHA-256 provides adequate security for most use cases",severity:"LOW",fix:"import { sha256 } from 'crypto-hash'; await sha256(data)",documentationLink:"https://www.npmjs.com/package/crypto-hash"}),useSha512:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use sha512",description:"SHA-512 provides stronger security with longer hash",severity:"LOW",fix:"import { sha512 } from 'crypto-hash'; await sha512(data)",documentationLink:"https://www.npmjs.com/package/crypto-hash"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow SHA1 in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},ImportDeclaration(node){if(isTestFile)return;if(node.source.value==="crypto-hash"){for(const specifier of node.specifiers){if(specifier.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier&&specifier.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&specifier.imported.name==="sha1"){context.report({node:specifier,messageId:"sha1Deprecated",suggest:[{messageId:"useSha256",fix:fixer=>{return fixer.replaceText(specifier.imported,"sha256")}},{messageId:"useSha512",fix:fixer=>{return fixer.replaceText(specifier.imported,"sha512")}}]})}}}},CallExpression(node){if(isTestFile)return;if(!(0,eslint_devkit_1.isModuleBinding)(node.callee,context.sourceCode.getScope(node),"crypto-hash",["sha1"])){return}const callee=node.callee;const target=callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.name==="sha1"?callee:callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed?callee.property:null;context.report({node,messageId:"sha1Deprecated",suggest:target===null?[]:[{messageId:"useSha256",fix:fixer=>fixer.replaceText(target,"sha256")}]})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noShellInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const constant_folding_1=require("../../utils/constant-folding");const SHELL_EXEC_FUNCTIONS=new Set(["exec","execSync"]);const SHELL_OPTION_FUNCTIONS=new Set(["spawn","spawnSync","execFile","execFileSync"]);function hasTruthyShellOption(node){for(const arg of node.arguments){if(arg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)continue;for(const prop of arg.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if((0,eslint_devkit_1.objectKeyName)(prop)!=="shell")continue;const{value}=prop;if(value.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&value.expressions.length===0){return value.quasis.some(q=>q.value.raw.length>0)}if(value.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return false;return value.value===true||typeof value.value==="string"&&value.value.length>0}}return false}function isStringConcatOrTemplate(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noShellInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const constant_folding_1=require("../../utils/constant-folding");const SHELL_EXEC_FUNCTIONS=new Set(["exec","execSync"]);const SHELL_OPTION_FUNCTIONS=new Set(["spawn","spawnSync","execFile","execFileSync"]);function hasTruthyShellOption(node){for(const arg of node.arguments){if(arg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)continue;for(const prop of arg.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if((0,eslint_devkit_1.objectKeyName)(prop)!=="shell")continue;const{value}=prop;if(value.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&value.expressions.length===0){return value.quasis.some(q=>q.value.raw.length>0)}if(value.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return false;return value.value===true||typeof value.value==="string"&&value.value.length>0}}return false}function isStringConcatOrTemplate(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return true;return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}exports.noShellInjection=(0,eslint_devkit_1.createRule)({name:"no-shell-injection",skipTestFiles:true,meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-shell-injection.md",description:"Disallow string concatenation or template expressions in shell command arguments (CWE-78)",cwe:"CWE-78",cvss:9.8},messages:{shellInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"OS Command Injection (CWE-78)",cwe:"CWE-78",description:"Shell command built via string concatenation or template literal. An attacker who controls any interpolated value can execute arbitrary OS commands.",severity:"CRITICAL",fix:"Use spawn(cmd, [arg1, arg2]) with separate arguments instead of exec(cmd + args). Never build shell commands via string interpolation.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html"})},schema:[{type:"object",properties:{requireModuleEvidence:{type:"boolean",default:true,description:"Only report when the callee resolves to child_process. Turning this off restores the pre-2026-08 behaviour, where any callee named exec/execSync/spawn was treated as a shell sink \u2014 which reported better-sqlite3 db.exec(sql) as CWE-78 at CVSS 9.8."}},additionalProperties:false}]},defaultOptions:[{requireModuleEvidence:true}],createOnce(context,currentOptions){let isLiteralConstant;let requireModuleEvidence;return{before(){const[options={}]=currentOptions();isLiteralConstant=(0,constant_folding_1.makeIsLiteralConstant)(context.sourceCode);({requireModuleEvidence=true}=options)},CallExpression(node){const callee=node.callee;const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,context.sourceCode.getScope(node));const resolved=binding?.module==="child_process"&&binding.path.length===1?binding.path[0]:null;const spelled=callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee):null;const fnName=resolved??(requireModuleEvidence?null:spelled);if(!fnName)return;const runsAShell=SHELL_EXEC_FUNCTIONS.has(fnName)||SHELL_OPTION_FUNCTIONS.has(fnName)&&hasTruthyShellOption(node);if(!runsAShell)return;const isInjectable=arg=>isStringConcatOrTemplate(arg)&&!isLiteralConstant(arg);const firstArg=node.arguments[0];if(firstArg&&isInjectable(firstArg)){context.report({node:firstArg,messageId:"shellInjection"})}if(SHELL_OPTION_FUNCTIONS.has(fnName)){const argsArray=node.arguments[1];if(argsArray?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of argsArray.elements){if(element&&isInjectable(element)){context.report({node:element,messageId:"shellInjection"})}}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSsrf=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const HTTP_CLIENT_FUNCTIONS=new Set(["fetch","got","nodeFetch","undici"]);const HTTP_CLIENT_METHODS=new Set(["get","post","put","patch","delete","head","options","request"]);const HTTP_CLIENT_MODULES=["axios","got","superagent","request","http","https","node:http","node:https","undici","needle"];const VALIDATION_FUNCTION_NAMES=new Set(["validateUrl","validateURL","isValidUrl","isSafeUrl","isAllowed","isValidURL","checkUrl","checkURL","sanitizeUrl","sanitizeURL"]);const USER_INPUT_SUBSTRINGS=["url","endpoint","uri","href","link","target","dest","source","host","user","input","param"];function isUserInputParamName(name){const lower=name.toLowerCase();return USER_INPUT_SUBSTRINGS.some(sub=>lower.includes(sub))}const REQUEST_ROOT_NAMES=new Set(["req","request","ctx","event"]);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSsrf=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const HTTP_CLIENT_FUNCTIONS=new Set(["fetch","got","nodeFetch","undici"]);const HTTP_CLIENT_METHODS=new Set(["get","post","put","patch","delete","head","options","request"]);const HTTP_CLIENT_MODULES=["axios","got","superagent","request","http","https","node:http","node:https","undici","needle"];const VALIDATION_FUNCTION_NAMES=new Set(["validateUrl","validateURL","isValidUrl","isSafeUrl","isAllowed","isValidURL","checkUrl","checkURL","sanitizeUrl","sanitizeURL"]);const USER_INPUT_SUBSTRINGS=["url","endpoint","uri","href","link","target","dest","source","host","user","input","param"];function isUserInputParamName(name){const lower=name.toLowerCase();return USER_INPUT_SUBSTRINGS.some(sub=>lower.includes(sub))}const REQUEST_ROOT_NAMES=new Set(["req","request","ctx","event"]);function isRequestSourced(node,sourceCode){if((0,eslint_devkit_1.readsRequestShape)(node,sourceCode))return true;let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){current=current.object}return current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_ROOT_NAMES.has(current.name.toLowerCase())}function makeCarriesUntrustedUrl(sourceCode,reportUnresolvedUrls){const carries=(node,depth)=>{if(depth>6)return false;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return carries(bare,depth);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=(0,provenance_1.bindingInit)(sourceCode,node);if(init!==void 0)return carries(init,depth+1);return reportUnresolvedUrls&&isUserInputParamName(node.name)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isRequestSourced(node,sourceCode)||carries(node.object,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(expression=>carries(expression,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return node.arguments.some(argument=>carries(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return carries(node.left,depth+1)||carries(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.ObjectExpression:return node.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&carries(property.value,depth+1));default:return false}};return node=>carries(node,0)}function nodeContainsValidation(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="URL"){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&VALIDATION_FUNCTION_NAMES.has(node.callee.name)){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method==="includes"||method==="has"||method==="startsWith"||method==="test"||method==="some"){return true}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&(node.operator==="==="||node.operator==="==")&&(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(node.left)==="hostname"||(0,eslint_devkit_1.propertyName)(node.left)==="host")||node.right.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(node.right)==="hostname"||(0,eslint_devkit_1.propertyName)(node.right)==="host"))){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}const SKIP_KEYS=new Set(["parent","range","loc","tokens","comments","start","end"]);for(const key of Object.keys(node)){if(SKIP_KEYS.has(key))continue;const value=node[key];if(value&&typeof value==="object"&&"type"in value){if(nodeContainsValidation(value))return true}if(Array.isArray(value)){for(const item of value){if(item&&typeof item==="object"&&"type"in item){if(nodeContainsValidation(item))return true}}}}return false}function hasValidationBefore(node){let current=node;while(current){const parent=current.parent;if(!parent)break;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const idx=body.indexOf(current);for(let i=idx-1;i>=0&&i>=idx-10;i--){if(nodeContainsValidation(body[i])){return true}}}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){if(nodeContainsValidation(parent.test)){return true}}current=parent}return false}exports.noSsrf=(0,eslint_devkit_1.createRule)({name:"no-ssrf",meta:{interop:{runtimes:["eslint","oxlint"]},type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-ssrf.md",description:"Flags HTTP calls whose URL argument is a user-input-named identifier or reads off a request object \u2014 a heuristic prompt for code review, not a proof of SSRF",cwe:"CWE-918",cvss:9.1},messages:{ssrfVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Possible SSRF \u2014 heuristic (CWE-918)",cwe:"CWE-918",description:"HTTP call whose URL argument name suggests user input. This is a naming heuristic, not data-flow analysis \u2014 review whether the URL could originate from an untrusted source at runtime.",severity:"LOW",fix:"If the URL comes from user input, validate it against an allowlist of permitted hosts before making the request.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},reportUnresolvedUrls:{type:"boolean",default:false,description:"Report a URL argument that is a user-input-named identifier with no traceable request source. Restores the pre-inversion naming heuristic."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],createOnce(context,currentOptions){let carriesUntrustedUrl;return{before(){const[options={}]=currentOptions();const{allowInTests=true,reportUnresolvedUrls=false}=options||{};carriesUntrustedUrl=makeCarriesUntrustedUrl(context.sourceCode,reportUnresolvedUrls);const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile)return false;return true},CallExpression(node){let isHttpCall=false;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HTTP_CLIENT_FUNCTIONS.has(node.callee.name)){isHttpCall=true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),HTTP_CLIENT_METHODS)&&HTTP_CLIENT_MODULES.some(mod=>(0,eslint_devkit_1.isModuleBinding)(node.callee.object,context.sourceCode.getScope(node),mod))){isHttpCall=true}if(!isHttpCall)return;const urlArg=node.arguments[0];if(!urlArg)return;if(hasValidationBefore(node)){return}if(!carriesUntrustedUrl(urlArg)){return}context.report({node,messageId:"ssrfVulnerability"})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noStaticIv=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
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noStaticIv=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 CIPHERIV_FACTORIES=["createCipheriv","createDecipheriv"];const TYPED_ARRAY_CONSTRUCTORS=new Set(["Uint8Array","Uint8ClampedArray","Int8Array"]);const RANDOM_FILL_FUNCTIONS=new Set(["randomFill","randomFillSync","getRandomValues"]);function calleeMemberName(callee){return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee):null}exports.noStaticIv=(0,eslint_devkit_1.createRule)({name:"no-static-iv",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-static-iv.md",description:"Disallow static or hardcoded initialization vectors (IVs)",cwe:"CWE-329",cvss:7.5},hasSuggestions:false,messages:{staticIv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Static IV detected",cwe:"CWE-329",description:"Hardcoded IV detected. Using static IVs makes encryption deterministic, allowing attackers to detect repeated plaintexts.",severity:"HIGH",fix:"Generate IV dynamically using crypto.randomBytes(16)",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#initialization-vectors"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow static IVs in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function isCipherivCall(node){const callee=node.callee;const spelled=calleeMemberName(callee)??(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:null);if(spelled!==null&&CIPHERIV_FACTORIES.includes(spelled))return true;const scope=context.sourceCode.getScope(node);return CIPHERIV_FACTORIES.some(fn=>(0,eslint_devkit_1.isModuleBinding)(callee,scope,"crypto",[fn]))}function checkCallExpression(node){if(isTestFile)return;if(isCipherivCall(node)&&node.arguments.length>=3){const ivArg=node.arguments[2];checkIvArgument(ivArg)}}function isStaticByteArray(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&node.elements.every(el=>el?.type===eslint_devkit_1.AST_NODE_TYPES.Literal)}function isRandomlyFilled(variable){return variable.references.some(ref=>{const parent=ref.identifier.parent;if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(!parent.arguments.includes(ref.identifier))return false;const callee=parent.callee;const name=calleeMemberName(callee)??(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:null);return name!==null&&RANDOM_FILL_FUNCTIONS.has(name)})}function isStaticIvValue(value,binding){const constant=(0,const_value_1.resolveConstantString)(context.sourceCode,value);if(constant!==null)return constant.value.length>0;if(value.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){return value.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TYPED_ARRAY_CONSTRUCTORS.has(value.callee.name)&&isStaticBufferSource(value.arguments[0],binding)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&value.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&value.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&value.callee.object.name==="Buffer"&&(calleeMemberName(value.callee)==="from"||calleeMemberName(value.callee)==="alloc")){return isStaticBufferSource(value.arguments[0],binding)}return false}function isStaticBufferSource(source,binding){if(source===void 0)return false;if((0,const_value_1.resolveConstantString)(context.sourceCode,source)!==null)return true;if(isStaticByteArray(source))return true;if((0,const_value_1.resolveConstant)(context.sourceCode,source)===null)return false;return binding===null||!isRandomlyFilled(binding)}function ivCandidates(identifier,variable){const constInit=(0,const_value_1.constInitializerOf)(context.sourceCode,identifier);if(constInit!==null)return[constInit];if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable")return null;if(def.node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const candidates=[];for(const ref of variable.references){if(!ref.isWrite())continue;if(!ref.writeExpr)return null;candidates.push(ref.writeExpr)}return candidates.length>0?candidates:null}function checkIvArgument(ivArg){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(ivArg);if(unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const binding=(0,provenance_1.findVariable)(context.sourceCode,unwrapped);if(binding===null)return;const candidates=ivCandidates(unwrapped,binding);if(candidates===null)return;if(candidates.every(c=>isStaticIvValue((0,eslint_devkit_1.unwrapTypeSyntax)(c),binding))){reportStaticIv(unwrapped)}return}if(isStaticIvValue(unwrapped,null))reportStaticIv(unwrapped)}function reportStaticIv(node){context.report({node,messageId:"staticIv"})}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTimingUnsafeCompare=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const names_1=require("../../utils/names");const DEFAULT_SECRET_PATTERNS=["token","secret","password","hash","signature","mac","hmac","digest","apiKey","api_key","api-key","auth","credential","bearer","jwt","csrf","nonce","ssn","social_security","social-security","pii","private_key","private-key","privateKey","access_token","access-token","accessToken","refresh_token","refresh-token","refreshToken","session_id","session-id","sessionId","auth_token","auth-token","authToken","encryption_key","encryption-key","encryptionKey"];function isSourceConstant(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name==="undefined")return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return node.expressions.length===0;return false}function isStringLiteral(node){return(0,eslint_devkit_1.staticString)(node)!==null}const BOOLEAN_PREDICATE_NAME=/^(?:is|has|should|can|did|was|will|does)[A-Z]/;const NAMED_CONSTANT=/^[A-Z][A-Z0-9_]*$/;const DEFAULT_UNTRUSTED_SOURCES=["req","request","ctx","event"];const NAMESPACE_NAME=/^(?:[A-Z][A-Z0-9_]*|[A-Z][a-zA-Z0-9]*)$/;function isNamedConstant(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const constant=(0,eslint_devkit_1.propertyName)(node);if(constant===null)return false;return NAMESPACE_NAME.test(node.object.name)&&NAMED_CONSTANT.test(constant)}function memberRoot(node){let current=node;for(;;){if(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){current=current.object;continue}if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){current=current.callee;continue}break}return current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?current:null}function isSelfComparison(left,right){const pair=(bare,derived)=>{if(bare.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(derived.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return memberRoot(derived)?.name===bare.name};return pair(left,right)||pair(right,left)}const NON_SECRET_MEMBERS=new Map([["hash",new Set(["location"])]]);const DEFAULT_NON_SECRET_WORDS=["author","authors","authored","authoring","authorship","hashtag","hashtags"];const DEFAULT_NON_SECRET_TAILS=["count","counts","limit","limits","usage","total","size","length","price","cost","quota","address","addresses","index","rank","percent","path","paths","pathname","pathnames","endpoint","endpoints","route","routes","hostname","host","port","origin","kind","kinds","type","types","flag","flags","category"];const CRYPTO_DERIVATIONS=new Set(["createHmac","createHash","createSign","pbkdf2Sync","scryptSync","hkdfSync","digest","sign","hmac"]);const RECEIVER_COMPARE_METHODS=new Set(["equals","startsWith","endsWith","localeCompare"]);const BINARY_EQUALITY_FUNCTIONS=new Set(["isEqual","isEqualWith","deepEqual","fastDeepEqual","shallowEqual"]);const SERVER_STATE_REQUEST_PROPERTIES=new Set(["session","user","locals","app","state"]);function unwrapChain(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?node.expression:node}function memberPropertyName(node){const{property}=node;return property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier?property.name:(0,eslint_devkit_1.propertyName)(node)}function isNonSecretMember(node){const member=memberPropertyName(node);if(member===null)return false;const receivers=NON_SECRET_MEMBERS.get(member.toLowerCase());if(!receivers)return false;const owner=node.object;const ownerName=owner.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?owner.name:owner.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(owner)??"":"";return receivers.has(ownerName.toLowerCase())}exports.noTimingUnsafeCompare=(0,eslint_devkit_1.createRule)({name:"no-timing-unsafe-compare",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-timing-unsafe-compare.md",description:"Disallow timing-unsafe comparison of secrets",cwe:"CWE-208",cvss:5.9},messages:{timingUnsafeCompare:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Timing-unsafe comparison",cwe:"CWE-208",description:"Using === to compare secrets enables timing attacks. The comparison short-circuits on first mismatch, leaking information about the secret.",severity:"HIGH",fix:"Use crypto.timingSafeEqual() for constant-time comparison",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"})},schema:[{type:"object",properties:{secretPatterns:{type:"array",items:{type:"string"},default:DEFAULT_SECRET_PATTERNS,description:"Variable name patterns that indicate secrets"},untrustedSources:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_SOURCES,description:"Identifier roots treated as attacker-controlled (default: req, request, ctx, event)"},reportUnverifiedComparisons:{type:"boolean",default:false,description:"Report on a secret-looking name alone, without an attacker-controlled operand. Restores the pre-inversion behaviour."},reportLiteralComparands:{type:"boolean",default:false,description:"Report a secret-named value compared against a string literal (password === 'mypass'), in either order, on the name alone. Off by default because string comparands are usually tags (revokedToken === 'access')."},nonSecretWords:{type:"array",items:{type:"string"},default:[...DEFAULT_NON_SECRET_WORDS],description:`Whole words that mean a secretPatterns match was a collision (default: ${DEFAULT_NON_SECRET_WORDS.join(", ")}). Replaces the list.`},nonSecretTails:{type:"array",items:{type:"string"},default:[...DEFAULT_NON_SECRET_TAILS],description:`Trailing words that make the value a measurement or location rather than a credential (default: ${DEFAULT_NON_SECRET_TAILS.join(", ")}). Replaces the list.`}},additionalProperties:false}]},defaultOptions:[{secretPatterns:DEFAULT_SECRET_PATTERNS,nonSecretWords:[...DEFAULT_NON_SECRET_WORDS],nonSecretTails:[...DEFAULT_NON_SECRET_TAILS]}],createOnce(context,currentOptions){let secretPatterns;let untrustedSources;let reportUnverifiedComparisons;let reportLiteralComparands;let nonSecretWords;let nonSecretTails;let nonSecretWordSet;let nonSecretTailSet;let sourceCode;let readsUntrusted;let patterns;function nameLooksSecret(name){if(BOOLEAN_PREDICATE_NAME.test(name))return false;const words=(0,names_1.identifierWords)(name);if(words.some(word=>nonSecretWordSet.has(word)))return false;if(words.length>0&&nonSecretTailSet.has(words[words.length-1])){return false}return patterns.some(p=>p.test(name))}function isCryptoDerivation(node){const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return isCryptoDerivation(bare);if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return CRYPTO_DERIVATIONS.has(callee.name)}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed)return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(CRYPTO_DERIVATIONS.has(callee.property.name))return true;return isCryptoDerivation(callee.object)}function isCryptoSecret(node){if(isCryptoDerivation(node))return true;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const init=(0,provenance_1.bindingInit)(sourceCode,bare);return init!==void 0&&containsCryptoDerivation(init)}function containsCryptoDerivation(node){if(isCryptoDerivation(node))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.some(expression=>containsCryptoDerivation(expression))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return containsCryptoDerivation(node.left)||containsCryptoDerivation(node.right)}return false}function isServerDerived(node,depth=0){if(depth>4)return false;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return isServerDerived(bare,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression)return true;if(containsCryptoDerivation(node))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const propertyName=memberPropertyName(node);if(propertyName!==null&&SERVER_STATE_REQUEST_PROPERTIES.has(propertyName)){return true}return isServerDerived(node.object,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,provenance_1.bindingInit)(sourceCode,node);return init!==void 0&&isServerDerived(init,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=unwrapChain(node.callee);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;return!readsUntrusted(callee.object)||isServerDerived(callee.object,depth+1)}return false}function isSecretIdentifier(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameLooksSecret(node.name)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(isNonSecretMember(node))return false;const propertyName=memberPropertyName(node);if(propertyName!==null){return nameLooksSecret(propertyName)}}return false}function isResolvedConstant(node){if(isSourceConstant(node))return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return(0,provenance_1.constLiteralOf)(sourceCode,node)!==void 0}function resolveLocalFunction(callee){const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(!variable||variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type==="FunctionName")return def.node;if(def.type!=="Variable")return null;const init=def.node.init;if(!init)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(init);if(bare.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||bare.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return bare}return null}function comparesLengths(node){const isLength=operand=>operand.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&memberPropertyName(operand)==="length";return isLength(node.left)||isLength(node.right)}function equalityWrapperParams(callee){const fn=resolveLocalFunction(callee);if(!fn||fn.params.length<2)return null;const paramIndex=new Map;fn.params.forEach((param,index)=>{if(param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)paramIndex.set(param.name,index)});let found=null;const visit=node=>{if(found||!node||typeof node.type!=="string")return;if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const isEquality=node.operator==="==="||node.operator==="!=="||node.operator==="=="||node.operator==="!=";if(isEquality&&!comparesLengths(node)){const leftIndex=paramIndex.get(memberRoot(node.left)?.name??"");const rightIndex=paramIndex.get(memberRoot(node.right)?.name??"");if(leftIndex!==void 0&&rightIndex!==void 0&&leftIndex!==rightIndex){found=[leftIndex,rightIndex];return}}}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;if(Array.isArray(value)){for(const entry of value)visit(entry)}else if(value&&typeof value==="object"&&"type"in value){visit(value)}}};visit(fn.body);return found}function comparisonOperands(node){const args=node.arguments;if(args.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)){return null}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(BINARY_EQUALITY_FUNCTIONS.has(callee.name)&&args.length===2){return[args[0],args[1]]}const wrapped=equalityWrapperParams(callee);if(!wrapped)return null;const[leftIndex,rightIndex]=wrapped;const leftArg=args[leftIndex];const rightArg=args[rightIndex];if(!leftArg||!rightArg)return null;return[leftArg,rightArg]}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return null;if(method==="compare"&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Buffer"&&args.length===2){return[args[0],args[1]]}if(BINARY_EQUALITY_FUNCTIONS.has(method)&&args.length===2){return[args[0],args[1]]}if(RECEIVER_COMPARE_METHODS.has(method)&&args.length===1){return[callee.object,args[0]]}return null}function checkComparison(node,rawLeft,rawRight){const left=unwrapChain(rawLeft);const right=unwrapChain(rawRight);if(reportLiteralComparands){const literalLeft=isStringLiteral(left);if(literalLeft!==isStringLiteral(right)){if(isSecretIdentifier(literalLeft?right:left)){context.report({node,messageId:"timingUnsafeCompare"});return}}}if(isResolvedConstant(left)||isResolvedConstant(right)){return}if(isNamedConstant(left)||isNamedConstant(right)){return}if(isSelfComparison(left,right)){return}const leftIsSecret=isSecretIdentifier(left)||isCryptoSecret(left);const rightIsSecret=isSecretIdentifier(right)||isCryptoSecret(right);if(leftIsSecret||rightIsSecret){if(!reportUnverifiedComparisons){const leftUntrusted=readsUntrusted(left);const rightUntrusted=readsUntrusted(right);if(leftUntrusted===rightUntrusted){if(!leftUntrusted)return;if(!isServerDerived(left)&&!isServerDerived(right))return}}context.report({node,messageId:"timingUnsafeCompare"})}}function checkBinaryExpression(node){if(node.operator!=="==="&&node.operator!=="=="&&node.operator!=="!=="&&node.operator!=="!="){return}checkComparison(node,node.left,node.right)}function checkCallExpression(node){const operands=comparisonOperands(node);if(!operands)return;checkComparison(node,operands[0],operands[1])}return{before(){const[options={}]=currentOptions();({secretPatterns=DEFAULT_SECRET_PATTERNS,untrustedSources=DEFAULT_UNTRUSTED_SOURCES,reportUnverifiedComparisons=false,reportLiteralComparands=false,nonSecretWords=[...DEFAULT_NON_SECRET_WORDS],nonSecretTails=[...DEFAULT_NON_SECRET_TAILS]}=options);nonSecretWordSet=new Set(nonSecretWords.map(word=>word.toLowerCase()));nonSecretTailSet=new Set(nonSecretTails.map(word=>word.toLowerCase()));sourceCode=context.sourceCode;readsUntrusted=(0,provenance_1.makeReadsTaintSource)(sourceCode,new Set(untrustedSources.map(source=>source.toLowerCase())));patterns=(0,eslint_devkit_1.compileUserPatterns)(secretPatterns,"i")},BinaryExpression:checkBinaryExpression,CallExpression:checkCallExpression}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTimingUnsafeCompare=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const names_1=require("../../utils/names");const DEFAULT_SECRET_PATTERNS=["token","secret","password","hash","signature","mac","hmac","digest","apiKey","api_key","api-key","auth","credential","bearer","jwt","csrf","nonce","ssn","social_security","social-security","pii","private_key","private-key","privateKey","access_token","access-token","accessToken","refresh_token","refresh-token","refreshToken","session_id","session-id","sessionId","auth_token","auth-token","authToken","encryption_key","encryption-key","encryptionKey"];function isSourceConstant(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name==="undefined")return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return node.expressions.length===0;return false}function isStringLiteral(node){return(0,eslint_devkit_1.staticString)(node)!==null}const BOOLEAN_PREDICATE_NAME=/^(?:is|has|should|can|did|was|will|does)[A-Z]/;const NAMED_CONSTANT=/^[A-Z][A-Z0-9_]*$/;const DEFAULT_UNTRUSTED_SOURCES=["req","request","ctx","event"];const NAMESPACE_NAME=/^(?:[A-Z][A-Z0-9_]*|[A-Z][a-zA-Z0-9]*)$/;function isNamedConstant(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const constant=(0,eslint_devkit_1.propertyName)(node);if(constant===null)return false;return NAMESPACE_NAME.test(node.object.name)&&NAMED_CONSTANT.test(constant)}function memberRoot(node){let current=node;for(;;){if(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){current=current.object;continue}if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){current=current.callee;continue}break}return current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?current:null}function isSelfComparison(left,right){const pair=(bare,derived)=>{if(bare.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return memberRoot(derived)?.name===bare.name};return pair(left,right)||pair(right,left)}const NON_SECRET_MEMBERS=new Map([["hash",new Set(["location"])]]);const DEFAULT_NON_SECRET_WORDS=["author","authors","authored","authoring","authorship","hashtag","hashtags"];const DEFAULT_NON_SECRET_TAILS=["count","counts","limit","limits","usage","total","size","length","price","cost","quota","address","addresses","index","rank","percent","path","paths","pathname","pathnames","endpoint","endpoints","route","routes","hostname","host","port","origin","kind","kinds","type","types","flag","flags","category"];const CRYPTO_DERIVATIONS=new Set(["createHmac","createHash","createSign","pbkdf2Sync","scryptSync","hkdfSync","digest","sign","hmac"]);const RECEIVER_COMPARE_METHODS=new Set(["equals","startsWith","endsWith","localeCompare"]);const BINARY_EQUALITY_FUNCTIONS=new Set(["isEqual","isEqualWith","deepEqual","fastDeepEqual","shallowEqual"]);const SERVER_STATE_REQUEST_PROPERTIES=new Set(["session","user","locals","app","state"]);function unwrapChain(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?node.expression:node}function memberPropertyName(node){const{property}=node;return property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier?property.name:(0,eslint_devkit_1.propertyName)(node)}function isNonSecretMember(node){const member=memberPropertyName(node);if(member===null)return false;const receivers=NON_SECRET_MEMBERS.get(member.toLowerCase());if(!receivers)return false;const owner=node.object;const ownerName=owner.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?owner.name:owner.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(owner)??"":"";return receivers.has(ownerName.toLowerCase())}exports.noTimingUnsafeCompare=(0,eslint_devkit_1.createRule)({name:"no-timing-unsafe-compare",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-timing-unsafe-compare.md",description:"Disallow timing-unsafe comparison of secrets",cwe:"CWE-208",cvss:5.9},messages:{timingUnsafeCompare:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Timing-unsafe comparison",cwe:"CWE-208",description:"Using === to compare secrets enables timing attacks. The comparison short-circuits on first mismatch, leaking information about the secret.",severity:"HIGH",fix:"Use crypto.timingSafeEqual() for constant-time comparison",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"})},schema:[{type:"object",properties:{secretPatterns:{type:"array",items:{type:"string"},default:DEFAULT_SECRET_PATTERNS,description:"Variable name patterns that indicate secrets"},untrustedSources:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_SOURCES,description:"Identifier roots treated as attacker-controlled (default: req, request, ctx, event)"},reportUnverifiedComparisons:{type:"boolean",default:false,description:"Report on a secret-looking name alone, without an attacker-controlled operand. Restores the pre-inversion behaviour."},reportLiteralComparands:{type:"boolean",default:false,description:"Report a secret-named value compared against a string literal (password === 'mypass'), in either order, on the name alone. Off by default because string comparands are usually tags (revokedToken === 'access')."},nonSecretWords:{type:"array",items:{type:"string"},default:[...DEFAULT_NON_SECRET_WORDS],description:`Whole words that mean a secretPatterns match was a collision (default: ${DEFAULT_NON_SECRET_WORDS.join(", ")}). Replaces the list.`},nonSecretTails:{type:"array",items:{type:"string"},default:[...DEFAULT_NON_SECRET_TAILS],description:`Trailing words that make the value a measurement or location rather than a credential (default: ${DEFAULT_NON_SECRET_TAILS.join(", ")}). Replaces the list.`}},additionalProperties:false}]},defaultOptions:[{secretPatterns:DEFAULT_SECRET_PATTERNS,nonSecretWords:[...DEFAULT_NON_SECRET_WORDS],nonSecretTails:[...DEFAULT_NON_SECRET_TAILS]}],createOnce(context,currentOptions){let secretPatterns;let untrustedSources;let reportUnverifiedComparisons;let reportLiteralComparands;let nonSecretWords;let nonSecretTails;let nonSecretWordSet;let nonSecretTailSet;let sourceCode;let readsUntrusted;let patterns;function nameLooksSecret(name){if(BOOLEAN_PREDICATE_NAME.test(name))return false;const words=(0,names_1.identifierWords)(name);if(words.some(word=>nonSecretWordSet.has(word)))return false;if(words.length>0&&nonSecretTailSet.has(words[words.length-1])){return false}return patterns.some(p=>p.test(name))}function isCryptoDerivation(node){const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return isCryptoDerivation(bare);if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return CRYPTO_DERIVATIONS.has(callee.name)}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed)return false;if(CRYPTO_DERIVATIONS.has(callee.property.name))return true;return isCryptoDerivation(callee.object)}function isCryptoSecret(node){if(isCryptoDerivation(node))return true;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const init=(0,provenance_1.bindingInit)(sourceCode,bare);return init!==void 0&&containsCryptoDerivation(init)}function containsCryptoDerivation(node){if(isCryptoDerivation(node))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.some(expression=>containsCryptoDerivation(expression))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return containsCryptoDerivation(node.left)||containsCryptoDerivation(node.right)}return false}function isServerDerived(node,visited=new Set){if(visited.has(node))return false;visited.add(node);const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return isServerDerived(bare,visited);if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression)return true;if(containsCryptoDerivation(node))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const propertyName=memberPropertyName(node);if(propertyName!==null&&SERVER_STATE_REQUEST_PROPERTIES.has(propertyName)){return true}return isServerDerived(node.object,visited)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,provenance_1.bindingInit)(sourceCode,node);return init!==void 0&&isServerDerived(init,visited)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=unwrapChain(node.callee);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;return!readsUntrusted(callee.object)||isServerDerived(callee.object,visited)}return false}function isSecretIdentifier(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameLooksSecret(node.name)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(isNonSecretMember(node))return false;const propertyName=memberPropertyName(node);if(propertyName!==null){return nameLooksSecret(propertyName)}}return false}function isResolvedConstant(node){if(isSourceConstant(node))return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return(0,provenance_1.constLiteralOf)(sourceCode,node)!==void 0}function resolveLocalFunction(callee){const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(!variable||variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type==="FunctionName")return def.node;if(def.type!=="Variable")return null;const init=def.node.init;if(!init)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(init);if(bare.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||bare.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return bare}return null}function comparesLengths(node){const isLength=operand=>operand.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&memberPropertyName(operand)==="length";return isLength(node.left)||isLength(node.right)}function equalityWrapperParams(callee){const fn=resolveLocalFunction(callee);if(!fn||fn.params.length<2)return null;const paramIndex=new Map;fn.params.forEach((param,index)=>{if(param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)paramIndex.set(param.name,index)});let found=null;const visit=node=>{if(found||!node||typeof node.type!=="string")return;if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const isEquality=node.operator==="==="||node.operator==="!=="||node.operator==="=="||node.operator==="!=";if(isEquality&&!comparesLengths(node)){const leftIndex=paramIndex.get(memberRoot(node.left)?.name??"");const rightIndex=paramIndex.get(memberRoot(node.right)?.name??"");if(leftIndex!==void 0&&rightIndex!==void 0&&leftIndex!==rightIndex){found=[leftIndex,rightIndex];return}}}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;if(Array.isArray(value)){for(const entry of value)visit(entry)}else if(value&&typeof value==="object"&&"type"in value){visit(value)}}};visit(fn.body);return found}function comparisonOperands(node){const args=node.arguments;if(args.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)){return null}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(BINARY_EQUALITY_FUNCTIONS.has(callee.name)&&args.length>=2){return[args[0],args[1]]}const wrapped=equalityWrapperParams(callee);if(!wrapped)return null;const[leftIndex,rightIndex]=wrapped;const leftArg=args[leftIndex];const rightArg=args[rightIndex];if(!leftArg||!rightArg)return null;return[leftArg,rightArg]}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return null;if(method==="compare"&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Buffer"&&args.length===2){return[args[0],args[1]]}if(BINARY_EQUALITY_FUNCTIONS.has(method)&&args.length>=2){return[args[0],args[1]]}if(RECEIVER_COMPARE_METHODS.has(method)&&args.length===1){return[callee.object,args[0]]}return null}function checkComparison(node,rawLeft,rawRight){const left=unwrapChain(rawLeft);const right=unwrapChain(rawRight);if(reportLiteralComparands){const literalLeft=isStringLiteral(left);if(literalLeft!==isStringLiteral(right)){if(isSecretIdentifier(literalLeft?right:left)){context.report({node,messageId:"timingUnsafeCompare"});return}}}if(isResolvedConstant(left)||isResolvedConstant(right)){return}if(isNamedConstant(left)||isNamedConstant(right)){return}if(isSelfComparison(left,right)){return}const leftIsSecret=isSecretIdentifier(left)||isCryptoSecret(left);const rightIsSecret=isSecretIdentifier(right)||isCryptoSecret(right);if(leftIsSecret||rightIsSecret){if(!reportUnverifiedComparisons){const leftUntrusted=readsUntrusted(left);const rightUntrusted=readsUntrusted(right);if(leftUntrusted===rightUntrusted){if(!leftUntrusted)return;if(!isServerDerived(left)&&!isServerDerived(right))return}}context.report({node,messageId:"timingUnsafeCompare"})}}function checkBinaryExpression(node){if(node.operator!=="==="&&node.operator!=="=="&&node.operator!=="!=="&&node.operator!=="!="){return}checkComparison(node,node.left,node.right)}function checkCallExpression(node){const operands=comparisonOperands(node);if(!operands)return;checkComparison(node,operands[0],operands[1])}return{before(){const[options={}]=currentOptions();({secretPatterns=DEFAULT_SECRET_PATTERNS,untrustedSources=DEFAULT_UNTRUSTED_SOURCES,reportUnverifiedComparisons=false,reportLiteralComparands=false,nonSecretWords=[...DEFAULT_NON_SECRET_WORDS],nonSecretTails=[...DEFAULT_NON_SECRET_TAILS]}=options);nonSecretWordSet=new Set(nonSecretWords.map(word=>word.toLowerCase()));nonSecretTailSet=new Set(nonSecretTails.map(word=>word.toLowerCase()));sourceCode=context.sourceCode;readsUntrusted=(0,provenance_1.makeReadsTaintSource)(sourceCode,new Set(untrustedSources.map(source=>source.toLowerCase())));patterns=(0,eslint_devkit_1.compileUserPatterns)(secretPatterns,"i")},BinaryExpression:checkBinaryExpression,CallExpression:checkCallExpression}}});
|