Computerglitch

An ongoing adventure

Extract IP's From a PF Table

This is a script I wrote to extract IP addresses from a table in pf.


I use this script in conjuction with my sshblock script which can be found here. I have only used/tested this script on openbsd so if you are using another OS you will need to modify the script accordingly.


First create the file extractip and make it executable:

# touch extractip
# chmod +x extractip

Next add the following lines to extractip with your favorite text editor:[download extractip]

#!/bin/sh
#Script to extract IP's from a pfctl table
#Created by: greEd 10/24/06

#SPECIFY THE PF TABLE NAME
TABLE=kiddies
#SPECIFY THE BLACKLIST DIRECTORY [NO TRAILING "/"]
LOCATION=/var/www/blacklist

#RUN THE SCRIPT
BLACKLIST=$LOCATION/blacklisted
SNAPSHOT=$LOCATION/list.tmp
COMPARE=$LOCATION/tmp.tmp
DIF=$LOCATION/dif.tmp

if [ -f $SNAPSHOT ]; then
pfctl -t $TABLE -vTshow | awk '{print $1}' | sed 's/Cleared://' | sed 's/In\/Block://' | sed 's/In\/Pass://' | sed 's/Out\/Block://' |
sed 's/Out\/Pass://' | sed '/./!d' > $COMPARE
diff -n $SNAPSHOT $COMPARE | sed -e '/a/d' | sed -e '/d/d' > $DIF
cat $DIF >> $SNAPSHOT
sed -n 'G; s/\n/&&/; /ˆ\([ -~]*\n\).*\n\1/d; s/\n//; h; P' $SNAPSHOT > $BLACKLIST
rm $COMPARE
rm $DIF
cat /dev/null > $SNAPSHOT
else
pfctl -t $TABLE -vTshow | awk '{print $1}' | sed 's/Cleared://' | sed 's/In\/Block://' | sed 's/In\/Pass://' | sed 's/Out\/Block://' |
sed 's/Out\/Pass://' | sed '/./!d' > $SNAPSHOT
fi

Modify the lines TABLE, and LOCATION to fit your environment.


Execute the script twice to get it rolling:

# ./extractip

The file specified in LOCATION will now be populated with the ip addresses in TABLE.


You can add the following line to /etc/pf.conf to keep the table populated with the ip addresses in the blacklist:

table <kiddies> persist file "/var/www/blacklist/blacklisted"

Modify <kiddies> and /var/www/blacklist/blacklisted to match your environment.

Comments