#!/bin/sh # ssh-login-notify — send a Discord webhook message on every SSH login. # # Reports: account, source IP, geo location (IP lookup), network/ISP, # auth method (SSH key vs password), key fingerprint, host, time. # # Portable POSIX sh: Linux (glibc / musl / BusyBox), FreeBSD, OpenBSD, NetBSD, macOS. # Needs: OpenSSH server, and curl or wget. # # sudo sh ssh-login-notify.sh install 'https://discord.com/api/webhooks/ID/TOKEN' [options] # sudo ssh-login-notify test # send a test message # sudo ssh-login-notify set name "Web 01" # change a setting # sudo ssh-login-notify config # show settings (webhook masked) # sudo ssh-login-notify uninstall # remove everything it added # # Settings (install --opt=value / --opt value, or `set opt value`): # name Name shown for this server (default: its hostname) # bot-name Name the message is posted as (default: SSH Monitor) # avatar Image URL for the poster's avatar # mention Ping added to each message: @here, @everyone, <@USER_ID>, <@&ROLE_ID> # ignore-users Space-separated accounts to not alert on # ignore-ips Space-separated IPs to not alert on # ipinfo-token ipinfo.io token for higher lookup limits # webhook Discord webhook URL # # Hook modes (picked automatically by `install`): # pam – pam_exec in /etc/pam.d/sshd. Runs as root, users can't skip it, # webhook config is root-only. Used on most Linux and FreeBSD. # sshrc – /etc/ssh/sshrc. Fallback where pam_exec/UsePAM isn't available # (macOS, OpenBSD, Alpine without openssh-server-pam). Runs as the # logging-in user, so the config must be world-readable. # # The alert is sent in the background with short timeouts, so a slow or dead # network/Discord never delays or blocks a login. set -u PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-} INSTALL_PATH=/usr/local/sbin/ssh-login-notify CONF=/etc/ssh-login-notify.conf SSHD_CONFIG=${SSHD_CONFIG:-/etc/ssh/sshd_config} PAM_FILE=/etc/pam.d/sshd SSHRC=/etc/ssh/sshrc MARK='# ssh-login-notify' die() { echo "ssh-login-notify: $*" >&2; exit 1; } info() { echo "ssh-login-notify: $*"; } have() { command -v "$1" >/dev/null 2>&1; } # ---------------------------------------------------------------- config ---- conf_key() { # friendly setting name -> config variable case "$1" in name|server-name) echo SERVER_NAME ;; bot-name) echo BOT_NAME ;; avatar) echo AVATAR_URL ;; mention|ping) echo MENTION ;; ignore-users) echo IGNORE_USERS ;; ignore-ips) echo IGNORE_IPS ;; ipinfo-token) echo IPINFO_TOKEN ;; webhook) echo WEBHOOK_URL ;; *) return 1 ;; esac } valid_webhook() { case "$1" in https://discord.com/api/webhooks/*|https://discordapp.com/api/webhooks/*|\ https://ptb.discord.com/api/webhooks/*|https://canary.discord.com/api/webhooks/*) return 0 ;; esac return 1 } write_conf_template() { ( umask 077; cat > "$CONF" <<'EOF' # ssh-login-notify config (sourced as shell). Change with: sudo ssh-login-notify set WEBHOOK_URL='' # Name shown for this server in alerts (blank = hostname) SERVER_NAME='' # Name and avatar image the message is posted as BOT_NAME='SSH Monitor' AVATAR_URL='' # Ping on each alert, e.g. '@here' or '<@&ROLE_ID>' MENTION='' # Space-separated lists to not alert on IGNORE_USERS='' IGNORE_IPS='' # Optional ipinfo.io token for higher lookup limits (free tier works without one) IPINFO_TOKEN='' EOF ) } set_conf() { # : replace VAR='...' in place (or append), safely single-quoted [ -f "$CONF" ] || write_conf_template SLN_LINE="$1='$(printf '%s' "$2" | sed "s/'/'\\\\''/g")'" SLN_KEY="$1=" \ awk 'index($0, ENVIRON["SLN_KEY"]) == 1 { if (!done) print ENVIRON["SLN_LINE"]; done = 1; next } { print } END { if (!done) print ENVIRON["SLN_LINE"] }' "$CONF" > "$CONF.tmp.$$" \ && cat "$CONF.tmp.$$" > "$CONF" rm -f "$CONF.tmp.$$" } apply_opts() { # args...: handles --opt=value and --opt value act=$1; shift while [ $# -gt 0 ]; do k="" v="" case "$1" in https://*) k=webhook v=$1 ;; --*=*) k=${1%%=*}; k=${k#--}; v=${1#*=} ;; --*) k=${1#--}; [ $# -ge 2 ] || die "--$k needs a value"; v=$2; shift ;; *) die "unexpected argument: $1" ;; esac var=$(conf_key "$k") || die "unknown setting --$k (see: $0 --help)" if [ "$var" = WEBHOOK_URL ] && ! valid_webhook "$v"; then die "that doesn't look like a Discord webhook URL"; fi [ "$act" = apply ] && set_conf "$var" "$v" shift done return 0 } do_set() { # [ "$(id -u)" = 0 ] || die "run as root" [ $# -eq 2 ] || die "usage: $0 set (names: name bot-name avatar mention ignore-users ignore-ips ipinfo-token webhook)" [ -f "$CONF" ] || die "not installed" apply_opts apply "--$1=$2" info "set $1" } do_show_config() { [ -r "$CONF" ] || die "can't read $CONF (not installed, or try sudo)" sed -n "s|^\(WEBHOOK_URL='https://[^']*/webhooks/[0-9]*/\).*'|\1••••••'|; /^[A-Z_]*=/p" "$CONF" } # ---------------------------------------------------------------- helpers --- json_escape() { # strip control chars (keep \n), escape \ and ", turn newlines into \n printf '%s' "$1" | tr -d '\000-\011\013-\037' \ | sed 's/\\/\\\\/g; s/"/\\"/g' \ | awk 'BEGIN{ORS=""} NR>1{print "\\n"} {print}' } json_field() { # -> string value (flat JSON only) printf '%s' "$1" | tr -d '\n' \ | sed -n "s/.*\"$2\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" } is_private_ip() { case "$1" in *:*) case "$1" in ::1|fe80:*|fc*|fd*|::ffff:10.*|::ffff:127.*|::ffff:192.168.*) return 0;; esac ;; 10.*|127.*|192.168.*|169.254.*) return 0 ;; 172.1[6-9].*|172.2[0-9].*|172.3[01].*) return 0 ;; 100.6[4-9].*|100.[7-9][0-9].*|100.1[01][0-9].*|100.12[0-7].*) return 0 ;; # CGNAT / Tailscale esac return 1 } http_get() { if have curl; then curl -fsS --max-time 5 "$1" elif have wget; then wget -qO- -T 5 "$1" elif have fetch; then fetch -qo - -T 5 "$1" else return 1; fi } http_post_json() { # if have curl; then # URL goes in via stdin config so the webhook token isn't visible in `ps` printf 'url = "%s"\n' "$1" | curl -fsS --max-time 10 -K - \ -H 'Content-Type: application/json' --data-binary "$2" -o /dev/null elif have wget; then wget -qO /dev/null -T 10 --header='Content-Type: application/json' --post-data="$2" "$1" else return 1 fi } join_nonempty() { # joins args with ", " out="" for p in "$@"; do [ -n "$p" ] || continue if [ -n "$out" ]; then out="$out, $p"; else out=$p; fi done printf '%s' "$out" } geo_lookup() { # -> sets GEO_LOC, GEO_ORG GEO_LOC="" GEO_ORG="" if is_private_ip "$1"; then GEO_LOC="Private / LAN address"; return; fi tok=""; [ -n "${IPINFO_TOKEN:-}" ] && tok="?token=$IPINFO_TOKEN" j=$(http_get "https://ipinfo.io/$1/json$tok" 2>/dev/null) city=$(json_field "$j" city); region=$(json_field "$j" region) country=$(json_field "$j" country); GEO_ORG=$(json_field "$j" org) if [ -z "$city$country" ]; then # fallback provider j=$(http_get "http://ip-api.com/json/$1?fields=country,regionName,city,isp,as" 2>/dev/null) city=$(json_field "$j" city); region=$(json_field "$j" regionName) country=$(json_field "$j" country) GEO_ORG=$(json_field "$j" as); [ -n "$GEO_ORG" ] || GEO_ORG=$(json_field "$j" isp) fi GEO_LOC=$(join_nonempty "$city" "$region" "$country") [ -n "$GEO_LOC" ] || GEO_LOC="Lookup failed" } auth_log_line() { # -> newest matching "Accepted ..." sshd log line { if have journalctl; then journalctl -q --no-pager --since '-10min' 2>/dev/null fi for f in /var/log/auth.log /var/log/secure /var/log/authlog /var/log/messages; do [ -r "$f" ] && tail -n 500 "$f" 2>/dev/null done if [ "$(uname -s)" = Darwin ]; then log show --last 2m --style syslog \ --predicate 'process == "sshd" OR process == "sshd-session"' 2>/dev/null fi } | grep -F 'Accepted ' | grep -F " for $1 from $2 port " | tail -n 1 } # Sets AUTH_LABEL, AUTH_FP, COLOR from captured AUTH_INFO (or the sshd log). detect_auth() { # methods="" AUTH_FP="" if [ -n "${AUTH_INFO:-}" ]; then # ExposeAuthInfo lines look like: "publickey ssh-ed25519 AAAA..." / "password" methods=$(printf '%s\n' "$AUTH_INFO" | awk '$1!="" && !seen[$1]++ {printf "%s ", $1}') key=$(printf '%s\n' "$AUTH_INFO" | awk '$1=="publickey"{print $2" "$3; exit}') if [ -n "$key" ] && have ssh-keygen; then AUTH_FP=$(printf '%s\n' "$key" | ssh-keygen -lf - 2>/dev/null | awk '{print $2" "$NF}') fi fi if [ -z "$methods" ]; then # e.g. "Accepted publickey for bob from 1.2.3.4 port 5555 ssh2: ED25519 SHA256:abc" line=$(auth_log_line "$1" "$2") methods=$(printf '%s' "$line" | sed -n 's/.*Accepted \([^ ]*\) for .*/\1/p') [ -n "$AUTH_FP" ] || AUTH_FP=$(printf '%s' "$line" | sed -n 's/.*ssh2: \(.*\)$/\1/p') fi pk=0 pw=0 case " $methods " in *" publickey"*) pk=1 ;; esac case " $methods " in *" password"*|*" keyboard-interactive"*) pw=1 ;; esac if [ $pk = 1 ] && [ $pw = 1 ]; then AUTH_LABEL="🔑 SSH key + 🔒 password (multi-factor)"; COLOR=3066993 elif [ $pk = 1 ]; then AUTH_LABEL="🔑 SSH key (passwordless)"; COLOR=3066993 elif [ $pw = 1 ]; then AUTH_LABEL="🔒 Password"; COLOR=15105570 else case "$methods" in *gssapi*) AUTH_LABEL="🎫 Kerberos/GSSAPI"; COLOR=3447003 ;; *hostbased*) AUTH_LABEL="🖥️ Host-based"; COLOR=3447003 ;; *none*) AUTH_LABEL="⚠️ NO authentication (none)"; COLOR=15158332 ;; *) AUTH_LABEL="❓ Unknown"; COLOR=9807270 ;; esac fi if [ -n "$methods" ]; then AUTH_LABEL="$AUTH_LABEL \`${methods% }\`"; fi } field() { # printf '{"name":"%s","value":"%s","inline":%s}' "$(json_escape "$1")" "$(json_escape "$2")" "$3" } notify() { # [ -r "$CONF" ] || exit 0 # shellcheck disable=SC1090 . "$CONF" [ -n "${WEBHOOK_URL:-}" ] || exit 0 user=$1 ip=$2 via=$3 # skip ignored users / IPs (space-separated lists in config) for u in ${IGNORE_USERS:-}; do [ "$u" = "$user" ] && exit 0; done for i in ${IGNORE_IPS:-}; do [ "$i" = "$ip" ] && exit 0; done detect_auth "$user" "$ip" geo_lookup "$ip" host=$(hostname 2>/dev/null || uname -n) name=${SERVER_NAME:-$host} os=$(uname -sr 2>/dev/null) ts=$(date -u +%Y-%m-%dT%H:%M:%SZ) title="SSH login on $name" [ "$user" = root ] && title="⚠️ ROOT $title" fields="$(field "👤 Account" "\`$user\`" true),$(field "🌐 IP address" "\`$ip\`" true),$(field "🔐 Auth method" "$AUTH_LABEL" true)" fields="$fields,$(field "📍 Location" "$GEO_LOC" true)" [ -n "$GEO_ORG" ] && fields="$fields,$(field "🏢 Network" "$GEO_ORG" true)" [ -n "$AUTH_FP" ] && fields="$fields,$(field "🗝️ Key fingerprint" "\`$AUTH_FP\`" false)" avatar=""; [ -n "${AVATAR_URL:-}" ] && avatar=",\"avatar_url\":\"$(json_escape "$AVATAR_URL")\"" body=$(printf '{"username":"%s"%s,"content":"%s","embeds":[{"title":"%s","color":%s,"fields":[%s],"footer":{"text":"%s"},"timestamp":"%s"}]}' \ "$(json_escape "${BOT_NAME:-SSH Monitor}")" "$avatar" "$(json_escape "${MENTION:-}")" \ "$(json_escape "$title")" "$COLOR" "$fields" \ "$(json_escape "$host · $os · via $via")" "$ts") if [ -n "${DRY_RUN:-}" ]; then printf '%s\n' "$body"; return 0; fi http_post_json "$WEBHOOK_URL" "$body" } capture_auth_info() { # PAM env (pam mode) or the per-session file (sshrc mode). Read it now: # the file can disappear before the background job runs. AUTH_INFO=${SSH_AUTH_INFO_0:-} if [ -z "$AUTH_INFO" ] && [ -n "${SSH_USER_AUTH:-}" ] && [ -r "$SSH_USER_AUTH" ]; then AUTH_INFO=$(cat "$SSH_USER_AUTH" 2>/dev/null) fi export AUTH_INFO } run_background() { # capture_auth_info ( sleep 1; notify "$@" ) /dev/null 2>&1 & exit 0 } # --------------------------------------------------------------- install ---- sshd_bin() { for s in "$(command -v sshd 2>/dev/null)" /usr/sbin/sshd /usr/local/sbin/sshd; do [ -n "$s" ] && [ -x "$s" ] && { echo "$s"; return; } done } sshd_opt() { # lowercase option name -> effective value "$SSHD" -T 2>/dev/null | awk -v k="$1" 'tolower($1)==k {print $2; exit}' } find_pam_exec() { for d in /lib/security /lib64/security /usr/lib/security /usr/lib64/security \ /lib/*/security /usr/lib/*/security /usr/lib /usr/lib/pam; do [ -f "$d/pam_exec.so" ] && return 0 done return 1 } strip_marked() { # : remove each "$MARK" line plus the line after it [ -f "$1" ] || return 0 awk -v m="$MARK" 'skip {skip=0; next} $0==m {skip=1; next} {print}' "$1" > "$1.tmp.$$" \ && cat "$1.tmp.$$" > "$1"; rm -f "$1.tmp.$$" } strip_block() { # : remove "$MARK begin" .. "$MARK end" [ -f "$1" ] || return 0 awk -v b="$MARK begin" -v e="$MARK end" '$0==b{s=1} !s{print} $0==e{s=0}' "$1" > "$1.tmp.$$" \ && cat "$1.tmp.$$" > "$1"; rm -f "$1.tmp.$$" } reload_sshd() { [ "$(uname -s)" = Darwin ] && return 0 # launchd starts sshd per connection if have systemctl && { systemctl reload ssh 2>/dev/null || systemctl reload sshd 2>/dev/null; }; then return 0; fi if have rcctl && rcctl reload sshd >/dev/null 2>&1; then return 0; fi # OpenBSD if have rc-service && rc-service sshd reload >/dev/null 2>&1; then return 0; fi # OpenRC if have service && { service sshd reload >/dev/null 2>&1 || service ssh reload >/dev/null 2>&1; }; then return 0; fi if have pkill && pkill -HUP -x sshd 2>/dev/null; then return 0; fi info "couldn't reload sshd automatically — restart it yourself to apply ExposeAuthInfo" } enable_expose_auth_info() { cur=$(sshd_opt exposeauthinfo) if [ -z "$cur" ]; then info "this sshd doesn't support ExposeAuthInfo (needs OpenSSH 7.6+); will read the auth log instead" return fi [ "$cur" = yes ] && return dropdir=${SSHD_CONFIG%/*}/sshd_config.d if [ -d "$dropdir" ] && grep -Eiq '^[[:space:]]*Include[[:space:]].*sshd_config\.d' "$SSHD_CONFIG"; then printf '%s\nExposeAuthInfo yes\n' "$MARK" > "$dropdir/00-ssh-login-notify.conf" else cp -p "$SSHD_CONFIG" "$SSHD_CONFIG.bak-ssh-login-notify" # prepend so it lands before any Match block { printf '%s\nExposeAuthInfo yes\n' "$MARK"; cat "$SSHD_CONFIG"; } > "$SSHD_CONFIG.tmp.$$" \ && cat "$SSHD_CONFIG.tmp.$$" > "$SSHD_CONFIG"; rm -f "$SSHD_CONFIG.tmp.$$" fi if ! "$SSHD" -t 2>/dev/null; then rm -f "$dropdir/00-ssh-login-notify.conf"; strip_marked "$SSHD_CONFIG" info "sshd rejected ExposeAuthInfo; reverted. Will read the auth log instead" return fi reload_sshd } do_install() { [ "$(id -u)" = 0 ] || die "install must run as root" apply_opts check "$@" # validate everything before touching the system case " $* " in *" https://"*|*" --webhook"*) ;; *) grep -q "^WEBHOOK_URL='https" "$CONF" 2>/dev/null \ || die "usage: $0 install 'https://discord.com/api/webhooks/ID/TOKEN' [--name 'My server' ...]" ;; esac have curl || have wget || die "needs curl or wget — install one first" SSHD=$(sshd_bin); [ -n "$SSHD" ] || die "OpenSSH sshd not found" [ -f "$0" ] || die "run this as a file (sh ssh-login-notify.sh install ...), not piped" mkdir -p "${INSTALL_PATH%/*}" [ "$0" -ef "$INSTALL_PATH" ] 2>/dev/null || cp "$0" "$INSTALL_PATH" chmod 755 "$INSTALL_PATH" # remove any previous hooks so re-running install is safe strip_marked "$PAM_FILE"; strip_block "$SSHRC" mode=sshrc if [ -f "$PAM_FILE" ] && find_pam_exec && [ "$(sshd_opt usepam)" = yes ]; then mode=pam; fi # existing settings are kept; only the options passed now are changed [ -f "$CONF" ] || write_conf_template apply_opts apply "$@" chown root "$CONF" 2>/dev/null if [ $mode = pam ]; then chmod 600 "$CONF"; else chmod 644 "$CONF"; fi enable_expose_auth_info if [ $mode = pam ]; then # Linux-PAM understands "quiet"; OpenPAM (FreeBSD) would treat it as the program opt=""; [ "$(uname -s)" = Linux ] && opt="quiet " printf '%s\nsession optional pam_exec.so %s%s\n' "$MARK" "$opt" "$INSTALL_PATH" >> "$PAM_FILE" info "installed PAM hook in $PAM_FILE" else new=0; [ -s "$SSHRC" ] || new=1 { echo "$MARK begin" echo "$INSTALL_PATH sshrc > "$SSHRC" chmod 755 "$SSHRC" info "installed hook in $SSHRC (no pam_exec here)" info "note: in this mode $CONF is readable by local users, and a user's own ~/.ssh/rc replaces sshrc" fi info "done — run '$INSTALL_PATH test' to send a test message" } do_uninstall() { [ "$(id -u)" = 0 ] || die "uninstall must run as root" strip_marked "$PAM_FILE" strip_block "$SSHRC" [ -f "$SSHRC" ] && ! grep -q '[^[:space:]]' "$SSHRC" && rm -f "$SSHRC" dropin=${SSHD_CONFIG%/*}/sshd_config.d/00-ssh-login-notify.conf if [ -f "$dropin" ] || grep -qxF "$MARK" "$SSHD_CONFIG" 2>/dev/null; then rm -f "$dropin"; strip_marked "$SSHD_CONFIG"; reload_sshd fi rm -f "$CONF" "$INSTALL_PATH" "$SSHD_CONFIG.bak-ssh-login-notify" info "removed" } # ------------------------------------------------------------------ main ---- case "${1:-}" in install) shift; do_install "$@" ;; uninstall) do_uninstall ;; set) shift; do_set "$@" ;; config) do_show_config ;; -h|--help|help) sed -n '2,/^# The alert/p' "$0" | sed 's/^# \{0,1\}//' | sed '$d'; exit 0 ;; test) AUTH_INFO="publickey ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl" notify "$(id -un)" "${2:-8.8.8.8}" "test" && info "sent" ;; sshrc) # running as the user from /etc/ssh/sshrc run_background "${USER:-$(id -un)}" "${SSH_CONNECTION%% *}" sshrc ;; *) # pam_exec: Linux-PAM sets PAM_TYPE, OpenPAM sets PAM_SM_FUNC if [ "${PAM_TYPE:-}" = open_session ] || [ "${PAM_SM_FUNC:-}" = pam_sm_open_session ]; then run_background "${PAM_USER:-?}" "${PAM_RHOST:-?}" pam fi [ -n "${PAM_TYPE:-}${PAM_SM_FUNC:-}" ] && exit 0 echo "usage: $0 install [--name NAME ...] | test [ip] | set | config | uninstall | --help" >&2 exit 2 ;; esac