def filter_ports(device, ports): """Adds to iptables the ports to filter for the given device.""" input_filter = 'gluster-input' output_filter = 'gluster-output' table = Table('filter') if input_filter in table.list_chains(): print "Gluster ports are already filtered out. Ignoring request..." return # Create and prepare the chains that will hold gluster rules. table.create_chain(input_filter) in_rule = Rule( in_interface=device, jump=input_filter) table.append_rule('INPUT', in_rule) table.create_chain(output_filter) out_rule = Rule( out_interface=device, jump=output_filter) table.append_rule('OUTPUT', out_rule) # Now we actually do the filtering. for protocol in ports['input'].keys(): for port in ports['input'][protocol]: in_rule = Rule( in_interface=device, protocol=protocol, matches=[Match(protocol, '--dport %s' % port)], jump='DROP') print "Filtering port %s from INPUT on device %s..." % (port, device) table.append_rule(input_filter, in_rule) for protocol in ports['output'].keys(): for port in ports['output'][protocol]: out_rule = Rule( out_interface=device, protocol=protocol, matches=[Match(protocol, '--dport %s' % port)], jump='DROP') print "Filtering port %s from OUTPUT on device %s..." % (port, device) table.append_rule(output_filter, out_rule)