Thursday, January 9, 2014

simple mac-binding using iptables

This script/article is useful when your have linux gateway as distribution and you want to bind the mac address of your client to specific ip address. We are using iptables here for this tasks.

#create a file called macfilter.sh using touch command with following contents

#!/bin/bash
#info@allaboutlinux.info


#display messages
echo "Mac Filter Staring"
/sbin/iptables -F             #flushing iptables rules


/sbin/iptables A INPUT -s ipaddress -m mac --mac-source macaddress -j ACCEPT
/sbin/iptables -A INPUT -s ipaddress -j DROP
/sbin/iptables -A INPUT -m mac --mac-source macaddress -j DROP

/sbin/iptables A FORWARD -s ipaddress -m mac --mac-source macaddress -j ACCEPT
/sbin/iptables -A FORWARD -s ipaddress -j DROP
/sbin/iptables -A FORWARD -m mac --mac-source macaddress -j DROP

echo "Mac Filter Applied"

Make sure you have given execute permission using chmod a+x /etc/macfilter.sh and put it in startup at /etc/rc.local :)


This is very basic script and need lots of lines if you have multiple clients. Here is simplified version using input from file.



#!/bin/bash
#info@allaboutlinux.info

echo "Mac Filter Staring"
/sbin/iptables -F             #flushing iptables rules



while read ipadd macadd clientname; do
        echo "Binding IP " $ipadd "with mac" $macadd  "of client" $clientname "\n"
        /sbin/iptables -A INPUT -s $ipadd -m mac --mac-source $macadd -j ACCEPT
        /sbin/iptables -A INPUT -s $ipadd -j DROP
        /sbin/iptables -A INPUT -m mac --mac-source $macadd -j DROP

        /sbin/iptables -A FORWARD -s $ipadd -m mac --mac-source $macadd -j ACCEPT
        /sbin/iptables -A FORWARD -s $ipadd -j DROP
        /sbin/iptables -A FORWARD -m mac --mac-source $macadd -j DROP

done < "/etc/mac.txt"


Create a file mac.txt in /etc with following contents in order
ipaddress       macaddress       clientname (just to show the order, donot include this in file)

1.1.1.1      00:00:00:11:11:11       ClientA

sample output 







Further the scripts can be make more efficient using perl or bash scripting with mysql as backend so that everything can be controlled from frontend without logging into the machine itself :) .




No comments :

Post a Comment