예제 #1
0
 def __init__(self, parent, title, err):
     """
     Open a child dialog of a tkinter application to present the user to an unhandled exception.
     Can be used to report issue to github.
     Args:
         parent: the tkinter parent view to use for this window construction.
         title: A title for the new windows
         err: the error that occured causing this window to appear
     """
     self.rvalue = None
     self.parent = parent
     self.app = tk.Toplevel(parent)
     self.app.title(title)
     appFrame = ttk.Frame(self.app)
     self.form = FormPanel()
     self.err = err
     self.form.addFormLabel(
         "An error occured. Please make an issue with the below stack trace and when it occured.",
         side=tk.TOP)
     self.form.addFormText("Error", ".+", self.err, None, side=tk.TOP)
     self.form.addFormButton("Report bug", self.onOk, side=tk.RIGHT)
     self.form.addFormButton("Close", self.onError, side=tk.RIGHT)
     self.rvalue = None
     self.form.constructView(appFrame)
     appFrame.pack(ipadx=10, ipady=10)
     self.app.transient(parent)
     try:
         self.app.wait_visibility()
         self.app.grab_set()
     except tk.TclError:
         pass
예제 #2
0
class ChildDialogException:
    """
    Open a child dialog of a tkinter application to present the user to an unhandled exception.
    Can be used to report issue to github.
    """
    def __init__(self, parent, title, err):
        """
        Open a child dialog of a tkinter application to present the user to an unhandled exception.
        Can be used to report issue to github.
        Args:
            parent: the tkinter parent view to use for this window construction.
            title: A title for the new windows
            err: the error that occured causing this window to appear
        """
        self.rvalue = None
        self.parent = parent
        self.app = tk.Toplevel(parent)
        self.app.title(title)
        appFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        self.err = err
        self.form.addFormLabel(
            "An error occured. Please make an issue with the below stack trace and when it occured.",
            side=tk.TOP)
        self.form.addFormText("Error", ".+", self.err, None, side=tk.TOP)
        self.form.addFormButton("Report bug", self.onOk, side=tk.RIGHT)
        self.form.addFormButton("Close", self.onError, side=tk.RIGHT)
        self.rvalue = None
        self.form.constructView(appFrame)
        appFrame.pack(ipadx=10, ipady=10)
        self.app.transient(parent)
        try:
            self.app.wait_visibility()
            self.app.grab_set()
        except tk.TclError:
            pass

    def onOk(self, _event=None):
        """
        Called when the user clicked the validation button. Set the rvalue attributes to the value selected and close the window.
        
        Args:
            _event: not used but mandatory
        """
        # send the data to the parent
        postIssue(self.err)

    def onError(self, _event=None):
        """
        Close the dialog and set rvalue to None
        Args:
            _event: not used but mandatory
        """
        self.rvalue = False
        self.app.destroy()
예제 #3
0
 def __init__(self, appTw, appViewFrame, mainApp, controller):
     """Constructor
     Args:
         appTw: a PollenisatorTreeview instance to put this view in
         appViewFrame: an view frame to build the forms in.
         mainApp: the Application instance
         controller: a CommandController for this view.
     """
     self.appliTw = appTw
     self.appliViewFrame = appViewFrame
     self.mainApp = mainApp
     self.controller = controller
     self.form = FormPanel()
예제 #4
0
    def __init__(self, parent, default):
        """
        Open a child dialog of a tkinter application to ask details about
        the new pentest.

        Args:
            parent: the tkinter parent view to use for this window construction.
        """
        self.app = tk.Toplevel(parent)
        self.app.resizable(False, False)
        self.rvalue = None
        self.parent = parent
        mainFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        form1 = self.form.addFormPanel(grid=True, side=tk.TOP, fill=tk.X)
        form1.addFormLabel("Database name")
        form1.addFormStr("Database name", r"^\S+$", default=default.get("name", ""), width=50, column=1)
        types = list(Settings.getPentestTypes().keys())
        if types:
            form1.addFormLabel("Pentest type", row=1)
            form1.addFormCombo(
                "Pentest type", types, default=default.get("type", types[0]), row=1, column=1)
        form1.addFormLabel("Starting", row=2)
        form1.addFormDate("startd", parent, default.get("start", datetime.strftime(datetime.now(), "%d/%m/%Y %H:%M:%S")), "%d/%m/%Y %H:%M:%S", row=2, column=1)
        form1.addFormLabel("Ending", row=3)
        form1.addFormDate("endd", parent, default.get("end", "31/12/2099 00:00:00"),
                          "%d/%m/%Y %H:%M:%S", row=3, column=1)
        form2 = self.form.addFormPanel(grid=True, side=tk.TOP, fill=tk.X, pady=5)
        form2.addFormLabel("Scope", pady=5)
        form2.addFormText(
            "Scope", "", default.get("scope", ""), height=5, column=1, sticky=tk.E, pady=5)
        form2.addFormHelper(
            "You can declare network ip as IP/MASKSIZE, ips or domains", column=2, sticky=tk.W)
        form2.addFormLabel("Pentester names", row=1, sticky=tk.E)
        form2.addFormText(
            "Pentester names", "", default.get("pentesters", ""),  row=1, column=1, sticky=tk.W, height=3, pady=5)
        form3 = self.form.addFormPanel(side=tk.TOP, fill=tk.X, pady=5)
        default_settings = []
        for key, val in default.get("settings", {}).items():
            if val == 1:
                default_settings.append(key)
        form3.addFormChecklist("Settings", ["Add domains whose IP are in scope",
                                            "Add domains who have a parent domain in scope", "Add all domains found"], default_settings, side=tk.TOP, fill=tk.X, pady=5)
        form3.addFormButton("Create", self.onOk, side=tk.BOTTOM)
        self.form.constructView(mainFrame)
        self.form.setFocusOn("Database name")
        mainFrame.pack(fill=tk.BOTH, ipadx=10, ipady=10)
        self.app.transient(parent)
        self.app.wait_visibility()
        self.app.grab_set()
예제 #5
0
    def __init__(self, parent):
        """
        Open a child dialog of a tkinter application to ask details about
        existing files parsing.

        Args:
            parent: the tkinter parent view to use for this window construction.
        """
        self.app = tk.Toplevel(parent)
        self.app.title("Upload result file")
        self.rvalue = None
        self.parent = parent
        appFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        self.form.addFormLabel("Import one file or choose a directory",
                               "",
                               side=tk.TOP)
        self.form.addFormFile("File",
                              ".+",
                              width=50,
                              side=tk.TOP,
                              mode="file|directory")
        self.form.addFormLabel("Plugins", side=tk.TOP)
        self.form.addFormCombo("Plugin", ["auto-detect"] + listPlugin(),
                               "auto-detect",
                               side=tk.TOP)
        self.form.addFormLabel("Wave name", side=tk.TOP)
        wave_list = Wave.listWaves()
        if "Imported files" not in wave_list:
            wave_list.append("Imported files")
        self.form.addFormCombo("Wave",
                               wave_list,
                               "Imported files",
                               side=tk.TOP)
        self.form.addFormButton("Parse", self.onOk, side=tk.TOP)

        self.form.constructView(appFrame)
        appFrame.pack(ipadx=10, ipady=10)

        self.app.transient(parent)
        self.app.grab_set()
    def __init__(self, parent, keys):
        """
        Open a child dialog of a tkinter application to ask details about
        an export of treeview items.

        Args:
            parent: the tkinter parent view to use for this window construction.
            keys: The keys to export
        """
        self.rvalue = None
        self.parent = parent
        self.app = tk.Toplevel(parent)
        self.app.title("Export selection")
        appFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        self.form.addFormChecklist("Fields", sorted(keys), [])
        self.form.addFormButton("Export", self.onOk)
        self.rvalue = None
        self.form.constructView(appFrame)
        appFrame.pack(ipadx=10, ipady=10)
        self.app.transient(parent)
        self.app.wait_visibility()
        self.app.grab_set()
예제 #7
0
    def __init__(self,
                 parent,
                 displayMsg="Choose a database to open:",
                 default=None):
        """
        Open a child dialog of a tkinter application to ask a combobox option.

        Args:
            parent: the tkinter parent view to use for this window construction.
            options: A list of string correspondig to options of the combobox
            displayMsg: The message that will explain to the user what he is choosing.
            default: Choose a default selected option (one of the string in options). default is None
        """
        self.app = tk.Toplevel(parent)
        self.app.title("Upload result file")
        self.rvalue = None
        self.parent = parent
        appFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        self.form.addFormLabel(displayMsg, side=tk.TOP)
        optionsFrame = self.form.addFormPanel(grid=True)
        optionsFrame.addFormLabel("Remote bin path", row=0, column=0)
        optionsFrame.addFormStr("bin", r".+", row=0, column=1)
        optionsFrame.addFormLabel("Plugin", row=1, column=0)
        optionsFrame.addFormCombo("plugin",
                                  tuple(listPlugin()),
                                  row=1,
                                  column=1)
        self.form.addFormButton("Cancel", self.onError)
        self.form.addFormButton("OK", self.onOk)
        self.form.constructView(appFrame)
        appFrame.pack(ipadx=10, ipady=10)
        self.app.transient(parent)
        try:
            self.app.grab_set()
        except tk.TclError:
            pass
class ChildDialogExportSelection:
    """
    Open a child dialog of a tkinter application to ask the user to select fields between many.
    """
    def __init__(self, parent, keys):
        """
        Open a child dialog of a tkinter application to ask details about
        an export of treeview items.

        Args:
            parent: the tkinter parent view to use for this window construction.
            keys: The keys to export
        """
        self.rvalue = None
        self.parent = parent
        self.app = tk.Toplevel(parent)
        self.app.title("Export selection")
        appFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        self.form.addFormChecklist("Fields", sorted(keys), [])
        self.form.addFormButton("Export", self.onOk)
        self.rvalue = None
        self.form.constructView(appFrame)
        appFrame.pack(ipadx=10, ipady=10)
        self.app.transient(parent)
        self.app.wait_visibility()
        self.app.grab_set()

    def onOk(self, _event=None):
        """Called the the Export button is pressed.
        return a list of strings corresponding to the selected fields.
        
        Args:
            _event: not used but mandatory"""
        res, msg = self.form.checkForm()
        if res:
            form_values = self.form.getValue()
            form_values_as_dicts = ViewElement.list_tuple_to_dict(form_values)
            mfields = form_values_as_dicts["Fields"]
            fields = [k for k, v in mfields.items() if v == 1]
            self.rvalue = fields
            self.app.destroy()
        else:
            tk.messagebox.showwarning("Form not validated",
                                      msg,
                                      parent=self.app)
예제 #9
0
class ChildDialogEditCommandSettings:
    """
    Open a child dialog of a tkinter application to fill settings for a command
    """
    def __init__(self,
                 parent,
                 displayMsg="Choose a database to open:",
                 default=None):
        """
        Open a child dialog of a tkinter application to ask a combobox option.

        Args:
            parent: the tkinter parent view to use for this window construction.
            options: A list of string correspondig to options of the combobox
            displayMsg: The message that will explain to the user what he is choosing.
            default: Choose a default selected option (one of the string in options). default is None
        """
        self.app = tk.Toplevel(parent)
        self.app.title("Upload result file")
        self.rvalue = None
        self.parent = parent
        appFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        self.form.addFormLabel(displayMsg, side=tk.TOP)
        optionsFrame = self.form.addFormPanel(grid=True)
        optionsFrame.addFormLabel("Remote bin path", row=0, column=0)
        optionsFrame.addFormStr("bin", r".+", row=0, column=1)
        optionsFrame.addFormLabel("Plugin", row=1, column=0)
        optionsFrame.addFormCombo("plugin",
                                  tuple(listPlugin()),
                                  row=1,
                                  column=1)
        self.form.addFormButton("Cancel", self.onError)
        self.form.addFormButton("OK", self.onOk)
        self.form.constructView(appFrame)
        appFrame.pack(ipadx=10, ipady=10)
        self.app.transient(parent)
        try:
            self.app.grab_set()
        except tk.TclError:
            pass

    def onOk(self, _event):
        """
        Called when the user clicked the validation button. Set the rvalue attributes to the value selected and close the window.
        """
        # send the data to the parent
        res, msg = self.form.checkForm()
        if not res:
            tk.messagebox.showwarning("Form not validated",
                                      msg,
                                      parent=self.app)
            return
        form_values = self.form.getValue()
        form_values_as_dicts = ViewElement.list_tuple_to_dict(form_values)
        self.rvalue = (form_values_as_dicts["bin"],
                       form_values_as_dicts["plugin"])
        self.app.destroy()

    def onError(self, _event=None):
        """
        Close the dialog and set rvalue to None
        """
        self.rvalue = None
        self.app.destroy()
예제 #10
0
class ViewElement(object):
    """
    Defines a basic view to be inherited. Those functions are generic entry points to models.
    Most of them should not be redefined in other Views.
    Attributes:
        icon: icon name to show in treeview. Icon filename must be in icon directory
        cachedClassIcon: a cached loaded PIL image icon of ViewElement.icon. Starts as None.
    """
    icon = 'undefined.png'
    cachedClassIcon = None

    def __init__(self, appTw, appViewFrame, mainApp, controller):
        """Constructor
        Args:
            appTw: a PollenisatorTreeview instance to put this view in
            appViewFrame: an view frame to build the forms in.
            mainApp: the Application instance
            controller: a CommandController for this view.
        """
        self.appliTw = appTw
        self.appliViewFrame = appViewFrame
        self.mainApp = mainApp
        self.controller = controller
        self.form = FormPanel()

    @classmethod
    def getClassIcon(cls):
        """
        Load the class icon in cache if it is not yet done, and returns it

        Return:
            Returns the ImageTk.PhotoImage icon representing this class .
        """
        from PIL import Image, ImageTk
        if cls.cachedClassIcon == None:
            abs_path = os.path.dirname(os.path.abspath(__file__))
            path = os.path.join(abs_path, "../../icon/"+cls.icon)
            cls.cachedClassIcon = ImageTk.PhotoImage(Image.open(path))
        return cls.cachedClassIcon

    def getIcon(self):
        """
        Load the object icon in cache if it is not yet done, and returns it

        Return:
            Returns the icon representing this object.
        """
        return self.__class__.getClassIcon()

    def addChildrenBaseNodes(self, newNode):
        """
        Add to the given node from a treeview the mandatory childrens.
        Will be redefined in children.

        Args:
            newNode: the newly created node we want to add children to.
        """
        # pass

    def delete(self, _event=None, showWarning=True):
        """
        Entry point to the model doDelete function.

        Args:
            _event: automatically filled if called by an event. Not used
            showWarning: a boolean. If true, the user will be asked a confirmation before supression. Default to True.
        """
        ret = True
        if showWarning:
            ret = tkinter.messagebox.askokcancel(
                "Delete", "You are going to delete this element, do you want to continue?")
        if(ret):
            self.controller.doDelete()

    def update(self, event=None):
        """
        Entry point to the model doUpdate function.

        Args:
            event: automatically filled if called by an event. Holds info on update clicked widget.
        Returns:
            * a boolean to shwo success or failure
            * an empty message on success, an error message on failure
        """
        res, msg = self.form.checkForm()
        if(res):
            form_values = self.form.getValue()
            form_values_as_dicts = ViewElement.list_tuple_to_dict(form_values)
            self.controller.doUpdate(form_values_as_dicts)
            if event is not None:
                caller = event.widget
                toast = ChildDialogToast(self.appliViewFrame, "Done" , x=caller.winfo_rootx(), y=caller.winfo_rooty()+caller.winfo_reqheight(), width=caller.winfo_reqwidth())
                toast.show()
            return True, ""
        else:
            tkinter.messagebox.showwarning(
                "Form not validated", msg, parent=self.appliViewFrame)
            return False, msg

    def insert(self, _event=None):
        """
        Entry point to the model doInsert function.

        Args:
            _event: automatically filled if called by an event. Not used
        Returns:
            * a boolean to shwo success or failure
            * an empty message on success, an error message on failure
        """
        res, msg = self.form.checkForm()
        if(res):
            form_values = self.form.getValue()
            form_values_as_dicts = ViewElement.list_tuple_to_dict(form_values)
            res, nbErrors = self.controller.doInsert(form_values_as_dicts)
            if not res:
                msg = "This element cannot be inserted, check for conflicts with existings elements."
                tkinter.messagebox.showerror(
                    "Insertion failed", msg, parent=self.appliViewFrame)
                return False, msg
            else:
                if nbErrors > 0:
                    msg = str(len(
                        res))+" were inserted, "+str(nbErrors)+" were not to avoid conflicts or out of wave elements."
                    tkinter.messagebox.showwarning(
                        "Insertion succeeded with warnings", msg, parent=self.appliViewFrame)
                    return True, msg
                else:
                    return True, ""
        else:
            tkinter.messagebox.showwarning(
                "Form not validated", msg, parent=self.appliViewFrame)
            return False, msg

    def tagClicked(self, name):
        """Callback intermediate for tag clicked
        Ensure that the tag name clicked is added to View item
        Args:
            name: a tag name
        """
        return lambda _event: self.tagButtonClicked(name)
    
    def tagButtonClicked(self, name):
        """Callback for tag button clicked
        Ensure that the tag name clicked is set to View item
        Args:
            name: a tag name
        """
        self.controller.setTags([name])

    def completeModifyWindow(self):
        """
        Add the buttons for an update window.
            -Submit button that validates the form with the update function.
            -Delete button that asks the user to delete the object with the delete function.
        """
        pan = self.form.addFormPanel()
        pan.addFormButton("Submit", self.update)
        pan.addFormButton("Delete", self.delete)
        
        registeredTags = Settings.getTags()
        keys = list(registeredTags.keys())
        column = 0
        item_no = 0
        listOfLambdas = [self.tagClicked(keys[i]) for i in range(len(keys))]
        for registeredTag, color in registeredTags.items():
            if not hasattr(self.mainApp, "parent"):
                break
            if column == 0:
                panTags = self.form.addFormPanel(pady=0)
            s = ttk.Style(self.mainApp.parent)
            s.configure(""+color+".TButton", background=color, foreground="black")
            s.map(""+color+".TButton", foreground=[('active', "dark gray")], background=[('active', color)])
            btn_tag = panTags.addFormButton(registeredTag, listOfLambdas[item_no], side="left", padx=0, pady=0)
            btn_tag.configure(style=""+color+".TButton")
            column += 1
            item_no += 1
            if column == 4:
                column = 0
        self.showForm()

    def showForm(self):
        """Resets the application view frame and start displaying the form in it
        """
        for widget in self.appliViewFrame.winfo_children():
            widget.destroy()
        self.form.constructView(self.appliViewFrame)

    def completeInsertWindow(self):
        """
        Add the button for an insert window.
            -Insert button that validate the form with the insert function.
        """
        pan = self.form.addFormPanel()
        pan.addFormButton("Insert", self.insert)
        for widget in self.appliViewFrame.winfo_children():
            widget.destroy()
        self.form.constructView(self.appliViewFrame)

    def hide(self):
        """Tells the application treeview to hide this node
        """
        self.appliTw.hide(str(self.controller.getDbId()))

    def unhide(self):
        """Tells the application treeview to unhide this node
        """
        self.appliTw.unhide(self)

    def __str__(self):
        """
        Return the __str__ method of the model
        """
        return str(self.controller.getModelRepr())

    @classmethod
    def DbToTreeviewListId(cls, parent_db_id):
        """Converts a mongo Id to a unique string identifying a list of view elemnt given its parent
        Args:
            parent_db_id: the parent node mongo ID
        Returns:
            A string that should be unique to describe the parent list of viewelement node
        """
        return str(parent_db_id)

    def getParent(self):
        """
        Return the id of the parent node in treeview.

        Returns:
            return the model parent id DbToTreeviewListId
        """
        return self.__class__.DbToTreeviewListId(self.controller.getParent())

    def updateReceived(self):
        """Called when any view element update is received by notification.
        Resets the node tags according to database and hide it if "hidden" is in tags
        """
        if self.controller.getDbId() is None:
            return
        tags = self.controller.getTags()
        try:
            self.appliTw.item(str(self.controller.getDbId()), tags=tags)
        except TclError:
            pass
        if "hidden" in tags:
            self.hide()

    def insertReceived(self):
        """Called when any view element insert is received by notificaiton
        To be overriden
        """
        pass

    def key(self):
        """Returns a key for sorting this node
        Returns:
            string, basic key: string so alphanumerical sorting will be used
        """
        return str(self.controller.getModelRepr())

    @classmethod
    def list_tuple_to_dict(cls, list_of_tuple):
        """Transforms a list of 2-tuple to a dictionnary
        Args:
            list_of_tuple: a 2-tuple with (key, value)
        Returns:
            A dictionnary with all key-values pair inserted
        """
        ret = dict()
        for key, value in list_of_tuple:
            ret[key] = value
        return ret
예제 #11
0
class ChildDialogFileParser:
    """
    Open a child dialog of a tkinter application to ask details about
    existing files parsing.
    """
    def __init__(self, parent):
        """
        Open a child dialog of a tkinter application to ask details about
        existing files parsing.

        Args:
            parent: the tkinter parent view to use for this window construction.
        """
        self.app = tk.Toplevel(parent)
        self.app.title("Upload result file")
        self.rvalue = None
        self.parent = parent
        appFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        self.form.addFormLabel("Import one file or choose a directory",
                               "",
                               side=tk.TOP)
        self.form.addFormFile("File",
                              ".+",
                              width=50,
                              side=tk.TOP,
                              mode="file|directory")
        self.form.addFormLabel("Plugins", side=tk.TOP)
        self.form.addFormCombo("Plugin", ["auto-detect"] + listPlugin(),
                               "auto-detect",
                               side=tk.TOP)
        self.form.addFormLabel("Wave name", side=tk.TOP)
        wave_list = Wave.listWaves()
        if "Imported files" not in wave_list:
            wave_list.append("Imported files")
        self.form.addFormCombo("Wave",
                               wave_list,
                               "Imported files",
                               side=tk.TOP)
        self.form.addFormButton("Parse", self.onOk, side=tk.TOP)

        self.form.constructView(appFrame)
        appFrame.pack(ipadx=10, ipady=10)

        self.app.transient(parent)
        self.app.grab_set()

    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()
예제 #12
0
class ChildDialogNewCalendar:
    """
    Open a child dialog of a tkinter application to ask details about
    a new pentest database to create.
    """

    def __init__(self, parent, default):
        """
        Open a child dialog of a tkinter application to ask details about
        the new pentest.

        Args:
            parent: the tkinter parent view to use for this window construction.
        """
        self.app = tk.Toplevel(parent)
        self.app.resizable(False, False)
        self.rvalue = None
        self.parent = parent
        mainFrame = ttk.Frame(self.app)
        self.form = FormPanel()
        form1 = self.form.addFormPanel(grid=True, side=tk.TOP, fill=tk.X)
        form1.addFormLabel("Database name")
        form1.addFormStr("Database name", r"^\S+$", default=default.get("name", ""), width=50, column=1)
        types = list(Settings.getPentestTypes().keys())
        if types:
            form1.addFormLabel("Pentest type", row=1)
            form1.addFormCombo(
                "Pentest type", types, default=default.get("type", types[0]), row=1, column=1)
        form1.addFormLabel("Starting", row=2)
        form1.addFormDate("startd", parent, default.get("start", datetime.strftime(datetime.now(), "%d/%m/%Y %H:%M:%S")), "%d/%m/%Y %H:%M:%S", row=2, column=1)
        form1.addFormLabel("Ending", row=3)
        form1.addFormDate("endd", parent, default.get("end", "31/12/2099 00:00:00"),
                          "%d/%m/%Y %H:%M:%S", row=3, column=1)
        form2 = self.form.addFormPanel(grid=True, side=tk.TOP, fill=tk.X, pady=5)
        form2.addFormLabel("Scope", pady=5)
        form2.addFormText(
            "Scope", "", default.get("scope", ""), height=5, column=1, sticky=tk.E, pady=5)
        form2.addFormHelper(
            "You can declare network ip as IP/MASKSIZE, ips or domains", column=2, sticky=tk.W)
        form2.addFormLabel("Pentester names", row=1, sticky=tk.E)
        form2.addFormText(
            "Pentester names", "", default.get("pentesters", ""),  row=1, column=1, sticky=tk.W, height=3, pady=5)
        form3 = self.form.addFormPanel(side=tk.TOP, fill=tk.X, pady=5)
        default_settings = []
        for key, val in default.get("settings", {}).items():
            if val == 1:
                default_settings.append(key)
        form3.addFormChecklist("Settings", ["Add domains whose IP are in scope",
                                            "Add domains who have a parent domain in scope", "Add all domains found"], default_settings, side=tk.TOP, fill=tk.X, pady=5)
        form3.addFormButton("Create", self.onOk, side=tk.BOTTOM)
        self.form.constructView(mainFrame)
        self.form.setFocusOn("Database name")
        mainFrame.pack(fill=tk.BOTH, ipadx=10, ipady=10)
        self.app.transient(parent)
        self.app.wait_visibility()
        self.app.grab_set()

    def onOk(self, _event):
        """
        Called when the user clicked the validation button. Set the rvalue attributes to the value selected and close the window.
        
        Args:
            _event: not used but mandatory
        """
        # send the data to the parent
        res, msg = self.form.checkForm()
        if res:
            form_values = self.form.getValue()
            form_values_as_dicts = ViewElement.list_tuple_to_dict(form_values)
            self.rvalue = {"name": form_values_as_dicts["Database name"],
                           "type": form_values_as_dicts.get("Pentest type", ""),
                           "start": form_values_as_dicts["startd"],
                           "end": form_values_as_dicts["endd"],
                           "settings": form_values_as_dicts["Settings"],
                           "scope": form_values_as_dicts["Scope"],
                           "pentesters": form_values_as_dicts["Pentester names"]}
            self.app.destroy()
        else:
            tk.messagebox.showwarning(
                "Form not validated", msg, parent=self.app)