Skip to content

Instantly share code, notes, and snippets.

@samuraee
Last active November 9, 2021 09:14
Show Gist options
  • Save samuraee/dc3a8d06f601b2def0afb2b6fd3fcb48 to your computer and use it in GitHub Desktop.
Save samuraee/dc3a8d06f601b2def0afb2b6fd3fcb48 to your computer and use it in GitHub Desktop.
SSH Login Notifications in Slack

SSH Login Notifications in Slack

It’s handy to know who’s logging into servers around your projects. Slack offers a beautiful way to do this in combination with pam.d.

I am assuming you’re using a CentOS-derived OS for locations, but this should work on any *nix-based OS with pam.d enabled.

  1. Add an incoming webhook in Slack – navigate to: https://YOUR_DOMAIN.slack.com/apps/manage/custom-integrations We recommend naming the spot something that is recognizable; that way it won’t get deleted in the future.

Make sure to copy the Webhook URL from the resulting page.

  1. Add an SSH script to your server Add and make executable (chmod+x) file to /etc/ssh/scripts/sshnotify.sh (note Make sure to replace with the URL from step 1 and #channel with the channel you want notifications going to)
#!/bin/bash

PATH=/bin:/usr/bin
  
if [ "$PAM_TYPE" != "close_session" ]; then
        url="<YOUR SLACK WEBHOOK>"
        channel="#channel"
        host="$(hostname)"
        content="\"attachments\": [ { \"mrkdwn_in\": [\"text\", \"fallback\"], \"fallback\": \"SSH login: $PAM_USER connected to \`$host\`\", \"text\": \"SSH login to \`$host\`\", \"fields\": [ { \"title\": \"User\", \"value\": \"$PAM_USER\", \"short\": true }, { \"title\": \"IP Address\", \"value\": \"$PAM_RHOST\", \"short\": true } ], \"color\": \"#F35A00\" } ]"
        curl -X POST --data-urlencode "payload={\"channel\": \"$channel\", \"mrkdwn\": true, \"username\": \"SSH Notifications\", $content, \"icon_emoji\": \":inbox-tray:\"}" "$url" &
fi
exit
  1. Add the script to your pam.d
sudo echo "session optional pam_exec.so seteuid /etc/ssh/scripts/sshnotify.sh" >> /etc/pam.d/sshd
  1. Verify the installation Log out and log back into your box to verify a notice hits your channel of choice.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment