-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathattack_tree.py
557 lines (495 loc) · 20.4 KB
/
attack_tree.py
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import re
import requests
import streamlit as st
from anthropic import Anthropic
from mistralai import Mistral
from openai import OpenAI, AzureOpenAI
from groq import Groq
from utils import process_groq_response, create_reasoning_system_prompt, extract_mermaid_code
import json
import google.generativeai as genai
# Function to create a prompt to generate an attack tree
def create_attack_tree_prompt(app_type, authentication, internet_facing, sensitive_data, app_input):
prompt = f"""
APPLICATION TYPE: {app_type}
AUTHENTICATION METHODS: {authentication}
INTERNET FACING: {internet_facing}
SENSITIVE DATA: {sensitive_data}
APPLICATION DESCRIPTION: {app_input}
"""
return prompt
def convert_tree_to_mermaid(tree_data):
"""
Convert structured tree data to Mermaid syntax.
Args:
tree_data (dict): Dictionary containing the tree structure
Returns:
str: Mermaid diagram code
"""
mermaid_lines = ["graph TD"]
def process_node(node, parent_id=None):
node_id = node["id"]
node_label = node["label"]
# Add quotes if label contains spaces or parentheses
if " " in node_label or "(" in node_label or ")" in node_label:
node_label = f'"{node_label}"'
# Add the node definition
mermaid_lines.append(f' {node_id}[{node_label}]')
# Add connection to parent if exists
if parent_id:
mermaid_lines.append(f' {parent_id} --> {node_id}')
# Process children
if "children" in node:
for child in node["children"]:
process_node(child, node_id)
# Process the root node(s)
for root_node in tree_data["nodes"]:
process_node(root_node)
# Join lines with newlines
return "\n".join(mermaid_lines)
def create_json_structure_prompt():
"""
Creates a prompt for generating attack tree data in JSON format.
"""
return """Your task is to analyze the application and create an attack tree structure in JSON format.
The JSON structure should follow this format:
{
"nodes": [
{
"id": "root",
"label": "Compromise Application",
"children": [
{
"id": "auth",
"label": "Gain Unauthorized Access",
"children": [
{
"id": "auth1",
"label": "Exploit OAuth2 Vulnerabilities"
}
]
}
]
}
]
}
Rules:
- Use simple IDs (root, auth, auth1, data, etc.)
- Make labels clear and descriptive
- Include all attack paths and sub-paths
- Maintain proper parent-child relationships
- Ensure the JSON is properly formatted
ONLY RESPOND WITH THE JSON STRUCTURE, NO ADDITIONAL TEXT."""
def clean_json_response(response_text):
"""
Clean JSON response by removing any markdown code block markers and finding the JSON content.
Args:
response_text (str): The raw response text that might contain JSON
Returns:
str: Cleaned JSON string
"""
# Remove markdown JSON code block if present
json_pattern = r'```json\s*(.*?)\s*```'
match = re.search(json_pattern, response_text, re.DOTALL)
if match:
return match.group(1).strip()
# If no JSON code block, try to find content between any code blocks
code_pattern = r'```\s*(.*?)\s*```'
match = re.search(code_pattern, response_text, re.DOTALL)
if match:
return match.group(1).strip()
# If no code blocks, return the original text
return response_text.strip()
# Function to get attack tree from the GPT response.
def get_attack_tree(api_key, model_name, prompt):
client = OpenAI(api_key=api_key)
# For models that support JSON output format
if model_name in ["o1", "o3-mini"]:
system_prompt = create_reasoning_system_prompt(
task_description="Create a structured attack tree by analyzing potential attack paths.",
approach_description="""Analyze the application and create an attack tree showing potential attack paths.
Rules:
- Use simple alphanumeric IDs (A1, A2, B1, etc.)
- Make labels clear and descriptive
- Include all attack paths and sub-paths
- Maintain proper parent-child relationships
- Ensure proper JSON structure
Example format:
{
"nodes": [
{
"id": "A1",
"label": "Compromise Application",
"children": [
{
"id": "B1",
"label": "Exploit Authentication Vulnerabilities",
"children": [
{
"id": "C1",
"label": "Brute Force Credentials",
"children": []
}
]
}
]
}
]
}
ONLY RESPOND WITH THE JSON STRUCTURE, NO ADDITIONAL TEXT."""
)
response = client.chat.completions.create(
model=model_name,
response_format=create_attack_tree_schema(),
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
max_completion_tokens=4000
)
else:
# For other models, try to get JSON output without format parameter
system_prompt = create_json_structure_prompt()
response = client.chat.completions.create(
model=model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
max_tokens=4000
)
# Try to parse JSON response
try:
# Clean the response text first
cleaned_response = clean_json_response(response.choices[0].message.content)
tree_data = json.loads(cleaned_response)
return convert_tree_to_mermaid(tree_data)
except json.JSONDecodeError:
# Fallback: try to extract Mermaid code if JSON parsing fails
return extract_mermaid_code(response.choices[0].message.content)
# Function to get attack tree from the Azure OpenAI response.
def get_attack_tree_azure(azure_api_endpoint, azure_api_key, azure_api_version, azure_deployment_name, prompt):
client = AzureOpenAI(
azure_endpoint = azure_api_endpoint,
api_key = azure_api_key,
api_version = azure_api_version,
)
# Try to get JSON output
system_prompt = create_json_structure_prompt()
response = client.chat.completions.create(
model = azure_deployment_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
]
)
# Try to parse JSON response
try:
cleaned_response = clean_json_response(response.choices[0].message.content)
tree_data = json.loads(cleaned_response)
return convert_tree_to_mermaid(tree_data)
except json.JSONDecodeError:
# Fallback: try to extract Mermaid code if JSON parsing fails
return extract_mermaid_code(response.choices[0].message.content)
# Function to get attack tree from the Mistral model's response.
def get_attack_tree_mistral(mistral_api_key, mistral_model, prompt):
client = Mistral(api_key=mistral_api_key)
# Try to get JSON output
system_prompt = create_json_structure_prompt()
response = client.chat.complete(
model=mistral_model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
]
)
# Try to parse JSON response
try:
cleaned_response = clean_json_response(response.choices[0].message.content)
tree_data = json.loads(cleaned_response)
return convert_tree_to_mermaid(tree_data)
except json.JSONDecodeError:
# Fallback: try to extract Mermaid code if JSON parsing fails
return extract_mermaid_code(response.choices[0].message.content)
# Function to get attack tree from Ollama hosted LLM.
def get_attack_tree_ollama(ollama_endpoint, ollama_model, prompt):
"""
Get attack tree from Ollama hosted LLM.
Args:
ollama_endpoint (str): The URL of the Ollama endpoint (e.g., 'http://localhost:11434')
ollama_model (str): The name of the model to use
prompt (str): The prompt to send to the model
Returns:
str: The generated attack tree code in Mermaid syntax
Raises:
requests.exceptions.RequestException: If there's an error communicating with the Ollama endpoint
KeyError: If the response doesn't contain the expected fields
"""
if not ollama_endpoint.endswith('/'):
ollama_endpoint = ollama_endpoint + '/'
url = ollama_endpoint + "api/chat"
# Try to get JSON output
system_prompt = create_json_structure_prompt()
data = {
"model": ollama_model,
"stream": False,
"format": "json", # Request JSON format if supported
"messages": [
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": prompt
}
]
}
try:
response = requests.post(url, json=data, timeout=60)
response.raise_for_status()
outer_json = response.json()
try:
# Try to parse the response content as JSON
cleaned_response = clean_json_response(outer_json["message"]["content"])
tree_data = json.loads(cleaned_response)
return convert_tree_to_mermaid(tree_data)
except (json.JSONDecodeError, KeyError):
# Fallback: try to extract Mermaid code if JSON parsing fails
return extract_mermaid_code(outer_json["message"]["content"])
except requests.exceptions.RequestException as e:
print(f"Error communicating with Ollama endpoint: {str(e)}")
raise
# Function to get attack tree from Anthropic's Claude model.
def get_attack_tree_anthropic(anthropic_api_key, anthropic_model, prompt):
client = Anthropic(api_key=anthropic_api_key)
# Try to get JSON output
system_prompt = create_json_structure_prompt()
response = client.messages.create(
model=anthropic_model,
max_tokens=4096,
system=system_prompt,
messages=[
{"role": "user", "content": prompt}
]
)
# Try to parse JSON response
try:
cleaned_response = clean_json_response(response.content[0].text)
tree_data = json.loads(cleaned_response)
return convert_tree_to_mermaid(tree_data)
except (json.JSONDecodeError, IndexError, AttributeError):
# Fallback: try to extract Mermaid code if JSON parsing fails
return extract_mermaid_code(response.content[0].text)
# Function to get attack tree from LM Studio Server response.
def get_attack_tree_lm_studio(lm_studio_endpoint, model_name, prompt):
client = OpenAI(
base_url=f"{lm_studio_endpoint}/v1",
api_key="not-needed" # LM Studio Server doesn't require an API key
)
# Try to get JSON output
system_prompt = create_json_structure_prompt()
response = client.chat.completions.create(
model=model_name,
response_format=create_attack_tree_schema_lm_studio(), # Use LM Studio specific schema
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
]
)
# Try to parse JSON response
try:
cleaned_response = clean_json_response(response.choices[0].message.content)
tree_data = json.loads(cleaned_response)
return convert_tree_to_mermaid(tree_data)
except json.JSONDecodeError:
# Fallback: try to extract Mermaid code if JSON parsing fails
return extract_mermaid_code(response.choices[0].message.content)
# Function to get attack tree from the Groq model's response.
def get_attack_tree_groq(groq_api_key, groq_model, prompt):
client = Groq(api_key=groq_api_key)
# Try to get JSON output
system_prompt = create_json_structure_prompt()
response = client.chat.completions.create(
model=groq_model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
]
)
# Process the response using our utility function
reasoning, content = process_groq_response(
response.choices[0].message.content,
groq_model,
expect_json=True
)
# If we got reasoning, display it in an expander in the UI
if reasoning:
with st.expander("View model's reasoning process", expanded=False):
st.write(reasoning)
# Try to parse JSON response
try:
if isinstance(content, dict): # If already parsed by process_groq_response
tree_data = content
else:
cleaned_response = clean_json_response(content)
tree_data = json.loads(cleaned_response)
return convert_tree_to_mermaid(tree_data)
except (json.JSONDecodeError, TypeError):
# Fallback: try to extract Mermaid code if JSON parsing fails
return extract_mermaid_code(content)
def create_attack_tree_schema():
"""
Creates a JSON schema for attack tree structure.
"""
return {
"type": "json_schema",
"json_schema": {
"name": "attack_tree",
"description": "A structured representation of an attack tree",
"schema": {
"type": "object",
"properties": {
"nodes": {
"type": "array",
"items": {
"$ref": "#/$defs/node"
}
}
},
"$defs": {
"node": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Simple alphanumeric identifier for the node"
},
"label": {
"type": "string",
"description": "Description of the attack vector or goal"
},
"children": {
"type": "array",
"items": {
"$ref": "#/$defs/node"
}
}
},
"required": ["id", "label", "children"],
"additionalProperties": False
}
},
"required": ["nodes"],
"additionalProperties": False
},
"strict": True
}
}
def create_attack_tree_schema_lm_studio():
"""
Creates a non-recursive JSON schema for attack tree structure specifically for LM Studio.
Limits the depth to 3 levels to avoid circular references.
"""
return {
"type": "json_schema",
"json_schema": {
"name": "attack_tree",
"description": "A structured representation of an attack tree",
"schema": {
"type": "object",
"properties": {
"nodes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Simple alphanumeric identifier for the root node"
},
"label": {
"type": "string",
"description": "Description of the attack vector or goal"
},
"children": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Simple alphanumeric identifier for the level 1 node"
},
"label": {
"type": "string",
"description": "Description of the attack vector or goal"
},
"children": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Simple alphanumeric identifier for the leaf node"
},
"label": {
"type": "string",
"description": "Description of the attack vector or goal"
},
"children": {
"type": "array",
"items": {},
"default": []
}
},
"required": ["id", "label", "children"],
"additionalProperties": False
}
}
},
"required": ["id", "label", "children"],
"additionalProperties": False
}
}
},
"required": ["id", "label", "children"],
"additionalProperties": False
}
}
},
"required": ["nodes"],
"additionalProperties": False
},
"strict": True
}
}
# Function to get attack tree from the Google model's response.
def get_attack_tree_google(google_api_key, google_model, prompt):
genai.configure(api_key=google_api_key)
model = genai.GenerativeModel(google_model)
# Create the system message
system_message = create_json_structure_prompt()
# Start a chat session with the system message in the history
chat = model.start_chat(history=[
{"role": "user", "parts": [system_message]},
{"role": "model", "parts": ["Understood. I will provide attack tree data in JSON format only."]}
])
# Configure safety settings to allow generation of attack trees
safety_settings = {
'HARASSMENT': 'BLOCK_NONE',
'HATE_SPEECH': 'BLOCK_NONE',
'SEXUALLY_EXPLICIT': 'BLOCK_NONE',
'DANGEROUS': 'BLOCK_NONE'
}
# Send the actual prompt with safety settings
response = chat.send_message(prompt, safety_settings=safety_settings)
try:
# Clean the response text and try to parse as JSON
cleaned_response = clean_json_response(response.text)
tree_data = json.loads(cleaned_response)
return convert_tree_to_mermaid(tree_data)
except (json.JSONDecodeError, AttributeError):
# Fallback: try to extract Mermaid code if JSON parsing fails
return extract_mermaid_code(response.text)