Programming Search⌘K

Weaknesscore

Code injection

Also called eval injection, dynamic code evaluation, server-side template injection, SSTI, cwe-94.

Code injection happens when a program builds code from outside input and then runs it, so the input can change what the code does.

Abstraction
base
OWASP Top 10 (2025)
A05
CWE Top 25 (2025)
rank 10
Languages affected
python, javascript, php, ruby, perl, powershell, bash, any-with-eval

Description

Some languages can run code that the program makes at run time. Python has eval and exec. JavaScript has eval and the Function constructor. PHP, Ruby and Perl have eval, and shells and PowerShell have their own forms. These functions take text and run it with all the rights of the program. Code injection happens when part of that text comes from outside input. The program meant the input to be a value, such as a number in a formula. The interpreter reads it as code.1

The root cause is the same as in SQL injection and OS command injection: code and data share one string. The difference is the interpreter. Here it is the language of the program itself, so the input can do anything that the program can do. It can read and change data, read files, start processes and make network requests.1

CWE-94 names this weakness. It is a base weakness. Its children include CWE-95, eval injection, and CWE-1336, improper neutralization of special elements used in a template engine.1 It is rank 10 of the 2025 CWE Top 25, up from rank 11 in 2024. The list counts 7 CVEs of this weakness in the Known Exploited Vulnerabilities catalog of CISA.3 In the OWASP Top 10:2025, it is part of A05:2025 Injection.2 Code injection through a deserializer is a separate weakness, Deserialization of untrusted data.

History

CWE-94 was one of the first CWE entries. It came from PLOVER, an earlier list of vulnerability types, in CWE Draft 3 in July 2006, with the name Code Injection.1 CWE renamed it four times. The fourth name, from October 2026, is Improper Control of Generation of Code.1

Why a restricted eval is not a sandbox

A common idea is to call eval with an empty set of names, so that the input cannot reach dangerous functions. The Python documentation says that overriding __builtins__ is not a security mechanism, because the code can still access all builtins.4 The Node.js documentation says that the node:vm module is not a security mechanism, and that it must not run untrusted code.7 MDN says that eval runs code with the privileges of the caller. A direct call to eval can also read and change the local variables of the caller.6 A language runtime is too large to make safe by removing names. Do not try to filter the input either. A denylist of words such as import misses other spellings of the same code.

Server-side template injection

A template engine is a small interpreter. It reads template text, and it runs the expressions inside it. When users can write the template text itself, they can write expressions too. This is server-side template injection, CWE-1336.1 James Kettle described it in 2015.8 His classic demonstration input is {{7*7}}: an engine that evaluates the expression shows 49 where the user expected the text.8 Engines that can call methods or reach the classes of the language can give the user the rights of the program.8

Template engines with fewer features still leak data. In Python, a format string can read any attribute of its arguments with .name, and any item with [index].9 Go templates can read the fields of the data and call its methods. The Go documentation says that the package assumes that template authors are trusted and the data is not.10 The Python and Go example files show both cases. The fix is the same in each engine. The template text comes from the program, and the user input is only data that the template prints.

Vulnerable code

The function below is a calculator. It passes the formula that the user typed to eval. The classic demonstration input is a call to __import__, which shows that the input can load any module. Here it only asks the module platform for the name of the interpreter.

This code runs but gives a wrong answer on purpose.

def calculate(expression):
    # The feature: a calculator for the formulas that users type.
    return eval(expression)


print(calculate("6 * 7"))
print(calculate("__import__('platform').python_implementation()"))
Output
42
CPython

The second call ran a function that the calculator never offered. The same input could call any function of any module, such as one that starts a process or deletes a file.

Fixed code

The fix is to stop running input as code. The program parses the input with a grammar that has only the features it needs, and it evaluates the result itself.1 The code below parses the formula with ast.parse and walks the tree. It accepts numbers and four operators, and it refuses every other kind of node.

import ast
import operator

OPERATORS = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.USub: operator.neg,
}


def evaluate(node):
    if isinstance(node, ast.Constant) and type(node.value) in (int, float):
        return node.value
    if isinstance(node, ast.BinOp) and type(node.op) in OPERATORS:
        return OPERATORS[type(node.op)](evaluate(node.left), evaluate(node.right))
    if isinstance(node, ast.UnaryOp) and type(node.op) in OPERATORS:
        return OPERATORS[type(node.op)](evaluate(node.operand))
    raise ValueError(f"not allowed: {type(getattr(node, 'op', node)).__name__}")


def calculate(expression):
    if len(expression) > 100:
        raise ValueError("expression too long")
    tree = ast.parse(expression, mode="eval")
    return evaluate(tree.body)


for text in ["6 * 7", "(1 + 2) / 4", "__import__('platform').python_implementation()", "2 ** 10"]:
    try:
        print(text, "=", calculate(text))
    except (ValueError, SyntaxError, ZeroDivisionError) as error:
        print(text, "->", error)
Output
6 * 7 = 42
(1 + 2) / 4 = 0.75
__import__('platform').python_implementation() -> not allowed: Call
2 ** 10 -> not allowed: Pow

The tree of the demonstration input has a Call node, and the walk refuses it. The power operator is also refused, because a short input such as 9 ** 9 ** 9 takes a very long time. The length limit protects the parser: the documentation of ast.parse warns that a large or complex string can crash the interpreter.5

Allow-list the operations

The tree walk is an allow-list. It names the node types and operators that are valid, and everything else fails. This is the opposite of a filter that looks for dangerous words. When the calculator needs a function such as sqrt, add it to the allow-list by name.

Prefer data formats and lookups

Many uses of eval do not need code at all. A program that reads a list or a dictionary from text can use json.loads. The Python documentation does not recommend ast.literal_eval for untrusted data, because a small input can exhaust memory or the C stack.5 A program that chooses a function from a name in the input can use a dictionary from names to functions. A program that reads a field by a name in the input can check the name against a fixed set.

How to detect it

  • Static analysis with taint tracking. CodeQL follows input to calls that run code. Its queries include py/code-injection, js/code-injection and cs/code-injection, and for Java the queries for SpEL, OGNL and other expression languages. The queries py/template-injection and java/server-side-template-injection find template text from input.11
  • Pattern linters. Ruff rule S307 flags eval, and S102 flags exec.12 ESLint rules no-eval, no-implied-eval and no-new-func flag eval, strings passed to setTimeout and setInterval, and the Function constructor.13 Treat every hit as a finding until a reviewer shows that the text is a constant.
  • Code review. Search for eval, exec, compile, Function(, Invoke-Expression, and for template engines that receive text from a request or the database.
  • Tests. Send {{7*7}} to inputs that end up in a template, and look for 49 in the output.8 Send a formula with a function call to inputs that reach a calculator. The feature must refuse it.

How to prevent it

  • Do not run input as code. Refactor the feature so that it does not generate code. CWE lists this first.1
  • Parse a small grammar. When users must write formulas or filters, parse them with a grammar that has only the needed operations. Evaluate the tree in the program.
  • Use data formats for data. Use JSON and the parser of the format, not eval.
  • Keep template text in the program. Pass user input to the template as data. When users must write templates, use a logic-less engine, or one with a sandbox that the vendor supports and patches.
  • Do not trust restricted builtins or vm contexts. Their documentation says that they are not security mechanisms.47
  • Run with least privilege. Run the process with few rights, in a sandbox or a container, so that injected code can do less.1
  • Watch for language models. Code that a language model writes from a prompt is outside input too. Do not pass it to eval or exec without a sandbox.18

Real cases

Case Date What happened
CVE-2003-0395 published 2003-06-10 Ultimate PHP Board 1.9 ran PHP code from the User-Agent header of a request. The code ran with administrator rights when the administrator opened admin_iplog.php.14
CVE-2008-5305 published 2008-12-10 Eval injection in TWiki before 4.2.4 let remote attackers run Perl code through the %SEARCH{}% variable.15
CVE-2020-8218 published 2020-07-30 Code injection in Pulse Connect Secure before 9.1R8 let an attacker run code through a crafted URI to the admin web interface.16
CVE-2022-26134 published 2022-06-03 OGNL injection in Confluence Server and Data Center let an attacker with no login run code.17
CVE-2023-29374 published 2023-04-05 In LangChain through 0.0.131, the LLMMathChain chain passed text from a prompt to the Python exec method. Prompt injection could run any code.18
PythonGitHub

This code runs but gives a wrong answer on purpose.

def calculate(expression):
    # The feature: a calculator for the formulas that users type.
    return eval(expression)


print(calculate("6 * 7"))
print(calculate("__import__('platform').python_implementation()"))
Output
42
CPython

The second call loads the module platform and calls one of its functions. The calculator never offered either.

import ast
import operator

OPERATORS = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.USub: operator.neg,
}


def evaluate(node):
    if isinstance(node, ast.Constant) and type(node.value) in (int, float):
        return node.value
    if isinstance(node, ast.BinOp) and type(node.op) in OPERATORS:
        return OPERATORS[type(node.op)](evaluate(node.left), evaluate(node.right))
    if isinstance(node, ast.UnaryOp) and type(node.op) in OPERATORS:
        return OPERATORS[type(node.op)](evaluate(node.operand))
    raise ValueError(f"not allowed: {type(getattr(node, 'op', node)).__name__}")


def calculate(expression):
    if len(expression) > 100:
        raise ValueError("expression too long")
    tree = ast.parse(expression, mode="eval")
    return evaluate(tree.body)


for text in ["6 * 7", "(1 + 2) / 4", "__import__('platform').python_implementation()", "2 ** 10"]:
    try:
        print(text, "=", calculate(text))
    except (ValueError, SyntaxError, ZeroDivisionError) as error:
        print(text, "->", error)
Output
6 * 7 = 42
(1 + 2) / 4 = 0.75
__import__('platform').python_implementation() -> not allowed: Call
2 ** 10 -> not allowed: Pow

The walk accepts only the node types in the allow-list. A call, an attribute, a name or a power fails before any evaluation.

This code runs but gives a wrong answer on purpose.

class User:
    def __init__(self, name, password_hash):
        self.name = name
        self.password_hash = password_hash


user = User("alice", "placeholder-hash-not-real")


def greeting(template):
    # The feature: each user writes the text of a greeting.
    return template.format(user=user)


print(greeting("Hello, {user.name}!"))
print(greeting("Hello, {user.password_hash}!"))
Output
Hello, alice!
Hello, placeholder-hash-not-real!

str.format reads attributes with .name and items with [index]. A user who writes the format string can read any attribute of the objects that the program passes in.

import string


class User:
    def __init__(self, name, password_hash):
        self.name = name
        self.password_hash = password_hash


user = User("alice", "placeholder-hash-not-real")


def greeting(template):
    # Only the values in this dictionary can appear in the text.
    values = {"name": user.name}
    return string.Template(template).safe_substitute(values)


print(greeting("Hello, $name!"))
print(greeting("Hello, $password_hash!"))
print(greeting("Hello, {user.password_hash}!"))
Output
Hello, alice!
Hello, $password_hash!
Hello, {user.password_hash}!

string.Template replaces $name with a value from the dictionary and has no attribute access. A placeholder with no value stays in the text, and braces are plain text.

  • Verdict: stdlib. Python has no safe form of eval. The ast module parses an expression into a tree that the program can check and evaluate itself.
  • The documentation of eval says that overriding __builtins__ is not a security mechanism. Do not pass input to eval or exec with a reduced set of globals and call it safe.
  • ast.literal_eval accepts only literals, but the documentation does not recommend it for untrusted data, because a small input can exhaust memory or the C stack. Use json.loads for data.
  • compile, exec, eval, pickle.loads and importlib.import_module with a module name from input all run code. The last two belong to Deserialization of untrusted data and to unsafe reflection.
  • Template engines from PyPI, such as Jinja2, can run more than str.format can. Keep their template text in the program, and pass input as context values.
  • Ruff rules S307 (eval) and S102 (exec) come from flake8-bandit. CodeQL has py/code-injection and py/template-injection.
JavaScriptGitHub

This code runs but gives a wrong answer on purpose.

function calculate(expression) {
  // The feature: a calculator for the formulas that users type.
  return eval(expression);
}

console.log(calculate("6 * 7"));
console.log(calculate("process.release.name"));
Output
42
node

The second call reads the global process object, which a calculator never offered. The same input could reach the file system or start a process.

// A parser for numbers, + - * / and parentheses. Anything else is an error.
function calculate(text) {
  if (text.length > 100) throw new Error("expression too long");
  const tokens = text.match(/\d+(?:\.\d+)?|[-+*/()]|\S/g) ?? [];
  let pos = 0;

  function primary() {
    const token = tokens[pos++];
    if (token === "(") {
      const value = sum();
      if (tokens[pos++] !== ")") throw new Error("missing )");
      return value;
    }
    if (token === "-") return -primary();
    if (/^\d/.test(token ?? "")) return Number(token);
    throw new Error(`unexpected ${JSON.stringify(token ?? "end")}`);
  }

  function product() {
    let value = primary();
    while (tokens[pos] === "*" || tokens[pos] === "/") {
      value = tokens[pos++] === "*" ? value * primary() : value / primary();
    }
    return value;
  }

  function sum() {
    let value = product();
    while (tokens[pos] === "+" || tokens[pos] === "-") {
      value = tokens[pos++] === "+" ? value + product() : value - product();
    }
    return value;
  }

  const value = sum();
  if (pos !== tokens.length) throw new Error(`unexpected ${JSON.stringify(tokens[pos])}`);
  return value;
}

for (const text of ["6 * 7", "(1 + 2) / 4", "process.release.name"]) {
  try {
    console.log(text, "=", calculate(text));
  } catch (error) {
    console.log(text, "->", error.message);
  }
}
Output
6 * 7 = 42
(1 + 2) / 4 = 0.75
process.release.name -> unexpected "p"

The parser knows numbers, four operators and parentheses. A name is not in its grammar, so it stops at the first letter.

  • Verdict: stdlib. JavaScript has no safe form of eval. A small recursive descent parser, as above, covers formulas. JSON.parse covers data.
  • eval, new Function(text), and setTimeout or setInterval with a string all compile text as code. MDN says to never use direct eval, because it runs with the privileges of the caller and can read the local variables.
  • The node:vm module is not a security mechanism. Its documentation says not to use it to run untrusted code.
  • To call a function by a name from input, use a Map from names to functions. Do not index globalThis or an object with the input, because the name can reach methods that you did not mean to offer.
  • In the browser, the same weakness with HTML is Cross-site scripting. A Content Security Policy without 'unsafe-eval' makes the browser refuse eval and new Function.
  • ESLint rules no-eval, no-implied-eval and no-new-func flag these calls. CodeQL has js/code-injection and js/unsafe-dynamic-method-access.

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"os"
	"text/template"
)

type Account struct {
	Name   string
	APIKey string
}

// greet parses the text that the user wrote as a template.
func greet(userText string, account Account) {
	t, err := template.New("greeting").Parse(userText)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	t.Execute(os.Stdout, account)
	fmt.Println()
}

func main() {
	account := Account{Name: "alice", APIKey: "placeholder-not-a-real-key"}
	greet("Hello, {{.Name}}!", account)
	greet("Hello, {{.APIKey}}!", account)
	greet("{{.}}", account)
}
Output
Hello, alice!
Hello, placeholder-not-a-real-key!
{alice placeholder-not-a-real-key}

The user wrote the template, so the user chose which fields to print. {{.}} prints the whole value.

package main

import (
	"os"
	"text/template"
)

// The template text is a constant in the code. Its author is trusted.
var greeting = template.Must(template.New("greeting").Parse("{{.Greeting}}, {{.Name}}!\n"))

// The view holds only the values that the template needs.
type view struct {
	Greeting string
	Name     string
}

func main() {
	for _, userText := range []string{"Hello", "Hello {{.APIKey}}"} {
		// The text from the user is data. The template prints it and never parses it.
		greeting.Execute(os.Stdout, view{Greeting: userText, Name: "alice"})
	}
}
Output
Hello, alice!
Hello {{.APIKey}}, alice!

The second greeting prints the braces as text. The template was parsed once, from a constant, so the input cannot add an action.

  • Verdict: stdlib. Go has no eval. Code injection in Go programs comes from template text, from plugins and from running other interpreters with input.
  • The security model of html/template assumes that template authors are trusted and the data passed to Execute is not. text/template has the same model and does not escape the output for HTML.
  • A template can read the exported fields and map keys of its data, and it can call methods. Pass a small view struct with only the values to print, not a whole domain object.
  • Functions that a template can call come from the FuncMap that the program installs. Do not add functions that read files, run commands or reach other data.
  • When users must write their own templates, give them a smaller language, such as a fixed set of $name placeholders, and replace them with strings.NewReplacer.

References

  1. CWE-94: Improper Control of Generation of Code, Description; Relationships; Common Consequences; Potential Mitigations; Detection Methods; Observed Examples; Content History
  2. OWASP Top 10:2025, A05:2025 Injection, List of Mapped CWEs
  3. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 10, CVEs in KEV, Rank Last Year
  4. The Python Standard Library, Built-in Functions, Python 3.15, eval; exec
  5. The Python Standard Library, ast, Python 3.15, ast.parse, the warning; ast.literal_eval, the warning
  6. MDN Web Docs, eval(), Never use direct eval()!; Security considerations
  7. Node.js documentation, VM (executing JavaScript), the warning at the top of the page
  8. James Kettle, Server-Side Template Injection, PortSwigger Research, 5 August 2015, the introduction; Detect
  9. The Python Standard Library, string, Python 3.15, Format String Syntax; Template strings, safe_substitute
  10. Go standard library, package html/template, Security Model
  11. CodeQL query help, Code injection (py/code-injection), the query description
  12. Ruff rules, suspicious-eval-usage (S307), What it does
  13. ESLint rules, no-eval, the introduction; Rule Details
  14. CVE-2003-0395, Ultimate PHP Board, the description and the publication date
  15. CVE-2008-5305, TWiki, the description and the publication date
  16. CVE-2020-8218, Pulse Connect Secure, the description and the publication date
  17. CVE-2022-26134, Atlassian Confluence Server and Data Center, the description and the publication date
  18. CVE-2023-29374, LangChain, the description and the publication date

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/MSMSQV/text.yaml