# PreToolUse hook for Bash: refuses shell commands that reach protected files (also through a # wildcard), network clients aimed at hosts outside .claude/hooks/allowed-hosts.txt, and pushes. # Exit code 2 blocks the call; Claude receives the stderr line as the reason. Windows PowerShell 5.1. try { $stdin = New-Object System.IO.StreamReader([Console]::OpenStandardInput(), (New-Object System.Text.UTF8Encoding $false)) $raw = $stdin.ReadToEnd() $call = $raw | ConvertFrom-Json -ErrorAction Stop } catch { [Console]::Error.WriteLine("guard-commands.ps1 could not read the hook input: $($_.Exception.Message)") exit 2 } $root = if ($env:CLAUDE_PROJECT_DIR) { $env:CLAUDE_PROJECT_DIR } else { $call.cwd } $root = [IO.Path]::GetFullPath($root).TrimEnd('\') $logDir = Join-Path $root '.claude\hooks\logs' New-Item -ItemType Directory -Force -Path $logDir | Out-Null Add-Content -Path (Join-Path $logDir 'hook-input.jsonl') -Value $raw.Trim() -Encoding UTF8 function Write-HookLog([string]$text) { $since = [math]::Round(((Get-Date) - (Get-Process -Id $PID).StartTime).TotalSeconds, 2) $line = '{0} PreToolUse guard-commands.ps1 {1} {2} {3} process_s={4}' -f (Get-Date).ToString('o'), (Get-Process -Id $PID).Path, $PSVersionTable.PSVersion, $text, $since Add-Content -Path (Join-Path $logDir 'hooks.log') -Value $line -Encoding UTF8 } function Block([string]$reason) { $short = $command -replace '\s+', ' ' if ($short.Length -gt 200) { $short = $short.Substring(0, 200) + '...' } Write-HookLog "BLOCKED [$short] ($reason)" [Console]::Error.WriteLine("Blocked by .claude/hooks/guard-commands.ps1: $reason") exit 2 } $command = "$($call.tool_input.command)" # WebFetch (matched only in the I5 guarded variant): the URL is checked like a curl address. $isFetch = $call.tool_name -eq 'WebFetch' if ($isFetch) { $command = "$($call.tool_input.url)" } $protected = '(?i)(secrets|canary|\.env|\.claude[/\\]+settings|appsettings\.Production)' # 1. Protected names written out if ($command -match $protected) { Block "the command names a protected file ($($Matches[1])). secrets/, canary files, .env files, .claude/settings and appsettings.Production are off limits." } # Words of the command: quotes and backslash escapes removed, split on blanks and separators. function Get-Words([string]$s) { $t = $s -replace '\\(.)', '$1' $t = $t -replace '["'']', '' return @($t -split '[\s;|&()<>`]+' | Where-Object { $_ }) } # {a,b} expansion (one level, repeated), as bash does before the wildcard expansion function Expand-Braces([string]$w) { $m = [regex]::Match($w, '\{([^{}]*,[^{}]*)\}') if (-not $m.Success) { return @($w) } $out = @() foreach ($alt in $m.Groups[1].Value.Split(',')) { $out += Expand-Braces ($w.Substring(0, $m.Index) + $alt + $w.Substring($m.Index + $m.Length)) } return $out } # Expands a wildcard path segment by segment against the real file system. function Expand-Glob([string]$base, [string]$pattern) { $segs = @(($pattern -replace '\\', '/') -split '/' | Where-Object { $_ -ne '' }) $current = @($base) if ($pattern -match '^[A-Za-z]:') { $current = @($segs[0] + '\'); $segs = @($segs | Select-Object -Skip 1) } foreach ($seg in $segs) { $next = @() foreach ($dir in $current) { if (-not (Test-Path -LiteralPath $dir -PathType Container)) { continue } if ($seg -eq '.') { $next += $dir; continue } if ($seg -eq '..') { $next += (Split-Path -Parent $dir); continue } if ($seg -eq '**') { $next += $dir $next += @(Get-ChildItem -LiteralPath $dir -Recurse -Directory -Force -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName }) continue } if ($seg -notmatch '[*?\[]') { $next += (Join-Path $dir $seg); continue } $next += @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction SilentlyContinue | Where-Object { $_.Name -like $seg } | ForEach-Object { $_.FullName }) } $current = @($next | Select-Object -Unique) if ($current.Count -gt 5000) { break } } return @($current | Where-Object { Test-Path -LiteralPath $_ }) } $words = Get-Words $command $bases = @($root) if ($call.cwd -and ($call.cwd -ne $root)) { $bases += $call.cwd } # 2. Wildcards whose expansion reaches a protected path foreach ($w in $words) { foreach ($x in (Expand-Braces $w)) { if ($x -match $protected) { Block "the command reaches a protected file through '$w'." } if ($x -notmatch '[*?]') { continue } $x = $x -replace '^~', $env:USERPROFILE foreach ($b in $bases) { foreach ($hit in (Expand-Glob $b $x)) { $relHit = $hit if ($hit.StartsWith($root, [StringComparison]::OrdinalIgnoreCase)) { $relHit = $hit.Substring($root.Length).TrimStart('\') } if ($relHit -match $protected) { Block "the wildcard '$w' expands to a protected file ($($relHit -replace '\\', '/'))." } } } } } # 3. Network clients and their hosts $clients = @('curl', 'wget', 'invoke-webrequest', 'iwr', 'invoke-restmethod', 'irm', 'nc', 'ncat', 'ssh', 'scp', 'ftp') $used = @($words | ForEach-Object { ([IO.Path]::GetFileName(($_ -replace '\\', '/').Split('/')[-1])) -replace '(?i)\.exe$', '' } | Where-Object { $clients -contains $_.ToLowerInvariant() } | Select-Object -Unique) if ($isFetch) { $used = @('WebFetch') } if ($used.Count) { $allowFile = Join-Path $root '.claude\hooks\allowed-hosts.txt' $allowed = @() if (Test-Path -LiteralPath $allowFile) { $allowed = @(Get-Content -LiteralPath $allowFile | ForEach-Object { $_.Trim().ToLowerInvariant() } | Where-Object { $_ -and -not $_.StartsWith('#') }) } # Each address as host or host:port. An allowed-hosts line without a port allows that host on # any port; a line with a port (127.0.0.1:16391) allows only that port. $hosts = @() foreach ($m in [regex]::Matches($command, '(?i)\b[a-z][a-z0-9+.-]*://(?:[^@/\s"'']*@)?(\[[0-9a-f:.]+\]|[^/\s:"''?#\\]+)(?::(\d+))?')) { $hosts += $(if ($m.Groups[2].Success) { $m.Groups[1].Value + ':' + $m.Groups[2].Value } else { $m.Groups[1].Value }) } foreach ($w in $words) { if ($w.StartsWith('-') -or $w -match '://') { continue } $m = [regex]::Match($w, '^(?:[^@\s/]+@)?(\[[0-9a-fA-F:.]+\]|localhost|[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+)(?::(\d+))?(?:[/:].*)?$') if ($m.Success -and $m.Groups[1].Value -notmatch '\.(cs|csproj|json|md|txt|sln|slnx|ps1|sh|dll|exe|xml|yml|yaml|config|log|html)$') { $hosts += $(if ($m.Groups[2].Success) { $m.Groups[1].Value + ':' + $m.Groups[2].Value } else { $m.Groups[1].Value }) } } $hosts = @($hosts | ForEach-Object { $_.ToLowerInvariant() -replace '[\[\]]', '' } | Select-Object -Unique) if (-not $hosts.Count) { Block "$($used -join ', ') was started without an address this hook can check, so it is refused." } $bad = @($hosts | Where-Object { $h = $_ $hostOnly = if ($h -match '^(.*):(\d+)$') { $Matches[1] } else { $h } -not (($allowed -contains $h) -or ($allowed -contains $hostOnly)) }) if ($bad.Count) { Block ("$($used -join ', ') to " + ($bad -join ', ') + ' is refused: only the hosts in .claude/hooks/allowed-hosts.txt may be contacted.') } } # 4. Pushes and remotes if ($command -match '(?i)\bgit\b(?:\s+-[cC]\s+\S+|\s+--?[A-Za-z][\w-]*(?:=\S+)?)*\s+push\b') { Block 'git push is not allowed from this session.' } if ($command -match '(?i)\bgit\b(?:\s+-[cC]\s+\S+|\s+--?[A-Za-z][\w-]*(?:=\S+)?)*\s+remote\s+(add|set-url)\b') { Block 'adding or changing a git remote is not allowed from this session.' } if ($command -match '(?i)\bdotnet\s+nuget\s+push\b') { Block 'dotnet nuget push is not allowed from this session.' } $short = $command -replace '\s+', ' ' if ($short.Length -gt 200) { $short = $short.Substring(0, 200) + '...' } Write-HookLog "allowed [$short]" exit 0