Repository navigation
Expand file tree
/
Copy pathfirewall_monitor.py
More file actions
4120 lines (3870 loc) · 207 KB
/
Copy pathfirewall_monitor.py
File metadata and controls
4120 lines (3870 loc) · 207 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 csv
import json
import time
import re
import socket
import ipaddress
import hashlib
import ctypes
from ctypes import wintypes
import queue
import subprocess
import threading
import traceback
from collections import deque
import tkinter as tk
from tkinter import ttk, messagebox, filedialog, simpledialog
try:
import psutil
from scapy.all import sniff, IP, IPv6, TCP, UDP
except ImportError as exc:
raise SystemExit(f'Missing dependency: {exc}. Install psutil, scapy, and Npcap first.')
DEFAULT_RATE_THRESHOLD = 50
DEFAULT_RATE_WINDOW = 5.0
DEFAULT_UPLOAD_THRESHOLD_MB = 50
DEFAULT_LOG_ALERTS_ONLY = True
DEFAULT_DARK_MODE = True
DEFAULT_MAX_CONNECTIONS_ALERTS = 250
CREATE_NO_WINDOW = 134217728
WATCH_PORTS = {23: 'Telnet', 445: 'SMB', 3389: 'RDP', 4444: 'Common remote-control port', 5555: 'Android Debug Bridge', 5900: 'VNC', 6667: 'IRC'}
GLOBAL_BLOCK_PREFIX = 'PyFirewall_GlobalIP_'
GLOBAL_ALLOW_PREFIX = 'PyFirewall_GlobalIPAllow_'
AUTO_HOLD_PREFIX = 'PyFirewall_AutoHold_'
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(SCRIPT_DIR, 'firewall_config.json')
ICON_FILE = os.path.join(SCRIPT_DIR, 'PyFirewall.ico')
FIREWALL_PROFILE_BACKUP_FILE = os.path.join(SCRIPT_DIR, 'firewall_profile_backup.json')
DNS_MAX_WORKERS = 8
DNS_MAX_PENDING = 256
DNS_CACHE_MAX_ENTRIES = 2048
DNS_CACHE_TTL = 900.0
FIREWALL_COMMAND_TIMEOUT = 30.0
TRAFFIC_MAX_IP_ENTRIES = 8192
TRAFFIC_MAX_PROC_IP_ENTRIES = 16384
TRAFFIC_PRUNE_INTERVAL = 30.0
INTERNAL_ERROR_LOG_FILE = os.path.join(SCRIPT_DIR, 'firewall_monitor_errors.log')
INTERNAL_ERROR_LOG_LOCK = threading.Lock()
if os.name != 'nt':
raise SystemExit('This application requires Windows.')
_MUTEX_HANDLE = None
def error_details(exc):
details = [str(exc)]
for field in ('stderr', 'stdout'):
output = getattr(exc, field, None)
if isinstance(output, bytes):
output = output.decode('utf-8', errors='replace')
if output and str(output).strip():
details.append(f'{field}: {str(output).strip()}')
return '\n'.join(details)
def log_internal_error(context, exc):
try:
with INTERNAL_ERROR_LOG_LOCK:
with open(INTERNAL_ERROR_LOG_FILE, 'a', encoding='utf-8') as f:
f.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {context}: {type(exc).__name__}: {error_details(exc)}\n")
traceback.print_exception(type(exc), exc, exc.__traceback__, file=f)
f.write('\n')
except Exception:
pass
def hide_console():
try:
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
if hwnd:
ctypes.windll.user32.ShowWindow(hwnd, 0)
except Exception:
pass
def is_admin():
try:
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
def elevate():
if is_admin():
return
executable = sys.executable
pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe')
if os.path.exists(pythonw):
executable = pythonw
try:
result = ctypes.windll.shell32.ShellExecuteW(None, 'runas', executable, subprocess.list2cmdline(sys.argv), None, 0)
if result <= 32:
raise OSError(f'ShellExecuteW returned {result}')
except Exception:
pass
raise SystemExit
def acquire_single_instance():
global _MUTEX_HANDLE
name = 'Local\\PyFirewall_' + hashlib.sha1(os.path.normcase(os.path.abspath(__file__)).encode()).hexdigest()
_MUTEX_HANDLE = ctypes.windll.kernel32.CreateMutexW(None, False, name)
if not _MUTEX_HANDLE:
return True
if ctypes.windll.kernel32.GetLastError() == 183:
ctypes.windll.user32.MessageBoxW(None, 'Python Personal Firewall & Network Monitor is already running.', 'Already Running', 48)
return False
return True
hide_console()
elevate()
if not acquire_single_instance():
raise SystemExit
def normalize_path(path):
if not path:
return ''
try:
return os.path.normcase(os.path.normpath(str(path).replace('/', '\\')))
except Exception:
return str(path).lower()
def display_path(path):
return os.path.normpath(str(path).replace('/', '\\')) if path else ''
def normalize_target(target):
value = str(target or '').strip().strip('[]').casefold().rstrip('.')
try:
return str(ipaddress.ip_address(value))
except ValueError:
return value
def is_ip(target):
try:
ipaddress.ip_address(str(target).strip().strip('[]').split('/', 1)[0].split(' (', 1)[0])
return True
except ValueError:
return False
def mb(value):
return f'{value / (1024 * 1024):.2f} MB'
def direction_name(value):
value = str(value or '').casefold()
if value in {'in', 'inbound', 'incoming'}:
return 'Inbound'
if value in {'out', 'outbound', 'outgoing'}:
return 'Outbound'
return 'Both'
def direction_set(value):
value = direction_name(value)
return {'in'} if value == 'Inbound' else {'out'} if value == 'Outbound' else {'in', 'out'}
class ToolTip:
def __init__(self, widget, text, delay=400):
self.widget, self.text, self.delay = (widget, text, delay)
self.tip = None
self.after_id = None
widget.bind('<Enter>', self._enter, add='+')
widget.bind('<Leave>', self._leave, add='+')
widget.bind('<ButtonPress>', self._leave, add='+')
widget.bind('<Destroy>', self._leave, add='+')
def _enter(self, _=None):
self._cancel()
self.after_id = self.widget.after(self.delay, self._show)
def _leave(self, _=None):
self._cancel()
if self.tip:
try:
self.tip.destroy()
except tk.TclError:
pass
self.tip = None
def _cancel(self):
if self.after_id:
try:
self.widget.after_cancel(self.after_id)
except tk.TclError:
pass
self.after_id = None
def _show(self):
text = self.text() if callable(self.text) else self.text
if self.tip or not str(text or '').strip():
return
try:
x = self.widget.winfo_rootx() + 10
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 4
tip = tk.Toplevel(self.widget)
tip.wm_overrideredirect(True)
tip.wm_geometry(f'+{x}+{y}')
tip.configure(bg='#2b2b2b')
tk.Label(tip, text=str(text), justify=tk.LEFT, bg='#2b2b2b', fg='#f0f0f0', relief='solid', borderwidth=1, font=('Segoe UI', 9), padx=8, pady=4).pack(ipadx=1)
self.tip = tip
except tk.TclError:
pass
def add_tooltip(widget, text, delay=400):
widget._tooltip = ToolTip(widget, text, delay)
return widget._tooltip
BUTTON_TIPS = {'Block Selected': 'Choose how to block the selected application.', 'Allow Selected': 'Allow all traffic for the selected application.', 'Export CSV': 'Export the visible connection rows to a CSV file.', 'Clear List': 'Clear the Live Monitor connection list.', 'Refresh Rules': 'Refresh the Managed Rules list from Windows Firewall.', 'Add Custom Rule': 'Create an inbound or outbound application rule.', 'Allow Global IP': 'Allow an IP address or domain globally.', 'Block Global IP': 'Block an IP address or domain globally.', 'Remove Selected': 'Remove the selected managed firewall rule(s).', 'Remove Selected Rule': 'Remove the selected managed firewall rule(s).', 'Export Rules': 'Export managed rules to a JSON backup.', 'Import Rules': 'Import and apply managed rules from a JSON file.', 'Windows Firewall': 'Open Windows Defender Firewall.', 'Clear Alerts': 'Clear all entries from the Alerts list.', 'Apply Settings': 'Save and apply the monitoring thresholds and options.', 'Reset to Defaults': 'Reset saved settings and remove PyFirewall-managed rules.'}
class PyFirewallSystemTray:
WM_TRAYICON = 1024 + 1
WM_CLOSE = 16
WM_DESTROY = 2
WM_NULL = 0
WM_RBUTTONUP = 517
WM_LBUTTONDBLCLK = 515
NIM_ADD = 0
NIM_DELETE = 2
NIF_MESSAGE = 1
NIF_ICON = 2
NIF_TIP = 4
MF_STRING = 0
MF_GRAYED = 1
TPM_LEFTALIGN = 0
TPM_BOTTOMALIGN = 32
TPM_RETURNCMD = 256
TPM_NONOTIFY = 128
ID_SHOW = 1001
ID_FILTER_ALL = 1002
ID_PAUSE = 1003
ID_SETTINGS = 1004
ID_CLOSE = 1005
SW_HIDE = 0
class POINT(ctypes.Structure):
_fields_ = [('x', wintypes.LONG), ('y', wintypes.LONG)]
class WNDCLASSEXW(ctypes.Structure):
_fields_ = [('cbSize', wintypes.UINT), ('style', wintypes.UINT), ('lpfnWndProc', ctypes.c_void_p), ('cbClsExtra', ctypes.c_int), ('cbWndExtra', ctypes.c_int), ('hInstance', wintypes.HINSTANCE), ('hIcon', wintypes.HICON), ('hCursor', ctypes.c_void_p), ('hbrBackground', wintypes.HBRUSH), ('lpszMenuName', wintypes.LPCWSTR), ('lpszClassName', wintypes.LPCWSTR), ('hIconSm', wintypes.HICON)]
class NOTIFYICONDATAW(ctypes.Structure):
_fields_ = [('cbSize', wintypes.DWORD), ('hWnd', wintypes.HWND), ('uID', wintypes.UINT), ('uFlags', wintypes.UINT), ('uCallbackMessage', wintypes.UINT), ('hIcon', wintypes.HICON), ('szTip', wintypes.WCHAR * 128), ('dwState', wintypes.DWORD), ('dwStateMask', wintypes.DWORD), ('szInfo', wintypes.WCHAR * 256), ('uVersion_or_Timeout', wintypes.UINT), ('szInfoTitle', wintypes.WCHAR * 64), ('dwInfoFlags', wintypes.DWORD), ('guidItem', ctypes.c_byte * 16), ('hBalloonIcon', wintypes.HICON)]
WNDPROC = ctypes.WINFUNCTYPE(ctypes.c_ssize_t, wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM)
def __init__(self, command_queue, filter_all_enabled=True, is_paused=False):
self.command_queue = command_queue
self.state_lock = threading.Lock()
self.filter_all_enabled = bool(filter_all_enabled)
self.is_paused = bool(is_paused)
self.thread = None
self.thread_id = None
self.hwnd = None
self.class_name = f'PyFirewallTray_{os.getpid()}_{id(self)}'
self._wndproc = None
self._hicon = None
self._registered = False
self._icon_added = False
self._ready = threading.Event()
self.thread = threading.Thread(target=self._run, daemon=True, name='PyFirewallTray')
self.thread.start()
def _run(self):
try:
user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
self.thread_id = kernel32.GetCurrentThreadId()
user32.RegisterClassExW.argtypes = [ctypes.POINTER(self.WNDCLASSEXW)]
user32.RegisterClassExW.restype = wintypes.ATOM
user32.CreateWindowExW.argtypes = [wintypes.DWORD, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, wintypes.HWND, wintypes.HMENU, wintypes.HINSTANCE, wintypes.LPVOID]
user32.CreateWindowExW.restype = wintypes.HWND
user32.DefWindowProcW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
user32.DefWindowProcW.restype = ctypes.c_ssize_t
user32.DestroyWindow.argtypes = [wintypes.HWND]
user32.DestroyWindow.restype = wintypes.BOOL
user32.ShowWindow.argtypes = [wintypes.HWND, ctypes.c_int]
user32.ShowWindow.restype = wintypes.BOOL
user32.LoadIconW.argtypes = [wintypes.HINSTANCE, wintypes.LPCWSTR]
user32.LoadIconW.restype = wintypes.HICON
user32.LoadImageW.argtypes = [wintypes.HINSTANCE, wintypes.LPCWSTR, wintypes.UINT, ctypes.c_int, ctypes.c_int, wintypes.UINT]
user32.LoadImageW.restype = wintypes.HICON
user32.LoadCursorW.argtypes = [wintypes.HINSTANCE, wintypes.LPCWSTR]
user32.LoadCursorW.restype = ctypes.c_void_p
user32.DestroyIcon.argtypes = [wintypes.HICON]
user32.DestroyIcon.restype = wintypes.BOOL
user32.GetCursorPos.argtypes = [ctypes.POINTER(self.POINT)]
user32.GetCursorPos.restype = wintypes.BOOL
user32.CreatePopupMenu.argtypes = []
user32.CreatePopupMenu.restype = wintypes.HMENU
user32.AppendMenuW.argtypes = [wintypes.HMENU, wintypes.UINT, ctypes.c_size_t, wintypes.LPCWSTR]
user32.AppendMenuW.restype = wintypes.BOOL
user32.DestroyMenu.argtypes = [wintypes.HMENU]
user32.DestroyMenu.restype = wintypes.BOOL
user32.SetForegroundWindow.argtypes = [wintypes.HWND]
user32.SetForegroundWindow.restype = wintypes.BOOL
user32.TrackPopupMenu.argtypes = [wintypes.HMENU, wintypes.UINT, ctypes.c_int, ctypes.c_int, ctypes.c_int, wintypes.HWND, wintypes.LPVOID]
user32.TrackPopupMenu.restype = wintypes.UINT
user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
user32.PostMessageW.restype = wintypes.BOOL
user32.PostThreadMessageW.argtypes = [wintypes.DWORD, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
user32.PostThreadMessageW.restype = wintypes.BOOL
shell32 = ctypes.windll.shell32
shell32.Shell_NotifyIconW.argtypes = [wintypes.DWORD, ctypes.POINTER(self.NOTIFYICONDATAW)]
shell32.Shell_NotifyIconW.restype = wintypes.BOOL
default_icon = ctypes.cast(ctypes.c_void_p(32512), wintypes.LPCWSTR)
arrow_cursor = user32.LoadCursorW(None, default_icon)
self._hicon = user32.LoadImageW(None, ICON_FILE, 1, 0, 0, 16 | 64)
if not self._hicon:
self._hicon = user32.LoadIconW(None, default_icon)
if not self._hicon:
raise OSError('Could not load a PyFirewall icon or the default Windows application icon')
self._wndproc = self.WNDPROC(self._window_proc)
wnd = self.WNDCLASSEXW()
wnd.cbSize = ctypes.sizeof(self.WNDCLASSEXW)
wnd.style = 0
wnd.lpfnWndProc = ctypes.cast(self._wndproc, wintypes.LPVOID)
wnd.cbClsExtra = 0
wnd.cbWndExtra = 0
wnd.hInstance = kernel32.GetModuleHandleW(None)
wnd.hIcon = self._hicon
wnd.hCursor = arrow_cursor
wnd.hbrBackground = None
wnd.lpszMenuName = None
wnd.lpszClassName = self.class_name
wnd.hIconSm = self._hicon
atom = user32.RegisterClassExW(ctypes.byref(wnd))
if not atom:
raise OSError(f'RegisterClassExW failed with error {ctypes.get_last_error()}')
self._registered = True
self.hwnd = user32.CreateWindowExW(0, self.class_name, 'PyFirewall', 0, 0, 0, 0, 0, None, None, wnd.hInstance, None)
if not self.hwnd:
raise OSError(f'CreateWindowExW failed with error {ctypes.get_last_error()}')
user32.ShowWindow(self.hwnd, self.SW_HIDE)
nid = self.NOTIFYICONDATAW()
nid.cbSize = ctypes.sizeof(self.NOTIFYICONDATAW)
nid.hWnd = self.hwnd
nid.uID = 1
nid.uFlags = self.NIF_MESSAGE | self.NIF_ICON | self.NIF_TIP
nid.uCallbackMessage = self.WM_TRAYICON
nid.hIcon = self._hicon
nid.szTip = 'PyFirewall'
if not shell32.Shell_NotifyIconW(self.NIM_ADD, ctypes.byref(nid)):
raise OSError(f'Shell_NotifyIconW(NIM_ADD) failed with error {ctypes.get_last_error()}')
self._icon_added = True
self._ready.set()
msg = wintypes.MSG()
while True:
result = user32.GetMessageW(ctypes.byref(msg), None, 0, 0)
if result == 0 or result == -1:
break
user32.TranslateMessage(ctypes.byref(msg))
user32.DispatchMessageW(ctypes.byref(msg))
except Exception:
self._ready.set()
finally:
try:
if self._icon_added and self.hwnd:
nid = self.NOTIFYICONDATAW()
nid.cbSize = ctypes.sizeof(self.NOTIFYICONDATAW)
nid.hWnd = self.hwnd
nid.uID = 1
ctypes.windll.shell32.Shell_NotifyIconW(self.NIM_DELETE, ctypes.byref(nid))
self._icon_added = False
except Exception:
pass
try:
if self.hwnd:
ctypes.windll.user32.DestroyWindow(self.hwnd)
self.hwnd = None
except Exception:
pass
try:
if self._registered:
ctypes.windll.user32.UnregisterClassW(self.class_name, ctypes.windll.kernel32.GetModuleHandleW(None))
self._registered = False
except Exception:
pass
try:
if self._hicon:
ctypes.windll.user32.DestroyIcon(self._hicon)
self._hicon = None
except Exception:
pass
def _window_proc(self, hwnd, msg, wparam, lparam):
if msg == self.WM_TRAYICON:
event = wintypes.UINT(lparam & 4294967295).value
if event == self.WM_RBUTTONUP:
self._show_context_menu(hwnd)
elif event == self.WM_LBUTTONDBLCLK:
self.command_queue.put('show')
return 0
if msg == self.WM_CLOSE:
ctypes.windll.user32.DestroyWindow(hwnd)
return 0
if msg == self.WM_DESTROY:
ctypes.windll.user32.PostQuitMessage(0)
return 0
return ctypes.windll.user32.DefWindowProcW(hwnd, msg, wparam, lparam)
def update_state(self, filter_all_enabled=None, is_paused=None):
with self.state_lock:
if filter_all_enabled is not None:
self.filter_all_enabled = bool(filter_all_enabled)
if is_paused is not None:
self.is_paused = bool(is_paused)
def _get_state(self):
with self.state_lock:
return (self.filter_all_enabled, self.is_paused)
def _show_context_menu(self, hwnd):
user32 = ctypes.windll.user32
menu = user32.CreatePopupMenu()
if not menu:
return
try:
filter_all_enabled, is_paused = self._get_state()
filter_command_flags = self.MF_STRING | (self.MF_GRAYED if is_paused else 0)
filter_text = 'Disable Filter All Connections' if filter_all_enabled else 'Filter All Connections'
pause_text = 'Resume Monitoring' if is_paused else 'Pause Monitoring'
user32.AppendMenuW(menu, self.MF_STRING, self.ID_SHOW, 'Show PyFirewall')
user32.AppendMenuW(menu, self.MF_STRING, self.ID_PAUSE, pause_text)
user32.AppendMenuW(menu, filter_command_flags, self.ID_FILTER_ALL, filter_text)
user32.AppendMenuW(menu, self.MF_STRING, self.ID_SETTINGS, 'Settings')
user32.AppendMenuW(menu, self.MF_STRING, self.ID_CLOSE, 'Close')
point = self.POINT()
if not user32.GetCursorPos(ctypes.byref(point)):
return
user32.SetForegroundWindow(hwnd)
command = user32.TrackPopupMenu(menu, self.TPM_LEFTALIGN | self.TPM_BOTTOMALIGN | self.TPM_RETURNCMD | self.TPM_NONOTIFY, point.x, point.y, 0, hwnd, None)
user32.PostMessageW(hwnd, self.WM_NULL, 0, 0)
if command == self.ID_SHOW:
self.command_queue.put('show')
elif command == self.ID_PAUSE:
self.command_queue.put('toggle_pause')
elif command == self.ID_FILTER_ALL:
self.command_queue.put('toggle_filter_all')
elif command == self.ID_SETTINGS:
self.command_queue.put('settings')
elif command == self.ID_CLOSE:
self.command_queue.put('close')
finally:
user32.DestroyMenu(menu)
def stop(self):
hwnd = self.hwnd
if hwnd:
try:
ctypes.windll.user32.PostMessageW(hwnd, self.WM_CLOSE, 0, 0)
except Exception:
pass
elif self.thread and self.thread.is_alive() and self.thread_id:
try:
ctypes.windll.user32.PostThreadMessageW(self.thread_id, self.WM_CLOSE, 0, 0)
except Exception:
pass
class FirewallMonitorApp:
MONITOR_COLUMNS = ('#', 'Process Name', 'Status', 'PID', 'Direction', 'Protocol', 'Local Port', 'Remote IP', 'Remote Host', 'Remote Port', 'Download (MB)', 'Upload (MB)', 'Signal', 'Exe Path')
ACTIVE_COLUMNS = ('#', 'Process Name', 'PID', 'Direction', 'Protocol', 'Local Port', 'Remote IP', 'Remote Host', 'Remote Port', 'Download (MB)', 'Upload (MB)', 'Signal', 'Exe Path')
RULE_COLUMNS = ('Status', 'Rule / Application', 'Direction', 'Download (MB)', 'Upload (MB)', 'Program Path')
ALERT_COLUMNS = ('Time', 'Severity', 'Process', 'PID', 'Remote IP', 'Remote Host', 'Reason')
DEFAULT_COLUMN_ORDERS = {'monitor': ('#', 'Process Name', 'Status', 'PID', 'Direction', 'Protocol', 'Local Port', 'Remote IP', 'Remote Host', 'Remote Port', 'Download (MB)', 'Upload (MB)', 'Exe Path', 'Signal'), 'active': ACTIVE_COLUMNS, 'rules': RULE_COLUMNS, 'alerts': ALERT_COLUMNS}
def __init__(self, root):
self.root = root
root.title('Python Personal Firewall & Network Monitor')
root.geometry('1800x900')
root.minsize(1500, 750)
self.lock = threading.RLock()
self.firewall_lock = threading.RLock()
self.dns_lock = threading.Lock()
self.settings_io_lock = threading.Lock()
self.settings_change_lock = threading.Lock()
self.settings_change_worker_running = False
self.settings_change_pending = False
self.settings_change_release_holds = False
self.settings_change_generation = 0
self.ui_queue = queue.Queue()
self.prompt_queue = queue.Queue()
self.alert_queue = queue.Queue()
self.tray_command_queue = queue.Queue()
self.tray = None
self.tray_hidden = False
self.sniffing = self.closed = self.is_paused = False
self.startup_complete = self.startup_running = False
self.active_connections = {}
self.next_connection_number = 1
self.connection_rates = {}
self.selection_anchors = {}
self._active_drag_tree = None
self._drag_indicator = None
self.default_column_orders = self.DEFAULT_COLUMN_ORDERS
self.column_orders = {key: list(order) for key, order in self.default_column_orders.items()}
self.header_drag = {}
self.proc_traffic = {}
self.ip_traffic = {}
self.proc_ip_upload = {}
self.ip_traffic_last_seen = {}
self.proc_ip_upload_last_seen = {}
self.last_traffic_prune = time.monotonic()
self.upload_alerted = set()
self.total_download = self.total_upload = 0
self.captured_packets = self.captured_bytes = 0
self._last_capture_bytes = self._last_capture_packets = 0
self._last_status_time = time.monotonic()
self.capture_rate = self.capture_pps = 0.0
self.allowed_apps = set()
self.blocked_paths = {}
self.global_blocks = {}
self.global_allows = {}
self.rule_rows = []
self.rules_loading = False
self.rules_generation = 0
self.rules_refresh_worker_running = False
self.rules_refresh_pending = False
self.pending_rules = []
self.alerts = deque(maxlen=DEFAULT_MAX_CONNECTIONS_ALERTS)
self.next_alert_id = 1
self.auto_prompt_keys = set()
self.auto_prompt_active = False
self.auto_prompt_dialog = None
self.auto_prompt_key = None
self.auto_prompt_generation = 0
self.firewall_profile_modified = False
self.settings_save_error = None
self.dns_cache = {}
self.dns_cache_times = {}
self.dns_pending = set()
self.dns_queue = queue.Queue(maxsize=DNS_MAX_PENDING)
self.dns_stop_event = threading.Event()
self.dns_workers = []
self._start_dns_workers()
self.socket_process_cache = {}
self.listener_process_cache = {}
self.cache_time = 0.0
self.local_addresses = set()
self.capture_error = None
self.capture_healthy = False
self.filter_all_enabled = True
self.filter_all_saved_alerts = None
self.filter_all_saved_auto_block = None
self.saved_rate_threshold = DEFAULT_RATE_THRESHOLD
self.rate_threshold = 1 if self.filter_all_enabled else DEFAULT_RATE_THRESHOLD
self.rate_window = DEFAULT_RATE_WINDOW
self.upload_threshold_mb = DEFAULT_UPLOAD_THRESHOLD_MB
self.max_connections_alerts = DEFAULT_MAX_CONNECTIONS_ALERTS
self.log_alerts_only = DEFAULT_LOG_ALERTS_ONLY
self.auto_block_enabled = True
self.dark_mode = DEFAULT_DARK_MODE
self.firewall_initialized = False
self.rate_threshold_var = tk.StringVar(value=str(self.rate_threshold))
self.rate_window_var = tk.StringVar(value=str(DEFAULT_RATE_WINDOW))
self.upload_threshold_var = tk.StringVar(value=str(DEFAULT_UPLOAD_THRESHOLD_MB))
self.max_connections_alerts_var = tk.StringVar(value=str(DEFAULT_MAX_CONNECTIONS_ALERTS))
self.log_alerts_var = tk.BooleanVar(value=DEFAULT_LOG_ALERTS_ONLY)
self.auto_block_var = tk.BooleanVar(value=True)
self.dark_mode_var = tk.BooleanVar(value=DEFAULT_DARK_MODE)
self.search_var = tk.StringVar()
self.active_search_var = tk.StringVar()
self.rule_search_var = tk.StringVar()
self.alert_search_var = tk.StringVar()
self.monitor_sort = ['#', True]
self.active_sort = ['Process Name', False]
self.rule_sort = [None, False]
self.alert_sort = ['Time', True]
self.load_settings()
self.setup_gui()
self.root.protocol('WM_DELETE_WINDOW', self.minimize_to_tray)
try:
self.tray = PyFirewallSystemTray(self.tray_command_queue, filter_all_enabled=self.filter_all_enabled, is_paused=self.is_paused)
except Exception:
self.tray = None
self.root.after(50, self._start_background_initialization)
self.root.after(100, self.update_loop)
def load_settings(self):
if not os.path.exists(CONFIG_FILE):
return
try:
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
config = json.load(f)
except Exception:
return
with self.lock:
self.filter_all_enabled = bool(config.get('filter_all_enabled', True))
self.saved_rate_threshold = max(1, int(config.get('saved_rate_threshold', config.get('rate_threshold', DEFAULT_RATE_THRESHOLD))))
self.rate_threshold = 1 if self.filter_all_enabled else max(1, int(config.get('rate_threshold', self.saved_rate_threshold)))
self.rate_window = max(0.1, float(config.get('rate_window', DEFAULT_RATE_WINDOW)))
self.upload_threshold_mb = max(0.1, float(config.get('upload_threshold_mb', DEFAULT_UPLOAD_THRESHOLD_MB)))
self.max_connections_alerts = max(1, int(config.get('max_connections_alerts', DEFAULT_MAX_CONNECTIONS_ALERTS)))
self.alerts = deque(self.alerts, maxlen=self.max_connections_alerts)
self.log_alerts_only = bool(config.get('log_alerts_only_enabled', DEFAULT_LOG_ALERTS_ONLY))
self.auto_block_enabled = self.log_alerts_only and bool(config.get('auto_block_enabled', True))
saved_filter_alerts = config.get('filter_all_saved_alerts')
saved_filter_auto = config.get('filter_all_saved_auto_block')
if self.filter_all_enabled:
if isinstance(saved_filter_alerts, bool):
self.filter_all_saved_alerts = saved_filter_alerts
else:
self.filter_all_saved_alerts = self.log_alerts_only
if isinstance(saved_filter_auto, bool):
self.filter_all_saved_auto_block = self.filter_all_saved_alerts and saved_filter_auto
else:
self.filter_all_saved_auto_block = self.filter_all_saved_alerts and self.auto_block_enabled
self.log_alerts_only = True
self.auto_block_enabled = True
else:
self.filter_all_saved_alerts = None
self.filter_all_saved_auto_block = None
self.dark_mode = bool(config.get('dark_mode', DEFAULT_DARK_MODE))
self.firewall_initialized = bool(config.get('firewall_initialized', False))
saved_column_orders = config.get('column_orders', {})
if isinstance(saved_column_orders, dict):
for key, default in self.default_column_orders.items():
saved = saved_column_orders.get(key)
if not isinstance(saved, (list, tuple)):
continue
valid = [column for column in saved if column in default]
if key == 'monitor' and 'Status' not in valid:
if 'Process Name' in valid:
valid.insert(valid.index('Process Name') + 1, 'Status')
else:
valid.append('Status')
valid.extend((column for column in default if column not in valid))
self.column_orders[key] = valid
self.allowed_apps = {normalize_path(p) for p in config.get('allowed_apps', []) if normalize_path(p)}
self.pending_rules = []
self.blocked_paths = {}
for rule in config.get('managed_rules', []) or []:
if not isinstance(rule, dict) or not rule.get('path'):
continue
if str(rule.get('action', 'Block')).casefold() == 'allow':
continue
path = display_path(rule.get('path', ''))
norm = normalize_path(path)
if not norm or norm in self.allowed_apps:
continue
direction = direction_name(rule.get('direction', 'Both'))
self.pending_rules.append({'path': path, 'direction': direction})
wanted = direction_set(direction)
self.blocked_paths[norm] = {'in': 'in' in wanted, 'out': 'out' in wanted, 'path': path}
for entry in config.get('global_ip_blocks', []) or []:
target = normalize_target(entry.get('target', '') if isinstance(entry, dict) else entry)
if target:
addresses = entry.get('addresses', []) if isinstance(entry, dict) else []
self.global_blocks[target] = {'addresses': tuple((str(a) for a in addresses if str(a).strip()))}
for entry in config.get('global_ip_allows', []) or []:
target = normalize_target(entry.get('target', '') if isinstance(entry, dict) else entry)
if target and target not in self.global_blocks:
addresses = entry.get('addresses', []) if isinstance(entry, dict) else []
self.global_allows[target] = {'addresses': tuple((str(a) for a in addresses if str(a).strip()))}
self.rate_threshold_var.set(str(self.rate_threshold))
self.rate_window_var.set(str(self.rate_window))
self.upload_threshold_var.set(str(self.upload_threshold_mb))
self.max_connections_alerts_var.set(str(self.max_connections_alerts))
self.log_alerts_var.set(self.log_alerts_only)
self.auto_block_var.set(self.auto_block_enabled)
self.dark_mode_var.set(self.dark_mode)
@staticmethod
def _direction_from_flags(data):
return 'Both' if data['in'] and data['out'] else 'Inbound' if data['in'] else 'Outbound'
def save_settings(self):
temp = CONFIG_FILE + '.tmp'
try:
with self.settings_io_lock:
with self.lock:
managed = [{'action': 'Allow', 'direction': 'Both', 'path': path} for path in sorted(self.allowed_apps)]
managed += [{'action': 'Block', 'direction': self._direction_from_flags(data), 'path': data.get('path', normalized)} for normalized, data in sorted(self.blocked_paths.items())]
config = {'filter_all_enabled': self.filter_all_enabled, 'filter_all_saved_alerts': self.filter_all_saved_alerts, 'filter_all_saved_auto_block': self.filter_all_saved_auto_block, 'saved_rate_threshold': self.saved_rate_threshold, 'rate_threshold': self.rate_threshold, 'rate_window': self.rate_window, 'upload_threshold_mb': self.upload_threshold_mb, 'max_connections_alerts': self.max_connections_alerts, 'log_alerts_only_enabled': self.log_alerts_only, 'auto_block_enabled': self.auto_block_enabled, 'allowed_apps': sorted(self.allowed_apps), 'managed_rules': managed, 'global_ip_blocks': [{'target': target, 'addresses': list(data.get('addresses', ()))} for target, data in sorted(self.global_blocks.items())], 'global_ip_allows': [{'target': target, 'addresses': list(data.get('addresses', ()))} for target, data in sorted(self.global_allows.items())], 'dark_mode': bool(self.dark_mode), 'firewall_initialized': self.firewall_initialized, 'column_orders': {key: list(order) for key, order in self.column_orders.items()}}
with open(temp, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(temp, CONFIG_FILE)
self.settings_save_error = None
return True
except (OSError, TypeError, ValueError) as exc:
self.settings_save_error = str(exc)
try:
if os.path.exists(temp):
os.remove(temp)
except OSError:
pass
return False
def apply_theme(self):
dark = self.dark_mode_var.get()
self.colors = {'bg': '#181818' if dark else '#f2f2f2', 'frame': '#1e1e1e' if dark else '#f2f2f2', 'sub': '#242424' if dark else '#ffffff', 'fg': '#e8e8e8' if dark else '#333333', 'muted': '#a8a8a8' if dark else '#757575', 'entry': '#252526' if dark else '#ffffff', 'select': '#3b78c8' if dark else '#0078D7', 'head': '#2d2d30' if dark else '#e0e0e0', 'even': '#252526' if dark else '#f9f9f9', 'odd': '#1e1e1e' if dark else '#ffffff', 'blocked': '#8b1e1e' if dark else '#ffcaca', 'blocked_in': '#7a4b11' if dark else '#ffe0b2', 'global_block': '#5f2a7a' if dark else '#d1b3e6', 'global_allow': '#90CAF9', 'allowed': '#294f31' if dark else '#e3f5e7', 'watch': '#5b4a16' if dark else '#fff3cd'}
self.root.configure(bg=self.colors['bg'])
style = ttk.Style(self.root)
try:
style.theme_use('clam')
except tk.TclError:
pass
style.configure('TFrame', background=self.colors['frame'])
style.configure('TLabel', background=self.colors['frame'], foreground=self.colors['fg'])
style.configure('TLabelframe', background=self.colors['sub'], foreground=self.colors['fg'], bordercolor=self.colors['blocked_in'])
style.configure('TLabelframe.Label', background=self.colors['sub'], foreground=self.colors['fg'])
style.configure('TNotebook', background=self.colors['bg'], borderwidth=0)
style.configure('TNotebook.Tab', background=self.colors['head'], foreground=self.colors['fg'], font=('Segoe UI', 10, 'bold'), padding=[10, 5, 10, 5])
style.map('TNotebook.Tab', background=[('selected', self.colors['frame']), ('active', self.colors['sub'])], foreground=[('selected', self.colors['fg']), ('active', self.colors['fg'])], padding=[('selected', [10, 8, 10, 4]), ('!selected', [10, 5, 10, 5])])
style.configure('TCheckbutton', background=self.colors['frame'], foreground=self.colors['fg'])
style.map('TCheckbutton', background=[('active', self.colors['frame'])], foreground=[('disabled', self.colors['muted']), ('active', self.colors['fg'])])
style.configure('Treeview', background=self.colors['sub'], foreground=self.colors['fg'], fieldbackground=self.colors['sub'], rowheight=25)
style.configure('Treeview.Heading', background=self.colors['head'], foreground=self.colors['fg'], font=('Segoe UI', 9, 'bold'))
style.map('Treeview.Heading', background=[('active', '#d8d8d8'), ('pressed', '#c8c8c8')], foreground=[('active', '#000000'), ('pressed', '#000000')])
style.map('Treeview', background=[('selected', self.colors['select'])], foreground=[('selected', '#ffffff')])
style.configure('TEntry', fieldbackground=self.colors['entry'], foreground=self.colors['fg'])
style.map('TEntry', fieldbackground=[('disabled', self.colors['head'])], foreground=[('disabled', self.colors['muted'])])
def repaint(parent):
for widget in parent.winfo_children():
try:
if isinstance(widget, tk.LabelFrame):
widget.configure(bg=self.colors['frame'], fg=self.colors['fg'])
elif isinstance(widget, tk.Frame):
widget.configure(bg='#555555' if getattr(widget, '_button_border_frame', False) else self.colors['frame'])
elif isinstance(widget, tk.Label):
widget.configure(bg=self.colors['frame'], fg=self.colors['fg'])
elif isinstance(widget, tk.Entry):
widget.configure(bg=self.colors['entry'], fg=self.colors['fg'], insertbackground=self.colors['fg'])
elif isinstance(widget, tk.Checkbutton):
widget.configure(bg=self.colors['frame'], fg=self.colors['fg'], activebackground=self.colors['frame'], activeforeground=self.colors['fg'], selectcolor=self.colors['entry'])
except tk.TclError:
pass
repaint(widget)
repaint(self.root)
self.configure_tags()
self.update_filter_ui()
self.update_status()
def configure_tags(self):
for name in ('tree', 'active_tree', 'rules_tree', 'alerts_tree'):
tree = getattr(self, name, None)
if tree is None:
continue
for tag, key, fg in (('even', 'even', None), ('odd', 'odd', None), ('blocked', 'blocked', None), ('blocked_in', 'blocked_in', None), ('global_block', 'global_block', '#ffffff' if self.dark_mode_var.get() else self.colors['fg']), ('global_allow', 'global_allow', '#000000'), ('allowed', 'allowed', None), ('watch', 'watch', None)):
tree.tag_configure(tag, background=self.colors[key], foreground=fg or self.colors['fg'])
def on_theme_changed(self):
with self.lock:
self.dark_mode = bool(self.dark_mode_var.get())
self.save_settings()
self.apply_theme()
def setup_gui(self):
self.apply_theme()
self.setup_status_bar()
self.main_area = tk.Frame(self.root, bg=self.colors['bg'])
self.main_area.pack(fill=tk.BOTH, expand=True, padx=10, pady=(10, 6))
self.top_controls = tk.Frame(self.root, bg=self.colors['bg'])
self.notebook = ttk.Notebook(self.main_area)
self.notebook.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
tabs = (('tab_monitor', 'Live Monitor'), ('tab_rules', 'Managed Rules'), ('tab_active', 'Active'), ('tab_alerts', 'Alerts'), ('tab_settings', 'Settings'))
for attr, title in tabs:
tab = ttk.Frame(self.notebook)
setattr(self, attr, tab)
self.notebook.add(tab, text=title)
self.setup_monitor_tab()
self.setup_rules_tab()
self.setup_active_tab()
self.setup_alerts_tab()
self.setup_settings_tab()
self.filter_border = self._button(self.top_controls, 'Filter All Connections OFF', self.toggle_filter_all, '#9E9E9E', pack=False, font=('Segoe UI', 10, 'bold'), padx=10, pady=2, tooltip=lambda: 'Filter All Connections is locked while monitoring is paused.' if self.is_paused else 'Force the Max Connections Threshold to 1 and inspect every new connection. Filter All Connections also enables and locks Alerts + Auto-Block Protection.')
self.btn_filter = self.filter_border.winfo_children()[0]
self.filter_border.pack(side=tk.LEFT, padx=(0, 4))
self.pause_border = self._button(self.top_controls, '⏸ Pause Monitoring', self.toggle_pause, '#2196F3', pack=False, font=('Segoe UI', 10, 'bold'), padx=10, pady=2, tooltip=lambda: 'Resume live packet capture and monitoring' if self.is_paused else 'Pause live packet capture and monitoring')
self.btn_pause = self.pause_border.winfo_children()[0]
self.pause_border.pack(side=tk.LEFT)
self.chk_dark_top = tk.Checkbutton(self.top_controls, text='Dark Theme', variable=self.dark_mode_var, command=self.on_theme_changed, bg=self.colors['bg'], fg=self.colors['fg'], activebackground=self.colors['bg'], activeforeground=self.colors['fg'], selectcolor=self.colors['entry'], font=('Segoe UI', 9, 'bold'), relief=tk.FLAT, bd=0, highlightthickness=0)
self.chk_dark_top.pack(side=tk.LEFT, padx=(10, 0))
add_tooltip(self.chk_dark_top, 'Toggle the application dark theme. This stays synchronized with Settings > Appearance.')
self.update_filter_ui()
self.top_controls.update_idletasks()
self.root.after_idle(self._position_top_controls)
self.main_area.bind('<Configure>', self._position_top_controls, add='+')
for tree in (self.tree, self.active_tree, self.rules_tree, self.alerts_tree):
self._bind_tree_selection(tree)
self.tree.bind('<Button-3>', lambda e: self.show_connection_menu(e, self.tree))
self.active_tree.bind('<Button-3>', lambda e: self.show_connection_menu(e, self.active_tree))
self.rules_tree.bind('<Button-3>', self.show_rules_menu)
self.alerts_tree.bind('<Button-3>', self.show_alert_menu)
self.alerts_tree.bind('<Double-1>', self.alert_details_from_event)
self.root.bind('<F5>', self._on_f5)
self.root.bind_all('<Delete>', self._on_global_delete_key, add='+')
self.root.bind_all('<KP_Delete>', self._on_global_delete_key, add='+')
self.apply_theme()
def _on_f5(self, _event=None):
if hasattr(self, 'notebook') and self.notebook.select() == str(self.tab_rules):
self.refresh_rules(force=True)
return 'break'
@staticmethod
def _hover_color(color):
try:
value = str(color).lstrip('#')
if len(value) != 6:
return str(color)
red, green, blue = (int(value[index:index + 2], 16) for index in (0, 2, 4))
return '#{:02x}{:02x}{:02x}'.format(max(0, int(red * 0.72)), max(0, int(green * 0.72)), max(0, int(blue * 0.72)))
except (TypeError, ValueError):
return str(color)
@classmethod
def _bind_button_hover(cls, button, border=None):
if getattr(button, '_pyfirewall_hover_bound', False):
return button
button._pyfirewall_hover_bound = True
def set_normal_state(bg=None, activebackground=None):
try:
if bg is not None:
button._pyfirewall_base_bg = bg
if activebackground is not None:
button._pyfirewall_base_active_bg = activebackground
else:
button._pyfirewall_base_active_bg = getattr(button, '_pyfirewall_base_bg', button.cget('bg'))
if border is not None:
border._pyfirewall_base_bg = getattr(button, '_pyfirewall_base_bg', border.cget('bg'))
except tk.TclError:
pass
set_normal_state(button.cget('bg'), button.cget('activebackground'))
def enter(_event=None):
try:
if str(button.cget('state')) == str(tk.DISABLED):
button.configure(cursor='arrow')
return
normal_bg = getattr(button, '_pyfirewall_base_bg', button.cget('bg'))
hover = cls._hover_color(normal_bg)
button.configure(bg=hover, activebackground=hover, cursor='hand2')
if border is not None:
border.configure(bg=hover)
except tk.TclError:
pass
def leave(_event=None):
try:
normal_bg = getattr(button, '_pyfirewall_base_bg', button.cget('bg'))
normal_active_bg = getattr(button, '_pyfirewall_base_active_bg', normal_bg)
button.configure(bg=normal_bg, activebackground=normal_active_bg, cursor='')
if border is not None:
border.configure(bg=normal_bg)
except tk.TclError:
pass
button.bind('<Enter>', enter, add='+')
button.bind('<Leave>', leave, add='+')
button._pyfirewall_set_normal_state = set_normal_state
return button
def _set_button_colors(self, button, border, color, fg='white', state=tk.NORMAL):
if button is None:
return
try:
button.configure(bg=color, activebackground=color, fg=fg, activeforeground=fg, state=state)
setter = getattr(button, '_pyfirewall_set_normal_state', None)
if callable(setter):
setter(color, color)
else:
button._pyfirewall_base_bg = color
button._pyfirewall_base_active_bg = color
if border is not None:
border.configure(bg=color)
border._pyfirewall_base_bg = color
except tk.TclError:
pass
def _button(self, parent, text, command, color=None, pack=True, tooltip=None, **options):
color = color or '#757575'
border = tk.Frame(parent, bg=color, bd=0, highlightthickness=0)
border._button_border_frame = True
settings = {'text': text, 'command': command, 'bg': color, 'fg': 'white', 'activebackground': color, 'activeforeground': 'white', 'relief': 'flat', 'borderwidth': 0, 'highlightthickness': 0, 'font': ('Segoe UI', 9, 'bold'), 'padx': 9}
settings.update(options)
button = tk.Button(border, **settings)
self._bind_button_hover(button, border)
button.pack(fill=tk.BOTH, expand=True, padx=1, pady=1)
if pack:
border.pack(side=tk.LEFT, padx=4)
add_tooltip(button, tooltip or BUTTON_TIPS.get(text, ''))
return button if pack else border
def _make_tree(self, parent, columns, widths, order_key):
tree = ttk.Treeview(parent, columns=columns, show='headings', selectmode='extended')
tree._column_order_key = order_key
for column in columns:
width, anchor, stretch = widths.get(column, (180, tk.W, True))
tree.heading(column, text=column)
tree.column(column, width=width, anchor=anchor, stretch=stretch)
order = self._normalized_column_order(order_key, columns)
tree['displaycolumns'] = tuple(order)
scrollbar = ttk.Scrollbar(parent, orient=tk.VERTICAL, command=tree.yview)
tree.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
tree.bind('<Control-a>', self.select_all_rows)
tree.bind('<Control-A>', self.select_all_rows)
self._bind_tree_headers(tree)
return tree
def _normalized_column_order(self, order_key, columns=None):
default = tuple(self.default_column_orders[order_key])
available = set(columns or default)
with self.lock:
saved = list(self.column_orders.get(order_key, list(default)))
result = [c for c in saved if c in available]
result.extend((c for c in default if c in available and c not in result))
if columns:
result.extend((c for c in columns if c not in result))
self.column_orders[order_key] = result
return list(result)
def _position_top_controls(self, _event=None):
if not hasattr(self, 'notebook') or not hasattr(self, 'top_controls'):
return
try:
self.notebook.update_idletasks()
self.top_controls.update_idletasks()
self.root.update_idletasks()
tabs = self.notebook.tabs()
if not tabs:
return
last_index = len(tabs) - 1
notebook_width = self.notebook.winfo_width()
notebook_height = self.notebook.winfo_height()
if notebook_width <= 0 or notebook_height <= 0:
self.root.after(50, self._position_top_controls)
return
tab_y = None
last_tab_start_x = None
for y in range(2, min(notebook_height, 40), 2):
found_x = None
for x in range(0, notebook_width, 4):
try:
index = self.notebook.index(f'@{x},{y}')
except tk.TclError:
continue
if index == last_index:
found_x = x
break
if found_x is not None:
tab_y = y
last_tab_start_x = found_x
break
if tab_y is None or last_tab_start_x is None:
self.root.after(50, self._position_top_controls)
return
tab_right = last_tab_start_x
for x in range(last_tab_start_x, notebook_width):
try:
index = self.notebook.index(f'@{x},{tab_y}')
except tk.TclError:
break
if index != last_index:
break
tab_right = x + 1
probe_x = max(last_tab_start_x, tab_right - 2)
tab_top = tab_y
tab_bottom = tab_y
for y in range(0, min(notebook_height, 50)):
try:
index = self.notebook.index(f'@{probe_x},{y}')
except tk.TclError:
continue
if index == last_index:
tab_top = y
break
for y in range(tab_top, min(notebook_height, 50)):
try:
index = self.notebook.index(f'@{probe_x},{y}')
except tk.TclError:
break
if index != last_index:
break
tab_bottom = y + 1
controls_h = self.top_controls.winfo_reqheight()
gap = 10
tab_root_x = self.notebook.winfo_rootx()
tab_root_y = self.notebook.winfo_rooty()
root_x = tab_root_x + tab_right + gap
tab_height = max(1, tab_bottom - tab_top)
root_y = tab_root_y + tab_top + max(0, (tab_height - controls_h) // 2)
x = root_x - self.root.winfo_rootx()
y = root_y - self.root.winfo_rooty()
self.top_controls.place(x=x, y=y, anchor=tk.NW)
self.top_controls.lift()
except tk.TclError:
pass
def _tree_column_from_x(self, tree, x):
try:
token = tree.identify_column(x)