Last active
December 1, 2017 07:31
-
-
Save subfission/7d81335e35d2bc32ea216b4cc0e6628b to your computer and use it in GitHub Desktop.
Script to ban attackers using HostGator Firewall, CPHulk, and iptables.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Script: hgfban | |
# | |
# Written By: Zach Jetson | |
# | |
# This script is intented to be used with webservers that | |
# consume flat files for banning hosts by IP. | |
# | |
# Copy this file in /opt/hgfban with execute permissions: chmod+x | |
# | |
# Add this to cPHulk Brute Force Protection "command to run" | |
# to auto-ban SSH abusers through HostGator firewall. | |
# /opt/hgfban %remote_ip% | |
# | |
BANFILE=/etc/firewall/IPDROP_GLOBAL | |
# Uncomment the line below to email notifications. | |
#EMAIL_ALERT="[email protected]" | |
if [ $(whoami) != "root" ]; then | |
echo "$0 must be run as root... Aborting."; exit 192 | |
fi | |
if [[ "$#" -eq 0 ]]; then | |
echo "Missing host to ban!"; exit 1 | |
fi | |
IP=$1 | |
REASON=$2 | |
if iptables -L -n -v | grep -q "$IP"; then | |
echo "IP address already banned: $IP" | |
exit 1 | |
fi | |
if [[ $IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then | |
# This bans the IP address using HG chain, which is cleanest menthod. | |
# Do not change this unless you stop using the HGF. | |
/sbin/iptables -A ipdrop_global -s $IP -j DROP | |
# Dump the banned IP into the ban file incase the the FW is restarted. | |
echo "$IP" >> $BANFILE | |
# dont restart firewall as the rule is already embedded into iptables | |
# /etc/rc.d/init.d/firewall restart | |
else | |
echo "invalid or no IP address given" | |
exit 1 | |
fi | |
if [ -z "${EMAIL_ALERT}" ]; then | |
exit 0 | |
fi | |
IP_INFO=$(curl --silent http://ipinfo.io/$IP 2>/dev/null) | |
# Use this method if hitting the 1000 api call limit. This method | |
# is not updated as frequently and requires geoip to be installed. | |
# install: sudo yum install geoip | |
#IP_INFO=$(geoiplookup $IP 2>/dev/null) | |
/bin/mail -s "HGFBAN: banned IP" -S from="no-reply<no-reply@$(hostname)>" $EMAIL_ALERT <<MSG_BODY | |
Banned IP: $IP | |
Date: $(date) | |
$REASON | |
$IP_INFO | |
MSG_BODY |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
updated for heredoc usage.