Summary
SandboxShellTool(ignore=[...]) refuses a command when a path written in the command matches an ignore pattern. It does not look at files a program finds by itself. readonly=True allows grep and diff, and with -r they open every file under a directory, so grep -r KEY . prints the contents of .env, .key and secrets/ while cat .env is refused.
The docs cover part of this. website/docs/user-guide/tools/localshell.mdx:112 says: "ignore checks only the literal path words of the command. [...] A program that opens paths on its own (sh -c, find) is not covered; use an isolated backend for that." Both examples in that note are programs readonly=True does not allow. The built-in read-only list contains grep, egrep, fgrep and diff (ag2/tools/sandbox/filter.py:25-43), the same page recommends grep -r --include='.py' in restricted mode (line 139), and commontoolkits.mdx:346-347 introduces ignore=["/.env", ".key", "secrets/"] as "Hide sensitive files from the agent". An operator who combines readonly=True with ignore can reasonably expect those files to stay hidden, and they don't. If you read the note at line 112 as already covering recursive grep, I'm fine with closing this as a documentation issue.
Affected versions
PyPI ag2 1.3.2 (latest, tested 2026-11-19) and 1.3.1 (tested 2026-11-15). main at 7a65080 has the same filter.py. Older releases were not checked.
Impact
The operator runs an agent with SandboxShellTool(readonly=True, ignore=[...]) on a local directory that contains the ignored files, and the agent processes content the attacker wrote (a document, a web page, tool output). If the model follows an injected instruction to run grep -r . ., the ignored files come back in the tool result. I scripted the model turn and did not test a live model. To receive the data the attacker also needs an output channel in the deployment, such as the agent's reply or another tool. The shell tool in readonly mode does not provide one.
Every command that names an ignored path was refused in my tests: relative, absolute and .. paths, globs, head/tail/cut/wc/stat, grep -f.env, and existing symlinks to an ignored file or directory. Shell syntax and find are refused in readonly mode. Recursion is the only way through that I found.
This report is limited to readonly=True. With ignore alone any program can run (sh -c 'cat .e""nv' prints the file), and the docs already say so.
Reproduction
ag2==1.3.2 from PyPI, Python 3.12.16, GNU grep 3.11, python:3.12-slim container without network.
python import asyncio, tempfile from pathlib import Path from ag2.tools import LocalEnvironment, SandboxShellTool
work = Path(tempfile.mkdtemp(prefix="proj")) (work / ".env").writetext("OPENAIAPIKEY=sk-MARKER-ENV\n") (work / "deploy.key").writetext("-----BEGIN MARKER PRIVATE KEY-----\n") (work / "secrets").mkdir() (work / "secrets" / "db.txt").writetext("DBPASSWORD=MARKER-DB\n") (work / "app.py").writetext("print('hello')\n")
sh = SandboxShellTool(LocalEnvironment(str(work)), readonly=True, ignore=["/.env", ".key", "secrets/"])
async def main(): for cmd in ["cat .env", "cat .en", "grep KEY .env", "cat secrets/db.txt", "grep -r KEY .", "grep -r . secrets", "grep -r MARKER"]: print(f"\n$ {cmd}\n{(await sh.adapter.run(cmd)).strip()}")
asyncio.run(main())
Output:
$ cat .env Access denied: /tmp/proj1j68or/.env
$ cat .en Access denied: /tmp/proj1j68or/.env
$ grep KEY .env Access denied: /tmp/proj1j68or/.env
$ cat secrets/db.txt Access denied: /tmp/proj1j68or/secrets/db.txt
$ grep -r KEY . ./.env:OPENAIAPIKEY=sk-MARKER-ENV ./deploy.key:-----BEGIN MARKER PRIVATE KEY-----
$ grep -r . secrets secrets/db.txt:DBPASSWORD=MARKER-DB
$ grep -r MARKER .env:OPENAIAPIKEY=sk-MARKER-ENV secrets/db.txt:DBPASSWORD=MARKER-DB deploy.key:-----BEGIN MARKER PRIVATE KEY-----
grep -R, --recursive, -d recurse, --directories=recurse, egrep -r, fgrep -r and diff -rN empty . (with an existing empty directory empty) also printed the ignored files. sh.adapter.run() is the coroutine the registered runshellcommand tool awaits (ag2/tools/shell/tool.py:100-105). Calling the tool through an Agent with a scripted ag2.testing.TestConfig turn gave the same tool result.
Root cause
ShellAdapter.filter() (ag2/tools/sandbox/adapter/shell.py:116-122) calls checkignore() (ag2/tools/sandbox/filter.py:108-149). It resolves each word of the command, the parts after = and after a short option, and any glob matches, then compares those paths with the patterns. A directory word such as . or secrets matches none of /.env, .key, secrets/, and grep -r PATTERN with no path has no path word at all.
Suggested fix
Either of these would do:
- When ignore is set, refuse grep/egrep/fgrep/diff with a recursion option (-r, -R, --recursive, -d recurse, --directories=recurse, bundled forms such as -rn) if a directory operand, or the implicit ., contains an ignored path. - Say in the ignore and readonly docs that recursive grep/diff read ignored files, and change the "Hide sensitive files from the agent" example.
Summary
SandboxShellTool(ignore=[...]) refuses a command when a path written in the command matches an ignore pattern. It does not look at files a program finds by itself. readonly=True allows grep and diff, and with -r they open every file under a directory, so grep -r KEY . prints the contents of .env, .key and secrets/ while cat .env is refused.
The docs cover part of this. website/docs/user-guide/tools/localshell.mdx:112 says: "ignore checks only the literal path words of the command. [...] A program that opens paths on its own (sh -c, find) is not covered; use an isolated backend for that." Both examples in that note are programs readonly=True does not allow. The built-in read-only list contains grep, egrep, fgrep and diff (ag2/tools/sandbox/filter.py:25-43), the same page recommends grep -r --include='.py' in restricted mode (line 139), and commontoolkits.mdx:346-347 introduces ignore=["/.env", ".key", "secrets/"] as "Hide sensitive files from the agent". An operator who combines readonly=True with ignore can reasonably expect those files to stay hidden, and they don't. If you read the note at line 112 as already covering recursive grep, I'm fine with closing this as a documentation issue.
Affected versions
PyPI ag2 1.3.2 (latest, tested 2026-11-19) and 1.3.1 (tested 2026-11-15). main at 7a65080 has the same filter.py. Older releases were not checked.
Impact
The operator runs an agent with SandboxShellTool(readonly=True, ignore=[...]) on a local directory that contains the ignored files, and the agent processes content the attacker wrote (a document, a web page, tool output). If the model follows an injected instruction to run grep -r . ., the ignored files come back in the tool result. I scripted the model turn and did not test a live model. To receive the data the attacker also needs an output channel in the deployment, such as the agent's reply or another tool. The shell tool in readonly mode does not provide one.
Every command that names an ignored path was refused in my tests: relative, absolute and .. paths, globs, head/tail/cut/wc/stat, grep -f.env, and existing symlinks to an ignored file or directory. Shell syntax and find are refused in readonly mode. Recursion is the only way through that I found.
This report is limited to readonly=True. With ignore alone any program can run (sh -c 'cat .e""nv' prints the file), and the docs already say so.
Reproduction
ag2==1.3.2 from PyPI, Python 3.12.16, GNU grep 3.11, python:3.12-slim container without network.
python import asyncio, tempfile from pathlib import Path from ag2.tools import LocalEnvironment, SandboxShellTool
work = Path(tempfile.mkdtemp(prefix="proj")) (work / ".env").writetext("OPENAIAPIKEY=sk-MARKER-ENV\n") (work / "deploy.key").writetext("-----BEGIN MARKER PRIVATE KEY-----\n") (work / "secrets").mkdir() (work / "secrets" / "db.txt").writetext("DBPASSWORD=MARKER-DB\n") (work / "app.py").writetext("print('hello')\n")
sh = SandboxShellTool(LocalEnvironment(str(work)), readonly=True, ignore=["/.env", ".key", "secrets/"])
async def main(): for cmd in ["cat .env", "cat .en", "grep KEY .env", "cat secrets/db.txt", "grep -r KEY .", "grep -r . secrets", "grep -r MARKER"]: print(f"\n$ {cmd}\n{(await sh.adapter.run(cmd)).strip()}")
asyncio.run(main())
Output:
$ cat .env Access denied: /tmp/proj1j68or/.env
$ cat .en Access denied: /tmp/proj1j68or/.env
$ grep KEY .env Access denied: /tmp/proj1j68or/.env
$ cat secrets/db.txt Access denied: /tmp/proj1j68or/secrets/db.txt
$ grep -r KEY . ./.env:OPENAIAPIKEY=sk-MARKER-ENV ./deploy.key:-----BEGIN MARKER PRIVATE KEY-----
$ grep -r . secrets secrets/db.txt:DBPASSWORD=MARKER-DB
$ grep -r MARKER .env:OPENAIAPIKEY=sk-MARKER-ENV secrets/db.txt:DBPASSWORD=MARKER-DB deploy.key:-----BEGIN MARKER PRIVATE KEY-----
grep -R, --recursive, -d recurse, --directories=recurse, egrep -r, fgrep -r and diff -rN empty . (with an existing empty directory empty) also printed the ignored files. sh.adapter.run() is the coroutine the registered runshellcommand tool awaits (ag2/tools/shell/tool.py:100-105). Calling the tool through an Agent with a scripted ag2.testing.TestConfig turn gave the same tool result.
Root cause
ShellAdapter.filter() (ag2/tools/sandbox/adapter/shell.py:116-122) calls checkignore() (ag2/tools/sandbox/filter.py:108-149). It resolves each word of the command, the parts after = and after a short option, and any glob matches, then compares those paths with the patterns. A directory word such as . or secrets matches none of /.env, .key, secrets/, and grep -r PATTERN with no path has no path word at all.
Suggested fix
Either of these would do:
- When ignore is set, refuse grep/egrep/fgrep/diff with a recursion option (-r, -R, --recursive, -d recurse, --directories=recurse, bundled forms such as -rn) if a directory operand, or the implicit ., contains an ignored path. - Say in the ignore and readonly docs that recursive grep/diff read ignored files, and change the "Hide sensitive files from the agent" example.
Summary SandboxShellTool's restricted modes — allowed=[...] (explicit command allowlist) and readonly=True (implicit READONLYCOMMANDS allowlist) — can both be bypassed by embedding a newline character inside the command string. The filter only inspects a single-line set of shell metacharacters, but execution runs the raw string through sh -c, where a shell treats an embedded newline exactly like a ; statement separator. An agent (or content that steers the agent, e.g. via prompt injection) can therefore run arbitrary shell commands even when the tool was configured to allow only a specific command prefix or only read-only commands. With the default LocalEnvironment() backend this is a real host subprocess (its own docstring: "Commands run via subprocess on the host, so there is no real isolation"), not an isolated container, so this is full host command execution, not merely an escape from an already-sandboxed environment.
Details Both restricted modes are enforced by ShellAdapter.filter() in ag2/tools/sandbox/adapter/shell.py:
python def filter(self, command: str) -> str | None: if self.allowed is not None: if not any(matches(p, command) for p in self.allowed): return f"Command not allowed: {command!r}" if containsshelloperator(command): return f"Command not allowed (shell operators are not permitted in restricted mode): {command!r}" ...
readonly=True reuses this exact same branch: SandboxShellTool.init / ShellAdapter.init sets self.allowed = list(READONLYCOMMANDS) when readonly is set and no explicit allowed is given, so both modes share one filter and one bypass.
containsshelloperator() in ag2/tools/sandbox/filter.py checks the command against:
python SHELLOPERATORS: tuple[str, ...] = (">", ">>", "|", ";", "&&", "||", "", "$(")
This tuple has no entry for \n (or \r). matches() only checks that the command starts with an allowed prefix followed by a space or end-of-string; it never inspects the remainder of the string. Execution is:
python argv = ["sh", "-c", command] ... return await sandbox.exec(argv, env=self.env, timeout=self.timeout)
A POSIX shell splits sh -c "<line1>\n<line2>" into two sequential statements, the same as if they were separated by ;. So a command such as "cat allowedfile.txt\nrm -rf /anything":
1. Passes matches("cat", command) — the string starts with "cat ". 2. 2. Passes containsshelloperator(command) — \n is not a recognized operator. 3. 3. Reaches sh -c "cat allowedfile.txt\nrm -rf /anything", which runs both statements. Proof of Concept Verified directly against the current main branch (github.com/ag2ai/ag2, commit a05ff1cb6ff4955ef252a4e0d4a27d3a32ad57f0, cloned 2026-09-21), by importing the real ag2/tools/sandbox/filter.py module (stdlib-only, no other AG2 dependencies needed) and reproducing ShellAdapter.filter()'s allowlist branch verbatim:
=== allowed=['cat'] === 'cat /etc/passwd; rm -rf /tmp/x' -> Command not allowed (shell operators are not permitted in restricted mode): ... 'cat /etc/passwd && rm -rf /tmp/x' -> Command not allowed (shell operators are not permitted in restricted mode): ... 'cat /etc/passwd | rm -rf /tmp/x' -> Command not allowed (shell operators are not permitted in restricted mode): ... 'cat /etc/passwd\nrm -rf /tmp/x' -> None <-- BYPASS: newline variant is NOT rejected
=== readonly=True (uses READONLYCOMMANDS as the allowed list) === 'echo hi\nid' -> None <-- BYPASS in readonly mode too
=== sh -c really treats the embedded newline as a second statement (mirrors ShellAdapter.execasync) === $ sh -c 'echo first-command-output\necho SECOND-STATEMENT-RAN-$((212))' first-command-output SECOND-STATEMENT-RAN-42
The three standard chaining attempts (;, &&, |) are correctly rejected by the real filter, confirming it does real work; the newline-separated variant, expressing the same intent, is accepted by the identical filter in both restricted modes, and a real sh -c call confirms the shell executes both statements.
Impact Any agent configured with SandboxShellTool(allowed=[...]) or SandboxShellTool(readonly=True) — the two configurations the tool's own docstring presents as actual security boundaries, as opposed to blocked, which the same docstring explicitly says "is not a security boundary" — can be made to execute arbitrary shell commands via a single embedded newline in the command argument. Because tool arguments are LLM-generated and can be steered by content the agent processes (a fetched document, tool output, or any other text reaching the model — i.e. indirect prompt injection), this is reachable without the operator of the agent writing the malicious command themselves. With the default LocalEnvironment() backend, this is command execution on the host process running the agent, not confined to a container.
Suggested Remediation - Add "\n" and "\r" to SHELLOPERATORS in ag2/tools/sandbox/filter.py so containsshelloperator() rejects embedded newlines the same way it rejects ;. - - More robustly, execute allowlisted/readonly commands without invoking a shell in restricted mode (shlex.split + exec with no sh -c wrapper), so redirection, chaining, substitution, and every kind of statement separator are inert by construction instead of relying on an enumerated denylist. Environment Tested - Repository: github.com/ag2ai/ag2, commit a05ff1cb6ff4955ef252a4e0d4a27d3a32ad57f0 (main), cloned 2026-09-21. - - PyPI package ag2, version 1.0.5 per pyproject.toml on this commit. - - Python 3, stdlib only (subprocess, importlib) against the real, unmodified ag2/tools/sandbox/filter.py — no AG2 runtime dependencies required to reproduce. -
Summary SandboxShellTool's restricted modes — allowed=[...] (explicit command allowlist) and readonly=True (implicit READONLYCOMMANDS allowlist) — can both be bypassed by embedding a newline character inside the command string. The filter only inspects a single-line set of shell metacharacters, but execution runs the raw string through sh -c, where a shell treats an embedded newline exactly like a ; statement separator. An agent (or content that steers the agent, e.g. via prompt injection) can therefore run arbitrary shell commands even when the tool was configured to allow only a specific command prefix or only read-only commands. With the default LocalEnvironment() backend this is a real host subprocess (its own docstring: "Commands run via subprocess on the host, so there is no real isolation"), not an isolated container, so this is full host command execution, not merely an escape from an already-sandboxed environment.
Details Both restricted modes are enforced by ShellAdapter.filter() in ag2/tools/sandbox/adapter/shell.py:
python def filter(self, command: str) -> str | None: if self.allowed is not None: if not any(matches(p, command) for p in self.allowed): return f"Command not allowed: {command!r}" if containsshelloperator(command): return f"Command not allowed (shell operators are not permitted in restricted mode): {command!r}" ...
readonly=True reuses this exact same branch: SandboxShellTool.init / ShellAdapter.init sets self.allowed = list(READONLYCOMMANDS) when readonly is set and no explicit allowed is given, so both modes share one filter and one bypass.
containsshelloperator() in ag2/tools/sandbox/filter.py checks the command against:
python SHELLOPERATORS: tuple[str, ...] = (">", ">>", "|", ";", "&&", "||", "", "$(")
This tuple has no entry for \n (or \r). matches() only checks that the command starts with an allowed prefix followed by a space or end-of-string; it never inspects the remainder of the string. Execution is:
python argv = ["sh", "-c", command] ... return await sandbox.exec(argv, env=self.env, timeout=self.timeout)
A POSIX shell splits sh -c "<line1>\n<line2>" into two sequential statements, the same as if they were separated by ;. So a command such as "cat allowedfile.txt\nrm -rf /anything":
1. Passes matches("cat", command) — the string starts with "cat ". 2. 2. Passes containsshelloperator(command) — \n is not a recognized operator. 3. 3. Reaches sh -c "cat allowedfile.txt\nrm -rf /anything", which runs both statements. Proof of Concept Verified directly against the current main branch (github.com/ag2ai/ag2, commit a05ff1cb6ff4955ef252a4e0d4a27d3a32ad57f0, cloned 2026-09-21), by importing the real ag2/tools/sandbox/filter.py module (stdlib-only, no other AG2 dependencies needed) and reproducing ShellAdapter.filter()'s allowlist branch verbatim:
=== allowed=['cat'] === 'cat /etc/passwd; rm -rf /tmp/x' -> Command not allowed (shell operators are not permitted in restricted mode): ... 'cat /etc/passwd && rm -rf /tmp/x' -> Command not allowed (shell operators are not permitted in restricted mode): ... 'cat /etc/passwd | rm -rf /tmp/x' -> Command not allowed (shell operators are not permitted in restricted mode): ... 'cat /etc/passwd\nrm -rf /tmp/x' -> None <-- BYPASS: newline variant is NOT rejected
=== readonly=True (uses READONLYCOMMANDS as the allowed list) === 'echo hi\nid' -> None <-- BYPASS in readonly mode too
=== sh -c really treats the embedded newline as a second statement (mirrors ShellAdapter.execasync) === $ sh -c 'echo first-command-output\necho SECOND-STATEMENT-RAN-$((212))' first-command-output SECOND-STATEMENT-RAN-42
The three standard chaining attempts (;, &&, |) are correctly rejected by the real filter, confirming it does real work; the newline-separated variant, expressing the same intent, is accepted by the identical filter in both restricted modes, and a real sh -c call confirms the shell executes both statements.
Impact Any agent configured with SandboxShellTool(allowed=[...]) or SandboxShellTool(readonly=True) — the two configurations the tool's own docstring presents as actual security boundaries, as opposed to blocked, which the same docstring explicitly says "is not a security boundary" — can be made to execute arbitrary shell commands via a single embedded newline in the command argument. Because tool arguments are LLM-generated and can be steered by content the agent processes (a fetched document, tool output, or any other text reaching the model — i.e. indirect prompt injection), this is reachable without the operator of the agent writing the malicious command themselves. With the default LocalEnvironment() backend, this is command execution on the host process running the agent, not confined to a container.
Suggested Remediation - Add "\n" and "\r" to SHELLOPERATORS in ag2/tools/sandbox/filter.py so containsshelloperator() rejects embedded newlines the same way it rejects ;. - - More robustly, execute allowlisted/readonly commands without invoking a shell in restricted mode (shlex.split + exec with no sh -c wrapper), so redirection, chaining, substitution, and every kind of statement separator are inert by construction instead of relying on an enumerated denylist. Environment Tested - Repository: github.com/ag2ai/ag2, commit a05ff1cb6ff4955ef252a4e0d4a27d3a32ad57f0 (main), cloned 2026-09-21. - - PyPI package ag2, version 1.0.5 per pyproject.toml on this commit. - - Python 3, stdlib only (subprocess, importlib) against the real, unmodified ag2/tools/sandbox/filter.py — no AG2 runtime dependencies required to reproduce. -
A vulnerability was determined in ag2ai ag2 up to 0.13.4. Affected by this issue is the function os.path.join of the component UserProxyAgent. This manipulation of the argument filename causes path traversal. The attack is possible to be carried out remotely. The exploit has been publicly disclosed and may be utilized. The vendor was contacted early about this disclosure but did not respond in any way.