Linux self-service firewall with Apache, Perl, IPtables, and UFW

I was recently in a situation where I was offering DNS service to some people. There just happened to be some records that were different from their ISPs DNS servers so I set up the server on my public IP address. I did not want to offer DNS to the world because last time I tried that, I got queries from all kinds of places for all kinds of records. I was initially opening up IP tables when people asked for the service and give me their IP address. After getting about 10 texts, I quickly got tired of collecting the IP addresses, so I made a webpage and with the perl script to write them to a list. With that, I would have a cron jobs go through the list and use UFW to update the IPTables to allow them access.

Here are the files inside of the directory where I’m creating the list.
dnsauth.tar

There’s a simple index.html file in the directory. It’s basically a form that asks for:
Name – who the person is. duh!
IP address – I want them to enter the IP address they want to authorize just in case they’re submitting someone else’s IP address.
Password – I don’t want just anyone to come in and get access to my DNS server.

The addip.cgi basically just writes all of those inputs and the IP address they’re coming in from into /tmp/iplist.txt in CSV format. I record the IP address they’re coming in from $ENV{‘REMOTE_ADDR’} just in case I get abuse or something.

The root user then has a cron job that runs through the iplist.txt file every 10 minutes. Here’s my file:

#!/bin/sh
if [ -f /tmp/iplist.txt ]; then
DATE=$(date +%Y%m%d)
cp /tmp/iplist.txt /home/alton/dnsservice/iplist.txt.$DATE
for i in `grep rice /tmp/iplist.txt | cut -f1 -d','`; do /usr/sbin/ufw insert 1 allow proto udp from $i to any port 53; done
grep rice /tmp/iplist.txt >> /home/alton/dnsservice/authorized_dns_ips.txt
grep -v rice /tmp/iplist.txt >> /home/alton/dnsservice/cheaters.txt
rm -rf /tmp/iplist.txt
sync
fi

Obviously, rice was my password. I just looped through the file and authorized anyone that used the right password. I also logged anyone that used the wrong password in /home/alton/dnsservice/cheaters.txt.

Hope this was useful! I welcome any comments. Obviously, this was quick and dirty. I’m sure there is a more secure way of doing this, but this is what came easy to me. Would love to hear your thoughts!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.