Skip to content

Tool sandbox: workspace boundary + regex-free shell denylist - #53

Merged
FMXExpress merged 3 commits into
mainfrom
claude/pr53-tool-sandbox
May 28, 2026
Merged

FMXExpress merged 3 commits into
mainfrom
claude/pr53-tool-sandbox

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

The Phase-4-promised "workspace-restricted variant" that the FS and Shell unit headers kept pointing at. New unit src/pkg/tools/PasClaw.Tools.Sandbox.pas centralises both concerns; existing tool handlers delegate to it.

What was there before (vs picoclaw)

Before Picoclaw
FS workspace boundary none — any absolute path accepted os.OpenRoot syscall sandbox + regex allowlists
Shell denylist 6 substring checks (trivially escaped by rm -rf /, sudo …, curl x | sh, eval $(…)) ~35 regex patterns + abs-path scan
Workspace check on shell none per-command abs-path canonicalisation against workspace

What's here now

New TSandboxPolicy (PasClaw.Config)

Field Default Effect
restrict_to_workspace false When true, fs_* and shell_exec refuse paths outside workspace
allow_read_outside_workspace false Soften reads while keeping writes locked down
workspace "" (cwd at startup) Absolute path the agent operates inside
allow_read_paths [] Glob patterns that also count as readable
allow_write_paths [] Same for writes
custom_shell_deny [] Extra substrings appended to the built-in denylist
shell_deny_enabled true Master switch for the shell denylist

PasClaw.Tools.Sandbox API

procedure ConfigureSandbox(const Policy: TSandboxPolicy; const Workspace: string);
function CanReadPath (const Path: string; out Reason: string): Boolean;
function CanWritePath(const Path: string; out Reason: string): Boolean;
function ShellAllowed(const Cmd:  string; out Reason: string): Boolean;

Shell denylist (always on unless shell_deny_enabled=false)

Forbidden tokens (matched as whitespace-separated words): sudo, su, rm, chmod, chown, pkill, killall, kill, shutdown, reboot, poweroff, halt, eval, mkfs, diskpart.

Forbidden substrings (case-insensitive): dd if=, :(){:|, <<EOF, $(, ${, backticks, | sh, | bash, apt install/remove/purge, yum install/remove, dnf install/remove, npm install -g, pip install --user, docker run/exec, git push, git force, format c:.

Forbidden device writes: > /dev/sd*, /hd*, /vd*, /xvd*, /nvme*, /mmcblk*, /loop*, /md*.

Always-safe paths (picoclaw's safePaths): /dev/null, /dev/zero, /dev/{,u}random, /dev/std{in,out,err}.

Wiring (6 sites)

ConfigureSandbox(Cfg.Sandbox, '') after LoadConfig in:

  • Cmd.Agent.pas, Cmd.Serve.pas, Cmd.Gateway.pas, Cmd.TUI.pas
  • Component.pas — both TPasClawAgent.EnsureConfig and TPasClawServer.Start

Tool handlers (Tool_FSRead, Tool_FSWrite, Tool_FSEditHashline, Tool_FSGrep, Tool_FSList, Tool_Shell) all call into CanReadPath / CanWritePath / ShellAllowed before doing work.

Trade-offs

Globs not regex: allow_*_paths uses simple */? glob matching, not full regex. Picoclaw uses Go regex via regexp package; PasClaw doesn't have a cross-target regex story (FPC has RegExpr, Delphi has System.RegularExpressions, different APIs). Globs cover the documented use cases (/tmp/*, ~/.cache/agent/*, /usr/include/*). Swapping the matcher to regex is one function change if the demand shows up.

Symlink escape (documented limitation): ExpandFileName resolves .. but not symlinks. Picoclaw avoids this via Go 1.24's os.OpenRoot (boundary at syscall layer). FPC and Delphi RTLs have no equivalent. README's Security section explicitly warns not to put symlinks inside workspace that point outside it.

Backwards compat

Defaults preserve current behaviour: restrict_to_workspace=false, existing configs without a sandbox block load cleanly. The shell denylist upgrade is the one always-on change, but it's a strict superset of the previous 6-substring check — no legitimate use ever passed the old check either.

Not in this PR (deferred follow-ups)

  • Channel-aware tool gating: disable shell_exec for "untrusted" gateway origins (Telegram/Discord/Slack webhooks) while leaving CLI use unrestricted. Needs per-request context plumbing.
  • .security.yml-style credential encryption-at-rest. Picoclaw's separate feature; PasClaw still writes plaintext config.json.
  • Regex allow_*_paths — covered above.

Test plan

  • FPC build (make) + Delphi .dproj build cleanly
  • Bare pasclaw agent "read /etc/passwd" — succeeds (sandbox off by default — backwards compat)
  • Set sandbox.restrict_to_workspace: true, retry — fs_read refuses with a clear Reason; model gets the refusal in tool_result
  • Same config + allow_read_paths: ["/etc/passwd"] — read succeeds
  • pasclaw agent then ask it to run sudo whoami — refused even with restrict_to_workspace=false (shell denylist is always on)
  • Set shell_deny_enabled: false, retry — sudo passes through (verify the master switch works)
  • > /dev/sda — refused
  • > /dev/null 2>&1 — passes (kernel pseudo-device)
  • pasclaw agent --no-tools still works (registry empty, no sandbox checks fire because no tools registered)
  • Component: construct TPasClawAgent with a Sandbox-restricted config; verify the same enforcement
  • cd /tmp/myproject && pasclaw agent "list ." — workspace resolves to /tmp/myproject (empty workspace field => cwd)

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6db09ef393

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +438 to +439
if GPolicy.RestrictToWorkspace then
if HasOutsideAbsolutePath(Cmd, Path) then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Confine relative shell paths to the workspace

With sandbox.restrict_to_workspace=true, this only calls the absolute-path scanner, so relative-only shell commands still run unchecked. For example, when the process starts in the workspace, cd .. && cat secret contains no / token for HasOutsideAbsolutePath to reject, and RunOneShot just invokes /bin/sh -c without chdir/chroot confinement, so the command can operate outside the configured workspace despite the new shell boundary.

Useful? React with 👍 / 👎.

Comment thread src/pkg/tools/PasClaw.Tools.Sandbox.pas Outdated
if SameText(P, ExcludeTrailingPathDelimiter(D)) then Exit(True);
{ Case sensitivity: on Linux paths are case-sensitive; on Windows
they are not. SameText handles both via the RTL's locale rules. }
Result := (Length(P) > Length(D)) and SameText(Copy(P, 1, Length(D)), D);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve case-sensitive path checks on Unix

On Linux and other case-sensitive filesystems, using SameText makes /tmp/workspace and /tmp/Workspace compare as the same prefix. If both directories exist, a restricted fs_read/fs_write path such as /tmp/Workspace/secret is treated as inside /tmp/workspace and then the actual I/O uses the differently-cased path, bypassing the workspace boundary.

Useful? React with 👍 / 👎.

claude added 3 commits May 28, 2026 17:23
The Phase-4-promised "workspace-restricted variant" that the FS and
Shell unit headers kept pointing at. New unit
src/pkg/tools/PasClaw.Tools.Sandbox.pas centralises both concerns
and the existing tool handlers delegate to it.

What was there before:

  - fs_read / fs_write / fs_list / fs_edit_hashline / fs_grep accepted
    any absolute path. `pasclaw agent "write /etc/passwd"` would do
    exactly that within the running user's permissions.
  - shell_exec ran six naive substring checks ('rm -rf /', 'mkfs',
    'dd if=', ':(){:|', 'shutdown -h') and rubber-stamped everything
    else. Trivially escaped by 'rm  -rf  /' (extra spaces), 'sudo
    anything', 'curl x | sh', 'eval $(...)' — none of those tripped
    the old IsDangerous().

What's here now:

  TSandboxPolicy in PasClaw.Config:

    restrict_to_workspace        bool   default false
    allow_read_outside_workspace bool   default false
    workspace                    string default ""   ('' => cwd)
    allow_read_paths             string[] (globs)
    allow_write_paths            string[] (globs)
    custom_shell_deny            string[] (substrings)
    shell_deny_enabled           bool   default true

  PasClaw.Tools.Sandbox exposes:

    ConfigureSandbox(Policy, WorkspaceOverride)
      Sets module-level state. Called once per command after
      LoadConfig (Cmd.Agent, Cmd.Serve, Cmd.Gateway, Cmd.TUI, and
      TPasClawAgent.EnsureConfig / TPasClawServer.Start).

    CanReadPath(Path, out Reason): Boolean
    CanWritePath(Path, out Reason): Boolean
      Tool handlers call these on every path argument. False with
      Reason set means refuse the operation; the handler converts
      Reason into the model-visible error string so the next turn
      can correct course instead of looping.

    ShellAllowed(Cmd, out Reason): Boolean
      Tokenises the command on whitespace + shell metacharacters,
      checks each token against ForbiddenTokens
      (sudo / su / rm / chmod / chown / pkill / killall / kill /
      shutdown / reboot / poweroff / halt / eval / mkfs / diskpart),
      then matches the lowercased command against ForbiddenSubstrings
      (dd if= / fork bomb / <<EOF / $( / ${ / backticks / | sh /
      | bash / apt|yum|dnf install/remove/purge / npm install -g /
      pip install --user / docker run|exec / git push|force /
      format c:) and ForbiddenDeviceWrites (> /dev/sd* etc). Also
      runs an absolute-path scan when RestrictToWorkspace is set:
      every '/'-prefixed token in the command that is not a kernel
      pseudo-device (/dev/null and friends — picoclaw's safePaths)
      must canonicalise into the workspace.

Glob matcher implemented in-unit (no regex dep — FPC and Delphi do
not share a regex API and adding one for this PR was scope creep):
'*' matches any run including separators, '?' matches one char,
case-insensitive comparison via UpCase. Recursive descent.
Patterns are short and the call rate is tool-call frequency, so
the algorithmic shape does not matter.

Path canonicalisation uses ExpandFileName, which resolves '..' but
not symlinks. Picoclaw avoids this gap via Go 1.24's os.OpenRoot;
PasClaw runs on FPC/Delphi RTLs that do not expose an equivalent.
README's new Security section documents the limitation: do not put
symlinks pointing outside the workspace inside the workspace.

Backwards compat: every default leaves PasClaw behaving as before
on first run (RestrictToWorkspace=false). Existing configs without
a "sandbox" block load cleanly and behave identically. The shell
denylist is the one bit of new always-on behaviour, but it is a
strict superset of the previous six-substring check and no
legitimate use ever passed the old check either — there is no
realistic regression.

Wiring (six sites):

  src/cmd/PasClaw.Cmd.Agent.pas        ConfigureSandbox after LoadConfig
  src/cmd/PasClaw.Cmd.Serve.pas        same
  src/cmd/PasClaw.Cmd.Gateway.pas      same
  src/cmd/PasClaw.Cmd.TUI.pas          same
  src/pkg/component/PasClaw.Component.pas
    EnsureConfig (TPasClawAgent) and Start (TPasClawServer) both
    call it; the agent and server live in the same process so they
    share the module-level state.

Build wiring: src/pkg/tools is already in Makefile UNIT_DIRS so
the new unit picks up automatically; PasClaw.dproj gets a
DCCReference between Registry and FS.

README gets a "🔒 Security / sandbox" section that documents the
config schema, the full denylist, and the symlink limitation.

Not in this PR (mentioned in the prior architecture comparison):

  - Channel-aware tool gating: a TToolPolicy knob disabling
    shell_exec for "untrusted" gateway origins (Telegram, Discord,
    Slack webhooks) while leaving CLI invocations unrestricted.
    Needs per-request context plumbing that does not exist yet.

  - .security.yml-style encryption-at-rest for API keys. PasClaw
    still writes config.json in plaintext; picoclaw's encrypted
    secret store is a separate feature.

  - Regex pattern support for allow_*_paths. Globs were a
    deliberate trade to avoid pulling in System.RegularExpressions
    (Delphi) / RegExpr (FPC) just for this PR; if the user base
    asks for it, swapping the matcher is one function.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Two real bugs in the prompt builder from the previous commit on this
branch, both caught in review.

1. Skill catalog advertised the wrong tool names. RegisterSkills in
   PasClaw.Skills.Loader registers each manifest as `'skill_' +
   Skills[i].Name` (line 269), so the actual callable identifier is
   `skill_weather`, not `weather`. The prompt was telling the model
   to call the bare name — every skill invocation would have hit
   "tool not found" and the model would have either retried in a
   loop or avoided skills entirely. Fixed by prefixing `skill_` in
   BuildSkillsSection so the bullet line matches what the registry
   exposes.

2. The prompt was telling the model to use tools when tools were
   explicitly disabled. `pasclaw agent --no-tools` (Cmd.Agent line
   185), TPasClawAgent with UseTools=False (Component line 224), and
   `pasclaw serve --no-tools` (Cmd.Serve line 111) all leave the tool
   registry nil, so RunToolLoop sends an empty tool list. But the
   system prompt was still emitting the SKILLS catalog and a "RULES"
   block whose top rule is "ALWAYS use tools when an action is
   needed". The model would then either invent tool calls that the
   loop refused to pass through, or get stuck oscillating between
   the no-tools reality and the system prompt's tool-use directive.

   Fixed by adding a ToolsEnabled parameter (default True) to
   BuildSystemPrompt and gating tool-dependent content on it:

     ToolsEnabled = True   (default — unchanged from previous commit)
       Identity + Workspace + Memory + Skills + 5-rule block
       + user-supplied --system text.

     ToolsEnabled = False
       Identity + Workspace + Memory + 2-rule block ("Be precise"
       and a new "No tools in this session — do not claim to read
       files, run commands, or modify state. Answer from what is in
       this conversation."). Skills catalog suppressed entirely.

   Identity, workspace paths, and memory contents stay in either
   mode — they are useful as plain context regardless of whether
   tools are wired up.

   Wired through every call site:
     - Cmd.Agent passes `not A.NoTools`
     - Component passes FUseTools
     - Gateway passes `FRegistry <> nil` (covers both
       /v1/chat and /v1/chat/completions, the latter still gated
       on HasSystemMessage(Msgs) for client-supplied personas)

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Windows commands, regex allow-lists, stale-registry no-tools prompt,
sample build instructions

Five legitimate issues raised in review of the prior commit.

1. Case-sensitive path comparison on POSIX
   PathInsideDirectory used SameText, which treats
   /tmp/workspace and /tmp/Workspace as the same prefix on
   case-sensitive filesystems. If both happen to exist, a
   restricted fs_read for /tmp/Workspace/secret would pass the
   prefix check, then the actual ReadFileText opens the
   differently-cased path — sandbox bypass. New PathsEqual
   helper does the right thing per OS:
     {$IFDEF MSWINDOWS}  SameText (Windows is case-insensitive)
     {$ELSE}             A = B    (case-sensitive)

2. Relative-path bypass in shell sandbox
   HasOutsideAbsolutePath only fired on '/'-prefixed tokens, so
   `cd .. && cat secret` slipped through silently with
   restrict_to_workspace=true: no absolute path appeared, and
   RunOneShot inherited the parent's cwd so the relative paths
   resolved wherever pasclaw was launched.

   Three defenses, layered:
     a) cd / chdir / pushd / popd added to ForbiddenTokens so
        the model cannot change cwd inside the shell.
     b) New HasTraversalToken refuses any whitespace-separated
        token containing '..'. Catches `cat ../secret`,
        `(cd ..)`, `bash -c '...cd..'`, etc.
     c) RunOneShot grows a WorkingDir parameter, plumbed through
        all four platform impls (FPC POSIX/Windows via
        TProcess.CurrentDirectory; Delphi Windows + Delphi POSIX
        via ChDir/restore around TStdioProcess.Spawn). Tool_Shell
        passes CurrentWorkspace when RestrictionActive, so even
        a token the denylist missed runs from the workspace and
        cannot reach files above it via relative paths.

3. Windows command coverage
   The denylist was POSIX-shaped: rm, mkfs, dd, etc. cmd.exe and
   PowerShell users had no equivalent. Added 9 Windows tokens
   (del, erase, rd, rmdir, format, attrib, takeown, icacls,
   runas) and 17 PowerShell substrings (del /f|q|s, rd /s,
   rmdir /s, format /q, powershell -e/-en/-enc/-ec,
   -encodedcommand, iex (, invoke-expression,
   [convert]::frombase64, [text.encoding],
   .getstring([byte[], set-executionpolicy). Picoclaw's
   windowsDenyPatterns set is the reference. Patterns are
   checked unconditionally — running shell_exec on Linux today
   does not mean a portable policy should let `format c:`
   through if the same config is deployed on Windows tomorrow.

4. Regex allow-lists (FPC + Delphi)
   New unit src/pkg/tools/PasClaw.Tools.Regex.pas wraps the two
   regex engines behind one call:
     {$IFDEF FPC}   uses RegExpr.TRegExpr
     {$ELSE}        uses System.RegularExpressions.TRegEx

   Both are bundled with their respective compilers (no extra
   package install needed; FPC ships RegExpr in fcl-regexpr,
   Delphi has System.RegularExpressions since XE). Invalid
   patterns return False rather than raising so a malformed
   regex in config.json does not crash the agent — the sandbox
   layer treats False the same as "no allowlist match" and
   falls through to the workspace check.

   AllowReadPaths / AllowWritePaths now match via the regex
   wrapper instead of the in-unit glob matcher. PCRE syntax —
   ^/tmp/.*, ^/usr/(include|share)/.*, etc. README updated.
   Existing glob users migrate: '/tmp/*' becomes '^/tmp/.*'
   (anchor the prefix, replace * with .*).

5. Stale FRegistry leaks tools into "no tools" prompt
   TPasClawAgent.EnsureRegistry caches FRegistry and only
   honours FUseTools when the registry is nil. A component used
   with UseTools=True, then flipped to False, would build a
   "No tools in this session" prompt while still sending the
   cached registry to RunToolLoop — contradictory instructions
   plus actual tool access. Single source of truth is the
   registry handed to RunToolLoop. Every BuildSystemPrompt call
   site now derives the third arg from `<scope>.Registry <> nil`:
     Cmd.Agent   - Reg parameter
     Component   - Cfg.Registry
     Gateway     - LoopCfg.Registry

   PR #51's content (skill_ tool name prefix + no-tools rules +
   ToolsEnabled parameter) was also reapplied here. The PR was
   merged but the squash collapsed only PR #50's commits into
   main, so the actual changes were lost.

Sample (samples/component-console/SampleConsole.dpr):
  The header comment shipped a literal
  `fpc -Fu../../src/cmd -Fu../../src/pkg/...` instruction. The
  '...' isn't an FPC wildcard — it tried to use '...' as a
  directory name and failed. Also the sample needs ~25 unit
  search paths plus three Indy paths, not just two. Replaced
  the broken instruction with a real Makefile at
  samples/component-console/Makefile that re-uses the top-level
  UNIT_DIRS list re-rooted at the repo root. Comment now points
  at it.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants