DEV Community

Cover image for SSH Login Notifications in Slack
Brennan for PullRequest

Posted on • Originally published at pullrequest.com on

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.

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.

Top comments (1)

Collapse
 
boly38 profile image
Brice • Edited

This post is 2 years old, anyway I'm using your tip.

Here is my feedback:

  • the script may be little more simple for a conventional slack hook (one channel only):
#!/bin/bash
if [ "$PAM_TYPE" != "close_session" ]; then
        SLACK_WEBHOOK_ENDPOINT=https://hooks.slack.com/services/blah/blahblah/blahblahblah
        host="$(hostname)"
        user="${PAM_USER}"
        remoteip="${PAM_RHOST}"
        curl -X POST --data "{\"type\": \"mrkdwn\",\"text\": \"${remoteip} - SSH Login : ${user} connected to \`$host\`\"}" ${SLACK_WEBHOOK_ENDPOINT}
fi
exit
Enter fullscreen mode Exit fullscreen mode
  • the script may start with shebang (#!/bin/bash) in order to avoid exit code 8

thanks for this tips πŸ‘