Esempio n. 1
0
 def setUp(self) -> None:
     from db.repositories.HostRepository import HostRepository
     self.mockDbAdapter = MagicMock()
     self.mockDbSession = MagicMock()
     self.mockProcess = MagicMock()
     self.mockDbAdapter.session.return_value = self.mockDbSession
     self.hostRepository = HostRepository(self.mockDbAdapter)
Esempio n. 2
0
    def openExistingProject(self, filename, projectType="legion"):
        try:
            log.info('Opening project..')
            self.istemp = False  # indicate the file is NOT temporary and should NOT be deleted later

            self.projectname = str(
                filename)  # set the new projectname and outputfolder vars
            nameOffset = len(projectType) + 1
            if not str(filename).endswith(projectType):
                self.outputfolder = str(
                    filename
                ) + '-tool-output'  # use the same name as the file for the folder (without the extension)
            else:
                self.outputfolder = str(
                    filename)[:-nameOffset] + '-tool-output'

            self.usernamesWordlist = Wordlist(
                self.outputfolder + '/' + projectType +
                '-usernames.txt')  # to store found usernames
            self.passwordsWordlist = Wordlist(
                self.outputfolder + '/' + projectType +
                '-passwords.txt')  # to store found passwords

            self.runningfolder = tempfile.mkdtemp(
                suffix="-running", prefix=projectType +
                '-')  # to store tool output of running processes
            self.cwd = ntpath.dirname(
                str(self.projectname)
            ) + '/'  # update cwd so it appears nicely in the window title
            self.db = Database(self.projectname)  # use the new db
            self.reinitialize(self.db, HostRepository(self.db))

        except:
            log.info('Something went wrong while opening the project..')
            log.info("Unexpected error: {0}".format(sys.exc_info()[0]))
Esempio n. 3
0
 def buildRepositories(self, database: Database) -> RepositoryContainer:
     hostRepository = HostRepository(database)
     processRepository = ProcessRepository(database, self.logger)
     serviceRepository = ServiceRepository(database)
     portRepository: PortRepository = PortRepository(database)
     cveRepository: CVERepository = CVERepository(database)
     noteRepository: NoteRepository = NoteRepository(database, self.logger)
     scriptRepository: ScriptRepository = ScriptRepository(database)
     return RepositoryContainer(serviceRepository, processRepository,
                                hostRepository, portRepository,
                                cveRepository, noteRepository,
                                scriptRepository)
Esempio n. 4
0
 def start(self, title='*untitled'):
     self.processes = [
     ]  # to store all the processes we run (nmaps, niktos, etc)
     self.fastProcessQueue = queue.Queue(
     )  # to manage fast processes (banner, snmpenum, etc)
     self.fastProcessesRunning = 0  # counts the number of fast processes currently running
     self.slowProcessesRunning = 0  # counts the number of slow processes currently running
     self.nmapImporter.setDB(
         self.logic.db)  # tell nmap importer which db to use
     self.nmapImporter.setHostRepository(HostRepository(self.logic.db))
     self.pythonImporter.setDB(self.logic.db)
     self.updateOutputFolder(
     )  # tell screenshooter where the output folder is
     self.view.start(title)
Esempio n. 5
0
 def createNewProject(self):
     self.view.closeProject()  # removes temp folder (if any)
     tf = self.logic.shell.create_named_temporary_file(
         suffix=".legion",
         prefix="legion-",
         directory="./tmp/",
         delete_on_close=False)  # to store the db file
     db = Database(tf.name)
     self.logic.projectname = tf.name
     self.logic.db = db
     self.logic.cwd = self.logic.shell.get_current_working_directory()
     self.logic.reinitialize(db, HostRepository(db))
     self.logic.createTemporaryFiles()
     self.start()  # initialisations (globals, etc)
Esempio n. 6
0
class HostRepositoryTest(unittest.TestCase):
    def setUp(self) -> None:
        from db.repositories.HostRepository import HostRepository
        self.mockDbAdapter = MagicMock()
        self.mockDbSession = MagicMock()
        self.mockProcess = MagicMock()
        self.mockDbAdapter.session.return_value = self.mockDbSession
        self.hostRepository = HostRepository(self.mockDbAdapter)

    def getHostsAndPortsTestCase(self, filters, service_name, expectedQuery):
        self.mockDbAdapter.metadata.bind.execute.return_value = mockExecuteFetchAll(
            [{
                'name': 'service_name1'
            }, {
                'name': 'service_name2'
            }])
        service_names = self.hostRepository.getHostsAndPortsByServiceName(
            service_name, filters)

        self.mockDbAdapter.metadata.bind.execute.assert_called_once_with(
            expectedQuery, service_name)
        self.assertEqual([{
            'name': 'service_name1'
        }, {
            'name': 'service_name2'
        }], service_names)

    def test_exists_WhenProvidedAExistingHosts_ReturnsTrue(self):
        self.mockDbAdapter.metadata.bind.execute.return_value = mockExecuteFetchAll(
            [['some-ip']])
        self.assertTrue(self.hostRepository.exists("some_host"))
        self.mockDbAdapter.metadata.bind.execute.assert_called_once_with(
            existsQuery, "some_host", "some_host")

    def test_exists_WhenProvidedANonExistingHosts_ReturnsFalse(self):
        self.mockDbAdapter.metadata.bind.execute.return_value = mockExecuteFetchAll(
            [])

        self.assertFalse(self.hostRepository.exists("some_host"))
        self.mockDbAdapter.metadata.bind.execute.assert_called_once_with(
            existsQuery, "some_host", "some_host")

    def test_getHosts_InvokedWithNoFilters_ReturnsHosts(self):
        from app.auxiliary import Filters
        self.mockDbAdapter.metadata.bind.execute.return_value = mockExecuteFetchAll(
            [['host1'], ['host2']])
        expectedQuery = "SELECT * FROM hostObj AS hosts WHERE 1=1"
        filters: Filters = Filters()
        filters.apply(up=True,
                      down=True,
                      checked=True,
                      portopen=True,
                      portfiltered=True,
                      portclosed=True,
                      tcp=True,
                      udp=True)
        result = self.hostRepository.getHosts(filters)
        self.assertEqual([['host1'], ['host2']], result)
        self.mockDbAdapter.metadata.bind.execute.assert_called_once_with(
            expectedQuery)

    def test_getHosts_InvokedWithAFewFilters_ReturnsFilteredHosts(self):
        from app.auxiliary import Filters
        self.mockDbAdapter.metadata.bind.execute.return_value = mockExecuteFetchAll(
            [['host1'], ['host2']])
        expectedQuery = (
            "SELECT * FROM hostObj AS hosts WHERE 1=1"
            " AND hosts.status != 'down' AND hosts.checked != 'True'")
        filters: Filters = Filters()
        filters.apply(up=True,
                      down=False,
                      checked=False,
                      portopen=True,
                      portfiltered=True,
                      portclosed=True,
                      tcp=True,
                      udp=True)
        result = self.hostRepository.getHosts(filters)
        self.assertEqual([['host1'], ['host2']], result)
        self.mockDbAdapter.metadata.bind.execute.assert_called_once_with(
            expectedQuery)

    def test_getHostInfo_WhenProvidedHostIpAddress_FetchesHostInformation(
            self):
        from db.entities.host import hostObj

        expected_host_info: hostObj = MagicMock()
        self.mockDbSession.query.return_value = mockQueryWithFilterBy(
            mockFirstByReturnValue(expected_host_info))

        actual_host_info = self.hostRepository.getHostInformation("127.0.0.1")
        self.assertEqual(actual_host_info, expected_host_info)

    def test_getHostsAndPorts_InvokedWithNoFilters_FetchesHostsAndPortsMatchingKeywords(
            self):
        from app.auxiliary import Filters

        filters: Filters = Filters()
        filters.apply(up=True,
                      down=True,
                      checked=True,
                      portopen=True,
                      portfiltered=True,
                      portclosed=True,
                      tcp=True,
                      udp=True)
        expectedQuery = expectedGetHostsAndPortsQuery()
        self.getHostsAndPortsTestCase(filters=filters,
                                      service_name="some_service_name",
                                      expectedQuery=expectedQuery)

    def test_getHostsAndPorts_InvokedWithFewFilters_FetchesHostsAndPortsWithFiltersApplied(
            self):
        from app.auxiliary import Filters

        filters: Filters = Filters()
        filters.apply(up=True,
                      down=False,
                      checked=True,
                      portopen=True,
                      portfiltered=True,
                      portclosed=True,
                      tcp=True,
                      udp=False)
        expectedQuery = expectedGetHostsAndPortsQuery(
            with_filter=
            " AND hosts.status != 'down' AND ports.protocol != 'udp'")
        self.getHostsAndPortsTestCase(filters=filters,
                                      service_name="some_service_name",
                                      expectedQuery=expectedQuery)

    def test_deleteHost_InvokedWithAHostId_DeletesProcess(self):
        self.mockDbSession.query.return_value = mockQueryWithFilterBy(
            mockFirstByReturnValue(self.mockProcess))

        self.hostRepository.deleteHost("some-host-id")
        self.mockDbSession.delete.assert_called_once_with(self.mockProcess)
        self.mockDbSession.commit.assert_called_once()

    def test_toggleHostCheckStatus_WhenHostIsSetToTrue_TogglesToFalse(self):
        self.mockProcess.checked = 'True'
        self.mockDbSession.query.return_value = mockQueryWithFilterBy(
            mockFirstByReturnValue(self.mockProcess))
        self.hostRepository.toggleHostCheckStatus("some-ip-address")
        self.assertEqual('False', self.mockProcess.checked)
        self.mockDbSession.add.assert_called_once_with(self.mockProcess)
        self.mockDbAdapter.commit.assert_called_once()

    def test_toggleHostCheckStatus_WhenHostIsSetToFalse_TogglesToTrue(self):
        self.mockProcess.checked = 'False'
        self.mockDbSession.query.return_value = mockQueryWithFilterBy(
            mockFirstByReturnValue(self.mockProcess))
        self.hostRepository.toggleHostCheckStatus("some-ip-address")
        self.assertEqual('True', self.mockProcess.checked)
        self.mockDbSession.add.assert_called_once_with(self.mockProcess)
        self.mockDbAdapter.commit.assert_called_once()