-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyWall.py
More file actions
6823 lines (6465 loc) · 395 KB
/
Copy pathPyWall.py
File metadata and controls
6823 lines (6465 loc) · 395 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
#!/usr/bin/env python3
"""
PyWall v4.2.0 - Windows Firewall & Network Command Center
Combined hosts file management + Windows Firewall control + live connection
monitoring. Block domains via hosts file OR firewall rules. Full local system control.
"""
import multiprocessing
multiprocessing.freeze_support()
import sys, os, subprocess, json, sqlite3, re, shutil, time, threading, hashlib, csv, io, html, base64
import tempfile, webbrowser, socket, datetime, ipaddress, logging, smtplib, ssl
import argparse, signal, hmac, secrets, fnmatch
import http.server
from email.message import EmailMessage
from pathlib import Path
from collections import OrderedDict, defaultdict
from dataclasses import dataclass, field
from queue import Queue, Empty
from threading import Lock, Event as TEvent
import urllib.request, urllib.error, urllib.parse
def _branding_icon_path() -> Path:
candidates = []
if getattr(sys, "frozen", False):
exe_dir = Path(sys.executable).resolve().parent
candidates.append(exe_dir / "icon.png")
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
candidates.append(Path(meipass) / "icon.png")
current = Path(__file__).resolve()
candidates.extend([current.parent / "icon.png", current.parent.parent / "icon.png", current.parent.parent.parent / "icon.png"])
for candidate in candidates:
if candidate.exists():
return candidate
return Path("icon.png")
# ─── DPI Awareness ───────────────────────────────────────────────────────────
os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "1"
if hasattr(sys, 'getwindowsversion'):
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(2) # PROCESS_PER_MONITOR_DPI_AWARE
except: pass
# ─── Bootstrap ───────────────────────────────────────────────────────────────
NOWIN = getattr(subprocess, 'CREATE_NO_WINDOW', 0x08000000)
def _is_frozen():
return getattr(sys, "frozen", False) or hasattr(sys, "_MEIPASS")
def _missing_dependency_message(missing):
packages = ", ".join(missing)
return (
f"Missing required runtime dependencies: {packages}\n"
"Install them before launching PyWall:\n"
f" {sys.executable} -m pip install -r requirements.txt"
)
def _check_dependencies():
deps = [('PyQt5', 'PyQt5'), ('psutil', 'psutil'), ('maxminddb', 'maxminddb'), ('cryptography', 'cryptography')]
if sys.platform == 'win32':
deps.append(('pywin32', 'win32serviceutil'))
missing = []
for pkg, mod in deps:
try: __import__(mod)
except ImportError: missing.append(pkg)
if missing:
print(_missing_dependency_message(missing), file=sys.stderr)
sys.exit(2)
def _kill_remnants():
"""Kill leftover PyWall python/powershell processes from prior runs."""
if sys.platform != 'win32': return
my_pid = os.getpid()
my_script = os.path.abspath(__file__).lower()
try:
import psutil as _ps_mod
for proc in _ps_mod.process_iter(['pid', 'name', 'cmdline']):
try:
if proc.info['pid'] == my_pid: continue
name = (proc.info['name'] or '').lower()
cmdline = ' '.join(proc.info['cmdline'] or []).lower()
# Kill python processes running this script
if 'python' in name and my_script in cmdline:
proc.kill()
# Kill orphaned powershell spawned by PyWall.
elif 'powershell' in name and (('pywall' in cmdline or 'hostsguard' in cmdline) or 'get-dnsclientcache' in cmdline
or 'get-netfirewallrule' in cmdline or 'get-winevent' in cmdline):
proc.kill()
except: continue
except ImportError:
# psutil not yet installed — use tasklist/taskkill fallback
try:
r = subprocess.run(['wmic', 'process', 'where',
f'CommandLine like "%{os.path.basename(__file__)}%" and ProcessId != "{my_pid}"',
'get', 'ProcessId'], capture_output=True, text=True, timeout=10, creationflags=NOWIN)
for line in r.stdout.splitlines():
pid = line.strip()
if pid.isdigit() and int(pid) != my_pid:
subprocess.run(['taskkill', '/F', '/PID', pid], capture_output=True, timeout=5, creationflags=NOWIN)
except: pass
except: pass
def _bootstrap():
"""Elevate to admin + install missing deps. Must run BEFORE heavy imports."""
if sys.version_info < (3, 8):
print("Python 3.8+ required"); sys.exit(1)
_check_dependencies()
if sys.platform == 'win32':
import ctypes
if not ctypes.windll.shell32.IsUserAnAdmin():
try:
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
hwnd.setWindowIcon(branding_icon)
if hwnd: ctypes.windll.user32.ShowWindow(hwnd, 0)
except: pass
ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable,
" ".join([f'"{os.path.abspath(__file__)}"'] + [f'"{a}"' for a in sys.argv[1:]]), None, 1)
os._exit(0)
# We're admin now — kill remnants from prior crashed runs
_kill_remnants()
_bootstrap()
import psutil
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
log = logging.getLogger("PyWall"); logging.basicConfig(level=logging.WARNING)
# ─── Constants ───────────────────────────────────────────────────────────────
APP_NAME = "PyWall"
APP_VERSION = "4.2.0"
FW_PFX = "PW_" # Firewall rule prefix
LEGACY_FW_PFX = ("HG_",)
FW_RULE_PREFIXES = (FW_PFX,) + LEGACY_FW_PFX
HOSTS_PATH = r"C:\Windows\System32\drivers\etc\hosts" if sys.platform == 'win32' else "/etc/hosts"
BLOCK_IPS = {"0.0.0.0", "127.0.0.1", "::0", "::1"}
CONFIG_DIR = os.path.join(os.environ.get('APPDATA', os.path.expanduser('~')), APP_NAME)
LEGACY_CONFIG_DIR = os.path.join(os.environ.get('APPDATA', os.path.expanduser('~')), "HostsGuard")
if not os.path.exists(CONFIG_DIR) and os.path.isdir(LEGACY_CONFIG_DIR):
try: shutil.copytree(LEGACY_CONFIG_DIR, CONFIG_DIR, dirs_exist_ok=True)
except Exception as e: log.warning(f"Config migration skipped: {e}")
DB_PATH = os.path.join(CONFIG_DIR, "pywall.db")
LEGACY_DB_PATH = os.path.join(CONFIG_DIR, "hostsguard.db")
if not os.path.exists(DB_PATH) and os.path.exists(LEGACY_DB_PATH):
try: shutil.copy2(LEGACY_DB_PATH, DB_PATH)
except Exception as e: log.warning(f"DB migration skipped: {e}")
CONN_DB_PATH = os.path.join(CONFIG_DIR, "connections.db")
CONFIG_PATH = os.path.join(CONFIG_DIR, "config.json")
FAVICON_DIR = os.path.join(CONFIG_DIR, "favicons")
REPORT_DIR = os.path.join(CONFIG_DIR, "reports")
REPORT_EMAIL_STATE_PATH = os.path.join(CONFIG_DIR, "report_email_state.json")
GEOIP_UPDATE_STATE_PATH = os.path.join(CONFIG_DIR, "geoip_update_state.json")
IDS_RULES_PATH = os.path.join(CONFIG_DIR, "ids_rules.yaral")
FEED_CACHE_DIR = os.path.join(CONFIG_DIR, "feed_cache")
PLUGINS_DIR = os.path.join(CONFIG_DIR, "plugins")
TRANSLATION_DIR = os.path.join(CONFIG_DIR, "translations")
PLUGIN_LOG_PATH = os.path.join(CONFIG_DIR, "plugin_events.log")
FW_TAMPER_LOG_PATH = os.path.join(CONFIG_DIR, "firewall_tamper.log")
PLUGIN_MANIFEST_NAMES = ("pywall-plugin.json", "plugin.json")
PLUGIN_MARKETPLACE_URL = ""
PLUGIN_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{1,79}$")
PLUGIN_ALLOWED_HOOKS = {
"connection_observed",
"dns_domain_seen",
"threat_detected",
"notification",
"report_generated",
"feed_import",
"geoip_lookup",
"service_snapshot",
}
PLUGIN_ALLOWED_PERMISSION_KEYS = {"network", "files", "firewall", "notifications", "reports", "config"}
os.makedirs(CONFIG_DIR, exist_ok=True); os.makedirs(FAVICON_DIR, exist_ok=True); os.makedirs(FEED_CACHE_DIR, exist_ok=True); os.makedirs(PLUGINS_DIR, exist_ok=True); os.makedirs(TRANSLATION_DIR, exist_ok=True)
SERVICE_NAME = "PyWallService"
SERVICE_DISPLAY_NAME = "PyWall Background Service"
SERVICE_DESCRIPTION = "Headless PyWall connection monitor and threat auto-blocker."
SERVICE_STATE_DIR = os.path.join(os.environ.get("PROGRAMDATA", CONFIG_DIR), APP_NAME) if sys.platform == "win32" else CONFIG_DIR
try: os.makedirs(SERVICE_STATE_DIR, exist_ok=True)
except: SERVICE_STATE_DIR = CONFIG_DIR
SERVICE_LOG_PATH = os.path.join(SERVICE_STATE_DIR, "service.log")
IPC_PIPE_NAME = r"\\.\pipe\PyWallService"
IPC_TOKEN_PATH = os.path.join(SERVICE_STATE_DIR, "service.token")
SERVICE_STATE_PATH = os.path.join(SERVICE_STATE_DIR, "service_state.json")
QUOTA_STATE_PATH = os.path.join(CONFIG_DIR, "quota_state.json")
RULE_SCHEDULES_PATH = os.path.join(CONFIG_DIR, "rule_schedules.json")
GEOIP_HTTPS_ENDPOINT = "https://ipwho.is/{ip}"
CONFIG_SCHEMA_VERSION = 1
CONFIG_DEFAULTS = {
"schema_version": CONFIG_SCHEMA_VERSION,
"theme": "Charcoal",
"tray": True,
"toast": True,
"toast_sec": 10,
"start_monitoring": False,
"learning_mode_enabled": True,
"learning_mode_window_minutes": 10.0,
"history_days": 30,
"threat_auto_block": False,
"service_auto_block": True,
"service_poll_seconds": 2.0,
"bandwidth_quotas": {},
"tls_sni_enabled": False,
"tls_sni_log_path": "",
"tls_sni_read_existing": False,
"detect_doh": True,
"doh_action": "warn",
"ids_rules_enabled": True,
"ids_rules_path": IDS_RULES_PATH,
"event_correlation_enabled": True,
"sysmon_event_correlation_enabled": False,
"geoip_provider": "ipwhois",
"geoip_https_endpoint": GEOIP_HTTPS_ENDPOINT,
"geoip_mmdb_path": "",
"geoip_mmdb_update": {"enabled": False, "url": "", "sha256": "", "path": "", "interval_hours": 168},
"geoip_fence": {"mode": "disabled", "countries": [], "action": "block"},
"report_email": {"enabled": False, "interval_hours": 24, "smtp_host": "", "smtp_port": 587, "username": "", "password": "", "from": "", "to": [], "use_tls": True},
"external_notifiers": {"enabled": False, "minimum_severity": "medium", "pushover": {"enabled": False, "endpoint": "https://api.pushover.net/1/messages.json", "token": "", "user": ""}, "ntfy": {"enabled": False, "endpoint": "https://ntfy.sh", "topic": "", "token": ""}},
"rest_api": {"enabled": False, "host": "127.0.0.1", "port": 8765, "token": "", "tls_cert": "", "tls_key": ""},
"fleet_agents": [],
"vpn_awareness_enabled": True,
"hyperv_awareness_enabled": True,
"plugins_enabled": False,
"plugin_marketplace_url": PLUGIN_MARKETPLACE_URL,
"plugin_enabled_ids": [],
"plugin_disabled_ids": [],
"auto_block_inbound": True,
"detect_portscan": True,
"detect_bruteforce": True,
"vt_api_key": "",
"notif_severity_threshold": "low",
"notif_snooze_minutes": 5,
"notif_digest_enabled": False,
"notif_digest_interval_minutes": 15,
}
@dataclass
class ConfigLoadResult:
data:dict
mtime:float|None=None
recovered:bool=False
backup_path:str=""
warnings:list=field(default_factory=list)
def _coerce_config_value(key, value):
default = CONFIG_DEFAULTS[key]
if key == "schema_version":
try: value = int(value)
except: raise ValueError("must be an integer")
if value < 1: raise ValueError("must be >= 1")
return min(value, CONFIG_SCHEMA_VERSION)
if isinstance(default, bool):
if isinstance(value, bool): return value
if isinstance(value, str) and value.lower() in ("true","1","yes","on"): return True
if isinstance(value, str) and value.lower() in ("false","0","no","off"): return False
raise ValueError("must be true or false")
if isinstance(default, int) and not isinstance(default, bool):
try: value = int(value)
except: raise ValueError("must be an integer")
return max(0, value)
if isinstance(default, float):
try: value = float(value)
except: raise ValueError("must be a number")
return max(1.0, value)
if isinstance(default, dict):
if isinstance(value, dict): return value
raise ValueError("must be an object")
if isinstance(default, list):
if isinstance(value, list):
return [str(v).strip() for v in value if str(v).strip()]
raise ValueError("must be a list")
text = str(value if value is not None else "")
if key == "doh_action" and text.lower() not in ("warn","block","ignore"):
raise ValueError("must be warn, block, or ignore")
if key == "geoip_provider" and text.lower() not in ("ipwhois","maxmind","disabled"):
raise ValueError("must be ipwhois, maxmind, or disabled")
if key == "geoip_https_endpoint" and text and not text.lower().startswith("https://"):
raise ValueError("must start with https://")
if key == "plugin_marketplace_url" and text and not text.lower().startswith("https://"):
raise ValueError("must start with https://")
if key == "notif_severity_threshold" and text.lower() not in ("low","medium","high"):
raise ValueError("must be low, medium, or high")
return text.lower() if key in ("doh_action","geoip_provider","notif_severity_threshold") else text
def _validate_runtime_config(raw):
warnings=[]; out=dict(CONFIG_DEFAULTS)
if not isinstance(raw, dict):
raise ValueError("config root must be an object")
for key,value in raw.items():
if key not in CONFIG_DEFAULTS:
warnings.append(f"unknown config field ignored by runtime: {key}")
out[key]=value
continue
try:
out[key]=_coerce_config_value(key,value)
except ValueError as e:
warnings.append(f"invalid config field {key}: {e}; using default")
out[key]=CONFIG_DEFAULTS[key]
out["schema_version"]=CONFIG_SCHEMA_VERSION
return out,warnings
def _write_json_atomic(path, data):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f: json.dump(data, f, indent=2, sort_keys=True)
os.replace(tmp, path)
def _config_backup_path(path, reason="corrupt"):
stamp=datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
return f"{path}.{reason}.{stamp}.bak"
def load_runtime_config(path=CONFIG_PATH, recover=True):
if not os.path.exists(path):
data=dict(CONFIG_DEFAULTS)
if recover:
try: _write_json_atomic(path,data)
except: pass
try: mtime=os.path.getmtime(path)
except: mtime=None
return ConfigLoadResult(data=data,mtime=mtime,warnings=["config missing; defaults created" if recover else "config missing"])
try:
with open(path,"r",encoding="utf-8") as f: raw=json.load(f)
data,warnings=_validate_runtime_config(raw)
if data != raw and recover:
try: _write_json_atomic(path,data)
except Exception as e: warnings.append(f"config rewrite failed: {e}")
try: mtime=os.path.getmtime(path)
except: mtime=None
return ConfigLoadResult(data=data,mtime=mtime,warnings=warnings)
except Exception as e:
warnings=[f"config recovery: {e}"]
backup=""
if recover:
try:
backup=_config_backup_path(path)
shutil.copy2(path,backup)
_write_json_atomic(path,dict(CONFIG_DEFAULTS))
except Exception as be:
warnings.append(f"config backup/write failed: {be}")
try: mtime=os.path.getmtime(path)
except: mtime=None
return ConfigLoadResult(data=dict(CONFIG_DEFAULTS),mtime=mtime,recovered=bool(backup),backup_path=backup,warnings=warnings)
_active_translator = None
def _tr(text):
return QCoreApplication.translate("PyWall", str(text or ""))
def load_translation(app, locale_name=None):
global _active_translator
locale_name = locale_name or QLocale.system().name()
translator = QTranslator(app)
loaded = translator.load(f"pywall_{locale_name}", TRANSLATION_DIR)
if not loaded and "_" in locale_name:
loaded = translator.load(f"pywall_{locale_name.split('_',1)[0]}", TRANSLATION_DIR)
if loaded:
app.installTranslator(translator)
_active_translator = translator
return bool(loaded)
def _a11y(widget, name, desc="", tooltip=None):
try: widget.setAccessibleName(_tr(name))
except: pass
if desc:
try: widget.setAccessibleDescription(_tr(desc))
except: pass
if tooltip:
try: widget.setToolTip(_tr(tooltip))
except: pass
return widget
# ─── Notification Fatigue Controller ─────────────────────────────────────────
SEVERITY_LEVELS = {"low": 0, "medium": 1, "high": 2}
@dataclass
class NotifDigestEntry:
key:str
severity:str
title:str
message:str
ts:float
class NotificationController:
def __init__(self, config=None):
self._lock = Lock()
self._cooldowns = {}
self._snoozed = {}
self._digest = []
self._launch_time = time.time()
self._last_digest_time = time.time()
self.reload_config(config or {})
def reload_config(self, config):
self._threshold = SEVERITY_LEVELS.get(str(config.get("notif_severity_threshold", "low")).lower(), 0)
self._snooze_sec = max(60, int(config.get("notif_snooze_minutes", 5) or 5) * 60)
self._digest_enabled = bool(config.get("notif_digest_enabled", False))
self._digest_interval = max(60, int(config.get("notif_digest_interval_minutes", 15) or 15) * 60)
self._warmup_sec = 15
def should_notify(self, key, severity="low", title="", message=""):
level = SEVERITY_LEVELS.get(severity, 0)
now = time.time()
with self._lock:
if now - self._launch_time < self._warmup_sec:
return False
if key in self._snoozed and now < self._snoozed[key]:
return False
if level < self._threshold:
if self._digest_enabled:
self._digest.append(NotifDigestEntry(key=key, severity=severity, title=title, message=message, ts=now))
return False
if key in self._cooldowns and now - self._cooldowns[key] < self._snooze_sec:
if self._digest_enabled:
self._digest.append(NotifDigestEntry(key=key, severity=severity, title=title, message=message, ts=now))
return False
self._cooldowns[key] = now
return True
def snooze(self, key, minutes=None):
with self._lock:
self._snoozed[key] = time.time() + (minutes or self._snooze_sec // 60) * 60
def drain_digest(self):
now = time.time()
with self._lock:
if now - self._last_digest_time < self._digest_interval:
return []
self._last_digest_time = now
items = list(self._digest)
self._digest.clear()
return items
def pending_digest_count(self):
with self._lock:
return len(self._digest)
@dataclass
class PluginManifest:
plugin_id:str
name:str
version:str
manifest_path:str
enabled:bool=False
hooks:list=field(default_factory=list)
permissions:dict=field(default_factory=dict)
trust_state:str="unknown"
publisher:str=""
signature:str=""
executable:bool=False
disabled_reason:str=""
errors:list=field(default_factory=list)
def as_dict(self):
return {
"id": self.plugin_id,
"name": self.name,
"version": self.version,
"manifest_path": self.manifest_path,
"enabled": self.enabled,
"hooks": list(self.hooks),
"permissions": dict(self.permissions),
"trust_state": self.trust_state,
"publisher": self.publisher,
"executable": self.executable,
"disabled_reason": self.disabled_reason,
"errors": list(self.errors),
}
@dataclass
class PluginScanResult:
plugins:list=field(default_factory=list)
errors:list=field(default_factory=list)
def summary(self):
total=len(self.plugins)
invalid=sum(1 for p in self.plugins if p.errors)
return {
"total": total,
"valid": total - invalid,
"invalid": invalid,
"enabled": sum(1 for p in self.plugins if p.enabled),
"executable": sum(1 for p in self.plugins if p.executable),
"signed": sum(1 for p in self.plugins if p.trust_state == "signed"),
"unsigned": sum(1 for p in self.plugins if p.trust_state == "unsigned"),
"unknown": sum(1 for p in self.plugins if p.trust_state == "unknown"),
"errors": list(self.errors),
}
def _safe_plugin_id(value):
text=str(value or "").strip().lower()
return text if PLUGIN_ID_RE.match(text) else ""
def _plugin_log(msg, level="INFO"):
line=f"{datetime.datetime.now().isoformat(timespec='seconds')} [{level}] {msg}"
try:
with open(PLUGIN_LOG_PATH,"a",encoding="utf-8") as f: f.write(line + "\n")
except: pass
logger=getattr(log, level.lower(), None) or getattr(log, "info", None)
if logger: logger(msg)
class PluginRegistry:
def __init__(self, plugin_dir=PLUGINS_DIR, config=None):
self.plugin_dir=plugin_dir
self.config=config
def _config(self):
if self.config is not None:
return self.config
return load_runtime_config().data
def scan(self, log_errors=True):
try: os.makedirs(self.plugin_dir, exist_ok=True)
except Exception as e:
msg=f"Plugin directory unavailable: {e}"
if log_errors: _plugin_log(msg,"WARNING")
return PluginScanResult(errors=[msg])
cfg=self._config()
plugins=[]; errors=[]
for manifest_path in self._manifest_paths():
manifest=self._load_manifest(manifest_path,cfg)
plugins.append(manifest)
if manifest.errors:
msg=f"Plugin {manifest.plugin_id or manifest.manifest_path} invalid: {'; '.join(manifest.errors)}"
errors.append(msg)
if log_errors: _plugin_log(msg,"WARNING")
return PluginScanResult(plugins=plugins, errors=errors)
def can_execute(self, plugin_id, hook):
wanted=_safe_plugin_id(plugin_id)
if not wanted: return False
for plugin in self.scan(log_errors=False).plugins:
if plugin.plugin_id == wanted:
return bool(plugin.executable and hook in plugin.hooks)
return False
def _manifest_paths(self):
root=Path(self.plugin_dir)
if not root.exists(): return []
paths=[]
try:
for name in PLUGIN_MANIFEST_NAMES:
path=root / name
if path.is_file(): paths.append(path)
for child in sorted(root.iterdir(), key=lambda p: p.name.lower()):
if not child.is_dir(): continue
for name in PLUGIN_MANIFEST_NAMES:
path=child / name
if path.is_file():
paths.append(path)
break
except Exception as e:
_plugin_log(f"Plugin scan failed: {e}","WARNING")
return paths
def _load_manifest(self, path, cfg):
errors=[]
try:
with open(path,"r",encoding="utf-8") as f: raw=json.load(f)
if not isinstance(raw,dict):
raise ValueError("manifest root must be an object")
except Exception as e:
return PluginManifest("", path.parent.name, "0.0.0", str(path), errors=[f"manifest read failed: {e}"], disabled_reason="invalid manifest")
plugin_id=_safe_plugin_id(raw.get("id") or path.parent.name)
if not plugin_id: errors.append("id must match [A-Za-z0-9_.-] and be 2-80 chars")
name=str(raw.get("name") or plugin_id or path.parent.name).strip() or "Unnamed Plugin"
version=str(raw.get("version") or "0.0.0").strip() or "0.0.0"
enabled=bool(raw.get("enabled", False))
hooks=self._parse_hooks(raw.get("hooks"), errors)
permissions=self._parse_permissions(raw.get("permissions"), errors)
trust=raw.get("trust") if isinstance(raw.get("trust"),dict) else {}
publisher=str(raw.get("publisher") or trust.get("publisher") or "").strip()
signature=str(raw.get("signature") or trust.get("signature") or "").strip()
trust_state="signed" if signature else "unsigned" if publisher else "unknown"
enabled_ids={_safe_plugin_id(x) for x in cfg.get("plugin_enabled_ids",[]) or []}
disabled_ids={_safe_plugin_id(x) for x in cfg.get("plugin_disabled_ids",[]) or []}
global_enabled=bool(cfg.get("plugins_enabled",False))
if errors:
executable=False; disabled_reason="invalid manifest"
elif not global_enabled:
executable=False; disabled_reason="plugins disabled in config"
elif plugin_id in disabled_ids:
executable=False; disabled_reason="disabled in config"
elif not enabled:
executable=False; disabled_reason="manifest disabled"
elif plugin_id not in enabled_ids:
executable=False; disabled_reason="not allowlisted in config"
else:
executable=True; disabled_reason=""
return PluginManifest(plugin_id,name,version,str(path),enabled,hooks,permissions,trust_state,publisher,signature,executable,disabled_reason,errors)
def _parse_hooks(self, value, errors):
if not isinstance(value,list) or not value:
errors.append("hooks must declare at least one event hook")
return []
hooks=[]
for raw_hook in value:
hook=str(raw_hook or "").strip()
if hook not in PLUGIN_ALLOWED_HOOKS:
errors.append(f"unsupported hook: {hook or '<empty>'}")
elif hook not in hooks:
hooks.append(hook)
return hooks
def _parse_permissions(self, value, errors):
if not isinstance(value,dict):
errors.append("permissions must declare network and files entries")
return {}
permissions={}
if "network" not in value:
errors.append("permissions.network must be declared")
if "files" not in value:
errors.append("permissions.files must be declared")
for raw_key, raw_value in value.items():
key=str(raw_key or "").strip()
if key not in PLUGIN_ALLOWED_PERMISSION_KEYS:
errors.append(f"unsupported permission: {key or '<empty>'}")
continue
if key in ("network","files"):
if raw_value in (None, False):
permissions[key]=[]
elif isinstance(raw_value,list):
permissions[key]=[str(v).strip() for v in raw_value if str(v).strip()]
else:
errors.append(f"permissions.{key} must be a list")
else:
if isinstance(raw_value,bool):
permissions[key]=raw_value
else:
errors.append(f"permissions.{key} must be true or false")
permissions.setdefault("network",[])
permissions.setdefault("files",[])
return permissions
@dataclass
class PluginMarketplaceResult:
source_url:str=""; checked_at:str=""; plugins:list=field(default_factory=list)
updates:list=field(default_factory=list); errors:list=field(default_factory=list)
def summary(self):
return {
"source_url": self.source_url,
"checked_at": self.checked_at,
"available": len(self.plugins),
"updates": len(self.updates),
"errors": list(self.errors),
}
def _plugin_version_key(value):
parts=[int(part) for part in re.findall(r"\d+",str(value or ""))[:4]]
return tuple((parts + [0,0,0,0])[:4])
class PluginMarketplace:
"""Check a HTTPS plugin index without downloading or executing plugin code."""
def __init__(self, registry=None, url=PLUGIN_MARKETPLACE_URL, opener=None):
self.registry=registry or PluginRegistry()
self.url=str(url or "").strip()
self.opener=opener or urllib.request.urlopen
def _local_versions(self):
result={}
for plugin in self.registry.scan(log_errors=False).plugins:
if plugin.plugin_id: result[plugin.plugin_id]=plugin.version
return result
def _read_index(self, raw):
if isinstance(raw,bytes): raw=raw.decode("utf-8",errors="replace")
data=json.loads(raw)
entries=data.get("plugins",[]) if isinstance(data,dict) else data
if not isinstance(entries,list): raise ValueError("marketplace index plugins must be a list")
clean=[]; errors=[]
for entry in entries:
if not isinstance(entry,dict):
errors.append("marketplace entry must be an object"); continue
plugin_id=_safe_plugin_id(entry.get("id"))
version=str(entry.get("version") or "").strip()
url=str(entry.get("url") or entry.get("homepage") or "").strip()
if not plugin_id or not version:
errors.append("marketplace entry needs a valid id and version"); continue
if url and not url.lower().startswith("https://"):
errors.append(f"{plugin_id}: plugin pointer must use https://"); continue
checksum=str(entry.get("sha256") or "").strip().lower()
if checksum and not re.match(r"^[0-9a-f]{64}$",checksum):
errors.append(f"{plugin_id}: sha256 must be 64 hex characters"); continue
clean.append({
"id":plugin_id,
"name":str(entry.get("name") or plugin_id).strip(),
"version":version,
"url":url,
"sha256":checksum,
"description":str(entry.get("description") or "").strip(),
})
return clean,errors
def check(self, url=None):
target=str(url if url is not None else self.url).strip()
result=PluginMarketplaceResult(source_url=target,checked_at=datetime.datetime.now().isoformat(timespec="seconds"))
if not target:
result.errors.append("Marketplace URL is not configured")
return result
if not target.lower().startswith("https://"):
result.errors.append("Marketplace URL must use https://")
return result
try:
request=urllib.request.Request(target,headers={"User-Agent":f"{APP_NAME}/{APP_VERSION}"})
try:
with self.opener(request,timeout=15) as response:
raw=response.read(1024*1024+1)
except TypeError:
with self.opener(request,timeout=15) as response:
raw=response.read()
if len(raw)>1024*1024:
raise ValueError("marketplace index exceeds 1 MiB")
result.plugins,result.errors=self._read_index(raw)
except Exception as e:
result.errors.append(f"marketplace check failed: {e}")
return result
local=self._local_versions()
result.updates=[entry for entry in result.plugins if entry["id"] in local and _plugin_version_key(entry["version"])>_plugin_version_key(local[entry["id"]])]
return result
def _service_log(msg, level="INFO"):
line = f"{datetime.datetime.now().isoformat(timespec='seconds')} [{level}] {msg}"
try:
with open(SERVICE_LOG_PATH, "a", encoding="utf-8") as f: f.write(line + "\n")
except: pass
getattr(log, level.lower(), log.info)(msg)
try:
import win32serviceutil, win32service, servicemanager, win32pipe, win32file, pywintypes
import win32security, ntsecuritycon
except ImportError:
win32serviceutil = win32service = servicemanager = win32pipe = win32file = pywintypes = None
win32security = ntsecuritycon = None
if win32serviceutil is not None:
class PyWallWindowsService(win32serviceutil.ServiceFramework):
_svc_name_ = SERVICE_NAME
_svc_display_name_ = SERVICE_DISPLAY_NAME
_svc_description_ = SERVICE_DESCRIPTION
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self._stop_event = threading.Event()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self._stop_event.set()
def SvcDoRun(self):
servicemanager.LogInfoMsg(f"{SERVICE_DISPLAY_NAME} starting")
try:
run_headless_service(stop_event=self._stop_event, auto_block=True)
except Exception as e:
_service_log(f"Service crashed: {e}", "ERROR")
servicemanager.LogErrorMsg(f"{SERVICE_DISPLAY_NAME} crashed: {e}")
raise
finally:
servicemanager.LogInfoMsg(f"{SERVICE_DISPLAY_NAME} stopped")
else:
PyWallWindowsService = None
IGNORED_DOMAINS = {'localhost','localhost.localdomain','local','broadcasthost','ip6-localhost','ip6-loopback','wpad','isatap'}
DOMAIN_RE = re.compile(r'^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$')
IPV4_RE = re.compile(r'^(25[0-5]|2[0-4]\d|[01]?\d\d?\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
WILDCARD_RE = re.compile(r'^\*\.?(.*)')
class _PrivateIPPattern:
"""Regex-compatible matcher that treats every non-global IP as local/reserved."""
def match(self, value):
text=str(value or "").strip()
try: return bool(text) and not ipaddress.ip_address(text).is_global
except ValueError: return bool(re.match(r'^(0\.0\.0\.0|127\.|169\.254\.|::1$|::$|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|fe80:|fc|fd)',text,re.IGNORECASE))
PRIV_RE = _PrivateIPPattern()
PORTS = {20:"FTP-D",21:"FTP",22:"SSH",25:"SMTP",53:"DNS",80:"HTTP",110:"POP3",123:"NTP",
135:"RPC",143:"IMAP",389:"LDAP",443:"HTTPS",445:"SMB",993:"IMAPS",995:"POP3S",
1433:"MSSQL",3306:"MySQL",3389:"RDP",5353:"mDNS",5432:"Postgres",5900:"VNC",8080:"Alt-HTTP"}
WINDOWS_HEADER = ["# Copyright (c) 1993-2009 Microsoft Corp.","#","# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.","#",
"# This file contains the mappings of IP addresses to host names.","#","#\t127.0.0.1 localhost","#\t::1 localhost",""]
MULTI_TLDS = {'co.uk','co.jp','co.kr','co.nz','co.za','co.in','com.au','com.br','com.cn','com.mx','com.tw','com.hk','com.sg',
'com.ar','com.tr','net.au','org.au','org.uk','ac.uk','gov.uk','ne.jp','or.jp','co.il','co.th','co.id','com.my','com.ph',
'com.vn','com.pk','com.ng','com.eg','com.ua','com.co','com.pe','com.ec','co.ke'}
RESEARCH_SITES = [("VirusTotal","https://www.virustotal.com/gui/domain/{domain}"),("who.is","https://who.is/whois/{domain}"),
("URLScan.io","https://urlscan.io/search/#{domain}"),("Shodan","https://www.shodan.io/search?query={domain}"),
("SecurityTrails","https://securitytrails.com/domain/{domain}"),("MXToolbox","https://mxtoolbox.com/SuperTool.aspx?action=dns%3a{domain}&run=toolpage"),
("AbuseIPDB","https://www.abuseipdb.com/check/{domain}"),("ThreatCrowd","https://www.threatcrowd.org/domain.php?domain={domain}"),
("DNSDumpster","https://dnsdumpster.com/?q={domain}")]
_CATEGORIES = {
"Streaming": {"netflix","hulu","disney","twitch","youtube","spotify","deezer","tidal","plex","crunchyroll","roku","primevideo"},
"Social Media": {"facebook","instagram","twitter","x.com","tiktok","snapchat","reddit","linkedin","pinterest","threads"},
"Gaming": {"steam","valve","epicgames","riotgames","blizzard","battle.net","xbox","playstation","ea.com","ubisoft"},
"Cloud Storage": {"dropbox","onedrive","gdrive","icloud","box.com","mega.nz","googledrive","sharepoint"},
"Messaging": {"discord","slack","telegram","whatsapp","signal","teams","zoom","webex","skype"},
"Development": {"github","gitlab","bitbucket","stackoverflow","npmjs","pypi","docker","aws","azure","gcp"},
"Security": {"virustotal","malwarebytes","norton","kaspersky","avast","mcafee","crowdstrike"},
"Microsoft": {"microsoft.com","windows.net","msedge","bing.com","live.com","outlook","office"},
"Google": {"google","googleapis","gstatic","youtube","doubleclick","googlevideo","gvt1","gvt2"},
"CDN": {"akamai","cloudflare","fastly","cloudfront","edgecast","jsdelivr","unpkg"},
}
# ─── Blocklist Sources ───────────────────────────────────────────────────────
BLOCKLIST_SOURCES = {
"Major / Unified": [
("HaGezi Ultimate","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/ultimate.txt"),
("HaGezi TIF","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/tif.txt"),
("StevenBlack Unified","https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"),
("OISD Full","https://hosts.oisd.nl/"),("OISD DBL","https://dbl.oisd.nl/"),
("MVPS Hosts","https://winhelp2002.mvps.org/hosts.txt"),
("SomeoneWhoCares","https://someonewhocares.org/hosts/zero/hosts"),
("HOSTShield Combined","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/SysAdminDoc/HOSTShield/releases/download/v.1/CombinedAll.txt"),
("The Great Wall","https://raw.githubusercontent.com/Sekhan/TheGreatWall/master/TheGreatWall.txt"),],
"Ads / Tracking": [
("Disconnect Tracking","https://s3.amazonaws.com/lists.disconnect.me/simple_tracking.txt"),
("Disconnect Ads","https://s3.amazonaws.com/lists.disconnect.me/simple_ad.txt"),
("DevDan Ads Extended","https://www.github.developerdan.com/hosts/lists/ads-and-tracking-extended.txt"),
("EasyList Hosts","https://v.firebog.net/hosts/Easylist.txt"),("EasyPrivacy Hosts","https://v.firebog.net/hosts/Easyprivacy.txt"),
("Prigent Ads","https://v.firebog.net/hosts/Prigent-Ads.txt"),
("Yoyo Ad Servers","https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&mimetype=plaintext"),
("Anudeep Ad Servers","https://raw.githubusercontent.com/anudeepND/blacklist/master/adservers.txt"),
("AdAway","https://adaway.org/hosts.txt"),("AdGuard DNS","https://v.firebog.net/hosts/AdguardDNS.txt"),
("NoCoin","https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt"),
("HOSTShield Ads","https://raw.githubusercontent.com/SysAdminDoc/HOSTShield/refs/heads/main/AdsTrackingAnalytics.txt"),
("Adobe Hosts","https://raw.githubusercontent.com/SysAdminDoc/HOSTShield/refs/heads/main/AdobeHosts.txt"),],
"Telemetry / Privacy": [
("Windows Spy Blocker","https://raw.githubusercontent.com/crazy-max/WindowsSpyBlocker/master/data/hosts/spy.txt"),
("Frogeye 1st Party","https://hostfiles.frogeye.fr/firstparty-trackers-hosts.txt"),
("Frogeye Multi Party","https://hostfiles.frogeye.fr/multiparty-trackers-hosts.txt"),
("NoTrack Tracking","https://gitlab.com/quidsup/notrack-blocklists/raw/master/notrack-blocklist.txt"),
("Perflyst Android","https://raw.githubusercontent.com/Perflyst/PiHoleBlocklist/master/android-tracking.txt"),
("Perflyst SmartTV","https://raw.githubusercontent.com/Perflyst/PiHoleBlocklist/master/SmartTV.txt"),],
"Malware / Phishing": [
("NoTrack Malware","https://gitlab.com/quidsup/notrack-blocklists/raw/master/notrack-malware.txt"),
("Spam404","https://raw.githubusercontent.com/Spam404/lists/master/main-blacklist.txt"),
("DandelionSprout","https://raw.githubusercontent.com/DandelionSprout/adfilt/master/Alternate%20versions%20Anti-Malware%20List/AntiMalwareHosts.txt"),
("Prigent Malware","https://v.firebog.net/hosts/Prigent-Malware.txt"),("Prigent Crypto","https://v.firebog.net/hosts/Prigent-Crypto.txt"),
("RPiList Malware","https://v.firebog.net/hosts/RPiList-Malware.txt"),("RPiList Phishing","https://v.firebog.net/hosts/RPiList-Phishing.txt"),
("Phishing Army","https://phishing.army/download/phishing_army_blocklist.txt"),("URLHaus","https://urlhaus.abuse.ch/downloads/hostfile/"),
("Stamparm Maltrail","https://raw.githubusercontent.com/stamparm/aux/master/maltrail-malware-domains.txt"),
("Disconnect Malware","https://s3.amazonaws.com/lists.disconnect.me/simple_malware.txt"),
("Badd Boyz","https://raw.githubusercontent.com/mitchellkrogza/Badd-Boyz-Hosts/master/hosts"),],
"Vendor / Platform": [
("Amazon Native","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/native.amazon.txt"),
("Apple Native","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/native.apple.txt"),
("Windows/Office","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/native.winoffice.txt"),
("Samsung Native","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/native.samsung.txt"),
("TikTok Extended","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/native.tiktok.extended.txt"),
("LG WebOS","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/native.lgwebos.txt"),
("Roku Native","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/native.roku.txt"),
("Xiaomi Native","https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/hosts/native.xiaomi.txt"),
("HOSTShield Apple","https://raw.githubusercontent.com/SysAdminDoc/HOSTShield/refs/heads/main/Apple.txt"),
("HOSTShield MS","https://raw.githubusercontent.com/SysAdminDoc/HOSTShield/refs/heads/main/Microsoft.txt"),
("HOSTShield TikTok","https://raw.githubusercontent.com/SysAdminDoc/HOSTShield/refs/heads/main/Tiktok.txt"),],
}
# ─── Theme (Catppuccin Mocha + Pro refinements) ─────────────────────────────
C = {"bg":"#0e0e16","base":"#1a1a2e","mantle":"#141422","crust":"#0e0e16","surface0":"#282842",
"surface1":"#3a3a5c","surface2":"#4a4a6a","text":"#e2e4f0","subtext":"#a0a4c0","overlay":"#6a6e8e",
"blue":"#7aa2f7","green":"#9ece6a","red":"#f7768e","peach":"#ff9e64","yellow":"#e0af68",
"mauve":"#bb9af7","teal":"#73daca","sky":"#7dcfff","lavender":"#b4befe","rosewater":"#f5e0dc",
"accent":"#7aa2f7","card_bg":"rgba(26,26,46,0.85)","card_border":"rgba(58,58,92,0.5)",
"glow":"rgba(122,162,247,0.08)","sel_bg":"rgba(122,162,247,0.15)"}
def _dp(px):
"""Scale pixel value for DPI. Called after QApplication exists."""
try:
s = QApplication.primaryScreen()
if s: return max(1, int(px * s.logicalDotsPerInch() / 96.0))
except: pass
return px
DARK_STYLE = f"""
* {{ font-family:'Segoe UI Variable','Segoe UI','Inter','SF Pro Display',sans-serif; }}
QMainWindow {{ background:{C['bg']}; }}
QWidget {{ background:transparent; color:{C['text']}; }}
/* ── Menu ── */
QMenuBar {{ background:{C['crust']}; color:{C['subtext']}; border-bottom:1px solid {C['surface0']}; padding:3px 0; }}
QMenuBar::item {{ padding:7px 14px; border-radius:5px; }} QMenuBar::item:selected {{ background:{C['surface0']}; color:{C['text']}; }}
QMenu {{ background:{C['mantle']}; border:1px solid {C['surface1']}; border-radius:10px; padding:6px; }}
QMenu::item {{ padding:8px 28px; border-radius:5px; color:{C['subtext']}; }} QMenu::item:selected {{ background:{C['surface0']}; color:{C['text']}; }}
QMenu::separator {{ height:1px; background:{C['surface0']}; margin:5px 10px; }}
/* ── Buttons ── */
QPushButton {{ background:{C['surface0']}; color:{C['subtext']}; border:1px solid {C['surface1']}; padding:7px 18px;
border-radius:8px; font-weight:600; font-size:12px; }}
QPushButton:hover {{ background:{C['surface1']}; color:{C['text']}; border-color:{C['surface2']}; }}
QPushButton:pressed {{ background:{C['surface0']}; }}
QPushButton:disabled {{ background:{C['surface0']}; color:{C['overlay']}; border-color:{C['surface0']}; }}
QPushButton[class="primary"] {{ background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #5b7ee5,stop:1 {C['blue']}); color:#fff; border:none; font-weight:700; }}
QPushButton[class="primary"]:hover {{ background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #6b8ef5,stop:1 #8ab4ff); }}
QPushButton[class="danger"] {{ background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #d5496a,stop:1 {C['red']}); color:#fff; border:none; font-weight:700; }}
QPushButton[class="danger"]:hover {{ background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #e5697a,stop:1 #ff8ea5); }}
QPushButton[class="success"] {{ background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #7ab85a,stop:1 {C['green']}); color:#111; border:none; font-weight:700; }}
QPushButton[class="success"]:hover {{ background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #8ac86a,stop:1 #b0e090); }}
QPushButton[class="warning"] {{ background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #d08040,stop:1 {C['peach']}); color:#111; border:none; font-weight:700; }}
QPushButton[class="dim"] {{ background:{C['surface0']}; color:{C['overlay']}; border:1px solid {C['surface1']}; font-weight:600; }}
QPushButton[class="dim"]:hover {{ color:{C['text']}; background:{C['surface1']}; }}
/* ── Inputs ── */
QLineEdit,QTextEdit,QPlainTextEdit {{ background:{C['mantle']}; color:{C['text']}; border:1px solid {C['surface0']}; border-radius:8px; padding:8px 12px;
selection-background-color:{C['blue']}; selection-color:#111; }}
QLineEdit:focus,QTextEdit:focus,QPlainTextEdit:focus {{ border-color:{C['blue']}; background:#1c1c30; }}
QComboBox {{ background:{C['mantle']}; color:{C['text']}; border:1px solid {C['surface0']}; border-radius:8px; padding:7px 12px; min-width:90px; }}
QComboBox:focus {{ border-color:{C['blue']}; }}
QComboBox::drop-down {{ border:none; width:28px; }} QComboBox::down-arrow {{ image:none; border-left:5px solid transparent; border-right:5px solid transparent; border-top:6px solid {C['subtext']}; margin-right:8px; }}
QComboBox QAbstractItemView {{ background:{C['mantle']}; color:{C['text']}; border:1px solid {C['surface1']}; selection-background-color:{C['blue']}; selection-color:#111; outline:none; border-radius:6px; padding:4px; }}
/* ── Tabs ── */
QTabWidget::pane {{ border:none; background:{C['base']}; }}
QTabBar {{ background:{C['crust']}; qproperty-drawBase:0; }}
QTabBar::tab {{ background:transparent; color:{C['overlay']}; padding:11px 20px; border:none; border-bottom:2px solid transparent; font-weight:700; font-size:11px; letter-spacing:0.3px; }}
QTabBar::tab:selected {{ color:{C['blue']}; border-bottom-color:{C['blue']}; background:rgba(122,162,247,0.06); }}
QTabBar::tab:hover:!selected {{ color:{C['text']}; background:rgba(122,162,247,0.04); }}
QTabBar::tab:first {{ margin-left:8px; }}
/* ── Tables ── */
QTableWidget,QTableView {{ background:{C['mantle']}; alternate-background-color:rgba(20,20,34,0.5); color:{C['text']}; border:1px solid {C['surface0']}; border-radius:10px;
gridline-color:rgba(58,58,92,0.3); selection-background-color:{C['sel_bg']}; selection-color:{C['text']}; outline:none; }}
QTableWidget::item,QTableView::item {{ padding:5px 10px; border:none; }} QTableWidget::item:selected,QTableView::item:selected {{ background:{C['sel_bg']}; }}
QHeaderView {{ background:transparent; }}
QHeaderView::section {{ background:{C['crust']}; color:{C['overlay']}; border:none; border-bottom:1px solid {C['surface0']}; border-right:1px solid rgba(58,58,92,0.3);
padding:9px 12px; font-weight:700; font-size:10px; text-transform:uppercase; letter-spacing:0.8px; }}
QHeaderView::section:first {{ border-top-left-radius:10px; }} QHeaderView::section:last {{ border-top-right-radius:10px; border-right:none; }}
/* ── Scrollbars ── */
QScrollBar:vertical {{ background:transparent; width:7px; margin:4px 0; }} QScrollBar::handle:vertical {{ background:{C['surface1']}; border-radius:3px; min-height:40px; }}
QScrollBar::handle:vertical:hover {{ background:{C['surface2']}; }} QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical {{ height:0; }}
QScrollBar:horizontal {{ background:transparent; height:7px; margin:0 4px; }} QScrollBar::handle:horizontal {{ background:{C['surface1']}; border-radius:3px; }}
QScrollBar::add-line:horizontal,QScrollBar::sub-line:horizontal {{ width:0; }}
/* ── Groups, Progress, Checks ── */
QGroupBox {{ border:1px solid {C['surface0']}; border-radius:12px; margin-top:1.5em; padding:18px 14px 14px; font-weight:700; background:{C['mantle']}; }}
QGroupBox::title {{ subcontrol-origin:margin; left:16px; padding:0 10px; color:{C['blue']}; font-size:11px; letter-spacing:0.5px; }}
QProgressBar {{ background:{C['surface0']}; border:none; border-radius:6px; text-align:center; color:#fff; font-weight:700; min-height:12px; }}
QProgressBar::chunk {{ background:qlineargradient(x1:0,y1:0,x2:1,y2:0,stop:0 #5b7ee5,stop:1 {C['teal']}); border-radius:6px; }}
QCheckBox {{ color:{C['text']}; spacing:8px; }} QCheckBox::indicator {{ width:18px; height:18px; border:2px solid {C['surface1']}; border-radius:5px; background:{C['mantle']}; }}
QCheckBox::indicator:hover {{ border-color:{C['overlay']}; }} QCheckBox::indicator:checked {{ background:{C['blue']}; border-color:{C['blue']}; }}
/* ── Misc ── */
QToolTip {{ background:{C['surface0']}; color:{C['text']}; border:1px solid {C['surface1']}; padding:7px 10px; border-radius:8px; font-size:11px; }}
QStatusBar {{ background:{C['crust']}; color:{C['overlay']}; border-top:1px solid {C['surface0']}; }}
QSplitter::handle {{ background:{C['surface0']}; width:2px; border-radius:1px; }}
QLabel {{ color:{C['text']}; background:transparent; }}
QScrollArea {{ background:transparent; border:none; }}
"""
# ─── Data Structures ────────────────────────────────────────────────────────
@dataclass
class CI:
key:str=""; ts:str=""; src:str=""; dir:str=""; proto:str=""
la:str=""; lp:str=""; ra:str=""; rp:str=""
host:str="-"; proc:str="?"; pid:int=0; svc:str="-"
parent:str="-"; package:str="-"; signer:str="-"
state:str=""; path:str=""; org:str="-"; cmd:str=""
stat:str="-"; country:str="-"; cc:str=""
category:str=""; bytes_sent:int=0; bytes_recv:int=0
event_source:str=""; event_id:int=0; event_record_id:int=0; rule_name:str=""; filter_id:str=""
def batch_connection_targets(conns, unknown_only=True):
"""Return deduplicated public remote endpoints suitable for batch firewall actions."""
targets={}
for ci in (conns or []):
if unknown_only and str(ci.stat or "-") not in ("-", ""):
continue
ip=str(ci.ra or "").strip()
if not ip or ip in ("*", "-", "0.0.0.0", "::", "::0") or PRIV_RE.match(ip):
continue
direction="Inbound" if str(ci.dir or "").lower() in ("in", "inbound", "listen") else "Outbound"
key=(ip,direction)
entry=targets.setdefault(key,{"ip":ip,"direction":direction,"processes":set(),"hosts":set()})
if ci.proc and ci.proc not in ("?","-"): entry["processes"].add(ci.proc)
if ci.host and ci.host not in ("-","..."): entry["hosts"].add(ci.host.lower())
return [
dict(entry, processes=sorted(entry["processes"]), hosts=sorted(entry["hosts"]))
for _,entry in sorted(targets.items())
]
@dataclass
class LearningReviewGroup:
key:str=""; proc:str=""; path:str=""; signer:str="-"; parent:str="-"
package:str="-"; svc:str="-"; first_seen:str=""; last_seen:str=""
count:int=0; endpoints:list=field(default_factory=list); hosts:list=field(default_factory=list); ips:list=field(default_factory=list)
def record(self, ci):
now=datetime.datetime.now().isoformat(timespec="seconds")
if not self.first_seen: self.first_seen=now
self.last_seen=now; self.count+=1
endpoint=f"{ci.ra}:{ci.rp}" if ci.rp else str(ci.ra or "")
if endpoint and endpoint not in self.endpoints: self.endpoints.append(endpoint)
if ci.ra and ci.ra not in self.ips: self.ips.append(ci.ra)
if ci.host and ci.host not in ("-","...") and ci.host not in self.hosts: self.hosts.append(ci.host)