#!/usr/bin/env bash
# uxlogin.sh - get an alert every time someone logs in to this machine over
# SSH: who, from where, and when. If it wasn't you, you know right away.
#
# Linux (all users, recommended) - run it from PAM. As root:
#   cp uxlogin.sh /usr/local/bin/ && chmod 755 /usr/local/bin/uxlogin.sh
#   (umask 077; printf '%s' 'YOUR-API-KEY' > /etc/useralertx_key)
#   echo 'session optional pam_exec.so /usr/local/bin/uxlogin.sh' >> /etc/pam.d/sshd
#
# Mac, or Linux without root - run it from your own ~/.ssh/rc (covers only
# your account; save your key once with uxsend.sh):
#   echo "$HOME/uxlogin.sh" >> ~/.ssh/rc
#   (Note: if ~/.ssh/rc exists, sshd skips its usual X11 xauth setup - only
#   matters if you use ssh -X.)
#
# Skip alerts from addresses you trust by adding their prefixes, e.g.
#   ... pam_exec.so /usr/local/bin/uxlogin.sh 192.168. 10.0.0.
#
# It never blocks or delays a login: the alert is sent in the background and
# the script always exits 0. API key: USERALERTX_API_KEY env var, else
# /etc/useralertx_key (PAM), else ~/.useralertx_key.
# USERALERTX_DRYRUN=1 prints instead of sending.

URL_API="${USERALERTX_URL:-https://useralertx.com/cgi-bin/itmessages.cgi}"

if [ -n "${PAM_TYPE:-}" ]; then
  # Called by pam_exec: alert on login only, not on logout.
  [ "$PAM_TYPE" = "open_session" ] || exit 0
  WHO="$PAM_USER"; FROM="${PAM_RHOST:-local}"; VIA="${PAM_SERVICE:-ssh}"
else
  # Called from ~/.ssh/rc: SSH_CONNECTION = "client-ip client-port server-ip server-port"
  WHO="${USER:-$(id -un)}"; FROM="${SSH_CONNECTION%% *}"; FROM="${FROM:-local}"; VIA="ssh"
fi

for trusted in "$@"; do
  case "$FROM" in "$trusted"*) exit 0 ;; esac
done

MSG="Login: $WHO on $(hostname) from $FROM ($VIA) at $(date '+%H:%M %b %d')"

if [ -n "${USERALERTX_DRYRUN:-}" ]; then echo "[dry run] would send: $MSG"; exit 0; fi

KEY="${USERALERTX_API_KEY:-}"
for kf in /etc/useralertx_key "$HOME/.useralertx_key"; do
  [ -z "$KEY" ] && [ -r "$kf" ] && KEY="$(tr -d '[:space:]' < "$kf")"
done
[ -z "$KEY" ] && exit 0

( curl -s -o /dev/null --max-time 20 -A 'UserAlertX-example-uxlogin/1.0' \
    -H "X-Api-Key: $KEY" --data-urlencode "body=$MSG" "$URL_API" ) </dev/null >/dev/null 2>&1 &
exit 0
