def iptablesFILTER(action, user_var): table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, "DOCKER-USER") rule = iptc.Rule() rule.out_interface = user_var.interface rule.create_target("ACCEPT") chain.insert_rule(rule) chain.delete_rule(rule) if action == 'insert': chain.insert_rule(rule) else: chain.delete_rule(rule)
def tag_packets_with_port(port): table_mangle = iptc.Table(iptc.Table.MANGLE) chain = iptc.Chain(table_mangle, "OUTPUT") rule = iptc.Rule() rule.protocol = "tcp" match = iptc.Match(rule, "tcp") match.dport = str(port) rule.add_match(match) rule.out_interface = "eth1" target = iptc.Target(rule, "MARK") target.set_mark = "0x01" rule.target = target chain.insert_rule(rule)
def applyRule(line, ip_list): for ip in ip_list: t = time.time() rule = iptc.Rule() rule.protocol = "tcp" rule.dst = ip rule.target = rule.create_target("DROP") match = rule.create_match("comment") #match.comment = line.rstrip() match.comment = str(t) + "-" + line.rstrip() table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, "OUTPUT") chain.insert_rule(rule)
def drop(): rule = iptc.Rule() rule.protocol = protocol match = iptc.Match(rule, protocol) match.sport = source_port match.dport = destination_port rule.add_match(match) rule.src = source rule.dst = destination rule.add_match(match) rule.target = iptc.Target(rule, targets) chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), Chain) chain.insert_rule(rule)
def insert_connection_packet_rules(self): table = iptc.Table(iptc.Table.MANGLE) chain = iptc.Chain(table, 'OUTPUT') rule = iptc.Rule() t = rule.create_target('NFQUEUE') t.set_parameter('queue-num', str(0)) t.set_parameter('queue-bypass') m = rule.create_match('conntrack') m.set_parameter('ctstate', 'NEW') chain.insert_rule(rule)
def block_port(): rule = iptc.Rule() rule.protocol = "tcp" match = iptc.Match(rule, "tcp") match.dport = secret_port rule.add_match(match) target = iptc.Target(rule, "REJECT") target.set_parameter("reject-with", "tcp-reset") rule.target = target chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT") chain.insert_rule(rule) print("Port", secret_port, "was blocked") return (chain, rule)
def main(): parser = argparse.ArgumentParser( description='Argument you need to know to add rule to firewall') parser.add_argument('--protocol', type=str, default=None, help='Protocol udp or tcp') parser.add_argument( '--interface', type=str, default=None, help='Rule for which interface. Leave blank for all interface') parser.add_argument('--src-ip', type=str, help='IP range source') parser.add_argument('--dst-ip', type=str, help='IP range destination') parser.add_argument('--src-port', type=str, help='Port range source') parser.add_argument('--dst-port', type=str, help='Port range destination') parser.add_argument('--port', type=str, help='Port range for both source and destination') parser.add_argument('--ip', type=str, help='IP range for both source and destination') parser.add_argument('--comment', '-m', type=str, help='Comment for the rule') parser.add_argument('--log', '-l', type=str, help='Log prefix for the rule') parser.add_argument('-f', '--flush', action="store_true", help='Clear all rule in this chain') args = parser.parse_args() if args.flush: init_chain() print("All rules in %s chain is clear" % chain_name) else: rule_d = filter_rule.resolveArgsToDict(args) if args.log != None: rule_d["target"] = {"LOG": {"log-prefix": args.log}} filter_rule.append_rule(filter_rule.convertDictToRule(rule_d), chain_name) rule_d["target"] = DEFAULT_TARGET filter_rule.append_rule(filter_rule.convertDictToRule(rule_d), chain_name) table = iptc.Table(iptc.Table.FILTER) table.refresh()
def main(): #check if user is root/sudo try: if os.geteuid() == 0: parser = argparse.ArgumentParser( description='Detect and block TCP port scans of your host.') parser.add_argument( '-H', '--hostIP', action='store', help= "Specify your host inet address. Will default to the inet address of default interface." ) parser.add_argument( '-i', '--interface', action='store', help= 'Specify an interface to sniff for port scans on. Will default to system default.' ) parser.add_argument( '-c', '--clear', action='store_true', help='Use this flag to clear all blocked IPs before running.') #parser.add_argument('-d', # '--daemon', # action='store_true', # help='Use this flag to run as daemon proccess and log to file.') args = parser.parse_args() if args.clear: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT") chain.flush() if args.interface and args.hostIP: log(args.interface, args.hostIP) if args.interface: log(args.interface) if args.hostIP: log(None, args.hostIP) else: log() else: print("[-] Warning: Must run as root.") sys.exit() finally: print("\nIP addresses blocked this session:") print([x.src for x in blockList]) sys.exit(0)
def _remove_policy_from_iptables(self, policy, table, chain): # table: FILTER | NAT # chain: INPUT | FORWARD | OUTPUT table_name = table.upper() chain_name = chain.upper() rule = iptc.Rule() if (policy.src_address is not None): rule.src = policy.src_address if (policy.dst_address is not None): rule.dst = policy.dst_address if (policy.protocol != "all"): rule.protocol = policy.protocol match = rule.create_match(policy.protocol) if (policy.src_port is not None): match.sport = policy.src_port if (policy.dst_port is not None): match.dport = policy.dst_port if (policy.description is not None): match = rule.create_match("comment") match.comment = policy.description rule.target = iptc.Target(rule, policy.action.upper()) if table_name == "FILTER": table = iptc.Table(iptc.Table.FILTER) elif table_name == "NAT": table = iptc.Table(iptc.Table.NAT) chain = iptc.Chain(table, chain_name) chain.delete_rule(rule)
def test_nat_policy(self): if is_table_available(iptc.Table.NAT): table = iptc.Table(iptc.Table.NAT) prerouting_chain = iptc.Chain(table, "PREROUTING") pol = iptc.Policy("DROP") prerouting_chain.set_policy(pol) rpol = prerouting_chain.get_policy() self.assertEquals(id(pol), id(rpol)) pol = iptc.Policy("ACCEPT") prerouting_chain.set_policy(pol) rpol = prerouting_chain.get_policy() self.assertEquals(id(pol), id(rpol)) pol = iptc.Policy("RETURN") try: prerouting_chain.set_policy(pol) except iptc.IPTCError: pass else: self.fail("managed to set PREROUTING policy to RETURN") if is_table_available(iptc.Table.MANGLE): table = iptc.Table(iptc.Table.MANGLE) forward_chain = iptc.Chain(table, "FORWARD") pol = iptc.Policy("DROP") forward_chain.set_policy(pol) rpol = forward_chain.get_policy() self.assertEquals(id(pol), id(rpol)) pol = iptc.Policy("ACCEPT") forward_chain.set_policy(pol) rpol = forward_chain.get_policy() self.assertEquals(id(pol), id(rpol)) pol = iptc.Policy("RETURN") try: forward_chain.set_policy(pol) except iptc.IPTCError: pass else: self.fail("managed to set FORWARD policy to RETURN")
def create_iptables_rule(port): global rule match = iptc.Match(rule, "tcp") match.dport = port match.tcp_flags = ['RST'] chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT") # -A OUTPUT rule.protocol = "tcp" # -p tcp rule.target = iptc.Target(rule, "DROP") # -j DROP rule.add_match(match) try: chain.delete_rule(rule) except: a = 0 chain.insert_rule(rule)
def bgp_block(): """ Uses IPTables to block BGP packets and also alerts the user of an packet using the BGP port :return: """ msgbox('BGP Packet Detected. Closing BGP port...', 'BGP Port is Open') rule = iptc.Rule() rule.protocol = 'tcp' match = rule.create_match('tcp') match.dport = '179' target = iptc.Target(rule, "DROP") rule.target = target chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT") chain.insert_rule(rule)
def get_table_name(table_name): # TODO: error handling if table_name == 'FILTER': table = iptc.Table.FILTER elif table_name == 'NAT': table = iptc.Table.NAT elif table_name == 'MANGLE': table = iptc.Table.MANGLE elif table_name == 'RAW': table = iptc.Table.RAW elif table_name == 'SECURITY': table = iptc.Table.SECURITY return iptc.Table(table)
def test_flush_builtin(self): filter_table = iptc.Table(iptc.Table.FILTER) output_rule_count = len(iptc.Chain(filter_table, "OUTPUT").rules) rule = iptc.Rule() rule.target = iptc.Target(rule, "ACCEPT") iptc.Chain(filter_table, "OUTPUT").append_rule(rule) self.assertEquals(len(iptc.Chain(filter_table, "OUTPUT").rules), output_rule_count + 1) filter_table.flush() self.assertEquals(len(iptc.Chain(filter_table, "OUTPUT").rules), 0)
def unban(ip): # Disable autocommit on FILTER table to efficiently delete duplicate bans table = iptc.Table(iptc.Table.FILTER) table.refresh() table.autocommit = False # Traverse through INPUT table for rules matching src ip and delete chain = iptc.Chain(table, "INPUT") for rule in chain.rules: if rule.src and ip == rule.src.split('/')[0]: chain.delete_rule(rule) table.commit() table.refresh() table.autocommit = True
def allowHTTPS(self): chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT') rule = iptc.Rule() rule.in_interface = 'eth+' rule.protocol = 'tcp' match = rule.create_match('tcp') match.dport = '443' rule.target = iptc.Target(rule, 'ACCEPT') chain.insert_rule(rule) ip = request.environ.get( 'HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR') iprecord = Ipfilters(ip, "ACCEPT", "allowHTTPS", "eth+_tcp_prt443") db.session.add(iprecord) db.session.commit()
def json_rule_chain(chainname): table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: if chain.name == chainname: dictchain = {} print("Chain:", chain.name, "Policy:", chain.get_policy().name) rules = [] for rule in chain.rules: rules.append(iptc.easy.decode_iptc_rule(rule)) dictchain[chain.name] = { 'policy': chain.get_policy().name, 'rules': rules } return json.dumps(dictchain, indent=4)
def list_chain(chain_name): """List rules in a chain. Returns a list of iptables rules, or raises ChainDoesNotExist. """ table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, chain_name) # TODO: is there any way to do this without listing all chains? (probably slow) # If the chain doesn't exist, chain.rules will be an empty list, so we need # to make sure the chain actually _does_ exist. if chain in table.chains: return tuple(Rule.from_iptc(rule) for rule in chain.rules) else: raise ChainDoesNotExist(chain_name)
def get_nf_table(self, tableName): """ Get IP tables """ self.log.debug('getIpTable'.format()) # exec embedded function table = iptc.Table(tableName) # refresh table to get current counters table.refresh() # create simple table (ie. without pointers to ctypes) # simpleTable = SimpleTable(table) # return simpleTable return None
def del_proxy_iptc(ports): """docstring for clear_iptc proxy""" table = iptc.Table(iptc.Table.NAT) table.autocommit = False chain = iptc.Chain(table, "PREROUTING") for rule in chain.rules: if 'DNAT' != rule.target.name: continue if match_port(rule, ports): chain.delete_rule(rule) table.commit() table.autocommit = True table.refresh() pass
def get_metrics(): table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: #packet, byte = chain.get_counters() packet, byte = chainInfo(table, chain.name, RULE_TOTAL, RULE_PACKET) if (chain.rules): RULE_COUNT.labels(table.name, chain.name).set(len(chain.rules)) else: RULE_COUNT.labels(table.name, chain.name).set(0) CHAIN_PACKET.labels(table.name, chain.name).set(packet) CHAIN_TOTAL.labels(table.name, chain.name).set(byte) return Response(prometheus_client.generate_latest(registry), mimetype="text/plain")
def dump(self): table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, "FORWARD") print("Table {0} / Chain {1}".format(table.name, chain.name)) for rule in chain.rules: print("Rule: proto: {0} src {1} dst {2} iface {3} out {4}".format( rule.protocol, rule.src, rule.dst, rule.in_interface, rule.out_interface)) print("Matches:") for match in rule.matches: print("{0} target {1} comment [{2}]".format( match.name, rule.target.name, match.comment))
def remove(self, protocol, port, range=''): # Remove rule(s) in our chain matching this port # If range is not provided, delete all rules for this port tb = iptc.Table(iptc.Table.FILTER) c = iptc.Chain(tb, "genesis-apps") if not tb.is_chain(c): return for r in c.rules: if range != '': if r.matches[0].dport == port and range in r.dst: c.delete_rule(r) else: if r.matches[0].dport == port: c.delete_rule(r)
def find(self, protocol, port, range=''): # Returns true if rule is found for this port # If range IS provided, return true only if range is the same tb = iptc.Table(iptc.Table.FILTER) c = iptc.Chain(tb, "genesis-apps") if not tb.is_chain(c): return False for r in c.rules: if range != '': if r.matches[0].dport == port and range in r.dst: return True elif range == '' and r.matches[0].dport == port: return True return False
def timer_delete(self, host, port): table = iptc.Table(iptc.Table.FILTER) table.autocommit = False chain = iptc.Chain(table, "INPUT") for rule in chain.rules: port_matches = False for match in rule.matches: if match.name == "tcp" and match.dport == port: port_matches = True if rule.src == "%s/255.255.255.255" % host and port_matches: print "deleted ", rule chain.delete_rule(rule) table.commit() table.autocommit = True
def get_whitelist(self): whitelist = [] table = iptc.Table(iptc.Table.FILTER) table.refresh() for chain in table.chains: for rule in chain.rules: for match in rule.matches: if match.name == "comment": tmp = match.comment.split(':') if tmp[0] == "whitelist": url = tmp[1] whitelist.append(url) # set() removes duplicate objects return set(whitelist)
def insert_dns_rule(self): """Get DNS responses""" table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, 'INPUT') rule = iptc.Rule() rule.protocol = 'udp' m = rule.create_match('udp') m.sport = '53' t = rule.create_target('NFQUEUE') t.set_parameter('queue-num', str(0)) t.set_parameter('queue-bypass') chain.insert_rule(rule)
def collect(self): # Metrics iptables_rules = GaugeMetricFamily( 'iptables_rules', 'Number of rules', labels=['ip_version', 'table', 'chain'], ) iptables_packets = CounterMetricFamily( 'iptables_packets', 'Number of matched packets', labels=['ip_version', 'table', 'chain', 'rule'], ) iptables_bytes = CounterMetricFamily( 'iptables_bytes', 'Number of matched bytes', labels=['ip_version', 'table', 'chain', 'rule'], ) for ip_version in self.ip_versions: labels = dict(ip_version=ip_version) for table_name in self.tables: if ip_version == '4': table = iptc.Table(TABLES[table_name]) else: table = iptc.Table6(TABLES[table_name]) table.refresh() labels['table'] = table_name for chain in table.chains: labels['chain'] = chain.name.lower() rule_count = 0 for rule in chain.rules: rule_count += 1 exporter_name = get_exporter_name(rule) if exporter_name: labels['rule'] = exporter_name counter_labels = [ labels['ip_version'], labels['table'], labels['chain'], labels['rule'] ] packets, bytes = rule.get_counters() iptables_packets.add_metric( counter_labels, packets) iptables_bytes.add_metric(counter_labels, bytes) rules_labels = [ labels['ip_version'], labels['table'], labels['chain'] ] iptables_rules.add_metric(rules_labels, rule_count) yield iptables_rules yield iptables_packets yield iptables_bytes
def _remove_iptables_rule(self, rule, ipv6=False, tables=None): if not isinstance(rule, tuple): return self._remove_iptables_rule_cmd(rule, ipv6) _global_lock.acquire() try: if ipv6: if rule[0] == 'POSTROUTING': if tables: table = tables['nat6'] else: table = iptc.Table6(iptc.Table.NAT) else: if tables: table = tables['filter6'] else: table = iptc.Table6(iptc.Table.FILTER) else: if rule[0] == 'POSTROUTING': if tables: table = tables['nat'] else: table = iptc.Table(iptc.Table.NAT) else: if tables: table = tables['filter'] else: table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, rule[0]) try: chain.delete_rule(rule[1]) except: pass return True finally: _global_lock.release()
def __init__(self, dport, to_ports): self.dport = dport self.to_ports = to_ports self.num_rules = len(self.to_ports) self.rules = [] # hold all rules self.protocol = "tcp" self.table = iptc.Table(iptc.Table.NAT) self.chain = iptc.Chain(self.table, "PREROUTING") self.stat_type = "random" self.src = "" self.dst = "" print(f'Route {self.dport} to {self.to_ports} - {self.num_rules} rules')