def applyButton_clicked_cb(self, widget):
        """Callback executed when the user clicks on the apply button"""
        workspacePath = self.getSelectedWorkspace()
        # We verify the workspace can be loaded.
        # if it can, we stop the current GTK
        if workspacePath is None or len(workspacePath) == 0:
            self.setError(_("No workspace provided."))
        else:
            logging.debug("Create the requested workspace")
            try:
                ResourcesConfiguration.createWorkspace(workspacePath)
            except OSError as e:
                self.log.warning("Impossible to create a workspace : {0}".format(e))
                self.setError("Impossible to create a workspace here.")

                return

            (workspace, error) = (Workspace.loadWorkspace(self._selectedWorkspace))
            if workspace is not None:
                # If we managed to load the given workspace, we save it and stop the GTK
                ResourcesConfiguration.generateUserFile(self._selectedWorkspace)
                self.loadedWorkspace = workspace
                self.stop()
            else:
                self.setError(error)
Example #2
0
    def retrieveMessagesFromFiles(self):
        # We read each file and create one message for each file
        self.messages = []
        self.lineView.get_model().clear()

        for file in self.filesToBeImported:

            from netzob.Common.ResourcesConfiguration import ResourcesConfiguration
            xmlSchemaPath = os.path.join(ResourcesConfiguration.getStaticResources(), "xsds/0.1/common.xsd")
            # If we find a version which validates the XML, we parse with the associated function
            if not Workspace.isSchemaValidateXML(xmlSchemaPath, file):
                logging.error(_("The specified XML file {0} is not valid according to the XSD ({1}).").format(str(file), str(xmlSchemaPath)))
            else:
                logging.debug(_("XML file valid according to the XSD schema"))

                # Parse the XML Document as 0.1 version
                tree = ElementTree()
                tree.parse(file)
                xmlFile = tree.getroot()

                for xmlMessage in xmlFile.findall("{" + Project.COMMON_NAMESPACE + "}message"):
                    message = AbstractMessageFactory.loadFromXML(xmlMessage, Project.COMMON_NAMESPACE, "0.1")
                    logging.debug(_("XML String data: {0}").format(message.getStringData()))
                    self.messages.append(message)
                    self.lineView.get_model().append(None, [str(message.getID()), message.getType(), message.getStringData()])
    def applyButton_clicked_cb(self, widget):
        """Callback executed when the user clicks on the apply button"""
        workspacePath = self.getSelectedWorkspace()
        # We verify the workspace can be loaded.
        # if it can, we stop the current GTK
        if workspacePath is None or len(workspacePath) == 0:
            self.setError(_("No workspace provided."))
        else:
            logging.debug("Create the requested workspace")
            try:
                ResourcesConfiguration.createWorkspace(workspacePath)
            except OSError as e:
                self.log.warning(
                    "Impossible to create a workspace : {0}".format(e))
                self.setError("Impossible to create a workspace here.")

                return

            (workspace,
             error) = (Workspace.loadWorkspace(self._selectedWorkspace))
            if workspace is not None:
                # If we managed to load the given workspace, we save it and stop the GTK
                ResourcesConfiguration.generateUserFile(
                    self._selectedWorkspace)
                self.loadedWorkspace = workspace
                self.stop()
            else:
                self.setError(error)
Example #4
0
 def createWorkspace(path):
     logging.info("Hosting workspace on " + str(path))
     # we do nothing if a global config file already exists
     if os.path.isfile(os.path.join(path, Workspace.CONFIGURATION_FILENAME)):
         return
     else:
         workspace = Workspace.createWorkspace(_("New Workspace"), path)
         return workspace
 def createWorkspace(path):
     logging.info("Hosting workspace on " + str(path))
     # we do nothing if a global config file already exists
     if os.path.isfile(os.path.join(path,
                                    Workspace.CONFIGURATION_FILENAME)):
         return
     else:
         workspace = Workspace.createWorkspace(_("New Workspace"), path)
         return workspace
Example #6
0
 def test_workspaceParsing(self):
     
     # We first load the workspace
     workspace = Workspace.loadWorkspace(ResourcesConfiguration.getWorkspaceFile())
     self.assertNotEqual(workspace, None)
     
     
     
     # Now we load all the project which are declared in
     for project_path in workspace.getProjectsPath() :
         project = Project.loadProject(workspace, project_path)
         if project != None :
             logging.info("The project " + project.getName() + " has been loaded !")        
Example #7
0
    def _readMessagesFromFile(self, filePath):
        from netzob.Common.ResourcesConfiguration import ResourcesConfiguration
        xmlSchemaPath = os.path.join(ResourcesConfiguration.getStaticResources(), "xsds/0.1/common.xsd")
        # If we find a version which validates the XML, we parse with the associated function
        if not Workspace.isSchemaValidateXML(xmlSchemaPath, filePath):
            logging.error("The specified XML file {0} is not valid "
                          "according to the XSD ({1}).".format(filePath, xmlSchemaPath))
        else:
            logging.debug("XML file valid according to the XSD schema")

            # Parse the XML Document as 0.1 version
            tree = ElementTree()
            tree.parse(filePath)
            xmlFile = tree.getroot()

            for xmlMessage in xmlFile.findall("{" + Project.COMMON_NAMESPACE + "}message"):
                message = AbstractMessageFactory.loadFromXML(xmlMessage, Project.COMMON_NAMESPACE, "0.1")
                logging.debug("XML String data: " + message.getStringData())
                self.messages.append(message)
    def getWorkspace(self, workspaceDir):
        """Request and load the specified workspace
        by user either through the dedicated interface
        either through the user config file.

        This method returns None if no workspace
        has been retrieved or the loaded workspace."""
        logging.debug("+ Load workspace...")

        self._selectedWorkspace = workspaceDir

        # Loading the workspace
        if workspaceDir is not None:
            (self.loadedWorkspace, error) = (Workspace.loadWorkspace(workspaceDir))
            if error is not None:
                self.setError(error)

        if self.loadedWorkspace is None:
            self.run()

        return self.loadedWorkspace
    def getWorkspace(self, workspaceDir):
        """Request and load the specified workspace
        by user either through the dedicated interface
        either through the user config file.

        This method returns None if no workspace
        has been retrieved or the loaded workspace."""
        logging.debug("+ Load workspace...")

        self._selectedWorkspace = workspaceDir

        # Loading the workspace
        if workspaceDir is not None:
            (self.loadedWorkspace,
             error) = (Workspace.loadWorkspace(workspaceDir))
            if error is not None:
                self.setError(error)

        if self.loadedWorkspace is None:
            self.run()

        return self.loadedWorkspace
Example #10
0
    def retrieveMessagesFromFiles(self):
        # We read each file and create one message for each file
        self.messages = []
        self.lineView.get_model().clear()

        for file in self.filesToBeImported:

            from netzob.Common.ResourcesConfiguration import ResourcesConfiguration
            xmlSchemaPath = os.path.join(
                ResourcesConfiguration.getStaticResources(),
                "xsds/0.1/common.xsd")
            # If we find a version which validates the XML, we parse with the associated function
            if not Workspace.isSchemaValidateXML(xmlSchemaPath, file):
                logging.error(
                    "The specified XML file {0} is not valid according to the XSD ({1})."
                    .format(str(file), str(xmlSchemaPath)))
            else:
                logging.debug("XML file valid according to the XSD schema")

                # Parse the XML Document as 0.1 version
                tree = ElementTree()
                tree.parse(file)
                xmlFile = tree.getroot()

                for xmlMessage in xmlFile.findall("{" +
                                                  Project.COMMON_NAMESPACE +
                                                  "}message"):
                    message = AbstractMessageFactory.loadFromXML(
                        xmlMessage, Project.COMMON_NAMESPACE, "0.1")
                    logging.debug("XML String data: {0}".format(
                        message.getStringData()))
                    self.messages.append(message)
                    self.lineView.get_model().append(None, [
                        str(message.getID()),
                        message.getType(),
                        message.getStringData()
                    ])
Example #11
0
 def getWorkspace(self):
     return Workspace.loadWorkspace(NetzobResources.WORKSPACE_DIR)
Example #12
0
    def switchWorkspace_activate_cb(self, action):
        """Callback executed when the user requests to switch to
        another workspace"""

        finish = False
        errorMessage = None
        while not finish:
            #open dialogbox
            builder2 = Gtk.Builder()
            builder2.add_from_file(os.path.join(
                ResourcesConfiguration.getStaticResources(),
                "ui",
                "dialogbox.glade"))

            dialog = builder2.get_object("switchWorkspace")
            dialog.set_transient_for(self.view.mainWindow)

            applybutton = builder2.get_object("switchWorkspaceApplyButton")
            fileChooserButton = builder2.get_object("switchWorkspaceFileChooserButton")
            fileChooserButton.connect("current-folder-changed", self.fileSetFileChooser_switchWorkspace_cb, applybutton)

            if errorMessage is not None:
                # Display a warning message on the dialog box
                warnLabel = builder2.get_object("switchWorkspaceWarnLabel")
                warnLabel.set_text(errorMessage)
                warnBox = builder2.get_object("switchWorkspaceWarnBox")
                warnBox.show_all()

            result = dialog.run()

            if result == 0:
                selectedFolder = fileChooserButton.get_current_folder()
                dialog.destroy()

                if selectedFolder is None:
                    errorMessage = _("No directory selected")
                else:
                    # we verify if its an empty directory
                    if len(os.listdir(selectedFolder)) > 0:
                        # is a valid workspace directory
                        errorMessage = Workspace.isFolderAValidWorkspace(selectedFolder)
                        if errorMessage is None:
                            try:
                                (self.currentWorkspace, error) = (Workspace.loadWorkspace(selectedFolder))
                                self.currentProject = self.currentWorkspace.getLastProject()
                                finish = True
                                errorMessage = None
                                self.view.currentWorkspaceHasChanged()
                            except Exception, e:
                                errorMessage = _("An error occurred while loading workspace.")
                                logging.warn("Error while loading workspace declared in folder {0}: {1}".format(selectedFolder, e))
                    else:
                        # create a new workspace
                        try:
                            self.currentWorkspace = ResourcesConfiguration.createWorkspace(selectedFolder)
                            finish = True
                            errorMessage = None
                            self.view.currentWorkspaceHasChanged()
                        except Exception, e:
                            errorMessage = _("An error occurred while creating workspace.")
                            logging.warn("Error while creating workspace declared in folder {0}: {1}".format(selectedFolder, e))
Example #13
0
    def __init__(self):

        # Command line commands
        parser = CommandLine.get_parser()
        opts, args = parser.parse_args()

        gettext.bindtextdomain("netzob", ResourcesConfiguration.getLocaleLocation())
        gettext.textdomain("netzob")

        try:
            locale.getlocale()
        except:
            logging.exception("setlocale failed, resetting to C")
            locale.setlocale(locale.LC_ALL, "C")

        (status, version) = DepCheck.test_lxml()
        if status == False:
            logging.fatal("Version of python-lxml ({0}) is too old for Netzob. Please install a recent version (>= 2.3)".format(version))
            sys.exit()

        # First we initialize and verify all the resources
        if not ResourcesConfiguration.initializeResources():
            logging.fatal("Error while configuring the resources of Netzob")
            sys.exit()

        if opts.workspace == None:
            workspace = str(ResourcesConfiguration.getWorkspaceFile())
        else:
            workspace = opts.workspace

        logging.debug("The workspace: {0}".format(str(workspace)))

        # loading the workspace
        self.currentWorkspace = (Workspace.loadWorkspace(workspace))

        # the semi-automatic loading of the workspace has failed (second attempt)
        if self.currentWorkspace == None:
            # we force the creation (or specification) of the workspace
            if not ResourcesConfiguration.initializeResources(True):
                logging.fatal("Error while configuring the resources of Netzob")
                sys.exit()
            workspace = str(ResourcesConfiguration.getWorkspaceFile())
            logging.debug("The workspace: {0}".format(str(workspace)))
            # loading the workspace
            self.currentWorkspace = (Workspace.loadWorkspace(workspace))
            if self.currentWorkspace == None:
                logging.fatal("Stopping the execution (no workspace computed)!")
                sys.exit()

        self.currentProject = self.currentWorkspace.getLastProject()

        # Second we create the logging infrastructure
        LoggingConfiguration().initializeLogging(self.currentWorkspace)

        # Now we load all the available plugins
        NetzobPlugin.loadPlugins(self)

        # create logger with the given configuration
        self.log = logging.getLogger('netzob.py')
        self.log.info(_("Starting netzob"))

        # Main window definition
        gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
        self.set_default_size(800, 600)
        self.set_title(_("Netzob: Inferring communication protocols"))

        self.set_icon_from_file(("%s/logo.png" %
                                 ResourcesConfiguration.getStaticResources()))
        self.connect("delete_event", self.evnmtDelete)
        self.connect("destroy", self.destroy)
        main_vbox = gtk.VBox(False, spacing=0)

        # Create and display the menu

        self.menu = Menu(self)
        menubar = self.menu.getMenuBar(self)
        menubar.show()
        self.menu.update()
        main_vbox.pack_start(menubar, False, True, 0)

        # Notebook definition
        self.notebook = gtk.Notebook()
        self.notebook.set_tab_pos(gtk.POS_TOP)
        self.notebook.connect("switch-page", self.notebookFocus)
        main_vbox.pack_start(self.notebook, True, True, 0)

        self.pageList = []
        # Adding the different notebook
        self.modelization = UImodelization(self)
        self.grammarInference = UIGrammarInference(self)
#        self.fuzzing = UIfuzzing(self)
        self.simulator = UISimulator(self)

        self.pageList.append([_("Vocabulary inference"), self.modelization])
        self.pageList.append([_("Grammar inference"), self.grammarInference])
#        self.pageList.append(["Fuzzing", self.fuzzing])
        self.pageList.append([_("Simulator"), self.simulator])

        for page in self.pageList:
            self.notebook.append_page(page[1].panel, gtk.Label(page[0]))

        # Initialize a clipboard object
        self.clipboard = (gtk.Clipboard(gtk.gdk.display_get_default(),
                                        "CLIPBOARD"))

        # Show every widgets
        self.notebook.show()
        main_vbox.show()
        self.add(main_vbox)
        self.show()
Example #14
0
    # Output is given through argument.
    # If no argument : output to stdout 
    
    outputStdout = True
    
    if (len(sys.argv) == 2) :
        outputStdout = False
        reportFile = sys.argv[1]
    
    
    # Configure the environment of execution
    NetzobResources.STATIC_DIR = "resources/static"
    NetzobResources.WORKSPACE_DIR = "resources/workspace"
#    NetzobResources.WORKSPACE_DIR = 
    
    currentWorkspace = Workspace.loadWorkspace(NetzobResources.WORKSPACE_DIR)
    if currentWorkspace == None :
        logging.error("Impossible to load the workspace") 
        exit()
    
    # Second we create the logging infrastructure
    LoggingConfiguration().initializeLogging(currentWorkspace)
    
    # Creates the main test suite
    globalTestSuite = unittest.TestSuite()
#    
#    # add the tests dedicated to the models
#    addTestsForModels(globalTestSuite)    

    # add the tests dedicated to the workspace config
    addTestsForWorkspace(globalTestSuite)
Example #15
0
    def switchWorkspace_activate_cb(self, action):
        """Callback executed when the user requests to switch to
        another workspace"""

        finish = False
        errorMessage = None
        while not finish:
            #open dialogbox
            builder2 = Gtk.Builder()
            builder2.add_from_file(os.path.join(
                ResourcesConfiguration.getStaticResources(),
                "ui",
                "dialogbox.glade"))

            dialog = builder2.get_object("switchWorkspace")
            dialog.set_transient_for(self.view.mainWindow)

            applybutton = builder2.get_object("switchWorkspaceApplyButton")
            fileChooserButton = builder2.get_object("switchWorkspaceFileChooserButton")
            fileChooserButton.connect("current-folder-changed", self.fileSetFileChooser_switchWorkspace_cb, applybutton)

            if errorMessage is not None:
                # Display a warning message on the dialog box
                warnLabel = builder2.get_object("switchWorkspaceWarnLabel")
                warnLabel.set_text(errorMessage)
                warnBox = builder2.get_object("switchWorkspaceWarnBox")
                warnBox.show_all()

            result = dialog.run()

            if result == 0:
                selectedFolder = fileChooserButton.get_current_folder()
                dialog.destroy()

                if selectedFolder is None:
                    errorMessage = _("No directory selected")
                else:
                    # we verify if its an empty directory
                    if len(os.listdir(selectedFolder)) > 0:
                        # is a valid workspace directory
                        errorMessage = Workspace.isFolderAValidWorkspace(selectedFolder)
                        if errorMessage is None:
                            try:
                                (self.currentWorkspace, error) = (Workspace.loadWorkspace(selectedFolder))
                                self.currentProject = self.currentWorkspace.getLastProject()
                                finish = True
                                errorMessage = None
                                self.view.currentWorkspaceHasChanged()
                            except Exception, e:
                                errorMessage = _("An error occurred while loading workspace.")
                                logging.warn("Error while loading workspace declared in folder {0}: {1}".format(selectedFolder, e))
                    else:
                        # create a new workspace
                        try:
                            self.currentWorkspace = ResourcesConfiguration.createWorkspace(selectedFolder)
                            finish = True
                            errorMessage = None
                            self.view.currentWorkspaceHasChanged()
                        except Exception, e:
                            errorMessage = _("An error occurred while creating workspace.")
                            logging.warn("Error while creating workspace declared in folder {0}: {1}".format(selectedFolder, e))
Example #16
0
 def getWorkspace(self):
     return Workspace.loadWorkspace(NetzobResources.WORKSPACE_DIR)