eslint-plugin-secure-coding 5.4.16 → 5.5.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 +26 -0
- package/package.json +5 -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-bidi-characters/index.js +1 -1
- package/src/rules/no-directive-injection/index.js +1 -1
- package/src/rules/no-disabled-template-escaping/index.js +1 -0
- 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-homoglyph-identifiers/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-invisible-characters/index.js +1 -0
- 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 +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-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
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureComparison=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const fileUsesAstTooling=(0,eslint_devkit_2.createModuleEvidence)({packages:["@babel/types","@babel/traverse","@babel/generator","@babel/parser","recast","jscodeshift","estree-walker","unist-util-visit","@typescript-eslint/utils","@typescript-eslint/typescript-estree","typescript","ts-morph","eslint"]});exports.noInsecureComparison=(0,eslint_devkit_2.createRule)({name:"no-insecure-comparison",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-insecure-comparison.md",description:"Detects insecure comparison operators (==, !=) that can lead to type coercion vulnerabilities",cwe:"CWE-697",cvss:5.3},hasSuggestions:true,messages:{insecureComparison:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure Comparison",cwe:"CWE-697",description:"Insecure comparison operator ({{operator}}) detected - can lead to type coercion vulnerabilities",severity:"HIGH",fix:"Use strict equality ({{strictOperator}}) instead: {{example}} \u2014 Not a finding if the comparison is against null, which tests null and undefined together on purpose",documentationLink:"https://cwe.mitre.org/data/definitions/697.html"}),useStrictEquality:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Strict Equality",description:"Use strict equality operator",severity:"LOW",fix:"Replace == with === and != with !== \u2014 Not a finding if the comparison is the idiomatic `x == null` nullish test",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality"}),useTimingSafeEqual:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use A Constant-Time Comparison",description:"Compare secrets in constant time, not with an operator that short-circuits",severity:"LOW",fix:"Rewrite as crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) \u2014 Not a finding if neither side is a secret the caller can guess one character at a time",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"}),timingUnsafeComparison:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Timing Attack Risk",cwe:"CWE-208",description:"Secret comparison with {{operator}} can leak timing information",severity:"HIGH",fix:"Use crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) \u2014 Not a finding if the compared value is public, such as an id or a status",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow insecure comparison in test files"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},reportLooseEquality:{type:"boolean",default:true,description:"Report `==` between non-secret operands. Turn off to keep only the secret-comparison findings and leave generic type coercion to eqeqeq."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,ignorePatterns:[],reportLooseEquality:true}],
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureComparison=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const fileUsesAstTooling=(0,eslint_devkit_2.createModuleEvidence)({packages:["@babel/types","@babel/traverse","@babel/generator","@babel/parser","recast","jscodeshift","estree-walker","unist-util-visit","@typescript-eslint/utils","@typescript-eslint/typescript-estree","typescript","ts-morph","eslint"]});exports.noInsecureComparison=(0,eslint_devkit_2.createRule)({name:"no-insecure-comparison",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-insecure-comparison.md",description:"Detects insecure comparison operators (==, !=) that can lead to type coercion vulnerabilities",cwe:"CWE-697",cvss:5.3},hasSuggestions:true,messages:{insecureComparison:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure Comparison",cwe:"CWE-697",description:"Insecure comparison operator ({{operator}}) detected - can lead to type coercion vulnerabilities",severity:"HIGH",fix:"Use strict equality ({{strictOperator}}) instead: {{example}} \u2014 Not a finding if the comparison is against null, which tests null and undefined together on purpose",documentationLink:"https://cwe.mitre.org/data/definitions/697.html"}),useStrictEquality:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Strict Equality",description:"Use strict equality operator",severity:"LOW",fix:"Replace == with === and != with !== \u2014 Not a finding if the comparison is the idiomatic `x == null` nullish test",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality"}),useTimingSafeEqual:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use A Constant-Time Comparison",description:"Compare secrets in constant time, not with an operator that short-circuits",severity:"LOW",fix:"Rewrite as crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) \u2014 Not a finding if neither side is a secret the caller can guess one character at a time",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"}),timingUnsafeComparison:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Timing Attack Risk",cwe:"CWE-208",description:"Secret comparison with {{operator}} can leak timing information",severity:"HIGH",fix:"Use crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) \u2014 Not a finding if the compared value is public, such as an id or a status",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow insecure comparison in test files"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},reportLooseEquality:{type:"boolean",default:true,description:"Report `==` between non-secret operands. Turn off to keep only the secret-comparison findings and leave generic type coercion to eqeqeq."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,ignorePatterns:[],reportLooseEquality:true}],createOnce(context,currentOptions){let allowInTests;let ignorePatterns;let reportLooseEquality;let isTestFile;let sourceCode;let isCodemodFile;function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return text.toLowerCase().includes(pattern.toLowerCase())}})}function isNullLiteral(node){return node.type==="Literal"&&node.raw==="null"}function isStringTyped(node,seen=new Set){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return typeof node.value==="string";if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(seen.has(node.name))return false;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length===0)return false;return writes.every(ref=>{const written=ref.writeExpr;return written!=null&&isStringTyped(written,seen)})}return false}function checkBinaryExpression(node){if(isTestFile){return}if(isCodemodFile){return}const secretKeywords=new Set(["secret","secrets","token","tokens","password","passwd","pwd","apikey","api_key","secretkey","secret_key","privatekey","private_key","signature","hmac","digest","checksum","nonce","otp","passwordhash","password_hash","hashedpassword","hashed_password","credential","credentials"]);const nameSegments=name=>{const parts=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map(p=>p.toLowerCase());const pairs=[];for(let i=0;i+1<parts.length;i+=1){pairs.push(parts[i]+parts[i+1],`${parts[i]}_${parts[i+1]}`)}return[...parts,...pairs,parts.join(""),parts.join("_"),name.toLowerCase()]};const scopeAtNode=sourceCode.getScope(node);const destructuringKeys=(pattern,target)=>{const keys=[];const walkPattern=n=>{if(n.type==="ObjectPattern"){for(const property of n.properties){if(property.type!=="Property")continue;if(property.value===target&&!property.computed&&property.key.type==="Identifier"){keys.push(property.key.name)}walkPattern(property.value)}}else if(n.type==="ArrayPattern"){for(const element of n.elements)if(element)walkPattern(element)}else if(n.type==="AssignmentPattern"){walkPattern(n.left)}};walkPattern(pattern);return keys};const namesIn=expr=>{const out=[];const visited=new Set;const walk=n=>{if(visited.has(n))return;visited.add(n);if(n.type==="Identifier"){out.push(n.name);resolveIdentifier(n)}else if(n.type==="MemberExpression"){walk(n.object);const key=(0,eslint_devkit_1.propertyName)(n);if(key!==null)out.push(key);else walk(n.property)}else if(n.type==="CallExpression"){walk(n.callee)}else if(n.type==="ConditionalExpression"){walk(n.consequent);walk(n.alternate)}else if(n.type==="TSAsExpression"||n.type==="TSSatisfiesExpression"||n.type==="TSNonNullExpression"){walk(n.expression)}};function resolveIdentifier(identifier){for(let scope=scopeAtNode;scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());const isObjectDestructured=variable.defs.some(def=>def.type==="Variable"&&def.node.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern);if(!isObjectDestructured&&writes.length===1&&writes[0].writeExpr){walk(writes[0].writeExpr)}for(const def of variable.defs){if(def.type!=="Variable")continue;out.push(...destructuringKeys(def.node.id,def.name))}return}}walk(expr);return out};const isPotentialSecret=expr=>namesIn(expr).flatMap(nameSegments).some(segment=>secretKeywords.has(segment));if((node.operator==="==="||node.operator==="!==")&&(isPotentialSecret(node.left)||isPotentialSecret(node.right))){const isLengthComparison=expr=>{return expr.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(expr)==="length"};if(isLengthComparison(node.left)||isLengthComparison(node.right)){return}const isNonSecretLiteral=expr=>expr.type===eslint_devkit_1.AST_NODE_TYPES.Literal||expr.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&expr.expressions.length===0||expr.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&expr.argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal||expr.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&expr.name==="undefined";if(isNonSecretLiteral(node.left)||isNonSecretLiteral(node.right)){return}const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`crypto.timingSafeEqual(Buffer.from(${leftText}), Buffer.from(${rightText}))`;context.report({node,messageId:"timingUnsafeComparison",data:{operator:node.operator,strictOperator:node.operator,example},suggest:[{messageId:"useTimingSafeEqual",fix:fixer=>fixer.replaceText(node,example)}]});return}if(node.operator==="=="||node.operator==="!="){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isNullLiteral(node.left)||isNullLiteral(node.right)){return}if(isStringTyped(node.left)&&isStringTyped(node.right)){return}const comparesSecret=isPotentialSecret(node.left)||isPotentialSecret(node.right);if(!reportLooseEquality&&!comparesSecret){return}const strictOperator=node.operator==="=="?"===":"!==";const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`${leftText} ${strictOperator} ${rightText}`;context.report({node,messageId:"insecureComparison",data:{operator:node.operator,strictOperator,example},suggest:[{messageId:"useStrictEquality",fix:fixer=>{return fixer.replaceText(node,example)}}]})}}return{before(){const[options={}]=currentOptions();({allowInTests=false,ignorePatterns=[],reportLooseEquality=true}=options);const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);sourceCode=context.sourceCode;isCodemodFile=(()=>{if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;return fileUsesAstTooling(sourceCode.ast)})()},BinaryExpression:checkBinaryExpression}}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInvisibleCharacters=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const INVISIBLE_LETTERS=new Map([["\u115F","U+115F HANGUL CHOSEONG FILLER"],["\u1160","U+1160 HANGUL JUNGSEONG FILLER"],["\u17B4","U+17B4 KHMER VOWEL INHERENT AQ"],["\u17B5","U+17B5 KHMER VOWEL INHERENT AA"],["\u3164","U+3164 HANGUL FILLER"],["\uFFA0","U+FFA0 HALFWIDTH HANGUL FILLER"]]);const INVISIBLE_PATTERN=new RegExp(`[${[...INVISIBLE_LETTERS.keys()].join("")}]`,"g");const inComment=(comments,index)=>comments.some(({range:[start,end]})=>index>=start&&index<end);exports.noInvisibleCharacters=(0,eslint_devkit_1.createRule)({name:"no-invisible-characters",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-invisible-characters",description:"Disallows invisible letters such as the Hangul fillers (U+3164, U+FFA0), which hide identifiers, values and comment text from code review (CWE-1007)",cwe:"CWE-1007",cweJustification:"CWE-1007 (Insufficient Visual Distinction of Homoglyphs Presented to User) \u2014 the reviewer is the user and the editor is the display: `admin` and `adm<U+3164>in` are two identifiers rendered as one, so a reviewer approves a binding or a value that is not the one the program uses. Chosen over CWE-176 (Improper Handling of Unicode Encoding), which describes a product mishandling Unicode it receives as input; here nothing is mishandled \u2014 the parser reads the character correctly, and the weakness is entirely in what the human can see. It is also the CWE the sibling rules no-bidi-characters and no-homoglyph-identifiers carry for the same review-deception class.",cvss:5.3},hasSuggestions:true,messages:{invisibleCharacterInCode:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Invisible character in code (CWE-1007)",cwe:"CWE-1007",description:"{{characterName}} found in code. It renders as nothing but is a real character: inside a name it makes a different identifier, inside a string a different value, and alone it is an identifier a reviewer cannot see.",severity:"MEDIUM",fix:"Remove the character. If a string genuinely needs it, write it as an escape (\\u3164) so it is visible in review.",documentationLink:"https://certitude.consulting/blog/en/invisible-backdoor/"}),invisibleCharacterInComment:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Invisible character in comment (CWE-1007)",cwe:"CWE-1007",description:"{{characterName}} found in a comment. It renders as nothing, so the comment a reviewer reads is not the text that is there.",severity:"MEDIUM",fix:"Remove the character.",documentationLink:"https://certitude.consulting/blog/en/invisible-backdoor/"}),removeInvisibleCharacter:"Remove {{characterName}}"},schema:[]},defaultOptions:[],createOnce(context){return{Program(node){const{sourceCode}=context;const text=sourceCode.text;const comments=sourceCode.getAllComments();for(const match of text.matchAll(INVISIBLE_PATTERN)){const index=match.index;const characterName=INVISIBLE_LETTERS.get(match[0]);const range=[index,index+1];context.report({node,loc:{start:sourceCode.getLocFromIndex(index),end:sourceCode.getLocFromIndex(index+1)},messageId:inComment(comments,index)?"invisibleCharacterInComment":"invisibleCharacterInCode",data:{characterName},suggest:[{messageId:"removeInvisibleCharacter",data:{characterName},fix:fixer=>fixer.removeRange(range)}]})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLdapInjection=void 0;exports.containsDangerousLdapFilter=containsDangerousLdapFilter;exports.looksLikeLdapFilterGrammar=looksLikeLdapFilterGrammar;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 containsDangerousLdapFilter(filterText){const dangerousPatterns=[/\*\)$/,/\|\)$/,/&\)$/,/!\)$/,/\*\|\*/,/\*&\*/,/\*!/];return dangerousPatterns.some(pattern=>pattern.test(filterText))}function looksLikeLdapFilterGrammar(staticText){return/\(\s*[A-Za-z][\w.;-]*\s*(?:[:~<>]?=)/.test(staticText)}const DEFAULT_LDAP_PACKAGES=["ldapjs","ldapts","ldapauth-fork","passport-ldapauth","ldap-authentication","ldap-escape","ldap-filter","activedirectory","activedirectory2","node-ldap"];const LDAP_SCOPES=new Set(["@ldapjs"]);const SEARCH_METHODS=new Set(["search","searchAsync","searchPaginated"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","httpRequest"];const DEFAULT_LDAP_FUNCTIONS=["search","searchAsync","searchPaginated","bind","modify","modifyDN","add","del","delete","compare"];const DEFAULT_ESCAPE_FUNCTIONS=["escape.filterValue","escape.dnValue","filterValue","dnValue","filterEscape","dnEscape"];const DEFAULT_VALIDATION_FUNCTIONS=["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"];exports.noLdapInjection=(0,eslint_devkit_1.createRule)({name:"no-ldap-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-ldap-injection.md",description:"Detects LDAP injection vulnerabilities",cwe:"CWE-90"},messages:{ldapInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"LDAP Injection",cwe:"CWE-90",description:"LDAP injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),unsafeLdapFilter:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe LDAP Filter",cwe:"CWE-90",description:"LDAP filter constructed with unsafe string operations",severity:"HIGH",fix:"Use ldap.escape.filterValue() to escape user input",documentationLink:"https://ldap.com/ldap-filters/"}),unescapedLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped LDAP Input",cwe:"CWE-90",description:"LDAP operation uses unescaped user input",severity:"MEDIUM",fix:"Escape all user input before LDAP operations",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),dangerousLdapOperation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous LDAP Operation",cwe:"CWE-90",description:"LDAP operation allows dangerous filter patterns",severity:"HIGH",fix:"Validate LDAP filters and restrict allowed operations",documentationLink:"https://ldap.com/ldap-filters/"}),validateLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate LDAP Input",description:"Validate LDAP input before processing",severity:"LOW",fix:"Validate input against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"})},schema:[{type:"object",properties:{ldapFunctions:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_FUNCTIONS,description:"LDAP client methods treated as query sinks"},ldapEscapeFunctions:{type:"array",items:{type:"string"},default:DEFAULT_ESCAPE_FUNCTIONS,description:"Function names that escape LDAP filter or DN values"},ldapValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_VALIDATION_FUNCTIONS,description:"Function names that count as LDAP input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as LDAP 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)"},ldapPackages:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_PACKAGES,description:"Package specifiers whose import opens the file gate. Nothing in a file is examined unless one of these is loaded. Replaces the built-in list."},additionalLdapPackages:{type:"array",items:{type:"string"},default:[],description:"Extra LDAP client packages, on top of `ldapPackages` \u2014 a house wrapper around ldapjs belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifiers naming a framework request object, matched as the exact ROOT of a member chain \u2014 never as a substring of the printed expression. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."}},additionalProperties:false}]},defaultOptions:[{ldapFunctions:DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions:DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions:DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers:[],trustedAnnotations:[],strictMode:false,ldapPackages:DEFAULT_LDAP_PACKAGES,additionalLdapPackages:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[]}],create(context){const options=context.options[0]||{};const{ldapFunctions=DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions=DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions=DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers=[],trustedAnnotations=[],strictMode=false,ldapPackages=DEFAULT_LDAP_PACKAGES,additionalLdapPackages=[],requestRoots=DEFAULT_REQUEST_ROOTS,additionalRequestRoots=[]}=options;const ldapPackageSet=new Set([...ldapPackages,...additionalLdapPackages]);const requestRootSet=new Set([...requestRoots,...additionalRequestRoots]);const fileImportsLdapClient=(0,eslint_devkit_1.createModuleEvidence)({packages:[...ldapPackageSet],scopes:[...LDAP_SCOPES]});const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const ldapLocals=new Set;let ldapInFile=false;const collectLdapLocals=program=>{const record=node=>{if(node?.type==="Identifier")ldapLocals.add(node.name);else if(node?.type==="ObjectPattern"){for(const property of node.properties){if(property.type==="Property")record(property.value)}}};const isLdapSource=raw=>typeof raw==="string"&&(ldapPackageSet.has(raw)||[...LDAP_SCOPES].some(scope=>raw.startsWith(`${scope}/`)));for(const statement of program.body){if(statement.type==="ImportDeclaration"&&isLdapSource(statement.source.value)){for(const specifier of statement.specifiers)record(specifier.local)}if(statement.type==="VariableDeclaration"){for(const declarator of statement.declarations){const init=declarator.init;if(init?.type==="CallExpression"&&init.callee.type==="Identifier"&&init.callee.name==="require"&&init.arguments[0]?.type==="Literal"&&isLdapSource(init.arguments[0].value)){record(declarator.id)}}}}};const unwrap=node=>{let current=node;while(current.type==="TSAsExpression"||current.type==="TSSatisfiesExpression"||current.type==="TSNonNullExpression"||current.type==="ChainExpression"){current=current.expression}return current};const writesOf=identifier=>{for(let scope=sourceCode.getScope(identifier);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;return variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr).map(ref=>ref.writeExpr)}return[]};const soleWriteOf=identifier=>{const writes=writesOf(identifier);return writes.length===1?writes[0]:void 0};const isLdapConstruction=node=>{const expression=unwrap(node);if(expression.type==="NewExpression"){const{callee:callee2}=expression;if(callee2.type==="Identifier")return ldapLocals.has(callee2.name);return callee2.type==="MemberExpression"&&callee2.object.type==="Identifier"&&ldapLocals.has(callee2.object.name)}if(expression.type!=="CallExpression")return false;const{callee}=expression;if(callee.type==="Identifier")return ldapLocals.has(callee.name);return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&ldapLocals.has(callee.object.name)};const enclosingClassBody=node=>{for(let current=node;current;current=current.parent){if(current.type==="ClassBody")return current}return void 0};const isProvablyNotLdapReceiver=receiver=>{const expression=unwrap(receiver);if(expression.type==="ArrayExpression"||expression.type==="ObjectExpression"||expression.type==="Literal"){return true}if(expression.type==="NewExpression"||expression.type==="CallExpression"){return!isLdapConstruction(expression)}if(expression.type==="Identifier"){const writes=writesOf(expression);if(writes.length===0)return false;if(writes.some(isLdapConstruction))return false;return writes.every(write=>{const value=unwrap(write);return value.type==="NewExpression"||value.type==="CallExpression"||value.type==="ArrayExpression"||value.type==="ObjectExpression"||value.type==="Literal"})}const fieldName=(0,eslint_devkit_1.memberPropertyName)(expression);if(expression.type==="MemberExpression"&&expression.object.type==="ThisExpression"&&fieldName!==null){const body=enclosingClassBody(expression);if(!body)return false;const field=body.body.find(member=>member.type==="PropertyDefinition"&&!member.computed&&member.key.type==="Identifier"&&member.key.name===fieldName);if(!field?.value)return false;return!isLdapConstruction(field.value)}return false};const isEscaped=node=>{const expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(write&&write!==expression&&isEscapedAt(write))return true}return isEscapedAt(node)};function isEscapedAt(node){for(let current=node;current;current=current.parent){if(current.type!=="CallExpression")continue;const{callee}=current;const escapeMethod=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&escapeMethod!==null){if(ldapEscapeFunctions.some(escapeFunc=>escapeFunc===escapeMethod||escapeFunc.endsWith(`.${escapeMethod}`))){return true}}if(callee.type==="Identifier"&&(ldapValidationFunctions.includes(callee.name)||ldapEscapeFunctions.includes(callee.name))){return true}}return false}const isStatic=node=>(0,eslint_devkit_1.isStaticExpression)({node,scope:sourceCode.getScope(node)});const dynamicParts=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return null;seen.add(expression);if(expression.type==="TemplateLiteral"){return expression.expressions.filter(part=>!isStatic(part)&&!isEscaped(part))}if(expression.type==="BinaryExpression"&&expression.operator==="+"){const leaves=[];const flatten=n=>{const inner=unwrap(n);if(inner.type==="BinaryExpression"&&inner.operator==="+"){flatten(inner.left);flatten(inner.right)}else leaves.push(inner)};flatten(expression);const hasStringPart=leaves.some(leaf=>(0,eslint_devkit_1.staticString)(leaf)!==null||leaf.type==="TemplateLiteral");if(!hasStringPart)return null;return leaves.filter(leaf=>!isStatic(leaf)&&!isEscaped(leaf))}if(expression.type==="ConditionalExpression"){const consequent=dynamicParts(expression.consequent,seen);const alternate=dynamicParts(expression.alternate,seen);if(consequent===null&&alternate===null)return null;return[...consequent??[],...alternate??[]]}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?dynamicParts(write,seen):null}return null};const isRequestValue=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return false;seen.add(expression);if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?isRequestValue(write,seen):false}if(expression.type==="CallExpression"){if(isEscaped(expression))return false;return expression.arguments.some(argument=>argument.type!=="SpreadElement"&&isRequestValue(argument,seen))}if(expression.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(expression)===null)return false;return!isStatic(expression)&&isUntrustedRequestChain(expression)};function isUntrustedRequestChain(node){let current=node;while(current.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(current)===null)return false;current=current.object}if(current.type!=="Identifier")return false;if(requestRootSet.has(current.name))return true;for(let scope=sourceCode.getScope(current);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===current.name);if(!variable)continue;return variable.defs.some(def=>{if(def.type!=="Variable")return false;const init=def.node.init?unwrap(def.node.init):void 0;if(!init)return false;if(init.type==="Identifier")return requestRootSet.has(init.name);return init.type==="MemberExpression"&&isUntrustedRequestChain(init)})}return false}const filterOption=node=>{let expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(!write)return void 0;expression=unwrap(write)}if(expression.type!=="ObjectExpression")return void 0;for(const property of expression.properties){if(property.type!=="Property")continue;const{key}=property;if(!property.computed&&key.type==="Identifier"&&key.name==="filter"){return property.value}if(key.type==="Literal"&&key.value==="filter")return property.value;if(property.computed&&key.type==="Identifier"){const keyWrite=soleWriteOf(key);if(keyWrite&&unwrap(keyWrite).type==="Literal"){const literal=unwrap(keyWrite);if(literal.value==="filter")return property.value}}}return void 0};const reported=new Set;const report=(node,messageId,data)=>{if(reported.has(node))return;if(safetyChecker.isSafe(node,context))return;reported.add(node);context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line),...data}})};const staticSkeleton=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return"";seen.add(expression);if(expression.type==="Literal"){return typeof expression.value==="string"?expression.value:""}if(expression.type==="TemplateLiteral"){return expression.quasis.map(quasi=>quasi.value.raw).join("\0")}if(expression.type==="BinaryExpression"&&expression.operator==="+"){return staticSkeleton(expression.left,seen)+"\0"+staticSkeleton(expression.right,seen)}if(expression.type==="ConditionalExpression"){return staticSkeleton(expression.consequent,seen)+"\0"+staticSkeleton(expression.alternate,seen)}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?staticSkeleton(write,seen):""}return""};const originOf=node=>{let current=unwrap(node);for(let hops=0;current.type==="Identifier"&&hops<8;hops+=1){const write=soleWriteOf(current);if(!write)break;current=unwrap(write)}return current};const checkFilter=rawFilterNode=>{const filterNode=originOf(rawFilterNode);const parts=dynamicParts(filterNode);if(parts&&parts.length>0){report(filterNode,"unsafeLdapFilter",{});return}if(isRequestValue(filterNode)){report(filterNode,"unescapedLdapInput",{});return}if(containsDangerousLdapFilter(staticSkeleton(filterNode).split("\0").join(""))){report(filterNode,"dangerousLdapOperation",{})}};const checkDn=rawDnNode=>{const dnNode=originOf(rawDnNode);const parts=dynamicParts(dnNode);if(parts&&parts.length>0){report(dnNode,"ldapInjection",{severity:"HIGH",safeAlternative:"Use ldap.escape.dnValue() or build the DN from validated components"});return}if(isRequestValue(dnNode)){report(dnNode,"ldapInjection",{severity:"MEDIUM",safeAlternative:"Use proper LDAP escaping and validation"})}};const checkConstructedFilter=node=>{if(!looksLikeLdapFilterGrammar(staticSkeleton(node)))return;checkFilter(node)};return{Program(program){ldapInFile=fileImportsLdapClient(program);if(ldapInFile)collectLdapLocals(program)},VariableDeclarator(node){if(!ldapInFile||!node.init)return;checkConstructedFilter(node.init)},AssignmentExpression(node){if(!ldapInFile)return;checkConstructedFilter(node.right)},CallExpression(node){if(!ldapInFile)return;const callee=unwrap(node.callee);if(callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return;if(!ldapFunctions.includes(method))return;if(isProvablyNotLdapReceiver(callee.object))return;const args=node.arguments.filter(argument=>argument.type!=="SpreadElement");if(args.length===0)return;checkDn(args[0]);if(args.length<2)return;if(SEARCH_METHODS.has(method)){const optionsFilter=filterOption(args[1]);checkFilter(optionsFilter??args[1]);return}checkConstructedFilter(args[1])}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLdapInjection=void 0;exports.containsDangerousLdapFilter=containsDangerousLdapFilter;exports.looksLikeLdapFilterGrammar=looksLikeLdapFilterGrammar;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 containsDangerousLdapFilter(filterText){const dangerousPatterns=[/\*\)$/,/\|\)$/,/&\)$/,/!\)$/,/\*\|\*/,/\*&\*/,/\*!/];return dangerousPatterns.some(pattern=>pattern.test(filterText))}function looksLikeLdapFilterGrammar(staticText){return/\(\s*[A-Za-z][\w.;-]*\s*(?:[:~<>]?=)/.test(staticText)}const DEFAULT_LDAP_PACKAGES=["ldapjs","ldapts","ldapauth-fork","passport-ldapauth","ldap-authentication","ldap-escape","ldap-filter","activedirectory","activedirectory2","node-ldap"];const LDAP_SCOPES=new Set(["@ldapjs"]);const SEARCH_METHODS=new Set(["search","searchAsync","searchPaginated"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","httpRequest"];const DEFAULT_LDAP_FUNCTIONS=["search","searchAsync","searchPaginated","bind","modify","modifyDN","add","del","delete","compare"];const DEFAULT_ESCAPE_FUNCTIONS=["escape.filterValue","escape.dnValue","filterValue","dnValue","filterEscape","dnEscape"];const DEFAULT_VALIDATION_FUNCTIONS=["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"];exports.noLdapInjection=(0,eslint_devkit_1.createRule)({name:"no-ldap-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-ldap-injection.md",description:"Detects LDAP injection vulnerabilities",cwe:"CWE-90"},messages:{ldapInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"LDAP Injection",cwe:"CWE-90",description:"LDAP injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),unsafeLdapFilter:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe LDAP Filter",cwe:"CWE-90",description:"LDAP filter constructed with unsafe string operations",severity:"HIGH",fix:"Use ldap.escape.filterValue() to escape user input",documentationLink:"https://ldap.com/ldap-filters/"}),unescapedLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped LDAP Input",cwe:"CWE-90",description:"LDAP operation uses unescaped user input",severity:"MEDIUM",fix:"Escape all user input before LDAP operations",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),dangerousLdapOperation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous LDAP Operation",cwe:"CWE-90",description:"LDAP operation allows dangerous filter patterns",severity:"HIGH",fix:"Validate LDAP filters and restrict allowed operations",documentationLink:"https://ldap.com/ldap-filters/"}),validateLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate LDAP Input",description:"Validate LDAP input before processing",severity:"LOW",fix:"Validate input against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"})},schema:[{type:"object",properties:{ldapFunctions:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_FUNCTIONS,description:"LDAP client methods treated as query sinks"},ldapEscapeFunctions:{type:"array",items:{type:"string"},default:DEFAULT_ESCAPE_FUNCTIONS,description:"Function names that escape LDAP filter or DN values"},ldapValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_VALIDATION_FUNCTIONS,description:"Function names that count as LDAP input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as LDAP 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)"},ldapPackages:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_PACKAGES,description:"Package specifiers whose import opens the file gate. Nothing in a file is examined unless one of these is loaded. Replaces the built-in list."},additionalLdapPackages:{type:"array",items:{type:"string"},default:[],description:"Extra LDAP client packages, on top of `ldapPackages` \u2014 a house wrapper around ldapjs belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifiers naming a framework request object, matched as the exact ROOT of a member chain \u2014 never as a substring of the printed expression. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."}},additionalProperties:false}]},defaultOptions:[{ldapFunctions:DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions:DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions:DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers:[],trustedAnnotations:[],strictMode:false,ldapPackages:DEFAULT_LDAP_PACKAGES,additionalLdapPackages:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[]}],createOnce(context){let ldapFunctions;let ldapEscapeFunctions;let ldapValidationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let ldapPackages;let additionalLdapPackages;let requestRoots;let additionalRequestRoots;let ldapPackageSet;let requestRootSet;let fileImportsLdapClient;let sourceCode;let filename;let safetyChecker;let ldapLocals;let ldapInFile;let reported;const collectLdapLocals=program=>{const record=node=>{if(node?.type==="Identifier")ldapLocals.add(node.name);else if(node?.type==="ObjectPattern"){for(const property of node.properties){if(property.type==="Property")record(property.value)}}};const isLdapSource=raw=>typeof raw==="string"&&(ldapPackageSet.has(raw)||[...LDAP_SCOPES].some(scope=>raw.startsWith(`${scope}/`)));for(const statement of program.body){if(statement.type==="ImportDeclaration"&&isLdapSource(statement.source.value)){for(const specifier of statement.specifiers)record(specifier.local)}if(statement.type==="VariableDeclaration"){for(const declarator of statement.declarations){const init=declarator.init;if(init?.type==="CallExpression"&&init.callee.type==="Identifier"&&init.callee.name==="require"&&init.arguments[0]?.type==="Literal"&&isLdapSource(init.arguments[0].value)){record(declarator.id)}}}}};const unwrap=node=>{let current=node;while(current.type==="TSAsExpression"||current.type==="TSSatisfiesExpression"||current.type==="TSNonNullExpression"||current.type==="ChainExpression"){current=current.expression}return current};const writesOf=identifier=>{for(let scope=sourceCode.getScope(identifier);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;return variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr).map(ref=>ref.writeExpr)}return[]};const soleWriteOf=identifier=>{const writes=writesOf(identifier);return writes.length===1?writes[0]:void 0};const isLdapConstruction=node=>{const expression=unwrap(node);if(expression.type==="NewExpression"){const{callee:callee2}=expression;if(callee2.type==="Identifier")return ldapLocals.has(callee2.name);return callee2.type==="MemberExpression"&&callee2.object.type==="Identifier"&&ldapLocals.has(callee2.object.name)}if(expression.type!=="CallExpression")return false;const{callee}=expression;if(callee.type==="Identifier")return ldapLocals.has(callee.name);return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&ldapLocals.has(callee.object.name)};const enclosingClassBody=node=>{for(let current=node;current;current=current.parent){if(current.type==="ClassBody")return current}return void 0};const isProvablyNotLdapReceiver=receiver=>{const expression=unwrap(receiver);if(expression.type==="ArrayExpression"||expression.type==="ObjectExpression"||expression.type==="Literal"){return true}if(expression.type==="NewExpression"||expression.type==="CallExpression"){return!isLdapConstruction(expression)}if(expression.type==="Identifier"){const writes=writesOf(expression);if(writes.length===0)return false;if(writes.some(isLdapConstruction))return false;return writes.every(write=>{const value=unwrap(write);return value.type==="NewExpression"||value.type==="CallExpression"||value.type==="ArrayExpression"||value.type==="ObjectExpression"||value.type==="Literal"})}const fieldName=(0,eslint_devkit_1.memberPropertyName)(expression);if(expression.type==="MemberExpression"&&expression.object.type==="ThisExpression"&&fieldName!==null){const body=enclosingClassBody(expression);if(!body)return false;const field=body.body.find(member=>member.type==="PropertyDefinition"&&!member.computed&&member.key.type==="Identifier"&&member.key.name===fieldName);if(!field?.value)return false;return!isLdapConstruction(field.value)}return false};const isEscaped=node=>{const expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(write&&write!==expression&&isEscapedAt(write))return true}return isEscapedAt(node)};function isEscapedAt(node){for(let current=node;current;current=current.parent){if(current.type!=="CallExpression")continue;const{callee}=current;const escapeMethod=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&escapeMethod!==null){if(ldapEscapeFunctions.some(escapeFunc=>escapeFunc===escapeMethod||escapeFunc.endsWith(`.${escapeMethod}`))){return true}}if(callee.type==="Identifier"&&(ldapValidationFunctions.includes(callee.name)||ldapEscapeFunctions.includes(callee.name))){return true}}return false}const isStatic=node=>(0,eslint_devkit_1.isStaticExpression)({node,scope:sourceCode.getScope(node)});const dynamicParts=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return null;seen.add(expression);if(expression.type==="TemplateLiteral"){return expression.expressions.filter(part=>!isStatic(part)&&!isEscaped(part))}if(expression.type==="BinaryExpression"&&expression.operator==="+"){const leaves=[];const flatten=n=>{const inner=unwrap(n);if(inner.type==="BinaryExpression"&&inner.operator==="+"){flatten(inner.left);flatten(inner.right)}else leaves.push(inner)};flatten(expression);const hasStringPart=leaves.some(leaf=>(0,eslint_devkit_1.staticString)(leaf)!==null||leaf.type==="TemplateLiteral");if(!hasStringPart)return null;return leaves.filter(leaf=>!isStatic(leaf)&&!isEscaped(leaf))}if(expression.type==="ConditionalExpression"){const consequent=dynamicParts(expression.consequent,seen);const alternate=dynamicParts(expression.alternate,seen);if(consequent===null&&alternate===null)return null;return[...consequent??[],...alternate??[]]}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?dynamicParts(write,seen):null}return null};const isRequestValue=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return false;seen.add(expression);if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?isRequestValue(write,seen):false}if(expression.type==="CallExpression"){if(isEscaped(expression))return false;return expression.arguments.some(argument=>argument.type!=="SpreadElement"&&isRequestValue(argument,seen))}if(expression.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(expression)===null)return false;return!isStatic(expression)&&isUntrustedRequestChain(expression)};function isUntrustedRequestChain(node){let current=node;while(current.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(current)===null)return false;current=current.object}if(current.type!=="Identifier")return false;if(requestRootSet.has(current.name))return true;for(let scope=sourceCode.getScope(current);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===current.name);if(!variable)continue;return variable.defs.some(def=>{if(def.type!=="Variable")return false;const init=def.node.init?unwrap(def.node.init):void 0;if(!init)return false;if(init.type==="Identifier")return requestRootSet.has(init.name);return init.type==="MemberExpression"&&isUntrustedRequestChain(init)})}return false}const filterOption=node=>{let expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(!write)return void 0;expression=unwrap(write)}if(expression.type!=="ObjectExpression")return void 0;for(const property of expression.properties){if(property.type!=="Property")continue;const{key}=property;if(!property.computed&&key.type==="Identifier"&&key.name==="filter"){return property.value}if(key.type==="Literal"&&key.value==="filter")return property.value;if(property.computed&&key.type==="Identifier"){const keyWrite=soleWriteOf(key);if(keyWrite&&unwrap(keyWrite).type==="Literal"){const literal=unwrap(keyWrite);if(literal.value==="filter")return property.value}}}return void 0};const report=(node,messageId,data)=>{if(reported.has(node))return;if(safetyChecker.isSafe(node,context))return;reported.add(node);context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line),...data}})};const staticSkeleton=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return"";seen.add(expression);if(expression.type==="Literal"){return typeof expression.value==="string"?expression.value:""}if(expression.type==="TemplateLiteral"){return expression.quasis.map(quasi=>quasi.value.raw).join("\0")}if(expression.type==="BinaryExpression"&&expression.operator==="+"){return staticSkeleton(expression.left,seen)+"\0"+staticSkeleton(expression.right,seen)}if(expression.type==="ConditionalExpression"){return staticSkeleton(expression.consequent,seen)+"\0"+staticSkeleton(expression.alternate,seen)}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?staticSkeleton(write,seen):""}return""};const originOf=node=>{let current=unwrap(node);for(let hops=0;current.type==="Identifier"&&hops<8;hops+=1){const write=soleWriteOf(current);if(!write)break;current=unwrap(write)}return current};const checkFilter=rawFilterNode=>{const filterNode=originOf(rawFilterNode);const parts=dynamicParts(filterNode);if(parts&&parts.length>0){report(filterNode,"unsafeLdapFilter",{});return}if(isRequestValue(filterNode)){report(filterNode,"unescapedLdapInput",{});return}if(containsDangerousLdapFilter(staticSkeleton(filterNode).split("\0").join(""))){report(filterNode,"dangerousLdapOperation",{})}};const checkDn=rawDnNode=>{const dnNode=originOf(rawDnNode);const parts=dynamicParts(dnNode);if(parts&&parts.length>0){report(dnNode,"ldapInjection",{severity:"HIGH",safeAlternative:"Use ldap.escape.dnValue() or build the DN from validated components"});return}if(isRequestValue(dnNode)){report(dnNode,"ldapInjection",{severity:"MEDIUM",safeAlternative:"Use proper LDAP escaping and validation"})}};const checkConstructedFilter=node=>{if(!looksLikeLdapFilterGrammar(staticSkeleton(node)))return;checkFilter(node)};return{before(){const options=context.options[0]||{};({ldapFunctions=DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions=DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions=DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers=[],trustedAnnotations=[],strictMode=false,ldapPackages=DEFAULT_LDAP_PACKAGES,additionalLdapPackages=[],requestRoots=DEFAULT_REQUEST_ROOTS,additionalRequestRoots=[]}=options);ldapPackageSet=new Set([...ldapPackages,...additionalLdapPackages]);requestRootSet=new Set([...requestRoots,...additionalRequestRoots]);fileImportsLdapClient=(0,eslint_devkit_1.createModuleEvidence)({packages:[...ldapPackageSet],scopes:[...LDAP_SCOPES]});sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});ldapLocals=new Set;ldapInFile=false;reported=new Set},Program(program){ldapInFile=fileImportsLdapClient(program);if(ldapInFile)collectLdapLocals(program)},VariableDeclarator(node){if(!ldapInFile||!node.init)return;checkConstructedFilter(node.init)},AssignmentExpression(node){if(!ldapInFile)return;checkConstructedFilter(node.right)},CallExpression(node){if(!ldapInFile)return;const callee=unwrap(node.callee);if(callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return;if(!ldapFunctions.includes(method))return;if(isProvablyNotLdapReceiver(callee.object))return;const args=node.arguments.filter(argument=>argument.type!=="SpreadElement");if(args.length===0)return;checkDn(args[0]);if(args.length<2)return;if(SEARCH_METHODS.has(method)){const optionsFilter=filterOption(args[1]);checkFilter(optionsFilter??args[1]);return}checkConstructedFilter(args[1])}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLogInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_LOGGER_RECEIVERS=["console","log","logger","winston","pino","bunyan"];const LOG_LEVEL_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];function requestFieldOf(node,roots,requestProperties){if(node.type!=="MemberExpression")return null;const properties=[];let root=node;while(root.type==="MemberExpression"){const name=(0,eslint_devkit_1.propertyName)(root);if(name!==null)properties.unshift(name);root=root.object}if(root.type!=="Identifier")return null;if(!roots.has(root.name))return null;if(!properties.some(p=>requestProperties.has(p)))return null;return`${root.name}.${properties.join(".")}`}function findLocalVariable(scope,name){let current=scope;for(;;){const variable=current.set.get(name);if(variable)return variable;if(current.type==="function"||!current.upper)return null;current=current.upper}}function attributableSource(node,scope,roots,requestProperties){if(node.type==="Identifier"){const variable=findLocalVariable(scope,node.name);if(!variable)return null;const definition=variable.defs[0];if(!definition||definition.type!=="Variable"||!definition.node.init){return null}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLogInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_LOGGER_RECEIVERS=["console","log","logger","winston","pino","bunyan"];const LOG_LEVEL_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];function requestFieldOf(node,roots,requestProperties){if(node.type!=="MemberExpression")return null;const properties=[];let root=node;while(root.type==="MemberExpression"){const name=(0,eslint_devkit_1.propertyName)(root);if(name!==null)properties.unshift(name);root=root.object}if(root.type!=="Identifier")return null;if(!roots.has(root.name))return null;if(!properties.some(p=>requestProperties.has(p)))return null;return`${root.name}.${properties.join(".")}`}function findLocalVariable(scope,name){let current=scope;for(;;){const variable=current.set.get(name);if(variable)return variable;if(current.type==="function"||!current.upper)return null;current=current.upper}}const LOOP_TYPES=new Set(["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"]);function isAncestor(outer,inner){for(let n=inner;n;n=n.parent){if(n===outer)return true}return false}function isStraightLineTo(target,read){const statement=target.parent.parent;if(statement?.type!=="ExpressionStatement"&&statement?.type!=="VariableDeclaration"){return false}const block=statement.parent;return(block?.type==="BlockStatement"||block?.type==="Program")&&isAncestor(block,read)}function isCarriedByLoop(write,read,dominator){for(let n=read;n;n=n.parent){if(LOOP_TYPES.has(n.type)&&isAncestor(n,write)&&!(dominator&&isAncestor(n,dominator))){return true}}return false}function writtenRequestField(ref,init,roots,requestProperties){if(ref.init)return requestFieldOf(init,roots,requestProperties);const write=ref.identifier.parent;if(write.type!=="AssignmentExpression"||write.operator!=="="){return null}return requestFieldOf(write.right,roots,requestProperties)}function attributableSource(node,scope,roots,requestProperties){if(node.type==="Identifier"){const variable=findLocalVariable(scope,node.name);if(!variable)return null;const definition=variable.defs[0];if(!definition||definition.type!=="Variable"||!definition.node.init){return null}const writes=variable.references.filter(ref=>ref.isWrite());const reaching=[];let dominator;for(const ref of writes.filter(w=>w.identifier.range[0]<node.range[0]).reverse()){reaching.push(ref);if(isStraightLineTo(ref.identifier,node)){dominator=ref.identifier;break}}for(const ref of writes){if(ref.identifier.range[0]>node.range[0]&&isCarriedByLoop(ref.identifier,node,dominator)){reaching.push(ref)}}for(const ref of reaching){const field=writtenRequestField(ref,definition.node.init,roots,requestProperties);if(field)return field}return null}return requestFieldOf(node,roots,requestProperties)}function isMessageShaped(node){return node.type==="TemplateLiteral"||node.type==="BinaryExpression"&&node.operator==="+"}function directOperands(node,out){if(node.type==="TemplateLiteral"){for(const expression of node.expressions)out.push(expression);return}if(node.type==="BinaryExpression"&&node.operator==="+"){directOperands(node.left,out);directOperands(node.right,out);return}out.push(node)}function receiverName(object,receivers){if(object.type==="Identifier"){return receivers.has(object.name)?object.name:null}if(object.type==="MemberExpression"){const held=(0,eslint_devkit_1.propertyName)(object);return held!==null&&receivers.has(held)?held:null}return null}exports.noLogInjection=(0,eslint_devkit_1.createRule)({name:"no-log-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-log-injection.md",description:"Detects request data concatenated into a log message, which lets an attacker forge log records",cwe:"CWE-117",cvss:5.3},messages:{logInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Log Injection",cwe:"CWE-117",description:"Log message embeds {{source}} directly - a CR/LF in that value forges a log record",severity:"MEDIUM",fix:'Log it as a structured field (logger.info({ value }, "message")) or strip CR/LF/control characters first',documentationLink:"https://cwe.mitre.org/data/definitions/117.html"})},schema:[{type:"object",properties:{loggerReceivers:{type:"array",items:{type:"string"},default:DEFAULT_LOGGER_RECEIVERS,description:"Receiver names whose level methods write a log line, compared as an exact name and never as a substring. Replaces the built-in list."},loggerNames:{type:"array",items:{type:"string"},default:[],description:"Additional receiver names whose level methods write a log line, on top of `loggerReceivers`"},requestRootNames:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},requestRoots:{type:"array",items:{type:"string"},default:[],description:"Additional identifier roots that denote an inbound request, on top of `requestRootNames`"},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here"}},additionalProperties:false}]},defaultOptions:[{loggerReceivers:DEFAULT_LOGGER_RECEIVERS,loggerNames:[],requestRootNames:DEFAULT_REQUEST_ROOTS,requestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[]}],createOnce(context){let receivers;let roots;let requestProperties;let sourceCode;function isLoggingCall(node){const callee=node.callee;if(callee.type!=="MemberExpression")return false;if(!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),LOG_LEVEL_METHODS))return false;return receiverName(callee.object,receivers)!==null}return{before(){const options=context.options[0]??{};receivers=new Set([...options.loggerReceivers??DEFAULT_LOGGER_RECEIVERS,...options.loggerNames??[]]);roots=new Set([...options.requestRootNames??DEFAULT_REQUEST_ROOTS,...options.requestRoots??[]]);requestProperties=new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]);sourceCode=context.sourceCode},CallExpression(node){if(!isLoggingCall(node))return;for(const argument of node.arguments){if(!isMessageShaped(argument))continue;const operands=[];directOperands(argument,operands);for(const operand of operands){const source=attributableSource(operand,sourceCode.getScope(operand),roots,requestProperties);if(source===null)continue;context.report({node:argument,messageId:"logInjection",data:{source}});return}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_AUTH_MIDDLEWARE_PATTERNS=["authenticate","auth","requireAuth","isAuthenticated","verifyToken","checkAuth","ensureAuthenticated","passport.authenticate","jwt","session"];const DEFAULT_PUBLIC_ROUTE_PATTERNS=["login","logout","signin","sign-in","signup","sign-up","register","forgot-password","reset-password","password-reset","verify-email","health","healthz","readyz","livez","alive","liveness","readiness","heartbeat","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];const ROUTER_NAME_WORDS=["app","router","route","server","express","fastify","koa","hapi"];const ROUTER_FACTORY_NAMES=new Set(["express","Router","fastify","polka","restify","connect","Koa"]);const ROUTER_FACTORY_MEMBERS=new Set(["Router","router","Server","server","createServer"]);function routeChainBase(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&¤t.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if((0,eslint_devkit_2.propertyName)(current.callee)==="route"){return current}current=current.callee.object}return null}function isDefinitelyNotRouter(init){return init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}function isRouterFactory(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_NAMES.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_2.propertyName)(callee)!==null){return ROUTER_FACTORY_MEMBERS.has((0,eslint_devkit_2.propertyName)(callee))}return false}function referencedName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=(0,eslint_devkit_1.propertyName)(node);if(property===null)return null;const objectPart=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${node.object.name}.`:"";return`${objectPart}${property}`}return null}function isAuthMiddlewareArg(arg,authPatterns){const target=arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression?arg.callee:arg;const name=referencedName(target);return name!==null&&(0,eslint_devkit_1.nameHasAnyWord)(name,authPatterns)}function isInsideAuthMiddleware(node,authPatterns){let current=node;while(current){if(current.parent&¤t.parent.type==="CallExpression"){const callExpr=current.parent;const isArgument=callExpr.arguments.some(arg=>arg===current);if(!isArgument){current=current.parent;continue}const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,authPatterns)){return true}}if(callee.type==="MemberExpression"&&(0,eslint_devkit_2.propertyName)(callee)!==null){const propertyName=(0,eslint_devkit_2.propertyName)(callee).toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){if(isAuthMiddlewareArg(arg,authPatterns)){return true}}}}}if("parent"in current&¤t.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-missing-authentication.md",description:"Detects missing authentication checks in route handlers",cwe:"CWE-287",cvss:9.8},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authentication",cwe:"CWE-287",description:"Route handler missing authentication check: {{route}}",severity:"CRITICAL",fix:"Add authentication middleware: app.{{method}}('{{path}}', authenticate(), handler)",documentationLink:"https://cwe.mitre.org/data/definitions/287.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing authentication in test files"},authMiddlewarePatterns:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,description:"Authentication middleware patterns to recognize"},routeHandlerPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROUTE_HANDLER_PATTERNS,description:"Route handler patterns to check"},ignorePatterns:{type:"array",items:{type:"string"},default:DEFAULT_PUBLIC_ROUTE_PATTERNS,description:"Route paths that are public by definition and need no authentication. Replaces the built-in list; supplying it also widens matching from the route path to the whole registration text."},routerNameWords:{type:"array",items:{type:"string"},default:ROUTER_NAME_WORDS,description:"Object names that denote an HTTP application or router, compared as WHOLE WORDS and never as a substring. Read only when the binding cannot be resolved to a framework factory call. Replaces the built-in list."},additionalRouterNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra router-object name words, on top of `routerNameWords`."},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords:ROUTER_NAME_WORDS,additionalRouterNameWords:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options;const routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const scansWholeCallText=context.options[0]?.ignorePatterns!==void 0;function looksLikeRouter(object){const scope=sourceCode.getScope(object);const reference=scope.references.find(ref=>ref.identifier===object);const resolved=reference?.resolved;for(const def of resolved?.defs??[]){const parent=def.name.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){if(isRouterFactory(parent.init)){return true}if(isDefinitelyNotRouter(parent.init)){return false}}}return(0,eslint_devkit_1.nameHasAnyWord)(object.name,routerWords)}function findVariableDeclaration(identifier){const varName=identifier.name;let current=identifier;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName){return declarator}}}}}if("parent"in current&¤t.parent){current=current.parent}else{break}}return null}function isIdentifierFromAuthMiddleware(identifier){const declarator=findVariableDeclaration(identifier);if(!declarator||!declarator.init){return false}if(declarator.init.type==="CallExpression"&&declarator.init.callee.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(declarator.init.callee.name,authMiddlewarePatterns)}return false}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const object=node.callee.object;let chainedPath;if(object.type==="Identifier"){if(!looksLikeRouter(object)){return}}else{const base=routeChainBase(object);const baseObject=base?.callee.type==="MemberExpression"?base.callee.object:void 0;if(!base||baseObject?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!looksLikeRouter(baseObject)){return}chainedPath=base.arguments[0]}const resolvedMethod=(0,eslint_devkit_2.propertyName)(node.callee);if(resolvedMethod!==null){const methodName=resolvedMethod.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName!=="use"&&chainedPath===void 0&&node.arguments.length<2){return}if(methodName==="use"){const first=node.arguments[0];const mountsAPath=first!==void 0&&first.type==="Literal"&&typeof first.value==="string";if(!mountsAPath){return}}const pathArgument=chainedPath??node.arguments[0];const routePath=pathArgument.type==="Literal"?String(pathArgument.value):sourceCode.getText(pathArgument);const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(scansWholeCallText&&matchesIgnorePattern(text,ignorePatterns)){return}const firstMiddlewareIndex=chainedPath===void 0?1:0;const middlewareArgs=methodName==="use"?node.arguments.slice(firstMiddlewareIndex):node.arguments.slice(firstMiddlewareIndex,-1);let hasAuth=false;for(const arg of middlewareArgs){if(isAuthMiddlewareArg(arg,authMiddlewarePatterns)){hasAuth=true;break}if(arg.type==="Identifier"&&isIdentifierFromAuthMiddleware(arg)){hasAuth=true;break}}if(!hasAuth&&node.arguments.length>0){const lastArg=node.arguments[node.arguments.length-1];if(lastArg.type==="ArrowFunctionExpression"||lastArg.type==="FunctionExpression"){if(isInsideAuthMiddleware(lastArg,authMiddlewarePatterns)){hasAuth=true}}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath}})}}}}}return{CallExpression:checkCallExpression}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_AUTH_MIDDLEWARE_PATTERNS=["authenticate","auth","requireAuth","isAuthenticated","verifyToken","checkAuth","ensureAuthenticated","passport.authenticate","jwt","session"];const DEFAULT_PUBLIC_ROUTE_PATTERNS=["login","logout","signin","sign-in","signup","sign-up","register","forgot-password","reset-password","password-reset","verify-email","health","healthz","readyz","livez","alive","liveness","readiness","heartbeat","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];const ROUTER_NAME_WORDS=["app","router","route","server","express","fastify","koa","hapi"];const ROUTER_FACTORY_NAMES=new Set(["express","Router","fastify","polka","restify","connect","Koa"]);const ROUTER_FACTORY_MEMBERS=new Set(["Router","router","Server","server","createServer"]);function routeChainBase(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&¤t.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if((0,eslint_devkit_2.propertyName)(current.callee)==="route"){return current}current=current.callee.object}return null}function isDefinitelyNotRouter(init){return init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}function isRouterFactory(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_NAMES.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_2.propertyName)(callee)!==null){return ROUTER_FACTORY_MEMBERS.has((0,eslint_devkit_2.propertyName)(callee))}return false}function referencedName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=(0,eslint_devkit_1.propertyName)(node);if(property===null)return null;const objectPart=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${node.object.name}.`:"";return`${objectPart}${property}`}return null}function isAuthMiddlewareArg(arg,authPatterns){const target=arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression?arg.callee:arg;const name=referencedName(target);return name!==null&&(0,eslint_devkit_1.nameHasAnyWord)(name,authPatterns)}function isInsideAuthMiddleware(node,authPatterns){let current=node;while(current){if(current.parent&¤t.parent.type==="CallExpression"){const callExpr=current.parent;const isArgument=callExpr.arguments.some(arg=>arg===current);if(!isArgument){current=current.parent;continue}const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,authPatterns)){return true}}if(callee.type==="MemberExpression"&&(0,eslint_devkit_2.propertyName)(callee)!==null){const propertyName=(0,eslint_devkit_2.propertyName)(callee).toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){if(isAuthMiddlewareArg(arg,authPatterns)){return true}}}}}if("parent"in current&¤t.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-missing-authentication.md",description:"Detects missing authentication checks in route handlers",cwe:"CWE-287",cvss:9.8},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authentication",cwe:"CWE-287",description:"Route handler missing authentication check: {{route}}",severity:"CRITICAL",fix:"Add authentication middleware: app.{{method}}('{{path}}', authenticate(), handler)",documentationLink:"https://cwe.mitre.org/data/definitions/287.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing authentication in test files"},authMiddlewarePatterns:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,description:"Authentication middleware patterns to recognize"},routeHandlerPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROUTE_HANDLER_PATTERNS,description:"Route handler patterns to check"},ignorePatterns:{type:"array",items:{type:"string"},default:DEFAULT_PUBLIC_ROUTE_PATTERNS,description:"Route paths that are public by definition and need no authentication. Replaces the built-in list; supplying it also widens matching from the route path to the whole registration text."},routerNameWords:{type:"array",items:{type:"string"},default:ROUTER_NAME_WORDS,description:"Object names that denote an HTTP application or router, compared as WHOLE WORDS and never as a substring. Read only when the binding cannot be resolved to a framework factory call. Replaces the built-in list."},additionalRouterNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra router-object name words, on top of `routerNameWords`."},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords:ROUTER_NAME_WORDS,additionalRouterNameWords:[]}],createOnce(context,currentOptions){let allowInTests;let testFilePattern;let authMiddlewarePatterns;let routeHandlerPatterns;let ignorePatterns;let routerNameWords;let additionalRouterNameWords;let routerWords;let isTestFile;let sourceCode;let scansWholeCallText;function looksLikeRouter(object){const scope=sourceCode.getScope(object);const reference=scope.references.find(ref=>ref.identifier===object);const resolved=reference?.resolved;for(const def of resolved?.defs??[]){const parent=def.name.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){if(isRouterFactory(parent.init)){return true}if(isDefinitelyNotRouter(parent.init)){return false}}}return(0,eslint_devkit_1.nameHasAnyWord)(object.name,routerWords)}function findVariableDeclaration(identifier){const varName=identifier.name;let current=identifier;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName){return declarator}}}}}if("parent"in current&¤t.parent){current=current.parent}else{break}}return null}function isIdentifierFromAuthMiddleware(identifier){const declarator=findVariableDeclaration(identifier);if(!declarator||!declarator.init){return false}if(declarator.init.type==="CallExpression"&&declarator.init.callee.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(declarator.init.callee.name,authMiddlewarePatterns)}return false}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const object=node.callee.object;let chainedPath;if(object.type==="Identifier"){if(!looksLikeRouter(object)){return}}else{const base=routeChainBase(object);const baseObject=base?.callee.type==="MemberExpression"?base.callee.object:void 0;if(!base||baseObject?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!looksLikeRouter(baseObject)){return}chainedPath=base.arguments[0]}const resolvedMethod=(0,eslint_devkit_2.propertyName)(node.callee);if(resolvedMethod!==null){const methodName=resolvedMethod.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName!=="use"&&chainedPath===void 0&&node.arguments.length<2){return}if(methodName==="use"){const first=node.arguments[0];const mountsAPath=first!==void 0&&first.type==="Literal"&&typeof first.value==="string";if(!mountsAPath){return}}const pathArgument=chainedPath??node.arguments[0];const routePath=pathArgument.type==="Literal"?String(pathArgument.value):sourceCode.getText(pathArgument);const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(scansWholeCallText&&matchesIgnorePattern(text,ignorePatterns)){return}const firstMiddlewareIndex=chainedPath===void 0?1:0;const middlewareArgs=methodName==="use"?node.arguments.slice(firstMiddlewareIndex):node.arguments.slice(firstMiddlewareIndex,-1);let hasAuth=false;for(const arg of middlewareArgs){if(isAuthMiddlewareArg(arg,authMiddlewarePatterns)){hasAuth=true;break}if(arg.type==="Identifier"&&isIdentifierFromAuthMiddleware(arg)){hasAuth=true;break}}if(!hasAuth&&node.arguments.length>0){const lastArg=node.arguments[node.arguments.length-1];if(lastArg.type==="ArrowFunctionExpression"||lastArg.type==="FunctionExpression"){if(isInsideAuthMiddleware(lastArg,authMiddlewarePatterns)){hasAuth=true}}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath}})}}}}}return{before(){const[options={}]=currentOptions();({allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options);routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));sourceCode=context.sourceCode;scansWholeCallText=context.options[0]?.ignorePatterns!==void 0},CallExpression:checkCallExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPiiInLogs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_CONSOLE_METHODS=["log","error","warn","info"];const DEFAULT_PII_TERMS=["email","ssn","password","credit card","phone"];const DEFAULT_PII_LABELS=["email:","ssn:","password:","credit card:","creditcard:"];function collectLoggedValues(root){const found=[];const pending=[root];while(pending.length>0){const node=pending.pop();found.push(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression){pending.push(node.expression)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){pending.push(...node.expressions)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){pending.push(node.left,node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of node.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property){pending.push(property.value)}}}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){pending.push(node.consequent,node.alternate)}}return found}function isPiiFieldAccess(node,piiTerms){const field=(0,eslint_devkit_1.memberPropertyName)(node);return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&field!==null&&(0,eslint_devkit_1.nameHasAnyWord)(field,piiTerms)}exports.noPiiInLogs=(0,eslint_devkit_1.createRule)({name:"no-pii-in-logs",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-pii-in-logs.md",description:"Prevent PII (email, SSN, credit cards) in console logs",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-359",description:"Prevent PII (email, SSN, credit cards) in console logs detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{consoleMethods:{type:"array",items:{type:"string"},default:DEFAULT_CONSOLE_METHODS,description:"`console` methods treated as a log sink, matched as an exact method name. Replaces the built-in list."},additionalConsoleMethods:{type:"array",items:{type:"string"},default:[],description:"Extra `console` methods, on top of `consoleMethods`."},piiTerms:{type:"array",items:{type:"string"},default:DEFAULT_PII_TERMS,description:'Field vocabulary, matched as WHOLE WORDS of an identifier \u2014 never as a substring. Multi-word terms such as "credit card" match consecutive segments. Replaces the built-in list.'},additionalPiiTerms:{type:"array",items:{type:"string"},default:[],description:"Extra PII field terms, on top of `piiTerms`."},piiLabels:{type:"array",items:{type:"string"},default:DEFAULT_PII_LABELS,description:"String literals that are EXACTLY a field label announcing the next argument. Compared case-insensitively after trimming. Replaces the built-in list."},additionalPiiLabels:{type:"array",items:{type:"string"},default:[],description:"Extra field labels, on top of `piiLabels`."}},additionalProperties:false}]},defaultOptions:[{consoleMethods:DEFAULT_CONSOLE_METHODS,additionalConsoleMethods:[],piiTerms:DEFAULT_PII_TERMS,additionalPiiTerms:[],piiLabels:DEFAULT_PII_LABELS,additionalPiiLabels:[]}],
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPiiInLogs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_CONSOLE_METHODS=["log","error","warn","info"];const DEFAULT_PII_TERMS=["email","ssn","password","credit card","phone"];const DEFAULT_PII_LABELS=["email:","ssn:","password:","credit card:","creditcard:"];function collectLoggedValues(root){const found=[];const pending=[root];while(pending.length>0){const node=pending.pop();found.push(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression){pending.push(node.expression)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){pending.push(...node.expressions)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){pending.push(node.left,node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of node.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property){pending.push(property.value)}}}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){pending.push(node.consequent,node.alternate)}}return found}function isPiiFieldAccess(node,piiTerms){const field=(0,eslint_devkit_1.memberPropertyName)(node);return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&field!==null&&(0,eslint_devkit_1.nameHasAnyWord)(field,piiTerms)}exports.noPiiInLogs=(0,eslint_devkit_1.createRule)({name:"no-pii-in-logs",meta:{interop:{runtimes:["eslint","oxlint"]},type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-pii-in-logs.md",description:"Prevent PII (email, SSN, credit cards) in console logs",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-359",description:"Prevent PII (email, SSN, credit cards) in console logs detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{consoleMethods:{type:"array",items:{type:"string"},default:DEFAULT_CONSOLE_METHODS,description:"`console` methods treated as a log sink, matched as an exact method name. Replaces the built-in list."},additionalConsoleMethods:{type:"array",items:{type:"string"},default:[],description:"Extra `console` methods, on top of `consoleMethods`."},piiTerms:{type:"array",items:{type:"string"},default:DEFAULT_PII_TERMS,description:'Field vocabulary, matched as WHOLE WORDS of an identifier \u2014 never as a substring. Multi-word terms such as "credit card" match consecutive segments. Replaces the built-in list.'},additionalPiiTerms:{type:"array",items:{type:"string"},default:[],description:"Extra PII field terms, on top of `piiTerms`."},piiLabels:{type:"array",items:{type:"string"},default:DEFAULT_PII_LABELS,description:"String literals that are EXACTLY a field label announcing the next argument. Compared case-insensitively after trimming. Replaces the built-in list."},additionalPiiLabels:{type:"array",items:{type:"string"},default:[],description:"Extra field labels, on top of `piiLabels`."}},additionalProperties:false}]},defaultOptions:[{consoleMethods:DEFAULT_CONSOLE_METHODS,additionalConsoleMethods:[],piiTerms:DEFAULT_PII_TERMS,additionalPiiTerms:[],piiLabels:DEFAULT_PII_LABELS,additionalPiiLabels:[]}],createOnce(context,currentOptions){let logMethods;let terms;let labels;let sourceCode;function report(node){context.report({node,messageId:"violationDetected"})}function isPiiBinding(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);const resolved=reference?.resolved;if(!resolved){return false}return resolved.defs.some(def=>{const declared=def.name;const parent=declared.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return(0,eslint_devkit_1.nameHasAnyWord)(parent.key.name,terms)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){return isPiiFieldAccess(parent.init,terms)}return false})}return{before(){const[options={}]=currentOptions();const{consoleMethods=DEFAULT_CONSOLE_METHODS,additionalConsoleMethods=[],piiTerms=DEFAULT_PII_TERMS,additionalPiiTerms=[],piiLabels=DEFAULT_PII_LABELS,additionalPiiLabels=[]}=options;logMethods=new Set([...consoleMethods,...additionalConsoleMethods]);terms=[...piiTerms,...additionalPiiTerms];labels=new Set([...piiLabels,...additionalPiiLabels].map(label=>label.trim().toLowerCase()));sourceCode=context.sourceCode},CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.object.name!=="console"||!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),logMethods)){return}for(const[index,arg]of node.arguments.entries()){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&index<node.arguments.length-1&&labels.has(arg.value.trim().toLowerCase())){report(node);return}for(const value of collectLoggedValues(arg)){if(isPiiFieldAccess(value,terms)||isPiiBinding(value)){report(node);return}}}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPrivilegeEscalation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_ROLE_CHECK_PATTERNS=["hasRole","checkRole","isAdmin","isAuthorized","hasPermission","checkPermission","verifyRole","requireRole"];const DEFAULT_USER_INPUT_PATTERNS=[/\breq\s*(?:\.\s*(?:body|query|params)(?![\w$])|\[\s*['"](?:body|query|params)['"]\s*\])/,/\brequest\s*(?:\.\s*(?:body|query|params)(?![\w$])|\[\s*['"](?:body|query|params)['"]\s*\])/,/\buserInput\b/];const DEFAULT_PRIVILEGE_PROPERTIES=["role","permission","privilege","access"];const DEFAULT_PRIVILEGE_TERMS=["setRole","updateRole","elevate","grant role","grant permission","grant access","grant privilege","promote user","promote admin","revoke role","revoke permission","revoke access","revoke privilege"];const DEFAULT_BARE_PRIVILEGE_VERBS=["grant","promote","revoke"];function isPrivilegeOperationName(name,privilegeTerms,bareVerbs){if((0,eslint_devkit_1.nameHasAnyWord)(name,privilegeTerms)){return true}const words=(0,eslint_devkit_1.identifierWords)(name);return words.length===1&&bareVerbs.has(words[0])}function assignedPropertyName(member){if(!member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return member.property.name}const staticText=(0,eslint_devkit_1.staticString)(member.property);if(staticText!==null){return staticText}return null}function forEachNode(root,visit){const pending=[root];while(pending.length>0){const node=pending.pop();visit(node);for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){pending.push(child)}}}}}function containsRoleCheck(root,roleCheckPatterns){let found=false;forEachNode(root,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.name,roleCheckPatterns)){found=true}});return found}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||statement.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}return false}function isAfterRoleGuard(node,roleCheckPatterns){let current=node;while(current.parent){const parent=current.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const index=body.indexOf(current);for(let i=0;i<index;i++){const statement=body[i];if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&exitsUnconditionally(statement.consequent)&&containsRoleCheck(statement.test,roleCheckPatterns)){return true}}}current=parent}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}function containsUserInput(node,sourceCode,userInputPatterns){const text=sourceCode.getText(node);return userInputPatterns.some(pattern=>pattern.test(text))}function isInsideRoleCheck(node,roleCheckPatterns){let current=node;while(current){if(current.parent&¤t.parent.type==="IfStatement"){const ifStmt=current.parent;if(containsRoleCheck(ifStmt.test,roleCheckPatterns)){return true}}if(current.parent&¤t.parent.type==="ConditionalExpression"){const condExpr=current.parent;if(containsRoleCheck(condExpr.test,roleCheckPatterns)){return true}}if(current.parent&¤t.parent.type==="CallExpression"){const callExpr=current.parent;const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,roleCheckPatterns)){return true}}const memberName=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&memberName!==null){if((0,eslint_devkit_1.nameHasAnyWord)(memberName,roleCheckPatterns)){return true}}}if("parent"in current&¤t.parent){current=current.parent}else{break}}return false}exports.noPrivilegeEscalation=(0,eslint_devkit_2.createRule)({name:"no-privilege-escalation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-privilege-escalation.md",description:"Detects potential privilege escalation vulnerabilities",cwe:"CWE-269",cvss:8.8},messages:{privilegeEscalation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Privilege Escalation",cwe:"CWE-269",description:"Potential privilege escalation: {{issue}} - user input used without role validation",severity:"HIGH",fix:'Add role check before using user input: if (!hasRole(user, requiredRole)) throw new Error("Unauthorized");',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow privilege escalation patterns in test files"},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."},roleCheckPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROLE_CHECK_PATTERNS,description:"Role check patterns to recognize"},userInputPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional user input patterns to check (regex strings)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},privilegeProperties:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_PROPERTIES,description:"Property names whose assignment is an authorisation decision, compared case-insensitively as an exact name. Replaces the built-in list."},additionalPrivilegeProperties:{type:"array",items:{type:"string"},default:[],description:"Extra privilege property names, on top of `privilegeProperties`."},privilegeTerms:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_TERMS,description:"Privilege operations, matched as whole words or whole consecutive phrases of a callee name \u2014 never as a substring. Replaces the built-in list."},additionalPrivilegeTerms:{type:"array",items:{type:"string"},default:[],description:"Extra privilege operation terms, on top of `privilegeTerms`."},barePrivilegeVerbs:{type:"array",items:{type:"string"},default:DEFAULT_BARE_PRIVILEGE_VERBS,description:"Verbs that count only when they are the WHOLE callee name, because their ordinary English sense dominates otherwise. Replaces the built-in list."},additionalBarePrivilegeVerbs:{type:"array",items:{type:"string"},default:[],description:"Extra bare privilege verbs, on top of `barePrivilegeVerbs`."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,roleCheckPatterns:DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:[],ignorePatterns:[],privilegeProperties:DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties:[],privilegeTerms:DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms:[],barePrivilegeVerbs:DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,roleCheckPatterns=DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:additionalUserInputPatterns=[],ignorePatterns=[],privilegeProperties=DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties=[],privilegeTerms=DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms=[],barePrivilegeVerbs=DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs=[]}=options;const privilegeProps=new Set([...privilegeProperties,...additionalPrivilegeProperties].map(name=>name.toLowerCase()));const privilegeOperationTerms=[...privilegeTerms,...additionalPrivilegeTerms];const bareVerbs=new Set([...barePrivilegeVerbs,...additionalBarePrivilegeVerbs]);const isPrivilegeOperationCallee=name=>isPrivilegeOperationName(name,privilegeOperationTerms,bareVerbs);const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const userInputPatterns=[...DEFAULT_USER_INPUT_PATTERNS,...(0,eslint_devkit_1.compileUserPatterns)(additionalUserInputPatterns,"i")];function isRoleChecked(node){return isInsideRoleCheck(node,roleCheckPatterns)||isAfterRoleGuard(node,roleCheckPatterns)}function resolvesToUserInput(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);for(const def of reference?.resolved?.defs??[]){let declarator=def.name;while(declarator&&declarator.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){declarator=declarator.parent}if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&containsUserInput(declarator.init,sourceCode,userInputPatterns)){return true}}return false}function isUserControlled(node){return containsUserInput(node,sourceCode,userInputPatterns)||resolvesToUserInput(node)}function checkAssignmentExpression(node){if(isTestFile){return}if(node.left.type==="MemberExpression"){const propertyName=assignedPropertyName(node.left)?.toLowerCase();if(propertyName!==void 0&&privilegeProps.has(propertyName)){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isUserControlled(node.right)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Role assignment from user input: ${sourceCode.getText(node.left)} = ${sourceCode.getText(node.right)}`}})}}}}}function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;let isPrivilegeOperation=false;let operationName="";if(callee.type==="Identifier"){if(isPrivilegeOperationCallee(callee.name)){isPrivilegeOperation=true;operationName=callee.name}}const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&method!==null){if(isPrivilegeOperationCallee(method)){isPrivilegeOperation=true;operationName=method.toLowerCase()}}if(isPrivilegeOperation){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const arg of node.arguments){if(isUserControlled(arg)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Privilege operation (${operationName}) with user input without role validation`}});return}}}}}function checkObjectExpression(node){if(isTestFile)return;for(const prop of node.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(privilegeProps.has(keyName)){const text=sourceCode.getText(prop);if(matchesIgnorePattern(text,ignorePatterns))continue;if(isUserControlled(prop.value)){if(!isRoleChecked(node)){context.report({node:prop,messageId:"privilegeEscalation",data:{issue:`Role assignment in object from user input: ${sourceCode.getText(prop)}`}})}}}}}}return{AssignmentExpression:checkAssignmentExpression,CallExpression:checkCallExpression,ObjectExpression:checkObjectExpression}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPrivilegeEscalation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_ROLE_CHECK_PATTERNS=["hasRole","checkRole","isAdmin","isAuthorized","hasPermission","checkPermission","verifyRole","requireRole"];const DEFAULT_USER_INPUT_PATTERNS=[/\breq\s*(?:\.\s*(?:body|query|params)(?![\w$])|\[\s*['"](?:body|query|params)['"]\s*\])/,/\brequest\s*(?:\.\s*(?:body|query|params)(?![\w$])|\[\s*['"](?:body|query|params)['"]\s*\])/,/\buserInput\b/];const DEFAULT_PRIVILEGE_PROPERTIES=["role","permission","privilege","access"];const DEFAULT_PRIVILEGE_TERMS=["setRole","updateRole","elevate","grant role","grant permission","grant access","grant privilege","promote user","promote admin","revoke role","revoke permission","revoke access","revoke privilege"];const DEFAULT_BARE_PRIVILEGE_VERBS=["grant","promote","revoke"];function isPrivilegeOperationName(name,privilegeTerms,bareVerbs){if((0,eslint_devkit_1.nameHasAnyWord)(name,privilegeTerms)){return true}const words=(0,eslint_devkit_1.identifierWords)(name);return words.length===1&&bareVerbs.has(words[0])}function assignedPropertyName(member){if(!member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return member.property.name}const staticText=(0,eslint_devkit_1.staticString)(member.property);if(staticText!==null){return staticText}return null}function forEachNode(root,visit){const pending=[root];while(pending.length>0){const node=pending.pop();visit(node);for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){pending.push(child)}}}}}function containsRoleCheck(root,roleCheckPatterns){let found=false;forEachNode(root,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.name,roleCheckPatterns)){found=true}});return found}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||statement.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}return false}function isAfterRoleGuard(node,roleCheckPatterns){let current=node;while(current.parent){const parent=current.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const index=body.indexOf(current);for(let i=0;i<index;i++){const statement=body[i];if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&exitsUnconditionally(statement.consequent)&&containsRoleCheck(statement.test,roleCheckPatterns)){return true}}}current=parent}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}function containsUserInput(node,sourceCode,userInputPatterns){const text=sourceCode.getText(node);return userInputPatterns.some(pattern=>pattern.test(text))}function isInsideRoleCheck(node,roleCheckPatterns){let current=node;while(current){if(current.parent&¤t.parent.type==="IfStatement"){const ifStmt=current.parent;if(containsRoleCheck(ifStmt.test,roleCheckPatterns)){return true}}if(current.parent&¤t.parent.type==="ConditionalExpression"){const condExpr=current.parent;if(containsRoleCheck(condExpr.test,roleCheckPatterns)){return true}}if(current.parent&¤t.parent.type==="CallExpression"){const callExpr=current.parent;const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,roleCheckPatterns)){return true}}const memberName=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&memberName!==null){if((0,eslint_devkit_1.nameHasAnyWord)(memberName,roleCheckPatterns)){return true}}}if("parent"in current&¤t.parent){current=current.parent}else{break}}return false}exports.noPrivilegeEscalation=(0,eslint_devkit_2.createRule)({name:"no-privilege-escalation",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-privilege-escalation.md",description:"Detects potential privilege escalation vulnerabilities",cwe:"CWE-269",cvss:8.8},messages:{privilegeEscalation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Privilege Escalation",cwe:"CWE-269",description:"Potential privilege escalation: {{issue}} - user input used without role validation",severity:"HIGH",fix:'Add role check before using user input: if (!hasRole(user, requiredRole)) throw new Error("Unauthorized");',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow privilege escalation patterns in test files"},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."},roleCheckPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROLE_CHECK_PATTERNS,description:"Role check patterns to recognize"},userInputPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional user input patterns to check (regex strings)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},privilegeProperties:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_PROPERTIES,description:"Property names whose assignment is an authorisation decision, compared case-insensitively as an exact name. Replaces the built-in list."},additionalPrivilegeProperties:{type:"array",items:{type:"string"},default:[],description:"Extra privilege property names, on top of `privilegeProperties`."},privilegeTerms:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_TERMS,description:"Privilege operations, matched as whole words or whole consecutive phrases of a callee name \u2014 never as a substring. Replaces the built-in list."},additionalPrivilegeTerms:{type:"array",items:{type:"string"},default:[],description:"Extra privilege operation terms, on top of `privilegeTerms`."},barePrivilegeVerbs:{type:"array",items:{type:"string"},default:DEFAULT_BARE_PRIVILEGE_VERBS,description:"Verbs that count only when they are the WHOLE callee name, because their ordinary English sense dominates otherwise. Replaces the built-in list."},additionalBarePrivilegeVerbs:{type:"array",items:{type:"string"},default:[],description:"Extra bare privilege verbs, on top of `barePrivilegeVerbs`."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,roleCheckPatterns:DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:[],ignorePatterns:[],privilegeProperties:DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties:[],privilegeTerms:DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms:[],barePrivilegeVerbs:DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,roleCheckPatterns=DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:additionalUserInputPatterns=[],ignorePatterns=[],privilegeProperties=DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties=[],privilegeTerms=DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms=[],barePrivilegeVerbs=DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs=[]}=options;const privilegeProps=new Set([...privilegeProperties,...additionalPrivilegeProperties].map(name=>name.toLowerCase()));const privilegeOperationTerms=[...privilegeTerms,...additionalPrivilegeTerms];const bareVerbs=new Set([...barePrivilegeVerbs,...additionalBarePrivilegeVerbs]);const isPrivilegeOperationCallee=name=>isPrivilegeOperationName(name,privilegeOperationTerms,bareVerbs);const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const userInputPatterns=[...DEFAULT_USER_INPUT_PATTERNS,...(0,eslint_devkit_1.compileUserPatterns)(additionalUserInputPatterns,"i")];function isRoleChecked(node){return isInsideRoleCheck(node,roleCheckPatterns)||isAfterRoleGuard(node,roleCheckPatterns)}function resolvesToUserInput(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);for(const def of reference?.resolved?.defs??[]){let declarator=def.name;while(declarator&&declarator.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){declarator=declarator.parent}if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&containsUserInput(declarator.init,sourceCode,userInputPatterns)){return true}}return false}function isUserControlled(node){return containsUserInput(node,sourceCode,userInputPatterns)||resolvesToUserInput(node)}function checkAssignmentExpression(node){if(isTestFile){return}if(node.left.type==="MemberExpression"){const propertyName=assignedPropertyName(node.left)?.toLowerCase();if(propertyName!==void 0&&privilegeProps.has(propertyName)){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isUserControlled(node.right)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Role assignment from user input: ${sourceCode.getText(node.left)} = ${sourceCode.getText(node.right)}`}})}}}}}function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;let isPrivilegeOperation=false;let operationName="";if(callee.type==="Identifier"){if(isPrivilegeOperationCallee(callee.name)){isPrivilegeOperation=true;operationName=callee.name}}const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&method!==null){if(isPrivilegeOperationCallee(method)){isPrivilegeOperation=true;operationName=method.toLowerCase()}}if(isPrivilegeOperation){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const arg of node.arguments){if(isUserControlled(arg)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Privilege operation (${operationName}) with user input without role validation`}});return}}}}}function checkObjectExpression(node){if(isTestFile)return;for(const prop of node.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(privilegeProps.has(keyName)){const text=sourceCode.getText(prop);if(matchesIgnorePattern(text,ignorePatterns))continue;if(isUserControlled(prop.value)){if(!isRoleChecked(node)){context.report({node:prop,messageId:"privilegeEscalation",data:{issue:`Role assignment in object from user input: ${sourceCode.getText(prop)}`}})}}}}}}return{AssignmentExpression:checkAssignmentExpression,CallExpression:checkCallExpression,ObjectExpression:checkObjectExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noRedosVulnerableRegex=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const regexpp_1=require("@eslint-community/regexpp");const refa_1=require("refa");const scslre_1=require("scslre");const regexp_intrinsic_1=require("../../utils/regexp-intrinsic");const redos_oracle_1=require("../../utils/redos-oracle");const COMPLEMENTARY_CLASS_PROBES=[["\\\\S","\\\\s"],["\\\\W","\\\\w"],["\\\\D","\\\\d"]].map(([x,y])=>({group:new RegExp(`\\(\\s*(?:${x}|${y})[+*][^)]*(?:${x}|${y})[+*?][^)]*\\)[+*]`),a:new RegExp(`${x}[+*]`),b:new RegExp(`${y}[+*?]`)}));const REGEXPP_PARSER=new regexpp_1.RegExpParser;const INTERPOLATION_PLACEHOLDER="\uE000";function relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern){const edits=[];const walk=(node,underUnbounded)=>{const n=node;if(n.type==="Quantifier"){const{min=0,max=0}=n;if(underUnbounded&&Number.isFinite(max)&&max>1&&min!==max){edits.push([n.element.end,n.end,`{${min},}${n.greedy===false?"?":""}`])}walk(n.element,underUnbounded||max===Infinity);return}for(const child of[...n.alternatives??[],...n.elements??[]]){walk(child,underUnbounded)}};walk(ast,false);if(edits.length===0)return pattern;let out=pattern;for(const[start,end,text]of edits.sort((a,b)=>b[0]-a[0])){out=out.slice(0,start)+text+out.slice(end)}return out}const isRegExpLiteral=node=>{return node.type==="Literal"&&Object.prototype.hasOwnProperty.call(node,"regex")};exports.noRedosVulnerableRegex=(0,eslint_devkit_2.createRule)({name:"no-redos-vulnerable-regex",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-redos-vulnerable-regex.md",description:"Detects ReDoS-vulnerable regex patterns in literal regex patterns",cwe:"CWE-400"},messages:{redosVulnerable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ReDoS vulnerable regex",cwe:"CWE-400",description:"{{vulnerabilityName}}: {{description}}",severity:"{{severity}}",fix:"{{fix}} \u2014 Not a finding if the quantifiers cannot overlap",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"})},schema:[{type:"object",properties:{allowCommonPatterns:{type:"boolean",default:false,description:"Deprecated and ignored. Gated the removed heuristic layer; kept so existing configs still load."},maxPatternLength:{type:"number",default:500,minimum:1,description:"Maximum pattern length to analyze"},reportSecondDegreePolynomial:{type:"boolean",default:true,description:"Report quadratic backtracking. On by default \u2014 the CWE-1333 corpus pins a degree-2 fixture as must-detect. Turn it off only for patterns that provably run over short, sized input; doing so costs recall. Requires the recheck oracle."}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowCommonPatterns:false,maxPatternLength:500,reportSecondDegreePolynomial:true}],create(context,[options={}]){const{maxPatternLength=500,reportSecondDegreePolynomial=true}=options||{};const MAX_SAFE_REPETITION=5;function isProvablyLinear(pattern){const groupUnderUnboundedQuantifier=/\)[*+]/.test(pattern);const bounded=groupUnderUnboundedQuantifier?null:/\)\{(\d+)(?:,(\d+))?\}/.exec(pattern);if(bounded!==null){const max=bounded[2]!==void 0?Number(bounded[2]):Number(bounded[1]);if(max<=MAX_SAFE_REPETITION)return true}for(const{group,a,b}of COMPLEMENTARY_CLASS_PROBES){if(!group.test(pattern))continue;if(a.test(pattern)&&b.test(pattern))return true}return false}function isProvablyCatastrophic(ast,flags){const unicode=flags.includes("u")||flags.includes("v");const charSetOf=alt=>{if(alt.elements.length!==1)return null;const el=alt.elements[0];if(el.type!=="Character"&&el.type!=="CharacterSet"&&el.type!=="CharacterClass"){return null}try{return refa_1.JS.parseCharSet(el,{unicode})}catch{return null}};let catastrophic=false;(0,regexpp_1.visitRegExpAST)(ast,{onQuantifierEnter(quantifier){if(catastrophic)return;if(quantifier.max!==Infinity)return;const{element}=quantifier;if(element.type!=="Group"&&element.type!=="CapturingGroup"){return}const sets=element.alternatives.map(charSetOf);if(sets.some(s=>s===null))return;for(let i=0;i<sets.length&&!catastrophic;i++){for(let j=i+1;j<sets.length;j++){if(!sets[i].isDisjointWith(sets[j])){catastrophic=true;break}}}}});return catastrophic}function checkWithScslre(node,pattern,flags,runtimeBuilt=false){try{const parse=source=>REGEXPP_PARSER.parsePattern(source,0,source.length,{unicode:flags.includes("u"),unicodeSets:flags.includes("v")});const run=ast2=>(0,scslre_1.analyse)({pattern:ast2,flags:{ignoreCase:flags.includes("i"),unicode:flags.includes("u"),unicodeSets:flags.includes("v"),dotAll:flags.includes("s"),multiline:flags.includes("m")}},{reportTypes:{Move:false}});const ast=parse(pattern);let result=run(ast);if(result.reports.length===0){const relaxed=relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern);if(relaxed!==pattern){result=run(parse(relaxed))}}if(isProvablyLinear(pattern)){return}if(result.reports.length===0&&isProvablyCatastrophic(ast,flags)){if(!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:"Ambiguous alternation (exponential backtracking)",description:"Alternatives inside a quantified group match the same input, so every character can be taken by either branch and the engine explores 2^n paths before failing.",severity:"CRITICAL",fix:"Remove the duplicate alternative, or make the branches mutually exclusive"}});return}const worst=result.reports.find(r=>r.exponential)??result.reports[0];if(worst&&!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;if(worst&&!reportSecondDegreePolynomial){const degree=(0,redos_oracle_1.worstBacktrackingDegree)(pattern,flags);if(degree!==null&°ree<=2)return}for(const report of worst?[worst]:[]){const isExp=report.exponential;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:`${runtimeBuilt?"Runtime-built ":""}${report.type==="Self"?`Self-loop quantifier (${isExp?"exponential":"polynomial"} backtracking)`:`Cross-quantifier trade (${isExp?"exponential":"polynomial"} backtracking)`}`,description:report.type==="Self"?`A quantifier reaches itself via the parent loop. An attacker can craft input that triggers ${isExp?"exponential":"polynomial"} backtracking.`:`Two quantifiers can exchange characters, enabling ${isExp?"exponential":"polynomial"} backtracking on crafted input.`,severity:isExp?"CRITICAL":"HIGH",fix:"Atomic group, possessive quantifier, or rewrite to remove the ambiguity"}})}}catch{}}function checkLiteralRegExp(node){if(!isRegExpLiteral(node)){return}const pattern=node.regex.pattern;const flags=node.regex.flags||"";if(pattern.length>maxPatternLength){return}checkWithScslre(node,pattern,flags)}function resolvePatternSource(node,seen){if(seen.has(node))return null;seen.add(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?{pattern:node.value,exact:true}:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return joinQuasis(node.quasis.map(q=>q.value.cooked??q.value.raw),node.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression&&node.tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(node.tag)==="raw"&&!isShadowed("String",node)){return joinQuasis(node.quasi.quasis.map(q=>q.value.raw),node.quasi.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=resolveOrPlaceholder(node.left,seen);const right=resolveOrPlaceholder(node.right,seen);return{pattern:left.pattern+right.pattern,exact:left.exact&&right.exact}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=resolveBindingInit(node);return init?resolvePatternSource(init,seen):null}return null}function joinQuasis(staticParts,expressions,seen){let pattern="";let exact=true;for(const[index,part]of staticParts.entries()){pattern+=part;const expression=expressions[index];if(!expression)continue;const resolved=resolveOrPlaceholder(expression,seen);pattern+=resolved.pattern;exact&&=resolved.exact}return{pattern,exact}}function resolveOrPlaceholder(node,seen){return resolvePatternSource(node,seen)??{pattern:INTERPOLATION_PLACEHOLDER,exact:false}}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;const writes=variable.references.filter(r=>r.isWrite());return writes.length===1?def.node.init:null}return null}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function checkNewRegExp(node){const callee=node.callee;if(!(0,regexp_intrinsic_1.isRegExpConstructor)(callee,context.sourceCode)){return}const firstArg=node.arguments[0];if(!firstArg||firstArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const resolved=resolvePatternSource(firstArg,new Set);if(!resolved||resolved.pattern.length>maxPatternLength){return}const flagsArg=node.arguments[1];const flags=flagsArg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof flagsArg.value==="string"?flagsArg.value:"";checkWithScslre(node,resolved.pattern,flags,!resolved.exact)}return{Literal:checkLiteralRegExp,CallExpression:node=>checkNewRegExp((0,regexp_intrinsic_1.asDirectConstruction)(node,context.sourceCode)),NewExpression:checkNewRegExp}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noRedosVulnerableRegex=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const regexpp_1=require("@eslint-community/regexpp");const refa_1=require("refa");const scslre_1=require("scslre");const regexp_intrinsic_1=require("../../utils/regexp-intrinsic");const redos_oracle_1=require("../../utils/redos-oracle");const COMPLEMENTARY_CLASS_PROBES=[["\\\\S","\\\\s"],["\\\\W","\\\\w"],["\\\\D","\\\\d"]].map(([x,y])=>({group:new RegExp(`\\(\\s*(?:${x}|${y})[+*][^)]*(?:${x}|${y})[+*?][^)]*\\)[+*]`),a:new RegExp(`${x}[+*]`),b:new RegExp(`${y}[+*?]`)}));const REGEXPP_PARSER=new regexpp_1.RegExpParser;const INTERPOLATION_PLACEHOLDER="\uE000";function relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern){const edits=[];const walk=(node,underUnbounded)=>{const n=node;if(n.type==="Quantifier"){const{min=0,max=0}=n;if(underUnbounded&&Number.isFinite(max)&&max>1&&min!==max){edits.push([n.element.end,n.end,`{${min},}${n.greedy===false?"?":""}`])}walk(n.element,underUnbounded||max===Infinity);return}for(const child of[...n.alternatives??[],...n.elements??[]]){walk(child,underUnbounded)}};walk(ast,false);if(edits.length===0)return pattern;let out=pattern;for(const[start,end,text]of edits.sort((a,b)=>b[0]-a[0])){out=out.slice(0,start)+text+out.slice(end)}return out}const isRegExpLiteral=node=>{return node.type==="Literal"&&Object.prototype.hasOwnProperty.call(node,"regex")};exports.noRedosVulnerableRegex=(0,eslint_devkit_2.createRule)({name:"no-redos-vulnerable-regex",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-redos-vulnerable-regex.md",description:"Detects ReDoS-vulnerable regex patterns in literal regex patterns",cwe:"CWE-400"},messages:{redosVulnerable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ReDoS vulnerable regex",cwe:"CWE-400",description:"{{vulnerabilityName}}: {{description}}",severity:"{{severity}}",fix:"{{fix}} \u2014 Not a finding if the quantifiers cannot overlap",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"})},schema:[{type:"object",properties:{allowCommonPatterns:{type:"boolean",default:false,description:"Deprecated and ignored. Gated the removed heuristic layer; kept so existing configs still load."},maxPatternLength:{type:"number",default:500,minimum:1,description:"Maximum pattern length to analyze"},reportSecondDegreePolynomial:{type:"boolean",default:true,description:"Report quadratic backtracking. On by default \u2014 the CWE-1333 corpus pins a degree-2 fixture as must-detect. Turn it off only for patterns that provably run over short, sized input; doing so costs recall. Requires the recheck oracle."}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowCommonPatterns:false,maxPatternLength:500,reportSecondDegreePolynomial:true}],createOnce(context,currentOptions){let maxPatternLength;let reportSecondDegreePolynomial;const MAX_SAFE_REPETITION=5;function isProvablyLinear(pattern){const groupUnderUnboundedQuantifier=/\)[*+]/.test(pattern);const bounded=groupUnderUnboundedQuantifier?null:/\)\{(\d+)(?:,(\d+))?\}/.exec(pattern);if(bounded!==null){const max=bounded[2]!==void 0?Number(bounded[2]):Number(bounded[1]);if(max<=MAX_SAFE_REPETITION)return true}for(const{group,a,b}of COMPLEMENTARY_CLASS_PROBES){if(!group.test(pattern))continue;if(a.test(pattern)&&b.test(pattern))return true}return false}function isProvablyCatastrophic(ast,flags){const unicode=flags.includes("u")||flags.includes("v");const charSetOf=alt=>{if(alt.elements.length!==1)return null;const el=alt.elements[0];if(el.type!=="Character"&&el.type!=="CharacterSet"&&el.type!=="CharacterClass"){return null}try{return refa_1.JS.parseCharSet(el,{unicode})}catch{return null}};let catastrophic=false;(0,regexpp_1.visitRegExpAST)(ast,{onQuantifierEnter(quantifier){if(catastrophic)return;if(quantifier.max!==Infinity)return;const{element}=quantifier;if(element.type!=="Group"&&element.type!=="CapturingGroup"){return}const sets=element.alternatives.map(charSetOf);if(sets.some(s=>s===null))return;for(let i=0;i<sets.length&&!catastrophic;i++){for(let j=i+1;j<sets.length;j++){if(!sets[i].isDisjointWith(sets[j])){catastrophic=true;break}}}}});return catastrophic}function checkWithScslre(node,pattern,flags,runtimeBuilt=false){try{const parse=source=>REGEXPP_PARSER.parsePattern(source,0,source.length,{unicode:flags.includes("u"),unicodeSets:flags.includes("v")});const run=ast2=>(0,scslre_1.analyse)({pattern:ast2,flags:{ignoreCase:flags.includes("i"),unicode:flags.includes("u"),unicodeSets:flags.includes("v"),dotAll:flags.includes("s"),multiline:flags.includes("m")}},{reportTypes:{Move:false}});const ast=parse(pattern);let result=run(ast);if(result.reports.length===0){const relaxed=relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern);if(relaxed!==pattern){result=run(parse(relaxed))}}if(isProvablyLinear(pattern)){return}if(result.reports.length===0&&isProvablyCatastrophic(ast,flags)){if(!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:"Ambiguous alternation (exponential backtracking)",description:"Alternatives inside a quantified group match the same input, so every character can be taken by either branch and the engine explores 2^n paths before failing.",severity:"CRITICAL",fix:"Remove the duplicate alternative, or make the branches mutually exclusive"}});return}const worst=result.reports.find(r=>r.exponential)??result.reports[0];if(worst&&!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;if(worst&&!reportSecondDegreePolynomial){const degree=(0,redos_oracle_1.worstBacktrackingDegree)(pattern,flags);if(degree!==null&°ree<=2)return}for(const report of worst?[worst]:[]){const isExp=report.exponential;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:`${runtimeBuilt?"Runtime-built ":""}${report.type==="Self"?`Self-loop quantifier (${isExp?"exponential":"polynomial"} backtracking)`:`Cross-quantifier trade (${isExp?"exponential":"polynomial"} backtracking)`}`,description:report.type==="Self"?`A quantifier reaches itself via the parent loop. An attacker can craft input that triggers ${isExp?"exponential":"polynomial"} backtracking.`:`Two quantifiers can exchange characters, enabling ${isExp?"exponential":"polynomial"} backtracking on crafted input.`,severity:isExp?"CRITICAL":"HIGH",fix:"Atomic group, possessive quantifier, or rewrite to remove the ambiguity"}})}}catch{}}function checkLiteralRegExp(node){if(!isRegExpLiteral(node)){return}const pattern=node.regex.pattern;const flags=node.regex.flags||"";if(pattern.length>maxPatternLength){return}checkWithScslre(node,pattern,flags)}function resolvePatternSource(node,seen){if(seen.has(node))return null;seen.add(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?{pattern:node.value,exact:true}:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return joinQuasis(node.quasis.map(q=>q.value.cooked??q.value.raw),node.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression&&node.tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(node.tag)==="raw"&&!isShadowed("String",node)){return joinQuasis(node.quasi.quasis.map(q=>q.value.raw),node.quasi.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=resolveOrPlaceholder(node.left,seen);const right=resolveOrPlaceholder(node.right,seen);return{pattern:left.pattern+right.pattern,exact:left.exact&&right.exact}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=resolveBindingInit(node);return init?resolvePatternSource(init,seen):null}return null}function joinQuasis(staticParts,expressions,seen){let pattern="";let exact=true;for(const[index,part]of staticParts.entries()){pattern+=part;const expression=expressions[index];if(!expression)continue;const resolved=resolveOrPlaceholder(expression,seen);pattern+=resolved.pattern;exact&&=resolved.exact}return{pattern,exact}}function resolveOrPlaceholder(node,seen){return resolvePatternSource(node,seen)??{pattern:INTERPOLATION_PLACEHOLDER,exact:false}}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;const writes=variable.references.filter(r=>r.isWrite());return writes.length===1?def.node.init:null}return null}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function checkNewRegExp(node){const callee=node.callee;if(!(0,regexp_intrinsic_1.isRegExpConstructor)(callee,context.sourceCode)){return}const firstArg=node.arguments[0];if(!firstArg||firstArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const resolved=resolvePatternSource(firstArg,new Set);if(!resolved||resolved.pattern.length>maxPatternLength){return}const flagsArg=node.arguments[1];const flags=flagsArg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof flagsArg.value==="string"?flagsArg.value:"";checkWithScslre(node,resolved.pattern,flags,!resolved.exact)}return{before(){const[options={}]=currentOptions();({maxPatternLength=500,reportSecondDegreePolynomial=true}=options||{})},Literal:checkLiteralRegExp,CallExpression:node=>checkNewRegExp((0,regexp_intrinsic_1.asDirectConstruction)(node,context.sourceCode)),NewExpression:checkNewRegExp}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?(0,eslint_devkit_1.staticString)(prop)!==null?(0,eslint_devkit_1.staticString)(prop):null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&(VALUE_FREE_PROPERTIES.has(propName)||DIAGNOSTIC_ACCESSORS.has(propName)))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);const DIAGNOSTIC_ACCESSORS=new Set(["message","stack","name","status","statusText"]);function isDiagnosticAccessor(node){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);const value=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;return value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(value),DIAGNOSTIC_ACCESSORS)}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{};const descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);const LOGGER_RECEIVERS=new Set(["console","logger","log"]);const LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}const name=node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(node):null;return name!==null&&LOGGER_RECEIVERS.has(name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);const staticText1=(0,eslint_devkit_1.staticString)(arg);if(staticText1!==null){const pattern=literalCarriesSecret(staticText1,sensitivePatterns)?containsSensitiveData(staticText1,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){const staticText2=(0,eslint_devkit_1.staticString)(arg.left);if(staticText2!==null){const labelled=literalLabelsValue(staticText2,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const allHolesAreDiagnostic=arg.expressions.every(isNonSecretHole);const fromText=arg.expressions.length>0&&!allHolesAreDiagnostic&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function isNonSecretHole(expression){if(!isDiagnosticAccessor(expression))return false;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(expression);const member=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return true;const init=resolveBindingInit(member.object);if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return true;const key=member.property.name;const assigned=init.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name===key||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value===key));if(!assigned)return true;return namedValueExposure(assigned.value)===null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const method=(0,eslint_devkit_1.propertyName)(node.callee);return method!==null&&LOG_METHODS.has(method.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?(0,eslint_devkit_1.staticString)(prop)!==null?(0,eslint_devkit_1.staticString)(prop):null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&(VALUE_FREE_PROPERTIES.has(propName)||DIAGNOSTIC_ACCESSORS.has(propName)))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);const DIAGNOSTIC_ACCESSORS=new Set(["message","stack","name","status","statusText"]);function isDiagnosticAccessor(node){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);const value=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;return value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(value),DIAGNOSTIC_ACCESSORS)}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{interop:{runtimes:["eslint","oxlint"]},type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],createOnce(context,currentOptions){let sensitivePatterns;let checkConsoleLog;let checkErrorMessages;let descriptorSegments;let additionalDescriptorSegments;let descriptors;let LOGGER_RECEIVERS;let LOG_METHODS;function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}const name=node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(node):null;return name!==null&&LOGGER_RECEIVERS.has(name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);const staticText1=(0,eslint_devkit_1.staticString)(arg);if(staticText1!==null){const pattern=literalCarriesSecret(staticText1,sensitivePatterns)?containsSensitiveData(staticText1,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){const staticText2=(0,eslint_devkit_1.staticString)(arg.left);if(staticText2!==null){const labelled=literalLabelsValue(staticText2,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const allHolesAreDiagnostic=arg.expressions.every(isNonSecretHole);const fromText=arg.expressions.length>0&&!allHolesAreDiagnostic&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function isNonSecretHole(expression){if(!isDiagnosticAccessor(expression))return false;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(expression);const member=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return true;const init=resolveBindingInit(member.object);if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return true;const key=member.property.name;const assigned=init.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name===key||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value===key));if(!assigned)return true;return namedValueExposure(assigned.value)===null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const method=(0,eslint_devkit_1.propertyName)(node.callee);return method!==null&&LOG_METHODS.has(method.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{before(){const[options={}]=currentOptions();({sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{});descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);LOGGER_RECEIVERS=new Set(["console","logger","log"]);LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"])},CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(isLocallyConstructed(resolveVariable(root.name,scope),scope))return null;if(!properties.some(property=>attribution.requestProperties.has(property))){return null}if(attribution.requestRoots.has(root.name)||attribution.trustRequestShape&&(0,eslint_devkit_1.readsRequestShape)(node,attribution.sourceCode)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)&&!isNarrowedByGuardClause(node.name,node,attribution.sourceCode)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function isNarrowedByGuardClause(name,node,sourceCode){let fn=node;while(fn.parent!==void 0&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){fn=fn.parent}const body=fn.body;if(body===void 0||body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return false;for(const statement of body.body){if(statement.range[0]>=node.range[0])break;if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)continue;const leaves=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(inner=>inner.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||inner.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return false};if(!leaves(statement.consequent))continue;const test=statement.test;if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")continue;const call=test.argument;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)continue;const method=call.callee.property;if(method.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||method.name!=="has"&&method.name!=="includes"){continue}const[checked]=call.arguments;if(checked?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||checked.name!==name)continue;const receiver=call.callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;let search=sourceCode.getScope(node);let declared;while(search!==null&&declared===void 0){declared=search.variables.find(v=>v.name===receiver.name);search=search.upper}const source=declared?.defs[0]?.node.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator?declared.defs[0].node.init:void 0;if(source===void 0||source===null)continue;const listOf=init=>{if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return[...init.elements].filter(Boolean);if(init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="Set"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return[...init.arguments[0].elements].filter(Boolean)}return void 0};const members=listOf(source);if(members===void 0||members.length===0)continue;if(members.every(el=>el.type===eslint_devkit_1.AST_NODE_TYPES.Literal))return true}return false}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if((0,eslint_devkit_1.propertyName)(callee)!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sql-injection.md",description:"Prevent SQL injection when a query is built from attacker-controlled input and executed through a driver-agnostic handle",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{sqlInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:'SQL statement built from "{{source}}" and executed. An attacker controls part of the statement text.',severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Pass the value as a bound parameter (`$1` / `?`) instead of concatenating it into the statement.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[{type:"object",properties:{reportUnattributedInterpolation:{type:"boolean",default:false,description:"Report SQL built by interpolation even when the interpolated value cannot be traced to a request in this file (a property of `this`, a property of a non-request object, a helper return). Parameterise either way. Set false to report only attributable taint."},treatParametersAsUntrusted:{type:"boolean",default:true,description:"Treat a function parameter spliced into statement text as an untrusted inlet \u2014 nothing in this file constrains what a caller passes. Set false to report only values traceable to a request within the linted file."},requestRoots:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Identifier roots that denote an inbound request. Matched exactly."},requestProperties:{type:"array",items:{type:"string"},default:[...REQUEST_PROPERTIES],description:"Request properties that carry caller-supplied data. Matched exactly."},sinkMethods:{type:"array",items:{type:"string"},default:[...SQL_SINK_METHODS],description:"Method names that execute a raw SQL string. Matched exactly against the called member name."},queryTextProperties:{type:"array",items:{type:"string"},default:[...QUERY_TEXT_PROPERTIES],description:"Properties of a driver query-config object that hold the statement text. Matched exactly."},transparentCalls:{type:"array",items:{type:"string"},default:[...TRANSPARENT_CALLS],description:"Ambient global calls that pass their argument through unchanged, so taint survives them. Matched exactly, and only when the file declares no binding of that name."}},additionalProperties:false}]},defaultOptions:[{reportUnattributedInterpolation:false,treatParametersAsUntrusted:true,requestRoots:REQUEST_ROOTS,requestProperties:REQUEST_PROPERTIES,sinkMethods:SQL_SINK_METHODS,transparentCalls:TRANSPARENT_CALLS,queryTextProperties:QUERY_TEXT_PROPERTIES}],create(context,[options={}]){const{reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options;const attribution={substitutions:NO_SUBSTITUTIONS,untrustedParameters:treatParametersAsUntrusted,requestRoots:new Set(requestRoots),trustRequestShape:requestRoots.length===REQUEST_ROOTS.length&&REQUEST_ROOTS.every((name,index)=>requestRoots[index]===name),requestProperties:new Set(requestProperties),transparentCalls:new Set(transparentCalls),queryTextProperties:new Set(queryTextProperties),sourceCode:context.sourceCode};const sinks=new Set(sinkMethods);const pending=[];let importsSqlDriver=false;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(isLocallyConstructed(resolveVariable(root.name,scope),scope))return null;if(!properties.some(property=>attribution.requestProperties.has(property))){return null}if(attribution.requestRoots.has(root.name)||attribution.trustRequestShape&&(0,eslint_devkit_1.readsRequestShape)(node,attribution.sourceCode)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)&&!isNarrowedByGuardClause(node.name,node,attribution.sourceCode)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function isNarrowedByGuardClause(name,node,sourceCode){let fn=node;while(fn.parent!==void 0&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){fn=fn.parent}const body=fn.body;if(body===void 0||body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return false;for(const statement of body.body){if(statement.range[0]>=node.range[0])break;if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)continue;const leaves=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(inner=>inner.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||inner.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return false};if(!leaves(statement.consequent))continue;const test=statement.test;if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")continue;const call=test.argument;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)continue;const method=call.callee.property;if(method.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||method.name!=="has"&&method.name!=="includes"){continue}const[checked]=call.arguments;if(checked?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||checked.name!==name)continue;const receiver=call.callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;let search=sourceCode.getScope(node);let declared;while(search!==null&&declared===void 0){declared=search.variables.find(v=>v.name===receiver.name);search=search.upper}const source=declared?.defs[0]?.node.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator?declared.defs[0].node.init:void 0;if(source===void 0||source===null)continue;const listOf=init=>{if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return[...init.elements].filter(Boolean);if(init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="Set"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return[...init.arguments[0].elements].filter(Boolean)}return void 0};const members=listOf(source);if(members===void 0||members.length===0)continue;if(members.every(el=>el.type===eslint_devkit_1.AST_NODE_TYPES.Literal))return true}return false}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if((0,eslint_devkit_1.propertyName)(callee)!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sql-injection.md",description:"Prevent SQL injection when a query is built from attacker-controlled input and executed through a driver-agnostic handle",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{sqlInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:'SQL statement built from "{{source}}" and executed. An attacker controls part of the statement text.',severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Pass the value as a bound parameter (`$1` / `?`) instead of concatenating it into the statement.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[{type:"object",properties:{reportUnattributedInterpolation:{type:"boolean",default:false,description:"Report SQL built by interpolation even when the interpolated value cannot be traced to a request in this file (a property of `this`, a property of a non-request object, a helper return). Parameterise either way. Set false to report only attributable taint."},treatParametersAsUntrusted:{type:"boolean",default:true,description:"Treat a function parameter spliced into statement text as an untrusted inlet \u2014 nothing in this file constrains what a caller passes. Set false to report only values traceable to a request within the linted file."},requestRoots:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Identifier roots that denote an inbound request. Matched exactly."},requestProperties:{type:"array",items:{type:"string"},default:[...REQUEST_PROPERTIES],description:"Request properties that carry caller-supplied data. Matched exactly."},sinkMethods:{type:"array",items:{type:"string"},default:[...SQL_SINK_METHODS],description:"Method names that execute a raw SQL string. Matched exactly against the called member name."},queryTextProperties:{type:"array",items:{type:"string"},default:[...QUERY_TEXT_PROPERTIES],description:"Properties of a driver query-config object that hold the statement text. Matched exactly."},transparentCalls:{type:"array",items:{type:"string"},default:[...TRANSPARENT_CALLS],description:"Ambient global calls that pass their argument through unchanged, so taint survives them. Matched exactly, and only when the file declares no binding of that name."}},additionalProperties:false}]},defaultOptions:[{reportUnattributedInterpolation:false,treatParametersAsUntrusted:true,requestRoots:REQUEST_ROOTS,requestProperties:REQUEST_PROPERTIES,sinkMethods:SQL_SINK_METHODS,transparentCalls:TRANSPARENT_CALLS,queryTextProperties:QUERY_TEXT_PROPERTIES}],createOnce(context,currentOptions){let reportUnattributedInterpolation;let treatParametersAsUntrusted;let requestRoots;let requestProperties;let sinkMethods;let transparentCalls;let queryTextProperties;let attribution;let sinks;let pending;let importsSqlDriver;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{before(){const[options={}]=currentOptions();({reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options);attribution={substitutions:NO_SUBSTITUTIONS,untrustedParameters:treatParametersAsUntrusted,requestRoots:new Set(requestRoots),trustRequestShape:requestRoots.length===REQUEST_ROOTS.length&&REQUEST_ROOTS.every((name,index)=>requestRoots[index]===name),requestProperties:new Set(requestProperties),transparentCalls:new Set(transparentCalls),queryTextProperties:new Set(queryTextProperties),sourceCode:context.sourceCode};sinks=new Set(sinkMethods);pending=[];importsSqlDriver=false},ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
|