Skip to content

Instantly share code, notes, and snippets.

@ianblenke
Last active August 29, 2015 14:13
Show Gist options
  • Save ianblenke/0d8b4bd2480f43df10b2 to your computer and use it in GitHub Desktop.
Save ianblenke/0d8b4bd2480f43df10b2 to your computer and use it in GitHub Desktop.
A braindead simple bash script for systemd hosts that uses etcd to track whitelisted and blacklisted IPs before running: ip route add blacklist $ip
#!/bin/bash
set -eo pipefail
case $1 in
stop)
if [ ! -f /var/run/blackhole.pid ] ; then
echo "Lack of /var/run/blackhole.pid means there is nothing to stop" 1>&2
exit 1
fi
kill $(cat /var/run/blackhole.pid)
;;
start)
if [ -f /var/run/blackhole.pid ] ; then
echo "According to /var/run/blackhole.pid, this script is already running. Exiting." 1>&2
exit 1
fi
echo $BASHPID > /var/run/blackhole.pid
(
last --time-format notime -awi | grep pts | cut -c38-
fleetctl list-machines --fields=ip -no-legend
) | sort | uniq | while read ip ; do if ! etcdctl get /blackhole/whitelist/$ip > /dev/null 2>&1 ; then date | etcdctl set /blackhole/whitelist/$ip; fi; done
(
/usr/bin/journalctl -f -o json | \
grep --line-buffered sshd | \
grep --line-buffered 'Disconnecting: Too many authentication failures\|Failed password for' | \
sed -u -e 's/^.*sshd@.*:22-//' -e 's/:.*$//' | \
while read ip; do \
if ! etcdctl get /blackhole/whitelist/$ip > /dev/null 2>&1; then \
date | etcdctl set --ttl 3600 /blackhole/blacklist/$ip ; \
ip route add blackhole $ip 2>/dev/null | true ; \
fi ; \
done &
CHILD_PID=$!
(( JOURNALCTL_PID = $CHILD_PID + 1 ))
_term() {
echo Killing journalctl pid $JOURNALCTL_PID 2>&1
kill $JOURNALCTL_PID
exit 0
}
trap _term SIGINT SIGTERM EXIT
wait $CHILD_PID
) &
CHILD_PID=$!
(( BLACKHOLE_PID = $CHILD_PID + 1 ))
_term() {
echo Killing blackhole pid $BLACKHOLE_PID 2>&1
kill $BLACKHOLE_PID > /dev/null 2>&1 || true
rm -f /var/run/blackhole.pid
exit 0
}
trap _term SIGINT SIGTERM EXIT
echo $BASHPID > /var/run/blackhole.pid
wait $CHILD_PID
;;
*)
echo "Unknown argument: '$1' Did you mean 'start' or 'stop'?"
exit 1;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment