Esempio n. 1
0
def backupIPTablesState():
    if iptc.is_table_available(iptc.Table.FILTER):
        subprocess.call('iptables-save > /tmp/iptables.bak', shell=True)
        LOG.debug("Backed up current IPTables Rules to /tmp/iptables.bak")
    if iptc.is_table_available(iptc.Table6.FILTER):
        subprocess.call('ip6tables-save > /tmp/ip6tables.bak', shell=True)
        LOG.debug("Backed up current IPTables Rules to /tmp/ip6tables.bak")
Esempio n. 2
0
def backupIPTablesState():
    if iptc.is_table_available(iptc.Table.FILTER):
        subprocess.call('iptables-save > /tmp/iptables.bak', shell=True)
        LOG.debug("Backed up current IPTables Rules to /tmp/iptables.bak")
    if iptc.is_table_available(iptc.Table6.FILTER):
        subprocess.call('ip6tables-save > /tmp/ip6tables.bak', shell=True)
        LOG.debug("Backed up current IPTables Rules to /tmp/ip6tables.bak")
Esempio n. 3
0
def getIPTablesRuleForClient(port, ipVersion, protocol, addr):
    if ipVersion == IP_VERSION.V4 and iptc.is_table_available(
            iptc.Table.FILTER):
        rule = iptc.Rule()
        rule.create_target('ACCEPT')
        rule.src = addr
        rule.protocol = protocol
        rule.create_match(protocol).dport = str(port)
        LOG.debug(
            "Created Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s",
            ipVersion, port, addr, protocol)

    elif ipVersion == IP_VERSION.V6 and iptc.is_table_available(
            iptc.Table6.FILTER):
        rule = iptc.Rule6()
        rule.create_target('ACCEPT')
        rule.src = addr
        rule.protocol = protocol
        rule.create_match(protocol).dport = str(port)
        LOG.debug(
            "Created Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s",
            ipVersion, port, addr, protocol)

    else:
        rule = None
        LOG.error(
            "Could not construct Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s",
            ipVersion, port, addr, protocol)

    return rule
Esempio n. 4
0
def getIPTablesChainForVersion(ipVersion, chain):
    if ipVersion == Constants.IP_VERSION.V4 and iptc.is_table_available(iptc.Table.FILTER):
        chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), chain)
    elif ipVersion == Constants.IP_VERSION.V6 and iptc.is_table_available(iptc.Table6.FILTER):
        chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), chain)
    else:
        LOG.error("Could not find chain \'%s\' for IPv%s IPTables", chain, ipVersion)

    return chain
Esempio n. 5
0
def setupIPTablesPortKnockingChainAndRedirectTraffic():
    if iptc.is_table_available(iptc.Table.FILTER):
        tableV4 = iptc.Table(iptc.Table.FILTER)
        try:
            knockChainV4 = getIPTablesChainForVersion(Constants.IP_VERSION.V4, IPTABLES_CHAIN_KNOCK)
            knockChainV4.flush()
        except iptc.IPTCError:
            knockChainV4 = tableV4.create_chain(IPTABLES_CHAIN_KNOCK)

        inputChainV4 = getIPTablesChainForVersion(Constants.IP_VERSION.V4, IPTABLES_CHAIN_INPUT)

        redirectRuleV4 = iptc.Rule()
        redirectRuleV4.target = iptc.Target(redirectRuleV4, IPTABLES_CHAIN_KNOCK)
        deleteIPTablesRuleIgnoringError(redirectRuleV4, inputChainV4)
        inputChainV4.insert_rule(redirectRuleV4)

        establishedRuleV4 = iptc.Rule()
        establishedRuleV4.create_match('state').state = "RELATED,ESTABLISHED"
        establishedRuleV4.target = iptc.Target(establishedRuleV4, 'ACCEPT')
        deleteIPTablesRuleIgnoringError(establishedRuleV4, inputChainV4)
        inputChainV4.insert_rule(establishedRuleV4)

        rejectRuleV4=iptc.Rule()
        rejectRuleV4.target = rejectRuleV4.create_target('REJECT')
        deleteIPTablesRuleIgnoringError(rejectRuleV4, inputChainV4)
        inputChainV4.append_rule(rejectRuleV4)

        LOG.debug("Setup Port-knocking IPTables Configuration for IPv4")

    if iptc.is_table_available(iptc.Table6.FILTER):
        tableV6 = iptc.Table6(iptc.Table6.FILTER)
        try:
            knockChainV6 = getIPTablesChainForVersion(Constants.IP_VERSION.V6, IPTABLES_CHAIN_KNOCK)
            knockChainV6.flush()
        except iptc.IPTCError:
            knockChainV6 = tableV6.create_chain(IPTABLES_CHAIN_KNOCK)

        inputChainV6 = getIPTablesChainForVersion(Constants.IP_VERSION.V6, IPTABLES_CHAIN_INPUT)

        redirectRuleV6 = iptc.Rule6()
        redirectRuleV6.target = iptc.Target(redirectRuleV6, IPTABLES_CHAIN_KNOCK)
        deleteIPTablesRuleIgnoringError(redirectRuleV6, inputChainV6)
        inputChainV6.insert_rule(redirectRuleV6)

        establishedRuleV6 = iptc.Rule6()
        establishedRuleV6.create_match('state').state = "RELATED,ESTABLISHED"
        establishedRuleV6.target = iptc.Target(establishedRuleV6, 'ACCEPT')
        deleteIPTablesRuleIgnoringError(establishedRuleV6, inputChainV6)
        inputChainV6.insert_rule(establishedRuleV6)

        rejectRuleV6=iptc.Rule6()
        rejectRuleV6.target = rejectRuleV6.create_target('REJECT')
        deleteIPTablesRuleIgnoringError(rejectRuleV6, inputChainV6)
        inputChainV6.append_rule(rejectRuleV6)

        LOG.debug("Setup Port-knocking IPTables Configuration for IPv6")
Esempio n. 6
0
def restoreIPTablesState():
    if iptc.is_table_available(iptc.Table.FILTER):
        subprocess.call('iptables-restore < /tmp/iptables.bak', shell=True)
        LOG.debug("Restored IPTables Rules from /tmp/iptables.bak")
        subprocess.call('rm /tmp/iptables.bak', shell=True)
        LOG.debug("Cleaned up backup file /tmp/iptables.bak")
    if iptc.is_table_available(iptc.Table6.FILTER):
        subprocess.call('ip6tables-restore < /tmp/ip6tables.bak', shell=True)
        LOG.debug("Restored IPTables Rules from /tmp/ip6tables.bak")
        subprocess.call('rm /tmp/iptables.bak', shell=True)
        LOG.debug("Cleaned up backup file /tmp/ip6tables.bak")
Esempio n. 7
0
def restoreIPTablesState():
    if iptc.is_table_available(iptc.Table.FILTER):
        subprocess.call('iptables-restore < /tmp/iptables.bak', shell=True)
        LOG.debug("Restored IPTables Rules from /tmp/iptables.bak")
        subprocess.call('rm /tmp/iptables.bak', shell=True)
        LOG.debug("Cleaned up backup file /tmp/iptables.bak")
    if iptc.is_table_available(iptc.Table6.FILTER):
        subprocess.call('ip6tables-restore < /tmp/ip6tables.bak', shell=True)
        LOG.debug("Restored IPTables Rules from /tmp/ip6tables.bak")
        subprocess.call('rm /tmp/ip6tables.bak', shell=True)
        LOG.debug("Cleaned up backup file /tmp/ip6tables.bak")
Esempio n. 8
0
def getIPTablesChainForVersion(ipVersion, chain):
    if ipVersion == IP_VERSION.V4 and iptc.is_table_available(
            iptc.Table.FILTER):
        chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), chain)
    elif ipVersion == IP_VERSION.V6 and iptc.is_table_available(
            iptc.Table6.FILTER):
        chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), chain)
    else:
        LOG.error("Could not find chain \'%s\' for IPv%s IPTables", chain,
                  ipVersion)

    return chain
Esempio n. 9
0
    def delete_trace_rule(self, mark_num=None):
        args_chain = ['OUTPUT', 'PREROUTING']

        if not iptc.is_table_available(iptc.Table.RAW):
            raise ValueError("table raw does not exist")

        table = iptc.Table("raw")

        rules = []
        for i in args_chain:
            chain = iptc.Chain(table, i)
            if len(chain.rules) != 0:
                count = len(chain.rules) - 1
                while (count > 0):
                    cur_rule = chain.rules[count]

                    target_name = cur_rule.target.name
                    if target_name == 'MARK':
                        target_mark = cur_rule.target.get_all_parameters().get(
                            'set-xmark', None)
                        if target_mark and target_mark[0].split(
                                '/')[0] in mark_num:
                            print len(chain.rules), cur_rule
                            chain.delete_rule(cur_rule)

                    matches = cur_rule.matches
                    for matche in matches:
                        if matche.name == 'mark':
                            matche_mark = matche.get_all_parameters().get(
                                'mark', None)
                            if matche_mark and matche_mark[0] in mark_num:
                                print len(chain.rules), cur_rule
                                chain.delete_rule(cur_rule)

                    count -= 1
Esempio n. 10
0
def getIPTablesRuleForClient(port, ipVersion, protocol, addr):
    if ipVersion == Constants.IP_VERSION.V4 and iptc.is_table_available(iptc.Table.FILTER):
        rule = iptc.Rule()
        rule.target = iptc.Target(rule, 'RETURN')
        rule.src = addr
        rule.protocol = protocol
        rule.create_match(protocol).dport = str(port)
        LOG.debug("Created Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s", ipVersion, port, addr, protocol)

    elif ipVersion == Constants.IP_VERSION.V6 and iptc.is_table_available(iptc.Table6.FILTER):
        rule = iptc.Rule6()
        rule.target = iptc.Target(rule, 'RETURN')
        rule.src = addr
        rule.protocol = protocol
        rule.create_match(protocol).dport = str(port)
        LOG.debug("Created Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s", ipVersion, port, addr, protocol)

    else:
        LOG.error("Could not construct Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s", ipVersion, port, addr, protocol)

    return rule
Esempio n. 11
0
def insertEmergencySSHAccessRule():
    if iptc.is_table_available(iptc.Table.FILTER):
        ruleV4 = iptc.Rule()
        ruleV4.create_target('ACCEPT')
        ruleV4.protocol = 'tcp'
        ruleV4.create_match('tcp').dport = '22'

        chainV4 = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
        deleteIPTablesRuleIgnoringError(ruleV4, chainV4)
        chainV4.insert_rule(ruleV4)

        LOG.debug("Inserted Emergency SSH Access Rule for IPv4")

    if iptc.is_table_available(iptc.Table6.FILTER):
        ruleV6 = iptc.Rule6()
        ruleV6.create_target('ACCEPT')
        ruleV6.protocol = 'tcp'
        ruleV6.create_match('tcp').dport = '22'

        chainV6 = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'INPUT')
        deleteIPTablesRuleIgnoringError(ruleV6, chainV6)
        chainV6.insert_rule(ruleV6)

        LOG.debug("Inserted Emergency SSH Access Rule for IPv6")
Esempio n. 12
0
def insertEmergencySSHAccessRule():
    if iptc.is_table_available(iptc.Table.FILTER):
        ruleV4 = iptc.Rule()
        ruleV4.target = iptc.Target(ruleV4, 'ACCEPT')
        ruleV4.protocol = 'tcp'
        ruleV4.create_match('tcp').dport = '22'

        chainV4 = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
        deleteIPTablesRuleIgnoringError(ruleV4, chainV4)
        chainV4.insert_rule(ruleV4)

        LOG.debug("Inserted Emergency SSH Access Rule for IPv4")

    if iptc.is_table_available(iptc.Table6.FILTER):
        ruleV6 = iptc.Rule6()
        ruleV6.target = iptc.Target(ruleV6, 'ACCEPT')
        ruleV6.protocol = 'tcp'
        ruleV6.create_match('tcp').dport = '22'

        chainV6 = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'INPUT')
        deleteIPTablesRuleIgnoringError(ruleV6, chainV6)
        chainV6.insert_rule(ruleV6)

        LOG.debug("Inserted Emergency SSH Access Rule for IPv6")
Esempio n. 13
0
    def delete_trace_rule(self, marknum_list=None, comment_pattern=None):
        args_chain = ['OUTPUT', 'PREROUTING']

        if not iptc.is_table_available(iptc.Table.RAW):
            raise ValueError("table raw does not exist")

        table = iptc.Table("raw")
        table.refresh()

        def scan_rule(chain=None):
            wait_delete = []
            if len(chain.rules) != 0:
                for cur_rule in chain.rules:
                    del_rule_flag = 0
                    target_name = cur_rule.target.name
                    if target_name == 'MARK':
                        target_mark = cur_rule.target.get_all_parameters().get(
                            'set-xmark', None)
                        if target_mark and target_mark[0].split(
                                '/')[0] in marknum_list:
                            del_rule_flag = 1
                            wait_delete.append(cur_rule)

                    matches = cur_rule.matches
                    for matche in matches:
                        if matche.name == 'mark':
                            matche_mark = matche.get_all_parameters().get(
                                'mark', None)
                            if matche_mark and matche_mark[0] in marknum_list:
                                wait_delete.append(cur_rule)

                        if not del_rule_flag and matche.name == 'comment':
                            matche_comment = matche.get_all_parameters().get(
                                'comment', None)
                            if matche_comment and comment_pattern and matche_comment[
                                    0] in comment_pattern:
                                #if del the --mark rule,then must del with this mark's  TRACE rule
                                marknum_list.append(
                                    target_mark[0].split('/')[0])
                                wait_delete.append(cur_rule)
            return wait_delete

        for i in args_chain:
            chain = iptc.Chain(table, i)
            wait_delete = scan_rule(chain)
            for rule in wait_delete:
                chain.delete_rule(rule)
Esempio n. 14
0
def main():
    global running
    import argparse
    import random

    parser = argparse.ArgumentParser(description="iptables-trace")

    parser.add_argument(
        "--clear-chain",
        action="store_true",
        default=False,
        help="delete all rules in the chain",
    )
    parser.add_argument(
        "--chain",
        "-c",
        type=str,
        nargs="*",
        choices=["OUTPUT", "PREROUTING"],
        default=["OUTPUT", "PREROUTING"],
        help="chain",
    )
    parser.add_argument("--source",
                        "-s",
                        type=str,
                        action="store",
                        default=None,
                        help="source")
    parser.add_argument(
        "--destination",
        "-d",
        type=str,
        action="store",
        default=None,
        help="destination",
    )
    parser.add_argument("--protocol",
                        "-p",
                        type=str,
                        action="store",
                        default=None,
                        help="protocol")
    parser.add_argument(
        "--xmark-mask",
        "-M",
        type=str,
        action="store",
        default="0x800001ff",
        help=
        "mark mask (bits to use) default is not to use lower 9 bits and the highest",
    )
    parser.add_argument(
        "--limit",
        action="store_true",
        default=False,
        help="limit rule matches to 1/second",
    )
    parser.add_argument("bpf", type=str, action="store", default="", nargs="*")

    args = parser.parse_args()
    print(args)

    if not iptc.is_table_available(iptc.Table.RAW):
        raise ValueError("table raw does not exist")
    table = iptc.Table("raw")

    rules = []
    for i in args.chain:
        chain = iptc.Chain(table, i)
        if args.clear_chain == True and len(chain.rules) != 0:
            while len(chain.rules) > 0:
                i = chain.rules[0]
                print("delete rule {}".format(i))
                chain.delete_rule(i)

        mark = iptc.Rule()
        if args.protocol:
            mark.protocol = args.protocol
        if args.source:
            mark.src = args.source
        if args.destination:
            mark.dst = args.destination

        if args.bpf:
            filter = args.bpf if isinstance(args.bpf, str) else " ".join(
                args.bpf)
            bpf = mark.create_match("bpf")
            bpf.bytecode = nfbpf_compile(filter)
            comment = mark.create_match("comment")
            comment.comment = 'bpf: "{}"'.format(filter)
        if args.limit:
            limit = mark.create_match("limit")
            limit.limit = "1/second"
        # 			limit.limit_burst = "1"

        mark.target = iptc.Target(mark, "MARK")
        m = 0
        while m == 0:
            _m = random.randint(0, 2**32 - 1)
            _m &= ~int(args.xmark_mask, 16)
            m = "0x{:x}".format(_m)
        mark.target.set_mark = m
        chain.append_rule(mark)
        rules.append((chain, mark))

        trace = iptc.Rule()
        match = trace.create_match("mark")
        match.mark = "{}/0x{:x}".format(m,
                                        0xFFFFFFFF & ~int(args.xmark_mask, 16))
        trace.target = iptc.Target(trace, "TRACE")
        chain.append_rule(trace)
        rules.append((chain, trace))

    n = nflog_handle.open()
    r = n.unbind_pf(socket.AF_INET)
    r = n.bind_pf(socket.AF_INET)
    qh = n.bind_group(0)
    qh.set_mode(0x02, 0xFFFF)

    qh.callback_register(trace_cb, int(args.xmark_mask, 16))

    fd = n.fd

    while running:
        try:
            r, w, x = select.select([fd], [], [], 1.0)
            if len(r) == 0:
                # timeout
                # 				print("timeout")
                continue
            if fd in r:
                n.handle_io()
        except:
            pass

    for chain, rule in rules:
        chain.delete_rule(rule)
Esempio n. 15
0
def main():
	global running
	import argparse
	import random

	parser = argparse.ArgumentParser(description='iptables-trace')

	parser.add_argument('--clear-chain', action='store_true', default=False, help="delete all rules in the chain")
	parser.add_argument('--chain','-c', type=str, nargs='*', choices=['OUTPUT','PREROUTING'], default=["OUTPUT",'PREROUTING'], help='chain')
	parser.add_argument('--source','-s', type=str, action='store', default=None, help='source')
	parser.add_argument('--destination','-d', type=str, action='store', default=None, help='destination')
	parser.add_argument('--protocol', '-p', type=str, action='store', default=None, help='protocol')
	parser.add_argument('--bpf',type=str, default=None, action='store')
	parser.add_argument('--xmark-mask', '-M', type=str, action='store', default="0x800001ff", help='mark mask (bits to use) default is not to use lower 9 bits and the highest')
	parser.add_argument("--limit", action='store_true', default=False, help="limit rule matches to 1/second")

	args = parser.parse_args()
	print(args)

	if not iptc.is_table_available(iptc.Table.RAW):
		raise ValueError("table raw does not exist")
	table = iptc.Table("raw")

	rules = []
	for i in args.chain:
		chain = iptc.Chain(table, i)
		if args.clear_chain == True and len(chain.rules) != 0:
			while len(chain.rules) > 0:
				i = chain.rules[0]
				print("delete rule {}".format(i))
				chain.delete_rule(i)

		mark = iptc.Rule()
		if args.protocol:
			mark.protocol = args.protocol
		if args.source:
			mark.src = args.source
		if args.destination:
			mark.dst = args.destination

		if args.bpf:
			bpf = mark.create_match("bpf")
			bpf.bytecode = nfbpf_compile(args.bpf)
			comment = mark.create_match("comment")
			comment.comment = 'bpf: "{}"'.format(args.bpf)
		if args.limit:
			limit = mark.create_match('limit')
			limit.limit = "1/second"
			limit.limit_burst = "1"

		mark.target = iptc.Target(mark, "MARK")
		m = 0
		while m == 0:
			_m = random.randint(0,2**32-1)
			_m &= ~int(args.xmark_mask, 16)
			m = "0x{:x}".format(_m)
		mark.target.set_mark = m
		chain.append_rule(mark)
		rules.append((chain,mark))

		trace = iptc.Rule()
		match = trace.create_match("mark")
		match.mark = "{}/0x{:x}".format(m,0xffffffff & ~int(args.xmark_mask, 16))
		trace.target = iptc.Target(trace, "TRACE")
		chain.append_rule(trace)
		rules.append((chain,trace))

	n = nflog_handle.open()
	r = n.unbind_pf(socket.AF_INET)
	r = n.bind_pf(socket.AF_INET)
	qh = n.bind_group(0)
	qh.set_mode(0x02, 0xffff)

	qh.callback_register(trace_cb, int(args.xmark_mask, 16));

	fd = n.fd

	while running:
		try:
			r,w,x = select.select([fd],[],[],1.)
			if len(r) == 0:
				# timeout
#				print("timeout")
				continue
			if fd in r:
				n.handle_io()
		except:
			pass

	for chain,rule in rules:
		chain.delete_rule(rule)
Esempio n. 16
0
def main():
	global running
	import argparse
	import random

	parser = argparse.ArgumentParser(description='iptables-trace')

	parser.add_argument('--clear-chain', action='store_true', default=False, help="delete all rules in the chain")
	parser.add_argument('--chain','-c', type=str, nargs='*', choices=['OUTPUT','PREROUTING'], default=["OUTPUT",'PREROUTING'], help='chain')
	parser.add_argument('--source','-s', type=str, action='store', default=None, help='source')
	parser.add_argument('--destination','-d', type=str, action='store', default=None, help='destination')
	parser.add_argument('--protocol', '-p', type=str, action='store', default=None, help='protocol')
	parser.add_argument('--iface', '-i', type=str, action='store', default=None, help='iface')
	parser.add_argument('--bpf',type=str, default=None, action='store')
	parser.add_argument('--xmark-mask', '-M', type=str, action='store', default="0x800001ff", help='mark mask (bits to use) default is not to use lower 9 bits and the highest')
	parser.add_argument("--limit", action='store_true', default=False, help="limit rule matches to 1/second")

	args = parser.parse_args()

	if not iptc.is_table_available(iptc.Table.RAW):
		raise ValueError("table raw does not exist")
	table = iptc.Table("raw")

	rules = []
	for i in args.chain:
		chain = iptc.Chain(table, i)

		if args.clear_chain == True and len(chain.rules) != 0:
                    count = len(chain.rules)-1
                    while (count > 0):
                        name = chain.rules[count].target.name
                        if name in ['MARK','TRACE']:
                            j = chain.rules[count]
                            print len(chain.rules), j
                            chain.delete_rule(j)
                        count -= 1;

		mark = iptc.Rule()
		if args.protocol:
			mark.protocol = args.protocol
		if args.source:
			mark.src = args.source
		if args.destination:
			mark.dst = args.destination

		if args.bpf:
			bpf = mark.create_match("bpf")
			bpf.bytecode = nfbpf_compile(args.bpf)
			comment = mark.create_match("comment")
			comment.comment = 'bpf: "{}"'.format(args.bpf)
		if args.limit:
			limit = mark.create_match('limit')
			limit.limit = "1/second"
			limit.limit_burst = "1"

		if i == 'PREROUTING':
			if args.iface:
				mark.in_interface = args.iface
		elif i == 'OUTPUT':
			if args.iface:
				mark.out_interface = args.iface

		mark.target = iptc.Target(mark, "MARK")
		m = 0
		while m == 0:
			_m = random.randint(0,2**32-1)
			_m &= ~int(args.xmark_mask, 16)
			m = "0x{:x}".format(_m)
		mark.target.set_mark = m
		chain.append_rule(mark)
		rules.append((chain,mark))

		trace = iptc.Rule()
		match = trace.create_match("mark")
		match.mark = "{}/0x{:x}".format(m,0xffffffff & ~int(args.xmark_mask, 16))
		trace.target = iptc.Target(trace, "TRACE")
		chain.append_rule(trace)
		rules.append((chain,trace))

	n = nflog_handle.open()
	r = n.unbind_pf(socket.AF_INET)
	r = n.bind_pf(socket.AF_INET)
	qh = n.bind_group(0)
	qh.set_mode(0x02, 0xffff)

	qh.callback_register(trace_cb, int(args.xmark_mask, 16));

	fd = n.fd

	while running:
		try:
			r,w,x = select.select([fd],[],[],1.)
			if len(r) == 0:
				# timeout
#				print("timeout")
				continue
			if fd in r:
				n.handle_io()
		except:
			pass

	for chain,rule in rules:
		chain.delete_rule(rule)
Esempio n. 17
0
def setupIPTablesPortKnockingChainAndRedirectTraffic(firewallPolicy):
    if iptc.is_table_available(iptc.Table.FILTER):
        tableV4 = iptc.Table(iptc.Table.FILTER)
        try:
            knockChainV4 = getIPTablesChainForVersion(IP_VERSION.V4,
                                                      IPTABLES_CHAIN_KNOCK)
            knockChainV4.flush()
        except iptc.IPTCError:
            knockChainV4 = tableV4.create_chain(IPTABLES_CHAIN_KNOCK)

        inputChainV4 = getIPTablesChainForVersion(IP_VERSION.V4,
                                                  IPTABLES_CHAIN_INPUT)

        redirectRuleV4 = iptc.Rule()
        redirectRuleV4.create_target(IPTABLES_CHAIN_KNOCK)
        deleteIPTablesRuleIgnoringError(redirectRuleV4, inputChainV4)
        inputChainV4.insert_rule(redirectRuleV4)

        establishedRuleV4 = iptc.Rule()
        establishedRuleV4.create_match('state').state = "RELATED,ESTABLISHED"
        establishedRuleV4.create_target('ACCEPT')
        deleteIPTablesRuleIgnoringError(establishedRuleV4, inputChainV4)
        inputChainV4.insert_rule(establishedRuleV4)

        icmpRuleV4 = iptc.Rule()
        icmpRuleV4.protocol = "icmp"
        icmpRuleV4.create_target('ACCEPT')
        deleteIPTablesRuleIgnoringError(icmpRuleV4, inputChainV4)
        inputChainV4.insert_rule(icmpRuleV4)

        defaultPolicyRuleV4 = iptc.Rule()
        if firewallPolicy == FIREWALL_POLICY.REJECT:
            defaultPolicyRuleV4.create_target('REJECT')
        elif firewallPolicy == FIREWALL_POLICY.DROP:
            defaultPolicyRuleV4.create_target('DROP')
        elif firewallPolicy == FIREWALL_POLICY.NONE:
            pass
        else:
            raise InvalidConfigException
        deleteIPTablesRuleIgnoringError(defaultPolicyRuleV4, inputChainV4)
        if not firewallPolicy == FIREWALL_POLICY.NONE:
            inputChainV4.append_rule(defaultPolicyRuleV4)

        LOG.debug("Setup Port-knocking IPTables Configuration for IPv4")

    if iptc.is_table_available(iptc.Table6.FILTER):
        tableV6 = iptc.Table6(iptc.Table6.FILTER)
        try:
            knockChainV6 = getIPTablesChainForVersion(IP_VERSION.V6,
                                                      IPTABLES_CHAIN_KNOCK)
            knockChainV6.flush()
        except iptc.IPTCError:
            knockChainV6 = tableV6.create_chain(IPTABLES_CHAIN_KNOCK)

        inputChainV6 = getIPTablesChainForVersion(IP_VERSION.V6,
                                                  IPTABLES_CHAIN_INPUT)

        redirectRuleV6 = iptc.Rule6()
        redirectRuleV6.create_target(IPTABLES_CHAIN_KNOCK)
        deleteIPTablesRuleIgnoringError(redirectRuleV6, inputChainV6)
        inputChainV6.insert_rule(redirectRuleV6)

        establishedRuleV6 = iptc.Rule6()
        establishedRuleV6.create_match('state').state = "RELATED,ESTABLISHED"
        establishedRuleV6.create_target('ACCEPT')
        deleteIPTablesRuleIgnoringError(establishedRuleV6, inputChainV6)
        inputChainV6.insert_rule(establishedRuleV6)

        icmpRuleV6 = iptc.Rule6()
        icmpRuleV6.protocol = "icmpv6"
        icmpRuleV6.create_target('ACCEPT')
        deleteIPTablesRuleIgnoringError(icmpRuleV6, inputChainV6)
        inputChainV6.insert_rule(icmpRuleV6)

        defaultPolicyRuleV6 = iptc.Rule6()
        if firewallPolicy == FIREWALL_POLICY.REJECT:
            defaultPolicyRuleV6.create_target('REJECT')
        elif firewallPolicy == FIREWALL_POLICY.DROP:
            defaultPolicyRuleV6.create_target('DROP')
        elif firewallPolicy == FIREWALL_POLICY.NONE:
            pass
        else:
            raise InvalidConfigException
        deleteIPTablesRuleIgnoringError(defaultPolicyRuleV6, inputChainV6)
        if not firewallPolicy == FIREWALL_POLICY.NONE:
            inputChainV6.append_rule(defaultPolicyRuleV6)

        LOG.debug("Setup Port-knocking IPTables Configuration for IPv6")
Esempio n. 18
0
    def insert_trace_rule(self, bpf=None, iface=None, clear_chain=False):

        args_chain = ['OUTPUT', 'PREROUTING']
        args_clear_chain = clear_chain
        args_bpf = bpf
        args_iface = iface
        args_xmark_mask = '0x800001ff'

        if not iptc.is_table_available(iptc.Table.RAW):
            raise ValueError("table raw does not exist")

        table = iptc.Table("raw")

        record_marks = []
        rules = []
        for i in args_chain:
            chain = iptc.Chain(table, i)
            if args_clear_chain == True and len(chain.rules) != 0:
                count = len(chain.rules) - 1
                while (count > 0):
                    name = chain.rules[count].target.name
                    if name in ['MARK', 'TRACE']:
                        j = chain.rules[count]
                        print len(chain.rules), j
                        chain.delete_rule(j)
                    count -= 1
            else:
                mark = iptc.Rule()
                if args_bpf:
                    bpf = mark.create_match("bpf")
                    bpf.bytecode = self.nfbpf_compile(args_bpf)
                    comment = mark.create_match("comment")
                    comment.comment = 'bpf: "{}"'.format(args_bpf)

                if i == 'PREROUTING':
                    if args_iface:
                        mark.in_interface = args_iface
                elif i == 'OUTPUT':
                    if args_iface:
                        mark.out_interface = args_iface

                mark.target = iptc.Target(mark, "MARK")
                m = 0
                while m == 0:
                    _m = random.randint(0, 2**32 - 1)
                    _m &= ~int(args_xmark_mask, 16)
                    m = "0x{:x}".format(_m)

                mark.target.set_mark = m
                chain.append_rule(mark)
                rules.append((chain, mark))

                trace = iptc.Rule()
                match = trace.create_match("mark")
                #match.mark = "{}/0x{:x}".format(m,0xffffffff & ~int(args_xmark_mask, 16))
                match.mark = "{}/0x{:x}".format(m, 0xffffffff)
                trace.target = iptc.Target(trace, "TRACE")
                chain.append_rule(trace)
                rules.append((chain, trace))

                record_marks.append(m)

        return record_marks