agentsqripts
Version:
Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems
282 lines (262 loc) • 14.3 kB
JavaScript
/**
* @file Modern vulnerability pattern detector
* @description Detects contemporary security vulnerabilities and emerging attack patterns
* This module focuses on modern vulnerability types that have emerged with new technologies,
* frameworks, and attack methodologies. Unlike classic vulnerabilities like SQL injection,
* these patterns reflect current threat landscapes including ReDoS, SSRF, deserialization
* attacks, and authentication bypass techniques that are prevalent in modern applications.
*/
/**
* Detect Regular Expression Denial of Service (ReDoS) vulnerabilities
* @param {string} content - Source code content to analyze
* @returns {Array<Object>} Array of detected ReDoS vulnerability objects
*
* Rationale: ReDoS has become a critical vulnerability class as applications increasingly
* rely on regular expressions for input validation and parsing. Maliciously crafted input
* can cause exponential backtracking in vulnerable regex patterns, leading to CPU exhaustion
* and application denial of service. This is particularly dangerous in web applications
* where user input is processed through regex validation.
*/
const detectReDoS = (content) => {
const vulnerabilities = [];
const lines = content.split('\n');
// Catastrophic backtracking patterns that can cause exponential time complexity
// Rationale: These patterns are known to be vulnerable to ReDoS attacks because they
// contain nested quantifiers or alternation with overlap that can cause the regex engine
// to explore exponentially many backtracking paths when given malicious input.
const redosPatterns = [
/(.*\+.*)+/, // Nested quantifiers with greedy matching - classic ReDoS pattern
/(.*\*.*)+/, // Nested Kleene stars - can cause exponential backtracking
/(.+)+/, // Nested plus quantifiers - extremely vulnerable to ReDoS
/(a|a)*b/ // Alternation with overlap - causes unnecessary backtracking
];
// Analyze each line for ReDoS patterns
lines.forEach((line, index) => {
redosPatterns.forEach(pattern => {
if (pattern.test(line)) {
vulnerabilities.push({
type: 'REDOS',
severity: 'HIGH', // High severity because ReDoS can completely disable services
category: 'Denial of Service',
description: 'Potential ReDoS vulnerability - catastrophic backtracking pattern detected',
line: index + 1,
code: line.trim(),
confidence: 'medium', // Medium confidence due to potential false positives in non-user-facing regex
// Rationale: ReDoS is high severity because a single malicious request can consume
// server resources for extended periods, effectively creating a DoS condition.
// However, confidence is medium because not all complex regex patterns are
// user-facing or exploitable in practice.
mitigation: 'Use atomic groups, possessive quantifiers, or validate input length limits'
});
}
});
});
return vulnerabilities;
};
/**
* Detect Server-Side Request Forgery (SSRF) vulnerabilities
* @param {string} content - Source code content to analyze
* @returns {Array<Object>} Array of detected SSRF vulnerability objects
*
* Rationale: SSRF vulnerabilities allow attackers to make HTTP requests from the server
* to arbitrary destinations, potentially accessing internal services, cloud metadata
* endpoints, or performing port scanning. This is particularly dangerous in cloud
* environments where internal services may be accessible and contain sensitive data
* or administrative interfaces not intended for external access.
*/
const detectSSRF = (content) => {
const vulnerabilities = [];
const lines = content.split('\n');
// SSRF patterns - HTTP client calls with user-controlled URLs
// Rationale: SSRF occurs when user input controls the destination of server-side
// HTTP requests. These patterns identify common HTTP client libraries that could
// be vulnerable if their URL parameters come from user input without validation.
const ssrfPatterns = [
/fetch\s*\(\s*[^)]*req\./, // Fetch API with request object data - potential user control
/axios\.\w+\s*\(\s*[^)]*req\./, // Axios HTTP client with request data
/request\s*\(\s*[^)]*req\./, // Request library with request object
/http\.get\s*\(\s*[^)]*req\./, // Node.js HTTP module with request data
/urllib\.\w+\s*\(\s*[^)]*req\./, // Python urllib with request data
/requests\.\w+\s*\(\s*[^)]*req\./ // Python requests library with request data
];
// Analyze each line for SSRF patterns
lines.forEach((line, index) => {
ssrfPatterns.forEach(pattern => {
if (pattern.test(line)) {
vulnerabilities.push({
type: 'SSRF',
severity: 'HIGH', // High severity due to potential for internal service access
category: 'Server-Side Request Forgery',
description: 'Potential SSRF vulnerability - server making HTTP requests with user-controlled data',
line: index + 1,
code: line.trim(),
confidence: 'medium', // Medium confidence - requires manual verification of user input flow
// Rationale: SSRF is high severity because it can lead to:
// 1. Access to internal services (databases, admin panels)
// 2. Cloud metadata API access (AWS EC2 metadata, etc.)
// 3. Port scanning of internal networks
// 4. Potential for further attack chaining
mitigation: 'Validate and whitelist allowed URLs, use URL parsing libraries, block internal IP ranges'
});
}
});
});
return vulnerabilities;
};
/**
* Detect insecure deserialization vulnerabilities
* @param {string} content - Source code content to analyze
* @returns {Array<Object>} Array of detected insecure deserialization vulnerability objects
*
* Rationale: Insecure deserialization is a critical vulnerability that can lead to remote
* code execution when untrusted data is deserialized without proper validation. This is
* particularly dangerous because serialization formats often preserve object structure
* and can include executable code or references to dangerous classes. The vulnerability
* is especially prevalent in web applications that accept serialized data from users.
*/
const detectInsecureDeserialization = (content) => {
const vulnerabilities = [];
const lines = content.split('\n');
// Insecure deserialization patterns - dangerous deserialization functions with user input
// Rationale: These patterns identify deserialization operations that could be exploited
// if they process untrusted user input. Each pattern represents a different serialization
// format that has known security issues when deserializing untrusted data.
const deserializationPatterns = [
/JSON\.parse\s*\(\s*[^)]*req\./, // JSON parsing with request data - prototype pollution risk
/pickle\.loads?\s*\(/, // Python pickle - arbitrary code execution via malicious objects
/yaml\.load\s*\(/, // YAML loading - code execution via YAML deserialization
/unserialize\s*\(/, // PHP unserialize - object injection and code execution
/readObject\s*\(/, // Java object deserialization - gadget chain exploitation
/JSON\.parse\s*\(\s*[^)]*\.cookie/, // Cookie deserialization - common attack vector
/eval\s*\(\s*[^)]*JSON\.stringify/ // Code evaluation of serialized data
];
// Analyze each line for insecure deserialization patterns
lines.forEach((line, index) => {
deserializationPatterns.forEach(pattern => {
if (pattern.test(line)) {
vulnerabilities.push({
type: 'INSECURE_DESERIALIZATION',
severity: 'CRITICAL', // Critical severity due to potential for remote code execution
category: 'Deserialization',
description: 'Potential insecure deserialization vulnerability - untrusted data deserialization',
line: index + 1,
code: line.trim(),
confidence: 'high', // High confidence because deserialization of user input is almost always dangerous
// Rationale: Insecure deserialization is critical severity because:
// 1. Can lead to arbitrary code execution on the server
// 2. Often bypasses authentication and authorization controls
// 3. Can result in complete system compromise
// 4. Difficult to detect and prevent with traditional security controls
// High confidence because any deserialization of user-controlled data is inherently risky
mitigation: 'Use safe serialization formats (JSON), validate data schemas, implement integrity checks'
});
}
});
});
return vulnerabilities;
};
/**
* Detect JWT vulnerabilities
* @param {string} content - Source code content to analyze
* @returns {Array<Object>} Array of detected JWT vulnerability objects
*
* Rationale: JWT (JSON Web Token) is widely used for authentication and information exchange.
* However, misconfigurations and insecure usage can lead to critical security flaws like
* authentication bypass, token forgery, and information leakage. This function aims to identify
* common JWT-related vulnerabilities in code.
*/
function detectJWTVulnerabilities(content) {
const vulnerabilities = [];
const lines = content.split('\n');
lines.forEach((line, index) => {
// Check for 'none' algorithm: Using the 'none' algorithm in JWT allows for unsigned tokens,
// enabling attackers to forge valid tokens without a signature. This is a critical flaw.
if (/algorithm\s*:\s*['"]none['"]/.test(line) ||
/algorithms\s*:\s*\[[^\]]*['"]none['"]/.test(line)) {
vulnerabilities.push({
type: 'JWT_NONE_ALGORITHM',
severity: 'CRITICAL', // Critical severity because it allows for complete token forgery
category: 'Authentication',
description: 'JWT accepts "none" algorithm - allows token forgery',
line: index + 1,
code: line.trim(),
confidence: 'high', // High confidence as this is a direct misconfiguration
// Rationale: The 'none' algorithm bypasses signature verification entirely, making any
// token with this header valid. This is a severe security risk.
mitigation: 'Do not allow the "none" algorithm. Ensure a strong signing algorithm (e.g., HS256, RS256) is enforced.'
});
}
// Check for hardcoded secrets: Hardcoding JWT secrets makes them vulnerable to exposure.
// If an attacker gains access to the codebase, they can compromise all JWTs signed with that secret.
if (/jwt\.(sign|verify)\s*\([^,]+,\s*['"][^'"]{1,32}['"]/.test(line)) {
vulnerabilities.push({
type: 'JWT_WEAK_SECRET',
severity: 'HIGH', // High severity due to potential compromise of all JWTs
category: 'Cryptography',
description: 'JWT secret appears to be hardcoded or weak',
line: index + 1,
code: line.trim(),
confidence: 'medium', // Medium confidence as the pattern might match non-secret strings
// Rationale: Hardcoded secrets are a common mistake. Weak secrets (short, guessable) are also problematic.
// Exposure of the secret allows an attacker to forge tokens or impersonate users.
mitigation: 'Store secrets securely (e.g., environment variables, secret management systems). Use strong, randomly generated secrets.'
});
}
// Check for missing verification: Decoding a JWT without verifying its signature means
// an attacker can manipulate the token's payload, potentially altering user roles or permissions.
if (/jwt\.decode\s*\(/.test(line) && !/verify/.test(line) && !/validationOptions/.test(line)) {
vulnerabilities.push({
type: 'JWT_NO_VERIFICATION',
severity: 'HIGH', // High severity due to potential for authentication bypass
category: 'Authentication',
description: 'JWT decoded without verification',
line: index + 1,
code: line.trim(),
confidence: 'high', // High confidence as this is a critical security step omission
// Rationale: JWT verification is crucial for ensuring the token's integrity and authenticity.
// Skipping it allows attackers to tamper with token data.
mitigation: 'Always verify JWT signatures using a trusted secret or public key. Use libraries that enforce verification by default.'
});
}
// Check for algorithm confusion: Allowing both symmetric (HS256) and asymmetric (RS256) algorithms
// in the same JWT configuration can lead to an "algorithm confusion" attack. An attacker can
// change the algorithm header to HS256 and sign the token with the public key, which the server
// might incorrectly treat as the secret key.
if (/algorithms\s*:\s*\[[^\]]*['"]HS256['"][^\]]*['"]RS256['"]/.test(line) ||
/algorithms\s*:\s*\[[^\]]*['"]RS256['"][^\]]*['"]HS256['"]/.test(line)) {
vulnerabilities.push({
type: 'JWT_ALGORITHM_CONFUSION',
severity: 'HIGH', // High severity due to potential for authentication bypass
category: 'Authentication',
description: 'JWT allows both HMAC and RSA algorithms - potential algorithm confusion attack',
line: index + 1,
code: line.trim(),
confidence: 'high', // High confidence as this configuration is inherently risky
// Rationale: Supporting multiple, fundamentally different algorithms (symmetric vs. asymmetric)
// opens the door for attackers to trick the server into using the wrong key for verification.
mitigation: 'Restrict JWTs to a single, secure algorithm. If multiple are needed, ensure strict validation and separation.'
});
}
});
return vulnerabilities;
}
/**
* Main function to detect all modern vulnerabilities
* @param {string} content - File content
* @returns {Array} All detected vulnerabilities
*/
function detectModernVulnerabilities(content) {
return [
...detectReDoS(content),
...detectSSRF(content),
...detectInsecureDeserialization(content),
...detectJWTVulnerabilities(content)
];
}
module.exports = {
detectModernVulnerabilities,
detectReDoS,
detectSSRF,
detectInsecureDeserialization,
detectJWTVulnerabilities
};