Python bindings for iptables
Welcome to python-iptables’s documentation! — python-iptables 0.4.0-dev documentation
How do I specify multi-argument matches with python-iptables?
For example, the following iptables
command:
-A INPUT -s 1.1.1.1 -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -j DROP
If I create the following:
import iptc
rule = iptc.Rule()
rule.src = '1.1.1.1'
rule.protocol = 'tcp'
t = rule.create_target('DROP')
m = rule.create_match('tcp')
m.tcp_flags = 'FIN,SYN,RST,ACK SYN'
it will complain:
ValueError: invalid value FIN,SYN,RST,ACK SYN
PS: I know that for my particular example, I can simply use m.syn = '1'
, but I'm trying to generalize on how to specify multi-argument matches.
Source: (StackOverflow)
I am using the script below to apply iptables
by filtering IP from the whitelist.txt
file.
if I have more than one IP in the list, my iptables
is showing multiple chains:
#!/bin/bash
# allowed ip file location
WHITELIST=/usr/src/firewall/whitelist.txt
#
## Specify where IP Tables is located
#
IPTABLES=/sbin/iptables
IPTABLES_SAVE=/sbin/iptables-save
#
## Save current iptables running configuration in case we want to revert back
## To restore using our example we would run "/sbin/iptables-restore < /usr/src/iptables.last"
#
$IPTABLES_SAVE > /usr/src/iptables.last
#
## Clear current rules
#
##If current INPUT policy is set to DROP we will be locked out once we flush the rules
## so we must first ensure it is set to ACCEPT.
#
$IPTABLES -P INPUT ACCEPT
echo 'Setting default INPUT policy to ACCEPT'
$IPTABLES -F
echo 'Clearing Tables F'
$IPTABLES -X
echo 'Clearing Tables X'
$IPTABLES -Z
echo 'Clearing Tables Z'
#Always allow localhost.
echo 'Allowing Localhost'
$IPTABLES -A INPUT -s 127.0.0.1 -j ACCEPT
#
## Whitelist
#
for x in `grep -v ^# $WHITELIST | awk '{print $1}'`; do
echo "Permitting $x..."
# $IPTABLES -A INPUT -s $x -j ACCEPT
$IPTABLES -A INPUT -p tcp --dport 22 -j ACCEPT
$IPTABLES -A INPUT -p tcp -m tcp -s "$x" --dport 80 -j ACCEPT
$IPTABLES -A INPUT -p udp -m udp -s "$x" --dport 5060 -j ACCEPT
done
# block all other traffice
$IPTABLES -A INPUT -p all -j DROP
#
## Save the rules so they are persistent on reboot.
#
/etc/init.d/iptables save
And my iptables -L -n output shows as
firewall]# iptables -L -n
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- 127.0.0.1 0.0.0.0/0
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
ACCEPT tcp -- 192.168.1.125 0.0.0.0/0 tcp dpt:80
ACCEPT udp -- 192.168.1.125 0.0.0.0/0 udp dpt:5060
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
ACCEPT tcp -- 192.168.1.1 0.0.0.0/0 tcp dpt:80
ACCEPT udp -- 192.168.1.1 0.0.0.0/0 udp dpt:5060
DROP all -- 0.0.0.0/0 0.0.0.0/0
Chain FORWARD (policy DROP)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
How to avoid duplicates, whats wrong in that script....
Source: (StackOverflow)