dsh-cmd-guard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Shell-syntax normalization, applied before any layer reads a token.
3
+ *
4
+ * The rules layer originally compared `tokens[0]` against a verb list. That is
5
+ * correct only for a command typed plainly. Measured evasions that reached the
6
+ * delete verb through a shape it never compared against:
7
+ *
8
+ * r\m -rf / backslash escape inside the word
9
+ * r""m -rf / quote removal inside the word
10
+ * rm$IFS-rf$IFS/ $IFS as the separator
11
+ * sudo rm -rf / wrapper in head position
12
+ * FOO=bar rm -rf / environment prefix in head position
13
+ * eval "rm -rf /" quoted payload as a single token
14
+ *
15
+ * Each is ordinary shell syntax, not an exotic trick, so they are normalized
16
+ * rather than listed. The output is not a simulation of the shell - it is the
17
+ * string a human would have read had the command been written plainly.
18
+ *
19
+ * De-obfuscation is applied to the command word ONLY. Paths keep their
20
+ * backslashes: `HKLM\SOFTWARE\...\CurrentVersion\Run` was measured losing every
21
+ * separator to the escape rule, which silently disabled the registry check.
22
+ * A path is compared as written; only a verb gets rewritten.
23
+ *
24
+ * Deliberately NOT normalized: `$VAR` other than IFS, and any expansion that
25
+ * requires running something. Those cannot be resolved statically, and the
26
+ * layers downstream are expected to treat the unresolved form as an ask.
27
+ */
28
+ import { tokenize, isAbsolutePath, hasParentEscape, isVolatilePath } from './lexical.js';
29
+ import { HUNT_STOP, HUNT_VERBS, SHELL_KEYWORDS } from './verbs.js';
30
+ /**
31
+ * Fold the spellings a human reads as ASCII back to ASCII.
32
+ *
33
+ * Measured evasions that no layer saw as a verb, because each one contains a
34
+ * character the comparison was not written for:
35
+ *
36
+ * rm -rf / fullwidth latin (NFKC folds it to "rm")
37
+ * rm -rf / zero-width space after the verb
38
+ * r-m -rf / soft hyphen inside the verb
39
+ * rm -rf / junk NUL standing in for a separator
40
+ *
41
+ * None of these is a trick a shell performs; they are characters that render
42
+ * as nothing or as their ASCII twin. Folding is the whole fix, and it has to
43
+ * happen before tokenizing, since a tokenizer that has never met U+200B will
44
+ * happily return a token that only looks like "rm".
45
+ */
46
+ export function canonicalCommand(cmd) {
47
+ // Called from the pipeline with whatever the caller supplied. A missing
48
+ // string is an empty command, not an exception: a guard that throws on a
49
+ // well-formed call fails in the one direction it must never fail.
50
+ if (typeof cmd !== 'string')
51
+ return '';
52
+ return cmd
53
+ .normalize('NFKC')
54
+ .replace(/[\u200b-\u200f\u2060\ufeff]/g, '')
55
+ .replace(/\u00ad/g, '')
56
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, ' ');
57
+ }
58
+ /** `$IFS` and `${IFS}` are the field separator, i.e. whitespace. */
59
+ export function expandIfs(value) {
60
+ return value.replace(/\$\{IFS\}|\$IFS/gi, ' ');
61
+ }
62
+ /**
63
+ * A token with quoting removed but structure intact.
64
+ *
65
+ * This is what path comparisons read. Quotes are syntax rather than content,
66
+ * so `"C:\Windows"` and `C:\Windows` are the same target; backslashes are not,
67
+ * so they stay.
68
+ */
69
+ export function plainToken(token) {
70
+ return token.replace(/["'`]/g, '');
71
+ }
72
+ /**
73
+ * A command word with the ways of spelling it without looking like itself
74
+ * undone: `r\m`, `r""m`, `p^ython`, `rm$IFS-rf`.
75
+ *
76
+ * Applied to the head only. A verb never contains a path separator, so the
77
+ * escape rule cannot damage anything that matters here, and it cannot damage
78
+ * a path because paths are never passed through this function.
79
+ */
80
+ export function deobfuscateToken(token) {
81
+ return expandIfs(token)
82
+ .replace(/\\([A-Za-z0-9])/g, '$1')
83
+ .replace(/\$(["'`])/g, '$1')
84
+ .replace(/["'`^]/g, '');
85
+ }
86
+ /**
87
+ * Programs that run the rest of the line rather than doing work themselves.
88
+ *
89
+ * `start /b del ...` and `call del ...` on Windows, `sudo`/`nice`/`timeout`
90
+ * onwards on POSIX. Each hides the real head one token further along, and the
91
+ * rules layer never looked past the first.
92
+ */
93
+ export const WRAPPERS = new Set([
94
+ 'sudo',
95
+ 'doas',
96
+ 'su',
97
+ 'runas',
98
+ 'env',
99
+ 'nice',
100
+ 'nohup',
101
+ 'timeout',
102
+ 'exec',
103
+ 'command',
104
+ 'builtin',
105
+ 'xargs',
106
+ 'start',
107
+ 'call',
108
+ 'eval',
109
+ // Nested shells put the work one token along: `cmd /c del ...` and
110
+ // `powershell -c "rm -rf /"` were both passing untouched.
111
+ 'cmd',
112
+ 'powershell',
113
+ 'pwsh',
114
+ 'script',
115
+ ]);
116
+ /** The wrapper's own flags and bare numeric arguments. */
117
+ const WRAPPER_ARG = /^[-/][A-Za-z0-9:,_=./\\-]*$/;
118
+ const BARE_NUMBER = /^\d+$/;
119
+ /**
120
+ * The verb a token spells, with the ways of spelling it without looking like
121
+ * itself undone, and with any path stripped.
122
+ *
123
+ * Measured evasions that reached a verb the head comparison never saw:
124
+ * `./rm -rf /`, `/bin/rm -rf /`, `rm.exe -rf C:\`, and the full path form.
125
+ * The verb is the last component; where it lives is not part of its identity.
126
+ */
127
+ export function stemVerb(token) {
128
+ const plain = plainToken(token);
129
+ const base = looksLikePath(plain) ? (plain.split(/[\\/]/).pop() ?? plain) : plain;
130
+ return deobfuscateToken(base).toLowerCase().replace(/^\$/, '').replace(/\.exe$/, '');
131
+ }
132
+ /**
133
+ * Does this token name a location rather than a word?
134
+ *
135
+ * The distinction cannot be skipped: `r\m` is one word spelled with an
136
+ * escape, and `C:\msys64\usr\bin\rm.exe` is one word behind five
137
+ * separators. De-obfuscating first turned the second into `c:msys64usrbinrm`.
138
+ */
139
+ function looksLikePath(plain) {
140
+ if (/^[A-Za-z]:[\\/]/.test(plain))
141
+ return true;
142
+ if (plain.includes('/'))
143
+ return true;
144
+ if (plain.includes('\\\\'))
145
+ return true;
146
+ return (plain.match(/\\/g) ?? []).length >= 2;
147
+ }
148
+ /** Is this token one of the words that decides what happens to a path? */
149
+ export function isHuntVerb(token) {
150
+ return HUNT_VERBS.has(stemVerb(token));
151
+ }
152
+ /** A token that could plausibly be an argument to a wrapper. */
153
+ function isPrefixArg(token) {
154
+ const plain = plainToken(token);
155
+ if (plain.includes(' '))
156
+ return false;
157
+ return WRAPPER_ARG.test(plain) || BARE_NUMBER.test(plain) || /[\\/]/.test(plain);
158
+ }
159
+ export function headTokens(tokens) {
160
+ let i = 0;
161
+ while (i < tokens.length) {
162
+ const token = tokens[i];
163
+ if (token === undefined)
164
+ break;
165
+ const stem = stemVerb(token);
166
+ // FOO=bar in head position.
167
+ if (/^[a-z_][a-z0-9_]*=/i.test(stem)) {
168
+ i += 1;
169
+ continue;
170
+ }
171
+ if (SHELL_KEYWORDS.has(stem)) {
172
+ i += 1;
173
+ continue;
174
+ }
175
+ if (WRAPPERS.has(stem)) {
176
+ i += 1;
177
+ // The wrapper's own flags, paths and bare numbers, but stop at a verb:
178
+ // `sudo /bin/rm -rf /` must not read `/bin/rm` as an argument.
179
+ while (i < tokens.length) {
180
+ const arg = tokens[i];
181
+ if (arg === undefined)
182
+ break;
183
+ if (isHuntVerb(arg))
184
+ break;
185
+ if (!isPrefixArg(arg))
186
+ break;
187
+ i += 1;
188
+ }
189
+ continue;
190
+ }
191
+ // A verb in head position is the answer.
192
+ if (isHuntVerb(stem))
193
+ break;
194
+ // An unrecognised head may be a wrapper nobody listed. Hunt a short way
195
+ // ahead for the real verb, unless this head's tail is known to be data.
196
+ if (HUNT_STOP.has(stem))
197
+ break;
198
+ let found = -1;
199
+ const limit = Math.min(tokens.length, i + 4);
200
+ for (let j = i + 1; j < limit; j += 1) {
201
+ const probe = tokens[j];
202
+ if (probe === undefined)
203
+ break;
204
+ if (isHuntVerb(probe)) {
205
+ found = j;
206
+ break;
207
+ }
208
+ if (!isPrefixArg(probe))
209
+ break;
210
+ }
211
+ // Not a wrapper shape: this head is what it is.
212
+ if (found < 0)
213
+ break;
214
+ // Found the verb behind the wrapper. Leaving it in head position and
215
+ // looping again made `i` stand still, which hung the whole pipeline.
216
+ i = found;
217
+ break;
218
+ }
219
+ return tokens.slice(i);
220
+ }
221
+ /**
222
+ * Effective tokens: separators expanded, wrappers stripped, and a quoted
223
+ * payload re-tokenized so `eval "rm -rf /"` is judged as `rm -rf /`.
224
+ */
225
+ export function effectiveTokens(cmd) {
226
+ let tokens = tokenize(expandIfs(cmd));
227
+ for (let depth = 0; depth < 3; depth += 1) {
228
+ const eff = headTokens(tokens);
229
+ const head = eff[0];
230
+ if (head === undefined)
231
+ return eff;
232
+ if (!/\s/.test(head))
233
+ return eff;
234
+ tokens = tokenize(expandIfs(deobfuscateToken(head)));
235
+ }
236
+ return headTokens(tokens);
237
+ }
238
+ /**
239
+ * Is any redirection target outside the workspace?
240
+ *
241
+ * `echo "const x = 1" > src/x.ts` is one command writing one relative file,
242
+ * and it was being asked as a chain. A redirect into a relative, non-escaping
243
+ * path is not a second stage. One into an absolute path, above the workspace,
244
+ * or into a volatile root is still worth surfacing.
245
+ *
246
+ * Returns true when the command has no readable target at all, so an
247
+ * unparseable redirect fails closed.
248
+ */
249
+ export function hasUnsafeRedirectTarget(cmd) {
250
+ const re = />>?|<(?![(<])/g;
251
+ let match = re.exec(cmd);
252
+ if (match === null)
253
+ return true;
254
+ while (match !== null) {
255
+ const rest = cmd.slice(match.index + match[0].length).trim();
256
+ const target = rest.split(/\s+/)[0] ?? '';
257
+ if (target.length === 0)
258
+ return true;
259
+ const cleaned = plainToken(target);
260
+ if (isAbsolutePath(cleaned) || hasParentEscape(cleaned) || isVolatilePath(cleaned))
261
+ return true;
262
+ match = re.exec(cmd);
263
+ }
264
+ return false;
265
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Layer 3: obfuscation.
3
+ *
4
+ * These are signals, not proofs. Any one of them means the literal text is not
5
+ * a faithful description of what will run, so the ask is about readability
6
+ * rather than about intent.
7
+ */
8
+ import type { Finding, GuardInput, GuardState } from './types.js';
9
+ export declare function check(input: GuardInput, _state: GuardState): Finding | null;
@@ -0,0 +1,89 @@
1
+ import { hasCaretInsideWord } from './lexical.js';
2
+ const SIGNALS = [
3
+ {
4
+ code: 'OBF_BASE64_EXEC',
5
+ test: (c) => /b64decode|base64[^;]*decode/i.test(c) && /exec|eval|compile/i.test(c),
6
+ reason: 'Base64 decoding feeding an evaluator: the executed text is not in the command.',
7
+ },
8
+ {
9
+ code: 'OBF_CHAR_ASSEMBLY',
10
+ test: (c) => /\[char\]\s*\d+/i.test(c) || /fromcharcode/i.test(c),
11
+ reason: 'Character codes assembled at runtime: the literal command never appears in the string.',
12
+ },
13
+ {
14
+ code: 'OBF_DYNAMIC_IMPORT',
15
+ test: (c) => /__import__|__builtins__|getattr\s*\(\s*__/i.test(c),
16
+ reason: 'Dynamic import via dunder access, used to dodge static inspection.',
17
+ },
18
+ {
19
+ code: 'OBF_BINARY_LOADER',
20
+ test: (c) => /ctypes|mmap\s*\(|virtualalloc|memcpy\s*\(/i.test(c),
21
+ reason: 'Native-code loader primitives.',
22
+ },
23
+ {
24
+ code: 'OBF_HEX_ESCAPES',
25
+ test: (c) => /(?:\\x[0-9a-f]{2}){4,}/i.test(c),
26
+ reason: 'Long hex-escape run: an encoded payload with no readable form.',
27
+ },
28
+ {
29
+ code: 'OBF_DOWNLOAD_EXECUTE',
30
+ // `iex (iwr ...)` is the canonical one-liner. Downloading alone is not a
31
+ // signal - `iwr` to a file is ordinary - but feeding the response into an
32
+ // evaluator means the command on screen is not what runs.
33
+ test: (c) => /\b(iex|invoke-expression)\b/i.test(c),
34
+ reason: 'Invoke-Expression evaluates text fetched at runtime. The executed command is not in this string.',
35
+ },
36
+ {
37
+ code: 'OBF_CERTUTIL_DECODE',
38
+ // certutil is legitimate for hashing and certificate work; only the
39
+ // download and decode verbs turn it into a payload carrier. Measured
40
+ // bypass: `certutil -urlcache -f <url> a.exe` and `-decode a.b64 a.exe`
41
+ // both passed with nothing objecting.
42
+ test: (c) => /\bcertutil(?:\.exe)?\b/i.test(c) && /(?:^|\s)-(?:urlcache|decode|decodehex)\b/i.test(c),
43
+ reason: 'certutil used as a downloader or decoder. The real payload is not readable in this command.',
44
+ },
45
+ {
46
+ code: 'OBF_STRING_CONCAT',
47
+ // Measured bypass: `"pyth"+"on" -c x` passed. The head token is a quoted
48
+ // fragment, so no interpreter or verb matching can see what it builds.
49
+ test: (c) => /(^|\s)['"][^'"\s]*['"]\s*\+\s*['"]/.test(c),
50
+ reason: 'A word is assembled by concatenation. The literal text is not the command that runs.',
51
+ },
52
+ {
53
+ code: 'OBF_BITSADMIN_TRANSFER',
54
+ // Measured bypass: `bitsadmin /transfer j <url> C:\a.exe` passed. It is a
55
+ // downloader built into Windows, used for exactly this.
56
+ test: (c) => /\bbitsadmin(?:\.exe)?\b/i.test(c) && /\/transfer\b/i.test(c),
57
+ reason: 'BITS is being used to transfer a payload. What lands on disk is not in this command.',
58
+ },
59
+ {
60
+ code: 'OBF_DOWNLOAD_TO_EXECUTABLE',
61
+ // Fetching an executable image to local disk is the first half of a
62
+ // download-and-run chain, and the second half is not visible here.
63
+ // Measured bypass: `iwr <url>/a.exe -OutFile a.exe` passed.
64
+ test: (c) => /\b(curl|wget|iwr|invoke-webrequest|start-bitstransfer)\b/i.test(c) &&
65
+ /\.(exe|dll|ps1|bat|cmd|scr|vbs|jse|wsf|hta)\b/i.test(c),
66
+ reason: 'A remote executable is being fetched to local disk. Running it is one step away and not visible here.',
67
+ },
68
+ ];
69
+ export function check(input, _state) {
70
+ for (const signal of SIGNALS) {
71
+ if (signal.test(input.cmd)) {
72
+ return {
73
+ layer: 'obfusc',
74
+ verdict: 'ask',
75
+ code: signal.code,
76
+ reason: signal.reason,
77
+ };
78
+ }
79
+ }
80
+ if (hasCaretInsideWord(input.cmd)) {
81
+ return {
82
+ layer: 'obfusc',
83
+ verdict: 'ask',
84
+ code: 'OBF_CARET_SPLIT',
85
+ reason: 'Caret inserted inside a word, splitting a token to defeat literal matching.',
86
+ };
87
+ }
88
+ return null;
89
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Layer 1: hard blacklist.
3
+ *
4
+ * This is the only layer allowed to return `deny`, and in the real mount it is
5
+ * the only layer wired to ctx.tools.guard, which structurally has no allow
6
+ * exit. Keep the surface small: a false deny is unrecoverable, so nothing
7
+ * enters this list unless no legitimate intent should ever reach it.
8
+ *
9
+ * The head token is read after normalization (separators expanded, wrappers
10
+ * stripped, escapes removed). Before that, only a plainly-spelled command was
11
+ * judged, and `sudo rm -rf /`, `r\m -rf /`, `rm$IFS-rf$IFS/` and
12
+ * `eval "rm -rf /"` all reached the end of the pipeline untouched.
13
+ */
14
+ import type { Finding, GuardInput, GuardState } from './types.js';
15
+ export declare function check(input: GuardInput, _state: GuardState): Finding | null;