eslint-plugin-secure-coding 5.5.1 → 5.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/index.js +1 -1
- package/src/rules/detect-object-injection/index.js +1 -1
- package/src/rules/no-directive-injection/index.js +1 -1
- package/src/rules/no-format-string-injection/index.js +1 -1
- package/src/rules/no-hardcoded-credentials/index.js +1 -1
- package/src/rules/no-pii-in-logs/index.js +1 -1
- package/src/rules/no-sql-injection/index.js +1 -1
- package/src/rules/no-template-injection/index.js +1 -1
- package/src/rules/no-unchecked-loop-condition/index.js +1 -1
- package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
- package/src/rules/no-unsafe-deserialization/index.js +1 -1
- package/src/rules/no-weak-password-recovery/index.js +1 -1
- package/src/rules/no-xpath-injection/index.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDeserialization=void 0;const node_fs_1=require("node:fs");const node_path_1=require("node:path");const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const GLOBAL_ONLY_SINKS=new Set(["eval","Function"]);function isLocallyBoundIn(identifier,sourceCode){for(let scope=sourceCode.getScope(identifier);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(variable!==void 0)return variable.defs.length>0}return false}const GLOBAL_OBJECTS=new Set(["window","globalThis","global","self"]);const TIMER_FUNCTIONS=new Set(["setTimeout","setInterval"]);const MODULE_SINKS={"js-yaml":new Set(["load","loadAll"]),"node-serialize":new Set(["unserialize"]),funcster:new Set(["deserialize","deepDeserialize"]),v8:new Set(["deserialize"])};const ALWAYS_UNSAFE_MODULES=new Set(["node-serialize","funcster"]);const majorCache=new Map;function declaredMajorFrom(startDir,pkg){const cacheKey=`${startDir}\0${pkg}`;const cached=majorCache.get(cacheKey);if(cached!==void 0)return cached;let dir=startDir;let found=0;for(let depth=0;depth<12;depth++){try{const manifest=JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(dir,"package.json"),"utf8"));const range=manifest.dependencies?.[pkg]??manifest.devDependencies?.[pkg]??manifest.peerDependencies?.[pkg];if(typeof range==="string"){const digits=/(\d+)/.exec(range);if(digits!==null)found=Number(digits[1]);break}}catch{}const parent=(0,node_path_1.dirname)(dir);if(parent===dir)break;dir=parent}majorCache.set(cacheKey,found);return found}const DEFAULT_SAFE_YAML_SCHEMAS=["JSON_SCHEMA","CORE_SCHEMA","FAILSAFE_SCHEMA"];const DEFAULT_NON_EXECUTING_PACKAGES=["yaml","bson","cbor","msgpackr","@msgpack/msgpack","protobufjs"];function isStringValued(arg){if(!arg)return false;if(arg.type==="Literal")return typeof arg.value==="string";if(arg.type==="TemplateLiteral")return true;if(arg.type==="BinaryExpression"&&arg.operator==="+"){return isStringValued(arg.left)||isStringValued(arg.right)}return false}exports.noUnsafeDeserialization=(0,eslint_devkit_1.createRule)({name:"no-unsafe-deserialization",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-deserialization.md",description:"Detects unsafe deserialization of untrusted data",cwe:"CWE-502"},fixable:"code",hasSuggestions:true,messages:{unsafeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Deserialization",cwe:"CWE-502",description:"Unsafe deserialization of untrusted data (incl. model/tool output)",severity:"{{severity}}",fix:"{{safeAlternative}} | validate model/tool output via schema and size limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),dangerousEvalUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous eval() Usage",cwe:"CWE-502",description:"eval() used for deserialization (code execution vulnerability)",severity:"CRITICAL",fix:"Use JSON.parse() or safe deserialization libraries",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),unsafeYamlParsing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe YAML Parsing",cwe:"CWE-502",description:"YAML parsing may execute code during deserialization",severity:"HIGH",fix:"Use yaml.safeLoad() or disable code execution",documentationLink:"https://www.npmjs.com/package/js-yaml#loadstr---options-"}),dangerousFunctionConstructor:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Function Constructor",cwe:"CWE-502",description:"Function constructor used with untrusted data",severity:"CRITICAL",fix:"Avoid Function constructor with user input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"}),useSafeDeserializer:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Safe Deserializer",description:"Use safe deserialization libraries",severity:"LOW",fix:"Use JSON.parse, safe-json-parse, or validated libraries",documentationLink:"https://www.npmjs.com/package/safe-json-parse"})},schema:[{type:"object",properties:{dangerousFunctions:{type:"array",items:{type:"string"},default:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],description:"Functions that execute or deserialize untrusted input"},validationFunctions:{type:"array",items:{type:"string"},default:["validateInput","sanitizeData","checkSchema","validateSchema"],description:"Function names that count as input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe deserializers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},safeYamlSchemas:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_YAML_SCHEMAS,description:"js-yaml schema exports that make `load` inert, matched against a resolved js-yaml binding. Add DEFAULT_SCHEMA on a repository pinned to js-yaml v4. Replaces the built-in list."},additionalSafeYamlSchemas:{type:"array",items:{type:"string"},default:[],description:"Extra safe js-yaml schema exports, on top of `safeYamlSchemas`."},nonExecutingPackages:{type:"array",items:{type:"string"},default:DEFAULT_NON_EXECUTING_PACKAGES,description:"Packages whose parse entry point cannot execute code or instantiate a payload-named type, matched against a resolved import binding. Replaces the built-in list."},additionalNonExecutingPackages:{type:"array",items:{type:"string"},default:[],description:"Extra non-executing packages, on top of `nonExecutingPackages`."}},additionalProperties:false}]},defaultOptions:[{dangerousFunctions:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions:["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false,safeYamlSchemas:DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas:[],nonExecutingPackages:DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages:[]}],createOnce(context){let dangerousFunctions;let validationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let safeYamlSchemas;let additionalSafeYamlSchemas;let nonExecutingPackages;let additionalNonExecutingPackages;let safeSchemas;let inertPackages;let sourceCode;let filename;let safetyChecker;let validatedVariables;let untrustedVariables;let literalPathFileVars;const pinsSafeYamlSchema=node=>{const optionsArg=node.arguments[1];if(optionsArg?.type!=="ObjectExpression")return false;return optionsArg.properties.some(property=>{if(property.type!=="Property"||property.computed)return false;if(property.key.type!=="Identifier"||property.key.name!=="schema"){return false}const schema=(0,eslint_devkit_1.resolveModuleBinding)(property.value,sourceCode.getScope(property.value));return schema?.module==="js-yaml"&&safeSchemas.has(schema.path.at(-1)??"")})};const isDangerousDeserialization=node=>{const callee=node.callee;const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));if(binding){const sinks=MODULE_SINKS[binding.module];if(sinks&&binding.path.some(segment=>sinks.has(segment))){if(binding.module==="js-yaml"&&declaredMajorFrom((0,node_path_1.dirname)(context.filename),"js-yaml")>=4){return false}return!pinsSafeYamlSchema(node)}if(inertPackages.has(binding.module))return false}if(callee.type==="Identifier"&&dangerousFunctions.includes(callee.name)){if(TIMER_FUNCTIONS.has(callee.name)){return isStringValued(node.arguments[0])}if(!isGlobalBinding(callee))return false;return true}if(callee.type==="MemberExpression"){const memberName=(0,eslint_devkit_1.propertyName)(callee)??"";const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(callee.object.type==="Super"||callee.object.type==="ThisExpression"){return false}if(TIMER_FUNCTIONS.has(memberName)){return isStringValued(node.arguments[0])}if(objectName==="JSON"&&memberName==="parse"||objectName==="yaml"&&memberName==="safeLoad"){return false}if(GLOBAL_ONLY_SINKS.has(memberName)){if(!GLOBAL_OBJECTS.has(objectName))return false;const object=callee.object;return object.type==="Identifier"&&!isLocallyBoundIn(object,sourceCode)}if(dangerousFunctions.includes(memberName)){return true}if(["yaml","js-yaml","node-serialize","serialize-javascript"].includes(objectName.toLowerCase())&&["load","parse","unserialize","deserialize"].includes(memberName)){return true}}if(callee.type==="Identifier"&&callee.name==="require"){const args=node.arguments;if(args.length>0&&args[0].type==="Literal"&&typeof args[0].value==="string"){const moduleName=args[0].value.toLowerCase();if(["node-serialize","serialize-javascript","yaml","js-yaml"].includes(moduleName)){return true}}}return false};const isUntrustedInput=inputNode=>{const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(inputNode);if(bare!==inputNode)return isUntrustedInput(bare);if(inputNode.type==="BinaryExpression"&&inputNode.operator==="+"){return isUntrustedInput(inputNode.left)||isUntrustedInput(inputNode.right)}if(inputNode.type==="TemplateLiteral"){return inputNode.expressions.some(e=>isUntrustedInput(e))}if(inputNode.type==="AwaitExpression"){return isUntrustedInput(inputNode.argument)}if(inputNode.type==="CallExpression"){const callee=inputNode.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)!==null){if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["text","json","arrayBuffer","formData","blob"])){return true}if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["readFile","readFileSync"])){return true}if(isUntrustedInput(callee.object)){return true}}return inputNode.arguments.some(arg=>arg.type!=="SpreadElement"&&isUntrustedInput(arg))}if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"){return true}}if(inputNode.type==="Identifier"){if(untrustedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;if(func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})){return true}}current=current.parent}}return false};const isInsideDeserializerImplementation=node=>{const DESERIALIZER_NAMES=new Set(["deserialize","unserialize","fromJSON","fromBuffer"]);let current=node.parent;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const fn=current;if("id"in fn&&fn.id?.name&&DESERIALIZER_NAMES.has(fn.id.name))return true;const owner=fn.parent;if(owner?.type==="MethodDefinition"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="Property"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="VariableDeclarator"&&owner.id.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.id.name))return true}current=current.parent}return false};const isAlwaysUnsafeSink=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node.callee));return binding!==void 0&&ALWAYS_UNSAFE_MODULES.has(binding.module)};const isGlobalBinding=identifier=>{let scope=sourceCode.getScope(identifier);while(scope){const found=scope.variables.find(v=>v.name===identifier.name);if(found)return found.defs.length===0;scope=scope.upper}return true};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"&&isGlobalBinding(node.callee)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));if(hasUntrustedInput){if(safetyChecker.isSafe(node,context))return;context.report({node,messageId:"dangerousFunctionConstructor",data:{filePath:context.filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Avoid dynamic function creation"}});return}}if(isDangerousDeserialization(node)&&!isInsideDeserializerImplementation(node)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg))||isAlwaysUnsafeSink(node);if(hasUntrustedInput){const safe=safetyChecker.isSafe(node,context);if(!safe){let messageId="unsafeDeserialization";const calleeText=sourceCode.getText(node.callee);if(calleeText.includes("yaml")||calleeText.includes("YAML")){messageId="unsafeYamlParsing"}if(node.callee.type==="Identifier"&&["eval","setTimeout","setInterval"].includes(node.callee.name)){messageId="dangerousEvalUsage"}context.report({node,messageId,data:{library:calleeText,filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use JSON.parse() or validated safe deserialization libraries"},suggest:messageId==="dangerousEvalUsage"?[{messageId:"useSafeDeserializer",fix:fixer=>{return fixer.replaceText(node,`JSON.parse(${sourceCode.getText(node.arguments[0])})`)}}]:void 0})}}}};return{before(){const options=context.options[0]||{};({dangerousFunctions=["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions=["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false,safeYamlSchemas=DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas=[],nonExecutingPackages=DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages=[]}=options);safeSchemas=new Set([...safeYamlSchemas,...additionalSafeYamlSchemas]);inertPackages=new Set([...nonExecutingPackages,...additionalNonExecutingPackages]);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});validatedVariables=new Set;untrustedVariables=new Set;literalPathFileVars=new Set},VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){if(isUntrustedInput(declarator.init)){untrustedVariables.add(declarator.id.name)}if(declarator.init.type==="CallExpression"){const callee=declarator.init.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["readFile","readFileSync"])){untrustedVariables.add(declarator.id.name);const pathArg=declarator.init.arguments[0];if(pathArg?.type==="Literal"&&typeof pathArg.value==="string"){literalPathFileVars.add(declarator.id.name)}}}}}},AssignmentExpression(node){if(node.left.type==="Identifier"&&isUntrustedInput(node.right)){untrustedVariables.add(node.left.name)}},CallExpression(node){checkCallExpression(node)},NewExpression(node){checkCallExpression(node)},VariableDeclarator(node){if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(validationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(node.id.name)}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDeserialization=void 0;const node_fs_1=require("node:fs");const node_path_1=require("node:path");const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const GLOBAL_ONLY_SINKS=new Set(["eval","Function"]);function isLocallyBoundIn(identifier,sourceCode){for(let scope=sourceCode.getScope(identifier);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(variable!==void 0)return variable.defs.length>0}return false}const GLOBAL_OBJECTS=new Set(["window","globalThis","global","self"]);const TIMER_FUNCTIONS=new Set(["setTimeout","setInterval"]);const MODULE_SINKS={"js-yaml":new Set(["load","loadAll"]),"node-serialize":new Set(["unserialize"]),funcster:new Set(["deserialize","deepDeserialize"]),v8:new Set(["deserialize"])};const ALWAYS_UNSAFE_MODULES=new Set(["node-serialize","funcster"]);const majorCache=new Map;function declaredMajorFrom(startDir,pkg){const cacheKey=`${startDir}\0${pkg}`;const cached=majorCache.get(cacheKey);if(cached!==void 0)return cached;let dir=startDir;let found=0;for(let depth=0;depth<12;depth++){try{const manifest=JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(dir,"package.json"),"utf8"));const range=manifest.dependencies?.[pkg]??manifest.devDependencies?.[pkg]??manifest.peerDependencies?.[pkg];if(typeof range==="string"){const digits=/(\d+)/.exec(range);if(digits!==null)found=Number(digits[1]);break}}catch{}const parent=(0,node_path_1.dirname)(dir);if(parent===dir)break;dir=parent}majorCache.set(cacheKey,found);return found}const DEFAULT_SAFE_YAML_SCHEMAS=["JSON_SCHEMA","CORE_SCHEMA","FAILSAFE_SCHEMA"];const DEFAULT_NON_EXECUTING_PACKAGES=["yaml","bson","cbor","msgpackr","@msgpack/msgpack","protobufjs"];function isStringValued(arg){if(!arg)return false;if(arg.type==="Literal")return typeof arg.value==="string";if(arg.type==="TemplateLiteral")return true;if(arg.type==="BinaryExpression"&&arg.operator==="+"){return isStringValued(arg.left)||isStringValued(arg.right)}return false}exports.noUnsafeDeserialization=(0,eslint_devkit_1.createRule)({name:"no-unsafe-deserialization",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-deserialization.md",description:"Detects unsafe deserialization of untrusted data",cwe:"CWE-502"},fixable:"code",hasSuggestions:true,messages:{unsafeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Deserialization",cwe:"CWE-502",description:"Unsafe deserialization of untrusted data (incl. model/tool output)",severity:"{{severity}}",fix:"{{safeAlternative}} | validate model/tool output via schema and size limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),dangerousEvalUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous eval() Usage",cwe:"CWE-502",description:"eval() used for deserialization (code execution vulnerability)",severity:"CRITICAL",fix:"Use JSON.parse() or safe deserialization libraries",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),unsafeYamlParsing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe YAML Parsing",cwe:"CWE-502",description:"YAML parsing may execute code during deserialization",severity:"HIGH",fix:"Use yaml.safeLoad() or disable code execution",documentationLink:"https://www.npmjs.com/package/js-yaml#loadstr---options-"}),dangerousFunctionConstructor:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Function Constructor",cwe:"CWE-502",description:"Function constructor used with untrusted data",severity:"CRITICAL",fix:"Avoid Function constructor with user input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"}),useSafeDeserializer:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Safe Deserializer",description:"Use safe deserialization libraries",severity:"LOW",fix:"Use JSON.parse, safe-json-parse, or validated libraries",documentationLink:"https://www.npmjs.com/package/safe-json-parse"})},schema:[{type:"object",properties:{dangerousFunctions:{type:"array",items:{type:"string"},default:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],description:"Functions that execute or deserialize untrusted input"},validationFunctions:{type:"array",items:{type:"string"},default:["validateInput","sanitizeData","checkSchema","validateSchema"],description:"Function names that count as input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe deserializers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},safeYamlSchemas:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_YAML_SCHEMAS,description:"js-yaml schema exports that make `load` inert, matched against a resolved js-yaml binding. Add DEFAULT_SCHEMA on a repository pinned to js-yaml v4. Replaces the built-in list."},additionalSafeYamlSchemas:{type:"array",items:{type:"string"},default:[],description:"Extra safe js-yaml schema exports, on top of `safeYamlSchemas`."},nonExecutingPackages:{type:"array",items:{type:"string"},default:DEFAULT_NON_EXECUTING_PACKAGES,description:"Packages whose parse entry point cannot execute code or instantiate a payload-named type, matched against a resolved import binding. Replaces the built-in list."},additionalNonExecutingPackages:{type:"array",items:{type:"string"},default:[],description:"Extra non-executing packages, on top of `nonExecutingPackages`."}},additionalProperties:false}]},defaultOptions:[{dangerousFunctions:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions:["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false,safeYamlSchemas:DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas:[],nonExecutingPackages:DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages:[]}],createOnce(context){let dangerousFunctions;let validationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let safeYamlSchemas;let additionalSafeYamlSchemas;let nonExecutingPackages;let additionalNonExecutingPackages;let safeSchemas;let inertPackages;let sourceCode;let filename;let safetyChecker;let validatedVariables;let untrustedVariables;let literalPathFileVars;const pinsSafeYamlSchema=node=>{const optionsArg=node.arguments[1];if(optionsArg?.type!=="ObjectExpression")return false;return optionsArg.properties.some(property=>{if(property.type!=="Property"||property.computed)return false;if(property.key.type!=="Identifier"||property.key.name!=="schema"){return false}const schema=(0,eslint_devkit_1.resolveModuleBinding)(property.value,sourceCode.getScope(property.value));return schema?.module==="js-yaml"&&safeSchemas.has(schema.path.at(-1)??"")})};const isDangerousDeserialization=node=>{const callee=node.callee;const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));if(binding){const sinks=MODULE_SINKS[binding.module];if(sinks&&binding.path.some(segment=>sinks.has(segment))){if(binding.module==="js-yaml"&&declaredMajorFrom((0,node_path_1.dirname)(context.filename),"js-yaml")>=4){return false}return!pinsSafeYamlSchema(node)}if(inertPackages.has(binding.module))return false}if(callee.type==="Identifier"&&dangerousFunctions.includes(callee.name)){if(TIMER_FUNCTIONS.has(callee.name)){return isStringValued(node.arguments[0])}if(!isGlobalBinding(callee))return false;return true}if(callee.type==="MemberExpression"){const memberName=(0,eslint_devkit_1.propertyName)(callee)??"";const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(callee.object.type==="Super"||callee.object.type==="ThisExpression"){return false}if(TIMER_FUNCTIONS.has(memberName)){return isStringValued(node.arguments[0])}if(objectName==="JSON"&&memberName==="parse"||objectName==="yaml"&&memberName==="safeLoad"){return false}if(GLOBAL_ONLY_SINKS.has(memberName)){if(!GLOBAL_OBJECTS.has(objectName))return false;const object=callee.object;return object.type==="Identifier"&&!isLocallyBoundIn(object,sourceCode)}if(dangerousFunctions.includes(memberName)){return true}if(["yaml","js-yaml","node-serialize","serialize-javascript"].includes(objectName.toLowerCase())&&["load","parse","unserialize","deserialize"].includes(memberName)){return true}}if(callee.type==="Identifier"&&callee.name==="require"){const args=node.arguments;if(args.length>0&&args[0].type==="Literal"&&typeof args[0].value==="string"){const moduleName=args[0].value.toLowerCase();if(["node-serialize","serialize-javascript","yaml","js-yaml"].includes(moduleName)){return true}}}return false};const isUntrustedInput=inputNode=>{const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(inputNode);if(bare!==inputNode)return isUntrustedInput(bare);if(inputNode.type==="BinaryExpression"&&inputNode.operator==="+"){return isUntrustedInput(inputNode.left)||isUntrustedInput(inputNode.right)}if(inputNode.type==="TemplateLiteral"){return inputNode.expressions.some(e=>isUntrustedInput(e))}if(inputNode.type==="AwaitExpression"){return isUntrustedInput(inputNode.argument)}if(inputNode.type==="CallExpression"){const callee=inputNode.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)!==null){if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["text","json","arrayBuffer","formData","blob"])){return true}if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["readFile","readFileSync"])){return true}if(isUntrustedInput(callee.object)){return true}}return inputNode.arguments.some(arg=>arg.type!=="SpreadElement"&&isUntrustedInput(arg))}if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"){return true}}if(inputNode.type==="Identifier"){if(untrustedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;if(func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})){return true}}current=current.parent}}return false};const isInsideDeserializerImplementation=node=>{const DESERIALIZER_NAMES=new Set(["deserialize","unserialize","fromJSON","fromBuffer"]);let current=node.parent;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const fn=current;if("id"in fn&&fn.id?.name&&DESERIALIZER_NAMES.has(fn.id.name))return true;const owner=fn.parent;if(owner?.type==="MethodDefinition"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="Property"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="VariableDeclarator"&&owner.id.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.id.name))return true}current=current.parent}return false};const isAlwaysUnsafeSink=node=>{const scope=sourceCode.getScope(node.callee);const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);return binding!==void 0&&ALWAYS_UNSAFE_MODULES.has(binding.module)&&node.arguments.some(arg=>!(0,eslint_devkit_1.isStaticExpression)({node:arg,scope}))};const isGlobalBinding=identifier=>{let scope=sourceCode.getScope(identifier);while(scope){const found=scope.variables.find(v=>v.name===identifier.name);if(found)return found.defs.length===0;scope=scope.upper}return true};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"&&isGlobalBinding(node.callee)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));if(hasUntrustedInput){if(safetyChecker.isSafe(node,context))return;context.report({node,messageId:"dangerousFunctionConstructor",data:{filePath:context.filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Avoid dynamic function creation"}});return}}if(isDangerousDeserialization(node)&&!isInsideDeserializerImplementation(node)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg))||isAlwaysUnsafeSink(node);if(hasUntrustedInput){const safe=safetyChecker.isSafe(node,context);if(!safe){let messageId="unsafeDeserialization";const calleeText=sourceCode.getText(node.callee);if(calleeText.includes("yaml")||calleeText.includes("YAML")){messageId="unsafeYamlParsing"}if(node.callee.type==="Identifier"&&["eval","setTimeout","setInterval"].includes(node.callee.name)){messageId="dangerousEvalUsage"}context.report({node,messageId,data:{library:calleeText,filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use JSON.parse() or validated safe deserialization libraries"},suggest:messageId==="dangerousEvalUsage"?[{messageId:"useSafeDeserializer",fix:fixer=>{return fixer.replaceText(node,`JSON.parse(${sourceCode.getText(node.arguments[0])})`)}}]:void 0})}}}};return{before(){const options=context.options[0]||{};({dangerousFunctions=["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions=["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false,safeYamlSchemas=DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas=[],nonExecutingPackages=DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages=[]}=options);safeSchemas=new Set([...safeYamlSchemas,...additionalSafeYamlSchemas]);inertPackages=new Set([...nonExecutingPackages,...additionalNonExecutingPackages]);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});validatedVariables=new Set;untrustedVariables=new Set;literalPathFileVars=new Set},VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){if(isUntrustedInput(declarator.init)){untrustedVariables.add(declarator.id.name)}if(declarator.init.type==="CallExpression"){const callee=declarator.init.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["readFile","readFileSync"])){untrustedVariables.add(declarator.id.name);const pathArg=declarator.init.arguments[0];if(pathArg?.type==="Literal"&&typeof pathArg.value==="string"){literalPathFileVars.add(declarator.id.name)}}}}}},AssignmentExpression(node){if(node.left.type==="Identifier"&&isUntrustedInput(node.right)){untrustedVariables.add(node.left.name)}},CallExpression(node){checkCallExpression(node)},NewExpression(node){checkCallExpression(node)},VariableDeclarator(node){if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(validationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(node.id.name)}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakPasswordRecovery=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const CREDENTIAL_GENERATORS=new Set(["randomBytes","randomUUID","randomInt","getRandomValues","nanoid","uuidv4"]);exports.noWeakPasswordRecovery=(0,eslint_devkit_1.createRule)({name:"no-weak-password-recovery",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-weak-password-recovery.md",description:"Detects weak password recovery mechanisms",cwe:"CWE-640"},messages:{missingRateLimit:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Rate Limit",cwe:"CWE-640",description:"Password recovery attempts not rate limited",severity:"HIGH",fix:"Implement rate limiting on recovery requests",documentationLink:"https://owasp.org/www-community/attacks/Brute_force_attack"}),predictableRecoveryToken:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Predictable Recovery Token",cwe:"CWE-640",description:"Recovery token can be predicted or guessed",severity:"CRITICAL",fix:"Use cryptographically secure random tokens",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),insufficientTokenEntropy:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insufficient Token Entropy",cwe:"CWE-640",description:"Recovery token has insufficient randomness",severity:"HIGH",fix:"Use at least 128-bit entropy for tokens",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),missingTokenExpiration:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Token Expiration",cwe:"CWE-640",description:"Recovery tokens never expire",severity:"HIGH",fix:"Implement token expiration (15-60 minutes)",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),recoveryLoggingSensitiveData:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Recovery Logging Sensitive Data",cwe:"CWE-640",description:"Logging sensitive data during password recovery",severity:"MEDIUM",fix:"Never log passwords, tokens, or sensitive recovery data",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"})},schema:[{type:"object",properties:{secureTokenFunctions:{type:"array",items:{type:"string"},default:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],description:"Functions that generate cryptographically secure tokens"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as secure"},trustedAnnotations:{type:"array",items:{type:"string"},default:["secure-recovery","rate-limited"],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{secureTokenFunctions:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers:[],trustedAnnotations:["secure-recovery","rate-limited"],strictMode:false}],createOnce(context){let secureTokenFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;const isRecoveryRelated=text=>{const lowerText=text.toLowerCase();const passwordKeywords=["password","pwd"];const recoveryKeywords=["reset","recover","forgot","restore"];const hasPasswordKeyword=passwordKeywords.some(keyword=>lowerText.includes(keyword));const hasRecoveryKeyword=recoveryKeywords.some(keyword=>lowerText.includes(keyword));if(hasPasswordKeyword&&hasRecoveryKeyword){return true}const strongRecoveryPatterns=["resetpassword","passwordreset","forgotpassword","passwordrecovery","recoverytoken","password_reset","forgot_password","reset_password","passwordforgot","recoverpassword"];return strongRecoveryPatterns.some(pattern=>lowerText.includes(pattern))};const isSecureTokenGeneration=callExpression=>{const callText=sourceCode.getText(callExpression);return secureTokenFunctions.some(func=>callText.includes(func))};const looksLikeTokenValue=callExpression=>!callExpression.arguments.some(arg=>arg.type==="ArrowFunctionExpression"||arg.type==="FunctionExpression");const usesPredictableSource=callExpression=>{const text=sourceCode.getText(callExpression);return/\bMath\s*(?:\.\s*random|\[\s*['"]random['"]\s*\])\s*\(/.test(text)||/\bDate\s*(?:\.\s*now|\[\s*['"]now['"]\s*\])\s*\(/.test(text)||/new\s+Date\s*\([^)]*\)\s*(?:\.\s*getTime|\[\s*['"]getTime['"]\s*\])\s*\(/.test(text)||/\buuid\s*(?:\.\s*v1|\[\s*['"]v1['"]\s*\])\s*\(/.test(text)||/\bv1\s*\(\s*\)/.test(text)};const isCredentialName=name=>/token|otp|code|secret|nonce|magiclink/i.test(name);const handlesRecoveryCredential=functionNode=>{const walk=scope=>{for(const reference of scope.references){if(CREDENTIAL_GENERATORS.has(reference.identifier.name)){return true}}for(const variable of scope.variables){for(const definition of variable.defs){if(definition.type==="Variable"&&definition.node.init?.type==="CallExpression"){const{callee}=definition.node.init;const calleeName=callee.type==="Identifier"?callee.name:callee.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(callee):null;if(calleeName!==null&&CREDENTIAL_GENERATORS.has(calleeName)){return true}}}if(!isCredentialName(variable.name)){continue}if(variable.defs.some(definition=>definition.type==="Parameter"||definition.type==="Variable"&&definition.node.init!==null)){return true}}return scope.childScopes.some(child=>walk(child))};return walk(sourceCode.getScope(functionNode.body))};const isDeclarationOnly=fn=>fn.body.body.length===1&&fn.body.body[0]?.type==="ReturnStatement";const hasTokenExpiration=functionNode=>{const functionText=sourceCode.getText(functionNode).toLowerCase();return functionText.includes("expire")||functionText.includes("ttl")||functionText.includes("timeout")||functionText.includes("lifetime")};return{before(){const options=context.options[0]||{};({secureTokenFunctions=["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers=[],trustedAnnotations=["secure-recovery","rate-limited"],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode})},VariableDeclarator(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name.toLowerCase();if(isRecoveryRelated(varName)){const initText=sourceCode.getText(node.init);if(node.init.type==="CallExpression"){if(looksLikeTokenValue(node.init)&&!isSecureTokenGeneration(node.init)&&usesPredictableSource(node.init)){if(safetyChecker.isSafe(node,context)||node.parent&&safetyChecker.isSafe(node.parent,context)){return}context.report({node:node.init,messageId:"predictableRecoveryToken",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(node.init.type==="BinaryExpression"){if(usesPredictableSource(node.init)||initText.includes("timestamp")){if(safetyChecker.isSafe(node,context)||node.parent&&safetyChecker.isSafe(node.parent,context)){return}context.report({node:node.init,messageId:"insufficientTokenEntropy",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},FunctionDeclaration(node){if(!node.id){return}const functionName=node.id.name;const functionText=sourceCode.getText(node).toLowerCase();if(isRecoveryRelated(functionName)&&!isDeclarationOnly(node)&&handlesRecoveryCredential(node)){if(!hasTokenExpiration(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.id,messageId:"missingTokenExpiration",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}if(!functionText.includes("limit")&&!functionText.includes("rate")){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.id,messageId:"missingRateLimit",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&(callee.object.name==="console"||callee.object.name==="logger")&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["log","info","warn","error"])||callee.type==="Identifier"&&callee.name==="logger"){const args=node.arguments;for(const arg of args){if(arg.type==="Literal"){continue}const argText=sourceCode.getText(arg).toLowerCase();if(isRecoveryRelated(argText)&&(argText.includes("token")||argText.includes("password")||argText.includes("reset")||argText.includes("code"))){if(safetyChecker.isSafe(node,context)){continue}context.report({node:arg,messageId:"recoveryLoggingSensitiveData",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakPasswordRecovery=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const RECOVERY_WORDS=["reset","recover","recovery","forgot","restore"];const RECOVERY_SECRET_WORDS=["token","code","otp","pin"];const CREDENTIAL_GENERATORS=new Set(["randomBytes","randomUUID","randomInt","getRandomValues","nanoid","uuidv4"]);exports.noWeakPasswordRecovery=(0,eslint_devkit_1.createRule)({name:"no-weak-password-recovery",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-weak-password-recovery.md",description:"Detects weak password recovery mechanisms",cwe:"CWE-640"},messages:{missingRateLimit:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Rate Limit",cwe:"CWE-640",description:"Password recovery attempts not rate limited",severity:"HIGH",fix:"Implement rate limiting on recovery requests",documentationLink:"https://owasp.org/www-community/attacks/Brute_force_attack"}),predictableRecoveryToken:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Predictable Recovery Token",cwe:"CWE-640",description:"Recovery token can be predicted or guessed",severity:"CRITICAL",fix:"Use cryptographically secure random tokens",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),insufficientTokenEntropy:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insufficient Token Entropy",cwe:"CWE-640",description:"Recovery token has insufficient randomness",severity:"HIGH",fix:"Use at least 128-bit entropy for tokens",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),missingTokenExpiration:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Token Expiration",cwe:"CWE-640",description:"Recovery tokens never expire",severity:"HIGH",fix:"Implement token expiration (15-60 minutes)",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),recoveryLoggingSensitiveData:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Recovery Logging Sensitive Data",cwe:"CWE-640",description:"Logging sensitive data during password recovery",severity:"MEDIUM",fix:"Never log passwords, tokens, or sensitive recovery data",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"})},schema:[{type:"object",properties:{secureTokenFunctions:{type:"array",items:{type:"string"},default:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],description:"Functions that generate cryptographically secure tokens"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as secure"},trustedAnnotations:{type:"array",items:{type:"string"},default:["secure-recovery","rate-limited"],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},recoveryWords:{type:"array",items:{type:"string"},default:[...RECOVERY_WORDS],description:"Whole words naming a recovery action in an identifier (replaces the default)"},recoverySecretWords:{type:"array",items:{type:"string"},default:[...RECOVERY_SECRET_WORDS],description:"Whole words naming a recovery secret in an identifier (replaces the default)"}},additionalProperties:false}]},defaultOptions:[{secureTokenFunctions:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers:[],trustedAnnotations:["secure-recovery","rate-limited"],strictMode:false,recoveryWords:[...RECOVERY_WORDS],recoverySecretWords:[...RECOVERY_SECRET_WORDS]}],createOnce(context){let secureTokenFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let recoveryWords;let recoverySecretWords;let sourceCode;let filename;let safetyChecker;const isRecoveryRelated=text=>{const lowerText=text.toLowerCase();const passwordKeywords=["password","pwd"];const recoveryKeywords=["reset","recover","forgot","restore"];const hasPasswordKeyword=passwordKeywords.some(keyword=>lowerText.includes(keyword));const hasRecoveryKeyword=recoveryKeywords.some(keyword=>lowerText.includes(keyword));if(hasPasswordKeyword&&hasRecoveryKeyword){return true}const strongRecoveryPatterns=["resetpassword","passwordreset","forgotpassword","passwordrecovery","recoverytoken","password_reset","forgot_password","reset_password","passwordforgot","recoverpassword"];return strongRecoveryPatterns.some(pattern=>lowerText.includes(pattern))};const namesRecoverySecret=name=>(0,eslint_devkit_1.nameHasAnyWord)(name,recoveryWords)&&(0,eslint_devkit_1.nameHasAnyWord)(name,recoverySecretWords);const isSecureTokenGeneration=callExpression=>{const callText=sourceCode.getText(callExpression);return secureTokenFunctions.some(func=>callText.includes(func))};const looksLikeTokenValue=callExpression=>!callExpression.arguments.some(arg=>arg.type==="ArrowFunctionExpression"||arg.type==="FunctionExpression");const usesPredictableSource=callExpression=>{const text=sourceCode.getText(callExpression);return/\bMath\s*(?:\.\s*random|\[\s*['"]random['"]\s*\])\s*\(/.test(text)||/\bDate\s*(?:\.\s*now|\[\s*['"]now['"]\s*\])\s*\(/.test(text)||/new\s+Date\s*\([^)]*\)\s*(?:\.\s*getTime|\[\s*['"]getTime['"]\s*\])\s*\(/.test(text)||/\buuid\s*(?:\.\s*v1|\[\s*['"]v1['"]\s*\])\s*\(/.test(text)||/\bv1\s*\(\s*\)/.test(text)};const isCredentialName=name=>/token|otp|code|secret|nonce|magiclink/i.test(name);const handlesRecoveryCredential=functionNode=>{const walk=scope=>{for(const reference of scope.references){if(CREDENTIAL_GENERATORS.has(reference.identifier.name)){return true}}for(const variable of scope.variables){for(const definition of variable.defs){if(definition.type==="Variable"&&definition.node.init?.type==="CallExpression"){const{callee}=definition.node.init;const calleeName=callee.type==="Identifier"?callee.name:callee.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(callee):null;if(calleeName!==null&&CREDENTIAL_GENERATORS.has(calleeName)){return true}}}if(!isCredentialName(variable.name)){continue}if(variable.defs.some(definition=>definition.type==="Parameter"||definition.type==="Variable"&&definition.node.init!==null)){return true}}return scope.childScopes.some(child=>walk(child))};return walk(sourceCode.getScope(functionNode.body))};const isDeclarationOnly=fn=>fn.body.body.length===1&&fn.body.body[0]?.type==="ReturnStatement";const hasTokenExpiration=functionNode=>{const functionText=sourceCode.getText(functionNode).toLowerCase();return functionText.includes("expire")||functionText.includes("ttl")||functionText.includes("timeout")||functionText.includes("lifetime")};return{before(){const options=context.options[0]||{};({secureTokenFunctions=["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers=[],trustedAnnotations=["secure-recovery","rate-limited"],strictMode=false,recoveryWords=RECOVERY_WORDS,recoverySecretWords=RECOVERY_SECRET_WORDS}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode})},VariableDeclarator(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name.toLowerCase();if(isRecoveryRelated(varName)||namesRecoverySecret(node.id.name)){const initText=sourceCode.getText(node.init);if(node.init.type==="CallExpression"){if(looksLikeTokenValue(node.init)&&!isSecureTokenGeneration(node.init)&&usesPredictableSource(node.init)){if(safetyChecker.isSafe(node,context)||node.parent&&safetyChecker.isSafe(node.parent,context)){return}context.report({node:node.init,messageId:"predictableRecoveryToken",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(node.init.type==="BinaryExpression"){if(usesPredictableSource(node.init)||initText.includes("timestamp")){if(safetyChecker.isSafe(node,context)||node.parent&&safetyChecker.isSafe(node.parent,context)){return}context.report({node:node.init,messageId:"insufficientTokenEntropy",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},FunctionDeclaration(node){if(!node.id){return}const functionName=node.id.name;const functionText=sourceCode.getText(node).toLowerCase();if(isRecoveryRelated(functionName)&&!isDeclarationOnly(node)&&handlesRecoveryCredential(node)){if(!hasTokenExpiration(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.id,messageId:"missingTokenExpiration",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}if(!functionText.includes("limit")&&!functionText.includes("rate")){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.id,messageId:"missingRateLimit",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&(callee.object.name==="console"||callee.object.name==="logger")&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["log","info","warn","error"])||callee.type==="Identifier"&&callee.name==="logger"){const args=node.arguments;for(const arg of args){if(arg.type==="Literal"){continue}const argText=sourceCode.getText(arg).toLowerCase();if(isRecoveryRelated(argText)&&(argText.includes("token")||argText.includes("password")||argText.includes("reset")||argText.includes("code"))){if(safetyChecker.isSafe(node,context)){continue}context.report({node:arg,messageId:"recoveryLoggingSensitiveData",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXpathInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");function literalTextOf(node){if(node.type==="Literal")return typeof node.value==="string"?node.value:"";if(node.type==="TemplateLiteral")return node.quasis.map(q=>q.value.raw).join(" ");if(node.type==="BinaryExpression"&&node.operator==="+"){return`${literalTextOf(node.left)} ${literalTextOf(node.right)}`}return""}const XPATH_AXIS="ancestor-or-self|ancestor|attribute|child|descendant-or-self|descendant|following-sibling|following|namespace|parent|preceding-sibling|preceding|self";const XPATH_SYNTAX=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\/\\*(?![\\w.*/-])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function looksLikeXpath(text){return XPATH_SYNTAX.test(text.replace(/:\/\//g," "))}const XPATH_SYNTAX_UNAMBIGUOUS=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function isWildcardOnlyXpath(text){const cleaned=text.replace(/:\/\//g," ");return XPATH_SYNTAX.test(cleaned)&&!XPATH_SYNTAX_UNAMBIGUOUS.test(cleaned)}const DEFAULT_XPATH_PACKAGES=["xpath","xmldom-xpath","xpath.js","libxmljs","libxmljs2","@xmldom/xmldom"];function isXpathModuleExport(node,scope,xpathPackages){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,scope);return binding!==void 0&&xpathPackages.has(binding.module)}exports.noXpathInjection=(0,eslint_devkit_1.createRule)({name:"no-xpath-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-xpath-injection.md",description:"Detects XPath injection vulnerabilities",cwe:"CWE-643"},messages:{xpathInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XPath Injection",cwe:"CWE-643",description:"XPath injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"}),unsafeXpathConcatenation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XPath Concatenation",cwe:"CWE-643",description:"Unsafe string concatenation in XPath expression",severity:"HIGH",fix:"Use parameterized XPath or escape user input",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),unvalidatedXpathInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unvalidated XPath Input",cwe:"CWE-643",description:"XPath query uses unvalidated user input",severity:"MEDIUM",fix:"Validate and sanitize XPath input before use",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),dangerousXpathExpression:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous XPath Expression",cwe:"CWE-643",description:"XPath expression allows dangerous operations",severity:"MEDIUM",fix:"Restrict XPath to safe patterns and validate expressions",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"})},schema:[{type:"object",properties:{reportDangerousConstructs:{type:"boolean",default:false,description:"Also report constant XPath containing ordinary axis syntax (//, text(), .., /*). These are not vulnerabilities; a constant expression has nothing to inject into. Off by default because it reported essentially every XPath in existence at CVSS 9.8."},xpathFunctions:{type:"array",items:{type:"string"},default:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],description:"XPath evaluation methods treated as query sinks"},safeXpathConstructors:{type:"array",items:{type:"string"},default:["buildXPath","createXPath","safeXPath","xpathBuilder"],description:"Builders that produce a parameterized XPath expression"},xpathValidationFunctions:{type:"array",items:{type:"string"},default:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],description:"Function names that escape or validate XPath input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as XPath sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},xpathPackages:{type:"array",items:{type:"string"},default:DEFAULT_XPATH_PACKAGES,description:"Module specifiers whose exports evaluate an XPath expression, matched against a resolved import binding. Replaces the built-in list."},additionalXpathPackages:{type:"array",items:{type:"string"},default:[],description:"Extra XPath package specifiers, on top of `xpathPackages`."}},additionalProperties:false}]},defaultOptions:[{xpathPackages:DEFAULT_XPATH_PACKAGES,additionalXpathPackages:[],xpathFunctions:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],safeXpathConstructors:["buildXPath","createXPath","safeXPath","xpathBuilder"],xpathValidationFunctions:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers:[],trustedAnnotations:["@xpath-safe"],strictMode:false}],createOnce(context){let reportDangerousConstructs;let xpathPackages;let additionalXpathPackages;let xpathFunctions;let xpathValidationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let xpathPackageSet;let sourceCode;let filename;let moduleEvaluatesXpath;let wildcardPending;let DOM_XPATH_MEMBERS;let safetyChecker;let validatedVariables;function everyUseAvoidsSink(node){const declarator=node.parent;if(declarator?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||declarator.init!==node||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const[variable]=context.sourceCode.getDeclaredVariables(declarator);const reads=variable.references.filter(ref=>ref.isRead());if(reads.length===0)return false;return reads.every(ref=>!reachesXpathSink(ref.identifier))}function isXpathSinkCall(call){const callee=call.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),xpathFunctions)}function reachesXpathSink(node){const parent=node.parent;if(!parent)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===node){return isXpathSinkCall(parent)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const declared=parent.id;const resolved=sourceCode.getScope(node).references.find(r=>r.identifier.name===declared.name)?.resolved;return(resolved?.references??[]).some(ref=>{const refParent=ref.identifier.parent;return refParent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&refParent.arguments[0]===ref.identifier&&isXpathSinkCall(refParent)})}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return reachesXpathSink(parent)}return false}const isXpathOperation=node=>{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),xpathFunctions)){if((0,eslint_devkit_1.propertyName)(callee)!=="select"){return true}const receiver=callee.object;return receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath|xpth/i.test(receiver.name)||receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&/xpath/i.test((0,eslint_devkit_1.propertyName)(receiver)??"")}if(callee.type==="Identifier"&&xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)){return true}return false};const containsDangerousXpath=xpathText=>{if(!reportDangerousConstructs)return false;const dangerousPatterns=[/\.\./,/\/\*/,/\[.*\*\]/,/\/\//,/text\(\)/,/comment\(\)/,/processing-instruction\(\)/];return dangerousPatterns.some(pattern=>pattern.test(xpathText))};const isUntrustedXpathInput=inputNode=>{if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(inputNode.object),["query","body","params","param"])){return true}if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}}if(inputNode.type!=="Identifier"){return false}const varName=inputNode.name.toLowerCase();if(["req","request","query","params","input","user","search"].some(keyword=>varName.includes(keyword))){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;return func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})}current=current.parent}return false};const isXpathInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&¤t.callee.type==="Identifier"&&xpathValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const hasSafeAnnotationOnStatement=node=>{let current=node;while(current){if(current.type==="VariableDeclaration"||current.type==="ExpressionStatement"||current.type==="FunctionDeclaration"){const comments=sourceCode.getCommentsBefore(current);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@xpath-safe")){return true}}}current=current.parent}return false};const declarationReachesSink=declarator=>{const name=declarator.id.name;for(let scope=context.sourceCode.getScope(declarator.id);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===name);if(variable){return variable.references.some(ref=>reachesXpathSink(ref.identifier))}}return false};return{before(){const options=context.options[0]||{};({reportDangerousConstructs=false,xpathPackages=DEFAULT_XPATH_PACKAGES,additionalXpathPackages=[],xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);xpathPackageSet=new Set([...xpathPackages,...additionalXpathPackages]);sourceCode=context.sourceCode;filename=context.filename;moduleEvaluatesXpath=false;wildcardPending=[];DOM_XPATH_MEMBERS=new Set(["evaluate","selectNodes","selectSingleNode","createExpression"]);safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});validatedVariables=new Set},CallExpression(node){if(!isXpathOperation(node)){return}const args=node.arguments;if(args.length===0){return}const xpathArg=args[0];const staticText=xpathArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?null:(0,eslint_devkit_1.staticString)(xpathArg);if(staticText!==null){const xpathText=staticText;if(containsDangerousXpath(xpathText)){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(xpathArg.type==="Identifier"){if(isUntrustedXpathInput(xpathArg)&&!isXpathInputValidated(xpathArg)&&!(xpathArg.type==="Identifier"&&validatedVariables.has(xpathArg.name))){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||safetyChecker.isSafe(xpathArg,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"unvalidatedXpathInput",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},ImportDeclaration(node){if(xpathPackageSet.has(String(node.source.value))){moduleEvaluatesXpath=true}},MemberExpression(node){const member=(0,eslint_devkit_1.propertyName)(node);if(member!==null&&DOM_XPATH_MEMBERS.has(member)){moduleEvaluatesXpath=true}},"Program:exit"(){if(!moduleEvaluatesXpath)return;for(const pending of wildcardPending){context.report({node:pending,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(pending.loc.start.line)}})}},TemplateLiteral(node){const staticText=literalTextOf(node);if(/https?:\/\//.test(staticText)||/^\s*\/api\//.test(staticText)){return}if(/^\s*\/home\//.test(staticText)||/^\s*\/usr\//.test(staticText)||/^\s*\/tmp\//.test(staticText)){return}if(/\[data-[\w-]+/.test(staticText)||/\[class=/.test(staticText)||/\[id=/.test(staticText)){return}if(/\?.*=/.test(staticText)&&!/\[@/.test(staticText)){return}if(!looksLikeXpath(staticText)){return}const wildcardOnly=isWildcardOnlyXpath(staticText);if(node.expressions.length>0){const hasUntrustedInterpolation=node.expressions.some(expr=>isUntrustedXpathInput(expr)&&!isXpathInputValidated(expr)&&!(expr.type==="Identifier"&&validatedVariables.has(expr.name)));if(hasUntrustedInterpolation){if(hasSafeAnnotationOnStatement(node)){return}if(wildcardOnly){wildcardPending.push(node);return}context.report({node,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}if(containsDangerousXpath(staticText)&&reachesXpathSink(node)){if(hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}if(!looksLikeXpath(literalTextOf(node))){return}const isInnerConcat=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.parent.operator==="+";if(isInnerConcat){return}const operands=[];(function flatten(n){if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="+"){flatten(n.left);flatten(n.right);return}operands.push(n)})(node);const unvalidated=operand=>!isXpathInputValidated(operand)&&!(operand.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&validatedVariables.has(operand.name));const hasUntrusted=operands.some(operand=>isUntrustedXpathInput(operand)&&unvalidated(operand));const dynamicAtSink=reachesXpathSink(node)&&operands.some(operand=>!(0,eslint_devkit_1.isStaticExpression)({node:operand,scope:context.sourceCode.getScope(operand)})&&unvalidated(operand));if((hasUntrusted||dynamicAtSink)&&!everyUseAvoidsSink(node)){if(safetyChecker.isSafe(node,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"xpathInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use parameterized XPath construction with input validation"}})}},VariableDeclarator(node){const declLine=String(node.loc?.start.line??0);if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(xpathValidationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("xpath")&&!varNameLower.includes("query")&&!varNameLower.includes("path")){return}if(node.init.type==="Literal"&&typeof node.init.value==="string"){if(looksLikeXpath(node.init.value)&&containsDangerousXpath(node.init.value)){if(safetyChecker.isSafe(node.init,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:node.init,messageId:"dangerousXpathExpression",data:{filePath:filename,line:declLine}})}}else if(isUntrustedXpathInput(node.init)&&declarationReachesSink(node)&&!isUntrustedXpathInput(node.id)){context.report({node:node.init,messageId:"xpathInjection",data:{filePath:filename,line:declLine,severity:"MEDIUM",safeAlternative:"Use safe XPath construction methods"}})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXpathInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");function literalTextOf(node){if(node.type==="Literal")return typeof node.value==="string"?node.value:"";if(node.type==="TemplateLiteral")return node.quasis.map(q=>q.value.raw).join(" ");if(node.type==="BinaryExpression"&&node.operator==="+"){return`${literalTextOf(node.left)} ${literalTextOf(node.right)}`}return""}const XPATH_AXIS="ancestor-or-self|ancestor|attribute|child|descendant-or-self|descendant|following-sibling|following|namespace|parent|preceding-sibling|preceding|self";const XPATH_SYNTAX=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\/\\*(?![\\w.*/-])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function looksLikeXpath(text){return XPATH_SYNTAX.test(text.replace(/:\/\//g," "))}const XPATH_SYNTAX_UNAMBIGUOUS=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function isWildcardOnlyXpath(text){const cleaned=text.replace(/:\/\//g," ");return XPATH_SYNTAX.test(cleaned)&&!XPATH_SYNTAX_UNAMBIGUOUS.test(cleaned)}const DEFAULT_XPATH_PACKAGES=["xpath","xmldom-xpath","xpath.js","libxmljs","libxmljs2","@xmldom/xmldom"];function isXpathModuleExport(node,scope,xpathPackages){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,scope);return binding!==void 0&&xpathPackages.has(binding.module)}exports.noXpathInjection=(0,eslint_devkit_1.createRule)({name:"no-xpath-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-xpath-injection.md",description:"Detects XPath injection vulnerabilities",cwe:"CWE-643"},messages:{xpathInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XPath Injection",cwe:"CWE-643",description:"XPath injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"}),unsafeXpathConcatenation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XPath Concatenation",cwe:"CWE-643",description:"Unsafe string concatenation in XPath expression",severity:"HIGH",fix:"Use parameterized XPath or escape user input",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),unvalidatedXpathInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unvalidated XPath Input",cwe:"CWE-643",description:"XPath query uses unvalidated user input",severity:"MEDIUM",fix:"Validate and sanitize XPath input before use",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),dangerousXpathExpression:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous XPath Expression",cwe:"CWE-643",description:"XPath expression allows dangerous operations",severity:"MEDIUM",fix:"Restrict XPath to safe patterns and validate expressions",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"})},schema:[{type:"object",properties:{reportDangerousConstructs:{type:"boolean",default:false,description:"Also report constant XPath containing ordinary axis syntax (//, text(), .., /*). These are not vulnerabilities; a constant expression has nothing to inject into. Off by default because it reported essentially every XPath in existence at CVSS 9.8."},xpathFunctions:{type:"array",items:{type:"string"},default:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],description:"XPath evaluation methods treated as query sinks"},safeXpathConstructors:{type:"array",items:{type:"string"},default:["buildXPath","createXPath","safeXPath","xpathBuilder"],description:"Builders that produce a parameterized XPath expression"},xpathValidationFunctions:{type:"array",items:{type:"string"},default:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],description:"Function names that escape or validate XPath input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as XPath sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},xpathPackages:{type:"array",items:{type:"string"},default:DEFAULT_XPATH_PACKAGES,description:"Module specifiers whose exports evaluate an XPath expression, matched against a resolved import binding. Replaces the built-in list."},additionalXpathPackages:{type:"array",items:{type:"string"},default:[],description:"Extra XPath package specifiers, on top of `xpathPackages`."}},additionalProperties:false}]},defaultOptions:[{xpathPackages:DEFAULT_XPATH_PACKAGES,additionalXpathPackages:[],xpathFunctions:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],safeXpathConstructors:["buildXPath","createXPath","safeXPath","xpathBuilder"],xpathValidationFunctions:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers:[],trustedAnnotations:["@xpath-safe"],strictMode:false}],createOnce(context){let reportDangerousConstructs;let xpathPackages;let additionalXpathPackages;let xpathFunctions;let xpathValidationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let xpathPackageSet;let sourceCode;let filename;let moduleEvaluatesXpath;let wildcardPending;let DOM_XPATH_MEMBERS;let safetyChecker;let validatedVariables;function everyUseAvoidsSink(node){const declarator=node.parent;if(declarator?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||declarator.init!==node||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const[variable]=context.sourceCode.getDeclaredVariables(declarator);const reads=variable.references.filter(ref=>ref.isRead());if(reads.length===0)return false;return reads.every(ref=>ref.identifier.parent.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement&&!reachesXpathSink(ref.identifier))}function isXpathSinkCall(call){const callee=call.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),xpathFunctions)}function reachesXpathSink(node){const parent=node.parent;if(!parent)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===node){return isXpathSinkCall(parent)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const declared=parent.id;const resolved=sourceCode.getScope(node).references.find(r=>r.identifier.name===declared.name)?.resolved;return(resolved?.references??[]).some(ref=>{const refParent=ref.identifier.parent;return refParent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&refParent.arguments[0]===ref.identifier&&isXpathSinkCall(refParent)})}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return reachesXpathSink(parent)}return false}const isXpathOperation=node=>{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),xpathFunctions)){if((0,eslint_devkit_1.propertyName)(callee)!=="select"){return true}const receiver=callee.object;return receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath|xpth/i.test(receiver.name)||receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&/xpath/i.test((0,eslint_devkit_1.propertyName)(receiver)??"")}if(callee.type==="Identifier"&&xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)){return true}return false};const containsDangerousXpath=xpathText=>{if(!reportDangerousConstructs)return false;const dangerousPatterns=[/\.\./,/\/\*/,/\[.*\*\]/,/\/\//,/text\(\)/,/comment\(\)/,/processing-instruction\(\)/];return dangerousPatterns.some(pattern=>pattern.test(xpathText))};const isUntrustedXpathInput=inputNode=>{if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(inputNode.object),["query","body","params","param"])){return true}if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}}if(inputNode.type!=="Identifier"){return false}const varName=inputNode.name.toLowerCase();if(["req","request","query","params","input","user","search"].some(keyword=>varName.includes(keyword))){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;return func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})}current=current.parent}return false};const isXpathInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&¤t.callee.type==="Identifier"&&xpathValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const hasSafeAnnotationOnStatement=node=>{let current=node;while(current){if(current.type==="VariableDeclaration"||current.type==="ExpressionStatement"||current.type==="FunctionDeclaration"){const comments=sourceCode.getCommentsBefore(current);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@xpath-safe")){return true}}}current=current.parent}return false};const declarationReachesSink=declarator=>{const name=declarator.id.name;for(let scope=context.sourceCode.getScope(declarator.id);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===name);if(variable){return variable.references.some(ref=>reachesXpathSink(ref.identifier))}}return false};return{before(){const options=context.options[0]||{};({reportDangerousConstructs=false,xpathPackages=DEFAULT_XPATH_PACKAGES,additionalXpathPackages=[],xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);xpathPackageSet=new Set([...xpathPackages,...additionalXpathPackages]);sourceCode=context.sourceCode;filename=context.filename;moduleEvaluatesXpath=false;wildcardPending=[];DOM_XPATH_MEMBERS=new Set(["evaluate","selectNodes","selectSingleNode","createExpression"]);safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});validatedVariables=new Set},CallExpression(node){if(!isXpathOperation(node)){return}const args=node.arguments;if(args.length===0){return}const xpathArg=args[0];const staticText=xpathArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?null:(0,eslint_devkit_1.staticString)(xpathArg);if(staticText!==null){const xpathText=staticText;if(containsDangerousXpath(xpathText)){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(xpathArg.type==="Identifier"){if(isUntrustedXpathInput(xpathArg)&&!isXpathInputValidated(xpathArg)&&!(xpathArg.type==="Identifier"&&validatedVariables.has(xpathArg.name))){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||safetyChecker.isSafe(xpathArg,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"unvalidatedXpathInput",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},ImportDeclaration(node){if(xpathPackageSet.has(String(node.source.value))){moduleEvaluatesXpath=true}},MemberExpression(node){const member=(0,eslint_devkit_1.propertyName)(node);if(member!==null&&DOM_XPATH_MEMBERS.has(member)){moduleEvaluatesXpath=true}},"Program:exit"(){if(!moduleEvaluatesXpath)return;for(const pending of wildcardPending){context.report({node:pending,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(pending.loc.start.line)}})}},TemplateLiteral(node){const staticText=literalTextOf(node);if(/https?:\/\//.test(staticText)||/^\s*\/api\//.test(staticText)){return}if(/^\s*\/home\//.test(staticText)||/^\s*\/usr\//.test(staticText)||/^\s*\/tmp\//.test(staticText)){return}if(/\[data-[\w-]+/.test(staticText)||/\[class=/.test(staticText)||/\[id=/.test(staticText)){return}if(/\?.*=/.test(staticText)&&!/\[@/.test(staticText)){return}if(!looksLikeXpath(staticText)){return}const wildcardOnly=isWildcardOnlyXpath(staticText);if(node.expressions.length>0){const hasUntrustedInterpolation=node.expressions.some(expr=>isUntrustedXpathInput(expr)&&!isXpathInputValidated(expr)&&!(expr.type==="Identifier"&&validatedVariables.has(expr.name)));if(hasUntrustedInterpolation){if(hasSafeAnnotationOnStatement(node)){return}if(wildcardOnly){wildcardPending.push(node);return}context.report({node,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}if(containsDangerousXpath(staticText)&&reachesXpathSink(node)){if(hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}if(!looksLikeXpath(literalTextOf(node))){return}const isInnerConcat=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.parent.operator==="+";if(isInnerConcat){return}const operands=[];(function flatten(n){if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="+"){flatten(n.left);flatten(n.right);return}operands.push(n)})(node);const unvalidated=operand=>!isXpathInputValidated(operand)&&!(operand.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&validatedVariables.has(operand.name));const hasUntrusted=operands.some(operand=>isUntrustedXpathInput(operand)&&unvalidated(operand));const dynamicAtSink=reachesXpathSink(node)&&operands.some(operand=>!(0,eslint_devkit_1.isStaticExpression)({node:operand,scope:context.sourceCode.getScope(operand)})&&unvalidated(operand));if((hasUntrusted||dynamicAtSink)&&!everyUseAvoidsSink(node)){if(safetyChecker.isSafe(node,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"xpathInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use parameterized XPath construction with input validation"}})}},VariableDeclarator(node){const declLine=String(node.loc?.start.line??0);if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(xpathValidationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("xpath")&&!varNameLower.includes("query")&&!varNameLower.includes("path")){return}if(node.init.type==="Literal"&&typeof node.init.value==="string"){if(looksLikeXpath(node.init.value)&&containsDangerousXpath(node.init.value)){if(safetyChecker.isSafe(node.init,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:node.init,messageId:"dangerousXpathExpression",data:{filePath:filename,line:declLine}})}}else if(isUntrustedXpathInput(node.init)&&declarationReachesSink(node)&&!isUntrustedXpathInput(node.id)){context.report({node:node.init,messageId:"xpathInjection",data:{filePath:filename,line:declLine,severity:"MEDIUM",safeAlternative:"Use safe XPath construction methods"}})}}}}});
|