HIGH CWE-74 Injection

CWE-74 in APIs

CWE ID
CWE-74
Category
Input Validation
Severity
CRITICAL
Short Name
Injection

What is Cwe 74?

CWE-74: Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') is a critical weakness where an application includes untrusted data in commands, queries, or other instructions that are interpreted by downstream components. This occurs when special characters that have syntactic meaning to the downstream interpreter are not properly neutralized, allowing attackers to alter the intended command structure.

The weakness manifests when applications construct commands or queries using string concatenation or interpolation with user-controlled data. Without proper validation or escaping, attackers can inject malicious payloads that change the semantics of the original command. This can affect SQL queries, operating system commands, NoSQL queries, LDAP filters, XPath expressions, and other interpreted languages.

The severity stems from the fact that successful injection attacks can lead to data breaches, unauthorized access, denial of service, or complete system compromise. Attackers exploit this weakness by crafting input that includes special characters (like quotes, semicolons, or operators) to manipulate how the downstream component interprets the command.

Cwe 74 in API Contexts

In API environments, CWE-74 appears in several critical contexts. SQL injection remains one of the most common manifestations, where API endpoints accept user input that gets concatenated into database queries. For example, a login endpoint might construct a query like SELECT * FROM users WHERE username='${username}' AND password='${password}', allowing attackers to inject SQL syntax through the username or password fields.

NoSQL injection affects APIs using document databases like MongoDB. An endpoint that constructs queries without proper validation can be exploited using operators like $where, $regex, or $ne. For instance, a search API might be vulnerable if it directly uses query parameters in database operations.

Command injection occurs when APIs execute operating system commands with user-supplied data. A file upload API that uses user-provided filenames in system commands, or an email service that incorporates user input into shell commands, can be exploited to execute arbitrary code on the server.

Object injection and deserialization vulnerabilities arise when APIs accept serialized objects or JSON data that gets deserialized without validation. Attackers can craft malicious objects that trigger arbitrary code execution during deserialization.

API-specific injection attacks include GraphQL injection, where malicious queries can access unintended data or cause denial of service through expensive operations, and template injection in APIs that render user input in server-side templates.

Detection

Detecting CWE-74 requires both static analysis and dynamic testing. Static analysis tools can identify code patterns that construct commands or queries using string concatenation with user input. Look for patterns like string concatenation with variables, use of eval(), exec(), or similar functions, and direct interpolation of user data into command strings.

Dynamic testing involves actively probing API endpoints with malicious payloads. Common injection payloads include single quotes to test SQL injection, semicolons and operators for command injection, and special characters for template injection. Tools like SQLMap, Burp Suite, and OWASP ZAP can automate this process, but manual testing is often needed to identify context-specific vulnerabilities.

middleBrick scans APIs for CWE-74 vulnerabilities through its black-box scanning approach. The scanner tests endpoints with injection payloads across multiple categories, including SQL injection attempts, command injection strings, and NoSQL injection patterns. For each endpoint, middleBrick attempts to identify whether special characters in user input are properly neutralized before being passed to downstream components.

The scanner evaluates authentication mechanisms to ensure that injection vulnerabilities aren't masked by authentication requirements. It also tests rate limiting to prevent abuse during scanning. middleBrick's parallel scanning approach tests multiple injection vectors simultaneously, providing comprehensive coverage of potential injection points in your API.

For OpenAPI spec analysis, middleBrick cross-references documented parameter types and constraints with actual runtime behavior, identifying discrepancies that might indicate injection vulnerabilities. The scanner provides specific findings with severity levels, showing exactly which endpoints and parameters are vulnerable to injection attacks.

Remediation

Proper remediation of CWE-74 requires a defense-in-depth approach. The most effective strategy is using parameterized queries or prepared statements instead of string concatenation. For SQL databases, use parameterized queries with placeholders that separate data from code. For example, instead of SELECT * FROM users WHERE username='${username}', use SELECT * FROM users WHERE username=? with bound parameters.

// Vulnerable - SQL Injection possible
const query = `SELECT * FROM users WHERE id = ${req.params.id}`;
const result = await db.query(query);

// Secure - Parameterized query
const query = 'SELECT * FROM users WHERE id = ?';
const result = await db.query(query, [req.params.id]);

For NoSQL databases like MongoDB, use parameterized queries and avoid constructing queries from user input. Use projection operators and limit the fields that can be queried. Validate and sanitize all input before using it in database operations.

// Vulnerable - NoSQL Injection possible
const query = { $where: `this.id == ${req.params.id}` };
const result = await collection.find(query);

// Secure - Use safe query operators
const query = { id: parseInt(req.params.id) };
const result = await collection.find(query);

Command injection can be prevented by avoiding shell command execution entirely, or if necessary, using safe APIs that don't invoke shells. Never use user input directly in command arguments. Validate and sanitize file paths, and use absolute paths instead of relative ones.

# Vulnerable - Command Injection possible
import subprocess
filename = request.args.get('file')
subprocess.run(['ls', filename])

# Secure - Use safe APIs or validate input
import os
filename = request.args.get('file')
if not os.path.basename(filename) == filename:  # Prevent path traversal
    raise ValueError('Invalid filename')
for file in os.listdir('.'):
    if file == filename:
        print(file)

Input validation is critical. Implement allowlists for acceptable characters and patterns, enforce length limits, and validate data types. Use context-aware escaping when output cannot be parameterized. For web contexts, use appropriate escaping functions for HTML, JavaScript, CSS, and URL contexts.

Implement the principle of least privilege. Database connections should use accounts with minimal necessary permissions. Application code should run with the least privileges required to function. This limits the potential impact if injection attacks succeed.

Regular security testing is essential. Use automated tools to scan for injection vulnerabilities, conduct manual penetration testing, and monitor for suspicious patterns in application logs. middleBrick's continuous monitoring can alert you when new injection vulnerabilities are introduced in your API endpoints.

Frequently Asked Questions

How can I tell if my API is vulnerable to CWE-74?
Look for code that constructs commands or queries using string concatenation with user input, uses eval() or similar functions with user data, or directly interpolates request parameters into database queries. Test your endpoints with single quotes, SQL keywords, and special characters. Tools like middleBrick can automatically scan your API for injection vulnerabilities and provide specific findings with severity levels.
What's the difference between CWE-74 and other injection types?
CWE-74 is the parent category for all injection weaknesses, while specific types like CWE-89 (SQL Injection) or CWE-94 (Code Injection) are more specific manifestations. CWE-74 covers any situation where untrusted data is included in commands interpreted by downstream components, regardless of the specific technology or context.