Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')
Description
Static Code Injection occurs when software receives input from an upstream component, stores it in a location that will later be parsed and executed as code, and does not neutralize or incorrectly neutralizes code directives. Unlike eval injection which executes code immediately, static code injection involves writing malicious code to files, databases, or other persistent storage that will be executed later when the stored content is parsed, included, or rendered. Common targets include configuration files, template files, log files that may be included, serialized data files, and any file that is later interpreted by application code.
Risk
Static code injection creates persistent backdoors that execute whenever the infected file is processed. Attackers can inject malicious code into PHP files that execute on every page load, add malicious templates that execute during rendering, poison configuration files to alter application behavior, or inject code into log files that administrators might view or process. The delayed execution makes detection difficult - the injection may occur at one time while the malicious code executes later, potentially under different user contexts or with elevated privileges. This vulnerability is particularly dangerous in CMS systems, template engines, and applications that dynamically generate or modify code files.
Solution
Never write user-controlled input to files that will be interpreted as code. Implement strict output encoding appropriate to the file format before writing any external data. Use allowlist validation to ensure input conforms to expected, safe patterns. Separate code from data by storing user content in databases rather than files that may be executed. If configuration files must be modified, use structured data formats (JSON, YAML) with proper serialization instead of executable code. Set restrictive file permissions to prevent unauthorized modification. Implement file integrity monitoring to detect unauthorized changes to code files.
Common Consequences
| Impact | Details |
|---|---|
| Confidentiality | Scope: Confidentiality Injected code can access all data available when the infected file is executed, potentially with elevated privileges if executed by administrators. |
| Integrity | Scope: Integrity Persistent code injection enables long-term manipulation of application behavior, data modification, and ongoing unauthorized access. |
| Availability | Scope: Availability Malicious code in critical files can crash applications, corrupt data, or render systems unusable. |
| Access Control | Scope: Persistent Compromise Static code injection creates backdoors that survive application restarts and may persist through updates. |
Example Code + Solution Code
Vulnerable Code
<?php
// VULNERABLE: Writing user input to an included PHP file
// Configuration update functionality
$setting_name = $_POST['setting'];
$setting_value = $_POST['value'];
// Attack: value="; system($_GET['cmd']); $x="
// Results in: $settings['name'] = ""; system($_GET['cmd']); $x="";
$config = fopen('config.php', 'a');
fwrite($config, "\$settings['$setting_name'] = \"$setting_value\";\n");
fclose($config);
// This config file is later included:
// include 'config.php'; // Executes injected code!
// VULNERABLE: Template file injection
$template_name = $_GET['template'];
$template_content = $_POST['content'];
file_put_contents("templates/$template_name.tpl", $template_content);
// Malicious template executed when rendered
Fixed Code
<?php
// SAFE: Use JSON for configuration storage
function updateConfig($setting_name, $setting_value) {
// Validate setting name against allowlist
$allowed_settings = ['theme', 'language', 'timezone'];
if (!in_array($setting_name, $allowed_settings)) {
throw new InvalidArgumentException("Unknown setting");
}
// Load existing config from JSON
$config_file = 'config.json';
$config = json_decode(file_get_contents($config_file), true) ?: [];
// Validate value format based on setting type
switch ($setting_name) {
case 'theme':
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $setting_value)) {
throw new InvalidArgumentException("Invalid theme name");
}
break;
case 'language':
if (!preg_match('/^[a-z]{2}(_[A-Z]{2})?$/', $setting_value)) {
throw new InvalidArgumentException("Invalid language code");
}
break;
// ... other validations
}
// Update and save as JSON (no code execution possible)
$config[$setting_name] = $setting_value;
file_put_contents(
$config_file,
json_encode($config, JSON_PRETTY_PRINT),
LOCK_EX
);
}
// SAFE: Template content with strict sanitization
function saveTemplate($template_name, $content) {
// Validate template name
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $template_name)) {
throw new InvalidArgumentException("Invalid template name");
}
// Strip any PHP tags and dangerous content
$content = preg_replace('/<\?.*?\?>/s', '', $content);
$content = strip_tags($content, '<p><br><div><span><a><img>');
// Store in database instead of file system
$db->prepare("INSERT INTO templates (name, content) VALUES (?, ?)")
->execute([$template_name, $content]);
}
Exploited in the Wild
WordPress Plugin Vulnerabilities (WordPress, Ongoing)
Multiple WordPress plugins have been exploited through static code injection, where attackers write malicious PHP code to theme or plugin files, creating persistent backdoors that survive plugin updates.
Web Shell Installation Campaigns (Various CMS, Ongoing)
Attackers exploit file upload and code injection vulnerabilities to write PHP web shells to servers, providing persistent remote access to compromised systems.
Tools to test/exploit
-
Burp Suite — web security testing platform for identifying static code injection vulnerabilities.
-
Web Shell Detection Tools — tools for detecting injected web shells in file systems.
CVE Examples
-
CVE-2023-48795 — SSH protocol configuration injection affecting connection security.
-
CVE-2022-26134 — Atlassian Confluence OGNL injection resulting in code written to server.
References
-
MITRE. "CWE-96: Improper Neutralization of Directives in Statically Saved Code." https://cwe.mitre.org/data/definitions/96.html
-
OWASP. "Code Injection." https://owasp.org/www-community/attacks/Code_Injection