Beispiel #1
0
 def generateReportPowerpoint(self):
     """
     Export a calendar defects to a pptx formatted file.
     """
     if self.ent_client.get().strip() == "":
         tk.messagebox.showerror(
             "Missing required field", "The client's name input must be filled.")
         return
     if self.ent_contract.get().strip() == "":
         tk.messagebox.showerror(
             "Missing required field", "The contract's name input must be filled.")
         return
     mongoInstance = MongoCalendar.getInstance()
     toExport = mongoInstance.calendarName
     if toExport != "":
         modele_pptx = str(self.val_ppt.get())
         timestr = datetime.now().strftime("%Y%m%d-%H%M%S")
         basename = self.ent_client.get().strip() + " - "+self.ent_contract.get().strip()
         out_name = str(timestr)+" - "+basename
         dialog = ChildDialogProgress(
             self.parent, "Powerpoint Report", "Creating report "+str(out_name) + ". Please wait.", 200, progress_mode="determinate")
         PowerpointExport.createReport(self.getDefectsAsDict(), modele_pptx, out_name, client=self.ent_client.get(
         ).strip(), contract=self.ent_contract.get().strip(), root=self.parent, progressbar=dialog)
         dialog.destroy()
         tkinter.messagebox.showinfo(
             "Success", "The document was generated in ./exports/"+str(out_name))
Beispiel #2
0
 def loadSummary(self):
     """Reload information about IP and Port and reload the view.
     """
     mongoInstance = MongoCalendar.getInstance()
     nonEmptyIps = list(
         mongoInstance.aggregate("ports", [{
             "$group": {
                 "_id": "$ip"
             }
         }, {
             "$count": "total"
         }]))
     if not nonEmptyIps:
         return
     nonEmptyIps = nonEmptyIps[0]
     step = 0
     dialog = ChildDialogProgress(
         self.parent, "Loading summary ",
         "Refreshing summary. Please wait for a few seconds.", 200,
         "determinate")
     dialog.show(nonEmptyIps["total"])
     nonEmptyIps = mongoInstance.aggregate("ports", [{
         "$group": {
             "_id": "$ip"
         }
     }])
     for ipCIDR in nonEmptyIps:
         step += 1
         ip = Ip.fetchObject({"ip": ipCIDR["_id"]})
         if ip.in_scopes:
             dialog.update(step)
             self.insertIp(ip.ip)
     self.frameTw.update_idletasks()
     self.parent.update_idletasks()
     smart_grid(self.frameTw, self.root, *list(self.treeviews.values()))
     dialog.destroy()
    def displayData(self):
        """
        Display loaded data in treeviews
        """
        dialog = ChildDialogProgress(
            self.parent, "Loading dashboard ",
            "Refreshing dashboard. Please wait for a few seconds.", 200,
            "determinate")
        dialog.show(10)

        # Reset Ip treeview
        for children in self.treevw.get_children():
            self.treevw.delete(children)
        dialog.update(1)
        listOfip = []
        for ip in self.ips:
            servicesCount = len([x for x in Port.fetchObjects({"ip": ip.ip})])
            listOfip.append((ip.ip, servicesCount))
        dialog.update(2)
        listOfip.sort(key=lambda tup: tup[1], reverse=True)
        for i in range(len(listOfip)):
            self.treevw.insert('',
                               'end',
                               i,
                               text=listOfip[i][0],
                               values=(listOfip[i][1]))
        dialog.update(3)
        # Reset Port treeview
        for children in self.treevwport.get_children():
            self.treevwport.delete(children)
        dialog.update(4)
        portCounts = {}
        for port in self.ports:
            if port.port not in portCounts.keys():
                portCounts[port.port] = 1
            else:
                portCounts[port.port] += 1
        dialog.update(5)

        port_id = 0
        # Ordering dictionnary
        portCounts = {
            k: v
            for k, v in sorted(
                portCounts.items(), key=lambda item: item[1], reverse=True)
        }
        for portCount in portCounts:
            self.treevwport.insert('',
                                   'end',
                                   port_id,
                                   text=str(portCount),
                                   values=(portCounts[portCount]))
            port_id += 1
        dialog.update(6)
        # Tool part
        # Reset Tools treeview
        for children in self.treevwtools.get_children():
            self.treevwtools.delete(children)
        dialog.update(7)
        listOfTools = [_ for _ in self.tools]
        listOfTools.sort(key=lambda x: x.status, reverse=True)

        result = MongoCalendar.getInstance().aggregate("tools", [{
            "$group": {
                "_id": {
                    "name": "$name",
                    "status": "$status",
                    "wave": "$wave"
                },
                "count": {
                    "$sum": 1
                }
            }
        }])

        result = [_ for _ in result]
        result.sort(key=lambda x: x["_id"]["name"])
        dialog.update(8)
        tools_dashboard = {}
        for tool in result:
            toolName = tool["_id"]["name"]
            toolWave = tool["_id"]["wave"]
            tools_dashboard[toolWave] = tools_dashboard.get(toolWave, {})
            tools_dashboard[toolWave][toolName] = tools_dashboard[
                toolWave].get(toolName, {})
            toolStatus = "Not ready" if len(
                tool["_id"]["status"]) == 0 else tool["_id"]["status"][0]
            tools_dashboard[toolWave][toolName][
                toolStatus] = tools_dashboard[toolWave][toolName].get(
                    toolStatus, 0) + 1
        for wave in tools_dashboard.keys():
            for toolName in tools_dashboard[wave].keys():
                self.treevwtools.insert(
                    '',
                    'end',
                    None,
                    text=str(toolName),
                    values=(wave, tools_dashboard[wave][toolName].get(
                        "ready",
                        0), tools_dashboard[wave][toolName].get("running", 0),
                            tools_dashboard[wave][toolName].get("done", 0)))
        dialog.update(9)
        # Defect Part
        # reset defect TW
        for children in self.treevwDefaults.get_children():
            self.treevwDefaults.delete(children)

        result = MongoCalendar.getInstance().aggregate("defects", [{
            "$group": {
                "_id": {
                    "risk": "$risk",
                    "type": "$type"
                },
                "count": {
                    "$sum": 1
                }
            }
        }])
        dialog.update(10)
        result = [_ for _ in result]
        result.sort(key=lambda x: x["count"], reverse=True)
        for defect in result:
            defectRisk = defect["_id"]["risk"]
            defectType = " ".join(defect["_id"]["type"])
            defectCount = defect["count"]
            self.treevwDefaults.insert('',
                                       'end',
                                       None,
                                       text=str(defectRisk),
                                       values=(defectType, defectCount))
        dialog.destroy()
    def onOk(self, _event=None):
        """
        Called when the user clicked the validation button.
        launch parsing with selected parser on selected file/directory.
        Close the window.

        Args:
            _event: not used but mandatory
        """
        res, msg = self.form.checkForm()
        if not res:
            tk.messagebox.showwarning("Form not validated",
                                      msg,
                                      parent=self.app)
            return
        notes = None
        tags = None
        form_values = self.form.getValue()
        form_values_as_dicts = ViewElement.list_tuple_to_dict(form_values)
        file_path = form_values_as_dicts["File"]
        plugin = form_values_as_dicts["Plugin"]
        wave = form_values_as_dicts["Wave"]
        files = []
        if os.path.isdir(file_path):
            # r=root, d=directories, f = files
            for r, _d, f in os.walk(file_path):
                for fil in f:
                    files.append(os.path.join(r, fil))
        else:
            files.append(file_path)
        results = {}
        dialog = ChildDialogProgress(
            self.parent, "Importing files", "Importing " + str(len(files)) +
            " files. Please wait for a few seconds.", 200, "determinate")
        dialog.show(len(files))
        # LOOP ON FOLDER FILES
        for f_i, file_path in enumerate(files):
            md5File = md5(file_path)
            toolName = os.path.splitext(
                os.path.basename(file_path))[0] + md5File[:6]
            dialog.update(f_i)
            if plugin == "auto-detect":
                # AUTO DETECT
                foundPlugin = "Ignored"
                for pluginName in listPlugin():
                    if foundPlugin != "Ignored":
                        break
                    mod = loadPlugin(pluginName)
                    if mod.autoDetectEnabled():
                        with io.open(file_path, 'r', encoding="utf-8") as f:
                            notes, tags, lvl, targets = mod.Parse(f)
                            if notes is not None and tags is not None:
                                foundPlugin = pluginName
                results[foundPlugin] = results.get(foundPlugin,
                                                   []) + [file_path]
            else:
                # SET PLUGIN
                mod = loadPlugin(plugin)
                with io.open(file_path, 'r', encoding="utf-8") as f:
                    notes, tags, lvl, targets = mod.Parse(f)
                    results[plugin] = results.get(plugin, []) + [file_path]
            # IF PLUGIN FOUND SOMETHING
            if notes is not None and tags is not None:
                # ADD THE RESULTING TOOL TO AFFECTED
                for target in targets.values():
                    date = datetime.fromtimestamp(os.path.getmtime(
                        file_path)).strftime("%d/%m/%Y %H:%M:%S")
                    if target is None:
                        scope = None
                        ip = None
                        port = None
                        proto = None
                    else:
                        scope = target.get("scope", None)
                        ip = target.get("ip", None)
                        port = target.get("port", None)
                        proto = target.get("proto", None)
                    Wave().initialize(wave, []).addInDb()
                    tool_m = Tool().initialize(toolName,
                                               wave,
                                               scope=scope,
                                               ip=ip,
                                               port=port,
                                               proto=proto,
                                               lvl=lvl,
                                               text="",
                                               dated=date,
                                               datef=date,
                                               scanner_ip="Imported file",
                                               status="done",
                                               notes=notes,
                                               tags=tags)
                    tool_m.addInDb()
                    mongoInstance = MongoCalendar.getInstance()
                    outputRelDir = tool_m.getOutputDir(
                        mongoInstance.calendarName)
                    abs_path = os.path.dirname(os.path.abspath(__file__))
                    outputDir = os.path.join(abs_path, "../../../results",
                                             outputRelDir)
                    mod.centralizeFile(file_path, outputDir)
                    tool_m.update({
                        "resultfile":
                        os.path.join(outputRelDir, os.path.basename(file_path))
                    })

        dialog.destroy()
        # DISPLAY RESULTS
        presResults = ""
        filesIgnored = 0
        for key, value in results.items():
            presResults += str(len(value)) + " " + str(key) + ".\n"
            if key == "Ignored":
                filesIgnored += 1
        if plugin == "auto-detect":
            if filesIgnored > 0:
                tk.messagebox.showwarning("Auto-detect ended",
                                          presResults,
                                          parent=self.app)
            else:
                tk.messagebox.showinfo("Auto-detect ended",
                                       presResults,
                                       parent=self.app)
        else:
            if filesIgnored > 0:
                tk.messagebox.showwarning("Parsing ended",
                                          presResults,
                                          parent=self.app)
            else:
                tk.messagebox.showinfo("Parsing ended",
                                       presResults,
                                       parent=self.app)

        self.rvalue = None
        self.app.destroy()
 def _load(self):
     """
     Load the treeview with database information
     """
     mongoInstance = MongoCalendar.getInstance()
     dialog = ChildDialogProgress(self.appli, "Loading "+str(
         mongoInstance.calendarName), "Opening "+str(mongoInstance.calendarName) + ". Please wait for a few seconds.", 200, "determinate")
     step = 0
     dialog.show(100)
     nbObjects = mongoInstance.find("waves").count()
     nbObjects += mongoInstance.find("scopes").count()
     nbObjects += mongoInstance.find("intervals").count()
     nbObjects += mongoInstance.find("scopes").count()
     nbObjects += mongoInstance.find("ips").count()
     nbObjects += mongoInstance.find("ports").count()
     nbObjects += mongoInstance.find("tools").count()
     onePercentNbObject = nbObjects//100 if nbObjects > 100 else 1
     nbObjectTreated = 0
     for child in self.get_children():
         self.delete(child)
     self._hidden = []
     self._detached = []
     self.waves_node = self.insert("", "end", str(
         "waves"), text="Waves", image=WaveView.getClassIcon())
     # Loading every category separatly is faster than recursivly.
     # This is due to cursor.next function calls in pymongo
     # Adding wave objects
     waves = Wave.fetchObjects({})
     for wave in waves:
         wave_o = WaveController(wave)
         wave_vw = WaveView(self, self.appli.viewframe, self.appli, wave_o)
         wave_vw.addInTreeview(self.waves_node, False)
         nbObjectTreated += 1
         if nbObjectTreated % onePercentNbObject == 0:
             step += 1
             dialog.update(step)
     scopes = Scope.fetchObjects({})
     for scope in scopes:
         scope_o = ScopeController(scope)
         scope_vw = ScopeView(self, self.appli.viewframe, self.appli, scope_o)
         scope_vw.addInTreeview(None, False)
         nbObjectTreated += 1
         if nbObjectTreated % onePercentNbObject == 0:
             step += 1
             dialog.update(step)
     intervals = Interval.fetchObjects({})
     for interval in intervals:
         interval_o = IntervalController(interval)
         interval_vw = IntervalView(self, self.appli.viewframe, self.appli, interval_o)
         interval_vw.addInTreeview(None, False)
         nbObjectTreated += 1
         if nbObjectTreated % onePercentNbObject == 0:
             step += 1
             dialog.update(step)
     # Adding ip objects
     self.ips_node = self.insert("", "end", str(
         "ips"), text="IPs", image=IpView.getClassIcon())
     ips = Ip.fetchObjects({})
     for ip in ips:
         ip_o = IpController(ip)
         ip_vw = IpView(self, self.appli.viewframe, self.appli, ip_o)
         ip_vw.addInTreeview(None, False)
         self.appli.statusbar.notify(ip_vw.controller.getTags())
         nbObjectTreated += 1
         if nbObjectTreated % onePercentNbObject == 0:
             step += 1
             dialog.update(step)
     # Adding port objects
     ports = Port.fetchObjects({})
     for port in ports:
         port_o = PortController(port)
         port_vw = PortView(self, self.appli.viewframe, self.appli, port_o)
         port_vw.addInTreeview(None, False)
         self.appli.statusbar.notify(port_vw.controller.getTags())
         nbObjectTreated += 1
         if nbObjectTreated % onePercentNbObject == 0:
             step += 1
             dialog.update(step)
     # Adding defect objects
     defects = Defect.fetchObjects({"ip":{"$ne":""}})
     for defect in defects:
         defect_o = DefectController(defect)
         defect_vw = DefectView(
             self, self.appli.viewframe, self.appli, defect_o)
         defect_vw.addInTreeview(None)
         nbObjectTreated += 1
         if nbObjectTreated % onePercentNbObject == 0:
             step += 1
             dialog.update(step)
     # Adding tool objects
     tools = Tool.fetchObjects({})
     for tool in tools:
         tool_o = ToolController(tool)
         tool_vw = ToolView(self, self.appli.viewframe, self.appli, tool_o)
         tool_vw.addInTreeview(None, False)
         self.appli.statusbar.notify(tool_vw.controller.getTags())
         nbObjectTreated += 1
         if nbObjectTreated % onePercentNbObject == 0:
             step += 1
             dialog.update(step)
     self.sort(self.ips_node)
     self.appli.statusbar.update()
     dialog.destroy()