-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAttackPathCVE.py
More file actions
executable file
·245 lines (216 loc) · 8.7 KB
/
AttackPathCVE.py
File metadata and controls
executable file
·245 lines (216 loc) · 8.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env python3
import http.client
import json
import csv
import argparse
from urllib.parse import urlencode
from datetime import datetime
import config
import os
def clean_url(url):
return url.replace('https://', '').replace('http://', '').rstrip('/')
# we are doing this proxy handling manually because of the limitation of not wanting to pip install additional pkgs
def get_proxy_settings():
https_proxy = os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy')
if https_proxy:
https_proxy = https_proxy.replace('https://', '').replace('http://', '')
if ':' in https_proxy:
proxy_host, proxy_port = https_proxy.split(':')
proxy_port = int(proxy_port)
print(f"Using proxy: {proxy_host}:{proxy_port}")
return proxy_host, proxy_port
return None, None
def create_connection(url, timeout=10):
proxy_host, proxy_port = get_proxy_settings()
if proxy_host and proxy_port:
conn = http.client.HTTPSConnection(proxy_host, proxy_port, timeout=timeout)
conn.set_tunnel(url)
else:
conn = http.client.HTTPSConnection(url, timeout=timeout)
return conn
def login(url, api_key, api_secret):
clean_base_url = clean_url(url)
print(f"Attempting login to {clean_base_url}...")
try:
conn = create_connection(clean_base_url)
payload = json.dumps({
"username": api_key,
"password": api_secret
})
headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json; charset=UTF-8'
}
conn.request("POST", "/login", payload, headers)
response = conn.getresponse()
if response.status == 200:
print("Login successful!")
return response.read().decode('utf-8')
else:
print(f"Login failed with HTTP status code: {response.status}")
print(f"Response: {response.read().decode('utf-8')}")
raise Exception(f"Login failed with status code {response.status}")
except TimeoutError:
print("Connection timed out. Please check:")
print("- Network connectivity")
print("- Proxy settings (if using corporate network)")
print("- URL in config file")
print(f"Current URL being used: {clean_base_url}")
raise
except Exception as e:
print(f"Connection error: {str(e)}")
raise
def get_alerts(params, headers):
print("\nFetching attack path alerts...")
clean_base_url = clean_url(config.url)
try:
conn = create_connection(clean_base_url)
query_string = urlencode(params)
endpoint = f"/alert?{query_string}"
conn.request("GET", endpoint, '', headers)
res = conn.getresponse()
if res.status != 200:
print(f"Failed to fetch alerts. Status code: {res.status}")
print(f"Response: {res.read().decode('utf-8')}")
raise Exception("Failed to fetch alerts")
data = res.read()
return json.loads(data.decode("utf-8"))
except Exception as e:
print(f"Error fetching alerts: {str(e)}")
raise
def get_alert_details(alert_id, headers):
clean_base_url = clean_url(config.url)
try:
conn = create_connection(clean_base_url)
endpoint = f"/alert/{alert_id}?detailed=false&withAlertRuleInfo=false"
conn.request("GET", endpoint, '', headers)
res = conn.getresponse()
if res.status != 200:
print(f"Failed to fetch alert details. Status code: {res.status}")
print(f"Response: {res.read().decode('utf-8')}")
raise Exception("Failed to fetch alert details")
data = res.read()
return json.loads(data.decode("utf-8"))
except Exception as e:
print(f"Error fetching alert details: {str(e)}")
raise
def extract_cves(detail):
try:
nodes = detail.get("metadata", {}).get("attackPathDetails", {}).get("graph", {}).get("nodes", {})
cves = []
for node_id, node_info in nodes.items():
if node_info.get("nodeType") == "vulnerability":
cves.append({
"id": node_id,
"severity": node_info.get("severity", "N/A"),
"cvss_score": node_info.get("cvssScore", "N/A")
})
return cves
except Exception as e:
print(f"Error extracting CVEs: {e}")
return []
def main():
parser = argparse.ArgumentParser(description='Fetch Prisma Cloud attack path alerts')
parser.add_argument('months', nargs='?', type=int, default=12,
help='Number of months to check (default: 12)')
args = parser.parse_args()
try:
auth_response = login(config.url, config.api_key, config.api_secret)
response = json.loads(auth_response)
JWTtoken = response["token"]
headers = {
'Accept': '*/*',
'x-redlock-auth': JWTtoken
}
except Exception as e:
print(f"Authentication failed: {e}")
return
initial_params = {
'timeType': 'relative',
'timeAmount': str(args.months),
'timeUnit': 'month',
'detailed': 'true',
'policy.type': "attack_path"
}
try:
attack_path_alerts = get_alerts(initial_params, headers)
alert_details = []
resources_without_cves = []
for alert in attack_path_alerts:
if "id" not in alert:
continue
attack_path_id = alert["id"]
detail = get_alert_details(attack_path_id, headers)
cves = extract_cves(detail)
if "resource" in detail:
resource = detail["resource"]
resource_name = resource.get("name", "N/A")
if not cves:
resources_without_cves.append(resource_name)
continue
alert_info = {
"resource_name": resource_name,
"resource_id": resource.get("id", "N/A"),
"attack_path_id": attack_path_id,
"account_id": resource.get("accountId", "N/A"),
"cloud_type": resource.get("cloudType", "N/A"),
"region": resource.get("region", "N/A"),
"resource_type": resource.get("resourceType", "N/A"),
"cves": cves
}
alert_details.append(alert_info)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
csv_filename = f"prisma_attack_paths_{timestamp}.csv"
with open(csv_filename, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow([
'Resource Name',
'Resource ID',
'Attack Path ID',
'Account ID',
'Cloud Type',
'Region',
'Resource Type',
'CVE ID',
'CVE Severity',
'CVSS Score'
])
for detail in alert_details:
for cve in detail["cves"]:
csvwriter.writerow([
detail["resource_name"],
detail["resource_id"],
detail["attack_path_id"],
detail["account_id"],
detail["cloud_type"],
detail["region"],
detail["resource_type"],
cve["id"],
cve["severity"],
cve["cvss_score"]
])
print("\nAttack Path Alert Summary:")
print("==========================")
for detail in alert_details:
print(f"\nResource: {detail['resource_name']}")
print(f"Resource ID: {detail['resource_id']}")
print(f"Attack Path ID: {detail['attack_path_id']}")
print(f"Account ID: {detail['account_id']}")
print(f"Cloud Type: {detail['cloud_type']}")
print(f"Region: {detail['region']}")
print(f"Resource Type: {detail['resource_type']}")
print("CVEs:")
for cve in detail["cves"]:
print(f" - {cve['id']} (Severity: {cve['severity']}, CVSS: {cve['cvss_score']})")
print()
print(f"\nResources without CVEs ({len(resources_without_cves)}):")
print("======================================")
for resource in resources_without_cves:
print(f"- {resource}")
print(f"\nTotal resources with CVEs: {len(alert_details)}")
print(f"Total resources without CVEs: {len(resources_without_cves)}")
print(f"\nCSV file has been created: {csv_filename}")
except Exception as e:
print(f"An error occurred while processing alerts: {str(e)}")
if __name__ == "__main__":
main()