On servers I maintain I usually have a script running that sends an email whenever someone logs in via SSH. It allows me to keep track on whether something fishy is going on in a very easy way.
It’s not bulletproof but at least provides me with a certain level of safety that everything is all right.
The other day I had to reinstall a server after some time and of course I had to – again – search for how to set that email script up.
So here’s the instructions:
Create the executable that will send the email
First we need a script that will send the email. Take this as a template:
#!/bin/sh
EMAIL_TO="sysadmin+misc@example.com"
EMAIL_FROM="ssh-alert@server.example.com"
SUBJECT="SSH Login Notification"
MESSAGE="
A user signed into your server through SSH.
-------------------------------------------
Username: ${PAM_USER}
IP Address: ${PAM_RHOST}"
if [ ${PAM_TYPE} = "open_session" ]; then
echo "${MESSAGE}" | mail -n -r "${EMAIL_FROM}" -s "${SUBJECT}" "${EMAIL_TO}"
fi
exit 0
test
Store this file wherever you like, I put it into /etc/pam_scripts/login_email_notification.sh
but it is really irrelevant where it is.
The variables PAM_USER, PAM_RHOST and PAM_TYPE will be replaced by the PAM system. A tad more on that shortly.
Next we need to make this script executable by running something along the line of sudo chmod 755 /etc/pam_scripts/login_email_notification.sh
Execute the script on SSH-Login
To execute this script now on login I added it to the servers PAM-scripts. The Pluggable Authentication Modules allow for each service to have files executed. SO for SSH there usually is a file /etc/pam.d/sshd
that contains a log of information.
The for me interesting part is that I can add this at the end:
# Login Email Notification
session required pam_exec.so /etc/pam_scripts/login_email_notification.sh
Save this file and on the next login via SSH on the machine you should receive an email.
That is: When your email system on the machine is set up properly…