validate-bash.sh 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/bin/bash
  2. # Example PreToolUse hook for validating Bash commands
  3. # This script demonstrates bash command validation patterns
  4. set -euo pipefail
  5. # Read input from stdin
  6. input=$(cat)
  7. # Extract command
  8. command=$(echo "$input" | jq -r '.tool_input.command // empty')
  9. # Validate command exists
  10. if [ -z "$command" ]; then
  11. echo '{"continue": true}' # No command to validate
  12. exit 0
  13. fi
  14. # Check for obviously safe commands (quick approval)
  15. if [[ "$command" =~ ^(ls|pwd|echo|date|whoami)(\s|$) ]]; then
  16. exit 0
  17. fi
  18. # Check for destructive operations
  19. if [[ "$command" == *"rm -rf"* ]] || [[ "$command" == *"rm -fr"* ]]; then
  20. echo '{"hookSpecificOutput": {"permissionDecision": "deny"}, "systemMessage": "Dangerous command detected: rm -rf"}' >&2
  21. exit 2
  22. fi
  23. # Check for other dangerous commands
  24. if [[ "$command" == *"dd if="* ]] || [[ "$command" == *"mkfs"* ]] || [[ "$command" == *"> /dev/"* ]]; then
  25. echo '{"hookSpecificOutput": {"permissionDecision": "deny"}, "systemMessage": "Dangerous system operation detected"}' >&2
  26. exit 2
  27. fi
  28. # Check for privilege escalation
  29. if [[ "$command" == sudo* ]] || [[ "$command" == su* ]]; then
  30. echo '{"hookSpecificOutput": {"permissionDecision": "ask"}, "systemMessage": "Command requires elevated privileges"}' >&2
  31. exit 2
  32. fi
  33. # Approve the operation
  34. exit 0