CWE-94 in APIs
- CWE ID
- CWE-94
- Category
- Input Validation
- Severity
- CRITICAL
- Short Name
- Code Injection
What is CWE-94?
CWE-94 refers to Improper Control of Generation of Code ('Code Injection'). This weakness occurs when an application constructs code using externally-influenced input without properly validating or sanitizing that input. Attackers can inject malicious code that gets executed by the application, leading to complete compromise of the system.
The weakness manifests when applications dynamically generate code (typically using eval(), exec(), or similar functions) and incorporate untrusted data directly into that code. Since the injected code executes with the same privileges as the application, attackers can achieve arbitrary code execution, data theft, or system compromise.
CWE-94 in API Contexts
In API environments, CWE-94 appears in several specific patterns:
- Dynamic query generation - APIs that construct database queries by concatenating user input without parameterization
- Template injection - APIs that process user-provided templates or allow template expression evaluation
- Expression evaluation - APIs that evaluate mathematical or logical expressions provided by clients
- Code generation endpoints - APIs that generate code (JavaScript, SQL, etc.) based on user input
- Configuration injection - APIs that process configuration files or settings containing executable code
A common example in REST APIs is an endpoint that accepts filter parameters and constructs SQL queries by directly embedding those parameters. If an attacker provides input like name='; DROP TABLE users; --, the resulting query becomes:
SELECT * FROM users WHERE name=''; DROP TABLE users; --'
This demonstrates how untrusted input in code generation can lead to severe security breaches.
Detection
Detecting CWE-94 requires both static analysis and dynamic testing approaches. Here's how to identify this weakness:
- Code review - Look for dangerous functions like eval(), exec(), system(), Runtime.exec(), and similar code execution primitives
- Input validation analysis - Check if user input is properly sanitized before being incorporated into code
- Dynamic scanning - Use tools like middleBrick to automatically test API endpoints for code injection vulnerabilities
middleBrick specifically scans for CWE-94 by:
- Testing input validation across all API parameters
- Attempting controlled code injection attacks to verify if they succeed
- Analyzing the API's response patterns to detect potential code execution
- Checking for unsafe consumption patterns where APIs process untrusted code
middleBrick's black-box scanning approach tests the unauthenticated attack surface, attempting to inject code through various API parameters and observing the responses. The scanner can detect if an API is vulnerable to code injection without requiring access to the source code or internal systems.
Remediation
Fixing CWE-94 requires eliminating unsafe code generation patterns. Here are the primary remediation strategies:
1. Use Parameterized Queries
Instead of concatenating user input into SQL queries, use prepared statements with parameter binding:
// Vulnerable - code injection possible
String query = "SELECT * FROM users WHERE name='" + name + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
// Secure - parameterized query
String query = "SELECT * FROM users WHERE name = ?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, name);
ResultSet rs = pstmt.executeQuery();2. Input Validation and Sanitization
Validate and sanitize all user input before using it in code generation:
import re
def sanitize_input(user_input):
# Remove potentially dangerous characters
sanitized = re.sub(r'[\';"`]', '', user_input)
# Validate against expected format
if not re.match(r'^[a-zA-Z0-9_]+$', sanitized):
raise ValueError('Invalid input format')
return sanitized
# Use sanitized input in safe context
clean_input = sanitize_input(request.args.get('filter'))
result = safe_operation(clean_input)3. Avoid Dangerous Functions
Eliminate the use of eval(), exec(), and similar functions. Replace them with safer alternatives:
// Vulnerable - eval allows code injection
const userInput = req.query.expression;
eval(userInput);
// Secure - use safe evaluation libraries
const mathjs = require('mathjs');
const result = mathjs.evaluate(userInput); // Limited to math operations only4. Implement Content Security Policy
For web APIs that serve content, implement CSP headers to prevent script injection:
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'");
next();
});5. Use middleBrick for Verification
After implementing fixes, use middleBrick to verify the vulnerabilities are resolved. The scanner can test your API endpoints to ensure code injection attacks no longer succeed. middleBrick provides specific findings about CWE-94 vulnerabilities, including the exact parameters that were tested and the severity of any remaining issues.