kneepad 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.
kneepad/winshell.py ADDED
@@ -0,0 +1,634 @@
1
+ """Windows command analysis: cmd.exe and PowerShell tokenising, path classification, delete handling.
2
+
3
+ The POSIX lexer in shellparse.py treats a backslash as an escape, so `C:\\Windows` becomes
4
+ `C:Windows`. This module reads the same text with Windows rules instead and feeds the same
5
+ engine. It runs on every command string (see Analyzer._walk), so it also works on Linux and
6
+ macOS when an agent shells out to pwsh or cmd.
7
+
8
+ Honest limits: this is a tokenizer plus pattern rules, not a PowerShell parser. Script blocks,
9
+ variables set in earlier statements and aliases defined by the user are not resolved. Anything
10
+ that cannot be resolved is treated as dynamic and, when it feeds a recursive delete, asked about.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import binascii
17
+ import glob
18
+ import ntpath
19
+ import os
20
+ import re
21
+ from typing import Dict, List, Optional, Tuple
22
+
23
+ from .argvtools import ParsedArgv, parse_argv
24
+ from .rules import match_argv
25
+ from .shellparse import Word
26
+ from .snapshots import SnapshotPlan, estimate_size
27
+
28
+ _DRIVE = re.compile(r"^[A-Za-z]:(?:[\\/]|$)")
29
+ _EXTS = (".exe", ".cmd", ".bat", ".com", ".ps1", ".vbs", ".msc")
30
+
31
+
32
+ def looks_windows(p: str) -> bool:
33
+ return bool(_DRIVE.match(p)) or p.startswith("\\\\")
34
+
35
+
36
+ def has_marker(text: str) -> bool:
37
+ """True when a token carries Windows path or variable syntax the POSIX lexer would mangle."""
38
+ return bool(
39
+ "\\" in text
40
+ or re.search(r"%[A-Za-z_]\w*%", text)
41
+ or re.search(r"(?i)\$env:|\$\{env:", text)
42
+ or _DRIVE.match(text)
43
+ )
44
+
45
+
46
+ def win_name(tok: str) -> str:
47
+ base = tok.replace("/", "\\").rstrip("\\").rsplit("\\", 1)[-1].lower()
48
+ for ext in _EXTS:
49
+ if base.endswith(ext):
50
+ return base[: -len(ext)]
51
+ return base
52
+
53
+
54
+ # --------------------------------------------------------------------------- tokenising
55
+ class Tok:
56
+ __slots__ = ("text", "quoted")
57
+
58
+ def __init__(self, text: str, quoted: bool) -> None:
59
+ self.text = text
60
+ self.quoted = quoted
61
+
62
+
63
+ def tokenize(text: str) -> List[Tuple[List[Tok], bool]]:
64
+ """Split into simple commands: list of (tokens, fed_by_pipe)."""
65
+ cmds: List[Tuple[List[Tok], bool]] = []
66
+ cur: List[Tok] = []
67
+ buf: List[str] = []
68
+ have = False
69
+ tq = False
70
+ quote: Optional[str] = None
71
+ pipe_in = False
72
+ n = len(text)
73
+ i = 0
74
+
75
+ def flush() -> None:
76
+ nonlocal buf, have, tq
77
+ if have:
78
+ cur.append(Tok("".join(buf), tq))
79
+ buf, have, tq = [], False, False
80
+
81
+ def end_cmd(next_pipe: bool) -> None:
82
+ nonlocal cur, pipe_in
83
+ flush()
84
+ if cur:
85
+ cmds.append((cur, pipe_in))
86
+ cur = []
87
+ pipe_in = next_pipe
88
+
89
+ while i < n:
90
+ c = text[i]
91
+ if quote:
92
+ if c == quote:
93
+ if i + 1 < n and text[i + 1] == quote:
94
+ buf.append(c)
95
+ i += 2
96
+ continue
97
+ quote = None
98
+ i += 1
99
+ continue
100
+ if quote == '"' and c == "`" and i + 1 < n:
101
+ buf.append(text[i + 1])
102
+ i += 2
103
+ continue
104
+ buf.append(c)
105
+ i += 1
106
+ continue
107
+ if c in "\"'":
108
+ quote, have, tq = c, True, True
109
+ i += 1
110
+ continue
111
+ if c == "`" and i + 1 < n:
112
+ if text[i + 1] in "\r\n":
113
+ i += 2
114
+ continue
115
+ buf.append(text[i + 1])
116
+ have = True
117
+ i += 2
118
+ continue
119
+ if c == "^" and i + 1 < n:
120
+ buf.append(text[i + 1])
121
+ have = True
122
+ i += 2
123
+ continue
124
+ if c in " \t":
125
+ flush()
126
+ i += 1
127
+ continue
128
+ if c in "<>":
129
+ prefix = ""
130
+ if have and not tq and "".join(buf).isdigit(): # 2> and 1>
131
+ prefix = "".join(buf)
132
+ buf, have = [], False
133
+ flush()
134
+ j = i + 1
135
+ while j < n and text[j] == ">":
136
+ j += 1
137
+ if j < n - 1 and text[j] == "&" and (text[j + 1].isdigit() or text[j + 1] == "-"): # 2>&1
138
+ j += 2
139
+ cur.append(Tok(prefix + text[i:j], False))
140
+ i = j
141
+ continue
142
+ if c == "|":
143
+ if i + 1 < n and text[i + 1] == "|":
144
+ end_cmd(False)
145
+ i += 2
146
+ else:
147
+ end_cmd(True)
148
+ i += 1
149
+ continue
150
+ if c in ";&\n\r(){}":
151
+ end_cmd(False)
152
+ i += 1
153
+ continue
154
+ buf.append(c)
155
+ have = True
156
+ i += 1
157
+ end_cmd(False)
158
+ return cmds
159
+
160
+
161
+ # --------------------------------------------------------------------------- paths
162
+ WIN_CRED_DIRS = (".ssh", ".aws", ".gnupg", ".kube", ".azure", ".docker", ".config\\gcloud", ".config\\gh", "appdata\\roaming\\gcloud")
163
+ WIN_SYSTEM_TOP = frozenset({
164
+ "windows", "program files", "program files (x86)", "programdata", "system volume information",
165
+ "$recycle.bin", "recovery", "boot", "perflogs", "msocache", "documents and settings", "efi",
166
+ })
167
+ _CRED_FILE = re.compile(r"(?i)^(id_[a-z0-9_]+|credentials|authorized_keys|config|config\.json|.*\.pem|.*\.key|.*\.pfx|hosts\.yml)$")
168
+ _SHORT_NAME = re.compile(r"[a-z0-9_$!#%&'()@^`{}-]{1,6}~\d+")
169
+ _REGISTRY = re.compile(r"(?i)^(?:registry::)?hk(?:lm|cu|cr|u|cc|ey_[a-z_]+)(?::|\\|$)")
170
+ WIN_PROTECTED_HOME_DIRS = (".ssh", ".aws", ".gnupg", ".kube", ".kneepad")
171
+ WIN_PROTECTED_HOME_FILES = (
172
+ ".netrc", "_netrc", ".npmrc", ".pypirc", ".gitconfig", ".docker\\config.json", ".claude\\settings.json",
173
+ ".claude\\settings.local.json", "documents\\windowspowershell\\profile.ps1",
174
+ "documents\\windowspowershell\\microsoft.powershell_profile.ps1", "documents\\powershell\\profile.ps1",
175
+ "documents\\powershell\\microsoft.powershell_profile.ps1",
176
+ )
177
+ WIN_PROTECTED_ABS = (
178
+ "\\windows\\system32\\drivers\\etc\\hosts",
179
+ "\\windows\\system32\\config",
180
+ "\\windows\\system32\\winevt",
181
+ )
182
+
183
+
184
+ def is_registry(p: str) -> bool:
185
+ return bool(_REGISTRY.match(p.strip()))
186
+
187
+
188
+ def norm_path(p: str, cwd: str) -> Optional[str]:
189
+ """Absolute, normalised Windows path, or None when it cannot be resolved."""
190
+ p = p.strip().strip('"').strip("'").replace("/", "\\")
191
+ if p.startswith("\\\\?\\") and not p.startswith("\\\\?\\UNC\\"):
192
+ p = p[4:]
193
+ if re.fullmatch(r"[A-Za-z]:", p):
194
+ p += "\\"
195
+ if not looks_windows(p):
196
+ if p.startswith("\\") and looks_windows(cwd):
197
+ p = ntpath.splitdrive(cwd)[0] + p
198
+ elif looks_windows(cwd):
199
+ p = ntpath.join(cwd, p)
200
+ else:
201
+ return None
202
+ return ntpath.normpath(p)
203
+
204
+
205
+ def classify(p: str, cwd: str, home: str) -> str:
206
+ """catastrophic | ancestor | dotgit | creds | system | normal for a normalised Windows path."""
207
+ low = p.lower().rstrip("\\")
208
+ drive, rest = ntpath.splitdrive(low)
209
+ parts = [x for x in rest.split("\\") if x]
210
+ if drive.startswith("\\\\"):
211
+ return "catastrophic" if not parts else "normal"
212
+ if len(parts) <= 1:
213
+ return "catastrophic"
214
+ h = home.lower().rstrip("\\") if home else ""
215
+ if h and (low == h or h.startswith(low + "\\")):
216
+ return "catastrophic"
217
+ c = cwd.lower().rstrip("\\") if cwd else ""
218
+ if c and (c == low or c.startswith(low + "\\")):
219
+ return "ancestor"
220
+ if parts[-1] == ".git":
221
+ return "dotgit"
222
+ if h:
223
+ for d in WIN_CRED_DIRS:
224
+ base = h + "\\" + d
225
+ if low == base or (low.startswith(base + "\\") and _CRED_FILE.match(parts[-1])):
226
+ return "creds"
227
+ if parts[0] in WIN_SYSTEM_TOP or _SHORT_NAME.fullmatch(parts[0]):
228
+ return "system" # a top-level 8.3 short name (PROGRA~1, DOCUME~1) is almost always a system directory
229
+ if parts[0] == "users" and not (h and (low == h or low.startswith(h + "\\"))):
230
+ return "system"
231
+ return "normal"
232
+
233
+
234
+ def protected_reason(p: str, home: str, kneepad_dir: str) -> Optional[str]:
235
+ """Why a write to this normalised Windows path needs a decision, or None."""
236
+ low = p.lower()
237
+ h = home.lower().rstrip("\\") if home else ""
238
+ sd = kneepad_dir.lower().rstrip("\\") if kneepad_dir else ""
239
+ if sd and (low == sd or low.startswith(sd + "\\")):
240
+ return "Kneepad's own state"
241
+ if h:
242
+ for rel in WIN_PROTECTED_HOME_DIRS:
243
+ base = h + "\\" + rel
244
+ if low == base or low.startswith(base + "\\"):
245
+ return f"protected directory ~\\{rel}"
246
+ for rel in WIN_PROTECTED_HOME_FILES:
247
+ if low == h + "\\" + rel:
248
+ return f"protected file ~\\{rel}"
249
+ startup = h + "\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\startup"
250
+ if low == startup or low.startswith(startup + "\\"):
251
+ return "startup folder (persistence)"
252
+ drive, rest = ntpath.splitdrive(low)
253
+ for suffix in WIN_PROTECTED_ABS:
254
+ if rest == suffix or rest.startswith(suffix + "\\"):
255
+ return "system path"
256
+ parts = [x for x in rest.split("\\") if x]
257
+ if parts and (parts[0] in WIN_SYSTEM_TOP or _SHORT_NAME.fullmatch(parts[0])):
258
+ return "system path"
259
+ base = parts[-1] if parts else ""
260
+ if base == ".kneepad.toml":
261
+ return "Kneepad project config"
262
+ return None
263
+
264
+
265
+ # --------------------------------------------------------------------------- expansion
266
+ _DEFAULT_ENV = {"systemroot": "C:\\Windows", "windir": "C:\\Windows", "programfiles": "C:\\Program Files",
267
+ "programdata": "C:\\ProgramData", "systemdrive": "C:", "allusersprofile": "C:\\ProgramData"}
268
+
269
+
270
+ def _lookup(az, name: str) -> Optional[str]:
271
+ n = name.lower()
272
+ for k, v in az.env.items():
273
+ if k.lower() == n and v:
274
+ return v
275
+ home = az.home
276
+ table: Dict[str, str] = {"userprofile": home, "home": home, "pwd": az.cwd}
277
+ if looks_windows(home):
278
+ table["appdata"] = home + "\\AppData\\Roaming"
279
+ table["localappdata"] = home + "\\AppData\\Local"
280
+ table["temp"] = home + "\\AppData\\Local\\Temp"
281
+ table["tmp"] = table["temp"]
282
+ table.update({k: v for k, v in _DEFAULT_ENV.items() if k not in table})
283
+ return table.get(n)
284
+
285
+
286
+ def expand(az, text: str) -> Tuple[str, bool]:
287
+ """Expand %VAR%, $env:VAR, $HOME and a leading ~. Returns (text, dynamic)."""
288
+ dyn = False
289
+
290
+ def sub(m: "re.Match[str]") -> str:
291
+ nonlocal dyn
292
+ name = next(g for g in m.groups() if g)
293
+ v = _lookup(az, name)
294
+ if v is None:
295
+ dyn = True
296
+ return m.group(0)
297
+ return v
298
+
299
+ out = re.sub(r"%([A-Za-z_]\w*)%|\$env:([A-Za-z_]\w*)|\$\{env:([A-Za-z_]\w*)\}|\$(home|pwd)\b", sub, text, flags=re.I)
300
+ if out == "~" or out.startswith("~\\") or out.startswith("~/"):
301
+ out = az.home + out[1:]
302
+ probe = re.sub(r"(?i)\$recycle\.bin", "", out)
303
+ if re.search(r"\$[A-Za-z_{(]|\$_|%[A-Za-z_]", probe):
304
+ dyn = True
305
+ return out, dyn
306
+
307
+
308
+ # --------------------------------------------------------------------------- argv view
309
+ def _native_pa(name: str, toks: List[Tok]) -> ParsedArgv:
310
+ tokens = [t.text for t in toks[1:]]
311
+ pa = ParsedArgv(name=name, words=[Word(text=t.text, raw=t.text, quoted=t.quoted) for t in toks], tokens=tokens,
312
+ raw0=toks[0].text)
313
+ for idx, t in enumerate(toks[1:], start=1):
314
+ s = t.text
315
+ cluster = (not t.quoted) and _SWITCH_CLUSTER.fullmatch(s) is not None and s.count("/") > 1
316
+ if cluster:
317
+ for part in re.findall(r"/[A-Za-z?](?::[^/\s]*)?", s):
318
+ pa.flags.add(part.split(":", 1)[0].lower())
319
+ continue
320
+ is_flag = (s.startswith("-") and len(s) > 1 and not s[1].isdigit()) or bool(re.fullmatch(r"/[A-Za-z?][A-Za-z0-9:=,._-]*", s))
321
+ if is_flag and not t.quoted:
322
+ m = re.split(r"[:=]", s.lower(), maxsplit=1)
323
+ pa.flags.add(m[0])
324
+ if len(m) == 2:
325
+ pa.flag_values[m[0]] = s[len(m[0]) + 1:]
326
+ else:
327
+ pa.pos.append(s)
328
+ pa.pos_words.append(pa.words[idx])
329
+ pa.pos_idx.append(idx)
330
+ pa.argstr = " ".join(tokens)
331
+ return pa
332
+
333
+
334
+ # --------------------------------------------------------------------------- handlers
335
+ # cmd.exe accepts switches run together: /s/q, /q/s, /s/q/f. Only used for deletes, never for POSIX words.
336
+ _SWITCH_CLUSTER = re.compile(r"(?i)(?:/[a-z?](?::[^/\s]*)?)+")
337
+ _RECURSE = re.compile(r"(?i)^-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?(?::\S*)?$")
338
+ _PS_VALUE_FLAGS = {"-filter", "-include", "-exclude", "-credential", "-stream", "-erroraction", "-ea", "-errorvariable", "-ev",
339
+ "-warningaction", "-wa", "-informationaction", "-ia", "-outvariable", "-ov", "-outbuffer", "-ob",
340
+ "-pipelinevariable", "-pv", "-warningvariable", "-wv", "-informationvariable", "-iv"}
341
+ _PS_PATH_FLAGS = {"-path", "-literalpath", "-pspath", "-lp", "-pa"}
342
+ DELETE_NAMES = frozenset({"del", "erase", "rd", "rmdir", "ri", "remove-item", "rm"})
343
+ _WRITERS_PS = frozenset({"set-content", "add-content", "out-file", "clear-content", "new-item", "tee-object", "export-csv", "sc", "ac", "ni"})
344
+ _WRITERS_COPY = frozenset({"copy-item", "move-item", "rename-item", "cpi", "mi", "mv", "cp", "copy", "move", "ren", "rename", "xcopy"})
345
+
346
+
347
+ def _ignorable(az, p: str) -> bool:
348
+ parts = {x.lower() for x in re.split(r"[\\/]", p)}
349
+ ign = {x.lower() for x in az.cfg.ignore_dirs}
350
+ base = parts and p.replace("/", "\\").rsplit("\\", 1)[-1].lower()
351
+ return bool(parts & ign) or base == "thumbs.db" or base == "desktop.ini" or str(base).endswith(".pyc")
352
+
353
+
354
+ def _delete(az, name: str, toks: List[Tok], pipe_in: bool) -> None:
355
+ args = toks[1:]
356
+ low = [t.text.lower() for t in args]
357
+ recursive = any(
358
+ (not t.quoted and _SWITCH_CLUSTER.fullmatch(t.text) and re.search(r"(?i)/s(?::|/|$)", t.text) is not None) or _RECURSE.match(t.text)
359
+ for t in args
360
+ )
361
+ forced = any(re.fullmatch(r"(?i)-fo(?:r(?:c(?:e)?)?)?(?::\S*)?", t.text) for t in args)
362
+ targets: List[Tok] = []
363
+ i = 0
364
+ while i < len(args):
365
+ t = args[i]
366
+ s = t.text
367
+ ls = s.lower()
368
+ if not t.quoted and (ls in _PS_PATH_FLAGS or re.match(r"(?i)^-(?:path|literalpath|pspath|lp|pa):", s)):
369
+ val = s.split(":", 1)[1] if ":" in s[1:] and ls not in _PS_PATH_FLAGS else (args[i + 1].text if i + 1 < len(args) else "")
370
+ if ls in _PS_PATH_FLAGS:
371
+ i += 1
372
+ for piece in val.split(","):
373
+ if piece:
374
+ targets.append(Tok(piece, t.quoted))
375
+ elif not t.quoted and ls in _PS_VALUE_FLAGS:
376
+ i += 1
377
+ elif not t.quoted and ((s.startswith("-") and len(s) > 1) or _SWITCH_CLUSTER.fullmatch(s)):
378
+ pass
379
+ elif s in (">", ">>", "<") or s.startswith(">"):
380
+ i += 1
381
+ else:
382
+ for piece in s.split(","):
383
+ if piece:
384
+ targets.append(Tok(piece, t.quoted))
385
+ i += 1
386
+ if not targets:
387
+ if pipe_in and (recursive or forced):
388
+ az.emit("fs-rm-dynamic-target", f"{toks[0].text} fed by a pipeline")
389
+ return
390
+ need: List[str] = []
391
+ for t in targets:
392
+ text, dyn = expand(az, t.text)
393
+ if dyn:
394
+ if recursive:
395
+ az.emit("fs-rm-dynamic-target", t.text)
396
+ continue
397
+ if is_registry(text):
398
+ az.emit("win-registry-delete", text)
399
+ continue
400
+ wild = bool(re.search(r"[*?]", ntpath.basename(text.replace("/", "\\"))))
401
+ probe = text
402
+ if wild:
403
+ probe = ntpath.dirname(text.replace("/", "\\")) or text
404
+ ap = norm_path(probe, az.cwd)
405
+ if ap is None:
406
+ continue
407
+ kind = classify(ap, az.cwd, az.home)
408
+ dir_delete = recursive or wild or name in ("del", "erase")
409
+ if name in ("rd", "rmdir") and not recursive:
410
+ continue
411
+ if kind in ("catastrophic", "ancestor", "dotgit") and not dir_delete:
412
+ continue
413
+ if kind == "catastrophic":
414
+ az.emit("fs-rm-catastrophic", ap)
415
+ elif kind == "ancestor":
416
+ az.emit("fs-rm-ancestor-of-cwd", ap)
417
+ elif kind == "dotgit":
418
+ az.emit("fs-rm-dot-git", ap)
419
+ elif kind == "creds":
420
+ az.emit("fs-rm-credentials-dir", ap)
421
+ elif kind == "system":
422
+ az.emit("fs-rm-system-path", ap)
423
+ elif dir_delete or os.path.isfile(ap):
424
+ if not wild:
425
+ need.append(ap)
426
+ else:
427
+ pattern = norm_path(text, az.cwd) or ap
428
+ matches = glob.glob(pattern) if os.sep == "\\" or not looks_windows(pattern) else []
429
+ if len(matches) > 2000:
430
+ if recursive:
431
+ az.emit("fs-rm-dynamic-target", f"glob {t.text} matches more than 2000 paths")
432
+ continue
433
+ need.extend(matches)
434
+ seen: set = set()
435
+ final: List[str] = []
436
+ for p in need:
437
+ if p in seen:
438
+ continue
439
+ seen.add(p)
440
+ if not os.path.lexists(p) or _ignorable(az, p) or az._git_recoverable(p):
441
+ continue
442
+ final.append(p)
443
+ if final:
444
+ b, _f, exceeded = estimate_size(final, az.cfg.snapshot_max_mb * 1024 * 1024, az.cfg.snapshot_max_files)
445
+ if exceeded:
446
+ az.emit("fs-rm-too-large-to-snapshot", ", ".join(final)[:160])
447
+ else:
448
+ az.emit("fs-rm-snapshot", ", ".join(final)[:160], plan=SnapshotPlan("files", az.cwd, paths=final, est_bytes=b))
449
+
450
+
451
+ def _write_targets(name: str, toks: List[Tok]) -> List[str]:
452
+ args = toks[1:]
453
+ out: List[str] = []
454
+ pos: List[str] = []
455
+ i = 0
456
+ while i < len(args):
457
+ s = args[i].text
458
+ ls = s.lower()
459
+ if s in (">", ">>") and i + 1 < len(args):
460
+ out.append(args[i + 1].text)
461
+ i += 2
462
+ continue
463
+ if not args[i].quoted and ls in ("-path", "-filepath", "-literalpath", "-destination", "-newname") and i + 1 < len(args):
464
+ out.append(args[i + 1].text)
465
+ i += 2
466
+ continue
467
+ if not args[i].quoted and (s.startswith("-") or re.fullmatch(r"/[A-Za-z?](?::\S*)?", s)) and len(s) > 1:
468
+ if ls in ("-value", "-inputobject", "-encoding", "-itemtype", "-name", "-width"):
469
+ i += 1
470
+ i += 1
471
+ continue
472
+ pos.append(s)
473
+ i += 1
474
+ if name in _WRITERS_COPY:
475
+ if len(pos) >= 2:
476
+ out.append(pos[-1])
477
+ elif name in _WRITERS_PS and not out and pos:
478
+ out.append(pos[0])
479
+ return out
480
+
481
+
482
+ def _check_writes(az, name: str, toks: List[Tok]) -> None:
483
+ redirects = [i for i, t in enumerate(toks) if t.text in (">", ">>")]
484
+ if name not in _WRITERS_PS and name not in _WRITERS_COPY and not redirects:
485
+ return
486
+ for raw in _write_targets(name, toks):
487
+ text, dyn = expand(az, raw)
488
+ if dyn or not text:
489
+ continue
490
+ ap = norm_path(text, az.cwd)
491
+ if ap is None:
492
+ continue
493
+ reason = protected_reason(ap, az.home, az_kneepad_dir())
494
+ if reason:
495
+ az.emit("fs-protected-path-write", f"{ap} ({reason})")
496
+
497
+
498
+ def az_kneepad_dir() -> str:
499
+ from .util import kneepad_home
500
+
501
+ return kneepad_home()
502
+
503
+
504
+ def _inner_from_ps(rest: List[Tok]) -> Tuple[Optional[str], Optional[str]]:
505
+ """Return (command text, encoded command) for a powershell/pwsh invocation."""
506
+ for i, t in enumerate(rest):
507
+ if t.quoted:
508
+ continue
509
+ s = t.text.lower()
510
+ if re.fullmatch(r"-(?:c|co|com|comm|comma|comman|command)", s):
511
+ return " ".join(x.text for x in rest[i + 1:]), None
512
+ if re.fullmatch(r"-e(?:c|nc|nco|ncod|ncode|ncoded|ncodedc|ncodedco|ncodedcom|ncodedcomm|ncodedcomma|ncodedcomman|ncodedcommand)?", s):
513
+ return None, rest[i + 1].text if i + 1 < len(rest) else ""
514
+ if s.startswith("-command:") or s.startswith("-c:"):
515
+ return t.text.split(":", 1)[1], None
516
+ return None, None
517
+
518
+
519
+ def _decode_ps(b64: str) -> Optional[str]:
520
+ try:
521
+ raw = base64.b64decode(b64 + "=" * (-len(b64) % 4), validate=False)
522
+ txt = raw.decode("utf-16-le")
523
+ except (binascii.Error, ValueError, UnicodeDecodeError):
524
+ return None
525
+ if not txt or not all(ch.isprintable() or ch in "\r\n\t" for ch in txt):
526
+ return None
527
+ return txt
528
+
529
+
530
+ def _wrappers(az, name: str, toks: List[Tok], depth: int) -> bool:
531
+ """Handle commands that run other commands. True when the command was fully delegated."""
532
+ rest = toks[1:]
533
+ if name in ("powershell", "pwsh", "powershell_ise"):
534
+ inner, enc = _inner_from_ps(rest)
535
+ if enc is not None:
536
+ txt = _decode_ps(enc)
537
+ if txt is None:
538
+ az.emit("win-encoded-command", f"{toks[0].text} -EncodedCommand (could not decode)")
539
+ else:
540
+ az._walk(txt, depth + 1)
541
+ elif inner:
542
+ az._walk(inner, depth + 1)
543
+ return False
544
+ if name == "cmd":
545
+ for i, t in enumerate(rest):
546
+ m = re.fullmatch(r"(?i)/([ck])(.*)", t.text)
547
+ if m:
548
+ tail = ([m.group(2)] if m.group(2) else []) + [x.text for x in rest[i + 1:]]
549
+ if tail:
550
+ az._walk(" ".join(tail), depth + 1)
551
+ break
552
+ return False
553
+ if name == "wsl":
554
+ skip = {"-d", "--distribution", "-u", "--user", "--cd", "--shell-type"}
555
+ i = 0
556
+ while i < len(rest):
557
+ s = rest[i].text.lower()
558
+ if s in skip:
559
+ i += 2
560
+ continue
561
+ if s in ("-e", "--exec", "--", "-l", "--login"):
562
+ i += 1
563
+ continue
564
+ if s.startswith("-"):
565
+ i += 1
566
+ continue
567
+ break
568
+ inner = " ".join(x.text for x in rest[i:])
569
+ if inner:
570
+ az._walk(inner, depth + 1)
571
+ return False
572
+ if name in ("iex", "invoke-expression"):
573
+ inner = " ".join(x.text for x in rest)
574
+ if inner:
575
+ az._walk(inner, depth + 1)
576
+ return False
577
+ if name in ("start-process", "saps", "start"):
578
+ files: List[str] = []
579
+ argl = ""
580
+ i = 0
581
+ while i < len(rest):
582
+ s = rest[i].text
583
+ ls = s.lower()
584
+ if ls in ("-argumentlist", "-args"):
585
+ argl = rest[i + 1].text if i + 1 < len(rest) else ""
586
+ i += 2
587
+ continue
588
+ if ls in ("-filepath", "-verb", "-workingdirectory", "-wd", "-windowstyle", "-credential"):
589
+ if ls == "-filepath" and i + 1 < len(rest):
590
+ files.append(rest[i + 1].text)
591
+ i += 2
592
+ continue
593
+ if s.startswith("-") or re.fullmatch(r"(?i)/(?:wait|b|min|max|low|normal|high|realtime|abovenormal|belownormal|separate|shared|node\s*\d*)", s):
594
+ i += 1
595
+ continue
596
+ files.append(s)
597
+ i += 1
598
+ if files:
599
+ az._walk((files[0] + " " + argl + " " + " ".join(files[1:])).strip(), depth + 1)
600
+ return False
601
+ if name == "call" and rest:
602
+ az._walk(" ".join(x.text for x in rest), depth + 1)
603
+ return False
604
+ if name == "runas" and rest:
605
+ az._walk(rest[-1].text, depth + 1)
606
+ return False
607
+ return False
608
+
609
+
610
+ def analyze(az, text: str, depth: int) -> None:
611
+ """Run the Windows pass over one command string."""
612
+ for toks, pipe_in in tokenize(text):
613
+ if not toks:
614
+ continue
615
+ name = win_name(toks[0].text)
616
+ if not name:
617
+ continue
618
+ marker = any(has_marker(t.text) for t in toks)
619
+ _wrappers(az, name, toks, depth)
620
+ pa = _native_pa(name, toks)
621
+ for r in az._win_dsl:
622
+ if match_argv(r, pa):
623
+ az.emit(r.id, " ".join([toks[0].text] + pa.tokens)[:200])
624
+ if name in DELETE_NAMES:
625
+ ps_style = any(_RECURSE.match(t.text) for t in toks[1:])
626
+ if name not in ("rm", "rmdir") or marker or ps_style:
627
+ _delete(az, name, toks, pipe_in)
628
+ continue
629
+ _check_writes(az, name, toks)
630
+ if marker and name not in DELETE_NAMES:
631
+ words = [Word(text=t.text, raw=t.text, quoted=t.quoted) for t in toks]
632
+ gp = parse_argv(words)
633
+ if gp is not None:
634
+ az._analyze_pa(gp, None, None, -1, depth)