Get an Email if Someone SSHs into Your Box

Graham Jenson
Maori Geek
Published in
2 min readJul 19, 2021

--

There are a couple different types of security; preventative will stop something bad from happening and detective will alert you when something bad does happen.

I have box that is SSH accessible on the internet that I want secure. There are lots of good sources for preventative SSH security (e.g. no passwords, tight config…) but not many for detective security. To be more secure (and decrease my paranoia) I want to be notified when someone SSH’s into that box from the wide internet, and I usually read my email.

The first part is being able to send an email from a script. I could use any old SMPT server, but using an authorised one will decrease the chance my email goes straight to spam. I use Gmail’s SMTP server since it is pretty easy to setup.

SSMTP is a pretty simple tools to send mail from the command line, it just needs a config like:

# /etc/ssmtp/ssmtp.conf# Use gmails SMTP
mailhub=smtp.gmail.com:587
UseSTARTTLS=YES
hostname=localhost
# Setup gmail
root=<user@gmail.com>
AuthUser=<user@gmail.com>
AuthPass=<gmail_password>
# Dont let SSMTP override FROM address
FromLineOverride=NO
  1. <user@gmail.com> is the user that authenticates to the SMTP server. I recommend setting up a new gmail account not used for anything else.
  2. <gmail_password> is either the normal gmail password (no 2FA and you have to enable less secure apps access) or generate unique app password.

With this you can send a test email with:

echo “Test Email” | ssmtp -vv <your_email@gmail.com>

Next is to set up a PAM script to be called when someone creates an SSH session. I followed this answer on askubuntu.com which I will outline below.

Create the file /etc/pam.d/email-on-login.sh:

#!/bin/bash
recepient="<your_email@gmail.com>"
if [ "$PAM_TYPE" != "close_session" ] && \
[[ "$PAM_RHOST" != 10.0.0.* ]] ; then
host="`hostname`"
subject="Subject: SSH Login: $PAM_USER from $PAM_RHOST on $host"
message="You should check on that"
printf "$subject\n$message" | ssmtp "$recepient"
fi

This is the script to execute when a SSH session is opened. It sends an email on the write PAM_TYPE and if the address is not from the local network.

To execute this on each session, add to /etc/pam.d/sshd the line:

session optional pam_exec.so seteuid /etc/pam.d/email-on-login.sh

This was a post with very little detail in it, leaving many questions unanswered like:

  1. What is SMTP?
  2. What is PAM?
  3. How many emails per second does it take to get banned from Gmails SMTP server?

They will remain unanswered unless you read one of these:

  1. Privileged Access Management (PAM)
  2. Simple Mail Transfer Protocol (SMTP)
  3. Gmail SMTP server limits (about 100 per day)

--

--