Jake Jake - 1 month ago 46
Python Question

Is it possible to write a firewall in python?

Is it possible to write a firewall in python? Say it would block all traffic?

Answer

Yes, yes it is.

I have some Python code that interacts with Linux iptables to perform firewalling duties, using nfqueue. I can use a rule in iptables that looks like:

iptables -A INPUT -j NFQUEUE --queue-num 1

And then have some Python code that looks like:

import nfqueue
from dpkt import ip

q = None

def cb(dummy, payload):
    # make decision about if the packet should be allowed. in this case, drop everything:
    payload.set_verdict(nfqueue.NF_DROP)

q = nfqueue.queue()
q.open()
q.bind()
q.set_callback(cb)
q.create_queue(1)

q.try_run()

Here is a nice write up that the above code is based on:

http://blog.yancomm.net/2011/05/nfqueue-packet-mangling-with-python.html