# Standard library imports. import re # Django imports. from django.template import Context, loader # Application imports. import iptables def generate_entity_iptables(entity): """ Generates full iptables rules for the supplied entity. The generated rules can be fed directly to the iptables-restore utility. Arguments: entity - An Entity instance for which the iptables rules should be generated. Returns: String containing the iptables rules for entity. """ # Fetch list of incoming communications. incoming = entity.incoming_communications() # Set-up the nat table. nat = iptables.Table("nat") for chain in ("PREROUTING", "INPUT", "OUTPUT", "POSTROUTING"): nat.add_chain(iptables.Chain(chain, "ACCEPT")) # Set-up the filter table INPUT chain. filter = iptables.Table("filter") input = iptables.Chain("INPUT", "DROP") input.add_rule(iptables.LoopbackRule()) input.add_rule(iptables.RelatedRule()) for communication in incoming: source = "%s/%s" % (communication.source.address, communication.source.netmask) destination = "%s/%s" % (communication.destination.address, communication.destination.netmask) input.add_rule(iptables.Rule(source, destination, communication.protocol, communication.port, communication.description)) filter.add_chain(input) # Set-up empty chains. filter.add_chain(iptables.Chain("OUTPUT", "ACCEPT")) filter.add_chain(iptables.Chain("FORWARD", "DROP")) # Construct the iptables file using the two tables. content = "%s%s" % (filter, nat) return content