Lightweight Vulnerability Scanner for Resourced-constrained Organizations

createTargets.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import csv
  2. import os
  3. from gvm.connections import TLSConnection
  4. from gvm.protocols.gmp import Gmp
  5. from gvm.transforms import EtreeTransform
  6. # Set up data directory
  7. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  8. DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "data"))
  9. os.makedirs(DATA_DIR, exist_ok=True)
  10. # OpenVAS Configuration
  11. OPENVAS_HOST = "localhost"
  12. OPENVAS_PORT = 9390
  13. USERNAME = "admin"
  14. PASSWORD = "admin"
  15. ACTIVE_HOSTS_CSV = os.path.join(DATA_DIR, "active_hosts.csv")
  16. TARGET_ID_CSV = os.path.join(DATA_DIR, "target_id.csv")
  17. def get_port_list_id(gmp):
  18. """
  19. Retrieve a valid port list ID.
  20. """
  21. port_lists = gmp.get_port_lists()
  22. default_port_list_id = None
  23. for port_list in port_lists.findall("port_list"):
  24. name = port_list.find("name").text
  25. port_list_id = port_list.get("id")
  26. print(f"Port List: {name} (ID: {port_list_id})")
  27. if "OpenVAS Default" in name:
  28. default_port_list_id = port_list_id
  29. # If "OpenVAS Default" is not found, use the first available port list
  30. if not default_port_list_id and len(port_lists.findall("port_list")) > 0:
  31. default_port_list_id = port_lists.find("port_list").get("id")
  32. print(f"'OpenVAS Default' not found. Using the first available port list with ID: {default_port_list_id}")
  33. return default_port_list_id
  34. def target_exists(gmp, ip):
  35. """
  36. Check if a target already exists for the given IP and return its target_id if it does.
  37. """
  38. targets = gmp.get_targets()
  39. for target in targets.findall("target"):
  40. if target.find("hosts").text == ip:
  41. target_id = target.get("id")
  42. print(f"Target for IP {ip} already exists with ID: {target_id}")
  43. return target_id
  44. return None
  45. def create_target(gmp, name, ip, port_list_id):
  46. """
  47. Create a target in OpenVAS.
  48. """
  49. response = gmp.create_target(name=name, hosts=[ip], port_list_id=port_list_id)
  50. target_id = response.get("id")
  51. if target_id:
  52. print(f"Created target '{name}' for IP '{ip}' with ID: {target_id}")
  53. else:
  54. print(f"Failed to create target for IP {ip}. Check logs.")
  55. return target_id
  56. def save_target_id_to_csv(ip, target_id):
  57. """
  58. Save the target ID to the target_id.csv file if it's not already there.
  59. """
  60. existing_data = []
  61. try:
  62. # Read existing data from the CSV
  63. with open(TARGET_ID_CSV, "r", newline="") as csvfile:
  64. reader = csv.reader(csvfile)
  65. existing_data = list(reader)
  66. except FileNotFoundError:
  67. # If the file doesn't exist, it will be created later
  68. pass
  69. # Check if the IP is already in the CSV
  70. for row in existing_data:
  71. if row[0] == ip:
  72. print(f"IP {ip} already recorded in {TARGET_ID_CSV}")
  73. return
  74. # Append the new target ID to the CSV
  75. with open(TARGET_ID_CSV, "a", newline="") as csvfile:
  76. writer = csv.writer(csvfile)
  77. writer.writerow([ip, target_id])
  78. print(f"Saved target ID {target_id} for IP {ip} to {TARGET_ID_CSV}")
  79. def read_csv_to_ip_list(csv_file):
  80. """
  81. Read the CSV file and extract IPs into a list.
  82. """
  83. ip_list = []
  84. with open(csv_file, newline="") as csvfile:
  85. reader = csv.DictReader(csvfile)
  86. for row in reader:
  87. ip_list.append(row["IP"])
  88. return ip_list
  89. def main():
  90. connection = TLSConnection(hostname=OPENVAS_HOST, port=OPENVAS_PORT)
  91. with Gmp(connection=connection, transform=EtreeTransform()) as gmp:
  92. # Authenticate with OpenVAS
  93. gmp.authenticate(username=USERNAME, password=PASSWORD)
  94. print("Authenticated with OpenVAS")
  95. # Get a valid port list ID
  96. port_list_id = get_port_list_id(gmp)
  97. if not port_list_id:
  98. print("Failed to retrieve a valid port list. Exiting.")
  99. return
  100. # Read IPs from the active hosts CSV
  101. ip_list = read_csv_to_ip_list(ACTIVE_HOSTS_CSV)
  102. if not ip_list:
  103. print("No IPs found in the CSV file. Exiting.")
  104. return
  105. print(f"Found {len(ip_list)} active hosts.")
  106. # Process each IP
  107. for ip in ip_list:
  108. print(f"Processing IP: {ip}")
  109. # Check if target already exists
  110. target_id = target_exists(gmp, ip)
  111. if target_id:
  112. # Save the existing target ID to the CSV if not already recorded
  113. save_target_id_to_csv(ip, target_id)
  114. continue
  115. # Create target if it doesn't exist
  116. target_name = f"Target for {ip}"
  117. target_id = create_target(gmp, target_name, ip, port_list_id)
  118. if target_id:
  119. save_target_id_to_csv(ip, target_id)
  120. else:
  121. print(f"Failed to create target for IP {ip}. Continuing.")
  122. if __name__ == "__main__":
  123. # Ensure the target_id.csv file exists with headers
  124. try:
  125. with open(TARGET_ID_CSV, "x", newline="") as csvfile:
  126. writer = csv.writer(csvfile)
  127. writer.writerow(["IP", "Target ID"]) # Write headers if the file doesn't exist
  128. except FileExistsError:
  129. pass # File already exists, no need to create
  130. main()