loading...
Cover image for SSH Login Notifications in Slack
PullRequest

SSH Login Notifications in Slack

bangel profile image Brennan Originally published at pullrequest.com on ・1 min read

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.

We're 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.

2. 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 <YOUR SLACKWEBHOOK> with the URL from step 1 and #channel with the channel you want notifications going to)

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

3. Add the script to your pam.d
sudo echo "session optional pam_exec.so seteuid /etc/ssh/scripts/sshnotify.sh" >> /etc/pam.d/sshd

4. Verify the installation

Log out and log back into your box to verify a notice hits your channel of choice.

Posted on by:

bangel profile

Brennan

@bangel

Hi DEV Community, I'm passionate about clean code and code review Check out PullRequest.com where professional code reviewers backed by automation help you improve your code

PullRequest

PullRequest is a platform for code review, built for teams of all sizes. We have the world's largest network of on-demand reviewers, backed by best-in-class automation tools. Because code quality is important.

Discussion

markdown guide