On this page
- Why use PAM for login alerts?
- What rules keep the hook from blocking logins?
- How do I set up the Telegram or webhook target?
- What does the notify script look like?
- How do I test the script before PAM uses it?
- How do I hook the script into SSH safely?
- Can I send the alert by email instead?
- Why does a manual test work but real logins stay silent?
- Questions
Why use PAM for login alerts?
PAM runs on every SSH session, whether it starts with a key, a password, a TOTP code or an SFTP client, so a hook there catches all of them. Alternatives like a line in .bashrc miss non interactive sessions and can be edited by the very user you want to watch. The pam_exec module, shipped with Linux PAM on every supported distribution, runs a program with the user name, remote address and service in environment variables. Our job is to make that program fast, quiet and harmless. A login alert is a detection tool, not a lock: pair it with key only access from SSH keys and hardening.
What rules keep the hook from blocking logins?
Four rules make the hook safe:
- Use
session optional, neverrequired, so the result of the script is ignored. - Return at once: put the network call in the background and exit 0.
- Cap every network call with
timeoutand curl's-m, so a dead endpoint cannot pile up processes. - Ignore every PAM stage except
open_session, which avoids duplicate messages when the session closes.
Also make sure curl is installed: sudo apt install curl or sudo dnf install -y curl.
How do I set up the Telegram or webhook target?
Keep secrets in a root only file rather than in the script. For Telegram, create a bot with the BotFather account, send your bot one message, and read your chat id from the getUpdates method. Then create /etc/login-notify.conf:
sudo install -m 600 /dev/null /etc/login-notify.conf
sudo nano /etc/login-notify.confTG_TOKEN="123456789:replace-with-your-bot-token"
TG_CHAT="123456789"
WEBHOOK_URL=""If you prefer a chat tool that accepts incoming webhooks, or your own endpoint such as https://hooks.example.net/ssh, put its address in WEBHOOK_URL and leave the Telegram values empty. The script below sends to whichever targets are filled in.
What does the notify script look like?
Save this as /usr/local/sbin/login-notify:
#!/bin/sh
# Sends one message per new SSH session. Never blocks a login.
[ "$PAM_TYPE" = "open_session" ] || exit 0
. /etc/login-notify.conf 2>/dev/null || exit 0
HOST=$(hostname)
WHEN=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
MSG="SSH login on $HOST: user $PAM_USER from ${PAM_RHOST:-local} at $WHEN"
(
if [ -n "$TG_TOKEN" ]; then
timeout 10 curl -fsS -m 8 "https://api.telegram.org/bot$TG_TOKEN/sendMessage" \
-d chat_id="$TG_CHAT" --data-urlencode text="$MSG"
fi
if [ -n "$WEBHOOK_URL" ]; then
timeout 10 curl -fsS -m 8 -H "Content-Type: application/json" \
-d "{\"text\":\"$MSG\"}" "$WEBHOOK_URL"
fi
) </dev/null >/dev/null 2>&1 &
exit 0sudo chmod 755 /usr/local/sbin/login-notify
sudo restorecon -v /usr/local/sbin/login-notify 2>/dev/null || trueThe subshell inherits no terminal and all output goes to /dev/null, so PAM is not left waiting for it.
How do I test the script before PAM uses it?
Run it by hand with the same variables PAM would set:
sudo env PAM_TYPE=open_session PAM_USER=deploy PAM_RHOST=203.0.113.7 /usr/local/sbin/login-notify; echo "exit $?"The command must return immediately with exit 0, and a message should arrive within a few seconds. If nothing arrives, run the curl line on its own without -s to see the error. Also test the failure case: put a wrong token in the config, run the script again, and confirm it still returns at once with exit 0.
How do I hook the script into SSH safely?
Back up the PAM file, schedule its restore, add one line at the end, and log in from a second terminal:
sudo cp /etc/pam.d/sshd /root/pam-sshd.alert.bak
sudo systemd-run --on-active=10min --unit=alert-undo cp /root/pam-sshd.alert.bak /etc/pam.d/sshd
echo "session optional pam_exec.so quiet /usr/local/sbin/login-notify" | sudo tee -a /etc/pam.d/sshdPAM files are read on every new session, so no restart is needed. Keep your current session open, then run ssh deploy@198.51.100.24 in a new window. If the login works and the alert arrives, cancel the undo: sudo systemctl stop alert-undo.timer. If the new login misbehaves, wait for the timer or copy the backup back from your open session.
Can I send the alert by email instead?
Yes, through an authenticated SMTP relay on port 587, which works more reliably than direct delivery. Ask support with a ticket before planning to send mail straight from port 25. Install msmtp (on Rocky and AlmaLinux it comes from EPEL):
sudo apt install msmtp
sudo dnf install -y epel-release && sudo dnf install -y msmtpCreate /etc/msmtprc with mode 600 and owner root:
defaults
auth on
tls on
tls_starttls on
logfile /var/log/msmtp.log
account relay
host smtp.example.net
port 587
from alerts@example.net
user alerts@example.net
password replace-with-relay-password
account default : relayThen add a third block to the subshell of the script: printf "Subject: SSH login on %s\n\n%s\n" "$HOST" "$MSG" | timeout 15 msmtp you@example.net. Test with the manual command from above. The SMTP relay guide explains how to pick and configure a relay.
Why does a manual test work but real logins stay silent?
Check three things. First, that the PAM line is present and below the other session lines: grep pam_exec /etc/pam.d/sshd. Second, that UsePAM yes is active: sudo sshd -T | grep usepam. Third, on Rocky and AlmaLinux, that SELinux allowed the script to reach the network; look for denials with sudo ausearch -m avc -ts recent and read SELinux basics before changing any policy. Drop quiet temporarily to see pam_exec messages in sudo journalctl -u ssh -u sshd -n 30.
Questions about Alerts for every SSH login
Will a slow alert delay my login?
No. The script hands the network call to a background process and exits at once, so the login continues while the message is sent.
Does this report failed logins too?
Are SFTP and scp sessions reported?
Yes. They open a PAM session like any shell login, so you get an alert for file transfers as well.
How do I silence alerts from my own address?
Add a line near the top of the script such as [ "$PAM_RHOST" = "203.0.113.7" ] && exit 0.
Can I alert on sudo use?
Yes, by adding the same session optional pam_exec.so line to /etc/pam.d/sudo. The PAM_SERVICE variable then reads sudo, which you can include in the message.
More in Security
- UFW firewall on Ubuntu and Debian
- firewalld on Rocky Linux and AlmaLinux
- iptables rules that survive a reboot
- Block brute force logins with fail2ban
- CrowdSec intrusion prevention
- Two-factor SSH logins with TOTP
- Disable or restrict root login
- Advanced OpenSSH settings
- Publish SSH host keys in DNS (SSHFP)
- Audit open ports with nmap
- File integrity checks with AIDE and Tripwire
- CSF firewall (ConfigServer Security)
- First security steps on Rocky and Alma
- Free TLS certificates with Certbot
- Self-signed certificates and a private CA
- Rate and connection limits in Nginx
- Wazuh security monitoring
- Kernel and sysctl hardening