def openInterface(data): # POSTFIX = "gw" POSTFIX = "" print(f"data: {data}") # TODO: create wg keys # TODO: replace subprocess !!! # import subprocess # subprocess.call(f"wg genkey | tee privatekey+{data['device_id']} | wg pubkey > publickey+{data['device_id']}", shell=True) # with open(f"privatekey+{data['device_id']}", 'r') as f: # priv = f.read() # print(f"PRIV: {priv}") # f.close() # with open(f"publickey+{data['device_id']}", 'r') as f: # pub = f.read() # print(f"PUB: {pub}") # f.close() # subprocess.call(f"rm privatekey+{data['device_id']} && rm publickey+{data['device_id']}", shell=True) import pysodium from base64 import b64encode keys = pysodium.crypto_box_keypair() priv = b64encode(keys[1]) pub = b64encode(keys[0]) # TODO: open interface router = Router() router.device_id = data['device_id'] + POSTFIX print(f"{data}") router.dev.link('add', ifname=data['device_id'] + POSTFIX, kind='wireguard') idx = router.dev.link_lookup(ifname=data['device_id'] + POSTFIX)[0] print(f"IDX: {idx}") # router.dev.addr('add', index=idx, address='192.168.42.50', mask=24) router.dev.addr('add', index=idx, local='192.168.42.50', mask=32, address='192.168.100.10') print(f"setup config") cfg = { "interface": data['device_id'] + POSTFIX, "listen_port": 42001, "private_key": priv, "peers": [{ "public_key": data["wgpubkey"], "allowed_ips": ["0.0.0.0/0"] }] } router.wg.set_device(ifname=data['device_id'] + POSTFIX, config=cfg) print(f"clientpubkey: {len(data['wgpubkey'])}") print(f"clientpubkey: {data['wgpubkey']}") router.dev.link('set', index=idx, state='up') # iptables for wg-interface chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "FORWARD") rule = iptc.Rule() rule.out_interface = "tf_gateone" target = iptc.Target(rule, "ACCEPT") rule.target = target chain.insert_rule(rule) chain = iptc.Chain(iptc.Table(iptc.Table.NAT), "POSTROUTING") rule = iptc.Rule() rule.out_interface = "eth0" target = iptc.Target(rule, "MASQUERADE") rule.target = target chain.insert_rule(rule) return pub
def test_create_chain(self): chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "iptc_test_chain") iptc.Table(iptc.Table.FILTER).create_chain(chain) self.failUnless(iptc.Table(iptc.Table.FILTER).is_chain(chain)) iptc.Table(iptc.Table.FILTER).delete_chain(chain) self.failIf(iptc.Table(iptc.Table.FILTER).is_chain(chain))
import iptc import json table = iptc.Table(iptc.Table.FILTER) print str(table) data = iptc.Chain(table, "INPUT") print data
def delete_chain(chain_name): log.debug(f'deleting chain: {chain_name}') chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), chain_name) chain.flush() chain.delete()
#!usr/bin/python import time, sys import iptc table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, "INPUT") try: table.autocommit = False for rule in chain.rules: (packets, bytes) = rule.get_counters() if int(packets) == 0: chain.delete_rule(rule) chain.zero_counters() table.commit() table.close() except iptc.ip4tc.IPTCError: print "Oops!"
def add_ip_to_iptable_outbound(ip, interface, add_drop="ADD"): log.info("creating chain in add to outbound") chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT") rule_result = rule_logic(interface, ip, add_drop) chain.insert_rule(rule_result) log.info("done creating chain")
def ban(address): global lock refreshF2boptions() BAN_TIME = int(f2boptions['ban_time']) MAX_ATTEMPTS = int(f2boptions['max_attempts']) RETRY_WINDOW = int(f2boptions['retry_window']) NETBAN_IPV4 = '/' + str(f2boptions['netban_ipv4']) NETBAN_IPV6 = '/' + str(f2boptions['netban_ipv6']) ip = ipaddress.ip_address(address) if type(ip) is ipaddress.IPv6Address and ip.ipv4_mapped: ip = ip.ipv4_mapped address = str(ip) if ip.is_private or ip.is_loopback: return self_network = ipaddress.ip_network(address) with lock: temp_whitelist = set(WHITELIST) if temp_whitelist: for wl_key in temp_whitelist: wl_net = ipaddress.ip_network(wl_key, False) if wl_net.overlaps(self_network): logInfo('Address %s is whitelisted by rule %s' % (self_network, wl_net)) return net = ipaddress.ip_network( (address + (NETBAN_IPV4 if type(ip) is ipaddress.IPv4Address else NETBAN_IPV6)), strict=False) net = str(net) if not net in bans or time.time( ) - bans[net]['last_attempt'] > RETRY_WINDOW: bans[net] = {'attempts': 0} active_window = RETRY_WINDOW else: active_window = time.time() - bans[net]['last_attempt'] bans[net]['attempts'] += 1 bans[net]['last_attempt'] = time.time() active_window = time.time() - bans[net]['last_attempt'] if bans[net]['attempts'] >= MAX_ATTEMPTS: cur_time = int(round(time.time())) logCrit('Banning %s for %d minutes' % (net, BAN_TIME / 60)) if type(ip) is ipaddress.IPv4Address: with lock: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) else: with lock: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) r.hset('F2B_ACTIVE_BANS', '%s' % net, cur_time + BAN_TIME) else: logWarn('%d more attempts in the next %d seconds until %s is banned' % (MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net))
def update_db(group_list): check_migration_lock() table = iptc.Table(iptc.Table.FILTER) client = pymongo.MongoClient('mongodb://localhost:27017/') db = client['tcpstat'] collection = db['accounting'] today_str = str(datetime.date.today()) logging.info("Connect to db") if not collection.find_one({"Name": group["Name"], "Time": today_str}): migrate_db(group_list) check_migration_lock() chain = iptc.Chain(table, 'ACCT') for group in group_list: for rule in chain.rules: for match in rule.matches: if not match.sport: port_number = str(match.dport) rule_type = "RX" else: port_number = str(match.sport) rule_type = "TX" entry = collection.find_one({ "Name": group["Name"], "Time": today_str }) if port_number in entry.keys(): # Counters in bytes if rule_type == "TX": # Fetch entries in db entry = collection.find_one({ "Name": group["Name"], "Time": today_str }) TX = rule.get_counters()[1] + entry[port_number]["TX"] RX = entry[port_number]["RX"] logging.debug("This record is TX " + str(TX) + " for " + port_number) # Modify data in db collection.update( { "Name": group["Name"], "Time": today_str }, { "$set": { port_number: { "TX": int(TX), "RX": int(RX) } } }) else: entry = collection.find_one({ "Name": group["Name"], "Time": today_str }) # Fetch entries in db RX = rule.get_counters()[1] + entry[port_number]["RX"] TX = entry[port_number]["TX"] logging.debug("This record is RX " + str(RX) + " for " + port_number) collection.update( { "Name": group["Name"], "Time": today_str }, { "$set": { port_number: { "TX": int(TX), "RX": int(RX) } } }) chain.zero_counters()
def add_rule(self, rule): table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, "c-lock") chain.insert_rule(rule)
def flush(): chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT") chain.flush()
next elif ch.rules[x].matches[i].comment == cm: return (ch.rules[x], x) else: next return (None, -1) if __name__ == '__main__': try: iptc.easy.add_chain('filter', 'CFDDNS_RULES') except: pass cfddns_chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "CFDDNS_RULES") # "f**k me gently with a chainsaw" config = loadConf(sys.argv[1]) for k in config.keys(): for proto in config[k].keys(): for i in range(0, len(config[k][proto])): searchcomment = '{}_{}_{}'.format(k, proto, config[k][proto][i]) searchrule, ruleidx = getRuleByComment(cfddns_chain, searchcomment) if not searchrule: #rule doesn't exist so make it newrule = mkCFDDNSRule(k, proto, config[k][proto][i])
def initChain(): # Is called before threads start, no locking print "Initializing mailcow netfilter chain" # IPv4 if not iptc.Chain(iptc.Table(iptc.Table.FILTER), "MAILCOW") in iptc.Table( iptc.Table.FILTER).chains: iptc.Table(iptc.Table.FILTER).create_chain("MAILCOW") for c in ['FORWARD', 'INPUT']: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), c) rule = iptc.Rule() rule.src = '0.0.0.0/0' rule.dst = '0.0.0.0/0' target = iptc.Target(rule, "MAILCOW") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) # IPv6 if not iptc.Chain(iptc.Table6(iptc.Table6.FILTER), "MAILCOW") in iptc.Table6(iptc.Table6.FILTER).chains: iptc.Table6(iptc.Table6.FILTER).create_chain("MAILCOW") for c in ['FORWARD', 'INPUT']: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), c) rule = iptc.Rule6() rule.src = '::/0' rule.dst = '::/0' target = iptc.Target(rule, "MAILCOW") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) # Apply blacklist BLACKLIST = r.hgetall('F2B_BLACKLIST') if BLACKLIST: for bl_key in BLACKLIST: if type(ipaddress.ip_network( bl_key.decode('ascii'), strict=False)) is ipaddress.IPv4Network: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = bl_key target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: log['time'] = int(round(time.time())) log['priority'] = 'crit' log['message'] = 'Blacklisting host/network %s' % bl_key r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print log['message'] chain.insert_rule(rule) r.hset('F2B_PERM_BANS', '%s' % bl_key, int(round(time.time()))) else: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = bl_key target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: log['time'] = int(round(time.time())) log['priority'] = 'crit' log['message'] = 'Blacklisting host/network %s' % bl_key r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print log['message'] chain.insert_rule(rule) r.hset('F2B_PERM_BANS', '%s' % bl_key, int(round(time.time())))
def ban(address): global lock refreshF2boptions() BAN_TIME = int(f2boptions['ban_time']) MAX_ATTEMPTS = int(f2boptions['max_attempts']) RETRY_WINDOW = int(f2boptions['retry_window']) NETBAN_IPV4 = '/' + str(f2boptions['netban_ipv4']) NETBAN_IPV6 = '/' + str(f2boptions['netban_ipv6']) WHITELIST = r.hgetall('F2B_WHITELIST') ip = ipaddress.ip_address(address.decode('ascii')) if type(ip) is ipaddress.IPv6Address and ip.ipv4_mapped: ip = ip.ipv4_mapped address = str(ip) if ip.is_private or ip.is_loopback: return self_network = ipaddress.ip_network(address.decode('ascii')) if WHITELIST: for wl_key in WHITELIST: wl_net = ipaddress.ip_network(wl_key.decode('ascii'), False) if wl_net.overlaps(self_network): log['time'] = int(round(time.time())) log['priority'] = 'info' log['message'] = 'Address %s is whitelisted by rule %s' % ( self_network, wl_net) r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print 'Address %s is whitelisted by rule %s' % (self_network, wl_net) return net = ipaddress.ip_network( (address + (NETBAN_IPV4 if type(ip) is ipaddress.IPv4Address else NETBAN_IPV6) ).decode('ascii'), strict=False) net = str(net) if not net in bans or time.time( ) - bans[net]['last_attempt'] > RETRY_WINDOW: bans[net] = {'attempts': 0} active_window = RETRY_WINDOW else: active_window = time.time() - bans[net]['last_attempt'] bans[net]['attempts'] += 1 bans[net]['last_attempt'] = time.time() active_window = time.time() - bans[net]['last_attempt'] if bans[net]['attempts'] >= MAX_ATTEMPTS: log['time'] = int(round(time.time())) log['priority'] = 'crit' log['message'] = 'Banning %s' % net r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print 'Banning %s for %d minutes' % (net, BAN_TIME / 60) if type(ip) is ipaddress.IPv4Address: with lock: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) else: with lock: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) r.hset('F2B_ACTIVE_BANS', '%s' % net, log['time'] + BAN_TIME) else: log['time'] = int(round(time.time())) log['priority'] = 'warn' log['message'] = '%d more attempts in the next %d seconds until %s is banned' % ( MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net) r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print '%d more attempts in the next %d seconds until %s is banned' % ( MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net)
def populate(self, options): if options.Interface is None and utils.IsOsX() is False: print utils.color("Error: -I <if> mandatory option is missing", 1) sys.exit(-1) # Config parsing config = ConfigParser.ConfigParser() config.read(os.path.join(self.ResponderPATH, 'Responder.conf')) # Servers self.HTTP_On_Off = self.toBool(config.get('Responder Core', 'HTTP')) self.SSL_On_Off = self.toBool(config.get('Responder Core', 'HTTPS')) self.SMB_On_Off = self.toBool(config.get('Responder Core', 'SMB')) self.SQL_On_Off = self.toBool(config.get('Responder Core', 'SQL')) self.FTP_On_Off = self.toBool(config.get('Responder Core', 'FTP')) self.POP_On_Off = self.toBool(config.get('Responder Core', 'POP')) self.IMAP_On_Off = self.toBool(config.get('Responder Core', 'IMAP')) self.SMTP_On_Off = self.toBool(config.get('Responder Core', 'SMTP')) self.LDAP_On_Off = self.toBool(config.get('Responder Core', 'LDAP')) self.DNS_On_Off = self.toBool(config.get('Responder Core', 'DNS')) self.Krb_On_Off = self.toBool(config.get('Responder Core', 'Kerberos')) # Db File self.DatabaseFile = os.path.join(self.ResponderPATH, config.get('Responder Core', 'Database')) # Log Files self.LogDir = os.path.join(self.ResponderPATH, 'logs') if not os.path.exists(self.LogDir): os.mkdir(self.LogDir) self.SessionLogFile = os.path.join(self.LogDir, config.get('Responder Core', 'SessionLog')) self.PoisonersLogFile = os.path.join(self.LogDir, config.get('Responder Core', 'PoisonersLog')) self.AnalyzeLogFile = os.path.join(self.LogDir, config.get('Responder Core', 'AnalyzeLog')) self.FTPLog = os.path.join(self.LogDir, 'FTP-Clear-Text-Password-%s.txt') self.IMAPLog = os.path.join(self.LogDir, 'IMAP-Clear-Text-Password-%s.txt') self.POP3Log = os.path.join(self.LogDir, 'POP3-Clear-Text-Password-%s.txt') self.HTTPBasicLog = os.path.join(self.LogDir, 'HTTP-Clear-Text-Password-%s.txt') self.LDAPClearLog = os.path.join(self.LogDir, 'LDAP-Clear-Text-Password-%s.txt') self.SMBClearLog = os.path.join(self.LogDir, 'SMB-Clear-Text-Password-%s.txt') self.SMTPClearLog = os.path.join(self.LogDir, 'SMTP-Clear-Text-Password-%s.txt') self.MSSQLClearLog = os.path.join(self.LogDir, 'MSSQL-Clear-Text-Password-%s.txt') self.LDAPNTLMv1Log = os.path.join(self.LogDir, 'LDAP-NTLMv1-Client-%s.txt') self.HTTPNTLMv1Log = os.path.join(self.LogDir, 'HTTP-NTLMv1-Client-%s.txt') self.HTTPNTLMv2Log = os.path.join(self.LogDir, 'HTTP-NTLMv2-Client-%s.txt') self.KerberosLog = os.path.join(self.LogDir, 'MSKerberos-Client-%s.txt') self.MSSQLNTLMv1Log = os.path.join(self.LogDir, 'MSSQL-NTLMv1-Client-%s.txt') self.MSSQLNTLMv2Log = os.path.join(self.LogDir, 'MSSQL-NTLMv2-Client-%s.txt') self.SMBNTLMv1Log = os.path.join(self.LogDir, 'SMB-NTLMv1-Client-%s.txt') self.SMBNTLMv2Log = os.path.join(self.LogDir, 'SMB-NTLMv2-Client-%s.txt') self.SMBNTLMSSPv1Log = os.path.join(self.LogDir, 'SMB-NTLMSSPv1-Client-%s.txt') self.SMBNTLMSSPv2Log = os.path.join(self.LogDir, 'SMB-NTLMSSPv2-Client-%s.txt') # HTTP Options self.Serve_Exe = self.toBool(config.get('HTTP Server', 'Serve-Exe')) self.Serve_Always = self.toBool(config.get('HTTP Server', 'Serve-Always')) self.Serve_Html = self.toBool(config.get('HTTP Server', 'Serve-Html')) self.Html_Filename = config.get('HTTP Server', 'HtmlFilename') self.Exe_Filename = config.get('HTTP Server', 'ExeFilename') self.Exe_DlName = config.get('HTTP Server', 'ExeDownloadName') self.WPAD_Script = config.get('HTTP Server', 'WPADScript') self.HtmlToInject = config.get('HTTP Server', 'HtmlToInject') # Throttle Options self.ThrottleAuditor = {} self.ThrottleThreshold = config.get('Throttle', 'Threshold') self.ThrottleTimeThreshold = float(config.get('Throttle', 'TimeBan')) self.ThrottleVerbose = self.toBool(config.get('Throttle', 'Verbose')) self.ThrottleIPTables = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT") self.ThrottleLock = threading.Lock() self.ThrottleAuditTimeFrame = float(config.get('Throttle', 'AuditTimeFrame')) # MAC Filtering self.ArpTable = {} self.VendorTable = {} self.ArtTableFilteringVerbose = self.toBool(config.get('MACFiltering', 'Verbose')) self.ArpTableRefreshRate = config.get('MACFiltering', 'RefreshRate') self.DontRespondToVendor = filter(None, [x.lower().strip() for x in config.get('MACFiltering', 'DontRespondTo').strip().split(',')]) if not os.path.exists(self.Html_Filename): print utils.color("/!\ Warning: %s: file not found" % self.Html_Filename, 3, 1) if not os.path.exists(self.Exe_Filename): print utils.color("/!\ Warning: %s: file not found" % self.Exe_Filename, 3, 1) # SSL Options self.SSLKey = config.get('HTTPS Server', 'SSLKey') self.SSLCert = config.get('HTTPS Server', 'SSLCert') # Respond to hosts self.RespondTo = filter(None, [x.upper().strip() for x in config.get('Responder Core', 'RespondTo').strip().split(',')]) self.RespondToName = filter(None, [x.upper().strip() for x in config.get('Responder Core', 'RespondToName').strip().split(',')]) self.DontRespondTo = filter(None, [x.upper().strip() for x in config.get('Responder Core', 'DontRespondTo').strip().split(',')]) self.DontRespondToName = filter(None, [x.upper().strip() for x in config.get('Responder Core', 'DontRespondToName').strip().split(',')]) # Auto Ignore List self.AutoIgnore = self.toBool(config.get('Responder Core', 'AutoIgnoreAfterSuccess')) self.CaptureMultipleCredentials = self.toBool(config.get('Responder Core', 'CaptureMultipleCredentials')) self.AutoIgnoreList = [] # CLI options self.LM_On_Off = options.LM_On_Off self.WPAD_On_Off = options.WPAD_On_Off self.Wredirect = options.Wredirect self.NBTNSDomain = options.NBTNSDomain self.Basic = options.Basic self.Finger_On_Off = options.Finger self.Interface = options.Interface self.OURIP = options.OURIP self.Force_WPAD_Auth = options.Force_WPAD_Auth self.Upstream_Proxy = options.Upstream_Proxy self.AnalyzeMode = options.Analyze self.Verbose = options.Verbose self.CommandLine = str(sys.argv) if self.HtmlToInject is None: self.HtmlToInject = '' self.Bind_To = utils.FindLocalIP(self.Interface, self.OURIP) self.IP_aton = socket.inet_aton(self.Bind_To) self.Os_version = sys.platform # Set up Challenge self.NumChal = config.get('Responder Core', 'Challenge') if len(self.NumChal) is not 16: print utils.color("[!] The challenge must be exactly 16 chars long.\nExample: 1122334455667788", 1) sys.exit(-1) self.Challenge = "" for i in range(0, len(self.NumChal),2): self.Challenge += self.NumChal[i:i+2].decode("hex") # Set up logging logging.basicConfig(filename=self.SessionLogFile, level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logging.warning('Responder Started: %s' % self.CommandLine) logging.warning('Responder Config: %s' % str(self)) Formatter = logging.Formatter('%(asctime)s - %(message)s') PLog_Handler = logging.FileHandler(self.PoisonersLogFile, 'w') ALog_Handler = logging.FileHandler(self.AnalyzeLogFile, 'a') PLog_Handler.setLevel(logging.INFO) ALog_Handler.setLevel(logging.INFO) PLog_Handler.setFormatter(Formatter) ALog_Handler.setFormatter(Formatter) self.PoisonersLogger = logging.getLogger('Poisoners Log') self.PoisonersLogger.addHandler(PLog_Handler) self.AnalyzeLogger = logging.getLogger('Analyze Log') self.AnalyzeLogger.addHandler(ALog_Handler)
def iptquery(): table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, "INPUT") for rule in chain.rules: if rule.src: print(rule.src)
def delete_rule(self, rule): table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, "c-lock") chain.delete_rule(rule)
def add_ip_to_iptables_inbound(ip, interface, add_drop="ADD"): log.info("creating chain in adding to inbound") chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT") rule_result = rule_logic(interface, ip, add_drop) chain.insert_rule(rule_result) log.info("Chain created")
if dst in vm_ports: vm_ports[dst].append(rule['tcp']['dport']) else: vm_ports[dst] = [] vm_ports[dst].append(rule['tcp']['dport']) for rule in prerouting: src = rule['target']['DNAT']['to-destination'] dport = rule['tcp']['dport'] # mapping the vm_port_opened with router_port_opened mapping_ports[src] = dport if (args.ip in vm_ports) and (args.vmport in vm_ports[args.ip]): dst = args.ip + ':' + args.vmport prerouting_chain = iptc.Chain(iptc.Table(iptc.Table.NAT), "custom-PREROUTING") old_rule = iptc.Rule() old_rule.protocol = "tcp" match = iptc.Match(old_rule, "tcp") match.dport = mapping_ports[dst] target = old_rule.create_target("DNAT") target.to_destination = dst old_rule.add_match(match) old_rule.target = target prerouting_chain.delete_rule(old_rule) postrouting_chain = iptc.Chain(iptc.Table(iptc.Table.NAT), "custom-POSTROUTING") new_rule = iptc.Rule() new_rule.protocol = "tcp" new_rule.dst = args.ip
def delete_ip_from_iptables_outbound(ip, interface, add_drop="DROP"): log.info("Creating chain in delete from outbound") chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT") rule_result = rule_logic(interface, ip, add_drop) chain.insert_rule(rule_result) log.info("Chain created")
def __init__(self, reactor, masterIP, masterPort, masterPasswd, infraPasswd, bridgeIF, intIP, bridgeIP, envPort, rosproxyPort, rootfsDir, confDir, dataDir, pkgDir, ubuntuRel, rosRel, data): """ Initialize the Container Client. @param reactor: Reference to the twisted reactor. @type reactor: twisted::reactor @param masterIP: IP address of the Master process. @type masterIP: str @param masterPort: Port of the Master process used for internal communications. @type masterPort: int @param masterPasswd: SHA 256 Digested Master Password. @type masterPasswd: str @param infraPasswd: SHA 256 Digested Infra Password. @type infraPasswd: str @param bridgeIF: Network interface used for the container communication. @type bridgeIF: str @param intIP: IP address of the network interface used for the internal communication. @type intIP: str @param bridgeIP: IP address of the network interface used for the container communication. @type bridgeIP: str @param envPort: Port where the environment process running inside the container is listening for connections to other endpoints. (Used for port forwarding.) @type envPort: int @param rosproxyPort: Port where the rosproxy process running inside the container is listening for connections to console clients. (Used for port forwarding.) @type rosproxyPort: int @param rootfsDir: Filesystem path to the root directory of the container filesystem. @type rootfsDir: str @param confDir: Filesystem path to the directory where container configuration files should be stored. @type confDir: str @param dataDir: Filesystem path to the directory where temporary data of a container should be stored. @type dataDir: str @param pkgDir: Filesystem paths to the package directories as a list of tuples where each tuple contains the path to the directory in the host machine and the path to the directory to which the host directory will be bound in the container filesystem (without the @param rootfsDir). @type pkgDir: [(str, str)] @param ubuntuRel: Host filesystem Ubuntu release used in this machine. @type ubuntuRel: str @param rosRel: Container filesytem ROS release in this deployment instance of the cloud engine @type rosRel: str @param data: More data about the machine configuration. @type data: dict """ self._reactor = reactor self._internalIP = intIP self._envPort = envPort self._rosproxyPort = rosproxyPort self._masterPort = masterPort if isLocalhost(masterIP): self._masterIP = bridgeIP else: self._masterIP = masterIP self._masterPasswd = masterPasswd self._infraPasswd = infraPasswd # Container directories self._rootfs = rootfsDir self._confDir = confDir self._dataDir = dataDir self._pkgDir = pkgDir # Release info self._ubuntuRel = ubuntuRel self._rosRel = rosRel for _, path in self._pkgDir: os.mkdir(os.path.join(self._rootfs, path)) # Container info self._nrs = set(range(100, 200)) self._containers = set() # Network configuration self._bridgeIF = bridgeIF self._bridgeIP = bridgeIP # Virtual network self._bridges = set() self._uid = {} # Physical parameters of machine # TODO: Is a human settings at this time, # rce.util.sysinfo should fill this role soon self._size = data.get('size') self._cpu = data.get('cpu') self._memeory = data.get('memory') self._bandwidth = data.get('bandwidth') self._specialFeatures = data.get('special_features') # Common iptables references nat = iptc.Table(iptc.Table.NAT) self._prerouting = iptc.Chain(nat, 'PREROUTING') self._output = iptc.Chain(nat, 'OUTPUT')
def insert_rule(chain_name, rule): log.debug(f'adding rule to {chain_name}: {rule}') chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), chain_name) chain.insert_rule(rule.to_iptc())
def startClean(): chainIn = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT') chainIn.flush() chainOut = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'OUTPUT') chainOut.flush()
def Remove_Rules(event): #Create a dictionary and retreive input from remove rule entry box rules_to_remove = {} index_of_rule = "" index_of_rule = remove_rule_entry_box.get() #print(index) # Create an index from input if "-" in index_of_rule: first_num = int(index_of_rule[0]) - 1 second_num = int(index_of_rule[2:]) index_range = str(first_num) + ":" + str(second_num) #print(index_range[0:3]) else: first_num = (int(index_of_rule) -1) second_num = first_num + 1 # Get values of specified rule(s) for key in table_of_rules[first_num:second_num]: rules_to_remove = Save_Helpers.get_current_values(key) #print(rules_to_remove) chain = '' rule = '' match = '' target = '' #print(the_rule) regex = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$''' # Create rule(s) to be removed from rules_to_remove dictionary chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), (rules_to_remove['input_options'])) rule = iptc.Rule() #rule.in_interface = "eth+" # Retrieve IPs and error check entries if(re.search(regex, str(rules_to_remove['source_ip']))): rule.src = rules_to_remove['source_ip'] #else: #print("FireTables: Rule Source IP set to anywhere") if(re.search(regex,str(rules_to_remove['destination_ip']))): rule.dst = rules_to_remove['destination_ip'] #else: #print("FireTables: Rule Destination IP set to anywhere") # Retrieve Accept or Drop options target = iptc.Target(rule, rules_to_remove['accept_or_drop_options']) rule.target = target # Retrieve Protocol rule.protocol = rules_to_remove['protocol_options'] match = iptc.Match(rule, rules_to_remove['protocol_options']) # Retrieve Ports and error check entries if rules_to_remove['protocol_options'] != 'icmp': if rules_to_remove['source_port'] != "": if int(rules_to_remove['source_port']) in range(65535): match.sport = rules_to_remove['source_port'] #else: #print("FireTables: Rule Source Port set to anywhere") if rules_to_remove['destination_port'] != "": if int(rules_to_remove['destination_port']) in range(65535): match.dport = rules_to_remove['destination_port'] #else: #print("FireTables: Rule Destination Port set to anywhere") rule.add_match(match) # Delete rule(s) from iptables chain.delete_rule(rule) # Clear terminal os.system('clear') # Display iptables rules os.system('sudo iptables-legacy -L')
def dropAllInbound(): chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT') rule = iptc.Rule() rule.target = iptc.Target(rule, 'DROP') chain.insert_rule(rule)
import iptc table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table,'FORWARD') #policy = iptc.Policy(iptc.Policy.ACCEPT) rule = iptc.Rule() #rule.in_interface = "wlo1" rule.src="98.136.103.24/255.255.255.0" rule.dst="98.136.103.24/255.255.255.0" rule.protocol="tcp" match=iptc.Match(rule,"state") match.state="RELATED,ESTABLISHED" rule.add_match(match) rule.target=iptc.Target(rule,"DROP") chain.insert_rule(rule) table.commit() #displays all the chains in that particular table for chain in table.chains: print(chain.name) for rule in chain.rules: print(rule.protocol,rule.src,rule.dst) for match in rule.matches: print(match.name) print(rule.target.name) #chain.delete_rule(rule)
delete_rule(rule_number, table, direction='input') delete_rule(rule_number, table, direction='output') #for chain in table.chains: #for rule in chain.rules: # chain.delete_rule(rule) elif (value == '-all'): if ((len(sys.argv) != 3) and (sys.argv[index + 1] != 'ACCEPT') and (sys.argv[index + 1] != 'DROP')): sys.exit("The -all option lets the user to ACCEPT or DROP all packets, independently of ports,"+\ " protocols or IPs. Please, specify a ACCEPT or DROP argument") else: single_options = True rule = iptc.Rule() rule.target = rule.create_target(sys.argv[index + 1]) chain1 = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT") chain2 = iptc.Chain(iptc.Table(iptc.Table.FILTER), "OUTPUT") chain1.insert_rule(rule) chain2.insert_rule(rule) elif (value == '-rule'): single_options = True if (len(sys.argv)) != 3: if (len(sys.argv) == 2): print("The list of rules available is:\n") for i in predesigned_rules: print(i) else: sys.exit( "The option -r does not accept additional options. Please, type: -rule RULE" )
def setUp(self): self.chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "iptc_test_chain") iptc.Table(iptc.Table.FILTER).create_chain(self.chain)
def init_rule(protocol): rule = iptc.Rule() rule.out_interface = 'eth0' rule.protocol = protocol rule.target = iptc.Target(rule, 'auto_proxy') iptc.Chain(iptc.Table(iptc.Table.FILTER), 'OUTPUT').insert_rule(rule)
def get_vnsf_forward_chain(): table = iptc.Table(iptc.Table.FILTER) table.refresh() chain = iptc.Chain(table, "FORWARD") return chain
def get_vnsf_forward_chain(): table = iptc.Table(iptc.Table.FILTER) table.refresh() chain = iptc.Chain(table, settings.vnsf_forward_chain) return chain