-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase64_decoder.py
More file actions
469 lines (350 loc) · 13.7 KB
/
base64_decoder.py
File metadata and controls
469 lines (350 loc) · 13.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
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
import argparse
import subprocess
import sys
from decoder_engine import decode_input
from detection_engine import analyze_decoded_result
from report_exporter import export_to_csv, export_to_json, export_to_markdown, export_to_html
from profile_loader import load_analyst_profile
def print_analysis_result(analysis):
print("====================================")
print(f"Timestamp: {analysis.get('timestamp', '')}")
print(f"Detected Encoding: {analysis.get('encoding', '')}")
if "decode_level" in analysis:
print(f"Decode Level: {analysis.get('decode_level')}")
if "source_encoding" in analysis:
print(f"Source Encoding: {analysis.get('source_encoding')}")
if "batch_item" in analysis:
print(f"Batch Item: {analysis.get('batch_item')}")
if "source_file" in analysis:
print(f"Source File: {analysis.get('source_file')}")
case_context = analysis.get("case_context", {})
if case_context:
print("\nCase Context:")
print("------------------------------------")
print(f"Case ID: {case_context.get('case_id', '')}")
print(f"Analyst: {case_context.get('analyst', '')}")
print(f"Alert Source: {case_context.get('alert_source', '')}")
print(f"Hostname: {case_context.get('hostname', '')}")
print(f"Username: {case_context.get('username', '')}")
print(f"Analyst Notes: {case_context.get('analyst_notes', '')}")
print("\nDecoded Output:")
print("------------------------------------")
print(analysis.get("decoded_text", ""))
print("\nSuspicious Keyword Check:")
print("------------------------------------")
suspicious_keywords = analysis.get("suspicious_keywords", [])
if suspicious_keywords:
for keyword in suspicious_keywords:
print(f"- {keyword}")
else:
print("No suspicious keywords found.")
print("\nRisk Score:")
print("------------------------------------")
print(f"Risk Level: {analysis.get('risk_level', 'None')}")
print(f"Score: {analysis.get('risk_score', 0)}")
reasons = analysis.get("reasons", [])
if reasons:
print("\nReasons:")
for reason in reasons:
print(f"- {reason}")
mitre_attack = analysis.get("mitre_attack", [])
if mitre_attack:
print("\nMITRE ATT&CK Mapping:")
print("------------------------------------")
for technique in mitre_attack:
print(
f"- {technique.get('technique_id')} - "
f"{technique.get('technique_name')} "
f"({technique.get('tactic')})"
)
if technique.get("reason"):
print(f" Reason: {technique.get('reason')}")
detection_rules = analysis.get("detection_rules", [])
if detection_rules:
print("\nDetection Rule Mapping:")
print("------------------------------------")
for rule in detection_rules:
print(f"- {rule.get('rule_name')}")
print(f" Severity: {rule.get('severity')}")
print(f" Description: {rule.get('description')}")
log_sources = rule.get("log_sources", [])
if log_sources:
print(f" Log Sources: {', '.join(log_sources)}")
if rule.get("reason"):
print(f" Reason: {rule.get('reason')}")
# IMPORTANT:
# This must be outside the detection_rules block.
# Otherwise clean inputs with no detection rules can cause:
# UnboundLocalError: detection_templates referenced before assignment
detection_templates = analysis.get("detection_templates", [])
if detection_templates:
print("\nDetection Templates:")
print("------------------------------------")
for template in detection_templates:
print(f"- {template.get('template_name')}")
print(f" Type: {template.get('template_type')}")
print(f" Severity: {template.get('severity')}")
print(f" Description: {template.get('description')}")
print(" Query:")
print("------------------------------------")
print(template.get("query", ""))
print("------------------------------------")
print()
def analyze_single_input(encoded_text):
decoded_results = decode_input(encoded_text)
analysis_results = []
for result in decoded_results:
analysis = analyze_decoded_result(result)
analysis["original_input"] = encoded_text
analysis_results.append(analysis)
return analysis_results
def analyze_batch_file(file_path):
analysis_results = []
try:
with open(file_path, "r", encoding="utf-8") as file:
lines = file.readlines()
encoded_values = []
for line in lines:
cleaned_line = line.strip()
if cleaned_line:
encoded_values.append(cleaned_line)
if not encoded_values:
print(f"No encoded values found in file: {file_path}")
return []
for index, encoded_text in enumerate(encoded_values, start=1):
decoded_results = decode_input(encoded_text)
for result in decoded_results:
analysis = analyze_decoded_result(result)
analysis["batch_item"] = index
analysis["original_input"] = encoded_text
analysis["source_file"] = file_path
analysis_results.append(analysis)
return analysis_results
except FileNotFoundError:
print(f"File not found: {file_path}")
return []
except Exception as error:
print(f"Error reading file: {error}")
return []
def print_detection_coverage_summary(analysis_results):
mitre_techniques = {}
detection_rules = {}
detection_templates = {}
for result in analysis_results:
for technique in result.get("mitre_attack", []):
technique_id = technique.get("technique_id", "")
technique_name = technique.get("technique_name", "")
tactic = technique.get("tactic", "")
if technique_id:
mitre_techniques[technique_id] = {
"technique_name": technique_name,
"tactic": tactic
}
for rule in result.get("detection_rules", []):
rule_name = rule.get("rule_name", "")
severity = rule.get("severity", "")
if rule_name:
detection_rules[rule_name] = severity
for template in result.get("detection_templates", []):
template_name = template.get("template_name", "")
template_type = template.get("template_type", "")
severity = template.get("severity", "")
if template_name:
detection_templates[template_name] = {
"template_type": template_type,
"severity": severity
}
print("====================================")
print("Detection Coverage Summary")
print("====================================")
print("MITRE Techniques Covered:")
print("------------------------------------")
if mitre_techniques:
for technique_id, details in mitre_techniques.items():
print(
f"- {technique_id} - {details.get('technique_name')} "
f"({details.get('tactic')})"
)
else:
print("No MITRE techniques identified.")
print("\nDetection Rule Ideas:")
print("------------------------------------")
if detection_rules:
for rule_name, severity in detection_rules.items():
print(f"- {rule_name} ({severity})")
else:
print("No detection rule ideas identified.")
print("\nDetection Templates:")
print("------------------------------------")
if detection_templates:
for template_name, details in detection_templates.items():
print(
f"- {details.get('template_type')}: {template_name} "
f"({details.get('severity')})"
)
else:
print("No detection templates identified.")
print("====================================")
def print_summary(analysis_results):
if not analysis_results:
print("No analysis results generated.")
return
highest_score = 0
highest_risk = "None"
risk_order = {
"None": 0,
"Low": 1,
"Medium": 2,
"High": 3
}
for result in analysis_results:
score = result.get("risk_score", 0)
risk_level = result.get("risk_level", "None")
if score > highest_score:
highest_score = score
if risk_order.get(risk_level, 0) > risk_order.get(highest_risk, 0):
highest_risk = risk_level
print("====================================")
print("Analysis Summary")
print("====================================")
print(f"Total Results: {len(analysis_results)}")
print(f"Highest Risk: {highest_risk}")
print(f"Highest Score: {highest_score}")
print("====================================")
def apply_case_context(analysis_results, args, analyst_profile):
case_context = {
"case_id": args.case_id or "",
"analyst": args.analyst or analyst_profile.get("analyst", ""),
"alert_source": args.alert_source or "",
"hostname": args.hostname or "",
"username": args.username or "",
"analyst_notes": args.notes or ""
}
has_context = any(value for value in case_context.values())
if not has_context:
return analysis_results
for result in analysis_results:
result["case_context"] = case_context
return analysis_results
def apply_report_branding(analysis_results, args, analyst_profile):
report_branding = {
"report_title": args.report_title or analyst_profile.get("default_report_title", "Encoded Command Analyzer Triage Report"),
"organization": args.organization or analyst_profile.get("organization", ""),
"classification": args.classification or analyst_profile.get("classification", "")
}
# Always attach branding so exported reports have a default title.
for result in analysis_results:
result["report_branding"] = report_branding
return analysis_results
def export_results(analysis_results):
if not analysis_results:
print("No results to export.")
return
json_path = export_to_json(analysis_results)
csv_path = export_to_csv(analysis_results)
markdown_path = export_to_markdown(analysis_results)
html_path = export_to_html(analysis_results)
print("\nExport Complete:")
print(f"- JSON: {json_path}")
print(f"- CSV: {csv_path}")
print(f"- Markdown: {markdown_path}")
print(f"- HTML: {html_path}")
def launch_gui():
try:
subprocess.run([sys.executable, "encoded_command_gui.py"], check=True)
except FileNotFoundError:
print("Could not find encoded_command_gui.py.")
except Exception as error:
print(f"Could not launch GUI: {error}")
def build_parser():
parser = argparse.ArgumentParser(
description="Encoded Command Analyzer - Decode and analyze encoded command-line content."
)
parser.add_argument(
"--input",
help="Analyze a single encoded string."
)
parser.add_argument(
"--file",
help="Analyze a batch file containing one encoded value per line."
)
parser.add_argument(
"--export",
action="store_true",
help="Export analysis results to JSON, CSV, Markdown, and HTML."
)
parser.add_argument(
"--gui",
action="store_true",
help="Launch the Tkinter GUI."
)
parser.add_argument(
"--case-id",
help="Case or incident ID to include in exported reports."
)
parser.add_argument(
"--analyst",
help="Analyst name to include in exported reports."
)
parser.add_argument(
"--alert-source",
help="Alert source or tool name to include in exported reports."
)
parser.add_argument(
"--hostname",
help="Hostname related to the investigation."
)
parser.add_argument(
"--username",
help="Username related to the investigation."
)
parser.add_argument(
"--notes",
help="Analyst notes to include in exported reports."
)
parser.add_argument(
"--report-title",
help="Custom report title to include in exported reports."
)
parser.add_argument(
"--organization",
help="Organization, team, or lab name to include in exported reports."
)
parser.add_argument(
"--classification",
help="Report classification or handling label, such as Internal Use Only."
)
return parser
def main():
parser = build_parser()
args = parser.parse_args()
analyst_profile = load_analyst_profile()
if args.gui:
launch_gui()
return
if args.input and args.file:
print("Use either --input or --file, not both.")
return
analysis_results = []
if args.input:
analysis_results = analyze_single_input(args.input)
elif args.file:
analysis_results = analyze_batch_file(args.file)
else:
print("No input provided.")
print()
parser.print_help()
return
if not analysis_results:
print("No decodable results found.")
return
analysis_results = apply_case_context(analysis_results, args, analyst_profile)
analysis_results = apply_report_branding(analysis_results, args, analyst_profile)
for analysis in analysis_results:
print_analysis_result(analysis)
print_summary(analysis_results)
print_detection_coverage_summary(analysis_results)
if args.export:
export_results(analysis_results)
if __name__ == "__main__":
main()