How it shows up in Python
Python makes running a string as code a one-liner, and that is the problem. The most common misuse is not a calculator; it is eval() used as a parser for something that looks like Python data:
from flask import request
@app.post("/saved-filters")
def save_filters():
filters = eval(request.form["filters"])
store_filters(current_user(), filters)
return "saved"
The form value was meant to be {'status': 'open'}. It can equally be an expression that imports a module and calls into it, which is everything the program itself can do. Passing {"__builtins__": {}} as the globals does not make this safe: attribute walks from any literal reach the builtins again. Parse data as data instead:
import json
from flask import request, abort
ALLOWED = {"status", "owner", "label"}
@app.post("/saved-filters")
def save_filters():
filters = json.loads(request.form["filters"])
if not isinstance(filters, dict) or not set(filters) <= ALLOWED:
abort(400)
store_filters(current_user(), filters)
return "saved"
The second shape is choosing code by name. A plugin loader or an action dispatcher that takes the name from a request lets the attacker pick a module or a function you never meant to expose:
import importlib
def load_exporter(fmt: str):
return importlib.import_module(fmt).export
def handle(action: str, payload: dict):
return getattr(handlers, action)(payload)
Map names to code you chose, and fail closed on anything else:
import importlib
EXPORTERS = {"csv": "exporters.csv_export", "xlsx": "exporters.xlsx_export"}
ACTIONS = {"archive": handlers.archive, "restore": handlers.restore}
def load_exporter(fmt: str):
if fmt not in EXPORTERS:
raise ValueError(f"unknown format {fmt!r}")
return importlib.import_module(EXPORTERS[fmt]).export
def handle(action: str, payload: dict):
if action not in ACTIONS:
raise ValueError(f"unknown action {action!r}")
return ACTIONS[action](payload)
The same applies to setattr(obj, field, value) with both parts from a request (mass assignment), to ctypes.CDLL() given an untrusted path, and to a debug console such as code.InteractiveConsole fed from a socket.
Why it is hard to see
- The call target is chosen at runtime.
getattr(os, fn)(arg)withfnfrom the request names no dangerous function anywhere in the source, so a scanner cannot connect it toos.system. - East-west input. A service picks a module by a name it received from another internal service. The request never crosses the edge, so a CDN or web application firewall in front of the public site never sees it.
- Indirection.
run = evalin one module andrun(expr)in another. Pattern rules keyed on the literal call do not follow the alias. - Data that only becomes code later. A value stored today and passed to
exec()by a scheduled job next week. No single request or function shows the whole flow.
What the es-python event looks like
es-python reports untrusted data reaching an operation that turns it into code: eval, exec and compile for the builtins, __import__ for an import by computed name, interactive console when a console runs untrusted input, and ctypes dlopen when a library is loaded from an untrusted path. These carry the rce impact tag, one of the classes the dashboard always shows in its critical colour. An importlib.import_module() call with an untrusted name is reported where the import system looks that name up on disk, as a file-system event.
Name-based access gets its own labels. setattr and monkey patch (a write onto a module or a class, which replaces code rather than data) carry the unsafe reflection tag. An untrusted name passed to getattr() is reported as getattr and tagged as template injection, because walking attributes is how template-injection payloads escape; EyalSec keeps those events only when the name reaches an introspection attribute such as __class__ or __globals__, and suppresses the rest. See server-side template injection.
One practical note: ast.literal_eval() and ast.parse() cannot run code, but they compile their input to a syntax tree, so on untrusted input es-python reports them as compile. If you rely on them deliberately, record that decision with a rule for that call site.
The severity is Critical when the data came from the network. Under a Raise rule, eval(), exec() and compile() raise a RuntimeError before anything is compiled, so the injected code never runs.
How to fix and prevent it
- Keep untrusted input out of
eval(),exec()andcompile(). Parse data withjson, configuration withtomllibor a schema library. - For expressions users really need (a pricing formula, a filter), use a purpose-built evaluator with an explicit grammar, not Python.
- Choose modules, functions and attributes from an allowlist dictionary, not from
getattr()orimport_module()on a raw name. - Keep interactive consoles and debuggers off network ports in production.
- In Report mode, sort by the
rcetag first: any untrusted flow into these sinks deserves a look.
Classification
Code injection is CWE-94, Improper Control of Generation of Code; eval() and exec() on untrusted input are its child CWE-95, Eval Injection, and picking code by an untrusted name is CWE-470, Unsafe Reflection. OWASP maps all three to A05:2025 Injection.
Questions people ask
The questions that come up on forums and in reviews about this class, each answered in a few sentences.
Is eval on user input ever safe?
No: eval() runs whatever expression it is given with the program's full privileges, and filtering the string first has been bypassed every time it has been tried. For arithmetic or a configuration value, parse the input with ast.literal_eval() or a small parser of your own, and map user choices to functions with a dictionary rather than getattr() or a computed import. es-python reports eval(), exec() and compile() on untrusted input as Critical.
Is ast.literal_eval a safe replacement for eval?
It is safe in the sense that matters: ast.literal_eval() accepts only literals (strings, numbers, tuples, lists, dicts, sets, booleans and None) and cannot call a function or run code. It still parses the input, so a very large or deeply nested string costs memory and time, and es-python reports it as a compile event on untrusted data so the call site stays visible. If you rely on it deliberately, record that decision with a rule for that line.
How does es-python detect code injection?
It reports untrusted data reaching the operation that turns it into code, eval, exec, compile, __import__ and the interactive console, at the moment the program performs it, with the value, its source and the stack trace. The event carries the rce impact tag and is Critical when the data came from the network. Under a Raise rule the call raises a Python RuntimeError before anything is compiled, so the injected code never runs.