#!/usr/bin/env bash
# wp-clickfix-detect.sh, find the injection points for ClickFix-family attacks on a WordPress install.
# Source: https://techearl.com/wordpress-fake-cloudflare-verification-clickfix
# Site:   https://techearl.com/
# Reports candidates; does NOT modify or delete.
#
# Usage: ./wp-clickfix-detect.sh /path/to/wordpress https://yoursite.com

set -e
WP_ROOT="${1:-$PWD}"
SITE_URL="${2:-}"

echo "========================================="
echo "  ClickFix Detection Pass"
echo "  WP root: $WP_ROOT"
echo "========================================="

# 1. Visitor-side check (requires the live URL)
if [ -n "$SITE_URL" ]; then
  echo
  echo "--- 1. Visitor-side check (Windows Chrome UA) ---"
  curl -s -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36" \
    "$SITE_URL/" | grep -iE 'cloudflare.*verify|verify.*cloudflare|browser.*update|<script[^>]*\.(cc|xyz|top|click|cfd|space)' | head -10 \
    || echo "  (no obvious markers in homepage HTML)"
fi

# 2. wp_options autoload scan
echo
echo "--- 2. Suspicious wp_options entries ---"
wp db query "SELECT option_id, option_name, LEFT(option_value, 200) AS preview \
  FROM wp_options \
  WHERE autoload IN ('yes','on') \
    AND option_value REGEXP '<script|document\\.write|fromCharCode|cloudflare.*verify|browser.*update|\\.(cc|xyz|top|click|cfd|space)/' \
  LIMIT 30" \
  --path="$WP_ROOT" --allow-root 2>/dev/null \
  || echo "  (wp-cli unavailable; run the SQL directly)"

# 3. Active theme audit
echo
echo "--- 3. Active theme injection scan ---"
THEME=$(wp option get template --path="$WP_ROOT" --allow-root 2>/dev/null)
if [ -n "$THEME" ]; then
  ACTIVE_DIR="$WP_ROOT/wp-content/themes/$THEME"
  echo "  Active theme: $THEME"
  grep -rlnE '<script[^>]*src=["'\''][^"'\'']+\.(cc|xyz|top|click|cfd|space|shop)' "$ACTIVE_DIR" 2>/dev/null \
    || echo "  (no remote-script signatures in active theme)"
  grep -rlnE 'eval\(base64_decode|eval\(gzinflate' "$ACTIVE_DIR" 2>/dev/null \
    || echo "  (no eval-decode patterns in active theme)"
fi

# 4. Drop-in files
echo
echo "--- 4. Drop-in files ---"
for f in advanced-cache.php object-cache.php db.php sunrise.php; do
  if [ -f "$WP_ROOT/wp-content/$f" ]; then
    echo "  PRESENT: wp-content/$f (size $(wc -c <"$WP_ROOT/wp-content/$f") bytes)"
  fi
done

# 5. Plugin list (manual cross-reference)
echo
echo "--- 5. Plugin list (cross-reference against your inventory) ---"
wp plugin list --format=table --fields=name,status,version --path="$WP_ROOT" --allow-root 2>/dev/null

# 6. Recently modified PHP files (last 30 days)
echo
echo "--- 6. PHP files modified in the last 30 days ---"
find "$WP_ROOT" -type f -name '*.php' -mtime -30 \
  -not -path '*/node_modules/*' 2>/dev/null \
  | head -30

echo
echo "========================================="
echo "  Done. Investigate each section manually."
echo "========================================="
