Repository navigation
Expand file tree
/
Copy pathfirewall.py
More file actions
2304 lines (2178 loc) · 128 KB
/
Copy pathfirewall.py
File metadata and controls
2304 lines (2178 loc) · 128 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
"""Windows Firewall commands, managed rules, verification and recovery."""
import hashlib
import ipaddress
import json
import os
import re
import socket
import subprocess
import tempfile
import time
import queue
import threading
import copy
from functools import lru_cache
from tkinter import messagebox
from constants import (
AUTO_HOLD_PREFIX,
CREATE_NO_WINDOW,
FIREWALL_COMMAND_TIMEOUT,
FIREWALL_PROFILE_BACKUP_FILE,
GLOBAL_PORT_PREFIX,
)
from helpers import (
address_networks,
global_targets,
ip_range,
normalize_address,
direction_name,
direction_set,
display_path,
executable_fields,
executable_identity,
error_details,
is_global_target,
is_ip,
log_internal_error,
log_rule_lookup,
normalize_path,
normalize_ports,
normalize_target,
rule_executables,
)
class GlobalLookupError(ValueError):
"""An ordinary name lookup rejection, with resolver data preserved."""
def __init__(self, target, category='lookup', resolver_code=None):
self.target, self.category, self.resolver_code = target, category, resolver_code
detail = f'Windows could not resolve {target}'
if resolver_code is not None:
detail += f' ({resolver_code})'
if category == 'no addresses':
detail += ': DNS returned no addresses'
super().__init__(f"Could not resolve global target '{target}': {detail}.")
class FirewallMixin:
"""Methods composed into FirewallMonitorApp; state is owned by that application."""
@staticmethod
def _direction_from_flags(data):
return 'Both' if data['in'] and data['out'] else 'Inbound' if data['in'] else 'Outbound'
# Command execution and verified transactions
def _start_native_worker(self):
self.native_jobs = queue.Queue(maxsize=128)
self.native_job_keys = set()
self.native_shutdown_requested = False
self.native_worker = threading.Thread(target=self._native_worker, daemon=True,
name='PyFirewall-Native')
self.native_worker.start()
def _native_ui_call(self):
return (hasattr(self, 'native_jobs') and
threading.get_ident() == self.ui_thread_id)
def _queue_native_job(self, label, operation, key=None):
"""Bound discardable requests; cleanup and shutdown use retained state."""
with self.lock:
if self.closed or getattr(self, 'native_shutdown_requested', False):
return False
if key is not None and key in self.native_job_keys:
return True
try:
self.native_jobs.put_nowait((label, operation, key))
except queue.Full:
self.queue_alert('High', 'Native work queue', '', '',
f'{label} was not queued: the worker is busy. Please retry.')
return False
if key is not None:
self.native_job_keys.add(key)
return True
def _native_worker(self):
while True:
if self.native_shutdown_requested:
self._shutdown_worker()
return
# Retired holds are durable cleanup obligations, not queue events.
if getattr(self, 'auto_hold_cleanup', {}):
self._release_auto_holds_for_generation(None)
try:
label, operation, key = self.native_jobs.get(timeout=0.1)
except queue.Empty:
continue
try:
if not self.native_shutdown_requested:
with self.firewall_lock:
with self.lock:
self.native_operation_label = label
operation()
except Exception as exc:
log_internal_error('native_worker', exc)
self.queue_alert('High', label, '', '', str(exc))
self._native_message('showerror', label, str(exc))
finally:
with self.lock:
self.native_operation_label = None
self.native_job_keys.discard(key)
self.native_jobs.task_done()
def _native_message(self, method, title, text, **options):
if threading.get_ident() != getattr(self, 'ui_thread_id', threading.main_thread().ident):
self.ui_queue.put(('message', method, title, text))
else:
options.setdefault('parent', self.root)
getattr(messagebox, method)(title, text, **options)
def _reserve_global_operation(self, sources=(), snapshots=None, versions=None):
"""Own every source atomically, from Save through UI completion."""
sources = set(sources)
with self.lock:
pending = getattr(self, 'pending_global_sources', {})
if any(key in pending for key in sources):
raise ValueError('This global rule is updating. Wait for completion before editing it again.')
for key in sources:
if (key not in self.global_ports or snapshots is not None and self.global_ports[key] != snapshots[key]
or versions is not None and getattr(self, 'global_policy_versions', {}).get(key) != versions.get(key)):
raise ValueError('This global rule changed or was removed. Reopen the editor before retrying.')
self.global_operation_serial = getattr(self, 'global_operation_serial', 0) + 1
operation = self.global_operation_serial
self.pending_global_sources = pending
for key in sources:
pending[key] = operation
if not hasattr(self, 'global_operations'):
self.global_operations = {}
self.global_operations[operation] = {'operation_id': operation, 'source_ids': sorted(sources),
'source_snapshots': copy.deepcopy({key: self.global_ports[key] for key in sources}),
'source_versions': {key: getattr(self, 'global_policy_versions', {}).get(key) for key in sources},
'result_ids': [], 'stage': 'queued', 'outcome': self._new_rule_outcome()}
return operation
@staticmethod
def _new_rule_outcome():
return dict(mutation_started=False, prior_readback_verified=False, readback_verified=False,
observation_published=False, reconciliation='not requested', applied=False,
persistence='not needed', failure_kind=None, lookup_failures=[], target_failures=[])
def _rule_operation_outcome(self, operation_id):
with self.lock:
operation = getattr(self, 'global_operations', {}).get(operation_id)
return operation['outcome'] if operation is not None else self._new_rule_outcome()
@staticmethod
def _rule_verification(outcome):
if outcome['reconciliation'] == 'pending':
return 'Verification pending'
if outcome['failure_kind'] == 'uncertain':
return 'Unknown'
if outcome['applied'] and outcome['readback_verified'] and outcome['observation_published']:
return 'Verified'
if outcome['mutation_started'] and outcome['prior_readback_verified'] and outcome['observation_published']:
return 'Restored'
return 'Unchanged' if not outcome['mutation_started'] else 'Unknown'
def _rule_outcome_text(self, outcome):
state = self._rule_verification(outcome)
if state == 'Restored':
return 'The previous firewall filters were restored and verified. This restores their captured state, including any disabled or missing filters.'
if state == 'Unchanged':
return 'No firewall changes were made.'
if state == 'Verification pending':
return 'The captured previous filters were read back, but verification of the current view is pending. Refresh Managed Rules.'
if state == 'Unknown':
return 'Firewall enforcement is unknown. Refresh Managed Rules and check the local error log before retrying.'
if outcome['persistence'] == 'pending':
return 'The firewall change was applied and verified, but its disk save is pending. Retry saving.'
return 'The firewall change was applied and verified.'
def _claim_global_sources(self, keys, operation_id=None):
"""Writer-side protection also covers merges, imports and removals."""
with self.lock:
pending = getattr(self, 'pending_global_sources', {})
if any(key in pending and pending[key] != operation_id for key in keys):
raise ValueError('A selected global rule is updating. Retry after completion.')
if operation_id is not None:
operation = self.global_operations.get(operation_id)
if operation is None:
raise ValueError('The global edit operation is no longer current.')
for key in keys:
pending[key] = operation_id
operation['result_ids'] = sorted(set(operation['result_ids']) | set(keys))
def _global_operation_stage(self, operation_id, stage):
with self.lock:
self.global_transaction = {'operation_id': operation_id, 'stage': stage}
if operation_id in getattr(self, 'global_operations', {}):
self.global_operations[operation_id]['stage'] = stage
diagnostics = getattr(self, 'diagnostics', None)
if diagnostics is not None:
diagnostics.transaction(operation_id, stage)
def _complete_global_operation(self, operation_id, success):
if operation_id is None:
return
with self.lock:
operation = getattr(self, 'global_operations', {}).get(operation_id)
if operation is None:
return
if operation.get('completion_queued'):
return
operation['completion_queued'] = True
outcome = {key: copy.deepcopy(operation[key]) for key in ('operation_id', 'source_ids', 'result_ids')}
receipt = getattr(self, '_unsaved_rule_batch', None)
unsaved = bool(receipt and receipt.get('operation_id') == operation_id and self._receipt_current(receipt))
outcome.update(copy.deepcopy(operation['outcome']))
outcome.update(success=bool(success), verification=self._rule_verification(outcome),
persistence_only=unsaved, stage='complete')
if threading.get_ident() == getattr(self, 'ui_thread_id', threading.main_thread().ident):
self._consume_global_operation(outcome)
else:
self.ui_queue.put(('global_operation_complete', outcome))
def _consume_global_operation(self, outcome):
operation_id = outcome['operation_id']
with self.lock:
operation = self.global_operations.pop(operation_id, None)
if operation is None:
return
self.pending_global_sources = {key: owner for key, owner in self.pending_global_sources.items() if owner != operation_id}
retry = getattr(self, 'retry_global_fields', None)
if retry and not self._global_draft_current(retry):
self.retry_global_fields = None
draft = operation.get('draft')
if draft and outcome['failure_kind'] == 'lookup' and self._global_draft_current(draft):
retry = getattr(self, 'retry_global_fields', None)
if not retry or retry[4] <= operation_id:
self.retry_global_fields = copy.deepcopy(draft)
elif outcome['success'] and draft and retry and retry[2:4] == draft[2:4] and retry[4] <= operation_id:
self.retry_global_fields = None
self.last_global_operation = outcome
def _global_draft_current(self, draft):
initial = draft[1]
sources, snapshots = self._global_editor_sources(initial)
versions = initial.get('_source_versions')
with self.lock:
return not self.closed and all(self.global_ports.get(key) == snapshots[key] and
(versions is None or getattr(self, 'global_policy_versions', {}).get(key) == versions.get(key)) for key in sources)
def _global_sources_available(self, sources):
with self.lock:
return not any(key in getattr(self, 'pending_global_sources', {}) for key in sources)
def _receipt_current(self, receipt):
if not receipt:
return False
with self.lock:
return all(self.global_ports.get(key) == value and
getattr(self, 'global_policy_versions', {}).get(key) == receipt['versions'].get(key)
for key, value in receipt['result_policies'].items())
def _run(self, args, check=True, timeout=None):
return subprocess.run(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=check,
creationflags=CREATE_NO_WINDOW,
timeout=FIREWALL_COMMAND_TIMEOUT if timeout is None else timeout,
)
def run_ps(self, command, check=True, timeout=None):
args = ('powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass')
options = {} if timeout is None else {'timeout': timeout}
# Large imports exceed Windows' command-line limit. A BOM also preserves
# Unicode paths when Windows PowerShell 5.1 reads the temporary script.
if len(command.encode('utf-16-le')) > 16000:
with tempfile.TemporaryDirectory(prefix='pyfirewall-') as directory:
path = os.path.join(directory, 'rules.ps1')
with open(path, 'w', encoding='utf-8-sig') as script:
script.write(command)
return self._run((*args, '-File', path), check, **options)
return self._run((*args, '-Command', command), check, **options)
def run_netsh(self, args, check=True):
return self._run(('netsh', 'advfirewall', 'firewall', *args), check)
def delete_rule_names(self, names, strict=True):
names = sorted(set(n for n in names if n))
if not names:
return False
command = "$ErrorActionPreference='Stop'\n$names=@(" + ','.join(self._ps_quote(n) for n in names) + ")\n"
command += '''
$existing = @(Get-NetFirewallRule -ErrorAction Stop | Where-Object { $_.DisplayName -in $names })
if ($existing.Count) { $existing | Remove-NetFirewallRule -ErrorAction Stop }
$remaining = @(Get-NetFirewallRule -ErrorAction Stop | Where-Object { $_.DisplayName -in $names })
if ($remaining.Count) { throw ('Firewall rules could not be removed: ' + ($remaining.DisplayName -join ', ')) }
if ($existing.Count) { 'removed' } else { 'absent' }
'''
try:
output = self.run_ps(command).stdout.strip()
if output not in {'removed', 'absent'}:
raise RuntimeError('Invalid firewall deletion result.')
return output == 'removed'
except Exception:
return self._delete_rule_names_individually(names, strict)
def _delete_rule_names_individually(self, names, strict=True):
names = set(n for n in names if n)
if not names:
return False
existing = {r['name'] for r in self.get_firewall_rules()}
for name in names & existing:
try:
self.run_netsh(['delete', 'rule', f'name={name}'])
except (subprocess.SubprocessError, OSError):
pass
remaining = names & {r['name'] for r in self.get_firewall_rules()}
if remaining:
raise RuntimeError('Firewall rules could not be removed: ' + ', '.join(sorted(remaining)))
return bool(names & existing)
def _replace_rule_records(self, previous, desired_names, apply, apply_first=False, preserve_holds=False, commit=None):
names = {r['name'] for r in previous} | set(desired_names)
try:
if preserve_holds:
self.delete_rule_names(r['name'] for r in previous if not r.get('is_hold'))
apply()
self.delete_rule_names(r['name'] for r in previous if r.get('is_hold'))
elif apply_first:
apply()
self.delete_rule_names(r['name'] for r in previous)
else:
self.delete_rule_names(r['name'] for r in previous)
apply()
if commit is not None:
commit()
except Exception as error:
cleanup_error = None
try:
self.delete_rule_names(names)
except Exception as exc:
cleanup_error = exc
try:
remaining = {r['name'] for r in self.get_firewall_rules()}
self._restore_app_rule_records([r for r in previous if r['name'] not in remaining])
if cleanup_error:
raise cleanup_error
except Exception as rollback_error:
try:
self.sync_rule_cache()
self._save_settings_with_feedback()
except Exception as reconcile_error:
log_internal_error('rule_reconciliation', reconcile_error)
raise RuntimeError(f'Rule update failed: {error}; rollback failed: {rollback_error}') from rollback_error
raise
# Rule discovery, identities and port policies
def get_firewall_rules(self):
command = '''
$rules = Get-NetFirewallRule -ErrorAction Stop |
Where-Object {$_.DisplayName -like "PyFirewall_*"} |
ForEach-Object {
$r = $_
$a = Get-NetFirewallApplicationFilter -AssociatedNetFirewallRule $r -ErrorAction Stop |
Select-Object -First 1
$p = Get-NetFirewallPortFilter -AssociatedNetFirewallRule $r -ErrorAction Stop | Select-Object -First 1
$address = Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $r -ErrorAction Stop
[PSCustomObject]@{
DisplayName=[string]$r.DisplayName
Action=[string]$r.Action
Direction=[string]$r.Direction
Enabled=[string]$r.Enabled
Profile=[string]$r.Profile
Addresses=@($address.RemoteAddress)
LocalAddresses=@($address.LocalAddress)
Program=if($null -ne $a){[string]$a.Program}else{""}
Protocol=if($p){[string]$p.Protocol}else{""}
LocalPorts=@(if($p){$p.LocalPort})
RemotePorts=@(if($p){$p.RemotePort})
}
}
if($null -eq $rules){"[]"}else{@($rules)|ConvertTo-Json -Compress}
'''
output = self.run_ps(command).stdout.strip()
if not output:
return []
try:
raw = json.loads(output)
except (json.JSONDecodeError, TypeError) as exc:
raise RuntimeError(f'Windows Firewall returned invalid rule data: {exc}') from exc
if isinstance(raw, dict):
raw = [raw]
if not isinstance(raw, list):
raise RuntimeError('Windows Firewall returned an unexpected rule-data format.')
records = []
for item in raw:
if not isinstance(item, dict):
raise RuntimeError('Windows Firewall returned an invalid rule record.')
if not str(item.get('DisplayName', '') or '').strip():
raise RuntimeError('Windows Firewall returned a rule without a display name.')
if 'Action' not in item or 'Direction' not in item:
raise RuntimeError('Windows Firewall returned incomplete rule metadata.')
name = str(item.get('DisplayName', '') or '')
global_rule = name.startswith(GLOBAL_PORT_PREFIX)
records.append({'name': name, 'action': str(item.get('Action', '') or ''), 'direction': str(item.get('Direction', '') or ''), 'path': '' if global_rule else display_path(item.get('Program', '')), 'normalized_path': '' if global_rule else normalize_path(item.get('Program', '')), 'is_global': global_rule, 'is_hold': name.startswith(AUTO_HOLD_PREFIX), 'addresses': item.get('Addresses', [])})
records[-1].update(enabled=str(item.get('Enabled', '')).casefold() == 'true',
profile=item.get('Profile', 'Any'), local_addresses=item.get('LocalAddresses', ['Any']),
program=display_path(item.get('Program', '')),
protocol=item.get('Protocol', ''), local_ports=item.get('LocalPorts', []),
remote_ports=item.get('RemotePorts', []))
if name.startswith(GLOBAL_PORT_PREFIX + '4_6_'):
records[-1].update(is_port=True, protocol=item.get('Protocol', ''),
path=display_path(item.get('Program', '')) if item.get('Program') not in ('Any', '', None) else '',
local_ports=item.get('LocalPorts', []), remote_ports=item.get('RemotePorts', []))
return records
def app_rule_base(self, proc_name, exe_path, kind='Block'):
base = re.sub('[^A-Za-z0-9_.-]+', '_', os.path.splitext(os.path.basename(exe_path))[0] or proc_name or 'Process')[:60]
digest = hashlib.sha1(normalize_path(exe_path).encode('utf-8', 'ignore')).hexdigest()[:8]
return f'PyFirewall_{kind}_{base}_{digest}'
@staticmethod
def _policy_key(rule):
identity = {key: rule[key] for key in ('action', 'direction', 'protocol', 'ports')}
identity['exes'] = executable_identity(rule)
identity['targets'] = sorted(item['target'] for item in rule['targets'])
return 'global:' + hashlib.sha256(json.dumps(identity, sort_keys=True, separators=(',', ':')).encode()).hexdigest()[:32]
@staticmethod
def _parse_port_rules(entries, canonical=False):
"""Expand reviewed drafts; persisted current records must be canonical."""
if not isinstance(entries, list):
raise ValueError('Global rules must be a JSON array.')
result = {}
fields = {'action', 'direction', 'protocol', 'exes', 'targets', 'ports'}
for entry in entries:
if not isinstance(entry, dict) or set(entry) != fields:
raise ValueError('Global rules require the current canonical format (version-10 backups). Older or mixed rules cannot be imported.')
if not isinstance(entry['action'], str) or entry['action'] not in {'Allow', 'Block'}:
raise ValueError('A global rule requires Allow or Block.')
if not isinstance(entry['direction'], str) or entry['direction'] not in {'Both', 'Inbound', 'Outbound'}:
raise ValueError('A global rule requires Both, Inbound or Outbound.')
if not isinstance(entry['protocol'], str) or entry['protocol'] not in {'TCP/UDP', 'TCP', 'UDP', 'Any'}:
raise ValueError('Invalid global rule protocol.')
if not isinstance(entry['ports'], list) or any(type(port) is not int or not 1 <= port <= 65535 for port in entry['ports']):
raise ValueError('Global ports must be an array of integers from 1 through 65535.')
if entry['protocol'] == 'Any' and entry['ports']:
raise ValueError('Ports require TCP or UDP.')
rule = {key: entry[key] for key in ('action', 'direction', 'protocol')}
rule['exes'] = sorted(rule_executables(entry), key=normalize_path)
if canonical and len(rule['exes']) > 1:
raise ValueError('Each saved global rule must select at most one executable.')
rule['ports'] = sorted(set(entry['ports']))
if not isinstance(entry['targets'], list):
raise ValueError('Global targets must be an array.')
targets = {}
for item in entry['targets']:
if not isinstance(item, dict) or set(item) != {'target', 'addresses'} or not isinstance(item['target'], str):
raise ValueError('Each target requires a target and its own addresses array.')
target = normalize_target(item['target'])
if ',' in target or not is_global_target(target):
raise ValueError('Invalid global target.')
if not isinstance(item['addresses'], list) or not all(isinstance(value, str) for value in item['addresses']):
raise ValueError('Target addresses must be an array of numeric address filters.')
addresses = {normalize_address(value) for value in item['addresses']}
if is_ip(target):
# A numeric target never borrows another target's coverage.
if addresses and addresses != {normalize_address(target)}:
raise ValueError('Numeric target addresses must match their target.')
addresses = {normalize_address(target)}
targets.setdefault(target, set()).update(addresses)
numeric = FirewallMixin._coverage(target for target in targets if is_ip(target))
domains = {target: addresses for target, addresses in targets.items() if not is_ip(target)}
if {str(network) for network in numeric} == {'0.0.0.0/0', '::/0'}:
targets = {}
else:
targets = dict(domains)
for network in numeric:
target = str(network.network_address) if network.prefixlen == network.max_prefixlen else str(network)
targets[target] = {target}
rule['targets'] = [{'target': target, 'addresses': sorted(addresses)} for target, addresses in sorted(targets.items())]
for paths in ([path] for path in rule['exes']) if rule['exes'] else [[]]:
policy = copy.deepcopy(dict(rule, exes=paths))
key = FirewallMixin._policy_key(policy)
if key in result:
if canonical:
raise ValueError('Duplicate saved global rule.')
saved = {item['target']: item['addresses'] for item in result[key]['targets']}
for item in policy['targets']:
item['addresses'] = sorted(set(item['addresses']) | set(saved[item['target']]))
result[key] = policy
return result
@staticmethod
def _validate_rule_order(order, apps, ports):
expected = {'app:' + normalize_path(path) for path in apps} | {'port:' + key for key in ports}
if (not isinstance(order, list) or any(not isinstance(value, str) for value in order)
or len(order) != len(set(order)) or set(order) != expected):
raise ValueError('Rule order must reference every saved rule exactly once.')
return list(order)
def _sync_rule_order_locked(self, changed=(), preferred=()):
"""Publish chronology with model state, independently of native filter identity."""
current = {'app:' + path for path in self.allowed_apps | self.blocked_paths.keys()}
current.update('port:' + key for key in self.global_ports)
current.update(getattr(self, 'observed_rule_order', []))
changed = set(changed)
order = [value for value in getattr(self, 'rule_order', []) if value in current and value not in changed]
for value in list(preferred) + sorted(current):
if value in current and value not in order:
order.append(value)
self.rule_order = order
@staticmethod
def _rule_addresses(rule):
return sorted({address for target in rule['targets'] for address in target['addresses']}) if rule['targets'] else ['Any']
@staticmethod
def _port_firewall_rules(ports, all_directions=False):
"""Expand one logical either-endpoint policy into disjoint filter branches."""
rules = []
for key, rule in ports.items():
digest = hashlib.sha256(key.encode()).hexdigest()[:32]
protocols = (('TCP', 6), ('UDP', 17)) if rule['protocol'] == 'TCP/UDP' else ((rule['protocol'], {'TCP': 6, 'UDP': 17, 'Any': 256}[rule['protocol']]),)
directions = ('Inbound', 'Outbound') if all_directions else tuple(side for side in ('Inbound', 'Outbound') if direction_set(side) <= direction_set(rule['direction']))
for path in rule_executables(rule) or ['']:
program = hashlib.sha256(normalize_path(path).encode()).hexdigest()[:16]
for protocol, number in protocols:
for direction in directions:
assigned = [str(port) for port in rule['ports']]
branches = (('Local', assigned, ['Any']), ('Remote', ['Any'], assigned)) if assigned else (('Any', ['Any'], ['Any']),)
for branch, local, remote in branches:
rules.append({'name': f'{GLOBAL_PORT_PREFIX}4_6_{digest}_{program}_{number}_{direction}_{branch}',
'action': rule['action'], 'direction': direction, 'path': path, 'is_port': True,
'protocol': protocol, 'addresses': FirewallMixin._rule_addresses(rule),
'local_ports': local, 'remote_ports': remote})
return rules
@staticmethod
def _coverage(values):
networks = [network for value in values for network in address_networks(value)]
return tuple(network for version in (4, 6) for network in ipaddress.collapse_addresses(n for n in networks if n.version == version))
@classmethod
def _address_subset(cls, first, second):
if not second['targets']:
return True
if not first['targets']:
numeric = cls._coverage(item['target'] for item in second['targets'] if is_ip(item['target']))
return {str(network) for network in numeric} == {'0.0.0.0/0', '::/0'}
# Domains retain their identities: today's DNS answer is not a promise
# that two domains will keep the same coverage tomorrow.
first_domains = {item['target'] for item in first['targets'] if not is_ip(item['target'])}
second_domains = {item['target'] for item in second['targets'] if not is_ip(item['target'])}
if not first_domains <= second_domains:
return False
first_numeric = cls._coverage(item['target'] for item in first['targets'] if is_ip(item['target']))
second_numeric = cls._coverage(item['target'] for item in second['targets'] if is_ip(item['target']))
if any(not any(net.version == other.version and net.subnet_of(other) for other in second_numeric) for net in first_numeric):
return False
coverage = cls._coverage(cls._rule_addresses(second))
return all(any(net.version == other.version and net.subnet_of(other) for other in coverage) for net in cls._coverage(cls._rule_addresses(first)))
@classmethod
def _exact_policy_union(cls, first, second):
if len(rule_executables(first)) > 1 or len(rule_executables(second)) > 1:
raise ValueError('Saved global policies must contain at most one executable.')
if any(first[key] != second[key] for key in ('action', 'direction', 'protocol')) or executable_identity(first) != executable_identity(second):
return None
ports_a, ports_b = set(first['ports']), set(second['ports'])
if ports_a != ports_b:
return None
merged = copy.deepcopy(first)
merged['exes'] = list(second['exes'])
merged['ports'] = sorted(ports_a)
targets = {}
if first['targets'] and second['targets']:
for target in first['targets'] + second['targets']:
targets.setdefault(target['target'], set()).update(target['addresses'])
merged['targets'] = [{'target': target, 'addresses': sorted(addresses)} for target, addresses in sorted(targets.items())]
return next(iter(cls._parse_port_rules([merged]).values()))
@classmethod
def _subtract_addresses(cls, values, removed):
"""Subtract bounded CIDR coverage, including /0, without enumerating hosts."""
remaining = list(cls._coverage(values))
for cut in cls._coverage(removed):
pieces = []
for network in remaining:
if network.version != cut.version or not network.overlaps(cut):
pieces.append(network)
elif network.subnet_of(cut):
continue
else:
pieces.extend(network.address_exclude(cut))
remaining = pieces
return [str(net.network_address) if net.prefixlen == net.max_prefixlen else str(net)
for net in cls._coverage(map(str, remaining))]
@classmethod
def _connection_target_remainder(cls, source, selections):
"""Remove named identities and observed points; None means exhausted, never Any.
Named matches leave independent overlapping domains alone. An IP-only
match through a domain freezes that domain's remaining saved addresses
as numeric targets, since re-resolving its name could restore the point.
"""
if len(rule_executables(source)) > 1:
raise ValueError('Saved global policies must contain at most one executable.')
domains = {item['target'] for item in source['targets'] if not is_ip(item['target'])}
points, named, anonymous = set(), set(), set()
coverage = cls._coverage(cls._rule_addresses(source)) if source['targets'] else ()
for selection in selections:
point = str(ipaddress.ip_address(selection['remote']))
address = ipaddress.ip_address(point)
if source['targets'] and not any(address.version == net.version and address in net for net in coverage):
raise ValueError('This connection no longer matches the saved global rule.')
points.add(point)
name = normalize_target(selection.get('domain', ''))
if name in domains:
named.add(name)
else:
anonymous.add(point)
if not points:
raise ValueError('No connection target was selected.')
numeric, domain_residuals, retained = [], [], []
for item in source['targets']:
if is_ip(item['target']):
numeric.append(item['target'])
elif item['target'] not in named:
rest = cls._subtract_addresses(item['addresses'], anonymous)
if cls._coverage(rest) == cls._coverage(item['addresses']):
retained.append(copy.deepcopy(item))
else:
domain_residuals.extend(rest)
if not source['targets']:
numeric = ['0.0.0.0/0', '::/0']
# Independent named coverage stays independent of numeric point cuts.
numeric = cls._subtract_addresses(numeric, points) + domain_residuals
retained.extend({'target': value, 'addresses': [value]}
for value in cls._subtract_addresses(numeric, ()))
if not retained:
return None
return next(iter(cls._parse_port_rules([dict(source, targets=retained)]).values()))
def _policy_revision_locked(self):
return (getattr(self, 'global_policy_epoch', 0), getattr(self, 'policy_revision', 0),
getattr(self, 'observation_revision', 0))
@staticmethod
def _compile_matchers(policies):
compiled = []
for key, rule in policies.items():
networks = []
for item in rule['targets']:
# Domains are identities, never numeric filters. Even corrupted
# saved values cannot broaden a nonempty target set to Any.
for address in item.get('addresses', ()):
try:
networks.extend(address_networks(address))
except ValueError:
continue
compiled.append((key, rule, frozenset(executable_identity(rule)),
frozenset(rule['ports']), rule['protocol'],
frozenset(direction_set(rule['direction'])),
not rule['targets'], tuple(networks)))
return tuple(compiled)
def _matching_snapshot(self):
with self.lock:
revision = self._policy_revision_locked()
# References are immutable after publication; a new policy object
# also invalidates partial fixtures and restored address snapshots.
policies = dict(getattr(self, 'global_ports', {}))
signature = (revision[0], tuple((key, id(rule)) for key, rule in policies.items()))
cached = getattr(self, '_compiled_matchers', None)
if cached is not None and cached[0] == signature:
return revision, cached[1]
compiled = self._compile_matchers(policies)
with self.lock:
if revision == self._policy_revision_locked() and all(self.global_ports.get(k) is v for k, v in policies.items()) and len(policies) == len(self.global_ports):
self._compiled_matchers = (signature, compiled)
return revision, compiled
@staticmethod
def _match_endpoint(row, compiled):
protocol = {'6': 'TCP', '17': 'UDP'}.get(str(row.get('protocol')), str(row.get('protocol', '')).upper())
path = normalize_path(row.get('exe', ''))
ports = {int(value) for value in (row.get('lport'), row.get('dport'))
if not isinstance(value, bool) and str(value).isdecimal() and 1 <= int(value) <= 65535}
try:
remote = ipaddress.ip_address(str(row.get('dst_ip', '')).split('%', 1)[0])
except ValueError:
remote = None
direction = frozenset(direction_set(row['direction'])) if row.get('direction') is not None else None
return {key: rule for key, rule, exes, assigned, proto, sides, any_address, networks in compiled
if (not assigned or bool(assigned & ports)) and (not exes or path in exes)
and (proto == 'Any' or proto == protocol or proto == 'TCP/UDP' and protocol in {'TCP', 'UDP'})
and (direction is None or direction <= sides)
and (any_address or remote is not None and any(remote.version == net.version and remote in net for net in networks))}
def matching_global_port_rules(self, row, snapshot=None):
_, compiled = snapshot if snapshot is not None else self._matching_snapshot()
matches = {}
for member in row.get('_members') or [row]:
matches.update(self._match_endpoint(member, compiled))
return matches
def global_port_action(self, row):
actions = [rule['action'] for key, rule in self.matching_global_port_rules(row).items()
if self._policy_verified('port', key)]
return 'Block' if 'Block' in actions else 'Allow' if 'Allow' in actions else None
def apply_global_port_rules(self, entries):
return self._apply_rule_batch((), port_updates=entries)
@staticmethod
def _ps_quote(value):
return "'" + str(value).replace("'", "''") + "'"
# Application rule creation and native command fallbacks
def _app_rule_commands(self, name, exe_path, side, action='block'):
direction = 'Inbound' if side == 'in' else 'Outbound'
action_name = 'Block' if str(action).casefold() == 'block' else 'Allow'
ps_command = (
f"New-NetFirewallRule -Name {self._ps_quote(name)} -DisplayName {self._ps_quote(name)} "
f"-Direction {direction} -Program {self._ps_quote(exe_path)} "
f"-Action {action_name} -Enabled True -Profile Any -ErrorAction Stop | Out-Null"
)
verify = (
f"$r=Get-NetFirewallRule -Name {self._ps_quote(name)} -ErrorAction Stop; "
f"$a=Get-NetFirewallApplicationFilter -AssociatedNetFirewallRule $r -ErrorAction Stop | Select-Object -First 1; "
f"if(-not $a){{throw 'Application filter is missing.'}}; "
f"if([string]$r.Enabled -ne 'True'){{throw 'Firewall rule is disabled.'}}; "
f"if([string]$r.Direction -ne {self._ps_quote(direction)}){{throw ('Wrong direction: ' + [string]$r.Direction)}}; "
f"if([string]$r.Action -ne {self._ps_quote(action_name)}){{throw ('Wrong action: ' + [string]$r.Action)}}; "
f"if(-not [string]::Equals([string]$a.Program,{self._ps_quote(exe_path)},[System.StringComparison]::OrdinalIgnoreCase)){{throw ('Wrong program: ' + [string]$a.Program)}}"
)
return ps_command, verify
def _add_app_firewall_rule(self, name, exe_path, side, action='block'):
"""Create one application rule, including the native netsh fallback."""
action_name = 'Block' if str(action).casefold() == 'block' else 'Allow'
created = False
used_netsh = False
ps_command, verify = self._app_rule_commands(name, exe_path, side, action)
try:
self.run_ps(ps_command)
created = True
except Exception as first_error:
first_detail = getattr(first_error, 'stderr', '') or ''
try:
self.run_netsh([
'add', 'rule',
f'name={name}',
f'dir={side}',
f'action={action_name.casefold()}',
f'program={exe_path}',
'enable=yes',
'profile=any',
])
created = True
used_netsh = True
except Exception as second_error:
second_detail = getattr(second_error, 'stderr', '') or ''
try:
self.delete_rule_names((name,))
except Exception:
pass
raise RuntimeError(
f"Could not create application firewall rule '{name}' for '{exe_path}'. "
f"PowerShell: {str(first_detail).strip() or str(first_error)}; "
f"netsh: {str(second_detail).strip() or str(second_error)}"
) from second_error
try:
self.run_ps(verify)
return
except Exception as exc:
if used_netsh:
try:
self.run_netsh(['show', 'rule', f'name={name}', 'verbose'])
return
except Exception:
pass
detail = getattr(exc, 'stderr', '') or ''
if created:
try:
self.delete_rule_names((name,))
except Exception:
pass
raise RuntimeError(
f"Windows Firewall created rule '{name}', but verification failed for '{exe_path}': "
f"{str(detail).strip() or str(exc)}"
) from exc
def add_app_rules(self, proc_name, exe_path, direction, kind='Block'):
base = self.app_rule_base(proc_name, exe_path, kind)
names, commands, checks = [], [], []
for side in direction_set(direction):
name = f"{base}_{'In' if side == 'in' else 'Out'}"
create, verify = self._app_rule_commands(name, exe_path, side)
names.append(name)
commands.append(create)
checks.append(verify)
try:
self.run_ps("$ErrorActionPreference='Stop'\n" + '\n'.join(commands + checks))
return base
except Exception as error:
try:
self.delete_rule_names(names)
except Exception as cleanup_error:
raise RuntimeError(f'Application rule batch failed: {error_details(error)}; cleanup failed: {cleanup_error}') from cleanup_error
return self._add_app_rules_individually(proc_name, exe_path, direction, kind)
def _add_app_rules_individually(self, proc_name, exe_path, direction, kind='Block'):
base = self.app_rule_base(proc_name, exe_path, kind)
created_names = []
try:
for side in direction_set(direction):
name = f"{base}_{('In' if side == 'in' else 'Out')}"
self._add_app_firewall_rule(name, exe_path, side, 'block')
created_names.append(name)
return base
except Exception:
if created_names:
try:
self.delete_rule_names(created_names)
except Exception:
pass
raise
def _restore_app_rule_records(self, records):
created = []
try:
for record in records:
path = display_path(record.get('path', ''))
name = str(record.get('name', '') or '').strip()
if not name:
continue
if record.get('is_port'):
self._create_rule_batch([record])
created.append(name)
continue
if record.get('is_global'):
raise ValueError('Only current global filters can be restored.')
if not path:
raise ValueError(f'Missing program for rule {name}')
action = 'Allow' if str(record.get('action', '')).casefold() == 'allow' else 'Block'
suffixes = {'in': 'In', 'out': 'Out'}
for side in direction_set(record.get('direction', 'Both')):
rule_name = name if name.endswith(f"_{suffixes[side]}") else f"{name}_{suffixes[side]}"
self._add_app_firewall_rule(rule_name, path, side, action)
created.append(rule_name)
if record.get('enabled', True) is False:
self.run_ps('$r=Get-NetFirewallRule -DisplayName ' + self._ps_quote(rule_name)
+ " -ErrorAction Stop; $r | Set-NetFirewallRule -Enabled False -ErrorAction Stop; "
+ 'if (@(Get-NetFirewallRule -DisplayName ' + self._ps_quote(rule_name)
+ " -ErrorAction Stop | Where-Object { [string]$_.Enabled -ne 'False' }).Count) { throw 'Disabled rule restoration failed' }")
except Exception:
if created:
try:
self.delete_rule_names(created)
except Exception:
pass
raise
# Global IP and domain rules
def resolve_global_target(self, target, observed_addresses=()):
target = normalize_target(target)
if ',' in target:
return tuple(sorted({address for part in global_targets(target)
for address in self.resolve_global_target(part)}))
if not is_global_target(target):
raise ValueError(f'Not a global IP/Domain target: {target}')
if is_ip(target):
return (normalize_address(target),)
# Only validated connection addresses may serve as a DNS fallback. Never
# guess an IP from a PTR-style hostname or pass a hostname to the firewall.
addresses = {normalize_address(value) for value in observed_addresses}
try:
addresses.update(str(ipaddress.ip_address(result[4][0]))
for result in self._bounded_forward_lookup(target))
if not addresses:
raise GlobalLookupError(target, 'no addresses')
except TimeoutError:
raise
except socket.gaierror as exc:
if not addresses:
raise GlobalLookupError(target, resolver_code=exc.errno) from exc
except GlobalLookupError:
raise
except (OSError, ValueError, UnicodeError) as exc:
if not addresses:
raise ValueError(f"Could not resolve global target '{target}': {error_details(exc)}") from exc
return tuple(sorted(addresses))
def _bounded_forward_lookup(self, target):
cache = getattr(self, '_transaction_dns_cache', None)
if cache is not None and target in cache:
ok, value = cache[target]
if not ok:
kind, code, detail = value
raise (socket.gaierror if kind == 'lookup' else OSError)(code, detail)
return value
try:
result = self._forward_lookup_uncached(target)
except OSError as exc:
if cache is not None and not isinstance(exc, TimeoutError):
cache[target] = (False, ('lookup' if isinstance(exc, socket.gaierror) else 'oserror',
exc.errno, exc.strerror or str(exc)))
raise
if cache is not None:
cache[target] = (True, result)
return result
def _forward_lookup_uncached(self, target):
"""One outstanding resolver per app; a timed out call cannot accumulate threads.
getaddrinfo cannot be cancelled portably. A retained single slot rejects
new lookups while an expired OS lookup finishes, and discards its result.
"""
if not hasattr(self, '_forward_lookup_slot'):
self._forward_lookup_slot = threading.BoundedSemaphore(1)
if not self._forward_lookup_slot.acquire(blocking=False):
raise RuntimeError('A previous DNS lookup is still finishing. Retry shortly.')
done = threading.Event()
result = []
def lookup():
try:
result.append((True, socket.getaddrinfo(target, None, type=socket.SOCK_STREAM)))
except Exception as exc:
result.append((False, exc))
finally:
self._forward_lookup_slot.release()
done.set()
threading.Thread(target=lookup, daemon=True, name='PyFirewall-ForwardDNS').start()
deadline = time.monotonic() + getattr(self, 'global_dns_timeout', 10.0)
while not done.wait(0.05):
if self.closed or getattr(self, 'native_shutdown_requested', False):
raise RuntimeError('Rule update cancelled during DNS; restoring previous filters.')
if time.monotonic() >= deadline:
raise TimeoutError('DNS lookup deadline exceeded; late results are discarded.')
ok, value = result[0]
if not ok:
raise value
return value
def add_global_rule_sync(self, target, allow, direction='both'):
target = normalize_target(target)
with self.firewall_lock:
self._commit_rule_batch([(target, allow, direction, True)])
addresses = tuple(sorted({address for rule in self.global_ports.values() for item in rule['targets'] if item['target'] == target for address in item['addresses']}))
return target, addresses
# Firewall profile backup and restoration
def _read_firewall_profile_state(self):
command = "Get-NetFirewallProfile -ErrorAction Stop | Select-Object Name,@{n='Enabled';e={[string]$_.Enabled}},@{n='DefaultInboundAction';e={[string]$_.DefaultInboundAction}},@{n='DefaultOutboundAction';e={[string]$_.DefaultOutboundAction}} | ConvertTo-Json -Compress"
output = self.run_ps(command).stdout.strip() or '[]'
raw = json.loads(output)
if isinstance(raw, dict):
raw = [raw]
profiles = []
for item in raw if isinstance(raw, list) else []:
name = str(item.get('Name', '') or '')
if not name:
continue
profiles.append({
'name': name,
'enabled': self._profile_enabled(item.get('Enabled', False)),
'default_inbound_action': self._profile_action(item.get('DefaultInboundAction')),
'default_outbound_action': self._profile_action(item.get('DefaultOutboundAction')),
})
if not profiles:
raise ValueError('No Windows Firewall profiles were returned.')
return profiles
def _backup_firewall_profile_state(self):