forked from WithSecureLabs/Kanvas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkanvas.py
More file actions
2226 lines (2081 loc) · 112 KB
/
kanvas.py
File metadata and controls
2226 lines (2081 loc) · 112 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 sqlite3
import shutil
import re
import traceback
import logging
from pathlib import Path
from datetime import datetime
from collections import defaultdict
import openpyxl
from PySide6 import __version__
from PySide6.QtWidgets import (
QApplication, QMessageBox, QPushButton, QMainWindow, QFileDialog, QTreeView, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit,
QComboBox, QGridLayout, QTextEdit, QSizePolicy, QWidget, QDateEdit, QProgressBar, QScrollArea, QHeaderView, QSplashScreen,
QMenu, QStyledItemDelegate, QStyle, QToolTip, QCheckBox
)
from PySide6.QtGui import QStandardItemModel, QStandardItem, QColor, QFont, QPixmap, QKeySequence, QAction, QPainter, QTextOption
from PySide6.QtCore import QFile, Qt, QDate, QRect, QTimer, QSize, QModelIndex, QSortFilterProxyModel
from helper.viz_network import visualize_network
from helper.viz_timeline import open_timeline_window
from helper.reporting.report_builder import open_report_builder
from helper.database_utils import create_all_tables
from helper.download_updates import download_updates
from helper.api_config import open_api_settings
from helper.mapping_defend import open_defend_window
from helper.mapping_attack import mitre_mapping
from helper.mapping_veris import open_veris_window
from helper.bookmarks import display_bookmarks_kb
from helper.lookups.lookup_entraid import open_entra_lookup_window
from helper.resources_data import display_msportals_data, display_event_id_kb
from helper import config, styles
from helper.lookups.lookup_domain import open_domain_lookup_window
from helper.lookups.lookup_cve import open_cve_window
from helper.lookups.lookup_ip import open_ip_lookup_window
from helper.lookups.lookup_file import open_hash_lookup_window
from helper.system_type import EvidenceTypeManager
from helper.lookups.lookup_email import open_email_lookup_window
from helper.lookups.lookup_ransomware import open_ransomware_kb_window
from helper.resources.lolbas import display_lolbas_kb
from helper.resources.artifacts import display_artifacts_kb
from helper.resources.hijacklibs import display_hijacklibs_kb
from helper.resources.windows_sid import display_windows_sid_kb
from helper.resources.lolesxi import display_lolesxi_kb
from helper.resources.loldrivers import display_loldrivers_kb
from helper.stix import convert_indicators_to_stix
from helper.defang import defang_excel_file
from helper.markdown_editor import handle_markdown_editor
from helper.mitre_attack_flow import open_mitre_flow_window
from filelock import FileLock, Timeout
from PySide6.QtGui import QIcon
from shiboken6 import isValid
from helper.windowsui import Ui_KanvasMainWindow
from helper.system_type import SystemTypeManager
from PySide6.QtGui import QFontDatabase
from helper.search_bar import SearchBarWidget
class CustomTreeItemDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
self.highlight_color = styles.COLOR_HIGHLIGHT_BG
self.important_color = styles.COLOR_IMPORTANT_BG
def paint(self, painter, option, index):
text = index.data(Qt.DisplayRole) or ""
painter.save()
rect = option.rect
painter.setRenderHint(QPainter.Antialiasing)
if option.state & QStyle.State_Selected:
painter.fillRect(rect, option.palette.highlight())
elif option.state & QStyle.State_MouseOver:
painter.fillRect(rect, styles.COLOR_MOUSE_OVER_BG)
elif index.row() % 2 == 1:
painter.fillRect(rect, styles.COLOR_ALTERNATE_ROW_BG)
text_rect = rect.adjusted(8, 4, -8, -4)
important_keywords = ['critical', 'high', 'alert', 'error', 'failed', 'blocked']
is_important = any(keyword.lower() in text.lower() for keyword in important_keywords)
if is_important:
painter.setPen(styles.COLOR_IMPORTANT_TEXT)
font = painter.font()
font.setBold(True)
painter.setFont(font)
painter.drawText(text_rect, Qt.AlignLeft | Qt.AlignVCenter, text)
painter.restore()
def sizeHint(self, option, index):
text = index.data(Qt.DisplayRole) or ""
if not text:
return QSize(100, 24)
font_metrics = option.fontMetrics
text_rect = font_metrics.boundingRect(text)
width = max(100, text_rect.width() + 16)
height = max(24, text_rect.height() + 8)
return QSize(width, height)
def helpEvent(self, event, view, option, index):
if event.type() == event.Type.ToolTip:
text = index.data(Qt.DisplayRole) or ""
if text and len(text) > 50:
QToolTip.showText(event.globalPos(), text, view)
return True
return super().helpEvent(event, view, option, index)
class MainApp:
def __init__(self):
self.app = QApplication(sys.argv)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename='kanvas.log')
self.logger = logging.getLogger(__name__)
image_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")
logo_path = os.path.join(image_dir, "logo.png")
app_icon = QIcon(logo_path)
self.app.setWindowIcon(app_icon)
splash_pixmap = QPixmap(logo_path)
if not splash_pixmap.isNull():
splash_pixmap = splash_pixmap.scaled(300, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.splash = QSplashScreen(splash_pixmap)
else:
splash_pixmap = QPixmap(300, 150)
splash_pixmap.fill(QColor(40, 44, 52))
self.splash = QSplashScreen(splash_pixmap)
self.splash.showMessage("KANVAS\n \nLoading...", Qt.AlignCenter, QColor(255, 255, 255))
self.splash.show()
self.app.processEvents()
self.child_windows = []
self.mitre_flow_window = None
self.db_path = "kanvas.db"
self.file_lock = None
self.read_only_mode = False
self.splash.showMessage("Initializing database...", Qt.AlignBottom | Qt.AlignCenter, QColor(255, 255, 255))
self.app.processEvents()
create_all_tables(self.db_path)
self.system_type_manager = SystemTypeManager(self.db_path)
self.splash.showMessage("Loading user interface...", Qt.AlignBottom | Qt.AlignCenter, QColor(255, 255, 255))
self.app.processEvents()
self.window = self.load_ui()
self.window.closeEvent = self.closeEvent
self.evidence_type_manager = EvidenceTypeManager(self.db_path, self.window)
from helper.reporting.report_engine import ReportEngine
self.report_engine = ReportEngine(self.window, self.db_path)
self.current_workbook = None
self.current_file_path = None
self.current_sheet_name = None
self.proxy_model = None
self.search_bar = None
self.splash.showMessage("Connecting UI elements...", Qt.AlignBottom | Qt.AlignCenter, QColor(255, 255, 255))
self.app.processEvents()
self.connect_ui_elements()
QTimer.singleShot(1000, self.finish_loading)
def get_monospace_font(self):
if sys.platform == "darwin":
font_families = ["SF Mono", "Monaco", "Menlo", "Courier"]
elif sys.platform == "win32":
font_families = ["Consolas", "Courier New", "Lucida Console"]
else:
font_families = ["DejaVu Sans Mono", "Liberation Mono", "Courier"]
for font in font_families:
if font in QFontDatabase.families():
return font
return "Courier"
def get_sans_serif_font(self):
if sys.platform == "darwin":
font_families = ["SF Pro Display", "Helvetica Neue", "Helvetica", "Arial"]
elif sys.platform == "win32":
font_families = ["Segoe UI", "Arial", "Calibri", "Tahoma"]
else:
font_families = ["Ubuntu", "DejaVu Sans", "Liberation Sans", "Arial"]
for font in font_families:
if font in QFontDatabase.families():
return font
return "Arial"
def finish_loading(self):
self.window.showMaximized()
self.splash.finish(self.window)
def get_lock_path(self, excel_path):
return f"{excel_path}.lock"
def acquire_file_lock(self, file_path):
try:
if self.file_lock:
self.release_file_lock()
lock_path = self.get_lock_path(file_path)
self.file_lock = FileLock(lock_path, timeout=1)
try:
self.file_lock.acquire(timeout=1)
self.read_only_mode = False
return True
except Timeout:
self.logger.info(f"File {file_path} is locked by another process")
result = QMessageBox.question( self.window, "File is in use", f"The file is currently being edited by another user.\nDo you want to open it in read-only mode?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
if result == QMessageBox.Yes:
self.read_only_mode = True
return False
else:
return None
except Exception as e:
self.logger.error(f"Error acquiring lock: {e}")
self.file_lock = None
return None
def release_file_lock(self):
if self.file_lock:
try:
if hasattr(self.file_lock, 'is_locked') and self.file_lock.is_locked:
self.file_lock.release()
self.logger.info("File lock released")
except Exception as e:
self.logger.error(f"Error releasing file lock: {e}")
finally:
self.file_lock = None
def closeEvent(self, event):
self.release_file_lock()
if self.mitre_flow_window:
try:
self.mitre_flow_window.close()
self.mitre_flow_window = None
except Exception as e:
self.logger.error(f"Error closing MITRE Flow window: {e}")
for window in self.child_windows:
if window and hasattr(window, 'setEnabled'):
window.setEnabled(False)
windows_to_close = self.child_windows.copy()
for i, window in enumerate(windows_to_close):
try:
if window and hasattr(window, 'close'):
window.close()
QApplication.processEvents()
except Exception as e:
self.logger.error(f"Error during first close attempt: {e}")
remaining = [w for w in self.child_windows if hasattr(w, 'isVisible') and w.isVisible()]
if remaining:
self.logger.info(f"Found {len(remaining)} windows still open, forcing deletion...")
for window in remaining:
try:
self.logger.info(f"Force closing: {window.windowTitle() if hasattr(window, 'windowTitle') else 'Unknown'}")
window.setAttribute(Qt.WA_DeleteOnClose, True)
window.setParent(None)
window.close()
window.deleteLater()
QApplication.processEvents()
except Exception as e:
self.logger.error(f"Error during forced close: {e}")
self.child_windows.clear()
event.accept()
def load_ui(self):
window = QMainWindow()
ui = Ui_KanvasMainWindow()
ui.setupUi(window)
window.ui = ui
return window
def connect_ui_elements(self):
self.tree_view = self.window.ui.treeViewMain
if self.tree_view:
self.apply_treeview_styling()
self.configure_treeview_properties()
self.tree_view.doubleClicked.connect(self.edit_row)
self.tree_view.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree_view.customContextMenuRequested.connect(self.show_context_menu)
# Add search bar above tree view
self.setup_search_bar()
else:
self.logger.warning("treeViewMain not found!")
self.connect_button("left_button_2", self.handle_veris_window)
self.connect_button("left_button_3", self.handle_defend_mapping)
self.connect_button("left_button_4", self.handle_mitre_mapping)
self.connect_button("left_button_5", self.handle_visualize_network)
self.connect_button("left_button_6", self.handle_timeline_window)
self.connect_button("left_button_7", self.open_new_case_window)
self.connect_button("left_button_8", self.load_data_into_treeview)
self.connect_button("left_button_9", self.handle_ip_lookup)
self.connect_button("left_button_10", self.handle_ransomware_kb)
self.connect_button("left_button_11", self.handle_domain_lookup)
self.connect_button("left_button_12", self.handle_hash_lookup)
self.connect_button("left_button_15", self.handle_markdown_editor)
self.connect_button("left_button_16", self.display_bookmarks_kb)
self.connect_button("left_button_18", self.open_api_settings)
self.connect_button("left_button_19", self.handle_download_updates)
self.connect_button("left_button_17", self.display_event_id_kb)
self.connect_button("left_button_13", self.entra_appid)
self.connect_button("left_button_14", self.handle_cve_lookup)
self.connect_button("left_button_21", self.handle_mitre_flow)
self.connect_button("left_button_23", self.handle_report_builder)
self.connect_button("left_button_22", self.handle_email_lookup)
self.connect_button("down_button_1", self.add_new_row)
self.connect_button("down_button_2", self.delete_row)
self.connect_button("down_button_3", self.load_sheet)
self.connect_button("down_button_6", self.defang)
self.connect_button("down_button_7", self.handle_stix_export)
self.connect_button("down_button_8", self.evidence_type_manager.show_add_evidence_type_dialog)
self.connect_button("down_button_9", self.handle_add_system_type)
self.connect_button("more_button", self.handle_more_button)
self.setup_more_button_menu()
self.hide_bottom_buttons()
def connect_button(self, button_name, handler):
button = getattr(self.window.ui, button_name, None)
if button:
button.clicked.connect(handler)
else:
self.logger.warning(f"{button_name} not found!")
def hide_bottom_buttons(self):
try:
self.window.ui.footerLayout.removeWidget(self.window.ui.down_button_2)
self.window.ui.footerLayout.removeWidget(self.window.ui.down_button_3)
self.window.ui.down_button_2.hide()
self.window.ui.down_button_3.hide()
self.logger.info("Bottom buttons 'Delete Entry' and 'Refresh Table' have been hidden")
except Exception as e:
self.logger.error(f"Error hiding bottom buttons: {e}")
def restore_bottom_buttons(self):
try:
self.window.ui.down_button_2.show()
self.window.ui.down_button_3.show()
self.window.ui.footerLayout.insertWidget(1, self.window.ui.down_button_2)
self.window.ui.footerLayout.insertWidget(2, self.window.ui.down_button_3)
self.logger.info("Bottom buttons 'Delete Entry' and 'Refresh Table' have been restored")
except Exception as e:
self.logger.error(f"Error restoring bottom buttons: {e}")
def get_platform_font_settings(self):
if sys.platform == "darwin":
return "font-size: 11pt; font-family: 'Helvetica Neue', 'Helvetica', Arial, sans-serif;"
elif sys.platform == "win32":
return "font-size: 9pt; font-family: 'Segoe UI', 'Tahoma', Arial, sans-serif;"
else:
return "font-size: 10pt; font-family: 'Ubuntu', 'DejaVu Sans', Arial, sans-serif;"
def apply_treeview_styling(self):
font_settings = self.get_platform_font_settings()
modern_style = styles.TREE_VIEW_MODERN_STYLE_TEMPLATE.format(font_settings)
self.tree_view.setStyleSheet(modern_style)
def configure_treeview_properties(self):
custom_delegate = CustomTreeItemDelegate(self.tree_view)
self.tree_view.setItemDelegate(custom_delegate)
self.tree_view.setAlternatingRowColors(True)
self.tree_view.setRootIsDecorated(True)
self.tree_view.setSortingEnabled(True)
self.tree_view.setSelectionBehavior(QTreeView.SelectRows)
self.tree_view.setSelectionMode(QTreeView.ExtendedSelection)
self.tree_view.setDragDropMode(QTreeView.NoDragDrop)
self.tree_view.setDefaultDropAction(Qt.IgnoreAction)
self.tree_view.setWordWrap(True)
self.tree_view.setUniformRowHeights(True)
self.tree_view.setToolTip("Click on items to view details. Use Ctrl+Click for multiple selections.")
header = self.tree_view.header()
if header:
header.setStretchLastSection(True)
header.setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
header.setHighlightSections(True)
header.setSortIndicatorShown(True)
header.setToolTip("Click column headers to sort. Drag to resize columns.")
self.tree_view.resizeColumnToContents(0)
def apply_standard_treeview_styling(self, tree_view):
if not tree_view:
return
if sys.platform == "darwin":
font_settings = "font-size: 10pt; font-family: 'Helvetica Neue', 'Helvetica', Arial, sans-serif;"
elif sys.platform == "win32":
font_settings = "font-size: 8pt; font-family: 'Segoe UI', 'Tahoma', Arial, sans-serif;"
else:
font_settings = "font-size: 9pt; font-family: 'Ubuntu', 'DejaVu Sans', Arial, sans-serif;"
standard_style = styles.TREE_VIEW_STANDARD_STYLE_TEMPLATE.format(font_settings)
tree_view.setStyleSheet(standard_style)
tree_view.setAlternatingRowColors(True)
tree_view.setSelectionBehavior(QTreeView.SelectRows)
tree_view.setSortingEnabled(True)
tree_view.setWordWrap(True)
tree_view.setUniformRowHeights(True)
header = tree_view.header()
if header:
header.setStretchLastSection(True)
header.setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
header.setHighlightSections(True)
header.setSortIndicatorShown(True)
tree_view.resizeColumnToContents(0)
def show_context_menu(self, position):
if not self.tree_view or not self.tree_view.model():
return
selected_indices = self.tree_view.selectionModel().selectedRows()
has_selection = len(selected_indices) > 0
context_menu = QMenu(self.tree_view)
edit_action = QAction("✏️ Edit Row", self.tree_view)
edit_action.triggered.connect(self.edit_row_from_context)
edit_action.setEnabled(has_selection and not self.read_only_mode)
context_menu.addAction(edit_action)
add_action = QAction("➕ Add New Row", self.tree_view)
add_action.triggered.connect(self.add_new_row)
add_action.setEnabled(not self.read_only_mode)
context_menu.addAction(add_action)
context_menu.addSeparator()
duplicate_action = QAction("📋 Duplicate Row", self.tree_view)
duplicate_action.triggered.connect(self.duplicate_row)
duplicate_action.setEnabled(has_selection and not self.read_only_mode)
context_menu.addAction(duplicate_action)
copy_action = QAction("📄 Copy Row Data", self.tree_view)
copy_action.triggered.connect(self.copy_row_data)
copy_action.setEnabled(has_selection)
context_menu.addAction(copy_action)
context_menu.addSeparator()
delete_action = QAction("🗑️ Delete Row(s)", self.tree_view)
delete_action.setShortcut(QKeySequence("Delete"))
delete_action.triggered.connect(self.delete_row)
delete_action.setEnabled(has_selection and not self.read_only_mode)
context_menu.addAction(delete_action)
context_menu.addSeparator()
refresh_action = QAction("🔄 Refresh Data", self.tree_view)
refresh_action.triggered.connect(self.load_sheet)
context_menu.addAction(refresh_action)
context_menu.addSeparator()
analysis_menu = context_menu.addMenu("🔍 Analysis")
network_analysis_action = QAction("Network Visualization", self.tree_view)
network_analysis_action.triggered.connect(self.handle_visualize_network)
analysis_menu.addAction(network_analysis_action)
timeline_analysis_action = QAction("Timeline Analysis", self.tree_view)
timeline_analysis_action.triggered.connect(self.handle_timeline_window)
analysis_menu.addAction(timeline_analysis_action)
mitre_analysis_action = QAction("MITRE Mapping", self.tree_view)
mitre_analysis_action.triggered.connect(self.handle_mitre_mapping)
analysis_menu.addAction(mitre_analysis_action)
report_action = QAction("Generate Report...", self.tree_view)
report_action.triggered.connect(self.handle_report_builder)
analysis_menu.addAction(report_action)
context_menu.exec(self.tree_view.mapToGlobal(position))
def check_excel_loaded(self):
if not self.current_workbook or not self.current_file_path:
QMessageBox.warning(self.window, "Warning", "No Excel file loaded. Please load a file first.")
return False
return True
def handle_veris_window(self):
if self.check_excel_loaded():
window = open_veris_window(self.window)
self.track_child_window(window)
def handle_mitre_mapping(self):
if self.check_excel_loaded():
window = mitre_mapping(self.window)
self.track_child_window(window)
def handle_visualize_network(self):
if self.check_excel_loaded():
window = visualize_network(self.window, self.system_type_manager)
self.track_child_window(window)
def handle_timeline_window(self):
if self.check_excel_loaded():
window = open_timeline_window(self.window)
self.track_child_window(window)
self.track_child_window(window)
def handle_download_updates(self):
window = download_updates(self.window)
self.track_child_window(window)
def handle_mitre_flow(self):
try:
if self.mitre_flow_window:
# Window already exists, just show it
self.mitre_flow_window.show()
self.mitre_flow_window.raise_()
self.mitre_flow_window.activateWindow()
self.logger.info("MITRE Flow window shown from cache")
else:
# Create window and show it immediately
# The web view will load when the window is shown (via showEvent)
window = open_mitre_flow_window(self.window)
if window:
self.mitre_flow_window = window
self.track_child_window(window)
# Show window immediately - web view loading is deferred to showEvent
window.show()
window.raise_()
window.activateWindow()
self.logger.info("MITRE Flow window created and shown")
except Exception as e:
self.logger.error(f"Error opening MITRE Attack Flow window: {str(e)}")
QMessageBox.critical(self.window, "Error", f"Failed to open MITRE Attack Flow: {str(e)}")
def open_custom_window(self):
custom_window = QWidget(self.window)
custom_window.setWindowTitle("New Case Details")
custom_window.setMinimumSize(600, 800)
layout = QVBoxLayout()
text_box = QTextEdit()
layout.addWidget(text_box)
submit_button = QPushButton("Submit")
layout.addWidget(submit_button)
def submit_data():
data = text_box.toPlainText()
custom_window.close()
submit_button.clicked.connect(submit_data)
custom_window.setLayout(layout)
self.track_child_window(custom_window)
custom_window.show()
def open_api_settings(self):
open_api_settings(self.window, self.logger, self.child_windows)
def open_new_case_window(self):
file_path, _ = QFileDialog.getSaveFileName(self.window, "Save New Case File", "New_Case.xlsx", "Excel files (*.xlsx)")
if not file_path:
QMessageBox.warning(self.window, "Warning", "No file selected. Case creation canceled.")
return
lock_acquired = False
try:
lock_status = self.acquire_file_lock(file_path)
if lock_status is None:
return
lock_acquired = True
template_file = "sod.xlsx"
if not os.path.exists(template_file):
QMessageBox.critical(self.window, "Error", f"Template file '{template_file}' not found.")
return
shutil.copy(template_file, file_path)
QMessageBox.information(self.window, "Success", f"New case created successfully and saved to {file_path}!")
workbook = openpyxl.load_workbook(file_path)
self.current_file_path = file_path
self.current_workbook = workbook
self.read_only_mode = False
file_status_label = self.window.ui.labelFileStatus
if file_status_label:
file_name = os.path.basename(file_path)
file_status_label.setText(f"Loaded: {file_name}")
else:
self.logger.warning("labelFileStatus not found!")
if self.tree_view:
self.load_data_into_treeview(file_path=file_path, workbook=workbook)
else:
self.logger.warning("treeViewMain not found!")
except Exception as e:
self.logger.error(f"Error creating new case: {e}")
QMessageBox.critical(self.window, "Error", f"Failed to create new case: {e}")
finally:
if lock_acquired and (not hasattr(self, 'current_workbook') or not self.current_workbook):
self.release_file_lock()
def load_data_into_treeview(self, file_path=None, workbook=None):
lock_acquired = False
progress = None
try:
if file_path is None or workbook is None:
file_path, _ = QFileDialog.getOpenFileName(
self.window, "Open Excel File", "", "Excel Files (*.xlsx *.xls)"
)
if not file_path:
self.logger.info("No file selected")
return
progress = QProgressBar()
progress.setWindowTitle("Loading Excel File")
progress.setGeometry(QRect(300, 300, 400, 30))
progress.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
progress.setRange(0, 0)
progress.show()
progress.setFormat("Loading file...")
QApplication.processEvents()
try:
lock_status = self.acquire_file_lock(file_path)
if lock_status is None:
if progress:
progress.close()
return
lock_acquired = True
progress.setFormat("Opening workbook...")
QApplication.processEvents()
workbook = openpyxl.load_workbook(file_path, read_only=self.read_only_mode)
except Exception as e:
if progress:
progress.close()
if lock_acquired:
self.release_file_lock()
lock_acquired = False
self.logger.error(f"Error loading Excel file: {e}")
QMessageBox.critical(self.window, "Error", f"Failed to load Excel file: {e}")
return
self.current_workbook = workbook
self.current_file_path = file_path
self.window.current_workbook = workbook
self.window.current_file_path = file_path
if progress:
progress.setFormat("Updating file status...")
QApplication.processEvents()
file_status_label = self.window.ui.labelFileStatus
if file_status_label:
file_name = os.path.basename(file_path)
read_only_text = " [READ-ONLY]" if self.read_only_mode else ""
file_status_label.setText(f"Loaded: {file_name}{read_only_text}")
else:
self.logger.warning("labelFileStatus not found!")
sheet_dropdown = self.window.ui.comboBoxSheet
if not sheet_dropdown:
if progress:
progress.close()
self.logger.warning("Sheet dropdown (comboBoxSheet) not found!")
return
if progress:
progress.setFormat("Loading sheet names...")
QApplication.processEvents()
sheet_dropdown.clear()
sheet_dropdown.blockSignals(True)
sheet_dropdown.addItems(workbook.sheetnames)
sheet_dropdown.blockSignals(False)
def load_selected_sheet():
selected_sheet_name = sheet_dropdown.currentText()
if not selected_sheet_name:
self.logger.info("No sheet selected")
return
show_progress = sys.platform != "darwin"
sheet_progress = None
if show_progress:
sheet_progress = QProgressBar()
sheet_progress.setWindowTitle(f"Loading Sheet: {selected_sheet_name}")
sheet_progress.setGeometry(QRect(300, 300, 400, 30))
sheet_progress.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
sheet_progress.show()
try:
current_workbook = self.current_workbook
if not current_workbook:
if sheet_progress:
sheet_progress.close()
return
self.current_sheet_name = selected_sheet_name
self.window.current_sheet_name = selected_sheet_name
sheet = current_workbook[selected_sheet_name]
max_row = sheet.max_row
if sheet_progress:
sheet_progress.setRange(0, max_row + 2)
sheet_progress.setValue(0)
sheet_progress.setFormat("Reading headers...")
QApplication.processEvents()
model = QStandardItemModel()
headers = [cell.value for cell in sheet[1]]
model.setHorizontalHeaderLabels(headers)
if sheet_progress:
sheet_progress.setValue(1)
sheet_progress.setFormat("Loading data...")
QApplication.processEvents()
for row_index, row in enumerate(sheet.iter_rows(min_row=2), start=2):
items = [QStandardItem(str(cell.value) if cell.value is not None else "") for cell in row]
model.appendRow(items)
if sheet_progress and (row_index % 100 == 0 or row_index == max_row):
sheet_progress.setValue(row_index)
sheet_progress.setFormat(f"Loading row {row_index}/{max_row}...")
QApplication.processEvents()
if sheet_progress:
sheet_progress.setFormat("Finalizing...")
QApplication.processEvents()
# Use proxy model for filtering
if self.proxy_model is None:
self.proxy_model = QSortFilterProxyModel()
self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.proxy_model.setFilterKeyColumn(-1) # Search all columns
self.proxy_model.setSourceModel(model)
self.tree_view.setModel(self.proxy_model)
self.tree_view.setEditTriggers(
QTreeView.NoEditTriggers if self.read_only_mode else
(QTreeView.DoubleClicked | QTreeView.EditKeyPressed | QTreeView.AnyKeyPressed)
)
for column in range(model.columnCount()):
self.tree_view.resizeColumnToContents(column)
if sheet_progress:
sheet_progress.setValue(max_row + 2)
sheet_progress.close()
except Exception as e:
if sheet_progress:
sheet_progress.close()
self.logger.error(f"Error loading sheet '{selected_sheet_name}': {e}")
self.tree_view.setModel(QStandardItemModel())
sheet_dropdown.currentIndexChanged.connect(load_selected_sheet)
if progress:
progress.setFormat("Initializing sheet view...")
QApplication.processEvents()
sheet_dropdown.setCurrentIndex(0)
load_selected_sheet()
if progress:
progress.close()
except Exception as e:
if progress:
progress.close()
self.logger.error(f"Error in load_data_into_treeview: {e}")
QMessageBox.critical(self.window, "Error", f"Failed to load data into tree view: {e}")
if lock_acquired and not workbook:
self.release_file_lock()
def get_evidence_types_from_db(self):
evidence_types = []
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT DISTINCT evidencetype FROM EvidenceType ORDER BY evidencetype")
evidence_types = [row[0] for row in cursor.fetchall()]
conn.close()
if not evidence_types:
evidence_types = []
except sqlite3.Error as e:
self.logger.error(f"Error fetching evidence types from database: {e}")
evidence_types = []
return evidence_types
def edit_row(self, index):
if self.read_only_mode:
QMessageBox.information(self.window, "Read-Only Mode", "This file is open in read-only mode. You cannot edit its contents.")
return
if not index.isValid():
QMessageBox.warning(self.window, "Warning", "No row selected. Please select a row to edit.")
return
visual_row_index = index.row()
model = self.tree_view.model()
if not model:
QMessageBox.critical(self.window, "Error", "No model found for the tree view.")
return
row_data = []
for col in range(model.columnCount()):
cell_data = model.index(visual_row_index, col).data()
row_data.append(cell_data)
actual_row_index = None
if self.current_workbook and self.current_sheet_name:
sheet = self.current_workbook[self.current_sheet_name]
for excel_row in range(2, sheet.max_row + 1):
excel_row_data = []
for col in range(1, sheet.max_column + 1):
cell_value = sheet.cell(row=excel_row, column=col).value
excel_row_data.append(str(cell_value) if cell_value is not None else "")
if excel_row_data == [str(d) if d is not None else "" for d in row_data]:
actual_row_index = excel_row
break
if actual_row_index is None:
QMessageBox.critical(self.window, "Error", "Could not find matching data row.")
return
row_index = visual_row_index
mitre_tactic_options = []
mitre_techniques_by_tactic = {}
current_tactic = None
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT DISTINCT PID FROM mitre_techniques")
mitre_tactic_options = [row[0] for row in cursor.fetchall()]
for tactic in mitre_tactic_options:
cursor.execute("SELECT ID FROM mitre_techniques WHERE PID = ?", (tactic,))
mitre_techniques_by_tactic[tactic] = [row[0] for row in cursor.fetchall()]
conn.close()
except sqlite3.Error as e:
QMessageBox.critical(self.window, "Error", f"Failed to fetch MITRE values: {e}")
evidence_types = self.get_evidence_types_from_db()
editor_widget = QWidget(self.window)
editor_widget.setWindowTitle("Edit Row - Widget Editor")
import sys
if sys.platform == "darwin":
editor_widget.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint | Qt.WindowTitleHint |
Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint)
editor_widget.setFixedSize(800, 600)
else:
editor_widget.setWindowFlags(Qt.Window | Qt.WindowTitleHint |
Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint |
Qt.WindowMaximizeButtonHint)
editor_widget.setMinimumSize(500, 400)
grid_layout = QGridLayout()
grid_layout.setContentsMargins(15, 15, 15, 15)
grid_layout.setHorizontalSpacing(20)
grid_layout.setVerticalSpacing(10)
input_fields = []
mitre_tactic_combo = None
mitre_technique_combo = None
existing_tactic_value = None
existing_technique_value = None
for col in range(model.columnCount()):
header_text = model.headerData(col, Qt.Horizontal)
cell_data = model.index(row_index, col).data()
header_label = QLabel(f"{header_text}:")
header_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
if header_text and header_text.strip().lower() == config.COL_VISUALIZE.lower():
combo_box = QComboBox()
combo_box.addItems(["Yes", "No"])
if cell_data in ["Yes", "No"]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_EVIDENCE_TYPE.lower():
combo_box = QComboBox()
combo_box.addItems(evidence_types)
if cell_data in evidence_types:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_INDICATOR_TYPE.lower():
combo_box = QComboBox()
combo_box.addItems(["IPAddress","UserName","FileName","FilePath","UserAgent","DomainName","JA3-JA3S","URL","Mutex","Other-Strings","EmailAddress","RegistryPath","GPO"])
if cell_data in ["IPAddress","UserName","FileName","FilePath","UserAgent","DomainName","JA3-JA3S","URL","Mutex","Other-Strings","EmailAddress","RegistryPath","GPO"]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_LOCATION.lower():
combo_box = QComboBox()
combo_box.addItems(["On-Prem", "Unknown", "Cloud-Generic", "Cloud-Azure", "Cloud-AWS", "Clous-GCP", "3rd Party Applications - Cloud"])
if cell_data in ["On-Prem", "Unknown", "Cloud-Generic", "Cloud-Azure", "Cloud-AWS", "Clous-GCP", "3rd Party Applications - Cloud"]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_CURRENT_STATUS.lower():
combo_box = QComboBox()
combo_box.addItems(["Completed" , "In Progress", "On Hold", "Not Started" ])
if cell_data in ["Completed" , "In Progress", "On Hold", "Not Started" ]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_PRIORITY.lower():
combo_box = QComboBox()
combo_box.addItems(["High" ,"Medium" ,"Low" ])
if cell_data in ["High" ,"Medium" ,"Low" ]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_EVIDENCE_COLLECTED.lower():
combo_box = QComboBox()
combo_box.addItems(["Yes", "No" ])
if cell_data in ["Yes", "No" ]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_TARGET_TYPE.lower():
combo_box = QComboBox()
combo_box.addItems(["Machine", "Identity", "Others"])
if cell_data in ["Machine", "Identity", "Others"]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_SYSTEM_TYPE.lower():
combo_box = QComboBox()
system_type_options = self.system_type_manager.get_system_type_options()
combo_box.addItems([option[0] for option in system_type_options])
if cell_data in [option[0] for option in system_type_options]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_ACCOUNT_TYPE.lower():
combo_box = QComboBox()
combo_box.addItems(["Normal User Account - Local","Normal User Account - On-Prem AD","Normal User Account - Azure","Service Account", "Domain Admin", "Global Admin - Azure", "Service Principle - Azure", "Computer Account", "Local Administrator"])
if cell_data in ["Normal User Account - Local","Normal User Account - On-Prem AD","Normal User Account - Azure","Service Account", "Domain Admin", "Global Admin - Azure", "Service Principle - Azure", "Computer Account", "Local Administrator"]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text.strip().lower() == config.COL_ENTRY_POINT.lower():
combo_box = QComboBox()
combo_box.addItems(["Yes", "No" ])
if cell_data in ["Yes", "No" ]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and (header_text.strip().lower() == config.COL_NOTES.lower() or header_text.strip().lower() == config.COL_ACTIVITY.lower()):
text_edit = QTextEdit()
text_edit.setPlainText(cell_data if cell_data else "")
input_field = text_edit
elif header_text and header_text.strip().lower() == config.COL_DATE_RECEIVED.lower() and self.current_sheet_name == config.SHEET_EVIDENCE_TRACKER:
date_received_container = QWidget()
date_received_layout = QHBoxLayout(date_received_container)
date_received_layout.setContentsMargins(0, 0, 0, 0)
date_not_received_cb = QCheckBox("Date not yet received")
date_received_edit = QDateEdit()
date_received_edit.setCalendarPopup(True)
date_received_edit.setDate(QDate.currentDate())
if not cell_data or not str(cell_data).strip():
date_not_received_cb.setChecked(True)
date_received_edit.setEnabled(False)
else:
date_not_received_cb.setChecked(False)
date_received_edit.setEnabled(True)
try:
date_received_edit.setDate(QDate.fromString(str(cell_data).strip(), "yyyy-MM-dd"))
except Exception:
pass
def toggle_date_received_edit(checked):
date_received_edit.setEnabled(not checked)
date_not_received_cb.toggled.connect(toggle_date_received_edit)
date_received_layout.addWidget(date_not_received_cb)
date_received_layout.addWidget(date_received_edit)
grid_layout.addWidget(header_label, col, 0)
grid_layout.addWidget(date_received_container, col, 1)
input_fields.append(("date_received_optional", date_not_received_cb, date_received_edit))
continue
elif header_text and header_text.strip().lower() in [config.COL_DATE_ADDED.lower(), config.COL_DATE_UPDATED.lower(), config.COL_DATE_COMPLETED.lower(), config.COL_DATE_REQUESTED.lower(), config.COL_DATE_RECEIVED.lower()]:
date_edit = QDateEdit()
date_edit.setCalendarPopup(True)
if cell_data:
try:
date_edit.setDate(QDate.fromString(cell_data, "yyyy-MM-dd"))
except Exception as e:
self.logger.error(f"Error parsing date: {e}")
input_field = date_edit
elif header_text and header_text == config.COL_TLP:
combo_box = QComboBox()
combo_box.addItems(["TLP-Red", "TLP-Amber", "TLP-Green", "TLP-Clear"])
if cell_data in ["TLP-Red", "TLP-Amber", "TLP-Green", "TLP-Clear"]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
elif header_text and header_text == config.COL_MITRE_TACTIC:
existing_tactic_value = cell_data if cell_data else ""
combo_box = QComboBox()
combo_box.addItem("")
combo_box.addItems(mitre_tactic_options)
if existing_tactic_value and existing_tactic_value in mitre_tactic_options:
combo_box.setCurrentText(existing_tactic_value)
mitre_tactic_combo = combo_box
input_field = combo_box
elif header_text and header_text == config.COL_MITRE_TECHNIQUE:
existing_technique_value = cell_data if cell_data else ""
combo_box = QComboBox()
combo_box.addItem("")
mitre_technique_combo = combo_box
input_field = combo_box
elif header_text and header_text == config.COL_DIRECTION:
combo_box = QComboBox()
combo_box.addItems([" ","->", "<-", "<->"])
if cell_data in [" ","->", "<-", "<->"]:
combo_box.setCurrentText(cell_data)
input_field = combo_box
else:
line_edit = QLineEdit()
line_edit.setText(cell_data if cell_data else "")
line_edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
input_field = line_edit
grid_layout.addWidget(header_label, col, 0)
grid_layout.addWidget(input_field, col, 1)
input_fields.append(input_field)
if mitre_tactic_combo and mitre_technique_combo:
current_tactic = mitre_tactic_combo.currentText()
if current_tactic and current_tactic in mitre_techniques_by_tactic:
available_techniques = mitre_techniques_by_tactic[current_tactic]
mitre_technique_combo.addItems(available_techniques)
if existing_technique_value:
if existing_technique_value in available_techniques:
mitre_technique_combo.setCurrentText(existing_technique_value)
else:
mitre_technique_combo.addItem(existing_technique_value)
mitre_technique_combo.setCurrentText(existing_technique_value)
def update_techniques(index):
selected_tactic = mitre_tactic_combo.currentText()
current_technique = mitre_technique_combo.currentText()
mitre_technique_combo.clear()
mitre_technique_combo.addItem("")
if selected_tactic and selected_tactic in mitre_techniques_by_tactic:
techniques = mitre_techniques_by_tactic[selected_tactic]
mitre_technique_combo.addItems(techniques)
if current_technique and current_technique in techniques:
mitre_technique_combo.setCurrentText(current_technique)
mitre_tactic_combo.currentIndexChanged.connect(update_techniques)
button_layout = QHBoxLayout()
button_layout.setSpacing(20)
save_button = QPushButton("Save")
cancel_button = QPushButton("Cancel")
button_layout.addStretch()
button_layout.addWidget(save_button)
button_layout.addWidget(cancel_button)
button_layout.addStretch()
main_layout = QVBoxLayout(editor_widget)
main_layout.addLayout(grid_layout)
main_layout.addLayout(button_layout)
editor_widget.setLayout(main_layout)
def save_changes():
try:
if not self.current_workbook or not self.current_sheet_name:
QMessageBox.critical(self.window, "Error", "No workbook or sheet loaded to save changes.")
return
workbook = self.current_workbook
sheet = workbook[self.current_sheet_name]
for col, field in enumerate(input_fields):
if isinstance(field, tuple) and len(field) == 3 and field[0] == "date_received_optional":
_, checkbox, date_edit = field
new_text = "" if checkbox.isChecked() else date_edit.date().toString("yyyy-MM-dd")
elif isinstance(field, QComboBox):
new_text = field.currentText()
elif isinstance(field, QTextEdit):
new_text = field.toPlainText()
elif isinstance(field, QDateEdit):
new_text = field.date().toString("yyyy-MM-dd")
else:
new_text = field.text()
sheet.cell(row=actual_row_index, column=col + 1, value=new_text)
model.setData(model.index(row_index, col), new_text)
workbook.save(self.current_file_path)
editor_widget.close()
except Exception as e:
self.logger.error(f"Error in edit_row save_changes: {e}")
QMessageBox.critical(self.window, "Error", f"Failed to save changes: {e}")
save_button.clicked.connect(save_changes)
cancel_button.clicked.connect(editor_widget.close)
editor_widget.show()
self.track_child_window(editor_widget)
def display_bookmarks_kb(self):
window = display_bookmarks_kb(self, self.db_path)