Lightweight Vulnerability Scanner for Resourced-constrained Organizations

generate_reports.py 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os
  2. import csv
  3. import base64
  4. from gvm.connections import TLSConnection
  5. from gvm.protocols.gmp import Gmp
  6. from gvm.transforms import EtreeTransform
  7. # Set up data directory
  8. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  9. DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "data"))
  10. os.makedirs(DATA_DIR, exist_ok=True)
  11. REPORT_ID_CSV = os.path.join(DATA_DIR, "report_id.csv")
  12. OPENVAS_SCAN_CSV = os.path.join(DATA_DIR, "openvasscan.csv")
  13. OPENVAS_HOST = "localhost"
  14. OPENVAS_PORT = 9390
  15. USERNAME = "admin"
  16. PASSWORD = "admin"
  17. CSV_FORMAT_ID = "c1645568-627a-11e3-a660-406186ea4fc5"
  18. def get_report_csv_data(gmp, report_id):
  19. report = gmp.get_report(report_id=report_id, report_format_id=CSV_FORMAT_ID)
  20. base64_data = report.find(".//report_format").tail
  21. if base64_data:
  22. try:
  23. decoded_data = base64.b64decode(base64_data).decode("utf-8")
  24. return decoded_data
  25. except Exception as e:
  26. print(f"[✗] Error decoding report {report_id}: {e}")
  27. return None
  28. else:
  29. print(f"[!] No data found in report {report_id}")
  30. return None
  31. def save_individual_report(report_id, content):
  32. report_path = os.path.join(DATA_DIR, f"report_{report_id}.csv")
  33. with open(report_path, "w", encoding="utf-8") as f:
  34. f.write(content)
  35. print(f"[✓] Saved individual report to {report_path}")
  36. def append_to_aggregate(content, is_first=False):
  37. mode = "w" if is_first else "a"
  38. with open(OPENVAS_SCAN_CSV, mode, encoding="utf-8") as f:
  39. if not is_first:
  40. # Skip header row to not duplicate rows
  41. content = "\n".join(content.splitlines()[1:])
  42. f.write(content + "\n")
  43. def main():
  44. connection = TLSConnection(hostname=OPENVAS_HOST, port=OPENVAS_PORT)
  45. with Gmp(connection=connection, transform=EtreeTransform()) as gmp:
  46. gmp.authenticate(username=USERNAME, password=PASSWORD)
  47. print("Authenticated with OpenVAS")
  48. first = True
  49. try:
  50. with open(REPORT_ID_CSV, newline="") as f:
  51. reader = csv.DictReader(f)
  52. for row in reader:
  53. report_id = row["Report ID"]
  54. print(f"Fetching report: {report_id}")
  55. content = get_report_csv_data(gmp, report_id)
  56. if content:
  57. #save_individual_report(report_id, content)
  58. append_to_aggregate(content, is_first=first)
  59. first = False
  60. except FileNotFoundError:
  61. print(f"[✗] Missing file: {REPORT_ID_CSV}")
  62. except KeyError:
  63. print(f"[✗] 'Report ID' column not found in {REPORT_ID_CSV}")
  64. if __name__ == "__main__":
  65. main()