Exemplo n.º 1
0
def security_center(request, vcr):
    '''
    test fixture for sc(security center)
    '''
    setup_logging_to_file()
    with vcr.use_cassette('sc_login',
                          filter_post_data_parameters=['username',
                                                       'password'
                                                       ]):
        tenable_security_center = TenableSC(
            os.getenv('SC_TEST_HOST', 'securitycenter.home.cugnet.net'),
            vendor='pytest',
            product='pytenable-automated-testing')
        tenable_security_center.login(
            os.getenv('SC_TEST_USER', 'username'),
            os.getenv('SC_TEST_PASS', 'password'))
        tenable_security_center.version  # noqa: PLW0104

    def teardown():
        try:
            with vcr.use_cassette('sc_login'):
                tenable_security_center.logout()
        except NotFoundError as error:
            log_exception(error)

    request.addfinalizer(teardown)
    return tenable_security_center
Exemplo n.º 2
0
def upload_file(target_filename):
    with open(target_filename, 'r') as myfile:
        sc = TenableSC(SC_HOST_IP)
        sc.login(access_key=access_key, secret_key=secret_key)
        file_uploaded = sc.files.upload(myfile)
        print(file_uploaded)
    return file_uploaded
Exemplo n.º 3
0
    def run(self):

        if len(sys.argv) != 3:
            print(
                "Usage: python2 sc-scan-webhook.py [scan ID] 'target list to add to message text sent in webhook'"
            )
            sys.exit(0)

        scanID = sys.argv[1]
        targetTXT = sys.argv[2]

        try:
            sc = TenableSC(self.ip)

            print("Logging in to SecurityCenter")
            response = sc.login(self.login, self.password)

            targets = targetTXT
            print('targets set: ' + targets)

            results = self.run_scan(sc, targets, scanID)

            sc.logout()

        except Exception as ex:
            print('Error: ' + str(ex))
Exemplo n.º 4
0
def tsc_login():
    try:
        sc = TenableSC(sc_address, port=sc_port)
        sc.login(access_key=sc_access_key, secret_key=sc_secret_key)
    except (NameError) as err:
        print("Please verify connection details.")
        exit()
    except (ConnectionError) as err:
        raise SystemExit(err)
    return sc
Exemplo n.º 5
0
def admin(request, vcr):
    with vcr.use_cassette('sc_login',
        filter_post_data_parameters=['username', 'password']):
        sc = TenableSC(os.getenv('SC_TEST_HOST', 'securitycenter.home.cugnet.net'))
        sc.login(
            os.getenv('SC_TEST_ADMIN_USER', 'admin'),
            os.getenv('SC_TEST_ADMIN_PASS', 'password'))
    def teardown():
        with vcr.use_cassette('sc_login'):
            sc.logout()
    request.addfinalizer(teardown)
    return sc
Exemplo n.º 6
0
 def connect(self):
     if self.host is not None and self.port is not None:
         if self.tio_access_key is not None and self.tio_secret_key is not None:
             self.tenable_connection = TenableIO(self.tio_access_key,
                                                 self.tio_secret_key)
             return self.tenable_connection
         elif self.tsc_username is not None and self.tsc_password is not None:
             self.tenable_connection = TenableSC(self.host, port=self.port)
             self.tenable_connection.login(self.tsc_username,
                                           self.tsc_password)
             return self.tenable_connection
     return False
Exemplo n.º 7
0
Arquivo: scan.py Projeto: barbich/navi
def bridge(un, pw, host, scanid, repoid, a, s):
    from tenable.sc import TenableSC

    sc = TenableSC(host)

    if un and pw:
        sc.login(un, pw)

    if a and s:
        sc.login(access_key=a, secret_key=s)

    try:
        click.echo("\nExporting your Scan ID: {} now\n".format(scanid))

        with open('{}.nessus'.format(str(scanid)), 'wb') as nessus:
            tio.scans.export(scanid, fobj=nessus)

        click.echo("Importing your Scan into Repo {} at https://{}\n".format(
            repoid, host))

        with open('{}.nessus'.format(str(scanid))) as file:
            sc.scan_instances.import_scan(file, repoid)

        # delete the scan
        os.remove('{}.nessus'.format(str(scanid)))
    except:
        pass

    sc.logout()
Exemplo n.º 8
0
def cli(ctx, verbose, tio_access_key, tio_secret_key, tsc_host, tsc_port,
        tsc_username, tsc_password, tsc_access_key, tsc_secret_key):
    '''
    Tenable Command-Line Interface (Tenable-CLI)
    '''
    # Setup the logging verbosity.
    log_fmt = '%(asctime)-15s %(message)s'
    if verbose == 0:
        logging.basicConfig(level=logging.WARNING, format=log_fmt)
    if verbose == 1:
        logging.basicConfig(level=logging.INFO, format=log_fmt)
    if verbose > 1:
        logging.basicConfig(level=logging.DEBUG, format=log_fmt)

    # Setup the context object
    ctx.ensure_object(dict)
    ctx.obj['tio'] = None
    ctx.obj['tsc'] = None

    # If the Tenable.io Secret Keys and Access Keys are passed, we will then
    # instantiate the TenableIO object
    if tio_access_key and tio_secret_key:
        ctx.obj['tio'] = TenableIO(access_key=tio_access_key,
                                   secret_key=tio_secret_key,
                                   vendor='Tenable',
                                   product='TenableCLI',
                                   build=__version__)

    # If the Tenable.sc parameters are specified with User Auth, then we will
    # instantiate the TenableSC object and login using user-auth.
    if tsc_host and tsc_port and tsc_username and tsc_password:
        ctx.obj['tsc'] = TenableSC(address=tsc_host,
                                   port=tsc_port,
                                   vendor='Tenable',
                                   product='TenableCLI',
                                   build=__version__)
        ctx.obj['tsc'].login(tsc_username, tsc_password)

    # if the Tenable.sc parameters are specified with API keys, then we will
    # instantiate the TenableSC object and use the API keys for keyed auth.
    elif tsc_host and tsc_port and tsc_access_key and tsc_secret_key:
        ctx.obj['tsc'] = TenableSC(address=tsc_host,
                                   port=tsc_port,
                                   access_key=tsc_access_key,
                                   secret_key=tsc_secret_key,
                                   vendor='Tenable',
                                   product='TenableCLI',
                                   build=__version__)
Exemplo n.º 9
0
def sc(request, vcr):
    with vcr.use_cassette('sc_login',
                          filter_post_data_parameters=['username',
                                                       'password']):
        sc = TenableSC(os.getenv('SC_TEST_HOST',
                                 'securitycenter.home.cugnet.net'),
                       vendor='pytest',
                       product='pytenable-automated-testing')
        sc.login(os.getenv('SC_TEST_USER', 'username'),
                 os.getenv('SC_TEST_PASS', 'password'))

    def teardown():
        with vcr.use_cassette('sc_login'):
            sc.logout()

    request.addfinalizer(teardown)
    return sc
Exemplo n.º 10
0
def unauth(request, vcr):
    with vcr.use_cassette('sc_login',
                          filter_post_data_parameters=['username',
                                                       'password']):
        sc = TenableSC(os.getenv('SC_TEST_HOST',
                                 'securitycenter.home.cugnet.net'),
                       vendor='pytest',
                       product='pytenable-automated-testing')
    return sc
Exemplo n.º 11
0
def test_init_connection_error():
    '''
    test init for connection error
    '''
    with pytest.raises(RequestsConnectionError):
        TenableSC(host='nothing_here',
                  username='******',
                  password='******',
                  vendor='pytest',
                  product='pytenable-automated-testing')
def verify_ip_address(ip_address):
    while True:
        try:
            sc = TenableSC(ip_address)
            return sc
        except:
            ip_address = input(
                "You have provided wrong Tenable.sc IP address, please provide the correct IP: "
            )
        else:
            break
Exemplo n.º 13
0
def ConnectSC(DEBUG, username, password, host, port):
    #Create the connection to Tenable.sc
    try:
        sc = TenableSC(host, port=port)
    except:
        print("Error connecting to SecurityCenter",
              sys.exc_info()[0],
              sys.exc_info()[1])
        return (False)

    try:
        sc.login(username, password)
    except:
        print("Error logging into to SecurityCenter",
              sys.exc_info()[0],
              sys.exc_info()[1])
        if DEBUG:
            print("Username:", username)
        return (False)

    return (sc)
Exemplo n.º 14
0
def get_info():
    # Set User data
    hostname = ""
    username = ""
    password = ""

    # Set SC object
    sc = TenableSC(hostname)

    # login to SC
    sc.login(username, password)

    # Get data
    # check Development tools in chrome -> Network tab --> Under Name, choose analysis --> Headers tab --> Request Payload
    # EXAMPLE: sc.analysis.vulns(('pluginID', '=', '19506'), ('firstSeen', '=', '0:60'),('repository','=',[{"id" : "1"}]), tool='sumip')

    current_devices = []

    for device in sc.analysis.vulns(('lastSeen', '=', '0:30'), tool='sumip'):
        current_devices.append(device)

    # logout of SC
    sc.logout()

    return render_template('index.html', current_devices=current_devices)
Exemplo n.º 15
0
def unauth(vcr):
    '''
    test fixture for un_authorization
    '''
    with vcr.use_cassette('sc_login',
                          filter_post_data_parameters=['username',
                                                       'password'
                                                       ]):
        sc = TenableSC(  # noqa: PLC0103
            os.getenv('SC_TEST_HOST', 'securitycenter.home.cugnet.net'),
            vendor='pytest',
            product='pytenable-automated-testing')
    return sc
Exemplo n.º 16
0
def admin(request, vcr):
    '''
    test fixture for admin
    '''
    with vcr.use_cassette('sc_login',
                          filter_post_data_parameters=['username',
                                                       'password'
                                                       ]):
        sc = TenableSC(  # noqa: PLC0103
            os.getenv('SC_TEST_HOST', 'securitycenter.home.cugnet.net'),
            vendor='pytest',
            product='pytenable-automated-testing')
        sc.login(
            os.getenv('SC_TEST_ADMIN_USER', 'admin'),
            os.getenv('SC_TEST_ADMIN_PASS', 'password'))
        sc.version  # noqa: PLW0104

    def teardown():
        with vcr.use_cassette('sc_login'):
            sc.logout()

    request.addfinalizer(teardown)
    return sc
Exemplo n.º 17
0
def main():
    hostip = '<IP>'
    username = '******'
    password = '******'

    sc = TenableSC(hostip)
    sc.login(username, password)

    for item in sc.get('scanResult').json()['response']['manageable']:
        if 'Running' in item['status']:
            print('{id}: {name}'.format(**item))

    sc.logout()
def main():
    # create an instance of the API and login
    sc = TenableSC(SC_HOST_IP)
    sc.login(access_key=sc_accessKey, secret_key=sc_secretKey)

    # run the diagnostic scan
    scan_result_id = sc.scans.launch(id=active_scan_id, diagnostic_target=target_ip,
                                     diagnostic_password=diagnostic_password)['scanResult']['id']
    print(f"Launched diagnostic scan run of Active Scan {active_scan_id}, with Scan Result ID {scan_result_id}.")

    # wait until the scan is finished
    wait_time_seconds = 0
    while wait_time_seconds < SCAN_MAX_WAIT_SECONDS:
        if is_scan_completed(sc, scan_result_id):
            print(f"Scan finished running after waiting {wait_time_seconds} seconds.")
            break
        else:
            print(f"Waited {wait_time_seconds} seconds, scan is still running.")
            time.sleep(SCAN_REFRESH_DELAY_SECONDS)
            wait_time_seconds += SCAN_REFRESH_DELAY_SECONDS

    if wait_time_seconds > SCAN_MAX_WAIT_SECONDS:
        print("ERROR: Script timed out waiting for the scan to complete.")
        exit(-1)
Exemplo n.º 19
0
def test_sc_compile(security_center):
    '''
    test to raise the exception when host is invalid, hence the connection wont be made
    '''

    try:
        TenableSC(host='127.0.0.1')
        AcceptRiskAPI(security_center)
        AlertAPI(security_center)
        AnalysisResultsIterator(security_center)
        AnalysisAPI(security_center)
        AssetListAPI(security_center)
        AuditFileAPI(security_center)
        SCEndpoint(security_center)
        SCResultsIterator(security_center)
        CredentialAPI(security_center)
        CurrentSessionAPI(security_center)
        FeedAPI(security_center)
        FileAPI(security_center)
        GroupAPI(security_center)
        OrganizationAPI(security_center)
        PluginAPI(security_center)
        PluginResultsIterator(security_center)
        ScanPolicyAPI(security_center)
        QueryAPI(security_center)
        RecastRiskAPI(security_center)
        RepositoryAPI(security_center)
        RoleAPI(security_center)
        ScanResultAPI(security_center)
        ScanZoneAPI(security_center)
        ScannerAPI(security_center)
        ScanAPI(security_center)
        StatusAPI(security_center)
        SystemAPI(security_center)
        UserAPI(security_center)

    except NameError as error:
        print("\n The following name error exists: {}".format(error))
        pytest.raises(NameError)
        assert True
    except ConnectionError as error:
        print("\n The following connection error exists: {}".format(error))
        pytest.raises(ConnectionError)
        assert True
    except TypeError as error:
        print("\n The following type error exists: {}".format(error))
        assert True
    def run(self):
        Analyzer.run(self)

        if self.data_type != 'ip' and self.data_type != 'fqdn':
            self.error('Invalid data type')

        try:
            sc = TenableSC(self.ip)
            sc.login(self.login, self.password)

            results = self._run_scan(sc)

            sc.logout()

        except Exception as ex:
            self.error('Error: %s' % ex)

        self.report(results)
Exemplo n.º 21
0
try:
    if args.tsc_port[0] != "":
        tsc_port = args.tsc_port[0]
except:
    pass

try:
    import_repo = int(args.import_repo[0])
except:
    print("Invalid repo ID")
    exit(-1)

# Create the connection to whatever platform has been specified.
conn = connector.connect()
sc = TenableSC(tsc_host, port=tsc_port)
sc.login(tsc_username, tsc_password)

if conn is False:
    print("Unable to connect.")
    exit(-1)

scan_list = connector.list_scans()
if scan_list is False:
    print("Could not get scan list.")
    exit(-1)

for scan in scan_list:
    if connector.export_scan(scan['id']) is True:
        print("Uploading file to Tenable.sc repo ID",import_repo)
        with open(str(scan['id'])+".nessus") as nessus_file:
Exemplo n.º 22
0
"""
The tag you want to delete is the first argument on the command line.  For example: rm_dyn_ls.py acme
"""
tagg = sys.argv[1]

"""
Put access key in file called acc.key.  Just the key, one line. Don't press enter.  Just save.
Put secret key in a file called sec.key.  Just the key, one line.
The next 2 lines read your access and secret keys so you don't have to expose them in your code.
"""

accesskey = open('acc.key').read().strip()
secretkey = open('sec.key').read().strip()

sc = TenableSC('127.0.0.1', port=8443)
sc.login(access_key = accesskey, secret_key = secretkey)

"""
Read manageable asset lists into sclist then obtain the length of the list and assign it to total.  total will be the range 
    for our inner loop.  We use i to count and compare to total so we know when to break out of the loop.
    We loop through sclist to obtain the asset list id, then use the id in the call to sc.asset_lists.details() to get that list's
    tag.  tag is not in sc.asset_lists so we have to make the call to the .details method.
    Once we have identified an asset list with the target tag, we call the .delete() method and pass it the id.
You can also us the usable asset lists as well.... but it seems that manageable asset lists are a super set.
    manageable = read write
    usable = read only
"""
i = 0

"""
def run_module():

    module_args = dict(
        asset_name=dict(type='str', required=True),
        asset_type=dict(type='str', required=True),
        targets=dict(type='str', required=False, default='.*'),
        file_location=dict(type='str', required=True),
        server=dict(type='str', required=True),
        nessus_username=dict(type='str', required=True),
        nessus_password=dict(type='str', required=True)
        )

    result = dict(
        changed=False,
        original_message='',
        message=''
    )

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )


    if not HAS_PYTENABLE:
        module.fail_json(msg = 'pyTenable required. pip install pytenable')

    if not HAS_PANDAS:
        module.fail_json(msg = 'Pandas required. pip install panda')


    if module.check_mode:
        module.exit_json(**result)


    asset_name = module.params['asset_name']
    asset_type = module.params['asset_type']
    targets = module.params['targets']
    file_location = module.params['file_location']
    server = module.params['server']
    nessus_username = module.params['nessus_username']
    nessus_password = module.params['nessus_password']


    try:
        sc = TenableSC(server)
        sc.login(nessus_username, nessus_password)
    except:
        module.fail_json(msg='Issues connecting to Nessus.sc. Please check connectivity and credetials')

    try:
        df = pd.read_csv(file_location,low_memory=False)
    except:
        module.fail_json(msg='Issues loading CSV file' + file_location)


    asset_list = sc.asset_lists.list()['usable']
    asset_id = [item for item in asset_list if item["name"] == asset_name]

    # overwrite existing asset list
    if asset_id:
        sc.asset_lists.delete(int(asset_id[0]['id']))


    if asset_type.lower() == 'dns':
        host_list = list(df[df['hostname'].str.contains(pat=targets)]['hostname'])

        try:
            sc.asset_lists.create(asset_name,list_type='dnsname',dns_names=host_list)
        except:
            module.fail_json(msg="Error creating Nessus asset list [" + asset_name + "]")

    elif asset_type.lower() == 'ip':
        ip_list = list(df[df['ip'].str.contains(pat=targets)]['ip'])

        try:
            sc.asset_lists.create(asset_name,list_type='static',ips=ip_list)
        except:
            module.fail_json(msg="Error creating Nessus asset list [" + asset_name + "]")



    result['changed'] = True
    result['output'] = "Nessus.sc Asset list name: [" + asset_name + "]"

    module.exit_json(**result)
Exemplo n.º 24
0
def dnp3_TCP_header_probe(**kwargs):

    sc = TenableSC(CONFIG['tenable_ip'], port=CONFIG['tenable_port'])
    try:
        sc.login(CONFIG['tenable_username'], CONFIG['tenable_password'])
    except tenable_errors.APIError as APIerror:
        _log.debug("Tenable API error: " + str(APIerror))
        return {
            'TARGET_IPADDR': kwargs['TARGET_IPADDR'],
            'SCAN_NAME': 'dnp3_TCP_header_probe',
            'SCAN_RESULT': -1,
            'SCAN_RESULT_DESC': json.loads(APIerror.response.text)['error_msg']
        }

    sc.scans.edit(1, targets=[kwargs['TARGET_IPADDR']])
    running = sc.scans.launch(1)
    scan_results_id = int(running['scanResult']['id'])
    scan_status = sc.scan_instances.details(scan_results_id, fields=['status'])
    while scan_status['status'] != 'Completed':
        time.sleep(15)
        scan_status = sc.scan_instances.details(scan_results_id,
                                                fields=['status'])
        if scan_status['status'] == 'Partial' or scan_status[
                'status'] == 'Error':
            scan_error = sc.scan_instances.details(scan_results_id,
                                                   fields=['errorDetails'])
            return {
                'TARGET_IPADDR': kwargs['TARGET_IPADDR'],
                'SCAN_NAME': 'dnp3_TCP_header_probe',
                'SCAN_RESULT': -1,
                'SCAN_RESULT_DESC': str(scan_error)
            }

    time.sleep(15)  # Give Tenable.sc some time to generate scan results

    filename = str(scan_results_id) + "_" + str(
        kwargs['TARGET_IPADDR']) + "tcp_scan_data.zip"
    unzipped_filename = str(scan_results_id) + ".nessus"

    with open(filename, 'wb') as fobj:
        sc.scan_instances.export_scan(scan_results_id, fobj)

    if zipfile.is_zipfile(filename):
        with zipfile.ZipFile(filename, 'r') as zipf:
            zipf.extractall("./")

        mydoc = minidom.parse(unzipped_filename)

    else:
        mydoc = minidom.parse(filename)

    report_items = mydoc.getElementsByTagName('ReportItem')
    results = dict.fromkeys([
        'TARGET_IPADDR', 'SCAN_NAME', 'TTL', 'WINDOW', 'SCALE', 'SACK',
        'TIMESTAMP', 'TCP_SIG', 'SCAN_RESULT', 'SCAN_RESULT_DESC'
    ])

    results['TARGET_IPADDR'] = kwargs['TARGET_IPADDR']
    results['SCAN_NAME'] = 'dnp3_TCP_header_probe'

    plugin_found = False
    for elem in report_items:
        if elem.attributes['pluginID'].value == '999999':
            plugin_found = True
            plugin_output = elem.getElementsByTagName(
                'plugin_output')[0].childNodes[0].data
            sig = plugin_output.split("Signature:")[1].lstrip().rstrip()

    if plugin_found:
        results['SCAN_RESULT'] = 1
        results['SCAN_RESULT_DESC'] = 'Success'
        new_sig = sig.split(':')[1:3] + sig.split(':')[4:]
        results['TCP_SIG'] = ':'
        for part in new_sig:
            results['TCP_SIG'] = results['TCP_SIG'] + part + ':'

        results['TCP_SIG'] = results['TCP_SIG'][:-1]
        results['TTL'] = sig.split(':')[3]
        results['WINDOW'] = sig.split(':')[4]
        if 'W' in sig.split(':')[5]:
            results['SCALE'] = sig.split(':')[6]
        else:
            results['SCALE'] = 'N'
        if 'S' in sig.split(':')[5]:
            results['SCALE'] = 'Y'
        else:
            results['SACK'] = 'N'
        if 'T' in sig.split(':')[5]:
            results['TIMESTAMP'] = 'Y'
        else:
            results['TIMESTAMP'] = 'N'

    os.remove(filename)
    os.remove(unzipped_filename)

    return results
Exemplo n.º 25
0
def snmp_device_info(**kwargs):

    sc = TenableSC(CONFIG['tenable_ip'], port=CONFIG['tenable_port'])
    try:
        sc.login(CONFIG['tenable_username'], CONFIG['tenable_password'])
    except tenable_errors.APIError as APIerror:
        _log.error("Tenable API error: " + str(APIerror))
        return {
            'TARGET_IPADDR': kwargs['TARGET_IPADDR'],
            'SCAN_NAME': 'snmp_device_info',
            'SCAN_RESULT': -1,
            'SCAN_RESULT_DESC': json.loads(APIerror.response.text)['error_msg']
        }

    sc.scans.edit(3, targets=[kwargs['TARGET_IPADDR']])
    running = sc.scans.launch(3)
    scan_results_id = int(running['scanResult']['id'])
    scan_status = sc.scan_instances.details(scan_results_id, fields=['status'])
    while scan_status['status'] != 'Completed':
        time.sleep(15)
        scan_status = sc.scan_instances.details(scan_results_id,
                                                fields=['status'])
        if scan_status['status'] == 'Partial' or scan_status[
                'status'] == 'Error':
            scan_error = sc.scan.instances.details(scan_results_id,
                                                   fields=['errorDetails'])
            return {
                'TARGET_IPADDR': kwargs['TARGET_IPADDR'],
                'SCAN_NAME': 'snmp_device_info',
                'SCAN_RESULT': -1,
                'SCAN_RESULT_DESC': str(scan_error)
            }

    time.sleep(15)  # Give Tenable.sc some time to generate scan results

    filename = str(scan_results_id) + "_" + str(
        kwargs['TARGET_IPADDR']) + "tcp_scan_data.zip"
    unzipped_filename = str(scan_results_id) + ".nessus"

    with open(filename, 'wb') as fobj:
        sc.scan_instances.export_scan(scan_results_id, fobj)

    if zipfile.is_zipfile(filename):
        with zipfile.ZipFile(filename, 'r') as zipf:
            zipf.extractall("./")

        mydoc = minidom.parse(unzipped_filename)

    else:
        mydoc = minidom.parse(filename)

    report_items = mydoc.getElementsByTagName('ReportItem')
    results = dict.fromkeys([
        'TARGET_IPADDR', 'SCAN_NAME', 'VENDOR', 'MODEL', 'SCAN_RESULT',
        'SCAN_RESULT_DESC'
    ])

    found_known_device = False
    for elem in report_items:
        if elem.attributes['pluginID'].value == '10800':
            plugin_output = elem.getElementsByTagName(
                'plugin_output')[0].childNodes[0].data
            for line in plugin_output.split('\n'):
                #TODO: Refactor this to use utils.py with a dictionary of values associated with searchable strings
                if '7UT613' in line:
                    found_known_device = True
                    results['MODEL'] = '7UT613'
                    results['VENDOR'] = 'siemens'
                if '7SJ64' in line:
                    found_known_device = True
                    results['MODEL'] = '7SJ64'
                    results['VENDOR'] = 'siemens'

    if found_known_device == True:
        results['SCAN_RESULTS'] = 1
        results['SCAN_RESULTS_DESC'] = 'Success'
    else:
        results['SCAN_RESULTS'] = 0
        results[
            'SCAN_RESULTS_DESC'] = 'Could not determine identity of device at {} from SNMP device info'.format(
                kwargs['TARGET_IPADDR'])

    results['TARGET_IPADDR'] = kwargs['TARGET_IPADDR']
    results['SCAN_NAME'] = 'snmp_device_info'

    os.remove(filename)
    os.remove(unzipped_filename)

    return results
Exemplo n.º 26
0
#!/usr/bin/env python3
#Disclaimer: This is NOT supported By Tenable!
#This script reaches out to Tenable IO and pulls down all of the current IPs of any Agent
#Then pushes those IPs into a Static IP address list in Security Center.
from tenable.sc import TenableSC
from tenable.io import TenableIO

sc = TenableSC("")
sc.login("", "")

tio = TenableIO(access_key='', secret_key='')


#Get Agent IPs from Tenable.io
def get_ips():
    #great an empty list
    list = []
    for agent in tio.agents.list():
        ip = agent['ip']
        list.append(ip)
    return list


def get_or_create():

    #load all of the current asset lists for parsing
    asset_lists = sc.asset_lists.list()

    #grab the latest agent IPs from Tenable.io
    list = get_ips()
Exemplo n.º 27
0
# -*- coding: utf-8 -*-
"""
Ed Matthews  
10-9-19

Tenable python connection test
"""

from tenable.sc import TenableSC
sc = TenableSC('insert your tenable url here')
sc.login('login', 'password')
for vuln in sc.analysis.vulns():
    ('listos', '=', 'Windows')
    # Change above OS
    print(vuln)
Exemplo n.º 28
0
#!/usr/bin/env python3
#Disclaimer: This is NOT supported By Tenable!
#This script pull the licensing information from SC
from tenable.sc import TenableSC
sc = TenableSC("1.1.1.1")
sc.login("admin", "password")

def status_Check():
    sc_license = sc.status.status()
    active_ips = sc_license['activeIPs']
    licensed_ips = sc_license['licensedIPs']
    utilization = int(100 * int(active_ips) / int(licensed_ips))

    print("Your License Status")
    print("-------------------")
    print("Your Purchased license for this SC is : {} ".format(licensed_ips))
    print("Your License Usage is : {} ".format(active_ips))
    print("Your current utilization is : {}% ".format(utilization))

if __name__ == '__main__':
    status_Check()
Exemplo n.º 29
0
def test_log_in(vcr):
    '''
    test log in
    '''
    tsc = TenableSC(url='https://localhost')
    tsc._version = '5.12.0'
    with pytest.raises(ConnectionError):
        tsc.login(access_key='access_key', secret_key='secret_key')

    tsc._version = '5.14.0'
    tsc.login(access_key='access_key', secret_key='secret_key')
    assert tsc._auth_mech == 'keys'

    tsc._version = None
    tsc._auth_mech = None
    with vcr.use_cassette('sc_login_5_20_0'):
        tsc.login(access_key='access_key', secret_key='secret_key')
        assert tsc._auth_mech == 'keys'
Exemplo n.º 30
0
def cli(configfile, observed_since, setup_only=False, troubleshoot=False):
    '''
    Tenable.io -> Jira Cloud Transformer & Ingester
    '''
    config_from_file = yaml.load(configfile, Loader=yaml.Loader)
    config = dict_merge(base_config(), config_from_file)

    # Get the logging definition and define any defaults as need be.
    log = config.get('log', {})
    log_lvls = {'debug': 10, 'info': 20, 'warn': 30, 'error': 40}
    log['level'] = log_lvls[log.get('level', 'warn')]
    log['format'] = log.get(
        'format', '%(asctime)-15s %(name)s %(levelname)s %(message)s')

    # Configure the root logging facility
    if troubleshoot:
        logging.basicConfig(level=logging.DEBUG,
                            format=log['format'],
                            filename='tenable_debug.log')
    else:
        logging.basicConfig(**log)

    # Output some basic information detailing the config file used and the
    # python version & system arch.
    logging.info('Tenable2JiraCloud Version {}'.format(__version__))
    logging.info('Using configuration file {}'.format(configfile.name))
    uname = platform.uname()
    logging.info('Running on Python {} {}/{}'.format(
        '.'.join([str(i) for i in sys.version_info][0:3]), uname[0],
        uname[-2]))

    # instantiate the Jira object
    jira = Jira('https://{}/rest/api/3'.format(config['jira']['address']),
                config['jira']['api_username'], config['jira']['api_token'])

    # Initiate the Tenable.io API model, the Ingester model, and start the
    # ingestion and data transformation.
    if config['tenable'].get('platform') == 'tenable.io':
        source = TenableIO(access_key=config['tenable'].get('access_key'),
                           secret_key=config['tenable'].get('secret_key'),
                           vendor='Tenable',
                           product='JiraCloud',
                           build=__version__)
    elif config['tenable'].get('platform') == 'tenable.sc':
        source = TenableSC(config['tenable'].get('address'),
                           port=int(config['tenable'].get('port', 443)),
                           username=config['tenable'].get('username'),
                           password=config['tenable'].get('password'),
                           access_key=config['tenable'].get('access_key'),
                           secret_key=config['tenable'].get('secret_key'),
                           vendor='Tenable',
                           product='JiraCloud',
                           build=__version__)
    else:
        logging.error('No valid Tenable platform configuration defined.')
        exit(1)
    ingest = Tio2Jira(source, jira, config)

    if troubleshoot:
        # if the troubleshooting flag is set, then we will be collecting some
        # basic information and outputting it to the screen in a format that
        # Github issues would expect to format it all pretty.  This should help
        # reduce the amount of time that is spent with back-and-forth debugging.
        try:
            ingest.ingest(observed_since)
        except:
            logging.exception('Caught the following Exception')

        # Some basic redaction of sensitive data, such as API Keys, Usernames,
        # Passwords, and hostnames.
        addr = config_from_file['jira']['address']
        sc_addr = 'NOTHING_TO_SEE_HERE_AT_ALL'
        config_from_file['jira']['address'] = '<REDACTED>'
        config_from_file['jira']['api_token'] = '<REDACTED>'
        config_from_file['jira']['api_username'] = '******'
        config_from_file['project']['leadAccountId'] = '<REDACTED>'
        if config_from_file['tenable'].get('address'):
            sc_addr = config_from_file['tenable']['address']
            config_from_file['tenable']['address'] = '<REDACTED>'
        if config_from_file['tenable'].get('access_key'):
            config_from_file['tenable']['access_key'] = '<REDACTED>'
        if config_from_file['tenable'].get('secret_key'):
            config_from_file['tenable']['secret_key'] = '<REDACTED>'
        if config_from_file['tenable'].get('username'):
            config_from_file['tenable']['username'] = '******'
        if config_from_file['tenable'].get('password'):
            config_from_file['tenable']['password'] = '******'

        output = troubleshooting.format(
            configfile=yaml.dump(config_from_file, default_flow_style=False),
            logging=open('tenable_debug.log').read() \
                .replace(addr, '<JIRA_CLOUD_HOST>') \
                .replace(sc_addr, '<TENABLE_SC_HOST>'),
            issuetypes='\n'.join(
                [
                    '{id}: {name}'.format(**a)
                    for a in jira.issue_types.list()
                    if a.get('name').lower() in ['task', 'subtask', 'sub-task']
                ]
            )
        )
        print(output)
        print('\n'.join([
            '/-------------------------------NOTICE-----------------------------------\\',
            '| The output above is helpful for us to troubleshoot exactly what is     |',
            '| happening within the code and offer a diagnosis for how to correct.    |',
            '| Please note that while some basic redaction has already been performed |',
            '| that we ask you to review the information you\'re about to send and     |',
            '| ensure that nothing deemed sensitive is transmitted.                   |',
            '| ---------------------------------------------------------------------- |',
            '| -- Copy of output saved to "issue_debug.md"                            |',
            '\\------------------------------------------------------------------------/'
        ]))
        with open('issue_debug.md', 'w') as reportfile:
            print(output, file=reportfile)
        os.remove('tenable_debug.log')
    elif not setup_only:
        ingest.ingest(observed_since)

        # If we are expected to continually re-run the transformer, then we will
        # need to track the passage of time and run every X hours, where X is
        # defined by the user in the configuration.
        if config.get('service', {}).get('interval', 0) > 0:
            sleeper = int(config['service']['interval']) * 3600
            while True:
                last_run = int(time.time())
                logging.info('Sleeping for {}h'.format(sleeper / 3600))
                time.sleep(sleeper)
                logging.info('Initiating ingest with observed_since={}'.format(
                    last_run))
                ingest.ingest(last_run)
    elif setup_only:
        # In setup-only mode, the ingest will not run, and instead a config file
        # will be generated that will have all of the JIRA identifiers baked in
        # and will also inform the integration to ignore the screen builder.
        # When using this config, if there are any changes to the code, then
        # this config will need to be re-generated.
        config['screen']['no_create'] = True
        logging.info('Set to setup-only.  Will not run ingest.')
        logging.info(
            'The following is the updated config file from the setup.')
        with open('generated_config.yaml', 'w') as outfile:
            outfile.write(yaml.dump(config, Dumper=yaml.Dumper))
        logging.info('Generated "generated_config.yaml" config file.')
        logging.info(
            'This config file should be updated for every new version of this integration.'
        )