class PluginsToModelControllerIntegration(unittest.TestCase): def setUp(self): """ Generic test to verify that the object exists and can be instantiated without problems. """ self.dbManager = mock() self.changesController = mock() self.reportManager = mock() self.dbManager = DbManager() self.mappersManager = MapperManager() self.model_controller = controller.ModelController(mock(), self.mappersManager) self.workspace_manager = WorkspaceManager(self.dbManager, self.mappersManager, self.changesController, self.reportManager) self.workspace_manager.createWorkspace('temp_workspace', 'desc', DBTYPE.FS) self.workspace_manager.openWorkspace('temp_workspace') self._plugin_controller = PluginControllerForApi("test", {"nmap": nmap_plugin.NmapPlugin(), "nessus": nessus_plugin.NessusPlugin()}, mock()) api.setUpAPIs(self.model_controller, self.workspace_manager) def tearDown(self): self.workspace_manager.removeWorkspace('temp_workspace') def test_nmap_scan_saves_host(self): output_file = open(os.path.join(os.getcwd(), 'test_cases/data/nmap_plugin_with_api.xml')) output = output_file.read() self._plugin_controller.processCommandInput("nmap localhost") self._plugin_controller.onCommandFinished("nmap localhost", output) self.model_controller.processAllPendingActions() self.assertEquals(len(self.model_controller.getAllHosts()), 1, "Not all hosts added to model") host = self.model_controller.getAllHosts()[0] self.assertEquals(len(host.getAllInterfaces()), 1, "Not all interfaces added to model") interface = host.getAllInterfaces()[0] self.assertEquals(len(interface.getAllServices()), 3, "Not all services added to model") services = interface.getAllServices() self.assertTrue(all( [ s.getStatus() == 'open' for s in services]), "Port status not saved correctly") def test_nessus_scan_saves_host(self): output_file = open(os.path.join(os.getcwd(), 'test_cases/data/nessus_plugin_with_api.nessus')) output = output_file.read() self._plugin_controller.processCommandInput("./nessus report") self._plugin_controller.onCommandFinished("./nessus report", output) self.model_controller.processAllPendingActions() self.assertEquals(len(self.model_controller.getAllHosts()), 7, "Not all hosts added to model")
def testOpenWorkspaceChangesAndReportManagerWatch(self): reportManager = mock() dbManager = mock() mappersManager = mock() dbConnector = mock() mappers = mock() changesController = mock() workspaceMapper = mock() workspace = Workspace('test_workspace', 'a desc') when(dbManager).getAllDbNames().thenReturn(['test_workspace']) when(dbManager).getConnector('test_workspace').thenReturn(dbConnector) when(mappersManager).createMappers(dbConnector).thenReturn(True) when(mappersManager).getMapper( Workspace.__name__).thenReturn(workspaceMapper) when(workspaceMapper).find('test_workspace').thenReturn(workspace) workspace_manager = WorkspaceManager(dbManager, mappersManager, changesController, reportManager) opened_workspace = workspace_manager.openWorkspace('test_workspace') verify(reportManager).watch('test_workspace') verify(changesController).watch(mappersManager, dbConnector) self.assertEquals(opened_workspace.getName(), 'test_workspace')
def testOpenWorkspaceChangesAndReportManagerWatch(self): reportManager = mock() dbManager = mock() mappersManager = mock() dbConnector = mock() mappers = mock() changesController = mock() workspaceMapper = mock() workspace = Workspace('test_workspace', 'a desc') when(dbManager).getAllDbNames().thenReturn(['test_workspace']) when(dbManager).getConnector('test_workspace').thenReturn(dbConnector) when(mappersManager).createMappers(dbConnector).thenReturn(True) when(mappersManager).getMapper(Workspace.__name__).thenReturn(workspaceMapper) when(workspaceMapper).find('test_workspace').thenReturn(workspace) workspace_manager = WorkspaceManager(dbManager, mappersManager, changesController, reportManager) opened_workspace = workspace_manager.openWorkspace('test_workspace') verify(reportManager).watch('test_workspace') verify(changesController).watch(mappersManager, dbConnector) self.assertEquals(opened_workspace.getName(), 'test_workspace')
def testOpenWorkspaceNoneExisting(self): dbManager = mock() mappersManager = mock() dbConnector = mock() mappers = mock() changesController = mock() workspace = Workspace('test_workspace', 'a desc') when(dbManager).getAllDbNames().thenReturn([]) workspace_manager = WorkspaceManager(dbManager, mappersManager, changesController, mock()) opened_workspace = workspace_manager.openWorkspace('test_workspace') verify(mappersManager, times=0).createMappers(dbConnector) verify(mappersManager, times=0).find('test_workspace') self.assertFalse(opened_workspace, 'Workspace retrieved but non existing')
def testOpenWorkspaceSetsChangesCallback(self): dbManager = mock() mappersManager = mock() dbConnector = mock() mappers = mock() changesController = mock() workspaceMapper = mock() workspace = Workspace('test_workspace', 'a desc') when(dbManager).getConnector('test_workspace').thenReturn(dbConnector) when(mappersManager).getMapper(Workspace.__name__).thenReturn(workspaceMapper) when(dbManager).getAllDbNames().thenReturn(['test_workspace']) when(mappersManager).createMappers(dbConnector).thenReturn(True) when(workspaceMapper).find('test_workspace').thenReturn(workspace) workspace_manager = WorkspaceManager(dbManager, mappersManager, changesController, mock()) opened_workspace = workspace_manager.openWorkspace('test_workspace') verify(changesController).watch(mappersManager, dbConnector)
def testOpenWorkspaceSetsChangesCallback(self): dbManager = mock() mappersManager = mock() dbConnector = mock() mappers = mock() changesController = mock() workspaceMapper = mock() workspace = Workspace('test_workspace', 'a desc') when(dbManager).getConnector('test_workspace').thenReturn(dbConnector) when(mappersManager).getMapper( Workspace.__name__).thenReturn(workspaceMapper) when(dbManager).getAllDbNames().thenReturn(['test_workspace']) when(mappersManager).createMappers(dbConnector).thenReturn(True) when(workspaceMapper).find('test_workspace').thenReturn(workspace) workspace_manager = WorkspaceManager(dbManager, mappersManager, changesController, mock()) opened_workspace = workspace_manager.openWorkspace('test_workspace') verify(changesController).watch(mappersManager, dbConnector)
class MainApplication(object): """ """ def __init__(self, args): self._original_excepthook = sys.excepthook self._configuration = CONF self._security_manager = SecurityManager() self._mappers_manager = MapperManager() self._changes_controller = ChangeController() self._db_manager = DbManager() self._model_controller = ModelController(self._security_manager, self._mappers_manager) self._plugin_manager = PluginManager( os.path.join(CONF.getConfigPath(), "plugins"), self._mappers_manager) self._reports_manager = ReportManager( 10, self._plugin_manager.createController("ReportManager")) self._workspace_manager = WorkspaceManager(self._db_manager, self._mappers_manager, self._changes_controller, self._reports_manager) self.gui_app = UiFactory.create(self._model_controller, self._plugin_manager, self._workspace_manager, args.gui) self.gui_app.setSplashImage( os.path.join(CONF.getImagePath(), "splash2.png")) def enableExceptHook(self): sys.excepthook = exception_handler installThreadExcepthook() def disableLogin(self): CONF.setAuth(sys.disablelogin) def start(self): try: self.gui_app.startSplashScreen() self.gui_app.splashMessage("Starting Faraday") signal.signal(signal.SIGINT, self.ctrlC) logged = True while True: username, password = "******", "password" if username is None and password is None: break result = self._security_manager.authenticateUser( username, password) if result == codes.successfulLogin: logged = True break if logged: model.api.devlog("Starting application...") model.api.devlog("Setting up remote API's...") # We need to create the last used workspace (or the default # workspace) before we start the model controller and the # report manager last_workspace = CONF.getLastWorkspace() if not self._workspace_manager.workspaceExists(last_workspace): getLogger(self).info( "Your last workspace (" + last_workspace + ") wasn't accessible, check configuration...") self._workspace_manager.openDefaultWorkspace() #self._workspace_manager.createWorkspace(last_workspace, 'default workspace, probably created already in couchb') else: self._workspace_manager.openWorkspace(last_workspace) model.api.setUpAPIs(self._model_controller, self._workspace_manager, CONF.getApiConInfoHost(), CONF.getApiConInfoPort()) model.guiapi.setUpGUIAPIs(self._model_controller) model.api.devlog("Starting model controller daemon...") self._model_controller.start() model.api.startAPIServer() restapi.startAPIs(self._plugin_manager, self._model_controller, self._mappers_manager, CONF.getApiConInfoHost(), CONF.getApiRestfulConInfoPort()) # Start report manager here getLogger(self).debug("Starting Reports Manager Thread") self._reports_manager.startWatch() model.api.devlog("Faraday ready...") model.api.__current_logged_user = username self.gui_app.splashMessage("Loading workspace... Please wait.") self.gui_app.loadWorkspaces() self.gui_app.stopSplashScreen() except Exception: print "There was an error while starting Faraday" print "-" * 50 traceback.print_exc() print "-" * 50 self.__exit(-1) if logged: exit_code = self.gui_app.run([]) #exit_code = self.app.exec_loop() else: exit_code = -1 return self.__exit(exit_code) def __exit(self, exit_code=0): """ Exits the application with the provided code. It also waits until all app threads end. """ model.api.devlog("Closing Faraday...") model.api.devlog("stopping model controller thread...") model.api.stopAPIServer() restapi.stopServer() self._reports_manager.stop() self._changes_controller.stop() self._model_controller.stop() self._model_controller.join() self.gui_app.quit() model.api.devlog("Waiting for controller threads to end...") return exit_code def quit(self): """ Redefined quit handler to nicely end up things """ self.gui_app.quit() def ctrlC(self, signal, frame): getLogger(self).info("Exiting...") self.__exit(exit_code=0) def getWorkspaceManager(self): return self._workspace_manager
class MainApplication(object): """ """ def __init__(self, args): self._original_excepthook = sys.excepthook self._configuration = CONF self._security_manager = SecurityManager() self._mappers_manager = MapperManager() self._changes_controller = ChangeController() self._db_manager = DbManager() self._model_controller = ModelController(self._security_manager, self._mappers_manager) self._plugin_manager = PluginManager(os.path.join(CONF.getConfigPath(), "plugins"), self._mappers_manager) self._reports_manager = ReportManager(10, self._plugin_manager.createController("ReportManager")) self._workspace_manager = WorkspaceManager( self._db_manager, self._mappers_manager, self._changes_controller, self._reports_manager ) self.gui_app = UiFactory.create(self._model_controller, self._plugin_manager, self._workspace_manager, args.gui) self.gui_app.setSplashImage(os.path.join(CONF.getImagePath(), "splash2.png")) self.timer = TimerClass() self.timer.start() def enableExceptHook(self): sys.excepthook = exception_handler installThreadExcepthook() def disableLogin(self): CONF.setAuth(sys.disablelogin) def start(self): try: self.gui_app.startSplashScreen() self.gui_app.splashMessage("Starting Faraday") signal.signal(signal.SIGINT, self.ctrlC) logged = True while True: username, password = "******", "password" if username is None and password is None: break result = self._security_manager.authenticateUser(username, password) if result == codes.successfulLogin: logged = True break if logged: model.api.devlog("Starting application...") model.api.devlog("Setting up remote API's...") # We need to create the last used workspace (or the default # workspace) before we start the model controller and the # report manager last_workspace = CONF.getLastWorkspace() try: if not self._workspace_manager.workspaceExists(last_workspace): getLogger(self).info( "Your last workspace (" + str(last_workspace) + ") wasn't accessible, check configuration..." ) self._workspace_manager.openDefaultWorkspace() # self._workspace_manager.createWorkspace(last_workspace, 'default workspace, probably created already in couchb') else: self._workspace_manager.openWorkspace(last_workspace) except restkit.errors.Unauthorized: print "You are trying to enter CouchDB with authentication" print "Add your credentials to your user configuration file in $HOME/.faraday/config/user.xml" print "For example: <couch_uri>http://john:[email protected]:5984</couch_uri>" return model.api.setUpAPIs( self._model_controller, self._workspace_manager, CONF.getApiConInfoHost(), CONF.getApiConInfoPort() ) model.guiapi.setUpGUIAPIs(self._model_controller) model.api.devlog("Starting model controller daemon...") self._model_controller.start() model.api.startAPIServer() restapi.startAPIs( self._plugin_manager, self._model_controller, self._mappers_manager, CONF.getApiConInfoHost(), CONF.getApiRestfulConInfoPort(), ) # Start report manager here getLogger(self).debug("Starting Reports Manager Thread") self._reports_manager.startWatch() model.api.devlog("Faraday ready...") model.api.__current_logged_user = username self.gui_app.splashMessage("Loading workspace... Please wait.") self.gui_app.loadWorkspaces() self.gui_app.stopSplashScreen() except Exception: print "There was an error while starting Faraday" print "-" * 50 traceback.print_exc() print "-" * 50 self.__exit(-1) if logged: exit_code = self.gui_app.run([]) # exit_code = self.app.exec_loop() else: exit_code = -1 return self.__exit(exit_code) def __exit(self, exit_code=0): """ Exits the application with the provided code. It also waits until all app threads end. """ model.api.devlog("Closing Faraday...") model.api.devlog("stopping model controller thread...") model.api.stopAPIServer() restapi.stopServer() self._reports_manager.stop() self._changes_controller.stop() self._model_controller.stop() self._model_controller.join() self.gui_app.quit() self.timer.stop() model.api.devlog("Waiting for controller threads to end...") return exit_code def quit(self): """ Redefined quit handler to nicely end up things """ self.gui_app.quit() def ctrlC(self, signal, frame): getLogger(self).info("Exiting...") self.__exit(exit_code=0) def getWorkspaceManager(self): return self._workspace_manager
class PluginsToModelControllerIntegration(unittest.TestCase): def setUp(self): """ Generic test to verify that the object exists and can be instantiated without problems. """ self.dbManager = mock() self.changesController = mock() self.reportManager = mock() self.dbManager = DbManager() self.mappersManager = MapperManager() self.model_controller = controller.ModelController( mock(), self.mappersManager) self.workspace_manager = WorkspaceManager(self.dbManager, self.mappersManager, self.changesController, self.reportManager) self.workspace_manager.createWorkspace('temp_workspace', 'desc', DBTYPE.FS) self.workspace_manager.openWorkspace('temp_workspace') self._plugin_controller = PluginControllerForApi( "test", { "nmap": nmap_plugin.NmapPlugin(), "nessus": nessus_plugin.NessusPlugin() }, mock()) api.setUpAPIs(self.model_controller, self.workspace_manager) def tearDown(self): self.workspace_manager.removeWorkspace('temp_workspace') def test_nmap_scan_saves_host(self): output_file = open( os.path.join(os.getcwd(), 'test_cases/data/nmap_plugin_with_api.xml')) output = output_file.read() self._plugin_controller.processCommandInput("nmap localhost") self._plugin_controller.onCommandFinished("nmap localhost", output) self.model_controller.processAllPendingActions() self.assertEquals(len(self.model_controller.getAllHosts()), 1, "Not all hosts added to model") host = self.model_controller.getAllHosts()[0] self.assertEquals(len(host.getAllInterfaces()), 1, "Not all interfaces added to model") interface = host.getAllInterfaces()[0] self.assertEquals(len(interface.getAllServices()), 3, "Not all services added to model") services = interface.getAllServices() self.assertTrue(all([s.getStatus() == 'open' for s in services]), "Port status not saved correctly") def test_nessus_scan_saves_host(self): output_file = open( os.path.join(os.getcwd(), 'test_cases/data/nessus_plugin_with_api.nessus')) output = output_file.read() self._plugin_controller.processCommandInput("./nessus report") self._plugin_controller.onCommandFinished("./nessus report", output) self.model_controller.processAllPendingActions() self.assertEquals(len(self.model_controller.getAllHosts()), 7, "Not all hosts added to model")
class TestWorkspacesManagement(unittest.TestCase): def setUp(self): self.couch_uri = CONF.getCouchURI() # self.cdm = CouchdbManager(uri=self.couch_uri) wpath = os.path.expanduser("~/.faraday/persistence/" ) # self.fsm = FSManager(wpath) self.dbManager = DbManager() self.mappersManager = MapperManager() self.changesController = ChangeController(self.mappersManager) self.wm = WorkspaceManager(self.dbManager, self.mappersManager, self.changesController) self._fs_workspaces = [] self._couchdb_workspaces = [] def tearDown(self): self.cleanCouchDatabases() self.cleanFSWorkspaces() # pass def new_random_workspace_name(self): return ("aworkspace" + "".join(random.sample( [chr(i) for i in range(65, 90)], 10))).lower() def cleanFSWorkspaces(self): import shutil basepath = os.path.expanduser("~/.faraday/persistence/") for d in self._fs_workspaces: wpath = os.path.join(basepath, d) if os.path.isdir(wpath): shutil.rmtree(wpath) def cleanCouchDatabases(self): try: for wname in self._couchdb_workspaces: self.cdm.removeWorkspace(wname) except Exception as e: print e def test_create_fs_workspace(self): """ Verifies the creation of a filesystem workspace """ wname = self.new_random_workspace_name() self._fs_workspaces.append(wname) self.wm.createWorkspace(wname, 'desc', DBTYPE.FS) wpath = os.path.expanduser("~/.faraday/persistence/%s" % wname) self.assertTrue(os.path.exists(wpath)) def test_create_couch_workspace(self): """ Verifies the creation of a couch workspace """ wname = self.new_random_workspace_name() self._couchdb_workspaces.append(wname) self.wm.createWorkspace(wname, 'a desc', DBTYPE.COUCHDB) res_connector = self.dbManager.getConnector(wname) self.assertTrue(res_connector) self.assertEquals(res_connector.getType(), DBTYPE.COUCHDB) self.assertTrue(self.mappersManager.find(wname), "Workspace document not found") wpath = os.path.expanduser("~/.faraday/persistence/%s" % wname) self.assertFalse(os.path.exists(wpath)) # self.assertEquals(WorkspaceOnCouch.__name__, self.wm.getWorkspaceType(wname)) def test_delete_couch_workspace(self): """ Verifies the deletion of a couch workspace """ wname = self.new_random_workspace_name() self.wm.createWorkspace(wname, 'a desc', DBTYPE.COUCHDB) self.assertTrue(self.mappersManager.find(wname), "Workspace document not found") #Delete workspace self.wm.removeWorkspace(wname) self.assertIsNone(self.mappersManager.find(wname)) self.assertFalse(self.dbManager.connectorExists(wname)) def test_delete_fs_workspace(self): """ Verifies the deletion of a filesystem workspace """ wname = self.new_random_workspace_name() self.wm.createWorkspace(wname, 'desc', DBTYPE.FS) wpath = os.path.expanduser("~/.faraday/persistence/%s" % wname) self.assertTrue(os.path.exists(wpath)) #Delete workspace self.wm.removeWorkspace(wname) self.assertFalse(os.path.exists(wpath)) def test_list_workspaces(self): """ Lists FS workspaces and Couch workspaces """ # First create workspaces manually wnamefs = self.new_random_workspace_name() wnamecouch = self.new_random_workspace_name() # FS self.wm.createWorkspace(wnamefs, 'a desc', DBTYPE.FS) # Couch self.wm.createWorkspace(wnamecouch, 'a desc', DBTYPE.COUCHDB) self.assertIn(wnamefs, self.wm.getWorkspacesNames(), 'FS Workspace not loaded') self.assertIn(wnamecouch, self.wm.getWorkspacesNames(), 'Couch Workspace not loaded') self.assertEquals(self.wm.getWorkspaceType(wnamecouch), 'CouchDB', 'Workspace type bad defined' ) self.assertEquals(self.wm.getWorkspaceType(wnamefs), 'FS', 'Workspace type bad defined') def test_get_workspace(self): """ Create a workspace, now ask for it """ # When wname = self.new_random_workspace_name() workspace = self.wm.createWorkspace(wname, 'a desc', DBTYPE.FS) added_workspace = self.wm.openWorkspace(wname) # Then self.assertIsNotNone(workspace, 'Workspace added should not be none') self.assertEquals(workspace, added_workspace, 'Workspace created and added diffier') def _test_get_existent_couch_workspace(self): # Deprecate """ Create a workspace in the backend, now ask for it """ # When wname = self.new_random_workspace_name() workspace = self.cdm.addWorkspace(wname) added_workspace = self.wm.getWorkspace(wname) # Then self.assertIsNotNone(added_workspace, 'Workspace added should not be none') def _test_get_existent_fs_workspace(self): # Deprecate """ Create a workspace in the backend, now ask for it """ # When wname = self.new_random_workspace_name() workspace = self.fsm.addWorkspace(wname) self.wm.loadWorkspaces() added_workspace = self.wm.getWorkspace(wname) # Then self.assertIsNotNone(added_workspace, 'Workspace added should not be none') def test_get_non_existent_workspace(self): """ Retrieve a non existent workspace """ added_workspace = self.wm.openWorkspace('inventado') # Then self.assertIsNone(added_workspace, 'Workspace added should not be none') def test_set_active_workspace(self): ''' create a workspace through the backend, then set it as active ''' wname = self.new_random_workspace_name() workspace = self.wm.createWorkspace(wname, 'desc', DBTYPE.FS) # when self.wm.setActiveWorkspace(workspace) self.assertEquals(workspace, self.wm.getActiveWorkspace(), 'Active workspace diffiers with expected workspace') self.assertTrue(self.wm.isActive(workspace.name), 'Workspace is active flag not set') def test_remove_fs_workspace(self): # First wname = self.new_random_workspace_name() added_workspace = self.wm.createWorkspace(wname, 'desc', DBTYPE.FS) # When self.wm.removeWorkspace(wname) # Then self.assertNotIn(wname, self.wm.getWorkspacesNames()) wpath = os.path.expanduser("~/.faraday/persistence/%s" % wname) self.assertFalse(os.path.exists(wpath)) def test_remove_couch_workspace(self): # First wname = self.new_random_workspace_name() added_workspace = self.wm.createWorkspace(wname, 'desc', DBTYPE.COUCHDB) # When self.wm.removeWorkspace(wname) # Then self.assertNotIn(wname, self.wm.getWorkspacesNames()) def test_remove_non_existent_workspace(self): # When self.wm.removeWorkspace('invented')