@glassbox-ai/engine 0.0.0-stage → 0.1.1
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.
- package/LICENSE +201 -0
- package/README.md +33 -2
- package/dist/action/acc.d.ts +48 -0
- package/dist/action/acc.js +117 -0
- package/dist/action/builtin-tools.d.ts +5 -0
- package/dist/action/builtin-tools.js +74 -0
- package/dist/action/inline.d.ts +14 -0
- package/dist/action/inline.js +54 -0
- package/dist/action/paths.d.ts +71 -0
- package/dist/action/paths.js +398 -0
- package/dist/action/powershell.d.ts +9 -0
- package/dist/action/powershell.js +848 -0
- package/dist/action/protected-write.d.ts +11 -0
- package/dist/action/protected-write.js +113 -0
- package/dist/action/schedule.d.ts +43 -0
- package/dist/action/schedule.js +213 -0
- package/dist/action/shell/analyze.d.ts +28 -0
- package/dist/action/shell/analyze.js +2057 -0
- package/dist/action/shell/parse.d.ts +74 -0
- package/dist/action/shell/parse.js +1037 -0
- package/dist/action/shell/view.d.ts +6 -0
- package/dist/action/shell/view.js +89 -0
- package/dist/action/sql.d.ts +3 -0
- package/dist/action/sql.js +259 -0
- package/dist/action/tools.d.ts +20 -0
- package/dist/action/tools.js +305 -0
- package/dist/action/upload.d.ts +17 -0
- package/dist/action/upload.js +72 -0
- package/dist/analysis/fields.d.ts +14 -0
- package/dist/analysis/fields.js +136 -0
- package/dist/analysis/findings.d.ts +25 -0
- package/dist/analysis/findings.js +82 -0
- package/dist/analysis/gate.d.ts +16 -0
- package/dist/analysis/gate.js +662 -0
- package/dist/analysis/manifest.d.ts +3 -0
- package/dist/analysis/manifest.js +369 -0
- package/dist/analysis/match.d.ts +54 -0
- package/dist/analysis/match.js +352 -0
- package/dist/analysis/scan.d.ts +17 -0
- package/dist/analysis/scan.js +97 -0
- package/dist/canon/confusables.generated.d.ts +3 -0
- package/dist/canon/confusables.generated.js +6 -0
- package/dist/canon/decode.d.ts +11 -0
- package/dist/canon/decode.js +147 -0
- package/dist/canon/views.d.ts +36 -0
- package/dist/canon/views.js +283 -0
- package/dist/evidence/evidence.d.ts +12 -0
- package/dist/evidence/evidence.js +149 -0
- package/dist/fingerprint/diff.d.ts +3 -0
- package/dist/fingerprint/diff.js +273 -0
- package/dist/fingerprint/fingerprint.d.ts +4 -0
- package/dist/fingerprint/fingerprint.js +77 -0
- package/dist/grade/score.d.ts +19 -0
- package/dist/grade/score.js +89 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +152 -0
- package/dist/intake/json.d.ts +17 -0
- package/dist/intake/json.js +284 -0
- package/dist/intake/snapshot.d.ts +14 -0
- package/dist/intake/snapshot.js +130 -0
- package/dist/limits.d.ts +4 -0
- package/dist/limits.js +30 -0
- package/dist/policy/decide.d.ts +32 -0
- package/dist/policy/decide.js +105 -0
- package/dist/rules/ids.d.ts +2 -0
- package/dist/rules/ids.js +99 -0
- package/dist/ruleset/baseline-tests.generated.d.ts +6 -0
- package/dist/ruleset/baseline-tests.generated.js +2935 -0
- package/dist/ruleset/baseline.d.ts +3 -0
- package/dist/ruleset/baseline.generated.d.ts +3 -0
- package/dist/ruleset/baseline.generated.js +5 -0
- package/dist/ruleset/baseline.js +44 -0
- package/dist/ruleset/fakes.d.ts +3 -0
- package/dist/ruleset/fakes.js +26 -0
- package/dist/ruleset/load.d.ts +13 -0
- package/dist/ruleset/load.js +187 -0
- package/dist/ruleset/schema.d.ts +120 -0
- package/dist/ruleset/schema.js +54 -0
- package/dist/ruleset/selftest.d.ts +18 -0
- package/dist/ruleset/selftest.js +42 -0
- package/dist/ruleset-entry.d.ts +5 -0
- package/dist/ruleset-entry.js +7 -0
- package/dist/secrets/detect.d.ts +17 -0
- package/dist/secrets/detect.js +236 -0
- package/dist/secrets/redact.d.ts +19 -0
- package/dist/secrets/redact.js +116 -0
- package/dist/types.d.ts +455 -0
- package/dist/types.js +10 -0
- package/dist/util/hash.d.ts +4 -0
- package/dist/util/hash.js +16 -0
- package/dist/util/initclock.d.ts +3 -0
- package/dist/util/initclock.js +17 -0
- package/dist/util/jcs.d.ts +4 -0
- package/dist/util/jcs.js +91 -0
- package/dist/util/misc.d.ts +17 -0
- package/dist/util/misc.js +77 -0
- package/dist/util/re.d.ts +14 -0
- package/dist/util/re.js +47 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/package.json +57 -4
|
@@ -0,0 +1,848 @@
|
|
|
1
|
+
// PowerShell analysis: hand-written tokenizer, alias table,
|
|
2
|
+
// cmdlet classes; native programs go through the shell command table.
|
|
3
|
+
import { Acc } from "./acc.js";
|
|
4
|
+
import { homeTopLevel, isProtected, isProtectedRead, normalizePath, persistenceHit, sensitiveLabel } from "./paths.js";
|
|
5
|
+
import { isProtectedWrite } from "./protected-write.js";
|
|
6
|
+
import { classifyNative } from "./shell/analyze.js";
|
|
7
|
+
import { allLoopback, classifyUpload, recordUpload } from "./upload.js";
|
|
8
|
+
import { commandFiles } from "./schedule.js";
|
|
9
|
+
import { litWord } from "./shell/parse.js";
|
|
10
|
+
class PsUnanalyzable extends Error {
|
|
11
|
+
reason;
|
|
12
|
+
constructor(reason) {
|
|
13
|
+
super(reason);
|
|
14
|
+
this.reason = reason;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const ALIASES = new Map([
|
|
18
|
+
["ls", "get-childitem"], ["dir", "get-childitem"], ["gci", "get-childitem"], ["cat", "get-content"], ["gc", "get-content"], ["type", "get-content"],
|
|
19
|
+
["sls", "select-string"], ["rm", "remove-item"], ["del", "remove-item"], ["erase", "remove-item"], ["rd", "remove-item"], ["ri", "remove-item"], ["rmdir", "remove-item"],
|
|
20
|
+
["cp", "copy-item"], ["copy", "copy-item"], ["cpi", "copy-item"], ["mv", "move-item"], ["move", "move-item"], ["mi", "move-item"], ["ren", "rename-item"], ["rni", "rename-item"],
|
|
21
|
+
["iwr", "invoke-webrequest"], ["curl", "invoke-webrequest"], ["wget", "invoke-webrequest"], ["irm", "invoke-restmethod"], ["iex", "invoke-expression"],
|
|
22
|
+
["sc", "set-content"], ["ac", "add-content"], ["ni", "new-item"], ["md", "new-item"], ["mkdir", "new-item"], ["echo", "write-output"], ["write", "write-output"], ["pwd", "get-location"], ["gl", "get-location"],
|
|
23
|
+
["cd", "set-location"], ["sl", "set-location"], ["chdir", "set-location"], ["%", "foreach-object"], ["foreach", "foreach-object"], ["?", "where-object"], ["where", "where-object"],
|
|
24
|
+
["select", "select-object"], ["sort", "sort-object"], ["measure", "measure-object"], ["ft", "format-table"], ["fl", "format-list"], ["gi", "get-item"], ["gp", "get-itemproperty"],
|
|
25
|
+
["sp", "set-itemproperty"], ["clc", "clear-content"], ["icm", "invoke-command"], ["saps", "start-process"], ["start", "start-process"], ["sajb", "start-job"], ["tee", "tee-object"],
|
|
26
|
+
["h", "get-history"], ["history", "get-history"], ["cls", "clear-host"], ["clear", "clear-host"], ["gcm", "get-command"], ["man", "get-help"], ["help", "get-help"], ["kill", "stop-process"], ["spps", "stop-process"], ["ps", "get-process"], ["gps", "get-process"],
|
|
27
|
+
]);
|
|
28
|
+
const READ = new Set([
|
|
29
|
+
"get-childitem", "get-content", "get-item", "get-itemproperty", "test-path", "resolve-path", "select-string", "get-location", "set-location", "push-location", "pop-location",
|
|
30
|
+
"measure-object", "sort-object", "select-object", "where-object", "foreach-object", "format-table", "format-list", "format-wide", "out-string", "out-host", "out-null", "write-output",
|
|
31
|
+
"write-host", "write-verbose", "write-warning", "write-error", "write-information", "get-command", "get-help", "get-date", "convertfrom-json", "convertto-json", "compare-object", "split-path",
|
|
32
|
+
"join-path", "get-process", "get-service", "get-history", "clear-host", "get-filehash", "get-member", "group-object", "get-unique", "convertto-csv", "convertfrom-csv", "import-csv",
|
|
33
|
+
"get-alias", "get-variable", "get-psdrive", "get-module", "get-host", "get-culture", "get-random", "start-sleep", "get-acl", "get-itempropertyvalue", "test-connection_local", "get-computerinfo",
|
|
34
|
+
"select-xml", "convertfrom-stringdata", "get-uptime", "get-timezone", "get-error", "out-default", "format-hex", "new-timespan", "get-filehash", "where", "tee-object_read",
|
|
35
|
+
]);
|
|
36
|
+
const WRITE = new Set(["set-content", "add-content", "out-file", "new-item", "copy-item", "move-item", "rename-item", "tee-object", "compress-archive", "expand-archive", "export-csv", "set-item", "new-variable", "set-variable", "export-clixml"]);
|
|
37
|
+
const NETWORK = new Set(["invoke-webrequest", "invoke-restmethod", "start-bitstransfer", "send-mailmessage", "test-netconnection", "new-pssession", "connect-pssession"]);
|
|
38
|
+
const PERM = new Set(["set-acl", "set-executionpolicy", "new-localuser", "add-localgroupmember", "set-localuser", "enable-psremoting", "grant-smbshareaccess"]);
|
|
39
|
+
const UNANALYZABLE = new Map([
|
|
40
|
+
["invoke-expression", "Invoke-Expression runs a string as code"], ["invoke-command", "Invoke-Command runs code remotely or in a script block"],
|
|
41
|
+
["enter-pssession", "Enter-PSSession opens a remote session"], ["add-type", "Add-Type compiles code"], ["start-job", "Start-Job runs code in the background"],
|
|
42
|
+
["invoke-item", "Invoke-Item opens files with their default program"], ["import-module", "Import-Module loads code"], ["new-module", "New-Module defines code at run time"],
|
|
43
|
+
]);
|
|
44
|
+
// Destructive system cmdlets (bench gap). Disk/partition wipes destroy data outright.
|
|
45
|
+
const DISK_WIPE = new Set(["format-volume", "clear-disk", "initialize-disk", "remove-partition", "remove-physicaldisk", "remove-virtualdisk", "remove-storagepool", "clear-recyclebin"]);
|
|
46
|
+
// Power and service state: irreversible for the session, so they ask.
|
|
47
|
+
const SYSTEM_STATE = new Set(["stop-computer", "restart-computer", "suspend-computer", "stop-service", "remove-service", "disable-computerrestore", "checkpoint-computer_off"]);
|
|
48
|
+
// Evidence and defence tampering.
|
|
49
|
+
const TAMPER = new Set(["clear-eventlog", "remove-eventlog", "limit-eventlog", "set-mppreference", "add-mppreference", "remove-mppreference", "disable-localuser", "remove-localuser", "remove-localgroupmember"]);
|
|
50
|
+
const STATIC_OK = /^\[(system\.)?(io\.path|math)\]::/i;
|
|
51
|
+
const isWordChar = (c) => !" \t\r\n;|&(){}<>'\"`,=".includes(c);
|
|
52
|
+
function tokenize(src) {
|
|
53
|
+
const toks = [];
|
|
54
|
+
let i = 0;
|
|
55
|
+
const n = src.length;
|
|
56
|
+
let count = 0;
|
|
57
|
+
const readBalanced = (open, close, from) => {
|
|
58
|
+
let depth = 0;
|
|
59
|
+
for (let j = from; j < n; j++) {
|
|
60
|
+
const c = src[j];
|
|
61
|
+
if (c === "`") {
|
|
62
|
+
j++;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (c === "'") {
|
|
66
|
+
const e = src.indexOf("'", j + 1);
|
|
67
|
+
if (e < 0)
|
|
68
|
+
throw new PsUnanalyzable("unterminated string");
|
|
69
|
+
j = e;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (c === '"') {
|
|
73
|
+
let e = j + 1;
|
|
74
|
+
while (e < n && src[e] !== '"') {
|
|
75
|
+
if (src[e] === "`")
|
|
76
|
+
e++;
|
|
77
|
+
e++;
|
|
78
|
+
}
|
|
79
|
+
if (e >= n)
|
|
80
|
+
throw new PsUnanalyzable("unterminated string");
|
|
81
|
+
j = e;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (c === open)
|
|
85
|
+
depth++;
|
|
86
|
+
else if (c === close) {
|
|
87
|
+
depth--;
|
|
88
|
+
if (depth === 0)
|
|
89
|
+
return j;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
throw new PsUnanalyzable(`unbalanced ${open}${close}`);
|
|
93
|
+
};
|
|
94
|
+
const readValueTok = () => {
|
|
95
|
+
const save = toks.length;
|
|
96
|
+
readOne();
|
|
97
|
+
return toks.length > save ? toks.pop() : null;
|
|
98
|
+
};
|
|
99
|
+
function readOne() {
|
|
100
|
+
if (++count > 4096)
|
|
101
|
+
throw new PsUnanalyzable("too many tokens");
|
|
102
|
+
const c = src[i];
|
|
103
|
+
// Here-strings
|
|
104
|
+
if ((c === "@") && (src[i + 1] === "'" || src[i + 1] === '"') && (src[i + 2] === "\n" || (src[i + 2] === "\r" && src[i + 3] === "\n"))) {
|
|
105
|
+
const q = src[i + 1];
|
|
106
|
+
const end = src.indexOf("\n" + q + "@", i + 2);
|
|
107
|
+
if (end < 0)
|
|
108
|
+
throw new PsUnanalyzable("unterminated here-string");
|
|
109
|
+
const body = src.slice(src.indexOf("\n", i) + 1, end);
|
|
110
|
+
const subs = q === '"' ? subexprs(body) : [];
|
|
111
|
+
toks.push({ k: "str", v: body, dyn: q === '"' && (body.includes("$")), subs });
|
|
112
|
+
i = end + 3;
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (c === "'") {
|
|
116
|
+
let j = i + 1, v = "";
|
|
117
|
+
for (;;) {
|
|
118
|
+
if (j >= n)
|
|
119
|
+
throw new PsUnanalyzable("unterminated string");
|
|
120
|
+
if (src[j] === "'") {
|
|
121
|
+
if (src[j + 1] === "'") {
|
|
122
|
+
v += "'";
|
|
123
|
+
j += 2;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
v += src[j];
|
|
129
|
+
j++;
|
|
130
|
+
}
|
|
131
|
+
toks.push({ k: "str", v, dyn: false, subs: [] });
|
|
132
|
+
i = j + 1;
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (c === '"') {
|
|
136
|
+
let j = i + 1, v = "";
|
|
137
|
+
for (;;) {
|
|
138
|
+
if (j >= n)
|
|
139
|
+
throw new PsUnanalyzable("unterminated string");
|
|
140
|
+
if (src[j] === "`") {
|
|
141
|
+
v += src[j + 1] ?? "";
|
|
142
|
+
j += 2;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (src[j] === '"') {
|
|
146
|
+
if (src[j + 1] === '"') {
|
|
147
|
+
v += '"';
|
|
148
|
+
j += 2;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
if (src[j] === "$" && src[j + 1] === "(") {
|
|
154
|
+
const e = readBalanced("(", ")", j + 1);
|
|
155
|
+
v += src.slice(j, e + 1);
|
|
156
|
+
j = e + 1;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
v += src[j];
|
|
160
|
+
j++;
|
|
161
|
+
}
|
|
162
|
+
const subs = subexprs(v);
|
|
163
|
+
toks.push({ k: "str", v, dyn: v.includes("$"), subs });
|
|
164
|
+
i = j + 1;
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (c === "$" && src[i + 1] === "(") {
|
|
168
|
+
const e = readBalanced("(", ")", i + 1);
|
|
169
|
+
toks.push({ k: "sub", inner: src.slice(i + 2, e), array: false });
|
|
170
|
+
i = e + 1;
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (c === "@" && src[i + 1] === "(") {
|
|
174
|
+
const e = readBalanced("(", ")", i + 1);
|
|
175
|
+
toks.push({ k: "sub", inner: src.slice(i + 2, e), array: true });
|
|
176
|
+
i = e + 1;
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (c === "@" && src[i + 1] === "{") {
|
|
180
|
+
const e = readBalanced("{", "}", i + 1);
|
|
181
|
+
toks.push({ k: "hash" });
|
|
182
|
+
i = e + 1;
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (c === "(") {
|
|
186
|
+
const e = readBalanced("(", ")", i);
|
|
187
|
+
toks.push({ k: "paren", inner: src.slice(i + 1, e) });
|
|
188
|
+
i = e + 1;
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (c === "{") {
|
|
192
|
+
const e = readBalanced("{", "}", i);
|
|
193
|
+
toks.push({ k: "block", inner: src.slice(i + 1, e) });
|
|
194
|
+
i = e + 1;
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (c === "[") {
|
|
198
|
+
const e = src.indexOf("]", i);
|
|
199
|
+
if (e < 0)
|
|
200
|
+
throw new PsUnanalyzable("unterminated type literal");
|
|
201
|
+
let j = e + 1;
|
|
202
|
+
let staticCall = null;
|
|
203
|
+
if (src[j] === ":" && src[j + 1] === ":") {
|
|
204
|
+
j += 2;
|
|
205
|
+
while (j < n && /[A-Za-z0-9_]/.test(src[j]))
|
|
206
|
+
j++;
|
|
207
|
+
staticCall = src.slice(i, j);
|
|
208
|
+
}
|
|
209
|
+
toks.push({ k: "type", v: src.slice(i, e + 1), staticCall });
|
|
210
|
+
i = j;
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
// Redirections
|
|
214
|
+
const redir = ["2>&1", "*>&1", "*>>", "*>", "2>>", "2>", "3>", ">>", ">", "<"].find((r) => src.startsWith(r, i));
|
|
215
|
+
if (redir) {
|
|
216
|
+
i += redir.length;
|
|
217
|
+
while (src[i] === " " || src[i] === "\t")
|
|
218
|
+
i++;
|
|
219
|
+
if (redir.endsWith("&1") || redir === "<") {
|
|
220
|
+
toks.push({ k: "redir", v: redir, target: null });
|
|
221
|
+
if (redir === "<")
|
|
222
|
+
throw new PsUnanalyzable("'<' is reserved in PowerShell");
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const target = i < n ? readValueTok() : null;
|
|
226
|
+
toks.push({ k: "redir", v: redir, target });
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (c === "-" && /[A-Za-z]/.test(src[i + 1] ?? "")) {
|
|
230
|
+
let j = i + 1;
|
|
231
|
+
while (j < n && /[A-Za-z0-9_-]/.test(src[j]))
|
|
232
|
+
j++;
|
|
233
|
+
const name = src.slice(i, j);
|
|
234
|
+
if (src[j] === ":") {
|
|
235
|
+
i = j + 1;
|
|
236
|
+
const value = readValueTok();
|
|
237
|
+
toks.push({ k: "param", v: name, value });
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
toks.push({ k: "param", v: name, value: null });
|
|
241
|
+
i = j;
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (c === "$" && /[A-Za-z_{?:]/.test(src[i + 1] ?? "")) {
|
|
245
|
+
let j = i + 1;
|
|
246
|
+
if (src[j] === "{") {
|
|
247
|
+
const e = src.indexOf("}", j);
|
|
248
|
+
if (e < 0)
|
|
249
|
+
throw new PsUnanalyzable("unterminated ${}");
|
|
250
|
+
j = e + 1;
|
|
251
|
+
}
|
|
252
|
+
else
|
|
253
|
+
while (j < n && /[A-Za-z0-9_:?]/.test(src[j]))
|
|
254
|
+
j++;
|
|
255
|
+
const name = src.slice(i + 1, j);
|
|
256
|
+
let k = j;
|
|
257
|
+
while (k < n && isWordChar(src[k]))
|
|
258
|
+
k++;
|
|
259
|
+
const tail = src.slice(j, k);
|
|
260
|
+
toks.push({ k: "var", name, tail });
|
|
261
|
+
i = k;
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
// Bareword
|
|
265
|
+
let j = i, v = "";
|
|
266
|
+
while (j < n) {
|
|
267
|
+
const ch = src[j];
|
|
268
|
+
if (ch === "`") {
|
|
269
|
+
v += src[j + 1] ?? "";
|
|
270
|
+
j += 2;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (!isWordChar(ch))
|
|
274
|
+
break;
|
|
275
|
+
v += ch;
|
|
276
|
+
j++;
|
|
277
|
+
}
|
|
278
|
+
if (j === i)
|
|
279
|
+
throw new PsUnanalyzable(`unexpected '${c}'`);
|
|
280
|
+
toks.push({ k: "word", v, dyn: v.includes("$"), pathish: v });
|
|
281
|
+
i = j;
|
|
282
|
+
}
|
|
283
|
+
while (i < n) {
|
|
284
|
+
const c = src[i];
|
|
285
|
+
if (c === " " || c === "\t" || c === "\r") {
|
|
286
|
+
i++;
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (c === "`" && (src[i + 1] === "\n" || src[i + 1] === "\r")) {
|
|
290
|
+
i += src[i + 1] === "\r" ? 3 : 2;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (c === "#") {
|
|
294
|
+
while (i < n && src[i] !== "\n")
|
|
295
|
+
i++;
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
if (c === "<" && src[i + 1] === "#") {
|
|
299
|
+
const e = src.indexOf("#>", i + 2);
|
|
300
|
+
if (e < 0)
|
|
301
|
+
throw new PsUnanalyzable("unterminated block comment");
|
|
302
|
+
i = e + 2;
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (c === "\n" || c === ";") {
|
|
306
|
+
toks.push({ k: "op", v: ";" });
|
|
307
|
+
i++;
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
if (c === "|" && src[i + 1] === "|") {
|
|
311
|
+
toks.push({ k: "op", v: ";" });
|
|
312
|
+
i += 2;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (c === "&" && src[i + 1] === "&") {
|
|
316
|
+
toks.push({ k: "op", v: ";" });
|
|
317
|
+
i += 2;
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if (c === "|") {
|
|
321
|
+
toks.push({ k: "op", v: "|" });
|
|
322
|
+
i++;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (c === "&") {
|
|
326
|
+
toks.push({ k: "op", v: "&" });
|
|
327
|
+
i++;
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (c === "=") {
|
|
331
|
+
toks.push({ k: "op", v: "=" });
|
|
332
|
+
i++;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (c === ",") {
|
|
336
|
+
i++;
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (c === "." && (src[i + 1] === " " || src[i + 1] === "\t") && (toks.length === 0 || toks[toks.length - 1]?.k === "op")) {
|
|
340
|
+
toks.push({ k: "op", v: "." });
|
|
341
|
+
i++;
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
if (c === "+" && (src[i + 1] === " " || src[i + 1] === "=")) {
|
|
345
|
+
i += src[i + 1] === "=" ? 2 : 1;
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
readOne();
|
|
349
|
+
}
|
|
350
|
+
return toks;
|
|
351
|
+
}
|
|
352
|
+
/** Subexpressions $( … ) inside an expandable string. */
|
|
353
|
+
function subexprs(s) {
|
|
354
|
+
const out = [];
|
|
355
|
+
for (let i = 0; i < s.length; i++) {
|
|
356
|
+
if (s[i] === "$" && s[i + 1] === "(") {
|
|
357
|
+
let depth = 0;
|
|
358
|
+
for (let j = i + 1; j < s.length; j++) {
|
|
359
|
+
if (s[j] === "(")
|
|
360
|
+
depth++;
|
|
361
|
+
else if (s[j] === ")") {
|
|
362
|
+
depth--;
|
|
363
|
+
if (depth === 0) {
|
|
364
|
+
out.push(s.slice(i + 2, j));
|
|
365
|
+
i = j;
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return out;
|
|
373
|
+
}
|
|
374
|
+
export function analyzePowerShell(src, st) {
|
|
375
|
+
const acc = new Acc();
|
|
376
|
+
if (src.length > st.maxBytes) {
|
|
377
|
+
acc.unanalyzable("command longer than the analysis limit");
|
|
378
|
+
return acc;
|
|
379
|
+
}
|
|
380
|
+
if (st.depth > 3) {
|
|
381
|
+
acc.unanalyzable("PowerShell nested too deep");
|
|
382
|
+
return acc;
|
|
383
|
+
}
|
|
384
|
+
let toks;
|
|
385
|
+
try {
|
|
386
|
+
toks = tokenize(src);
|
|
387
|
+
}
|
|
388
|
+
catch (e) {
|
|
389
|
+
acc.unanalyzable(e instanceof PsUnanalyzable ? e.reason : "PowerShell parse error");
|
|
390
|
+
return acc;
|
|
391
|
+
}
|
|
392
|
+
// Split into statements and pipeline elements.
|
|
393
|
+
const cwd = { cwd: st.pctx.cwd };
|
|
394
|
+
let element = [];
|
|
395
|
+
let upstream = null; // the previous element when the current one is piped into
|
|
396
|
+
let pipedNext = false;
|
|
397
|
+
const flush = (sep) => {
|
|
398
|
+
if (element.length)
|
|
399
|
+
analyzeElement(element, st, acc, cwd, pipedNext ? upstream : null);
|
|
400
|
+
upstream = element.length ? element : null;
|
|
401
|
+
pipedNext = sep === "|";
|
|
402
|
+
element = [];
|
|
403
|
+
};
|
|
404
|
+
for (const t of toks) {
|
|
405
|
+
if (t.k === "op" && (t.v === ";" || t.v === "|")) {
|
|
406
|
+
flush(t.v);
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
element.push(t);
|
|
410
|
+
}
|
|
411
|
+
flush(";");
|
|
412
|
+
// Same correlation as bash: a sensitive file and a network call in one command.
|
|
413
|
+
if (acc.network && (acc.sensitiveArgs || acc.envDump))
|
|
414
|
+
acc.find("CP-EXFIL-030", "sensitive file or environment and a network call in one command");
|
|
415
|
+
return acc;
|
|
416
|
+
}
|
|
417
|
+
function inner(src, st, acc, commandPosition, allowWrite) {
|
|
418
|
+
const a = analyzePowerShell(src, { ...st, depth: st.depth + 1 });
|
|
419
|
+
if (a.selfProtection) {
|
|
420
|
+
acc.selfProtection = true;
|
|
421
|
+
acc.tags.add("self-protection");
|
|
422
|
+
for (const f of a.findings)
|
|
423
|
+
if (f.ruleId.startsWith("CP-SELF"))
|
|
424
|
+
acc.find(f.ruleId, f.note);
|
|
425
|
+
acc.raise("high-risk");
|
|
426
|
+
}
|
|
427
|
+
if (commandPosition) {
|
|
428
|
+
acc.unanalyzable("command name comes from a subexpression");
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
if (a.unanalyzableFlag) {
|
|
432
|
+
acc.unanalyzable("subexpression contains an unanalyzable command");
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
if (a.level === "high-risk" || a.sensitive.length > 0) {
|
|
436
|
+
for (const t of a.tags)
|
|
437
|
+
acc.tags.add(t);
|
|
438
|
+
acc.unanalyzable("subexpression runs a dangerous command");
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
if (a.tags.has("exec.unknown") || a.tags.has("exec.project-code") || a.tags.has("exec.inline-code")) {
|
|
442
|
+
acc.unanalyzable("subexpression runs an unknown command");
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
if (a.level === "write-reversible") {
|
|
446
|
+
if (!allowWrite)
|
|
447
|
+
acc.raise("write-reversible");
|
|
448
|
+
for (const t of a.tags)
|
|
449
|
+
acc.tags.add(t);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* A recursive delete of this path destroys data a user can't easily get back: a drive or
|
|
454
|
+
* filesystem root, the home directory, everything in it (home/*), or a folder directly under it
|
|
455
|
+
* (Documents, Desktop, .ssh, a whole project). Deeper paths (node_modules, dist) don't count.
|
|
456
|
+
*/
|
|
457
|
+
function destroysTopLevel(path, pctx) {
|
|
458
|
+
if (path === null)
|
|
459
|
+
return false;
|
|
460
|
+
const home = normalizePath("~", pctx).path ?? "";
|
|
461
|
+
const lp = path.toLowerCase(), lh = home.toLowerCase();
|
|
462
|
+
if (/^[a-z]:\/?\*?$/i.test(path) || path === "/" || path === "/*")
|
|
463
|
+
return true;
|
|
464
|
+
if (lh !== "" && (lp === lh || lp === lh + "/"))
|
|
465
|
+
return true;
|
|
466
|
+
return homeTopLevel(path, pctx);
|
|
467
|
+
}
|
|
468
|
+
function tokText(t) {
|
|
469
|
+
if (!t)
|
|
470
|
+
return { value: null, pathValue: null };
|
|
471
|
+
if (t.k === "str")
|
|
472
|
+
return { value: t.dyn ? null : t.v, pathValue: t.dyn ? (/^\$env:USERPROFILE|^\$HOME/i.test(t.v) && !t.v.includes("$(") ? t.v : null) : t.v };
|
|
473
|
+
if (t.k === "word")
|
|
474
|
+
return { value: t.dyn ? null : t.v, pathValue: t.v };
|
|
475
|
+
if (t.k === "var") {
|
|
476
|
+
const full = "$" + t.name + t.tail;
|
|
477
|
+
const homeish = /^(env:USERPROFILE|HOME)$/i.test(t.name);
|
|
478
|
+
return { value: null, pathValue: homeish ? full : null };
|
|
479
|
+
}
|
|
480
|
+
return { value: null, pathValue: null };
|
|
481
|
+
}
|
|
482
|
+
function wi(t) {
|
|
483
|
+
const { value, pathValue } = tokText(t);
|
|
484
|
+
const word = value !== null ? litWord(value) : { parts: [{ t: "var", name: "X", braced: false, quoted: false }], raw: t.k === "word" ? t.v : t.k === "str" ? t.v : "$x", brace: false };
|
|
485
|
+
return { word, value, pathValue, suffix: "", dynamic: value === null, glob: false, substs: [] };
|
|
486
|
+
}
|
|
487
|
+
function np(t, pctx) {
|
|
488
|
+
const { pathValue } = tokText(t);
|
|
489
|
+
return pathValue === null ? null : normalizePath(pathValue, pctx);
|
|
490
|
+
}
|
|
491
|
+
function hasParam(params, full) {
|
|
492
|
+
const f = full.toLowerCase();
|
|
493
|
+
return params.some((p) => p.k === "param" && p.v.length >= 2 && f.startsWith(p.v.toLowerCase()));
|
|
494
|
+
}
|
|
495
|
+
function paramValue(el, ...names) {
|
|
496
|
+
for (let i = 0; i < el.length; i++) {
|
|
497
|
+
const t = el[i];
|
|
498
|
+
if (t.k !== "param")
|
|
499
|
+
continue;
|
|
500
|
+
const lower = t.v.toLowerCase();
|
|
501
|
+
if (names.some((n) => n.toLowerCase().startsWith(lower) && lower.length >= 3))
|
|
502
|
+
return t.value ?? el[i + 1] ?? null;
|
|
503
|
+
}
|
|
504
|
+
return null;
|
|
505
|
+
}
|
|
506
|
+
function positional(el) {
|
|
507
|
+
const out = [];
|
|
508
|
+
const switches = new Set(["-recurse", "-force", "-whatif", "-confirm", "-verbose", "-passthru", "-nonewline", "-append", "-raw", "-wait", "-file", "-directory", "-hidden", "-r", "-fo", "-rec", "-literalpath_s"]);
|
|
509
|
+
for (let i = 1; i < el.length; i++) {
|
|
510
|
+
const t = el[i];
|
|
511
|
+
if (t.k === "param") {
|
|
512
|
+
if (t.value === null && !switches.has(t.v.toLowerCase()) && !t.v.toLowerCase().startsWith("-rec") && el[i + 1] && el[i + 1]?.k !== "param")
|
|
513
|
+
i++;
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
if (t.k === "redir" || t.k === "op")
|
|
517
|
+
continue;
|
|
518
|
+
out.push(t);
|
|
519
|
+
}
|
|
520
|
+
return out;
|
|
521
|
+
}
|
|
522
|
+
function analyzeElement(el, st, acc, cwd, upstream = null) {
|
|
523
|
+
const pctx = { ...st.pctx, cwd: cwd.cwd };
|
|
524
|
+
// Destinations of copy/move/write cmdlets are writes, not sensitive reads.
|
|
525
|
+
const head0 = el[0];
|
|
526
|
+
const name0 = head0?.k === "word" ? head0.v.toLowerCase() : "";
|
|
527
|
+
const cmd0 = ALIASES.get(name0) ?? name0;
|
|
528
|
+
const writeDest = new Set();
|
|
529
|
+
if (["copy-item", "move-item", "set-content", "add-content", "out-file", "new-item", "rename-item", "tee-object"].includes(cmd0)) {
|
|
530
|
+
const pos0 = positional(el);
|
|
531
|
+
const last = cmd0 === "copy-item" || cmd0 === "move-item" ? pos0[pos0.length - 1] : pos0[0];
|
|
532
|
+
if (last)
|
|
533
|
+
writeDest.add(last);
|
|
534
|
+
const dest = paramValue(el, "-Destination");
|
|
535
|
+
if (dest)
|
|
536
|
+
writeDest.add(dest);
|
|
537
|
+
}
|
|
538
|
+
// Nested pieces anywhere in the element.
|
|
539
|
+
el.forEach((t, idx) => {
|
|
540
|
+
if (t.k === "sub")
|
|
541
|
+
inner(t.inner, st, acc, idx === 0 || (idx === 1 && el[0]?.k === "op"), true);
|
|
542
|
+
if (t.k === "str")
|
|
543
|
+
for (const s of t.subs)
|
|
544
|
+
inner(s, st, acc, false, true);
|
|
545
|
+
if (t.k === "paren" && idx > 0)
|
|
546
|
+
inner(t.inner, st, acc, false, true);
|
|
547
|
+
if (t.k === "block" && idx > 0) {
|
|
548
|
+
const a = analyzePowerShell(t.inner, { ...st, depth: st.depth + 1 });
|
|
549
|
+
acc.merge(a);
|
|
550
|
+
}
|
|
551
|
+
if (t.k === "type" && t.staticCall && !STATIC_OK.test(t.staticCall))
|
|
552
|
+
acc.unanalyzable(`static .NET call ${t.staticCall.slice(0, 60)}`);
|
|
553
|
+
if (t.k === "redir" && t.target) {
|
|
554
|
+
const p = np(t.target, pctx);
|
|
555
|
+
if (p === null) {
|
|
556
|
+
acc.unanalyzable("redirects to a path that isn't known statically");
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
if (isProtected(p, pctx) || isProtectedRead(p, pctx))
|
|
560
|
+
acc.protect("CP-SELF-001", "writes a file that controls the agent or Glassbox");
|
|
561
|
+
acc.tag("write-reversible", "fs.write");
|
|
562
|
+
}
|
|
563
|
+
if (t.k === "word" || t.k === "str" || t.k === "var") {
|
|
564
|
+
const p = np(t, pctx);
|
|
565
|
+
if (p && (t.k !== "word" || /[\\/~.]/.test(t.v))) {
|
|
566
|
+
if (isProtectedRead(p, pctx))
|
|
567
|
+
acc.protect("CP-SELF-002", "reads a Glassbox credential file");
|
|
568
|
+
const label = idx > 0 && !writeDest.has(t) ? sensitiveLabel(p, pctx) : null;
|
|
569
|
+
if (label && !acc.selfProtection) {
|
|
570
|
+
acc.tags.add("fs.read.sensitive");
|
|
571
|
+
acc.sensitive.push(label);
|
|
572
|
+
acc.sensitiveArgs = true;
|
|
573
|
+
acc.find("CP-EXFIL-040", label);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
let head = el[0];
|
|
579
|
+
if (!head)
|
|
580
|
+
return;
|
|
581
|
+
// Assignment: $x = …
|
|
582
|
+
if (head.k === "var" && el[1]?.k === "op" && el[1].v === "=") {
|
|
583
|
+
const name = head.name.toLowerCase();
|
|
584
|
+
if (["env:path", "env:psmodulepath", "profile", "env:pathext", "env:comspec", "psdefaultparametervalues", "executioncontext"].includes(name))
|
|
585
|
+
acc.unanalyzable(`assignment to $${head.name} changes what later commands run`);
|
|
586
|
+
const rhs = el.slice(2);
|
|
587
|
+
if (rhs[0]?.k === "word" || (rhs[0]?.k === "op" && rhs[0].v === "&"))
|
|
588
|
+
analyzeElement(rhs, st, acc, cwd);
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
// Call operators.
|
|
592
|
+
let callOp = false;
|
|
593
|
+
if (head.k === "op" && (head.v === "&" || head.v === ".")) {
|
|
594
|
+
callOp = true;
|
|
595
|
+
const target = el[1];
|
|
596
|
+
const { value } = tokText(target);
|
|
597
|
+
if (!target || value === null) {
|
|
598
|
+
acc.unanalyzable(`'${head.v}' with a non-literal target`);
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
el = [{ k: "word", v: value, dyn: false, pathish: value }, ...el.slice(2)];
|
|
602
|
+
head = el[0];
|
|
603
|
+
}
|
|
604
|
+
if (head.k !== "word") {
|
|
605
|
+
// Expression statement (string, variable, number, paren…): only its pieces matter.
|
|
606
|
+
if (head.k === "block")
|
|
607
|
+
acc.merge(analyzePowerShell(head.inner, { ...st, depth: st.depth + 1 }));
|
|
608
|
+
if (head.k === "paren")
|
|
609
|
+
inner(head.inner, st, acc, false, false);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (head.dyn) {
|
|
613
|
+
acc.unanalyzable("command name isn't literal");
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const name = head.v.toLowerCase().replace(/\.exe$/, "");
|
|
617
|
+
const base = name.includes("\\") || name.includes("/") ? (name.split(/[\\/]/).pop() ?? name) : name;
|
|
618
|
+
const cmdlet = ALIASES.get(base) ?? base;
|
|
619
|
+
const params = el.filter((t) => t.k === "param");
|
|
620
|
+
const pos = positional(el);
|
|
621
|
+
const reason = UNANALYZABLE.get(cmdlet);
|
|
622
|
+
if (reason) {
|
|
623
|
+
acc.unanalyzable(reason);
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (cmdlet === "start-process") {
|
|
627
|
+
const file = paramValue(el, "-FilePath") ?? pos[0];
|
|
628
|
+
const args = paramValue(el, "-ArgumentList");
|
|
629
|
+
if (!file || tokText(file).value === null || (args && tokText(args).value === null)) {
|
|
630
|
+
acc.unanalyzable("Start-Process with a non-literal program or arguments");
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
if (params.some((p) => p.k === "param" && p.v.toLowerCase().startsWith("-verb")) && el.some((t) => (t.k === "word" || t.k === "str") && /^runas$/i.test(t.v)))
|
|
634
|
+
acc.tag("high-risk", "perm.change");
|
|
635
|
+
acc.tag("write-reversible", "exec.unknown");
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
if (base === "powershell" || base === "pwsh") {
|
|
639
|
+
if (params.some((p) => p.k === "param" && /^-(e|ec|en|enc|enco|encod|encode|encoded|encodedc|encodedcommand)$/i.test(p.v))) {
|
|
640
|
+
acc.unanalyzable("encoded PowerShell command");
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
const cmd = paramValue(el, "-Command");
|
|
644
|
+
if (cmd) {
|
|
645
|
+
const { value } = tokText(cmd);
|
|
646
|
+
if (value === null) {
|
|
647
|
+
acc.unanalyzable("PowerShell -Command with a non-literal command");
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
acc.merge(analyzePowerShell(value, { ...st, depth: st.depth + 1 }));
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
if (paramValue(el, "-File")) {
|
|
654
|
+
acc.tag("write-reversible", "exec.project-code");
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
acc.unanalyzable("nested PowerShell reads commands it can't see");
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
if (base === "cmd") {
|
|
661
|
+
acc.unanalyzable("cmd.exe syntax isn't analyzed");
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
const pathTargets = () => {
|
|
665
|
+
const named = [paramValue(el, "-Path"), paramValue(el, "-LiteralPath"), paramValue(el, "-Destination"), paramValue(el, "-FilePath"), paramValue(el, "-OutFile")].filter((x) => x !== null);
|
|
666
|
+
return [...named, ...pos.filter((t) => t.k !== "block")];
|
|
667
|
+
};
|
|
668
|
+
const isRegistry = (t) => /^(hk(lm|cu|cr|u|cc):|registry::)/i.test(tokText(t).pathValue ?? "");
|
|
669
|
+
const policyKey = (t) => (tokText(t).pathValue ?? "").toLowerCase().replace(/[\\/]/g, "").includes("policiesclaudecode");
|
|
670
|
+
if (READ.has(cmdlet)) {
|
|
671
|
+
if (cmdlet === "set-location") {
|
|
672
|
+
const t = pos[0] ?? paramValue(el, "-Path");
|
|
673
|
+
const p = np(t, pctx);
|
|
674
|
+
cwd.cwd = p?.path ?? null;
|
|
675
|
+
}
|
|
676
|
+
if (cmdlet === "get-itemproperty" && pathTargets().some(policyKey))
|
|
677
|
+
return;
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
if (["set-itemproperty", "new-itemproperty", "remove-itemproperty", "clear-itemproperty", "rename-itemproperty"].includes(cmdlet) || ((cmdlet === "new-item" || cmdlet === "remove-item" || cmdlet === "set-item") && pathTargets().some(isRegistry))) {
|
|
681
|
+
if (pathTargets().some(policyKey)) {
|
|
682
|
+
acc.protect("CP-SELF-003", "changes Claude Code policy in the registry");
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
acc.tag("high-risk", "config.agent");
|
|
686
|
+
acc.reason("changes the Windows registry");
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
if (cmdlet === "remove-item" || cmdlet === "clear-content" || cmdlet === "clear-item") {
|
|
690
|
+
acc.tag("high-risk", "fs.delete");
|
|
691
|
+
let recurse = hasParam(params, "-Recurse");
|
|
692
|
+
let targets = pathTargets();
|
|
693
|
+
let narrowed = false;
|
|
694
|
+
if (targets.length === 0 && upstream) {
|
|
695
|
+
// `Get-ChildItem <path> [-Recurse] | Remove-Item`: the items come from the upstream path.
|
|
696
|
+
const up = upstream[0];
|
|
697
|
+
const upName = up?.k === "word" ? (ALIASES.get(up.v.toLowerCase()) ?? up.v.toLowerCase()) : "";
|
|
698
|
+
if (upName !== "get-childitem" && upName !== "get-item") {
|
|
699
|
+
acc.unanalyzable("deletes whatever an earlier pipeline stage produces");
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
const upParams = upstream.filter((t) => t.k === "param");
|
|
703
|
+
const upTargets = [paramValue(upstream, "-Path"), paramValue(upstream, "-LiteralPath"), ...positional(upstream)].filter((x) => x !== null);
|
|
704
|
+
// A filter or a wildcard narrows what is deleted: not a whole-folder delete.
|
|
705
|
+
narrowed = hasParam(upParams, "-Filter") || hasParam(upParams, "-Include") || upTargets.some((t) => /[*?]/.test(tokText(t).pathValue ?? ""));
|
|
706
|
+
targets = upTargets.length > 0 ? upTargets : [{ k: "word", v: ".", dyn: false, pathish: "." }];
|
|
707
|
+
recurse ||= hasParam(upParams, "-Recurse");
|
|
708
|
+
}
|
|
709
|
+
for (const t of targets) {
|
|
710
|
+
const p = np(t, pctx);
|
|
711
|
+
if (p === null) {
|
|
712
|
+
acc.unanalyzable("deletes a path that isn't known statically");
|
|
713
|
+
continue;
|
|
714
|
+
}
|
|
715
|
+
if (isProtectedWrite(p, pctx, /[*?[]/.test(p.path ?? "")))
|
|
716
|
+
acc.protect("CP-SELF-001", "deletes a file that controls the agent or Glassbox");
|
|
717
|
+
acc.persist(persistenceHit(p, pctx), "deletes", p.path);
|
|
718
|
+
acc.wrote(p.path);
|
|
719
|
+
if (recurse && !narrowed && destroysTopLevel(p.path, pctx)) {
|
|
720
|
+
acc.tag("high-risk", "fs.destroy");
|
|
721
|
+
acc.find("CP-ACTION-001", "deletes a whole drive, the home directory or a top-level folder in it");
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
// Scheduled tasks and services (rev 9): ask with the schedule and the command (CP-SELF-006).
|
|
727
|
+
// Register-ScheduledTask's action and trigger are usually built earlier in the script; the
|
|
728
|
+
// gate reads them from the whole command (psTaskJob).
|
|
729
|
+
if (cmdlet === "register-scheduledtask" || cmdlet === "register-scheduledjob" || cmdlet === "set-scheduledtask") {
|
|
730
|
+
acc.scheduleJob({ kind: "task-scheduler", verb: cmdlet === "set-scheduledtask" ? "changes" : "creates", path: null, schedule: null, files: [] });
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if (cmdlet === "unregister-scheduledtask" || cmdlet === "unregister-scheduledjob") {
|
|
734
|
+
acc.scheduleJob({ kind: "task-scheduler", verb: "removes", path: null, schedule: null, files: [] });
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
if (cmdlet === "new-service" || cmdlet === "set-service" && hasParam(params, "-StartupType")) {
|
|
738
|
+
const bin = paramValue(el, "-BinaryPathName");
|
|
739
|
+
const start = paramValue(el, "-StartupType");
|
|
740
|
+
const binText = bin ? tokText(bin).value : null;
|
|
741
|
+
acc.scheduleJob({ kind: "service", verb: cmdlet === "new-service" ? "creates" : "changes", path: null, schedule: start ? `startup type ${tokText(start).value ?? "?"}` : "as a Windows service", files: binText ? commandFiles(binText) : [] });
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
if (cmdlet === "clear-history" || (cmdlet === "set-psreadlineoption" && (hasParam(params, "-AddToHistoryHandler") || /savenothing/i.test(el.map((t) => tokText(t).value ?? "").join(" "))))) {
|
|
745
|
+
acc.tag("high-risk", "fs.delete");
|
|
746
|
+
acc.find("CP-ACTION-030", `${cmdlet} clears or stops PowerShell history`);
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
if (DISK_WIPE.has(cmdlet)) {
|
|
750
|
+
acc.tag("high-risk", "fs.destroy");
|
|
751
|
+
acc.find("CP-ACTION-001", `${cmdlet} erases a disk, partition or the recycle bin`);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (SYSTEM_STATE.has(cmdlet)) {
|
|
755
|
+
acc.tag("high-risk", "infra.change");
|
|
756
|
+
acc.reason(`${cmdlet} changes the machine's power or service state`);
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
if (TAMPER.has(cmdlet)) {
|
|
760
|
+
acc.tag("high-risk", "perm.change");
|
|
761
|
+
acc.reason(`${cmdlet} changes logs, Defender settings or accounts`);
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (WRITE.has(cmdlet)) {
|
|
765
|
+
acc.tag("write-reversible", cmdlet === "move-item" || cmdlet === "rename-item" ? "fs.move" : "fs.write");
|
|
766
|
+
const targets = pathTargets();
|
|
767
|
+
const writeTargets = cmdlet === "copy-item" || cmdlet === "move-item" ? (paramValue(el, "-Destination") ? [paramValue(el, "-Destination")] : targets.slice(-1)) : targets.slice(0, cmdlet === "set-content" || cmdlet === "add-content" ? 1 : targets.length);
|
|
768
|
+
for (const t of [...writeTargets, ...(cmdlet === "move-item" || cmdlet === "rename-item" ? targets : [])]) {
|
|
769
|
+
const p = np(t, pctx);
|
|
770
|
+
if (p === null) {
|
|
771
|
+
acc.unanalyzable("writes a path that isn't known statically");
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
if (isProtectedWrite(p, pctx, /[*?[]/.test(p.path ?? "")))
|
|
775
|
+
acc.protect("CP-SELF-001", "changes a file that controls the agent or Glassbox");
|
|
776
|
+
acc.persist(persistenceHit(p, pctx), "changes", p.path);
|
|
777
|
+
acc.wrote(p.path);
|
|
778
|
+
const lp = (p.path ?? "").toLowerCase();
|
|
779
|
+
if (lp.endsWith("profile.ps1") || lp.includes("/.git/hooks/"))
|
|
780
|
+
acc.tag("high-risk", "config.agent");
|
|
781
|
+
}
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
if (NETWORK.has(cmdlet)) {
|
|
785
|
+
const dest = paramValue(el, "-Uri") ?? paramValue(el, "-SmtpServer") ?? (cmdlet === "send-mailmessage" ? null : positional(el)[0] ?? null);
|
|
786
|
+
const loop = allLoopback(dest ? [tokText(dest).value] : []);
|
|
787
|
+
if (!loop) {
|
|
788
|
+
acc.tag("high-risk", "net.egress");
|
|
789
|
+
acc.network = true;
|
|
790
|
+
}
|
|
791
|
+
// Uploads: -InFile, and -Attachments (comma-separated).
|
|
792
|
+
const files = [];
|
|
793
|
+
const inFile = paramValue(el, "-InFile");
|
|
794
|
+
if (inFile)
|
|
795
|
+
files.push(tokText(inFile).pathValue);
|
|
796
|
+
const att = paramValue(el, "-Attachments");
|
|
797
|
+
if (att) {
|
|
798
|
+
const v = tokText(att).pathValue;
|
|
799
|
+
if (v === null)
|
|
800
|
+
files.push(null);
|
|
801
|
+
else
|
|
802
|
+
files.push(...v.split(",").map((x) => x.trim()).filter(Boolean));
|
|
803
|
+
}
|
|
804
|
+
if (cmdlet === "send-mailmessage") {
|
|
805
|
+
// Further positional words after -Attachments a, b are more attachments.
|
|
806
|
+
const i = el.findIndex((t) => t.k === "param" && t.v.toLowerCase() === "-attachments");
|
|
807
|
+
for (let k = i + 2; i >= 0 && k < el.length && el[k]?.k !== "param"; k++) {
|
|
808
|
+
const t = tokText(el[k]);
|
|
809
|
+
if (t.pathValue !== null && t.pathValue !== ",")
|
|
810
|
+
files.push(t.pathValue.replace(/^,|,$/g, ""));
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (!loop) {
|
|
814
|
+
for (const f of files) {
|
|
815
|
+
const p = f === null ? null : np({ k: "word", v: f, dyn: false }, pctx);
|
|
816
|
+
recordUpload(acc, classifyUpload(p, pctx, st.pctx.cwd), f ?? "a file named at run time");
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
if (PERM.has(cmdlet)) {
|
|
822
|
+
acc.tag("high-risk", "perm.change");
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
if (cmdlet === "new-object") {
|
|
826
|
+
if (el.some((t) => (t.k === "word" || t.k === "str") && /net\.(webclient|sockets)|system\.net/i.test(t.v))) {
|
|
827
|
+
acc.tag("high-risk", "net.egress");
|
|
828
|
+
acc.network = true;
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
acc.unanalyzable("New-Object creates arbitrary .NET objects");
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
if (cmdlet === "stop-process") {
|
|
835
|
+
acc.tag("write-reversible", "exec.unknown");
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
if (/^[a-z]+-[a-z]+$/.test(cmdlet) && !callOp) {
|
|
839
|
+
acc.tag("write-reversible", "exec.unknown");
|
|
840
|
+
acc.reason(`runs the cmdlet ${cmdlet.slice(0, 40)}`);
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
// Native program: same rules as the bash command table.
|
|
844
|
+
const args = el.slice(1).filter((t) => t.k !== "redir").map((t) => (t.k === "param" ? wi({ k: "word", v: t.v, dyn: false, pathish: t.v }) : wi(t)));
|
|
845
|
+
const fake = { kind: "simple", assigns: [], words: [litWord(base)], redirects: [], pipedIn: false, pipedFrom: null };
|
|
846
|
+
classifyNative(base, args, fake, { pctx, depth: st.depth, maxBytes: st.maxBytes }, acc, cwd);
|
|
847
|
+
}
|
|
848
|
+
//# sourceMappingURL=powershell.js.map
|