@yagyeshvyas/vibeguard 1.0.0 → 1.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.
@@ -1,276 +1,292 @@
1
- 'use strict';
2
-
3
- /*
4
- * src/shell-guard.js — Shell-level pre-execution guard with anti-evasion.
5
- *
6
- * Scans a command string BEFORE it runs. Normalizes obfuscation attempts,
7
- * then matches against danger patterns. If blocked, returns { blocked: true }.
8
- *
9
- * Anti-evasion layers (applied in order, all checked):
10
- * 1. Base64 decode: echo "cm0gLXJmIC8" | base64 -d | sh -> rm -rf /
11
- * 2. Env-var indirection: RM="rm -rf"; $RM / -> blocked
12
- * 3. Subshell expansion: $(echo rm) -rf / -> rm -rf /
13
- * 4. Backtick eval: `echo rm` -rf / -> rm -rf /
14
- * 5. Hex/unicode escapes: \x72\x6d -> rm
15
- * 6. rm obfuscation: rm -r -f, rm --recursive --force, /bin/rm, r""m
16
- * 7. Path splitting: /bin/r""m -rf /, /sbin/r''m
17
- * 8. Quoted command: "rm" -rf /, 'rm' -rf /
18
- * 9. Variable concatenation: r=m; ${r}m -rf / -> blocked
19
- *
20
- * IMPORTANT: This catches accidental/AI-mistake dangerous commands. A
21
- * determined adversary with knowledge of the patterns can still evade
22
- * (no static guard is unbreakable). This stops the agent from nuking
23
- * your machine — it is NOT sandbox escape prevention.
24
- *
25
- * 100% local. Zero network. Zero dependencies.
26
- */
27
-
28
- const path = require('path');
29
-
30
- // ─── Anti-evasion normalizer ──────────────────────────────────────────────
31
-
32
- function normalizeCommand(cmd) {
33
- if (!cmd || typeof cmd !== 'string') return cmd || '';
34
- let normalized = cmd;
35
-
36
- // Layer 1: Base64 decode — catch "echo <base64> | base64 -d | sh"
37
- const b64Match = normalized.match(/echo\s+["']?([A-Za-z0-9+/=]{8,})["']?\s*\|\s*(?:base64|b64)\s+-d\s*\|/i);
38
- if (b64Match) {
39
- try {
40
- const decoded = Buffer.from(b64Match[1], 'base64').toString('utf8');
41
- normalized = normalized.replace(b64Match[0], decoded);
42
- } catch {}
43
- }
44
-
45
- // Layer 2: Env-var indirection — VAR="rm -rf"; $VAR /
46
- // Extract assignments and substitute $VAR references
47
- const assignMatch = normalized.match(/(\w+)=(["'])([^"']*)\2/);
48
- if (assignMatch) {
49
- const varName = assignMatch[1];
50
- const varValue = assignMatch[3];
51
- // If the variable contains a dangerous command fragment, substitute it
52
- if (/rm|sudo|chmod|mkfs|dd\s|shutdown|reboot|curl|wget/i.test(varValue)) {
53
- normalized = normalized.replace(new RegExp('\\$' + varName + '\\b', 'g'), varValue);
54
- normalized = normalized.replace(assignMatch[0], ''); // remove the assignment
55
- }
56
- }
57
-
58
- // Layer 3: Subshell expansion — $(echo rm) -> rm
59
- normalized = normalized.replace(/\$\(\s*echo\s+([^)]+)\s*\)/g, '$1');
60
- // $(printf "rm") -> rm
61
- normalized = normalized.replace(/\$\(\s*printf\s+["']([^"']+)["']\s*\)/g, '$1');
62
-
63
- // Layer 4: Backtick eval — `echo rm` -> rm
64
- normalized = normalized.replace(/`\s*echo\s+([^`]+)\s*`/g, '$1');
65
- normalized = normalized.replace(/`\s*printf\s+["']([^"']+)["']\s*`/g, '$1');
66
-
67
- // Layer 5: Hex/unicode escapes — \x72\x6d -> rm
68
- normalized = normalized.replace(/\\x([0-9a-f]{2})/gi, (m, hex) => {
69
- try { return String.fromCharCode(parseInt(hex, 16)); } catch { return m; }
70
- });
71
- // \u0072 -> r
72
- normalized = normalized.replace(/\\u([0-9a-f]{4})/gi, (m, hex) => {
73
- try { return String.fromCharCode(parseInt(hex, 16)); } catch { return m; }
74
- });
75
-
76
- // Layer 6: rm obfuscation — rm -r -f, rm --recursive --force, /bin/rm, /sbin/rm
77
- // Normalize rm flags: -r -f, -fr, -rf, -Rf, --recursive --force all -> -rf
78
- normalized = normalized.replace(/\brm\s+(?:-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*|-[a-zA-Z]*f[a-zA-Z]*r[a-zA-Z]*|--recursive(?:\s+--force)?)\b/i, 'rm -rf');
79
- normalized = normalized.replace(/\brm\s+-r\s+-f\b/i, 'rm -rf');
80
- normalized = normalized.replace(/\brm\s+-f\s+-r\b/i, 'rm -rf');
81
- normalized = normalized.replace(/\brm\s+--recursive\s+--force\b/i, 'rm -rf');
82
- // /bin/rm, /sbin/rm -> rm
83
- normalized = normalized.replace(/(?:\/bin\/|\/sbin\/)rm\b/g, 'rm');
84
-
85
- // Layer 7: String concatenation — r""m, r''m, r\m -> rm
86
- // Remove quotes and backslashes between letters to detect split commands
87
- normalized = normalized.replace(/([a-zA-Z])["'\\]+([a-zA-Z])/g, '$1$2');
88
-
89
- // Layer 8: Quoted command — "rm", 'rm' -> rm
90
- normalized = normalized.replace(/["']([a-z]{2,})["']/gi, (m, inner) => inner);
91
-
92
- // Layer 9: Variable concatenation — ${r}m, ${RM} -> rm
93
- // If there's a var assignment followed by ${var}, substitute
94
- const varAssigns = {};
95
- const assignPattern = /(\w+)=(["']?)([^"'\s]*)\2/g;
96
- let am;
97
- while ((am = assignPattern.exec(cmd)) !== null) {
98
- varAssigns[am[1]] = am[3];
99
- }
100
- normalized = normalized.replace(/\$\{(\w+)\}/g, (m, name) => varAssigns[name] || m);
101
-
102
- return normalized.trim();
103
- }
104
-
105
- // ─── Danger patterns (matched against BOTH raw AND normalized) ───────────
106
-
107
- const DANGEROUS_COMMANDS = [
108
- { re: /\brm\s+-rf\b/i, reason: 'rm -rf can delete entire directory trees', severity: 'critical' },
109
- { re: /\brm\s+-rf\s+\/(?:\s|$)/i, reason: 'rm -rf / — catastrophic deletion of root filesystem', severity: 'critical' },
110
- { re: /\brm\s+-rf\s+~(?:\s|$|\/)/i, reason: 'rm -rf ~ — deleting home directory', severity: 'critical' },
111
- { re: /\brm\s+-rf\s+\.(?:\s|$)/i, reason: 'rm -rf . — deleting current directory', severity: 'critical' },
112
- { re: /\brm\s+-rf\s+\.\.(?:\s|$)/i, reason: 'rm -rf .. — deleting parent directory', severity: 'critical' },
113
- { re: /\bsudo\b/i, reason: 'sudo escalates privileges — agents should not use sudo', severity: 'high' },
114
- { re: /\bchmod\s+777\b/i, reason: 'chmod 777 grants world write — insecure', severity: 'high' },
115
- { re: /\bmkfs\b/i, reason: 'mkfs formats filesystem — destructive', severity: 'critical' },
116
- { re: /\bdd\s+if=/i, reason: 'dd can overwrite disks — destructive', severity: 'critical' },
117
- { re: /\bdd\s+.*of=\/dev\//i, reason: 'dd writing directly to device — destructive', severity: 'critical' },
118
- { re: /\bshutdown\b/i, reason: 'shutdown stops the machine', severity: 'critical' },
119
- { re: /\breboot\b/i, reason: 'reboot restarts the machine', severity: 'critical' },
120
- { re: /\bhalt\b/i, reason: 'halt stops the machine', severity: 'critical' },
121
- { re: /\bpoweroff\b/i, reason: 'poweroff stops the machine', severity: 'critical' },
122
- { re: /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;/i, reason: 'fork bomb detected', severity: 'critical' },
123
- { re: /\b(?:curl|wget)\b.*\|\s*(?:sh|bash|zsh)\b/i, reason: 'curl|sh — remote code execution via pipe to shell', severity: 'critical' },
124
- { re: /\b(?:curl|wget)\b.*(?:169\.254\.169\.254|metadata\.google\.internal)/i, reason: 'cloud metadata service access — credential theft', severity: 'critical' },
125
- { re: /\bnc\s+-l/i, reason: 'nc -l opens a listener — reverse shell risk', severity: 'high' },
126
- { re: /\b(?:python|python3|node|ruby|perl)\s+-c\s+['"]\s*(?:import|require)\s+(?:os|subprocess|child_process)/i, reason: 'inline script importing OS modules — potential injection', severity: 'high' },
127
- { re: /\bkill(?:\s+-9)?\s+-1\b/i, reason: 'kill -1 kills all processes — system-wide kill', severity: 'critical' },
128
- { re: /\bpkill\s+-9\b/i, reason: 'pkill -9 force kills processes — destructive', severity: 'high' },
129
- { re: /\biotop\s+--only\b/i, reason: 'iotop in batch mode can cause system instability', severity: 'low' },
130
- // Anti-evasion: base64 pipe to shell
131
- { re: /\|\s*(?:base64|b64)\s+-d\s*\|/i, reason: 'base64 decode piped to shell — obfuscated command execution', severity: 'critical' },
132
- { re: /\|\s*(?:sh|bash|zsh|python|python3|node|perl|ruby)\b/i, reason: 'piping to interpreter — potential remote code execution', severity: 'high' },
133
- ];
134
-
135
- const SECRET_PATTERNS = [
136
- { re: /\bsk-proj-[A-Za-z0-9_-]{20,}\b/i, type: 'OpenAI API key' },
137
- { re: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/i, type: 'Anthropic API key' },
138
- { re: /\bsk_live_[A-Za-z0-9]{16,}\b/i, type: 'Stripe secret key' },
139
- { re: /\bAKIA[A-Z0-9]{16}\b/, type: 'AWS access key' },
140
- { re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/i, type: 'GitHub token' },
141
- { re: /\bglpat-[A-Za-z0-9_-]{20,}\b/i, type: 'GitLab token' },
142
- { re: /\bxox[bpoa]-[A-Za-z0-9-]{10,}\b/i, type: 'Slack token' },
143
- { re: /-----BEGIN\s+(?:RSA\s+|EC\s+)?PRIVATE\s+KEY-----/i, type: 'Private key' },
144
- ];
145
-
146
- const SENSITIVE_PATHS = [
147
- /\.env\b/i,
148
- /\.ssh\b/i,
149
- /\.aws\b/i,
150
- /\.gnupg\b/i,
151
- /\.npmrc\b/i,
152
- /\.gitconfig\b/i,
153
- /\/etc\/passwd/i,
154
- /\/etc\/shadow/i,
155
- /\/etc\/sudoers/i,
156
- /\/etc\/ssh\//i,
157
- /~\/\.ssh\//i,
158
- ];
159
-
160
- const EXFIL_PATTERNS = [
161
- { re: /\b(?:curl|wget|nc|netcat)\b.*(?:\bapi\.|webhook|callback|exfil|upload|send)/i, reason: 'Potential data exfiltration via network tool to external endpoint' },
162
- { re: /\b(?:curl|wget)\b.*-d\s.*(?:token|key|password|secret|credential)/i, reason: 'Sending secrets via curl/wget POST data' },
163
- { re: /\b(?:curl|wget)\b.*--data\b.*(?:token|key|password|secret|credential)/i, reason: 'Sending secrets via curl/wget --data' },
164
- { re: /\b(?:scp|rsync)\b.*@(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/i, reason: 'File transfer to raw IP — potential exfiltration' },
165
- { re: /\b(?:curl|wget)\b.*-F\s.*(?:token|key|password|secret)/i, reason: 'Sending secrets via curl/wget multipart form' },
166
- ];
167
-
168
- // ─── Main check function ──────────────────────────────────────────────────
169
-
170
- function checkCommand(cmd) {
171
- if (!cmd || typeof cmd !== 'string') return { blocked: false, allowed: true };
172
- const trimmed = cmd.trim();
173
-
174
- // Skip empty lines and comments
175
- if (!trimmed || trimmed.startsWith('#')) return { blocked: false, allowed: true };
176
-
177
- // Normalize for anti-evasion
178
- const normalized = normalizeCommand(trimmed);
179
-
180
- // Check BOTH the raw command AND the normalized version
181
- const inputs = [trimmed, normalized];
182
- const violations = [];
183
- const seen = new Set(); // dedupe violations across raw + normalized
184
-
185
- for (const input of inputs) {
186
- // 1. Dangerous commands
187
- for (const { re, reason, severity } of DANGEROUS_COMMANDS) {
188
- if (re.test(input)) {
189
- const key = reason;
190
- if (!seen.has(key)) {
191
- seen.add(key);
192
- violations.push({ type: 'dangerous_command', reason, severity, pattern: re.source });
193
- }
194
- }
195
- }
196
-
197
- // 2. Secret exfiltration
198
- for (const { re, reason } of EXFIL_PATTERNS) {
199
- if (re.test(input)) {
200
- const key = reason;
201
- if (!seen.has(key)) {
202
- seen.add(key);
203
- violations.push({ type: 'exfiltration', reason, severity: 'high', pattern: re.source });
204
- }
205
- }
206
- }
207
-
208
- // 3. Secrets in command
209
- for (const { re, type } of SECRET_PATTERNS) {
210
- if (re.test(input)) {
211
- const key = type;
212
- if (!seen.has(key)) {
213
- seen.add(key);
214
- violations.push({ type: 'secret_exposure', reason: `Secret detected in command: ${type}`, severity: 'critical', pattern: re.source });
215
- }
216
- }
217
- }
218
-
219
- // 4. Sensitive file access
220
- for (const re of SENSITIVE_PATHS) {
221
- if (re.test(input)) {
222
- const match = input.match(re)[0];
223
- const key = 'path:' + match;
224
- if (!seen.has(key)) {
225
- seen.add(key);
226
- violations.push({ type: 'sensitive_path', reason: `Access to sensitive path: ${match}`, severity: 'high', pattern: re.source });
227
- }
228
- }
229
- }
230
- }
231
-
232
- // 5. Prompt injection in shell (e.g., agent putting LLM output into eval)
233
- for (const input of inputs) {
234
- if (/\beval\s+["'].*(?:ignore|disregard|forget|system prompt)/i.test(input)) {
235
- violations.push({ type: 'prompt_injection', reason: 'eval with prompt injection pattern — agent may be compromised', severity: 'critical' });
236
- break;
237
- }
238
- }
239
-
240
- // 6. Obfuscation detection — flag suspicious patterns even if we can't decode them
241
- if (/[a-zA-Z]\[([0-9a-f]{1,2})\]/i.test(trimmed)) {
242
- violations.push({ type: 'obfuscation', reason: 'Bash escape sequence $\'\\xNN\' detected — possible command obfuscation', severity: 'high' });
243
- }
244
- if (trimmed.includes('eval ') && trimmed.includes('$((')) {
245
- violations.push({ type: 'obfuscation', reason: 'eval with arithmetic expansion — possible obfuscation', severity: 'high' });
246
- }
247
-
248
- if (violations.length === 0) return { blocked: false, allowed: true };
249
-
250
- return {
251
- blocked: true,
252
- allowed: false,
253
- violations,
254
- reason: violations[0].reason,
255
- severity: violations[0].severity,
256
- command: trimmed.slice(0, 200),
257
- normalized: normalized !== trimmed ? normalized.slice(0, 200) : undefined,
258
- };
259
- }
260
-
261
- // ─── Batch check (for scripts) ─────────────────────────────────────────────
262
-
263
- function checkScript(content) {
264
- if (!content || typeof content !== 'string') return { blocked: false, findings: [] };
265
- const lines = content.split(/\r?\n/);
266
- const findings = [];
267
- for (let i = 0; i < lines.length; i++) {
268
- const result = checkCommand(lines[i]);
269
- if (result.blocked) {
270
- findings.push({ line: i + 1, ...result });
271
- }
272
- }
273
- return { blocked: findings.length > 0, findings };
274
- }
275
-
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/shell-guard.js — Shell-level pre-execution guard with anti-evasion.
5
+ *
6
+ * Scans a command string BEFORE it runs. Normalizes obfuscation attempts,
7
+ * then matches against danger patterns. If blocked, returns { blocked: true }.
8
+ *
9
+ * Anti-evasion layers (applied in order, all checked):
10
+ * 1. Base64 decode: echo "cm0gLXJmIC8" | base64 -d | sh -> rm -rf /
11
+ * 2. Env-var indirection: RM="rm -rf"; $RM / -> blocked
12
+ * 3. Subshell expansion: $(echo rm) -rf / -> rm -rf /
13
+ * 4. Backtick eval: `echo rm` -rf / -> rm -rf /
14
+ * 5. Hex/unicode escapes: \x72\x6d -> rm
15
+ * 6. rm obfuscation: rm -r -f, rm --recursive --force, /bin/rm, r""m
16
+ * 7. Path splitting: /bin/r""m -rf /, /sbin/r''m
17
+ * 8. Quoted command: "rm" -rf /, 'rm' -rf /
18
+ * 9. Variable concatenation: r=m; ${r}m -rf / -> blocked
19
+ *
20
+ * IMPORTANT: This catches accidental/AI-mistake dangerous commands. A
21
+ * determined adversary with knowledge of the patterns can still evade
22
+ * (no static guard is unbreakable). This stops the agent from nuking
23
+ * your machine — it is NOT sandbox escape prevention.
24
+ *
25
+ * 100% local. Zero network. Zero dependencies.
26
+ */
27
+
28
+ const path = require('path');
29
+
30
+ // ─── Anti-evasion normalizer ──────────────────────────────────────────────
31
+
32
+ // One normalization pass. Run repeatedly to a fixpoint by normalizeCommand so
33
+ // layered obfuscation (a var expanding to another var, base64 decoding to a
34
+ // quoted command) unwinds step by step instead of in one brittle sweep.
35
+ function normalizeOnce(cmd) {
36
+ let normalized = cmd;
37
+
38
+ // Layer 1: Base64 decode — catch "echo <base64> | base64 -d | sh"
39
+ const b64Match = normalized.match(/echo\s+["']?([A-Za-z0-9+/=]{8,})["']?\s*\|\s*(?:base64|b64)\s+-d\s*\|/i);
40
+ if (b64Match) {
41
+ try {
42
+ const decoded = Buffer.from(b64Match[1], 'base64').toString('utf8');
43
+ normalized = normalized.replace(b64Match[0], decoded);
44
+ } catch {}
45
+ }
46
+
47
+ // Layer 2: Env-var indirection — collect EVERY assignment and substitute all
48
+ // references. The original code matched only the FIRST assignment (non-global),
49
+ // so `A=rm; B=-rf; $A $B /` slipped through. We now sweep all of them, quoted
50
+ // and bare, then substitute $VAR and ${VAR}.
51
+ const assignAll = {};
52
+ const quotedAssign = /(\w+)=(["'])([^"']*)\2/g;
53
+ let qa;
54
+ while ((qa = quotedAssign.exec(normalized)) !== null) assignAll[qa[1]] = qa[3];
55
+ const bareAssign = /(?:^|[;\s])(\w+)=([^"'\s;|&]+)/g;
56
+ let ba;
57
+ while ((ba = bareAssign.exec(normalized)) !== null) {
58
+ if (!(ba[1] in assignAll)) assignAll[ba[1]] = ba[2];
59
+ }
60
+ for (const [name, value] of Object.entries(assignAll)) {
61
+ if (/rm|sudo|chmod|mkfs|dd\s|shutdown|reboot|curl|wget|-rf?\b/i.test(value)) {
62
+ normalized = normalized.replace(new RegExp('\\$\\{?' + name + '\\}?\\b', 'g'), value);
63
+ }
64
+ }
65
+ // Strip the assignment statements themselves so they don't linger as noise.
66
+ normalized = normalized.replace(/(?:^|[;\s])(\w+)=(?:(["'])[^"']*\2|[^"'\s;|&]+)\s*/g, ' ');
67
+
68
+ // Layer 3: Subshell expansion — $(echo rm) -> rm
69
+ normalized = normalized.replace(/\$\(\s*echo\s+([^)]+)\s*\)/g, '$1');
70
+ // $(printf "rm") -> rm
71
+ normalized = normalized.replace(/\$\(\s*printf\s+["']([^"']+)["']\s*\)/g, '$1');
72
+
73
+ // Layer 4: Backtick eval — `echo rm` -> rm
74
+ normalized = normalized.replace(/`\s*echo\s+([^`]+)\s*`/g, '$1');
75
+ normalized = normalized.replace(/`\s*printf\s+["']([^"']+)["']\s*`/g, '$1');
76
+
77
+ // Layer 5: Hex/unicode escapes — \x72\x6d -> rm
78
+ normalized = normalized.replace(/\\x([0-9a-f]{2})/gi, (m, hex) => {
79
+ try { return String.fromCharCode(parseInt(hex, 16)); } catch { return m; }
80
+ });
81
+ // \u0072 -> r
82
+ normalized = normalized.replace(/\\u([0-9a-f]{4})/gi, (m, hex) => {
83
+ try { return String.fromCharCode(parseInt(hex, 16)); } catch { return m; }
84
+ });
85
+
86
+ // Layer 5b: $IFS word-splitting — rm$IFS-rf$IFS/ -> rm -rf /
87
+ normalized = normalized.replace(/\$\{?IFS\}?/g, ' ');
88
+
89
+ // Layer 6: rm obfuscation — rm -r -f, rm --recursive --force, /bin/rm, /sbin/rm
90
+ // Normalize rm flags: -r -f, -fr, -rf, -Rf, --recursive --force all -> -rf
91
+ normalized = normalized.replace(/\brm\s+(?:-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*|-[a-zA-Z]*f[a-zA-Z]*r[a-zA-Z]*|--recursive(?:\s+--force)?)\b/i, 'rm -rf');
92
+ normalized = normalized.replace(/\brm\s+-r\s+-f\b/i, 'rm -rf');
93
+ normalized = normalized.replace(/\brm\s+-f\s+-r\b/i, 'rm -rf');
94
+ normalized = normalized.replace(/\brm\s+--recursive\s+--force\b/i, 'rm -rf');
95
+ // /bin/rm, /sbin/rm, /usr/bin/rm -> rm
96
+ normalized = normalized.replace(/(?:\/usr)?(?:\/bin\/|\/sbin\/)rm\b/g, 'rm');
97
+
98
+ // Layer 7: String concatenation — r""m, r''m, r\m -> rm
99
+ // Remove quotes and backslashes between letters to detect split commands
100
+ normalized = normalized.replace(/([a-zA-Z])["'\\]+([a-zA-Z])/g, '$1$2');
101
+
102
+ // Layer 8: Quoted command — "rm", 'rm' -> rm
103
+ normalized = normalized.replace(/["']([a-z]{2,})["']/gi, (m, inner) => inner);
104
+
105
+ return normalized;
106
+ }
107
+
108
+ function normalizeCommand(cmd) {
109
+ if (!cmd || typeof cmd !== 'string') return cmd || '';
110
+ let current = cmd;
111
+ // Iterate to a fixpoint (bounded at 5) so layered obfuscation unwinds fully.
112
+ // The bound guards against pathological input causing an unbounded loop.
113
+ for (let i = 0; i < 5; i++) {
114
+ const next = normalizeOnce(current);
115
+ if (next === current) break;
116
+ current = next;
117
+ }
118
+ return current.replace(/[ \t]+/g, ' ').trim();
119
+ }
120
+
121
+ // ─── Danger patterns (matched against BOTH raw AND normalized) ───────────
122
+
123
+ const DANGEROUS_COMMANDS = [
124
+ { re: /\brm\s+-rf\b/i, reason: 'rm -rf can delete entire directory trees', severity: 'critical' },
125
+ { re: /\brm\s+-rf\s+\/(?:\s|$)/i, reason: 'rm -rf / — catastrophic deletion of root filesystem', severity: 'critical' },
126
+ { re: /\brm\s+-rf\s+~(?:\s|$|\/)/i, reason: 'rm -rf ~ — deleting home directory', severity: 'critical' },
127
+ { re: /\brm\s+-rf\s+\.(?:\s|$)/i, reason: 'rm -rf . — deleting current directory', severity: 'critical' },
128
+ { re: /\brm\s+-rf\s+\.\.(?:\s|$)/i, reason: 'rm -rf .. — deleting parent directory', severity: 'critical' },
129
+ { re: /\bsudo\b/i, reason: 'sudo escalates privileges — agents should not use sudo', severity: 'high' },
130
+ { re: /\bchmod\s+777\b/i, reason: 'chmod 777 grants world write — insecure', severity: 'high' },
131
+ { re: /\bmkfs\b/i, reason: 'mkfs formats filesystem — destructive', severity: 'critical' },
132
+ { re: /\bdd\s+if=/i, reason: 'dd can overwrite disks — destructive', severity: 'critical' },
133
+ { re: /\bdd\s+.*of=\/dev\//i, reason: 'dd writing directly to device — destructive', severity: 'critical' },
134
+ { re: /\bshutdown\b/i, reason: 'shutdown stops the machine', severity: 'critical' },
135
+ { re: /\breboot\b/i, reason: 'reboot restarts the machine', severity: 'critical' },
136
+ { re: /\bhalt\b/i, reason: 'halt stops the machine', severity: 'critical' },
137
+ { re: /\bpoweroff\b/i, reason: 'poweroff stops the machine', severity: 'critical' },
138
+ { re: /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;/i, reason: 'fork bomb detected', severity: 'critical' },
139
+ { re: /\b(?:curl|wget)\b.*\|\s*(?:sh|bash|zsh)\b/i, reason: 'curl|sh — remote code execution via pipe to shell', severity: 'critical' },
140
+ { re: /\b(?:curl|wget)\b.*(?:169\.254\.169\.254|metadata\.google\.internal)/i, reason: 'cloud metadata service access — credential theft', severity: 'critical' },
141
+ { re: /\bnc\s+-l/i, reason: 'nc -l opens a listener — reverse shell risk', severity: 'high' },
142
+ { re: /\b(?:python|python3|node|ruby|perl)\s+-c\s+['"]\s*(?:import|require)\s+(?:os|subprocess|child_process)/i, reason: 'inline script importing OS modules — potential injection', severity: 'high' },
143
+ { re: /\bkill(?:\s+-9)?\s+-1\b/i, reason: 'kill -1 kills all processes — system-wide kill', severity: 'critical' },
144
+ { re: /\bpkill\s+-9\b/i, reason: 'pkill -9 force kills processes — destructive', severity: 'high' },
145
+ { re: /\biotop\s+--only\b/i, reason: 'iotop in batch mode can cause system instability', severity: 'low' },
146
+ // Anti-evasion: base64 pipe to shell
147
+ { re: /\|\s*(?:base64|b64)\s+-d\s*\|/i, reason: 'base64 decode piped to shell — obfuscated command execution', severity: 'critical' },
148
+ { re: /\|\s*(?:sh|bash|zsh|python|python3|node|perl|ruby)\b/i, reason: 'piping to interpreter — potential remote code execution', severity: 'high' },
149
+ ];
150
+
151
+ const SECRET_PATTERNS = [
152
+ { re: /\bsk-proj-[A-Za-z0-9_-]{20,}\b/i, type: 'OpenAI API key' },
153
+ { re: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/i, type: 'Anthropic API key' },
154
+ { re: /\bsk_live_[A-Za-z0-9]{16,}\b/i, type: 'Stripe secret key' },
155
+ { re: /\bAKIA[A-Z0-9]{16}\b/, type: 'AWS access key' },
156
+ { re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/i, type: 'GitHub token' },
157
+ { re: /\bglpat-[A-Za-z0-9_-]{20,}\b/i, type: 'GitLab token' },
158
+ { re: /\bxox[bpoa]-[A-Za-z0-9-]{10,}\b/i, type: 'Slack token' },
159
+ { re: /-----BEGIN\s+(?:RSA\s+|EC\s+)?PRIVATE\s+KEY-----/i, type: 'Private key' },
160
+ ];
161
+
162
+ const SENSITIVE_PATHS = [
163
+ /\.env\b/i,
164
+ /\.ssh\b/i,
165
+ /\.aws\b/i,
166
+ /\.gnupg\b/i,
167
+ /\.npmrc\b/i,
168
+ /\.gitconfig\b/i,
169
+ /\/etc\/passwd/i,
170
+ /\/etc\/shadow/i,
171
+ /\/etc\/sudoers/i,
172
+ /\/etc\/ssh\//i,
173
+ /~\/\.ssh\//i,
174
+ ];
175
+
176
+ const EXFIL_PATTERNS = [
177
+ { re: /\b(?:curl|wget|nc|netcat)\b.*(?:\bapi\.|webhook|callback|exfil|upload|send)/i, reason: 'Potential data exfiltration via network tool to external endpoint' },
178
+ { re: /\b(?:curl|wget)\b.*-d\s.*(?:token|key|password|secret|credential)/i, reason: 'Sending secrets via curl/wget POST data' },
179
+ { re: /\b(?:curl|wget)\b.*--data\b.*(?:token|key|password|secret|credential)/i, reason: 'Sending secrets via curl/wget --data' },
180
+ { re: /\b(?:scp|rsync)\b.*@(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/i, reason: 'File transfer to raw IP — potential exfiltration' },
181
+ { re: /\b(?:curl|wget)\b.*-F\s.*(?:token|key|password|secret)/i, reason: 'Sending secrets via curl/wget multipart form' },
182
+ ];
183
+
184
+ // ─── Main check function ──────────────────────────────────────────────────
185
+
186
+ function checkCommand(cmd) {
187
+ if (!cmd || typeof cmd !== 'string') return { blocked: false, allowed: true };
188
+ const trimmed = cmd.trim();
189
+
190
+ // Skip empty lines and comments
191
+ if (!trimmed || trimmed.startsWith('#')) return { blocked: false, allowed: true };
192
+
193
+ // Normalize for anti-evasion
194
+ const normalized = normalizeCommand(trimmed);
195
+
196
+ // Check BOTH the raw command AND the normalized version
197
+ const inputs = [trimmed, normalized];
198
+ const violations = [];
199
+ const seen = new Set(); // dedupe violations across raw + normalized
200
+
201
+ for (const input of inputs) {
202
+ // 1. Dangerous commands
203
+ for (const { re, reason, severity } of DANGEROUS_COMMANDS) {
204
+ if (re.test(input)) {
205
+ const key = reason;
206
+ if (!seen.has(key)) {
207
+ seen.add(key);
208
+ violations.push({ type: 'dangerous_command', reason, severity, pattern: re.source });
209
+ }
210
+ }
211
+ }
212
+
213
+ // 2. Secret exfiltration
214
+ for (const { re, reason } of EXFIL_PATTERNS) {
215
+ if (re.test(input)) {
216
+ const key = reason;
217
+ if (!seen.has(key)) {
218
+ seen.add(key);
219
+ violations.push({ type: 'exfiltration', reason, severity: 'high', pattern: re.source });
220
+ }
221
+ }
222
+ }
223
+
224
+ // 3. Secrets in command
225
+ for (const { re, type } of SECRET_PATTERNS) {
226
+ if (re.test(input)) {
227
+ const key = type;
228
+ if (!seen.has(key)) {
229
+ seen.add(key);
230
+ violations.push({ type: 'secret_exposure', reason: `Secret detected in command: ${type}`, severity: 'critical', pattern: re.source });
231
+ }
232
+ }
233
+ }
234
+
235
+ // 4. Sensitive file access
236
+ for (const re of SENSITIVE_PATHS) {
237
+ if (re.test(input)) {
238
+ const match = input.match(re)[0];
239
+ const key = 'path:' + match;
240
+ if (!seen.has(key)) {
241
+ seen.add(key);
242
+ violations.push({ type: 'sensitive_path', reason: `Access to sensitive path: ${match}`, severity: 'high', pattern: re.source });
243
+ }
244
+ }
245
+ }
246
+ }
247
+
248
+ // 5. Prompt injection in shell (e.g., agent putting LLM output into eval)
249
+ for (const input of inputs) {
250
+ if (/\beval\s+["'].*(?:ignore|disregard|forget|system prompt)/i.test(input)) {
251
+ violations.push({ type: 'prompt_injection', reason: 'eval with prompt injection pattern — agent may be compromised', severity: 'critical' });
252
+ break;
253
+ }
254
+ }
255
+
256
+ // 6. Obfuscation detection — flag suspicious patterns even if we can't decode them
257
+ if (/[a-zA-Z]\[([0-9a-f]{1,2})\]/i.test(trimmed)) {
258
+ violations.push({ type: 'obfuscation', reason: 'Bash escape sequence $\'\\xNN\' detected — possible command obfuscation', severity: 'high' });
259
+ }
260
+ if (trimmed.includes('eval ') && trimmed.includes('$((')) {
261
+ violations.push({ type: 'obfuscation', reason: 'eval with arithmetic expansion — possible obfuscation', severity: 'high' });
262
+ }
263
+
264
+ if (violations.length === 0) return { blocked: false, allowed: true };
265
+
266
+ return {
267
+ blocked: true,
268
+ allowed: false,
269
+ violations,
270
+ reason: violations[0].reason,
271
+ severity: violations[0].severity,
272
+ command: trimmed.slice(0, 200),
273
+ normalized: normalized !== trimmed ? normalized.slice(0, 200) : undefined,
274
+ };
275
+ }
276
+
277
+ // ─── Batch check (for scripts) ─────────────────────────────────────────────
278
+
279
+ function checkScript(content) {
280
+ if (!content || typeof content !== 'string') return { blocked: false, findings: [] };
281
+ const lines = content.split(/\r?\n/);
282
+ const findings = [];
283
+ for (let i = 0; i < lines.length; i++) {
284
+ const result = checkCommand(lines[i]);
285
+ if (result.blocked) {
286
+ findings.push({ line: i + 1, ...result });
287
+ }
288
+ }
289
+ return { blocked: findings.length > 0, findings };
290
+ }
291
+
276
292
  module.exports = { checkCommand, checkScript, normalizeCommand, DANGEROUS_COMMANDS, SECRET_PATTERNS, SENSITIVE_PATHS, EXFIL_PATTERNS };