Description:

A simple shell script that executes automatically once a ssh user logs into a server with SSH. The script sends a Signal encrypted message to a phone number of your choice. It also has features to identify the user who has just logged in.

The script reports the following:

  1. Date and time.
  2. Username used to gain ssh login.
  3. The IP address of the user trying to login.
  4. The AS code of the User trying to login.
  5. Physical address and the country of the user attempting login.
  6. SSH port the login was attempted on.

Operational security disclaimer:

This script isn’t designed to gain logs of ‘anyone’ trying to gain authorized/unauthorized access to a machine with SSH. But it can be modified to do so. This script focus on notifying the owner of a machine if anyone has attempted successful login with SSH. THIS IS DETECTION, NOT PREVENTION.

Prerequisites:

  • Second phone number to be used in the script for sending signal texts to your phone.
  • A SSH machine with sudo access.
  • Signal-cli installed and registered. Follow instructions at https://github.com/AsamK/signal-cli
DATE_EXEC="$(date "+%d %b %Y %H:%M")" #Collect date & time.
TMPFILE='/tmp/ipinfo-$DATE_EXEC.txt' #Create a temporary file to keep data in.
if [ -n "$SSH_CLIENT" ] && [ -z "$TMUX" ]; then #Trigger
IP=$(echo $SSH_CLIENT | awk '{print $1}') #Get Client IP address.
PORT=$(echo $SSH_CLIENT | awk '{print $3}') #Get SSH port
HOSTNAME=$(hostname -f) #Get hostname
IPADDR=$(hostname -I | awk '{print $1}')
curl https://ipinfo.io/$IP -s -o $TMPFILE #Get info on client IP.
CITY=$(cat $TMPFILE | sed -n 's/^  "city":[[:space:]]*//p' | sed 's/"//g') #Client IP info parsing
REGION=$(cat $TMPFILE | sed -n 's/^  "region":[[:space:]]*//p' | sed 's/"//g')
COUNTRY=$(cat $TMPFILE | sed -n 's/^  "country":[[:space:]]*//p' | sed 's/"//g')
ORG=$(cat $TMPFILE | sed -n 's/^  "org":[[:space:]]*//p' | sed 's/"//g')
TEXT="$DATE_EXEC: ${USER} logged in to $HOSTNAME ($IPADDR) from $IP - $ORG - $CITY, $REGION, $COUNTRY port $PORT"
signal-cli  -u +<senders phone> send -m "$TEXT" +<recipient> #  Replace <>s with phone numbers with the country code.
rm $TMPFILE #clean up after
fi

Raw script: https://gitlab.com/snippets/1871386/raw

Instructions:

  1. Install and test Signal-cli. AUR Package is available https://aur.archlinux.org/packages/signal-cli/
  2. Clone the script on your target machine. Edit the sshd file located at

    /etc/pam.d/sshd
    

    and add the following line at the end of the file

    session optional pam_exec.so /<path_to_yourscript.sh>
    

    IMPORTANT

    Setting the session to ‘optional’ will allow the user to login in case the script fails. (ex. Telegram servers are down) This prevents you from being locked out. But setting the session to ‘required’ will enforce the execution of this script as absolute.

  3. Edit the script and add the senders and recipients phone number with country codes. (ex. +11234567890)