#!/bin/sh
# website-attack-check.sh - read-only check for "is my website or server
# under attack right now?"
# Guide: https://alertkick.com/blog/how-to-check-if-website-is-under-attack/
#
# Reads the web access log, the kernel connection table and the SSH auth log,
# and prints PASS, WARN or FAIL per check with the numbers behind it. It
# changes nothing, installs nothing and makes no network calls (the only
# writes are temp files it deletes on exit). POSIX sh: works with dash and
# bash on Ubuntu, Debian and RHEL-family servers.
#
#   sudo sh website-attack-check.sh
#   sudo ACCESS_LOG=/var/log/nginx/shop.access.log sh website-attack-check.sh
#   sudo LINES=50000 sh website-attack-check.sh   # read more of the log
#
# The access log must be in the default "combined" format (nginx and Apache
# default). Exit code: 0 when nothing FAILs, 1 otherwise.

PATH=/usr/sbin:/usr/bin:/sbin:/bin:$PATH
LC_ALL=C
export PATH LC_ALL
LINES=${LINES:-20000}
pass=0 warn=0 fail=0

tmp=$(mktemp -d 2>/dev/null || mktemp -d -t wac) || { echo "cannot create a temp dir" >&2; exit 2; }
trap 'rm -rf "$tmp"' EXIT
trap 'exit 130' INT TERM

out() { # STATUS check-id reason
  printf '%-4s  %-13s %s\n' "$1" "$2" "$3"
  case $1 in
    PASS) pass=$((pass + 1)) ;;
    WARN) warn=$((warn + 1)) ;;
    FAIL) fail=$((fail + 1)) ;;
  esac
}
have() { command -v "$1" >/dev/null 2>&1; }
pct() { awk -v a="$1" -v b="$2" 'BEGIN { if (b > 0) printf "%d", a * 100 / b; else print 0 }'; }
ge() { awk -v a="$1" -v b="$2" 'BEGIN { exit !(a >= b) }'; }
private_ip() {
  case $1 in
    10.* | 127.* | 192.168.* | 172.1[6-9].* | 172.2[0-9].* | 172.3[01].* | ::1 | fc* | fd*) return 0 ;;
  esac
  return 1
}

os=$(. /etc/os-release 2>/dev/null && echo "$PRETTY_NAME")
echo "host $(uname -n) | ${os:-unknown OS} | $(date -u '+%Y-%m-%d %H:%M UTC') | uid $(id -u)"
[ "$(id -u)" -eq 0 ] || echo "not root: logs that only root can read will WARN"
echo

# 1. Load against CPU count ------------------------------------------------
cores=$(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)
read -r l1 l5 _ < /proc/loadavg
if ge "$l5" $((cores * 2)); then out FAIL load "5-min load $l5 on $cores cores: saturated"
elif ge "$l5" "$cores"; then out WARN load "5-min load $l5 on $cores cores: busy (1-min $l1)"
else out PASS load "5-min load $l5 on $cores cores"; fi

# 2. Access log --------------------------------------------------------------
log=${ACCESS_LOG:-}
if [ -z "$log" ]; then
  for f in /var/log/nginx/access.log /var/log/apache2/access.log /var/log/httpd/access_log /usr/local/apache/logs/access_log; do
    if [ -s "$f" ]; then log=$f; break; fi
  done
fi
topips=""
if [ -z "$log" ]; then
  out WARN access-log "no access log found (set ACCESS_LOG=/path/to/access.log)"
elif [ ! -r "$log" ]; then
  out WARN access-log "$log is not readable (run with sudo)"
else
  tail -n "$LINES" "$log" | awk '$4 ~ /^\[/ && NF >= 9' > "$tmp/a"
  n=$(wc -l < "$tmp/a" | tr -d ' ')
  if [ "$n" -lt 50 ]; then
    out WARN access-log "$log: only $n combined-format lines, too few to judge"
  else
    first=$(head -n 1 "$tmp/a" | awk '{ print substr($4, 2) }')
    last=$(tail -n 1 "$tmp/a" | awk '{ print substr($4, 2) }')
    echo "access log $log: last $n requests, $first -> $last"

    # 2a. Concentration: one IP carrying a large share
    awk '{ print $1 }' "$tmp/a" | sort | uniq -c | sort -rn > "$tmp/ips"
    read -r c1 ip1 < "$tmp/ips"
    distinct=$(wc -l < "$tmp/ips" | tr -d ' ')
    share=$(pct "$c1" "$n")
    topips=$(head -n 5 "$tmp/ips" | awk '{ printf "%s(%s) ", $2, $1 }')
    if private_ip "$ip1"; then
      out WARN proxy "top address $ip1 is private: a proxy or load balancer is in front, so the log shows it, not the client (log X-Forwarded-For or CF-Connecting-IP)"
    fi
    if [ "$share" -ge 30 ]; then out FAIL top-ip "$ip1 sent $share% of requests ($c1 of $n, $distinct IPs in total)"
    elif [ "$share" -ge 15 ]; then out WARN top-ip "$ip1 sent $share% of requests ($c1 of $n, $distinct IPs in total)"
    else out PASS top-ip "busiest IP $ip1 has $share%, spread over $distinct IPs"; fi

    # 2b. Probe paths: scanners looking for weak spots
    grep -Ei '"[A-Z]+ [^ "]*(wp-login\.php|xmlrpc\.php|/\.env|/\.git/|phpmyadmin|/vendor/phpunit|/\.aws/|/cgi-bin/|/actuator|/server-status)' "$tmp/a" > "$tmp/probe"
    p=$(wc -l < "$tmp/probe" | tr -d ' ')
    ps=$(pct "$p" "$n")
    if [ "$p" -gt 0 ]; then
      pt=$(awk '{ print $1 }' "$tmp/probe" | sort | uniq -c | sort -rn | head -n 1 | awk '{ printf "%s (%s)", $2, $1 }')
      if [ "$ps" -ge 25 ]; then out FAIL probes "$p probe requests ($ps%) for wp-login, .env, .git, phpMyAdmin and similar; top: $pt"
      elif [ "$p" -ge 50 ] || [ "$ps" -ge 5 ]; then out WARN probes "$p probe requests ($ps%) for wp-login, .env, .git, phpMyAdmin and similar; top: $pt (wp-login is normal traffic on a WordPress site)"
      else out PASS probes "$p probe requests ($ps%): normal background scanning"; fi
    else
      out PASS probes "no requests for common probe paths"
    fi

    # 2c. Status mix
    set -- $(awk '{ s = $9 } s == 404 { a++ } s == 401 || s == 403 { b++ } s ~ /^5/ || s == 499 { c++ } END { print a + 0, b + 0, c + 0 }' "$tmp/a")
    s404=$(pct "$1" "$n") s40x=$(pct "$2" "$n") s5=$(pct "$3" "$n")
    st="404 $s404%, 401/403 $s40x%, 5xx/499 $s5%"
    if [ "$s5" -ge 10 ]; then out FAIL status "$st: the backend is failing under load"
    elif [ "$s404" -ge 30 ]; then out WARN status "$st: a flood of 404s points to scanning"
    elif [ "$s40x" -ge 20 ]; then out WARN status "$st: many 401/403s point to password guessing"
    elif [ "$s5" -ge 2 ]; then out WARN status "$st: some backend errors"
    else out PASS status "$st"; fi

    # 2d. One URL hammered
    awk '{ sub(/\?.*/, "", $7); print $7 }' "$tmp/a" | sort | uniq -c | sort -rn | head -n 1 > "$tmp/path"
    read -r pc pp < "$tmp/path"
    psh=$(pct "$pc" "$n")
    if [ "$psh" -ge 50 ] && [ "$pp" != "/" ]; then out WARN top-path "$pp got $psh% of requests ($pc): check whether that is a launch or a flood"
    else out PASS top-path "busiest path $pp has $psh%"; fi

    # 2e. Scripted user agents
    set -- $(awk -F'"' '{ ua = tolower($6) }
      ua == "" || ua == "-" || ua ~ /curl|wget|python|go-http-client|libwww|java\/|okhttp|scrapy|httpclient|masscan|zgrab|nikto|sqlmap|nmap/ { s++ }
      END { print s + 0 }' "$tmp/a")
    us=$(pct "$1" "$n")
    if [ "$us" -ge 30 ]; then out WARN user-agents "$us% of requests have an empty or scripted user agent (curl, python, Go, scanners)"
    else out PASS user-agents "$us% empty or scripted user agents"; fi

    # 2f. Requests per minute: peak against the median minute
    awk '{ print substr($4, 2, 17) }' "$tmp/a" | uniq -c | awk '{ print $1 }' | sort -n > "$tmp/rpm"
    mins=$(wc -l < "$tmp/rpm" | tr -d ' ')
    if [ "$mins" -ge 10 ]; then
      peak=$(tail -n 1 "$tmp/rpm")
      med=$(awk -v m="$mins" 'NR == int((m + 1) / 2) { print; exit }' "$tmp/rpm")
      if [ "$peak" -ge 100 ] && [ "$peak" -ge $((med * 5)) ]; then
        out WARN rate "peak minute $peak requests against a median of $med per minute"
      else out PASS rate "peak minute $peak requests, median $med per minute"; fi
    fi
  fi
fi

# 3. Connections now ---------------------------------------------------------
if have ss; then
  syn=$(ss -tan state syn-recv 2>/dev/null | awk 'NR > 1' | wc -l | tr -d ' ')
  if [ "$syn" -ge 256 ]; then out FAIL syn-recv "$syn half-open connections: SYN flood signature"
  elif [ "$syn" -ge 50 ]; then out WARN syn-recv "$syn half-open connections"
  else out PASS syn-recv "$syn half-open connections"; fi

  ss -tn state established '( sport = :443 or sport = :80 )' 2>/dev/null | awk 'NR > 1 { print $4 }' |
    sed 's/:[0-9]*$//; s/^\[//; s/\]$//; s/^::ffff://' | sort | uniq -c | sort -rn > "$tmp/conn"
  est=$(awk '{ t += $1 } END { print t + 0 }' "$tmp/conn")
  if [ "$est" -gt 0 ]; then
    read -r cc cip < "$tmp/conn"
    if private_ip "$cip"; then out PASS web-conns "$est established on :80/:443, most from $cip (a proxy)"
    elif [ "$cc" -ge 100 ]; then out FAIL web-conns "$cip holds $cc of $est established connections on :80/:443"
    elif [ "$cc" -ge 30 ]; then out WARN web-conns "$cip holds $cc of $est established connections on :80/:443"
    else out PASS web-conns "$est established on :80/:443, at most $cc from one IP ($cip)"; fi
  else
    out PASS web-conns "no established connections on :80/:443 right now"
  fi
else
  out WARN syn-recv "ss not found (install iproute2)"
fi
cookies=$(awk '/^TcpExt:/ { if (!h) { for (i = 1; i <= NF; i++) if ($i == "SyncookiesSent") k = i; h = 1 } else print $k }' /proc/net/netstat 2>/dev/null)
if [ -n "$cookies" ] && [ "$cookies" -gt 0 ]; then
  out WARN syncookies "kernel has sent $cookies SYN cookies since boot: a SYN flood hit at some point (compare later runs)"
fi

# 4. SSH ---------------------------------------------------------------------
alog=${AUTH_LOG:-}
if [ -z "$alog" ]; then
  for f in /var/log/auth.log /var/log/secure; do
    if [ -s "$f" ]; then alog=$f; break; fi
  done
fi
src=""
if [ -n "$alog" ] && [ -r "$alog" ]; then
  tail -n 100000 "$alog" > "$tmp/s"; src=$alog
elif have journalctl && journalctl -q --no-pager -u ssh -u sshd --since "24 hours ago" > "$tmp/s" 2>/dev/null && [ -s "$tmp/s" ]; then
  src="journal (24 h)"
fi
if [ -z "$src" ]; then
  if [ -n "$alog" ]; then out WARN ssh "$alog is not readable (run with sudo)"
  else out WARN ssh "no SSH auth log or journal entries found"; fi
else
  grep -E 'Failed password|Invalid user' "$tmp/s" |
    awk '{ for (i = 1; i < NF; i++) if ($i == "from") { print $(i + 1); break } }' | sort | uniq -c | sort -rn > "$tmp/sf"
  nf=$(awk '{ t += $1 } END { print t + 0 }' "$tmp/sf")
  nfi=$(wc -l < "$tmp/sf" | tr -d ' ')
  if [ "$nf" -ge 100 ]; then
    out WARN ssh-failed "$nf failed or invalid-user attempts from $nfi IPs in $src; top: $(head -n 3 "$tmp/sf" | awk '{ printf "%s(%s) ", $2, $1 }')"
  else
    out PASS ssh-failed "$nf failed or invalid-user attempts in $src"
  fi
  grep -E 'Accepted (password|publickey|keyboard-interactive)' "$tmp/s" |
    awk '{ for (i = 1; i < NF; i++) if ($i == "from") { print $(i + 1); break } }' | sort -u > "$tmp/sa"
  na=$(wc -l < "$tmp/sa" | tr -d ' ')
  bad=""
  while read -r ip; do
    if awk -v ip="$ip" '$2 == ip { f = 1 } END { exit !f }' "$tmp/sf"; then bad="$bad$ip "; fi
  done < "$tmp/sa"
  if [ -n "$bad" ]; then
    out FAIL ssh-accepted "login ACCEPTED from an IP that also failed: $bad- treat the server as compromised: https://alertkick.com/blog/is-my-linux-server-hacked-checklist/"
  elif [ "$na" -gt 0 ]; then
    out PASS ssh-accepted "$na source IP(s) logged in, none of them also failing: $(tr '\n' ' ' < "$tmp/sa")"
  else
    out PASS ssh-accepted "no successful SSH logins in $src"
  fi
fi

# 5. Who to look up ----------------------------------------------------------
echo
[ -n "$topips" ] && echo "top web IPs:  $topips"
[ -s "$tmp/sf" ] && echo "top SSH IPs:  $(head -n 5 "$tmp/sf" | awk '{ printf "%s(%s) ", $2, $1 }')"
if [ -n "$topips" ] || [ -s "$tmp/sf" ]; then
  echo "look them up: dig -x <ip> +short, or https://alertkick.com/tools/ip-reputation/"
  echo "before blocking, confirm a high-volume IP is not Googlebot (reverse DNS googlebot.com or google.com)"
fi

echo
echo "$pass pass, $warn warn, $fail fail"
[ "$fail" -eq 0 ]
