|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# Tool Guardian Hook |
| 4 | +# Blocks dangerous tool operations (destructive file ops, force pushes, DB drops, |
| 5 | +# etc.) before the Copilot coding agent executes them. |
| 6 | +# |
| 7 | +# Environment variables: |
| 8 | +# GUARD_MODE - "warn" (log only) or "block" (exit non-zero on threats) (default: block) |
| 9 | +# SKIP_TOOL_GUARD - "true" to disable entirely (default: unset) |
| 10 | +# TOOL_GUARD_LOG_DIR - Directory for guard logs (default: logs/copilot/tool-guardian) |
| 11 | +# TOOL_GUARD_ALLOWLIST - Comma-separated patterns to skip (default: unset) |
| 12 | + |
| 13 | +set -euo pipefail |
| 14 | + |
| 15 | +# --------------------------------------------------------------------------- |
| 16 | +# Early exit if disabled |
| 17 | +# --------------------------------------------------------------------------- |
| 18 | +if [[ "${SKIP_TOOL_GUARD:-}" == "true" ]]; then |
| 19 | + exit 0 |
| 20 | +fi |
| 21 | + |
| 22 | +# --------------------------------------------------------------------------- |
| 23 | +# Read tool invocation from stdin (JSON with toolName + toolInput) |
| 24 | +# --------------------------------------------------------------------------- |
| 25 | +INPUT=$(cat) |
| 26 | + |
| 27 | +MODE="${GUARD_MODE:-block}" |
| 28 | +LOG_DIR="${TOOL_GUARD_LOG_DIR:-logs/copilot/tool-guardian}" |
| 29 | +TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ") |
| 30 | + |
| 31 | +mkdir -p "$LOG_DIR" |
| 32 | +LOG_FILE="$LOG_DIR/guard.log" |
| 33 | + |
| 34 | +# --------------------------------------------------------------------------- |
| 35 | +# Extract tool name and input text |
| 36 | +# --------------------------------------------------------------------------- |
| 37 | +TOOL_NAME="" |
| 38 | +TOOL_INPUT="" |
| 39 | + |
| 40 | +if command -v jq &>/dev/null; then |
| 41 | + TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.toolName // empty' 2>/dev/null || echo "") |
| 42 | + TOOL_INPUT=$(printf '%s' "$INPUT" | jq -r '.toolInput // empty' 2>/dev/null || echo "") |
| 43 | +fi |
| 44 | + |
| 45 | +# Fallback: extract with grep/sed if jq unavailable or fields empty |
| 46 | +if [[ -z "$TOOL_NAME" ]]; then |
| 47 | + TOOL_NAME=$(printf '%s' "$INPUT" | grep -oE '"toolName"\s*:\s*"[^"]*"' | head -1 | sed 's/.*"toolName"\s*:\s*"//;s/"//') |
| 48 | +fi |
| 49 | +if [[ -z "$TOOL_INPUT" ]]; then |
| 50 | + TOOL_INPUT=$(printf '%s' "$INPUT" | grep -oE '"toolInput"\s*:\s*"[^"]*"' | head -1 | sed 's/.*"toolInput"\s*:\s*"//;s/"//') |
| 51 | +fi |
| 52 | + |
| 53 | +# Combine for pattern matching |
| 54 | +COMBINED="${TOOL_NAME} ${TOOL_INPUT}" |
| 55 | + |
| 56 | +# --------------------------------------------------------------------------- |
| 57 | +# Parse allowlist |
| 58 | +# --------------------------------------------------------------------------- |
| 59 | +ALLOWLIST=() |
| 60 | +if [[ -n "${TOOL_GUARD_ALLOWLIST:-}" ]]; then |
| 61 | + IFS=',' read -ra ALLOWLIST <<< "$TOOL_GUARD_ALLOWLIST" |
| 62 | +fi |
| 63 | + |
| 64 | +is_allowlisted() { |
| 65 | + local text="$1" |
| 66 | + for pattern in "${ALLOWLIST[@]}"; do |
| 67 | + pattern=$(printf '%s' "$pattern" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') |
| 68 | + [[ -z "$pattern" ]] && continue |
| 69 | + if [[ "$text" == *"$pattern"* ]]; then |
| 70 | + return 0 |
| 71 | + fi |
| 72 | + done |
| 73 | + return 1 |
| 74 | +} |
| 75 | + |
| 76 | +# Check allowlist early — if the combined text matches, skip all scanning |
| 77 | +if [[ ${#ALLOWLIST[@]} -gt 0 ]] && is_allowlisted "$COMBINED"; then |
| 78 | + printf '{"timestamp":"%s","event":"guard_skipped","reason":"allowlisted","tool":"%s"}\n' \ |
| 79 | + "$TIMESTAMP" "$TOOL_NAME" >> "$LOG_FILE" |
| 80 | + exit 0 |
| 81 | +fi |
| 82 | + |
| 83 | +# --------------------------------------------------------------------------- |
| 84 | +# Threat patterns (6 categories, ~20 patterns) |
| 85 | +# |
| 86 | +# Each entry: "CATEGORY:::SEVERITY:::REGEX:::SUGGESTION" |
| 87 | +# Uses ::: as delimiter to avoid conflicts with regex pipe characters |
| 88 | +# --------------------------------------------------------------------------- |
| 89 | +PATTERNS=( |
| 90 | + # Destructive file operations |
| 91 | + "destructive_file_ops:::critical:::rm -rf /:::Use targeted 'rm' on specific paths instead of root" |
| 92 | + "destructive_file_ops:::critical:::rm -rf ~:::Use targeted 'rm' on specific paths instead of home directory" |
| 93 | + "destructive_file_ops:::critical:::rm -rf \.:::Use targeted 'rm' on specific files instead of current directory" |
| 94 | + "destructive_file_ops:::critical:::rm -rf \.\.:::Never remove parent directories recursively" |
| 95 | + "destructive_file_ops:::critical:::(rm|del|unlink).*\.env:::Use 'mv' to back up .env files before removing" |
| 96 | + "destructive_file_ops:::critical:::(rm|del|unlink).*\.git[^i]:::Never delete .git directory — use 'git' commands to manage repo state" |
| 97 | + |
| 98 | + # Destructive git operations |
| 99 | + "destructive_git_ops:::critical:::git push --force.*(main|master):::Use 'git push --force-with-lease' or push to a feature branch" |
| 100 | + "destructive_git_ops:::critical:::git push -f.*(main|master):::Use 'git push --force-with-lease' or push to a feature branch" |
| 101 | + "destructive_git_ops:::high:::git reset --hard:::Use 'git stash' to preserve changes, or 'git reset --soft'" |
| 102 | + "destructive_git_ops:::high:::git clean -fd:::Use 'git clean -n' (dry run) first to preview what will be deleted" |
| 103 | + |
| 104 | + # Database destruction |
| 105 | + "database_destruction:::critical:::DROP TABLE:::Use 'ALTER TABLE' or create a migration with rollback support" |
| 106 | + "database_destruction:::critical:::DROP DATABASE:::Create a backup first; consider revoking DROP privileges" |
| 107 | + "database_destruction:::critical:::TRUNCATE:::Use 'DELETE FROM ... WHERE' with a condition for safer data removal" |
| 108 | + "database_destruction:::high:::DELETE FROM [a-zA-Z_]+ *;:::Add a WHERE clause to 'DELETE FROM' to avoid deleting all rows" |
| 109 | + |
| 110 | + # Permission abuse |
| 111 | + "permission_abuse:::high:::chmod 777:::Use 'chmod 755' for directories or 'chmod 644' for files" |
| 112 | + "permission_abuse:::high:::chmod -R 777:::Use specific permissions ('chmod -R 755') and limit scope" |
| 113 | + |
| 114 | + # Network exfiltration |
| 115 | + "network_exfiltration:::critical:::curl.*\|.*bash:::Download the script first, review it, then execute" |
| 116 | + "network_exfiltration:::critical:::wget.*\|.*sh:::Download the script first, review it, then execute" |
| 117 | + "network_exfiltration:::high:::curl.*--data.*@:::Review what data is being sent before using 'curl --data @file'" |
| 118 | + |
| 119 | + # System danger |
| 120 | + "system_danger:::high:::sudo :::Avoid 'sudo' — run commands with the least privilege needed" |
| 121 | + "system_danger:::high:::npm publish:::Use 'npm publish --dry-run' first to verify package contents" |
| 122 | +) |
| 123 | + |
| 124 | +# --------------------------------------------------------------------------- |
| 125 | +# Escape a string for safe JSON embedding |
| 126 | +# --------------------------------------------------------------------------- |
| 127 | +json_escape() { |
| 128 | + printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g; s/ /\\t/g' |
| 129 | +} |
| 130 | + |
| 131 | +# --------------------------------------------------------------------------- |
| 132 | +# Scan combined text against threat patterns |
| 133 | +# --------------------------------------------------------------------------- |
| 134 | +THREATS=() |
| 135 | +THREAT_COUNT=0 |
| 136 | + |
| 137 | +for entry in "${PATTERNS[@]}"; do |
| 138 | + category="${entry%%:::*}" |
| 139 | + rest="${entry#*:::}" |
| 140 | + severity="${rest%%:::*}" |
| 141 | + rest="${rest#*:::}" |
| 142 | + regex="${rest%%:::*}" |
| 143 | + suggestion="${rest#*:::}" |
| 144 | + |
| 145 | + if printf '%s\n' "$COMBINED" | grep -qiE "$regex" 2>/dev/null; then |
| 146 | + local_match=$(printf '%s\n' "$COMBINED" | grep -oiE "$regex" 2>/dev/null | head -1) |
| 147 | + THREATS+=("${category} ${severity} ${local_match} ${suggestion}") |
| 148 | + THREAT_COUNT=$((THREAT_COUNT + 1)) |
| 149 | + fi |
| 150 | +done |
| 151 | + |
| 152 | +# --------------------------------------------------------------------------- |
| 153 | +# Output and logging |
| 154 | +# --------------------------------------------------------------------------- |
| 155 | +if [[ $THREAT_COUNT -gt 0 ]]; then |
| 156 | + echo "" |
| 157 | + echo "🛡️ Tool Guardian: $THREAT_COUNT threat(s) detected in '$TOOL_NAME' invocation" |
| 158 | + echo "" |
| 159 | + printf " %-24s %-10s %-40s %s\n" "CATEGORY" "SEVERITY" "MATCH" "SUGGESTION" |
| 160 | + printf " %-24s %-10s %-40s %s\n" "--------" "--------" "-----" "----------" |
| 161 | + |
| 162 | + # Build JSON findings array |
| 163 | + FINDINGS_JSON="[" |
| 164 | + FIRST=true |
| 165 | + for threat in "${THREATS[@]}"; do |
| 166 | + IFS=$'\t' read -r category severity match suggestion <<< "$threat" |
| 167 | + |
| 168 | + # Truncate match for display |
| 169 | + display_match="$match" |
| 170 | + if [[ ${#match} -gt 38 ]]; then |
| 171 | + display_match="${match:0:35}..." |
| 172 | + fi |
| 173 | + printf " %-24s %-10s %-40s %s\n" "$category" "$severity" "$display_match" "$suggestion" |
| 174 | + |
| 175 | + if [[ "$FIRST" != "true" ]]; then |
| 176 | + FINDINGS_JSON+="," |
| 177 | + fi |
| 178 | + FIRST=false |
| 179 | + FINDINGS_JSON+="{\"category\":\"$(json_escape "$category")\",\"severity\":\"$(json_escape "$severity")\",\"match\":\"$(json_escape "$match")\",\"suggestion\":\"$(json_escape "$suggestion")\"}" |
| 180 | + done |
| 181 | + FINDINGS_JSON+="]" |
| 182 | + |
| 183 | + echo "" |
| 184 | + |
| 185 | + # Write structured log entry |
| 186 | + printf '{"timestamp":"%s","event":"threats_detected","mode":"%s","tool":"%s","threat_count":%d,"threats":%s}\n' \ |
| 187 | + "$TIMESTAMP" "$MODE" "$(json_escape "$TOOL_NAME")" "$THREAT_COUNT" "$FINDINGS_JSON" >> "$LOG_FILE" |
| 188 | + |
| 189 | + if [[ "$MODE" == "block" ]]; then |
| 190 | + echo "🚫 Operation blocked: resolve the threats above or adjust TOOL_GUARD_ALLOWLIST." |
| 191 | + echo " Set GUARD_MODE=warn to log without blocking." |
| 192 | + exit 1 |
| 193 | + else |
| 194 | + echo "⚠️ Threats logged in warn mode. Set GUARD_MODE=block to prevent dangerous operations." |
| 195 | + fi |
| 196 | +else |
| 197 | + # Log clean result |
| 198 | + printf '{"timestamp":"%s","event":"guard_passed","mode":"%s","tool":"%s"}\n' \ |
| 199 | + "$TIMESTAMP" "$MODE" "$(json_escape "$TOOL_NAME")" >> "$LOG_FILE" |
| 200 | +fi |
| 201 | + |
| 202 | +exit 0 |
0 commit comments