forked from sujayadkesar/vscexplorer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvscexplorer.py
More file actions
3500 lines (2973 loc) · 140 KB
/
vscexplorer.py
File metadata and controls
3500 lines (2973 loc) · 140 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
import sys
import os
import logging
import datetime
import struct
import shutil
import re
import hashlib
import csv
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import pytsk3
import pyewf
# Check for optional libraries
try:
import pyvshadow
PYVSHADOW_AVAILABLE = True
except ImportError:
PYVSHADOW_AVAILABLE = False
try:
import pybde
BITLOCKER_AVAILABLE = True
except ImportError:
BITLOCKER_AVAILABLE = False
try:
import win32api
import win32file
PYWIN32_AVAILABLE = True
except ImportError:
PYWIN32_AVAILABLE = False
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QTreeWidget, QTreeWidgetItem, QTableWidget, QTableWidgetItem,
QSplitter, QMenuBar, QMenu, QAction, QFileDialog, QMessageBox,
QComboBox, QLabel, QPushButton, QProgressBar, QStatusBar,
QHeaderView, QAbstractItemView, QFrame, QGroupBox, QTextEdit,
QGridLayout, QSpacerItem, QSizePolicy, QLineEdit, QDialog,
QDialogButtonBox, QToolBar, QListWidget, QListWidgetItem,
QTabWidget, QCheckBox, QRadioButton, QButtonGroup, QScrollArea,
QFormLayout, QStyleFactory
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer, QSize, QRect, QFileInfo, QMutex, QMutexLocker
from PyQt5.QtGui import QIcon, QFont, QPixmap, QStandardItemModel, QStandardItem, QColor, QPalette
# Configure enhanced logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('forensic_explorer.log', encoding='utf-8')
]
)
logger = logging.getLogger('VSCExplorer')
class EWFImgInfo(pytsk3.Img_Info):
"""Wrapper class to handle EWF images with pytsk3"""
def __init__(self, ewf_handle):
self._ewf_handle = ewf_handle
super(EWFImgInfo, self).__init__(url="", type=pytsk3.TSK_IMG_TYPE_EXTERNAL)
def close(self):
self._ewf_handle.close()
def read(self, offset, size):
self._ewf_handle.seek(offset)
return self._ewf_handle.read(size)
def get_size(self):
return self._ewf_handle.get_media_size()
class BitLockerFileObject:
"""File-like object for BitLocker partition access"""
def __init__(self, img_info, offset, size):
self.img_info = img_info
self.partition_offset = offset
self.partition_size = size
self.position = 0
def read(self, size=-1):
if size == -1:
size = self.partition_size - self.position
if self.position + size > self.partition_size:
size = self.partition_size - self.position
if size <= 0:
return b''
data = self.img_info.read(self.partition_offset + self.position, size)
self.position += len(data)
return data
def seek(self, position, whence=0):
if whence == 0:
self.position = position
elif whence == 1:
self.position += position
elif whence == 2:
self.position = self.partition_size + position
self.position = max(0, min(self.position, self.partition_size))
return self.position
def tell(self):
return self.position
def close(self):
pass
class DecryptedVolumeAccess(pytsk3.Img_Info):
"""Custom Img_Info class to access decrypted BitLocker volume through pybde"""
def __init__(self, bde_volume):
self.bde_volume = bde_volume
super(DecryptedVolumeAccess, self).__init__(url="", type=pytsk3.TSK_IMG_TYPE_EXTERNAL)
def close(self):
pass
def read(self, offset, size):
self.bde_volume.seek_offset(offset, 0)
return self.bde_volume.read_buffer(size)
def get_size(self):
return self.bde_volume.get_size()
class VShadowVolume(object):
"""Volume wrapper for VSS access."""
def __init__(self, img_info, offset):
self._img_info = img_info
self._offset = offset
self._current_offset = 0
def seek(self, offset, whence=0):
if whence == 0:
self._current_offset = offset
elif whence == 1:
self._current_offset += offset
elif whence == 2:
size = self._img_info.get_size() - self._offset
self._current_offset = size + offset
return self._current_offset
def tell(self):
return self._current_offset
def read(self, size):
try:
data = self._img_info.read(self._offset + self._current_offset, size)
self._current_offset += len(data)
return data
except Exception as e:
logger.debug(f"Error reading from image: {str(e)}")
return b''
def close(self):
pass
class VShadowImgInfo(pytsk3.Img_Info):
"""Interface for pytsk3 to access VSS stores."""
def __init__(self, store):
self._store = store
super(VShadowImgInfo, self).__init__(url="", type=pytsk3.TSK_IMG_TYPE_EXTERNAL)
def close(self):
self._store.close()
def read(self, offset, size):
self._store.seek(offset)
return self._store.read(size)
def get_size(self):
return self._store.get_size()
class BitLockerInfo:
"""Class to store comprehensive BitLocker information"""
def __init__(self):
self.is_encrypted = False
self.volume_id = ""
self.encryption_method = ""
self.encryption_method_name = ""
self.volume_label = ""
self.creation_time = ""
self.description = ""
self.key_protectors = []
self.is_unlocked = False
self.bde_volume = None
self.volume_size = 0
class KeyProtectorInfo:
"""Class to store key protector information"""
def __init__(self, index, protector_type, type_code, guid):
self.index = index
self.protector_type = protector_type
self.type_code = type_code
self.guid = guid
class PartitionInfo:
"""Class to store partition information"""
def __init__(self, index, description, start_offset, size, fs_type="Unknown"):
self.index = index
self.description = description
self.start_offset = start_offset
self.size = size
self.fs_type = fs_type
self.vss_copies = []
self.bitlocker_info = BitLockerInfo()
self.has_real_vss = False
def __str__(self):
size_mb = self.size / (1024 * 1024)
bitlocker_status = " [BitLocker]" if self.bitlocker_info.is_encrypted else ""
return f"Partition {self.index}: {self.description} ({size_mb:.1f} MB) - {self.fs_type}{bitlocker_status}"
class VSSCopy:
"""Enhanced class to store comprehensive VSS copy information"""
def __init__(self, index, creation_time_utc, size=0, store_id="", shadow_copy_id="", provider=""):
self.index = index
self.creation_time_utc = creation_time_utc
self.size = size
self.store_id = store_id
self.shadow_copy_id = shadow_copy_id
self.provider = provider
def __str__(self):
return f"Shadow Copy {self.index+1} - {self.creation_time_utc}"
class ExportOptionsDialog(QDialog):
"""Improved dialog for export options with better visibility"""
def __init__(self, parent=None):
super().__init__(parent)
self.generate_csv = False
self.include_hashes = False
self.hash_types = []
self.init_ui()
def init_ui(self):
self.setWindowTitle("Export Configuration")
self.resize(500, 500)
self.setModal(True)
# Set window icon if available
if os.path.exists("logo.png"):
self.setWindowIcon(QIcon("logo.png"))
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(20)
# Title
title = QLabel("Export Configuration")
title.setStyleSheet("""
QLabel {
font-size: 18px;
font-weight: bold;
color: #2196F3;
padding: 12px;
}
""")
title.setAlignment(Qt.AlignCenter)
layout.addWidget(title)
# CSV Report option
csv_group = QGroupBox("Export Summary Report")
csv_group.setStyleSheet("""
QGroupBox {
font-weight: bold;
border: 2px solid #cccccc;
border-radius: 8px;
margin-top: 16px;
padding-top: 16px;
background-color: white;
font-size: 14px;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 16px;
padding: 0 10px 0 10px;
color: #333333;
}
""")
csv_layout = QVBoxLayout()
csv_layout.setSpacing(12)
self.csv_checkbox = QCheckBox("Generate CSV export summary report")
self.csv_checkbox.setChecked(True)
self.csv_checkbox.setStyleSheet("""
QCheckBox {
font-size: 14px;
font-weight: normal;
padding: 8px;
spacing: 8px;
}
QCheckBox::indicator {
width: 20px;
height: 20px;
}
""")
self.csv_checkbox.toggled.connect(self.on_csv_toggled)
csv_layout.addWidget(self.csv_checkbox)
csv_info = QLabel("Includes file metadata, timestamps, and export status")
csv_info.setStyleSheet("""
color: #666;
font-size: 12px;
margin-left: 30px;
padding: 4px;
""")
csv_layout.addWidget(csv_info)
csv_group.setLayout(csv_layout)
layout.addWidget(csv_group)
# Hash options
self.hash_group = QGroupBox("File Hash Calculation")
self.hash_group.setStyleSheet("""
QGroupBox {
font-weight: bold;
border: 2px solid #cccccc;
border-radius: 8px;
margin-top: 16px;
padding-top: 16px;
background-color: white;
font-size: 14px;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 16px;
padding: 0 10px 0 10px;
color: #333333;
}
""")
hash_layout = QVBoxLayout()
hash_layout.setSpacing(12)
self.hash_checkbox = QCheckBox("Include file hashes in report")
self.hash_checkbox.setStyleSheet("""
QCheckBox {
font-size: 14px;
font-weight: normal;
padding: 8px;
spacing: 8px;
}
QCheckBox::indicator {
width: 20px;
height: 20px;
}
""")
self.hash_checkbox.toggled.connect(self.on_hash_toggled)
hash_layout.addWidget(self.hash_checkbox)
# Hash type selection
self.hash_types_widget = QWidget()
hash_types_layout = QVBoxLayout(self.hash_types_widget)
hash_types_layout.setContentsMargins(30, 12, 0, 0)
hash_types_layout.setSpacing(8)
hash_label = QLabel("Select hash algorithms:")
hash_label.setStyleSheet("font-weight: bold; margin-bottom: 8px; font-size: 13px;")
hash_types_layout.addWidget(hash_label)
self.md5_checkbox = QCheckBox("MD5")
self.sha1_checkbox = QCheckBox("SHA-1")
self.sha256_checkbox = QCheckBox("SHA-256")
self.sha256_checkbox.setChecked(True) # Default
for checkbox in [self.md5_checkbox, self.sha1_checkbox, self.sha256_checkbox]:
checkbox.setStyleSheet("""
QCheckBox {
font-size: 13px;
padding: 4px;
spacing: 8px;
}
QCheckBox::indicator {
width: 16px;
height: 16px;
}
""")
hash_types_layout.addWidget(self.md5_checkbox)
hash_types_layout.addWidget(self.sha1_checkbox)
hash_types_layout.addWidget(self.sha256_checkbox)
hash_note = QLabel("⚠️ Note: Hash calculation may significantly increase export time")
hash_note.setStyleSheet("""
color: #f44336;
font-size: 11px;
font-style: italic;
padding: 8px;
""")
hash_types_layout.addWidget(hash_note)
self.hash_types_widget.setEnabled(False)
hash_layout.addWidget(self.hash_types_widget)
self.hash_group.setLayout(hash_layout)
layout.addWidget(self.hash_group)
# pywin32 warning if not available
if not PYWIN32_AVAILABLE:
warning_label = QLabel("⚠️ pywin32 not available - some timestamp preservation features may be limited")
warning_label.setStyleSheet("""
QLabel {
color: #ff9800;
font-size: 12px;
font-style: italic;
padding: 12px;
background-color: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 4px;
}
""")
layout.addWidget(warning_label)
# Buttons
button_layout = QHBoxLayout()
button_layout.addStretch()
ok_btn = QPushButton("Start Export")
ok_btn.setFixedSize(140, 40)
ok_btn.clicked.connect(self.accept)
ok_btn.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
border-radius: 6px;
font-weight: bold;
font-size: 14px;
}
QPushButton:hover {
background-color: #45a049;
}
""")
cancel_btn = QPushButton("Cancel")
cancel_btn.setFixedSize(120, 40)
cancel_btn.clicked.connect(self.reject)
cancel_btn.setStyleSheet("""
QPushButton {
background-color: #f44336;
color: white;
border: none;
padding: 10px 20px;
border-radius: 6px;
font-weight: bold;
font-size: 14px;
}
QPushButton:hover {
background-color: #d32f2f;
}
""")
button_layout.addWidget(ok_btn)
button_layout.addWidget(cancel_btn)
layout.addLayout(button_layout)
# Initialize state
self.on_csv_toggled(True)
def on_csv_toggled(self, checked):
self.hash_group.setEnabled(checked)
if not checked:
self.hash_checkbox.setChecked(False)
def on_hash_toggled(self, checked):
self.hash_types_widget.setEnabled(checked)
def accept(self):
self.generate_csv = self.csv_checkbox.isChecked()
self.include_hashes = self.hash_checkbox.isChecked()
if self.include_hashes:
self.hash_types = []
if self.md5_checkbox.isChecked():
self.hash_types.append('md5')
if self.sha1_checkbox.isChecked():
self.hash_types.append('sha1')
if self.sha256_checkbox.isChecked():
self.hash_types.append('sha256')
if not self.hash_types:
QMessageBox.warning(self, "Warning", "Please select at least one hash algorithm.")
return
super().accept()
class BitLockerCredentialsDialog(QDialog):
"""Fixed BitLocker credentials dialog with proper radio button logic"""
def __init__(self, bitlocker_info, parent=None):
super().__init__(parent)
self.bitlocker_info = bitlocker_info
self.password = ""
self.recovery_key = ""
self.init_ui()
def init_ui(self):
self.setWindowTitle("BitLocker Volume Unlock")
self.resize(600, 650)
self.setModal(True)
# Set window icon if available
if os.path.exists("logo.png"):
self.setWindowIcon(QIcon("logo.png"))
# Remove help button
self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
self.setStyleSheet("""
QDialog {
background-color: #f5f5f5;
font-size: 14px;
}
QGroupBox {
font-weight: bold;
border: 2px solid #cccccc;
border-radius: 8px;
margin-top: 16px;
padding-top: 16px;
background-color: white;
font-size: 14px;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 16px;
padding: 0 10px 0 10px;
color: #333333;
}
QPushButton {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
border-radius: 6px;
font-weight: bold;
min-width: 90px;
font-size: 14px;
}
QPushButton:hover {
background-color: #45a049;
}
QPushButton:pressed {
background-color: #3e8e41;
}
QLineEdit {
padding: 10px;
border: 2px solid #ddd;
border-radius: 6px;
font-size: 14px;
background-color: white;
min-height: 25px;
}
QLineEdit:focus {
border-color: #4CAF50;
}
QLabel {
font-size: 14px;
}
QRadioButton {
font-size: 14px;
spacing: 8px;
padding: 6px;
}
QRadioButton::indicator {
width: 18px;
height: 18px;
}
""")
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(20)
# Title with lock icon
title_layout = QHBoxLayout()
title = QLabel("🔒 BitLocker Encrypted Volume")
title.setStyleSheet("font-size: 20px; font-weight: bold; color: #d32f2f; margin: 10px; padding: 10px;")
title_layout.addStretch()
title_layout.addWidget(title)
title_layout.addStretch()
layout.addLayout(title_layout)
# Volume Info with better visibility
info_group = QGroupBox("Volume Information")
info_layout = QFormLayout()
info_layout.setSpacing(12)
# Create labels with better formatting
volume_id_label = QLabel(self.bitlocker_info.volume_id or "Unknown")
volume_id_label.setStyleSheet("""
font-family: 'Courier New';
background-color: #f0f0f0;
padding: 8px;
border-radius: 4px;
font-size: 13px;
""")
size_text = f"{self.bitlocker_info.volume_size // (1024*1024):,} MB" if self.bitlocker_info.volume_size > 0 else "Unknown"
size_label = QLabel(size_text)
size_label.setStyleSheet("font-weight: bold; color: #2196F3; font-size: 14px;")
encryption_label = QLabel(self.bitlocker_info.encryption_method_name or "Unknown")
encryption_label.setStyleSheet("font-weight: bold; color: #ff9800; font-size: 14px;")
creation_label = QLabel(self.bitlocker_info.creation_time or "Unknown")
creation_label.setStyleSheet("font-family: 'Courier New'; font-size: 13px;")
info_layout.addRow("Volume ID:", volume_id_label)
info_layout.addRow("Size:", size_label)
info_layout.addRow("Encryption:", encryption_label)
info_layout.addRow("Created:", creation_label)
info_layout.addRow("Description:", QLabel(self.bitlocker_info.description or "Unknown"))
info_group.setLayout(info_layout)
layout.addWidget(info_group)
# Key Protectors with proper visibility
if self.bitlocker_info.key_protectors:
key_group = QGroupBox("Available Key Protectors")
key_layout = QVBoxLayout()
key_layout.setSpacing(8)
for kp in self.bitlocker_info.key_protectors:
kp_widget = QWidget()
kp_widget_layout = QVBoxLayout(kp_widget)
kp_widget_layout.setContentsMargins(0, 0, 0, 0)
kp_widget_layout.setSpacing(6)
kp_text = f"🔑 {kp.protector_type}"
kp_label = QLabel(kp_text)
kp_label.setStyleSheet("""
border: 1px solid #4CAF50;
padding: 10px;
margin: 3px;
border-radius: 6px;
background-color: #f0f8ff;
font-weight: bold;
font-size: 14px;
""")
# Add GUID if available
if kp.guid and kp.guid != "N/A":
guid_label = QLabel(f"ID: {kp.guid}")
guid_label.setStyleSheet("""
font-size: 12px;
color: #666;
font-family: 'Courier New';
margin-left: 16px;
padding: 4px;
""")
kp_widget_layout.addWidget(guid_label)
kp_widget_layout.addWidget(kp_label)
key_layout.addWidget(kp_widget)
key_group.setLayout(key_layout)
layout.addWidget(key_group)
# Determine available key protectors to show only relevant options
has_password = any("Password" in kp.protector_type for kp in self.bitlocker_info.key_protectors)
has_recovery = any("Recovery" in kp.protector_type for kp in self.bitlocker_info.key_protectors)
# Credentials - Fixed logic to show proper UI elements
cred_group = QGroupBox("Unlock Credentials")
cred_layout = QVBoxLayout()
cred_layout.setSpacing(16)
# Initialize radio buttons and input fields
self.password_radio = None
self.recovery_radio = None
self.password_edit = None
self.recovery_edit = None
# Create radio buttons only if both types are available
if has_password and has_recovery:
radio_layout = QHBoxLayout()
self.password_radio = QRadioButton("🔑 Password")
self.recovery_radio = QRadioButton("🔐 Recovery Key")
self.password_radio.setChecked(True)
self.password_radio.setStyleSheet("font-weight: bold; padding: 8px; font-size: 14px;")
self.recovery_radio.setStyleSheet("font-weight: bold; padding: 8px; font-size: 14px;")
radio_layout.addWidget(self.password_radio)
radio_layout.addWidget(self.recovery_radio)
cred_layout.addLayout(radio_layout)
# Connect toggle signal
self.password_radio.toggled.connect(self.toggle_inputs)
elif has_password:
# Only password available
label = QLabel("🔑 Password Authentication")
label.setStyleSheet("font-weight: bold; padding: 8px; font-size: 14px;")
cred_layout.addWidget(label)
elif has_recovery:
# Only recovery key available
label = QLabel("🔐 Recovery Key Authentication")
label.setStyleSheet("font-weight: bold; padding: 8px; font-size: 14px;")
cred_layout.addWidget(label)
else:
# Unknown - show both options
radio_layout = QHBoxLayout()
self.password_radio = QRadioButton("🔑 Password")
self.recovery_radio = QRadioButton("🔐 Recovery Key")
self.password_radio.setChecked(True)
self.password_radio.setStyleSheet("font-weight: bold; padding: 8px; font-size: 14px;")
self.recovery_radio.setStyleSheet("font-weight: bold; padding: 8px; font-size: 14px;")
radio_layout.addWidget(self.password_radio)
radio_layout.addWidget(self.recovery_radio)
cred_layout.addLayout(radio_layout)
# Connect toggle signal
self.password_radio.toggled.connect(self.toggle_inputs)
# Create input fields based on what's available
if has_password or not (has_password or has_recovery):
self.password_edit = QLineEdit()
self.password_edit.setEchoMode(QLineEdit.Password)
self.password_edit.setPlaceholderText("Enter BitLocker password")
cred_layout.addWidget(self.password_edit)
if has_recovery or not (has_password or has_recovery):
self.recovery_edit = QLineEdit()
self.recovery_edit.setPlaceholderText("Enter 48-digit recovery key (######-######-######-######-######-######-######-######)")
cred_layout.addWidget(self.recovery_edit)
# Set initial visibility based on available options
if has_password and has_recovery:
# Both available - show password first
if self.recovery_edit:
self.recovery_edit.hide()
elif has_password and not has_recovery:
# Only password - hide recovery field
if self.recovery_edit:
self.recovery_edit.hide()
elif has_recovery and not has_password:
# Only recovery - hide password field
if self.password_edit:
self.password_edit.hide()
# If neither detected, show both (fallback)
cred_group.setLayout(cred_layout)
layout.addWidget(cred_group)
# Buttons
button_layout = QHBoxLayout()
button_layout.addStretch()
unlock_btn = QPushButton("🔓 Unlock Volume")
unlock_btn.setFixedSize(160, 45)
unlock_btn.clicked.connect(self.accept)
unlock_btn.setStyleSheet("""
QPushButton {
background-color: #2196F3;
font-size: 15px;
padding: 12px 24px;
min-width: 140px;
}
QPushButton:hover {
background-color: #1976D2;
}
""")
cancel_btn = QPushButton("❌ Cancel")
cancel_btn.setFixedSize(140, 45)
cancel_btn.clicked.connect(self.reject)
cancel_btn.setStyleSheet("""
QPushButton {
background-color: #f44336;
font-size: 15px;
padding: 12px 24px;
min-width: 120px;
}
QPushButton:hover {
background-color: #d32f2f;
}
""")
button_layout.addWidget(unlock_btn)
button_layout.addWidget(cancel_btn)
layout.addLayout(button_layout)
def toggle_inputs(self):
"""Toggle between password and recovery key inputs"""
if self.password_radio and self.recovery_radio and self.password_edit and self.recovery_edit:
if self.password_radio.isChecked():
self.password_edit.show()
self.recovery_edit.hide()
self.password_edit.setFocus()
else:
self.password_edit.hide()
self.recovery_edit.show()
self.recovery_edit.setFocus()
def accept(self):
"""Handle unlock button click"""
if self.password_radio and self.password_radio.isChecked() and self.password_edit:
self.password = self.password_edit.text().strip()
if not self.password:
QMessageBox.warning(self, "Warning", "Please enter a password.")
return
elif self.recovery_radio and self.recovery_radio.isChecked() and self.recovery_edit:
self.recovery_key = self.recovery_edit.text().strip()
if not self.recovery_key:
QMessageBox.warning(self, "Warning", "Please enter a recovery key.")
return
elif self.password_edit and self.password_edit.isVisible():
# Single password field visible
self.password = self.password_edit.text().strip()
if not self.password:
QMessageBox.warning(self, "Warning", "Please enter a password.")
return
elif self.recovery_edit and self.recovery_edit.isVisible():
# Single recovery field visible
self.recovery_key = self.recovery_edit.text().strip()
if not self.recovery_key:
QMessageBox.warning(self, "Warning", "Please enter a recovery key.")
return
super().accept()
class BitLockerAnalyzer:
"""BitLocker analysis functionality with proper recovery key handling"""
@staticmethod
def detect_bitlocker(img_info, partition_offset):
"""Detect if partition is BitLocker encrypted"""
try:
boot_sector = img_info.read(partition_offset, 512)
return b'-FVE-FS-' in boot_sector
except Exception:
return False
@staticmethod
def format_recovery_key(recovery_key):
"""Format recovery key properly for pybde"""
# Remove all non-digit characters
clean_key = re.sub(r'[^0-9]', '', recovery_key)
# Ensure it's exactly 48 digits
if len(clean_key) != 48:
raise ValueError(f"Recovery key must be exactly 48 digits, got {len(clean_key)}")
# Format with dashes
formatted = '-'.join([clean_key[i:i+6] for i in range(0, 48, 6)])
return formatted
@staticmethod
def analyze_bitlocker_volume(img_info, partition_offset, partition_size):
"""Analyze BitLocker volume and extract comprehensive information"""
bitlocker_info = BitLockerInfo()
if not BITLOCKER_AVAILABLE:
logger.warning("BitLocker analysis not available - pybde library not installed")
return bitlocker_info
try:
# Create BDE volume object
bde_volume = pybde.volume()
# Create file-like object for the partition
partition_file = BitLockerFileObject(img_info, partition_offset, partition_size)
# Open the BitLocker volume
bde_volume.open_file_object(partition_file)
bitlocker_info.is_encrypted = True
bitlocker_info.volume_size = partition_size
# Get basic volume information
try:
bitlocker_info.volume_id = bde_volume.get_volume_identifier()
except:
bitlocker_info.volume_id = "Unknown"
try:
encryption_method = bde_volume.get_encryption_method()
encryption_methods = {
32768: "AES 128-bit with Diffuser",
32769: "AES 256-bit with Diffuser",
32770: "AES 128-bit",
32771: "AES 256-bit",
32772: "AES 256-bit XTS"
}
bitlocker_info.encryption_method = encryption_method
bitlocker_info.encryption_method_name = encryption_methods.get(
encryption_method, f"Unknown (Code: {encryption_method})"
)
except:
bitlocker_info.encryption_method = 0
bitlocker_info.encryption_method_name = "Unknown"
try:
bitlocker_info.description = bde_volume.get_description()
except:
bitlocker_info.description = "BitLocker Encrypted Volume"
try:
creation_time = bde_volume.get_creation_time()
if creation_time:
if hasattr(creation_time, 'strftime'):
bitlocker_info.creation_time = creation_time.strftime("%Y-%m-%d %H:%M:%S")
else:
bitlocker_info.creation_time = str(creation_time)
else:
bitlocker_info.creation_time = "Unknown"
except:
bitlocker_info.creation_time = "Unknown"
# Get key protectors with better error handling
try:
num_protectors = bde_volume.get_number_of_key_protectors()
for i in range(num_protectors):
try:
kp = bde_volume.get_key_protector(i)
# Get protector type
type_code = None
try:
if hasattr(kp, 'get_type'):
type_code = kp.get_type()
except:
pass
# Map type code to description
type_description = BitLockerAnalyzer.get_key_protector_type_name(type_code)
# Get GUID with better handling
guid = "N/A"
try:
if hasattr(kp, 'get_identifier'):
guid_raw = kp.get_identifier()
if guid_raw:
if isinstance(guid_raw, bytes):
guid = guid_raw.decode('utf-8', errors='replace')
else:
guid = str(guid_raw)
except:
pass
key_protector = KeyProtectorInfo(i, type_description, type_code, guid)
bitlocker_info.key_protectors.append(key_protector)
except Exception as e:
logger.debug(f"Error reading key protector {i}: {e}")
except Exception as e:
logger.debug(f"Error reading key protectors: {e}")
bitlocker_info.bde_volume = bde_volume
except Exception as e:
logger.error(f"Error analyzing BitLocker volume: {e}")
return bitlocker_info
@staticmethod
def get_key_protector_type_name(type_code):
"""Map BitLocker key protector type codes to human-readable names"""
type_map = {
8192: "TPM/Hardware-based",
2048: "Recovery Password",
512: "Password",
256: "Smart Card"
}
if type_code in type_map:
return type_map[type_code]
else:
return f"Unknown Type (Code: {type_code})" if type_code else "Unknown"
@staticmethod
def unlock_bitlocker_volume(bitlocker_info, password=None, recovery_key=None):
"""Unlock BitLocker volume with proper recovery key handling"""
if not bitlocker_info.bde_volume:
return False
try:
unlocked = False
# Try password first
if password:
try:
logger.info("Trying password unlock...")
bitlocker_info.bde_volume.set_password(password.encode('utf-8'))
bitlocker_info.bde_volume.unlock()
if not bitlocker_info.bde_volume.is_locked():
logger.info("Password unlock successful!")
unlocked = True
bitlocker_info.is_unlocked = True
return True
except Exception as e:
logger.debug(f"Password unlock failed: {e}")
# Try recovery key with multiple methods
if not unlocked and recovery_key:
try:
logger.info("Trying recovery key unlock...")
# Format the recovery key properly