-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwiredigg_ML_only.py
More file actions
8670 lines (6258 loc) · 368 KB
/
Copy pathwiredigg_ML_only.py
File metadata and controls
8670 lines (6258 loc) · 368 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 tkinter as tk
from tkinter import ttk, messagebox, filedialog, scrolledtext
import threading
import queue
import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pickle
import networkx as nx
import ipaddress
import os
import re
import socket
import warnings
import traceback
from ctypes import windll
from add_ico_hook import resource_path
import ctypes
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2)
except:
try:
ctypes.windll.user32.SetProcessDPIAware()
except:
pass
ico_path = resource_path("wiredigg.ico")
warnings.filterwarnings('ignore')
class NetworkAnalyzer:
def __init__(self, root):
self.root = root
self.root.title("Wiredigg - Advanced Network Analysis Tool")
self.root.geometry("1200x900")
self.root.configure(bg="#2e3440")
root.iconbitmap(ico_path)
# Nordic dark theme setup
self.style = ttk.Style()
self.style.theme_use("clam")
# Basic setup -dark theme with light text
self.style.configure(".", background="#2e3440", foreground="#eceff4")
self.style.configure("TFrame", background="#2e3440")
self.style.configure("TLabel", background="#2e3440", foreground="#eceff4")
self.style.configure("TButton", background="#5e81ac", foreground="#eceff4")
self.style.configure("TNotebook", background="#2e3440", foreground="#eceff4")
self.style.configure("TNotebook.Tab", background="#3b4252", foreground="#eceff4")
self.style.configure("TCheckbutton", background="#2e3440", foreground="#eceff4")
# Mapping to keep text visible in all states
self.style.map("TButton",
foreground=[("active", "#ffffff"), ("disabled", "#a0a0a0")],
background=[("active", "#7799cc"), ("disabled", "#4c6a8f")]
)
self.style.map("TNotebook.Tab", background=[("selected", "#5e81ac")])
# Styles for black text dialogs
self.style.configure("Dialog.TFrame", background="white")
self.style.configure("Dialog.TLabel", background="white", foreground="black")
self.style.configure("Dialog.TButton", background="#e0e0e0", foreground="black")
self.style.map("Dialog.TButton",
foreground=[("active", "black"), ("disabled", "gray")],
background=[("active", "#d0d0d0"), ("disabled", "#f0f0f0")]
)
self.style.configure("Dialog.TCheckbutton", background="white", foreground="black")
self.style.configure("Dialog.TCombobox", foreground="black", fieldbackground="white")
self.style.map("TCombobox",
foreground=[("active", "black"), ("disabled", "gray")],
fieldbackground=[("readonly", "white")]
)
# Global configuration for black text widgets
root.option_add('*TCombobox*Listbox.foreground', 'black')
root.option_add('*TCombobox*Listbox.background', 'white')
# State variables
self.is_capturing = False
self.captured_packets = []
self.packet_queue = queue.Queue()
self.ml_model = None
self.ml_model_trained = False
self.threat_db = None
self.initialize_ml_model()
self.start_background_training()
self.selected_interface = tk.StringVar()
self.filter_text = tk.StringVar()
self.dark_mode = tk.BooleanVar(value=True)
self.promisc_mode = tk.BooleanVar(value=False)
# Initialize threat database
self.init_threat_database()
# Load ML model
self.load_ml_model()
# Create main layout
self.create_main_layout()
# Initialize network interfaces
self.interfaces = self.get_network_interfaces()
self.interface_dropdown['values'] = self.interfaces
if self.interfaces:
self.selected_interface.set(self.interfaces[0])
# Configure timer for UI refresh
self.root.after(100, self.process_packet_queue)
def create_main_layout(self):
# Main frame
main_frame = ttk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Top frame for controls
control_frame = ttk.Frame(main_frame)
control_frame.pack(fill=tk.X, padx=5, pady=5)
# Frame for the first row of controls (interface, filters, buttons)
top_row_frame = ttk.Frame(control_frame)
top_row_frame.pack(fill=tk.X, padx=5, pady=5)
# Dropdown for interfaces
ttk.Label(top_row_frame, text="Interface:", style="BlackText.TLabel",foreground="white").pack(side=tk.LEFT, padx=2)
self.interface_dropdown = ttk.Combobox(top_row_frame, textvariable=self.selected_interface, width=20, foreground="black")
self.interface_dropdown.pack(side=tk.LEFT, padx=2)
# Protocol filter
ttk.Label(top_row_frame, text="Protocol:", style="BlackText.TLabel",foreground="white").pack(side=tk.LEFT, padx=2)
self.proto_filter_var = tk.StringVar()
proto_combo = ttk.Combobox(top_row_frame, textvariable=self.proto_filter_var,
values=["", "TCP", "UDP", "ICMP", "HTTP", "HTTPS", "DNS"], width=6, foreground="black")
proto_combo.pack(side=tk.LEFT, padx=2)
# IP filter
ttk.Label(top_row_frame, text="IP:", style="BlackText.TLabel",foreground="white").pack(side=tk.LEFT, padx=2)
self.ip_filter_var = tk.StringVar()
ip_entry = ttk.Entry(top_row_frame, textvariable=self.ip_filter_var, width=12, foreground="black")
ip_entry.pack(side=tk.LEFT, padx=2)
# Port filter
ttk.Label(top_row_frame, text="Port:", style="BlackText.TLabel",foreground="white").pack(side=tk.LEFT, padx=2)
self.port_filter_var = tk.StringVar()
port_entry = ttk.Entry(top_row_frame, textvariable=self.port_filter_var, width=5, foreground="black")
port_entry.pack(side=tk.LEFT, padx=2)
# Filter buttons
apply_btn = ttk.Button(top_row_frame, text="Apply", command=self.apply_filters, width=7)
apply_btn.pack(side=tk.LEFT, padx=2)
reset_btn = ttk.Button(top_row_frame, text="Reset", command=self.reset_filters, width=6)
reset_btn.pack(side=tk.LEFT, padx=2)
# Promiscuous Mode
promisc_check = ttk.Checkbutton(top_row_frame, text="Promiscuous Mode", variable=self.promisc_mode)
promisc_check.pack(side=tk.LEFT, padx=2)
# Frame for the filter status line (below the first line)
filter_status_frame = ttk.Frame(control_frame)
filter_status_frame.pack(fill=tk.X, padx=5, pady=10)
# Filter status label
self.filter_status = ttk.Label(filter_status_frame, text="No active filters", font=("Arial", 8), foreground="white")
self.filter_status.pack(side=tk.LEFT, padx=5,pady=15)
# Add tooltip to help user
self.create_tooltip(proto_combo, "Select the protocol to filter")
self.create_tooltip(ip_entry, "Filter by source or destination IP address")
self.create_tooltip(port_entry, "Filter by source or destination port")
self.create_tooltip(apply_btn, "Apply selected filters")
self.create_tooltip(reset_btn, "Remove all filters")
# Control buttons
self.start_button = ttk.Button(control_frame, text="Start capture", command=self.start_capture)
self.start_button.pack(side=tk.LEFT, padx=5)
self.stop_button = ttk.Button(control_frame, text="Stop capture", command=self.stop_capture, state=tk.DISABLED)
self.stop_button.pack(side=tk.LEFT, padx=5)
save_button = ttk.Button(control_frame, text="Save capture", command=self.save_capture)
save_button.pack(side=tk.LEFT, padx=5)
load_button = ttk.Button(control_frame, text="Load capture", command=self.load_capture)
load_button.pack(side=tk.LEFT, padx=5)
mlbutton_button = ttk.Button(control_frame, text="Reset ML Model", command=self.reset_ml_model)
mlbutton_button.pack(side=tk.LEFT, padx=5)
test_button = ttk.Button(control_frame, text="Generate test traffic", command=self.generate_test_traffic)
test_button.pack(side=tk.LEFT, padx=5)
info_button = ttk.Button(control_frame, text="Interface info", command=self.show_interface_info)
info_button.pack(side=tk.LEFT, padx=5)
simple_send_button = ttk.Button(control_frame, text="Send Simple Package", command=self.send_simple_packet)
simple_send_button.pack(side=tk.LEFT, padx=5)
# Notebook for cards
self.notebook = ttk.Notebook(main_frame)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Packages tab
packets_frame = ttk.Frame(self.notebook)
self.notebook.add(packets_frame, text="Pacchetti")
# First define the columns
packet_columns = ("No.", "Time", "Source", "Destination", "Protocol", "Length", "Information")
# Then create and configure the package table
self.setup_virtual_treeview = ttk.Treeview(packets_frame, columns=packet_columns, show="headings")
self.setup_virtual_treeview.bind("<KeyRelease-Up>", self.on_packet_select)
self.setup_virtual_treeview.bind("<KeyRelease-Down>", self.on_packet_select)
self.setup_virtual_treeview.bind("<<TreeviewSelect>>", self.on_packet_select)
for col in packet_columns:
self.setup_virtual_treeview.heading(col, text=col)
width = 100 if col != "Information" else 300
self.setup_virtual_treeview.column(col, width=width)
self.setup_virtual_treeview.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.setup_virtual_treeview.bind("<ButtonRelease-1>", self.on_packet_select)
# Scrollbar for package table
packet_scrollbar = ttk.Scrollbar(packets_frame, orient=tk.VERTICAL, command=self.setup_virtual_treeview.yview)
packet_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.setup_virtual_treeview.configure(yscrollcommand=packet_scrollbar.set)
# Package details frame
self.packet_details_frame = ttk.Frame(packets_frame)
self.packet_details_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.packet_details = ttk.Treeview(self.packet_details_frame, show="tree")
self.packet_details.pack(fill=tk.BOTH, expand=True, side=tk.LEFT)
packet_details_scrollbar = ttk.Scrollbar(self.packet_details_frame, orient=tk.VERTICAL, command=self.packet_details.yview)
packet_details_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.packet_details.configure(yscrollcommand=packet_details_scrollbar.set)
# Now that packets_frame is configured, add the options frame
view_options_frame = ttk.LabelFrame(self.root, text="Viewing options")
view_options_frame.pack(fill=tk.X, padx=10, pady=5)
# Variable for auto-scroll state
self.auto_scroll_var = tk.BooleanVar(value=True) # Active by default
# Checkbox for automatic scrolling
auto_scroll_check = ttk.Checkbutton(
view_options_frame,
text="Scroll automatico",
variable=self.auto_scroll_var
)
auto_scroll_check.pack(side=tk.LEFT, padx=10, pady=5)
# Optional tooltip
if hasattr(self, 'create_tooltip'):
self.create_tooltip(auto_scroll_check,
"If enabled, the view automatically scrolls to show new packages")
# Statistics tab
stats_frame = ttk.Frame(self.notebook)
self.notebook.add(stats_frame, text="Statistics")
# Graphs for statistics
self.stats_notebook = ttk.Notebook(stats_frame)
self.stats_notebook.pack(fill=tk.BOTH, expand=True)
# Protocols tab
protocols_frame = ttk.Frame(self.stats_notebook)
self.stats_notebook.add(protocols_frame, text="Protocols")
self.protocol_fig = plt.Figure(figsize=(6, 5), dpi=100)
self.protocol_canvas = FigureCanvasTkAgg(self.protocol_fig, protocols_frame)
self.protocol_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
# Flows tab
flows_frame = ttk.Frame(self.stats_notebook)
self.stats_notebook.add(flows_frame, text="Network flows")
self.flow_fig = plt.Figure(figsize=(6, 5), dpi=100)
self.flow_canvas = FigureCanvasTkAgg(self.flow_fig, flows_frame)
self.flow_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
# Safety tab
security_frame = ttk.Frame(self.notebook)
self.notebook.add(security_frame, text="Security Analysis")
# Add control buttons
security_controls = ttk.Frame(security_frame)
security_controls.pack(fill=tk.X, padx=5, pady=5)
ttk.Button(security_controls, text="Analyze Threats", command=self.analyze_threats).pack(side=tk.LEFT, padx=5)
ttk.Button(security_controls, text="ML Detection", command=self.run_anomaly_detection).pack(side=tk.LEFT, padx=5)
ttk.Button(security_controls, text="Batch Actions", command=self.create_batch_action_dialog).pack(side=tk.LEFT, padx=5)
# Create tree frame to contain table and scrollbars
tree_frame = ttk.Frame(security_frame)
tree_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Create threat table with multi-selection support
threat_columns = ("Timestamp", "Source", "Destination", "Threat type", "Severity", "Description")
self.threat_tree = ttk.Treeview(tree_frame, columns=threat_columns, show="headings")
for col in threat_columns:
self.threat_tree.heading(col, text=col)
width = 100 if col not in ("Description", "Threat type") else 200
self.threat_tree.column(col, width=width)
# Vertical scrollbar
vsb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.threat_tree.yview)
vsb.pack(side=tk.RIGHT, fill=tk.Y)
# Horizontal scrollbar
hsb = ttk.Scrollbar(tree_frame, orient="horizontal", command=self.threat_tree.xview)
hsb.pack(side=tk.BOTTOM, fill=tk.X)
# Configure the Treeview to use scrollbars
self.threat_tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
self.threat_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Configure tag colors for threat severity
self.threat_tree.tag_configure('high_severity', background='#ffcccc')
self.threat_tree.tag_configure('medium_severity', background='#ffffcc')
self.threat_tree.tag_configure('low_severity', background='#e6ffe6')
self.threat_tree.tag_configure('false_positive', foreground='gray')
# Configure keyboard shortcuts for multi-selection operations
self.threat_tree.bind("<Control-a>", self.select_all_threats) # Ctrl+A to select all
# Double-click still shows details
self.threat_tree.bind("<Double-1>", self.show_threat_details)
# IoT/Cloud Tab
iot_frame = ttk.Frame(self.notebook)
self.notebook.add(iot_frame, text="IoT/Cloud")
iot_controls = ttk.Frame(iot_frame)
iot_controls.pack(fill=tk.X, padx=5, pady=5)
ttk.Button(iot_controls, text="Identify IoT devices", command=self.detect_iot_devices).pack(side=tk.LEFT, padx=5)
ttk.Button(iot_controls, text="Analyze cloud protocols", command=self.analyze_cloud_protocols).pack(side=tk.LEFT, padx=5)
# IoT device table
iot_columns = ("IP", "Device type", "Manufacturer", "Protocols", "Traffic", "Risk")
self.iot_tree = ttk.Treeview(iot_frame, columns=iot_columns, show="headings")
for col in iot_columns:
self.iot_tree.heading(col, text=col)
self.iot_tree.column(col, width=100)
self.iot_tree.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Predictive analysis card
predictive_frame = ttk.Frame(self.notebook)
self.notebook.add(predictive_frame, text="Predictive analytics")
predict_controls = ttk.Frame(predictive_frame)
predict_controls.pack(fill=tk.X, padx=5, pady=5)
ttk.Button(predict_controls, text="Generate predictions", command=self.generate_predictions).pack(side=tk.LEFT, padx=5)
self.predict_fig = plt.Figure(figsize=(6, 5), dpi=100)
self.predict_canvas = FigureCanvasTkAgg(self.predict_fig, predictive_frame)
self.predict_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
# Status bar
self.status_bar = ttk.Label(self.root, text="Wiredigg Ready - Select an Interface and Start Capturing", relief=tk.SUNKEN, anchor=tk.W)
self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
def initialize_ml_model(self):
"""Initialize the machine learning model with incremental support"""
from sklearn.linear_model import SGDOneClassSVM
from sklearn.preprocessing import StandardScaler
# Initialize the model and scaler
self.ml_model = SGDOneClassSVM(nu=0.05, random_state=42)
self.scaler = StandardScaler()
self.ml_model_trained = False
# Variables for automatic training
self.training_in_progress = False
self.last_trained_packet_count = 0
self.training_threshold = 500 # Number of new packages that trigger training
# Try loading a pre-trained model if it exists
self.load_ml_model()
print("Initialized incremental ML model")
def start_background_training(self):
"""Start the automatic training process in the background"""
def check_for_training():
#Check if we have enough new packages to justify a training
if hasattr(self, 'captured_packets') and len(self.captured_packets) > 0:
current_packet_count = len(self.captured_packets)
new_packets = current_packet_count - self.last_trained_packet_count
# If we have enough new packages and there is no training already underway
if new_packets >= self.training_threshold and not self.training_in_progress:
self.background_train_model()
# Check again after 30 seconds
self.root.after(30000, check_for_training)
# Start the first check after 10 seconds from the application startup
self.root.after(10000, check_for_training)
print("Automatic background training configured")
def background_train_model(self):
"""Train the model in the background with incremental learning"""
if self.training_in_progress:
return
self.training_in_progress = True
# Update status in status bar
original_status = self.status_bar.cget("text")
self.status_bar.config(text="ML model training in the background...")
def run_training():
try:
# Check the model type
from sklearn.linear_model import SGDOneClassSVM
from sklearn.ensemble import IsolationForest
if isinstance(self.ml_model, IsolationForest):
print("WARNING: IsolationForest model detected instead of SGDOneClassSVM")
print("Reinitializing the model to support incremental learning...")
# Create a new SGDOneClassSVM model
self.ml_model = SGDOneClassSVM(nu=0.05, random_state=42)
self.ml_model_trained = False
print("Model replaced with SGDOneClassSVM")
# Use only new packages for incremental upgrade
if self.ml_model_trained:
packets_to_train = self.captured_packets[self.last_trained_packet_count:]
training_mode = "incremental"
else:
# For the first training, use all packages
packets_to_train = self.captured_packets
training_mode = "initial"
if not packets_to_train:
print("No training packages available")
return
print(f"Start training {training_mode} in background with {len(packets_to_train)} packets")
# Extract features with validity checks
features = []
for packet in packets_to_train:
packet_features = self.extract_ml_features(packet)
if packet_features:
# Make sure all features are numbers
try:
numeric_features = [float(f) for f in packet_features]
features.append(numeric_features)
except (ValueError, TypeError) as e:
print(f"Ignored non-numeric feature: {e}")
if not features:
print("Unable to extract valid features from packages")
return
# Make sure all lines are the same length
feature_lengths = [len(f) for f in features]
if len(set(feature_lengths)) > 1:
print(f"NOTICE: Different lengths of features: {set(feature_lengths)}")
# Find the most common length
from collections import Counter
common_length = Counter(feature_lengths).most_common(1)[0][0]
print(f"Normalization to length {common_length}")
# Normalize all lines to the most common length
normalized_features = []
for f in features:
if len(f) == common_length:
normalized_features.append(f)
elif len(f) < common_length:
# If too short, add zeros
normalized_features.append(f + [0.0] * (common_length - len(f)))
else:
# If too long, cut it off
normalized_features.append(f[:common_length])
features = normalized_features
# Convert to numpy array with explicit type
try:
X = np.array(features, dtype=np.float64)
print(f"Array X created successfully: shape {X.shape}")
except Exception as e:
print(f"Error converting to numpy array: {str(e)}")
return
# Different management for first training vs subsequent updates
if not self.ml_model_trained:
# First time: Full fit with scaler adaptation
print("Running fit_transform on scaler")
X_scaled = self.scaler.fit_transform(X)
print("Initial model training")
self.ml_model.fit(X_scaled)
self.ml_model_trained = True
else:
# Later updates: use partial_fit and existing scaler
print("Running transform on existing scaler")
X_scaled = self.scaler.transform(X)
print("Updating model with partial_fit")
# Check that the model supports partial_fit
if hasattr(self.ml_model, 'partial_fit'):
self.ml_model.partial_fit(X_scaled)
else:
print("NOTICE: The model does not support partial_fit. Use full fit.")
self.ml_model.fit(X_scaled)
# Update the processed packet counter
self.last_trained_packet_count = len(self.captured_packets)
# Save the model
self.save_ml_model()
print(f"Training {training_mode} in background completato con {len(features)} pacchetti")
# Update the status in the status bar in the main thread
self.root.after(0, lambda: self.status_bar.config(
text=f"Training ML {training_mode} completato ({len(features)} pacchetti analizzati)"))
# Restore the original state after 5 seconds
self.root.after(5000, lambda: self.status_bar.config(text=original_status))
except Exception as e:
print(f"Error in background training: {str(e)}")
traceback.print_exc()
finally:
# Always set training_in_progress to False when it finishes
self.training_in_progress = False
# Start training in a separate thread
training_thread = threading.Thread(target=run_training)
training_thread.daemon = True
training_thread.start()
def save_ml_model(self):
"""Save the ML model on disk"""
if not hasattr(self, 'ml_model') or not self.ml_model_trained:
return
try:
import pickle
import os
# Create directories if it doesn't exist
os.makedirs('models', exist_ok=True)
# Save the model with updated name
with open('models/sgd_oneclass_svm_model.pkl', 'wb') as f:
pickle.dump(self.ml_model, f)
# Save the scaler
with open('models/scaler.pkl', 'wb') as f:
pickle.dump(self.scaler, f)
# Also save the meter of processed packages
with open('models/last_trained_count.pkl', 'wb') as f:
pickle.dump(self.last_trained_packet_count, f)
print("Modello ML incrementale salvato su disco")
except Exception as e:
print(f"Errore nel salvataggio del modello: {str(e)}")
def load_ml_model(self):
"""Load incremental ML model from disk if it exists"""
try:
import pickle
import os
# Check if the files exist
model_path = 'models/sgd_oneclass_svm_model.pkl'
scaler_path = 'models/scaler.pkl'
count_path = 'models/last_trained_count.pkl'
if os.path.exists(model_path) and os.path.exists(scaler_path):
# Load the model
with open(model_path, 'rb') as f:
self.ml_model = pickle.load(f)
# Load the scaler
with open(scaler_path, 'rb') as f:
self.scaler = pickle.load(f)
# Load the processed packet counter if it exists
if os.path.exists(count_path):
with open(count_path, 'rb') as f:
self.last_trained_packet_count = pickle.load(f)
self.ml_model_trained = True
print(f"Incremental ML model loaded from disk (trained on {self.last_trained_packet_count} packets)")
return True
# Check if old Isolation Forest template files exist
# for backwards compatibility
elif os.path.exists('models/isolation_forest_model.pkl'):
print("Found old Isolation Forest model. A new SGDOneClassSVM model will be created")
# We don't load the old model, let a new model be created
except Exception as e:
print(f"Error loading template: {str(e)}")
return False
def setup_virtual_treeview(self):
"""Set up a virtual Treeview that loads only visible items"""
# Create the standard Treeview
self.setup_virtual_treeview = ttk.Treeview(self.packets_frame, columns=self.packet_columns, show="headings")
# Create a separate data structure to store all the packets
if not hasattr(self, 'all_packets'):
self.all_packets = [] # Store all package data here
# Configure scrolling events
vsb = ttk.Scrollbar(self.packets_frame, orient="vertical", command=self.on_treeview_scroll)
self.setup_virtual_treeview.configure(yscrollcommand=vsb.set)
vsb.pack(side='right', fill='y')
self.setup_virtual_treeview.pack(expand=True, fill='both')
# Also configure the window resize event
self.root.bind("<Configure>", lambda e: self.after(100, self.update_visible_items))
# Number of items to display (buffer)
self.visible_buffer = 100 # Visible elements + buffers above and below
# Configure the scroll event handler
self.setup_virtual_treeview.bind("<<TreeviewSelect>>", self.on_packet_select)
def on_treeview_scroll(self, *args):
"""# Configure the scroll event handler"""
# Apply normal scrolling
self.setup_virtual_treeview.yview(*args)
# Update visible items
self.after(10, self.update_visible_items)
def update_visible_items(self):
"""Refresh the visible items in the Treeview"""
if not hasattr(self, 'all_packets') or not self.all_packets:
return
# Get the current scroll position
try:
first, last = self.setup_virtual_treeview.yview()
except:
return
# Calculate which elements should be visible
total_items = len(self.all_packets)
if total_items == 0:
return
# Calculate the approximate index of visible elements
first_visible_index = int(first * total_items)
last_visible_index = int(last * total_items) + 1
# Add a buffer for smooth scrolling
buffer_size = self.visible_buffer // 2
start_index = max(0, first_visible_index - buffer_size)
end_index = min(total_items, last_visible_index + buffer_size)
# Get the IDs of the currently displayed items
current_items = self.setup_virtual_treeview.get_children()
# If there are too many elements, remove the ones out of view
if len(current_items) > self.visible_buffer * 2:
# Calculate which elements are outside the visible area + buffer
visible_range = set(range(start_index, end_index))
# Create a mapping between the indices and the ID of the elements
item_indices = {}
for i, item_id in enumerate(current_items):
values = self.setup_virtual_treeview.item(item_id, 'values')
if values and len(values) > 0:
try:
packet_index = int(values[0]) - 1 # The first value is the package index
item_indices[packet_index] = item_id
except:
continue
# Remove the elements that are outside the sight
for idx, item_id in item_indices.items():
if idx not in visible_range:
self.setup_virtual_treeview.delete(item_id)
# Add the missing elements in the current view
existing_indices = set()
for item_id in self.setup_virtual_treeview.get_children():
values = self.setup_virtual_treeview.item(item_id, 'values')
if values and len(values) > 0:
try:
existing_indices.add(int(values[0]) - 1) # The first value is the package index
except:
continue
# Add the missing elements
for i in range(start_index, end_index):
if i < len(self.all_packets) and i not in existing_indices:
# Enter the element from our All_packets archive
self.setup_virtual_treeview.insert("", "end", values=self.all_packets[i])
def on_packet_select(self, event=None):
"""Manages the selection of a package in the list"""
selected_items = self.setup_virtual_treeview.selection()
if not selected_items:
return
# Get the selected element
item_id = selected_items[0]
# Make sure the element is visible
self.setup_virtual_treeview.see(item_id)
# Get the package index
values = self.setup_virtual_treeview.item(item_id, 'values')
if values:
try:
packet_index = int(values[0]) - 1 # I subtract 1 for the indices to start from 0
if 0 <= packet_index < len(self.captured_packets):
packet = self.captured_packets[packet_index]
# Clean the previous details
for item in self.packet_details.get_children():
self.packet_details.delete(item)
# View details of the package
self.display_packet_details(packet)
except (ValueError, IndexError) as e:
print(f"Error in the recovery of the package: {e}")
def create_tooltip(self, widget, text):
"" "Create a tooltip for specified widget" ""
def enter(event):
x, y, _, _ = widget.bbox("insert")
x += widget.winfo_rootx() + 25
y += widget.winfo_rooty() + 20
# Create a top-level window
self.tooltip = tk.Toplevel(widget)
self.tooltip.wm_overrideredirect(True)
self.tooltip.wm_geometry(f"+{x}+{y}")
label = ttk.Label(self.tooltip, text=text, background="#ffffe0", relief="solid", borderwidth=1,foreground="black")
label.pack()
def leave(event):
if hasattr(self, 'tooltip'):
self.tooltip.destroy()
widget.bind("<Enter>", enter)
widget.bind("<Leave>", leave)
def apply_filters(self):
"" "Apply the selected filters" ""
# Get the values of the filters
proto = self.proto_filter_var.get()
ip = self.ip_filter_var.get()
port = self.port_filter_var.get()
# Check if there are active filters
if not proto and not ip and not port:
messagebox.showinfo("Filters", "No specified filter")
self.reset_filters()
return
# Update the State of the Filter
filter_desc = []
if proto:
filter_desc.append(f"Protocol: {proto}")
if ip:
filter_desc.append(f"IP: {ip}")
if port:
filter_desc.append(f"Port: {port}")
status_text = "Active filters: " + ", ".join(filter_desc)
self.filter_status.config(text=status_text)
# If we are in capture mode, apply the filters immediately
if self.is_capturing:
# Delete the current view
for item in self.setup_virtual_treeview.get_children():
self.setup_virtual_treeview.delete(item)
# Reset the indexes
self.packet_indices = {}
# Reapply the filters you packages already captured and update the view
self.apply_filters_to_captured_packets()
messagebox.showinfo("Filters", "Successful filters applied")
def reset_filters(self):
"""Removes all filters"""
# Reset controls
self.proto_filter_var.set("")
self.ip_filter_var.set("")
self.port_filter_var.set("")
# Update the state
self.filter_status.config(text="No active filter")
# If we are in capture mode, update the view
if self.is_capturing:
# Delete the current view
for item in self.setup_virtual_treeview.get_children():
self.setup_virtual_treeview.delete(item)
# Reset the indexes
self.packet_indices = {}
# Reapply the packages without filter
self.apply_filters_to_captured_packets()
messagebox.showinfo("Filters", "Removed filters")
def apply_filters_to_captured_packets(self):
"""Apply the filters to the packages already captured and update the view"""
# Get the values of the filters
proto_filter = self.proto_filter_var.get().upper()
ip_filter = self.ip_filter_var.get()
port_filter = self.port_filter_var.get()
# Elaborates all packages
filtered_packets = []
for packet in self.captured_packets:
# Apply filters
should_include = True
# Protocol filter
if proto_filter:
if proto_filter == "TCP" and packet.get('proto_name') not in ['TCP', 'HTTP', 'HTTPS']:
should_include = False
elif proto_filter == "UDP" and packet.get('proto_name') not in ['UDP', 'DNS']:
should_include = False
elif proto_filter == "ICMP" and packet.get('proto_name') != 'ICMP':
should_include = False
elif proto_filter == "HTTP" and packet.get('proto_name') != 'HTTP':
should_include = False
elif proto_filter == "HTTPS" and packet.get('proto_name') != 'HTTPS':
should_include = False
elif proto_filter == "DNS" and packet.get('proto_name') != 'DNS':