def create(self, name, text_targets, template): """Get scan by ID. :param name: The name of the Scan to be created. :param text_targets: A string of comma separated targets or a list of targets. :param template: The name or title of the template, or an instance of Template. :return: ScanRef referenced by id if exists. """ if isinstance(text_targets, list): text_targets = ','.join(text_targets) t = template if not isinstance(t, Template): t = self.template(name=template) if not t: t = self.template(title=template) if not t: raise TenableIOException( u'Template with name or title as "%s" not found.' % template) scan_id = self._client.scans_api.create( ScanCreateRequest(t.uuid, ScanSettings( name, text_targets, ))) return ScanRef(self._client, scan_id)
def scan_id(self, app, client, template): """ Create a scan for testing. """ scan_id = client.scans_api.create( ScanCreateRequest( template.uuid, ScanSettings( app.session_name('test_scans'), TenableIOTestConfig.get('scan_text_targets'), ))) yield scan_id try: client.scans_api.delete(scan_id) except TenableIOApiException: # This happens when the scan is not idling. client.scans_api.stop(scan_id) self.wait_until( lambda: client.scans_api.details(scan_id), lambda details: details.info.status in [ Scan.STATUS_CANCELED, Scan.STATUS_COMPLETED, Scan. STATUS_EMPTY ]) client.scans_api.delete(scan_id)
def test_scans_agent_scan(client, new_agent_group): template_list = client.editor_api.list('scan') assert len( template_list.templates) > 0, u'Expected at least one scan template.' agent_group_uuid = client.agent_groups_api.details(new_agent_group).uuid test_templates = [ t for t in template_list.templates if t.name == 'agent_basic' ] scan_id = client.scans_api.create( ScanCreateRequest( test_templates[0].uuid, ScanSettings( 'test_basic_agent_scan', agent_group_id=[agent_group_uuid], ))) # we need to launch the scan in order for some fields to be fully populated client.scans_api.launch(scan_id, ScanLaunchRequest()) scan_details = client.scans_api.details(scan_id) assert isinstance( scan_details, ScanDetails ), u'The `details` method did not return type `ScanDetails`.' assert scan_details.info.agent_targets is not None, u'Expected agent_targets attribute to be present.' assert len( scan_details.info.agent_targets ) == 1, u'Expected a single agent group to be included in agent_targets.' assert scan_details.info.agent_targets[0].uuid == agent_group_uuid, \ u'Expected agent group uuid to match configured value.'
def init_scan(new_host_ip, timestamp): # Fetch a list of all scanners on the account and group them into a dictionary {scannerName: scannerId} scanners = { scanner.name: scanner.id for scanner in tio_client.scanners_api.list().scanners } # Fetch a list of all folders on the account and group them into a dictionary {folderName: folderId} folders = { folder.name: folder.id for folder in tio_client.folders_api.list().folders } # This controls the name formatting for the automatically generated scan. scan_name = 'NNM Initiated Scan - New Host %s @ %s' % (new_host_ip, timestamp) # This controls which template is used, see the 'TEMPLATE_TYPE' variable at the top. basic_template = tio_client.scan_helper.template(name=TEMPLATE_TYPE) # Create the scan and use the corresponding scanner id for the scanner name supplied scan_id = tio_client.scans_api.create( ScanCreateRequest( basic_template.uuid, ScanSettings(scan_name, new_host_ip, folder_id=folders[FOLDER_NAME], scanner_id=scanners[SCANNER_NAME]))) # Get the scanRef object using the previously returned scan id scan_ref = tio_client.scan_helper.id(scan_id) # launch the scan but don't block until it finishes scan_ref.launch(wait=False)
def create(self, name, text_targets, template, credentials=None, policy_id=None, policy_name=None): """Get scan by ID. :param name: The name of the Scan to be created. :param text_targets: A string of comma separated targets or a list of targets. :param template: The name or title of the template, or an instance of Template. :return: ScanRef referenced by id if exists. """ if isinstance(text_targets, list): text_targets = ','.join(text_targets) t = template if not isinstance(t, Template): t = self.template(name=template) if not t: t = self.template(title=template) if not t: raise TenableIOException( u'Template with name or title as "%s" not found.' % template) if not policy_id and policy_name: p = self.policy(policy_name) if not p: raise TenableIOException( u'Policy with name as "%s" not found.' % policy_name) policy_id = p.id if credentials and not isinstance(credentials, PolicyCredentials): raise TenableIOException( u'Credentials is not an instance of PolicyCredentials.') if policy_id and credentials: # create a new policy with the credentials copy_custom_policy_id = self._client.policies_api.copy(policy_id) payload = {"credentials": credentials.as_payload()} self._client.put('policies/%(policy_id)s', payload, path_params={'policy_id': copy_custom_policy_id}) policy_id = copy_custom_policy_id scan_id = self._client.scans_api.create( ScanCreateRequest( t.uuid, ScanSettings( name, text_targets, policy_id=policy_id, ), credentials)) return ScanRef(self._client, scan_id)
def new_scan_id(client): template_list = client.editor_api.list('scan') assert len( template_list.templates) > 0, u'Expected at least one scan template.' test_templates = [t for t in template_list.templates if t.name == 'basic'] return client.scans_api.create( ScanCreateRequest( test_templates[0].uuid, ScanSettings( 'test_scan_fixture', TenableIOTestConfig.get('scan_text_targets'), )))
def scan(self, app, client, scanner, template): """ Create scan for testing. Ensure there is one active (running or paused) scan in given scanner. """ scan_id = client.scans_api.create( ScanCreateRequest( template.uuid, ScanSettings(app.session_name('test_scanners'), TenableIOTestConfig.get('scan_text_targets'), scanner_id=scanner.id))) client.scans_api.launch(scan_id, ScanLaunchRequest()) scan_details = client.scans_api.details(scan_id) assert scan_details.info.status in [ Scan.STATUS_PENDING, Scan.STATUS_RUNNING ], u'Scan is in launched state.' scan_details = self.wait_until( lambda: client.scans_api.details(scan_id), lambda details: details. info.status in [Scan.STATUS_COMPLETED, Scan.STATUS_RUNNING]) assert scan_details.info.status == Scan.STATUS_RUNNING, u'Scan should be running to test pause.' client.scans_api.pause(scan_id) scan_details = client.scans_api.details(scan_id) assert scan_details.info.status in [ Scan.STATUS_PAUSED, Scan.STATUS_PAUSING ], u'Scan is pausing.' scan_details = self.wait_until( lambda: client.scans_api.details(scan_id), lambda details: details.info.status in [Scan.STATUS_PAUSED]) assert scan_details.info.status == Scan.STATUS_PAUSED, u'Scan is paused.' yield scan_details try: client.scans_api.delete(scan_id) except TenableIOApiException: # This happens when the scan is not idling. client.scans_api.stop(scan_id) self.wait_until( lambda: client.scans_api.details(scan_id), lambda details: details.info.status in [ Scan.STATUS_CANCELED, Scan.STATUS_COMPLETED, Scan. STATUS_EMPTY ]) client.scans_api.delete(scan_id)
def test_scanner_control_scan(client, fetch_scanner): template_list = client.editor_api.list('scan') assert len( template_list.templates) > 0, u'Expected at least one scan template.' test_templates = [t for t in template_list.templates if t.name == 'basic'] scan_id = client.scans_api.create( ScanCreateRequest( test_templates[0].uuid, ScanSettings('test_scanners_scan', TenableIOTestConfig.get('scan_text_targets'), scanner_id=fetch_scanner.id))) client.scans_api.launch(scan_id, ScanLaunchRequest()) scan = client.scans_api.details(scan_id) wait_until( lambda: client.scans_api.details(scan_id), lambda details: details.info.status in [Scan.STATUS_PENDING, Scan.STATUS_RUNNING, Scan.STATUS_INITIALIZING]) assert scan.info.status in [Scan.STATUS_PENDING, Scan.STATUS_INITIALIZING, Scan.STATUS_RUNNING], \ u'Scan is in launched state.' scan_details = wait_until( lambda: client.scans_api.details(scan_id), lambda details: details.info.status in [Scan.STATUS_RUNNING]) assert scan_details.info.status == Scan.STATUS_RUNNING, u'Scan should be running to test pause.' scan_list = client.scanners_api.get_scans(fetch_scanner.id) assert isinstance(scan_list, ScannerScanList), u'Get request returns type.' assert len(scan_list.scans) > 0, u'At least one test scan.' scan_uuid = scan.info.uuid test_scans = [s for s in scan_list.scans if s.id == scan_uuid] assert len(test_scans) == 1, u'Must contain test scan.' client.scanners_api.control_scans(fetch_scanner.id, scan_uuid, ScannerControlRequest(u'pause')) scan_details = wait_until( lambda: client.scans_api.details(scan_id), lambda details: details.info.status in [Scan.STATUS_PAUSED]) assert scan_details.info.status == Scan.STATUS_PAUSED, u'Scan is paused.'
# Establish the login session using our client API helper. client = TenableIOClient(access_key=accessKey, secret_key=secretKey) # Fetch a list of all scanners on the account and group them into a dictionary {scannerName: scannerId} scanners = {scanner.name: scanner.id for scanner in client.scanners_api.list().scanners} # Fetch a list of all folders on the account and group them into a dictionary {folderName: folderId} folders = {folder.name: folder.id for folder in client.folders_api.list().folders} # Fetch the template uuid to be used in our call to launch the scan. template = client.scan_helper.template(name=scanTemplate) # Create the scan and use the corresponding scanner id for the scanner name supplied scan_id = client.scans_api.create( ScanCreateRequest( template.uuid, ScanSettings( scanName, scanTarget, folder_id=folders[folderName], scanner_id=scanners[scannerName] ) ) ) # Get the scanRef object using the previously returned scan id scan = client.scan_helper.id(scan_id) # launch & download the scan result scan.launch().download('{}.nessus'.format(scanName), scan.histories()[0].history_id, format=ScanExportRequest.FORMAT_NESSUS)
def create_tenable_scan(**kwargs): """ Schedule scan job in Tenable.io account :param kwargs: list of arguments (see call function details) :return: datetime object """ # Assign arguments settings = kwargs['settings'][kwargs['scan_target']] client = kwargs['client'] logger = kwargs['logger'] scan_time = kwargs['scan_time'] # Scan name time part settings['policy'] = get_tenable_policy_uuid( client=client, policy_name=settings['policy_name']) settings['folder_id'] = get_tenable_folder_id( client=client, folder_name=settings['folder_name']) # Set correct ACLs acls = [{ 'display_name': settings['acl_name'], 'name': settings['acl_name'], 'id': settings['acl_id'], 'permissions': settings['acl_permissions'], 'type': 'group' }] targets, scan_time = get_composed_scan_jobs( projects=kwargs['target'], license_count=kwargs['settings']['TENABLE.IO']['license_count'], scan_settings=settings, scan_time=scan_time) # Create and launch scans in Tenable for target in targets: project = targets[target] # Set scan name scan_name = "{0}-{1}-{2}".format(targets[target]['starttime'], settings['name'], project['name']) # Set scan targets targets_list = [address['target'] for address in project['targets']] targets_str = ",".join(targets_list) settings['text_targets'] = targets_str # Create scan object scan_settings = ScanSettings(name=scan_name, emails=settings['emails'] if 'emails' in settings.keys() else False, enabled=settings['enabled'], starttime=targets[target]['starttime'], rrules=settings['rrules'], timezone=settings['timezone'], folder_id=settings['folder_id'], policy_id=settings['policy'].id, scanner_id=settings['scanner_id'], text_targets=targets_str, acls=acls) scan_request = ScanCreateRequest(uuid=settings['policy'].template_uuid, settings=scan_settings) client.scans_api.create(scan_request) logger.info("Successfully created scan {0}".format(scan_name)) return scan_time
def example(test_targets): # Generate unique name and file. scan_name = u'example scan' test_nessus_file = u'example_report.nessus' test_pdf_file = u'example_report.pdf' ''' Instantiate an instance of the TenableIOClient. ''' client = TenableIOClient() ''' Create a scan. ''' scan = client.scan_helper.create(name=scan_name, text_targets=test_targets, template='basic') assert scan.name() == scan_name ''' Retrieve a scan by ID. ''' scan_b = client.scan_helper.id(scan.id) assert scan_b is not scan assert scan_b.name() == scan_name ''' Select scans by name. ''' scans = client.scan_helper.scans(name=scan_name) assert scans[0].name() == scan_name ''' Select scans by name with regular expression. ''' scans = client.scan_helper.scans(name_regex=r'.*example scan.*') assert len(scans) > 0 ''' Launch a scan, then download when scan is completed. Note: The `download` method blocks until the scan is completed and the report is downloaded. ''' scan.launch().download(test_pdf_file) first_scan_history_id = min( [int(history.history_id) for history in scan.histories()]) assert os.path.isfile(test_pdf_file) os.remove(test_pdf_file) ''' Get hosts returned from scan ''' host_id = scan.details().hosts[0].host_id host_details = client.scans_api.host_details( scan.id, host_id=host_id).info.as_payload() assert host_details['host-fqdn'] == test_targets ''' Check if a target has recently been scanned (including running scans). ''' # Host IP is being used here because it is a more reliable field to search on. activities = client.scan_helper.activities(ipv4s=[host_details['host-ip']]) last_history_id = scan.last_history().history_id assert last_history_id in [a.history_id for a in activities] ''' Launch a scan, pause it, resume it, then stop it. ''' scan.launch().pause() assert scan.status() == Scan.STATUS_PAUSED scan.resume().stop() assert scan.status() == Scan.STATUS_CANCELED ''' Stop a running scan if it does not complete within a specific duration. ''' start = time() scan.launch().wait_or_cancel_after(10) assert time() - start >= 10 ''' Retrieve the history of a scan since a specific date or all. Note: The `since` argument is optional, all the history if omitted. ''' histories = scan.histories(since=datetime(2016, 12, 1)) assert len(histories) > 0 ''' Download the report for a specific scan in history. ''' scan.download(test_pdf_file, history_id=histories[0].history_id) assert os.path.isfile(test_pdf_file) os.remove(test_pdf_file) ''' Create a new scan by copying a scan. ''' scan_copy = scan.copy() assert scan_copy.id != scan.id assert scan_copy.status() == Scan.STATUS_EMPTY ''' Export a scan into a NESSUS file. ''' scan.download(test_nessus_file, history_id=first_scan_history_id, format=ScanExportRequest.FORMAT_NESSUS) assert os.path.isfile(test_nessus_file) ''' Create a new scan by importing a NESSUS file. ''' imported_scan = client.scan_helper.import_scan(test_nessus_file) assert imported_scan.details().info.name == scan.details().info.name os.remove(test_nessus_file) ''' Create a new scan using managed credentials. Note: First we must create a new managed credential ''' # Created managed credential for SSH test_user = client.users_api.list().users[0] test_permission = CredentialPermission( grantee_uuid=test_user.uuid, type=CredentialPermission.USER_TYPE, permissions=CredentialPermission.CAN_EDIT, name=test_user.username, isPending=True) credential_request = CredentialRequest( name='Lab SSH', description='SSH Credentials for Lab', type_='SSH', settings={ 'auth_method': 'password', 'elevate_privledges_with': 'Nothing', 'username': '******', 'password': '******' }, permissions=[test_permission]) credential_uuid = client.credentials_api.create(credential_request) credential_detail = client.credentials_api.details(credential_uuid) # Create scan settings settings = ScanSettings(name='Credentialed Scan', text_targets=test_targets) credentials = ScanCredentials(add=[credential_detail]) template_uuid = client.scan_helper.template('basic').uuid # Create Scan scan_request = ScanCreateRequest(uuid=template_uuid, settings=settings, credentials=credentials) scan_id = client.scans_api.create(scan_request) assert scan_id ''' Stop all scans. Note: Use with caution as this will stop all ongoing scans (including any automated test). ''' # client.scan_helper.stop_all() ''' Delete scans. ''' scan.delete() scan_copy.delete() imported_scan.delete() try: scan.details() assert False except TenableIOApiException: pass try: scan_copy.details() assert False except TenableIOApiException: pass try: imported_scan.details() assert False except TenableIOApiException: pass