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.
- agent_killswitch/__init__.py +63 -0
- agent_killswitch/__main__.py +10 -0
- agent_killswitch/ancestry.py +767 -0
- agent_killswitch/cloud.py +477 -0
- agent_killswitch/core.py +1214 -0
- agent_killswitch/hooks.py +748 -0
- agent_killswitch/mcp_server.py +551 -0
- agent_killswitch/network.py +1442 -0
- agent_killswitch/web.py +426 -0
- integrity_killswitch-0.3.0.dist-info/METADATA +356 -0
- integrity_killswitch-0.3.0.dist-info/RECORD +15 -0
- integrity_killswitch-0.3.0.dist-info/WHEEL +5 -0
- integrity_killswitch-0.3.0.dist-info/entry_points.txt +2 -0
- integrity_killswitch-0.3.0.dist-info/licenses/LICENSE +21 -0
- integrity_killswitch-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,767 @@
|
|
|
1
|
+
"""OS process-tree ancestry & caller classification for Windows, Linux, and macOS.
|
|
2
|
+
|
|
3
|
+
Zero external dependencies (Python 3.10+ stdlib).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ctypes
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import socket
|
|
12
|
+
import struct
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
if os.name == "nt":
|
|
20
|
+
import ctypes.wintypes
|
|
21
|
+
|
|
22
|
+
LINUX_ANCESTRY = sys.platform.startswith("linux")
|
|
23
|
+
MACOS_ANCESTRY = sys.platform == "darwin"
|
|
24
|
+
ANCESTRY_SUPPORTED = os.name == "nt" or LINUX_ANCESTRY or MACOS_ANCESTRY
|
|
25
|
+
|
|
26
|
+
KNOWN_VENDORS = (
|
|
27
|
+
"claude",
|
|
28
|
+
"codex",
|
|
29
|
+
"cursor",
|
|
30
|
+
"antigravity",
|
|
31
|
+
"copilot",
|
|
32
|
+
"aider",
|
|
33
|
+
"cline",
|
|
34
|
+
"windsurf",
|
|
35
|
+
"grok",
|
|
36
|
+
"gemini",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# Order matters: more specific markers first.
|
|
40
|
+
LLM_MARKERS: tuple[tuple[str, tuple[str, ...]], ...] = (
|
|
41
|
+
("antigravity", ("antigravity", "language_server")),
|
|
42
|
+
("claude", ("claude",)),
|
|
43
|
+
("codex", ("codex",)),
|
|
44
|
+
("cursor", ("cursor",)),
|
|
45
|
+
("windsurf", ("windsurf",)),
|
|
46
|
+
("copilot", ("copilot",)),
|
|
47
|
+
("aider", ("aider",)),
|
|
48
|
+
("cline", ("cline",)),
|
|
49
|
+
("grok", ("grok",)),
|
|
50
|
+
("gemini", ("gemini",)),
|
|
51
|
+
)
|
|
52
|
+
_AGY_BIN_RE = re.compile(r"(?:^|[\s/\\])agy(?:\.exe)?(?:\s|$)", re.I)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def match_llm_marker(joined: str, names: list[str] | None = None) -> str | None:
|
|
56
|
+
"""Return canonical LLM vendor if any known marker or exact `agy` binary matches."""
|
|
57
|
+
for vendor, markers in LLM_MARKERS:
|
|
58
|
+
if any(marker in joined for marker in markers):
|
|
59
|
+
return vendor
|
|
60
|
+
if names and any(name in {"agy", "agy.exe"} for name in names):
|
|
61
|
+
return "antigravity"
|
|
62
|
+
if _AGY_BIN_RE.search(joined):
|
|
63
|
+
return "antigravity"
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
# Windows classification sets
|
|
67
|
+
SERVICE_ROOTS = ("svchost.exe", "services.exe", "taskhostw.exe")
|
|
68
|
+
INTERACTIVE_SHELLS = {"powershell.exe", "pwsh.exe", "cmd.exe"}
|
|
69
|
+
UI_ANCHORS = {"explorer.exe", "windowsterminal.exe", "mintty.exe", "alacritty.exe", "wezterm-gui.exe"}
|
|
70
|
+
MSYS_SHELLS = {"bash.exe", "sh.exe"}
|
|
71
|
+
SYSTEM_ROOTS = {
|
|
72
|
+
"wininit.exe",
|
|
73
|
+
"winlogon.exe",
|
|
74
|
+
"userinit.exe",
|
|
75
|
+
"sihost.exe",
|
|
76
|
+
"runtimebroker.exe",
|
|
77
|
+
"system",
|
|
78
|
+
"[system process]",
|
|
79
|
+
}
|
|
80
|
+
NEUTRAL_NAMES = (
|
|
81
|
+
INTERACTIVE_SHELLS
|
|
82
|
+
| UI_ANCHORS
|
|
83
|
+
| MSYS_SHELLS
|
|
84
|
+
| SYSTEM_ROOTS
|
|
85
|
+
| set(SERVICE_ROOTS)
|
|
86
|
+
| {
|
|
87
|
+
"python.exe",
|
|
88
|
+
"py.exe",
|
|
89
|
+
"conhost.exe",
|
|
90
|
+
"openconsole.exe",
|
|
91
|
+
"git-bash.exe",
|
|
92
|
+
"git.exe",
|
|
93
|
+
"ssh.exe",
|
|
94
|
+
"scp.exe",
|
|
95
|
+
"sftp.exe",
|
|
96
|
+
"plink.exe",
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
MSYS_PS_CANDIDATES = (
|
|
101
|
+
r"C:\Program Files\Git\usr\bin\ps.exe",
|
|
102
|
+
r"C:\Program Files (x86)\Git\usr\bin\ps.exe",
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# POSIX / Linux / macOS classification sets
|
|
106
|
+
POSIX_INTERPRETERS = {"python", "node", "bun", "deno"}
|
|
107
|
+
POSIX_MAX_DEPTH = 64
|
|
108
|
+
_PYTHON_NAME_RE = re.compile(r"python[0-9.]*")
|
|
109
|
+
|
|
110
|
+
POSIX_SHELLS = {"bash", "sh", "dash", "zsh", "fish", "ksh", "tcsh"}
|
|
111
|
+
POSIX_SSH_DAEMONS = {"sshd", "sshd-session"}
|
|
112
|
+
LINUX_TERMINALS = {
|
|
113
|
+
"login",
|
|
114
|
+
"agetty",
|
|
115
|
+
"gnome-terminal-server",
|
|
116
|
+
"konsole",
|
|
117
|
+
"xterm",
|
|
118
|
+
"alacritty",
|
|
119
|
+
"kitty",
|
|
120
|
+
"tilix",
|
|
121
|
+
"xfce4-terminal",
|
|
122
|
+
"terminator",
|
|
123
|
+
"foot",
|
|
124
|
+
"wezterm-gui",
|
|
125
|
+
"ghostty",
|
|
126
|
+
}
|
|
127
|
+
LINUX_ROOTS = {"systemd", "init"}
|
|
128
|
+
LINUX_NEUTRAL = POSIX_SHELLS | LINUX_TERMINALS | LINUX_ROOTS | {"sudo", "su"}
|
|
129
|
+
|
|
130
|
+
MACOS_TERMINALS = {
|
|
131
|
+
"login",
|
|
132
|
+
"terminal",
|
|
133
|
+
"iterm2",
|
|
134
|
+
"itermserver",
|
|
135
|
+
"wezterm-gui",
|
|
136
|
+
"alacritty",
|
|
137
|
+
"kitty",
|
|
138
|
+
"ghostty",
|
|
139
|
+
"warp",
|
|
140
|
+
"hyper",
|
|
141
|
+
}
|
|
142
|
+
MACOS_ROOTS = {"launchd"}
|
|
143
|
+
MACOS_NEUTRAL = POSIX_SHELLS | MACOS_TERMINALS | MACOS_ROOTS | {"sudo", "su"}
|
|
144
|
+
|
|
145
|
+
BROWSER_NAMES = {
|
|
146
|
+
"chrome.exe",
|
|
147
|
+
"msedge.exe",
|
|
148
|
+
"firefox.exe",
|
|
149
|
+
"brave.exe",
|
|
150
|
+
"opera.exe",
|
|
151
|
+
"vivaldi.exe",
|
|
152
|
+
"chrome",
|
|
153
|
+
"chromium",
|
|
154
|
+
"firefox",
|
|
155
|
+
"brave",
|
|
156
|
+
"safari",
|
|
157
|
+
"google chrome",
|
|
158
|
+
"arc",
|
|
159
|
+
"brave browser",
|
|
160
|
+
"microsoft edge",
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _posix_name(basename: str) -> str:
|
|
165
|
+
"""Normalizes executable names (e.g., `-zsh` -> `zsh`, `python3.12` -> `python`)."""
|
|
166
|
+
name = basename.strip().lstrip("-").lower()
|
|
167
|
+
return "python" if _PYTHON_NAME_RE.fullmatch(name) else name
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _interpreter_script(name: str, argv: list[str]) -> str | None:
|
|
171
|
+
"""Returns the script path an interpreter executes, or '' for inline/REPL, or None if unparsable."""
|
|
172
|
+
takes_value = {
|
|
173
|
+
"python": {"-W", "-X", "-Q"},
|
|
174
|
+
"node": {"-r", "--require", "--import", "--loader"},
|
|
175
|
+
"bun": set(),
|
|
176
|
+
"deno": set(),
|
|
177
|
+
}[name]
|
|
178
|
+
inline = {
|
|
179
|
+
"python": {"-c"},
|
|
180
|
+
"node": {"-e", "--eval", "-p", "--print"},
|
|
181
|
+
"bun": {"-e", "--eval"},
|
|
182
|
+
"deno": {"eval"},
|
|
183
|
+
}[name]
|
|
184
|
+
args = argv[1:]
|
|
185
|
+
if name in {"deno", "bun"} and args and args[0] == "run":
|
|
186
|
+
args = args[1:]
|
|
187
|
+
idx = 0
|
|
188
|
+
while idx < len(args):
|
|
189
|
+
arg = args[idx]
|
|
190
|
+
if arg in inline:
|
|
191
|
+
return ""
|
|
192
|
+
if name == "python" and arg == "-m":
|
|
193
|
+
return args[idx + 1] if idx + 1 < len(args) else None
|
|
194
|
+
if name == "python" and arg.startswith("-m") and len(arg) > 2:
|
|
195
|
+
return arg[2:]
|
|
196
|
+
if name == "python" and arg.startswith("-c"):
|
|
197
|
+
return ""
|
|
198
|
+
if arg == "--":
|
|
199
|
+
return args[idx + 1] if idx + 1 < len(args) else ""
|
|
200
|
+
if arg.startswith("-"):
|
|
201
|
+
idx += 2 if arg in takes_value else 1
|
|
202
|
+
continue
|
|
203
|
+
return arg
|
|
204
|
+
return ""
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# --------------------------------------------------------------------------- Windows ancestry
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _parse_msys_ps(out: str) -> dict[int, int]:
|
|
211
|
+
"""Parses Git/MSYS `ps -e` output into {winpid: parent_winpid}."""
|
|
212
|
+
win_of: dict[int, int] = {}
|
|
213
|
+
parent_of: dict[int, int] = {}
|
|
214
|
+
for line in out.splitlines()[1:]:
|
|
215
|
+
parts = line.split()
|
|
216
|
+
if parts and not parts[0].isdigit():
|
|
217
|
+
parts = parts[1:] # optional leading status column (S/I)
|
|
218
|
+
if len(parts) < 4 or not all(x.isdigit() for x in parts[:4]):
|
|
219
|
+
continue
|
|
220
|
+
mpid, mppid, winpid = int(parts[0]), int(parts[1]), int(parts[3])
|
|
221
|
+
win_of[mpid] = winpid
|
|
222
|
+
parent_of[mpid] = mppid
|
|
223
|
+
result: dict[int, int] = {}
|
|
224
|
+
for mpid, winpid in win_of.items():
|
|
225
|
+
parent_win = win_of.get(parent_of.get(mpid, 0), 0)
|
|
226
|
+
if parent_win and parent_win != winpid:
|
|
227
|
+
result[winpid] = parent_win
|
|
228
|
+
return result
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _msys_parent_winpids() -> dict[int, int]:
|
|
232
|
+
ps = next((p for p in MSYS_PS_CANDIDATES if os.path.exists(p)), None)
|
|
233
|
+
if not ps:
|
|
234
|
+
return {}
|
|
235
|
+
try:
|
|
236
|
+
proc = subprocess.run(
|
|
237
|
+
[ps, "-e"],
|
|
238
|
+
capture_output=True,
|
|
239
|
+
text=True,
|
|
240
|
+
timeout=5,
|
|
241
|
+
check=False,
|
|
242
|
+
stdin=subprocess.DEVNULL,
|
|
243
|
+
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
|
244
|
+
)
|
|
245
|
+
return _parse_msys_ps(proc.stdout)
|
|
246
|
+
except (OSError, subprocess.SubprocessError):
|
|
247
|
+
return {}
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _read_windows_ancestors(start_pid: int | None = None) -> list[str]:
|
|
251
|
+
if os.name != "nt":
|
|
252
|
+
return []
|
|
253
|
+
try:
|
|
254
|
+
th32cs_snapprocess = 0x00000002
|
|
255
|
+
|
|
256
|
+
class _ProcessEntry32(ctypes.Structure):
|
|
257
|
+
_fields_ = [
|
|
258
|
+
("dwSize", ctypes.wintypes.DWORD),
|
|
259
|
+
("cntUsage", ctypes.wintypes.DWORD),
|
|
260
|
+
("th32ProcessID", ctypes.wintypes.DWORD),
|
|
261
|
+
("th32DefaultHeapID", ctypes.POINTER(ctypes.wintypes.ULONG)),
|
|
262
|
+
("th32ModuleID", ctypes.wintypes.DWORD),
|
|
263
|
+
("cntThreads", ctypes.wintypes.DWORD),
|
|
264
|
+
("th32ParentProcessID", ctypes.wintypes.DWORD),
|
|
265
|
+
("pcPriClassBase", ctypes.wintypes.LONG),
|
|
266
|
+
("dwFlags", ctypes.wintypes.DWORD),
|
|
267
|
+
("szExeFile", ctypes.c_char * 260),
|
|
268
|
+
]
|
|
269
|
+
|
|
270
|
+
h_snap = ctypes.windll.kernel32.CreateToolhelp32Snapshot(th32cs_snapprocess, 0)
|
|
271
|
+
if h_snap == -1:
|
|
272
|
+
return []
|
|
273
|
+
|
|
274
|
+
pe = _ProcessEntry32()
|
|
275
|
+
pe.dwSize = ctypes.sizeof(_ProcessEntry32)
|
|
276
|
+
procs: dict[int, tuple[int, str]] = {}
|
|
277
|
+
try:
|
|
278
|
+
if ctypes.windll.kernel32.Process32First(h_snap, ctypes.byref(pe)):
|
|
279
|
+
while True:
|
|
280
|
+
procs[pe.th32ProcessID] = (
|
|
281
|
+
pe.th32ParentProcessID,
|
|
282
|
+
pe.szExeFile.decode("ansi", errors="ignore").lower(),
|
|
283
|
+
)
|
|
284
|
+
if not ctypes.windll.kernel32.Process32Next(h_snap, ctypes.byref(pe)):
|
|
285
|
+
break
|
|
286
|
+
finally:
|
|
287
|
+
ctypes.windll.kernel32.CloseHandle(h_snap)
|
|
288
|
+
|
|
289
|
+
ancestors: list[str] = []
|
|
290
|
+
chain: list[int] = []
|
|
291
|
+
pid = start_pid or os.getpid()
|
|
292
|
+
visited: set[int] = set()
|
|
293
|
+
msys: dict[int, int] | None = None
|
|
294
|
+
while True:
|
|
295
|
+
while pid in procs and pid != 0 and pid not in visited:
|
|
296
|
+
visited.add(pid)
|
|
297
|
+
chain.append(pid)
|
|
298
|
+
ppid, name = procs[pid]
|
|
299
|
+
ancestors.append(name)
|
|
300
|
+
pid = ppid
|
|
301
|
+
if ancestors and ancestors[-1] == "explorer.exe":
|
|
302
|
+
break
|
|
303
|
+
if msys is None:
|
|
304
|
+
msys = _msys_parent_winpids()
|
|
305
|
+
nxt = 0
|
|
306
|
+
for known in chain:
|
|
307
|
+
cand = msys.get(known, 0)
|
|
308
|
+
if cand and cand in procs and cand not in visited:
|
|
309
|
+
nxt = cand
|
|
310
|
+
break
|
|
311
|
+
if not nxt:
|
|
312
|
+
break
|
|
313
|
+
pid = nxt
|
|
314
|
+
return ancestors
|
|
315
|
+
except (OSError, AttributeError, ValueError):
|
|
316
|
+
return []
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# --------------------------------------------------------------------------- Linux ancestry
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _linux_stat(proc: Path, pid: int) -> tuple[int, int] | None:
|
|
323
|
+
"""Returns (ppid, start_time) from /proc/<pid>/stat, or None."""
|
|
324
|
+
try:
|
|
325
|
+
raw = (proc / str(pid) / "stat").read_bytes().decode("utf-8", "replace")
|
|
326
|
+
rest = raw[raw.rindex(")") + 2 :].split()
|
|
327
|
+
return int(rest[1]), int(rest[19])
|
|
328
|
+
except (OSError, ValueError, IndexError):
|
|
329
|
+
return None
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _linux_entry(proc: Path, pid: int) -> tuple[str, str] | None:
|
|
333
|
+
"""Returns (normalized_name, marker_text) for one Linux PID, or None to refuse."""
|
|
334
|
+
base = proc / str(pid)
|
|
335
|
+
try:
|
|
336
|
+
exe = os.readlink(base / "exe")
|
|
337
|
+
except OSError:
|
|
338
|
+
exe = ""
|
|
339
|
+
try:
|
|
340
|
+
comm: str | None = (base / "comm").read_bytes().decode("utf-8", "replace").strip()
|
|
341
|
+
except OSError:
|
|
342
|
+
comm = None
|
|
343
|
+
try:
|
|
344
|
+
raw_cmdline = (base / "cmdline").read_bytes()
|
|
345
|
+
argv: list[str] | None = [part.decode("utf-8", "replace") for part in raw_cmdline.split(b"\0") if part]
|
|
346
|
+
except OSError:
|
|
347
|
+
argv = None
|
|
348
|
+
|
|
349
|
+
exe = exe.removesuffix(" (deleted)")
|
|
350
|
+
if exe:
|
|
351
|
+
name = _posix_name(os.path.basename(exe))
|
|
352
|
+
elif comm and argv is not None:
|
|
353
|
+
name = _posix_name(comm)
|
|
354
|
+
else:
|
|
355
|
+
return None
|
|
356
|
+
|
|
357
|
+
if name in POSIX_INTERPRETERS:
|
|
358
|
+
if argv is None:
|
|
359
|
+
return None
|
|
360
|
+
script = _interpreter_script(name, argv)
|
|
361
|
+
if script is None:
|
|
362
|
+
return None
|
|
363
|
+
return name, script.lower()
|
|
364
|
+
parts = (exe, comm or "") if exe else (comm or "", argv[0] if argv else "")
|
|
365
|
+
return name, " ".join(part for part in parts if part).lower()
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def read_linux_ancestry(
|
|
369
|
+
start_pid: int | None = None,
|
|
370
|
+
proc_root: str = "/proc",
|
|
371
|
+
) -> list[tuple[str, str]] | None:
|
|
372
|
+
"""Walks the Linux process tree from start_pid to PID 1 with PID-reuse validation."""
|
|
373
|
+
proc = Path(proc_root)
|
|
374
|
+
pid = start_pid or os.getpid()
|
|
375
|
+
chain: list[tuple[int, int, int]] = []
|
|
376
|
+
entries: list[tuple[str, str]] = []
|
|
377
|
+
seen: set[int] = set()
|
|
378
|
+
while pid > 0:
|
|
379
|
+
if pid in seen or len(chain) >= POSIX_MAX_DEPTH:
|
|
380
|
+
return None
|
|
381
|
+
seen.add(pid)
|
|
382
|
+
stat = _linux_stat(proc, pid)
|
|
383
|
+
if stat is None:
|
|
384
|
+
return None
|
|
385
|
+
ppid, start = stat
|
|
386
|
+
if chain and start > chain[-1][1]:
|
|
387
|
+
return None
|
|
388
|
+
entry = _linux_entry(proc, pid)
|
|
389
|
+
if entry is None:
|
|
390
|
+
return None
|
|
391
|
+
chain.append((pid, start, ppid))
|
|
392
|
+
entries.append(entry)
|
|
393
|
+
pid = ppid
|
|
394
|
+
if not chain or chain[-1][0] != 1:
|
|
395
|
+
return None
|
|
396
|
+
for cpid, start, ppid in chain:
|
|
397
|
+
if _linux_stat(proc, cpid) != (ppid, start):
|
|
398
|
+
return None
|
|
399
|
+
return entries
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
# --------------------------------------------------------------------------- macOS ancestry
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _parse_macos_ps(out: str) -> dict[int, tuple[int, str]]:
|
|
406
|
+
"""Parses `ps -axo pid=,ppid=,comm=` output into {pid: (ppid, comm)}."""
|
|
407
|
+
table: dict[int, tuple[int, str]] = {}
|
|
408
|
+
for line in out.splitlines():
|
|
409
|
+
stripped = line.strip()
|
|
410
|
+
if not stripped:
|
|
411
|
+
continue
|
|
412
|
+
parts = stripped.split(None, 2)
|
|
413
|
+
if len(parts) < 3 or not parts[0].isdigit() or not parts[1].isdigit():
|
|
414
|
+
continue
|
|
415
|
+
table[int(parts[0])] = (int(parts[1]), parts[2].strip())
|
|
416
|
+
return table
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _macos_pid_args(pid: int) -> list[str]:
|
|
420
|
+
"""Reads argv for a single macOS PID via `/bin/ps -ww -p <pid> -o args=`."""
|
|
421
|
+
try:
|
|
422
|
+
proc = subprocess.run(
|
|
423
|
+
["/bin/ps", "-ww", "-p", str(pid), "-o", "args="],
|
|
424
|
+
capture_output=True,
|
|
425
|
+
text=True,
|
|
426
|
+
timeout=5,
|
|
427
|
+
check=False,
|
|
428
|
+
stdin=subprocess.DEVNULL,
|
|
429
|
+
)
|
|
430
|
+
raw = proc.stdout.strip()
|
|
431
|
+
return raw.split() if raw else []
|
|
432
|
+
except (OSError, subprocess.SubprocessError):
|
|
433
|
+
return []
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _macos_entry(pid: int, comm: str, args_loader: Any = _macos_pid_args) -> tuple[str, str] | None:
|
|
437
|
+
"""Returns (normalized_name, marker_text) for one macOS process."""
|
|
438
|
+
if not comm:
|
|
439
|
+
return None
|
|
440
|
+
base = os.path.basename(comm.rstrip("/"))
|
|
441
|
+
name = _posix_name(base)
|
|
442
|
+
if name in POSIX_INTERPRETERS:
|
|
443
|
+
argv = args_loader(pid)
|
|
444
|
+
if not argv:
|
|
445
|
+
return None
|
|
446
|
+
script = _interpreter_script(name, argv)
|
|
447
|
+
if script is None:
|
|
448
|
+
return None
|
|
449
|
+
return name, script.lower()
|
|
450
|
+
return name, comm.lower()
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def read_macos_ancestry(
|
|
454
|
+
start_pid: int | None = None,
|
|
455
|
+
ps_table: dict[int, tuple[int, str]] | None = None,
|
|
456
|
+
args_loader: Any = _macos_pid_args,
|
|
457
|
+
) -> list[tuple[str, str]] | None:
|
|
458
|
+
"""Walks the macOS process tree from start_pid up to launchd (PID 1)."""
|
|
459
|
+
if ps_table is None:
|
|
460
|
+
try:
|
|
461
|
+
proc = subprocess.run(
|
|
462
|
+
["/bin/ps", "-axo", "pid=,ppid=,comm="],
|
|
463
|
+
capture_output=True,
|
|
464
|
+
text=True,
|
|
465
|
+
timeout=5,
|
|
466
|
+
check=False,
|
|
467
|
+
stdin=subprocess.DEVNULL,
|
|
468
|
+
)
|
|
469
|
+
if proc.returncode != 0:
|
|
470
|
+
return None
|
|
471
|
+
ps_table = _parse_macos_ps(proc.stdout)
|
|
472
|
+
except (OSError, subprocess.SubprocessError):
|
|
473
|
+
return None
|
|
474
|
+
|
|
475
|
+
pid = start_pid or os.getpid()
|
|
476
|
+
entries: list[tuple[str, str]] = []
|
|
477
|
+
seen: set[int] = set()
|
|
478
|
+
last_pid = 0
|
|
479
|
+
while pid > 0:
|
|
480
|
+
if pid in seen or len(entries) >= POSIX_MAX_DEPTH:
|
|
481
|
+
return None
|
|
482
|
+
if pid not in ps_table:
|
|
483
|
+
return None
|
|
484
|
+
seen.add(pid)
|
|
485
|
+
last_pid = pid
|
|
486
|
+
ppid, comm = ps_table[pid]
|
|
487
|
+
entry = _macos_entry(pid, comm, args_loader=args_loader)
|
|
488
|
+
if entry is None:
|
|
489
|
+
return None
|
|
490
|
+
entries.append(entry)
|
|
491
|
+
if pid == 1:
|
|
492
|
+
break
|
|
493
|
+
pid = ppid
|
|
494
|
+
if not entries or last_pid != 1:
|
|
495
|
+
return None
|
|
496
|
+
return entries
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
# --------------------------------------------------------------------------- unified ancestry & classification
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def get_process_ancestor_names(start_pid: int | None = None) -> list[str]:
|
|
503
|
+
"""Returns executable names of ancestor processes from caller upwards."""
|
|
504
|
+
if os.name == "nt":
|
|
505
|
+
return _read_windows_ancestors(start_pid)
|
|
506
|
+
if LINUX_ANCESTRY:
|
|
507
|
+
entries = read_linux_ancestry(start_pid)
|
|
508
|
+
return [name for name, _text in entries] if entries else []
|
|
509
|
+
if MACOS_ANCESTRY:
|
|
510
|
+
entries = read_macos_ancestry(start_pid)
|
|
511
|
+
return [name for name, _text in entries] if entries else []
|
|
512
|
+
return []
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def claude_code_env(env: Mapping[str, Any]) -> bool:
|
|
516
|
+
"""True when environment carries markers Claude Code sets on child processes."""
|
|
517
|
+
return (
|
|
518
|
+
str(env.get("CLAUDECODE", "")).strip() == "1"
|
|
519
|
+
or str(env.get("AI_AGENT", "")).strip().lower().startswith("claude-code")
|
|
520
|
+
or bool(str(env.get("CLAUDE_CODE_ENTRYPOINT", "")).strip())
|
|
521
|
+
)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _stdin_is_tty() -> bool:
|
|
525
|
+
try:
|
|
526
|
+
return bool(sys.stdin and sys.stdin.isatty())
|
|
527
|
+
except (OSError, ValueError):
|
|
528
|
+
return False
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _classify_posix(
|
|
532
|
+
entries: list[tuple[str, str]] | None,
|
|
533
|
+
env: Mapping[str, Any],
|
|
534
|
+
*,
|
|
535
|
+
terminals: set[str],
|
|
536
|
+
roots: set[str],
|
|
537
|
+
neutral: set[str],
|
|
538
|
+
is_tty: bool | None = None,
|
|
539
|
+
) -> str:
|
|
540
|
+
if entries:
|
|
541
|
+
joined = " ".join(text for _name, text in entries)
|
|
542
|
+
matched = match_llm_marker(joined, [name for name, _text in entries])
|
|
543
|
+
if matched:
|
|
544
|
+
return matched
|
|
545
|
+
env_vendor = str(env.get("LLM_VENDOR", "")).strip().lower()
|
|
546
|
+
if env_vendor in KNOWN_VENDORS:
|
|
547
|
+
return env_vendor
|
|
548
|
+
if claude_code_env(env):
|
|
549
|
+
return "claude"
|
|
550
|
+
if not entries:
|
|
551
|
+
return "unknown_llm"
|
|
552
|
+
names = [name for name, _text in entries]
|
|
553
|
+
if names[0] == "python":
|
|
554
|
+
names = names[1:]
|
|
555
|
+
if not names:
|
|
556
|
+
return "unknown_llm"
|
|
557
|
+
if all(name in neutral for name in names):
|
|
558
|
+
if any(name in terminals for name in names):
|
|
559
|
+
return "owner"
|
|
560
|
+
if any(name in POSIX_SHELLS for name in names):
|
|
561
|
+
return "unknown_llm"
|
|
562
|
+
if names[-1] in roots:
|
|
563
|
+
return "service"
|
|
564
|
+
return "unknown_llm"
|
|
565
|
+
# Interactive human SSH session: requires verified sshd/sshd-session ancestry,
|
|
566
|
+
# SSH_TTY env, and an attached TTY. Non-interactive `ssh host "cmd"` stays
|
|
567
|
+
# fail-closed as unknown_llm so remote LLM commands cannot restore access.
|
|
568
|
+
ssh_allowed = neutral | POSIX_SSH_DAEMONS
|
|
569
|
+
if all(name in ssh_allowed for name in names) and any(name in POSIX_SSH_DAEMONS for name in names):
|
|
570
|
+
tty_active = _stdin_is_tty() if is_tty is None else bool(is_tty)
|
|
571
|
+
if tty_active and str(env.get("SSH_TTY", "")).strip():
|
|
572
|
+
return "owner"
|
|
573
|
+
return "unknown_llm"
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def classify_linux(
|
|
577
|
+
entries: list[tuple[str, str]] | None,
|
|
578
|
+
env: Mapping[str, Any],
|
|
579
|
+
*,
|
|
580
|
+
is_tty: bool | None = None,
|
|
581
|
+
) -> str:
|
|
582
|
+
return _classify_posix(
|
|
583
|
+
entries,
|
|
584
|
+
env,
|
|
585
|
+
terminals=LINUX_TERMINALS,
|
|
586
|
+
roots=LINUX_ROOTS,
|
|
587
|
+
neutral=LINUX_NEUTRAL,
|
|
588
|
+
is_tty=is_tty,
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def classify_macos(
|
|
593
|
+
entries: list[tuple[str, str]] | None,
|
|
594
|
+
env: Mapping[str, Any],
|
|
595
|
+
*,
|
|
596
|
+
is_tty: bool | None = None,
|
|
597
|
+
) -> str:
|
|
598
|
+
return _classify_posix(
|
|
599
|
+
entries,
|
|
600
|
+
env,
|
|
601
|
+
terminals=MACOS_TERMINALS,
|
|
602
|
+
roots=MACOS_ROOTS,
|
|
603
|
+
neutral=MACOS_NEUTRAL,
|
|
604
|
+
is_tty=is_tty,
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def cut_chain_vendor(ancestors: list[str], env: Mapping[str, Any]) -> str:
|
|
609
|
+
"""Verdict when a Windows walk dead-ended without reaching a live owner/service anchor."""
|
|
610
|
+
if ancestors and all(name in NEUTRAL_NAMES for name in ancestors) and claude_code_env(env):
|
|
611
|
+
return "claude"
|
|
612
|
+
return "unknown_llm"
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def detect_vendor(
|
|
616
|
+
ancestors: list[str] | None = None,
|
|
617
|
+
env: Mapping[str, Any] | None = None,
|
|
618
|
+
) -> str:
|
|
619
|
+
"""Identifies the caller (`owner`, `service`, a known LLM vendor, or `unknown_llm`).
|
|
620
|
+
|
|
621
|
+
Security order:
|
|
622
|
+
1. Any LLM executable in the ancestor chain wins (cannot spoof via env).
|
|
623
|
+
2. LLM_VENDOR may only select a known vendor, never `owner`.
|
|
624
|
+
3. Detached/orphan shells never qualify as `owner` (fail-closed).
|
|
625
|
+
4. `owner` requires a verified chain anchored to an interactive terminal/UI.
|
|
626
|
+
"""
|
|
627
|
+
active_env: Mapping[str, Any] = os.environ if env is None else env
|
|
628
|
+
if ancestors is None and LINUX_ANCESTRY:
|
|
629
|
+
return classify_linux(read_linux_ancestry(), active_env)
|
|
630
|
+
if ancestors is None and MACOS_ANCESTRY:
|
|
631
|
+
return classify_macos(read_macos_ancestry(), active_env)
|
|
632
|
+
if ancestors is None:
|
|
633
|
+
ancestors = get_process_ancestor_names()
|
|
634
|
+
|
|
635
|
+
joined = " ".join(ancestors)
|
|
636
|
+
matched = match_llm_marker(joined, ancestors)
|
|
637
|
+
if matched:
|
|
638
|
+
return matched
|
|
639
|
+
|
|
640
|
+
env_vendor = str(active_env.get("LLM_VENDOR", "")).strip().lower()
|
|
641
|
+
if env_vendor in KNOWN_VENDORS:
|
|
642
|
+
return env_vendor
|
|
643
|
+
|
|
644
|
+
if not ancestors:
|
|
645
|
+
return "unknown_llm"
|
|
646
|
+
if "pythonw.exe" in ancestors:
|
|
647
|
+
return "service"
|
|
648
|
+
if ancestors[-1] in MSYS_SHELLS:
|
|
649
|
+
return cut_chain_vendor(ancestors, active_env)
|
|
650
|
+
if not all(name in NEUTRAL_NAMES for name in ancestors):
|
|
651
|
+
return "unknown_llm"
|
|
652
|
+
if ancestors[-1] in INTERACTIVE_SHELLS or claude_code_env(active_env):
|
|
653
|
+
return cut_chain_vendor(ancestors, active_env)
|
|
654
|
+
if any(name in UI_ANCHORS for name in ancestors):
|
|
655
|
+
return "owner"
|
|
656
|
+
if any(name in SERVICE_ROOTS for name in ancestors):
|
|
657
|
+
return "service"
|
|
658
|
+
if any(name in INTERACTIVE_SHELLS for name in ancestors):
|
|
659
|
+
return "owner"
|
|
660
|
+
return cut_chain_vendor(ancestors, active_env)
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
# --------------------------------------------------------------------------- loopback peer PID & web actor
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def _parse_lsof_peer(out: str, client_port: int, server_port: int) -> int:
|
|
667
|
+
"""Parses `lsof -nP -iTCP:<port> -sTCP:ESTABLISHED -F pn` to find client PID."""
|
|
668
|
+
current_pid = 0
|
|
669
|
+
needle = f"127.0.0.1:{client_port}->127.0.0.1:{server_port}"
|
|
670
|
+
needle_v6 = f"[::1]:{client_port}->[::1]:{server_port}"
|
|
671
|
+
for line in out.splitlines():
|
|
672
|
+
if line.startswith("p") and line[1:].isdigit():
|
|
673
|
+
current_pid = int(line[1:])
|
|
674
|
+
elif line.startswith("n") and current_pid:
|
|
675
|
+
name = line[1:]
|
|
676
|
+
if needle in name or needle_v6 in name:
|
|
677
|
+
return current_pid
|
|
678
|
+
return 0
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _linux_tcp_peer_pid(client_port: int, server_port: int, proc_root: str = "/proc") -> int:
|
|
682
|
+
"""Finds the PID owning loopback socket 127.0.0.1:client_port -> 127.0.0.1:server_port."""
|
|
683
|
+
proc = Path(proc_root)
|
|
684
|
+
target_local = f"0100007F:{client_port:04X}"
|
|
685
|
+
target_remote = f"0100007F:{server_port:04X}"
|
|
686
|
+
inode = ""
|
|
687
|
+
try:
|
|
688
|
+
for line in (proc / "net" / "tcp").read_text(encoding="utf-8", errors="replace").splitlines()[1:]:
|
|
689
|
+
cols = line.split()
|
|
690
|
+
if len(cols) >= 10 and cols[1].upper() == target_local and cols[2].upper() == target_remote:
|
|
691
|
+
inode = cols[9]
|
|
692
|
+
break
|
|
693
|
+
except OSError:
|
|
694
|
+
return 0
|
|
695
|
+
if not inode or inode == "0":
|
|
696
|
+
return 0
|
|
697
|
+
want = f"socket:[{inode}]"
|
|
698
|
+
try:
|
|
699
|
+
for entry in proc.iterdir():
|
|
700
|
+
if not entry.name.isdigit():
|
|
701
|
+
continue
|
|
702
|
+
fd_dir = entry / "fd"
|
|
703
|
+
try:
|
|
704
|
+
for fd in fd_dir.iterdir():
|
|
705
|
+
try:
|
|
706
|
+
if os.readlink(fd) == want:
|
|
707
|
+
return int(entry.name)
|
|
708
|
+
except OSError:
|
|
709
|
+
continue
|
|
710
|
+
except OSError:
|
|
711
|
+
continue
|
|
712
|
+
except OSError:
|
|
713
|
+
return 0
|
|
714
|
+
return 0
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def tcp_peer_pid(client_port: int, server_port: int) -> int:
|
|
718
|
+
"""Returns PID of the local process holding the client side of a loopback connection."""
|
|
719
|
+
if os.name == "nt":
|
|
720
|
+
try:
|
|
721
|
+
iphlpapi = ctypes.windll.iphlpapi
|
|
722
|
+
size = ctypes.wintypes.DWORD(0)
|
|
723
|
+
iphlpapi.GetExtendedTcpTable(None, ctypes.byref(size), False, 2, 5, 0)
|
|
724
|
+
buf = ctypes.create_string_buffer(size.value + 8192)
|
|
725
|
+
size = ctypes.wintypes.DWORD(len(buf))
|
|
726
|
+
if iphlpapi.GetExtendedTcpTable(buf, ctypes.byref(size), False, 2, 5, 0) != 0:
|
|
727
|
+
return 0
|
|
728
|
+
(count,) = struct.unpack_from("<I", buf, 0)
|
|
729
|
+
for idx in range(count):
|
|
730
|
+
_st, _la, lport, _ra, rport, pid = struct.unpack_from("<6I", buf, 4 + idx * 24)
|
|
731
|
+
if socket.ntohs(lport & 0xFFFF) == client_port and socket.ntohs(rport & 0xFFFF) == server_port:
|
|
732
|
+
return int(pid)
|
|
733
|
+
except (OSError, AttributeError, struct.error):
|
|
734
|
+
return 0
|
|
735
|
+
return 0
|
|
736
|
+
|
|
737
|
+
if LINUX_ANCESTRY:
|
|
738
|
+
return _linux_tcp_peer_pid(client_port, server_port)
|
|
739
|
+
|
|
740
|
+
if MACOS_ANCESTRY:
|
|
741
|
+
try:
|
|
742
|
+
proc = subprocess.run(
|
|
743
|
+
["/usr/sbin/lsof", "-nP", f"-iTCP:{server_port}", "-sTCP:ESTABLISHED", "-F", "pn"],
|
|
744
|
+
capture_output=True,
|
|
745
|
+
text=True,
|
|
746
|
+
timeout=5,
|
|
747
|
+
check=False,
|
|
748
|
+
stdin=subprocess.DEVNULL,
|
|
749
|
+
)
|
|
750
|
+
return _parse_lsof_peer(proc.stdout, client_port, server_port)
|
|
751
|
+
except (OSError, subprocess.SubprocessError):
|
|
752
|
+
return 0
|
|
753
|
+
return 0
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def web_actor(names: list[str]) -> str:
|
|
757
|
+
"""Classifies the caller behind a local dashboard request.
|
|
758
|
+
|
|
759
|
+
A browser without an LLM ancestor counts as `owner`.
|
|
760
|
+
"""
|
|
761
|
+
joined = " ".join(names)
|
|
762
|
+
matched = match_llm_marker(joined, names)
|
|
763
|
+
if matched:
|
|
764
|
+
return matched
|
|
765
|
+
if any(name in BROWSER_NAMES for name in names):
|
|
766
|
+
return "owner"
|
|
767
|
+
return detect_vendor(names, env={})
|