Installing fail2ban and blockng unsuccessful SSH login attempts is one thing, but how do we deal with successful breaches?
Let's assume someone has already obtained your SSH private key, or exploited a zeroday bug in SSH - we need to be able to know when this happens and take appropriate steps.

You will want to install and configure a Mail Transport Agent to send email notifications.

Create a mail notification script

Create a new BASH script : /usr/bin/pam_mail_notify

#!/bin/sh
if [ "$PAM_TYPE" = "open_session" ]
then
  {
	echo "User:        $PAM_USER"
	echo "Remote Host: $PAM_RHOST"
	echo "Service:     $PAM_SERVICE"
	echo "TTY:         $PAM_TTY"
	echo "Date:        `date`"
	echo "Server:      `uname -a`"
  } | mail -s "$PAM_SERVICE login on `hostname -s` for account $PAM_USER" <you@email.domain>
fi
exit 0

Add a script option to PAM

In PAM’s SSH configuration file: /etc/pam.d/sshd, add this line at the bottom of the file:

# on any activity, execute send_email.sh
session   optional      pam_exec.so /usr/bin/pam_mail_notify

The optional keyword is very important here as PAM will still allow login, even if the email script fails.

The other value allowed is: required, which will always execute the script on login. If the script fails when the setting is required, login will fail, even with proper login authentication.

Tags