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.
- 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.
- 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
- Add the script to your
pam.d
sudo echo "session optional pam_exec.so seteuid /etc/ssh/scripts/sshnotify.sh" >> /etc/pam.d/sshd
- Verify the installation Log out and log back into your box to verify a notice hits your channel of choice.