Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add example mean_cve_resolution_time_per_year.py #67

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions examples/mean_cve_resolution_time_per_year.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#!/usr/bin/env python
# coding: utf-8

from cyberwatch_api import Cyberwatch_Pyhelper
from datetime import datetime, timedelta, timezone
import csv
import statistics


cbw = Cyberwatch_Pyhelper()

def retrieve_assets():
listassets = []
output = cbw.request(
method="get",
endpoint="/api/v3/servers?active=true&per_page=500"
)

for page in output:
listassets.extend(page.json())
print("\tAssets : {}".format(len(listassets)), end='\r')

print("")
return listassets

def time_between(d1, d2):
d1 = datetime.strptime(d1, '%Y-%m-%dT%H:%M:%S.%f%z')
d2 = datetime.strptime(d2, '%Y-%m-%dT%H:%M:%S.%f%z')
time_difference = d1 - d2
return time_difference.days

def retrieve_actif_CVEs(actifID):
"""retrieve all CVE for a given actif"""
apiResponse = Cyberwatch_Pyhelper().request(
method="GET",
endpoint="/api/v3/vulnerabilities/servers/{}".format(actifID)
)
return next(apiResponse).json()["cve_announcements"]

print("")
print("Retrieve assets : ")
listassets = retrieve_assets()


print("Retrieve CVE")

csvcve = [["Hostname","Asset id","CVE","Detected at","Fixed at","Resolution time (days)"]]
now = datetime.now(timezone.utc)
cvePerYear = {"last365d":[]}

i = 0
for i, asset in enumerate(listassets[0:15]):

print("Assets : {}/{}".format(i + 1,len(listassets)), end='\r')
cves = retrieve_actif_CVEs(asset["id"])
cvesfixed = [cve for cve in cves if cve['fixed_at'] is not None]

if(not cvesfixed):

continue


for cvefixed in cvesfixed:
cvetab = []
timeToResolve = time_between(cvefixed["fixed_at"], cvefixed["detected_at"])

cvetab.append(asset["hostname"])
cvetab.append(asset["id"])
cvetab.append(cvefixed["cve_code"])
cvetab.append(cvefixed["detected_at"])
cvetab.append(cvefixed["fixed_at"])
cvetab.append(timeToResolve)

fixed = datetime.strptime(cvefixed["fixed_at"],'%Y-%m-%dT%H:%M:%S.%f%z')

if (str(fixed.year) not in cvePerYear.keys()):
cvePerYear[str(fixed.year)] = []
cvePerYear[str(fixed.year)].append(timeToResolve)

if ( (now - timedelta(days=365)) <= fixed <= now):
cvePerYear["last365d"].append(timeToResolve)


csvcve.append(cvetab)

print("Assets : {}/{}".format(i + 1,len(listassets)), end='\r')

print("")

path = "timeresolution.csv"

with open(path, mode='w', newline='') as f:
writer = csv.writer(f)
writer.writerows(csvcve)

print("CSV file created at {}".format(path))


resolutionlist = []

print("")
print("Stats per year :")
for FixedPerYear in sorted(cvePerYear.keys()):

resolutionlist.extend(cvePerYear[FixedPerYear])

print("\tYear {} : Mean resolution time {} ; Median resolution Time {} ; Number of cve {}".format(FixedPerYear,statistics.mean(cvePerYear[FixedPerYear]), statistics.median(cvePerYear[FixedPerYear]), len(cvePerYear[FixedPerYear])))

print("")
print("Stats global: Mean resolution time {} ; Median resolution Time {} ; Number of cve : {}".format(statistics.mean(resolutionlist), statistics.median(resolutionlist),len(resolutionlist)))