Recently I became aware of how hard it can be to notice that someone has accessed your machine. No one is going to monitor the system journal to find all successful login attempts and then crossreference them to their own memories of logging in.
And if a hacker wipes all the marks of their presence, you'd never know that all your ssh keys, configs with credentials, and password managers were stolen. BAAD!

So I set up email notifications for each successfully opened remote session using pam_exec.so module. But email isn't always reliable for notifications, so I use an SMTP to Telegram gateway. SMTP is widely supported by software for notifications, so this is a nice option. And I'm sure there are similar relays/gateways for different messengers.

Here is the notification script I used:

#!/bin/bash

# Your Email Information: Recipient (To:), Subject and Body
HOSTNAME=$(cat /etc/hostname)
SENDER="login@$HOSTNAME"
SUBJECT="Login on $HOSTNAME"

BODY="
A SSH login was successful, so here is some information for security:
  User:        $PAM_USER
  User IP Host: $PAM_RHOST
  Service:     $PAM_SERVICE
  TTY:         $PAM_TTY
  Date:        `date`
  Server:      `uname -a`
"

if [[ "${PAM_TYPE}" = "open_session" ]]; then
    curl --url 'smtp://<smtp_server>:<smtp_port>' --mail-from "$SENDER" --mail-rcpt "
mango@telegram.com" -T <(echo -e "From: $SENDER\\nTo: mango@telegram.com\\nSubject: New login\\n\\n$BODY")
fi

exit 0

Notice I didn't use SMTP authentication and SSL encryption in the curl command. That's intentional, because the SmtpTelegramGateway doesn't need authentication, and is hosted locally. Here is how you can modify the curl command to use SSL and authentication: stackoverflow.com/questions/14722556...

Save this script somewhere and make it executable. Then you need to add this line at the bottom of a pam config files:

session optional pam_exec.so /usr/local/bin/pam_alert.sh

You can add it to the /etc/pam.d/system-remote-login or /etc/pam.d/sshd file. I recommend you to try connecting to the machine in a new session to test if everything works before you close your current session. Otherwise, you could lock yourself out of the system.

You should receive an email that looks something like this:

A screenshot of the login notification


0 Comments latest

No comments.