Send Mail for every SSH Login

If you’re googling this topic there is an unbelievable amount of grossly negligent “solutions” to this problem.

The top two results in my search engine tell you to do this:

$ cd /root
$ vi .bashrc

And trigger some mail there with the information wanted. This is insecure for multiple reasons:

  1. One can login via SSH without triggering the .bashrc file. For example with ssh -N
  2. This is the most important part: You should never ever enable direct ssh login for root! The fact that those tutorials are encouraging such behaviour is sick
  3. Every authentication should only and only be managed by PAM

This is the reason why I have the following setup I hereby share with you:

This script (placed somewhere in your system) is used to send a mail after a login. To trigger it, PAM has to be told so in /etc/pam.d/sshd:

session optional pam_exec.so seteuid /etc/ssh/login_notify.sh

The second word optional is important here as it allows a login even if the script doesn’t exit with code 0. If you replace it with required the login will fail if the script fails. This might not be what you want because the mail sending process may be broken because some issues your server might have and this will prevent you from logging in. Don’t forget to make the script itself executable:

chmod +x /path/to/login_notify.sh