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="[email protected]"
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