Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write specific iptables rules using python-iptables

I am trying to use python-iptables to write a script to set certain rules. I figured out how to set rules to allow all and deny all, but I need to figure out how to write a rule to allow established connections.

For example I need to write the following rules using python-iptables:

iptables -A INPUT  -m state --state     RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

If anyone has firsthand knowledge or knows a good resource for writing the above or similar rules I would greatly appreciate it. Thanks in advance!

Here's the finished product. I plan on adding more rule options to allow users to allow http/s etc. connections if they desire.Thanks for all the help.

import iptc

def dropAll():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.in_interface = "eth+"
    target = iptc.Target(rule, "DROP")
    rule.target = target
    chain.insert_rule(rule)

def allowLoopback():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.in_interface = "lo"
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target
    chain.insert_rule(rule)

def allowEstablished():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
    rule = iptc.Rule()
    match = rule.create_match('state')
    match.state = "RELATED,ESTABLISHED"
    rule.target = iptc.Target(rule, 'ACCEPT')
    chain.insert_rule(rule)

dropAll()
allowLoopback()
allowEstablished()
like image 765
h33th3n Avatar asked Dec 22 '13 21:12

h33th3n


2 Answers

Try this

 import subprocess

p = subprocess.Popen(["iptables", "-A", "INPUT", "-p", "tcp", "-m", "tcp", "--dport", "22" , "-j", "ACCEPT"], stdout=subprocess.PIPE)
        output , err = p.communicate()
        print output
like image 118
sivakumar Avatar answered Sep 20 '22 12:09

sivakumar


i've not tried to use python-iptables, but it looks like you need something like:

rule = iptc.Rule()
match = rule.create_match('state')
match.state = 'RELATED,ESTABLISHED'
match.target = iptc.Target('ACCEPT')

chain = iptc.Chain(iptc.Table.(iptc.Table.FILTER), "INPUT")
chain.insert_rule(rule)

and so on.

like image 27
SingleNegationElimination Avatar answered Sep 21 '22 12:09

SingleNegationElimination