CertSafari
    Anthropic Claude Certified Developer – Foundations (CCDV-F) - December 7 onwards· Lessons

    Domain 7 · Lesson 20/24

    Deterministic guardrails: permission rules, hooks and sandboxing

    Deterministic Guardrails and Least Privilege

    21 min read
    2.67% of exam
    6 sources
    Published 18 Nov 2026
    Docs as of 18 Nov 2026

    What you will be able to do

    • Explain why a rule written in CLAUDE.md or a system prompt cannot stop a destructive action, and where enforcement has to live instead
    • Tell apart a bare-name deny rule, which takes a tool out of Claude's context, and a scoped deny rule, which blocks only the calls it matches
    • Write a PreToolUse hook that denies a destructive command before it runs, and say why PostToolUse and exit 0 cannot do that job
    • Identify the command forms a pattern rule misses and close them with OS-level sandboxing
    • Apply least privilege to an agent deployment by limiting its filesystem, network, capabilities and credentials

    Key concept

    Deterministic enforcement at the tool boundary — A guardrail is deterministic when code outside the model decides whether an action runs, at a point the model's output cannot skip. Examples are a permission rule, a PreToolUse hook or an OS sandbox. However the model was persuaded, the check returns the same answer for the same call.

    1.Why an instruction is not a guardrail

    An instruction such as "never run recursive deletes" can only shape what the model decides. It cannot stop the model from deciding otherwise. A CLAUDE.md file is loaded into context like any other text, and a poisoned README, web page or tool result lands in that same context. Once injected text has argued the model into running rm -rf, nothing written earlier in the prompt sits between that decision and the shell. Phrasing the rule more firmly or placing it in the system prompt gives it more weight. It is still only text the model reads. How injected instructions reach the model, and how to screen for them, is covered in prompt injection defense. This lesson starts from the assumption that the screening sometimes fails.

    A guardrail has to sit in code that runs between the model's tool call and its effect. Claude Code and the Agent SDK provide three such layers, and each catches something the others miss:

    • Permission rules decide whether a call runs, prompts or is blocked, by matching the tool name and its arguments.
    • Hooks run your own program on the call's JSON before it executes and can return a deny decision.
    • Sandboxing and container isolation limit what any process can reach at the operating-system level, whatever the command looks like.

    Least privilege is how you configure all three. Give the agent only the tools, paths, hosts and credentials its task needs, so that even an action the guardrails fail to catch can reach very little. The sections below build these layers up in order. Each layer answers a weakness of the one before it.

    Checkpoint 1 of 9· Check yourself

    Your agent's CLAUDE.md says "never run recursive deletes". A poisoned README in the repo then persuades Claude to call Bash with rm -rf ./src. Which change would stop that call from running, however convincing the injected text is?

    Sources12

    2.Permission rules: bare names versus scoped patterns

    Permission rules come in three kinds. Allow rules let a tool run without approval, ask rules force a confirmation prompt, and deny rules prevent the tool from being used. You place them in the permissions block of a settings file. Rules in managed policy settings apply across the whole organization and are controlled by administrators.

    A permissions block that pre-approves build and commit commands but denies pushesjson
    {
      "permissions": {
        "allow": [
          "Bash(npm run *)",
          "Bash(git commit *)"
        ],
        "deny": [
          "Bash(git push *)"
        ]
      }
    }

    A rule's shape decides which layer it acts on. A bare tool name in a deny list works on availability: the tool leaves Claude's context, so for the rest of the session the model has no Bash tool to call, however it was instructed. This is least privilege in its strongest form. A scoped rule such as Bash(rm *) works on permission. Bash stays available, and calls whose text matches the pattern are denied.

    How the form of a deny rule changes its effect
    Deny entryLayerWhat the model experiences
    BashAvailabilityThe Bash tool is gone from its context. It cannot attempt any shell command
    Bash(rm *)PermissionBash is still offered. Calls matching rm * as written are denied, and all other commands go through the normal flow
    mcp__*PermissionCalls to tools whose names match mcp__* are denied

    Do not confuse deny rules with the built-in set of read-only Bash commands. That set decides which commands run without an approval prompt when no rule applies. It has no bearing on what a deny rule blocks. A bare Bash deny has no exception for ls or cat, and it does not single out compound commands. The tool simply stops being available.

    Checkpoint 2 of 9· Fill the gap

    This settings block should let Claude run build and commit commands without approval, and stop it from pushing. Pushing must not just trigger a confirmation prompt. Which key goes in the blank?

    {
      "permissions": {
        "allow": [
          "Bash(npm run *)",
          "Bash(git commit *)"
        ],
        " ? ": [
          "Bash(git push *)"
        ]
      }
    }

    Checkpoint 3 of 9· Exam question

    A security engineer adds the bare tool name Bash to the deny list in managed settings. What is the effect on the agent?

    Sources341

    3.PreToolUse hooks: a deny decision before the call runs

    A PreToolUse hook is your own program, and Claude Code runs it before every matching tool call. The hook receives the call as JSON on stdin, including tool_name and tool_input. For Bash, the shell command is in tool_input.command. The hook inspects the call and can return permissionDecision: "deny". When it does, the call never executes. The model's reasoning plays no part in that outcome: the script returns the same answer for the same input whatever argument talked the model into the call.

    A PreToolUse hook script that denies any Bash command containing rm -rf and otherwise makes no decisionbash
    #!/bin/bash
    # .claude/hooks/block-rm.sh
    COMMAND=$(jq -r '.tool_input.command')
    
    if echo "$COMMAND" | grep -q 'rm -rf'; then
      jq -n '{
        hookSpecificOutput: {
          hookEventName: "PreToolUse",
          permissionDecision: "deny",
          permissionDecisionReason: "Destructive command blocked by hook"
        }
      }'
    else
      exit 0  # no decision; normal permission flow applies
    fi

    To register the script, put it under PreToolUse with "matcher": "Bash". The matcher is an exact tool name, a |-separated list of names, or a regular expression such as mcp__.*__write.*. A script can also block without printing JSON: write a reason to stderr and exit with code 2. Depending on the event, that reason goes back to Claude as feedback, so it can adjust its approach.

    Exit code 0 is a common trap. It does not approve the call. It means the hook has no decision, and the call continues through the normal permission flow, including any deny or ask rules. A hook therefore adds a check on top of your permission rules. It cannot quietly open a gap in them.

    The event you choose matters as much as the logic. PostToolUse fires after a tool call succeeds. That works for linting or logging, but by then the directory is already deleted. A reviewer subagent, or a hook of type prompt or agent, returns its verdict from a model. That is useful for judgement calls, but it brings back the very model judgement an injection might sway. When an action must be impossible rather than merely discouraged, use a command hook on PreToolUse. Define it in managed policy settings when it must apply to the whole organization, not to one developer's machine.

    Where hook choices land on the deterministic scale
    ChoiceWhen it actsCan it stop a destructive Bash call?
    PreToolUse command hook returning denyBefore a tool call executesYes. The call never runs
    PreToolUse hook that exits 2Before a tool call executesYes. The stderr text goes back as feedback
    PreToolUse hook that exits 0Before a tool call executesNo. There is no decision, and the normal permission flow decides
    PostToolUse hookAfter a tool call succeedsNo. The effect has already happened
    prompt or agent hook typeBefore or after, depending on the eventOnly as reliably as a model's verdict

    Checkpoint 4 of 9· Match them up

    A team is comparing ways to stop Claude from running rm -rf through Bash. Match each hook setup to what happens when Claude attempts that command.

    Tap a term, then the definition that fits it.

    Checkpoint 5 of 9· Exam question

    A repository's CLAUDE.md says "never run recursive deletes". A poisoned README still convinces the agent to run rm -rf on the project. Which change makes that action impossible no matter what the model decides?

    Sources15

    4.Where pattern matching leaks, and the sandbox that closes it

    A content pattern matches the text of a command, not what the command does. So the same action can get past a pattern once it is written differently. An injected instruction only has to find one form the rule missed.

    Forms a scoped Bash deny rule stops and forms it lets through
    RuleStopsDoesn't stop
    Bash(curl *)curl https://example.com/usr/bin/curl https://example.com, sh -c 'curl https://example.com'
    Bash(rm *)rm -rf build//bin/rm -rf build/, bash -c 'rm -rf build/'
    Bash(git push *)git push origin maingit -C . push origin main, git -c push.default=current push origin main

    The tempting fixes don't close the gap. Removing the space, as in Bash(rm*), only widens the literal prefix: the rule then also matches rmdir or any other command whose name starts with rm. It still misses bash -c 'rm ...'. Adding a deny entry for each known variant (/bin/rm, sh -c, find -delete) stays one form behind, because exec wrappers such as watch and flock, git's -C and -c options, and a find action can each reach the same effect. A grep inside a hook script works on the same command text and has the same weakness. Asking the agent in CLAUDE.md to avoid wrapper shells brings back the instruction-only defense the first section ruled out.

    The sandbox enforces the boundary below the command text. With sandboxing on, Bash commands run inside an OS-level boundary: Seatbelt on macOS, bubblewrap on Linux and WSL2. By default, writes are allowed only in the working directory, a per-user temp directory, and any directories you've added. You can narrow that with filesystem.allowWrite and filesystem.denyWrite. Network connections have no direct route out. They pass through a proxy that checks each host against network.allowedDomains, and that list starts empty. Restrict writes to the build directory, and rm -rf ../data fails whether it is typed directly, wrapped in bash -c or run as /bin/rm. The kernel refuses the write, so the wording of the command no longer matters.

    Two settings decide whether the sandbox holds under pressure. When a command fails in the sandbox, Claude can ask to retry it unsandboxed. Setting allowUnsandboxedCommands to false removes that fallback. Commands listed in excludedCommands always run outside the sandbox, so keep that list short. Your existing rules keep working in sandboxed mode: a command in a form a Bash deny rule matches is still blocked.

    Checkpoint 6 of 9· Check yourself

    An injected instruction got a cleanup agent to run /bin/rm -rf ../data, which slipped past the team's Bash(rm *) deny rule. The requirement is that ../data cannot be deleted no matter how the command is written. Which change meets it?

    Checkpoint 7 of 9· Exam question

    A deny rule for Bash(rm *) is in place. After a prompt injection, the agent runs bash -c 'rm -rf build/ ../data' and the files are deleted. Which addition enforces the restriction regardless of how the command is written?

    Sources36

    5.Layering: what each guardrail does not cover

    No single layer covers every tool, so you need all of them. The Bash sandbox constrains shell commands only. Built-in file and web tools such as Read, Edit, Write, WebFetch and WebSearch follow permission rules instead: a denyRead entry does not stop the Read tool, and allowedDomains does not limit WebFetch. Some other processes Claude Code starts run with your full access, not inside the sandbox. These include command hooks, local MCP servers and helper commands such as apiKeyHelper.

    Which layer governs which kind of action
    ActionGoverned byGap to cover with another layer
    Bash commandSandbox, plus Bash permission rules and PreToolUse hooksexcludedCommands and approved unsandboxed retries run outside the sandbox
    Read, Edit, WritePermission rules and PreToolUse hooks (matcher Edit|Write)Sandbox filesystem settings do not apply to them
    WebFetchPermission rules such as WebFetch(domain:example.com)network.allowedDomains does not limit it
    MCP tool callPermission rules (mcp__*) and hooks matching mcp__.*Local MCP servers run with full access, outside the sandbox

    Some built-in checks look like guardrails but are only gates. With the default permission mode, an rm or rmdir that Claude Code recognizes as removing the working directory or another critical path needs approval, even when an allow rule matches it. That approval is a prompt, though, not a boundary. To limit what the agent can actually write, you still need filesystem controls.

    Checkpoint 8 of 9· Match them up

    The sandbox is on, writes are limited to the working directory, and allowUnsandboxedCommands is false. For each action, match what governs it or what gap it exposes.

    Tap a term, then the definition that fits it.

    Sources62

    6.Least privilege for a deployed agent

    In a deployed agent, least privilege means the container itself grants almost nothing. The sandbox's defaults are not tight enough on their own. Reads still cover most of the machine, including ~/.ssh and ~/.aws/credentials, and commands inherit Claude Code's environment variables, including any secrets in them. For a production agent, start from a container that denies everything and add back only what the task needs.

    A hardened container launch for an agent: no capabilities, no network, read-only root and code, non-root userbash
    docker run \
      --cap-drop ALL \
      --security-opt no-new-privileges \
      --security-opt seccomp=/path/to/seccomp-profile.json \
      --read-only \
      --tmpfs /tmp:rw,noexec,nosuid,size=100m \
      --tmpfs /home/agent:rw,noexec,nosuid,size=500m \
      --network none \
      --memory 2g \
      --cpus 2 \
      --pids-limit 600 \
      --user 1000:1000 \
      -v /path/to/code:/workspace:ro \
      -v /var/run/proxy.sock:/var/run/proxy.sock:ro \
      agent-image
    What each restriction takes away from the agent
    OptionPrivilege removed
    --cap-drop ALLLinux capabilities like NET_ADMIN and SYS_ADMIN that could enable privilege escalation
    --network noneAny route to external networks
    --read-onlyPersisting changes to the container's root filesystem
    -v ...:/workspace:roModifying the code, which the agent can still analyze
    --user 1000:1000Running as root
    --pids-limit 600Fork bombs from unbounded processes and threads

    The only way out of that container is the mounted proxy socket. Outside the container, run the agent in a private subnet with egress blocked except to your proxy. Give its service account minimal IAM permissions, and route sensitive access through the proxy so it can enforce an endpoint allowlist and log every request. Don't mount host directories like ~/.ssh, ~/.aws or ~/.config into the container. Keeping keys out of what the agent can reach at all is covered in credential handling.

    Checkpoint 9 of 9· Check yourself

    Before shipping a production agent, an engineer suggests skipping the hardened container. They would run it with Claude Code's sandbox turned on and its default settings left unchanged. What would those defaults still leave within the agent's reach?

    Sources62

    Practise it for real

    Start Claude Code with the Bash sandbox enforced and no unsandboxed fallback, then confirm that writes outside the working directory and direct network routes are refused at the OS level.

    1. 1.On Linux or WSL2, install the sandbox dependencies: sudo apt-get install bubblewrap socat (or sudo dnf install bubblewrap socat). On macOS, skip this step.

      Why: bubblewrap enforces filesystem isolation, and socat relays network traffic through the sandbox proxy. macOS uses the built-in Seatbelt framework.

      You should see: Both packages install. If /sandbox later shows only a Dependencies tab, something is still missing.

    2. 2.Launch: claude --settings '{"sandbox": {"enabled": true, "allowUnsandboxedCommands": false}}'

      Why: This turns the sandbox on and removes the option of retrying a failed command outside it.

      You should see: The session starts. Running /sandbox shows the resolved config under its Config tab.

    3. 3.Ask Claude to run: touch ~/sandbox-probe

      Why: Your home directory is outside the default write boundary, so this tests the filesystem layer.

      You should see: The command fails with Operation not permitted on macOS, or Read-only file system on Linux and WSL2.

    4. 4.Ask Claude to run: curl --noproxy '*' https://example.com

      Why: This tries to go around the sandbox proxy, which is the only network path.

      You should see: The command fails with Could not resolve host, because there is no route around the proxy.

    Stuck? Get a nudge

    If the touch succeeds, check whether the command matched excludedCommands, or whether the session picked up a settings file that sets allowUnsandboxedCommands back to true.

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “When a CLAUDE.md or .claude/rules/*.md file is loaded into context.”
      ↩︎ Why an instruction is not a guardrail
      “Managed policy settings | Organization-wide | Yes, admin-controlled”
      ↩︎ Permission rules: bare names versus scoped patterns
      “Before a tool call executes. Can block it”
      ↩︎ PreToolUse hooks: a deny decision before the call runs
      “send a prompt to a Claude model for single-turn evaluation. The model returns its decision as JSON.”
      ↩︎ PreToolUse hooks: a deny decision before the call runs
      “Before a tool call executes. Can block it”
      ↩︎ Key concept
      “After a tool call succeeds”
      ↩︎ Exam trap 3
      “Before a tool call executes. Can block it”
      ↩︎ Checkpoint
    2. 2.
      “Permission rules decide whether a tool call runs, is blocked, or asks for approval first.”
      ↩︎ Why an instruction is not a guardrail
      “This is a permission gate, not a sandbox. To control what the agent can write, use filesystem controls.”
      ↩︎ Layering: what each guardrail does not cover
      “Assign minimal IAM permissions to the agent’s service account, routing sensitive access through the proxy where possible”
      ↩︎ Least privilege for a deployed agent
      “Removes Linux capabilities like NET_ADMIN and SYS_ADMIN that could enable privilege escalation”
      ↩︎ Least privilege for a deployed agent
    3. 3.
      “Deny rules prevent Claude Code from using the specified tool.”
      ↩︎ Permission rules: bare names versus scoped patterns
      “The space before a trailing * is part of the rule.”
      ↩︎ Where pattern matching leaks, and the sandbox that closes it
      “The space before a trailing * is part of the rule.”
      ↩︎ Exam trap 4
    4. 4.
      “A bare built-in name such as "Bash" removes the tool from Claude’s context.”
      ↩︎ Permission rules: bare names versus scoped patterns
      “A bare built-in name such as "Bash" removes the tool from Claude’s context.”
      ↩︎ Exam trap 1
      “A scoped rule such as "Bash(rm *)" leaves the tool in context and denies the calls that match it as written.”
      ↩︎ Prediction
    5. 5.
      “if you exit 0 from a PreToolUse hook, the tool call still goes through the normal permission flow, because exit 0 doesn’t approve it.”
      ↩︎ PreToolUse hooks: a deny decision before the call runs
      “Exit 2: write a reason to stderr. Depending on the event, Claude receives it as feedback so it can adjust”
      ↩︎ PreToolUse hooks: a deny decision before the call runs
      “if you exit 0 from a PreToolUse hook, the tool call still goes through the normal permission flow, because exit 0 doesn’t approve it.”
      ↩︎ Exam trap 2
      “if you exit 0 from a PreToolUse hook, the tool call still goes through the normal permission flow, because exit 0 doesn’t approve it”
      ↩︎ Checkpoint
    6. 6.
      “bubblewrap: the unprivileged sandboxing tool that enforces filesystem isolation”
      ↩︎ Where pattern matching leaks, and the sandbox that closes it
      “Connections go through a proxy on your machine that checks each host against your allowed domains, which start empty.”
      ↩︎ Where pattern matching leaks, and the sandbox that closes it
      “Unsandboxed retries: Claude can ask to run a command unsandboxed, usually after it fails in the sandbox”
      ↩︎ Where pattern matching leaks, and the sandbox that closes it
      “A command in a form that a Bash deny rule matches is still blocked”
      ↩︎ Where pattern matching leaks, and the sandbox that closes it
      “A denyRead entry doesn’t stop the Read tool, and allowedDomains doesn’t limit WebFetch”
      ↩︎ Layering: what each guardrail does not cover
      “Most of the machine, including credential files such as ~/.ssh and ~/.aws/credentials”
      ↩︎ Least privilege for a deployed agent
      “Built-in file and web tools: tools such as Read, Edit, Write, WebFetch, and WebSearch follow permission rules instead.”
      ↩︎ Exam trap 5
      “Restrict the files and network hosts Claude Code’s shell commands can reach with the built-in sandbox.”
      ↩︎ Checkpoint
      “A denyRead entry doesn't stop the Read tool, and allowedDomains doesn't limit WebFetch”
      ↩︎ Checkpoint

    Ready to test yourself?

    Practise Anthropic Claude Certified Developer – Foundations (CCDV-F) - December 7 onwards in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.