Skip to content

Instantly share code, notes, and snippets.

@jakewarren
Last active March 27, 2023 20:50
Show Gist options
  • Save jakewarren/7e86405919dd640dcbfa9b6e9c067683 to your computer and use it in GitHub Desktop.
Save jakewarren/7e86405919dd640dcbfa9b6e9c067683 to your computer and use it in GitHub Desktop.
PAM configuration for sending email alerts for ssh logins

Receive an email alert for each ssh login. The script can be extended to support other notification methods such as Slack, etc.

mkdir -p /etc/pam.scripts
chmod 0755 /etc/pam.scripts
vim /etc/pam.scripts/ssh_alert.sh

add the following script to ssh_alert.sh, modifying the variables from their default value

#!/bin/bash

# Your Email Information: Recipient (To:), Subject and Body
RECIPIENT="test@example.com"
SUBJECT="SSH Login on example.com"

# enable IP whitelisting by setting to 'true'. doesn't alert if the ip address is contained within the whitelist
WHITELIST_ENABLED="true"

if [[ "$WHITELIST_ENABLED" == "true" ]]; then
	# use this regex to whitelist any IP addresses you want to ignore. 
    if [[ "$PAM_RHOST" =~ ^(1.1.1.1)$ ]]; then
        exit 0
    fi
fi

BODY="
A SSH login was successful, so here are 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
	echo "${BODY}" | mail -s "${SUBJECT}" ${RECIPIENT}
fi

exit 0

set the permissions on the script chmod 0700 /etc/pam.scripts/ssh_alert.sh

add the script to the PAM configuration vim /etc/pam.d/sshd

# SSH Alert script
session optional pam_exec.so /etc/pam.scripts/ssh_alert.sh

Receive a pushover notification for each ssh login.

mkdir -p /etc/pam.scripts
chmod 0755 /etc/pam.scripts
vim /etc/pam.scripts/ssh_alert.sh

add the following script to ssh_alert.sh, modifying the variables from their default value

#!/bin/bash

# enable IP whitelisting by setting to 'true'. doesn't alert if the ip address is contained within the whitelist
WHITELIST_ENABLED="true"

if [[ "$WHITELIST_ENABLED" == "true" ]]; then
	# use this regex to whitelist any IP addresses you want to ignore. 
    if [[ "$PAM_RHOST" =~ ^(1.1.1.1)$ ]]; then
        exit 0
    fi
fi

if [[ "${PAM_TYPE}" = "open_session" ]]; then
	curl -s \
    --form-string "token=APP_TOKEN" \
    --form-string "user=USER_KEY" \
    --form-string "message=SSH login for $PAM_USER on $HOSTNAME from $PAM_RHOST" \
    https://api.pushover.net/1/messages.json
fi

exit 0

set the permissions on the script chmod 0700 /etc/pam.scripts/ssh_alert.sh

add the script to the PAM configuration vim /etc/pam.d/sshd

# SSH Alert script
session optional pam_exec.so /etc/pam.scripts/ssh_alert.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment