-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforensic_analysis_tool.py
More file actions
1392 lines (1167 loc) · 57.1 KB
/
Copy pathforensic_analysis_tool.py
File metadata and controls
1392 lines (1167 loc) · 57.1 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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Windows Forensic Analysis Tool
Production-ready forensic investigation tool with GUI interface
Features: File Recovery, Log Analysis, Timeline Creation, Evidence Collection, Reporting
"""
import os
import sys
import json
import csv
import sqlite3
import datetime
import subprocess
import shutil
import zipfile
import hashlib
import xml.etree.ElementTree as ET
from pathlib import Path
from collections import defaultdict
import threading
import time
import re
import struct
# Platform-specific imports
if os.name == 'nt':
import winreg
else:
# Mock winreg for non-Windows systems
class MockWinReg:
HKEY_CURRENT_USER = None
HKEY_LOCAL_MACHINE = None
def OpenKey(self, *args): pass
def QueryValueEx(self, *args): return ("", 0)
def CloseKey(self, *args): pass
winreg = MockWinReg()
try:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
PYQT_AVAILABLE = True
except ImportError:
print("PyQt5 not available. Please install: pip install PyQt5")
PYQT_AVAILABLE = False
try:
import send2trash
except ImportError:
print("Installing send2trash...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "send2trash"])
import send2trash
# Core forensic analysis classes
class FileRecoveryEngine:
"""Handles deleted file recovery from Recycle Bin and NTFS"""
def __init__(self):
self.recovered_files = []
self.recycle_bin_files = []
def scan_recycle_bin(self):
"""Scan and recover files from Recycle Bin"""
recycle_paths = [
os.path.expanduser("~/.local/share/Trash/files"), # Linux
"C:\\$Recycle.Bin", # Windows
]
for path in recycle_paths:
if os.path.exists(path):
self._scan_directory(path, "recycle_bin")
return self.recycle_bin_files
def scan_deleted_files(self, drive_path="C:\\"):
"""Attempt to recover deleted files using MFT analysis"""
try:
if os.name == 'nt':
self._scan_ntfs_deleted(drive_path)
else:
self._scan_unix_deleted()
except Exception as e:
print(f"Error scanning deleted files: {e}")
return self.recovered_files
def _scan_directory(self, path, source_type):
"""Recursively scan directory for files"""
try:
for root, dirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
file_info = self._get_file_info(file_path, source_type)
if source_type == "recycle_bin":
self.recycle_bin_files.append(file_info)
else:
self.recovered_files.append(file_info)
except Exception as e:
print(f"Error scanning directory {path}: {e}")
def _scan_ntfs_deleted(self, drive_path):
"""Scan NTFS Master File Table for deleted files"""
# This is a simplified implementation
# In production, you'd use libraries like pytsk3 or direct MFT parsing
try:
# Look for recently deleted files in temp directories
temp_dirs = [
os.path.expandvars("%TEMP%"),
os.path.expandvars("%TMP%"),
"C:\\Windows\\Temp",
"C:\\Users\\%USERNAME%\\AppData\\Local\\Temp"
]
for temp_dir in temp_dirs:
if os.path.exists(temp_dir):
self._scan_directory(temp_dir, "deleted")
except Exception as e:
print(f"Error in NTFS scan: {e}")
def _scan_unix_deleted(self):
"""Scan Unix-like systems for deleted files"""
# Check common locations where deleted files might be recovered
search_paths = [
"/tmp",
"/var/tmp",
os.path.expanduser("~/.local/share/Trash")
]
for path in search_paths:
if os.path.exists(path):
self._scan_directory(path, "deleted")
def _get_file_info(self, file_path, source):
"""Extract file metadata"""
try:
stat = os.stat(file_path)
return {
'path': file_path,
'name': os.path.basename(file_path),
'size': stat.st_size,
'modified': datetime.datetime.fromtimestamp(stat.st_mtime),
'accessed': datetime.datetime.fromtimestamp(stat.st_atime),
'created': datetime.datetime.fromtimestamp(stat.st_ctime),
'source': source,
'hash': self._calculate_hash(file_path)
}
except Exception as e:
return {
'path': file_path,
'name': os.path.basename(file_path),
'error': str(e),
'source': source
}
def _calculate_hash(self, file_path):
"""Calculate SHA-256 hash of file"""
try:
hash_sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
except:
return "N/A"
class LogAnalyzer:
"""Analyzes Windows Event Logs and browser history"""
def __init__(self):
self.event_logs = []
self.browser_history = []
self.app_logs = []
def analyze_windows_logs(self):
"""Analyze Windows Event Logs"""
if os.name != 'nt':
print("Windows logs only available on Windows systems")
return []
log_types = ['System', 'Security', 'Application']
for log_type in log_types:
try:
self._parse_event_log(log_type)
except Exception as e:
print(f"Error analyzing {log_type} log: {e}")
return self.event_logs
def analyze_browser_history(self):
"""Extract browser history from Chrome, Firefox, Edge"""
browsers = ['chrome', 'firefox', 'edge']
for browser in browsers:
try:
if browser == 'chrome':
self._extract_chrome_history()
elif browser == 'firefox':
self._extract_firefox_history()
elif browser == 'edge':
self._extract_edge_history()
except Exception as e:
print(f"Error extracting {browser} history: {e}")
return self.browser_history
def _parse_event_log(self, log_type):
"""Parse Windows Event Log using WMI"""
try:
# Using PowerShell to query event logs
cmd = f'powershell "Get-EventLog -LogName {log_type} -Newest 1000 | ConvertTo-Json"'
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
try:
events = json.loads(result.stdout)
if not isinstance(events, list):
events = [events]
for event in events:
self.event_logs.append({
'log_type': log_type,
'event_id': event.get('EventID', 'N/A'),
'level': event.get('EntryType', 'N/A'),
'source': event.get('Source', 'N/A'),
'message': event.get('Message', 'N/A'),
'timestamp': event.get('TimeGenerated', 'N/A'),
'computer': event.get('MachineName', 'N/A')
})
except json.JSONDecodeError:
print(f"Failed to parse {log_type} log JSON")
except Exception as e:
print(f"Error parsing {log_type} event log: {e}")
def _extract_chrome_history(self):
"""Extract Chrome browser history"""
try:
chrome_paths = [
os.path.expanduser("~/AppData/Local/Google/Chrome/User Data/Default/History"),
os.path.expanduser("~/.config/google-chrome/Default/History"),
os.path.expanduser("~/Library/Application Support/Google/Chrome/Default/History")
]
for path in chrome_paths:
if os.path.exists(path):
# Copy database to avoid lock issues
temp_path = path + "_temp"
shutil.copy2(path, temp_path)
conn = sqlite3.connect(temp_path)
cursor = conn.cursor()
cursor.execute("""
SELECT url, title, visit_count, last_visit_time
FROM urls
ORDER BY last_visit_time DESC
LIMIT 1000
""")
for row in cursor.fetchall():
# Convert Chrome timestamp to datetime
timestamp = datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=row[3])
self.browser_history.append({
'browser': 'Chrome',
'url': row[0],
'title': row[1],
'visit_count': row[2],
'timestamp': timestamp
})
conn.close()
os.remove(temp_path)
break
except Exception as e:
print(f"Error extracting Chrome history: {e}")
def _extract_firefox_history(self):
"""Extract Firefox browser history"""
try:
firefox_paths = [
os.path.expanduser("~/AppData/Roaming/Mozilla/Firefox/Profiles"),
os.path.expanduser("~/.mozilla/firefox"),
os.path.expanduser("~/Library/Application Support/Firefox/Profiles")
]
for base_path in firefox_paths:
if os.path.exists(base_path):
for profile in os.listdir(base_path):
profile_path = os.path.join(base_path, profile)
history_path = os.path.join(profile_path, "places.sqlite")
if os.path.exists(history_path):
temp_path = history_path + "_temp"
shutil.copy2(history_path, temp_path)
conn = sqlite3.connect(temp_path)
cursor = conn.cursor()
cursor.execute("""
SELECT p.url, p.title, p.visit_count, h.visit_date
FROM moz_places p
LEFT JOIN moz_historyvisits h ON p.id = h.place_id
ORDER BY h.visit_date DESC
LIMIT 1000
""")
for row in cursor.fetchall():
if row[3]:
timestamp = datetime.datetime.fromtimestamp(row[3] / 1000000)
else:
timestamp = None
self.browser_history.append({
'browser': 'Firefox',
'url': row[0],
'title': row[1],
'visit_count': row[2],
'timestamp': timestamp
})
conn.close()
os.remove(temp_path)
break
except Exception as e:
print(f"Error extracting Firefox history: {e}")
def _extract_edge_history(self):
"""Extract Microsoft Edge browser history"""
try:
edge_paths = [
os.path.expanduser("~/AppData/Local/Microsoft/Edge/User Data/Default/History"),
os.path.expanduser("~/Library/Application Support/Microsoft Edge/Default/History")
]
for path in edge_paths:
if os.path.exists(path):
temp_path = path + "_temp"
shutil.copy2(path, temp_path)
conn = sqlite3.connect(temp_path)
cursor = conn.cursor()
cursor.execute("""
SELECT url, title, visit_count, last_visit_time
FROM urls
ORDER BY last_visit_time DESC
LIMIT 1000
""")
for row in cursor.fetchall():
timestamp = datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=row[3])
self.browser_history.append({
'browser': 'Edge',
'url': row[0],
'title': row[1],
'visit_count': row[2],
'timestamp': timestamp
})
conn.close()
os.remove(temp_path)
break
except Exception as e:
print(f"Error extracting Edge history: {e}")
class TimelineCreator:
"""Creates forensic timeline from various artifacts"""
def __init__(self):
self.timeline_events = []
def create_timeline(self, file_data, log_data, browser_data):
"""Create comprehensive timeline from all data sources"""
self.timeline_events = []
# Add file events
for file_info in file_data:
if 'modified' in file_info:
self.timeline_events.append({
'timestamp': file_info['modified'],
'event_type': 'File Modified',
'source': 'File System',
'details': f"File: {file_info['name']} ({file_info['path']})",
'artifact_type': 'file'
})
if 'accessed' in file_info:
self.timeline_events.append({
'timestamp': file_info['accessed'],
'event_type': 'File Accessed',
'source': 'File System',
'details': f"File: {file_info['name']} ({file_info['path']})",
'artifact_type': 'file'
})
# Add log events
for log_entry in log_data:
if 'timestamp' in log_entry and log_entry['timestamp'] != 'N/A':
try:
timestamp = datetime.datetime.strptime(log_entry['timestamp'], '%m/%d/%Y %I:%M:%S %p')
self.timeline_events.append({
'timestamp': timestamp,
'event_type': f"{log_entry['log_type']} Event",
'source': log_entry['source'],
'details': f"Event ID: {log_entry['event_id']} - {log_entry['message'][:100]}...",
'artifact_type': 'log'
})
except:
pass
# Add browser events
for browser_entry in browser_data:
if browser_entry['timestamp']:
self.timeline_events.append({
'timestamp': browser_entry['timestamp'],
'event_type': 'Web Navigation',
'source': browser_entry['browser'],
'details': f"{browser_entry['title']} ({browser_entry['url']})",
'artifact_type': 'browser'
})
# Sort by timestamp
self.timeline_events.sort(key=lambda x: x['timestamp'] if x['timestamp'] else datetime.datetime.min)
return self.timeline_events
class EvidenceCollector:
"""Handles evidence collection and packaging"""
def __init__(self):
self.evidence_items = []
def add_evidence(self, file_path, description, case_id):
"""Add evidence item with chain of custody"""
evidence_item = {
'id': len(self.evidence_items) + 1,
'file_path': file_path,
'description': description,
'case_id': case_id,
'collected_time': datetime.datetime.now(),
'hash': self._calculate_hash(file_path) if os.path.exists(file_path) else 'N/A',
'size': os.path.getsize(file_path) if os.path.exists(file_path) else 0
}
self.evidence_items.append(evidence_item)
return evidence_item
def export_evidence(self, export_path, format_type='zip'):
"""Export evidence as zip archive or organized folder"""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
if format_type == 'zip':
zip_path = os.path.join(export_path, f"evidence_collection_{timestamp}.zip")
with zipfile.ZipFile(zip_path, 'w') as zipf:
# Add evidence files
for item in self.evidence_items:
if os.path.exists(item['file_path']):
zipf.write(item['file_path'], f"evidence_{item['id']:03d}_{os.path.basename(item['file_path'])}")
# Add chain of custody report
custody_report = self._generate_custody_report()
zipf.writestr("chain_of_custody.json", json.dumps(custody_report, indent=2, default=str))
return zip_path
else: # folder format
folder_path = os.path.join(export_path, f"evidence_collection_{timestamp}")
os.makedirs(folder_path, exist_ok=True)
# Copy evidence files
for item in self.evidence_items:
if os.path.exists(item['file_path']):
dest_path = os.path.join(folder_path, f"evidence_{item['id']:03d}_{os.path.basename(item['file_path'])}")
shutil.copy2(item['file_path'], dest_path)
# Save chain of custody
custody_path = os.path.join(folder_path, "chain_of_custody.json")
with open(custody_path, 'w') as f:
json.dump(self._generate_custody_report(), f, indent=2, default=str)
return folder_path
def _calculate_hash(self, file_path):
"""Calculate SHA-256 hash"""
try:
hash_sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest()
except:
return "N/A"
def _generate_custody_report(self):
"""Generate chain of custody report"""
return {
'report_generated': datetime.datetime.now(),
'total_items': len(self.evidence_items),
'evidence_items': self.evidence_items,
'investigator': os.getenv('USERNAME', 'Unknown'),
'system_info': {
'hostname': os.environ.get('COMPUTERNAME', 'Unknown'),
'platform': sys.platform,
'python_version': sys.version
}
}
class ReportGenerator:
"""Generates forensic reports in various formats"""
def __init__(self):
pass
def generate_csv_report(self, data, output_path, report_type):
"""Generate CSV report"""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{report_type}_report_{timestamp}.csv"
filepath = os.path.join(output_path, filename)
with open(filepath, 'w', newline='', encoding='utf-8') as csvfile:
if data and len(data) > 0:
fieldnames = data[0].keys()
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in data:
# Convert datetime objects to strings
clean_row = {}
for key, value in row.items():
if isinstance(value, datetime.datetime):
clean_row[key] = value.strftime("%Y-%m-%d %H:%M:%S")
else:
clean_row[key] = str(value)
writer.writerow(clean_row)
return filepath
def generate_html_report(self, file_data, log_data, browser_data, timeline_data, output_path):
"""Generate comprehensive HTML report"""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"forensic_report_{timestamp}.html"
filepath = os.path.join(output_path, filename)
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<title>Forensic Analysis Report</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 40px; }}
h1, h2 {{ color: #2c3e50; }}
table {{ border-collapse: collapse; width: 100%; margin-bottom: 30px; }}
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
th {{ background-color: #f2f2f2; }}
.summary {{ background-color: #ecf0f1; padding: 15px; margin-bottom: 20px; }}
.timestamp {{ color: #7f8c8d; font-size: 0.9em; }}
</style>
</head>
<body>
<h1>Forensic Analysis Report</h1>
<div class="summary">
<h2>Report Summary</h2>
<p><strong>Generated:</strong> {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
<p><strong>Investigator:</strong> {os.getenv('USERNAME', 'Unknown')}</p>
<p><strong>System:</strong> {os.environ.get('COMPUTERNAME', 'Unknown')}</p>
<p><strong>Files Analyzed:</strong> {len(file_data)}</p>
<p><strong>Log Entries:</strong> {len(log_data)}</p>
<p><strong>Browser Records:</strong> {len(browser_data)}</p>
<p><strong>Timeline Events:</strong> {len(timeline_data)}</p>
</div>
<h2>File Recovery Results</h2>
<table>
<tr>
<th>File Name</th>
<th>Path</th>
<th>Size</th>
<th>Modified</th>
<th>Source</th>
<th>Hash</th>
</tr>
"""
for file_item in file_data[:100]: # Limit to first 100 files
html_content += f"""
<tr>
<td>{file_item.get('name', 'N/A')}</td>
<td>{file_item.get('path', 'N/A')}</td>
<td>{file_item.get('size', 'N/A')}</td>
<td>{file_item.get('modified', 'N/A')}</td>
<td>{file_item.get('source', 'N/A')}</td>
<td>{file_item.get('hash', 'N/A')[:16]}...</td>
</tr>"""
html_content += """
</table>
<h2>System Log Analysis</h2>
<table>
<tr>
<th>Log Type</th>
<th>Event ID</th>
<th>Source</th>
<th>Timestamp</th>
<th>Message</th>
</tr>"""
for log_entry in log_data[:50]: # Limit to first 50 log entries
html_content += f"""
<tr>
<td>{log_entry.get('log_type', 'N/A')}</td>
<td>{log_entry.get('event_id', 'N/A')}</td>
<td>{log_entry.get('source', 'N/A')}</td>
<td>{log_entry.get('timestamp', 'N/A')}</td>
<td>{str(log_entry.get('message', 'N/A'))[:100]}...</td>
</tr>"""
html_content += """
</table>
<h2>Browser History Analysis</h2>
<table>
<tr>
<th>Browser</th>
<th>Title</th>
<th>URL</th>
<th>Visit Count</th>
<th>Timestamp</th>
</tr>"""
for browser_entry in browser_data[:50]: # Limit to first 50 browser entries
html_content += f"""
<tr>
<td>{browser_entry.get('browser', 'N/A')}</td>
<td>{browser_entry.get('title', 'N/A')}</td>
<td>{browser_entry.get('url', 'N/A')}</td>
<td>{browser_entry.get('visit_count', 'N/A')}</td>
<td>{browser_entry.get('timestamp', 'N/A')}</td>
</tr>"""
html_content += """
</table>
<h2>Timeline Analysis</h2>
<table>
<tr>
<th>Timestamp</th>
<th>Event Type</th>
<th>Source</th>
<th>Details</th>
</tr>"""
for timeline_entry in timeline_data[:100]: # Limit to first 100 timeline entries
html_content += f"""
<tr>
<td>{timeline_entry.get('timestamp', 'N/A')}</td>
<td>{timeline_entry.get('event_type', 'N/A')}</td>
<td>{timeline_entry.get('source', 'N/A')}</td>
<td>{str(timeline_entry.get('details', 'N/A'))[:100]}...</td>
</tr>"""
html_content += """
</table>
<div class="timestamp">
<p>Report generated by Windows Forensic Analysis Tool</p>
</div>
</body>
</html>"""
with open(filepath, 'w', encoding='utf-8') as f:
f.write(html_content)
return filepath
# PyQt5 GUI Application
if PYQT_AVAILABLE:
class ForensicAnalysisGUI(QMainWindow):
def __init__(self):
super().__init__()
self.file_recovery = FileRecoveryEngine()
self.log_analyzer = LogAnalyzer()
self.timeline_creator = TimelineCreator()
self.evidence_collector = EvidenceCollector()
self.report_generator = ReportGenerator()
self.file_data = []
self.log_data = []
self.browser_data = []
self.timeline_data = []
self.init_ui()
def init_ui(self):
self.setWindowTitle('Windows Forensic Analysis Tool')
self.setGeometry(100, 100, 1200, 800)
# Create central widget and main layout
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QHBoxLayout(central_widget)
# Create sidebar
sidebar = QWidget()
sidebar.setFixedWidth(200)
sidebar.setStyleSheet("background-color: #2c3e50; color: white;")
sidebar_layout = QVBoxLayout(sidebar)
# Sidebar buttons
self.btn_file_recovery = QPushButton('File Recovery')
self.btn_log_analysis = QPushButton('Log Analysis')
self.btn_timeline = QPushButton('Timeline')
self.btn_evidence = QPushButton('Evidence Collection')
self.btn_reports = QPushButton('Generate Reports')
sidebar_buttons = [
self.btn_file_recovery,
self.btn_log_analysis,
self.btn_timeline,
self.btn_evidence,
self.btn_reports
]
for btn in sidebar_buttons:
btn.setStyleSheet("""
QPushButton {
background-color: #34495e;
color: white;
border: none;
padding: 10px;
text-align: left;
margin: 2px;
}
QPushButton:hover {
background-color: #3498db;
}
QPushButton:pressed {
background-color: #2980b9;
}
""")
sidebar_layout.addWidget(btn)
sidebar_layout.addStretch()
# Connect sidebar buttons
self.btn_file_recovery.clicked.connect(lambda: self.show_tab(0))
self.btn_log_analysis.clicked.connect(lambda: self.show_tab(1))
self.btn_timeline.clicked.connect(lambda: self.show_tab(2))
self.btn_evidence.clicked.connect(lambda: self.show_tab(3))
self.btn_reports.clicked.connect(lambda: self.show_tab(4))
# Create tab widget
self.tab_widget = QTabWidget()
self.tab_widget.setTabPosition(QTabWidget.North)
# Create tabs
self.create_file_recovery_tab()
self.create_log_analysis_tab()
self.create_timeline_tab()
self.create_evidence_tab()
self.create_reports_tab()
# Add widgets to main layout
main_layout.addWidget(sidebar)
main_layout.addWidget(self.tab_widget, 1)
# Status bar
self.statusBar().showMessage('Ready')
def show_tab(self, index):
self.tab_widget.setCurrentIndex(index)
def create_file_recovery_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Header
header = QLabel('File Recovery Module')
header.setStyleSheet("font-size: 18px; font-weight: bold; color: #2c3e50;")
layout.addWidget(header)
# Buttons
button_layout = QHBoxLayout()
btn_scan_recycle = QPushButton('Scan Recycle Bin')
btn_scan_deleted = QPushButton('Scan Deleted Files')
btn_export_files = QPushButton('Export Results')
btn_scan_recycle.clicked.connect(self.scan_recycle_bin)
btn_scan_deleted.clicked.connect(self.scan_deleted_files)
btn_export_files.clicked.connect(self.export_file_results)
button_layout.addWidget(btn_scan_recycle)
button_layout.addWidget(btn_scan_deleted)
button_layout.addWidget(btn_export_files)
button_layout.addStretch()
layout.addLayout(button_layout)
# Progress bar
self.file_progress = QProgressBar()
layout.addWidget(self.file_progress)
# Results table
self.file_table = QTableWidget()
self.file_table.setColumnCount(6)
self.file_table.setHorizontalHeaderLabels(['Name', 'Path', 'Size', 'Modified', 'Source', 'Hash'])
layout.addWidget(self.file_table)
self.tab_widget.addTab(tab, 'File Recovery')
def create_log_analysis_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Header
header = QLabel('Log Analysis Module')
header.setStyleSheet("font-size: 18px; font-weight: bold; color: #2c3e50;")
layout.addWidget(header)
# Buttons
button_layout = QHBoxLayout()
btn_scan_event_logs = QPushButton('Analyze Event Logs')
btn_scan_browser = QPushButton('Extract Browser History')
btn_export_logs = QPushButton('Export Results')
btn_scan_event_logs.clicked.connect(self.analyze_event_logs)
btn_scan_browser.clicked.connect(self.extract_browser_history)
btn_export_logs.clicked.connect(self.export_log_results)
button_layout.addWidget(btn_scan_event_logs)
button_layout.addWidget(btn_scan_browser)
button_layout.addWidget(btn_export_logs)
button_layout.addStretch()
layout.addLayout(button_layout)
# Progress bar
self.log_progress = QProgressBar()
layout.addWidget(self.log_progress)
# Results tabs
log_tabs = QTabWidget()
# Event logs table
self.event_log_table = QTableWidget()
self.event_log_table.setColumnCount(6)
self.event_log_table.setHorizontalHeaderLabels(['Log Type', 'Event ID', 'Source', 'Timestamp', 'Level', 'Message'])
log_tabs.addTab(self.event_log_table, 'Event Logs')
# Browser history table
self.browser_table = QTableWidget()
self.browser_table.setColumnCount(5)
self.browser_table.setHorizontalHeaderLabels(['Browser', 'Title', 'URL', 'Visit Count', 'Timestamp'])
log_tabs.addTab(self.browser_table, 'Browser History')
layout.addWidget(log_tabs)
self.tab_widget.addTab(tab, 'Log Analysis')
def create_timeline_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Header
header = QLabel('Timeline Creation Module')
header.setStyleSheet("font-size: 18px; font-weight: bold; color: #2c3e50;")
layout.addWidget(header)
# Buttons
button_layout = QHBoxLayout()
btn_create_timeline = QPushButton('Create Timeline')
btn_export_timeline = QPushButton('Export Timeline')
btn_create_timeline.clicked.connect(self.create_timeline)
btn_export_timeline.clicked.connect(self.export_timeline)
button_layout.addWidget(btn_create_timeline)
button_layout.addWidget(btn_export_timeline)
button_layout.addStretch()
layout.addLayout(button_layout)
# Progress bar
self.timeline_progress = QProgressBar()
layout.addWidget(self.timeline_progress)
# Timeline table
self.timeline_table = QTableWidget()
self.timeline_table.setColumnCount(4)
self.timeline_table.setHorizontalHeaderLabels(['Timestamp', 'Event Type', 'Source', 'Details'])
layout.addWidget(self.timeline_table)
self.tab_widget.addTab(tab, 'Timeline')
def create_evidence_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Header
header = QLabel('Evidence Collection Module')
header.setStyleSheet("font-size: 18px; font-weight: bold; color: #2c3e50;")
layout.addWidget(header)
# Case information
case_layout = QHBoxLayout()
case_layout.addWidget(QLabel('Case ID:'))
self.case_id_input = QLineEdit()
case_layout.addWidget(self.case_id_input)
case_layout.addStretch()
layout.addLayout(case_layout)
# Buttons
button_layout = QHBoxLayout()
btn_add_evidence = QPushButton('Add Evidence File')
btn_export_zip = QPushButton('Export as ZIP')
btn_export_folder = QPushButton('Export as Folder')
btn_add_evidence.clicked.connect(self.add_evidence_file)
btn_export_zip.clicked.connect(lambda: self.export_evidence('zip'))
btn_export_folder.clicked.connect(lambda: self.export_evidence('folder'))
button_layout.addWidget(btn_add_evidence)
button_layout.addWidget(btn_export_zip)
button_layout.addWidget(btn_export_folder)
button_layout.addStretch()
layout.addLayout(button_layout)
# Evidence table
self.evidence_table = QTableWidget()
self.evidence_table.setColumnCount(5)
self.evidence_table.setHorizontalHeaderLabels(['ID', 'File Path', 'Description', 'Collected Time', 'Hash'])
layout.addWidget(self.evidence_table)
self.tab_widget.addTab(tab, 'Evidence Collection')
def create_reports_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Header
header = QLabel('Report Generation Module')
header.setStyleSheet("font-size: 18px; font-weight: bold; color: #2c3e50;")
layout.addWidget(header)
# Report options
options_layout = QVBoxLayout()
self.include_files = QCheckBox('Include File Recovery Results')
self.include_logs = QCheckBox('Include Log Analysis Results')
self.include_browser = QCheckBox('Include Browser History')
self.include_timeline = QCheckBox('Include Timeline')
self.include_files.setChecked(True)
self.include_logs.setChecked(True)
self.include_browser.setChecked(True)
self.include_timeline.setChecked(True)
options_layout.addWidget(self.include_files)
options_layout.addWidget(self.include_logs)
options_layout.addWidget(self.include_browser)
options_layout.addWidget(self.include_timeline)
layout.addLayout(options_layout)
# Buttons
button_layout = QHBoxLayout()
btn_generate_csv = QPushButton('Generate CSV Report')
btn_generate_html = QPushButton('Generate HTML Report')
btn_generate_csv.clicked.connect(self.generate_csv_report)
btn_generate_html.clicked.connect(self.generate_html_report)
button_layout.addWidget(btn_generate_csv)
button_layout.addWidget(btn_generate_html)
button_layout.addStretch()
layout.addLayout(button_layout)
# Report preview
self.report_preview = QTextEdit()
self.report_preview.setReadOnly(True)
layout.addWidget(self.report_preview)
self.tab_widget.addTab(tab, 'Generate Reports')
# File Recovery Methods
def scan_recycle_bin(self):
try:
self.statusBar().showMessage("Scanning Recycle Bin...")
self.file_progress.setRange(0, 0) # Indeterminate progress
# Run scan directly in main thread to avoid threading issues
recycle_files = self.file_recovery.scan_recycle_bin()
self.file_data.extend(recycle_files)
self._update_file_table()
self.file_progress.setRange(0, 1)