Пример #1
0
 def test_client_smoke_fails_non_topic_mocked(self, mock_post, mock_get):
     client = query_client.OpenVulnQueryClient(CLIENT_ID,
                                               CLIENT_SECRET,
                                               REQUEST_TOKEN_URL,
                                               user_agent='foo')
     self.assertRaises(KeyError, client.get_by,
                       'let_this_topic_be_non_existing', None, None, **{})
Пример #2
0
def periodic_check():
    """ 
    This function will run inside a loop and check if psirt database has changed at an interval defined by background scheduler
    """
    logger.debug(f"checking psirt for updates")

    # check timedelta of most recent 5 alerts and send alert if newer than last 1hr
    psirt_query = query_client.OpenVulnQueryClient(
        client_id=config.credentials.get("CLIENT_ID"),
        client_secret=config.credentials.get("CLIENT_SECRET"),
    )
    advisories = psirt_query.get_by_latest(adv_format="default", latest=20)

    for advisory in advisories:
        logger.debug(f"advisory last_updated: {advisory.last_updated}")
        advisory_date = date_from_string(advisory.last_updated)

        print("advisory date: ", advisory_date)
        print("now      date: ", datetime.now())

        advisory_time_delta = (datetime.now() - advisory_date).total_seconds()
        if advisory_time_delta <= 3600:
            logger.info(
                f"timedelta is less than 1 hr: {advisory_time_delta} - sending alert"
            )
            full_message = construct_message_alert(advisory)
            bot.alert_subscribers(full_message)
        else:
            logger.debug(
                f"timedelta is greater than 1 hr since last_update: {advisory_time_delta}"
            )

    # update the cache after peridoic check
    notification_cache(advisories[0])
def main():
    ovq_client = query_client.OpenVulnQueryClient(CLIENT_ID, CLIENT_SECRET)

    with open("data.dmp", "rb") as input_file:
        platform_ibj_list = pickle.load(input_file)

    print_dictionary(build_dictionary(ovq_client, platform_ibj_list))
Пример #4
0
 def test_client_smoke_init_succeeds_mocked(self, mock_post):
     client = query_client.OpenVulnQueryClient(CLIENT_ID,
                                               CLIENT_SECRET,
                                               REQUEST_TOKEN_URL,
                                               user_agent='foo')
     self.assertIsInstance(client, query_client.OpenVulnQueryClient)
     self.assertEqual(client.auth_token,
                      OAUTH2_RESPONSE_BOGUS_BUT_OK['access_token'])
     self.assertEqual(client.auth_url, REQUEST_TOKEN_URL)
Пример #5
0
 def test_client_cvrf_all_succeeds_mocked(self, mock_post, mock_get):
     client = query_client.OpenVulnQueryClient(CLIENT_ID,
                                               CLIENT_SECRET,
                                               REQUEST_TOKEN_URL,
                                               user_agent='foo')
     sample_all = 'all'
     advisories_as_cvrf = client.get_by(
         'all',
         format=constants.CVRF_ADVISORY_FORMAT_TOKEN,
         aspect=sample_all,
         a_filter=query_client.Filter())
     self.assertTrue(len(advisories_as_cvrf) == 1)
     cvrf_first = advisories_as_cvrf[0]
     self.assertIsInstance(cvrf_first, advisory.CVRF)
Пример #6
0
 def test_client_cvrf_succeeds_product_mocked(self, mock_post, mock_get):
     client = query_client.OpenVulnQueryClient(CLIENT_ID,
                                               CLIENT_SECRET,
                                               REQUEST_TOKEN_URL,
                                               user_agent='foo')
     advisories_as_cvrf = client.get_by(
         'product',
         format=constants.CVRF_ADVISORY_FORMAT_TOKEN,
         aspect=SAMPLE_PRODUCT,
         **{'a_filter': None})
     self.assertTrue(len(advisories_as_cvrf) == 1)
     cvrf_first = advisories_as_cvrf[0]
     self.assertIsInstance(cvrf_first, advisory.CVRF)
     self.assertIn(SAMPLE_PRODUCT, cvrf_first.product_names)
Пример #7
0
 def test_client_cvrf_succeeds_cve_mocked(self, mock_post, mock_get):
     client = query_client.OpenVulnQueryClient(CLIENT_ID,
                                               CLIENT_SECRET,
                                               REQUEST_TOKEN_URL,
                                               user_agent='foo')
     advisories_as_cvrf = client.get_by(
         'cve',
         format=constants.CVRF_ADVISORY_FORMAT_TOKEN,
         aspect=SAMPLE_CVE,
         **{'a_filter': None})
     self.assertTrue(len(advisories_as_cvrf) == 1)
     cvrf_first = advisories_as_cvrf[0]
     self.assertIsInstance(cvrf_first, advisory.CVRF)
     self.assertEqual(cvrf_first.cves, CVES_EXPECTED)
Пример #8
0
 def test_client_cvrf_succeeds_advisory_mocked(self, mock_post, mock_get):
     client = query_client.OpenVulnQueryClient(CLIENT_ID,
                                               CLIENT_SECRET,
                                               REQUEST_TOKEN_URL,
                                               user_agent='foo')
     advisories_as_cvrf = client.get_by(
         'advisory',
         format=constants.CVRF_ADVISORY_FORMAT_TOKEN,
         aspect='non_existing_aspect_on_server',
         **{'a_filter': None})
     self.assertTrue(len(advisories_as_cvrf) == 1)
     cvrf_first = advisories_as_cvrf[0]
     self.assertIsInstance(cvrf_first, advisory.CVRF)
     self.assertEqual(cvrf_first.advisory_id, mock_response['advisoryId'])
Пример #9
0
def get_latest_advisories(room_id, product="cisco", count=5):
    api.messages.create(
        roomId=room_id,
        markdown=f"One moment please while I retrieve the last {count} alerts",
    )
    psirt_query = query_client.OpenVulnQueryClient(
        client_id=config.credentials.get("CLIENT_ID"),
        client_secret=config.credentials.get("CLIENT_SECRET"),
    )
    advisories = psirt_query.get_by_latest(adv_format="default", latest=count)

    for advisory in advisories:
        full_message = construct_message_alert(advisory)
        api.messages.create(roomId=room_id, markdown=full_message)

    return True
Пример #10
0
def worker():
    """Obtains host version by SNMP, then queries Cisco Openvuln API"""
    global query_client
    query_client = query_client.OpenVulnQueryClient(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    for address in address_ipv4:
        address = str(address[0])
        result = get(address, ['1.3.6.1.2.1.1.1.0'], snmp_community)
        sysdescr = sysdescrparser(result['1.3.6.1.2.1.1.1.0'])

        print('HOST: %s; vendor: %s; model: %s; version: %s' % (address, sysdescr.vendor, sysdescr.model, sysdescr.version))

        if sysdescr.vendor == 'CISCO':
            try:
                advisories = query_client.get_by_ios('ios', sysdescr.version)
                for element in advisories:
                    print('title: %s; cves: %s; cvss_base_score: %s' % (element.advisory_title, element.cves, element.cvss_base_score))
            except:
                print('version not found')
Пример #11
0
def main():
    devs = CiscoDevice.objects.all()
    dev_versions = {}
    for dev in devs:
        dev_versions[dev.ios_version] = dev.ios_type

    # load credentials from file
    with open('credentials.json', 'r') as f:
        jdata = json.load(f)

    qclient = query_client.OpenVulnQueryClient(
        client_id=jdata['client_id'], client_secret=jdata['client_secret'])

    progress = 0
    end_progress = len(dev_versions)
    # key => ios version, value => ios/ios-xe
    for key, value in dev_versions.iteritems():
        devs = CiscoDevice.objects.filter(ios_version=key)
        advisories = []
        progress += 1
        print "LOG ::: Progress... %s of %s" % (progress, end_progress)
        successful = False
        if value == 'ios':
            while not successful:
                try:
                    print "LOG ::: Cisco API query for IOS version %s" % (key)
                    advisories = qclient.get_by_ios(key)
                    if len(advisories) > 0:
                        successful = True
                except HTTPError as e:
                    print str(e)
                    print "IOS version %s not found in Cisco PRIST API for:\n%s" % (
                        key, devs)
                    break
                except ConnectionError as e:
                    print str(e)
                    print "LOG ::: Sleeping for 30secs and then retrying..."
                    time.sleep(30)
                    continue
        if value == 'ios-xe':
            while not successful:
                try:
                    print "LOG ::: Cisco API query for IOS-XE version %s" % (
                        key)
                    advisories = qclient.get_by_ios_xe(key)
                    if len(advisories) > 0:
                        successful = True
                except HTTPError as e:
                    print str(e)
                    print "IOS-XE version %s not found in Cisco PRIST API for:\n%s" % (
                        key, devs)
                    break
                except ConnectionError as e:
                    print str(e)
                    print "LOG ::: Sleeping for 30secs and then retrying..."
                    time.sleep(30)
                    continue
        if len(advisories) > 0:
            for adv in advisories:
                vuln_db, created = IosVulnerability.objects.get_or_create(
                    cisco_id=adv.advisory_id)
                vuln_db.title = adv.advisory_title
                vuln_db.url = adv.publication_url
                vuln_db.description = adv.summary
                vuln_db.severity = adv.sir
                vuln_db.save()

                for dev in devs:
                    vuln_map, created = VulnMapper.objects.get_or_create(
                        device=dev, vulnerab=vuln_db)
                    if True:  #created:
                        vuln_map.ios_version = key
                        vuln_map.affecting = True
                        vuln_map.save()
        time.sleep(10)
Пример #12
0
if os.path.exists(f"{this_folder}/logs/logfile.log"):
    pass
else:
    os.makedirs(os.path.dirname(f"{this_folder}/logs/logfile.log"), exist_ok=True)
    open(f"{this_folder}/logs/logfile.log", "a").close()

logging_config = yaml.safe_load(open("./logging_config.yaml", "r"))
logging.config.dictConfig(logging_config)
logger = logging.getLogger("standard")


api = WebexTeamsAPI(access_token=config.webex_teams_token)

psirt_query = query_client.OpenVulnQueryClient(
    client_id=config.credentials.get("CLIENT_ID"),
    client_secret=config.credentials.get("CLIENT_SECRET"),
)


def format_severity(sev_level):
    if sev_level == "High":
        alert_icon = f"🔒"
        alert_color = "danger"
        return alert_icon, alert_color
    elif sev_level == "Medium":
        alert_icon = f"🔒"
        alert_color = "warning"
        return alert_icon, alert_color
    elif sev_level == "Critical":
        alert_icon = f"💀"
        alert_color = "dark"
 def setUp(self):
     self.open_vuln_client = query_client.OpenVulnQueryClient(
         config.CLIENT_ID, config.CLIENT_SECRET)
     self.adv_format = "cvrf"