Beispiel #1
0
 def get_all_simple_path_new(self, rule, current_path):
     """
     create a list of path in order to go from the source to the dest of the rule
     :param rule: rule with the ip_source / port_source / port_dest / protocol / dest
     :param current_path: an empty list to begin
     :return: a list of list containing each element the packet go through
     """
     path_list = []
     if len(current_path) == 0:
         current_path.append([
             rule.ip_source[0], rule.ip_dest[0], rule.port_source,
             rule.port_dest, rule.protocol
         ])
         fw_ip_list = self.find_fw_from_ip(rule.ip_source[0])
         for data in fw_ip_list:
             new_rule = Rule(rule.identifier, rule.name, rule.protocol,
                             [data[1]], rule.port_source, rule.ip_dest,
                             rule.port_dest, Action(True))
             tmp_path = list(current_path)
             tmp_path.append(data[0])
             tmp_list = self.get_all_simple_path_new(new_rule, tmp_path)
             path_list += tmp_list
     elif len(current_path) == 1:
         print "error when searching path"
         return
     else:
         current_fw = current_path[len(current_path) - 1]
         # if prerouting insert here
         datas = self.check_rule_fw(rule, current_fw)
         if len(datas):
             for data in datas:
                 check_end = False
                 tmp = list(current_path)
                 for fw_interface in current_fw.interfaces:
                     if fw_interface.network is not None:
                         tmp_ope = Operator("EQ", fw_interface.network)
                         final_ip = self.ip_operator_merge(data[1], tmp_ope)
                         if final_ip is not None:
                             tmp.append([
                                 data[0], final_ip, data[2], data[3],
                                 data[4]
                             ])
                             path_list.append(tmp)
                             check_end = True
                 if not check_end:
                     routes_dests = self.find_routes(current_path, rule)
                     for route_dest in routes_dests:
                         rule.ip_dest = [routes_dests[1]]
                         fw_list = self.find_fw_from_intefarce(
                             route_dest[0].iface, current_fw)
                         for fw in fw_list:
                             tmp = list(current_path)
                             tmp.append(fw)
                             new_rule = Rule(0, "tmp_rule", data[4],
                                             [data[0]], data[2], [data[1]],
                                             data[3], Action(True))
                             tmp_list = self.get_all_simple_path_new(
                                 new_rule, tmp)
                             path_list += tmp_list
     return path_list
Beispiel #2
0
def init(name, raise_on_error=False):
    # clear object variables
    parser.object_dict.clear()
    # init firewall
    p_info['firewall'] = Firewall()
    p_info['firewall'].name = name
    p_info['firewall'].hostname = ntpath.basename(name)
    p_info['firewall'].type = 'Iptables'
    # create default acl
    p_info['firewall'].acl.append(ACL('INPUT'))
    p_info['firewall'].acl.append(ACL('FORWARD'))
    p_info['firewall'].acl.append(ACL('OUTPUT'))
    # init parser state
    p_info['current_interface_name'] = None
    p_info['used_object'] = set()
    p_info['default_policy'] = dict()
    p_info['default_policy']['INPUT'] = Action(True)
    p_info['default_policy']['FORWARD'] = Action(True)
    p_info['default_policy']['OUTPUT'] = Action(True)
    p_info['current_chain'] = None
    p_info['rule_id'] = 0
    p_info['rule_list'] = []
    p_info['rule_bind'] = dict()
    p_info['current_rule'] = Rule(p_info['rule_id'], None, [], [], [], [], [],
                                  Action(False))
    p_info['rule_bind'][p_info['rule_id']] = [None, None]
    p_info['current_table'] = None
    # raise on error option
    p_info['raise_on_error'] = raise_on_error
Beispiel #3
0
def p_action_reject2(p):
    '''action_line : DENY SEMI_COLON'''
    global parsing_level3, current_acl
    if parsing_level3 == 'policy':
        p_info['current_policy'].action = Action(False)
        p_info['rules'].append(p_info['current_policy'])
        current_acl.rules.append(p_info['current_policy'])
        p_info['current_policy'] = Rule(0, "", [], [], [], [], [],
                                        Action(False))
        parsing_level3 = ''
Beispiel #4
0
 def get_all_flows(self):
     for flow in self.liststore:
         current_rule = Rule(None, None, [], [], [], [], [], Action(False))
         try:
             if isinstance(flow[0], str) and len(flow[0]) != 0:
                 current_rule.identifier = int(flow[0])
             if isinstance(flow[1], str) and len(flow[1]) != 0:
                 protocols = flow[1].split(',')
                 for protocol in protocols:
                     current_rule.protocol.append(
                         Operator('EQ', Protocol(protocol)))
             if isinstance(flow[2], str) and len(flow[2]) != 0:
                 ips = flow[2].split(',')
                 for ip in ips:
                     if '/' in ip:
                         mask = ip[ip.index('/') + 1:]
                         ip = ip[:ip.index('/')]
                         current_rule.ip_source.append(
                             Operator(
                                 'EQ', Ip(ip,
                                          self.fromDec2Dotted(int(mask)))))
                     else:
                         current_rule.ip_source.append(
                             Operator('EQ', Ip(ip, '255.255.255.255')))
             if isinstance(flow[3], str) and len(flow[3]) != 0:
                 ports = flow[3].split(',')
                 for port in ports:
                     current_rule.port_source.append(
                         Operator('EQ', Port(int(port))))
             if isinstance(flow[4], str) and len(flow[4]) != 0:
                 ips = flow[4].split(',')
                 for ip in ips:
                     if '/' in ip:
                         mask = ip[ip.index('/') + 1:]
                         ip = ip[:ip.index('/')]
                         current_rule.ip_dest.append(
                             Operator(
                                 'EQ', Ip(ip,
                                          self.fromDec2Dotted(int(mask)))))
                     else:
                         current_rule.ip_dest.append(
                             Operator('EQ', Ip(ip, '255.255.255.255')))
             if isinstance(flow[5], str) and len(flow[5]) != 0:
                 ports = flow[5].split(',')
                 for port in ports:
                     current_rule.port_dest.append(
                         Operator('EQ', Port(int(port))))
             if flow[6] == 'deny':
                 current_rule.action = Action(False)
             elif flow[6] == 'accept':
                 current_rule.action = Action(True)
         except KeyError:
             print 'error'  #
         self.flows.append(current_rule)
 def get_rule_from_iptable_line(self, rule_line):
     """
     get one iptable line and return a corresponding rule
     This function need some improvement in order to manage every case
     """
     action = Action(True) if rule_line[0] != "DROP" else Action(False)
     if rule_line[3] == "anywhere":
         ip_source = []
     else:
         if "/" not in rule_line[3]:
             ip_source = [Operator("EQ", Ip(rule_line[3]))]
         else:
             ip_source = [
                 Operator(
                     'EQ',
                     Ip(rule_line[3].split('/')[0],
                        fromDec2Dotted(int(rule_line[3].split('/')[1]))))
             ]
     if rule_line[4] == "anywhere":
         ip_dest = []
     else:
         if "/" not in rule_line[4]:
             ip_dest = [Operator("EQ", Ip(rule_line[4]))]
         else:
             ip_dest = [
                 Operator(
                     'EQ',
                     Ip(rule_line[4].split('/')[0],
                        fromDec2Dotted(int(rule_line[4].split('/')[1]))))
             ]
     port_source = []
     port_dest = []
     protocol = [] if rule_line[1] == "all" else [
         Operator("EQ", Protocol(rule_line[1]))
     ]
     if len(rule_line) >= 7:
         if "spt" in rule_line[6]:
             port_source.append(Operator("EQ", Port(rule_line[6][4:-1])))
         elif "dpt" in rule_line[6]:
             port_dest.append(Operator("EQ", Port(rule_line[6][4:-1])))
         elif "multiport" in rule_line:
             tmp_idx = rule_line.index("multiport")
             if rule_line[tmp_idx + 1] == "dports":
                 ports_dest_list = rule_line[tmp_idx + 2].split(",")
                 for tmp_port_dest in ports_dest_list:
                     port_dest.append(Operator("EQ", Port(tmp_port_dest)))
         else:
             tmp_line = ""
             for tmp_elem in rule_line:
                 tmp_line += "  " + tmp_elem
             print tmp_line
     return Rule(0, "", protocol, ip_source, port_source, ip_dest,
                 port_dest, action)
Beispiel #6
0
def finish():
    acls = {}
    index = 0
    for fw in firewalls:
        acls[fw['name']] = []
    for rule in rules:
        p_info['current_rule'] = Rule(None, None, [], [], [], [], [],
                                      Action(False))
        p_info['current_rule'].identifier = index
        index += 1
        if rule['action'] == 'accept':
            p_info['current_rule'].action = Action(True)
        elif rule['action'] == 'drop':
            p_info['current_rule'].action = Action(False)
        p_info['current_rule'].name = rule['name'] if rule[
            'name'] else 'Rule' + str(index)
        if rule['src']:
            for s in rule['src']:
                finish_src(s)
            for s in rule['dst']:
                finish_dst(s)
            for s in rule['services']:
                finish_serv(s)

        if len(rule['install']) > 0:
            for elt in rule['install']:
                if elt == 'Gateways':
                    for k in acls.keys():
                        acls[k].append(p_info['current_rule'])
                elif acls.has_key(elt):
                    acls[elt].append(p_info['current_rule'])

    fill_unused_obj()
    for obj in object_dict:
        if obj['type'] in {
                'host', 'gateway', 'gateway_cluster', 'network',
                'dynamic_net_obj'
        } and obj.has_key('ipaddr'):
            fill_obj_dict_netobj(obj)
        elif obj['type'] in {'udp', 'UDP', 'Udp', 'tcp', 'Tcp', 'TCP'}:
            fill_obj_dict_serv1(obj)
        elif obj['type'] in {'other', 'Other'}:
            if obj.has_key('protocol'):
                fill_obj_dict_serv2(obj)
        elif obj['type'] in {
                'icmp', 'Icmp', 'igmp', 'Igmp', 'Gre', 'gre', 'GRE', 'ospf',
                'OSPF', 'Ospf'
        }:
            fill_obj_dict_serv3(obj)
    finish_fw(acls)
    del firewalls[:]
Beispiel #7
0
 def get_general_rule(self, node):
     """
     Return a rule in accords with the policy
     """
     rule = None
     txt = node.data_list[0][2] + " " + node.data_list[0][3]
     if txt == "(policy DROP)\n":
         rule = Rule(self.instance.identifier, "all", [], [], [], [], [],
                     Action(False))
         self.instance.identifier += 1
     elif txt == "(policy ACCEPT)\n":
         rule = Rule(self.instance.identifier, "all", [], [], [], [], [],
                     Action(False))
         self.instance.identifier += 1
     return rule
def init(name, raise_on_error=False):
    global i, j, k, cptr, current_rule, d, nd
    i, j, k, cptr = 0, 0, 0, 0
    current_rule = {
        'index': None,
        'action': None,
        'src': [],
        'dst': [],
        'install': [],
        'services': []
    }
    p_info['firewall_list'] = []
    p_info['name'] = name
    p_info['hostname'] = ntpath.basename(name)
    p_info['current_rule'] = Rule(None, None, [], [], [], [], [],
                                  Action(False))
    p_info['firewall'] = Firewall()
    del object_dict[:], firewalls[:], used_objects[:], rules[:]
    d = {
        'host': list(),
        'port': list(),
        'protocol': list(),
        'machines_range': list(),
        'netobj': list()
    }
    nd = {
        'host': list(),
        'port': list(),
        'protocol': list(),
        'machines_range': list(),
        'netobj': list()
    }
Beispiel #9
0
def init(name, raise_on_error=False):
    object_dict.clear()
    p_info['firewall'] = Firewall()
    p_info['firewall'].name = name
    p_info['firewall'].hostname = ntpath.basename(name)
    p_info['firewall'].type = 'Juniper Netscreen'
    p_info['current_policy'] = Rule(0, "", [], [], [], [], [], Action(False))
    p_info['context_policy'] = Rule(0, "", [], [], [], [], [], Action(False)),
    p_info['policy_zone_src'] = None
    p_info['policy_zone_dst'] = None
    p_info['current_object'] = []
    p_info['used_object'] = set()
    p_info['policy_context'] = 0
    p_info['index_rule'] = -1
    p_info['default_permit_all'] = False
    p_info['raise_on_error'] = raise_on_error
def insert_rule():
    if p_info['policy_zone_src'] and p_info['policy_zone_dst']:
        acl = p_info['firewall'].get_acl_by_name(p_info['policy_zone_src'] +
                                                 '-' +
                                                 p_info['policy_zone_dst'])

        if not acl:
            acl = ACL(p_info['policy_zone_src'] + '-' +
                      p_info['policy_zone_dst'])
            p_info['firewall'].acl.append(acl)
            NetworkGraph.NetworkGraph.NetworkGraph().bind_acl(
                acl, p_info['firewall'],
                p_info['firewall'].get_interface_by_name(
                    p_info['policy_zone_src']),
                p_info['firewall'].get_interface_by_name(
                    p_info['policy_zone_dst']))

        if p_info['index_rule'] != -1:
            acl.rules.insert(p_info['index_rule'], p_info['current_policy'])
        else:
            acl.rules.append(p_info['current_policy'])
    else:
        for acl in p_info['firewall'].acl:
            acl.rules.append(p_info['current_policy'])

    p_info['current_policy'] = Rule(0, "", [], [], [], [], [], Action(False))
    p_info['policy_zone_src'] = None
    p_info['policy_zone_dst'] = None
    p_info['index_rule'] = -1
Beispiel #11
0
def p_edit_line(p):
    '''edit_line : EDIT NUMBER
                 | EDIT WORD'''
    if get_state() == 'vdom':
        finish()  # finish
        restore_or_create_fw(p[2])  # reset to a new firewall
    elif get_state() == 'policy':
        p_info['current_rule'] = Rule(int(p[2]), None, [], [], [], [], [],
                                      Action(False))
        p_info['srcintf'] = []
        p_info['dstintf'] = []
    elif get_state() in ('address', 'address_group', 'service',
                         'service_group'):
        object_dict[remove_quote(p[2])] = []
        p_info['current_object'] = remove_quote(p[2])
        p_info['range_ip'] = None
        p_info['range_port'] = None
    elif get_state() == 'interface':
        p_info['current_interface'] = Interface(remove_quote(p[2]), None, None,
                                                [])
        p_info['interface_list'].append([p_info['current_interface'], None])
    elif get_state() == 'zone':
        p_info['zone_list'][remove_quote(p[2])] = []
        p_info['current_zone'] = remove_quote(p[2])
    elif parsing_route == True:
        p_info['current_route'].id = int(p[2])
Beispiel #12
0
def p_policy_name_line2(p):
    '''policy_name_line : POLICY NUMBER WORD LBRACKET'''
    global parsing_level3, cptr
    cptr += 1
    parsing_level3 = 'policy'
    p_info['current_policy'] = Rule(p[2] + p[3], p[2] + p[3], [], [], [], [],
                                    [], Action(False))
def finish():
    p_info['firewall'].dictionnary = dict(object_dict)
    for k in object_dict:
        if k not in p_info['used_object']:
            p_info['firewall'].unused_objects.add(k)

    if p_info['default_permit_all']:
        for acl in p_info['firewall'].acl:
            acl.rules.append(
                Rule(-1, 'default', [], [], [], [], [], Action(True)))
def finish():
    acls = {}
    for rule in rules:
        p_info['current_rule'] = Rule(None, None, [], [], [], [], [],
                                      Action(False))
        p_info['current_rule'].identifier = rule['index']
        if rule['action'] == 'accept':
            p_info['current_rule'].action = Action(True)
        elif rule['action'] == 'drop':
            p_info['current_rule'].action = Action(False)
        p_info['current_rule'].name = 'Rule-' + rule['index']
        if rule['src']:
            for s in rule['src']:
                finish_src(s)
            for s in rule['dst']:
                finish_dst(s)
            for s in rule['services']:
                finish_serv(s)

        if acls.has_key(rule['install'][0]):
            acls[rule['install'][0]].append(p_info['current_rule'])
        else:
            acls[rule['install'][0]] = []
            acls[rule['install'][0]].append(p_info['current_rule'])
    fill_unused_obj()
    for obj in object_dict:
        if obj['type'] in {
                'host', 'gateway', 'gateway_cluster', 'network', 'bogus_ip'
        }:
            fill_obj_dict_netobj(obj)
        elif obj['type'] in {'udp', 'UDP', 'Udp', 'tcp', 'Tcp', 'TCP'}:
            fill_obj_dict_serv1(obj)
        elif obj['type'] in {'other', 'Other'}:
            fill_obj_dict_serv2(obj)
        elif obj['type'] in {
                'icmp', 'Icmp', 'igmp', 'Igmp', 'Gre', 'gre', 'GRE', 'ospf',
                'OSPF', 'Ospf'
        }:
            fill_obj_dict_serv3(obj)
    finish_fw(acls)
    del firewalls[:]
Beispiel #15
0
def init(name, raise_on_error=False):
    object_dict.clear()
    p_info['firewall'] = Firewall()
    p_info['firewall'].name = name
    p_info['firewall'].hostname = ntpath.basename(name)
    p_info['firewall'].type = 'Cisco Asa'
    p_info['interface_state'] = False
    p_info['current_interface'] = None
    p_info['object_name'] = None
    p_info['used_object'] = set()
    p_info['bounded_rules'] = set()
    p_info['rule_id'] = 0
    p_info['rule_list'] = []
    p_info['current_rule'] = Rule(None, None, [], [], [], [], [], Action(False))
    p_info['index_rule'] = 0
    p_info['global_rules'] = []
    p_info['raise_on_error'] = raise_on_error
Beispiel #16
0
def _init(vdom):
    object_dict.clear()
    p_info['firewall'] = Firewall()
    p_info['firewall'].name = p_info['name']
    p_info['firewall'].hostname = p_info['hostname'] + ('-' +
                                                        vdom if vdom else '')
    p_info['firewall'].type = 'Fortinet FortiGate'
    p_info['vdom'] = vdom
    p_info['srcintf'] = []
    p_info['dstintf'] = []
    p_info['used_object'] = set()
    p_info['bounded_rules'] = set()
    p_info['current_rule'] = Rule(None, None, [], [], [], [], [],
                                  Action(False))
    p_info['current_interface'] = Interface(None, None, None, [])
    p_info['current_object'] = None
    p_info['range_ip'] = None
    p_info['range_port'] = None
    p_info['route_list'] = []
    p_info['current_route'] = Route(None, None, None, None, None, 1)
    p_info['index_route'] = 0
Beispiel #17
0
    def search_rules(self, rule, operator, action, tree_path):
        """Deep search option.
        Reparse all rules corresponding to the anomaly.

        Parameters
        ----------
        rule : Rule. The rule to compare
        operator : Bdd.Operator. The operation to perform
        action : Bool or None. Filter rules having this action
        path : the current tested path
        index_path : the current position of the rule in the current path"""
        error_rules = deque()
        parent = tree_path[0]
        for i in xrange(1, len(tree_path)):
            if self.cancel:
                break
            if len(tree_path[i]) > 1:
                error_rules += self.search_rules(rule, operator, action,
                                                 tree_path[i])
            acl_list = NetworkGraph.NetworkGraph().get_acl_list(
                src=tree_path[i][0], dst=parent)
            for acl in acl_list:
                for rule_path in acl.get_rules_path():
                    for r, a in rule_path:
                        rule_action = r.action.chain if isinstance(
                            r.action.chain, bool) else a
                        if action is not None and rule_action != action:
                            continue
                        if compare_bdd(rule.toBDD(), operator, r.toBDD()):
                            error_rules.append(r)

        if not error_rules:
            deny_rule = Rule(-1, 'probably implicit deny', [], [], [], [], [],
                             Action(False))
            if not action and compare_bdd(rule.toBDD(), operator,
                                          deny_rule.toBDD()):
                error_rules.append(deny_rule)

        return error_rules
Beispiel #18
0
def p_hyphen_line(p):
    '''hyphen_line : DBL_HYPHEN'''
    p_info['rule_list'].append(p_info['current_rule'])
    p_info['current_rule'] = Rule(0, '', [], [], [], [], [], Action(False))
Beispiel #19
0
def init():
    p_info['rule_list'] = []
    p_info['current_rule'] = Rule(0, '', [], [], [], [], [], Action(True))
Beispiel #20
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-

from Parser.ply import yacc
from Parser.QueryPathParser.QueryPathLex import tokens
from Parser.QueryPathParser.QueryPathLex import lexer
from SpringBase.Rule import Rule
from SpringBase.Operator import Operator
from SpringBase.Protocol import Protocol
from SpringBase.Ip import Ip
from SpringBase.Port import Port
from SpringBase.Action import Action

p_info = {
    'rule_list': [],
    'current_rule': Rule(0, '', [], [], [], [], [], Action(True)),
}


def init():
    p_info['rule_list'] = []
    p_info['current_rule'] = Rule(0, '', [], [], [], [], [], Action(True))


def get_query():
    p_info['rule_list'].append(p_info['current_rule'])
    return p_info['rule_list']


def p_lines(p):
    '''lines : line
Beispiel #21
0
def p_policy_set_line_2(p):
    '''policy_set_line : SET ACTION DENY'''
    if get_state() == 'policy':
        p_info['current_rule'].action = Action(False)
Beispiel #22
0
def p_policy_set_line_1(p):
    '''policy_set_line : SET ACTION ACCEPT'''
    if get_state() == 'policy':
        p_info['current_rule'].action = Action(True)
Beispiel #23
0
def p_target2(p):
    '''target : DROP'''
    p[0] = Action(False)
Beispiel #24
0
# Use for construct dictionary of object and object group
object_dict = {}
parsing_route = False
parsing_ipsec = False
# Use for detect state
p_info = {
    'firewall_list': [],
    'firewall': Firewall(),
    'vdom': None,
    'name': None,
    'hostname': None,
    'srcintf': [],
    'dstintf': [],
    'used_object': set(),
    'bounded_rules': set(),
    'current_rule': Rule(None, None, [], [], [], [], [], Action(False)),
    'current_interface': Interface(None, None, None, []),
    'current_object': None,
    'current_state': [],
    'range_ip': None,
    'range_port': None,
    'raise_on_error': False,
    'use_vdom': False,
    'interface_list': [],
    'zone_list': {},
    'current_zone': None,
    'route_list': [],
    'current_route': Route(None, None, None, None, None, 1),
    'index_route': 0,
}
Beispiel #25
0
def p_target4(p):
    '''target : RETURN'''
    p[0] = Action('RETURN')
Beispiel #26
0
def p_target1(p):
    '''target : ACCEPT'''
    p[0] = Action(True)
Beispiel #27
0
zones = []

current_acl = ACL(None)

current_iface = Interface(None)
current_sub_iface = Interface(None)
ifaces = []

# Use for construct dictionary of object and object group
object_dict = {}

# Use for detect state
p_info = {
    'firewall': Firewall(),
    'current_policy': Rule(0, "", [], [], [], [], [], Action(False)),
    'context_policy': Rule(0, "", [], [], [], [], [], Action(False)),
    'policy_zone_src': None,
    'policy_zone_dst': None,
    'current_object': None,
    'used_object': set(),
    'policy_context': 0,
    'index_rule': -1,
    'default_permit_all': False,
    'raise_on_error': False,
    'route_list': [],
    'current_route': Route(None, None, None, None, None, 1),
    'index_route': 0,
    'rules': [],
}
Beispiel #28
0
def p_action_2(p):
    '''action : DENY'''
    p_info['current_rule'].action = Action(False)
Beispiel #29
0
def p_action_1(p):
    '''action : ACCEPT'''
    p_info['current_rule'].action = Action(True)
Beispiel #30
0
def p_target5(p):
    '''target : WORD'''
    if p_info['current_table'] == 'filter':
        p[0] = Action(find_chain_by_name(p[1]))