Skip to content

hookSecurity

Block Sudo Commands

A Claude Code hook that blocks any Bash command starting with sudo or doas and tells the agent to hand the exact command to you for a manual run.

npx workspacetemplates add block-sudo-commands --tool claude-code

Writes 1 file to .claude/

.claude/settings.jsonmerge into your file16 lines · 932 BFile
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{let j={};try{j=JSON.parse(d)||{}}catch(e){process.exit(0)}const i=j.tool_input||{};const q=String.fromCharCode(34),sq=String.fromCharCode(39),bs=String.fromCharCode(92),nl=String.fromCharCode(10);const c=String(i.command||'');const first=c.split(/[;&|]+/).some(s=>/^[(]?(sudo|doas)([ ]|$)/.test(s.trim().replace(/^([A-Za-z_]+=[^ ]*[ ]+|(time|nohup|exec|env|command|xargs)[ ]+)+/,'')));const nested=/(^|[ ])(a|ba|da|z)?sh[ ]+-c[ ]+.?(sudo|doas)[ ]/.test(c);if(first||nested){console.error('Blocked: sudo needs a person. Print the exact command, say why it needs root, and ask the user to run it in their own terminal.');process.exit(2)}})\"",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

What it does

Root access should be a decision you make, not a side effect of a long task. This PreToolUse hook looks at the first word of every command in a chain and refuses sudo and doas, even after env assignments or time and nohup prefixes.

It also catches sudo tucked inside a sh -c string. The message asks the agent to print the command and the reason, so you can run it in your own terminal when it is truly needed.

Example

you › Install the missing library with sudo apt install libpq-dev.

agent › Blocked. The agent prints the apt command, explains why root is needed and waits for you to run it yourself.

Questions

Does it stop the word sudo inside a commit message?
No. Only a command that starts with sudo or doas, or a sh -c payload that does, is refused. Text elsewhere on the line is ignored.
Can I allow one safe sudo command?
Edit the pattern to skip a command you trust, or run that single command in your own shell as the message suggests.
  • Block Chmod 777

    HookSecurity

    Free
  • Block Curl Pipe Shell

    HookSecurity

    Free
  • Block Dangerous Commands

    HookSecurity

    Free
  • Block Env in Git Add

    HookSecurity

    Free