Yes, we can perform firewall in python.
Using nfqueue, we can able to perform firewalling duties and we have the code which interacts with linux iptables.
We can use a rule in iptables:
iptables -A INPUT -j NFQUEUE --queue-num 1
Then have a look at the following code:
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()