phiward 0.2.0b1__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.
Files changed (53) hide show
  1. phiward/__init__.py +8 -0
  2. phiward/__main__.py +5 -0
  3. phiward/_toml.py +211 -0
  4. phiward/adapters/__init__.py +105 -0
  5. phiward/adapters/claude.py +429 -0
  6. phiward/broker.py +831 -0
  7. phiward/carryover.py +1613 -0
  8. phiward/claude_settings.py +1307 -0
  9. phiward/cli.py +110 -0
  10. phiward/config.py +936 -0
  11. phiward/confine.py +476 -0
  12. phiward/copying.py +533 -0
  13. phiward/core.py +105 -0
  14. phiward/data/agents-section.md +43 -0
  15. phiward/doctor.py +1132 -0
  16. phiward/fasthook.py +70 -0
  17. phiward/fsinfo.py +241 -0
  18. phiward/gateway.py +159 -0
  19. phiward/githooks.py +248 -0
  20. phiward/guards/__init__.py +0 -0
  21. phiward/guards/protected_paths.py +1138 -0
  22. phiward/hidden.py +281 -0
  23. phiward/init.py +155 -0
  24. phiward/install.py +828 -0
  25. phiward/inventory.py +173 -0
  26. phiward/mcp.py +186 -0
  27. phiward/mcp_config.py +1736 -0
  28. phiward/names.py +5 -0
  29. phiward/packs/dates.toml +17 -0
  30. phiward/packs/genomics.toml +51 -0
  31. phiward/packs/msk.toml +32 -0
  32. phiward/pathid.py +403 -0
  33. phiward/pathmatch.py +98 -0
  34. phiward/paths.py +942 -0
  35. phiward/pin.py +214 -0
  36. phiward/procinfo.py +73 -0
  37. phiward/remote.py +448 -0
  38. phiward/run.py +788 -0
  39. phiward/safeio.py +84 -0
  40. phiward/sanitize.py +691 -0
  41. phiward/selfcheck.py +1506 -0
  42. phiward/service.py +321 -0
  43. phiward/session_note.py +86 -0
  44. phiward/setup_cmd.py +886 -0
  45. phiward/shell.py +504 -0
  46. phiward/wholetool.py +1463 -0
  47. phiward-0.2.0b1.dist-info/METADATA +147 -0
  48. phiward-0.2.0b1.dist-info/RECORD +53 -0
  49. phiward-0.2.0b1.dist-info/WHEEL +5 -0
  50. phiward-0.2.0b1.dist-info/entry_points.txt +3 -0
  51. phiward-0.2.0b1.dist-info/licenses/LICENSE +662 -0
  52. phiward-0.2.0b1.dist-info/licenses/NOTICE +16 -0
  53. phiward-0.2.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1138 @@
1
+ """The protected-paths guard: the text layer in front of the kernel boundary.
2
+
3
+ The boundary is the kernel: Claude Code's sandbox (as `install` writes it) keeps the agent's
4
+ shell commands from protected roots, and only the gateway (`phiward run|copy`, started by the
5
+ broker, confined by confine.py, output sanitized) can read them. This guard:
6
+ - allows a gateway call written as the whole command (a client of the broker; the broker checks
7
+ the grants, `--write-to` and `--net`, against the user config);
8
+ - refuses a shell command that names a protected path (inside one), with a reason that says to
9
+ use the gateway;
10
+ - when the tool's shell is NOT confined (no sandbox), refuses every command but a whole gateway
11
+ call, `doctor` or `check`; with `[shell] best_effort` it instead also refuses a command that
12
+ runs in, or names, a folder above a protected path, and applies `unresolved` to variables it
13
+ cannot see (best effort, docs/threat-model.md);
14
+ - refuses file tools (read, search, write) on a protected path, and searches from above one.
15
+ No shell sandbox covers the file tools, so this check always applies;
16
+ - refuses file-tool writes to the files that turn the guards off or widen the gateway: the
17
+ phiward config, code and status file, and the agent tool's own settings files.
18
+
19
+ A command "names" a path when its working folder, a `cd` target, any word (after the guard
20
+ expands `~`, known variables, braces and globs, and resolves symlinks before it normalizes), the
21
+ text of an inner command, or the command text itself, reaches it.
22
+ """
23
+
24
+ import os
25
+ import stat
26
+ import re
27
+ from dataclasses import replace
28
+ from typing import AbstractSet, Dict, List, Mapping, NamedTuple, Optional, Sequence, Set, Tuple
29
+
30
+ from phiward import gateway, paths, pathid, shell
31
+ from phiward.config import Config
32
+ from phiward.core import (ALLOW, ALLOWED, ASK, DENY, FILE_READ, FILE_SEARCH, FILE_WRITE,
33
+ SHELL, Action, Decision)
34
+
35
+ NAME = "protected-paths"
36
+ MAX_DEPTH = 8 # nesting of $( ) inside $( ) the guard follows before it gives up (fail closed)
37
+
38
+ # one short line: the rules themselves are in AGENTS.md and the skill, which
39
+ # the agent already has; a long reason on every refusal only costs context
40
+ RULE = ("Use `phiward run -- CMD` (the whole command) or `phiward copy`. Rules: AGENTS.md or "
41
+ "the phiward skill.")
42
+
43
+
44
+ def deny(why: str, step: str = RULE) -> Decision:
45
+ """A refusal: what is refused, then its one next step. RULE (the gateway) is the step only
46
+ for a refusal that names protected data; any other refusal carries its own (`step=""`: the
47
+ reason already says what to do)."""
48
+ return Decision(DENY, f"{why} {step}".strip(), NAME)
49
+
50
+
51
+ class _Touch:
52
+ """What one command (with its inner commands) does."""
53
+
54
+ def __init__(self) -> None:
55
+ self.relation: Optional[str] = None
56
+ self.unresolved: List[str] = [] # names of unknown variables, or "syntax"
57
+
58
+ def add(self, rel: Optional[str]) -> None:
59
+ self.relation = paths.worst(self.relation, rel)
60
+
61
+
62
+ def check(action: Action, cfg: Config) -> Decision:
63
+ from phiward import claude_settings
64
+ home = pathid.home()
65
+ for project in claude_settings.project_folders(action.cwd or "", home):
66
+ redirect = claude_settings.project_redirects(project, home)
67
+ if redirect:
68
+ # the hook would read another config (or none): nothing it decides can be trusted
69
+ text = claude_settings.redirect_text(redirect)
70
+ return Decision(DENY, text[:1].upper() + text[1:]
71
+ + ", which can change what phiward's hook runs or reads. Every tool "
72
+ "call is refused until the operator fixes the project's "
73
+ ".claude/settings*.json.", NAME)
74
+ if cfg.problem:
75
+ return Decision(DENY, f"The phiward config cannot be used, so guarded actions are "
76
+ f"refused until it is fixed: {cfg.problem}", NAME)
77
+ home0 = pathid.home()
78
+ memo: dict = {} # the Claude folders and each path's answer, once for this call
79
+ if action.kind == FILE_WRITE and _writes_a_guard_file(action, home0, cfg, memo=memo):
80
+ # also before any config exists: the first setup is when the config is written, and a
81
+ # file tool must not write it then either
82
+ return deny("This file tool writes a file that controls the guards (the phiward "
83
+ "config, code or status file, the agent tool's settings, `.mcp.json`, anything "
84
+ "inside a `.git` folder or a `.git` file, or a `phiward` on PATH). Only the operator changes these.",
85
+ step="")
86
+ if action.starts:
87
+ # the app starts the project's own code outside the sandbox, with the operator's rights;
88
+ # first every other check (a starter that names protected data is refused, not asked)
89
+ first = check(replace(action, starts=""), cfg)
90
+ if first.verdict == DENY:
91
+ return first
92
+ return _ask_or_deny(
93
+ action, f"phiward: this tool starts {action.starts}, outside Claude Code's sandbox "
94
+ "and with your rights: code the agent wrote there runs unconfined. Allow it only if "
95
+ "you have read what it runs.",
96
+ f"This tool starts {action.starts}, outside the sandbox and with the operator's "
97
+ "rights, and this session cannot ask the operator: the operator starts it "
98
+ "themselves.")
99
+ if action.kind == FILE_WRITE and _writes_code(action, home0, memo):
100
+ return _ask_or_deny(action, ASK_CODE, DENY_CODE)
101
+ if action.kind == FILE_WRITE and _another_name(action, home0):
102
+ return _ask_or_deny(action, ASK_LINK, DENY_LINK)
103
+ if "powershell" in (action.tool or "").lower() and cfg.has_protected_paths:
104
+ # its commands are not parsed like a POSIX shell's, and phiward does not know how
105
+ # Claude Code confines them: only Bash is checked as a shell
106
+ return deny("phiward does not check PowerShell commands as a shell; use Bash.", step="")
107
+ if not cfg.has_protected_paths:
108
+ # no config yet (first setup): no protected data is known, but the
109
+ # credentials are: a key or ticket the agent reads now reaches the model all the same.
110
+ # Only direct reads are refused here, not searches above them.
111
+ return _credentials_only(action, cfg)
112
+ # the hidden list (credentials, tickets, histories) is refused like protected
113
+ # data: a credential that reaches the model undoes every mask
114
+ from phiward import hidden
115
+ pset = paths.ProtectedSet(cfg.all_roots + hidden.paths(None, cfg, session=True),
116
+ list(cfg.patterns) + list(hidden.KRB5_NAME_PATTERNS))
117
+ pset.secret = paths.ProtectedSet(cfg.all_roots, cfg.patterns)
118
+ home = pathid.home()
119
+ try:
120
+ if action.searches:
121
+ # the paths a tool names by its path fields, as a search: only adds a refusal
122
+ mode = pset.mode
123
+ pset.mode = "file"
124
+ d = _check_file(replace(action, kind=FILE_SEARCH, paths=action.searches), pset, home)
125
+ pset.mode = mode
126
+ if d.verdict == DENY:
127
+ return d
128
+ if action.kind == SHELL:
129
+ # a named tool other than Claude Code's shells (no name: a generic shell, `check`)
130
+ other = bool(action.tool) and action.tool not in ("Bash", "bash", "Monitor")
131
+ if action.text and other:
132
+ # a shell under another name: every string of its input, not only the command
133
+ d = _check_text(action.text, pset, home, cwd=action.cwd or "/", cfg=cfg,
134
+ ask=action.can_ask, tool=action.tool)
135
+ if d.verdict == DENY:
136
+ return d
137
+ if other and action.shape and not cfg.shell_best_effort:
138
+ return deny(UNSANDBOXED_TOOL.format(why=action.shape, advice=action.advice),
139
+ step="")
140
+ if not action.confined and not cfg.shell_best_effort:
141
+ kind = _kernel_route(action.command)
142
+ if kind is None:
143
+ if other:
144
+ return deny(UNSANDBOXED_TOOL.format(
145
+ why="its command is not one whole gateway call",
146
+ advice=action.advice), step="")
147
+ # said once: the rule's tail would repeat the gateway call
148
+ return Decision(DENY, gateway.not_whole(action.command) or
149
+ unconfined_text(action.unconfined_why,
150
+ action.unconfined_step), NAME)
151
+ if kind == "kernel": # `doctor`, `check`: no protected data read here
152
+ action = replace(action, confined=True)
153
+ return _check_shell(action, cfg, pset, home)
154
+ if action.kind in (FILE_READ, FILE_WRITE, FILE_SEARCH):
155
+ pset.mode = "file"
156
+ d = _check_file(action, pset, home)
157
+ if d.verdict != ALLOW or action.kind != FILE_WRITE:
158
+ return d
159
+ # a file tool writes where the sandbox lets the shell write (Mode A; inside `launch`
160
+ # the kernel confines the whole tool)
161
+ if action.claude_code and not os.environ.get("PHIWARD_LAUNCH_DEPTH") and \
162
+ _writes_outside(action, home):
163
+ return _ask_or_deny(action, ASK_OUT, DENY_OUT)
164
+ return d
165
+ if action.remote:
166
+ # a remote server runs nothing here and writes no file here: only its text
167
+ return _check_text(action.text + action.paths, pset, home)
168
+ return _check_text(action.text + action.paths, pset, home, cwd=action.cwd or "/",
169
+ ask=action.can_ask, tool=action.tool, cfg=cfg)
170
+ except paths.GlobUnchecked as exc:
171
+ return deny(str(exc), step="")
172
+
173
+
174
+ # why an unconfined shell call is refused (`[shell] best_effort` off, the default)
175
+ UNCONFINED = ("This shell is not confined by Claude Code's sandbox, so every command is refused "
176
+ "but a whole gateway call (`phiward run -- CMD`, `phiward copy SRC... DST`). The "
177
+ "operator turns the sandbox on with `(cd ~ && phiward install claude --user --write)` "
178
+ "(`phiward doctor` says what is missing).")
179
+
180
+
181
+ def unconfined_text(why: str, step: str = "") -> str:
182
+ """UNCONFINED, with the confinement check's reason and its own step when there is one: the
183
+ same answer as `doctor`."""
184
+ if not why:
185
+ return UNCONFINED
186
+ return (f"This shell is not confined by Claude Code's sandbox ({why}), so every command is "
187
+ "refused but a whole gateway call (`phiward run -- CMD`, `phiward copy SRC... DST`)."
188
+ + (f" To fix it: {step}." if step else ""))
189
+
190
+
191
+ # why a shell tool other than Claude Code's Bash and Monitor is refused
192
+ UNSANDBOXED_TOOL = ("This tool runs commands outside Claude Code's sandbox, with the operator's "
193
+ "rights, and {why}, so phiward refuses it. Such a tool may make one whole "
194
+ "gateway call (`phiward run -- CMD`, `phiward copy SRC... DST`), in its one "
195
+ "command field, with no other options. {advice}")
196
+
197
+
198
+ def _kernel_route(command: str) -> Optional[str]:
199
+ """For a shell that Claude Code's sandbox does not confine: "gateway" for a gateway call
200
+ (the broker runs it), "kernel" for `doctor` or `check` (they read no protected data), each
201
+ written whole; else None (refused)."""
202
+ words = gateway.whole_command(command)
203
+ if not words:
204
+ return None
205
+ if words[0] in ("run", "copy"):
206
+ return "gateway"
207
+ if words[0] in ("doctor", "check"):
208
+ return "kernel"
209
+ return None
210
+
211
+
212
+ def _credentials_only(action: Action, cfg: Config) -> Decision:
213
+ try:
214
+ return _credentials_check(action, cfg)
215
+ except paths.GlobUnchecked as exc:
216
+ return deny(str(exc), step="")
217
+
218
+
219
+ def _credentials_check(action: Action, cfg: Config) -> Decision:
220
+ from phiward import hidden
221
+ pset = paths.ProtectedSet(hidden.paths(None, cfg, session=True), list(hidden.KRB5_NAME_PATTERNS))
222
+ pset.secret = paths.ProtectedSet([], []) # no protected paths yet
223
+ if action.kind != SHELL:
224
+ pset.mode = "file"
225
+ else:
226
+ pset.mode = "confined" if action.confined else "shell"
227
+ home = pathid.home()
228
+ why = ("This names a credential or a trace that no agent may read (phiward's hidden list): "
229
+ "leave it out of the call.")
230
+ if action.kind == SHELL:
231
+ cmd = action.command
232
+ if pset.text_search(_expand_home_in_text(cmd, home)):
233
+ return deny(why, step="")
234
+ touch = _Touch()
235
+ try:
236
+ _walk(shell.parse(cmd), [action.cwd or "/"], pset, home, touch, depth=0)
237
+ except (shell.ShellSyntaxError, ValueError, RecursionError):
238
+ touch.unresolved.append("syntax")
239
+ if touch.relation == paths.INSIDE:
240
+ return deny(why, step="")
241
+ for p in action.searches: # a shell-named tool's path fields
242
+ p = _expand_home(p, home)
243
+ full = p if p.startswith("/") else os.path.join(action.cwd or "/", p)
244
+ if any(paths.word_relation(v, [action.cwd or "/"], pset, glob=True) == paths.INSIDE
245
+ for v in paths.loose_variants(full)):
246
+ return deny(why, step="")
247
+ return ALLOWED if action.confined else _unresolved(touch, cfg)
248
+ # a file tool's paths, and the paths any tool names by its path fields (`searches`)
249
+ for p in tuple(action.paths) + tuple(action.searches):
250
+ p = _expand_home(p, home)
251
+ full = p if p.startswith("/") else os.path.join(action.cwd or "/", p)
252
+ for variant in paths.loose_variants(full):
253
+ if paths.word_relation(variant, [action.cwd or "/"], pset, glob=True) == paths.INSIDE:
254
+ return deny(why, step="")
255
+ return ALLOWED
256
+
257
+
258
+ # -- file tools ---------------------------------------------------------------------------------
259
+
260
+ _SETTINGS = ("settings.json", "settings.local.json")
261
+ _SETTINGS_FOLDED = tuple(n.casefold() for n in _SETTINGS)
262
+
263
+
264
+ def _guard_places(home: str, cfg: Optional[Config] = None) -> List[str]:
265
+ from phiward import claude_settings, config
266
+ places = config.guard_files() + [os.path.join(claude_settings.user_dir(home), n)
267
+ for n in _SETTINGS]
268
+ places += claude_settings.shell_code_paths(home) # what the shell runs before a command
269
+ if cfg is not None:
270
+ places += config.command_paths(cfg) # the operator's own scripts the gateway may run
271
+ for m in claude_settings.MANAGED:
272
+ places += [m, os.path.join(os.path.dirname(m), "managed-settings.d")]
273
+ # git's own config, which names programs git runs (Claude Code runs git outside its sandbox)
274
+ from phiward import config as _config
275
+ xdg = _config.xdg_config_home(home)
276
+ places += [os.path.join(home, ".gitconfig"), os.path.join(xdg, "git")]
277
+ # a launcher by the name the hook and the gateway are started by, in any PATH folder
278
+ for e in os.environ.get("PATH", "").split(":"):
279
+ if e.startswith("/"):
280
+ places += [os.path.join(e, "phiward"), os.path.join(e, "agent-guards")]
281
+ out: List[str] = []
282
+ for p in places:
283
+ for v in (os.path.normpath(p), os.path.realpath(p)):
284
+ if v not in out:
285
+ out.append(v)
286
+ return out
287
+
288
+
289
+
290
+
291
+ def _guard_index(home: str, cfg: Optional[Config] = None) -> "tuple":
292
+ """The guard places as `_writes_a_guard_file` compares them: (folded names, identities).
293
+ Built once for a tool call that names many paths."""
294
+ from phiward.pathid import fold
295
+ places = _guard_places(home, cfg)
296
+ return ([fold(g.rstrip("/")) for g in places],
297
+ {i for i in (pathid.identity(g) for g in places) if i is not None})
298
+
299
+
300
+ def _writes_a_guard_file(action: Action, home: str, cfg: Optional[Config] = None,
301
+ index: "Optional[tuple]" = None, memo: Optional[dict] = None) -> bool:
302
+ """Does a file tool write one of the files that control the guards? Compared as the file
303
+ system compares names (letter case and Unicode form on macOS), and by what the target is
304
+ (device and inode of it or of its nearest existing folder), so another spelling or another
305
+ name of the same file is caught too."""
306
+ from phiward.pathid import fold
307
+ folded, ids = index if index is not None else _guard_index(home, cfg)
308
+ for p in action.paths:
309
+ p = _expand_home(p, home)
310
+ raw = os.path.join(action.cwd or "/", p)
311
+ full = os.path.normpath(raw)
312
+ # `realpath` of the raw path resolves a link before the `..` after it, as the kernel
313
+ # does; `normpath` first would drop the link as text
314
+ kernel = os.path.realpath(raw)
315
+ from phiward import claude_settings
316
+ if claude_settings.claude_place(raw, home, _bases(action), memo=memo) == "settings":
317
+ return True # a Claude Code settings file, under a `.claude` by what it is
318
+ for v in (full, os.path.realpath(full), kernel, pathid.canon_new(kernel)):
319
+ parts = fold(v).split("/")
320
+ if len(parts) >= 2 and parts[-2] == ".claude" and parts[-1] in _SETTINGS_FOLDED:
321
+ return True # any project's Claude Code settings
322
+ if parts[-1] == ".mcp.json":
323
+ return True # an MCP server added there runs later
324
+ if ".git" in parts:
325
+ # git runs what its control files name (config, hooks, commondir, a `.git`
326
+ # file's gitdir): a file tool has no reason to write anything there
327
+ return True
328
+ fv = fold(v)
329
+ if any(fv == g or fv.startswith(g + "/") for g in folded):
330
+ return True
331
+ # the target, or the nearest folder of it that exists, is a guard file or folder
332
+ probe = kernel
333
+ while True:
334
+ i = pathid.identity(probe)
335
+ if i is not None:
336
+ if i in ids:
337
+ return True
338
+ break
339
+ parent = os.path.dirname(probe)
340
+ if parent == probe:
341
+ break
342
+ probe = parent
343
+ # and every folder above it: a new file inside a guarded folder
344
+ up = os.path.dirname(probe)
345
+ while up and up != "/":
346
+ if pathid.identity(up) in ids:
347
+ return True
348
+ nxt = os.path.dirname(up)
349
+ if nxt == up:
350
+ break
351
+ up = nxt
352
+ return False
353
+
354
+
355
+ # a file tool's write that only a person may let through: the reason for "ask" is shown to the
356
+ # person, the reason for a refusal to the agent
357
+ ASK_CODE = ("phiward: this file is run as code with your rights, outside the sandbox (a skill, "
358
+ "subagent, command, hook, plugin or workflow of Claude Code, or an editor's or git's "
359
+ "settings that name commands). Allow it only if you have read what the agent "
360
+ "writes.")
361
+ DENY_CODE = ("This file tool writes a file that is run as code (a skill, subagent, command, "
362
+ "hook, plugin or workflow of Claude Code, or an editor's or git's settings that name "
363
+ "commands), and this session cannot ask the operator: the operator "
364
+ "writes it, in their own editor.")
365
+ ASK_OUT = ("phiward: the agent writes outside the folders its sandbox may write (the project, "
366
+ "the temp folder, allowWrite). Allow it only if you expect it; to stop these prompts "
367
+ "for a folder, add it to permissions.additionalDirectories in your user settings.")
368
+ DENY_OUT = ("This file tool writes outside the folders the sandbox lets this session write: "
369
+ "write inside the project, or ask the operator to add the folder to "
370
+ "`permissions.additionalDirectories` in their user settings (a folder added with "
371
+ "`--add-dir` is not known to phiward).")
372
+ ASK_NAMED = ("phiward: an MCP server's tool names a file Claude Code runs as code with your "
373
+ "rights (a skill, subagent, command, hook, plugin or workflow), and may write it. "
374
+ "Allow it only if you know what this tool does with it.")
375
+ DENY_NAMED = ("This MCP tool names a file Claude Code runs as code (a skill, subagent, command, "
376
+ "hook, plugin or workflow), and may write it, and this session cannot ask the "
377
+ "operator: read the file with the Read tool instead.")
378
+ ASK_LINK = ("phiward: this file has another name (a hard link), which may be a file Claude "
379
+ "Code runs as code. Allow it only if you know what the other name is.")
380
+ DENY_LINK = ("This file tool writes a file that has another name (a hard link), which may be a "
381
+ "file Claude Code runs as code, and this session cannot ask the operator: give the "
382
+ "file a name of its own first (`cp FILE FILE.new && mv FILE.new FILE` in the "
383
+ "shell; the other name keeps its content), then write it.")
384
+
385
+
386
+ def _ask_or_deny(action: Action, ask: str, refuse: str) -> Decision:
387
+ """A prompt to the person where the session shows one (`can_ask`: a Claude Code payload in
388
+ a mode known to prompt), else a refusal."""
389
+ return Decision(ASK, ask, NAME) if action.can_ask else deny(refuse, step="")
390
+
391
+
392
+ def _bases(action: Action) -> List[str]:
393
+ return [b for b in (action.cwd, os.environ.get("CLAUDE_PROJECT_DIR")) if b]
394
+
395
+
396
+ def _writes_code(action: Action, home: str, memo: Optional[dict] = None) -> bool:
397
+ from phiward import claude_settings
398
+ for p in action.paths:
399
+ p = _expand_home(p, home)
400
+ full = os.path.join(action.cwd or "/", p)
401
+ if claude_settings.claude_place(full, home, _bases(action), memo=memo) == "code":
402
+ return True
403
+ if claude_settings.workspace_code(full):
404
+ return True
405
+ return False
406
+
407
+
408
+ def _another_name(action: Action, home: str) -> bool:
409
+ """Whether a file a file tool writes has another name (a hard link): that name may be a
410
+ settings or code file anywhere, which no rule here can see."""
411
+ for p in action.paths:
412
+ p = _expand_home(p, home)
413
+ try:
414
+ st = os.stat(os.path.join(action.cwd or "/", p)) # through a symlink too
415
+ except OSError:
416
+ continue
417
+ if stat.S_ISREG(st.st_mode) and st.st_nlink > 1:
418
+ return True
419
+ return False
420
+
421
+
422
+ def _writes_outside(action: Action, home: str) -> bool:
423
+ """Whether a file tool writes outside the folders the sandbox lets the shell write and the
424
+ folders where Claude Code keeps its memory and plans (`claude_settings.memory_places`):
425
+ compared as the file system compares names."""
426
+ import fnmatch
427
+ from phiward import claude_settings
428
+ project = os.environ.get("CLAUDE_PROJECT_DIR") or action.cwd or "/"
429
+ # a write place over start-up files (a session in the home folder) does not count: there a
430
+ # file tool asks or is refused (claude_settings.startup_write_problem)
431
+ roots = [pathid.fold(r).rstrip("/") for r in claude_settings.agent_writable(project, home)
432
+ if not claude_settings.startup_write_problem(r, home)]
433
+ mem = [pathid.fold(m).rstrip("/") for m in claude_settings.memory_places(home)]
434
+ for p in action.paths:
435
+ p = _expand_home(p, home)
436
+ full = os.path.realpath(os.path.join(action.cwd or "/", p))
437
+ v = pathid.fold(pathid.canon_new(full))
438
+ w = pathid.fold(full)
439
+ ok = any(x == r or x.startswith(r + "/") for x in (v, w) for r in roots if r)
440
+ ok = ok or any(fnmatch.fnmatchcase(x, m) or fnmatch.fnmatchcase(x, m + "/*")
441
+ for x in (v, w) for m in mem)
442
+ if not ok:
443
+ return True
444
+ return False
445
+
446
+
447
+ def _hidden_place(path: str) -> bool:
448
+ """Whether `path` is on the hidden list (credentials, histories), not a protected root."""
449
+ from phiward import hidden
450
+ real = os.path.realpath(path)
451
+ return any(pathid.inside(real, h) or pathid.inside(path, h)
452
+ for h in hidden.paths(session=True))
453
+
454
+
455
+ def _check_file(action: Action, pset: paths.ProtectedSet, home: str) -> Decision:
456
+ targets: Sequence[str] = action.paths or ((action.cwd,) if action.kind == FILE_SEARCH else ())
457
+ for p in targets:
458
+ p = _expand_home(p, home)
459
+ base = [action.cwd or "/"]
460
+ absolute = p if p.startswith("/") else os.path.join(base[0], p)
461
+ rel = None
462
+ for variant in paths.loose_variants(absolute): # braces, escapes, groups
463
+ rel = paths.worst(rel, paths.word_relation(variant, base, pset, glob=True))
464
+ if rel == paths.INSIDE:
465
+ if _hidden_place(absolute):
466
+ # the gateway cannot read the hidden list either: no gateway step
467
+ return deny("This file is a credential or a trace (a login, a key, a history) "
468
+ "that no session may read, and the gateway cannot read it either. "
469
+ "If the work needs it, stop and ask the operator.", step="")
470
+ return deny("This file tool names a protected path.")
471
+ if rel == paths.ABOVE and action.kind in (FILE_SEARCH, FILE_READ):
472
+ return deny("This file tool starts above a folder that holds protected data, so it "
473
+ "would reach it: give `path` a folder that holds no protected folder "
474
+ "(or a pattern that stays out of it).", step="")
475
+ return _check_text(action.text, pset, home)
476
+
477
+
478
+ _FILE_NAME = re.compile(r"[\w.-]+\.[A-Za-z0-9]{1,10}")
479
+
480
+
481
+ def _leads_inside(p: str, pset: paths.ProtectedSet, seen: Optional[dict] = None) -> bool:
482
+ """Whether a path, or the nearest folder of it that exists (a file not made yet), leads
483
+ inside a protected path once its links are followed. `seen`: the answers of this one tool
484
+ call, by that nearest existing path (many new files in one folder)."""
485
+ try:
486
+ q = os.path.abspath(p)
487
+ while not os.path.lexists(q) and os.path.dirname(q) != q:
488
+ q = os.path.dirname(q)
489
+ if seen is not None and q in seen:
490
+ return seen[q]
491
+ out = pset.relation(q) == paths.INSIDE
492
+ if seen is not None:
493
+ seen[q] = out
494
+ return out
495
+ except (OSError, ValueError):
496
+ return False
497
+
498
+
499
+ def _check_text(texts: Sequence[str], pset: paths.ProtectedSet, home: str,
500
+ cwd: Optional[str] = None, cfg: Optional[Config] = None,
501
+ ask: bool = False, tool: str = "") -> Decision:
502
+ """A protected path written in any of `texts`; also percent-decoded (a `file://` URL), and,
503
+ with `cwd` (a tool phiward does not otherwise read: an MCP tool), a whole string that is an
504
+ existing path, by where it really leads (`repo/leak.txt` linked into a root)."""
505
+ from urllib.parse import unquote, urlsplit
506
+ index = None # the guard places, built once (a call may name thousands of paths)
507
+ seen: dict = {}
508
+ memo: dict = {} # the Claude folders, found once per folder in this call
509
+ for t in dict.fromkeys(texts):
510
+ forms = [t]
511
+ if "%" in t:
512
+ forms.append(unquote(t))
513
+ for f in forms:
514
+ if pset.text_search(_expand_home_in_text(f, home)):
515
+ return deny("This tool call names a protected path.")
516
+ if cwd is None or len(t) > 4096 or not t.strip() or "\n" in t or "\0" in t:
517
+ continue
518
+ bases = list(dict.fromkeys(b for b in (cwd, os.environ.get("CLAUDE_PROJECT_DIR")) if b))
519
+ for f in dict.fromkeys(forms + [x.strip() for x in forms]):
520
+ web = False
521
+ if f.startswith("file:"):
522
+ f = unquote(urlsplit(f).path)
523
+ elif _URL.match(f):
524
+ # a web address may name `.mcp.json` (nothing here is written), unless it climbs
525
+ # above its host (`https://x/../../f`) or something named like its scheme
526
+ # (`https:`) is in the folder; it is always followed as a path, since a local
527
+ # server may join it to its folder, where `https:` may be a link
528
+ web = not _climbs(f) and not any(
529
+ os.path.lexists(os.path.join(b, f.split("/", 1)[0])) for b in bases)
530
+ # only what looks like a path (a `/`, `~`, or a file name with an extension): a plain
531
+ # word (`data`) is text, not a file
532
+ if "/" not in f and not f.startswith("~") and not _FILE_NAME.fullmatch(f):
533
+ continue
534
+ f = _expand_home(f, home)
535
+ for base in ([""] if f.startswith("/") else bases):
536
+ if _leads_inside(os.path.join(base, f) if base else f, pset, seen):
537
+ return deny("This tool call names a protected path (through a link).")
538
+ # a tool phiward cannot see into (an MCP server's) may write what it names: not
539
+ # the files that control the guards
540
+ if web:
541
+ continue
542
+ if index is None:
543
+ index = _guard_index(home, cfg)
544
+ probe = Action(FILE_WRITE, base or "/", paths=(f,))
545
+ if _writes_a_guard_file(probe, home, cfg, index, memo):
546
+ return deny("This tool call names a file that controls the guards (the "
547
+ "phiward config, code, status or session files, or the agent "
548
+ "tool's settings). Only the operator changes these.", step="")
549
+ if tool.startswith("mcp__") and _writes_code(probe, home, memo):
550
+ # an MCP server's tool may write what it names; Claude Code's own tools
551
+ # that are not file tools (Skill, LSP) read or run, and write nothing
552
+ return _ask_or_deny(replace(probe, can_ask=ask), ASK_NAMED, DENY_NAMED)
553
+ return ALLOWED
554
+
555
+
556
+ _URL = re.compile(r"(?i)(?:https?|wss?)://")
557
+
558
+
559
+ def _climbs(url: str) -> bool:
560
+ """Whether a web address climbs above its own host with `..` parts (`https://x/../../f`):
561
+ joined to a folder by a local server, it leads out of `https:/x`. `https://x/a/../f` stays
562
+ inside and is just a web address."""
563
+ parts = re.split(r"[/\\]", url)
564
+ if len(parts) > 2 and parts[2] in ("", ".", ".."):
565
+ return True # no host, or one that is itself a step (`https://../f`)
566
+ depth = 0
567
+ for part in parts[3:]: # after `scheme:`, ``, the host
568
+ if part == "..":
569
+ depth -= 1
570
+ if depth < 0:
571
+ return True
572
+ elif part not in ("", "."):
573
+ depth += 1
574
+ return False
575
+
576
+
577
+ def _expand_home(p: str, home: str) -> str:
578
+ if p == "~" or p.startswith("~/"):
579
+ p = home + p[1:]
580
+ return p.replace("${HOME}", home).replace("$HOME", home)
581
+
582
+
583
+ def _expand_home_in_text(t: str, home: str) -> str:
584
+ t = t.replace("${HOME}", home).replace("$HOME", home)
585
+ return re.sub(r"(^|[\s=:'\"(])~(?=/|$|[\s'\"])", lambda m: m.group(1) + home, t)
586
+
587
+
588
+ # -- shell --------------------------------------------------------------------------------------
589
+
590
+ def _check_shell(action: Action, cfg: Config, pset: paths.ProtectedSet, home: str) -> Decision:
591
+ cmd = action.command
592
+ if gateway.is_operator_command(cmd):
593
+ return deny("`phiward setup`, `pin`, `carryover` and `broker` are the operator's once "
594
+ "phiward is set up: ask the operator to run it in their own terminal.",
595
+ step="")
596
+ call = gateway.parse_call(cmd)
597
+ if call is not None:
598
+ if not action.confined and _has_unquoted_glob(cmd):
599
+ # the agent's own shell would expand it: the names would sit in the request, in the
600
+ # spool, which the agent can read
601
+ return deny("A gateway call may not hold an unquoted wildcard inside a protected "
602
+ "path: this shell would list the names. Let the gateway expand it: "
603
+ "`phiward run -- sh -c 'CMD /protected/*'`.", step="")
604
+ return _check_gateway(call)
605
+ if _writes_claude_settings(cmd):
606
+ return deny("This command writes Claude Code settings (`.claude/settings*.json`) or the "
607
+ "MCP config (`.mcp.json`). Only the operator changes these.", step="")
608
+ if action.confined:
609
+ pset.fail_closed = False # the kernel decides about paths the walk cannot resolve
610
+ pset.mode = "confined" if action.confined else "shell"
611
+ touch = _Touch()
612
+ parsed: Optional[shell.Parsed]
613
+ try:
614
+ parsed = shell.parse(cmd)
615
+ except (shell.ShellSyntaxError, ValueError, RecursionError):
616
+ parsed = None
617
+ if pset.text_search(_expand_home_in_text(cmd, home)):
618
+ touch.add(paths.INSIDE)
619
+ if parsed is None:
620
+ touch.unresolved.append("syntax")
621
+ touch.add(pset.relation(action.cwd or "/"))
622
+ else:
623
+ _walk(parsed, [action.cwd or "/"], pset, home, touch, depth=0)
624
+
625
+ if touch.relation == paths.INSIDE:
626
+ return deny("This command names a protected path.")
627
+ if action.confined:
628
+ return ALLOWED # the kernel denies whatever the text missed
629
+ if touch.relation == paths.ABOVE:
630
+ return deny("This command runs in, or names, a folder that holds protected data, so a "
631
+ "listing or a recursive search from there reaches it (this tool's shell is "
632
+ "not sandboxed, so the guard must refuse it).")
633
+ return _unresolved(touch, cfg)
634
+
635
+
636
+ # what makes a command unresolved besides a variable's name (`_walk`)
637
+ _REASONS = {"syntax": "text the guard cannot parse",
638
+ "group": "a zsh or extglob group (`(a|b)`, `@(a)`)",
639
+ "built": "a path built from `$(...)`, backticks, `$'...'` or variables the command "
640
+ "sets",
641
+ "dotdot": "`..` after a folder that does not exist yet",
642
+ "moved": "`cd -`, `popd` or `~-` (a folder the guard does not know)",
643
+ "fresh": "a path through a link or folder the command makes",
644
+ "lookup": "a change to how bash finds commands or folders (`PATH`, `CDPATH`, "
645
+ "`HOME`, `hash`, `shopt`, ...)"}
646
+
647
+
648
+ def _unresolved(touch: "_Touch", cfg: Config) -> Decision:
649
+ """The decision for what the guard could not see, by `cfg.unresolved` (deny by default)."""
650
+ if not touch.unresolved or cfg.unresolved == ALLOW:
651
+ return ALLOWED
652
+ names = sorted({u for u in touch.unresolved if u not in _REASONS})
653
+ what = [_REASONS[r] for r in _REASONS if r in touch.unresolved]
654
+ if names:
655
+ what.insert(0, "variables the guard cannot see (" + ", ".join("$" + n for n in names)
656
+ + ")")
657
+ reason = (f"This command uses {' and '.join(what)}, so the guard cannot tell whether it "
658
+ "reaches protected data. Write the paths out in full.")
659
+ return Decision(ASK if cfg.unresolved == ASK else DENY, reason, NAME)
660
+
661
+
662
+ def _has_unquoted_glob(cmd: str) -> bool:
663
+ try:
664
+ parsed = shell.parse(cmd)
665
+ except (shell.ShellSyntaxError, ValueError, RecursionError):
666
+ return True
667
+ # any unquoted wildcard or brace: the agent's own shell expands it before the request is
668
+ # written, and a link in the project can lead the expansion into a protected root, whose
669
+ # names would then sit in the request (a prefix check cannot see through the link)
670
+ for w in parsed.items:
671
+ if isinstance(w, shell.Word) and (w.has_glob or w.has_brace):
672
+ return True
673
+ return False
674
+
675
+
676
+ _SETTINGS_NAME = re.compile(r"(^|/)\.claude/settings(\.local)?\.json$|managed-settings|"
677
+ r"(^|/)\.mcp\.json$", re.I)
678
+ _SETTINGS_TEXT = re.compile(r"settings(\.local)?\.json|managed-settings|\.mcp\.json", re.I)
679
+ # programs that write the files their arguments name
680
+ _WRITERS = {"cp", "mv", "tee", "ln", "rm", "install", "truncate", "touch", "rsync", "dd", "chmod",
681
+ "unlink", "patch"}
682
+ _INPLACE = {"sed": "-i", "perl": "-i", "gsed": "-i"}
683
+
684
+
685
+ def _writes_claude_settings(cmd: str) -> bool:
686
+ """A shell command that writes a Claude Code settings file: a redirection into one, or a
687
+ writing program (cp, mv, tee, dd of=, sed -i, git checkout/restore, an interpreter's code)
688
+ that names one, after quotes are removed (`sett""ings.json` passed a text
689
+ match, and `grep … 2>/dev/null` was refused). A name built from variables, or reached after
690
+ `cd .claude`, is not seen: in a project wired with `install --project`, Claude Code's
691
+ sandbox denies the write itself."""
692
+ if not _SETTINGS_TEXT.search(cmd.replace('"', "").replace("'", "")):
693
+ return False
694
+ try:
695
+ parsed = shell.parse(cmd)
696
+ except (shell.ShellSyntaxError, ValueError, RecursionError):
697
+ return True # cannot tell: refuse
698
+ words: List[str] = []
699
+
700
+ def simple_command_writes(ws: List[str]) -> bool:
701
+ if not ws:
702
+ return False
703
+ prog = ws[0].rsplit("/", 1)[-1]
704
+ if prog.startswith(("python", "node", "ruby", "perl", "bash", "sh", "zsh")) and \
705
+ not (prog in _INPLACE and any(w.startswith(_INPLACE[prog]) for w in ws[1:])):
706
+ # code that names the file anywhere: it may write it
707
+ return any(_SETTINGS_TEXT.search(w) and (".claude" in w or ".mcp.json" in w)
708
+ for w in ws[1:])
709
+ names = [w for w in ws[1:] if _SETTINGS_NAME.search(w.split("=", 1)[-1])]
710
+ if not names:
711
+ return False
712
+ if prog in _WRITERS:
713
+ return prog != "dd" or any(w.startswith("of=") and _SETTINGS_NAME.search(w[3:])
714
+ for w in ws)
715
+ if prog in _INPLACE and any(w.startswith(_INPLACE[prog]) for w in ws[1:]):
716
+ return True
717
+ if prog == "git" and len(ws) > 1 and ws[1] in ("checkout", "restore", "apply", "stash"):
718
+ return True
719
+ return False
720
+
721
+ for it in parsed.items:
722
+ if isinstance(it, shell.Op):
723
+ if it.target is not None and it.text.rstrip("&").endswith(">") and \
724
+ _SETTINGS_NAME.search(it.target.text()):
725
+ return True
726
+ if not it.is_redirect:
727
+ if simple_command_writes(words):
728
+ return True
729
+ words = []
730
+ else:
731
+ words.append(it.text())
732
+ return simple_command_writes(words)
733
+
734
+
735
+ def _check_gateway(call: "gateway.Call") -> Decision:
736
+ if call.name == "copy":
737
+ if len([a for a in call.args if a != "--dry-run"]) < 2:
738
+ return deny("`phiward copy` needs a source and a destination.", step="")
739
+ return ALLOWED
740
+ from phiward import run
741
+ a = run.parse(call.args)
742
+ if a is None:
743
+ return deny("`phiward run` must be written as `phiward run [--write-to DIR]... "
744
+ "[--net] [--names-from FILE]... [--table] -- CMD [ARG]...`.", step="")
745
+ return ALLOWED # grants: the broker checks them against the user config
746
+
747
+
748
+ def _walk(parsed: shell.Parsed, cwds: List[str], pset: paths.ProtectedSet, home: str,
749
+ touch: _Touch, depth: int) -> None:
750
+ if depth > MAX_DEPTH:
751
+ touch.unresolved.append("syntax")
752
+ touch.add(paths.ABOVE)
753
+ return
754
+ env = dict(os.environ)
755
+ env["HOME"] = home
756
+ env["PWD"] = cwds[0] # the command's own folder, not the hook's
757
+ env.pop("OLDPWD", None)
758
+ unconfined = pset.mode != "confined"
759
+ bound = shell.bound_names(parsed)
760
+ words = parsed.words()
761
+ cmds = _commands(parsed)
762
+ where = _folders(parsed, cmds, cwds, env, bound, home)
763
+ if where.moved:
764
+ touch.unresolved.append("moved")
765
+ if unconfined and parsed.groups:
766
+ touch.unresolved.append("group")
767
+ for b in where.union:
768
+ touch.add(paths.word_relation(b, [], pset, glob=isinstance(b, paths.GlobBase)))
769
+ made = _made_names(cmds, words)
770
+ if unconfined and _changes_lookup(cmds, words):
771
+ touch.unresolved.append("lookup")
772
+ makes_links = any(c.words and c.words[0].text().rsplit("/", 1)[-1] == "ln" for c in cmds)
773
+ plain_text = depth == 0 and not _redefines_commands(parsed, cmds)
774
+ for i, (cmd, in_folders, from_start) in enumerate(zip(cmds, where.per_command,
775
+ where.started)):
776
+ # `echo` and `printf` print text, not paths: only at the top of a line that redefines
777
+ # no command, and when their output does not go on to another command (a pipe)
778
+ piped = cmd.sep in ("|", "|&") or (i + 1 < len(cmds) and cmds[i + 1].sep in ("|", "|&"))
779
+ text_only = plain_text and not piped and bool(cmd.words) and \
780
+ cmd.words[0].text() in ("echo", "printf")
781
+ for w in cmd.all:
782
+ bases = from_start if id(w) in where.option_values else in_folders
783
+ if shell.ASSIGNMENT.match(w.text()) and w.text().startswith("IFS="):
784
+ continue # a field separator, not a path
785
+ if not where.changed:
786
+ w = _pwd_as_variable(w)
787
+ values, unknown = shell.expand(w, env, bound, home)
788
+ text = text_only and not w.redirect_target
789
+ if unknown and not text:
790
+ touch.unresolved.extend([n for k, n, _ in w.segs if (k == "varx" or k == "var" and
791
+ n not in env and n not in bound)] or ["moved"])
792
+ if unconfined and not text and _built(w, bound, made):
793
+ # without the sandbox the text is all the guard sees: a word it cannot read
794
+ # whole is unresolved (docs/threat-model.md, "The hook: a first layer")
795
+ touch.unresolved.append("built")
796
+ if unconfined and where.changed:
797
+ # $PWD is the command's folder; after a `cd` in the line it may be another
798
+ touch.unresolved.extend(n for k, n, _ in w.segs
799
+ if k == "var" and n in ("PWD", "OLDPWD"))
800
+ for v in _variants(values, w):
801
+ if not v:
802
+ continue
803
+ full = paths.candidates(v, bases)
804
+ if unconfined and any(_dotdot_after_missing(f) for f in full):
805
+ touch.unresolved.append("dotdot")
806
+ if unconfined and makes_links and any(_through_missing(f) for f in full):
807
+ touch.unresolved.append("fresh")
808
+ touch.add(paths.word_relation(v, bases, pset, glob=w.has_glob))
809
+ for inner in _shell_text(cmd, parsed, env, bound, home):
810
+ _walk_text(inner, in_folders, pset, home, touch, depth)
811
+ for name in parsed.vars - set(env) - bound:
812
+ # variables used in heredocs and ${...} parts
813
+ if not any(n == name for w in words for k, n, _ in w.segs if k in ("var", "varx")):
814
+ touch.unresolved.append(name)
815
+ for inner in parsed.subs:
816
+ _walk_text(inner, where.union, pset, home, touch, depth)
817
+
818
+
819
+ def _walk_text(text: str, bases: List[str], pset: paths.ProtectedSet, home: str,
820
+ touch: _Touch, depth: int) -> None:
821
+ """Shell text inside the command (`$(...)`, `bash -c '...'`, `eval`), checked as a
822
+ command run in `bases`."""
823
+ try:
824
+ inner = shell.parse(text)
825
+ except (shell.ShellSyntaxError, ValueError, RecursionError):
826
+ touch.unresolved.append("syntax")
827
+ return
828
+ _walk(inner, bases, pset, home, touch, depth + 1)
829
+
830
+
831
+ _SHELLS = {"sh", "bash", "zsh", "dash", "ksh"}
832
+
833
+
834
+ def _shell_text(cmd: "_Cmd", parsed: shell.Parsed, env: Mapping[str, str], bound: Set[str],
835
+ home: str) -> List[str]:
836
+ """Shell code a command runs from a string: the argument after `-c` of a shell, the words
837
+ of `eval`, and the heredocs a shell without `-c` reads."""
838
+ if not cmd.words:
839
+ return []
840
+ prog = cmd.words[0].text().rsplit("/", 1)[-1]
841
+ args = cmd.words[1:]
842
+
843
+ def value(w: shell.Word) -> str:
844
+ return " ".join(shell.expand(w, env, bound, home)[0])
845
+ if prog == "eval":
846
+ return [" ".join(value(a) for a in args)] if args else []
847
+ if prog not in _SHELLS:
848
+ return []
849
+ for i, a in enumerate(args):
850
+ t = a.text()
851
+ if t.startswith("-") and not t.startswith("--") and "c" in t[1:]:
852
+ return [value(args[i + 1])] if i + 1 < len(args) else []
853
+ return list(parsed.heredocs)
854
+
855
+
856
+ def _pwd_as_variable(w: shell.Word) -> shell.Word:
857
+ """`$(pwd)` as `$PWD`: the command's folder, when the line does not change folder."""
858
+ if not any(k == "sub" and t.strip() in _PWD_COMMANDS for k, t, _ in w.segs):
859
+ return w
860
+ segs = [("var", "PWD", q) if k == "sub" and t.strip() in _PWD_COMMANDS else (k, t, q)
861
+ for k, t, q in w.segs]
862
+ return shell.Word(w.raw, segs, w.has_glob, w.has_brace, w.has_sub, w.has_dollar,
863
+ w.redirect_target)
864
+
865
+
866
+ _PWD_COMMANDS = {"pwd", "pwd -P", "pwd -L", "/bin/pwd"}
867
+
868
+
869
+ def _redefines_commands(parsed: shell.Parsed, cmds: List["_Cmd"]) -> bool:
870
+ """Whether the line defines a function (`name()`, `function name`), or uses `alias` or
871
+ `enable`: then `echo` may not be the shell's own."""
872
+ items = parsed.items
873
+ if any(isinstance(a, shell.Op) and a.text == "(" and isinstance(b, shell.Op) and
874
+ b.text == ")" for a, b in zip(items, items[1:])):
875
+ return True
876
+ return any(w.text() in ("function", "alias", "enable", "unalias") for c in cmds
877
+ for w in c.words[:1])
878
+
879
+
880
+ # what bash reads to find a command or a folder: a line that sets one (by any means), or runs a
881
+ # builtin that changes the lookup, makes every later name in it mean something the text does not
882
+ # say (`printf -v CDPATH ..; cd phi`, `printf -v PATH ...; cat x`, `shopt -s cdable_vars`)
883
+ LOOKUP_NAMES = frozenset({"PATH", "CDPATH", "HOME", "BASH_ENV", "ENV", "GLOBIGNORE", "BASHOPTS",
884
+ "SHELLOPTS", "PWD", "OLDPWD", "BASH_CMDS", "BASH_ALIASES", "FIGNORE"})
885
+ LOOKUP_BUILTINS = frozenset({"hash", "enable", "shopt", "alias"})
886
+ _SETTERS = frozenset({"export", "declare", "typeset", "local", "readonly", "read", "mapfile",
887
+ "readarray", "printf"})
888
+
889
+
890
+ def _changes_lookup(cmds: List["_Cmd"], words: List[shell.Word]) -> bool:
891
+ """Whether the line sets a LOOKUP_NAMES variable or runs a LOOKUP_BUILTINS builtin."""
892
+ for w in words:
893
+ m = shell.ASSIGNMENT.match(w.text())
894
+ if m and m.group(1) in LOOKUP_NAMES:
895
+ return True
896
+ for c in cmds:
897
+ ws = [w.text() for w in c.words]
898
+ if not ws:
899
+ continue
900
+ if ws[0] in LOOKUP_BUILTINS:
901
+ return True
902
+ if ws[0] in _SETTERS:
903
+ # a name as its own word (`read PATH`, `export CDPATH`), or after a `-v` cluster
904
+ # (`printf -vPATH`)
905
+ for t in ws[1:]:
906
+ name = t[2:] if t.startswith("-v") and len(t) > 2 else t
907
+ if name in LOOKUP_NAMES:
908
+ return True
909
+ return False
910
+
911
+
912
+ def _made_names(cmds: List["_Cmd"], words: List[shell.Word]) -> Set[str]:
913
+ """Variables whose value is put together over several steps: more than one assignment,
914
+ `+=`, `printf -v`, `read`, `mapfile`."""
915
+ count: Dict[str, int] = {}
916
+ made: Set[str] = set()
917
+ for w in words:
918
+ m = shell.ASSIGNMENT.match(w.text())
919
+ if m:
920
+ count[m.group(1)] = count.get(m.group(1), 0) + 1
921
+ if w.text()[:m.end()].endswith("+="):
922
+ made.add(m.group(1))
923
+ made |= {n for n, c in count.items() if c > 1}
924
+ for c in cmds:
925
+ ws = [w.text() for w in c.words]
926
+ if not ws:
927
+ continue
928
+ if ws[0] == "printf" and "-v" in ws[1:-1]:
929
+ made.add(ws[ws.index("-v", 1) + 1])
930
+ elif ws[0] in ("read", "mapfile", "readarray"):
931
+ made |= {t for t in ws[1:] if shell.NAME.fullmatch(t)}
932
+ return made
933
+
934
+
935
+ def _built(w: shell.Word, bound: AbstractSet[str], made: AbstractSet[str]) -> bool:
936
+ """Whether a word's path is put together at run time from parts the guard does not see:
937
+ `$'...'` (escapes); a variable whose value is made over several steps (`made`); or text
938
+ from `$(...)`, backticks, a special parameter (`$1`, `$_`, `${1:-x}`, `$((...))`) or a
939
+ variable the command sets, joined to anything else. A word that is exactly one `$(...)`
940
+ is not: its command is checked, and a command that prints a path is the interpreter case
941
+ the threat model accepts."""
942
+ segs: List[Tuple[str, str]] = []
943
+ for k, n, _ in w.segs: # literal text joined (the lexer keeps it in pieces)
944
+ if k == "lit" and segs and segs[-1][0] == "lit":
945
+ segs[-1] = ("lit", segs[-1][1] + n)
946
+ elif k != "lit" or n:
947
+ segs.append((k, n))
948
+ if segs and segs[0][0] == "lit": # `X=$(...)`: the value after `=` counts, not the name
949
+ m = shell.ASSIGNMENT.match(segs[0][1])
950
+ if m:
951
+ rest = segs[0][1][m.end():]
952
+ segs = ([("lit", rest)] if rest else []) + segs[1:]
953
+ if any(k == "ansi" or (k == "var" and n in made) for k, n in segs):
954
+ return True
955
+ mixed = [k for k, n in segs if k in ("sub", "special") or (k == "var" and n in bound)]
956
+ return bool(mixed) and len(segs) > 1
957
+
958
+
959
+ def _dotdot_after_missing(path: str) -> bool:
960
+ """Whether a `..` in `path` follows a folder that does not exist now: the command may make
961
+ it (a link, as in `ln -s x s && cat s/../..`), and the kernel would then resolve the `..`
962
+ from where that link points."""
963
+ prefix = "/"
964
+ for c in path.split("/"):
965
+ if not c:
966
+ continue
967
+ if c == ".." and not os.path.lexists(prefix):
968
+ return True
969
+ prefix = os.path.join(prefix, c)
970
+ return False
971
+
972
+
973
+ def _variants(values: List[str], w: shell.Word) -> List[str]:
974
+ """Every spelling of a word to check: the word, its brace expansions, and the parts after
975
+ `=` and `:` (as in `--file=PATH` and `host:PATH`)."""
976
+ out: List[str] = []
977
+ for v in values:
978
+ forms = [v]
979
+ if w.has_brace:
980
+ try:
981
+ forms += paths.expand_braces(v)
982
+ except ValueError:
983
+ forms.append("/") # too many: count it as touching everything
984
+ for f in forms:
985
+ out.append(f)
986
+ if f.startswith("-") and not f.startswith("--") and len(f) > 2:
987
+ out.append(f[2:]) # a glued option value, as in -C../x or -o/path
988
+ for sep in ("=", ":"):
989
+ if sep in f:
990
+ out.extend(part for part in f.split(sep)[1:] if part)
991
+ return out
992
+
993
+
994
+ _SEPARATORS = {";", "&&", "||", "|", "|&", "&", "\n", "(", ")", ";;"}
995
+ _SEQUENCE = {"", ";", "&&", "\n"} # each step runs after the one before, in its folder
996
+ # words before a command that are not the command: reserved words, groups and prefixes
997
+ _KEYWORDS = {"{", "}", "!", "if", "then", "elif", "else", "fi", "do", "done", "while", "until",
998
+ "time", "command", "builtin", "exec", "nohup"}
999
+ _FOLDER_CHANGE = ("cd", "pushd", "popd")
1000
+ # programs that run in a folder an option names
1001
+ _FOLDER_OPTIONS = {"git": ("-C",), "make": ("-C", "--directory"), "tar": ("-C", "--directory"),
1002
+ "env": ("-C", "--chdir")}
1003
+
1004
+
1005
+ class _Cmd(NamedTuple):
1006
+ words: List[shell.Word] # from the command word on (keywords, assignments left out)
1007
+ all: List[shell.Word] # every word, redirection targets too
1008
+ sep: str # the operator before it
1009
+ keyword: bool # it started with a keyword or a group
1010
+
1011
+
1012
+ def _commands(parsed: shell.Parsed) -> List[_Cmd]:
1013
+ """The simple commands of a parsed line, in order."""
1014
+ out: List[_Cmd] = []
1015
+ words: List[shell.Word] = []
1016
+ every: List[shell.Word] = []
1017
+ sep, keyword = "", False
1018
+ for it in parsed.items:
1019
+ if isinstance(it, shell.Op):
1020
+ if it.text in _SEPARATORS:
1021
+ if every:
1022
+ out.append(_Cmd(words, every, sep, keyword))
1023
+ words, every, sep, keyword = [], [], it.text, it.text in ("(", ")")
1024
+ elif it.target is not None:
1025
+ every.append(it.target)
1026
+ continue
1027
+ every.append(it)
1028
+ t = it.text()
1029
+ if not words and not it.has_dollar and t in _KEYWORDS:
1030
+ keyword = True
1031
+ elif words or not shell.ASSIGNMENT.match(t):
1032
+ words.append(it)
1033
+ if every:
1034
+ out.append(_Cmd(words, every, sep, keyword))
1035
+ return out
1036
+
1037
+
1038
+ class _Folders(NamedTuple):
1039
+ per_command: List[List[str]] # the folders each command may run in
1040
+ started: List[List[str]] # the same before its own `-C` options: where their values are read
1041
+ option_values: Set[int] # the words that are such values (by id)
1042
+ union: List[str] # every folder the line may run in
1043
+ moved: bool # it may run in a folder the guard cannot know
1044
+ changed: bool # it changes folder at all
1045
+
1046
+
1047
+ def _folders(parsed: shell.Parsed, cmds: List[_Cmd], cwds: List[str], env: Mapping[str, str],
1048
+ bound: Set[str], home: str) -> _Folders:
1049
+ """The folders each command may run in. A line of plain steps (`;`, `&&`, new lines, no
1050
+ group or keyword) follows its `cd`s in order; any other line may run every command in
1051
+ every folder it names. `cd` with no folder, or only `--`, is the home folder; `cd -`,
1052
+ `popd`, `pushd` without a folder, a folder built from variables, `find -execdir` and a
1053
+ `cd` word the guard does not read as a command mean a folder the guard cannot know."""
1054
+ linear = all(c.sep in _SEQUENCE and not c.keyword for c in cmds) and \
1055
+ not any(isinstance(it, shell.Op) and it.text in ("(", ")") for it in parsed.items)
1056
+ current, union = list(cwds), list(cwds)
1057
+ per: List[List[str]] = []
1058
+ started: List[List[str]] = []
1059
+ values: Set[int] = set()
1060
+ moved = changed = False
1061
+ command_words = {id(c.words[0]) for c in cmds if c.words}
1062
+ for w in parsed.words():
1063
+ if w.text() in _FOLDER_CHANGE and not w.has_dollar and id(w) not in command_words:
1064
+ moved = True # `cd` where the guard does not see a command
1065
+ for c in cmds:
1066
+ here = list(current)
1067
+ new: Optional[List[str]] = None
1068
+ prog = c.words[0] if c.words else None
1069
+ name = prog.text().rsplit("/", 1)[-1] if prog else ""
1070
+ args = c.words[1:]
1071
+ if prog is not None and not prog.has_dollar and name in _FOLDER_CHANGE:
1072
+ changed = True
1073
+ targets = [a for a in args if a.text() == "-" or not a.text().startswith("-")]
1074
+ if name == "popd" or (name == "pushd" and not targets) or \
1075
+ (targets and targets[0].text() == "-"):
1076
+ moved = True
1077
+ elif not targets:
1078
+ new = [home]
1079
+ else:
1080
+ new, unknown = _targets(targets[0], here, env, bound, home)
1081
+ moved = moved or unknown
1082
+ elif name in _FOLDER_OPTIONS:
1083
+ for i, a in enumerate(args):
1084
+ t = a.text()
1085
+ for opt in _FOLDER_OPTIONS[name]:
1086
+ target = args[i + 1] if t == opt and i + 1 < len(args) else None
1087
+ if target is None and t.startswith(opt + "=") and opt.startswith("--"):
1088
+ target = shell.Word(a.raw, [("lit", t[len(opt) + 1:], False)])
1089
+ if target is not None:
1090
+ changed = True
1091
+ values.add(id(target) if t == opt else id(a)) # `-C dir`, `--directory=dir`
1092
+ dirs, unknown = _targets(target, here, env, bound, home)
1093
+ moved = moved or unknown
1094
+ here += [d for d in dirs or [] if d not in here]
1095
+ union += [d for d in dirs or [] if d not in union]
1096
+ elif name == "find" and any(a.text() in ("-execdir", "-okdir") for a in args):
1097
+ moved = True # it runs in the folder of every file it finds
1098
+ per.append(here)
1099
+ started.append(list(current))
1100
+ if new is not None:
1101
+ current = new if linear else current + [b for b in new if b not in current]
1102
+ union += [b for b in new if b not in union]
1103
+ if not linear:
1104
+ per = started = [union] * len(cmds)
1105
+ return _Folders(per, started, values, union, moved, changed)
1106
+
1107
+
1108
+ def _targets(target: shell.Word, bases: List[str], env: Mapping[str, str], bound: Set[str],
1109
+ home: str) -> Tuple[Optional[List[str]], bool]:
1110
+ """The folders a `cd` (or `-C`) target names, and whether it is unknown. A target that is
1111
+ exactly one `$(...)` leaves the folders as they are (its command is checked); one built
1112
+ from variables or special parameters is unknown."""
1113
+ segs = [(k, n) for k, n, _ in target.segs if k != "lit" or n]
1114
+ if [k for k, _ in segs] == ["sub"]:
1115
+ return None, False
1116
+ values, unknown = shell.expand(target, env, bound, home)
1117
+ if unknown or any(k in ("sub", "special", "varx", "ansi") or (k == "var" and n in bound)
1118
+ for k, n in segs):
1119
+ return None, True
1120
+ out: List[str] = []
1121
+ for v in _variants(values, target):
1122
+ found = paths.candidates(v or home, bases)
1123
+ # a glob target stays a pattern: the folders it names are not listed
1124
+ out += [paths.GlobBase(f) for f in found] if target.has_glob else found
1125
+ return out, False
1126
+
1127
+
1128
+ def _through_missing(path: str) -> bool:
1129
+ """Whether a path goes through a name that does not exist now (a link or folder the line
1130
+ may make, which the kernel would then follow)."""
1131
+ prefix = "/"
1132
+ for c in [c for c in path.split("/") if c][:-1]:
1133
+ prefix = os.path.join(prefix, c)
1134
+ if c not in (".", "..") and not os.path.lexists(prefix):
1135
+ return True
1136
+ return False
1137
+
1138
+