def on_click(self, widget):
        """
        Event listener : launch when "Run Query" is clicked.
        Launch the query path search algorithm.
        """
        protocol_op = []
        ip_source_op = []
        port_source_op = []
        ip_dest_op = []
        port_dest_op = []

        if self.protocol_entry.get_text() != '':
            protocol_op = [
                Operator.Operator(
                    'EQ', Protocol.Protocol(self.protocol_entry.get_text()))
            ]
        if self.ip_source_entry.get_text() != '':
            mask_src = self.mask_source_entry.get_text(
            ) if self.mask_source_entry.get_text() else '255.255.255.255'
            ip_source_op = [
                Operator.Operator(
                    'EQ', Ip.Ip(self.ip_source_entry.get_text(), mask_src))
            ]
        if self.port_source_entry.get_text() != '':
            port_source_op = [
                Operator.Operator('EQ',
                                  Port.Port(self.port_source_entry.get_text()))
            ]
        if self.ip_dest_entry.get_text() != '':
            mask_dst = self.mask_dest_entry.get_text(
            ) if self.mask_dest_entry.get_text() else '255.255.255.255'
            ip_dest_op = [
                Operator.Operator(
                    'EQ', Ip.Ip(self.ip_dest_entry.get_text(), mask_dst))
            ]
        if self.port_dest_entry.get_text() != '':
            port_dest_op = [
                Operator.Operator('EQ',
                                  Port.Port(self.port_dest_entry.get_text()))
            ]

        test_rule = Rule.Rule(0, 'query_path', protocol_op, ip_source_op,
                              port_source_op, ip_dest_op, port_dest_op,
                              Action.Action(True))

        self.popup.destroy()

        res = []

        #try:
        res, routedPaths = run_query(test_rule)
        if not res:
            Gtk_DialogBox("No path found !")
        # except:
        # message popup if no result

        g = NetworkGraph.NetworkGraph()

        # clear old path
        Gtk_Main.Gtk_Main().lateral_pane.path.clear()
        Gtk_Main.Gtk_Main().lateral_pane.path_route.clear()
        for edge in g.graph.edges(data=True):
            edge[2]['object'].clear_path()

        # construct and add path string
        """
        for path_data in res:
            path = path_data[0]
            i = 0
            while i < len(path) - 1:
                # mark path
                g.graph[path[i]][path[i + 1]]['object'].mark_path()
                i += 1
            Gtk_Main.Gtk_Main().lateral_pane.path.add_row(path_to_string(path_data[0], '\n'))
        """
        routedPaths = []
        # add routed path result
        for path_data in routedPaths:
            path = path_data[0]
            i = 0
            while i < len(path) - 1:
                # mark path
                g.graph[path[i]][path[i + 1]]['object'].mark_path()
                i += 1
            Gtk_Main.Gtk_Main().lateral_pane.path_route.add_row(
                path_to_string(path_data[0], '\n'))

        # Gtk_Main.Gtk_Main().lateral_pane.path_data = res
        Gtk_Main.Gtk_Main().lateral_pane.focus_path()
        Gtk_Main.Gtk_Main().statusbar.change_message("Ready")
示例#2
0
    def on_open_project(self, widget):
        """Open project and load saved object"""
        Gtk_Main.Gtk_Main().statusbar.change_message("Open project ...")

        filename = self.open_filechooser("Open project")
        if not filename:
            return

        # clear #
        Gtk_Main.Gtk_Main().lateral_pane.firewalls.clear()
        Gtk_Main.Gtk_Main().lateral_pane.details.clear()
        Gtk_Main.Gtk_Main().lateral_pane.path.clear()
        while Gtk_Main.Gtk_Main().notebook.notebook.notebook.get_n_pages() > 0:
            Gtk_Main.Gtk_Main().notebook.notebook.notebook.remove_page(0)
        while Gtk_Main.Gtk_Main().notebook.notebook_split.notebook.get_n_pages(
        ) > 0:
            Gtk_Main.Gtk_Main().notebook.notebook_split.notebook.remove_page(0)
        Gtk_Main.Gtk_Main().notebook.notebook.add_tab(
            Gtk_Main.Gtk_Main().networkcanvas.vbox, "Topology")
        Gtk_Main.Gtk_Main().notebook.tab_dict.clear()
        for node in NetworkGraph.NetworkGraph().graph.node.items():
            if isinstance(node[0], Firewall):
                NetworkGraph.NetworkGraph().remove_firewall(node[1]['object'])

        fh = open(filename, 'rb')
        p = pickle.Unpickler(fh)
        # get network graph singleton
        NetworkGraph.NetworkGraph._instance = p.load()
        # get saved query path
        [Gtk_Main.Gtk_Main().lateral_pane.path.add_row(m) for m in p.load()]
        Gtk_Main.Gtk_Main().lateral_pane.path_data = p.load()
        # get notebook list
        notebook_list = p.load()
        fh.close()

        # add firewall list
        [
            Gtk_Main.Gtk_Main().lateral_pane.firewalls.add_row(fw.hostname)
            for fw in NetworkGraph.NetworkGraph().firewalls
        ]
        # redraw
        Gtk_Main.Gtk_Main().networkcanvas.draw()
        # add notebook page
        for i in notebook_list:
            if isinstance(i, ACL):
                Gtk_Main.Gtk_Main().notebook.add_interface_tab(i)
            elif isinstance(i, InternalDetection):
                Gtk_Main.Gtk_Main().notebook.add_internal_anomaly_tab(i)
            elif isinstance(i, DistributedDetection):
                Gtk_Main.Gtk_Main().notebook.add_distributed_anomaly_tab(i)

        Gtk_Main.Gtk_Main().notebook.notebook.notebook.set_page(0)

        Gtk_Main.Gtk_Main().statusbar.change_message("Construct ROBDD ...")
        firewall_list = NetworkGraph.NetworkGraph().firewalls
        for fw in firewall_list:
            t0 = time.time()
            fw.build_bdd()
            message = "ROBDD build bdd in %.3f seconds" % (time.time() - t0)
            if len(firewall_list) - firewall_list.index(fw) - 1 > 0:
                message += ", %d remaining ..." % (len(firewall_list) -
                                                   firewall_list.index(fw) - 1)
            Gtk_Main.Gtk_Main().change_statusbar(message)

        Gtk_Main.Gtk_Main().statusbar.change_message("Ready")
def run_query(rule, ip_source=None, ip_dest=None):
    """Get all simple path, run query and return a formatted result list.

    Parameters
    ----------
    rule : Rule. The rule to test
    ip_source : Ip (optional, default=None). If not None, specify the interface source
    ip_dest : Ip (optional, default=None). If not None, specifu the interface destination

    Return
    ------
    Return a formatted list containing data about matching path
    """
    res = []

    g = NetworkGraph.NetworkGraph()

    # get all simple path
    start = time.time()
    simple_path = g.get_all_simple_path_new(rule, [])
    if len(simple_path):
        create_graph(simple_path)
        return (["success"], [])
    else:
        return ([], [])

    simple_path = g.get_all_simple_path(ip_source, ip_dest)
    end = time.time()
    print 'temps mis = ', str(end - start)
    print 'simple len', len(simple_path)

    for node in g.graph.nodes(data=True):
        if node[1]['object'].marker_type == 'from':
            ip_source = node[0]
        if node[1]['object'].marker_type == 'to':
            ip_dest = node[0]
    """
    simple_path = []
    [simple_path.append(i) for i in g.get_all_simple_path(ip_source, ip_dest)]
    # delete double
    simple_path.sort()
    simple_path = list(simple_path for simple_path, _ in itertools.groupby(simple_path))
    """

    ress = []
    count = 0
    length = len(simple_path)
    for i in range(len(simple_path)):
        pass  # print simple_path[i]
    for path in simple_path:
        i = 0
        trouve = False
        while i < len(path):
            if i < len(path) - 1:
                # if path[i] and path[i + 1] are ip, find the corresponding firewall to add in the path, so we can
                # mark the path passing through the firewall
                if not isinstance(path[i],
                                  Firewall.Firewall) and not isinstance(
                                      path[i + 1], Firewall.Firewall):
                    # get the firewall
                    trouve = True
            i += 1
        if trouve == False:
            ress.append(path)
    simple_path = list(ress)
    # parse all path
    for path in simple_path:
        count += 1
        Gtk_Main.Gtk_Main().statusbar.change_message(
            "QueryPath : test path %d of %d" % (count, length))
        Gtk_Main.Gtk_Main().update_interface()
        # list of rule list
        rule_list = [[]]
        i = 0
        while i < len(path) - 1:
            # list of acl between path[i] and path[i + 1] who match the query
            acl_list = []
            for acl in g.get_acl_list(path[i], path[i + 1]):
                sub_rule = get_subset_rule(rule, acl.get_rules())
                if sub_rule and sub_rule.action.chain:
                    acl_list.append((acl, sub_rule))
            # acl_list empty : this mean we don't find an accepting rule between path[i] and path[i + 1]
            # so we give up
            if not acl_list:
                break

            # duplicate rule_list depending on the number of acl found in acl_list
            # this mean that if we found to acl who match the query between path[i] and path[i + 1],
            # we duplicate the rule_list to have all acl and rules possible
            rule_list += [
                list(l) for l in rule_list for _ in xrange(len(acl_list) - 1)
            ]
            [
                rule_list[j].append(acl_list[j * len(acl_list) /
                                             len(rule_list)])
                for j in xrange(len(rule_list))
            ]
            i += 1

        if i == len(path) - 1:
            # res += [(list(path), rule_list[0])]
            # res += [(list(path), [l for l in rule_list])]

            for l in rule_list:
                # add the path list for each list in rule_list
                res += [(list(path), l)]

    # format result #
    for path_data in res:
        path = path_data[0]
        i = 0
        acl_index = 0
        while i < len(path):
            if i < len(path) - 1:
                # if path[i] and path[i + 1] are ip, find the corresponding firewall to add in the path, so we can
                # mark the path passing through the firewall
                if not isinstance(path[i],
                                  Firewall.Firewall) and not isinstance(
                                      path[i + 1], Firewall.Firewall):
                    # get the firewall
                    fw = [
                        fw for fw in g.firewalls
                        for acl in g.get_acl_list(firewall=fw)
                        if acl == path_data[1][acl_index][0]
                    ][0]
                    path.insert(i + 1, fw)
                    acl_index -= 1
            i += 1
            acl_index += 1
    routed_paths = get_routed_paths(list(res), ip_dest)
    # print res[0][0]

    # delete double from res

    # remove_double(res)
    # remove_bad_path(res)
    # print 'res', res

    # delete bad results : path containing the same firewall twice or more

    return (res, routed_paths)
示例#4
0
    def popup(self, object, event, node):
        """Clear the popup menu and add child element depending if node is a firewall or a network.

        Parameters
        ----------
        node : the clicked Node
        """
        self.node = node
        self.object = object
        map(self.menu.remove, self.menu.get_children())

        # Show conf #
        if isinstance(self.node.object, Firewall.Firewall):
            self.show_conf = gtk.MenuItem("Show configuration")
            self.menu.append(self.show_conf)
            self.show_conf.connect("activate", self.on_show_conf)

        # Add Note #
        if isinstance(self.node.object, Firewall.Firewall) or isinstance(
                self.node.object, Ip.Ip):
            self.add_note = gtk.MenuItem("Add note")
            self.menu.append(self.add_note)
            self.add_note.connect("activate", self.on_add_note)

        # Anomaly detection #
        if isinstance(self.node.object, Firewall.Firewall):
            self.anomaly_menu = gtk.MenuItem("Detect anomaly")
            self.menu.append(self.anomaly_menu)
            self.anomaly_menu.connect("activate", self.on_anomaly_menu)

        # Configuration error #
        if isinstance(self.node.object, Firewall.Firewall):
            self.config_error_menu = gtk.MenuItem("Configuration error")
            self.menu.append(self.config_error_menu)
            self.config_error_menu.connect("activate",
                                           self.on_config_error_menu)

        # Object list #
        if isinstance(self.node.object, Firewall.Firewall):
            self.object_menu = gtk.MenuItem("Object list")
            self.menu.append(self.object_menu)
            self.object_menu.connect("activate", self.on_object_menu)

        # Service list #
        if isinstance(self.node.object, Firewall.Firewall):
            self.service_menu = gtk.MenuItem("Service list")
            self.menu.append(self.service_menu)
            self.service_menu.connect("activate", self.on_service_menu)

        # Export Interfaces #
        if isinstance(self.node.object, Firewall.Firewall):
            self.export_itf_menu = gtk.MenuItem("Export interfaces list")
            self.menu.append(self.export_itf_menu)
            self.export_itf_menu.connect("activate", self.on_export_itf_list)

        # Error conf #
        if isinstance(self.node.object, Firewall.Firewall):
            self.error_conf_menu = gtk.MenuItem(
                "Generate anonymous configuration")
            self.menu.append(self.error_conf_menu)
            self.error_conf_menu.connect("activate", self.on_error_conf)

        # Remove #
        if isinstance(self.node.object, Firewall.Firewall):
            self.remove_menu = gtk.MenuItem("Remove")
            self.menu.append(self.remove_menu)
            self.remove_menu.connect("activate", self.on_remove_menu)

        # Show Nat rules #
        if isinstance(self.node.object, Firewall.Firewall):
            self.show_nat_rule = gtk.MenuItem("Show nat rules")
            self.menu.append(self.show_nat_rule)
            self.show_nat_rule.connect("activate", self.on_show_nat_rule)

        # Show IPSec Tunnels #
        if isinstance(self.node.object, Firewall.Firewall):
            self.show_ipsec_tunnels = gtk.MenuItem("Show IPSec tunnels")
            self.menu.append(self.show_ipsec_tunnels)
            self.show_ipsec_tunnels.connect("activate",
                                            self.on_show_ipsec_tunnels)

        # Add route config file #
        if isinstance(self.node.object, Firewall.Firewall):
            self.add_route_config = gtk.MenuItem("add route config")
            self.menu.append(self.add_route_config)
            self.add_route_config.connect("activate", self.on_add_route_config)

        # Add interface config file #
        if isinstance(self.node.object, Firewall.Firewall):
            self.add_interface_config = gtk.MenuItem("add interface config")
            self.menu.append(self.add_interface_config)
            self.add_interface_config.connect("activate",
                                              self.on_add_interface_config)

        # Itinerary #
        if isinstance(self.node.object, Ip.Ip):
            self.itinerary_menu = gtk.Menu()

            self.itinerary = gtk.MenuItem("Itinerary")
            self.itinerary.set_submenu(self.itinerary_menu)

            self.itinerary_from = gtk.MenuItem("Itinerary from this place")
            self.itinerary_to = gtk.MenuItem("Itinerary to this place")

            self.itinerary_menu.append(self.itinerary_from)
            self.itinerary_menu.append(self.itinerary_to)

            self.menu.append(self.itinerary)
            self.itinerary_from.connect("activate", self.on_itinerary, 'from')
            self.itinerary_to.connect("activate", self.on_itinerary, 'to')

        # Sensitivity #
        if isinstance(self.node.object, Ip.Ip):
            self.sensitivity_menu = gtk.Menu()

            self.sensitivity = gtk.MenuItem("Sensitivity")
            self.sensitivity.set_submenu(self.sensitivity_menu)

            self.sensitivity_vhigh = gtk.MenuItem("Very high")
            self.sensitivity_high = gtk.MenuItem("High")
            self.sensitivity_normal = gtk.MenuItem("Normal")
            self.sensitivity_low = gtk.MenuItem("Low")
            self.sensitivity_vlow = gtk.MenuItem("Very low")

            self.sensitivity_menu.append(self.sensitivity_vhigh)
            self.sensitivity_menu.append(self.sensitivity_high)
            self.sensitivity_menu.append(self.sensitivity_normal)
            self.sensitivity_menu.append(self.sensitivity_low)
            self.sensitivity_menu.append(self.sensitivity_vlow)

            self.menu.append(self.sensitivity)
            self.sensitivity_vhigh.connect("activate", self.on_sensitivity,
                                           'vhigh')
            self.sensitivity_high.connect("activate", self.on_sensitivity,
                                          'high')
            self.sensitivity_normal.connect("activate", self.on_sensitivity,
                                            'normal')
            self.sensitivity_low.connect("activate", self.on_sensitivity,
                                         'low')
            self.sensitivity_vlow.connect("activate", self.on_sensitivity,
                                          'vlow')

        # Show rules #
        if isinstance(self.node.object, Interface.Interface):

            def get_firewall(x, y):
                if isinstance(x, Firewall.Firewall):
                    return x
                elif isinstance(y, Firewall.Firewall):
                    return y
                return None

            def get_ip(x, y):
                if isinstance(x, Ip.Ip):
                    return x
                elif isinstance(y, Ip.Ip):
                    return y
                return None

            self.acl_menu = gtk.Menu()
            self.acl = gtk.MenuItem("ACL")
            self.acl.set_submenu(self.acl_menu)
            firewall = get_firewall(self.object[0], self.object[1])
            ip = get_ip(self.object[0], self.object[1])
            acl_list = NetworkGraph.NetworkGraph().get_acl_list(
                ip, None, firewall)
            acl_list += NetworkGraph.NetworkGraph().get_acl_list(
                None, ip, firewall)
            for acl in set(acl_list):
                self.tmp_acl = gtk.MenuItem(acl.name)
                self.acl_menu.append(self.tmp_acl)
                self.tmp_acl.connect("activate", self.on_acl, acl)
            self.menu.append(self.acl)

        self.menu.popup(None, None, None, event.button, event.time)
        self.menu.show_all()