瀏覽代碼

Upload files to ''

Jose E. Rodriguez 1 月之前
父節點
當前提交
6bd60f6130
共有 5 個文件被更改,包括 446 次插入0 次删除
  1. 154
    0
      createTargers.py
  2. 41
    0
      networkdiscovery.py
  3. 54
    0
      portscanner.py
  4. 62
    0
      starttask.py
  5. 135
    0
      taskmaker.py

+ 154
- 0
createTargers.py 查看文件

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

+ 41
- 0
networkdiscovery.py 查看文件

@@ -0,0 +1,41 @@
1
+import nmap
2
+import psutil
3
+import socket
4
+import ipaddress
5
+import pandas as pd
6
+from datetime import datetime
7
+
8
+def get_ipv4_interfaces():
9
+    ipv4_interfaces = []
10
+    for name, addrs in psutil.net_if_addrs().items():
11
+        for addr in addrs:
12
+            if addr.family == socket.AF_INET:
13
+                ipv4_interfaces.append((name, addr.address, addr.netmask))
14
+    return ipv4_interfaces
15
+
16
+def network_discovery():
17
+    ipv4_interfaces = get_ipv4_interfaces()
18
+    if not ipv4_interfaces:
19
+        print("No active IPv4 network interfaces found.")
20
+        return
21
+
22
+    nm = nmap.PortScanner()
23
+    active_hosts = []
24
+
25
+    for name, ip, netmask in ipv4_interfaces:
26
+        network = ipaddress.IPv4Network((ip, netmask), strict=False)
27
+        if str(network) == "127.0.0.0/8":
28
+            continue
29
+
30
+        print(f"Discovering hosts in IP range {network}...")
31
+        nm.scan(hosts=str(network), arguments='-sn -T4 --open')
32
+        
33
+        for host in nm.all_hosts():
34
+            active_hosts.append([host, datetime.now().strftime("%Y-%m-%d %H:%M:%S")])
35
+
36
+    columns = ['IP', 'Discovery Timestamp']
37
+    df = pd.DataFrame(active_hosts, columns=columns)
38
+    df.to_csv('active_hosts.csv', index=False)
39
+
40
+if __name__ == "__main__":
41
+    network_discovery()

+ 54
- 0
portscanner.py 查看文件

@@ -0,0 +1,54 @@
1
+import nmap
2
+import pandas as pd
3
+from datetime import datetime
4
+import os
5
+
6
+def detailed_scan():
7
+    try:
8
+        active_hosts_df = pd.read_csv('active_hosts.csv')
9
+    except FileNotFoundError:
10
+        print("File active_hosts.csv not found. Please run the network discovery script first.")
11
+        return
12
+
13
+    nm = nmap.PortScanner()
14
+    scan_results = []
15
+
16
+    start_time = datetime.now()
17
+    print(f"Scan started at: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
18
+
19
+    for index, row in active_hosts_df.iterrows():
20
+        ip = row['IP']
21
+        print(f"Scanning {ip} for detailed information...")
22
+        nm.scan(ip, arguments='-p- -T5 ')
23
+
24
+        for host in nm.all_hosts():
25
+            hostnames = [x['name'] for x in nm[host].get('hostnames', [])]
26
+            mac_address = nm[host]['addresses'].get('mac', 'N/A')
27
+            scan_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
28
+
29
+            for proto in nm[host].all_protocols():
30
+                for port in nm[host][proto]:
31
+                    state = nm[host][proto][port]['state']
32
+                    name = nm[host][proto][port]['name']
33
+                    product = nm[host][proto][port]['product']
34
+                    version = nm[host][proto][port]['version']
35
+                    extrainfo = nm[host][proto][port]['extrainfo']
36
+                    row = [ip, ', '.join(hostnames), mac_address, proto, port, name, state, product, version, extrainfo, scan_timestamp]
37
+                    scan_results.append(row)
38
+
39
+    end_time = datetime.now()
40
+    print(f"Scan finished at: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
41
+    print(f"Total scan duration: {end_time - start_time}")
42
+
43
+    columns = ['IP', 'Hostname', 'MAC Address', 'Protocol', 'Port', 'Name', 'State', 'Product', 'Version', 'Extra Info', 'Timestamp']
44
+    detailed_df = pd.DataFrame(scan_results, columns=columns)
45
+
46
+    if os.path.exists('detailed_scan_results.csv'):
47
+        detailed_df.to_csv('detailed_scan_results.csv', mode='a', header=False, index=False)
48
+    else:
49
+        detailed_df.to_csv('detailed_scan_results.csv', index=False)
50
+
51
+    print(detailed_df)
52
+
53
+if __name__ == "__main__":
54
+    detailed_scan()

+ 62
- 0
starttask.py 查看文件

@@ -0,0 +1,62 @@
1
+import csv
2
+from gvm.connections import TLSConnection
3
+from gvm.protocols.gmp import Gmp
4
+from gvm.transforms import EtreeTransform
5
+
6
+
7
+# OpenVAS Configuration
8
+OPENVAS_HOST = "localhost"
9
+OPENVAS_PORT = 9390
10
+USERNAME = "admin"
11
+PASSWORD = "admin"
12
+
13
+# CSV file
14
+TASK_ID_CSV = "task_id.csv"
15
+
16
+
17
+def start_task(gmp, task_id):
18
+    """
19
+    Start a task in OpenVAS.
20
+    """
21
+    try:
22
+        gmp.start_task(task_id=task_id)
23
+        print(f"Started task with ID: {task_id}")
24
+    except Exception as e:
25
+        print(f"Failed to start task with ID {task_id}. Error: {e}")
26
+
27
+
28
+def read_csv_to_task_list(csv_file):
29
+    """
30
+    Read the CSV file and extract task IDs into a list.
31
+    """
32
+    task_list = []
33
+    with open(csv_file, newline="") as csvfile:
34
+        reader = csv.DictReader(csvfile)
35
+        for row in reader:
36
+            task_list.append(row["Task ID"])
37
+    return task_list
38
+
39
+
40
+def main():
41
+    connection = TLSConnection(hostname=OPENVAS_HOST, port=OPENVAS_PORT)
42
+    with Gmp(connection=connection, transform=EtreeTransform()) as gmp:
43
+        # Authenticate with OpenVAS
44
+        gmp.authenticate(username=USERNAME, password=PASSWORD)
45
+        print("Authenticated with OpenVAS")
46
+
47
+        # Read task IDs from the task_id.csv file
48
+        task_list = read_csv_to_task_list(TASK_ID_CSV)
49
+        if not task_list:
50
+            print("No task IDs found in the CSV file. Exiting.")
51
+            return
52
+
53
+        print(f"Found {len(task_list)} tasks to start.")
54
+
55
+        # Start each task
56
+        for task_id in task_list:
57
+            start_task(gmp, task_id)
58
+
59
+
60
+if __name__ == "__main__":
61
+    main()
62
+

+ 135
- 0
taskmaker.py 查看文件

@@ -0,0 +1,135 @@
1
+import csv
2
+from gvm.connections import TLSConnection
3
+from gvm.protocols.gmp import Gmp
4
+from gvm.transforms import EtreeTransform
5
+
6
+
7
+# OpenVAS Configuration
8
+OPENVAS_HOST = "localhost"
9
+OPENVAS_PORT = 9390
10
+USERNAME = "admin"
11
+PASSWORD = "admin"
12
+
13
+# CSV files
14
+TARGET_ID_CSV = "target_id.csv"
15
+TASK_ID_CSV = "task_id.csv"
16
+
17
+
18
+def get_scan_config_id(gmp):
19
+    """
20
+    Retrieve the ID of the 'Full and Fast' scan configuration.
21
+    """
22
+    scan_configs = gmp.get_scan_configs()
23
+    for config in scan_configs.findall("config"):
24
+        if config.find("name").text == "Full and fast":
25
+            config_id = config.get("id")
26
+            print(f"'Full and Fast' scan configuration found with ID: {config_id}")
27
+            return config_id
28
+    print("Failed to find 'Full and Fast' scan configuration.")
29
+    return None
30
+
31
+
32
+def get_scanner_id(gmp):
33
+    """
34
+    Retrieve the ID of the default scanner.
35
+    """
36
+    scanners = gmp.get_scanners()
37
+    for scanner in scanners.findall("scanner"):
38
+        if "OpenVAS Default" in scanner.find("name").text:
39
+            scanner_id = scanner.get("id")
40
+            print(f"'OpenVAS Default' scanner found with ID: {scanner_id}")
41
+            return scanner_id
42
+    print("Failed to find 'OpenVAS Default' scanner.")
43
+    return None
44
+
45
+
46
+
47
+def read_csv_to_target_list(csv_file):
48
+    """
49
+    Read the CSV file and extract target IDs into a list.
50
+    """
51
+    target_list = []
52
+    with open(csv_file, newline="") as csvfile:
53
+        reader = csv.DictReader(csvfile)
54
+        for row in reader:
55
+            target_list.append(row["Target ID"])
56
+    return target_list
57
+
58
+def save_task_id_to_csv(target_id, task_id):
59
+    """
60
+    Save the task ID to the task_id.csv file.
61
+    """
62
+    with open(TASK_ID_CSV, "a", newline="") as csvfile:
63
+        writer = csv.writer(csvfile)
64
+        writer.writerow([target_id, task_id])
65
+    print(f"Saved task ID {task_id} for target ID {target_id} to {TASK_ID_CSV}")
66
+
67
+
68
+def create_task(gmp, task_name, target_id, scan_config_id, scanner_id):
69
+    """
70
+    Create a task in OpenVAS.
71
+    """
72
+    response = gmp.create_task(
73
+        name=task_name,
74
+        config_id=scan_config_id,
75
+        target_id=target_id,
76
+        scanner_id=scanner_id
77
+    )
78
+    task_id = response.get("id")
79
+    if task_id:
80
+        print(f"Created task '{task_name}' for target ID '{target_id}' with ID: {task_id}")
81
+    else:
82
+        print(f"Failed to create task for target ID {target_id}. Check logs.")
83
+    return task_id
84
+
85
+
86
+def main():
87
+    connection = TLSConnection(hostname=OPENVAS_HOST, port=OPENVAS_PORT)
88
+    with Gmp(connection=connection, transform=EtreeTransform()) as gmp:
89
+        # Authenticate with OpenVAS
90
+        gmp.authenticate(username=USERNAME, password=PASSWORD)
91
+        print("Authenticated with OpenVAS")
92
+
93
+        # Get the scan configuration ID
94
+        scan_config_id = get_scan_config_id(gmp)
95
+        if not scan_config_id:
96
+            print("Failed to retrieve a valid scan configuration. Exiting.")
97
+            return
98
+
99
+        # Get the scanner ID
100
+        scanner_id = get_scanner_id(gmp)
101
+        if not scanner_id:
102
+            print("Failed to retrieve a valid scanner. Exiting.")
103
+            return
104
+
105
+        # Read target IDs from the target_id.csv file
106
+        target_list = read_csv_to_target_list(TARGET_ID_CSV)
107
+        if not target_list:
108
+            print("No target IDs found in the CSV file. Exiting.")
109
+            return
110
+
111
+        print(f"Found {len(target_list)} targets to create tasks for.")
112
+
113
+        # Process each target
114
+        for target_id in target_list:
115
+            print(f"Processing target ID: {target_id}")
116
+
117
+            # Create task for the target
118
+            task_name = f"Task for Target {target_id}"
119
+            task_id = create_task(gmp, task_name, target_id, scan_config_id, scanner_id)
120
+            if task_id:
121
+                save_task_id_to_csv(target_id, task_id)
122
+            else:
123
+                print(f"Failed to create task for target ID {target_id}. Continuing.")
124
+
125
+
126
+if __name__ == "__main__":
127
+    # Ensure the task_id.csv file exists with headers
128
+    try:
129
+        with open(TASK_ID_CSV, "x", newline="") as csvfile:
130
+            writer = csv.writer(csvfile)
131
+            writer.writerow(["Target ID", "Task ID"])  # Write headers if the file doesn't exist
132
+    except FileExistsError:
133
+        pass  # File already exists, no need to create
134
+
135
+    main()