eslint-plugin-secure-coding 5.1.3 → 5.2.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 +55 -58
- package/package.json +2 -2
- package/src/index.js +1 -1
- package/src/rules/detect-non-literal-regexp/index.js +1 -1
- package/src/rules/detect-object-injection/index.js +1 -1
- package/src/rules/detect-weak-password-validation/index.js +1 -1
- package/src/rules/no-directive-injection/index.js +1 -1
- package/src/rules/no-electron-security-issues/index.js +1 -1
- package/src/rules/no-fail-open-auth/index.js +1 -1
- package/src/rules/no-format-string-injection/index.js +1 -1
- package/src/rules/no-graphql-injection/index.js +1 -1
- package/src/rules/no-hardcoded-credentials/index.js +1 -1
- package/src/rules/no-hardcoded-session-tokens/index.js +1 -1
- package/src/rules/no-improper-sanitization/index.js +1 -1
- package/src/rules/no-insecure-comparison/index.js +1 -1
- package/src/rules/no-ldap-injection/index.js +1 -1
- package/src/rules/no-log-injection/index.js +1 -1
- package/src/rules/no-privilege-escalation/index.js +1 -1
- package/src/rules/no-sensitive-data-exposure/index.js +1 -1
- package/src/rules/no-sql-injection/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-unsafe-regex-construction/index.js +1 -1
- package/src/rules/no-xpath-injection/index.js +1 -1
- package/src/rules/no-xxe-injection/index.js +1 -1
- package/src/rules/require-backend-authorization/index.js +1 -1
- package/src/rules/require-secure-defaults/index.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeRegexConstruction=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_TRUSTED_ESCAPING_FUNCTIONS=["escapeRegex","escapeRegExp","escapeStringRegexp","regexpEscape"];const INLINE_ESCAPE_SUFFIX='.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")';function taintSource(node,scope,depth=0){if(depth>6)return null;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(unwrapped!==node)return taintSource(unwrapped,scope,depth+1);if(node.type==="TemplateLiteral"){for(const expression of node.expressions){const found=taintSource(expression,scope,depth+1);if(found!==null)return found}return null}if(node.type==="BinaryExpression"&&node.operator==="+"){return taintSource(node.left,scope,depth+1)??taintSource(node.right,scope,depth+1)}if(node.type==="AwaitExpression"){return taintSource(node.argument,scope,depth+1)}if(node.type==="MemberExpression"){let root=node;const properties=[];while(root.type==="MemberExpression"){if(root.property.type==="Identifier")properties.unshift(root.property.name);root=root.object}if(root.type==="Identifier"){if(REQUEST_ROOTS.has(root.name)&&properties.some(p=>REQUEST_PROPERTIES.has(p))&&isInboundRequestBinding(root,scope)){return`${root.name}.${properties.join(".")}`}if(root.name==="process"&&properties[0]==="argv"){return"process.argv"}}return null}if(node.type==="CallExpression"){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(READER_METHODS.has(callee.property.name)){return callee.property.name}}if(callee.type==="Identifier"&&READER_METHODS.has(callee.name)){return callee.name}for(const arg of node.arguments){if(arg.type==="SpreadElement")continue;const found=taintSource(arg,scope,depth+1);if(found!==null)return found}return null}if(node.type==="Identifier"){const variable=lookupVariable(node.name,scope);if(!variable)return null;for(const reference of variable.references){if(!reference.isWrite()||!reference.writeExpr)continue;const found=taintSource(reference.writeExpr,scope,depth+1);if(found!==null)return found}return null}return null}function isInboundRequestBinding(root,scope){const variable=lookupVariable(root.name,scope);if(!variable||variable.defs.length===0)return true;return variable.defs.every(def=>def.type==="Parameter")}function lookupVariable(name,scope){for(let current=scope;current;current=current.upper){const found=current.variables.find(v=>v.name===name);if(found)return found}return void 0}const REQUEST_ROOTS=new Set(["req","request","ctx","event","message"]);const REQUEST_PROPERTIES=new Set(["query","params","body","headers","url","path","cookies","data"]);const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const MEMBER_ESCAPERS=new Set(["escapeRegExp","escapeRegex","escapeStringRegexp","regexpEscape"]);const ESCAPER_PACKAGES=new Set(["escape-string-regexp","lodash.escaperegexp","escape-regexp","regexp.escape"]);function isEscaperPackageBinding(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding&&ESCAPER_PACKAGES.has(binding.module))return true;return binding?.module==="lodash"&&binding.path.at(-1)==="escapeRegExp"}function isRegExpConstructor(callee,scope,depth=0){if(depth>4)return false;if(callee.type!=="Identifier")return false;if(callee.name==="RegExp"){const shadow=lookupVariable("RegExp",scope);return shadow===void 0||shadow.defs.length===0}const variable=lookupVariable(callee.name,scope);if(!variable)return false;const writes=variable.references.filter(ref=>ref.isWrite());return writes.length>0&&writes.every(ref=>{const written=ref.writeExpr;return written!=null&&isRegExpConstructor(written,scope,depth+1)})}function isTrustedMemberEscaper(callee){if(callee.type!=="MemberExpression"||callee.computed)return false;if(callee.property.type!=="Identifier")return false;if(callee.property.name==="escape"&&callee.object.type==="Identifier"&&callee.object.name==="RegExp"){return true}return MEMBER_ESCAPERS.has(callee.property.name)}function isEscaped(node,trustedFunctions,sourceCode,scope){if(node.type==="CallExpression"&&node.callee.type==="Identifier"){const functionName=node.callee.name;if(trustedFunctions.includes(functionName)){return true}}if(node.type==="CallExpression"&&isEscaperPackageBinding(node.callee,scope)){return true}if(node.type==="CallExpression"&&isTrustedMemberEscaper(node.callee)){return true}let current=node;let depth=0;const maxDepth=5;while(depth<maxDepth){const parent=sourceCode.getNodeByRangeIndex?.(current.range[0]-1)||current.parent;if(!parent)break;if(parent.type==="CallExpression"&&parent.callee.type==="Identifier"){const functionName=parent.callee.name;if(trustedFunctions.includes(functionName)){return true}}current=parent;depth++}return false}function isRegexClone(node){if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="source"){return true}if(node.type==="BinaryExpression"&&node.operator==="+"){return isRegexClone(node.left)||isRegexClone(node.right)}return false}function hasDynamicFlags(node){if(node.arguments.length>1){const flagsNode=node.arguments[1];return!(flagsNode.type==="Literal"&&typeof flagsNode.value==="string")}return false}function extractPattern(node,sourceCode,trustedFunctions,scope){const patternNode=node.arguments.length>0?node.arguments[0]:null;if(!patternNode){return{patternNode:null,isUserInput:false,taintedBy:null,isEscaped:false}}const taintedBy=taintSource(patternNode,scope);const isUserInputValue=taintedBy!==null;const allTrustedFunctions=[...new Set([...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS,...trustedFunctions])];const isEscapedValue=isEscaped(patternNode,allTrustedFunctions,sourceCode,scope);return{patternNode,isUserInput:isUserInputValue,taintedBy,isEscaped:isEscapedValue}}exports.noUnsafeRegexConstruction=(0,eslint_devkit_2.createRule)({name:"no-unsafe-regex-construction",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-regex-construction.md",description:"Detects unsafe regex construction patterns (user input without escaping, dynamic flags)",cwe:"CWE-400",cvss:7.5},hasSuggestions:true,messages:{unsafeRegexConstruction:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe regex construction",cwe:"CWE-400",description:"{{issue}}: {{details}}",severity:"HIGH",fix:"{{fix}}",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),escapeUserInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Escape User Input",description:"Escape user input for regex",severity:"LOW",fix:'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:true,description:"Allow literal string patterns"},trustedEscapingFunctions:{type:"array",items:{type:"string"},default:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],description:"Trusted functions that escape input"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:true,trustedEscapingFunctions:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],maxPatternLength:100}],create(context,[options={}]){const{allowLiterals=true,maxPatternLength=100,trustedEscapingFunctions=[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS]}=options;const sourceCode=context.sourceCode;function checkRegExpCall(node){if(!isRegExpConstructor(node.callee,sourceCode.getScope(node))){return}const{patternNode,isUserInput:isUserInputValue,isEscaped:isEscapedValue}=extractPattern(node,sourceCode,trustedEscapingFunctions,sourceCode.getScope(node));if(!patternNode){return}if(patternNode.type==="Literal"&&typeof patternNode.value==="string"){const patternLength=patternNode.value.length;if(patternLength>maxPatternLength){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Pattern too long",details:`Pattern length (${patternLength}) exceeds maximum (${maxPatternLength})`,fix:"Split into smaller patterns or validate length"}});return}if(!allowLiterals){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Literal regex pattern",details:"Literal regex patterns should be avoided for security. Use variables instead.",fix:"Use a variable or RegExp constructor with a string variable"}});return}}if(isUserInputValue&&!isEscapedValue){const patternText=context.sourceCode.getText(patternNode);context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"User input in regex without escaping",details:"User input in regex pattern can lead to ReDoS or injection attacks",fix:"Escape special characters before using in regex"},suggest:[{messageId:"escapeUserInput",fix:fixer=>fixer.replaceText(patternNode,`(${patternText})${INLINE_ESCAPE_SUFFIX}`)}]})}if(hasDynamicFlags(node)&&!isRegexClone(patternNode)){context.report({node,messageId:"unsafeRegexConstruction",data:{issue:"Dynamic regex flags",details:"Dynamic flags can lead to unexpected behavior or security issues",fix:"Use static flags instead of dynamic flags"}})}}return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeRegexConstruction=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_TRUSTED_ESCAPING_FUNCTIONS=["escapeRegex","escapeRegExp","escapeStringRegexp","regexpEscape"];const INLINE_ESCAPE_SUFFIX='.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")';function taintSource(node,scope,requestRoots,depth=0){if(depth>6)return null;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(unwrapped!==node)return taintSource(unwrapped,scope,requestRoots,depth+1);if(node.type==="TemplateLiteral"){for(const expression of node.expressions){const found=taintSource(expression,scope,requestRoots,depth+1);if(found!==null)return found}return null}if(node.type==="BinaryExpression"&&node.operator==="+"){return taintSource(node.left,scope,requestRoots,depth+1)??taintSource(node.right,scope,requestRoots,depth+1)}if(node.type==="AwaitExpression"){return taintSource(node.argument,scope,requestRoots,depth+1)}if(node.type==="MemberExpression"){let root=node;const properties=[];while(root.type==="MemberExpression"){if(root.property.type==="Identifier")properties.unshift(root.property.name);root=root.object}if(root.type==="Identifier"){if(requestRoots.has(root.name)&&properties.some(p=>REQUEST_PROPERTIES.has(p))&&isInboundRequestBinding(root,scope)){return`${root.name}.${properties.join(".")}`}if(root.name==="process"&&properties[0]==="argv"){return"process.argv"}}return null}if(node.type==="CallExpression"){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(READER_METHODS.has(callee.property.name)){return callee.property.name}}if(callee.type==="Identifier"&&READER_METHODS.has(callee.name)){return callee.name}for(const arg of node.arguments){if(arg.type==="SpreadElement")continue;const found=taintSource(arg,scope,requestRoots,depth+1);if(found!==null)return found}return null}if(node.type==="Identifier"){const variable=lookupVariable(node.name,scope);if(!variable)return null;for(const reference of variable.references){if(!reference.isWrite()||!reference.writeExpr)continue;const found=taintSource(reference.writeExpr,scope,requestRoots,depth+1);if(found!==null)return found}return null}return null}function isInboundRequestBinding(root,scope){const variable=lookupVariable(root.name,scope);if(!variable||variable.defs.length===0)return true;return variable.defs.every(def=>def.type==="Parameter")}function lookupVariable(name,scope){for(let current=scope;current;current=current.upper){const found=current.variables.find(v=>v.name===name);if(found)return found}return void 0}const DEFAULT_REQUEST_ROOT_NAMES=["req","request","ctx","event","message"];const REQUEST_PROPERTIES=new Set(["query","params","body","headers","url","path","cookies","data"]);const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const MEMBER_ESCAPERS=new Set(["escapeRegExp","escapeRegex","escapeStringRegexp","regexpEscape"]);const ESCAPER_PACKAGES=new Set(["escape-string-regexp","lodash.escaperegexp","escape-regexp","regexp.escape"]);function isEscaperPackageBinding(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding&&ESCAPER_PACKAGES.has(binding.module))return true;return binding?.module==="lodash"&&binding.path.at(-1)==="escapeRegExp"}function isRegExpConstructor(callee,scope,depth=0){if(depth>4)return false;if(callee.type!=="Identifier")return false;if(callee.name==="RegExp"){const shadow=lookupVariable("RegExp",scope);return shadow===void 0||shadow.defs.length===0}const variable=lookupVariable(callee.name,scope);if(!variable)return false;const writes=variable.references.filter(ref=>ref.isWrite());return writes.length>0&&writes.every(ref=>{const written=ref.writeExpr;return written!=null&&isRegExpConstructor(written,scope,depth+1)})}function isTrustedMemberEscaper(callee){if(callee.type!=="MemberExpression"||callee.computed)return false;if(callee.property.type!=="Identifier")return false;if(callee.property.name==="escape"&&callee.object.type==="Identifier"&&callee.object.name==="RegExp"){return true}return MEMBER_ESCAPERS.has(callee.property.name)}function isEscaped(node,trustedFunctions,sourceCode,scope){if(node.type==="CallExpression"&&node.callee.type==="Identifier"){const functionName=node.callee.name;if(trustedFunctions.includes(functionName)){return true}}if(node.type==="CallExpression"&&isEscaperPackageBinding(node.callee,scope)){return true}if(node.type==="CallExpression"&&isTrustedMemberEscaper(node.callee)){return true}let current=node;let depth=0;const maxDepth=5;while(depth<maxDepth){const parent=sourceCode.getNodeByRangeIndex?.(current.range[0]-1)||current.parent;if(!parent)break;if(parent.type==="CallExpression"&&parent.callee.type==="Identifier"){const functionName=parent.callee.name;if(trustedFunctions.includes(functionName)){return true}}current=parent;depth++}return false}function isRegexClone(node){if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="source"){return true}if(node.type==="BinaryExpression"&&node.operator==="+"){return isRegexClone(node.left)||isRegexClone(node.right)}return false}function isSameObjectPair(pattern,flags){const root=node=>node.type==="MemberExpression"&&!node.computed&&node.object.type==="Identifier"&&node.property.type==="Identifier"?node.object.name:null;const a=root(pattern);return a!==null&&a===root(flags)}function hasDynamicFlags(node){if(node.arguments.length>1){const flagsNode=node.arguments[1];return!((0,eslint_devkit_1.staticString)(flagsNode)!==null)}return false}function extractPattern(node,sourceCode,trustedFunctions,scope,requestRoots){const patternNode=node.arguments.length>0?node.arguments[0]:null;if(!patternNode){return{patternNode:null,isUserInput:false,taintedBy:null,isEscaped:false}}const taintedBy=taintSource(patternNode,scope,requestRoots);const isUserInputValue=taintedBy!==null;const allTrustedFunctions=[...new Set([...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS,...trustedFunctions])];const isEscapedValue=isEscaped(patternNode,allTrustedFunctions,sourceCode,scope);return{patternNode,isUserInput:isUserInputValue,taintedBy,isEscaped:isEscapedValue}}exports.noUnsafeRegexConstruction=(0,eslint_devkit_2.createRule)({name:"no-unsafe-regex-construction",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-regex-construction.md",description:"Detects unsafe regex construction patterns (user input without escaping, dynamic flags)",cwe:"CWE-400",cvss:7.5},hasSuggestions:true,messages:{unsafeRegexConstruction:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe regex construction",cwe:"CWE-400",description:"{{issue}}: {{details}}",severity:"HIGH",fix:"{{fix}}",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),escapeUserInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Escape User Input",description:"Escape user input for regex",severity:"LOW",fix:'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping"})},schema:[{type:"object",properties:{requestRootNames:{type:"array",items:{type:"string"},default:[...DEFAULT_REQUEST_ROOT_NAMES],description:"Identifier names that select a candidate inbound request. Replaces the default."},allowLiterals:{type:"boolean",default:true,description:"Allow literal string patterns"},trustedEscapingFunctions:{type:"array",items:{type:"string"},default:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],description:"Trusted functions that escape input"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:true,trustedEscapingFunctions:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],maxPatternLength:100}],create(context,[options={}]){const{allowLiterals=true,maxPatternLength=100,trustedEscapingFunctions=[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS]}=options;const sourceCode=context.sourceCode;const requestRoots=new Set(options.requestRootNames??DEFAULT_REQUEST_ROOT_NAMES);function checkRegExpCall(node){if(!isRegExpConstructor(node.callee,sourceCode.getScope(node))){return}const{patternNode,isUserInput:isUserInputValue,isEscaped:isEscapedValue}=extractPattern(node,sourceCode,trustedEscapingFunctions,sourceCode.getScope(node),requestRoots);if(!patternNode){return}if(patternNode.type==="Literal"&&typeof patternNode.value==="string"){const patternLength=patternNode.value.length;if(patternLength>maxPatternLength){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Pattern too long",details:`Pattern length (${patternLength}) exceeds maximum (${maxPatternLength})`,fix:"Split into smaller patterns or validate length"}});return}if(!allowLiterals){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Literal regex pattern",details:"Literal regex patterns should be avoided for security. Use variables instead.",fix:"Use a variable or RegExp constructor with a string variable"}});return}}if(isUserInputValue&&!isEscapedValue){const patternText=context.sourceCode.getText(patternNode);context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"User input in regex without escaping",details:"User input in regex pattern can lead to ReDoS or injection attacks",fix:"Escape special characters before using in regex"},suggest:[{messageId:"escapeUserInput",fix:fixer=>fixer.replaceText(patternNode,`(${patternText})${INLINE_ESCAPE_SUFFIX}`)}]})}if(hasDynamicFlags(node)&&!isRegexClone(patternNode)&&!isSameObjectPair(patternNode,node.arguments[1])){context.report({node,messageId:"unsafeRegexConstruction",data:{issue:"Dynamic regex flags",details:"Dynamic flags can lead to unexpected behavior or security issues",fix:"Use static flags instead of dynamic flags"}})}}return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall}}});
|
|
@@ -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.*/-])|\\[@|\\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_*@.])|\\[@|\\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:{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}],create(context){const options=context.options[0]||{};const{reportDangerousConstructs=false,xpathPackages=DEFAULT_XPATH_PACKAGES,additionalXpathPackages=[],xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const xpathPackageSet=new Set([...xpathPackages,...additionalXpathPackages]);const sourceCode=context.sourceCode;const filename=context.filename;let moduleEvaluatesXpath=false;const wildcardPending=[];const DOM_XPATH_MEMBERS=new Set(["evaluate","selectNodes","selectSingleNode","createExpression"]);const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;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&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&xpathFunctions.includes(callee.property.name)}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&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&xpathFunctions.includes(callee.property.name)){if(callee.property.name!=="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&&receiver.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath/i.test(receiver.property.name)}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"&&inputNode.object.property.type==="Identifier"&&["query","body","params","param"].includes(inputNode.object.property.name)){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{CallExpression(node){if(!isXpathOperation(node)){return}const args=node.arguments;if(args.length===0){return}const xpathArg=args[0];if(xpathArg.type==="Literal"&&typeof xpathArg.value==="string"){const xpathText=xpathArg.value;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[computed=false] > Identifier.property"(node){if(DOM_XPATH_MEMBERS.has(node.name)){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:{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}],create(context){const options=context.options[0]||{};const{reportDangerousConstructs=false,xpathPackages=DEFAULT_XPATH_PACKAGES,additionalXpathPackages=[],xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const xpathPackageSet=new Set([...xpathPackages,...additionalXpathPackages]);const sourceCode=context.sourceCode;const filename=context.filename;let moduleEvaluatesXpath=false;const wildcardPending=[];const DOM_XPATH_MEMBERS=new Set(["evaluate","selectNodes","selectSingleNode","createExpression"]);const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;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&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&xpathFunctions.includes(callee.property.name)}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&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&xpathFunctions.includes(callee.property.name)){if(callee.property.name!=="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&&receiver.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath/i.test(receiver.property.name)}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"&&inputNode.object.property.type==="Identifier"&&["query","body","params","param"].includes(inputNode.object.property.name)){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{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[computed=false] > Identifier.property"(node){if(DOM_XPATH_MEMBERS.has(node.name)){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 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXxeInjection=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 DEFAULT_SAFE_PARSER_OPTIONS=["noent","resolveExternals","expandEntityReferences","entityResolver","processEntities","dtdload"];const DEFAULT_XML_VALIDATION_FUNCTIONS=["validateXml","sanitizeXml","cleanXml","parseXmlSafe"];const DEFAULT_XML_MODULES=["libxmljs","libxmljs2","xml2js","xml2json","fast-xml-parser","@xmldom/xmldom","xmldom","node-expat","xpath"];const DEFAULT_XML_PARSE_METHODS=["parseFromString","parseString","parseStringPromise","parseXml","parseXmlAsync","parseXmlString","parseXML"];const DEFAULT_DANGEROUS_PARSER_OPTIONS=["resolveExternals","expandEntityReferences","noent","processEntities","dtdload"];const optionKey=prop=>{if(prop.type!==eslint_devkit_3.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===eslint_devkit_3.AST_NODE_TYPES.Identifier)return prop.key.name;return prop.key.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"?prop.key.value:void 0};const hasDangerousParserOptions=(optionsNode,dangerousKeys)=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!dangerousKeys.has(key))continue;const{value}=prop;if(value.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&value.value===true)return true}return false};const containsDangerousEntities=xmlText=>{return/<!ENTITY/i.test(xmlText)&&/SYSTEM\s+["']/i.test(xmlText)};exports.noXxeInjection=(0,eslint_devkit_1.createRule)({name:"no-xxe-injection",meta:{type:"problem",docs:{description:"Detect XML External Entity (XXE) injection vulnerabilities",url:"https://cwe.mitre.org/data/definitions/611.html",cwe:"CWE-611",cvss:9.1},messages:{xxeInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XXE Injection",cwe:"CWE-611",description:"XML contains dangerous entity declarations",severity:"CRITICAL",fix:"Remove SYSTEM/PUBLIC entity declarations or use safe XML parser",documentationLink:"https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"}),unsafeXmlParser:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XML Parser",cwe:"CWE-611",description:"Using unsafe XML parser without secure configuration",severity:"HIGH",fix:"Use libxmljs with noent: false or xmldom with entityResolver: null",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"}),externalEntityEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"External Entity Processing",cwe:"CWE-611",description:"External entity processing is enabled",severity:"CRITICAL",fix:"Disable external entity processing",documentationLink:"https://cwe.mitre.org/data/definitions/611.html"}),untrustedXmlSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted XML Source",cwe:"CWE-611",description:"XML from untrusted source without validation",severity:"HIGH",fix:"Validate and sanitize XML input before parsing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{safeParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_PARSER_OPTIONS,description:"Parser option keys whose disabled value proves entity expansion is off"},xmlValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_XML_VALIDATION_FUNCTIONS,description:"Function names that count as XML input validation"},xmlModules:{type:"array",items:{type:"string"},default:DEFAULT_XML_MODULES,description:"Module specifiers whose parsers can resolve an external entity, matched against a resolved import binding. Replaces the built-in list."},additionalXmlModules:{type:"array",items:{type:"string"},default:[],description:"Extra XML package specifiers, on top of `xmlModules`."},xmlParseMethods:{type:"array",items:{type:"string"},default:DEFAULT_XML_PARSE_METHODS,description:"Method names that only ever parse XML, matched as an exact method name whatever the receiver. Replaces the built-in list."},additionalXmlParseMethods:{type:"array",items:{type:"string"},default:[],description:"Extra XML-only parse method names, on top of `xmlParseMethods`."},dangerousParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_DANGEROUS_PARSER_OPTIONS,description:"Parser option keys whose `true` value turns entity expansion ON. Replaces the built-in list."},additionalDangerousParserOptions:{type:"array",items:{type:"string"},default:[],description:"Extra entity-expansion option keys, on top of `dangerousParserOptions`."}},additionalProperties:false}]},defaultOptions:[{safeParserOptions:DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions:DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules:DEFAULT_XML_MODULES,additionalXmlModules:[],xmlParseMethods:DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods:[],dangerousParserOptions:DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions:[]}],create(context,[options]){const{safeParserOptions=DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions=DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules=DEFAULT_XML_MODULES,additionalXmlModules=[],xmlParseMethods=DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods=[],dangerousParserOptions=DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions=[]}=options;const xmlPackages=new Set([...xmlModules,...additionalXmlModules]);const parseMethods=new Set([...xmlParseMethods,...additionalXmlParseMethods]);const dangerousKeys=new Set([...dangerousParserOptions,...additionalDangerousParserOptions]);const filename=context.filename;const sourceCode=context.sourceCode;const reportData=node=>({filePath:filename,line:String(node.loc.start.line)});const resolvesToXmlModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&xmlPackages.has(binding.module)};const constructionSite=callee=>{if(callee.type!==eslint_devkit_3.AST_NODE_TYPES.MemberExpression)return void 0;const receiver=callee.object;if(receiver.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression)return receiver;if(receiver.type!==eslint_devkit_3.AST_NODE_TYPES.Identifier)return void 0;const variable=sourceCode.getScope(receiver).references.find(reference=>reference.identifier===receiver)?.resolved;const definition=variable?.defs[0];if(definition?.type!=="Variable")return void 0;if(variable.references.filter(reference=>reference.isWrite()).length!==1){return void 0}return definition.node.init?.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression?definition.node.init:void 0};const isXmlParsingCall=node=>{const callee=node.callee;if(callee.type===eslint_devkit_3.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&parseMethods.has(callee.property.name)){return true}if(hasDangerousParserOptions(node.arguments[1],dangerousKeys))return true;if(resolvesToXmlModule(callee))return true;const construction=constructionSite(callee);return construction!==void 0&&resolvesToXmlModule(construction.callee)};const hasSecureParserOptions=optionsNode=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!safeParserOptions.includes(key))continue;const{value}=prop;if(value.type!==eslint_devkit_3.AST_NODE_TYPES.Literal)continue;if(value.value===false||value.value===null)return true}return false};const isXmlInputValidated=xmlSource=>{let current=xmlSource;while(current){if(current.type===eslint_devkit_3.AST_NODE_TYPES.CallExpression&¤t.callee.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&xmlValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const isTrustedXmlSource=xmlSource=>(0,eslint_devkit_1.isStaticExpression)({node:xmlSource,scope:sourceCode.getScope(xmlSource)});return{CallExpression(node){if(!isXmlParsingCall(node))return;const xmlInput=node.arguments[0];if(!xmlInput)return;const callOptions=node.arguments[1];const construction=constructionSite(node.callee);const constructionOptions=construction?.arguments[0];if(hasDangerousParserOptions(callOptions,dangerousKeys)){context.report({node:callOptions,messageId:"externalEntityEnabled",data:reportData(node)});return}if(hasDangerousParserOptions(constructionOptions,dangerousKeys)){context.report({node:node.callee,messageId:"unsafeXmlParser",data:reportData(node)});return}if(hasSecureParserOptions(callOptions)||hasSecureParserOptions(constructionOptions)){return}if(isTrustedXmlSource(xmlInput)||isXmlInputValidated(xmlInput))return;context.report({node:xmlInput,messageId:"untrustedXmlSource",data:reportData(node)})},Literal(node){if(typeof node.value==="string"&&containsDangerousEntities(node.value)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}},TemplateElement(node){if(containsDangerousEntities(node.value.raw)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXxeInjection=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 DEFAULT_SAFE_PARSER_OPTIONS=["noent","resolveExternals","expandEntityReferences","entityResolver","processEntities","dtdload"];const DEFAULT_XML_VALIDATION_FUNCTIONS=["validateXml","sanitizeXml","cleanXml","parseXmlSafe"];const DEFAULT_XML_MODULES=["libxmljs","libxmljs2","xml2js","xml2json","fast-xml-parser","@xmldom/xmldom","xmldom","node-expat"];const PROVEN_NO_EXTERNAL_ENTITIES=["xml2js","fast-xml-parser","@xmldom/xmldom","xmldom"];const DEFAULT_XML_PARSE_METHODS=["parseFromString","parseString","parseStringPromise","parseXml","parseXmlAsync","parseXmlString","parseXML"];const DEFAULT_DANGEROUS_PARSER_OPTIONS=["resolveExternals","expandEntityReferences","noent","processEntities","dtdload"];const optionKey=prop=>{if(prop.type!==eslint_devkit_3.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===eslint_devkit_3.AST_NODE_TYPES.Identifier)return prop.key.name;return(0,eslint_devkit_1.staticString)(prop.key)??void 0};const hasDangerousParserOptions=(optionsNode,dangerousKeys)=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!dangerousKeys.has(key))continue;const{value}=prop;if(value.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&value.value===true)return true}return false};const containsDangerousEntities=xmlText=>{return/<!ENTITY/i.test(xmlText)&&/SYSTEM\s+["']/i.test(xmlText)};exports.noXxeInjection=(0,eslint_devkit_1.createRule)({name:"no-xxe-injection",meta:{type:"problem",docs:{description:"Detect XML External Entity (XXE) injection vulnerabilities",url:"https://cwe.mitre.org/data/definitions/611.html",cwe:"CWE-611",cvss:9.1},messages:{xxeInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XXE Injection",cwe:"CWE-611",description:"XML contains dangerous entity declarations",severity:"CRITICAL",fix:"Remove SYSTEM/PUBLIC entity declarations or use safe XML parser",documentationLink:"https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"}),unsafeXmlParser:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XML Parser",cwe:"CWE-611",description:"Using unsafe XML parser without secure configuration",severity:"HIGH",fix:"Use libxmljs with noent: false or xmldom with entityResolver: null",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"}),externalEntityEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"External Entity Processing",cwe:"CWE-611",description:"External entity processing is enabled",severity:"CRITICAL",fix:"Disable external entity processing",documentationLink:"https://cwe.mitre.org/data/definitions/611.html"}),untrustedXmlSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted XML Source",cwe:"CWE-611",description:"XML from untrusted source without validation",severity:"HIGH",fix:"Validate and sanitize XML input before parsing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{safeParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_PARSER_OPTIONS,description:"Parser option keys whose disabled value proves entity expansion is off"},xmlValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_XML_VALIDATION_FUNCTIONS,description:"Function names that count as XML input validation"},xmlModules:{type:"array",items:{type:"string"},default:DEFAULT_XML_MODULES,description:"Module specifiers this rule treats as XML parsers, matched against a resolved import binding. Replaces the built-in list."},additionalXmlModules:{type:"array",items:{type:"string"},default:[],description:"Extra XML package specifiers, on top of `xmlModules`."},xmlParseMethods:{type:"array",items:{type:"string"},default:DEFAULT_XML_PARSE_METHODS,description:"Method names that only ever parse XML, matched as an exact method name whatever the receiver. Replaces the built-in list."},additionalXmlParseMethods:{type:"array",items:{type:"string"},default:[],description:"Extra XML-only parse method names, on top of `xmlParseMethods`."},dangerousParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_DANGEROUS_PARSER_OPTIONS,description:"Parser option keys whose `true` value turns entity expansion ON. Replaces the built-in list."},entityIncapableModules:{type:"array",items:{type:"string"},default:PROVEN_NO_EXTERNAL_ENTITIES,description:"Packages proven unable to resolve an external entity, and therefore never reported for parsing untrusted input. Replaces the built-in list."},additionalDangerousParserOptions:{type:"array",items:{type:"string"},default:[],description:"Extra entity-expansion option keys, on top of `dangerousParserOptions`."}},additionalProperties:false}]},defaultOptions:[{safeParserOptions:DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions:DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules:DEFAULT_XML_MODULES,additionalXmlModules:[],xmlParseMethods:DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods:[],dangerousParserOptions:DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions:[],entityIncapableModules:PROVEN_NO_EXTERNAL_ENTITIES}],create(context,[options]){const{safeParserOptions=DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions=DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules=DEFAULT_XML_MODULES,additionalXmlModules=[],xmlParseMethods=DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods=[],dangerousParserOptions=DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions=[],entityIncapableModules=PROVEN_NO_EXTERNAL_ENTITIES}=options;const xmlPackages=new Set([...xmlModules,...additionalXmlModules]);const incapablePackages=new Set(entityIncapableModules);const parseMethods=new Set([...xmlParseMethods,...additionalXmlParseMethods]);const dangerousKeys=new Set([...dangerousParserOptions,...additionalDangerousParserOptions]);const filename=context.filename;const sourceCode=context.sourceCode;const isHtmlParse=node=>{const mime=node.arguments[1];return mime!==void 0&&mime.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&typeof mime.value==="string"&&mime.value.toLowerCase().startsWith("text/html")};const reportData=node=>({filePath:filename,line:String(node.loc.start.line)});const resolvesToXmlModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&xmlPackages.has(binding.module)};const resolvesToEntityIncapableModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&incapablePackages.has(binding.module)};const constructionSite=callee=>{if(callee.type!==eslint_devkit_3.AST_NODE_TYPES.MemberExpression)return void 0;const receiver=callee.object;if(receiver.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression)return receiver;if(receiver.type!==eslint_devkit_3.AST_NODE_TYPES.Identifier)return void 0;const variable=sourceCode.getScope(receiver).references.find(reference=>reference.identifier===receiver)?.resolved;const definition=variable?.defs[0];if(definition?.type!=="Variable")return void 0;if(variable.references.filter(reference=>reference.isWrite()).length!==1){return void 0}return definition.node.init?.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression?definition.node.init:void 0};const isXmlParsingCall=node=>{const callee=node.callee;if(callee.type===eslint_devkit_3.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&parseMethods.has(callee.property.name)){return true}if(hasDangerousParserOptions(node.arguments[1],dangerousKeys))return true;if(resolvesToXmlModule(callee))return true;const construction=constructionSite(callee);return construction!==void 0&&resolvesToXmlModule(construction.callee)};const hasSecureParserOptions=optionsNode=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!safeParserOptions.includes(key))continue;const{value}=prop;if(value.type!==eslint_devkit_3.AST_NODE_TYPES.Literal)continue;if(value.value===false||value.value===null)return true}return false};const isXmlInputValidated=xmlSource=>{let current=xmlSource;while(current){if(current.type===eslint_devkit_3.AST_NODE_TYPES.CallExpression&¤t.callee.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&xmlValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const isTrustedXmlSource=xmlSource=>(0,eslint_devkit_1.isStaticExpression)({node:xmlSource,scope:sourceCode.getScope(xmlSource)});return{CallExpression(node){if(!isXmlParsingCall(node))return;const xmlInput=node.arguments[0];if(!xmlInput)return;if(isHtmlParse(node))return;const callOptions=node.arguments[1];const construction=constructionSite(node.callee);const constructionOptions=construction?.arguments[0];if(hasDangerousParserOptions(callOptions,dangerousKeys)){context.report({node:callOptions,messageId:"externalEntityEnabled",data:reportData(node)});return}if(hasDangerousParserOptions(constructionOptions,dangerousKeys)){context.report({node:node.callee,messageId:"unsafeXmlParser",data:reportData(node)});return}if(hasSecureParserOptions(callOptions)||hasSecureParserOptions(constructionOptions)){return}if(isTrustedXmlSource(xmlInput)||isXmlInputValidated(xmlInput))return;if(resolvesToEntityIncapableModule(node.callee)||construction!==void 0&&resolvesToEntityIncapableModule(construction.callee)){return}context.report({node:xmlInput,messageId:"untrustedXmlSource",data:reportData(node)})},Literal(node){if(typeof node.value==="string"&&containsDangerousEntities(node.value)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}},TemplateElement(node){if(containsDangerousEntities(node.value.raw)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireBackendAuthorization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_AUTH_PROPERTIES=["role","roles","isAdmin","isAuthenticated","isAuthorized","permissions","admin"];const DEFAULT_BROWSER_GLOBALS=["window","document","localStorage","sessionStorage","navigator"];const DEFAULT_SERVER_MODULES=["express","fastify","koa","@hapi/hapi","@nestjs/common","@nestjs/core","next/server","http","https","node:http","node:https"];const memberPropertyName=node=>{if(node.computed){return
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireBackendAuthorization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_AUTH_PROPERTIES=["role","roles","isAdmin","isAuthenticated","isAuthorized","permissions","admin"];const DEFAULT_BROWSER_GLOBALS=["window","document","localStorage","sessionStorage","navigator"];const DEFAULT_SERVER_MODULES=["express","fastify","koa","@hapi/hapi","@nestjs/common","@nestjs/core","next/server","http","https","node:http","node:https"];const memberPropertyName=node=>{if(node.computed){return(0,eslint_devkit_1.staticString)(node.property)??void 0}return node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:void 0};exports.requireBackendAuthorization=(0,eslint_devkit_1.createRule)({name:"require-backend-authorization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/require-backend-authorization.md",description:"Require server-side authorization checks",cwe:"CWE-602",cvss:6.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Client-Side Authorization",cwe:"CWE-602",description:"Authorization logic in client code - easily bypassed",severity:"CRITICAL",fix:"Move authorization checks to server-side API endpoints",documentationLink:"https://cwe.mitre.org/data/definitions/602.html"})},schema:[{type:"object",properties:{authProperties:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_PROPERTIES,description:"Property names that hold an authorization claim, matched as an exact property name. Replaces the built-in list."},additionalAuthProperties:{type:"array",items:{type:"string"},default:[],description:"Extra claim property names, on top of `authProperties`."},browserGlobals:{type:"array",items:{type:"string"},default:DEFAULT_BROWSER_GLOBALS,description:"Globals whose unresolved reference proves the file runs in a browser. Replaces the built-in list."},additionalBrowserGlobals:{type:"array",items:{type:"string"},default:[],description:"Extra browser-only globals, on top of `browserGlobals`."},serverModules:{type:"array",items:{type:"string"},default:DEFAULT_SERVER_MODULES,description:"Module specifiers that can only load in a server process; importing one suppresses the finding. Replaces the built-in list."},additionalServerModules:{type:"array",items:{type:"string"},default:[],description:"Extra server-only module specifiers, on top of `serverModules`."}},additionalProperties:false}]},defaultOptions:[{authProperties:DEFAULT_AUTH_PROPERTIES,additionalAuthProperties:[],browserGlobals:DEFAULT_BROWSER_GLOBALS,additionalBrowserGlobals:[],serverModules:DEFAULT_SERVER_MODULES,additionalServerModules:[]}],create(context,[options={}]){const{authProperties=DEFAULT_AUTH_PROPERTIES,additionalAuthProperties=[],browserGlobals=DEFAULT_BROWSER_GLOBALS,additionalBrowserGlobals=[],serverModules=DEFAULT_SERVER_MODULES,additionalServerModules=[]}=options;const authNames=new Set([...authProperties,...additionalAuthProperties]);const browserNames=new Set([...browserGlobals,...additionalBrowserGlobals]);const serverSpecifiers=new Set([...serverModules,...additionalServerModules]);const sourceCode=context.sourceCode;const candidates=[];const claimBackedVariables=new Set;const indirectTests=[];let hasJsx=false;const noteIndirect=(test,node)=>{if(test.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)indirectTests.push({node,identifier:test})};const resolveReference=identifier=>{for(let scope=sourceCode.getScope(identifier);scope;scope=scope.upper){const reference=scope.references.find(entry=>entry.identifier===identifier);if(reference)return reference.resolved??void 0}return void 0};return{JSXElement(){hasJsx=true},JSXFragment(){hasJsx=true},MemberExpression(node){const property=memberPropertyName(node);if(property===void 0||!authNames.has(property))return;let current=node;for(let parent=node.parent;parent;current=parent,parent=parent.parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&parent.test===current){candidates.push(parent);return}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.SwitchStatement&&parent.discriminant===current){candidates.push(parent);return}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===current){for(const variable of sourceCode.getDeclaredVariables(parent)){claimBackedVariables.add(variable)}return}}},IfStatement(node){noteIndirect(node.test,node)},SwitchStatement(node){noteIndirect(node.discriminant,node)},"Program:exit"(program){for(const{node,identifier}of indirectTests){const resolved=resolveReference(identifier);if(!resolved||!claimBackedVariables.has(resolved))continue;if(resolved.references.filter(reference=>reference.isWrite()).length!==1)continue;candidates.push(node)}if(candidates.length===0)return;const importsServerModule=program.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&serverSpecifiers.has(String(statement.source.value)));if(importsServerModule)return;const hasUseClient=program.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement&&statement.directive==="use client");const touchesBrowserGlobal=sourceCode.getScope(program).through.some(reference=>browserNames.has(reference.identifier.name));if(!hasUseClient&&!hasJsx&&!touchesBrowserGlobal)return;for(const node of candidates){context.report({node,messageId:"violationDetected"})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireSecureDefaults=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_INSECURE_WHEN_FALSE=["strictSSL","httpOnly","requireTLS","sslValidate"];const DEFAULT_INSECURE_WHEN_TRUE=["tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","allowInvalidCertificates","ignoreHTTPSErrors"];const CORROBORATION_REQUIRED=new Set(["secure"]);const DEFAULT_COOKIE_ATTRIBUTES=["httpOnly","sameSite","maxAge","expires","domain","path","signed","partitioned","priority"];const COOKIE_CONTAINER_KEYS=new Set(["cookie","cookies"]);const VERIFICATION_CALLBACKS=new Set(["checkServerIdentity"]);const isBenignReturnValue=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name==="undefined"||node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(node.value===null||node.value===true);const isNoopCallback=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return false}if(node.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return isBenignReturnValue(node.body);if(node.body.body.length===0)return true;const[only]=node.body.body;if(node.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return false;return only.argument===null||isBenignReturnValue(only.argument)};const propertyKey=node=>{if(node.computed)return void 0;if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.key.name;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireSecureDefaults=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_INSECURE_WHEN_FALSE=["strictSSL","httpOnly","requireTLS","sslValidate"];const DEFAULT_INSECURE_WHEN_TRUE=["tlsAllowInvalidCertificates","tlsAllowInvalidHostnames","allowInvalidCertificates","ignoreHTTPSErrors"];const CORROBORATION_REQUIRED=new Set(["secure"]);const DEFAULT_COOKIE_ATTRIBUTES=["httpOnly","sameSite","maxAge","expires","domain","path","signed","partitioned","priority"];const COOKIE_CONTAINER_KEYS=new Set(["cookie","cookies"]);const VERIFICATION_CALLBACKS=new Set(["checkServerIdentity"]);const isBenignReturnValue=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name==="undefined"||node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(node.value===null||node.value===true);const isNoopCallback=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return false}if(node.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return isBenignReturnValue(node.body);if(node.body.body.length===0)return true;const[only]=node.body.body;if(node.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return false;return only.argument===null||isBenignReturnValue(only.argument)};const propertyKey=node=>{if(node.computed)return void 0;if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.key.name;const staticText=(0,eslint_devkit_1.staticString)(node.key);if(staticText!==null){return staticText}return void 0};const hasCookieContext=(property,cookieAttributes)=>{const object=property.parent;for(const sibling of object.properties){if(sibling===property)continue;if(sibling.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const siblingKey=propertyKey(sibling);if(siblingKey!==void 0&&cookieAttributes.has(siblingKey))return true}const owner=object.parent;if(owner.type!==eslint_devkit_1.AST_NODE_TYPES.Property)return false;const ownerKey=propertyKey(owner);return ownerKey!==void 0&&COOKIE_CONTAINER_KEYS.has(ownerKey)};const isLiteral=(node,value)=>node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&node.value===value;exports.requireSecureDefaults=(0,eslint_devkit_1.createRule)({name:"require-secure-defaults",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/require-secure-defaults.md",description:"Ensure secure default configurations",cwe:"CWE-1188",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-1188",description:"Ensure secure default configurations detected - Insecure default values",severity:"MEDIUM",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/1188.html"})},schema:[{type:"object",properties:{insecureWhenFalse:{type:"array",items:{type:"string"},default:DEFAULT_INSECURE_WHEN_FALSE,description:"Config keys whose `false` value is the insecure one. Replaces the built-in list; matched as an exact key name, never a substring."},additionalInsecureWhenFalse:{type:"array",items:{type:"string"},default:[],description:"Extra keys where `false` is insecure, on top of `insecureWhenFalse`."},insecureWhenTrue:{type:"array",items:{type:"string"},default:DEFAULT_INSECURE_WHEN_TRUE,description:"Config keys whose `true` value accepts the insecure thing. Replaces the built-in list."},additionalInsecureWhenTrue:{type:"array",items:{type:"string"},default:[],description:"Extra keys where `true` is insecure, on top of `insecureWhenTrue`."},cookieAttributes:{type:"array",items:{type:"string"},default:DEFAULT_COOKIE_ATTRIBUTES,description:"Keys that exist on a cookie and nowhere else. Used only as corroborating structure for `secure: false`. Replaces the built-in list."},additionalCookieAttributes:{type:"array",items:{type:"string"},default:[],description:"Extra cookie attribute names, on top of `cookieAttributes`."}},additionalProperties:false}]},defaultOptions:[{insecureWhenFalse:DEFAULT_INSECURE_WHEN_FALSE,additionalInsecureWhenFalse:[],insecureWhenTrue:DEFAULT_INSECURE_WHEN_TRUE,additionalInsecureWhenTrue:[],cookieAttributes:DEFAULT_COOKIE_ATTRIBUTES,additionalCookieAttributes:[]}],create(context,[options={}]){const{insecureWhenFalse=DEFAULT_INSECURE_WHEN_FALSE,additionalInsecureWhenFalse=[],insecureWhenTrue=DEFAULT_INSECURE_WHEN_TRUE,additionalInsecureWhenTrue=[],cookieAttributes=DEFAULT_COOKIE_ATTRIBUTES,additionalCookieAttributes=[]}=options;const falseIsInsecure=new Set([...insecureWhenFalse,...additionalInsecureWhenFalse]);const trueIsInsecure=new Set([...insecureWhenTrue,...additionalInsecureWhenTrue]);const cookieKeys=new Set([...cookieAttributes,...additionalCookieAttributes]);return{Property(node){const key=propertyKey(node);if(key===void 0)return;const insecure=falseIsInsecure.has(key)&&isLiteral(node.value,false)||trueIsInsecure.has(key)&&isLiteral(node.value,true)||VERIFICATION_CALLBACKS.has(key)&&isNoopCallback(node.value)||CORROBORATION_REQUIRED.has(key)&&isLiteral(node.value,false)&&hasCookieContext(node,cookieKeys);if(insecure){context.report({node,messageId:"violationDetected"})}}}}});
|