Repository navigation
Expand file tree
/
Copy pathviews.py
More file actions
2099 lines (1951 loc) · 117 KB
/
Copy pathviews.py
File metadata and controls
2099 lines (1951 loc) · 117 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
"""Connection, rule and alert views, context actions and import/export."""
import csv
import copy
import ctypes
import ipaddress
import json
import os
import psutil
import queue
import subprocess
import threading
import time
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from constants import CREATE_NO_WINDOW, GLOBAL_PURPLE, GLOBAL_TEAL, GLOBAL_YELLOW
from helpers import (
direction_name,
direction_set,
display_path,
executable_identity,
is_global_target,
is_ip,
log_internal_error,
mb,
normalize_path,
normalize_ports,
normalize_target,
global_targets,
rule_executables,
)
from widgets import add_tooltip, ask_undo_string
class ViewsMixin:
"""Methods composed into FirewallMonitorApp; state is owned by that application."""
# Managed-rule refresh
def refresh_rules(self, force=False):
with self.lock:
if self.closed or not getattr(self, 'firewall_ready', False):
return
self.rules_generation += 1
self.rules_refresh_pending = True
self.rules_loading = True
if self.rules_refresh_worker_running:
return
self.rules_refresh_worker_running = True
self.rules_tree.delete(*self.rules_tree.get_children())
self.rules_tree.insert('', tk.END, iid='__loading__', values=('', 'Loading', 'Reading Windows Firewall...', '', '', '', '', '', ''), tags=('even',))
try:
if hasattr(self, 'native_jobs'):
if not self._queue_native_job('Refresh rules', self._refresh_rules_worker):
raise RuntimeError('Native work queue is busy. Retry Refresh.')
else:
threading.Thread(target=self._refresh_rules_worker, daemon=True, name='RuleRefresh').start()
except Exception as exc:
with self.lock:
self.rules_refresh_worker_running = self.rules_refresh_pending = self.rules_loading = False
generation = self.rules_generation
log_internal_error('rule_refresh_start', exc)
self.ui_queue.put(('rules_error', generation, str(exc)))
def _refresh_rules_worker(self):
while True:
with self.lock:
if self.closed:
self.rules_refresh_pending = False
self.rules_refresh_worker_running = False
return
if not self.rules_refresh_pending:
self.rules_refresh_worker_running = False
return
self.rules_refresh_pending = False
generation = self.rules_generation
try:
with self.firewall_lock:
records = self.get_firewall_rules()
with self.lock:
if self.closed:
continue
result = self._reconcile_native_rules_locked(records)
if result is None:
with self.lock:
self.rules_refresh_pending = True
continue
blocked, allowed, blocks, allows, ports = result
self.ui_queue.put(('rules', generation, blocked, allowed, blocks, allows, ports))
except Exception as exc:
self._invalidate_native_observation()
self.ui_queue.put(('rules_error', generation, str(exc)))
with self.lock:
if self.closed:
self.rules_refresh_pending = False
self.rules_refresh_worker_running = False
return
if self.rules_refresh_pending:
continue
self.rules_refresh_worker_running = False
return
@staticmethod
def _global_rule_description(rule):
targets = []
for item in rule['targets']:
target = item['target']
if not is_ip(target) and item['addresses']:
target += " (" + ', '.join(item['addresses']) + ")"
targets.append(target)
target = ', '.join(targets) or 'All domains/IPs'
ports = ', '.join(map(str, rule['ports'])) or 'All'
names = ', '.join(os.path.basename(path) for path in rule_executables(rule))
process = names + ' | ' if names else ''
return f"{process}{target} | Ports: {ports} | Protocol: {rule['protocol']}"
def _make_rule_rows(self, blocked, allowed, blocks, allows, ports=None):
rows = []
for path in sorted(allowed):
rows.append({'iid': f'app:allow:{path}', 'status': 'Allowed', 'rule': os.path.basename(path) or path,
'action': 'Allow', 'direction': 'Both', 'path': path, 'normalized_path': path,
'port': 'All', 'protocol': 'Any', 'download': 0, 'upload': 0})
for path, data in sorted(blocked.items()):
direction = self._direction_from_flags(data)
rows.append({'iid': f'app:block:{path}', 'status': 'Blocked' if direction != 'Inbound' else 'Blocked (in)',
'rule': os.path.basename(data['path']) or data['path'], 'action': 'Block', 'direction': direction,
'path': data['path'], 'normalized_path': path, 'port': 'All',
'protocol': 'Any', 'download': 0, 'upload': 0})
if ports is None:
with self.lock:
ports = copy.deepcopy(getattr(self, 'global_ports', {}))
for key, rule in sorted(ports.items()):
description = self._global_rule_description(rule)
paths = rule_executables(rule)
if len(paths) > 1:
raise ValueError('Saved global policies must contain at most one executable.')
program_display = paths[0] if paths else description
rows.append({'iid': f'port:{key}', 'status': self._global_status(rule['action'], rule['direction']),
'rule': description, 'port': ', '.join(map(str, rule['ports'])) or 'All',
'protocol': rule['protocol'], 'action': rule['action'], 'direction': rule['direction'],
'path': key, 'normalized_path': key, 'display_path': program_display,
'executable_paths': paths, 'global_type': rule['action'].lower(), 'is_port': True,
'download': 0, 'upload': 0})
for row in rows:
key = row['normalized_path']
row['order_id'] = ('port:' if row.get('is_port') else
'observed:' if blocked.get(key, {}).get('_native_only') and row['action'] == 'Block' else 'app:') + key
if row.get('is_port'):
state = ports[key].get('_enforcement', 'Verified')
elif row['action'] == 'Allow':
state = 'Verified'
else:
state = blocked.get(key, {}).get('_enforcement', 'Verified')
row['enforcement'] = state
if state not in {'Verified', 'Observed'}:
origin = 'observed' if blocked.get(key, {}).get('_native_only') else 'intended'
row['status'] = f"{row['action']} {origin} ({state.lower()})"
with self.lock:
self._sync_rule_order_locked()
identities = {row['order_id'] for row in rows}
observed = {value for value in identities if value.startswith('observed:')}
self.observed_rule_order = [value for value in getattr(self, 'observed_rule_order', []) if value in observed]
self.observed_rule_order.extend(sorted(observed - set(self.observed_rule_order)))
self._sync_rule_order_locked(preferred=self.observed_rule_order)
order = [value for value in self.rule_order if value in identities]
order.extend(sorted(identities - set(order)))
numbers = {value: index for index, value in enumerate(order, 1)}
for row in rows:
row['number'] = numbers[row['order_id']]
return rows
def _finish_rule_refresh(self, generation, blocked, allowed, blocks, allows, ports=None):
if generation != self.rules_generation or self.closed:
return
rows = self._make_rule_rows(blocked, allowed, blocks, allows, ports)
with self.lock:
if generation != self.rules_generation or self.closed:
return
self._update_rule_traffic_locked(rows)
self.rule_rows = rows
self.rules_loading = False
self.render_rules()
self.render_monitor()
# Rule creation dialogs
def _focus_rule_editor(self):
"""Reject another manual editor without making Auto-Block prompts modal."""
dialog = getattr(self, 'rule_editor_dialog', None)
if dialog is None or not dialog.winfo_exists():
self.rule_editor_dialog = None
return False
dialog.deiconify()
dialog.lift()
dialog.focus_set()
prompt = getattr(self, 'auto_prompt_dialog', None)
if prompt is not None and prompt.winfo_exists():
prompt.lift()
prompt.focus_set()
return True
def _new_rule_editor(self):
if self._focus_rule_editor():
return None
dialog = tk.Toplevel(self.root)
self.rule_editor_dialog = dialog
self._diagnostic_event('manual editor opened', dialog)
def release(event):
if event.widget is dialog and self.rule_editor_dialog is dialog:
self._diagnostic_event('manual editor destroyed', dialog)
self.rule_editor_dialog = None
dialog.bind('<Destroy>', release, add='+')
return dialog
def add_custom_rule(self):
if self._focus_rule_editor():
return
selected = filedialog.askopenfilenames(title='Select Executable', filetypes=[('Executable Files', '*.exe')])
if not selected:
return
try:
paths = rule_executables({'exes': list(selected)})
except ValueError as exc:
messagebox.showwarning('App Rule', str(exc), parent=self.root)
return
action = self._choose_option('App Rule', '\n'.join(paths) + '\n\nChoose the application rule:', (
('Allow', 'allow', '#4CAF50'), ('Block', 'both', '#c62828'), ('Block Incoming', 'in', '#ff9800')))
if action:
self._apply_rule_batch([(path, action == 'allow', 'both' if action == 'allow' else action, False)
for path in paths], report=True)
def add_monitor_rule(self):
rows = self.selected_connection_data(self.tree)
choice = self._choose_option('Create Rule', 'Choose a rule type:', (
('App Rule', 'app', '#4CAF50'), ('Global Rule', 'global', GLOBAL_PURPLE)))
if choice == 'app':
self.add_custom_rule()
elif choice == 'global':
if rows:
self._combined_connection_global_editor(rows)
else:
self.add_global_rule_dialog()
def _choose_option(self, title, prompt, choices, current=None):
result = [None]
dialog = self._new_rule_editor()
if dialog is None:
return None
dialog.withdraw()
dialog.title(title)
dialog.transient(self.root)
dialog.resizable(False, False)
self._theme_dialog(dialog)
ttk.Label(dialog, text=prompt, wraplength=420, padding=16).pack(fill=tk.X)
def choose(value):
result[0] = value
dialog.destroy()
for label, value, color in choices:
selected_light = value == current and not self.dark_mode
parent = dialog
if selected_light:
# Use a flat, explicitly colored border: Windows can draw
# black top/left edges even for a grey SUNKEN frame.
parent = tk.Frame(dialog, bg=self.colors['fg'], relief=tk.FLAT,
borderwidth=0, highlightthickness=0)
parent.pack(fill=tk.X, padx=16, pady=4)
button = tk.Button(parent, text=label + (' (Current)' if value == current else ''), command=lambda v=value: choose(v),
bg=color, fg='#e8e8e8', relief=tk.SUNKEN if value == current else tk.FLAT,
font=('Segoe UI', 9, 'bold'), padx=16, pady=8)
self._bind_button_hover(button)
if selected_light:
button.configure(relief=tk.FLAT, borderwidth=0, highlightthickness=0)
button.pack(fill=tk.X, padx=2, pady=2)
else:
button.pack(fill=tk.X, padx=16, pady=4)
ttk.Button(dialog, text='Cancel', command=dialog.destroy).pack(pady=12)
dialog.bind('<Escape>', lambda _: dialog.destroy())
self._position_dialog_near_pointer(dialog)
dialog.deiconify()
self.root.wait_window(dialog)
return result[0]
@staticmethod
def _validate_global_rule_fields(target, port):
targets = global_targets(target.strip()) if target.strip() else []
return ', '.join(targets), normalize_ports(port)
def _global_editor_conflict(self, fields, replace_rule=None, target_context=None, pending_reviews=None):
def draft(values):
target, ports, protocol, action, paths = values
targets = [{'target': normalize_target(value), 'addresses': []} for value in target.split(',')
if is_global_target(normalize_target(value))] if target else []
return list(self._parse_port_rules([{
'targets': targets, 'ports': ports, 'protocol': protocol, 'exes': paths,
'action': action.split()[0], 'direction': 'Inbound' if action.endswith('Incoming') else
'Outbound' if action.endswith('Outgoing') else 'Both'}]).values())
candidates = draft(fields)
def filters(rule):
return (frozenset(item['target'] for item in rule['targets']),
tuple(rule['ports']), executable_identity(rule))
def protocols(rule):
value = rule['protocol']
return {'TCP', 'UDP'} if value == 'TCP/UDP' else {'TCP', 'UDP', 'Any'} if value == 'Any' else {value}
with self.lock:
policies = list(getattr(self, 'global_ports', {}).items())
removals = {}
contexts = [review[2] for review in pending_reviews or ()] + [target_context]
for context in contexts:
for item in self._target_contexts(context):
removals.setdefault(item['source'], []).extend(item['selections'])
policies = [(key, self._connection_target_remainder(rule, removals[key]) if key in removals else rule)
for key, rule in policies]
policies.extend((None, rule) for review in pending_reviews or () for rule in draft(review[0]))
for candidate in candidates:
for key, existing in policies:
if existing is None or replace_rule == ('port', key) or filters(candidate) != filters(existing):
continue
if not protocols(candidate) & protocols(existing):
continue
wanted, present = direction_set(candidate['direction']), direction_set(existing['direction'])
if not wanted & present:
continue
if candidate['protocol'] != existing['protocol']:
return (f"Overlapping protocol: {candidate['protocol']} and {existing['protocol']} cover "
'some of the same traffic. Choose protocols or directions that do not overlap.')
if wanted != present:
return ('Conflicting direction: a matching rule already applies to '
f"{existing['direction']}. Both overlaps Incoming and Outgoing.")
if candidate['action'] != existing['action']:
return ('Conflicting rule: a matching rule already has the opposite action '
f"({existing['action']}) for the same direction.")
return None
@staticmethod
def _target_contexts(context):
return context if isinstance(context, list) else [context] if context else []
def _ask_global_rule_fields(self, initial=None):
initial = initial or {}
result = [None]
dialog = self._new_rule_editor()
if dialog is None:
return None
try:
dialog.withdraw()
dialog.title('Edit Global Rule' if initial.get('editing') else 'Add Global Rule')
dialog.transient(self.root)
dialog.resizable(False, False)
self._theme_dialog(dialog)
fields = ttk.Frame(dialog, padding=16)
fields.pack(fill=tk.BOTH, expand=True)
text_options = {} if self.dark_mode else {'foreground': '#222222'}
ttk.Label(fields, text='Action:', **text_options).grid(row=0, column=0, sticky='w')
action = ttk.Combobox(fields, values=('Allow', 'Allow Outgoing', 'Allow Incoming', 'Block Incoming', 'Block Outgoing', 'Block'), state='readonly', width=30)
action.set(initial.get('action', 'Allow'))
action.grid(row=0, column=1, sticky='ew', pady=(0, 12))
ttk.Label(fields, text='Executable (optional):', **text_options).grid(row=1, column=0, sticky='w', padx=(0, 12))
exe_frame = ttk.Frame(fields)
exe_frame.grid(row=1, column=1, sticky='ew', pady=4)
# Keep invalid prefilled paths visible until Save validates them.
selected_paths = rule_executables(initial, validate=False)
variables = [tk.StringVar(master=dialog, value=', '.join(os.path.basename(path) for path in selected_paths))]
dialog.bind('<Destroy>', lambda event: variables.clear() if event.widget is dialog else None, add='+')
exe = ttk.Entry(exe_frame, width=30, state='readonly', textvariable=variables[0], **text_options)
exe.pack(side=tk.LEFT, fill=tk.X, expand=True)
def display_executables():
variables[0].set(', '.join(os.path.basename(path) for path in selected_paths))
def browse_executable():
paths = filedialog.askopenfilenames(parent=dialog, title='Select Executable',
filetypes=[('Executable Files', '*.exe')])
for path in paths:
if normalize_path(path) not in {normalize_path(item) for item in selected_paths}:
selected_paths.append(display_path(path))
display_executables()
def clear_executables():
selected_paths.clear()
display_executables()
ttk.Button(exe_frame, text='Browse', command=browse_executable).pack(side=tk.LEFT, padx=(4, 0))
ttk.Button(exe_frame, text='Clear', command=clear_executables).pack(side=tk.LEFT, padx=(4, 0))
ttk.Label(fields, text='Domains or IP addresses:', **text_options).grid(row=2, column=0, sticky='w', padx=(0, 12))
target = ttk.Entry(fields, width=36, **text_options)
self._bind_entry_menu(target)
target.insert(0, ', '.join(item['target'] for item in initial.get('targets', [])))
target.grid(row=2, column=1, sticky='ew', pady=4)
ttk.Label(fields, text='Port / Protocol:', **text_options).grid(row=3, column=0, sticky='w')
port_frame = ttk.Frame(fields)
port_frame.grid(row=3, column=1, sticky='ew', pady=4)
port = ttk.Entry(port_frame, width=18, **text_options)
self._bind_entry_menu(port)
port.insert(0, ', '.join(map(str, initial.get('ports', []))))
port.pack(side=tk.LEFT)
ttk.Label(port_frame, text='(1-65535)', **text_options).pack(side=tk.LEFT, padx=6)
protocol = ttk.Combobox(port_frame, values=('TCP/UDP', 'TCP', 'UDP'), state='readonly', width=10)
protocol.set(initial.get('protocol', 'TCP/UDP'))
protocol.pack(side=tk.RIGHT, fill=tk.X, expand=True)
ttk.Label(fields, text='Separate targets and ports with commas; use start-end for IP ranges.\nLeave targets blank for all domains/IPs; leave ports blank for all ports.\nAssigned port numbers represent either Local or Remote ports.', **text_options).grid(row=4, column=0, columnspan=2, sticky='w', pady=8)
def submit():
try:
paths = rule_executables({'exes': selected_paths})
except ValueError as exc:
messagebox.showwarning(dialog.title(), str(exc), parent=dialog)
dialog.focus_set()
return
try:
# Validate shared fields now; individual targets are processed independently.
raw_target = target.get().strip()
syntax_target = raw_target if initial.get('_replace_rule') or initial.get('_target_context') else '192.0.2.1' if raw_target else ''
_, numbers = self._validate_global_rule_fields(syntax_target, port.get())
proposed = (raw_target, numbers, protocol.get(), action.get(), paths)
conflict = self._global_editor_conflict(proposed, initial.get('_replace_rule'),
initial.get('_target_context'), initial.get('_pending_reviews'))
if conflict:
messagebox.showwarning('Global Rule Not Saved', conflict +
'\n\nChange the rule settings or cancel this editor.', parent=dialog)
return
sources, snapshots = self._global_editor_sources(initial)
if not self._global_sources_available(sources):
raise ValueError('This global rule is updating. Wait for completion before saving.')
if not initial.get('_review_only'):
initial['_operation_id'] = self._reserve_global_operation(sources, snapshots, initial.get('_source_versions'))
result[0] = proposed
except ValueError as exc:
if initial.get('editing'):
messagebox.showwarning('Global Rule Not Saved', str(exc), parent=dialog)
return
if not messagebox.askokcancel('Add Global Rule', str(exc), icon='warning', parent=dialog):
dialog.destroy()
return
dialog.destroy()
buttons = ttk.Frame(fields)
buttons.grid(row=5, column=1, pady=(12, 0))
ttk.Button(buttons, text='Save', command=submit).pack(side=tk.LEFT, padx=4)
ttk.Button(buttons, text='Cancel', command=dialog.destroy).pack(side=tk.LEFT, padx=4)
dialog.bind('<Return>', lambda _: submit())
dialog.bind('<Escape>', lambda _: dialog.destroy())
self._position_dialog_near_pointer(dialog)
dialog.deiconify()
target.focus_set()
self.root.wait_window(dialog)
return result[0]
except Exception:
if dialog.winfo_exists():
dialog.destroy()
self._complete_global_operation(initial.get('_operation_id'), False)
raise
def _global_editor_sources(self, initial):
initial = initial or {}
snapshots = {item['source']: item['snapshot'] for item in self._target_contexts(initial.get('_target_context'))}
if initial.get('_replace_rule'):
key = initial['_replace_rule'][1]
snapshots[key] = initial.get('_source_snapshot')
return set(snapshots), snapshots
def add_global_rule_dialog(self, initial=None, replace_rule=None, target_context=None, review=None, pending_reviews=None):
initial = copy.deepcopy(initial or {})
if replace_rule:
with self.lock:
snapshot = self.global_ports.get(replace_rule[1])
if snapshot is None:
self._native_message('showwarning', 'Global Rule', 'This global rule changed or was removed. Refresh Managed Rules.')
return False
initial.update(_replace_rule=replace_rule, _source_snapshot=copy.deepcopy(snapshot))
if target_context:
initial['_target_context'] = copy.deepcopy(target_context)
if pending_reviews:
initial['_pending_reviews'] = copy.deepcopy(pending_reviews)
if review is not None:
initial['_review_only'] = True
sources, snapshots = self._global_editor_sources(initial)
with self.lock:
initial.setdefault('_source_versions', {key: getattr(self, 'global_policy_versions', {}).get(key) for key in sources})
if not self._global_sources_available(sources):
self._native_message('showinfo', 'Global Rule Updating', 'This global rule is updating. Wait for completion before editing it again.')
return False
retry = getattr(self, 'retry_global_fields', None)
if retry and not self._global_draft_current(retry):
self.retry_global_fields = retry = None
if retry and retry[2:4] == (replace_rule, target_context):
draft, _ = self._prepare_global_rule_fields(retry[0], retry[1], replace_rule[1] if replace_rule else None)
initial.update(draft, action=retry[0][3])
elif target_context:
for draft_fields, draft_initial, draft_context in getattr(self, 'retry_connection_reviews', ()):
if draft_context == target_context and self._global_draft_current(
(draft_fields, dict(draft_initial, _target_context=draft_context), None, draft_context, 0)):
contexts = self._target_contexts(target_context)
draft, _ = self._prepare_global_rule_fields(draft_fields, draft_initial,
contexts[0]['source'] if len(contexts) == 1 else None)
initial.update(draft, action=draft_fields[3])
break
fields = self._ask_global_rule_fields(initial)
if fields is None:
if retry and retry[2:4] == (replace_rule, target_context):
self.retry_global_fields = None
self.retry_connection_reviews = [item for item in getattr(self, 'retry_connection_reviews', ())
if item[2] != target_context]
return
if review is not None:
reviewed_initial = {key: value for key, value in initial.items() if key not in {'_pending_reviews', '_review_only'}}
review(copy.deepcopy((fields, reviewed_initial, target_context)))
return
operation_id = initial.get('_operation_id')
if operation_id is None:
try:
operation_id = self._reserve_global_operation(sources, snapshots, initial.get('_source_versions'))
except ValueError as exc:
retry = getattr(self, 'retry_global_fields', None)
if retry and not self._global_draft_current(retry):
self.retry_global_fields = None
self._native_message('showwarning', 'Global Rule', str(exc))
return False
with self.lock:
operation = self.global_operations.get(operation_id)
if operation is not None:
initial['_source_versions'] = copy.deepcopy(operation['source_versions'])
operation['draft'] = copy.deepcopy((fields, initial, replace_rule, target_context, operation_id))
if self._native_ui_call():
snapshot = copy.deepcopy((fields, initial, replace_rule, target_context, operation_id))
if not self._queue_native_job('Global rule update', lambda: self._apply_global_rule_fields(*snapshot)):
self.retry_global_fields = snapshot
self._complete_global_operation(operation_id, False)
self._native_message('showwarning', 'Global Rule', 'The edit was not queued. Its draft was retained; reopen the rule to retry.')
return False
if retry and retry[2:4] == (replace_rule, target_context):
self.retry_global_fields = None
return None
return self._apply_global_rule_fields(fields, initial, replace_rule, target_context, operation_id)
def _prepare_global_rule_fields(self, fields, initial=None, source=None):
"""Syntax only. Every forward lookup belongs to the native transaction."""
target, ports, protocol, action, paths = fields
entry = {'targets': [], 'ports': ports, 'protocol': protocol, 'exes': paths,
'action': action.split()[0], 'direction': 'Inbound' if action.endswith('Incoming') else
'Outbound' if action.endswith('Outgoing') else 'Both'}
self._parse_port_rules([entry])
with self.lock:
saved_policy = self.global_ports.get(source, {}) if source is not None else initial or {}
saved = {item['target']: list(item['addresses']) for item in (initial or {}).get('targets', [])}
saved.update({item['target']: list(item['addresses']) for item in saved_policy.get('targets', [])})
failures = []
for value in dict.fromkeys(target.split(',')) if target else []:
name = normalize_target(value)
if not is_global_target(name):
failures.append(f'{value.strip() or "(empty target)"}: Not a valid domain or IP address.')
else:
entry['targets'].append({'target': name, 'addresses': saved.get(name, [])})
return entry, failures
def _apply_global_rule_fields(self, fields, initial=None, replace_rule=None, target_context=None, operation_id=None):
if isinstance(target_context, list):
return self._apply_connection_reviews([(fields, initial or {}, target_context)], operation_id)
outcome = self._rule_operation_outcome(operation_id)
source = target_context['source'] if target_context else replace_rule[1] if replace_rule else None
try:
entry, failures = self._prepare_global_rule_fields(fields, initial, source)
if failures and (replace_rule or target_context):
self._native_message('showwarning', 'Global Rule Update',
'No rules were changed. The existing rule was kept.\n\nTargets not added:\n' + '\n'.join(failures))
self._complete_global_operation(operation_id, False)
return False
if not entry['targets'] and fields[0]:
self._native_message('showwarning', 'Global Rule Update', 'No rules were changed.\n\n' + '\n'.join(failures))
self._complete_global_operation(operation_id, False)
return False
if replace_rule:
with self.lock:
old = self.global_ports.get(source)
parsed = self._parse_port_rules([entry])
if old is not None and len(parsed) == 1 and self._editable_policy(next(iter(parsed.values()))) == self._editable_policy(old) and self._policy_verified('port', source):
receipt = getattr(self, '_unsaved_rule_batch', None)
if getattr(self, 'settings_save_error', None) and self._receipt_current(receipt):
identity = receipt['identity']
return self._apply_rule_batch(identity[0], port_updates=identity[1], observed_addresses=identity[2],
replace_rule=identity[3], target_edits=identity[4], order_hint=identity[5],
allow_partial_targets=identity[6], operation_id=operation_id, report=True)
self._complete_global_operation(operation_id, True)
return True
# Receipt data retains the original submitted fields after a native
# commit, even though its source key may already have been retired.
retry = getattr(self, '_unsaved_global_fields', None)
receipt = getattr(self, '_unsaved_rule_batch', None)
if receipt and retry and retry[:4] == (fields, initial, replace_rule, target_context) and self._receipt_current(receipt):
return self._apply_rule_batch(*copy.deepcopy(retry[4]), operation_id=operation_id,
allow_partial_targets=receipt['identity'][6])
if target_context:
args = ([], False, None, None, None, True, [dict(copy.deepcopy(target_context), replacement=entry)], None)
else:
args = ([], False, [entry], None, replace_rule, not failures, None, None)
self._last_global_target_failures = []
applied = self._apply_rule_batch(*args, operation_id=operation_id,
allow_partial_targets=not (replace_rule or target_context),
lookup_feedback=bool(replace_rule or target_context), outcome=outcome)
if applied is False and getattr(self, '_unsaved_rule_batch', None):
self._unsaved_global_fields = copy.deepcopy((fields, initial, replace_rule, target_context, args))
failures.extend(outcome['target_failures'])
if failures and not (applied is False and outcome['applied']):
processed = len(entry['targets']) - len(outcome['target_failures'])
summary = f'{processed} valid target(s) processed.' if applied else 'No rules were changed.'
text = (summary + '\n\nTargets not added:\n' + '\n'.join(failures)
+ '\nCheck the names or remove rejected targets before retrying.')
self.queue_alert('Warning', 'Global rule lookup', '', '', text)
self._native_message('showwarning', 'Global Rule Update', text)
return applied
except Exception as exc:
if not isinstance(exc, ValueError):
log_internal_error('global_rule_fields', exc)
self.queue_alert('High', 'Global rule update', '', '', str(exc))
self._complete_global_operation(operation_id, False)
self._native_message('showerror', 'Global Rule Update', str(exc) + '\n\n' + self._rule_outcome_text(outcome))
return False
def _apply_connection_reviews(self, reviews, operation_id=None):
"""Validate all reviewed slices, reserve together, then enqueue one writer."""
updates, edits, failures = [], [], []
try:
for fields, initial, context in reviews:
contexts = self._target_contexts(context)
entry, errors = self._prepare_global_rule_fields(fields, initial, contexts[0]['source'] if len(contexts) == 1 else None)
failures.extend(errors)
if contexts:
edits.extend(dict(copy.deepcopy(item), replacement=entry) for item in contexts)
else:
updates.append(entry)
if failures:
self._native_message('showwarning', 'Global Rule Update',
'No rules were changed. Existing target slices were kept.\n\nTargets not added:\n' + '\n'.join(failures))
self._complete_global_operation(operation_id, False)
return False
retry = getattr(self, '_unsaved_connection_reviews', None)
receipt = getattr(self, '_unsaved_rule_batch', None)
if receipt and retry == reviews and self._receipt_current(receipt):
identity = receipt['identity']
return self._apply_rule_batch(identity[0], port_updates=identity[1], observed_addresses=identity[2],
replace_rule=identity[3], target_edits=identity[4], order_hint=identity[5],
allow_partial_targets=identity[6], operation_id=operation_id, report=True)
for fields, initial, context in reviews:
if not self._global_draft_current((fields, dict(initial, _target_context=context), None, context, 0)):
raise ValueError('This global rule changed or was removed. Reopen the connection editor before retrying.')
applied = self._apply_rule_batch([], port_updates=updates, target_edits=edits,
operation_id=operation_id, report=True)
if applied is False:
self.retry_connection_reviews = copy.deepcopy(reviews)
else:
self.retry_connection_reviews = []
if applied is False and getattr(self, '_unsaved_rule_batch', None):
self._unsaved_connection_reviews = copy.deepcopy(reviews)
return applied
except Exception as exc:
if not isinstance(exc, ValueError):
log_internal_error('connection_reviews', exc)
self.queue_alert('High', 'Global rule update', '', '', str(exc))
self._complete_global_operation(operation_id, False)
self._native_message('showerror', 'Global Rule Update', str(exc))
return False
def _combined_connection_global_editor(self, rows):
"""Review shared fields once, replacing only the captured source target slices."""
targets, paths, ports, protocols, contexts = {}, {}, set(), set(), {}
all_matched = True
try:
for row in copy.deepcopy(rows):
members = row.get('_members') or [row]
for member in members:
path, = rule_executables({'exes': [member.get('exe')]})
paths[normalize_path(path)] = path
selections = self._connection_target_selections(member)
raw_port, protocol = str(member.get('dport', '')), str(member.get('protocol', '')).upper()
if not selections or not raw_port.isdecimal() or not 1 <= int(raw_port) <= 65535 or protocol not in {'TCP', 'UDP'}:
raise ValueError('Every selected connection needs a valid remote IP, port, protocol and full executable path.')
ports.add(int(raw_port)); protocols.add(protocol)
for item in selections:
for target in self._connection_global_targets(item['remote'], item['domain']):
targets.setdefault(target, set()).add(item['remote'])
matches = self.connection_global_rules(member)
all_matched = all_matched and bool(matches)
for rule in matches:
context = self._connection_target_context(member, rule)
saved = contexts.setdefault(context['source'], dict(context, selections=[]))
saved['selections'].extend(context['selections'])
initial = {'exes': [paths[key] for key in sorted(paths)], 'ports': sorted(ports),
'protocol': next(iter(protocols)) if len(protocols) == 1 else 'TCP/UDP',
'action': 'Allow', 'editing': all_matched,
'targets': [{'target': target, 'addresses': sorted(addresses)} for target, addresses in sorted(targets.items())]}
except ValueError as exc:
messagebox.showwarning('Global Rule', str(exc), parent=self.root)
return False
return self.add_global_rule_dialog(initial, target_context=list(contexts.values()) or None)
def bulk_remote_ports(self, tree, allow):
ports = set()
for row in self.selected_connection_data(tree):
raw = str(row.get('dport', ''))
if str(row.get('protocol', '')).upper() in {'TCP', 'UDP'} and raw.isdecimal() and 1 <= int(raw) <= 65535:
ports.add(int(raw))
if not ports:
messagebox.showinfo('Global Port Rule', 'No valid TCP/UDP remote port was selected.', parent=self.root)
return
self._apply_rule_batch([], port_updates=[{'ports': sorted(ports), 'targets': [], 'exes': [],
'protocol': 'TCP/UDP', 'direction': 'Both', 'action': 'Allow' if allow else 'Block'}], report=True)
def change_selected_ports(self, allow, direction='both'):
self.prompt_selected_global_rules(allow, direction)
def add_global_target(self, action):
target = ask_undo_string(f'{action} Global Target', 'IP address or domain:', parent=self.root)
if not target or not target.strip():
return
allow = action == 'Allow'
direction = 'both' if allow else self.ask_direction(
f'Choose how to block {target.strip()} globally across all processes.',
block_labels=('Block All', 'Block Only Incoming'))
if direction:
self.add_global_rule(target.strip(), allow, direction=direction)
def ask_direction(self, prompt, allow=False, block_labels=('Block In & Out', 'Block Incoming')):
result = {'value': None}
dialog = tk.Toplevel(self.root)
dialog.title('Firewall Action')
dialog.resizable(False, False)
dialog.withdraw()
dialog.transient(self.root)
self._theme_dialog(dialog)
tk.Label(dialog, text=prompt, wraplength=380, padx=18, pady=15, bg=self.colors['frame'], fg=self.colors['fg']).pack()
buttons = tk.Frame(dialog, bg=self.colors['frame'])
buttons.pack(fill=tk.X, padx=15, pady=5)
def choose(value):
result['value'] = value
dialog.destroy()
for text, value, color, tip in ((block_labels[0], 'both', '#c62828', 'Block incoming and outgoing traffic.'), (block_labels[1], 'in', '#ff9800', 'Block incoming traffic and leave outgoing traffic allowed.')):
button = tk.Button(buttons, text=text, command=lambda v=value: choose(v), bg=color, fg='white', relief='flat')
self._bind_button_hover(button)
button.pack(fill=tk.X, pady=3)
add_tooltip(button, tip)
if allow:
button = tk.Button(buttons, text='Allow All', command=lambda: choose('allow'), bg='#4CAF50', fg='white', relief='flat')
self._bind_button_hover(button)
button.pack(fill=tk.X, pady=3)
add_tooltip(button, 'Allow all traffic for the executable.')
button = tk.Button(buttons, text='Cancel', command=dialog.destroy, bg=self.colors.get('head', '#757575'), fg=self.colors['fg'], relief='flat')
self._bind_button_hover(button)
button.pack(fill=tk.X, pady=3)
add_tooltip(button, 'Close without changing the firewall rules.')
dialog.update_idletasks()
self._position_dialog_near_pointer(dialog)
dialog.deiconify()
dialog.lift()
dialog.focus_force()
self.root.wait_window(dialog)
return result['value']
# Sorting and table rendering
def sort_tree(self, tree, column):
states = ((self.tree, self.monitor_sort, self.render_monitor), (self.rules_tree, self.rule_sort, self.render_rules))
state, renderer = (self.alert_sort, self.render_alerts)
for target, candidate, fn in states:
if tree is target:
state, renderer = (candidate, fn)
break
if state[0] == column:
state[1] = not state[1]
else:
state[:] = [column, column in {'#', 'Download (MB)', 'Upload (MB)', 'Time', 'PID'}
and not (tree is self.rules_tree and column == '#')]
renderer()
@staticmethod
def search_text(row):
return ' '.join(map(str, (ViewsMixin._connection_time_text(row), row.get('name', ''), row.get('pid', ''), row.get('direction', ''), row.get('protocol', ''), row.get('_local_ports', row.get('lport', '')), row.get('dst_ip', ''), row.get('remote_host', row.get('domain', '')), row.get('dport', ''), mb(row.get('_down', 0)), mb(row.get('_up', 0)), row.get('signal', ''), row.get('exe', '')))).casefold()
@staticmethod
def _connection_time_text(row):
stamp = row.get('run_created_at', row.get('created_at'))
return time.strftime('%H:%M:%S', time.localtime(stamp)) if stamp is not None else '—'
def _aggregate_connection_rows(self, members, key=None):
row = dict(members[0])
row['_members'] = members
row['_local_ports'] = list(dict.fromkeys(int(member['lport']) for member in members
if str(member.get('lport', '')).isdecimal()
and 1 <= int(member['lport']) <= 65535))
row['_local_port_unknown'] = any(not str(member.get('lport', '')).isdecimal()
or not 1 <= int(member['lport']) <= 65535 for member in members)
row['_grouped'] = len(members) > 1
unique = {self._flow_identity(member): member for member in members}
for side, label in (('download', '_down'), ('upload', '_up')):
row[side] = row[label] = sum(member.get('_flow_totals', member).get(side, 0)
for member in unique.values())
if key is not None:
row['key'] = key
return row
@staticmethod
def _connection_local_port(row):
ports = row.get('_local_ports')
if ports is None:
return row.get('lport') or '—'
return ports[0] if len(ports) == 1 and not row.get('_local_port_unknown') else '—'
def _connection_groups(self, members):
"""Build arrival runs before filtering or sorting; DNS is not identity."""
runs = []
last = None
for member in sorted(members, key=lambda row: row.get('_capture_id', row.get('number', 0))):
signature = self._connection_group_signature(member)
identity = member.get('_run_id')
boundary = (signature, identity)
if signature is not None and runs and boundary == last:
runs[-1].append(member)
else:
runs.append([member])
last = boundary
return [self._aggregate_connection_rows(run, run[0].get('_run_id', run[0]['key'])) for run in runs]
def sort_monitor_rows(self, rows, state):
column, reverse = state
fields = {'#': lambda r: r['number'], 'Process Name': lambda r: r['name'].casefold(), 'Status': lambda r: (r['_render_status'] if '_render_status' in r else self.connection_status(r)).casefold(), 'PID': lambda r: r['pid'], 'Direction': lambda r: r['direction'].casefold(), 'Protocol': lambda r: r['protocol'].casefold(), 'Local Port': lambda r: int(self._connection_local_port(r)) if str(self._connection_local_port(r)).isdecimal() else -1, 'Remote IP': lambda r: self._ip_sort_key(r['dst_ip']), 'Remote Host': lambda r: r.get('remote_host', r.get('domain', '')).casefold(), 'Remote Port': lambda r: r['dport'], 'Download (MB)': lambda r: r.get('_down', 0), 'Upload (MB)': lambda r: r.get('_up', 0), 'Signal': lambda r: r.get('signal', '').casefold(), 'Exe Path': lambda r: r['exe'].casefold()}
fields['Time'] = lambda r: r.get('run_created_at', r.get('created_at', 0))
fields['Remote Port'] = lambda r: int(r['dport']) if str(r.get('dport', '')).isdecimal() else -1
rows.sort(key=lambda r: (r.get('name', '').casefold(), normalize_path(r.get('exe')), str(r.get('key', ''))))
rows.sort(key=fields.get(column, lambda r: ''), reverse=reverse)
@staticmethod
def _ip_sort_key(value):
text = str(value or '').strip()
try:
address = ipaddress.ip_address(text.strip('[]').split('%', 1)[0])
return address.version, int(address), text.casefold()
except ValueError:
# Keep empty/unavailable addresses sortable alongside IPv4 and IPv6.
return 0, 0, text.casefold()
def _render_connections(self, tree, search_var, sort_state):
if not isinstance(tree, ttk.Treeview):
return
search = search_var.get().casefold().strip()
self._refresh_retained_hosts(alerts=False, discover=True)
with self.lock:
members = [dict(row) for row in self.active_connections.values()]
rows = self._connection_groups(members)
snapshot = self._connection_render_snapshot()
self.connection_display_groups = {row['key']: row for row in rows}
for row in rows:
row['_render_tag'], row['_render_status'] = self._connection_presentation(row, snapshot)
row['remote_host'] = self.remote_host(row)
row['_down'] = row.get('download', 0)
row['_up'] = row.get('upload', 0)
if search:
rows = [row for row in rows if search in self.search_text(row)]
self.sort_monitor_rows(rows, sort_state)
selected = set(tree.selection())
tree.delete(*tree.get_children())
for index, row in enumerate(rows):
tree.insert('', tk.END, iid=row['key'], values=self.connection_values(row, include_status=True), tags=(row['_render_tag'] or ('watch' if row.get('signal') else 'even' if index % 2 == 0 else 'odd'),))
if selected:
tree.selection_set([iid for iid in selected if tree.exists(iid)])
def render_monitor(self):
self._render_connections(self.tree, self.search_var, self.monitor_sort)
def connection_values(self, row, include_status=True):
values = {'#': row['number'], 'Time': self._connection_time_text(row), 'Process Name': row['name'], 'Status': row['_render_status'] if '_render_status' in row else self.connection_status(row),
'PID': row['pid'], 'Direction': row['direction'], 'Protocol': row['protocol'],
'Local Port': self._connection_local_port(row), 'Remote IP': row['dst_ip'], 'Remote Host': self.remote_host(row) or '—',
'Remote Port': row['dport'], 'Download (MB)': mb(row.get('_down', 0)),
'Upload (MB)': mb(row.get('_up', 0)), 'Signal': row.get('signal') or '—', 'Exe Path': row['exe']}
return tuple(values[c] for c in self.MONITOR_COLUMNS if include_status or c != 'Status')
@staticmethod
def _global_tag(action, direction='Both'):
suffix = {'Inbound': '_in', 'Outbound': '_out'}.get(direction_name(direction), '')
return 'global_' + action.lower() + suffix
@staticmethod
def _global_status(action, direction='Both'):
suffix = {'Inbound': ' (in)', 'Outbound': ' (out)'}.get(direction_name(direction), '')
return f'{action.title()}ed{suffix} (Global)'
def _connection_render_snapshot(self):
for attempt in range(2):
matching = self._matching_snapshot()
with self.lock:
if matching[0] != self._policy_revision_locked():
continue
return (matching, dict(getattr(self, 'rule_enforcement', {})) if hasattr(self, 'rule_enforcement') else None,
{key: dict(value) for key, value in getattr(self, 'verified_blocked_paths', self.blocked_paths).items()},
frozenset(self.allowed_apps), frozenset(self.blocked_paths), frozenset(self.auto_prompt_keys))
return None
def _connection_presentation(self, row, snapshot):
if snapshot is None:
return '', 'Policy updating'
matching, states, blocked, allowed, intended, pending = snapshot
results = []
for member in row.get('_members') or [row]:
path = normalize_path(member.get('exe', ''))
if path in pending:
results.append(('blocked', 'Blocked (Pending)'))
continue
rules = self._match_endpoint(member, matching[1])
verified = [rule for key, rule in rules.items() if states is None or states.get(('port', key)) == 'Verified']
app = blocked.get(path, {})
direction = direction_name(member.get('direction'))
app_block = (app.get('in') and direction != 'Outbound' or app.get('out') and direction != 'Inbound')
found = None
for action in ('Block', 'Allow'):
if action == 'Allow' and app_block:
tag = 'blocked_in' if app.get('in') and not app.get('out') else 'blocked'
found = (tag, 'Blocked (in)' if tag == 'blocked_in' else 'Blocked')
break
choices = [rule for rule in verified if rule['action'] == action]
if choices:
rule = next((rule for rule in choices if rule['direction'] == 'Both'), choices[0])
found = (self._global_tag(action, rule['direction']), self._global_status(action, rule['direction']))
break
if found is None:
if path in allowed:
found = ('allowed', 'Allowed')
elif rules and any(states is not None and states.get(('port', key)) != 'Verified' for key in rules):
found = ('', 'Policy drift')
elif path in intended:
found = ('', 'Block intended (unverified)')
else:
found = ('', '—')
results.append(found)
return results[0] if all(result == results[0] for result in results) else ('', 'Mixed coverage')
def connection_status(self, row):
return self._connection_presentation(row, self._connection_render_snapshot())[1]
def connection_tag(self, row, index=0):
tag, _ = self._connection_presentation(row, self._connection_render_snapshot())
return tag or ('watch' if row.get('signal') else 'even' if index % 2 == 0 else 'odd')
def alert_tag(self, values, iid=None):
row = self.alert_connection_row(values, iid) if iid else self.alert_context(values)[0]
remote_ip = row.get('dst_ip', '') if row else self.alert_context(values)[1]
if row:
tag = self.connection_tag(row)
return '' if tag in {'even', 'odd', 'watch'} else tag
if self.is_globally_blocked(remote_ip):
return self.global_block_tag(remote_ip)
if self.is_globally_allowed(remote_ip):
return 'global_allow'
return ''
def global_block_tag(self, remote, domain='', direction=None):
row = {'dst_ip': remote, 'domain': domain, 'direction': direction}
for rule in self.matching_global_port_rules(row).values():
if rule['action'] == 'Block':
return self._global_tag('Block', rule['direction'])
return 'global_block'
def render_rules(self):
if not hasattr(self, 'rules_tree'):
return
search = self.rule_search_var.get().casefold().strip()
rows = [dict(row) for row in self.rule_rows]
with self.lock:
pending = set(getattr(self, 'pending_global_sources', {}))
states = dict(getattr(self, 'rule_enforcement', {}))
for row in rows:
if row.get('is_port'):
key = row['normalized_path']
state = 'Updating' if key in pending else states.get(('port', key), row.get('enforcement', 'Verified'))
row['status'] = (self._global_status(row['action'], row['direction']) if state == 'Verified' else
f"{row['action']} intended ({state.lower()})")
if search:
rows = [row for row in rows if search in ' '.join(map(str, (row.get('number', ''), row['status'], row['rule'], row['action'], row['direction'], row.get('display_path', row['path']), row.get('port', ''), row.get('protocol', ''), ' '.join(row.get('executable_paths', ())), mb(row.get('download', 0)), mb(row.get('upload', 0))))).casefold()]
column, reverse = self.rule_sort
if column:
fields = {'#': lambda r: r.get('number', 0), 'Status': lambda r: r['status'].casefold(), 'Application & Global Rules': lambda r: r['rule'].casefold(), 'Direction': lambda r: r['direction'].casefold(), 'Download (MB)': lambda r: r.get('download', 0), 'Upload (MB)': lambda r: r.get('upload', 0), 'Program Path': lambda r: r.get('display_path', r['path']).casefold()}
for label, key in (('Port', 'port'),):
fields[label] = lambda r, key=key: tuple(int(value.strip()) for value in str(r.get(key, '')).split(',')
if value.strip().isdecimal())
fields['Protocol'] = lambda r: r.get('protocol', '').casefold()
rows.sort(key=lambda r: ((os.path.basename(r['executable_paths'][0]) if r.get('executable_paths') else
r['rule']).casefold(), normalize_path(r.get('display_path', r['path'])), r['iid']))
rows.sort(key=fields.get(column, lambda r: ''), reverse=reverse)
selected = set(self.rules_tree.selection())
self.rules_tree.delete(*self.rules_tree.get_children())
for row in rows:
tag = self._global_tag(row['action'], row['direction']) if row.get('global_type') else 'allowed' if row['status'] == 'Allowed' else 'blocked_in' if row['status'] == 'Blocked (in)' else 'blocked'
down = mb(row.get('download', 0))
up = mb(row.get('upload', 0))
self.rules_tree.insert('', tk.END, iid=row['iid'], values=(row.get('number', ''), row['status'], row['rule'], row['direction'], row.get('port') or 'All', row.get('protocol', ''), down, up, row.get('display_path', row['path'])), tags=(tag,))
if selected:
self.rules_tree.selection_set([iid for iid in selected if self.rules_tree.exists(iid)])
def render_alerts(self):
if not hasattr(self, 'alerts_tree'):