2014년 2월 27일 목요일

iptables를 이용하여 mac addr 필터링 하기

[출처 : http://kldp.org/ ]

#!/bin/sh
# PlusGenie Ltd
#set -x
 
DB_FILE=mac_dbfile.txt
DOOR=24810
 
# port example, 135:139 for range
 
function filter_one {
        iptables $1 INPUT $2 --protocol tcp --destination-port $DOOR -m mac --mac-source $3 -j ACCEPT > /dev/null 2>&1
        iptables $1 INPUT $2 --protocol tcp --source-port $DOOR -m mac --mac-source $3 -j ACCEPT  > /dev/null 2>&1
        iptables $1 INPUT $2 --protocol udp --destination-port $DOOR -m mac --mac-source $3 -j ACCEPT > /dev/null 2>&1
        iptables $1 INPUT $2 --protocol udp --source-port $DOOR -m mac --mac-source $3 -j ACCEPT > /dev/null 2>&1
}
 
 
#deny all other traffic
function filter_other {
        iptables $1 INPUT --protocol tcp --destination-port $DOOR -j DROP
        iptables $1 INPUT --protocol tcp --source-port $DOOR -j DROP
        iptables $1 INPUT --protocol udp --destination-port $DOOR -j DROP
        iptables $1 INPUT --protocol udp --source-port $DOOR -j DROP
}
 
if [ ! -e $DB_FILE ]; then
        echo "There is no config file"
        exit 1
fi
function setup_first_rule {
        echo "\n=====SETUP INIT RULES==========================="
        echo "Allow established sessions to receive traffic"
        iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
        # We need to insert this rule before that. Since this is a lot of traffic
        # we'll insert it as the first rule so it's processed first.
        echo "\n================================================"
        iptables -I INPUT 2 -i lo -j ACCEPT
        echo "\n================================================"
        echo "allow incoming traffic on the default SSH port (22)"
        iptables -A INPUT -p tcp --dport 22 -j ACCEPT
        echo "\n================================================"
#       echo "let's allow all incoming web traffic "
#       iptables -A INPUT -p tcp --dport 80 -j ACCEPT
}
 
#Just check whether we already set the rules or not
SETUP_DONE=0
for MAC in `cat $DB_FILE`; do
        if iptables -L | grep -q $MAC; then
                echo "checking configs"
                # Already add drop rules before
                SETUP_DONE=1
        fi
done
 
# let's set up the first rule
if [ $SETUP_DONE -eq 0 ]; then
        setup_first_rule
fi
 
for MAC in `cat $DB_FILE`; do
        if iptables -L | grep -q $MAC; then
                echo "already found in rules"
        else
        echo "\n================================================"
                echo "Inserting new rules"
                filter_one -I 4 $MAC
        fi
done
 
if [ $SETUP_DONE -eq 0 ]; then
        filter_other -A
fi
#Showing what we done:
#iptables -L -v

댓글 없음:

댓글 쓰기