eslint-plugin-secure-coding 5.6.0 → 5.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/index.js +1 -1
- package/src/rules/detect-non-literal-regexp/index.js +1 -1
- package/src/rules/detect-object-injection/index.js +1 -1
- package/src/rules/no-directive-injection/index.js +1 -1
- package/src/rules/no-disabled-template-escaping/index.js +1 -1
- package/src/rules/no-electron-security-issues/index.js +1 -1
- package/src/rules/no-fail-open-auth/index.js +1 -1
- package/src/rules/no-format-string-injection/index.js +1 -1
- package/src/rules/no-graphql-injection/index.js +1 -1
- package/src/rules/no-hardcoded-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-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-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-secure-defaults/index.js +1 -1
|
@@ -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:"];const DEFAULT_LOGGERS=["logger","log"];const LOGGER_METHODS=new Set(["trace","debug","verbose","info","log","warn","error","fatal"]);const DEFAULT_PII_RECORDS=["user","person","customer","account","applicant","patient"];const EMAIL_IN_TEXT=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/;const SSN_IN_TEXT=/(?<!\d)\d{3}-\d{2}-\d{4}(?!\d)/;const CARD_IN_TEXT=/(?<![\d-])\d(?:[ -]?\d){12,18}(?![\d-])/g;function passesLuhn(digits){let sum=0;for(let i=0;i<digits.length;i++){let digit=Number(digits[digits.length-1-i]);if(i%2===1){digit*=2;if(digit>9)digit-=9}sum+=digit}return sum%10===0}function constantTextHasPii(node){const constant=(0,eslint_devkit_1.staticString)(node);let text;if(constant!==null){text=constant}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){text=node.quasis.map(quasi=>quasi.value.raw).join(" ")}else{return false}if(EMAIL_IN_TEXT.test(text)||SSN_IN_TEXT.test(text))return true;return[...text.matchAll(CARD_IN_TEXT)].some(match=>passesLuhn(match[0].replace(/[ -]/g,"")))}function stringifiedValue(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||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!=="JSON"||(0,eslint_devkit_1.propertyName)(node.callee)!=="stringify"){return null}const[value]=node.arguments;return value===void 0||value.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement?null:value}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
|
|
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:"];const DEFAULT_LOGGERS=["logger","log"];const LOGGER_METHODS=new Set(["trace","debug","verbose","info","log","warn","error","fatal"]);const DEFAULT_PII_RECORDS=["user","person","customer","account","applicant","patient"];const EMAIL_IN_TEXT=/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/;const SSN_IN_TEXT=/(?<!\d)\d{3}-\d{2}-\d{4}(?!\d)/;const CARD_IN_TEXT=/(?<![\d-])\d(?:[ -]?\d){12,18}(?![\d-])/g;function passesLuhn(digits){let sum=0;for(let i=0;i<digits.length;i++){let digit=Number(digits[digits.length-1-i]);if(i%2===1){digit*=2;if(digit>9)digit-=9}sum+=digit}return sum%10===0}function constantTextHasPii(node){const constant=(0,eslint_devkit_1.staticString)(node);let text;if(constant!==null){text=constant}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){text=node.quasis.map(quasi=>quasi.value.raw).join(" ")}else{return false}if(EMAIL_IN_TEXT.test(text)||SSN_IN_TEXT.test(text))return true;return[...text.matchAll(CARD_IN_TEXT)].some(match=>passesLuhn(match[0].replace(/[ -]/g,"")))}const INVERTIBLE_UNARY=new Set(["+","-","~"]);const VALUE_PRESERVING_BINARY=new Set(["+","-","*","/"]);function stringifiedValue(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||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!=="JSON"||(0,eslint_devkit_1.propertyName)(node.callee)!=="stringify"){return null}const[value]=node.arguments;return value===void 0||value.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement?null:value}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&&VALUE_PRESERVING_BINARY.has(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)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&INVERTIBLE_UNARY.has(node.operator)){pending.push(node.argument)}else{const serialized=stringifiedValue(node);if(serialized!==null)pending.push(serialized)}}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`."},loggers:{type:"array",items:{type:"string"},default:DEFAULT_LOGGERS,description:"Receiver names that denote an application logger (`logger.info`, `this.logger.error`); every level method on one is a log sink. Replaces the built-in list."},additionalLoggers:{type:"array",items:{type:"string"},default:[],description:"Extra logger receiver names, on top of `loggers`."},piiRecords:{type:"array",items:{type:"string"},default:DEFAULT_PII_RECORDS,description:"Words naming a whole person record, matched as WHOLE WORDS of an identifier. `JSON.stringify` of one is reported. Replaces the built-in list."},additionalPiiRecords:{type:"array",items:{type:"string"},default:[],description:"Extra person-record words, on top of `piiRecords`."}},additionalProperties:false}]},defaultOptions:[{consoleMethods:DEFAULT_CONSOLE_METHODS,additionalConsoleMethods:[],piiTerms:DEFAULT_PII_TERMS,additionalPiiTerms:[],piiLabels:DEFAULT_PII_LABELS,additionalPiiLabels:[],loggers:DEFAULT_LOGGERS,additionalLoggers:[],piiRecords:DEFAULT_PII_RECORDS,additionalPiiRecords:[]}],createOnce(context,currentOptions){let logMethods;let terms;let labels;let loggerNames;let records;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 bound=declared.parent?.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentPattern?declared.parent:declared;const parent=bound.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property){const key=(0,eslint_devkit_1.objectKeyName)(parent);return key!==null&&(0,eslint_devkit_1.nameHasAnyWord)(key,terms)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){return isPiiFieldAccess(parent.init,terms)}return false})}function isLogSink(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,eslint_devkit_1.propertyName)(callee);const receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return receiver.name==="console"?(0,eslint_devkit_1.namesOneOf)(method,logMethods):loggerNames.has(receiver.name)&&(0,eslint_devkit_1.namesOneOf)(method,LOGGER_METHODS)}return receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&loggerNames.has((0,eslint_devkit_1.propertyName)(receiver))&&(0,eslint_devkit_1.namesOneOf)(method,LOGGER_METHODS)}function isSerializedRecord(node){const serialized=stringifiedValue(node);return serialized?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(serialized.name,records)}return{before(){const[options={}]=currentOptions();const{consoleMethods=DEFAULT_CONSOLE_METHODS,additionalConsoleMethods=[],piiTerms=DEFAULT_PII_TERMS,additionalPiiTerms=[],piiLabels=DEFAULT_PII_LABELS,additionalPiiLabels=[],loggers=DEFAULT_LOGGERS,additionalLoggers=[],piiRecords=DEFAULT_PII_RECORDS,additionalPiiRecords=[]}=options;loggerNames=new Set([...loggers,...additionalLoggers]);records=[...piiRecords,...additionalPiiRecords];logMethods=new Set([...consoleMethods,...additionalConsoleMethods]);terms=[...piiTerms,...additionalPiiTerms];labels=new Set([...piiLabels,...additionalPiiLabels].map(label=>label.trim().toLowerCase()));sourceCode=context.sourceCode},CallExpression(node){if(!isLogSink(node.callee)){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)||isSerializedRecord(value)||constantTextHasPii(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:{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
|
+
"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.property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier){return member.property.name}return(0,eslint_devkit_1.propertyName)(member)}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")continue;const keyName=(0,eslint_devkit_1.objectKeyName)(prop)?.toLowerCase();if(keyName!==void 0&&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:{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
|
+
"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).filter(set=>set!==null);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:{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
|
+
"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):prop.name;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)}const ERROR_CONSTRUCTORS=new Set(["Error","TypeError","RangeError","SyntaxError","ReferenceError","EvalError","URIError","AggregateError"]);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=!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&&ERROR_CONSTRUCTORS.has(node.callee.name)){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.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration?declared.node:null}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;
|
|
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 unlessVisiting(visiting,key,onCycle,follow){if(visiting.has(key))return onCycle;visiting.add(key);try{return follow()}finally{visiting.delete(key)}}function boundExpression(bound){const seen=new Set;let current=bound;for(;;){seen.add(current);const next=current.node===null?void 0:substitutionFor(current.node,current.scope,current.substitutions);if(next===void 0||seen.has(next)){return{node:current.node,scope:current.scope}}current=next}}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){const{node:argument,scope:argumentScope}=boundExpression(bound);return argument!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:argument,scope:argumentScope})}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){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=[/\bselect\b[\s\S]*\bfrom\b/i,/\binsert\s+into\b/i,/\bupdate\b[\s\S]*\bset\b/i,/\bdelete\s+from\b/i,/\breplace\s+into\b/i,/\bmerge\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))}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 isOverwrittenWithConstant(variable,scope,use){const writes=variable.references.filter(reference=>reference.writeExpr);if(writes.length===0)return false;if(!writes.every(reference=>(0,eslint_devkit_1.isStaticExpression)({node:reference.writeExpr,scope}))){return false}const declaring=variable.defs[0]?.node;return writes.some(reference=>{const assignment=reference.identifier.parent;const statement=assignment?.parent;return assignment?.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&assignment.operator==="="&&statement?.type===eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement&&statement.parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&statement.parent.parent===declaring&&statement.range[1]<=use.range[0]})}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(writeExpr){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,visiting){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){const[argument]=node.arguments;return argument===void 0?null:attributedSource(argument,scope,attribution,visiting)}return unlessVisiting(visiting,node,null,()=>{const inlined=effectiveExpression(node,scope,attribution);const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,visiting);if(found!==null)return found}return null})}function attributedSource(node,scope,attribution,visiting=new Set){const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,visiting);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,visiting);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,visiting)??attributedSource(node.right,scope,attribution,visiting)}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,visiting)??attributedSource(node.alternate,scope,attribution,visiting)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,visiting)??attributedSource(node.right,scope,attribution,visiting)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,visiting)}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){const argument=bound.node;return argument===null?null:unlessVisiting(visiting,bound,null,()=>attributedSource(argument,bound.scope,{...attribution,substitutions:bound.substitutions},visiting))}const writes=writeExpressions(variable);for(const write of writes){const found=unlessVisiting(visiting,write,null,()=>attributedSource(write,scope,attribution,visiting));if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!isOverwrittenWithConstant(variable,scope,node)&&!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.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;if(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,visiting=new Set){const unresolved={nodes:[node],scope,substitutions:attribution.substitutions};const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,visiting)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,visiting)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:attribution.substitutions}}return unlessVisiting(visiting,node,null,()=>resolveBuilderCall(node,scope,attribution,visiting))??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,visiting)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const bound=attribution.substitutions.get(variable);if(bound!==void 0){const argument=bound.node;return argument===null?unresolved:unlessVisiting(visiting,bound,unresolved,()=>effectiveExpression(argument,bound.scope,{...attribution,substitutions:bound.substitutions},visiting))}const writes=writeExpressions(variable);const[only]=writes;if(writes.length===1&&only!==void 0){return unlessVisiting(visiting,only,unresolved,()=>effectiveExpression(only,scope,attribution,visiting))}return{nodes:writes,scope,substitutions:attribution.substitutions}}function resolveBuilderCall(node,scope,attribution,visiting){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)return null;const bindings=bindParameters(impl,node.arguments,scope,attribution.substitutions,attribution.sourceCode);if(bindings===null)return null;return effectiveExpression(returned,attribution.sourceCode.getScope(returned),{...attribution,substitutions:bindings},visiting)}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.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration?declared.node:null}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[first]=impl.body.body;if(first?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return null;return first.argument}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)continue;elements.push(element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement?element.argument: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 argumentAt(args,position){for(const[index,argument]of args.entries()){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return argument.argument;if(index===position)return argument}return void 0}function bindParameters(impl,args,callerScope,callerSubstitutions,sourceCode){const parameters=sourceCode.getDeclaredVariables(impl).filter(variable=>variable.defs[0]?.type==="Parameter");const bindings=new Map;let position=0;for(const[index,param]of impl.params.entries()){const target=param.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentPattern?param.left:param;if(target.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(target.name==="this")continue;const variable=parameters[index];const passed=argumentAt(args,position);position+=1;if(passed!==void 0){bindings.set(variable,{node:passed,scope:callerScope,substitutions:callerSubstitutions})}else if(param.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentPattern){bindings.set(variable,{node:param.right,scope:sourceCode.getScope(impl),substitutions:bindings})}else{bindings.set(variable,{node:null,scope:callerScope,substitutions:callerSubstitutions})}}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:REQUEST_ROOTS.every(name=>requestRoots.includes(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)return;const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);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 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",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-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow an infinite-loop form (`while (true)`, `while (1)`, `do \u2026 while (true)`, `for (;;)`) whose body leaves it: a `break` of that loop, a `return` or a `throw`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let maxStaticIterations;let userInputVariables;let allowWhileTrueWithBreak;let maxRecursionDepth;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let functionCalls;let reportedRecursion;let currentFunctionStack;let taintedVariables;let REQUEST_OBJECTS;const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(side)==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){const bounded=side=>isClamped(side)||!involvesUserInput(side);return bounded(expression.left)&&bounded(expression.right)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(node)==="length"){return false}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasLoopExit=loopBody=>{let found=false;const innerLabels=new Set;const walk=(node,insideNestedBreakable)=>{if(found)return;switch(node.type){case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return;case"BreakStatement":if(node.label===null){if(!insideNestedBreakable)found=true}else if(!innerLabels.has(node.label.name)){found=true}return;case"ReturnStatement":case"ThrowStatement":found=true;return;default:break}if(node.type==="LabeledStatement")innerLabels.add(node.label.name);const breakable=insideNestedBreakable||node.type==="ForStatement"||node.type==="ForInStatement"||node.type==="ForOfStatement"||node.type==="WhileStatement"||node.type==="DoWhileStatement"||node.type==="SwitchStatement";for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(child===null||typeof child!=="object")continue;if(Array.isArray(child)){for(const item of child){if(item!==null&&typeof item==="object"&&"type"in item){walk(item,breakable)}}}else if("type"in child){walk(child,breakable)}}};walk(loopBody,false);return found};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);for(let child=call,current=call.parent;;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return false}if(current.type==="FunctionDeclaration")return true}};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=test=>{if(test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};const checkInfiniteLoop=node=>{if(safetyChecker.isSafe(node,context)){return}if(allowWhileTrueWithBreak&&hasLoopExit(node.body)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})};const isConstantlyTrue=test=>test.type==="Literal"&&Boolean(test.value);const checkLargeBound=(node,test)=>{const estimatedIterations=estimateIterations(test);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}};return{before(){const options=context.options[0]||{};({maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});functionCalls=new Map;reportedRecursion=new Set;currentFunctionStack=[];taintedVariables=new Set;REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"])},VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&¤tFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(isConstantlyTrue(test)){checkInfiniteLoop(node);return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}checkLargeBound(node,test)},ForStatement(node){if(!node.test&&!node.update){checkInfiniteLoop(node);return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}checkLargeBound(node,node.test)},DoWhileStatement(node){const test=node.test;if(isConstantlyTrue(test)){checkInfiniteLoop(node);return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",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-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow an infinite-loop form (`while (true)`, `while (1)`, `do \u2026 while (true)`, `for (;;)`) whose body leaves it: a `break` of that loop, a `return` or a `throw`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let maxStaticIterations;let userInputVariables;let allowWhileTrueWithBreak;let maxRecursionDepth;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let functionCalls;let reportedRecursion;let currentFunctionStack;let taintedVariables;let REQUEST_OBJECTS;const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(side)==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){const bounded=side=>isClamped(side)||!involvesUserInput(side);return bounded(expression.left)&&bounded(expression.right)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(node)==="length"){return false}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasLoopExit=loopBody=>{let found=false;const innerLabels=new Set;const walk=(node,insideNestedBreakable)=>{if(found)return;switch(node.type){case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return;case"BreakStatement":if(node.label===null){if(!insideNestedBreakable)found=true}else if(!innerLabels.has(node.label.name)){found=true}return;case"ReturnStatement":case"ThrowStatement":found=true;return;default:break}if(node.type==="LabeledStatement")innerLabels.add(node.label.name);const breakable=insideNestedBreakable||node.type==="ForStatement"||node.type==="ForInStatement"||node.type==="ForOfStatement"||node.type==="WhileStatement"||node.type==="DoWhileStatement"||node.type==="SwitchStatement";for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(child===null||typeof child!=="object")continue;if(Array.isArray(child)){for(const item of child){if(item!==null&&typeof item==="object"&&"type"in item){walk(item,breakable)}}}else if("type"in child){walk(child,breakable)}}};walk(loopBody,false);return found};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);for(let child=call,current=call.parent;;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return false}if(current.type==="FunctionDeclaration")return true}};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=test=>{if(test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}if(right.type==="Literal"&&"bigint"in right){return Math.abs(Number(right.bigint))}}}return null};const checkInfiniteLoop=node=>{if(safetyChecker.isSafe(node,context)){return}if(allowWhileTrueWithBreak&&hasLoopExit(node.body)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})};const isConstantlyTrue=test=>test.type==="Literal"&&Boolean(test.value);const checkLargeBound=(node,test)=>{const estimatedIterations=estimateIterations(test);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}};return{before(){const options=context.options[0]||{};({maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});functionCalls=new Map;reportedRecursion=new Set;currentFunctionStack=[];taintedVariables=new Set;REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"])},VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.init){const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){for(const variable of sourceCode.getDeclaredVariables(declarator)){taintedVariables.add(variable.name)}}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&¤tFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(isConstantlyTrue(test)){checkInfiniteLoop(node);return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}checkLargeBound(node,test)},ForStatement(node){if(!node.test&&!node.update){checkInfiniteLoop(node);return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}checkLargeBound(node,node.test)},DoWhileStatement(node){const test=node.test;if(isConstantlyTrue(test)){checkInfiniteLoop(node);return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnlimitedResourceAllocation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const DEFAULT_SIZE_PROPERTIES=["length","size","byteLength","count"];const DEFAULT_LIMIT_OPTION_NAMES=["maxOutputLength","maxSize","limit"];const BYTE_BUFFER_CONSTRUCTORS=new Set(["ArrayBuffer","SharedArrayBuffer"]);exports.noUnlimitedResourceAllocation=(0,eslint_devkit_1.createRule)({name:"no-unlimited-resource-allocation",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-unlimited-resource-allocation.md",description:"Detects unlimited resource allocation that could cause DoS",cwe:"CWE-770"},messages:{unlimitedBufferAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Buffer Allocation",cwe:"CWE-770",description:"Buffer allocated without size limits",severity:"HIGH",fix:"Set maximum buffer size limits \u2014 Not a finding if the size is a constant, or already clamped before this line",documentationLink:"https://nodejs.org/api/buffer.html"}),unlimitedFileOperations:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited File Operations",cwe:"CWE-770",description:"File operations without size limits",severity:"MEDIUM",fix:"Validate file size before operations \u2014 Not a finding if the decompressed bytes are counted against a ceiling downstream",documentationLink:"https://nodejs.org/api/fs.html"}),unlimitedMemoryAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Memory Allocation",cwe:"CWE-770",description:"Memory allocated without limits",severity:"MEDIUM",fix:"Set memory allocation limits \u2014 Not a finding if the length comes from data the process already holds",documentationLink:"https://nodejs.org/api/buffer.html"}),userControlledResourceSize:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Resource Size",cwe:"CWE-770",description:"Resource size controlled by user input",severity:"HIGH",fix:"Validate and limit user-controlled resource sizes \u2014 Not a finding if the value is content rather than a byte count",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),resourceAllocationInLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Resource Allocation in Loop",cwe:"CWE-770",description:"Resource allocation inside loop without limits",severity:"HIGH",fix:"Move resource allocation outside loop or add iteration limits \u2014 Not a finding if the loop bound is a constant or a collection the process already holds",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"})},schema:[{type:"object",properties:{sizeProperties:{type:"array",items:{type:"string"},default:[...DEFAULT_SIZE_PROPERTIES],description:"Property names that carry a magnitude. Replaces the default."},limitOptionNames:{type:"array",items:{type:"string"},default:[...DEFAULT_LIMIT_OPTION_NAMES],description:"Option keys a library accepts to cap an operation. Replaces the default."},maxResourceSize:{type:"number",minimum:1024,default:1048576,description:"Allocation size in bytes above which a call is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},safeResourceFunctions:{type:"array",items:{type:"string"},default:["validateSize","checkLimits","limitResource","safeAlloc"],description:"Function names that bound an allocation"},requireResourceValidation:{type:"boolean",default:true,description:"Require an explicit size check before allocating"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as resource validators"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{maxResourceSize:1048576,userInputVariables:["req","request","body","query","params","input","data"],safeResourceFunctions:["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let sizeProperties;let limitOptionNames;let maxResourceSize;let userInputVariables;let safeResourceFunctions;let requireResourceValidation;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let safetyChecker;let REQUEST_SURFACE;let requestRoots;const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;let archiveBindings;let ALLOCATORS;const readsRequestSurface=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);const initializerOf=id=>{const resolved=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved;const def=resolved?.defs[0];if(def?.type!=="Variable")return void 0;return def.node.init??void 0};const isInvokerControlled=(node,depth=0)=>{if(depth>12)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(requestRoots.has(node.name.toLowerCase())&&readsRequestSurface(node.parent)){return true}const init=initializerOf(node);return init!==void 0&&isInvokerControlled(init,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isInvokerControlled(node.object,depth+1)||node.computed&&isInvokerControlled(node.property,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return isInvokerControlled(node.callee,depth+1)||node.arguments.some(argument=>isInvokerControlled(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return isInvokerControlled(node.left,depth+1)||isInvokerControlled(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return isInvokerControlled(node.consequent,depth+1)||isInvokerControlled(node.alternate,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>isInvokerControlled(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return isInvokerControlled(node.argument,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return isInvokerControlled(node.expression,depth+1);default:return false}};const isUserInput=expression=>isInvokerControlled(expression);const couldBeASize=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","**","<<",">>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return node.operator==="+"||node.operator==="-"||node.operator==="~";case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return["Number","parseInt","parseFloat","BigInt"].includes(callee.name)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Math"}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),sizeProperties);case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=initializerOf(node);return init!==void 0&&couldBeASize(init)}case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return couldBeASize(node.left)||couldBeASize(node.right);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return couldBeASize(node.consequent)||couldBeASize(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return couldBeASize(node.expression);default:return false}};const hasSizeValidation=node=>{const args=node.arguments;const sizeArg=args[0];const sizeText=sizeArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${sourceCode.getText(sizeArg)} ${sourceCode.getText(initializerOf(sizeArg))}`:sourceCode.getText(sizeArg);return sizeText.includes("Math.min(")||sizeText.includes("Math.max(")||sizeText.includes("Math.clamp(")||safeResourceFunctions.some(func=>sizeText.includes(func))};const testsUpperBound=(test,name)=>{if(test.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return testsUpperBound(test.left,name)||testsUpperBound(test.right,name)}if(test.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)return false;const isName=side=>side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&side.name===name;return(test.operator===">"||test.operator===">=")&&isName(test.left)||(test.operator==="<"||test.operator==="<=")&&isName(test.right)};const alwaysExits=statement=>{const last=statement.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement?statement.body.at(-1):statement;return last?.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||last?.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};const hasUpperBoundGuard=node=>{const[sizeArg]=node.arguments;if(sizeArg.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let child=node,parent=node.parent;parent;child=parent,parent=parent.parent){if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&parent.type!==eslint_devkit_1.AST_NODE_TYPES.Program){continue}const statements=parent.body;if(statements.slice(0,statements.indexOf(child)).some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&testsUpperBound(statement.test,sizeArg.name)&&alwaysExits(statement.consequent))){return true}}return false};const isBounded=node=>hasSizeValidation(node)||hasUpperBoundGuard(node);const estimateResourceSize=sizeExpression=>{if(sizeExpression.type==="Literal"&&typeof sizeExpression.value==="number"){return sizeExpression.value}if(sizeExpression.type==="BinaryExpression"){const left=estimateResourceSize(sizeExpression.left);const right=estimateResourceSize(sizeExpression.right);if(left!==null&&right!==null){switch(sizeExpression.operator){case"*":return left*right;case"+":return left+right;case"-":return left-right;case"/":return right!==0?left/right:null;default:return null}}}return null};const noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};const enclosingLoop=node=>{let child=node;let current=node.parent;while(current!=null){switch(current.type){case eslint_devkit_1.AST_NODE_TYPES.ForStatement:return current.init===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.ForOfStatement:case eslint_devkit_1.AST_NODE_TYPES.ForInStatement:return current.right===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.WhileStatement:case eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement:return current;default:break}child=current;current=current.parent}return void 0};const isAllocationInLoopBody=node=>{const callee=node.callee;let name;const member=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&member!==null){name=`${callee.object.name}.${member}`}if(name===void 0||!ALLOCATORS.has(name))return false;const loop=enclosingLoop(node);if(loop===void 0)return false;const bound=loop.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||loop.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement?loop.right:loop.test??void 0;return bound!==void 0&&isInvokerControlled(bound)};const checkArrayLength=node=>{const args=node.arguments;if(args.length!==1)return;const sizeArg=args[0];if(sizeArg.type==="SpreadElement")return;const unbounded=isUserInput(sizeArg)&&!isBounded(node);const estimatedSize=estimateResourceSize(sizeArg);if(!unbounded&&(estimatedSize===null||estimatedSize<=maxResourceSize)){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation"})};return{before(){const options=context.options[0]||{};sizeProperties=new Set(options.sizeProperties??DEFAULT_SIZE_PROPERTIES);limitOptionNames=new Set(options.limitOptionNames??DEFAULT_LIMIT_OPTION_NAMES);({maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});REQUEST_SURFACE=new Set(["body","query","params","headers","cookies","url","originalUrl","rawBody","files","payload","searchParams"]);requestRoots=new Set(userInputVariables.map(name=>name.toLowerCase()));archiveBindings=new Set(["zlib"]);ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"])},ImportDeclaration(node){for(const spec of node.specifiers){if(spec.type==="ImportDefaultSpecifier"||spec.type==="ImportNamespaceSpecifier"){noteArchiveBinding(spec.local.name,String(node.source.value))}}},VariableDeclarator(node){if(node.id.type==="Identifier"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]?.type==="Literal"){noteArchiveBinding(node.id.name,String(node.init.arguments[0].value))}},CallExpression(node){const callee=node.callee;const isBufferAlloc=callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="Buffer"&&((0,eslint_devkit_1.propertyName)(callee)==="alloc"||(0,eslint_devkit_1.propertyName)(callee)==="allocUnsafe");if(isBufferAlloc){const args=node.arguments;if(args.length>0){const sizeArg=args[0];if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)&&!isBounded(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize"});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation"});return}}}if(callee.type==="Identifier"&&callee.name==="multer"){const args=node.arguments;if(args.length>0&&args[0].type==="ObjectExpression"){const props=args[0].properties;const hasValidLimits=props.some(prop=>{if(prop.type!=="Property"||prop.key.type!=="Identifier"){return false}if(prop.key.name==="fileSize")return true;if(prop.key.name==="limits"&&prop.value.type==="ObjectExpression"){return prop.value.properties.some(limitProp=>limitProp.type==="Property"&&limitProp.key.type==="Identifier"&&limitProp.key.name==="fileSize")}return false});if(!hasValidLimits){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unlimitedFileOperations"})}}return}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&["readFile","writeFile","readFileSync","writeFileSync"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){const args=node.arguments;if(args.length>0){const pathArg=args[0];if(pathArg.type!=="SpreadElement"&&(0,eslint_devkit_1.isStaticExpression)({node:pathArg,scope:context.sourceCode.getScope(pathArg)})){return}if(pathArg.type!=="SpreadElement"&&isUserInput(pathArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:pathArg,messageId:"unlimitedFileOperations"})}}}if(callee.type==="Identifier"&&callee.name==="Array"){checkArrayLength(node)}const isDecompression=()=>{if(callee.type!=="MemberExpression")return false;const member=callee;const receiver=member.object.type==="Identifier"?member.object.name:"";if(!archiveBindings.has(receiver))return false;const method=(0,eslint_devkit_1.propertyName)(member)??"";return/^(Extract|Parse|extract|createGunzip|createUnzip|createInflate|open)$/.test(method)};const hasDecompressionLimit=()=>node.arguments.some(argument=>argument.type==="ObjectExpression"&&argument.properties.some(property=>property.type==="Property"&&property.key.type==="Identifier"&&limitOptionNames.has(property.key.name)));const countsOutputBytes=()=>{const scope=context.sourceCode.getScope(node).variableScope.block;const accumulators=new Set;const compared=new Set;const visit=current=>{if(current===null||typeof current!=="object")return;if(Array.isArray(current)){for(const item of current)visit(item);return}const candidate=current;if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&candidate.operator==="+="&&candidate.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&candidate.right.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(candidate.right)==="length"||(0,eslint_devkit_1.propertyName)(candidate.right)==="byteLength")){accumulators.add(candidate.left.name)}if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&[">",">=","<","<="].includes(candidate.operator)){for(const side of[candidate.left,candidate.right]){if(side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)compared.add(side.name)}}for(const[key,value]of Object.entries(candidate)){if(key==="parent")continue;visit(value)}};visit(scope);return[...accumulators].some(name=>compared.has(name))};if(isDecompression()&&!hasDecompressionLimit()&&!countsOutputBytes()){context.report({node,messageId:"unlimitedFileOperations"})}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop"})}},NewExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&(callee.name==="Buffer"||BYTE_BUFFER_CONSTRUCTORS.has(callee.name))){const reservesBytes=BYTE_BUFFER_CONSTRUCTORS.has(callee.name);const args=node.arguments;if(args.length>0){const sizeArg=args[0];const hasEncodingArgument=args.length>1;if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&(reservesBytes||!hasEncodingArgument&&couldBeASize(sizeArg))&&isUserInput(sizeArg)&&!isBounded(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize"});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation"});return}}}if(callee.type==="Identifier"&&callee.name==="Array"){checkArrayLength(node)}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop"})}}}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnlimitedResourceAllocation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const DEFAULT_SIZE_PROPERTIES=["length","size","byteLength","count"];const DEFAULT_LIMIT_OPTION_NAMES=["maxOutputLength","maxSize","limit"];const BYTE_BUFFER_CONSTRUCTORS=new Set(["ArrayBuffer","SharedArrayBuffer"]);exports.noUnlimitedResourceAllocation=(0,eslint_devkit_1.createRule)({name:"no-unlimited-resource-allocation",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-unlimited-resource-allocation.md",description:"Detects unlimited resource allocation that could cause DoS",cwe:"CWE-770"},messages:{unlimitedBufferAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Buffer Allocation",cwe:"CWE-770",description:"Buffer allocated without size limits",severity:"HIGH",fix:"Set maximum buffer size limits \u2014 Not a finding if the size is a constant, or already clamped before this line",documentationLink:"https://nodejs.org/api/buffer.html"}),unlimitedFileOperations:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited File Operations",cwe:"CWE-770",description:"File operations without size limits",severity:"MEDIUM",fix:"Validate file size before operations \u2014 Not a finding if the decompressed bytes are counted against a ceiling downstream",documentationLink:"https://nodejs.org/api/fs.html"}),unlimitedMemoryAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Memory Allocation",cwe:"CWE-770",description:"Memory allocated without limits",severity:"MEDIUM",fix:"Set memory allocation limits \u2014 Not a finding if the length comes from data the process already holds",documentationLink:"https://nodejs.org/api/buffer.html"}),userControlledResourceSize:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Resource Size",cwe:"CWE-770",description:"Resource size controlled by user input",severity:"HIGH",fix:"Validate and limit user-controlled resource sizes \u2014 Not a finding if the value is content rather than a byte count",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),resourceAllocationInLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Resource Allocation in Loop",cwe:"CWE-770",description:"Resource allocation inside loop without limits",severity:"HIGH",fix:"Move resource allocation outside loop or add iteration limits \u2014 Not a finding if the loop bound is a constant or a collection the process already holds",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"})},schema:[{type:"object",properties:{sizeProperties:{type:"array",items:{type:"string"},default:[...DEFAULT_SIZE_PROPERTIES],description:"Property names that carry a magnitude. Replaces the default."},limitOptionNames:{type:"array",items:{type:"string"},default:[...DEFAULT_LIMIT_OPTION_NAMES],description:"Option keys a library accepts to cap an operation. Replaces the default."},maxResourceSize:{type:"number",minimum:1024,default:1048576,description:"Allocation size in bytes above which a call is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},safeResourceFunctions:{type:"array",items:{type:"string"},default:["validateSize","checkLimits","limitResource","safeAlloc"],description:"Function names that bound an allocation"},requireResourceValidation:{type:"boolean",default:true,description:"Require an explicit size check before allocating"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as resource validators"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{maxResourceSize:1048576,userInputVariables:["req","request","body","query","params","input","data"],safeResourceFunctions:["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let sizeProperties;let limitOptionNames;let maxResourceSize;let userInputVariables;let safeResourceFunctions;let requireResourceValidation;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let safetyChecker;let REQUEST_SURFACE;let requestRoots;const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;let archiveBindings;let ALLOCATORS;const readsRequestSurface=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);const initializerOf=id=>{const resolved=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved;const def=resolved?.defs[0];if(def?.type!=="Variable")return void 0;return def.node.init??void 0};const destructuresRequestSurface=id=>{const def=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved?.defs[0];if(def?.type!=="Variable"||def.node.init?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!requestRoots.has(def.node.init.name.toLowerCase())){return false}let outermostKey=null;for(let child=def.name;child!==def.node.id;child=child.parent){const parent=child.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property){outermostKey=(0,eslint_devkit_1.objectKeyName)(parent)}}return(0,eslint_devkit_1.namesOneOf)(outermostKey,REQUEST_SURFACE)};const isInvokerControlled=(node,depth=0)=>{if(depth>12)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(requestRoots.has(node.name.toLowerCase())&&readsRequestSurface(node.parent)){return true}if(destructuresRequestSurface(node))return true;const init=initializerOf(node);return init!==void 0&&isInvokerControlled(init,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isInvokerControlled(node.object,depth+1)||node.computed&&isInvokerControlled(node.property,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return isInvokerControlled(node.callee,depth+1)||node.arguments.some(argument=>isInvokerControlled(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return isInvokerControlled(node.left,depth+1)||isInvokerControlled(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return isInvokerControlled(node.consequent,depth+1)||isInvokerControlled(node.alternate,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>isInvokerControlled(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return isInvokerControlled(node.argument,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return isInvokerControlled(node.expression,depth+1);default:return false}};const isUserInput=expression=>isInvokerControlled(expression);const couldBeASize=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","**","<<",">>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return node.operator==="+"||node.operator==="-"||node.operator==="~";case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return["Number","parseInt","parseFloat","BigInt"].includes(callee.name)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Math"}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),sizeProperties);case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=initializerOf(node);return init!==void 0&&couldBeASize(init)}case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return couldBeASize(node.left)||couldBeASize(node.right);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return couldBeASize(node.consequent)||couldBeASize(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return couldBeASize(node.expression);default:return false}};const hasSizeValidation=node=>{const args=node.arguments;const sizeArg=args[0];const sizeText=sizeArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${sourceCode.getText(sizeArg)} ${sourceCode.getText(initializerOf(sizeArg))}`:sourceCode.getText(sizeArg);return sizeText.includes("Math.min(")||sizeText.includes("Math.max(")||sizeText.includes("Math.clamp(")||safeResourceFunctions.some(func=>sizeText.includes(func))};const testsUpperBound=(test,name)=>{if(test.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return testsUpperBound(test.left,name)||testsUpperBound(test.right,name)}if(test.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)return false;const isName=side=>side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&side.name===name;return(test.operator===">"||test.operator===">=")&&isName(test.left)||(test.operator==="<"||test.operator==="<=")&&isName(test.right)};const alwaysExits=statement=>{const last=statement.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement?statement.body.at(-1):statement;return last?.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||last?.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};const hasUpperBoundGuard=node=>{const[sizeArg]=node.arguments;if(sizeArg.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let child=node,parent=node.parent;parent;child=parent,parent=parent.parent){if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&parent.type!==eslint_devkit_1.AST_NODE_TYPES.Program){continue}const statements=parent.body;if(statements.slice(0,statements.indexOf(child)).some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&testsUpperBound(statement.test,sizeArg.name)&&alwaysExits(statement.consequent))){return true}}return false};const isBounded=node=>hasSizeValidation(node)||hasUpperBoundGuard(node);const estimateResourceSize=sizeExpression=>{if(sizeExpression.type==="Literal"&&typeof sizeExpression.value==="number"){return sizeExpression.value}if(sizeExpression.type==="BinaryExpression"){const left=estimateResourceSize(sizeExpression.left);const right=estimateResourceSize(sizeExpression.right);if(left!==null&&right!==null){switch(sizeExpression.operator){case"*":return left*right;case"+":return left+right;case"-":return left-right;case"/":return right!==0?left/right:null;default:return null}}}return null};const noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};const enclosingLoop=node=>{let child=node;let current=node.parent;while(current!=null){switch(current.type){case eslint_devkit_1.AST_NODE_TYPES.ForStatement:return current.init===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.ForOfStatement:case eslint_devkit_1.AST_NODE_TYPES.ForInStatement:return current.right===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.WhileStatement:case eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement:return current;default:break}child=current;current=current.parent}return void 0};const isAllocationInLoopBody=node=>{const callee=node.callee;let name;const member=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&member!==null){name=`${callee.object.name}.${member}`}if(name===void 0||!ALLOCATORS.has(name))return false;const loop=enclosingLoop(node);if(loop===void 0)return false;const bound=loop.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||loop.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement?loop.right:loop.test??void 0;return bound!==void 0&&isInvokerControlled(bound)};const checkArrayLength=node=>{const args=node.arguments;if(args.length!==1)return;const sizeArg=args[0];if(sizeArg.type==="SpreadElement")return;const unbounded=isUserInput(sizeArg)&&!isBounded(node);const estimatedSize=estimateResourceSize(sizeArg);if(!unbounded&&(estimatedSize===null||estimatedSize<=maxResourceSize)){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation"})};return{before(){const options=context.options[0]||{};sizeProperties=new Set(options.sizeProperties??DEFAULT_SIZE_PROPERTIES);limitOptionNames=new Set(options.limitOptionNames??DEFAULT_LIMIT_OPTION_NAMES);({maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});REQUEST_SURFACE=new Set(["body","query","params","headers","cookies","url","originalUrl","rawBody","files","payload","searchParams"]);requestRoots=new Set(userInputVariables.map(name=>name.toLowerCase()));archiveBindings=new Set(["zlib"]);ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"])},ImportDeclaration(node){for(const spec of node.specifiers){if(spec.type==="ImportDefaultSpecifier"||spec.type==="ImportNamespaceSpecifier"){noteArchiveBinding(spec.local.name,String(node.source.value))}}},VariableDeclarator(node){if(node.id.type==="Identifier"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]?.type==="Literal"){noteArchiveBinding(node.id.name,String(node.init.arguments[0].value))}},CallExpression(node){const callee=node.callee;const isBufferAlloc=callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="Buffer"&&((0,eslint_devkit_1.propertyName)(callee)==="alloc"||(0,eslint_devkit_1.propertyName)(callee)==="allocUnsafe");if(isBufferAlloc){const args=node.arguments;if(args.length>0){const sizeArg=args[0];if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)&&!isBounded(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize"});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation"});return}}}if(callee.type==="Identifier"&&callee.name==="multer"){const args=node.arguments;if(args.length>0&&args[0].type==="ObjectExpression"){const props=args[0].properties;const hasValidLimits=props.some(prop=>{if(prop.type!=="Property"||prop.key.type!=="Identifier"){return false}if(prop.key.name==="fileSize")return true;if(prop.key.name==="limits"&&prop.value.type==="ObjectExpression"){return prop.value.properties.some(limitProp=>limitProp.type==="Property"&&limitProp.key.type==="Identifier"&&limitProp.key.name==="fileSize")}return false});if(!hasValidLimits){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unlimitedFileOperations"})}}return}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&["readFile","writeFile","readFileSync","writeFileSync"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){const args=node.arguments;if(args.length>0){const pathArg=args[0];if(pathArg.type!=="SpreadElement"&&(0,eslint_devkit_1.isStaticExpression)({node:pathArg,scope:context.sourceCode.getScope(pathArg)})){return}if(pathArg.type!=="SpreadElement"&&isUserInput(pathArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:pathArg,messageId:"unlimitedFileOperations"})}}}if(callee.type==="Identifier"&&callee.name==="Array"){checkArrayLength(node)}const isDecompression=()=>{if(callee.type!=="MemberExpression")return false;const member=callee;const receiver=member.object.type==="Identifier"?member.object.name:"";if(!archiveBindings.has(receiver))return false;const method=(0,eslint_devkit_1.propertyName)(member)??"";return/^(Extract|Parse|extract|createGunzip|createUnzip|createInflate|open)$/.test(method)};const hasDecompressionLimit=()=>node.arguments.some(argument=>argument.type==="ObjectExpression"&&argument.properties.some(property=>property.type==="Property"&&property.key.type==="Identifier"&&limitOptionNames.has(property.key.name)));const countsOutputBytes=()=>{const scope=context.sourceCode.getScope(node).variableScope.block;const accumulators=new Set;const compared=new Set;const visit=current=>{if(current===null||typeof current!=="object")return;if(Array.isArray(current)){for(const item of current)visit(item);return}const candidate=current;if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&candidate.operator==="+="&&candidate.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&candidate.right.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(candidate.right)==="length"||(0,eslint_devkit_1.propertyName)(candidate.right)==="byteLength")){accumulators.add(candidate.left.name)}if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&[">",">=","<","<="].includes(candidate.operator)){for(const side of[candidate.left,candidate.right]){if(side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)compared.add(side.name)}}for(const[key,value]of Object.entries(candidate)){if(key==="parent")continue;visit(value)}};visit(scope);return[...accumulators].some(name=>compared.has(name))};if(isDecompression()&&!hasDecompressionLimit()&&!countsOutputBytes()){context.report({node,messageId:"unlimitedFileOperations"})}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop"})}},NewExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&(callee.name==="Buffer"||BYTE_BUFFER_CONSTRUCTORS.has(callee.name))){const reservesBytes=BYTE_BUFFER_CONSTRUCTORS.has(callee.name);const args=node.arguments;if(args.length>0){const sizeArg=args[0];const hasEncodingArgument=args.length>1;if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&(reservesBytes||!hasEncodingArgument&&couldBeASize(sizeArg))&&isUserInput(sizeArg)&&!isBounded(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize"});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation"});return}}}if(callee.type==="Identifier"&&callee.name==="Array"){checkArrayLength(node)}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop"})}}}}});
|