eslint-plugin-secure-coding 4.2.0 → 5.0.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 +39 -0
- package/package.json +9 -3
- 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-bidi-characters/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-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-improper-sanitization/index.js +1 -1
- package/src/rules/no-improper-type-validation/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-missing-authentication/index.js +1 -1
- package/src/rules/no-pii-in-logs/index.js +1 -1
- package/src/rules/no-privilege-escalation/index.js +1 -1
- package/src/rules/no-redos-vulnerable-regex/index.js +0 -0
- 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-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-unsafe-regex-construction/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
- 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
- package/src/utils/redos-oracle.js +1 -0
- package/src/utils/regexp-intrinsic.js +1 -0
- package/src/utils/resolve-reference.js +1 -0
|
@@ -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"
|
|
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 +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:{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:{weakPasswordRecovery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Weak Password Recovery",cwe:"CWE-640",description:"Password recovery mechanism has security weaknesses",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),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"}),unlimitedRecoveryAttempts:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Recovery Attempts",cwe:"CWE-640",description:"No limit on password recovery attempts",severity:"MEDIUM",fix:"Limit recovery attempts per time period",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"}),weakRecoveryVerification:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Weak Recovery Verification",cwe:"CWE-640",description:"Recovery request verification is insufficient",severity:"HIGH",fix:"Require strong verification (email + SMS, security questions)",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),tokenReuseVulnerability:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Token Reuse Vulnerability",cwe:"CWE-640",description:"Recovery tokens can be reused",severity:"HIGH",fix:"Mark tokens as used after successful recovery",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),implementRateLimiting:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Implement Rate Limiting",description:"Add rate limiting to recovery endpoints",severity:"LOW",fix:"Limit recovery attempts to 5 per hour per IP/user",documentationLink:"https://owasp.org/www-community/attacks/Brute_force_attack"}),useCryptographicallySecureTokens:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Cryptographically Secure Tokens",description:"Generate tokens with crypto.randomBytes()",severity:"LOW",fix:'const token = crypto.randomBytes(32).toString("hex");',documentationLink:"https://nodejs.org/api/crypto.html#cryptorandombytessize-callback"}),implementTokenExpiration:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Implement Token Expiration",description:"Set reasonable token expiration times",severity:"LOW",fix:"Expire tokens after 15-60 minutes",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),secureRecoveryFlow:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Secure Recovery Flow",description:"Implement secure password recovery flow",severity:"LOW",fix:"Verify identity, send secure link, require current password",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html"}),strategyMultiFactor:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Multi-Factor Strategy",description:"Require multiple verification factors",severity:"LOW",fix:"Email + SMS verification for password recovery",documentationLink:"https://owasp.org/www-community/attacks/Brute_force_attack"}),strategyOutOfBandVerification:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Out-of-Band Verification Strategy",description:"Use out-of-band verification channels",severity:"LOW",fix:"Send recovery codes via SMS or authenticator app",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html"}),strategyTimeBoundTokens:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Time-Bound Tokens Strategy",description:"Use time-bound recovery tokens",severity:"LOW",fix:"Tokens expire quickly and can only be used once",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"})},schema:[{type:"object",properties:{minTokenEntropy:{type:"number",minimum:64,default:128,description:"Minimum recovery-token entropy in bits"},maxTokenLifetimeHours:{type:"number",minimum:.25,default:1,description:"Maximum recovery-token lifetime in hours"},recoveryKeywords:{type:"array",items:{type:"string"},default:["reset","password","recovery","forgot","token","resetToken"],description:"Identifier keywords that mark password-recovery code"},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:[],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:[{minTokenEntropy:128,maxTokenLifetimeHours:1,recoveryKeywords:["reset","password","recovery","forgot","token","resetToken"],secureTokenFunctions:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{secureTokenFunctions=["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers=[],trustedAnnotations=["secure-recovery","rate-limited"],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});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*\(/.test(text)||/\bDate\s*\.\s*now\s*\(/.test(text)||/new\s+Date\s*\([^)]*\)\s*\.\s*getTime\s*\(/.test(text)||/\buuid\s*\.\s*v1\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"&&callee.property.type==="Identifier"?callee.property.name: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{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"){const weakPatterns=["Date.now()","Math.random()","timestamp","new Date()"];if(weakPatterns.some(pattern=>initText.includes(pattern))){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")&&callee.property.type==="Identifier"&&["log","info","warn","error"].includes(callee.property.name)||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 CREDENTIAL_GENERATORS=new Set(["randomBytes","randomUUID","randomInt","getRandomValues","nanoid","uuidv4"]);exports.noWeakPasswordRecovery=(0,eslint_devkit_1.createRule)({name:"no-weak-password-recovery",meta:{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}],create(context){const options=context.options[0]||{};const{secureTokenFunctions=["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers=[],trustedAnnotations=["secure-recovery","rate-limited"],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});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*\(/.test(text)||/\bDate\s*\.\s*now\s*\(/.test(text)||/new\s+Date\s*\([^)]*\)\s*\.\s*getTime\s*\(/.test(text)||/\buuid\s*\.\s*v1\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"&&callee.property.type==="Identifier"?callee.property.name: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{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"){const weakPatterns=["Date.now()","Math.random()","timestamp","new Date()"];if(weakPatterns.some(pattern=>initText.includes(pattern))){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")&&callee.property.type==="Identifier"&&["log","info","warn","error"].includes(callee.property.name)||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(`\\/\\/|\\/\\*(?![\\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," "))}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"},hasSuggestions:true,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"}),useParameterizedXpath:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Parameterized XPath",description:"Use parameterized XPath queries",severity:"LOW",fix:"Construct XPath with proper escaping and validation",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),escapeXpathInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Escape XPath Input",description:"Escape special characters in XPath input",severity:"LOW",fix:"Use xpath.escape() or equivalent escaping function",documentationLink:"https://www.npmjs.com/package/xpath-escape"}),validateXpathQueries:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate XPath Queries",description:"Validate XPath queries against allowed patterns",severity:"LOW",fix:"Whitelist allowed XPath operations and validate syntax",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),strategyParameterizedQueries:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Parameterized Queries Strategy",description:"Use parameterized XPath construction",severity:"LOW",fix:"Build XPath queries programmatically with escaped parameters",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate XPath input at application boundary",severity:"LOW",fix:"Validate XPath syntax and restrict to safe operations",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"}),strategySafeConstruction:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Safe Construction Strategy",description:"Use safe XPath construction libraries",severity:"LOW",fix:"Use libraries that provide safe XPath building",documentationLink:"https://www.npmjs.com/package/xpath-builder"})},schema:[{type:"object",properties:{xpathFunctions:{type:"array",items:{type:"string"},default:["evaluate","selectSingleNode","selectNodes","xpath","select"],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)"}},additionalProperties:false}]},defaultOptions:[{xpathFunctions:["evaluate","selectSingleNode","selectNodes","xpath","select"],safeXpathConstructors:["buildXPath","createXPath","safeXPath","xpathBuilder"],xpathValidationFunctions:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers:[],trustedAnnotations:["@xpath-safe"],strictMode:false}],create(context){const options=context.options[0]||{};const{xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;function isXpathSinkCall(call){const callee=call.callee;const name=callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:null;return name!==null&&xpathFunctions.includes(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==="MemberExpression"&&callee.property.type==="Identifier"&&xpathFunctions.includes(callee.property.name)){return true}if(callee.type==="Identifier"&&xpathFunctions.includes(callee.name)){return true}return false};const containsDangerousXpath=xpathText=>{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};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)}})}}},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}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}context.report({node,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"useParameterizedXpath",fix:()=>null}]})}}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 leftUntrusted=isUntrustedXpathInput(node.left)&&!isXpathInputValidated(node.left)&&!(node.left.type==="Identifier"&&validatedVariables.has(node.left.name));const rightUntrusted=isUntrustedXpathInput(node.right)&&!isXpathInputValidated(node.right)&&!(node.right.type==="Identifier"&&validatedVariables.has(node.right.name));if(leftUntrusted||rightUntrusted){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){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:String(node.loc?.start.line??0)}})}}else if(isUntrustedXpathInput(node.init)){context.report({node:node.init,messageId:"xpathInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),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.*/-])|\\[@|\\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 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;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)}})}}},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}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}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
|
|
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 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireBackendAuthorization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");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:[
|
|
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 node.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.property.value==="string"?node.property.value: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");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: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:[]},defaultOptions:[],create(context){return{Property(node){if(
|
|
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;if(node.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.key.value==="string"){return node.key.value}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"})}}}}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.confirmsRedos=confirmsRedos;exports.oracleAvailable=oracleAvailable;exports.resetOracleForTests=resetOracleForTests;exports.__setOracleForTests=__setOracleForTests;let loaded;let moduleId="recheck";function oracle(){if(loaded!==void 0)return loaded;try{loaded=require(moduleId)}catch{loaded=null}return loaded}const decided=new Map;function confirmsRedos(source,flags,timeoutMs=1e3){const recheck=oracle();if(recheck===null)return true;const key=`${flags} ${source}`;const memo=decided.get(key);if(memo!==void 0)return memo;let survives=true;try{const result=recheck.checkSync(source,flags,{timeout:timeoutMs});survives=result.status!=="safe"}catch{survives=true}decided.set(key,survives);return survives}function oracleAvailable(){return oracle()!==null}function resetOracleForTests(forceAbsent=false){loaded=forceAbsent?null:void 0;moduleId="recheck";decided.clear()}function __setOracleForTests(next){decided.clear();if(typeof next==="string"){moduleId=next;loaded=void 0;return}loaded=next}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveVariable=resolveVariable;exports.isEnvironmentGlobal=isEnvironmentGlobal;exports.isRegExpConstructor=isRegExpConstructor;exports.asDirectConstruction=asDirectConstruction;const GLOBAL_NAMESPACES=new Set(["globalThis","global","window","self"]);function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name)??null;if(variable!==null){return variable}}return null}function isEnvironmentGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function isRegExpConstructor(node,sourceCode,depth=0){if(depth>4){return false}if(node.type==="MemberExpression"){return!node.computed&&node.property.type==="Identifier"&&node.property.name==="RegExp"&&node.object.type==="Identifier"&&GLOBAL_NAMESPACES.has(node.object.name)&&isEnvironmentGlobal(node.object.name,sourceCode.getScope(node.object))}if(node.type!=="Identifier"){return false}if(node.name==="RegExp"&&isEnvironmentGlobal(node.name,sourceCode.getScope(node))){return true}const variable=resolveVariable(node.name,sourceCode.getScope(node));if(variable===null||variable.defs.length!==1){return false}const definition=variable.defs[0];if(definition.type==="ClassName"){const superClass=definition.node.superClass;return superClass!=null&&isRegExpConstructor(superClass,sourceCode,depth+1)}if(definition.type!=="Variable"||definition.parent.kind!=="const"){return false}if(definition.node.id.type==="ObjectPattern"){const namespace=definition.node.init;if(namespace===null||namespace.type!=="Identifier"){return false}if(!GLOBAL_NAMESPACES.has(namespace.name)||!isEnvironmentGlobal(namespace.name,sourceCode.getScope(namespace))){return false}return definition.node.id.properties.some(property=>property.type==="Property"&&!property.computed&&property.key.type==="Identifier"&&property.key.name==="RegExp"&&property.value.type==="Identifier"&&property.value.name===node.name)}const init=definition.node.init;return init!==null&&isRegExpConstructor(init,sourceCode,depth+1)}function asDirectConstruction(node,sourceCode){if(node.type!=="CallExpression"||node.callee.type!=="MemberExpression"||node.callee.computed||node.callee.property.type!=="Identifier"||node.callee.property.name!=="construct"||node.callee.object.type!=="Identifier"||node.callee.object.name!=="Reflect"||!isEnvironmentGlobal(node.callee.object.name,sourceCode.getScope(node.callee.object))){return node}const[target,argsArray]=node.arguments;if(target===void 0||!isRegExpConstructor(target,sourceCode)){return node}if(argsArray===void 0||argsArray.type!=="ArrayExpression"){return node}return{...node,callee:target,arguments:argsArray.elements.filter(element=>element!==null)}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolvedReference=void 0;const indexes=new WeakMap;const indexOf=scope=>{const existing=indexes.get(scope);if(existing)return existing;const built=new Map;for(const reference of scope.references){if(!built.has(reference.identifier))built.set(reference.identifier,reference.resolved??null)}indexes.set(scope,built);return built};const resolvedReference=(scope,node)=>indexOf(scope).get(node)??null;exports.resolvedReference=resolvedReference;
|