Notifications on successful SSH logins

By chimo on (updated on )

A long time ago, I setup mail notifications when a successful SSH login happens on Linode. While switching over to OVH, I realized I never really documented this anywhere. So here’s another note-to-self post.

Add the following line to “/etc/pam.d/system-remote-login”:

session   optional  pam_exec.so    /etc/pam.d/pam-notify-login.sh

This tells PAM to run the “pam-notify-login.sh” script on remote logins. The “/etc/pam.d/pam-notify-login.sh” script looks like:

#!/bin/sh

[ "$PAM_TYPE" = "open_session" ] || exit 0
{
  printf "Subject: $(hostname -s) $PAM_SERVICE login: $PAM_USER\n\n"
  echo "User: $PAM_USER"
  echo "Ruser: $PAM_RUSER"
  echo "Rhost: $PAM_RHOST"
  echo "Service: $PAM_SERVICE"
  echo "TTY: $PAM_TTY"
  echo "Server: `uname -a`"
  echo "Date: `date`"
  echo "Console: `who -a -H`"
} | msmtp -a default recipient@example.org

It uses “msmtp” to send an email to “recipient@example.org”. The config file for msmtp, located at “/root/.msmtprc” contains:

# Set default values for all following accounts.
defaults
auth           on
tls            on
tls_trust_file system
logfile        ~/.msmtp.log

# mail
account        pam
host           smtp.example.org # Change this
port           587
tls_starttls   on
from           "SSH Auth (pam)" <pam@example.org> # Change this
user           pam@example.org # Change this
password       hunter2 # Change this

# Set a default account
account default : pam

I might switch this responsibility to some log-monitoring mechanism when I get around to looking into that, but the PAM method has been working well for years now.

References: