So having a bastion kind of server in any environment is nice but having bots trying to endlessly try and bruteforce such machines is a pain in the butt, so hardening them is crucial!
When using ssh, always use some kind of swiss cheese approach, eg. no passwords, only valid ssh-keys, no root, 2auth, limit number of users directly in ssh config, use custom ports and so on and on.
But even with all the precautions, you may never know so another good practice is logging and alerting!
So some of my bastions I also want to notify a slack chat if a client or some one logs onto the machine.
Edit the SSHD Configuration File
Open the
/etc/pam.d/sshdfile in a text editor. Add the following line to the end of the file:session required pam_exec.so /opt/scripts/login-logger.shThis line tells PAM (Pluggable Authentication Modules) to execute the
/opt/scripts/login-logger.shscript every time a user logs in or out via SSH.Create a Login Logger Script
Create a new file named
/opt/scripts/login-logger.shand paste the following code into it:#!/bin/sh LOG_FILE="/var/log/ssh-auth" WHITELIST_FILE="/etc/ssh/whitelist.txt" SLACK_NOTIFY_SCRIPT="/opt/scripts/slack-notify.sh" SLACK_WEBHOOK_URL="<YOUR_SLACK_WEBHOOK_URL>" SLACK_CHANNEL="" DATE_ISO=`date --iso-8601="seconds"` LOG_ENTRY="[${DATE_ISO}] ${PAM_TYPE}: ${PAM_USER} from ${PAM_RHOST}" if [ ! -f ${LOG_FILE} ]; then touch ${LOG_FILE} chown root:adm ${LOG_FILE} chmod 0640 ${LOG_FILE} fi if [ "${PAM_TYPE}" = "close_session" ]; then exit 0 fi # Check if the user is in the whitelist if grep -q "${PAM_USER}" "${WHITELIST_FILE}"; then echo "User ${PAM_USER} is in the whitelist. Not notifying Slack." else # Notify Slack using the Slack notification script in a separate shell ${SLACK_NOTIFY_SCRIPT} -u "${SLACK_WEBHOOK_URL}" -c "${SLACK_CHANNEL}" -m "User ${PAM_USER} logged in from ${PAM_RHOST}" & fi echo ${LOG_ENTRY} >> ${LOG_FILE} exit 0Make the Script Executable
Save the file and make it executable:
chmod +x /opt/scripts/login-logger.shCreate a Slack Notification Script
Create a new file named
/opt/scripts/slack-notify.shand paste the following code into it:#!/bin/bash while getopts "u:c:m:" opt; do case $opt in u) WEBHOOK_URL=$OPTARG;; c) CHANNEL=$OPTARG;; m) MESSAGE=$OPTARG;; \?) echo "Invalid option -$OPTARG" >&2 exit 1;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1;; esac done curl -sS -X POST -H 'Content-Type: application/json' -d "{\"text\":\"${MESSAGE}\",\"channel\":\"${CHANNEL}\"}" "${WEBHOOK_URL}"Make the Script Executable
Save the file and make it executable:
chmod +x /opt/scripts/slack-notify.shConfigure Your Slack Webhook URL
Edit the
SLACK_WEBHOOK_URLvariable in thelogin-logger.shscript and replace<YOUR_SLACK_WEBHOOK_URL>with the webhook URL for your Slack server.Specify the Slack Channel
Edit the
SLACK_CHANNELvariable in thelogin-logger.shscript and replace""with the name of the channel you want to send notifications.
That’s it!
Buy Me a Coffee