diff --git a/examples/retrieve_high_priorities_cve.py b/examples/retrieve_high_priorities_cve.py
new file mode 100644
index 0000000..5a6fb13
--- /dev/null
+++ b/examples/retrieve_high_priorities_cve.py
@@ -0,0 +1,260 @@
+import os
+import glob
+import smtplib
+import json
+import ssl
+from email.mime.text import MIMEText
+from configparser import ConfigParser
+from datetime import datetime, timedelta
+from cyberwatch_api import Cyberwatch_Pyhelper
+
+############################################################
+# CONFIGURATION - USE THIS SECTION TO CONFIGURE SCRIPT
+############################################################
+
+# Add the following block to api.conf and set variables in smtp_settings:
+# [cyberwatch] #Configure API acess
+# api_key =
+# secret_key =
+# url =
+#
+# [SMTP] #Configure SMTP server to send mail
+# smtp_server =
+# login =
+# password =
+
+SENDER_EMAIL = ""
+RECEIVER_EMAILS = ""
+SUBJECT = "Cyberwatch - Rapport 'CVEs prioritaires'"
+
+############################################################
+
+def send_email(html):
+ """Sends an email using smtp specified in the file api.conf"""
+
+ conf = ConfigParser()
+ conf.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'api.conf'))
+
+ smtp_settings = {
+ "server": conf.get('SMTP', 'smtp_server'),
+ "port": 587,
+ "username": conf.get('SMTP', 'login'),
+ "password": conf.get('SMTP', 'password'),
+ "sender": SENDER_EMAIL,
+ "recipient": RECEIVER_EMAILS
+ }
+
+ print("[*] Trying the SMTP server..")
+ context = ssl.create_default_context()
+ smtpserver = smtplib.SMTP(smtp_settings["server"], smtp_settings["port"])
+ smtpserver.starttls(context=context) # Secure the connection
+ smtpserver.login(smtp_settings["username"], smtp_settings["password"])
+ print("[+] SMTP server connected !")
+
+ today = datetime.now().strftime("%d-%m-%Y")
+ msg = MIMEText(html, 'html', 'utf-8')
+ msg['Subject'] = SUBJECT + " - " + today
+ msg['From'] = smtp_settings["sender"]
+ msg['To'] = smtp_settings["recipient"]
+ smtpserver.send_message(msg)
+
+ smtpserver.quit()
+
+def build_email(cve_list):
+ """Send email with report"""
+ conf = ConfigParser()
+ conf.read(os.path.join(os.path.abspath(
+ os.path.dirname(__file__)), 'api.conf'))
+ api_url = conf.get('cyberwatch', 'url')
+ yesterday = datetime.today() - timedelta(days=1)
+
+ html_start = """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+ |
+
+
+ |
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+ Veille sécurité Cyberwatch
+
+
+
+
+ """
+
+ html_end = """
+
+
+
+
+
+
+
+
+ Message généré automatiquement par Cyberwatch.
+ Toute notre équipe vous remercie pour votre confiance. Pour toute question, n'hésitez pas à contacter support@cyberwatch.fr
+ |
+
+ """
+
+ if len(cve_list) == 0:
+ html = """ Aucune nouvelle CVE prioritaire détectée depuis {} """.format(
+ datetime.strftime(yesterday, '%d-%m-%Y'))
+ final_html = html_start + html + html_end
+
+ else:
+ html_start += """
+
+ Listes des nouvelles CVEs prioritaires depuis le {} :
+
+ """.format(datetime.strftime(yesterday, '%d-%m-%Y'))
+
+ for cve in cve_list.items():
+ html_for_each = """
+ -
+ {} (score {})
+
+ """.format(
+ api_url, cve[0], cve[0], cve[1])
+ html_start += html_for_each
+ final_html = html_start + html_end
+
+ return final_html
+
+def retrieve_assets():
+ """retrieve all assets for a cyberwatch node"""
+ assets = []
+ apiResponse = Cyberwatch_Pyhelper().request(
+ method="GET",
+ endpoint="/api/v3/vulnerabilities/servers",
+ verify_ssl=False
+ )
+ for page in apiResponse:
+ assets = assets + page.json()
+ return assets
+
+def retrieve_asset_cve(assetID):
+ """retrieve all CVE for a given actif"""
+ apiResponse = Cyberwatch_Pyhelper().request(
+ method="GET",
+ endpoint="/api/v3/vulnerabilities/servers/" + str(assetID),
+ verify_ssl=False
+ )
+ return next(apiResponse).json()["cve_announcements"]
+
+def only_new_found_element(new_set):
+ """keep only CVEs not already found and stored in the last .json backup"""
+ old_high_priority_cves = {}
+
+ # Get latest backup of high-priority CVEs
+ list_of_files = glob.glob((os.path.join(os.path.abspath(os.path.dirname(__file__)), '*new_cves.json')))
+ if list_of_files:
+ with open(max(list_of_files, key=os.path.getctime), "r") as old_backup:
+ old_high_priority_cves = json.load(old_backup)
+
+ # Compare old backup with latest high-priority CVEs
+ new_set = {k: v for k, v in new_set.items() if k not in old_high_priority_cves}
+
+ # Write new backup file with all high-priority CVEs
+ with open((os.path.join(os.path.abspath(os.path.dirname(__file__)), datetime.strftime(datetime.now(), '%d-%m-%Y') + "_new_cves.json")), "w") as new_backup:
+ new_backup.write(json.dumps({**old_high_priority_cves, **new_set}))
+
+ return new_set
+
+def launch_script():
+ # Retrieving all assets on the Cyberwatch node
+ assets = retrieve_assets()
+ print("[+] " + str(len(assets)) + " assets were found")
+ if(not assets):
+ return
+
+ high_priority_cve_set = {} # Set that will contain all high-priority CVEs
+
+ # Fetching all vulnerabilities for every asset
+ for asset in assets:
+ print()
+
+ cveList = retrieve_asset_cve(asset["id"])
+ print("[+] Asset ID : " + str(asset["id"]) + " | " + str(len(cveList)) + " CVEs found", end="")
+
+ countHighCVE = 0
+ for cve in cveList:
+ if(cve["prioritized"]):
+ high_priority_cve_set[cve["cve_code"]] = cve["score"]
+ countHighCVE += 1
+ print(" including " + str(countHighCVE) + " of high-priority")
+
+ # Keeping only newly found high-priority vulnerabilities since last execution
+ high_priority_cve_set = only_new_found_element(high_priority_cve_set)
+
+ # Outputing
+ print("\n\n================= " + str(len(high_priority_cve_set)) + " new high-priority CVEs found ================='")
+ for key, value in high_priority_cve_set.items(): print("{: >20} : {}".format(key, value))
+
+ # Send the email
+ try:
+ html = build_email(high_priority_cve_set)
+ send_email(html)
+ print("[+] Email successfully sent !")
+ except Exception as e:
+ print("[-] An error occurred and the email couldn't be sent")
+ print(e)
+
+
+launch_script()
\ No newline at end of file
|