integrity-killswitch 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1442 @@
1
+ """Hardened OS-level Absolute Killswitch: network cutoff, process freeze, and ACL hardening.
2
+
3
+ Zero external dependencies (Python 3.10+ stdlib only).
4
+
5
+ All mutating functions accept `--dry-run` plus injectable `runner` / `resolver` /
6
+ `signaler` / `process_table` / `platform_name` hooks so every backend (Linux
7
+ nftables/iptables, Windows netsh/icacls, macOS pf/chown) is hermetically tested
8
+ without touching live host firewall rules, ACLs, or processes.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ctypes
14
+ import ipaddress
15
+ import os
16
+ import re
17
+ import shlex
18
+ import shutil
19
+ import signal
20
+ import socket
21
+ import subprocess
22
+ import sys
23
+ from collections.abc import Callable, Iterable, Sequence
24
+ from dataclasses import asdict, dataclass, field
25
+ from pathlib import Path, PurePosixPath, PureWindowsPath
26
+ from typing import Any
27
+
28
+ from . import ancestry
29
+
30
+ if os.name == "nt":
31
+ import ctypes.wintypes
32
+
33
+ NFT_TABLE_NAME = "agent_killswitch_net"
34
+ IPTABLES_CHAIN_NAME = "AGENT_KILLSWITCH_OUT"
35
+ WINDOWS_RULE_PREFIX = "AgentKillswitch_Block_"
36
+ MACOS_PF_ANCHOR = "com.agent-killswitch/cutoff"
37
+
38
+ DEFAULT_LLM_HOSTS: tuple[str, ...] = (
39
+ "api.anthropic.com",
40
+ "api.openai.com",
41
+ "generativelanguage.googleapis.com",
42
+ "cloudcode-pa.googleapis.com",
43
+ "api2.cursor.sh",
44
+ "api.githubcopilot.com",
45
+ "openrouter.ai",
46
+ "api.x.ai",
47
+ "api.mistral.ai",
48
+ "api.deepseek.com",
49
+ )
50
+
51
+ ALWAYS_ALLOW_HOSTS: tuple[str, ...] = (
52
+ "integrity.subnet.zp.ua",
53
+ "localhost",
54
+ )
55
+
56
+ ALWAYS_ALLOW_PORTS: dict[str, tuple[int, ...]] = {
57
+ "ssh_tcp": (22,),
58
+ "dns_udp_tcp": (53,),
59
+ }
60
+
61
+ BLOCKED_LLM_PORTS: tuple[int, ...] = (80, 443)
62
+
63
+ _HOSTNAME_RE = re.compile(
64
+ r"^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$",
65
+ re.IGNORECASE,
66
+ )
67
+ _WINDOWS_RULE_LINE_RE = re.compile(r"^\s*Rule Name:\s*(AgentKillswitch_Block_\S+)\s*$", re.IGNORECASE)
68
+ _VENDOR_NAME_RE = re.compile(r"[a-z0-9][a-z0-9_-]{0,31}")
69
+
70
+ _PROTECTED_PROCESS_NAMES: frozenset[str] = frozenset(
71
+ ancestry.POSIX_SHELLS
72
+ | ancestry.LINUX_TERMINALS
73
+ | ancestry.MACOS_TERMINALS
74
+ | ancestry.LINUX_ROOTS
75
+ | ancestry.MACOS_ROOTS
76
+ | ancestry.POSIX_SSH_DAEMONS
77
+ | ancestry.INTERACTIVE_SHELLS
78
+ | ancestry.UI_ANCHORS
79
+ | ancestry.MSYS_SHELLS
80
+ | ancestry.SYSTEM_ROOTS
81
+ | set(ancestry.SERVICE_ROOTS)
82
+ | ancestry.BROWSER_NAMES
83
+ | {"sudo", "su", "conhost.exe", "openconsole.exe", "git-bash.exe", "ssh", "ssh.exe", "tmux", "screen"}
84
+ )
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class CommandResult:
89
+ """Minimal result shape returned by command runners."""
90
+
91
+ returncode: int
92
+ stdout: str = ""
93
+ stderr: str = ""
94
+
95
+
96
+ CommandRunner = Callable[[Sequence[str], str | None], CommandResult]
97
+ HostResolver = Callable[[str], list[str]]
98
+ SignalSender = Callable[[int, int], None]
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class ProcessRecord:
103
+ """Normalized running process entry used by freeze/thaw."""
104
+
105
+ pid: int
106
+ ppid: int
107
+ name: str
108
+ cmdline: str = ""
109
+ vendor: str = ""
110
+
111
+ def to_dict(self) -> dict[str, Any]:
112
+ return asdict(self)
113
+
114
+
115
+ @dataclass
116
+ class NetworkPlan:
117
+ """Structured plan/result for `net-cut`, `net-restore`, and `net-status`."""
118
+
119
+ action: str
120
+ platform: str
121
+ backend: str
122
+ dry_run: bool
123
+ ok: bool = True
124
+ active: bool | None = None
125
+ blocked_hosts: list[str] = field(default_factory=list)
126
+ allowed_hosts: list[str] = field(default_factory=list)
127
+ blocked_ipv4: list[str] = field(default_factory=list)
128
+ blocked_ipv6: list[str] = field(default_factory=list)
129
+ allowed_ipv4: list[str] = field(default_factory=list)
130
+ allowed_ipv6: list[str] = field(default_factory=list)
131
+ unresolved_hosts: list[str] = field(default_factory=list)
132
+ blocked_binaries: list[str] = field(default_factory=list)
133
+ ruleset: str = ""
134
+ commands: list[list[str]] = field(default_factory=list)
135
+ rollback_commands: list[list[str]] = field(default_factory=list)
136
+ active_rules: list[str] = field(default_factory=list)
137
+ warnings: list[str] = field(default_factory=list)
138
+ error: str | None = None
139
+
140
+ def to_dict(self) -> dict[str, Any]:
141
+ return asdict(self)
142
+
143
+
144
+ def detect_platform(override: str | None = None) -> str:
145
+ """Returns canonical platform name: `linux`, `windows`, or `macos`."""
146
+ if override:
147
+ key = override.strip().lower()
148
+ if key in ("linux", "windows", "macos"):
149
+ return key
150
+ if key in ("nt", "win32"):
151
+ return "windows"
152
+ if key == "darwin":
153
+ return "macos"
154
+ raise ValueError(f"Unsupported platform {override!r}")
155
+ if os.name == "nt":
156
+ return "windows"
157
+ if sys.platform == "darwin":
158
+ return "macos"
159
+ return "linux"
160
+
161
+
162
+ def is_elevated(platform_name: str | None = None) -> bool:
163
+ """Returns True when the current process holds root/Administrator privileges."""
164
+ plat = detect_platform(platform_name)
165
+ if plat == "windows":
166
+ if os.name != "nt":
167
+ return False
168
+ try:
169
+ return bool(ctypes.windll.shell32.IsUserAnAdmin())
170
+ except (OSError, AttributeError):
171
+ return False
172
+ geteuid = getattr(os, "geteuid", None)
173
+ return bool(geteuid is not None and geteuid() == 0)
174
+
175
+
176
+ def default_runner(cmd: Sequence[str], stdin_text: str | None = None) -> CommandResult:
177
+ """Executes an OS command safely without shell interpolation."""
178
+ try:
179
+ proc = subprocess.run(
180
+ list(cmd),
181
+ input=stdin_text,
182
+ capture_output=True,
183
+ text=True,
184
+ timeout=20,
185
+ check=False,
186
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0,
187
+ )
188
+ return CommandResult(returncode=proc.returncode, stdout=proc.stdout, stderr=proc.stderr)
189
+ except OSError as exc:
190
+ return CommandResult(returncode=127, stdout="", stderr=str(exc))
191
+
192
+
193
+ def validate_endpoint(entry: str) -> str:
194
+ """Validates a hostname or IP literal to prevent firewall syntax injection."""
195
+ clean = entry.strip().rstrip(".").lower()
196
+ if not clean:
197
+ raise ValueError("Empty endpoint entry")
198
+ try:
199
+ return str(ipaddress.ip_address(clean))
200
+ except ValueError:
201
+ pass
202
+ if not _HOSTNAME_RE.fullmatch(clean):
203
+ raise ValueError(f"Invalid hostname or IP address: {entry!r}")
204
+ return clean
205
+
206
+
207
+ def load_endpoints_file(path: str | Path) -> list[str]:
208
+ """Reads additional LLM hostnames/IPs from a newline-delimited file."""
209
+ target = Path(path)
210
+ endpoints: list[str] = []
211
+ for raw_line in target.read_text(encoding="utf-8-sig").splitlines():
212
+ line = raw_line.split("#", 1)[0].strip()
213
+ if not line:
214
+ continue
215
+ endpoints.append(validate_endpoint(line))
216
+ return endpoints
217
+
218
+
219
+ def default_resolver(host: str) -> list[str]:
220
+ """Resolves a hostname (or literal IP) to sorted unique IPv4/IPv6 strings."""
221
+ try:
222
+ addr = ipaddress.ip_address(host)
223
+ return [str(addr)]
224
+ except ValueError:
225
+ pass
226
+ ips: set[str] = set()
227
+ try:
228
+ infos = socket.getaddrinfo(host, 443, type=socket.SOCK_STREAM)
229
+ except OSError:
230
+ return []
231
+ for _family, _socktype, _proto, _canon, sockaddr in infos:
232
+ raw_ip = str(sockaddr[0]).split("%", 1)[0]
233
+ try:
234
+ ips.add(str(ipaddress.ip_address(raw_ip)))
235
+ except ValueError:
236
+ continue
237
+ return sorted(ips)
238
+
239
+
240
+ def _split_and_filter_ips(
241
+ raw_ips: Iterable[str],
242
+ *,
243
+ exclude_ips: set[str] | None = None,
244
+ ) -> tuple[list[str], list[str]]:
245
+ """Splits valid IPs into sorted unique (ipv4, ipv6), always stripping loopback & excluded IPs."""
246
+ excluded = exclude_ips or set()
247
+ v4: set[str] = set()
248
+ v6: set[str] = set()
249
+ for raw in raw_ips:
250
+ try:
251
+ addr = ipaddress.ip_address(raw.strip())
252
+ except ValueError:
253
+ continue
254
+ canonical = str(addr)
255
+ if addr.is_loopback or canonical in excluded:
256
+ continue
257
+ if isinstance(addr, ipaddress.IPv4Address):
258
+ v4.add(canonical)
259
+ else:
260
+ v6.add(canonical)
261
+ return sorted(v4), sorted(v6)
262
+
263
+
264
+ def resolve_endpoint_sets(
265
+ *,
266
+ endpoints_file: str | Path | None = None,
267
+ allow_hosts: Sequence[str] | None = None,
268
+ resolver: HostResolver = default_resolver,
269
+ ) -> dict[str, list[str]]:
270
+ """Resolves blocked and anti-lockout allowed hosts into safe disjoint IP sets."""
271
+ allowed_host_set: set[str] = {validate_endpoint(h) for h in ALWAYS_ALLOW_HOSTS}
272
+ for host in allow_hosts or ():
273
+ allowed_host_set.add(validate_endpoint(host))
274
+ allowed_hosts_sorted = sorted(allowed_host_set)
275
+
276
+ raw_allow_ips: set[str] = set()
277
+ for host in allowed_hosts_sorted:
278
+ for ip_str in resolver(host):
279
+ try:
280
+ addr = ipaddress.ip_address(ip_str)
281
+ except ValueError:
282
+ continue
283
+ if not addr.is_loopback:
284
+ raw_allow_ips.add(str(addr))
285
+ allowed_v4, allowed_v6 = _split_and_filter_ips(raw_allow_ips)
286
+ allow_ip_union = set(allowed_v4) | set(allowed_v6)
287
+
288
+ candidate_hosts: list[str] = list(DEFAULT_LLM_HOSTS)
289
+ if endpoints_file is not None:
290
+ candidate_hosts.extend(load_endpoints_file(endpoints_file))
291
+
292
+ blocked_hosts: list[str] = []
293
+ seen_blocked: set[str] = set()
294
+ for host in candidate_hosts:
295
+ clean = validate_endpoint(host)
296
+ if clean in allowed_host_set or clean in seen_blocked:
297
+ continue
298
+ seen_blocked.add(clean)
299
+ blocked_hosts.append(clean)
300
+
301
+ raw_block_ips: set[str] = set()
302
+ unresolved: list[str] = []
303
+ for host in blocked_hosts:
304
+ resolved = resolver(host)
305
+ if not resolved:
306
+ unresolved.append(host)
307
+ continue
308
+ raw_block_ips.update(resolved)
309
+
310
+ blocked_v4, blocked_v6 = _split_and_filter_ips(raw_block_ips, exclude_ips=allow_ip_union)
311
+ return {
312
+ "blocked_hosts": blocked_hosts,
313
+ "allowed_hosts": allowed_hosts_sorted,
314
+ "blocked_ipv4": blocked_v4,
315
+ "blocked_ipv6": blocked_v6,
316
+ "allowed_ipv4": allowed_v4,
317
+ "allowed_ipv6": allowed_v6,
318
+ "unresolved_hosts": unresolved,
319
+ }
320
+
321
+
322
+ # --------------------------------------------------------------------------- Ruleset & command builders
323
+
324
+
325
+ def build_nftables_ruleset(
326
+ *,
327
+ blocked_ipv4: Sequence[str],
328
+ blocked_ipv6: Sequence[str],
329
+ allowed_ipv4: Sequence[str],
330
+ allowed_ipv6: Sequence[str],
331
+ ) -> str:
332
+ """Builds an isolated idempotent nftables ruleset for `table inet agent_killswitch_net`."""
333
+ lines = [
334
+ f"table inet {NFT_TABLE_NAME}",
335
+ f"delete table inet {NFT_TABLE_NAME}",
336
+ f"table inet {NFT_TABLE_NAME} {{",
337
+ " chain output {",
338
+ " type filter hook output priority 0; policy accept;",
339
+ " # Anti-lockout safeguards (evaluated before any block rule)",
340
+ ' oifname "lo" accept',
341
+ " ip daddr 127.0.0.0/8 accept",
342
+ " ip6 daddr ::1 accept",
343
+ " tcp dport 22 accept",
344
+ " udp dport 53 accept",
345
+ " tcp dport 53 accept",
346
+ ]
347
+ if allowed_ipv4:
348
+ lines.append(f" ip daddr {{ {', '.join(allowed_ipv4)} }} accept")
349
+ if allowed_ipv6:
350
+ lines.append(f" ip6 daddr {{ {', '.join(allowed_ipv6)} }} accept")
351
+ lines.append(" # Block outbound TCP and UDP 80/443 (HTTP/HTTPS/QUIC) to LLM API provider IPs")
352
+ if blocked_ipv4:
353
+ lines.append(
354
+ f" ip daddr {{ {', '.join(blocked_ipv4)} }} meta l4proto {{ tcp, udp }} th dport {{ 80, 443 }} reject"
355
+ )
356
+ if blocked_ipv6:
357
+ lines.append(
358
+ f" ip6 daddr {{ {', '.join(blocked_ipv6)} }} meta l4proto {{ tcp, udp }} th dport {{ 80, 443 }} reject"
359
+ )
360
+ lines.extend([" }", "}"])
361
+ return "\n".join(lines) + "\n"
362
+
363
+
364
+ def build_iptables_commands(
365
+ *,
366
+ blocked_ipv4: Sequence[str],
367
+ blocked_ipv6: Sequence[str],
368
+ allowed_ipv4: Sequence[str],
369
+ allowed_ipv6: Sequence[str],
370
+ ) -> tuple[list[list[str]], list[list[str]]]:
371
+ """Builds dedicated `AGENT_KILLSWITCH_OUT` iptables/ip6tables TCP+UDP commands and rollback."""
372
+ apply_cmds: list[list[str]] = []
373
+ rollback_cmds: list[list[str]] = []
374
+
375
+ if blocked_ipv4 or not blocked_ipv6:
376
+ apply_cmds.extend(
377
+ [
378
+ ["iptables", "-N", IPTABLES_CHAIN_NAME],
379
+ ["iptables", "-F", IPTABLES_CHAIN_NAME],
380
+ ["iptables", "-A", IPTABLES_CHAIN_NAME, "-o", "lo", "-j", "RETURN"],
381
+ ["iptables", "-A", IPTABLES_CHAIN_NAME, "-d", "127.0.0.0/8", "-j", "RETURN"],
382
+ ["iptables", "-A", IPTABLES_CHAIN_NAME, "-p", "tcp", "--dport", "22", "-j", "RETURN"],
383
+ ["iptables", "-A", IPTABLES_CHAIN_NAME, "-p", "udp", "--dport", "53", "-j", "RETURN"],
384
+ ["iptables", "-A", IPTABLES_CHAIN_NAME, "-p", "tcp", "--dport", "53", "-j", "RETURN"],
385
+ ]
386
+ )
387
+ for ip in allowed_ipv4:
388
+ apply_cmds.append(["iptables", "-A", IPTABLES_CHAIN_NAME, "-d", ip, "-j", "RETURN"])
389
+ for ip in blocked_ipv4:
390
+ apply_cmds.append(
391
+ [
392
+ "iptables",
393
+ "-A",
394
+ IPTABLES_CHAIN_NAME,
395
+ "-d",
396
+ ip,
397
+ "-p",
398
+ "tcp",
399
+ "-m",
400
+ "multiport",
401
+ "--dports",
402
+ "80,443",
403
+ "-j",
404
+ "REJECT",
405
+ "--reject-with",
406
+ "tcp-reset",
407
+ ]
408
+ )
409
+ apply_cmds.append(
410
+ [
411
+ "iptables",
412
+ "-A",
413
+ IPTABLES_CHAIN_NAME,
414
+ "-d",
415
+ ip,
416
+ "-p",
417
+ "udp",
418
+ "-m",
419
+ "multiport",
420
+ "--dports",
421
+ "80,443",
422
+ "-j",
423
+ "REJECT",
424
+ "--reject-with",
425
+ "icmp-port-unreachable",
426
+ ]
427
+ )
428
+ apply_cmds.append(["iptables", "-I", "OUTPUT", "1", "-j", IPTABLES_CHAIN_NAME])
429
+ rollback_cmds.extend(
430
+ [
431
+ ["iptables", "-D", "OUTPUT", "-j", IPTABLES_CHAIN_NAME],
432
+ ["iptables", "-F", IPTABLES_CHAIN_NAME],
433
+ ["iptables", "-X", IPTABLES_CHAIN_NAME],
434
+ ]
435
+ )
436
+
437
+ if blocked_ipv6:
438
+ apply_cmds.extend(
439
+ [
440
+ ["ip6tables", "-N", IPTABLES_CHAIN_NAME],
441
+ ["ip6tables", "-F", IPTABLES_CHAIN_NAME],
442
+ ["ip6tables", "-A", IPTABLES_CHAIN_NAME, "-o", "lo", "-j", "RETURN"],
443
+ ["ip6tables", "-A", IPTABLES_CHAIN_NAME, "-d", "::1/128", "-j", "RETURN"],
444
+ ["ip6tables", "-A", IPTABLES_CHAIN_NAME, "-p", "tcp", "--dport", "22", "-j", "RETURN"],
445
+ ["ip6tables", "-A", IPTABLES_CHAIN_NAME, "-p", "udp", "--dport", "53", "-j", "RETURN"],
446
+ ["ip6tables", "-A", IPTABLES_CHAIN_NAME, "-p", "tcp", "--dport", "53", "-j", "RETURN"],
447
+ ]
448
+ )
449
+ for ip in allowed_ipv6:
450
+ apply_cmds.append(["ip6tables", "-A", IPTABLES_CHAIN_NAME, "-d", ip, "-j", "RETURN"])
451
+ for ip in blocked_ipv6:
452
+ apply_cmds.append(
453
+ [
454
+ "ip6tables",
455
+ "-A",
456
+ IPTABLES_CHAIN_NAME,
457
+ "-d",
458
+ ip,
459
+ "-p",
460
+ "tcp",
461
+ "-m",
462
+ "multiport",
463
+ "--dports",
464
+ "80,443",
465
+ "-j",
466
+ "REJECT",
467
+ "--reject-with",
468
+ "tcp-reset",
469
+ ]
470
+ )
471
+ apply_cmds.append(
472
+ [
473
+ "ip6tables",
474
+ "-A",
475
+ IPTABLES_CHAIN_NAME,
476
+ "-d",
477
+ ip,
478
+ "-p",
479
+ "udp",
480
+ "-m",
481
+ "multiport",
482
+ "--dports",
483
+ "80,443",
484
+ "-j",
485
+ "REJECT",
486
+ "--reject-with",
487
+ "icmp6-port-unreachable",
488
+ ]
489
+ )
490
+ apply_cmds.append(["ip6tables", "-I", "OUTPUT", "1", "-j", IPTABLES_CHAIN_NAME])
491
+ rollback_cmds.extend(
492
+ [
493
+ ["ip6tables", "-D", "OUTPUT", "-j", IPTABLES_CHAIN_NAME],
494
+ ["ip6tables", "-F", IPTABLES_CHAIN_NAME],
495
+ ["ip6tables", "-X", IPTABLES_CHAIN_NAME],
496
+ ]
497
+ )
498
+
499
+ return apply_cmds, rollback_cmds
500
+
501
+
502
+ def _chunked(items: Sequence[str], size: int) -> list[list[str]]:
503
+ return [list(items[i : i + size]) for i in range(0, len(items), size)]
504
+
505
+
506
+ def _windows_powershell_exe() -> str:
507
+ """Returns `pwsh` when installed, else `powershell`."""
508
+ return "pwsh" if shutil.which("pwsh") else "powershell"
509
+
510
+
511
+ def windows_get_rules_command() -> list[str]:
512
+ """Locale-independent PowerShell command to list active AgentKillswitch_Block_* rules."""
513
+ return [
514
+ _windows_powershell_exe(),
515
+ "-NoProfile",
516
+ "-NonInteractive",
517
+ "-Command",
518
+ (
519
+ f"Get-NetFirewallRule -DisplayName '{WINDOWS_RULE_PREFIX}*' "
520
+ "-ErrorAction SilentlyContinue | Select-Object -ExpandProperty DisplayName"
521
+ ),
522
+ ]
523
+
524
+
525
+ def windows_remove_rules_command() -> list[str]:
526
+ """Locale-independent PowerShell command to remove all AgentKillswitch_Block_* rules."""
527
+ return [
528
+ _windows_powershell_exe(),
529
+ "-NoProfile",
530
+ "-NonInteractive",
531
+ "-Command",
532
+ f"Remove-NetFirewallRule -DisplayName '{WINDOWS_RULE_PREFIX}*' -ErrorAction SilentlyContinue",
533
+ ]
534
+
535
+
536
+ def build_windows_netsh_commands(
537
+ *,
538
+ blocked_ipv4: Sequence[str],
539
+ blocked_ipv6: Sequence[str],
540
+ block_binaries: Sequence[str] | None = None,
541
+ ) -> tuple[list[list[str]], list[list[str]]]:
542
+ """Builds Windows Firewall TCP+UDP outbound block rules prefixed `AgentKillswitch_Block_`."""
543
+ apply_cmds: list[list[str]] = []
544
+
545
+ for idx, chunk in enumerate(_chunked(blocked_ipv4, 40), start=1):
546
+ for proto in ("TCP", "UDP"):
547
+ rule_name = f"{WINDOWS_RULE_PREFIX}IPv4_{proto}_{idx}"
548
+ apply_cmds.append(
549
+ [
550
+ "netsh",
551
+ "advfirewall",
552
+ "firewall",
553
+ "add",
554
+ "rule",
555
+ f"name={rule_name}",
556
+ "dir=out",
557
+ "action=block",
558
+ f"protocol={proto}",
559
+ "remoteport=80,443",
560
+ f"remoteip={','.join(chunk)}",
561
+ "enable=yes",
562
+ ]
563
+ )
564
+
565
+ for idx, chunk in enumerate(_chunked(blocked_ipv6, 40), start=1):
566
+ for proto in ("TCP", "UDP"):
567
+ rule_name = f"{WINDOWS_RULE_PREFIX}IPv6_{proto}_{idx}"
568
+ apply_cmds.append(
569
+ [
570
+ "netsh",
571
+ "advfirewall",
572
+ "firewall",
573
+ "add",
574
+ "rule",
575
+ f"name={rule_name}",
576
+ "dir=out",
577
+ "action=block",
578
+ f"protocol={proto}",
579
+ "remoteport=80,443",
580
+ f"remoteip={','.join(chunk)}",
581
+ "enable=yes",
582
+ ]
583
+ )
584
+
585
+ for idx, raw_bin in enumerate(block_binaries or (), start=1):
586
+ clean_bin = raw_bin.strip()
587
+ if not clean_bin or any(ch in clean_bin for ch in ("\r", "\n", '"')):
588
+ raise ValueError(f"Invalid binary path for Windows firewall rule: {raw_bin!r}")
589
+ for proto in ("TCP", "UDP"):
590
+ rule_name = f"{WINDOWS_RULE_PREFIX}Bin_{proto}_{idx}"
591
+ apply_cmds.append(
592
+ [
593
+ "netsh",
594
+ "advfirewall",
595
+ "firewall",
596
+ "add",
597
+ "rule",
598
+ f"name={rule_name}",
599
+ "dir=out",
600
+ "action=block",
601
+ f"program={clean_bin}",
602
+ f"protocol={proto}",
603
+ "remoteport=80,443",
604
+ "enable=yes",
605
+ ]
606
+ )
607
+
608
+ rollback_cmds = [windows_remove_rules_command()]
609
+ return apply_cmds, rollback_cmds
610
+
611
+
612
+ def parse_windows_rule_names(stdout: str) -> list[str]:
613
+ """Extracts active `AgentKillswitch_Block_*` rule names from PowerShell or netsh output.
614
+
615
+ Locale-independent: works directly with PowerShell `Get-NetFirewallRule |
616
+ Select-Object -ExpandProperty DisplayName` bare lines, and also supports
617
+ legacy `Rule Name: ...` output if encountered.
618
+ """
619
+ names: list[str] = []
620
+ seen: set[str] = set()
621
+ for raw_line in stdout.splitlines():
622
+ line = raw_line.strip()
623
+ if not line:
624
+ continue
625
+ name: str | None = None
626
+ if line.startswith(WINDOWS_RULE_PREFIX) and " " not in line:
627
+ name = line
628
+ else:
629
+ match = _WINDOWS_RULE_LINE_RE.match(raw_line)
630
+ if match:
631
+ name = match.group(1)
632
+ if name and name not in seen:
633
+ seen.add(name)
634
+ names.append(name)
635
+ return names
636
+
637
+
638
+ def build_macos_pf_ruleset(
639
+ *,
640
+ blocked_ipv4: Sequence[str],
641
+ blocked_ipv6: Sequence[str],
642
+ allowed_ipv4: Sequence[str],
643
+ allowed_ipv6: Sequence[str],
644
+ ) -> str:
645
+ """Builds a dedicated macOS `pf` anchor ruleset for `com.agent-killswitch/cutoff` (TCP + UDP)."""
646
+ all_allowed = [*allowed_ipv4, *allowed_ipv6]
647
+ all_blocked = [*blocked_ipv4, *blocked_ipv6]
648
+ lines = [
649
+ f"# agent-killswitch dedicated pf anchor: {MACOS_PF_ANCHOR}",
650
+ "# Anti-lockout safeguards (evaluated first with quick)",
651
+ "pass out quick on lo0 all",
652
+ "pass out quick to { 127.0.0.0/8, ::1 }",
653
+ "pass out quick proto tcp to any port 22",
654
+ "pass out quick proto { tcp, udp } to any port 53",
655
+ ]
656
+ if all_allowed:
657
+ lines.append(f"table <ak_allow> const {{ {', '.join(all_allowed)} }}")
658
+ lines.append("pass out quick to <ak_allow>")
659
+ if all_blocked:
660
+ lines.append(f"table <ak_block> const {{ {', '.join(all_blocked)} }}")
661
+ lines.append("block return out quick proto { tcp, udp } to <ak_block> port { 80, 443 }")
662
+ return "\n".join(lines) + "\n"
663
+
664
+
665
+ # --------------------------------------------------------------------------- Network operations
666
+
667
+
668
+ def _pick_linux_backend(backend: str | None) -> str:
669
+ if backend in ("nftables", "iptables"):
670
+ return backend
671
+ if shutil.which("nft"):
672
+ return "nftables"
673
+ return "iptables"
674
+
675
+
676
+ def net_cut(
677
+ *,
678
+ endpoints_file: str | Path | None = None,
679
+ allow_hosts: Sequence[str] | None = None,
680
+ block_binaries: Sequence[str] | None = None,
681
+ dry_run: bool = False,
682
+ platform_name: str | None = None,
683
+ linux_backend: str | None = None,
684
+ resolver: HostResolver = default_resolver,
685
+ runner: CommandRunner = default_runner,
686
+ elevated: bool | None = None,
687
+ ) -> NetworkPlan:
688
+ """Builds and (unless `dry_run`) applies OS-level LLM API outbound cutoff rules."""
689
+ plat = detect_platform(platform_name)
690
+ resolved = resolve_endpoint_sets(
691
+ endpoints_file=endpoints_file,
692
+ allow_hosts=allow_hosts,
693
+ resolver=resolver,
694
+ )
695
+ blocked_v4 = resolved["blocked_ipv4"]
696
+ blocked_v6 = resolved["blocked_ipv6"]
697
+ allowed_v4 = resolved["allowed_ipv4"]
698
+ allowed_v6 = resolved["allowed_ipv6"]
699
+
700
+ plan = NetworkPlan(
701
+ action="net-cut",
702
+ platform=plat,
703
+ backend="",
704
+ dry_run=dry_run,
705
+ blocked_hosts=resolved["blocked_hosts"],
706
+ allowed_hosts=resolved["allowed_hosts"],
707
+ blocked_ipv4=blocked_v4,
708
+ blocked_ipv6=blocked_v6,
709
+ allowed_ipv4=allowed_v4,
710
+ allowed_ipv6=allowed_v6,
711
+ unresolved_hosts=resolved["unresolved_hosts"],
712
+ blocked_binaries=list(block_binaries or ()),
713
+ )
714
+
715
+ if not blocked_v4 and not blocked_v6 and not (plat == "windows" and block_binaries):
716
+ plan.warnings.append("No LLM API IP addresses resolved (offline or DNS unavailable).")
717
+
718
+ if plat == "linux":
719
+ backend = _pick_linux_backend(linux_backend)
720
+ plan.backend = backend
721
+ if backend == "nftables":
722
+ plan.ruleset = build_nftables_ruleset(
723
+ blocked_ipv4=blocked_v4,
724
+ blocked_ipv6=blocked_v6,
725
+ allowed_ipv4=allowed_v4,
726
+ allowed_ipv6=allowed_v6,
727
+ )
728
+ plan.commands = [["nft", "-f", "-"]]
729
+ plan.rollback_commands = [["nft", "delete", "table", "inet", NFT_TABLE_NAME]]
730
+ else:
731
+ apply_cmds, rollback_cmds = build_iptables_commands(
732
+ blocked_ipv4=blocked_v4,
733
+ blocked_ipv6=blocked_v6,
734
+ allowed_ipv4=allowed_v4,
735
+ allowed_ipv6=allowed_v6,
736
+ )
737
+ plan.commands = apply_cmds
738
+ plan.rollback_commands = rollback_cmds
739
+ elif plat == "windows":
740
+ plan.backend = "netsh"
741
+ apply_cmds, rollback_cmds = build_windows_netsh_commands(
742
+ blocked_ipv4=blocked_v4,
743
+ blocked_ipv6=blocked_v6,
744
+ block_binaries=block_binaries,
745
+ )
746
+ plan.commands = apply_cmds
747
+ plan.rollback_commands = rollback_cmds
748
+ else:
749
+ plan.backend = "pf"
750
+ plan.ruleset = build_macos_pf_ruleset(
751
+ blocked_ipv4=blocked_v4,
752
+ blocked_ipv6=blocked_v6,
753
+ allowed_ipv4=allowed_v4,
754
+ allowed_ipv6=allowed_v6,
755
+ )
756
+ plan.commands = [["pfctl", "-a", MACOS_PF_ANCHOR, "-f", "-"]]
757
+ plan.rollback_commands = [["pfctl", "-a", MACOS_PF_ANCHOR, "-F", "all"]]
758
+ plan.warnings.append(
759
+ f"Ensure /etc/pf.conf includes `anchor \"{MACOS_PF_ANCHOR}\"` and pf is enabled (`sudo pfctl -e`)."
760
+ )
761
+
762
+ if dry_run:
763
+ plan.active = False
764
+ return plan
765
+
766
+ priv = is_elevated(plat) if elevated is None else elevated
767
+ if not priv:
768
+ plan.ok = False
769
+ plan.error = (
770
+ "Elevation required to apply OS firewall rules. "
771
+ + (
772
+ "Re-run from an elevated PowerShell 7 (Run as Administrator)."
773
+ if plat == "windows"
774
+ else "Re-run with sudo (or preview safely with --dry-run)."
775
+ )
776
+ )
777
+ return plan
778
+
779
+ if not blocked_v4 and not blocked_v6 and not (plat == "windows" and block_binaries):
780
+ plan.ok = False
781
+ plan.error = "Refusing to apply empty cutoff rule set: no LLM endpoints resolved to IPs."
782
+ return plan
783
+
784
+ if plat == "linux" and plan.backend == "nftables":
785
+ res = runner(plan.commands[0], plan.ruleset)
786
+ if res.returncode != 0:
787
+ plan.ok = False
788
+ plan.error = f"nft failed (rc={res.returncode}): {res.stderr.strip()}"
789
+ return plan
790
+ plan.active = True
791
+ return plan
792
+
793
+ if plat == "linux" and plan.backend == "iptables":
794
+ for cmd in plan.commands:
795
+ if len(cmd) >= 3 and cmd[1] == "-N":
796
+ runner(cmd, None) # ignore if chain already exists
797
+ continue
798
+ if len(cmd) >= 4 and cmd[1] == "-I" and cmd[2] == "OUTPUT":
799
+ check = runner([cmd[0], "-C", "OUTPUT", "-j", IPTABLES_CHAIN_NAME], None)
800
+ if check.returncode == 0:
801
+ continue
802
+ res = runner(cmd, None)
803
+ if res.returncode != 0:
804
+ plan.ok = False
805
+ plan.error = f"{' '.join(cmd)} failed (rc={res.returncode}): {res.stderr.strip()}"
806
+ return plan
807
+ plan.active = True
808
+ return plan
809
+
810
+ if plat == "windows":
811
+ runner(windows_remove_rules_command(), None)
812
+ for cmd in plan.commands:
813
+ res = runner(cmd, None)
814
+ if res.returncode != 0:
815
+ plan.ok = False
816
+ plan.error = f"netsh failed (rc={res.returncode}): {res.stderr.strip() or res.stdout.strip()}"
817
+ return plan
818
+ plan.active = True
819
+ return plan
820
+
821
+ # macOS pf
822
+ res = runner(plan.commands[0], plan.ruleset)
823
+ if res.returncode != 0:
824
+ plan.ok = False
825
+ plan.error = f"pfctl failed (rc={res.returncode}): {res.stderr.strip()}"
826
+ return plan
827
+ # Best-effort kill existing states to blocked LLM endpoints so active streams sever immediately
828
+ for ip in (*blocked_v4, *blocked_v6):
829
+ runner(["pfctl", "-k", ip], None)
830
+ plan.active = True
831
+ return plan
832
+
833
+
834
+ def net_restore(
835
+ *,
836
+ dry_run: bool = False,
837
+ platform_name: str | None = None,
838
+ linux_backend: str | None = None,
839
+ runner: CommandRunner = default_runner,
840
+ elevated: bool | None = None,
841
+ ) -> NetworkPlan:
842
+ """Atomically removes agent-killswitch OS firewall cutoff rules."""
843
+ plat = detect_platform(platform_name)
844
+ plan = NetworkPlan(action="net-restore", platform=plat, backend="", dry_run=dry_run)
845
+
846
+ if plat == "linux":
847
+ backend = _pick_linux_backend(linux_backend)
848
+ plan.backend = backend
849
+ if backend == "nftables":
850
+ plan.commands = [["nft", "delete", "table", "inet", NFT_TABLE_NAME]]
851
+ else:
852
+ plan.commands = [
853
+ ["iptables", "-D", "OUTPUT", "-j", IPTABLES_CHAIN_NAME],
854
+ ["iptables", "-F", IPTABLES_CHAIN_NAME],
855
+ ["iptables", "-X", IPTABLES_CHAIN_NAME],
856
+ ["ip6tables", "-D", "OUTPUT", "-j", IPTABLES_CHAIN_NAME],
857
+ ["ip6tables", "-F", IPTABLES_CHAIN_NAME],
858
+ ["ip6tables", "-X", IPTABLES_CHAIN_NAME],
859
+ ]
860
+ elif plat == "windows":
861
+ plan.backend = "powershell-netfirewall"
862
+ status = net_status(platform_name="windows", runner=runner)
863
+ plan.active_rules = status.active_rules
864
+ plan.commands = [windows_remove_rules_command()]
865
+ if not status.active_rules:
866
+ plan.warnings.append(f"No active {WINDOWS_RULE_PREFIX}* rules detected.")
867
+ else:
868
+ plan.backend = "pf"
869
+ plan.commands = [["pfctl", "-a", MACOS_PF_ANCHOR, "-F", "all"]]
870
+
871
+ if dry_run:
872
+ return plan
873
+
874
+ priv = is_elevated(plat) if elevated is None else elevated
875
+ if not priv:
876
+ plan.ok = False
877
+ plan.error = (
878
+ "Elevation required to remove OS firewall rules. "
879
+ + (
880
+ "Re-run from an elevated PowerShell 7 (Run as Administrator)."
881
+ if plat == "windows"
882
+ else "Re-run with sudo."
883
+ )
884
+ )
885
+ return plan
886
+
887
+ if plat == "linux":
888
+ if plan.backend == "nftables":
889
+ res = runner(plan.commands[0], None)
890
+ if res.returncode != 0 and "no such file or directory" not in res.stderr.lower():
891
+ plan.ok = False
892
+ plan.error = f"nft delete failed (rc={res.returncode}): {res.stderr.strip()}"
893
+ return plan
894
+ else:
895
+ for cmd in plan.commands:
896
+ runner(cmd, None) # best-effort cleanup of v4/v6 chains
897
+ plan.active = False
898
+ return plan
899
+
900
+ if plat == "windows":
901
+ res = runner(plan.commands[0], None)
902
+ if res.returncode != 0:
903
+ plan.ok = False
904
+ plan.error = (
905
+ f"Remove-NetFirewallRule failed (rc={res.returncode}): "
906
+ f"{res.stderr.strip() or res.stdout.strip()}"
907
+ )
908
+ return plan
909
+ plan.active = False
910
+ return plan
911
+
912
+ # macOS pf
913
+ res = runner(plan.commands[0], None)
914
+ if res.returncode != 0:
915
+ plan.ok = False
916
+ plan.error = f"pfctl flush failed (rc={res.returncode}): {res.stderr.strip()}"
917
+ return plan
918
+ plan.active = False
919
+ return plan
920
+
921
+
922
+ def net_status(
923
+ *,
924
+ platform_name: str | None = None,
925
+ linux_backend: str | None = None,
926
+ runner: CommandRunner = default_runner,
927
+ ) -> NetworkPlan:
928
+ """Read-only inspection of whether OS network cutoff rules are active (strictly zero-write)."""
929
+ plat = detect_platform(platform_name)
930
+ plan = NetworkPlan(action="net-status", platform=plat, backend="", dry_run=True)
931
+
932
+ if plat == "linux":
933
+ backend = _pick_linux_backend(linux_backend)
934
+ plan.backend = backend
935
+ if backend == "nftables":
936
+ cmd = ["nft", "list", "table", "inet", NFT_TABLE_NAME]
937
+ plan.commands = [cmd]
938
+ res = runner(cmd, None)
939
+ plan.active = res.returncode == 0 and NFT_TABLE_NAME in res.stdout
940
+ if plan.active:
941
+ plan.ruleset = res.stdout
942
+ plan.active_rules = [line.strip() for line in res.stdout.splitlines() if "reject" in line]
943
+ else:
944
+ cmd = ["iptables", "-L", IPTABLES_CHAIN_NAME, "-n"]
945
+ plan.commands = [cmd]
946
+ res = runner(cmd, None)
947
+ plan.active = res.returncode == 0 and IPTABLES_CHAIN_NAME in res.stdout
948
+ if plan.active:
949
+ plan.ruleset = res.stdout
950
+ plan.active_rules = [line.strip() for line in res.stdout.splitlines() if "REJECT" in line]
951
+ return plan
952
+
953
+ if plat == "windows":
954
+ plan.backend = "powershell-netfirewall"
955
+ cmd = windows_get_rules_command()
956
+ plan.commands = [cmd]
957
+ res = runner(cmd, None)
958
+ rules = parse_windows_rule_names(res.stdout) if res.returncode == 0 else []
959
+ plan.active_rules = rules
960
+ plan.active = len(rules) > 0
961
+ return plan
962
+
963
+ # macOS pf
964
+ plan.backend = "pf"
965
+ cmd = ["pfctl", "-a", MACOS_PF_ANCHOR, "-sr"]
966
+ plan.commands = [cmd]
967
+ res = runner(cmd, None)
968
+ rules = [line.strip() for line in res.stdout.splitlines() if line.strip() and not line.strip().startswith("#")]
969
+ plan.active_rules = rules
970
+ plan.active = res.returncode == 0 and any("block" in r for r in rules)
971
+ return plan
972
+
973
+
974
+ # --------------------------------------------------------------------------- Process freeze & thaw
975
+
976
+
977
+ def _read_linux_process_table(proc_root: str = "/proc") -> list[ProcessRecord]:
978
+ root = Path(proc_root)
979
+ records: list[ProcessRecord] = []
980
+ try:
981
+ entries = list(root.iterdir())
982
+ except OSError:
983
+ return []
984
+ for entry in entries:
985
+ if not entry.name.isdigit():
986
+ continue
987
+ pid = int(entry.name)
988
+ stat = ancestry._linux_stat(root, pid)
989
+ if stat is None:
990
+ continue
991
+ ppid = stat[0]
992
+ try:
993
+ comm = (entry / "comm").read_bytes().decode("utf-8", "replace").strip()
994
+ except OSError:
995
+ comm = ""
996
+ try:
997
+ raw_cmd = (entry / "cmdline").read_bytes()
998
+ argv = [p.decode("utf-8", "replace") for p in raw_cmd.split(b"\0") if p]
999
+ except OSError:
1000
+ argv = []
1001
+ try:
1002
+ exe = os.readlink(entry / "exe").removesuffix(" (deleted)")
1003
+ except OSError:
1004
+ exe = ""
1005
+ name = ancestry._posix_name(os.path.basename(exe) if exe else comm)
1006
+ cmdline = " ".join(argv) if argv else (exe or comm)
1007
+ records.append(ProcessRecord(pid=pid, ppid=ppid, name=name, cmdline=cmdline))
1008
+ return records
1009
+
1010
+
1011
+ def _read_macos_process_table(runner: CommandRunner = default_runner) -> list[ProcessRecord]:
1012
+ res = runner(["/bin/ps", "-axo", "pid=,ppid=,comm=,args="], None)
1013
+ if res.returncode != 0:
1014
+ return []
1015
+ records: list[ProcessRecord] = []
1016
+ for line in res.stdout.splitlines():
1017
+ parts = line.strip().split(None, 3)
1018
+ if len(parts) < 3 or not parts[0].isdigit() or not parts[1].isdigit():
1019
+ continue
1020
+ pid, ppid = int(parts[0]), int(parts[1])
1021
+ comm = parts[2]
1022
+ args_str = parts[3] if len(parts) > 3 else comm
1023
+ name = ancestry._posix_name(os.path.basename(comm.rstrip("/")))
1024
+ records.append(ProcessRecord(pid=pid, ppid=ppid, name=name, cmdline=args_str))
1025
+ return records
1026
+
1027
+
1028
+ def _read_windows_process_table() -> list[ProcessRecord]:
1029
+ if os.name != "nt":
1030
+ return []
1031
+ try:
1032
+ class _ProcessEntry32(ctypes.Structure):
1033
+ _fields_ = [
1034
+ ("dwSize", ctypes.wintypes.DWORD),
1035
+ ("cntUsage", ctypes.wintypes.DWORD),
1036
+ ("th32ProcessID", ctypes.wintypes.DWORD),
1037
+ ("th32DefaultHeapID", ctypes.POINTER(ctypes.wintypes.ULONG)),
1038
+ ("th32ModuleID", ctypes.wintypes.DWORD),
1039
+ ("cntThreads", ctypes.wintypes.DWORD),
1040
+ ("th32ParentProcessID", ctypes.wintypes.DWORD),
1041
+ ("pcPriClassBase", ctypes.wintypes.LONG),
1042
+ ("dwFlags", ctypes.wintypes.DWORD),
1043
+ ("szExeFile", ctypes.c_char * 260),
1044
+ ]
1045
+
1046
+ h_snap = ctypes.windll.kernel32.CreateToolhelp32Snapshot(0x00000002, 0)
1047
+ if h_snap == -1:
1048
+ return []
1049
+ pe = _ProcessEntry32()
1050
+ pe.dwSize = ctypes.sizeof(_ProcessEntry32)
1051
+ records: list[ProcessRecord] = []
1052
+ try:
1053
+ if ctypes.windll.kernel32.Process32First(h_snap, ctypes.byref(pe)):
1054
+ while True:
1055
+ name = pe.szExeFile.decode("ansi", errors="ignore").lower()
1056
+ records.append(
1057
+ ProcessRecord(
1058
+ pid=int(pe.th32ProcessID),
1059
+ ppid=int(pe.th32ParentProcessID),
1060
+ name=name,
1061
+ cmdline=name,
1062
+ )
1063
+ )
1064
+ if not ctypes.windll.kernel32.Process32Next(h_snap, ctypes.byref(pe)):
1065
+ break
1066
+ finally:
1067
+ ctypes.windll.kernel32.CloseHandle(h_snap)
1068
+ return records
1069
+ except (OSError, AttributeError, ValueError):
1070
+ return []
1071
+
1072
+
1073
+ def list_processes(
1074
+ *,
1075
+ platform_name: str | None = None,
1076
+ runner: CommandRunner = default_runner,
1077
+ ) -> list[ProcessRecord]:
1078
+ """Lists running OS processes as normalized `ProcessRecord` entries."""
1079
+ plat = detect_platform(platform_name)
1080
+ if plat == "windows":
1081
+ return _read_windows_process_table()
1082
+ if plat == "macos":
1083
+ return _read_macos_process_table(runner=runner)
1084
+ return _read_linux_process_table()
1085
+
1086
+
1087
+ def _ancestor_pids(records: Sequence[ProcessRecord], start_pid: int) -> set[int]:
1088
+ ppid_map = {rec.pid: rec.ppid for rec in records}
1089
+ protected: set[int] = set()
1090
+ pid = start_pid
1091
+ while pid > 0 and pid not in protected and len(protected) < 128:
1092
+ protected.add(pid)
1093
+ pid = ppid_map.get(pid, 0)
1094
+ return protected
1095
+
1096
+
1097
+ def _classify_process_vendor(rec: ProcessRecord) -> str | None:
1098
+ """Returns canonical LLM vendor for a process, matching executable/script names only.
1099
+
1100
+ Never substring-matches arbitrary CLI arguments (so `vim claude.md` or
1101
+ `grep cursor notes.txt` will NEVER be mistaken for an AI agent).
1102
+ """
1103
+ norm_name = rec.name.lower().strip()
1104
+ if norm_name in _PROTECTED_PROCESS_NAMES:
1105
+ return None
1106
+ if "killswitch" in norm_name:
1107
+ return None
1108
+
1109
+ try:
1110
+ argv = shlex.split(rec.cmdline) if rec.cmdline else []
1111
+ except ValueError:
1112
+ argv = rec.cmdline.split()
1113
+
1114
+ if norm_name in ancestry.POSIX_INTERPRETERS or norm_name in {
1115
+ "python.exe",
1116
+ "py.exe",
1117
+ "node.exe",
1118
+ "bun.exe",
1119
+ "deno.exe",
1120
+ }:
1121
+ interp = norm_name.removesuffix(".exe")
1122
+ if interp == "py":
1123
+ interp = "python"
1124
+ script = ancestry._interpreter_script(interp, argv) if argv and interp in ancestry.POSIX_INTERPRETERS else ""
1125
+ if not script:
1126
+ return None
1127
+ lower_script = script.lower()
1128
+ if "killswitch" in lower_script or "pytest" in lower_script or "unittest" in lower_script:
1129
+ return None
1130
+ return ancestry.match_llm_marker(lower_script, [os.path.basename(lower_script.replace("\\", "/"))])
1131
+
1132
+ # Non-interpreter executable: inspect ONLY executable basename(s) and macOS .app bundle name.
1133
+ candidates: list[str] = [norm_name]
1134
+ exact_names: list[str] = [norm_name]
1135
+ if argv:
1136
+ argv0_norm = argv[0].replace("\\", "/").rstrip("/")
1137
+ exe_base = os.path.basename(argv0_norm).lower()
1138
+ if exe_base and "killswitch" in exe_base:
1139
+ return None
1140
+ if exe_base and exe_base not in exact_names:
1141
+ exact_names.append(exe_base)
1142
+ candidates.append(exe_base)
1143
+ for segment in argv0_norm.split("/"):
1144
+ if segment.lower().endswith(".app"):
1145
+ candidates.append(segment.lower())
1146
+ return ancestry.match_llm_marker(" ".join(candidates), exact_names)
1147
+
1148
+
1149
+ def find_agent_processes(
1150
+ *,
1151
+ vendor_filter: str | None = None,
1152
+ process_table: Sequence[ProcessRecord] | None = None,
1153
+ current_pid: int | None = None,
1154
+ platform_name: str | None = None,
1155
+ runner: CommandRunner = default_runner,
1156
+ ) -> list[ProcessRecord]:
1157
+ """Finds running AI agent processes (and POSIX descendants), excluding self & owner ancestors."""
1158
+ clean_vendor: str | None = None
1159
+ if vendor_filter is not None and vendor_filter.strip():
1160
+ clean_vendor = vendor_filter.strip().lower()
1161
+ if not _VENDOR_NAME_RE.fullmatch(clean_vendor):
1162
+ raise ValueError(f"Invalid vendor name {vendor_filter!r}")
1163
+
1164
+ plat = detect_platform(platform_name)
1165
+ records = (
1166
+ list(process_table)
1167
+ if process_table is not None
1168
+ else list_processes(platform_name=plat, runner=runner)
1169
+ )
1170
+ self_pid = os.getpid() if current_pid is None else current_pid
1171
+ protected_pids = _ancestor_pids(records, self_pid) | {0, 1, self_pid}
1172
+
1173
+ roots: list[ProcessRecord] = []
1174
+ matched_pids: set[int] = set()
1175
+ for rec in records:
1176
+ if rec.pid in protected_pids:
1177
+ continue
1178
+ vendor = _classify_process_vendor(rec)
1179
+ if not vendor:
1180
+ continue
1181
+ if clean_vendor and vendor != clean_vendor:
1182
+ continue
1183
+ roots.append(
1184
+ ProcessRecord(
1185
+ pid=rec.pid,
1186
+ ppid=rec.ppid,
1187
+ name=rec.name,
1188
+ cmdline=rec.cmdline,
1189
+ vendor=vendor,
1190
+ )
1191
+ )
1192
+ matched_pids.add(rec.pid)
1193
+
1194
+ matched: list[ProcessRecord] = list(roots)
1195
+
1196
+ # On POSIX, also include child/descendant processes spawned by matched agents
1197
+ # so freezing an agent halts its active subshells/builds too.
1198
+ if plat != "windows" and roots:
1199
+ children_by_ppid: dict[int, list[ProcessRecord]] = {}
1200
+ for rec in records:
1201
+ children_by_ppid.setdefault(rec.ppid, []).append(rec)
1202
+ queue: list[tuple[int, str]] = [(r.pid, r.vendor) for r in roots]
1203
+ while queue:
1204
+ parent_pid, parent_vendor = queue.pop(0)
1205
+ for child in children_by_ppid.get(parent_pid, ()):
1206
+ if child.pid in protected_pids or child.pid in matched_pids:
1207
+ continue
1208
+ matched_pids.add(child.pid)
1209
+ matched.append(
1210
+ ProcessRecord(
1211
+ pid=child.pid,
1212
+ ppid=child.ppid,
1213
+ name=child.name,
1214
+ cmdline=child.cmdline,
1215
+ vendor=parent_vendor,
1216
+ )
1217
+ )
1218
+ queue.append((child.pid, parent_vendor))
1219
+
1220
+ return sorted(matched, key=lambda r: (r.vendor, r.pid))
1221
+
1222
+
1223
+ def freeze_or_thaw_agents(
1224
+ *,
1225
+ thaw: bool,
1226
+ vendor_filter: str | None = None,
1227
+ dry_run: bool = False,
1228
+ platform_name: str | None = None,
1229
+ process_table: Sequence[ProcessRecord] | None = None,
1230
+ current_pid: int | None = None,
1231
+ signaler: SignalSender | None = None,
1232
+ runner: CommandRunner = default_runner,
1233
+ ) -> dict[str, Any]:
1234
+ """Freezes (`SIGSTOP`) or resumes (`SIGCONT`) running AI agent processes."""
1235
+ plat = detect_platform(platform_name)
1236
+ action = "thaw" if thaw else "freeze"
1237
+ targets = find_agent_processes(
1238
+ vendor_filter=vendor_filter,
1239
+ process_table=process_table,
1240
+ current_pid=current_pid,
1241
+ platform_name=plat,
1242
+ runner=runner,
1243
+ )
1244
+
1245
+ if plat == "windows":
1246
+ safe_commands = [
1247
+ f"pssuspend {'-r ' if thaw else ''}{rec.pid} # {rec.vendor} ({rec.name})"
1248
+ for rec in targets
1249
+ ]
1250
+ note = (
1251
+ "Windows does not expose POSIX SIGSTOP/SIGCONT in Python stdlib (live freeze/thaw unsupported). "
1252
+ "Use Sysinternals `pssuspend` (`pssuspend <pid>` / `pssuspend -r <pid>`) "
1253
+ "or `Stop-Process -Id <pid>` from an interactive owner PowerShell 7 shell."
1254
+ )
1255
+ return {
1256
+ "action": action,
1257
+ "platform": plat,
1258
+ "supported": False,
1259
+ "dry_run": dry_run,
1260
+ "ok": bool(dry_run),
1261
+ "signal": "WINDOWS_PLAN_ONLY",
1262
+ "vendor_filter": vendor_filter,
1263
+ "matched": [rec.to_dict() for rec in targets],
1264
+ "affected": [],
1265
+ "failed": [],
1266
+ "safe_plan_commands": safe_commands,
1267
+ "note": note,
1268
+ }
1269
+
1270
+ sig_name = "SIGCONT" if thaw else "SIGSTOP"
1271
+ sig_num = getattr(signal, sig_name, 18 if thaw else 19)
1272
+ send = signaler or os.kill
1273
+
1274
+ affected: list[dict[str, Any]] = []
1275
+ failed: list[dict[str, Any]] = []
1276
+ for rec in targets:
1277
+ if dry_run:
1278
+ affected.append({**rec.to_dict(), "status": f"would_{action}"})
1279
+ continue
1280
+ try:
1281
+ send(rec.pid, sig_num)
1282
+ affected.append({**rec.to_dict(), "status": "thawed" if thaw else "frozen"})
1283
+ except OSError as exc:
1284
+ failed.append({**rec.to_dict(), "error": str(exc)})
1285
+
1286
+ return {
1287
+ "action": action,
1288
+ "platform": plat,
1289
+ "supported": True,
1290
+ "dry_run": dry_run,
1291
+ "ok": len(failed) == 0,
1292
+ "signal": sig_name,
1293
+ "vendor_filter": vendor_filter,
1294
+ "matched": [rec.to_dict() for rec in targets],
1295
+ "affected": affected,
1296
+ "failed": failed,
1297
+ }
1298
+
1299
+
1300
+ # --------------------------------------------------------------------------- OS-level ACL hardening
1301
+
1302
+
1303
+ def default_hardened_state_path(platform_name: str | None = None) -> str:
1304
+ """Returns the default system-owned hardened state path for the target OS."""
1305
+ plat = detect_platform(platform_name)
1306
+ if plat == "windows":
1307
+ return r"C:\ProgramData\agent-killswitch\state.json"
1308
+ return "/etc/agent-killswitch/state.json"
1309
+
1310
+
1311
+ def build_harden_plan(
1312
+ state_file: str | Path | None = None,
1313
+ *,
1314
+ platform_name: str | None = None,
1315
+ ) -> dict[str, Any]:
1316
+ """Builds OS-level read-only ACL hardening commands and rollback commands.
1317
+
1318
+ Defaults to a system-owned directory (`/etc/agent-killswitch/state.json` on
1319
+ POSIX, `C:\\ProgramData\\agent-killswitch\\state.json` on Windows) so same-user
1320
+ agents cannot bypass ACLs via `mv ~/.agent-killswitch` and user audit logging
1321
+ in `~/.agent-killswitch/audit.jsonl` stays writable.
1322
+ """
1323
+ plat = detect_platform(platform_name)
1324
+ resolved_target = (
1325
+ state_file
1326
+ if state_file is not None and str(state_file).strip()
1327
+ else default_hardened_state_path(plat)
1328
+ )
1329
+ sf: PurePosixPath | PureWindowsPath = (
1330
+ PureWindowsPath(resolved_target) if plat == "windows" else PurePosixPath(resolved_target)
1331
+ )
1332
+ sd = sf.parent
1333
+ sf_str = str(sf)
1334
+ sd_str = str(sd)
1335
+ warnings: list[str] = []
1336
+
1337
+ if ".agent-killswitch" in sf_str.lower():
1338
+ warnings.append(
1339
+ "Hardening inside a user-owned home directory can be bypassed by renaming the parent "
1340
+ "folder (`mv ~/.agent-killswitch`) and may block audit.jsonl writes. Prefer "
1341
+ f"`{default_hardened_state_path(plat)}`."
1342
+ )
1343
+
1344
+ if plat == "windows":
1345
+ # Universal locale-independent well-known Windows SIDs:
1346
+ # *S-1-5-32-544 = Administrators, *S-1-5-18 = SYSTEM, *S-1-5-32-545 = Users
1347
+ commands = [
1348
+ [
1349
+ "icacls",
1350
+ sd_str,
1351
+ "/inheritance:r",
1352
+ "/grant:r",
1353
+ "*S-1-5-32-544:(OI)(CI)F",
1354
+ "*S-1-5-18:(OI)(CI)F",
1355
+ "*S-1-5-32-545:(OI)(CI)RX",
1356
+ ],
1357
+ [
1358
+ "icacls",
1359
+ sf_str,
1360
+ "/inheritance:r",
1361
+ "/grant:r",
1362
+ "*S-1-5-32-544:F",
1363
+ "*S-1-5-18:F",
1364
+ "*S-1-5-32-545:RX",
1365
+ ],
1366
+ ]
1367
+ rollback = [
1368
+ ["icacls", sd_str, "/inheritance:e"],
1369
+ ["icacls", sf_str, "/inheritance:e"],
1370
+ ]
1371
+ else:
1372
+ owner_group = "root:wheel" if plat == "macos" else "root:root"
1373
+ commands = [
1374
+ ["chown", owner_group, sd_str],
1375
+ ["chmod", "0755", sd_str],
1376
+ ["chown", owner_group, sf_str],
1377
+ ["chmod", "0644", sf_str],
1378
+ ]
1379
+ user = os.environ.get("SUDO_USER") or os.environ.get("USER") or "<your-user>"
1380
+ rollback = [
1381
+ ["chown", "-R", user, sd_str],
1382
+ ["chmod", "0755", sd_str],
1383
+ ["chmod", "0644", sf_str],
1384
+ ]
1385
+
1386
+ return {
1387
+ "action": "harden",
1388
+ "platform": plat,
1389
+ "state_dir": sd_str,
1390
+ "state_file": sf_str,
1391
+ "commands": commands,
1392
+ "rollback_commands": rollback,
1393
+ "warnings": warnings,
1394
+ }
1395
+
1396
+
1397
+ def harden_state(
1398
+ state_file: str | Path | None = None,
1399
+ *,
1400
+ dry_run: bool = False,
1401
+ platform_name: str | None = None,
1402
+ runner: CommandRunner = default_runner,
1403
+ elevated: bool | None = None,
1404
+ ) -> dict[str, Any]:
1405
+ """Applies OS-level read-only ACL hardening on the state directory and `state.json`."""
1406
+ plan = build_harden_plan(state_file, platform_name=platform_name)
1407
+ plat = plan["platform"]
1408
+ plan["dry_run"] = dry_run
1409
+ plan["ok"] = True
1410
+ plan["error"] = None
1411
+
1412
+ if dry_run:
1413
+ return plan
1414
+
1415
+ priv = is_elevated(plat) if elevated is None else elevated
1416
+ if not priv:
1417
+ plan["ok"] = False
1418
+ plan["error"] = (
1419
+ "Elevation required to harden state ACLs. "
1420
+ + (
1421
+ f'Re-run from an elevated PowerShell 7: agent-killswitch harden --state "{plan["state_file"]}"'
1422
+ if plat == "windows"
1423
+ else f'Re-run with sudo: sudo agent-killswitch harden --state "{plan["state_file"]}"'
1424
+ )
1425
+ )
1426
+ return plan
1427
+
1428
+ sf = Path(plan["state_file"])
1429
+ sd = sf.parent
1430
+ sd.mkdir(parents=True, exist_ok=True)
1431
+
1432
+ for cmd in plan["commands"]:
1433
+ # Skip file-level ACL command if state.json does not exist yet
1434
+ if plan["state_file"] in cmd and not sf.exists():
1435
+ continue
1436
+ res = runner(cmd, None)
1437
+ if res.returncode != 0:
1438
+ plan["ok"] = False
1439
+ plan["error"] = f"{' '.join(cmd)} failed (rc={res.returncode}): {res.stderr.strip() or res.stdout.strip()}"
1440
+ return plan
1441
+
1442
+ return plan