#!/bin/bash

#this script written by Steve Murphy
# It will upgrade the whitelisting of IP's in fail2ban, by looking at all current
# sip peers' IPs, and adds them to the ignoreip in the jail.conf file.
# It keeps the current list, and makes sure that duplicates are removed.
# This script can be safely run during the day, and probably should be,
# as it raises the probability that all phones are logged in and registering.
# As our fail2ban asterisk filters get more stringent, this is the las bastion
# of defense against "false positives", and also protects us against DOS attackes
# this shoudl probably be run every time new phones or new networks are added to the GUI.

#it will also capture the trunk connections, and make sure that fail2ban doesn't ban a trunk IP.
# It collects all private IP addresses like 10.x.x.x and 192.168.x.x addresses, and represents
# them with 10.0.0.0/8 and 192.168.0.0/16 entries. Broadvox addresses are also so covered.

# Tested on 35 machines so far, seems to work fine!


rasterisk -x "sip show peers"  | sed -e "1D" -e "/ sip peers /D" -e "/(Unspecified)/D" -e '/\[0m/D' -e 's/^[^ ]\+ \+\([^ ]\+\) \+.\+/\1/' | sed -e 's/208\.93\.[0-9]\+\.[0-9]\+/208.93.224.0/' -e 's/10\.[0-9]\+\.[0-9]\+\.[0-9]\+/10.0.0.0/' -e 's/192\.168\.[0-9]\+\.[0-9]\+/192.168.0.0/' | sort | uniq > /tmp/xx1

them=`grep ignoreip /etc/fail2ban/jail.conf | sed -e 's/ignoreip *= *127.0.0.1//'`
echo -n "" > /tmp/xx2
for i in $them; do
        echo $i >> /tmp/xx2
done

sort /tmp/xx2 | uniq > /tmp/xx2a

x=`sort -m /tmp/xx1 /tmp/xx2a | sed -e 's@208\.93\.[0-9]\+\.[0-9]\+\(/[0-9]\+\)\?@208.93.224.0/22@' -e 's@10\.[0-9]\+\.[0-9]\+\.[0-9]\+\(/[0-9]\+\)\?@10.0.0.0/8@' -e 's@192\.168\.[0-9]\+\.[0-9]\+\(/[0-9]\+\)\?@192.168.0.0/16@' | uniq | sed -e :a  -e N -e 's/\n/ /' -e ta`

sed -e "s@ignoreip.\\+@ignoreip = 127.0.0.1 $x@" -ibup -c /etc/fail2ban/jail.conf
