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.noToctouVulnerability=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const PER_USER_ROOT_FUNCTIONS=new Set(["homedir","userInfo"]);const PER_USER_ENV_VARS=new Set(["HOME","USERPROFILE","LOCALAPPDATA","APPDATA","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME"]);const DEFAULT_FS_METHODS=["fs.existsSync","fs.statSync","fs.accessSync","fs.exists","fs.stat","fs.access"];const MKDIR_METHODS=new Set(["mkdir","mkdirSync"]);const RISKY_USE_METHODS=new Set(["readFileSync","readFile","openSync","open","createReadStream","writeFileSync","writeFile","appendFileSync","appendFile","createWriteStream","unlinkSync","unlink","rmSync","rm","rmdirSync","rmdir","mkdirSync","mkdir","renameSync","rename","copyFileSync","copyFile","truncateSync","truncate","chmodSync","chmod","chownSync","chown","symlinkSync","symlink","linkSync","link"]);function memberName(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;if(callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!callee.computed){return callee.property.name}return callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof callee.property.value==="string"?callee.property.value:null}exports.noToctouVulnerability=(0,eslint_devkit_2.createRule)({name:"no-toctou-vulnerability",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-toctou-vulnerability.md",description:"Detects Time-of-Check-Time-of-Use vulnerabilities",cwe:"CWE-367",cvss:7},messages:{toctouVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"TOCTOU vulnerability",cwe:"CWE-367",description:"Time-of-check Time-of-use race condition detected",severity:"HIGH",fix:"Act on the result and handle the failure \u2014 open/unlink and catch ENOENT \u2014 instead of checking first. Not a finding if the path is inside a directory only this user can write",documentationLink:"https://cwe.mitre.org/data/definitions/367.html"})},schema:[{type:"object",properties:{ignoreInTests:{type:"boolean",default:true},fsMethods:{type:"array",items:{type:"string"},default:DEFAULT_FS_METHODS,description:"Filesystem check calls that create a time-of-check window. Replaces the built-in list. Only the final dotted segment is compared, so `fs.existsSync` and `existsSync` are the same entry."}},additionalProperties:false}]},defaultOptions:[{ignoreInTests:true,fsMethods:DEFAULT_FS_METHODS}],createOnce(context,currentOptions){let checkMethods;let sourceCode;let EXISTENCE_CHECKS;let READ_ONLY_USES;function returnedExpression(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;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 null;const body=def.node.body;if(body?.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return null;for(const statement of body.body){if(statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement&&statement.argument){return statement.argument}}return null}function reachesPerUserRoot(node,depth=0){if(depth>8)return false;const next=child=>reachesPerUserRoot(child,depth+1);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const variable=(0,provenance_1.findVariable)(sourceCode,node);const def=variable?.defs.length===1?variable.defs[0]:void 0;if(def?.type!=="Variable"||!def.node.init)return false;return next(def.node.init)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PER_USER_ENV_VARS)){return true}return next(node.object)}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;const name=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;if(name!==null&&PER_USER_ROOT_FUNCTIONS.has(name))return true;if(node.arguments.some(argument=>next(argument)))return true;const returned=returnedExpression(callee);return returned!==null&&next(returned)}case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return next(node.consequent)||next(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return next(node.left)||next(node.right);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(expression=>next(expression));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return next(node.left)||next(node.right);default:return false}}function isSecurityRelevantWindow(checkMethod,useMethod){if(!EXISTENCE_CHECKS.has(checkMethod))return true;return!READ_ONLY_USES.has(useMethod)}function resolvesToNonFsLocal(callee,at){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=sourceCode.getScope(at);if((0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs")||(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs/promises")){return false}const variable=(0,provenance_1.findVariable)(sourceCode,callee);return!!variable&&variable.defs.length>0}function usedMethodName(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return resolvesToNonFsLocal(callee,node)?"":callee.name}const name=memberName(callee);if(name===null)return"";const objectName=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.object.name:"";if(objectName==="fs"||objectName==="fsPromises")return name;const scope=sourceCode.getScope(node);return(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs")||(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs/promises")?name:""}function collectConditionCalls(node,out,depth=0){if(depth>8)return;const inner=(0,eslint_devkit_1.unwrapTypeSyntax)(node);switch(inner.type){case eslint_devkit_1.AST_NODE_TYPES.CallExpression:out.push(inner);return;case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:collectConditionCalls(inner.argument,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:collectConditionCalls(inner.left,out,depth+1);collectConditionCalls(inner.right,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:collectConditionCalls(inner.test,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.ChainExpression:collectConditionCalls(inner.expression,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:collectConditionCalls(inner.object,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=(0,const_value_1.constInitializerOf)(sourceCode,inner);if(init!==null)collectConditionCalls(init,out,depth+1);return}default:return}}function sameTarget(checkArg,useArg){const check=(0,eslint_devkit_1.unwrapTypeSyntax)(checkArg);const use=(0,eslint_devkit_1.unwrapTypeSyntax)(useArg);if(check.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&use.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return check.name===use.name}return sourceCode.getText(check).replace(/\s/g,"")===sourceCode.getText(use).replace(/\s/g,"")}function hasRecursiveOption(node){return node.arguments.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&argument.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)==="recursive"&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value.value===true))}function checkCallExpression(node){const useMethodName=usedMethodName(node);if(!RISKY_USE_METHODS.has(useMethodName)){return}if(MKDIR_METHODS.has(useMethodName)&&hasRecursiveOption(node)){return}const rawUseArg=node.arguments[0];if(!rawUseArg)return;const useArg=(0,eslint_devkit_1.unwrapTypeSyntax)(rawUseArg);if(reachesPerUserRoot(useArg))return;let current=node.parent;while(current){if(current.type==="IfStatement"){const conditionCalls=[];collectConditionCalls(current.test,conditionCalls);for(const condition of conditionCalls){const checkMethodName=resolvesToNonFsLocal(condition.callee,condition)?"":memberName(condition.callee)??(condition.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?condition.callee.name:"");if(checkMethods.has(checkMethodName)&&isSecurityRelevantWindow(checkMethodName,useMethodName)){const checkArg=condition.arguments[0];if(checkArg&&sameTarget(checkArg,useArg)){reportToctou(node);return}}if(condition.callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(condition.callee),["isFile","isDirectory"])&&condition.callee.object.type==="Identifier"){const statsVarName=condition.callee.object.name;let currentScope=sourceCode.getScope(condition);let variable=null;while(currentScope){variable=currentScope.variables.find(v=>v.name===statsVarName)||null;if(variable)break;currentScope=currentScope.upper}if(variable&&variable.defs.length>0){const def=variable.defs[0];const declared=def.type==="Variable"&&def.node.init?(0,eslint_devkit_1.unwrapTypeSyntax)(def.node.init):null;const init=declared?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?(0,eslint_devkit_1.unwrapTypeSyntax)(declared.argument):declared;if(init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const statMethod=memberName(init.callee)??(init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?init.callee.name:"");if(["statSync","lstatSync","stat","lstat"].includes(statMethod)){const statArg=init.arguments[0];if(statArg&&sameTarget(statArg,useArg)){reportToctou(node);return}}}}}}}current=current.parent}}function reportToctou(node){context.report({node,messageId:"toctouVulnerability"})}return{before(){const[options={}]=currentOptions();const{ignoreInTests=true,fsMethods=DEFAULT_FS_METHODS}=options||{};checkMethods=new Set(fsMethods.map(entry=>entry.split(".").at(-1)));const filename=context.filename;const isTestFile=ignoreInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return false}sourceCode=context.sourceCode;EXISTENCE_CHECKS=new Set(["existsSync","exists"]);READ_ONLY_USES=new Set(["readFileSync","readFile"]);return true},CallExpression:checkCallExpression}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noToctouVulnerability=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const PER_USER_ROOT_FUNCTIONS=new Set(["homedir","userInfo"]);const PER_USER_ENV_VARS=new Set(["HOME","USERPROFILE","LOCALAPPDATA","APPDATA","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME"]);const ACCESS_CHECKS=new Set(["access","accessSync"]);const DEFAULT_FS_METHODS=["fs.existsSync","fs.statSync","fs.accessSync","fs.exists","fs.stat","fs.access"];const MKDIR_METHODS=new Set(["mkdir","mkdirSync"]);const RISKY_USE_METHODS=new Set(["readFileSync","readFile","openSync","open","createReadStream","writeFileSync","writeFile","appendFileSync","appendFile","createWriteStream","unlinkSync","unlink","rmSync","rm","rmdirSync","rmdir","mkdirSync","mkdir","renameSync","rename","copyFileSync","copyFile","truncateSync","truncate","chmodSync","chmod","chownSync","chown","symlinkSync","symlink","linkSync","link"]);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(0,eslint_devkit_1.propertyName)(callee)??""}return""}exports.noToctouVulnerability=(0,eslint_devkit_2.createRule)({name:"no-toctou-vulnerability",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-toctou-vulnerability.md",description:"Detects Time-of-Check-Time-of-Use vulnerabilities",cwe:"CWE-367",cvss:7},messages:{toctouVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"TOCTOU vulnerability",cwe:"CWE-367",description:"Time-of-check Time-of-use race condition detected",severity:"HIGH",fix:"Act on the result and handle the failure \u2014 open/unlink and catch ENOENT \u2014 instead of checking first. Not a finding if the path is inside a directory only this user can write",documentationLink:"https://cwe.mitre.org/data/definitions/367.html"})},schema:[{type:"object",properties:{ignoreInTests:{type:"boolean",default:true},fsMethods:{type:"array",items:{type:"string"},default:DEFAULT_FS_METHODS,description:"Filesystem check calls that create a time-of-check window. Replaces the built-in list. Only the final dotted segment is compared, so `fs.existsSync` and `existsSync` are the same entry."}},additionalProperties:false}]},defaultOptions:[{ignoreInTests:true,fsMethods:DEFAULT_FS_METHODS}],createOnce(context,currentOptions){let checkMethods;let sourceCode;let EXISTENCE_CHECKS;let READ_ONLY_USES;function returnedExpression(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;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 null;const body=def.node.body;if(body?.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return null;for(const statement of body.body){if(statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement&&statement.argument){return statement.argument}}return null}function reachesPerUserRoot(node,visited=new Set){if(visited.has(node))return false;visited.add(node);const next=child=>reachesPerUserRoot(child,visited);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const variable=(0,provenance_1.findVariable)(sourceCode,node);const def=variable?.defs.length===1?variable.defs[0]:void 0;if(def?.type!=="Variable"||!def.node.init)return false;return next(def.node.init)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PER_USER_ENV_VARS)){return true}return next(node.object)}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;const name=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;if(name!==null&&PER_USER_ROOT_FUNCTIONS.has(name))return true;if(node.arguments.some(argument=>next(argument)))return true;const returned=returnedExpression(callee);return returned!==null&&next(returned)}case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return next(node.consequent)||next(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return next(node.left)||next(node.right);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(expression=>next(expression));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return next(node.left)||next(node.right);default:return false}}function isSecurityRelevantWindow(checkMethod,useMethod){if(!EXISTENCE_CHECKS.has(checkMethod))return true;return!READ_ONLY_USES.has(useMethod)}function resolvesToNonFsLocal(callee,at){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=sourceCode.getScope(at);if((0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs")||(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs/promises")){return false}const variable=(0,provenance_1.findVariable)(sourceCode,callee);return!!variable&&variable.defs.length>0}function usedMethodName(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return resolvesToNonFsLocal(callee,node)?"":callee.name}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return"";const name=(0,eslint_devkit_1.propertyName)(callee);if(name===null)return"";const objectName=callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.object.name:"";if(objectName==="fs"||objectName==="fsPromises")return name;const scope=sourceCode.getScope(node);return(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs")||(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs/promises")?name:""}function collectConditionCalls(node,out,visited=new Set){if(visited.has(node))return;visited.add(node);const inner=(0,eslint_devkit_1.unwrapTypeSyntax)(node);switch(inner.type){case eslint_devkit_1.AST_NODE_TYPES.CallExpression:out.push(inner);if(inner.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){collectConditionCalls(inner.callee.object,out,visited)}return;case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:collectConditionCalls(inner.argument,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:collectConditionCalls(inner.left,out,visited);collectConditionCalls(inner.right,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:collectConditionCalls(inner.test,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.ChainExpression:collectConditionCalls(inner.expression,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:collectConditionCalls(inner.object,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=(0,const_value_1.constInitializerOf)(sourceCode,inner);if(init!==null)collectConditionCalls(init,out,visited);return}}}function sameTarget(checkArg,useArg){const check=(0,eslint_devkit_1.unwrapTypeSyntax)(checkArg);const use=(0,eslint_devkit_1.unwrapTypeSyntax)(useArg);return sourceCode.getText(check).replace(/\s/g,"")===sourceCode.getText(use).replace(/\s/g,"")}function checkMethodOf(call){if(resolvesToNonFsLocal(call.callee,call))return"";return calleeName(call.callee)}function precededByAccessCheck(use,useArg){let child=use;let parent=use.parent;for(;parent;child=parent,parent=child.parent){if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&parent.type!==eslint_devkit_1.AST_NODE_TYPES.Program){continue}const statements=parent.body;const before=statements.slice(0,statements.indexOf(child));for(const statement of before){if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement)continue;const expression=(0,eslint_devkit_1.unwrapTypeSyntax)(statement.expression);const call=(0,eslint_devkit_1.unwrapTypeSyntax)(expression.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?expression.argument:expression);if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;const method=checkMethodOf(call);const checkArg=call.arguments[0];if(ACCESS_CHECKS.has(method)&&checkMethods.has(method)&&checkArg!==void 0&&sameTarget(checkArg,useArg)){return true}}}return false}function hasRecursiveOption(node){return node.arguments.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&argument.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)==="recursive"&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value.value===true))}function checkCallExpression(node){const useMethodName=usedMethodName(node);if(!RISKY_USE_METHODS.has(useMethodName)){return}if(MKDIR_METHODS.has(useMethodName)&&hasRecursiveOption(node)){return}const rawUseArg=node.arguments[0];if(!rawUseArg)return;const useArg=(0,eslint_devkit_1.unwrapTypeSyntax)(rawUseArg);if(reachesPerUserRoot(useArg))return;if(precededByAccessCheck(node,useArg)){reportToctou(node);return}let current=node.parent;while(current){if(current.type==="IfStatement"){const conditionCalls=[];collectConditionCalls(current.test,conditionCalls);for(const condition of conditionCalls){const checkMethodName=checkMethodOf(condition);if(checkMethods.has(checkMethodName)&&isSecurityRelevantWindow(checkMethodName,useMethodName)){const checkArg=condition.arguments[0];if(checkArg&&sameTarget(checkArg,useArg)){reportToctou(node);return}}if(condition.callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(condition.callee),["isFile","isDirectory"])&&condition.callee.object.type==="Identifier"){const variable=(0,provenance_1.findVariable)(sourceCode,condition.callee.object);if(variable&&variable.defs.length>0){const def=variable.defs[0];const declared=def.type==="Variable"?(0,eslint_devkit_1.unwrapTypeSyntax)(def.node.init):null;const init=declared?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?(0,eslint_devkit_1.unwrapTypeSyntax)(declared.argument):declared;if(init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const statMethod=calleeName(init.callee);if(["statSync","lstatSync","stat","lstat"].includes(statMethod)){const statArg=init.arguments[0];if(statArg&&sameTarget(statArg,useArg)){reportToctou(node);return}}}}}}}current=current.parent}}function reportToctou(node){context.report({node,messageId:"toctouVulnerability"})}return{before(){const[options={}]=currentOptions();const{ignoreInTests=true,fsMethods=DEFAULT_FS_METHODS}=options||{};checkMethods=new Set(fsMethods.map(entry=>entry.split(".").at(-1)));const filename=context.filename;const isTestFile=ignoreInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return false}sourceCode=context.sourceCode;EXISTENCE_CHECKS=new Set(["existsSync","exists"]);READ_ONLY_USES=new Set(["readFileSync","readFile"]);return true},CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnboundedDecompression=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const ZLIB_MODULE=/^(node:)?zlib$/;const ASYNC_DECOMPRESSORS=new Set(["gunzip","inflate","inflateRaw","unzip","brotliDecompress","zstdDecompress"]);const SYNC_DECOMPRESSORS=new Set(["gunzipSync","inflateSync","inflateRawSync","unzipSync","brotliDecompressSync","zstdDecompressSync"]);exports.noUnboundedDecompression=(0,eslint_devkit_1.createRule)({name:"no-unbounded-decompression",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unbounded-decompression.md",description:"Require a maxOutputLength ceiling on zlib one-shot decompression",cwe:"CWE-409",cvss:7.5},hasSuggestions:false,messages:{unboundedDecompression:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unbounded decompression",cwe:"CWE-409",description:"zlib.{{fn}}() buffers the whole decompressed result in memory with no maxOutputLength cap. A few KB of crafted input can expand to gigabytes and exhaust the heap (decompression bomb).",severity:"HIGH",fix:"Pass an explicit ceiling: zlib.{{fn}}(input, { maxOutputLength: 10 * 1024 * 1024 }, \u2026)",documentationLink:"https://nodejs.org/api/zlib.html#class-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unbounded decompression in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function isZlibSpecifier(node){
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnboundedDecompression=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const ZLIB_MODULE=/^(node:)?zlib$/;const ASYNC_DECOMPRESSORS=new Set(["gunzip","inflate","inflateRaw","unzip","brotliDecompress","zstdDecompress"]);const SYNC_DECOMPRESSORS=new Set(["gunzipSync","inflateSync","inflateRawSync","unzipSync","brotliDecompressSync","zstdDecompressSync"]);exports.noUnboundedDecompression=(0,eslint_devkit_1.createRule)({name:"no-unbounded-decompression",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unbounded-decompression.md",description:"Require a maxOutputLength ceiling on zlib one-shot decompression",cwe:"CWE-409",cvss:7.5},hasSuggestions:false,messages:{unboundedDecompression:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unbounded decompression",cwe:"CWE-409",description:"zlib.{{fn}}() buffers the whole decompressed result in memory with no maxOutputLength cap. A few KB of crafted input can expand to gigabytes and exhaust the heap (decompression bomb).",severity:"HIGH",fix:"Pass an explicit ceiling: zlib.{{fn}}(input, { maxOutputLength: 10 * 1024 * 1024 }, \u2026)",documentationLink:"https://nodejs.org/api/zlib.html#class-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unbounded decompression in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function isZlibSpecifier(node){const specifier=(0,eslint_devkit_1.staticString)(node);return specifier!==null&&ZLIB_MODULE.test(specifier)}function extraZlibPath(identifier,scope){let variable;for(let s=scope;s;s=s.upper){variable=s.set.get(identifier.name);if(variable)break}const def=variable?.defs[0];if(!variable||!def)return null;if(def.node.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator)return null;const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.AwaitExpression||init.argument.type!==eslint_devkit_1.AST_NODE_TYPES.ImportExpression||!isZlibSpecifier(init.argument.source)){return null}if(variable.references.filter(ref=>ref.isWrite()).length!==1){return null}const id=def.node.id;if(id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return[];if(id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return null;for(const property of id.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const key=(0,eslint_devkit_1.objectKeyName)(property);if(key!==null&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===identifier.name){return[key]}}return null}function zlibPath(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding!==void 0){return binding.module==="zlib"?binding.path:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return extraZlibPath(callee,scope)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=(0,eslint_devkit_1.propertyName)(callee);const base=extraZlibPath(callee.object,scope);return name!==null&&base!==null?[...base,name]:null}return null}function decompressorName(node){const path=zlibPath(node.callee,context.sourceCode.getScope(node));if(path===null||path.length!==1)return null;const[name]=path;return ASYNC_DECOMPRESSORS.has(name)||SYNC_DECOMPRESSORS.has(name)?name:null}function isLiteralPayload(argument){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;return argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&argument.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&argument.callee.object.name==="Buffer"&&argument.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal}function outputCap(options_){let capped=false;for(const property of options_.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return"unknown";const named=(0,eslint_devkit_1.objectKeyName)(property);if(named==="maxOutputLength")capped=true}return capped?"capped":"uncapped"}function judge(node){const fn=decompressorName(node);if(fn===null)return;const args=node.arguments;const payload=args[0];if(payload===void 0)return;if(isLiteralPayload(payload))return;const isAsync=ASYNC_DECOMPRESSORS.has(fn);if(isAsync&&args.length<2)return;const optionsArgument=isAsync&&args.length===2?void 0:args[1];if(optionsArgument!==void 0){if(optionsArgument.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;if(outputCap(optionsArgument)!=="uncapped")return}context.report({node,messageId:"unboundedDecompression",data:{fn}})}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename)},CallExpression(node){if(isTestFile)return;judge(node)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeBufferAlloc=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 UNSAFE_ALLOCATORS=new Set(["allocUnsafe","allocUnsafeSlow"]);const SIZED_ALLOCATORS=new Set(["Array","Buffer","Uint8Array","Uint16Array","Uint32Array","Int8Array","Int16Array","Int32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","ArrayBuffer","SharedArrayBuffer"]);function looksNumeric(node,countNames){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","<<",">>",">>>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.Identifier:return countNames.has(node.name.toLowerCase());case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{const prop=(0,eslint_devkit_1.propertyName)(node);return prop!==null&&countNames.has(prop.toLowerCase())}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="Math"){return true}const name=calleeName(node.callee);return name!==null&&/^(read|len|size|count|decode|parse)/i.test(name)}default:return false}}function toLowerSet(names){return new Set(names.map(n=>n.toLowerCase()))}const COUNT_NAMES=new Set(["length","len","size","count","n","num","total","capacity","bytelength"]);const BUFFER_ALLOCATORS=new Set(["alloc","allocUnsafe","allocUnsafeSlow"]);const WIRE_NAMES=new Set(["chunk","chunks","buffer","buf","payload","frame","packet","raw","message","msg"]);const REQUEST_ROOTS=new Set(["req","request","ctx","event"]);function isWriteMethod(name){return name==="fill"||name==="set"||name.startsWith("write")}const DESTINATION_ARGUMENT_CALLS=new Set(["copy","randomFill","randomFillSync"]);const METADATA_PROPERTIES=new Set(["length","byteLength","byteOffset","buffer"]);const WRITE_WIDTHS=new Map([["writeUInt8",1],["writeInt8",1],["writeUInt16LE",2],["writeUInt16BE",2],["writeInt16LE",2],["writeInt16BE",2],["writeUInt32LE",4],["writeUInt32BE",4],["writeInt32LE",4],["writeInt32BE",4],["writeFloatLE",4],["writeFloatBE",4],["writeDoubleLE",8],["writeDoubleBE",8],["writeBigInt64LE",8],["writeBigInt64BE",8],["writeBigUInt64LE",8],["writeBigUInt64BE",8]]);const MAX_TRACKED_ALLOCATION=4096;const BUFFER_MODULES=new Set(["buffer","node:buffer"]);const CRYPTO_MODULES=new Set(["crypto","node:crypto"]);const RANDOM_FILL_CALLS=new Set(["randomFill","randomFillSync"]);function isCryptoModuleRequire(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"&&CRYPTO_MODULES.has(node.arguments[0].value)}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 isBufferObject(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="Buffer";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node)==="Buffer"&&isBufferModuleRequire(node.object)}function isInsideLoop(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement){return true}current=current.parent}return false}function coversWholeBuffer(call,method){if(method==="fill")return true;const width=WRITE_WIDTHS.get(method);if(width!==void 0){const offset2=call.arguments[1];return offset2!==void 0&&offset2.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&isInsideLoop(call)}if(call.arguments.length===1)return true;const offset=call.arguments[1];return offset.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&isInsideLoop(call)}function fixedWriteSpan(call,method){const width=WRITE_WIDTHS.get(method);if(width===void 0)return null;const offset=call.arguments[1];if(offset===void 0)return{start:0,end:width};if(offset.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||typeof offset.value!=="number"){return null}return{start:offset.value,end:offset.value+width}}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){if(!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier){return callee.property.name}return(0,eslint_devkit_1.propertyName)(callee)}return null}function declaredName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&node.id)return node.id.name;const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?parent.id.name:null}if((parent?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition||parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property)&&!parent.computed){const key=parent.key;return key.name}return null}exports.noUnsafeBufferAlloc=(0,eslint_devkit_1.createRule)({name:"no-unsafe-buffer-alloc",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unsafe-buffer-alloc.md",description:"Disallow `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()`, which return uninitialized memory",cwe:"CWE-908",cweJustification:"CWE-908 (Use of Uninitialized Resource) \u2014 allocUnsafe returns a view over non-zeroed heap memory; any byte not overwritten before the buffer is read or transmitted discloses prior process memory.",cvss:7.5,confidence:"high"},messages:{unsafeAlloc:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Uninitialized Buffer Allocation",cwe:"CWE-908",cvss:7.5,description:"`Buffer.allocUnsafe(size)` returns memory that has not been zeroed. Every byte not overwritten before the buffer is read or sent leaks whatever the allocator previously stored there.",severity:"HIGH",fix:"Use `Buffer.alloc(size)` (zero-filled), or keep `allocUnsafe` only where the very next statement overwrites the whole buffer \u2014 `Buffer.allocUnsafe(size).fill(0)` is accepted by this rule.",documentationLink:"https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize"}),unsafeAllocSlow:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Uninitialized Buffer Allocation (allocUnsafeSlow)",cwe:"CWE-908",cvss:7.5,description:"`Buffer.allocUnsafeSlow(size)` allocates outside the shared pool but is equally uninitialized \u2014 the returned bytes are whatever was last in that memory.",severity:"HIGH",fix:"Use `Buffer.alloc(size)`, or append `.fill(0)` to zero the allocation at the call site.",documentationLink:"https://nodejs.org/api/buffer.html#static-method-bufferallocunsafeslowsize"}),useSafeAlloc:"Replace with `Buffer.alloc()` (zero-filled).",unboundedAllocation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Allocation Sized By Untrusted Input",cwe:"CWE-789",cvss:7.5,description:'The allocation size is read off the wire, so the peer picks it. For `new Array(n)` the hazard is a narrow band, not "large n": V8 keeps a packed backing store only up to ~33.5M elements, and a length just under that turns a 12-byte length prefix into a 229MB allocation (measured: `new Array(3e7)` = 228.9MB in 20.7ms). Past the threshold V8 switches the array to dictionary mode and the allocation costs nothing at all (`new Array(4e7)` and `new Array(1e9)` are both 0.0MB in ~0.005ms). A typed allocation \u2014 `Buffer.alloc(n)`, `new Uint8Array(n)` \u2014 has no such threshold and commits n bytes at any n.',severity:"HIGH",fix:'Clamp the length against the maximum the protocol actually permits, before allocating: `if (length > MAX_LENGTH) throw new Error("too long")`, or `new Array(Math.min(length, MAX_LENGTH))`. A guard that only rejects implausibly huge values is not a fix for `new Array` \u2014 those are the sizes V8 makes free. The damaging lengths are the plausible ones just below the packed-elements limit.',documentationLink:"https://cwe.mitre.org/data/definitions/789.html"})},schema:[{type:"object",properties:{wireNames:{type:"array",items:{type:"string"},default:[...WIRE_NAMES],description:"Binding names that carry bytes off the wire. Replaces the default; pass [] to turn the name arm off."},requestRootNames:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Root identifiers treated as a request. Replaces the default."},countNames:{type:"array",items:{type:"string"},default:[...COUNT_NAMES],description:"Identifiers that hold an allocation size rather than a payload. Replaces the default."}},additionalProperties:false}]},defaultOptions:[{}],createOnce(context,currentOptions){let sourceCode;let vocab;let wireParams;let pendingAllocations;let pendingCallSites;function readsWire(node,depth=0){if(depth>10)return false;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return readsWire(bare,depth+1);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(node.name==="Buffer"){const bound=(0,provenance_1.findVariable)(sourceCode,node);if(bound===null||bound.defs.length===0)return false;if(bound.defs[0].type==="ImportBinding")return false}const lower=node.name.toLowerCase();if(vocab.wireNames.has(lower)||vocab.requestRoots.has(lower)){const bound=(0,provenance_1.findVariable)(sourceCode,node);const def=bound===null?void 0:bound.defs[0];if(def!==void 0&&def.type==="Variable"&&def.node.init!==null&&def.node.init!==void 0){return readsWire(def.node.init,depth+1)}return true}const owner=enclosingFunction(node);if(owner!==null){const name=declaredName(owner);const indices=name===null?void 0:wireParams.get(name);if(indices!==void 0){const index=paramIndexOf(node,owner);if(index!==null&&indices.has(index))return true}}const variable=(0,provenance_1.findVariable)(sourceCode,node);const lastWrite=(variable?.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!==void 0&&readsWire(lastWrite,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:if((0,eslint_devkit_1.readsRequestShape)(node,sourceCode))return true;return readsWire(node.object,depth+1);case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return node.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&readsWire(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return readsWire(node.callee,depth+1)||node.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&readsWire(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsWire(node.left,depth+1)||readsWire(node.right,depth+1);default:return false}}function enclosingFunction(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}function paramIndexOf(node,owner){const params=owner.params;const index=params.findIndex(param=>param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&¶m.name===node.name);return index===-1?null:index}function isClamped(size){if(size.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&size.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&size.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&size.callee.object.name==="Math"&&(0,eslint_devkit_1.propertyName)(size.callee)==="min"){return size.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!readsWire(argument))}if(size.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const name=size.name;let current=size.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(mentionsInComparison(current.test,name))return true}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){const body=current.body;if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){for(const statement of body.body){if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&mentionsInComparison(statement.test,name)){return true}}}return false}current=current.parent}return false}function mentionsInComparison(test,name){if(test.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return mentionsInComparison(test.left,name)||mentionsInComparison(test.right,name)}if(test.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)return false;if(!["<","<=",">",">="].includes(test.operator))return false;const named=side=>side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&side.name===name;return named(test.left)||named(test.right)}function allocationSize(node){const size=node.arguments[0];if(size===void 0||size.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return null;const callee=node.callee;if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&SIZED_ALLOCATORS.has(callee.name)){return looksNumeric(size,vocab.countNames)?size:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Buffer"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),BUFFER_ALLOCATORS)){return size}return null}function recordCallSite(node){const name=calleeName(node.callee);if(name===null)return;node.arguments.forEach((argument,index)=>{if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return;if(!readsWire(argument))return;const indices=wireParams.get(name)??new Set;indices.add(index);wireParams.set(name,indices)})}function judgeAllocation(node,size){if(isClamped(size))return;if(!readsWire(size))return;context.report({node,messageId:"unboundedAllocation"})}function classifyUse(identifier){const parent=identifier.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===identifier){if(parent.computed){const grandparent2=parent.parent;const isWrite=grandparent2.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&grandparent2.left===parent;if(!isWrite)return"read";return parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&isInsideLoop(parent)?"covering":"partial"}if(parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return"read";const name=parent.property.name;if(METADATA_PROPERTIES.has(name))return"metadata";const grandparent=parent.parent;if(grandparent.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||grandparent.callee!==parent||!isWriteMethod(name)){return"read"}return coversWholeBuffer(grandparent,name)?"covering":"partial"}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===identifier){const method=destinationArgumentCallee(parent.callee);if(method===null)return"read";return coversWholeBuffer(parent,method)?"covering":"partial"}return"read"}function destinationArgumentCallee(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),DESTINATION_ARGUMENT_CALLS)){return(0,eslint_devkit_1.propertyName)(callee)}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!RANDOM_FILL_CALLS.has(callee.name)){return null}const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(variable===null||variable.defs.length===0)return null;const def=variable.defs[0];if(def.type==="ImportBinding"){const declaration=def.parent;return declaration.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&CRYPTO_MODULES.has(declaration.source.value)?callee.name:null}return def.type==="Variable"&&def.node.init!==null&&isCryptoModuleRequire(def.node.init)?callee.name:null}function isCoveredBeforeRead(call){const parent=call.parent;let target;let variable;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===call&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){target=parent.id;variable=context.sourceCode.getDeclaredVariables(parent)[0]}else if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.operator==="="&&parent.right===call&&parent.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){target=parent.left;variable=(0,provenance_1.findVariable)(context.sourceCode,target)??void 0}if(target===void 0||variable===void 0){return false}const uses=variable.references.filter(reference=>reference.identifier!==target&&reference.identifier.range[0]>call.range[1]).sort((a,b)=>a.identifier.range[0]-b.identifier.range[0]);const covered=byteMapFor(call);let remaining=covered===null?-1:covered.length;for(const use of uses){const kind=classifyUse(use.identifier);if(kind==="metadata")continue;if(kind==="partial"){if(covered!==null){remaining-=markFixedWrite(covered,use.identifier);if(remaining===0)return true}continue}return kind==="covering"}return false}function byteMapFor(call){const argument=call.arguments[0];if(argument===void 0||argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return null}const resolved=(0,const_value_1.resolveConstant)(sourceCode,argument);if(resolved===null||typeof resolved.value!=="number")return null;const size=resolved.value;if(!Number.isInteger(size)||size<=0||size>MAX_TRACKED_ALLOCATION){return null}return new Uint8Array(size)}function markFixedWrite(covered,identifier){const member=identifier.parent;if(member.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return 0}const call=member.parent;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return 0;const span=fixedWriteSpan(call,member.property.name);if(span===null||span.start<0||span.end>covered.length)return 0;let added=0;for(let index=span.start;index<span.end;index+=1){if(covered[index]===0){covered[index]=1;added+=1}}return added}function unsafeAllocator(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(!isBufferObject(callee.object))return null;const name=callee.computed?(0,const_value_1.resolveConstantString)(sourceCode,callee.property)?.value:callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:void 0;return name!==void 0&&UNSAFE_ALLOCATORS.has(name)?name:null}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(variable===null||variable.defs.length===0)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.node.init===null)return null;if(!isBufferObject(def.node.init))return null;const property=def.name.parent;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed||property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return null}return UNSAFE_ALLOCATORS.has(property.key.name)?property.key.name:null}function isFilledInPlace(node){const parent=node.parent;if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||parent.object!==node||parent.computed||parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||parent.property.name!=="fill"){return false}const grandparent=parent.parent;return grandparent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&grandparent.callee===parent}return{before(){const[options={}]=currentOptions();sourceCode=context.sourceCode;vocab={wireNames:toLowerSet(options.wireNames??[...WIRE_NAMES]),requestRoots:toLowerSet(options.requestRootNames??[...REQUEST_ROOTS]),countNames:toLowerSet(options.countNames??[...COUNT_NAMES])};wireParams=new Map;pendingAllocations=[];pendingCallSites=[]},NewExpression(node){pendingCallSites.push(node);const size=allocationSize(node);if(size!==null)pendingAllocations.push({node,size})},"Program:exit"(){for(const call of pendingCallSites)recordCallSite(call);for(const{node,size}of pendingAllocations)judgeAllocation(node,size)},CallExpression(node){pendingCallSites.push(node);const size=allocationSize(node);if(size!==null)pendingAllocations.push({node,size});const callee=node.callee;const allocator=unsafeAllocator(callee);if(allocator===null)return;if(isFilledInPlace(node))return;if(isCoveredBeforeRead(node))return;const rewritable=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property:null;context.report({node,messageId:allocator==="allocUnsafe"?"unsafeAlloc":"unsafeAllocSlow",...rewritable===null?{}:{suggest:[{messageId:"useSafeAlloc",fix:fixer=>fixer.replaceText(rewritable,"alloc")}]}})}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeBufferAlloc=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 UNSAFE_ALLOCATORS=new Set(["allocUnsafe","allocUnsafeSlow"]);const SIZED_ALLOCATORS=new Set(["Array","Buffer","Uint8Array","Uint16Array","Uint32Array","Int8Array","Int16Array","Int32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","ArrayBuffer","SharedArrayBuffer"]);function looksNumeric(node,countNames){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","<<",">>",">>>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.Identifier:return countNames.has(node.name.toLowerCase());case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{const prop=(0,eslint_devkit_1.propertyName)(node);return prop!==null&&countNames.has(prop.toLowerCase())}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="Math"){return true}const name=calleeName(node.callee);return name!==null&&/^(read|len|size|count|decode|parse)/i.test(name)}default:return false}}function toLowerSet(names){return new Set(names.map(n=>n.toLowerCase()))}const COUNT_NAMES=new Set(["length","len","size","count","n","num","total","capacity","bytelength"]);const BUFFER_ALLOCATORS=new Set(["alloc","allocUnsafe","allocUnsafeSlow"]);const WIRE_NAMES=new Set(["chunk","chunks","buffer","buf","payload","frame","packet","raw","message","msg"]);const REQUEST_ROOTS=new Set(["req","request","ctx","event"]);function isWriteMethod(name){return name==="fill"||name==="set"||name.startsWith("write")}const DESTINATION_ARGUMENT_CALLS=new Set(["copy","randomFill","randomFillSync","getRandomValues"]);const METADATA_PROPERTIES=new Set(["length","byteLength","byteOffset","buffer"]);const WRITE_WIDTHS=new Map([["writeUInt8",1],["writeInt8",1],["writeUInt16LE",2],["writeUInt16BE",2],["writeInt16LE",2],["writeInt16BE",2],["writeUInt32LE",4],["writeUInt32BE",4],["writeInt32LE",4],["writeInt32BE",4],["writeFloatLE",4],["writeFloatBE",4],["writeDoubleLE",8],["writeDoubleBE",8],["writeBigInt64LE",8],["writeBigInt64BE",8],["writeBigUInt64LE",8],["writeBigUInt64BE",8]]);const MAX_TRACKED_ALLOCATION=4096;const ASSIGNING_OPERATORS=new Set(["=","??=","||=","&&="]);const BUFFER_MODULES=new Set(["buffer","node:buffer"]);const CRYPTO_MODULES=new Set(["crypto","node:crypto"]);const RANDOM_FILL_CALLS=new Set(["randomFill","randomFillSync","getRandomValues"]);function isCryptoModuleRequire(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"&&CRYPTO_MODULES.has(node.arguments[0].value)}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 isBufferObject(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="Buffer";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node)==="Buffer"&&isBufferModuleRequire(node.object)}function isInsideLoop(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement){return true}current=current.parent}return false}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){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;const{property}=callee;return property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier?property.name:null}return null}function declaredName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&node.id)return node.id.name;const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?parent.id.name:null}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition&&parent.kind==="constructor"){const owner=parent.parent.parent;return owner.id?.name??declaredName(owner)}if((parent?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition||parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property)&&!parent.computed){const key=parent.key;return key.name}return null}exports.noUnsafeBufferAlloc=(0,eslint_devkit_1.createRule)({name:"no-unsafe-buffer-alloc",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unsafe-buffer-alloc.md",description:"Disallow `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()`, which return uninitialized memory",cwe:"CWE-908",cweJustification:"CWE-908 (Use of Uninitialized Resource) \u2014 allocUnsafe returns a view over non-zeroed heap memory; any byte not overwritten before the buffer is read or transmitted discloses prior process memory.",cvss:7.5,confidence:"high"},messages:{unsafeAlloc:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Uninitialized Buffer Allocation",cwe:"CWE-908",cvss:7.5,description:"`Buffer.allocUnsafe(size)` returns memory that has not been zeroed. Every byte not overwritten before the buffer is read or sent leaks whatever the allocator previously stored there.",severity:"HIGH",fix:"Use `Buffer.alloc(size)` (zero-filled), or keep `allocUnsafe` only where the very next statement overwrites the whole buffer \u2014 `Buffer.allocUnsafe(size).fill(0)` is accepted by this rule.",documentationLink:"https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize"}),unsafeAllocSlow:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Uninitialized Buffer Allocation (allocUnsafeSlow)",cwe:"CWE-908",cvss:7.5,description:"`Buffer.allocUnsafeSlow(size)` allocates outside the shared pool but is equally uninitialized \u2014 the returned bytes are whatever was last in that memory.",severity:"HIGH",fix:"Use `Buffer.alloc(size)`, or append `.fill(0)` to zero the allocation at the call site.",documentationLink:"https://nodejs.org/api/buffer.html#static-method-bufferallocunsafeslowsize"}),useSafeAlloc:"Replace with `Buffer.alloc()` (zero-filled).",unboundedAllocation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Allocation Sized By Untrusted Input",cwe:"CWE-789",cvss:7.5,description:'The allocation size is read off the wire, so the peer picks it. For `new Array(n)` the hazard is a narrow band, not "large n": V8 keeps a packed backing store only up to ~33.5M elements, and a length just under that turns a 12-byte length prefix into a 229MB allocation (measured: `new Array(3e7)` = 228.9MB in 20.7ms). Past the threshold V8 switches the array to dictionary mode and the allocation costs nothing at all (`new Array(4e7)` and `new Array(1e9)` are both 0.0MB in ~0.005ms). A typed allocation \u2014 `Buffer.alloc(n)`, `new Uint8Array(n)` \u2014 has no such threshold and commits n bytes at any n.',severity:"HIGH",fix:'Clamp the length against the maximum the protocol actually permits, before allocating: `if (length > MAX_LENGTH) throw new Error("too long")`, or `new Array(Math.min(length, MAX_LENGTH))`. A guard that only rejects implausibly huge values is not a fix for `new Array` \u2014 those are the sizes V8 makes free. The damaging lengths are the plausible ones just below the packed-elements limit.',documentationLink:"https://cwe.mitre.org/data/definitions/789.html"})},schema:[{type:"object",properties:{wireNames:{type:"array",items:{type:"string"},default:[...WIRE_NAMES],description:"Binding names that carry bytes off the wire. Replaces the default; pass [] to turn the name arm off."},requestRootNames:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Root identifiers treated as a request. Replaces the default."},countNames:{type:"array",items:{type:"string"},default:[...COUNT_NAMES],description:"Identifiers that hold an allocation size rather than a payload. Replaces the default."}},additionalProperties:false}]},defaultOptions:[{}],createOnce(context,currentOptions){let sourceCode;let vocab;let wireParams;let pendingAllocations;let pendingCallSites;function readsWire(node,seen=new Set){if(seen.has(node))return false;seen.add(node);const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return readsWire(bare,seen);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(node.name==="Buffer"){const bound=(0,provenance_1.findVariable)(sourceCode,node);if(bound===null||bound.defs.length===0)return false;if(bound.defs[0].type==="ImportBinding")return false}const lower=node.name.toLowerCase();if(vocab.wireNames.has(lower)||vocab.requestRoots.has(lower)){const def=(0,provenance_1.findVariable)(sourceCode,node)?.defs[0];if(def?.type!=="Variable")return true;if(def.parent.parent.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement){return true}}const owner=enclosingFunction(node);if(owner!==null){const name=declaredName(owner);const indices=name===null?void 0:wireParams.get(name);if(indices?.has(paramIndexOf(node,owner)))return true}const variable=(0,provenance_1.findVariable)(sourceCode,node);const lastWrite=(variable?.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!==void 0&&readsWire(lastWrite,seen)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:if((0,eslint_devkit_1.readsRequestShape)(node,sourceCode))return true;return readsWire(node.object,seen);case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return node.arguments.some(argument=>readsWire(argument,seen));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return readsWire(node.callee,seen)||node.arguments.some(argument=>readsWire(argument,seen));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsWire(node.left,seen)||readsWire(node.right,seen);default:return false}}function enclosingFunction(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}function paramIndexOf(node,owner){const params=owner.params;return params.findIndex(param=>{const bound=param.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentPattern?param.left:param;return bound.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&bound.name===node.name})}function isClamped(size){if(size.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&size.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&size.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&size.callee.object.name==="Math"&&(0,eslint_devkit_1.propertyName)(size.callee)==="min"){return size.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!readsWire(argument))}if(size.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const name=size.name;let child=size;for(let current=size.parent;current;child=current,current=current.parent){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(child===current.consequent&&capsWhenTrue(current.test,name))return true;if(child===current.alternate&&capsWhenFalse(current.test,name))return true}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const before=current.body.slice(0,current.body.indexOf(child));if(before.some(statement=>rejectsOversized(statement,name)))return true}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 false}}return false}function rejectsOversized(statement,name){if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)return false;const taken=statement.consequent;const last=taken.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement?taken.body.at(-1):taken;return(last?.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||last?.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)&&capsWhenFalse(statement.test,name)}function capsWhenTrue(test,name){if(test.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression&&test.operator==="&&"){return capsWhenTrue(test.left,name)||capsWhenTrue(test.right,name)}return comparesAgainstCap(test,name,"below")}function capsWhenFalse(test,name){if(test.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression&&test.operator==="||"){return capsWhenFalse(test.left,name)||capsWhenFalse(test.right,name)}return comparesAgainstCap(test,name,"above")}function comparesAgainstCap(test,name,side){if(test.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)return false;const less=test.operator==="<"||test.operator==="<=";const greater=test.operator===">"||test.operator===">=";if(!less&&!greater)return false;const named=operand=>operand.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&operand.name===name;const left=test.left;const nameBelow=named(left)?less:greater;const cap=named(left)?test.right:named(test.right)?left:null;return cap!==null&&nameBelow===(side==="below")&&!readsWire(cap)}function allocationSize(node){const size=node.arguments[0];if(size===void 0)return null;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&SIZED_ALLOCATORS.has(callee.name)){return looksNumeric(size,vocab.countNames)?size:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Buffer"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),BUFFER_ALLOCATORS)){return size}return null}function recordCallSite(node){const name=calleeName(node.callee);if(name===null)return;node.arguments.forEach((argument,index)=>{if(!readsWire(argument))return;const indices=wireParams.get(name)??new Set;indices.add(index);wireParams.set(name,indices)})}function judgeAllocation(node,size){if(isClamped(size))return;if(!readsWire(size))return;context.report({node,messageId:"unboundedAllocation"})}function classifyUse(identifier){const parent=identifier.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===identifier){if(parent.computed){const grandparent2=parent.parent;const isWrite=grandparent2.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&grandparent2.left===parent;if(!isWrite)return"read";return parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&isInsideLoop(parent)?"covering":"partial"}const name=parent.property.name;if(METADATA_PROPERTIES.has(name))return"metadata";const grandparent=parent.parent;if(grandparent.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||grandparent.callee!==parent||!isWriteMethod(name)){return"read"}return coversWholeBuffer(grandparent,name)?"covering":"partial"}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===identifier){const method=destinationArgumentCallee(parent.callee);if(method===null)return"read";return coversWholeBuffer(parent,method)?"covering":"partial"}return"read"}function destinationArgumentCallee(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),DESTINATION_ARGUMENT_CALLS)){return(0,eslint_devkit_1.propertyName)(callee)}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!RANDOM_FILL_CALLS.has(callee.name)){return null}const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(variable===null||variable.defs.length===0)return null;const def=variable.defs[0];if(def.type==="ImportBinding"){const declaration=def.parent;return declaration.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&CRYPTO_MODULES.has(declaration.source.value)?callee.name:null}return def.type==="Variable"&&def.node.init!==null&&isCryptoModuleRequire(def.node.init)?callee.name:null}function offsetOf(argument){if(argument===void 0)return"start";const resolved=(0,const_value_1.resolveConstant)(sourceCode,argument);if(resolved===null)return null;return typeof resolved.value==="string"?"start":resolved.value}function coversWholeBuffer(call,method){const offset=offsetOf(call.arguments[1]);if(offset==="start")return!WRITE_WIDTHS.has(method);return offset===null&&isInsideLoop(call)}function fixedWriteSpan(call,method){const width=WRITE_WIDTHS.get(method);if(width===void 0)return null;const offset=offsetOf(call.arguments[1]);if(offset===null)return null;const start=offset==="start"?0:offset;return{start,end:start+width}}function isCoveredBeforeRead(call){const parent=call.parent;let variable=null;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){variable=context.sourceCode.getDeclaredVariables(parent)[0]}else if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&ASSIGNING_OPERATORS.has(parent.operator)&&parent.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){variable=(0,provenance_1.findVariable)(context.sourceCode,parent.left)}if(variable===null)return false;const uses=variable.references.filter(reference=>reference.identifier.range[0]>call.range[1]);const covered=byteMapFor(call);let remaining=covered===null?-1:covered.length;for(const use of uses){const kind=classifyUse(use.identifier);if(kind==="metadata")continue;if(kind==="partial"){if(covered!==null){remaining-=markFixedWrite(covered,use.identifier);if(remaining===0)return true}continue}return kind==="covering"}return false}function byteMapFor(call){const argument=call.arguments[0];if(argument===void 0)return null;const resolved=(0,const_value_1.resolveConstant)(sourceCode,argument);if(resolved===null||typeof resolved.value!=="number")return null;const size=resolved.value;if(!Number.isInteger(size)||size<=0||size>MAX_TRACKED_ALLOCATION){return null}return new Uint8Array(size)}function markFixedWrite(covered,identifier){const member=identifier.parent;if(member.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return 0}const call=member.parent;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return 0;const span=fixedWriteSpan(call,member.property.name);if(span===null||span.end>covered.length)return 0;let added=0;for(let index=span.start;index<span.end;index+=1){if(covered[index]===0){covered[index]=1;added+=1}}return added}function unsafeAllocator(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(!isBufferObject(callee.object))return null;const name=callee.computed?(0,const_value_1.resolveConstantString)(sourceCode,callee.property)?.value:callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:void 0;return name!==void 0&&UNSAFE_ALLOCATORS.has(name)?name:null}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(variable===null||variable.defs.length===0)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.node.init===null)return null;if(!isBufferObject(def.node.init))return null;const property=def.name.parent;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed||property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return null}return UNSAFE_ALLOCATORS.has(property.key.name)?property.key.name:null}function isFilledInPlace(node){const parent=node.parent;if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||parent.object!==node||parent.computed||parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||parent.property.name!=="fill"){return false}const grandparent=parent.parent;return grandparent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&grandparent.callee===parent}return{before(){const[options={}]=currentOptions();sourceCode=context.sourceCode;vocab={wireNames:toLowerSet(options.wireNames??[...WIRE_NAMES]),requestRoots:toLowerSet(options.requestRootNames??[...REQUEST_ROOTS]),countNames:toLowerSet(options.countNames??[...COUNT_NAMES])};wireParams=new Map;pendingAllocations=[];pendingCallSites=[]},NewExpression(node){pendingCallSites.push(node);const size=allocationSize(node);if(size!==null)pendingAllocations.push({node,size})},"Program:exit"(){for(const call of pendingCallSites)recordCallSite(call);for(const{node,size}of pendingAllocations)judgeAllocation(node,size)},CallExpression(node){pendingCallSites.push(node);const size=allocationSize(node);if(size!==null)pendingAllocations.push({node,size});const callee=node.callee;const allocator=unsafeAllocator(callee);if(allocator===null)return;if(isFilledInPlace(node))return;if(isCoveredBeforeRead(node))return;const rewritable=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property:null;context.report({node,messageId:allocator==="allocUnsafe"?"unsafeAlloc":"unsafeAllocSlow",...rewritable===null?{}:{suggest:[{messageId:"useSafeAlloc",fix:fixer=>fixer.replaceText(rewritable,"alloc")}]}})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDynamicRequire=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const const_value_1=require("../../utils/const-value");const DEFAULT_TAINT_SOURCES=["req","request","ctx","event","process"];exports.noUnsafeDynamicRequire=(0,eslint_devkit_2.createRule)({name:"no-unsafe-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-unsafe-dynamic-require.md",description:"Prevent unsafe dynamic require() calls that could enable code injection",cwe:"CWE-95",cvss:9.8},hasSuggestions:false,messages:{unsafeDynamicRequire:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic require()",cwe:"CWE-95",description:"Dynamic require() detected",severity:"CRITICAL",fix:'Use allowlist: const ALLOWED = ["mod1", "mod2"]; if (!ALLOWED.includes(name)) throw Error("Not allowed")',documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),unsafeDynamicImport:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic import()",cwe:"CWE-95",description:"import() resolves and EVALUATES the module it is given, exactly as require() does. This specifier is reachable from request or process input, so an attacker chooses which file executes.",severity:"CRITICAL",fix:'Use allowlist: const ALLOWED = { csv: "./formatters/csv" }; const specifier = ALLOWED[name]; if (!specifier) throw Error("Not allowed"); await import(specifier)',documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"})},schema:[{type:"object",properties:{allowDynamicImport:{type:"boolean",default:false},taintSources:{type:"array",items:{type:"string"},default:DEFAULT_TAINT_SOURCES,description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},reportUnresolvedSpecifiers:{type:"boolean",default:false,description:'Report specifiers whose provenance cannot be resolved. Restores the pre-inversion "any non-literal is dangerous" behaviour.'}},additionalProperties:false}]},defaultOptions:[{allowDynamicImport:false}],createOnce(context){let readsTaintSource;let reportUnresolvedSpecifiers;let allowDynamicImport;let requireVariables;const isRequireReference=node=>{if(node.type==="Identifier"
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDynamicRequire=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const const_value_1=require("../../utils/const-value");const DEFAULT_TAINT_SOURCES=["req","request","ctx","event","process"];exports.noUnsafeDynamicRequire=(0,eslint_devkit_2.createRule)({name:"no-unsafe-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-unsafe-dynamic-require.md",description:"Prevent unsafe dynamic require() calls that could enable code injection",cwe:"CWE-95",cvss:9.8},hasSuggestions:false,messages:{unsafeDynamicRequire:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic require()",cwe:"CWE-95",description:"Dynamic require() detected",severity:"CRITICAL",fix:'Use allowlist: const ALLOWED = ["mod1", "mod2"]; if (!ALLOWED.includes(name)) throw Error("Not allowed")',documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),unsafeDynamicImport:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic import()",cwe:"CWE-95",description:"import() resolves and EVALUATES the module it is given, exactly as require() does. This specifier is reachable from request or process input, so an attacker chooses which file executes.",severity:"CRITICAL",fix:'Use allowlist: const ALLOWED = { csv: "./formatters/csv" }; const specifier = ALLOWED[name]; if (!specifier) throw Error("Not allowed"); await import(specifier)',documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"})},schema:[{type:"object",properties:{allowDynamicImport:{type:"boolean",default:false},taintSources:{type:"array",items:{type:"string"},default:DEFAULT_TAINT_SOURCES,description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},reportUnresolvedSpecifiers:{type:"boolean",default:false,description:'Report specifiers whose provenance cannot be resolved. Restores the pre-inversion "any non-literal is dangerous" behaviour.'}},additionalProperties:false}]},defaultOptions:[{allowDynamicImport:false}],createOnce(context){let readsTaintSource;let reportUnresolvedSpecifiers;let allowDynamicImport;let requireVariables;const isRequireReference=node=>{if(node.type==="Identifier"){if(node.name==="require")return true;const variable=(0,provenance_1.findVariable)(context.sourceCode,node);return variable!==null&&requireVariables.has(variable)}return node.type==="MemberExpression"&&node.object.type==="Identifier"&&node.object.name==="module"&&(0,eslint_devkit_1.propertyName)(node)==="require"};const isDangerousSpecifier=arg=>{if((0,const_value_1.resolveConstantString)(context.sourceCode,arg)!==null)return false;if((0,const_value_1.isClosedStringTableLookup)(context.sourceCode,arg))return false;if(arg.type==="Identifier"){const variable=(0,provenance_1.findVariable)(context.sourceCode,arg);if(variable?.defs.length===1&&variable.defs[0].type==="Parameter"){return reportUnresolvedSpecifiers}}if(readsTaintSource(arg))return true;return reportUnresolvedSpecifiers};return{before(){const options=context.options[0]??{};readsTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,new Set((options.taintSources??DEFAULT_TAINT_SOURCES).map(s=>s.toLowerCase())));reportUnresolvedSpecifiers=options.reportUnresolvedSpecifiers??false;allowDynamicImport=options.allowDynamicImport??false;requireVariables=new Set},VariableDeclarator(node){if(node.id.type!=="Identifier"||!node.init)return;const init=node.init;const callee=init.type==="CallExpression"?init.callee:null;const aliasesRequire=init.type==="Identifier"&&init.name==="require"||callee!==null&&((0,eslint_devkit_1.isModuleBinding)(callee,context.sourceCode.getScope(node),"module",["createRequire"])||callee.type==="Identifier"&&callee.name==="createRequire"&&!(0,provenance_1.findVariable)(context.sourceCode,callee)?.defs.length);if(!aliasesRequire)return;for(const variable of context.sourceCode.getDeclaredVariables(node)){requireVariables.add(variable)}},ImportExpression(node){if(allowDynamicImport)return;if(!isDangerousSpecifier(node.source))return;context.report({node,messageId:"unsafeDynamicImport"})},CallExpression(node){if(!isRequireReference(node.callee)){return}if(node.arguments.length===0)return;const firstArg=node.arguments[0];const specifier=firstArg.type==="SpreadElement"?firstArg.argument:firstArg;if(!isDangerousSpecifier(specifier))return;context.report({node,messageId:"unsafeDynamicRequire"})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakCipherAlgorithm=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const WEAK_CIPHER_PATTERNS=[{pattern:/\bdes\b(?!-ede)/i,name:"DES",
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakCipherAlgorithm=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 WEAK_CIPHER_PATTERNS=[{pattern:/\bdes\b(?!-ede)/i,name:"DES",replacement:"aes-256-gcm"},{pattern:/\bdes(?:-ede3?|3)\b|\b3des\b|\btripledes\b/i,name:"3DES",replacement:"aes-256-gcm"},{pattern:/\brc4\b|\barc4\b/i,name:"RC4",replacement:"aes-256-gcm"},{pattern:/\bblowfish\b|\bbf\b/i,name:"Blowfish",replacement:"aes-256-gcm"},{pattern:/\brc2\b/i,name:"RC2",replacement:"aes-256-gcm"},{pattern:/\bidea\b/i,name:"IDEA",replacement:"aes-256-gcm"}];function findWeakCipher(value,additionalPatterns){for(const pattern of WEAK_CIPHER_PATTERNS){if(pattern.pattern.test(value)){return pattern}}for(const additionalPattern of additionalPatterns){const regex=new RegExp(`\\b${additionalPattern}\\b`,"i");if(regex.test(value)){return{pattern:regex,name:additionalPattern.toUpperCase(),replacement:"aes-256-gcm"}}}return null}exports.noWeakCipherAlgorithm=(0,eslint_devkit_1.createRule)({name:"no-weak-cipher-algorithm",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-weak-cipher-algorithm.md",description:"Disallow weak cipher algorithms (DES, 3DES, RC4, Blowfish)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{weakCipherAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak cipher algorithm",cwe:"CWE-327",description:"Use of weak cipher algorithm: {{algorithm}}. {{algorithm}} has known vulnerabilities and should not be used.",severity:"CRITICAL",fix:'Replace with {{replacement}}: crypto.createCipheriv("{{replacement}}", key, iv)',documentationLink:"https://owasp.org/www-community/vulnerabilities/Weak_Cryptography"}),useAes256Gcm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use AES-256-GCM",description:"Replace with AES-256-GCM for authenticated encryption",severity:"LOW",fix:'crypto.createCipheriv("aes-256-gcm", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"}),useChaCha20:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use ChaCha20-Poly1305",description:"Replace with ChaCha20-Poly1305 for modern encryption",severity:"LOW",fix:'crypto.createCipheriv("chacha20-poly1305", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"})},schema:[{type:"object",properties:{additionalWeakCiphers:{type:"array",items:{type:"string"},default:[],description:"Additional weak ciphers to detect"},allowInTests:{type:"boolean",default:false,description:"Allow weak ciphers in test files"}},additionalProperties:false}]},defaultOptions:[{additionalWeakCiphers:[],allowInTests:false}],createOnce(context,currentOptions){let additionalWeakCiphers;let allowInTests;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");if(calleeName!==null&&cipherMethods.has(calleeName)){checkCipherArgument(node)}}function checkCipherArgument(node){const firstArg=node.arguments[0];if(firstArg===void 0)return;const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;const weakPattern=findWeakCipher(resolved.value,additionalWeakCiphers);if(!weakPattern)return;const target=resolved.source;context.report({node:firstArg,messageId:"weakCipherAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:[{messageId:"useAes256Gcm",fix:fixer=>fixer.replaceText(target,`"aes-256-gcm"`)},{messageId:"useChaCha20",fix:fixer=>fixer.replaceText(target,`"chacha20-poly1305"`)}]})}return{before(){const[options={}]=currentOptions();({additionalWeakCiphers=[],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.noWeakDhParameters=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const MODP_GROUP_BITS=new Map([["modp1",768],["modp2",1024],["modp5",1536],["modp14",2048],["modp15",3072],["modp16",4096],["modp17",6144],["modp18",8192]]);const WEAK_CURVES=new Set(["secp112r1","secp112r2","secp128r1","secp128r2","secp160k1","secp160r1","secp160r2","secp192k1","prime192v1","prime192v2","prime192v3","sect113r1","sect113r2","sect131r1","sect131r2","sect163k1","sect163r1","sect163r2","sect193r1","sect193r2","brainpoolP160r1","brainpoolP192r1"]);const GROUP_APIS=new Set(["getDiffieHellman","createDiffieHellmanGroup"]);const PRIME_LENGTH_APIS=new Set(["createDiffieHellman"]);const CURVE_APIS=new Set(["createECDH"]);function calleeName(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node.callee)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.callee.name}return null}exports.noWeakDhParameters=(0,eslint_devkit_1.createRule)({name:"no-weak-dh-parameters",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-weak-dh-parameters.md",description:"Disallow Diffie-Hellman and ECDH parameters below a safe strength",cwe:"CWE-326",cvss:5.9},hasSuggestions:false,messages:{weakModpGroup:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Diffie-Hellman group",cwe:"CWE-326",description:"MODP group {{group}} is {{bits}}-bit, below the {{minimum}}-bit floor. A named group is a fixed prime, so one precomputation breaks every session that used it \u2014 this is the Logjam attack.",severity:"MEDIUM",fix:"Use crypto.getDiffieHellman('modp14') or larger, or prefer ECDH on a modern curve",documentationLink:"https://weakdh.org"}),weakPrimeLength:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Diffie-Hellman prime length",cwe:"CWE-326",description:"A {{bits}}-bit Diffie-Hellman prime is below the {{minimum}}-bit floor.",severity:"MEDIUM",fix:"crypto.createDiffieHellman({{minimum}})",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatediffiehellmanprimelength-generator"}),weakCurve:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak elliptic curve",cwe:"CWE-326",description:"Curve {{curve}} has a field size under 224 bits and does not offer contemporary security margins.",severity:"MEDIUM",fix:"crypto.createECDH('prime256v1'), or 'secp384r1' for a larger margin",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreateecdhcurvename"})},schema:[{type:"object",properties:{minPrimeBits:{type:"integer",minimum:0,default:2048,description:"Smallest acceptable Diffie-Hellman prime, in bits"},additionalWeakCurves:{type:"array",items:{type:"string"},default:[],description:"Curves to treat as weak beyond the built-in list"},allowInTests:{type:"boolean",default:false,description:"Allow weak parameters in test files"}},additionalProperties:false}]},defaultOptions:[{minPrimeBits:2048,additionalWeakCurves:[],allowInTests:false}],createOnce(context){let minPrimeBits;let additionalWeakCurves;let allowInTests;let weakCurves;return{before(){({minPrimeBits=2048,additionalWeakCurves=[],allowInTests=false}=context.options[0]??{});if(allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename))return false;weakCurves=new Set([...WEAK_CURVES,...additionalWeakCurves]);return true},CallExpression(node){const name=calleeName(node);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakDhParameters=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const MODP_GROUP_BITS=new Map([["modp1",768],["modp2",1024],["modp5",1536],["modp14",2048],["modp15",3072],["modp16",4096],["modp17",6144],["modp18",8192]]);const WEAK_CURVES=new Set(["secp112r1","secp112r2","secp128r1","secp128r2","secp160k1","secp160r1","secp160r2","secp192k1","prime192v1","prime192v2","prime192v3","sect113r1","sect113r2","sect131r1","sect131r2","sect163k1","sect163r1","sect163r2","sect193r1","sect193r2","brainpoolP160r1","brainpoolP192r1"]);const GROUP_APIS=new Set(["getDiffieHellman","createDiffieHellmanGroup"]);const PRIME_LENGTH_APIS=new Set(["createDiffieHellman"]);const CURVE_APIS=new Set(["createECDH"]);function calleeName(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node.callee)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.callee.name}return null}exports.noWeakDhParameters=(0,eslint_devkit_1.createRule)({name:"no-weak-dh-parameters",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-weak-dh-parameters.md",description:"Disallow Diffie-Hellman and ECDH parameters below a safe strength",cwe:"CWE-326",cvss:5.9},hasSuggestions:false,messages:{weakModpGroup:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Diffie-Hellman group",cwe:"CWE-326",description:"MODP group {{group}} is {{bits}}-bit, below the {{minimum}}-bit floor. A named group is a fixed prime, so one precomputation breaks every session that used it \u2014 this is the Logjam attack.",severity:"MEDIUM",fix:"Use crypto.getDiffieHellman('modp14') or larger, or prefer ECDH on a modern curve",documentationLink:"https://weakdh.org"}),weakPrimeLength:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Diffie-Hellman prime length",cwe:"CWE-326",description:"A {{bits}}-bit Diffie-Hellman prime is below the {{minimum}}-bit floor.",severity:"MEDIUM",fix:"crypto.createDiffieHellman({{minimum}})",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatediffiehellmanprimelength-generator"}),weakCurve:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak elliptic curve",cwe:"CWE-326",description:"Curve {{curve}} has a field size under 224 bits and does not offer contemporary security margins.",severity:"MEDIUM",fix:"crypto.createECDH('prime256v1'), or 'secp384r1' for a larger margin",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreateecdhcurvename"})},schema:[{type:"object",properties:{minPrimeBits:{type:"integer",minimum:0,default:2048,description:"Smallest acceptable Diffie-Hellman prime, in bits"},additionalWeakCurves:{type:"array",items:{type:"string"},default:[],description:"Curves to treat as weak beyond the built-in list"},allowInTests:{type:"boolean",default:false,description:"Allow weak parameters in test files"}},additionalProperties:false}]},defaultOptions:[{minPrimeBits:2048,additionalWeakCurves:[],allowInTests:false}],createOnce(context){let minPrimeBits;let additionalWeakCurves;let allowInTests;let weakCurves;return{before(){({minPrimeBits=2048,additionalWeakCurves=[],allowInTests=false}=context.options[0]??{});if(allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename))return false;weakCurves=new Set([...WEAK_CURVES,...additionalWeakCurves]);return true},CallExpression(node){const name=calleeName(node);const firstArg=node.arguments[0];if(firstArg===void 0)return;if((0,eslint_devkit_1.namesOneOf)(name,GROUP_APIS)){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;const bits=MODP_GROUP_BITS.get(resolved.value);if(bits===void 0||bits>=minPrimeBits)return;context.report({node:firstArg,messageId:"weakModpGroup",data:{group:resolved.value,bits:String(bits),minimum:String(minPrimeBits)}});return}if((0,eslint_devkit_1.namesOneOf)(name,PRIME_LENGTH_APIS)){const resolved=(0,const_value_1.resolveConstant)(context.sourceCode,firstArg);if(resolved===null||typeof resolved.value!=="number")return;if(resolved.value>=minPrimeBits)return;context.report({node:firstArg,messageId:"weakPrimeLength",data:{bits:String(resolved.value),minimum:String(minPrimeBits)}});return}if((0,eslint_devkit_1.namesOneOf)(name,CURVE_APIS)){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;if(!weakCurves.has(resolved.value))return;context.report({node:firstArg,messageId:"weakCurve",data:{curve:resolved.value}})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakHashAlgorithm=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const names_1=require("../../utils/names");const const_value_1=require("../../utils/const-value");const WEAK_HASH_PATTERNS=[{pattern:/\bmd5(?:withrsaencryption)?\b/i,name:"MD5",alternatives:["SHA-256","SHA-512","SHA-3"],replacement:"sha256"},{pattern:/\bmd4\b/i,name:"MD4",alternatives:["SHA-256","SHA-512","SHA-3"],replacement:"sha256"},{pattern:/\bsha-?1(?:withrsaencryption)?\b/i,name:"SHA-1",alternatives:["SHA-256","SHA-512","SHA-3"],replacement:"sha256"},{pattern:/\b(?:ripemd(?:160(?:withrsa)?)?|rmd160)\b/i,name:"RIPEMD",alternatives:["SHA-256","SHA-512"],replacement:"sha256"}];const DEFAULT_NON_CRYPTOGRAPHIC_NAMES=["sha","etag","cachekey","cachebuster","thumbprint","x5t"];const DEFAULT_SECURITY_USE_NAMES=["password","passwd","secret","secrets","token","tokens","signature","signing","signed","sign","hmac","credential","credentials","certificate","cert","certs","apikey","privatekey","secretkey","signingkey","encryptionkey","session","csrf","salt","jwt","nonce","integrity","auth","authorization","authenticate","otp","mfa","totp","passphrase","pincode","mnemonic","seedphrase","masterkey","securityanswer","recoverycode","backupcode"];function normalizeName(name){return name.replaceAll(/[_-]/g,"").toLowerCase()}function chainTop(node){let current=node;let parent=current.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===current){current=parent;parent=current.parent;continue}break}return current}const EQUALITY_OPERATORS=new Set(["===","==","!==","!="]);function comparedName(node){const current=chainTop(node);const parent=current.parent;if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||!EQUALITY_OPERATORS.has(parent.operator)){return null}return expressionName(parent.left===current?parent.right:parent.left)}function assignedName(node){const current=chainTop(node);const parent=current.parent;if(!parent)return null;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===current){return parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?parent.id.name:null}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.right===current){const target=parent.left;if(target.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return target.name;if(target.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(target)}return null}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===current){if(parent.computed)return null;if(parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return parent.key.name;if(parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof parent.key.value==="string"){return parent.key.value}return null}return null}function expressionName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node)}return null}function hashInputNames(node){const names=[];for(const argument of node.arguments){const name=expressionName(argument);if(name!==null)names.push(name)}let current=node;let parent=current.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===current){for(const argument of parent.arguments){const name=expressionName(argument);if(name!==null)names.push(name)}current=parent;parent=current.parent;continue}break}return names}function enclosingFunctionName(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){if(current.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&¤t.id){return current.id.name}const owner=current.parent;if(owner?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return owner.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?owner.id.name:null}if((owner?.type===eslint_devkit_1.AST_NODE_TYPES.Property||owner?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition)&&!owner.computed){return expressionName(owner.key)}return null}current=current.parent}return null}function findWeakHash(value,additionalPatterns){for(const pattern of WEAK_HASH_PATTERNS){if(pattern.pattern.test(value)){return pattern}}for(const additionalPattern of additionalPatterns){const regex=new RegExp(`\\b${additionalPattern}\\b`,"i");if(regex.test(value)){return{pattern:regex,name:additionalPattern.toUpperCase(),alternatives:["SHA-256","SHA-512"],replacement:"sha256"}}}return null}exports.noWeakHashAlgorithm=(0,eslint_devkit_1.createRule)({name:"no-weak-hash-algorithm",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-weak-hash-algorithm.md",description:"Disallow weak hash algorithms (MD5, SHA1, MD4)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{weakHashAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak hash algorithm",cwe:"CWE-327",description:"Use of weak hash algorithm: {{algorithm}}. {{algorithm}} is cryptographically broken and unsuitable for security purposes.",severity:"CRITICAL",fix:'Replace with {{replacement}}: crypto.createHash("{{replacement}}").update(data). If this hash is an identifier rather than a security control \u2014 an EVALSHA key, an ETag, a cache key \u2014 store it under one of the nonCryptographicNames instead.',documentationLink:"https://owasp.org/www-community/vulnerabilities/Weak_Cryptography"}),useSha256:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-256",description:"Replace with SHA-256 for secure hashing",severity:"LOW",fix:'crypto.createHash("sha256").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"}),useSha512:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-512",description:"Replace with SHA-512 for stronger hashing",severity:"LOW",fix:'crypto.createHash("sha512").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"}),useSha3:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-3",description:"Replace with SHA-3 for latest standard",severity:"LOW",fix:'crypto.createHash("sha3-256").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"})},schema:[{type:"object",properties:{additionalWeakAlgorithms:{type:"array",items:{type:"string"},default:[],description:"Additional weak algorithms to detect"},allowInTests:{type:"boolean",default:false,description:"Allow weak hashes in test files"},nonCryptographicNames:{type:"array",items:{type:"string"},default:DEFAULT_NON_CRYPTOGRAPHIC_NAMES,description:"Assignment target names that mark a hash as an identifier rather than a security control"},securityUseNames:{type:"array",items:{type:"string"},default:DEFAULT_SECURITY_USE_NAMES,description:"Names that mark a hash as a security control (whole-word matched)"},reportUnclassifiedHashes:{type:"boolean",default:false,description:"Report weak hashes whose purpose cannot be determined. Restores the pre-inversion behaviour."}},additionalProperties:false}]},defaultOptions:[{additionalWeakAlgorithms:[],allowInTests:false,nonCryptographicNames:DEFAULT_NON_CRYPTOGRAPHIC_NAMES}],createOnce(context,currentOptions){let additionalWeakAlgorithms;let allowInTests;let nonCryptographicNames;let securityUseNames;let reportUnclassifiedHashes;let isSecurityUse;let isComparedSecurityValue;let isNonCryptographicName;let isTestFile;function isNonCryptographicUse(node){const stored=assignedName(node);if(stored!==null&&isNonCryptographicName(stored))return true;const enclosing=enclosingFunctionName(node);return enclosing!==null&&isNonCryptographicName(enclosing)}function hasSecurityUse(node){const stored=assignedName(node);if(stored!==null&&isSecurityUse(stored))return true;const compared=comparedName(node);if(compared!==null&&isComparedSecurityValue(compared))return true;for(const argument of hashInputNames(node)){if(isSecurityUse(argument))return true}if(stored!==null)return false;const enclosing=enclosingFunctionName(node);return enclosing!==null&&isSecurityUse(enclosing)}function isLocalHmacHelper(callee){const scope=context.sourceCode.getScope(callee);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===callee.name);if(!variable)continue;return variable.defs.some(def=>def.type!=="ImportBinding"&&computesHmac(def.node))}return false}function computesHmac(root){const stack=[root];while(stack.length>0){const node=stack.pop();if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isCreateHmacCall(node)){return true}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){stack.push(child)}}}}return false}function isCreateHmacCall(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return callee.name==="createHmac"}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee)==="createHmac"}function canCallSha256(callee){const scope=context.sourceCode.getScope(callee);const declared=name=>{for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable)return variable.defs.length>0}return false};return declared("sha256")||!declared(callee.name)}function checkCallExpression(node){if(isTestFile)return;if(isNonCryptographicUse(node))return;if(!reportUnclassifiedHashes&&!hasSecurityUse(node))return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="createHash"){checkHashArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="createHash"){checkHashArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const funcName=node.callee.name.toLowerCase();if((funcName==="sha1"||funcName==="md5"||funcName==="md4")&&!isLocalHmacHelper(node.callee)){const weakPattern=findWeakHash(funcName,additionalWeakAlgorithms);context.report({node,messageId:"weakHashAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:canCallSha256(node.callee)?[{messageId:"useSha256",fix:fixer=>fixer.replaceText(node.callee,"sha256")}]:[]})}}}function checkHashArgument(node){for(const arg of node.arguments){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,arg);if(resolved===null)continue;const weakPattern=findWeakHash(resolved.value,additionalWeakAlgorithms);if(!weakPattern)continue;const target=resolved.source;context.report({node:arg,messageId:"weakHashAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:[{messageId:"useSha256",fix:fixer=>fixer.replaceText(target,`"sha256"`)},{messageId:"useSha512",fix:fixer=>fixer.replaceText(target,`"sha512"`)},{messageId:"useSha3",fix:fixer=>fixer.replaceText(target,`"sha3-256"`)}]})}}return{before(){const[options={}]=currentOptions();({additionalWeakAlgorithms=[],allowInTests=false,nonCryptographicNames=DEFAULT_NON_CRYPTOGRAPHIC_NAMES,securityUseNames=DEFAULT_SECURITY_USE_NAMES,reportUnclassifiedHashes=false}=options);isSecurityUse=(0,names_1.makeNameTest)(securityUseNames);isComparedSecurityValue=(0,names_1.makeNameTest)([...securityUseNames,"mac","digest"]);isNonCryptographicName=(0,names_1.makeNameTest)(nonCryptographicNames.map(normalizeName));const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakHashAlgorithm=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const names_1=require("../../utils/names");const const_value_1=require("../../utils/const-value");const WEAK_HASH_PATTERNS=[{pattern:/\bmd5(?:withrsaencryption)?\b/i,name:"MD5",replacement:"sha256"},{pattern:/\bmd4\b/i,name:"MD4",replacement:"sha256"},{pattern:/\bsha-?1(?:withrsaencryption)?\b/i,name:"SHA-1",replacement:"sha256"},{pattern:/\b(?:ripemd(?:160(?:withrsa)?)?|rmd160)\b/i,name:"RIPEMD",replacement:"sha256"}];const DEFAULT_NON_CRYPTOGRAPHIC_NAMES=["sha","etag","cachekey","cachebuster","thumbprint","x5t"];const DEFAULT_SECURITY_USE_NAMES=["password","passwd","secret","secrets","token","tokens","signature","signing","signed","sign","hmac","credential","credentials","certificate","cert","certs","apikey","privatekey","secretkey","signingkey","encryptionkey","session","csrf","salt","jwt","nonce","integrity","auth","authorization","authenticate","otp","mfa","totp","passphrase","pincode","mnemonic","seedphrase","masterkey","securityanswer","recoverycode","backupcode"];function normalizeName(name){return name.replaceAll(/[_-]/g,"")}function chainTop(node){let current=node;let parent=current.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===current){current=parent;parent=current.parent;continue}break}return current}const EQUALITY_OPERATORS=new Set(["===","==","!==","!="]);function comparedName(node){const current=chainTop(node);const parent=current.parent;if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||!EQUALITY_OPERATORS.has(parent.operator)){return null}return expressionName(parent.left===current?parent.right:parent.left)}function assignedName(node){const current=chainTop(node);const parent=current.parent;if(!parent)return null;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===current){return parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?parent.id.name:null}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.right===current){const target=parent.left;if(target.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return target.name;if(target.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(target)}return null}if((parent.type===eslint_devkit_1.AST_NODE_TYPES.Property||parent.type===eslint_devkit_1.AST_NODE_TYPES.PropertyDefinition)&&parent.value===current){const named=(0,eslint_devkit_1.objectKeyName)(parent);if(named!==null)return named;const{key}=parent;return key.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier?key.name:null}return null}function expressionName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node)}return null}function hashInputNames(node){const names=[];for(const argument of node.arguments){const name=expressionName(argument);if(name!==null)names.push(name)}let current=node;let parent=current.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===current){for(const argument of parent.arguments){const name=expressionName(argument);if(name!==null)names.push(name)}current=parent;parent=current.parent;continue}break}return names}function enclosingFunctionName(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){if(current.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&¤t.id){return current.id.name}const owner=current.parent;if(owner?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return owner.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?owner.id.name:null}if((owner?.type===eslint_devkit_1.AST_NODE_TYPES.Property||owner?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition)&&!owner.computed){return expressionName(owner.key)}return null}current=current.parent}return null}function findWeakHash(value,additionalPatterns){for(const pattern of WEAK_HASH_PATTERNS){if(pattern.pattern.test(value)){return pattern}}for(const additionalPattern of additionalPatterns){const regex=new RegExp(`\\b${additionalPattern}\\b`,"i");if(regex.test(value)){return{pattern:regex,name:additionalPattern.toUpperCase(),replacement:"sha256"}}}return null}exports.noWeakHashAlgorithm=(0,eslint_devkit_1.createRule)({name:"no-weak-hash-algorithm",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-weak-hash-algorithm.md",description:"Disallow weak hash algorithms (MD5, SHA1, MD4)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{weakHashAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak hash algorithm",cwe:"CWE-327",description:"Use of weak hash algorithm: {{algorithm}}. {{algorithm}} is cryptographically broken and unsuitable for security purposes.",severity:"CRITICAL",fix:'Replace with {{replacement}}: crypto.createHash("{{replacement}}").update(data). If this hash is an identifier rather than a security control \u2014 an EVALSHA key, an ETag, a cache key \u2014 store it under one of the nonCryptographicNames instead.',documentationLink:"https://owasp.org/www-community/vulnerabilities/Weak_Cryptography"}),useSha256:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-256",description:"Replace with SHA-256 for secure hashing",severity:"LOW",fix:'crypto.createHash("sha256").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"}),useSha512:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-512",description:"Replace with SHA-512 for stronger hashing",severity:"LOW",fix:'crypto.createHash("sha512").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"}),useSha3:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-3",description:"Replace with SHA-3 for latest standard",severity:"LOW",fix:'crypto.createHash("sha3-256").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"})},schema:[{type:"object",properties:{additionalWeakAlgorithms:{type:"array",items:{type:"string"},default:[],description:"Additional weak algorithms to detect"},allowInTests:{type:"boolean",default:false,description:"Allow weak hashes in test files"},nonCryptographicNames:{type:"array",items:{type:"string"},default:DEFAULT_NON_CRYPTOGRAPHIC_NAMES,description:"Assignment target names that mark a hash as an identifier rather than a security control"},securityUseNames:{type:"array",items:{type:"string"},default:DEFAULT_SECURITY_USE_NAMES,description:"Names that mark a hash as a security control (whole-word matched)"},reportUnclassifiedHashes:{type:"boolean",default:false,description:"Report weak hashes whose purpose cannot be determined. Restores the pre-inversion behaviour."}},additionalProperties:false}]},defaultOptions:[{additionalWeakAlgorithms:[],allowInTests:false,nonCryptographicNames:DEFAULT_NON_CRYPTOGRAPHIC_NAMES}],createOnce(context,currentOptions){let additionalWeakAlgorithms;let allowInTests;let nonCryptographicNames;let securityUseNames;let reportUnclassifiedHashes;let isSecurityUse;let isComparedSecurityValue;let isNonCryptographicName;let isTestFile;function isNonCryptographicUse(node){const stored=assignedName(node);if(stored!==null&&isNonCryptographicName(stored))return true;const enclosing=enclosingFunctionName(node);return enclosing!==null&&isNonCryptographicName(enclosing)}function hasSecurityUse(node){const stored=assignedName(node);if(stored!==null&&isSecurityUse(stored))return true;const compared=comparedName(node);if(compared!==null&&isComparedSecurityValue(compared))return true;for(const argument of hashInputNames(node)){if(isSecurityUse(argument))return true}if(stored!==null)return false;const enclosing=enclosingFunctionName(node);return enclosing!==null&&isSecurityUse(enclosing)}function isLocalHmacHelper(callee){const scope=context.sourceCode.getScope(callee);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===callee.name);if(!variable)continue;return variable.defs.some(def=>computesHmac(def.node))}return false}function computesHmac(root){const stack=[root];while(stack.length>0){const node=stack.pop();if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isCreateHmacCall(node)){return true}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){stack.push(child)}}}}return false}function isCreateHmacCall(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return callee.name==="createHmac"}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee)==="createHmac"}function canCallSha256(callee){const scope=context.sourceCode.getScope(callee);const declared=name=>{for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable)return variable.defs.length>0}return false};return declared("sha256")||!declared(callee.name)}function checkCallExpression(node){if(isTestFile)return;if(isNonCryptographicUse(node))return;if(!reportUnclassifiedHashes&&!hasSecurityUse(node))return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="createHash"){checkHashArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="createHash"){checkHashArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const funcName=node.callee.name.toLowerCase();if((funcName==="sha1"||funcName==="md5"||funcName==="md4")&&!isLocalHmacHelper(node.callee)){const weakPattern=findWeakHash(funcName,additionalWeakAlgorithms);context.report({node,messageId:"weakHashAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:canCallSha256(node.callee)?[{messageId:"useSha256",fix:fixer=>fixer.replaceText(node.callee,"sha256")}]:[]})}}}function checkHashArgument(node){for(const arg of node.arguments){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,arg);if(resolved===null)continue;const weakPattern=findWeakHash(resolved.value,additionalWeakAlgorithms);if(!weakPattern)continue;const target=resolved.source;context.report({node:arg,messageId:"weakHashAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:[{messageId:"useSha256",fix:fixer=>fixer.replaceText(target,`"sha256"`)},{messageId:"useSha512",fix:fixer=>fixer.replaceText(target,`"sha512"`)},{messageId:"useSha3",fix:fixer=>fixer.replaceText(target,`"sha3-256"`)}]})}}return{before(){const[options={}]=currentOptions();({additionalWeakAlgorithms=[],allowInTests=false,nonCryptographicNames=DEFAULT_NON_CRYPTOGRAPHIC_NAMES,securityUseNames=DEFAULT_SECURITY_USE_NAMES,reportUnclassifiedHashes=false}=options);isSecurityUse=(0,names_1.makeNameTest)(securityUseNames);isComparedSecurityValue=(0,names_1.makeNameTest)([...securityUseNames,"mac","digest"]);isNonCryptographicName=(0,names_1.makeNameTest)(nonCryptographicNames.map(normalizeName));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.noZipSlip=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const AMBIGUOUS_EXTRACTORS=new Set(["extract","extractAll","unzip","untar"]);const DEFAULT_ARCHIVE_ENTRY_FIELDS=["name","path","fileName","entryName","filename"];const DEFAULT_ARCHIVE_MODULES=["adm-zip","unzipper","yauzl","yazl","tar","tar-fs","tar-stream","extract-zip","node-stream-zip","jszip","archiver","decompress","unzip-stream","zip-stream","gunzip-maybe","7zip-min","node-7z"];const containsPathTraversal=pathText=>{return/\.\.\//.test(pathText)||/\.\.\\/.test(pathText)||pathText.startsWith("..")||/\/\.\./.test(pathText)};const isDangerousDestination=destText=>{if(destText.startsWith("/tmp")||destText.includes("os.tmpdir")||destText.includes("TMPDIR")){return false}return destText.includes("/var")||destText.includes("/usr")||destText.includes("/etc")||destText.includes("/root")||destText.includes("/home")||destText.includes("C:\\Windows")||destText.includes("C:\\Program Files")||destText.includes("C:\\Users")};exports.noZipSlip=(0,eslint_devkit_1.createRule)({name:"no-zip-slip",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-zip-slip.md",description:"Detects zip slip/archive extraction vulnerabilities",cwe:"CWE-22"},messages:{unsafeArchiveExtraction:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Archive Extraction",cwe:"CWE-22",description:"Archive extraction without path validation",severity:"HIGH",fix:"Use safe extraction libraries or validate all paths",documentationLink:"https://snyk.io/research/zip-slip-vulnerability"}),pathTraversalInArchive:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Path Traversal in Archive",cwe:"CWE-22",description:"Archive contains path traversal sequences",severity:"CRITICAL",fix:"Reject archives with path traversal or sanitize paths",documentationLink:"https://cwe.mitre.org/data/definitions/22.html"}),unvalidatedArchivePath:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unvalidated Archive Path",cwe:"CWE-22",description:"Archive entry path used without validation",severity:"HIGH",fix:"Validate paths before extraction",documentationLink:"https://snyk.io/research/zip-slip-vulnerability"}),dangerousArchiveDestination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Archive Destination",cwe:"CWE-22",description:"Archive extracted to sensitive location",severity:"MEDIUM",fix:"Extract to safe temporary directory",documentationLink:"https://cwe.mitre.org/data/definitions/22.html"})},schema:[{type:"object",properties:{archiveFunctions:{type:"array",items:{type:"string"},default:["extract","extractAll","extractAllTo","unzip","untar","extractArchive"]},pathValidationFunctions:{type:"array",items:{type:"string"},default:["validatePath","sanitizePath","checkPath","safePath"]},safeLibraries:{type:"array",items:{type:"string"},default:["yauzl","safe-archive-extract","tar-stream","unzipper"]},archiveEntryFields:{type:"array",items:{type:"string"},default:[...DEFAULT_ARCHIVE_ENTRY_FIELDS],description:"Property names an archive entry exposes its path on. Replaces the default."},archiveModules:{type:"array",items:{type:"string"},default:DEFAULT_ARCHIVE_MODULES,description:"Module specifiers that mean this file works with archives"},reportWithoutArchiveContext:{type:"boolean",default:false,description:"Report entry-name and traversal shapes in files with no archive. Restores the pre-inversion behaviour."}},additionalProperties:false}]},defaultOptions:[{archiveFunctions:["extract","extractAll","extractAllTo","unzip","untar","extractArchive"],pathValidationFunctions:["validatePath","sanitizePath","checkPath","safePath"],safeLibraries:["yauzl","safe-archive-extract","tar-stream","unzipper"]}],createOnce(context){let archiveEntryFields;let archiveFunctions;let pathValidationFunctions;let safeLibraries;let archiveModules;let reportWithoutArchiveContext;let filename;let archiveModuleSet;let hasArchiveContext;const ARCHIVE_NAME=/zip|tarball|archive|gzip|gunzip|untar|tarstream|\btar\b/i;let pending;let EXITS;const isArchiveModule=specifier=>typeof specifier==="string"&&archiveModuleSet.has(specifier.toLowerCase());const namesArchive=node=>{if(node.type==="Identifier")return ARCHIVE_NAME.test(node.name);if(node.type==="MemberExpression"){return namesArchive(node.object)||ARCHIVE_NAME.test((0,eslint_devkit_1.propertyName)(node)??"")}return false};const isArchiveExtraction=node=>{const callee=node.callee;const method=callee.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(callee):null;if(method!==null&&archiveFunctions.includes(method)){if(!AMBIGUOUS_EXTRACTORS.has(method))return true;return namesArchive(callee.object)}if(callee.type==="Identifier"&&archiveFunctions.includes(callee.name)){if(!AMBIGUOUS_EXTRACTORS.has(callee.name))return true;return node.arguments.length>=2}return false};const isNamedPathFunction=(callee,fns)=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,context.sourceCode.getScope(callee),{equivalents:{"path/posix":"path"}});return binding?.module==="path"&&binding.path.length===1&&fns.includes(binding.path[0])};const safeOutcome=test=>{if(test.type==="UnaryExpression"&&test.operator==="!"){const inner=safeOutcome(test.argument);return inner===null?null:inner==="true"?"false":"true"}if(test.type==="LogicalExpression"){const sides=new Set([safeOutcome(test.left),safeOutcome(test.right)]);if(test.operator==="||"&&sides.has("false"))return"false";if(test.operator==="&&"&&sides.has("true"))return"true";return null}if(test.type!=="CallExpression"||test.callee.type!=="MemberExpression"){return null}const method=(0,eslint_devkit_1.propertyName)(test.callee);if(method!=="startsWith"&&method!=="includes")return null;const needle=(0,eslint_devkit_1.staticString)(test.arguments[0]);const findsTraversal=needle!==null&&(method==="includes"?needle.includes(".."):needle.startsWith(".."));return findsTraversal?"false":"true"};const alwaysExits=statement=>EXITS.has(statement.type)||statement.type==="BlockStatement"&&statement.body.some(inner=>EXITS.has(inner.type));const isGuardClause=statement=>{if(statement.type!=="IfStatement")return false;const safe=safeOutcome(statement.test);if(safe==="false")return alwaysExits(statement.consequent);return safe==="true"&&statement.alternate!=null&&alwaysExits(statement.alternate)};const statementsOf=container=>{if(container.type==="BlockStatement"||container.type==="Program"){return container.body}return container.type==="SwitchCase"?container.consequent:null};const isCheckedAfterBinding=call=>{const declarator=call.parent;if(declarator?.type!=="VariableDeclarator"||declarator.id.type!=="Identifier"){return false}const declaration=declarator.parent;const list=statementsOf(declaration.parent);if(list===null)return false;const subjects=[...context.sourceCode.getDeclaredVariables(declarator)];const reads=node=>subjects.some(variable=>variable.references.some(ref=>!ref.init&&ref.identifier.range[0]>=node.range[0]&&ref.identifier.range[1]<=node.range[1]));for(const sibling of list.slice(list.indexOf(declaration)+1)){if(isGuardClause(sibling)){if(reads(sibling.test))return true}if(!reads(sibling))continue;if(sibling.type==="VariableDeclaration"&&sibling.declarations[0].init?.type==="CallExpression"&&sibling.declarations[0].init.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(sibling.declarations[0].init.callee)==="relative"){subjects.push(...context.sourceCode.getDeclaredVariables(sibling.declarations[0]));continue}return false}return false};const isPathValidated=pathNode=>{let child=pathNode;let current=pathNode;while(current){if(current.type==="CallExpression"&¤t.callee.type==="Identifier"&&pathValidationFunctions.includes(current.callee.name)){return true}if(current.type==="CallExpression"&¤t.callee.type==="MemberExpression"&¤t.callee.object.type==="Identifier"&¤t.callee.object.name==="path"&&(0,eslint_devkit_1.propertyName)(current.callee)==="basename"){return true}if(current.type==="CallExpression"&&isCheckedAfterBinding(current)){return true}if(current.type==="IfStatement"){const safe=safeOutcome(current.test);if(child===current.test&&safe!==null)return true;if(child===current.consequent&&safe==="true")return true;if(child===current.alternate&&safe==="false")return true}const list=statementsOf(current);if(list!==null){for(const sibling of list){if(sibling===child)break;if(isGuardClause(sibling))return true}}child=current;current=current.parent}return false};const isSafeLibrary=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&safeLibraries.includes(callee.object.name)){return true}if(callee.type==="Identifier"){const name=callee.name.toLowerCase();if(name==="extract"||name==="unzipper"||safeLibraries.some(lib=>name.includes(lib.toLowerCase()))){return true}}return false};return{before(){const options=context.options[0]||{};archiveEntryFields=new Set(options.archiveEntryFields??DEFAULT_ARCHIVE_ENTRY_FIELDS);({archiveFunctions=["extract","extractAll","extractAllTo","unzip","untar","extractArchive"],pathValidationFunctions=["validatePath","sanitizePath","checkPath","safePath"],safeLibraries=["yauzl","safe-archive-extract","tar-stream","unzipper"],archiveModules=DEFAULT_ARCHIVE_MODULES,reportWithoutArchiveContext=false}=options);filename=context.filename;archiveModuleSet=new Set(archiveModules.map(name=>name.toLowerCase()));hasArchiveContext=reportWithoutArchiveContext;pending=[];EXITS=new Set(["ReturnStatement","ThrowStatement","ContinueStatement","BreakStatement"])},ImportDeclaration(node){if(isArchiveModule(node.source.value))hasArchiveContext=true},NewExpression(node){if(namesArchive(node.callee))hasArchiveContext=true},"Program:exit"(){for(const report of pending)report()},CallExpression(node){if(node.callee.type==="Identifier"&&node.callee.name==="require"&&node.arguments[0]?.type==="Literal"&&isArchiveModule(node.arguments[0].value)){hasArchiveContext=true}if(namesArchive(node.callee))hasArchiveContext=true;if(isArchiveExtraction(node)&&!isSafeLibrary(node)){const sourceCode=context.sourceCode;let hasSafeAnnotation=false;for(let annotated=node;annotated&&!hasSafeAnnotation;annotated=annotated.parent){if(!/Statement|Declaration/.test(annotated.type))continue;hasSafeAnnotation=sourceCode.getCommentsBefore(annotated).some(comment=>/@safe\b/.test(comment.value))}if(hasSafeAnnotation){return}const args=node.arguments;let destArg;const extractor=node.callee.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(node.callee):null;if(extractor!==null){const methodName=extractor;if(["extractAllTo","unzip"].includes(methodName)){destArg=args[0]}else{destArg=args.length>=2?args[1]:void 0}}else{destArg=args.length>=2?args[1]:void 0}const destText=(destArg===void 0?null:(0,eslint_devkit_1.staticString)(destArg))??"";const isDestDangerous=isDangerousDestination(destText);const isMethodCall=node.callee.type==="MemberExpression";if(isMethodCall){const isSafeRelativePath=destText.startsWith("./")||destText.startsWith("../");if(!isSafeRelativePath){context.report({node,messageId:"unsafeArchiveExtraction",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}if(isDestDangerous&&destArg){context.report({node:destArg,messageId:"dangerousArchiveDestination",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else{if(isDestDangerous){context.report({node,messageId:"dangerousArchiveDestination",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}else{context.report({node,messageId:"unsafeArchiveExtraction",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}const callee=node.callee;const pathFns=["join","resolve","relative","normalize"];if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),pathFns)||callee.type==="Identifier"&&isNamedPathFunction(callee,pathFns)){const args=node.arguments;for(const arg of args){if(arg.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(arg),archiveEntryFields)){if(!isPathValidated(arg)){pending.push(()=>{if(!hasArchiveContext)return;context.report({node:arg,messageId:"unvalidatedArchivePath",data:{filePath:filename,line:String(node.loc?.start.line??0)}})})}}}}},Literal(node){if(typeof node.value!=="string"){return}const text=node.value;if(!(text.includes("/")||text.includes("\\"))||!containsPathTraversal(text)){return}let current=node;while(current){if(current.type==="CallExpression"&&isArchiveExtraction(current)){context.report({node,messageId:"pathTraversalInArchive",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}current=current.parent}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noZipSlip=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const AMBIGUOUS_EXTRACTORS=new Set(["extract","extractAll","unzip","untar"]);const DEFAULT_ARCHIVE_ENTRY_FIELDS=["name","path","fileName","entryName","filename"];const DEFAULT_ARCHIVE_MODULES=["adm-zip","unzipper","yauzl","yazl","tar","tar-fs","tar-stream","extract-zip","node-stream-zip","jszip","archiver","decompress","unzip-stream","zip-stream","gunzip-maybe","7zip-min","node-7z"];const DESTINATION_FIRST=new Set(["extractAllTo","unzip"]);const PARENT_SEGMENT=/(?:^|[/\\])\.\.(?:[/\\]|$)/;const containsPathTraversal=pathText=>PARENT_SEGMENT.test(pathText);const isDangerousDestination=destText=>{if(destText.startsWith("/tmp")||destText.includes("os.tmpdir")||destText.includes("TMPDIR")){return false}return destText.includes("/var")||destText.includes("/usr")||destText.includes("/etc")||destText.includes("/root")||destText.includes("/home")||destText.includes("C:\\Windows")||destText.includes("C:\\Program Files")||destText.includes("C:\\Users")};exports.noZipSlip=(0,eslint_devkit_1.createRule)({name:"no-zip-slip",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-zip-slip.md",description:"Detects zip slip/archive extraction vulnerabilities",cwe:"CWE-22"},messages:{unsafeArchiveExtraction:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Archive Extraction",cwe:"CWE-22",description:"Archive extraction without path validation",severity:"HIGH",fix:"Use safe extraction libraries or validate all paths",documentationLink:"https://snyk.io/research/zip-slip-vulnerability"}),pathTraversalInArchive:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Path Traversal in Archive",cwe:"CWE-22",description:"Archive contains path traversal sequences",severity:"CRITICAL",fix:"Reject archives with path traversal or sanitize paths",documentationLink:"https://cwe.mitre.org/data/definitions/22.html"}),unvalidatedArchivePath:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unvalidated Archive Path",cwe:"CWE-22",description:"Archive entry path used without validation",severity:"HIGH",fix:"Validate paths before extraction",documentationLink:"https://snyk.io/research/zip-slip-vulnerability"}),dangerousArchiveDestination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Archive Destination",cwe:"CWE-22",description:"Archive extracted to sensitive location",severity:"MEDIUM",fix:"Extract to safe temporary directory",documentationLink:"https://cwe.mitre.org/data/definitions/22.html"})},schema:[{type:"object",properties:{archiveFunctions:{type:"array",items:{type:"string"},default:["extract","extractAll","extractAllTo","unzip","untar","extractArchive"]},pathValidationFunctions:{type:"array",items:{type:"string"},default:["validatePath","sanitizePath","checkPath","safePath"]},safeLibraries:{type:"array",items:{type:"string"},default:["yauzl","safe-archive-extract","tar-stream","unzipper"]},archiveEntryFields:{type:"array",items:{type:"string"},default:[...DEFAULT_ARCHIVE_ENTRY_FIELDS],description:"Property names an archive entry exposes its path on. Replaces the default."},archiveModules:{type:"array",items:{type:"string"},default:DEFAULT_ARCHIVE_MODULES,description:"Module specifiers that mean this file works with archives"},reportWithoutArchiveContext:{type:"boolean",default:false,description:"Report entry-name and traversal shapes in files with no archive. Restores the pre-inversion behaviour."}},additionalProperties:false}]},defaultOptions:[{archiveFunctions:["extract","extractAll","extractAllTo","unzip","untar","extractArchive"],pathValidationFunctions:["validatePath","sanitizePath","checkPath","safePath"],safeLibraries:["yauzl","safe-archive-extract","tar-stream","unzipper"]}],createOnce(context){let archiveEntryFields;let archiveFunctions;let pathValidationFunctions;let safeLibraries;let archiveModules;let reportWithoutArchiveContext;let filename;let archiveModuleSet;let hasArchiveContext;const ARCHIVE_NAME=/zip|tarball|archive|gzip|gunzip|untar|tarstream|\btar\b/i;let pending;let EXITS;const isArchiveModule=specifier=>specifier!==null&&archiveModuleSet.has(specifier.toLowerCase());const namesArchive=node=>{if(node.type==="Identifier")return ARCHIVE_NAME.test(node.name);if(node.type==="MemberExpression"){return namesArchive(node.object)||ARCHIVE_NAME.test((0,eslint_devkit_1.propertyName)(node)??"")}return false};const isLocalObjectLiteral=receiver=>{if(receiver.type!=="Identifier")return false;const init=(0,const_value_1.constInitializerOf)(context.sourceCode,receiver);return init!==null&&init.type==="ObjectExpression"};const isArchiveExtraction=node=>{const callee=node.callee;const method=callee.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(callee):null;if(method!==null&&archiveFunctions.includes(method)){if(isLocalObjectLiteral(callee.object))return false;if(!AMBIGUOUS_EXTRACTORS.has(method))return true;return namesArchive(callee.object)}if(callee.type==="Identifier"&&archiveFunctions.includes(callee.name)){if(!AMBIGUOUS_EXTRACTORS.has(callee.name))return true;return node.arguments.length>=2}return false};const isNamedPathFunction=(callee,fns)=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,context.sourceCode.getScope(callee),{equivalents:{"path/posix":"path"}});return binding?.module==="path"&&binding.path.length===1&&fns.includes(binding.path[0])};const safeOutcome=test=>{if(test.type==="UnaryExpression"&&test.operator==="!"){const inner=safeOutcome(test.argument);return inner===null?null:inner==="true"?"false":"true"}if(test.type==="LogicalExpression"){const sides=new Set([safeOutcome(test.left),safeOutcome(test.right)]);if(test.operator==="||"&&sides.has("false"))return"false";if(test.operator==="&&"&&sides.has("true"))return"true";return null}if(test.type!=="CallExpression"||test.callee.type!=="MemberExpression"){return null}const method=(0,eslint_devkit_1.propertyName)(test.callee);if(method!=="startsWith"&&method!=="includes")return null;const needle=(0,eslint_devkit_1.staticString)(test.arguments[0]);const findsTraversal=needle!==null&&(method==="includes"?needle.includes(".."):needle.startsWith(".."));return findsTraversal?"false":"true"};const alwaysExits=statement=>EXITS.has(statement.type)||statement.type==="BlockStatement"&&statement.body.some(inner=>EXITS.has(inner.type));const isGuardClause=statement=>{if(statement.type!=="IfStatement")return false;const safe=safeOutcome(statement.test);if(safe==="false")return alwaysExits(statement.consequent);return safe==="true"&&statement.alternate!=null&&alwaysExits(statement.alternate)};const statementsOf=container=>{if(container.type==="BlockStatement"||container.type==="Program"){return container.body}return container.type==="SwitchCase"?container.consequent:null};const isCheckedAfterBinding=init=>{const declarator=init.parent;if(declarator?.type!=="VariableDeclarator"||declarator.id.type!=="Identifier"){return false}const declaration=declarator.parent;const list=statementsOf(declaration.parent);if(list===null)return false;const subjects=[...context.sourceCode.getDeclaredVariables(declarator)];const reads=node=>subjects.some(variable=>variable.references.some(ref=>!ref.init&&ref.identifier.range[0]>=node.range[0]&&ref.identifier.range[1]<=node.range[1]));for(const sibling of list.slice(list.indexOf(declaration)+1)){if(isGuardClause(sibling)){if(reads(sibling.test))return true}if(!reads(sibling))continue;if(sibling.type==="VariableDeclaration"&&sibling.declarations[0].init?.type==="CallExpression"&&sibling.declarations[0].init.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(sibling.declarations[0].init.callee)==="relative"){subjects.push(...context.sourceCode.getDeclaredVariables(sibling.declarations[0]));continue}return false}return false};const isPathValidated=pathNode=>{let child=pathNode;let current=pathNode;while(current){if(current.type==="CallExpression"&¤t.callee.type==="Identifier"&&pathValidationFunctions.includes(current.callee.name)){return true}if(current.type==="CallExpression"&¤t.callee.type==="MemberExpression"&¤t.callee.object.type==="Identifier"&¤t.callee.object.name==="path"&&(0,eslint_devkit_1.propertyName)(current.callee)==="basename"){return true}if(isCheckedAfterBinding(current))return true;if(current.type==="IfStatement"){const safe=safeOutcome(current.test);if(child===current.test&&safe!==null)return true;if(child===current.consequent&&safe==="true")return true;if(child===current.alternate&&safe==="false")return true}const list=statementsOf(current);if(list!==null){for(const sibling of list){if(sibling===child)break;if(isGuardClause(sibling))return true}}child=current;current=current.parent}return false};const isSafeLibrary=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&safeLibraries.includes(callee.object.name)){return true}if(callee.type==="Identifier"){const name=callee.name.toLowerCase();if(name==="extract"||safeLibraries.some(lib=>name.includes(lib.toLowerCase()))){return true}}return false};return{before(){const options=context.options[0]||{};archiveEntryFields=new Set(options.archiveEntryFields??DEFAULT_ARCHIVE_ENTRY_FIELDS);({archiveFunctions=["extract","extractAll","extractAllTo","unzip","untar","extractArchive"],pathValidationFunctions=["validatePath","sanitizePath","checkPath","safePath"],safeLibraries=["yauzl","safe-archive-extract","tar-stream","unzipper"],archiveModules=DEFAULT_ARCHIVE_MODULES,reportWithoutArchiveContext=false}=options);filename=context.filename;archiveModuleSet=new Set(archiveModules.map(name=>name.toLowerCase()));hasArchiveContext=reportWithoutArchiveContext;pending=[];EXITS=new Set(["ReturnStatement","ThrowStatement","ContinueStatement","BreakStatement"])},ImportDeclaration(node){if(isArchiveModule(node.source.value))hasArchiveContext=true},NewExpression(node){if(namesArchive(node.callee))hasArchiveContext=true},"Program:exit"(){for(const report of pending)report()},CallExpression(node){if(node.callee.type==="Identifier"&&node.callee.name==="require"&&isArchiveModule((0,eslint_devkit_1.staticString)(node.arguments[0]))){hasArchiveContext=true}if(namesArchive(node.callee))hasArchiveContext=true;if(isArchiveExtraction(node)&&!isSafeLibrary(node)){const sourceCode=context.sourceCode;let hasSafeAnnotation=false;for(let annotated=node;annotated&&!hasSafeAnnotation;annotated=annotated.parent){if(!/Statement|Declaration/.test(annotated.type))continue;hasSafeAnnotation=sourceCode.getCommentsBefore(annotated).some(comment=>/@safe\b/.test(comment.value))}if(hasSafeAnnotation){return}const args=node.arguments;const extractor=node.callee.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(node.callee):null;const destArg=(0,eslint_devkit_1.namesOneOf)(extractor,DESTINATION_FIRST)?args[0]:args[1];const destText=(0,eslint_devkit_1.staticString)(destArg)??"";const isDestDangerous=isDangerousDestination(destText);const isMethodCall=node.callee.type==="MemberExpression";if(isMethodCall){const isSafeRelativePath=destText.startsWith("./")||destText.startsWith("../");if(!isSafeRelativePath){context.report({node,messageId:"unsafeArchiveExtraction",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}if(isDestDangerous&&destArg){context.report({node:destArg,messageId:"dangerousArchiveDestination",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else{if(isDestDangerous){context.report({node,messageId:"dangerousArchiveDestination",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}else{context.report({node,messageId:"unsafeArchiveExtraction",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}const callee=node.callee;const pathFns=["join","resolve","relative","normalize"];if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),pathFns)||callee.type==="Identifier"&&isNamedPathFunction(callee,pathFns)){const args=node.arguments;for(const arg of args){if(arg.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(arg),archiveEntryFields)){if(!isPathValidated(arg)){pending.push(()=>{if(!hasArchiveContext)return;context.report({node:arg,messageId:"unvalidatedArchivePath",data:{filePath:filename,line:String(node.loc?.start.line??0)}})})}}}}},Literal(node){if(typeof node.value!=="string"){return}if(!containsPathTraversal(node.value))return;let current=node;while(current){if(current.type==="CallExpression"&&isArchiveExtraction(current)){context.report({node,messageId:"pathTraversalInArchive",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}current=current.parent}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.preferNativeCrypto=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");function isCreateRequireCall(sourceCode,node){if(!node||node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;return(0,eslint_devkit_1.isModuleBinding)(node.callee,sourceCode.getScope(node),"module",["createRequire"])}function isRequireCallee(sourceCode,callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const def=(0,provenance_1.findVariable)(sourceCode,callee)?.defs[0];if(def?.type==="Variable"&&isCreateRequireCall(sourceCode,def.node.init))return true;if(callee.name!=="require")return false;if(def===void 0)return true;return def.type==="Variable"&&def.node.init?.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&def.node.init?.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression}function moduleSpecifierListener(sourceCode,judge){const fromExpression=(report,source)=>{if(!source)return;const resolved=(0,const_value_1.resolveConstantString)(sourceCode,source);if(resolved!==null)judge(report,resolved.value)};return{ImportDeclaration:node=>fromExpression(node,node.source),ImportExpression:node=>fromExpression(node,node.source),ExportNamedDeclaration:node=>fromExpression(node,node.source),ExportAllDeclaration:node=>fromExpression(node,node.source),TSImportEqualsDeclaration:node=>{if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){fromExpression(node,node.moduleReference.expression)}},CallExpression:node=>{if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.preferNativeCrypto=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");function isCreateRequireCall(sourceCode,node){if(!node||node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;return(0,eslint_devkit_1.isModuleBinding)(node.callee,sourceCode.getScope(node),"module",["createRequire"])}function isRequireCallee(sourceCode,callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const def=(0,provenance_1.findVariable)(sourceCode,callee)?.defs[0];if(def?.type==="Variable"&&isCreateRequireCall(sourceCode,def.node.init))return true;if(callee.name!=="require")return false;if(def===void 0)return true;return def.type==="Variable"&&def.node.init?.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&def.node.init?.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression}function moduleSpecifierListener(sourceCode,judge){const fromExpression=(report,source)=>{if(!source)return;const resolved=(0,const_value_1.resolveConstantString)(sourceCode,source);if(resolved!==null)judge(report,resolved.value)};return{ImportDeclaration:node=>fromExpression(node,node.source),ImportExpression:node=>fromExpression(node,node.source),ExportNamedDeclaration:node=>fromExpression(node,node.source),ExportAllDeclaration:node=>fromExpression(node,node.source),TSImportEqualsDeclaration:node=>{if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){fromExpression(node,node.moduleReference.expression)}},CallExpression:node=>{if(!isRequireCallee(sourceCode,node.callee))return;fromExpression(node,node.arguments[0])}}}const THIRD_PARTY_CRYPTO_LIBS=new Set(["crypto-js","cryptojs","sjcl","forge","node-forge","jsencrypt","js-sha256","js-sha512","js-sha3","js-md5","js-sha1","blueimp-md5","aes-js","md5","sha.js","hash.js"]);const PURE_JS_PASSWORD_HASH_LIBS=new Set(["bcryptjs","bcrypt-nodejs"]);exports.preferNativeCrypto=(0,eslint_devkit_1.createRule)({name:"prefer-native-crypto",meta:{interop:{runtimes:["eslint","oxlint"]},type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/prefer-native-crypto.md",description:"Prefer native crypto over third-party libraries",cwe:"CWE-1104",cvss:5.3},messages:{preferNative:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Third-party crypto library",cwe:"CWE-1104",description:"{{library}} is a third-party crypto library. Native crypto (Node.js crypto or Web Crypto API) is faster, more secure, and always maintained.",severity:"MEDIUM",fix:"Migrate to native crypto module",documentationLink:"https://nodejs.org/api/crypto.html"}),preferNativePasswordHash:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Pure-JS password hashing library",cwe:"CWE-1104",description:"{{library}} is a pure-JavaScript password hash. It is orders of magnitude slower than a native implementation, so the same cost factor buys far less protection, and its maintenance has repeatedly lagged the native bindings.",severity:"MEDIUM",fix:"Use the native `bcrypt` binding, or `argon2` (Argon2id) for new code. Do NOT reach for node:crypto's createHash here \u2014 it has no bcrypt, and a general-purpose digest is not a password hash (CWE-916). crypto.scrypt is the only node:crypto function in this category.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html"})},schema:[]},defaultOptions:[{}],create(context){function checkSpecifier(node,specifier){const lib=specifier.split("/")[0];if(PURE_JS_PASSWORD_HASH_LIBS.has(lib)){context.report({node,messageId:"preferNativePasswordHash",data:{library:lib}});return}if(THIRD_PARTY_CRYPTO_LIBS.has(lib)){context.report({node,messageId:"preferNative",data:{library:lib}})}}return moduleSpecifierListener(context.sourceCode,checkSpecifier)}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireAeadTagVerification=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireAeadTagVerification=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const module_binding_1=require("../../utils/module-binding");const AEAD_MODE=/-(gcm|ccm|ocb|poly1305)/;const STREAM_METHODS=new Set(["pipe","write","end","setEncoding"]);exports.requireAeadTagVerification=(0,eslint_devkit_1.createRule)({name:"require-aead-tag-verification",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/require-aead-tag-verification.md",description:"Require AEAD decryption to verify the authentication tag (setAuthTag + final)",cwe:"CWE-327",cvss:7.5},hasSuggestions:false,messages:{missingAuthTag:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"AEAD decryption without setAuthTag",cwe:"CWE-327",description:"An AEAD decipher (GCM/CCM/OCB/ChaCha20-Poly1305) is created but setAuthTag() is never called, so the authentication tag is never checked. Forged or tampered ciphertext decrypts as if it were authentic.",severity:"HIGH",fix:"Call decipher.setAuthTag(tag) with the tag produced at encryption time, then decipher.final()",documentationLink:"https://nodejs.org/api/crypto.html#decipher_setauthtagbuffer"}),missingFinal:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"AEAD decryption never calls final()",cwe:"CWE-327",description:"setAuthTag() was called but decipher.final() never is. final() is the call that compares the tag and throws on mismatch \u2014 without it the tag is loaded and then ignored, so update() returns unauthenticated plaintext.",severity:"HIGH",fix:"Append decipher.final() to the decryption and let it throw on a tag mismatch",documentationLink:"https://nodejs.org/api/crypto.html#decipherfinaloutputencoding"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unverified AEAD decryption in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function isCreateDecipheriv(callee){return(0,module_binding_1.calleeNameOn)(callee,context.sourceCode.getScope(callee),"crypto")==="createDecipheriv"}function isAeadAlgorithm(argument){return argument!==void 0&&argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"&&AEAD_MODE.test(argument.value.toLowerCase())}function collectMethods(variable){const methods=new Set;for(const reference of variable.references){const identifier=reference.identifier;const parent=identifier.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator)continue;const method=(0,eslint_devkit_1.memberPropertyName)(parent);if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===identifier&&method!==null){methods.add(method);continue}return null}return methods}function checkVariableDeclarator(node){if(isTestFile)return;if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const init=node.init;if(!init||init.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return;if(!isCreateDecipheriv(init.callee))return;if(!isAeadAlgorithm(init.arguments[0]))return;const[variable]=context.sourceCode.getDeclaredVariables(node);const methods=collectMethods(variable);if(methods===null)return;if(!methods.has("setAuthTag")){context.report({node:init,messageId:"missingAuthTag"});return}const drivenAsStream=[...methods].some(name=>STREAM_METHODS.has(name));if(!methods.has("final")&&!drivenAsStream){context.report({node:init,messageId:"missingFinal"})}}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename)},VariableDeclarator:checkVariableDeclarator}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireDependencyIntegrity=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const RESOURCE_TAG=/<(script|link)\b(?:"[^"]*"|'[^']*'|[^>"'])*>/gi;const TAG_ATTRIBUTE=/
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireDependencyIntegrity=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const RESOURCE_TAG=/<(script|link)\b(?:"[^"]*"|'[^']*'|[^>"'])*>/gi;const TAG_ATTRIBUTE=/[\s/]([a-z][a-z0-9-]*)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi;const CDN_HOSTS=["cdn.","cdnjs.","unpkg.","jsdelivr."];const SRI_LINK_RELS=new Set(["stylesheet","modulepreload"]);const SRI_PRELOAD_DESTINATIONS=new Set(["style","script"]);function attributesOf(tag){const attributes=new Map;for(const match of tag.matchAll(TAG_ATTRIBUTE)){const raw=match[2];const quoted=raw.startsWith('"')||raw.startsWith("'");attributes.set(match[1].toLowerCase(),quoted?raw.slice(1,-1):raw)}return attributes}function hostOf(url){const match=/^\s*(?:[a-z][a-z0-9+.-]*:)?\/\/([^/?#]*)/i.exec(url);return match?.[1].toLowerCase()}function linkTakesIntegrity(attributes){const relations=(attributes.get("rel")??"").toLowerCase().match(/\S+/g);if(relations===null)return true;if(relations.some(value=>SRI_LINK_RELS.has(value)))return true;if(!relations.includes("preload"))return false;return SRI_PRELOAD_DESTINATIONS.has((attributes.get("as")??"").toLowerCase())}function hasUnprotectedCdnTag(text){for(const match of text.matchAll(RESOURCE_TAG)){const isScript=match[1].toLowerCase()==="script";if(isUnprotectedCdnResource(isScript,attributesOf(match[0])))return true}return false}function isUnprotectedCdnResource(isScript,attributes){const url=attributes.get(isScript?"src":"href");if(url===void 0)return false;const host=hostOf(url);if(host===void 0)return false;if(!CDN_HOSTS.some(fragment=>host.includes(fragment)))return false;if(!isScript&&!linkTakesIntegrity(attributes))return false;return!attributes.has("integrity")}exports.requireDependencyIntegrity=(0,eslint_devkit_1.createRule)({name:"require-dependency-integrity",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/require-dependency-integrity.md",description:"Require SRI (Subresource Integrity) for CDN resources",cwe:"CWE-494",cvss:8.1},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing SRI",cwe:"CWE-494",description:"External resource loaded without integrity hash - supply chain risk",severity:"HIGH",fix:'Add integrity="sha384-..." and crossorigin="anonymous" attributes',documentationLink:"https://cwe.mitre.org/data/definitions/494.html"})},schema:[]},defaultOptions:[],createOnce(context){function report(node){context.report({node,messageId:"violationDetected"})}const renderTemplate=node=>{let text=node.quasis[0].value.cooked??node.quasis[0].value.raw;for(const[index,expression]of node.expressions.entries()){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,expression);text+=resolved===null?"\0":resolved.value;text+=node.quasis[index+1].value.cooked??node.quasis[index+1].value.raw}return text};const jsxAttributeValue=value=>{if(value===null)return"";if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return String(value.value);if(value.type!==eslint_devkit_1.AST_NODE_TYPES.JSXExpressionContainer)return null;const expression=value.expression;if(expression.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const rendered=renderTemplate(expression);return rendered.includes("\0")?null:rendered}return(0,const_value_1.resolveConstantString)(context.sourceCode,expression)?.value??null};return{Literal(node){if(typeof node.value!=="string")return;if(hasUnprotectedCdnTag(node.value))report(node)},TemplateLiteral(node){if(hasUnprotectedCdnTag(renderTemplate(node)))report(node)},JSXOpeningElement(node){if(node.name.type!==eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier)return;const tag=node.name.name;if(tag!=="script"&&tag!=="link")return;const attributes=new Map;for(const attribute of node.attributes){if(attribute.type!==eslint_devkit_1.AST_NODE_TYPES.JSXAttribute||attribute.name.type!==eslint_devkit_1.AST_NODE_TYPES.JSXIdentifier){return}const name=attribute.name.name.toLowerCase();const value=jsxAttributeValue(attribute.value);if(value===null&&name==="rel")return;attributes.set(name,value??"")}if(isUnprotectedCdnResource(tag==="script",attributes)){report(node)}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireSecureDeletion=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const SENSITIVE_PROPERTY_NAMES=["password","passwd","pwd","passphrase","secret","token","jwt","bearer","credential","api key","secret key","private key","signing key","encryption key","access key","session id","ssn","credit card","card number","cvv"];function isSensitiveName(name,phrases){const words=(0,eslint_devkit_1.identifierWords)(name);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireSecureDeletion=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const SENSITIVE_PROPERTY_NAMES=["password","passwd","pwd","passphrase","secret","token","jwt","bearer","credential","api key","secret key","private key","signing key","encryption key","access key","session id","ssn","credit card","card number","cvv"];function isSensitiveName(name,phrases){const words=(0,eslint_devkit_1.identifierWords)(name);return phrases.some(phrase=>{const needle=(0,eslint_devkit_1.identifierWords)(phrase);if(needle.length===0)return false;const start=words.length-needle.length;return needle.every((word,offset)=>words[start+offset]===word)})}exports.requireSecureDeletion=(0,eslint_devkit_1.createRule)({name:"require-secure-deletion",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/require-secure-deletion.md",description:"Require secure data deletion patterns",cwe:"CWE-459",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Incomplete Secret Cleanup",cwe:"CWE-459",description:"`delete` on the sensitive property `{{property}}` unbinds it without scrubbing the value",severity:"MEDIUM",fix:"Overwrite the value before deleting it (obj.{{property}} = undefined, or zero-fill the Buffer), and make sure no copy of the object was spread, logged, or serialised first",documentationLink:"https://cwe.mitre.org/data/definitions/459.html"})},schema:[{type:"object",properties:{sensitiveProperties:{type:"array",items:{type:"string"},default:[...SENSITIVE_PROPERTY_NAMES],description:"Replace the built-in sensitive-property vocabulary. Takes precedence over additionalSensitiveProperties."},additionalSensitiveProperties:{type:"array",items:{type:"string"},default:[],description:'Extra sensitive property names, matched as whole words at the END of the name. "pin code", "pin_code" and "pinCode" all match a property called pinCode; "pincode" does not.'}},additionalProperties:false}]},defaultOptions:[{additionalSensitiveProperties:[],sensitiveProperties:[...SENSITIVE_PROPERTY_NAMES]}],createOnce(context,currentOptions){let phrases;function deletedPropertyName(node){const argument=node.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?node.expression:node;if(argument.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return void 0;const property=argument.property;if(!argument.computed&&property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return property.name;const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,property);return resolved?.value}function reportIfSensitive(node,property){if(!property)return;if(!isSensitiveName(property,phrases))return;context.report({node,messageId:"violationDetected",data:{property}})}return{before(){const[options={}]=currentOptions();const{additionalSensitiveProperties=[],sensitiveProperties=SENSITIVE_PROPERTY_NAMES}=options;phrases=[...sensitiveProperties,...additionalSensitiveProperties]},UnaryExpression(node){if(node.operator!=="delete")return;reportIfSensitive(node,deletedPropertyName(node.argument))},CallExpression(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||callee.object.name!=="Reflect"||(0,eslint_devkit_1.propertyName)(callee)!=="deleteProperty"){return}const key=node.arguments[1];if(!key)return;reportIfSensitive(node,(0,const_value_1.resolveConstantString)(context.sourceCode,key)?.value)}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireStorageEncryption=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const credential_evidence_1=require("../../utils/credential-evidence");exports.requireStorageEncryption=(0,eslint_devkit_1.createRule)({name:"require-storage-encryption",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/require-storage-encryption.md",description:"Require encryption for persistent storage",cwe:"CWE-312",cvss:5.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-312",description:"Require encryption for persistent storage detected - Storage without encryption",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/312.html"})},schema:[]},defaultOptions:[],createOnce(context){return{CallExpression(node){if(!(0,credential_evidence_1.isFileWrite)(node))return;if(!(0,credential_evidence_1.storesACredential)(node)||(0,credential_evidence_1.isEncrypted)(node,context.sourceCode))return;context.report({node,messageId:"violationDetected"})}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireStorageEncryption=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const credential_evidence_1=require("../../utils/credential-evidence");exports.requireStorageEncryption=(0,eslint_devkit_1.createRule)({name:"require-storage-encryption",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/require-storage-encryption.md",description:"Require encryption for persistent storage",cwe:"CWE-312",cvss:5.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-312",description:"Require encryption for persistent storage detected - Storage without encryption",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/312.html"})},schema:[]},defaultOptions:[],createOnce(context){return{CallExpression(node){if(!(0,credential_evidence_1.isFileWrite)(node,context.sourceCode))return;if(!(0,credential_evidence_1.storesACredential)(node)||(0,credential_evidence_1.isEncrypted)(node,context.sourceCode))return;context.report({node,messageId:"violationDetected"})}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireStreamErrorHandler=void 0;exports.calleeMethodName=calleeMethodName;exports.constructsStream=constructsStream;const eslint_devkit_1=require("@interlace/eslint-devkit");const STREAM_CONSTRUCTORS=new Set(["createReadStream","createWriteStream","createGzip","createGunzip","createDeflate","createInflate","createBrotliCompress","createBrotliDecompress"]);const LISTENER_METHODS=new Set(["on","once","addListener","prependListener","prependOnceListener"]);function calleeMethodName(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(0,eslint_devkit_1.propertyName)(callee)??void 0}return void 0}function constructsStream(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const name=calleeMethodName(node.callee);return name!==void 0&&STREAM_CONSTRUCTORS.has(name)}exports.requireStreamErrorHandler=(0,eslint_devkit_1.createRule)({name:"require-stream-error-handler",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/require-stream-error-handler.md",description:"Require an 'error' listener on streams passed to .pipe(), which does not forward errors",cwe:"CWE-248",cvss:7.5},messages:{unhandledStreamError:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unhandled stream error",cwe:"CWE-248",description:".pipe() forwards data but not errors. A stream that emits 'error' with no listener throws inside the EventEmitter, which is an uncaught exception \u2014 the process exits. A single request for a missing or unreadable file is enough to stop the server.",severity:"HIGH",fix:"Attach stream.on('error', handler) before piping, or use pipeline(), which destroys every stream and reports the failure.",documentationLink:"https://cwe.mitre.org/data/definitions/248.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow unhandled stream errors in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],createOnce(context,currentOptions){let handled;let streamBindings;let pending;function unhandledStream(node){if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireStreamErrorHandler=void 0;exports.calleeMethodName=calleeMethodName;exports.constructsStream=constructsStream;const eslint_devkit_1=require("@interlace/eslint-devkit");const STREAM_CONSTRUCTORS=new Set(["createReadStream","createWriteStream","createGzip","createGunzip","createDeflate","createInflate","createBrotliCompress","createBrotliDecompress"]);const STREAM_CLASSES=new Set(["PassThrough","Transform","Readable","Writable","Duplex"]);const LISTENER_METHODS=new Set(["on","once","addListener","prependListener","prependOnceListener"]);function calleeMethodName(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(0,eslint_devkit_1.propertyName)(callee)??void 0}return void 0}function constructsStream(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const name=calleeMethodName(node.callee);return name!==void 0&&STREAM_CONSTRUCTORS.has(name)}exports.requireStreamErrorHandler=(0,eslint_devkit_1.createRule)({name:"require-stream-error-handler",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/require-stream-error-handler.md",description:"Require an 'error' listener on streams passed to .pipe(), which does not forward errors",cwe:"CWE-248",cvss:7.5},messages:{unhandledStreamError:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unhandled stream error",cwe:"CWE-248",description:".pipe() forwards data but not errors. A stream that emits 'error' with no listener throws inside the EventEmitter, which is an uncaught exception \u2014 the process exits. A single request for a missing or unreadable file is enough to stop the server.",severity:"HIGH",fix:"Attach stream.on('error', handler) before piping, or use pipeline(), which destroys every stream and reports the failure.",documentationLink:"https://cwe.mitre.org/data/definitions/248.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true,description:"Allow unhandled stream errors in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],createOnce(context,currentOptions){let handled;let escaped;let streamBindings;let pending;function unhandledStream(node){if(constructsStreamHere(node))return node;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(!streamBindings.has(node.name))return null;if(handled.has(node.name)||escaped.has(node.name))return null;return node}function constructsStreamHere(node){if(constructsStream(node))return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression)return false;const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,context.sourceCode.getScope(node));const name=binding?.path.at(-1);return binding?.module==="stream"&&binding.path.length===1&&name!==void 0&&STREAM_CLASSES.has(name)}return{before(){const[options={}]=currentOptions();const{allowInTests=true}=options;if(allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename)){return false}handled=new Set;escaped=new Set;streamBindings=new Set;pending=[];return true},VariableDeclarator(node){if(node.init!==null&&node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&constructsStreamHere(node.init)){streamBindings.add(node.id.name)}},CallExpression(node){const callee=node.callee;const isPipe=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee)==="pipe";if(!isPipe){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){escaped.add(argument.name)}}}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return;if(LISTENER_METHODS.has(method)){const event=node.arguments[0];if(event?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&event.value==="error"&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){handled.add(callee.object.name)}return}if(method!=="pipe")return;pending.push({node,offender:node})},"Program:exit"(){for(const{node}of pending){const callee=node.callee;const source=unhandledStream(callee.object);const destinationArg=node.arguments[0];const destination=destinationArg===void 0?null:unhandledStream(destinationArg);const offender=source??destination;if(offender===null)continue;context.report({node:offender,messageId:"unhandledStreamError"})}}}}});
|