Skip to content

Instantly share code, notes, and snippets.

@thelfensdrfer
Forked from Nihisil/jail.local
Last active July 26, 2016 15:47
Show Gist options
  • Save thelfensdrfer/b842e656dfd3bbd38e6e to your computer and use it in GitHub Desktop.
Save thelfensdrfer/b842e656dfd3bbd38e6e to your computer and use it in GitHub Desktop.
Send notifications to the Slack from fail2ban
# /etc/fail2ban/jail.local
[...]
action_with_slack_notification = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
slack[name=%(__name__)s]
action = %(action_with_slack_notification)s
[...]
# /etc/fail2ban/action.d/slack.conf
[Definition]
actioncheck=
actionstart =
actionstop =
actionban = /bin/bash /etc/fail2ban/slack_notify.sh "Banned _country_ <ip> in the jail <name> after <failures> attempts" "<ip>" > /dev/null 2>&1
actionunban = /bin/bash /etc/fail2ban/slack_notify.sh "Unbanned _country_ <ip> in the jail <name>" "<ip>" > /dev/null 2>&1
# /etc/fail2ban/slack_notify.sh
#!/bin/bash
# message first command argument
MESSAGE=$1
HOOK_URL=YOUR_SLACK_WEBHOOK_URL
HOST=$(hostname)
CHANNEL="#security"
USERNAME="fail2ban"
ICON=":cop:"
# ip second command argument
IP=$2
# lets find out from what country we have our hacker
COUNTRY=$(curl ipinfo.io/${IP}/country)
# converting country to lover case. I love you bash script =\
COUNTRY=$(echo "$COUNTRY" | tr -s '[:upper:]' '[:lower:]')
# slack emoji
COUNTRY=":flag-$COUNTRY:"
# replace _country_ template to the country emoji
MESSAGE="${MESSAGE/_country_/$COUNTRY}"
curl -X POST --data-urlencode "payload={\"channel\": \"${CHANNEL}\", \"username\": \"${USERNAME}\", \"text\": \"[${HOST}] ${MESSAGE}\", \"icon_emoji\": \"${ICON}\"}" ${HOOK_URL}
exit 0
# /etc/ssh/slack_notify.sh
#!/bin/sh
if [ "$PAM_TYPE" != "close_session" ]; then
url="YOUR_SLACK_WEBHOOK_URL"
channel="#security"
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-bot\", $content, \"icon_emoji\": \":computer:\"}" $url
fi
# /etc/pam.d/sshd
[...]
session optional pam_exec.so seteuid /etc/ssh/slack_notify.sh
@JelmerT
Copy link

JelmerT commented Jul 26, 2016

Thanks for the added SSH login notification! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment