Setup server alerts using webhooks

If you’re using self-hosted servers, you might have run into this (or similar) blog which covers most of the things you need to do on your first login to the server.

Over the past weeks, I’ve failed to setup mail alerts on ssh login, sudo, and other events due to the various cloud providers blocking the SMTP ports for security reasons and making it difficult to setup a Mail Transfer Agent (MTA) quickly.

Slack alerts seemed to be the next logical step, and it takes considerably less time to setup. We’ll be leveraging Unix systems’ Pluggable Authentication Module (PAM) – which can be configured under /etc/pam.d – to setup slack alert on ssh login and logout events.

The following steps shall guide you to easily setup the same and maybe adapt the process to other services like discord, telegram, or what have you.



if [ "$PAM_TYPE" == "open_session" ] || [ "$PAM_TYPE" == "close_session" ]; then
    content="\"attachments\": [{ 
        \"mrkdwn_in\": [\"text\", \"fallback\"], 
        \"fallback\": \"Event : $PAM_TYPE to \`$HOST\`\", 
        \"text\": \"SSH: $PAM_TYPE to \`$HOST\`\", 
        \"fields\": [ { 
                \"title\": \"User\", 
                \"value\": \"$PAM_USER\", 
                \"short\": true 
            }, { 
                \"title\": \"IP Address\", 
                \"value\": \"$PAM_RHOST\", 
                \"short\": true 
        } ],
        \"color\": \"#f30c00\" 
    curl -X POST --data-urlencode \
                \"channel\": \"$CHANNEL\",
                \"mrkdwn\": true, 
                \"username\": \"SSH Notifications\", 
                \"icon_emoji\": \":warning:\"}" \
        "$WEBHOOK_URL" &
$ chmod +x /usr/local/sbin/ssh-slack
$ sudo echo "session   optional   /usr/local/sbin/ssh-slack" >> /etc/pam.d/sshd