If you manage a remote server, and you are a bit paranoiac about the bad guys outside, it could be nice to have some sort of notification every time a SSH connection is successful.
I found this post and it seems working pretty well for me as well.
I’ve installed this on my CentOS7 server and seems working good! Of course, this in addition to an aggressive Fail2Ban setup.
- Make sure you have your MTA (Postfix/Sendmail…) configured to deliver emails to the user root
- Make sure you get the emails for the user root (otherwise doesn’t make any sense 😛 )
- Create this script (this is a slightly modified version comparing with the one in the original post:
#!/bin/sh if [ "$PAM_TYPE" != "open_session" ] then exit 0 else { 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` from user $PAM_USER@$PAM_RHOST" root fi exit 0
- Set the permission:
chmod +x /usr/local/bin/send-mail-on-ssh-login.sh
- Append this line to /etc/pam.d/sshd
session optional pam_exec.so /usr/local/bin/send-mail-on-ssh-login.sh
- …and that’s it! 😉
If you’d like to have a specific domain/IP whitelisted, for example if you don’t want to get notified when you connect from your office or your home (fixed IP or dynamic IP is required), you can use this version of the script:
#!/bin/bash if [ "$PAM_TYPE" != "open_session" ]; then exit 0 else MSG="$PAM_SERVICE login on `hostname -s` from user $PAM_USER@$PAM_RHOST" # check if the PAM_RHOST is shown as IP echo "$PAM_RHOST" | grep -q -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' if [ $? -eq 0 ]; then SRCIP=$PAM_RHOST else SRCIP=$(dig +short $PAM_RHOST) fi SAFEIP=$(dig +short myofficedomain.com) if [ "$SRCIP" == "$SAFEIP" ]; then echo "Authorised $MSG" | logger else { 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 "Unexpected $MSG" root fi fi exit 0
The script will send an email ONLY if the source IP is not the one from myofficedomain.com; however, it will log the authentication in /var/log/messages using logger command.