Email notification on SSH login using PAM
There are cases where you are interested in getting a email message on every successful login through SSH. This could have been solved by adding a simple line in .bash_profile for every user, but this solution does not catch all SSH logins. The preferred way of doing it is by using PAM and a custom email notify script.
Add the following line to the bottom of file /etc/pam.d/sshd
session optional pam_exec.so seteuid /usr/local/bin/login-notify.sh
This is the contents of /usr/local/bin/login-notify.sh
#!/bin/sh # Change these two lines: sender="root@example.com" recepient="root" if [ "$PAM_TYPE" != "close_session" ]; then host="`hostname`" subject="SSH Login: $PAM_USER from $PAM_RHOST on $host" # Message to send, e.g. the current environment variables. message="`env`" echo "$message" | mailx -r "$sender" -s "$subject" "$recepient" fi
Make the script executable
# chmod 0700 /usr/local/bin/login-notify.sh
This is the email message you receive the next time you or someone else log in using SSH
SSH Login: username from hostname-remote.user.com on target-host.example.com
XDG_SESSION_ID=775
SELINUX_ROLE_REQUESTED=
PAM_SERVICE=sshd
SELINUX_USE_CURRENT_RANGE=
PAM_RHOST=hostname-remote.user.com
PAM_USER=username
PWD=/
SELINUX_LEVEL_REQUESTED=
SHLVL=1
PAM_TYPE=open_session
PAM_TTY=ssh
XDG_RUNTIME_DIR=/run/user/9000
_=/usr/bin/env
This has been tested on CentOS 7 and Ubuntu 18.04, but I guess most recent distributions supports this.
DATA PRIVACY
Sending emails on login may conflict with data privacy on multiuser systems. This can be circumvented by just sending emails for specific users or root (if at all accessible via SSH). I might cover that in a later post.