SSH Login Notifications with Gotify
First I created created the file /usr/local/bin/sshnotif
. At the top you can add your own token and Gotify url
Update: I had to push the current time back a full minute in order to improve consistency. I'll defiantly want to revisit this at a later date
#!/bin/bash exec &> /dev/null #Hide output Gotify_URL='https://example.tld/gotify' Gotify_Token='gotify-app-token' notify() { now=$(date -d "-60 seconds" +%s) #Get current time minus 60 seconds end=$((SECONDS+30)) #Set 30s Timeout for loop while [ $SECONDS -lt $end ]; do SSHdate=$(date -d "$(who |grep pts|tail -1 | awk '{print $3, $4}')" +%s) #Check for the latest SSH session if [ $SSHdate -ge $now ]; then #Once who is updated continue with sending Notification title="SSH Login for $(/bin/hostname -f)" message="$(/usr/bin/who | grep pts)" /usr/bin/curl -X POST -s \ -F "title=${title}" \ -F "message=${message}" \ -F "priority=5" \ "${Gotify_URL}/message?token=${Gotify_Token}" break fi done } notify & #Run in background to prevent holding up the login process
Run the command chmod +x /usr/local/bin/sshnotif
In the file /etc/pam.d/sshd
add the following line
# note optional is set to prevent ssh login failure session optional pam_exec.so /usr/local/bin/sshnotif
I now get a nice notification with all the open SSH sessions listed. Unlike the post on 8192.one I didn't want any IP address resolution using an online service. I plan on integrating the MaxMind GeoLite2 database at some point. However as I already have Graylog set up to do this it's not a high priority for me.
Thanks for the shoutout: https://zerosec.xyz/posts/gotify-notifications/