01Summary

Code injection occurs when an application constructs executable code using untrusted input without proper validation or sanitization. An attacker can inject malicious code that gets executed by the application, leading to unauthorized actions, data theft, or system compromise. This is one of the most dangerous vulnerability classes because it grants the attacker the ability to run arbitrary code within the application's context.

02How It Happens

Code injection happens when user-supplied data is directly incorporated into code that is then evaluated or executed by an interpreter. This commonly occurs when developers use functions like eval(), exec(), dynamic SQL construction, template engines without sandboxing, or any mechanism that treats user input as code rather than data. The vulnerability exists because the application fails to distinguish between code structure and user-provided values, allowing an attacker to break out of the intended code context and inject new instructions.

The root cause is typically a combination of two factors: (1) accepting external input, and (2) passing that input to an execution context without neutralizing special characters or syntax elements that have meaning in that context. Even seemingly "safe" input validation can fail if it only blocks obvious attack patterns rather than using a whitelist or parameterized approach.

03Real-World Impact

Successful code injection can result in complete application compromise. An attacker can read or modify sensitive data, create unauthorized user accounts, execute system commands, install malware, or pivot to other systems on the network. The impact depends on the privileges of the application process and what code is injected, but in most cases it is severe. Unlike some vulnerabilities that require chaining or specific conditions, code injection often provides direct, immediate access to the application's full capabilities.

04Vulnerable & Fixed Patterns

Vulnerable pattern
user_input = request.args.get('formula')
result = eval(user_input)
return str(result)

Why it's vulnerable:
The eval() function executes the user input as Python code. An attacker can inject code like __import__('os').system('rm -rf /') or access sensitive variables in the application's namespace.

Fixed pattern
import ast
import operator

user_input = request.args.get('formula')
# Use a safe expression evaluator instead of eval()
allowed_names = {'abs': abs, 'round': round}
allowed_ops = {ast.Add: operator.add, ast.Sub: operator.sub}
result = safe_eval(user_input, allowed_names, allowed_ops)
return str(result)
Vulnerable pattern
<?php
$action = $_GET['action'];
$code = "if (\$user_role == 'admin') { " . $action . " }";
eval($code);
?>

Why it's vulnerable:
The eval() function executes the concatenated string as PHP code. An attacker can inject arbitrary PHP by controlling the action parameter, such as phpinfo(); or database queries.

Fixed pattern
<?php
$action = $_GET['action'];
$allowed_actions = ['delete_user', 'reset_password', 'send_email'];

if (in_array($action, $allowed_actions, true)) {
    call_user_func('handle_' . $action);
} else {
    die('Invalid action');
}
?>

05Prevention Checklist

Never use eval(), exec(), or equivalent dynamic code execution functions
on user input. If you must execute code dynamically, use a whitelist of allowed functions or a sandboxed, restricted interpreter.
Use parameterized queries and prepared statements
for database operations instead of string concatenation.
Validate input against a strict whitelist
of allowed values (e.g., enum-like checks) rather than trying to blacklist dangerous patterns.
Use templating engines with auto-escaping enabled
and avoid passing raw user input to template evaluation functions.
Apply the principle of least privilege
— run the application with minimal permissions so that even if injection occurs, the damage is limited.
Implement code review processes
that specifically flag any use of dynamic code execution functions and require justification and security review.

06Signs You May Already Be Affected

Look for unexpected files or scripts in your application directories, unusual entries in application logs showing strange code patterns or function calls, or unexpected changes to database records. If you notice processes spawning unusual child processes or system commands being executed from your web server, code injection may have occurred. Review access logs for requests containing suspicious syntax like parentheses, quotes, or function names in parameter values.

07Related Recent Vulnerabilities