@orchestraai/agent-tools 0.10.16 → 0.10.18
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/.agents/plugins/marketplace.json +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/.devin/adapter.json +1 -1
- package/.hermes/adapter.json +1 -1
- package/.opencode/adapter.json +1 -1
- package/dist/commands/claude-setup.d.ts +1 -1
- package/dist/runtime/conversation/command-guard.js +1347 -63
- package/dist/runtime/conversation/command-guard.js.map +1 -1
- package/dist/runtime/conversation/shell-parse.d.ts +44 -0
- package/dist/runtime/conversation/shell-parse.js +525 -0
- package/dist/runtime/conversation/shell-parse.js.map +1 -0
- package/docs/security.md +18 -2
- package/node_modules/@hono/node-server/dist/index.cjs +63 -17
- package/node_modules/@hono/node-server/dist/index.mjs +63 -17
- package/node_modules/@hono/node-server/dist/serve-static.cjs +1 -1
- package/node_modules/@hono/node-server/dist/serve-static.mjs +1 -1
- package/node_modules/@hono/node-server/package.json +1 -1
- package/node_modules/cross-spawn/README.md +19 -3
- package/node_modules/cross-spawn/lib/parse.js +38 -10
- package/node_modules/cross-spawn/lib/util/escape.js +84 -25
- package/node_modules/cross-spawn/lib/util/readShebang.js +8 -2
- package/node_modules/cross-spawn/lib/util/resolveCommand.js +8 -1
- package/node_modules/cross-spawn/package.json +21 -24
- package/node_modules/hono/README.md +2 -3
- package/node_modules/hono/dist/adapter/aws-lambda/handler.js +2 -2
- package/node_modules/hono/dist/adapter/bun/websocket.js +19 -4
- package/node_modules/hono/dist/adapter/lambda-edge/handler.js +5 -1
- package/node_modules/hono/dist/cjs/adapter/aws-lambda/handler.js +2 -2
- package/node_modules/hono/dist/cjs/adapter/bun/websocket.js +19 -4
- package/node_modules/hono/dist/cjs/adapter/lambda-edge/handler.js +5 -1
- package/node_modules/hono/dist/cjs/client/fetch-result-please.js +1 -1
- package/node_modules/hono/dist/cjs/client/utils.js +9 -5
- package/node_modules/hono/dist/cjs/context.js +1 -1
- package/node_modules/hono/dist/cjs/helper/accepts/accepts.js +7 -1
- package/node_modules/hono/dist/cjs/helper/css/common.js +11 -8
- package/node_modules/hono/dist/cjs/helper/css/index.js +1 -1
- package/node_modules/hono/dist/cjs/helper/proxy/index.js +2 -0
- package/node_modules/hono/dist/cjs/helper/route/index.js +3 -1
- package/node_modules/hono/dist/cjs/helper/ssg/ssg.js +5 -3
- package/node_modules/hono/dist/cjs/helper/streaming/sse.js +6 -2
- package/node_modules/hono/dist/cjs/hono-base.js +9 -10
- package/node_modules/hono/dist/cjs/hono.js +0 -1
- package/node_modules/hono/dist/cjs/jsx/base.js +51 -32
- package/node_modules/hono/dist/cjs/jsx/components.js +2 -2
- package/node_modules/hono/dist/cjs/jsx/constants.js +2 -0
- package/node_modules/hono/dist/cjs/jsx/context.js +15 -2
- package/node_modules/hono/dist/cjs/jsx/dom/components.js +1 -1
- package/node_modules/hono/dist/cjs/jsx/dom/hooks/index.js +38 -8
- package/node_modules/hono/dist/cjs/jsx/dom/intrinsic-element/components.js +8 -5
- package/node_modules/hono/dist/cjs/jsx/dom/render.js +9 -3
- package/node_modules/hono/dist/cjs/jsx/jsx-runtime.js +13 -17
- package/node_modules/hono/dist/cjs/middleware/basic-auth/index.js +3 -1
- package/node_modules/hono/dist/cjs/middleware/bearer-auth/index.js +9 -1
- package/node_modules/hono/dist/cjs/middleware/body-limit/index.js +9 -10
- package/node_modules/hono/dist/cjs/middleware/combine/index.js +4 -0
- package/node_modules/hono/dist/cjs/middleware/compress/index.js +2 -3
- package/node_modules/hono/dist/cjs/middleware/csrf/index.js +2 -2
- package/node_modules/hono/dist/cjs/middleware/etag/index.js +3 -1
- package/node_modules/hono/dist/cjs/middleware/jwk/jwk.js +2 -2
- package/node_modules/hono/dist/cjs/middleware/jwt/jwt.js +2 -2
- package/node_modules/hono/dist/cjs/middleware/method-not-allowed/index.js +1 -1
- package/node_modules/hono/dist/cjs/middleware/method-override/index.js +35 -12
- package/node_modules/hono/dist/cjs/middleware/mount/index.js +5 -4
- package/node_modules/hono/dist/cjs/middleware/pretty-json/index.js +1 -0
- package/node_modules/hono/dist/cjs/middleware/request-id/request-id.js +3 -3
- package/node_modules/hono/dist/cjs/middleware/secure-headers/secure-headers.js +6 -3
- package/node_modules/hono/dist/cjs/middleware/serve-static/index.js +4 -2
- package/node_modules/hono/dist/cjs/middleware/timing/timing.js +4 -3
- package/node_modules/hono/dist/cjs/router/reg-exp-router/node.js +13 -11
- package/node_modules/hono/dist/cjs/router/reg-exp-router/prepared-router.js +4 -4
- package/node_modules/hono/dist/cjs/router/reg-exp-router/router.js +39 -51
- package/node_modules/hono/dist/cjs/router/reg-exp-router/trie.js +15 -5
- package/node_modules/hono/dist/cjs/router/trie-router/node.js +6 -4
- package/node_modules/hono/dist/cjs/utils/body.js +2 -1
- package/node_modules/hono/dist/cjs/utils/cookie.js +3 -3
- package/node_modules/hono/dist/cjs/utils/html.js +5 -0
- package/node_modules/hono/dist/cjs/utils/jwt/jwt.js +8 -5
- package/node_modules/hono/dist/cjs/utils/mime.js +3 -2
- package/node_modules/hono/dist/cjs/utils/mount.js +59 -0
- package/node_modules/hono/dist/cjs/utils/url.js +23 -11
- package/node_modules/hono/dist/cjs/validator/validator.js +5 -5
- package/node_modules/hono/dist/client/fetch-result-please.js +1 -1
- package/node_modules/hono/dist/client/utils.js +9 -5
- package/node_modules/hono/dist/context.js +1 -1
- package/node_modules/hono/dist/helper/accepts/accepts.js +7 -1
- package/node_modules/hono/dist/helper/css/common.js +11 -8
- package/node_modules/hono/dist/helper/css/index.js +1 -1
- package/node_modules/hono/dist/helper/proxy/index.js +2 -0
- package/node_modules/hono/dist/helper/route/index.js +3 -1
- package/node_modules/hono/dist/helper/ssg/ssg.js +5 -3
- package/node_modules/hono/dist/helper/streaming/sse.js +6 -2
- package/node_modules/hono/dist/hono-base.js +9 -10
- package/node_modules/hono/dist/hono.js +0 -1
- package/node_modules/hono/dist/jsx/base.js +51 -34
- package/node_modules/hono/dist/jsx/components.js +2 -2
- package/node_modules/hono/dist/jsx/constants.js +2 -1
- package/node_modules/hono/dist/jsx/context.js +15 -2
- package/node_modules/hono/dist/jsx/dom/components.js +2 -2
- package/node_modules/hono/dist/jsx/dom/hooks/index.js +39 -9
- package/node_modules/hono/dist/jsx/dom/intrinsic-element/components.js +8 -5
- package/node_modules/hono/dist/jsx/dom/render.js +9 -3
- package/node_modules/hono/dist/jsx/jsx-runtime.js +15 -19
- package/node_modules/hono/dist/middleware/basic-auth/index.js +3 -1
- package/node_modules/hono/dist/middleware/bearer-auth/index.js +9 -1
- package/node_modules/hono/dist/middleware/body-limit/index.js +9 -10
- package/node_modules/hono/dist/middleware/combine/index.js +4 -0
- package/node_modules/hono/dist/middleware/compress/index.js +2 -3
- package/node_modules/hono/dist/middleware/csrf/index.js +2 -2
- package/node_modules/hono/dist/middleware/etag/index.js +3 -1
- package/node_modules/hono/dist/middleware/jwk/jwk.js +2 -2
- package/node_modules/hono/dist/middleware/jwt/jwt.js +2 -2
- package/node_modules/hono/dist/middleware/method-not-allowed/index.js +1 -1
- package/node_modules/hono/dist/middleware/method-override/index.js +35 -12
- package/node_modules/hono/dist/middleware/mount/index.js +5 -4
- package/node_modules/hono/dist/middleware/pretty-json/index.js +1 -0
- package/node_modules/hono/dist/middleware/request-id/request-id.js +3 -3
- package/node_modules/hono/dist/middleware/secure-headers/secure-headers.js +6 -3
- package/node_modules/hono/dist/middleware/serve-static/index.js +4 -2
- package/node_modules/hono/dist/middleware/timing/timing.js +4 -3
- package/node_modules/hono/dist/router/reg-exp-router/node.js +13 -11
- package/node_modules/hono/dist/router/reg-exp-router/prepared-router.js +5 -5
- package/node_modules/hono/dist/router/reg-exp-router/router.js +40 -52
- package/node_modules/hono/dist/router/reg-exp-router/trie.js +15 -5
- package/node_modules/hono/dist/router/trie-router/node.js +6 -4
- package/node_modules/hono/dist/types/adapter/aws-lambda/conninfo.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/bun/conninfo.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/bun/ssg.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/cloudflare-pages/conninfo.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/cloudflare-workers/conninfo.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/deno/conninfo.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/deno/ssg.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/lambda-edge/conninfo.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/netlify/conninfo.d.ts +1 -1
- package/node_modules/hono/dist/types/adapter/vercel/conninfo.d.ts +1 -1
- package/node_modules/hono/dist/types/helper/accepts/accepts.d.ts +5 -0
- package/node_modules/hono/dist/types/helper/factory/index.d.ts +1 -1
- package/node_modules/hono/dist/types/helper/ssg/ssg.d.ts +6 -1
- package/node_modules/hono/dist/types/helper/streaming/sse.d.ts +1 -1
- package/node_modules/hono/dist/types/helper/streaming/stream.d.ts +1 -1
- package/node_modules/hono/dist/types/helper/streaming/text.d.ts +1 -1
- package/node_modules/hono/dist/types/helper/testing/index.d.ts +2 -1
- package/node_modules/hono/dist/types/helper/websocket/index.d.ts +13 -3
- package/node_modules/hono/dist/types/hono-base.d.ts +23 -9
- package/node_modules/hono/dist/types/index.d.ts +1 -1
- package/node_modules/hono/dist/types/jsx/base.d.ts +6 -3
- package/node_modules/hono/dist/types/jsx/components.d.ts +2 -2
- package/node_modules/hono/dist/types/jsx/constants.d.ts +1 -0
- package/node_modules/hono/dist/types/jsx/context.d.ts +2 -2
- package/node_modules/hono/dist/types/jsx/dom/components.d.ts +2 -2
- package/node_modules/hono/dist/types/jsx/dom/css.d.ts +2 -2
- package/node_modules/hono/dist/types/jsx/dom/hooks/index.d.ts +5 -3
- package/node_modules/hono/dist/types/jsx/dom/index.d.ts +1 -1
- package/node_modules/hono/dist/types/jsx/dom/server.d.ts +1 -1
- package/node_modules/hono/dist/types/jsx/index.d.ts +1 -1
- package/node_modules/hono/dist/types/jsx/jsx-runtime.d.ts +2 -1
- package/node_modules/hono/dist/types/jsx/streaming.d.ts +4 -3
- package/node_modules/hono/dist/types/middleware/basic-auth/index.d.ts +1 -0
- package/node_modules/hono/dist/types/middleware/bearer-auth/index.d.ts +2 -1
- package/node_modules/hono/dist/types/middleware/ip-restriction/index.d.ts +3 -3
- package/node_modules/hono/dist/types/middleware/jsx-renderer/index.d.ts +3 -3
- package/node_modules/hono/dist/types/middleware/mount/index.d.ts +2 -0
- package/node_modules/hono/dist/types/middleware/request-id/request-id.d.ts +3 -3
- package/node_modules/hono/dist/types/middleware/secure-headers/secure-headers.d.ts +2 -0
- package/node_modules/hono/dist/types/router/reg-exp-router/node.d.ts +3 -3
- package/node_modules/hono/dist/types/router/reg-exp-router/trie.d.ts +1 -1
- package/node_modules/hono/dist/types/utils/cookie.d.ts +1 -1
- package/node_modules/hono/dist/types/utils/ipaddr.d.ts +1 -1
- package/node_modules/hono/dist/types/utils/jwt/jwt.d.ts +4 -2
- package/node_modules/hono/dist/types/utils/mount.d.ts +4 -0
- package/node_modules/hono/dist/types/utils/types.d.ts +12 -2
- package/node_modules/hono/dist/utils/body.js +2 -1
- package/node_modules/hono/dist/utils/cookie.js +3 -3
- package/node_modules/hono/dist/utils/html.js +5 -0
- package/node_modules/hono/dist/utils/jwt/jwt.js +8 -5
- package/node_modules/hono/dist/utils/mime.js +3 -2
- package/node_modules/hono/dist/utils/mount.js +58 -0
- package/node_modules/hono/dist/utils/url.js +23 -11
- package/node_modules/hono/dist/validator/validator.js +5 -5
- package/node_modules/hono/package.json +1 -1
- package/package.json +1 -1
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { parseShell, ShellParseError, } from "./shell-parse.js";
|
|
1
3
|
const SHELL_TOOL_NAMES = new Set([
|
|
2
4
|
"bash",
|
|
3
5
|
"exec_command",
|
|
@@ -6,18 +8,95 @@ const SHELL_TOOL_NAMES = new Set([
|
|
|
6
8
|
"shell",
|
|
7
9
|
"terminal",
|
|
8
10
|
]);
|
|
9
|
-
|
|
11
|
+
/** Rule metadata, in priority order. When several rules match, the first critical one wins, then the first high one. */
|
|
12
|
+
const RULE_INFO = {
|
|
13
|
+
"shell.fork-bomb": {
|
|
14
|
+
reason: "This command appears to create an unbounded process fork bomb.",
|
|
15
|
+
severity: "critical",
|
|
16
|
+
},
|
|
17
|
+
"filesystem.rm-critical-target": {
|
|
18
|
+
reason: "Recursive forced deletion targets a root, home, working directory, or variable-derived path.",
|
|
19
|
+
severity: "critical",
|
|
20
|
+
},
|
|
21
|
+
"filesystem.rm-recursive-force": {
|
|
22
|
+
reason: "Recursive forced deletion can permanently remove uncommitted or user data.",
|
|
23
|
+
severity: "high",
|
|
24
|
+
},
|
|
25
|
+
"filesystem.sensitive-path-write": {
|
|
26
|
+
reason: "This command writes to a credential, SSH, shell startup, Git config, scheduler, or system file outside the workspace.",
|
|
27
|
+
severity: "high",
|
|
28
|
+
},
|
|
29
|
+
"storage.raw-device-write": {
|
|
30
|
+
reason: "This command formats, erases, or writes directly to a block device.",
|
|
31
|
+
severity: "critical",
|
|
32
|
+
},
|
|
33
|
+
"process.mass-kill": {
|
|
34
|
+
reason: "This command can terminate every process available to the current user or system.",
|
|
35
|
+
severity: "critical",
|
|
36
|
+
},
|
|
37
|
+
"git.discard-worktree": {
|
|
38
|
+
reason: "This Git operation can discard uncommitted work or unreachable local commits.",
|
|
39
|
+
severity: "high",
|
|
40
|
+
},
|
|
41
|
+
"git.rewrite-remote": {
|
|
42
|
+
reason: "This Git operation can overwrite remote history.",
|
|
43
|
+
severity: "high",
|
|
44
|
+
},
|
|
45
|
+
"database.destructive-ddl": {
|
|
46
|
+
reason: "This command contains destructive database DDL.",
|
|
47
|
+
severity: "high",
|
|
48
|
+
},
|
|
49
|
+
"infrastructure.destroy": {
|
|
50
|
+
reason: "This command destroys infrastructure, namespaces, or persistent container data.",
|
|
51
|
+
severity: "high",
|
|
52
|
+
},
|
|
53
|
+
"cloud.bulk-delete": {
|
|
54
|
+
reason: "This command can recursively delete cloud data or an entire cloud project.",
|
|
55
|
+
severity: "high",
|
|
56
|
+
},
|
|
57
|
+
"supply-chain.remote-pipe-shell": {
|
|
58
|
+
reason: "Piping downloaded content directly into a shell executes unreviewed remote code.",
|
|
59
|
+
severity: "high",
|
|
60
|
+
},
|
|
61
|
+
"shell.program-launcher-option": {
|
|
62
|
+
reason: "This option makes the tool run another program (for example a preprocessor, pager, or config-defined command), which the guard cannot review.",
|
|
63
|
+
severity: "high",
|
|
64
|
+
},
|
|
65
|
+
"shell.excessive-nesting": {
|
|
66
|
+
reason: "This command nests shells or substitutions too deeply for the guard to review.",
|
|
67
|
+
severity: "high",
|
|
68
|
+
},
|
|
69
|
+
"shell.unparsed-command": {
|
|
70
|
+
reason: "The guard could not parse this command, so it cannot check what it would run.",
|
|
71
|
+
severity: "high",
|
|
72
|
+
},
|
|
73
|
+
"shell.unresolved-command-name": {
|
|
74
|
+
reason: "The program name is quoted, escaped, or built from an expansion, so the guard cannot tell which program would run. Write the program name as a plain word.",
|
|
75
|
+
severity: "high",
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
const RULE_ORDER = Object.keys(RULE_INFO);
|
|
79
|
+
/**
|
|
80
|
+
* Text the pattern rules see. Normalization is for pattern matching only:
|
|
81
|
+
* the parser reads the raw text, because bash treats look-alike characters
|
|
82
|
+
* (fullwidth quotes, Unicode dashes) as ordinary letters.
|
|
83
|
+
*/
|
|
84
|
+
function patternText(command) {
|
|
10
85
|
return command
|
|
11
86
|
.normalize("NFKC")
|
|
12
87
|
.replace(/\\\r?\n/g, "")
|
|
13
|
-
.replace(/[
|
|
88
|
+
.replace(/[‐-―−]/g, "-")
|
|
14
89
|
.trim();
|
|
15
90
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
91
|
+
/* ------------------------------------------------------------------------ */
|
|
92
|
+
/* Text-pattern rules */
|
|
93
|
+
/* */
|
|
94
|
+
/* These run over the raw command text in every case. They catch payloads */
|
|
95
|
+
/* the parser cannot see into, such as code passed to an interpreter */
|
|
96
|
+
/* (python -c, psql -c). The only text they do not see is the arguments of */
|
|
97
|
+
/* commands that cannot run anything (see TEXT_ONLY below), and only when */
|
|
98
|
+
/* every command in the line is such a command. */
|
|
99
|
+
/* ------------------------------------------------------------------------ */
|
|
21
100
|
function invocation(command, executable) {
|
|
22
101
|
const matches = [];
|
|
23
102
|
const pattern = new RegExp(`\\b${executable}\\s+([^;&|\\n]+)`, "gi");
|
|
@@ -25,90 +104,67 @@ function invocation(command, executable) {
|
|
|
25
104
|
matches.push(match[1]);
|
|
26
105
|
return matches;
|
|
27
106
|
}
|
|
28
|
-
function
|
|
107
|
+
function patternWords(value) {
|
|
29
108
|
return (value.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((word) => word.replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, "$1$2"));
|
|
30
109
|
}
|
|
31
|
-
function
|
|
110
|
+
function rmTargetsAreCritical(operands) {
|
|
111
|
+
return operands.some((operand) => {
|
|
112
|
+
const target = operand.replace(/\/+$/, "") || "/";
|
|
113
|
+
return (["/", ".", "..", "~", "$HOME", "${HOME}"].includes(target) ||
|
|
114
|
+
/^(?:\/|~|\$HOME|\$\{HOME\})\/\*$/.test(operand) ||
|
|
115
|
+
/\$(?:\{?[A-Za-z_][A-Za-z0-9_]*\}?)(?:\/|\*|$)/.test(operand));
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
function patternRecursiveForcedRemove(command) {
|
|
32
119
|
for (const args of invocation(command, "rm")) {
|
|
33
|
-
const words =
|
|
34
|
-
const recursive = words.some((word) => word === "--recursive" || /^-[^-]*r
|
|
120
|
+
const words = patternWords(args);
|
|
121
|
+
const recursive = words.some((word) => word === "--recursive" || /^-[^-]*r/i.test(word));
|
|
35
122
|
const forced = words.some((word) => word === "--force" || /^-[^-]*f/.test(word));
|
|
36
123
|
if (!recursive || !forced)
|
|
37
124
|
continue;
|
|
38
|
-
|
|
39
|
-
const critical = operands.some((operand) => {
|
|
40
|
-
const target = operand.replace(/\/+$/, "") || "/";
|
|
41
|
-
return (["/", ".", "..", "~", "$HOME", "${HOME}"].includes(target) ||
|
|
42
|
-
/^(?:\/|~|\$HOME|\$\{HOME\})\/\*$/.test(operand) ||
|
|
43
|
-
/\$(?:\{?[A-Za-z_][A-Za-z0-9_]*\}?)(?:\/|\*|$)/.test(operand));
|
|
44
|
-
});
|
|
45
|
-
return { matched: true, critical };
|
|
125
|
+
return { matched: true, critical: rmTargetsAreCritical(words.filter((word) => !word.startsWith("-"))) };
|
|
46
126
|
}
|
|
47
127
|
return { matched: false, critical: false };
|
|
48
128
|
}
|
|
49
|
-
const
|
|
129
|
+
const PATTERN_RULES = [
|
|
50
130
|
{
|
|
51
131
|
id: "shell.fork-bomb",
|
|
52
|
-
reason: "This command appears to create an unbounded process fork bomb.",
|
|
53
|
-
severity: "critical",
|
|
54
132
|
matches: (command) => /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;?\s*:/.test(command),
|
|
55
133
|
},
|
|
56
|
-
{
|
|
57
|
-
|
|
58
|
-
reason: "Recursive forced deletion targets a root, home, working directory, or variable-derived path.",
|
|
59
|
-
severity: "critical",
|
|
60
|
-
matches: (command) => recursiveForcedRemove(command).critical,
|
|
61
|
-
},
|
|
62
|
-
{
|
|
63
|
-
id: "filesystem.rm-recursive-force",
|
|
64
|
-
reason: "Recursive forced deletion can permanently remove uncommitted or user data.",
|
|
65
|
-
severity: "high",
|
|
66
|
-
matches: (command) => recursiveForcedRemove(command).matched,
|
|
67
|
-
},
|
|
134
|
+
{ id: "filesystem.rm-critical-target", matches: (command) => patternRecursiveForcedRemove(command).critical },
|
|
135
|
+
{ id: "filesystem.rm-recursive-force", matches: (command) => patternRecursiveForcedRemove(command).matched },
|
|
68
136
|
{
|
|
69
137
|
id: "storage.raw-device-write",
|
|
70
|
-
reason: "This command formats, erases, or writes directly to a block device.",
|
|
71
|
-
severity: "critical",
|
|
72
138
|
matches: (command) => /\b(?:mkfs(?:\.[A-Za-z0-9_+-]+)?|wipefs)\b/i.test(command) ||
|
|
73
139
|
/\bdiskutil\s+(?:eraseDisk|zeroDisk|secureErase)\b/i.test(command) ||
|
|
74
|
-
/\bdd\b[^;&|\n]*\bof\s*=\s*\/dev
|
|
140
|
+
/\bdd\b[^;&|\n]*\bof\s*=\s*\/dev\/(?!(?:null|zero|stdout|stderr|shm\/)\b)/i.test(command),
|
|
75
141
|
},
|
|
76
142
|
{
|
|
77
143
|
id: "process.mass-kill",
|
|
78
|
-
reason: "This command can terminate every process available to the current user or system.",
|
|
79
|
-
severity: "critical",
|
|
80
144
|
matches: (command) => /\bkill\b[^;&|\n]*(?:-9\s+-1|--signal\s+KILL\s+-1)\b/i.test(command) ||
|
|
81
145
|
/\bpkill\b[^;&|\n]*\s-(?:9|KILL)\b[^;&|\n]*(?:\.\*|\^\.\*\$)/i.test(command),
|
|
82
146
|
},
|
|
83
147
|
{
|
|
84
148
|
id: "git.discard-worktree",
|
|
85
|
-
reason: "This Git operation can discard uncommitted work or unreachable local commits.",
|
|
86
|
-
severity: "high",
|
|
87
149
|
matches: (command) => /\bgit\b[^;&|\n]*\breset\b[^;&|\n]*--hard\b/i.test(command) ||
|
|
88
150
|
/\bgit\b[^;&|\n]*\bclean\b(?=[^;&|\n]*-[A-Za-z]*f)[^;&|\n]*/i.test(command) ||
|
|
89
151
|
/\bgit\b[^;&|\n]*\bcheckout\s+--(?:\s|$)/i.test(command) ||
|
|
90
152
|
/\bgit\b[^;&|\n]*\brestore\b/i.test(command) ||
|
|
91
|
-
/\bgit\b[^;&|\n]*\bbranch\b[^;&|\n]*(?:-D|--delete\s+--force)\b
|
|
153
|
+
/\bgit\b[^;&|\n]*\bbranch\b[^;&|\n]*(?:-D|--delete\s+--force)\b/.test(command) ||
|
|
92
154
|
/\bgit\b[^;&|\n]*\bstash\s+(?:clear|drop)\b/i.test(command),
|
|
93
155
|
},
|
|
94
156
|
{
|
|
95
157
|
id: "git.rewrite-remote",
|
|
96
|
-
reason: "This Git operation can overwrite remote history.",
|
|
97
|
-
severity: "high",
|
|
98
158
|
matches: (command) => /\bgit\b[^;&|\n]*\bpush\b[^;&|\n]*--force(?:=|\s|$)/i.test(command),
|
|
99
159
|
},
|
|
100
160
|
{
|
|
101
161
|
id: "database.destructive-ddl",
|
|
102
|
-
reason: "This command contains destructive database DDL.",
|
|
103
|
-
severity: "high",
|
|
104
162
|
matches: (command) => /\bDROP\s+(?:DATABASE|SCHEMA|TABLE)\b/i.test(command) ||
|
|
105
163
|
/\bTRUNCATE\s+(?:TABLE\s+)?[A-Za-z_]/i.test(command) ||
|
|
106
164
|
/\b(?:dropdb|redis-cli\s+(?:FLUSHALL|FLUSHDB))\b/i.test(command),
|
|
107
165
|
},
|
|
108
166
|
{
|
|
109
167
|
id: "infrastructure.destroy",
|
|
110
|
-
reason: "This command destroys infrastructure, namespaces, or persistent container data.",
|
|
111
|
-
severity: "high",
|
|
112
168
|
matches: (command) => /\b(?:terraform|tofu|pulumi)\s+destroy\b/i.test(command) ||
|
|
113
169
|
/\bkubectl\b[^;&|\n]*\bdelete\s+(?:namespace|ns)\b/i.test(command) ||
|
|
114
170
|
/\bdocker\s+(?:system|volume)\s+prune\b/i.test(command) ||
|
|
@@ -116,8 +172,6 @@ const RULES = [
|
|
|
116
172
|
},
|
|
117
173
|
{
|
|
118
174
|
id: "cloud.bulk-delete",
|
|
119
|
-
reason: "This command can recursively delete cloud data or an entire cloud project.",
|
|
120
|
-
severity: "high",
|
|
121
175
|
matches: (command) => /\baws\s+s3\s+rm\b[^;&|\n]*--recursive\b/i.test(command) ||
|
|
122
176
|
/\bgsutil\b[^;&|\n]*\brm\b[^;&|\n]*-[A-Za-z]*r/i.test(command) ||
|
|
123
177
|
/\bgcloud\s+projects\s+delete\b/i.test(command) ||
|
|
@@ -125,11 +179,1248 @@ const RULES = [
|
|
|
125
179
|
},
|
|
126
180
|
{
|
|
127
181
|
id: "supply-chain.remote-pipe-shell",
|
|
128
|
-
reason: "Piping downloaded content directly into a shell executes unreviewed remote code.",
|
|
129
|
-
severity: "high",
|
|
130
182
|
matches: (command) => /\b(?:curl|wget)\b[^|\n]*\|\s*(?:sudo\s+)?(?:ba|z|k|fi)?sh\b/i.test(command),
|
|
131
183
|
},
|
|
132
184
|
];
|
|
185
|
+
/* ------------------------------------------------------------------------ */
|
|
186
|
+
/* Parsed-command rules */
|
|
187
|
+
/* ------------------------------------------------------------------------ */
|
|
188
|
+
const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "mksh", "ash", "fish", "yash"]);
|
|
189
|
+
const FETCHERS = new Set(["curl", "wget"]);
|
|
190
|
+
const SHELL_KEYWORDS = new Set([
|
|
191
|
+
"!", "{", "}", "if", "then", "else", "elif", "fi", "do", "done", "while", "until",
|
|
192
|
+
]);
|
|
193
|
+
/** Segments that start with these words do not run their remaining words as a command. */
|
|
194
|
+
const NON_COMMAND_KEYWORDS = new Set(["for", "select", "case", "esac", "in"]);
|
|
195
|
+
/** Environment variables whose value is a command line that a later program runs. */
|
|
196
|
+
const COMMAND_ENV_VARS = new Set([
|
|
197
|
+
"GIT_PAGER", "PAGER", "GIT_EDITOR", "EDITOR", "VISUAL", "GIT_SEQUENCE_EDITOR", "GIT_EXTERNAL_DIFF",
|
|
198
|
+
"GIT_SSH_COMMAND", "GIT_SSH", "GIT_ASKPASS", "SSH_ASKPASS", "GIT_PROXY_COMMAND", "LESSOPEN", "LESSCLOSE",
|
|
199
|
+
"MANPAGER", "BROWSER", "PROMPT_COMMAND", "BASH_ENV", "ENV",
|
|
200
|
+
]);
|
|
201
|
+
/** Environment variables that inject Git configuration. */
|
|
202
|
+
const GIT_CONFIG_ENV = /^(?:GIT_CONFIG_PARAMETERS|GIT_CONFIG_COUNT|GIT_CONFIG_KEY_\d+|GIT_CONFIG_VALUE_\d+|GIT_CONFIG|GIT_CONFIG_GLOBAL|GIT_CONFIG_SYSTEM)$/;
|
|
203
|
+
/** Git config keys that may be set with `git -c`: they only hold data, never a command. */
|
|
204
|
+
const GIT_SAFE_CONFIG_KEY = /^(?:color\.[a-z0-9.-]+|user\.(?:name|email)|author\.(?:name|email)|committer\.(?:name|email)|core\.(?:quotepath|autocrlf|safecrlf|filemode|ignorecase|longpaths|abbrev|precomposeunicode)|advice\.[a-z0-9-]+|init\.defaultbranch|(?:commit|tag)\.gpgsign|log\.(?:showsignature|date|decorate|follow)|safe\.directory|protocol\.version|pull\.(?:rebase|ff)|merge\.(?:ff|conflictstyle)|fetch\.(?:prune|parallel)|i18n\.[a-z]+|diff\.(?:noprefix|renames|algorithm|mnemonicprefix|colormoved)|status\.[a-z]+|column\.ui|blame\.[a-z]+|format\.pretty|gc\.auto|maintenance\.auto|submodule\.recurse|rerere\.enabled|grep\.[a-z]+|http\.(?:sslverify|postbuffer|version)|rebase\.(?:autosquash|autostash)|push\.(?:default|autosetupremote))$/;
|
|
205
|
+
/** Git config keys whose value is run as a program (or that pull in other config). */
|
|
206
|
+
const GIT_EXEC_CONFIG_KEY = /^(?:core\.(?:pager|editor|sshcommand|fsmonitor|hookspath|askpass|gitproxy)|alias\..+|pager\..+|diff\.external|diff\..+\.(?:textconv|command)|filter\..+\.(?:clean|smudge|process)|merge\..+\.driver|credential\.(?:.+\.)?helper|sequence\.editor|gpg\.(?:.+\.)?program|uploadpack\.packobjectshook|web\.browser|browser\..+\.cmd|(?:diff|merge)tool\..+\.cmd|remote\..+\.(?:uploadpack|receivepack)|include\.path|includeif\..+|sendemail\..+|ssh\.variant|interactive\.difffilter|core\.alternaterefscommand|trailer\..+\.(?:cmd|command)|gpg\.ssh\.defaultkeycommand|man\..+\.(?:cmd|path)|(?:diff|merge)tool\..+\.path|browser\..+\.path)$/;
|
|
207
|
+
const SAFE_COMPRESSORS = new Set([
|
|
208
|
+
"gzip", "gunzip", "pigz", "zstd", "unzstd", "pzstd", "xz", "unxz", "pixz", "bzip2", "bunzip2", "pbzip2",
|
|
209
|
+
"lz4", "lzip", "lzma", "brotli", "zcat", "compress", "uncompress",
|
|
210
|
+
]);
|
|
211
|
+
const SAFE_DEVICE = /^\/dev\/(?:null|zero|stdin|stdout|stderr|tty\w*|fd\/\d+|random|urandom|ptmx|pts\/\d+|console|shm\/.*|(?:tcp|udp)\/.*)$/;
|
|
212
|
+
/**
|
|
213
|
+
* Commands that only read or print text and cannot run any program named in
|
|
214
|
+
* their arguments, with their allowed form. Their arguments are treated as
|
|
215
|
+
* plain text (so `rg "rm -rf" src` is not mistaken for a deletion), but only
|
|
216
|
+
* when every command in the line is one of these.
|
|
217
|
+
*/
|
|
218
|
+
const TEXT_ONLY = new Set([
|
|
219
|
+
"echo", "printf", "rg", "grep", "egrep", "fgrep", "ag", "ack", "cat", "head", "tail", "wc", "ls", "pwd",
|
|
220
|
+
"true", "false", "sort", "uniq", "cut", "tr", "nl", "basename", "dirname", "realpath", "cd",
|
|
221
|
+
]);
|
|
222
|
+
const TEXT_ONLY_GIT = new Set([
|
|
223
|
+
"status", "log", "show", "diff", "commit", "add", "grep", "blame", "shortlog", "rev-parse", "ls-files",
|
|
224
|
+
]);
|
|
225
|
+
function basename(value) {
|
|
226
|
+
return (value.split("/").pop() ?? value).toLowerCase();
|
|
227
|
+
}
|
|
228
|
+
function isAssignment(word) {
|
|
229
|
+
return /^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=/.test(word);
|
|
230
|
+
}
|
|
231
|
+
function longValue(arg, name, args, index) {
|
|
232
|
+
if (arg === name)
|
|
233
|
+
return args[index + 1];
|
|
234
|
+
if (arg.startsWith(`${name}=`))
|
|
235
|
+
return arg.slice(name.length + 1);
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
function compressorIsPlain(value) {
|
|
239
|
+
if (value === undefined)
|
|
240
|
+
return false;
|
|
241
|
+
const words = value.trim().split(/\s+/);
|
|
242
|
+
// A bare name resolved from PATH only; an explicit path could be any program.
|
|
243
|
+
return SAFE_COMPRESSORS.has(words[0] ?? "") && words.slice(1).every((word) => /^-[A-Za-z0-9=]+$/.test(word));
|
|
244
|
+
}
|
|
245
|
+
/** Separates option-like words from operands, honouring `--`. */
|
|
246
|
+
function splitOptions(args) {
|
|
247
|
+
const options = [];
|
|
248
|
+
const operands = [];
|
|
249
|
+
let ended = false;
|
|
250
|
+
for (const arg of args) {
|
|
251
|
+
if (!ended && arg === "--")
|
|
252
|
+
ended = true;
|
|
253
|
+
else if (!ended && arg.startsWith("-") && arg !== "-")
|
|
254
|
+
options.push(arg);
|
|
255
|
+
else
|
|
256
|
+
operands.push(arg);
|
|
257
|
+
}
|
|
258
|
+
return { options, operands };
|
|
259
|
+
}
|
|
260
|
+
/** Returns option words that are not the value of a preceding value-taking option. */
|
|
261
|
+
function optionsOutsideValues(args, takesValue) {
|
|
262
|
+
const options = [];
|
|
263
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
264
|
+
const arg = args[i];
|
|
265
|
+
if (arg === "--")
|
|
266
|
+
break;
|
|
267
|
+
if (!arg.startsWith("-") || arg === "-")
|
|
268
|
+
continue;
|
|
269
|
+
options.push(arg);
|
|
270
|
+
if (takesValue.has(arg))
|
|
271
|
+
i += 1;
|
|
272
|
+
}
|
|
273
|
+
return options;
|
|
274
|
+
}
|
|
275
|
+
const RG_VALUE_OPTIONS = new Set([
|
|
276
|
+
"-e", "--regexp", "-f", "--file", "-g", "--glob", "--iglob", "-t", "--type", "-T", "--type-not", "-m", "--max-count",
|
|
277
|
+
"-A", "--after-context", "-B", "--before-context", "-C", "--context", "-M", "--max-columns", "-j", "--threads",
|
|
278
|
+
"-E", "--encoding", "-r", "--replace", "--type-add", "--type-clear", "--sort", "--sortr", "-d", "--max-depth",
|
|
279
|
+
"--max-filesize", "--path-separator", "--ignore-file", "--colors", "--color", "--context-separator",
|
|
280
|
+
"--field-match-separator", "--field-context-separator", "--pre-glob", "--engine", "--dfa-size-limit",
|
|
281
|
+
"--regex-size-limit",
|
|
282
|
+
]);
|
|
283
|
+
const GIT_GREP_VALUE_OPTIONS = new Set(["-e", "-f", "-A", "-B", "-C", "-m", "--max-count", "--max-depth", "--threads"]);
|
|
284
|
+
/** Wrappers that only change how a program runs (privileges, environment, limits), not what it runs. */
|
|
285
|
+
const TRANSPARENT_WRAPPERS = new Set([
|
|
286
|
+
"command", "builtin", "exec", "nohup", "nice", "timeout", "stdbuf", "ionice", "sudo", "doas", "env", "time", "setsid",
|
|
287
|
+
"flock", "strace", "ltrace",
|
|
288
|
+
]);
|
|
289
|
+
/** Compound commands that can follow `coproc NAME`. */
|
|
290
|
+
const COMPOUND_STARTS = new Set(["{", "while", "until", "if", "for", "select", "case"]);
|
|
291
|
+
const STRACE_VALUE_OPTIONS = new Set([
|
|
292
|
+
"-a", "-b", "-e", "-E", "-I", "-o", "-O", "-p", "-P", "-s", "-S", "-u", "-U", "-X",
|
|
293
|
+
"--output", "--trace", "--attach", "--user", "--env", "--signal", "--status", "--detach-on",
|
|
294
|
+
]);
|
|
295
|
+
const LTRACE_VALUE_OPTIONS = new Set([
|
|
296
|
+
"-a", "-A", "-D", "-e", "-F", "-l", "-n", "-o", "-p", "-s", "-u", "-w", "-x", "--align", "--output", "--library", "--indent",
|
|
297
|
+
]);
|
|
298
|
+
/**
|
|
299
|
+
* True when a word in command position names a program the guard can identify:
|
|
300
|
+
* an unquoted, unescaped word with no expansion, glob, or brace list.
|
|
301
|
+
*/
|
|
302
|
+
function plainCommandWord(raw) {
|
|
303
|
+
if (!/^~?[A-Za-z0-9_.\/+:@%=\[\]!{}-]+$/.test(raw))
|
|
304
|
+
return false;
|
|
305
|
+
return !/\{[^{}]*(?:,|\.\.)[^{}]*\}/.test(raw);
|
|
306
|
+
}
|
|
307
|
+
/** True when a span can be hidden from the pattern rules: bash and the parser cannot disagree about it. */
|
|
308
|
+
function safeToMask(span, kind) {
|
|
309
|
+
if (span !== span.normalize("NFKC"))
|
|
310
|
+
return false;
|
|
311
|
+
if (kind !== "word")
|
|
312
|
+
return true;
|
|
313
|
+
// A bare word with no shell metacharacters, or one fully single- or double-quoted string that cannot expand.
|
|
314
|
+
return /^[^\s;|&$(){}<>`'"\\]+$/.test(span) || /^'[^'\n]*'$/.test(span) || /^"[^"$`\\\n]*"$/.test(span);
|
|
315
|
+
}
|
|
316
|
+
function shortCluster(options, letter) {
|
|
317
|
+
return options.some((option) => /^-[A-Za-z0-9]+$/.test(option) && option.slice(1).includes(letter));
|
|
318
|
+
}
|
|
319
|
+
const HOME_A = "\u0000home";
|
|
320
|
+
const HOME_B = "\u0000user";
|
|
321
|
+
const HOME = ["/", HOME_A, HOME_B];
|
|
322
|
+
const START = ["."];
|
|
323
|
+
const MAX_CWDS = 16;
|
|
324
|
+
/** Files and directories that a command should not write to. `**` matches the directory itself and everything below it. */
|
|
325
|
+
const SENSITIVE_HOME_PATHS = [
|
|
326
|
+
".ssh/**",
|
|
327
|
+
".bashrc", ".bash_profile", ".bash_login", ".bash_logout", ".profile", ".zshrc", ".zshenv", ".zprofile", ".zlogin",
|
|
328
|
+
".zlogout", ".kshrc", ".cshrc", ".tcshrc", ".login", ".config/fish/**",
|
|
329
|
+
".gitconfig", ".config/git/**",
|
|
330
|
+
".aws/**", ".netrc", ".npmrc", ".docker/config.json", ".kube/**", ".gnupg/**",
|
|
331
|
+
"Library/LaunchAgents/**", ".config/systemd/**",
|
|
332
|
+
];
|
|
333
|
+
const SENSITIVE_SYSTEM_PATHS = [
|
|
334
|
+
"etc/**", "private/etc/**", "usr/**", "bin/**", "sbin/**", "boot/**", "lib/systemd/**",
|
|
335
|
+
"Library/LaunchAgents/**", "Library/LaunchDaemons/**",
|
|
336
|
+
"var/spool/cron/**", "var/at/**", "private/var/at/**",
|
|
337
|
+
];
|
|
338
|
+
const HOME_PATTERNS = SENSITIVE_HOME_PATHS.map((path) => [...HOME, ...path.split("/")]);
|
|
339
|
+
const SYSTEM_PATTERNS = SENSITIVE_SYSTEM_PATHS.map((path) => ["/", ...path.split("/")]);
|
|
340
|
+
/** A segment built from an expansion ($X, $(...)) can be any name. */
|
|
341
|
+
function isExpansionSegment(segment) {
|
|
342
|
+
return /[$`]/.test(segment);
|
|
343
|
+
}
|
|
344
|
+
function globToRegExp(glob) {
|
|
345
|
+
if (!/[*?[]/.test(glob))
|
|
346
|
+
return undefined;
|
|
347
|
+
let source = "";
|
|
348
|
+
for (let i = 0; i < glob.length; i += 1) {
|
|
349
|
+
const c = glob[i];
|
|
350
|
+
if (c === "*")
|
|
351
|
+
source += ".*";
|
|
352
|
+
else if (c === "?")
|
|
353
|
+
source += ".";
|
|
354
|
+
else if (c === "[") {
|
|
355
|
+
const close = glob.indexOf("]", i + 2);
|
|
356
|
+
if (close === -1)
|
|
357
|
+
source += "\\[";
|
|
358
|
+
else {
|
|
359
|
+
source += `[${glob.slice(i + 1, close).replace(/^!/, "^").replace(/\\/g, "\\\\")}]`;
|
|
360
|
+
i = close;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
else
|
|
364
|
+
source += c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
return new RegExp(`^${source}$`, "i");
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
// Not a valid pattern (for example an out-of-order range): compare it literally.
|
|
371
|
+
return undefined;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
function segmentMatches(target, pattern) {
|
|
375
|
+
if (isExpansionSegment(target))
|
|
376
|
+
return true;
|
|
377
|
+
const glob = globToRegExp(target);
|
|
378
|
+
if (glob)
|
|
379
|
+
return glob.test(pattern);
|
|
380
|
+
// Case-insensitive, as on the default macOS file system.
|
|
381
|
+
return target.toLowerCase() === pattern.toLowerCase();
|
|
382
|
+
}
|
|
383
|
+
function pathMatches(target, pattern, t = 0, p = 0) {
|
|
384
|
+
if (p === pattern.length)
|
|
385
|
+
return t === target.length;
|
|
386
|
+
if (pattern[p] === "**")
|
|
387
|
+
return true;
|
|
388
|
+
if (t === target.length)
|
|
389
|
+
return false;
|
|
390
|
+
return segmentMatches(target[t], pattern[p]) && pathMatches(target, pattern, t + 1, p + 1);
|
|
391
|
+
}
|
|
392
|
+
/** Appends path segments, applying `.` and `..`. */
|
|
393
|
+
function joinPath(base, segments) {
|
|
394
|
+
const path = [...base];
|
|
395
|
+
for (const segment of segments) {
|
|
396
|
+
if (segment === "" || segment === ".")
|
|
397
|
+
continue;
|
|
398
|
+
if (segment !== "..")
|
|
399
|
+
path.push(segment);
|
|
400
|
+
else if (path.length > 1)
|
|
401
|
+
path.pop();
|
|
402
|
+
// Climbing out of the start directory leads somewhere the guard cannot name.
|
|
403
|
+
else if (path[0] === ".")
|
|
404
|
+
path[0] = "?";
|
|
405
|
+
}
|
|
406
|
+
return path;
|
|
407
|
+
}
|
|
408
|
+
const HOME_SEGMENTS = (() => {
|
|
409
|
+
try {
|
|
410
|
+
return homedir().split("/").filter(Boolean);
|
|
411
|
+
}
|
|
412
|
+
catch {
|
|
413
|
+
return [];
|
|
414
|
+
}
|
|
415
|
+
})();
|
|
416
|
+
/** Rewrites an absolute path inside a home directory to start with HOME. */
|
|
417
|
+
function withHomeMarker(path) {
|
|
418
|
+
if (path[0] !== "/")
|
|
419
|
+
return path;
|
|
420
|
+
const rest = path.slice(1);
|
|
421
|
+
const lower = rest.map((segment) => segment.toLowerCase());
|
|
422
|
+
if (HOME_SEGMENTS.length && HOME_SEGMENTS.every((segment, i) => lower[i] === segment.toLowerCase())) {
|
|
423
|
+
return [...HOME, ...rest.slice(HOME_SEGMENTS.length)];
|
|
424
|
+
}
|
|
425
|
+
if ((lower[0] === "home" || lower[0] === "users") && rest.length >= 2)
|
|
426
|
+
return [...HOME, ...rest.slice(2)];
|
|
427
|
+
if (lower[0] === "root")
|
|
428
|
+
return [...HOME, ...rest.slice(1)];
|
|
429
|
+
if (lower[0] === "var" && lower[1] === "root")
|
|
430
|
+
return [...HOME, ...rest.slice(2)];
|
|
431
|
+
return path;
|
|
432
|
+
}
|
|
433
|
+
/** Resolves a path word (after quote removal) against the current directory. */
|
|
434
|
+
function resolvePath(value, cwd) {
|
|
435
|
+
const home = /^(?:~[^/]*|\$HOME(?![A-Za-z0-9_])|\$\{HOME(?:[:#%/^,@][^}]*)?\})(?=\/|$)/.exec(value);
|
|
436
|
+
if (home)
|
|
437
|
+
return withHomeMarker(joinPath(HOME, value.slice(home[0].length).split("/")));
|
|
438
|
+
if (value.startsWith("/"))
|
|
439
|
+
return withHomeMarker(joinPath(["/"], value.split("/")));
|
|
440
|
+
const segments = value.split("/");
|
|
441
|
+
// A path that starts with an expansion ($DIR/x) is relative to a directory the guard cannot name.
|
|
442
|
+
if (isExpansionSegment(segments[0]))
|
|
443
|
+
return joinPath(["?"], segments.slice(1));
|
|
444
|
+
return withHomeMarker(joinPath(cwd, segments));
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* True when a resolved path is one of the sensitive locations. A path under
|
|
448
|
+
* an unknown directory is compared with the home-directory locations only,
|
|
449
|
+
* since those names (.ssh, .bashrc, ...) rarely appear anywhere else.
|
|
450
|
+
*/
|
|
451
|
+
function isSensitivePath(path) {
|
|
452
|
+
if (path[0] === ".")
|
|
453
|
+
return false;
|
|
454
|
+
if (path[0] === "?")
|
|
455
|
+
return HOME_PATTERNS.some((pattern) => pathMatches([...HOME, ...path.slice(1)], pattern));
|
|
456
|
+
return [...HOME_PATTERNS, ...SYSTEM_PATTERNS].some((pattern) => pathMatches(path, pattern));
|
|
457
|
+
}
|
|
458
|
+
/** Options that take a value, for programs that copy, move, or link files. */
|
|
459
|
+
const COPY_VALUE_OPTIONS = {
|
|
460
|
+
cp: new Set(["-t", "--target-directory", "-S", "--suffix"]),
|
|
461
|
+
mv: new Set(["-t", "--target-directory", "-S", "--suffix"]),
|
|
462
|
+
ln: new Set(["-t", "--target-directory", "-S", "--suffix"]),
|
|
463
|
+
install: new Set(["-t", "--target-directory", "-S", "--suffix", "-m", "--mode", "-o", "--owner", "-g", "--group", "-B", "-f"]),
|
|
464
|
+
};
|
|
465
|
+
/** For cp, mv, ln and install: the destination and the sources. */
|
|
466
|
+
function copyOperands(name, args) {
|
|
467
|
+
const takesValue = COPY_VALUE_OPTIONS[name];
|
|
468
|
+
const operands = [];
|
|
469
|
+
let parents = false;
|
|
470
|
+
let targetDirectory;
|
|
471
|
+
let directoriesOnly = false;
|
|
472
|
+
let ended = false;
|
|
473
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
474
|
+
const arg = args[i];
|
|
475
|
+
if (ended || arg === "-" || !arg.startsWith("-")) {
|
|
476
|
+
operands.push(arg);
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (arg === "--") {
|
|
480
|
+
ended = true;
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
const target = longValue(arg, "--target-directory", args, i) ?? (arg === "-t" ? args[i + 1] : /^-t./.test(arg) ? arg.slice(2) : undefined);
|
|
484
|
+
if (target !== undefined)
|
|
485
|
+
targetDirectory = target;
|
|
486
|
+
if (name === "install" && (arg === "-d" || arg === "--directory"))
|
|
487
|
+
directoriesOnly = true;
|
|
488
|
+
if (name === "cp" && arg === "--parents")
|
|
489
|
+
parents = true;
|
|
490
|
+
if (takesValue.has(arg))
|
|
491
|
+
i += 1;
|
|
492
|
+
}
|
|
493
|
+
if (directoriesOnly)
|
|
494
|
+
return { destinations: operands, sources: [], parents };
|
|
495
|
+
if (targetDirectory !== undefined)
|
|
496
|
+
return { destinations: [targetDirectory], sources: operands, parents };
|
|
497
|
+
if (operands.length < 2) {
|
|
498
|
+
return { destinations: name === "ln" ? operands : [], sources: name === "ln" ? [] : operands, parents };
|
|
499
|
+
}
|
|
500
|
+
return { destinations: [operands[operands.length - 1]], sources: operands.slice(0, -1), parents };
|
|
501
|
+
}
|
|
502
|
+
/** Pager commands that only display text: the value of PAGER, GIT_PAGER, core.pager and similar settings. */
|
|
503
|
+
function pagerIsPlain(value) {
|
|
504
|
+
const words = value.trim().split(/\s+/).filter(Boolean);
|
|
505
|
+
if (!words.length)
|
|
506
|
+
return true;
|
|
507
|
+
// Bare names from PATH; less options that neither take a value nor write a file.
|
|
508
|
+
return ["cat", "less", "more", "most", "true", "false", ":"].includes(words[0]) &&
|
|
509
|
+
words.slice(1).every((word) => /^-[RrFXSsiIMmNnEeKwWJ]+$/.test(word));
|
|
510
|
+
}
|
|
511
|
+
/** Environment variables whose value is used as a pager. */
|
|
512
|
+
const PAGER_ENV_VARS = new Set(["GIT_PAGER", "PAGER", "MANPAGER"]);
|
|
513
|
+
class Analysis {
|
|
514
|
+
source;
|
|
515
|
+
constructor(source) {
|
|
516
|
+
this.source = source;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Every directory the current command may run in. A `cd` adds its target
|
|
520
|
+
* rather than replacing the set, because it may be skipped (`a || cd x`)
|
|
521
|
+
* or fail.
|
|
522
|
+
*/
|
|
523
|
+
cwds = [START];
|
|
524
|
+
/** Source text of the arguments of the program currently being checked, when known. */
|
|
525
|
+
currentRawArgs;
|
|
526
|
+
findings = new Set();
|
|
527
|
+
extraTexts = [];
|
|
528
|
+
allTextOnly = true;
|
|
529
|
+
/** Spans of the top-level text that hold only plain text. */
|
|
530
|
+
maskable = [];
|
|
531
|
+
add(id) {
|
|
532
|
+
this.findings.add(id);
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Parses a string the shell would run as a command line and checks it.
|
|
536
|
+
* It runs in a child process unless `sameShell` is set (eval), so its `cd`
|
|
537
|
+
* commands do not change the directory of later commands.
|
|
538
|
+
*/
|
|
539
|
+
nestedScript(text, depth, sameShell = false) {
|
|
540
|
+
this.allTextOnly = false;
|
|
541
|
+
this.extraTexts.push(text);
|
|
542
|
+
const cwds = this.cwds;
|
|
543
|
+
try {
|
|
544
|
+
this.script(parseShell(text, 0, depth), depth, false);
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
this.add(parseFailureRule(error));
|
|
548
|
+
}
|
|
549
|
+
finally {
|
|
550
|
+
if (!sameShell)
|
|
551
|
+
this.cwds = cwds;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
script(script, depth, topLevel) {
|
|
555
|
+
const names = new Set();
|
|
556
|
+
if (topLevel) {
|
|
557
|
+
for (const [start, end] of script.comments) {
|
|
558
|
+
const before = start === 0 ? " " : this.source[start - 1];
|
|
559
|
+
if (/[ \t\n;&|()<>]/.test(before) && safeToMask(this.source.slice(start, end), "comment")) {
|
|
560
|
+
this.maskable.push([start, end]);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
// A `cd` inside a `( ... )` subshell does not change the directory outside it.
|
|
565
|
+
let open = [];
|
|
566
|
+
const cwdsOutside = [];
|
|
567
|
+
for (const pipeline of script.pipelines) {
|
|
568
|
+
let shared = 0;
|
|
569
|
+
while (shared < open.length && open[shared] === pipeline.subshells[shared])
|
|
570
|
+
shared += 1;
|
|
571
|
+
if (shared < open.length)
|
|
572
|
+
this.cwds = cwdsOutside[shared];
|
|
573
|
+
cwdsOutside.length = shared;
|
|
574
|
+
for (let i = shared; i < pipeline.subshells.length; i += 1)
|
|
575
|
+
cwdsOutside[i] = this.cwds;
|
|
576
|
+
open = pipeline.subshells;
|
|
577
|
+
// Each stage of a multi-command pipeline runs in its own subshell.
|
|
578
|
+
const before = this.cwds;
|
|
579
|
+
const isolated = pipeline.commands.length > 1;
|
|
580
|
+
const pipelineNames = pipeline.commands.map((command) => {
|
|
581
|
+
const stageNames = this.command(command, depth, topLevel);
|
|
582
|
+
if (isolated)
|
|
583
|
+
this.cwds = before;
|
|
584
|
+
return stageNames;
|
|
585
|
+
});
|
|
586
|
+
pipelineNames.forEach((set) => set.forEach((name) => names.add(name)));
|
|
587
|
+
// A download piped into a shell later in the same pipeline.
|
|
588
|
+
const fetchAt = pipelineNames.findIndex((set) => [...set].some((name) => FETCHERS.has(name)));
|
|
589
|
+
if (fetchAt !== -1 && pipelineNames.slice(fetchAt + 1).some((set) => [...set].some((name) => SHELLS.has(name)))) {
|
|
590
|
+
this.add("supply-chain.remote-pipe-shell");
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return names;
|
|
594
|
+
}
|
|
595
|
+
/** Checks a command or process substitution, which runs in its own subshell. */
|
|
596
|
+
substitution(sub, depth) {
|
|
597
|
+
const cwds = this.cwds;
|
|
598
|
+
try {
|
|
599
|
+
return this.script(sub, depth + 1, false);
|
|
600
|
+
}
|
|
601
|
+
finally {
|
|
602
|
+
this.cwds = cwds;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
/** Checks one simple command. Returns the names of the programs it runs (including nested ones). */
|
|
606
|
+
command(command, depth, topLevel) {
|
|
607
|
+
const names = new Set();
|
|
608
|
+
const wordFetches = [];
|
|
609
|
+
for (const word of command.words) {
|
|
610
|
+
let fetches = false;
|
|
611
|
+
for (const sub of word.substitutions) {
|
|
612
|
+
const inner = this.substitution(sub, depth);
|
|
613
|
+
inner.forEach((name) => names.add(name));
|
|
614
|
+
if ([...inner].some((name) => FETCHERS.has(name)))
|
|
615
|
+
fetches = true;
|
|
616
|
+
}
|
|
617
|
+
wordFetches.push(fetches);
|
|
618
|
+
}
|
|
619
|
+
let redirectFetches = false;
|
|
620
|
+
for (const redirect of command.redirects) {
|
|
621
|
+
for (const sub of [...(redirect.target?.substitutions ?? []), ...(redirect.heredoc?.substitutions ?? [])]) {
|
|
622
|
+
const inner = this.substitution(sub, depth);
|
|
623
|
+
inner.forEach((name) => names.add(name));
|
|
624
|
+
if ([...inner].some((name) => FETCHERS.has(name)))
|
|
625
|
+
redirectFetches = true;
|
|
626
|
+
}
|
|
627
|
+
this.redirect(redirect);
|
|
628
|
+
}
|
|
629
|
+
if (command.casePattern)
|
|
630
|
+
return names;
|
|
631
|
+
// Brace expansion turns one word into several; keep a map back to the source word.
|
|
632
|
+
const argv = [];
|
|
633
|
+
const wordOf = [];
|
|
634
|
+
command.words.forEach((word, index) => {
|
|
635
|
+
for (const value of word.braceExpansion ?? [word.value]) {
|
|
636
|
+
argv.push(value);
|
|
637
|
+
wordOf.push(index);
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
const raws = argv.map((_, i) => command.words[wordOf[i]].raw);
|
|
641
|
+
const effective = this.argv(argv, depth, command, raws);
|
|
642
|
+
effective.names.forEach((name) => names.add(name));
|
|
643
|
+
// Running the output of a download: `$(curl ...)` as the command, or fed to a shell.
|
|
644
|
+
const commandWord = command.words.findIndex((word) => !isAssignment(word.value));
|
|
645
|
+
if (commandWord !== -1 && wordFetches[commandWord])
|
|
646
|
+
this.add("supply-chain.remote-pipe-shell");
|
|
647
|
+
if ((effective.scriptWords ?? []).some((index) => wordFetches[wordOf[index]]))
|
|
648
|
+
this.add("supply-chain.remote-pipe-shell");
|
|
649
|
+
if (effective.readsStdin && redirectFetches)
|
|
650
|
+
this.add("supply-chain.remote-pipe-shell");
|
|
651
|
+
if (!effective.textOnly)
|
|
652
|
+
this.allTextOnly = false;
|
|
653
|
+
else if (topLevel) {
|
|
654
|
+
// Only the final program's own arguments are plain text; wrapper options are not.
|
|
655
|
+
const firstArgument = effective.runnerIndex === undefined ? command.words.length : wordOf[effective.runnerIndex] + 1;
|
|
656
|
+
this.markTextOnly(command, firstArgument);
|
|
657
|
+
}
|
|
658
|
+
return names;
|
|
659
|
+
}
|
|
660
|
+
markTextOnly(command, firstArgument) {
|
|
661
|
+
for (const word of command.words.slice(firstArgument)) {
|
|
662
|
+
if (safeToMask(this.source.slice(word.start, word.end), "word"))
|
|
663
|
+
this.maskable.push([word.start, word.end]);
|
|
664
|
+
}
|
|
665
|
+
for (const redirect of command.redirects) {
|
|
666
|
+
const heredoc = redirect.heredoc;
|
|
667
|
+
if (heredoc?.quoted && safeToMask(this.source.slice(heredoc.start, heredoc.end), "heredoc")) {
|
|
668
|
+
this.maskable.push([heredoc.start, heredoc.end]);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
redirect(redirect) {
|
|
673
|
+
const target = redirect.target?.value;
|
|
674
|
+
if (!target || !/>/.test(redirect.op))
|
|
675
|
+
return;
|
|
676
|
+
// `>&2`, `2>&1` and `>&-` duplicate or close a descriptor; `>(...)` is checked as a command.
|
|
677
|
+
if (/&/.test(redirect.op) && /^(?:\d+-?|-)$/.test(target))
|
|
678
|
+
return;
|
|
679
|
+
if (/^[<>]\(/.test(target))
|
|
680
|
+
return;
|
|
681
|
+
if (target.startsWith("/dev/") && !SAFE_DEVICE.test(target))
|
|
682
|
+
this.add("storage.raw-device-write");
|
|
683
|
+
this.writeTarget(target);
|
|
684
|
+
}
|
|
685
|
+
/** Records a write to a file at `target`, a word after quote removal. */
|
|
686
|
+
writeTarget(target) {
|
|
687
|
+
if (this.cwds.some((cwd) => isSensitivePath(resolvePath(target, cwd))))
|
|
688
|
+
this.add("filesystem.sensitive-path-write");
|
|
689
|
+
}
|
|
690
|
+
/** Follows `cd`, so later relative paths also resolve against the new directory. */
|
|
691
|
+
changeDirectory(name, args) {
|
|
692
|
+
const operand = name === "popd" ? "-" : splitOptions(args).operands[0];
|
|
693
|
+
let added;
|
|
694
|
+
if (operand === undefined)
|
|
695
|
+
added = name === "cd" ? [HOME] : [];
|
|
696
|
+
else if (operand === "-" || /^[+-]\d+$/.test(operand))
|
|
697
|
+
added = [["?"]];
|
|
698
|
+
else
|
|
699
|
+
added = this.cwds.map((cwd) => resolvePath(operand, cwd));
|
|
700
|
+
const next = [...this.cwds];
|
|
701
|
+
for (const path of added)
|
|
702
|
+
if (!next.some((known) => known.join("/") === path.join("/")))
|
|
703
|
+
next.push(path);
|
|
704
|
+
// Past a handful of possibilities, an unknown directory stands for the rest.
|
|
705
|
+
this.cwds = next.length > MAX_CWDS ? [...next.slice(0, MAX_CWDS), ["?"]] : next;
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* Unwraps wrappers (sudo, env, xargs, find -exec, sh -c, ...) and applies
|
|
709
|
+
* the per-program rules. Returns the program names involved, the final
|
|
710
|
+
* runner, and whether the command is text-only.
|
|
711
|
+
*/
|
|
712
|
+
argv(input, depth, command, raws) {
|
|
713
|
+
const names = new Set();
|
|
714
|
+
let argv = [...input];
|
|
715
|
+
let textOnly = true;
|
|
716
|
+
let afterWrapper = false;
|
|
717
|
+
for (let guard = 0; guard < 32; guard += 1) {
|
|
718
|
+
// Leading assignments: FOO=bar cmd
|
|
719
|
+
while (argv.length && isAssignment(argv[0])) {
|
|
720
|
+
if (this.assignment(argv[0], depth))
|
|
721
|
+
textOnly = false;
|
|
722
|
+
argv = argv.slice(1);
|
|
723
|
+
}
|
|
724
|
+
if (!argv.length)
|
|
725
|
+
return { names, textOnly };
|
|
726
|
+
const index = input.length - argv.length;
|
|
727
|
+
const raw = raws?.[index];
|
|
728
|
+
if (raw !== undefined && !plainCommandWord(raw))
|
|
729
|
+
this.add("shell.unresolved-command-name");
|
|
730
|
+
// A wrapper whose options were misread would leave an option value here.
|
|
731
|
+
if (afterWrapper && /^(?:-|\d+$)/.test(argv[0]))
|
|
732
|
+
this.add("shell.unresolved-command-name");
|
|
733
|
+
const name = basename(argv[0]);
|
|
734
|
+
if (NON_COMMAND_KEYWORDS.has(name))
|
|
735
|
+
return { names, textOnly };
|
|
736
|
+
if (name === "coproc") {
|
|
737
|
+
// coproc [NAME] COMMAND: NAME is only present before a compound command.
|
|
738
|
+
argv = argv.length > 2 && COMPOUND_STARTS.has(argv[2]) ? argv.slice(2) : argv.slice(1);
|
|
739
|
+
textOnly = false;
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
742
|
+
if (name === "function") {
|
|
743
|
+
// `function NAME { body; }`: the body follows as its own commands.
|
|
744
|
+
argv = argv.slice(2);
|
|
745
|
+
textOnly = false;
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
if (SHELL_KEYWORDS.has(name)) {
|
|
749
|
+
argv = argv.slice(1);
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
names.add(name);
|
|
753
|
+
const args = argv.slice(1);
|
|
754
|
+
// The effective argv is always a suffix of the input, so positions map back to words.
|
|
755
|
+
const offset = input.length - args.length;
|
|
756
|
+
if (SHELLS.has(name)) {
|
|
757
|
+
const info = this.shell(args, depth, command);
|
|
758
|
+
return {
|
|
759
|
+
names,
|
|
760
|
+
runner: name,
|
|
761
|
+
textOnly: false,
|
|
762
|
+
scriptWords: info.scriptIndex === undefined ? [] : [offset + info.scriptIndex],
|
|
763
|
+
readsStdin: info.readsStdin,
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
if (name === "source" || name === ".") {
|
|
767
|
+
return { names, runner: name, textOnly: false, scriptWords: args.length ? [offset] : [], readsStdin: false };
|
|
768
|
+
}
|
|
769
|
+
if (name === "eval") {
|
|
770
|
+
this.nestedScript(args.join(" "), depth + 1, true);
|
|
771
|
+
return { names, runner: name, textOnly: false, scriptWords: args.map((_, i) => offset + i), readsStdin: false };
|
|
772
|
+
}
|
|
773
|
+
this.currentRawArgs = raws?.slice(offset);
|
|
774
|
+
const unwrapped = this.unwrap(name, args, depth);
|
|
775
|
+
if (unwrapped === "stop")
|
|
776
|
+
return { names, runner: name, textOnly: false };
|
|
777
|
+
if (unwrapped) {
|
|
778
|
+
if (!TRANSPARENT_WRAPPERS.has(name))
|
|
779
|
+
textOnly = false;
|
|
780
|
+
argv = unwrapped;
|
|
781
|
+
afterWrapper = true;
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
this.currentRawArgs = raws?.slice(offset);
|
|
785
|
+
this.programRules(name, args, depth);
|
|
786
|
+
if (!this.isTextOnly(name, args))
|
|
787
|
+
textOnly = false;
|
|
788
|
+
return { names, runner: name, runnerIndex: index, textOnly };
|
|
789
|
+
}
|
|
790
|
+
this.add("shell.excessive-nesting");
|
|
791
|
+
return { names, textOnly: false };
|
|
792
|
+
}
|
|
793
|
+
/** Records an assignment; returns true when it carries a command. */
|
|
794
|
+
assignment(word, depth) {
|
|
795
|
+
const eq = word.indexOf("=");
|
|
796
|
+
const name = word.slice(0, eq).replace(/\+$/, "");
|
|
797
|
+
const value = word.slice(eq + 1);
|
|
798
|
+
if (GIT_CONFIG_ENV.test(name)) {
|
|
799
|
+
this.add("shell.program-launcher-option");
|
|
800
|
+
return true;
|
|
801
|
+
}
|
|
802
|
+
if (COMMAND_ENV_VARS.has(name)) {
|
|
803
|
+
this.nestedScript(value, depth + 1);
|
|
804
|
+
// A pager runs whenever output is paged; like `git -c core.pager`, only plain pagers are allowed.
|
|
805
|
+
if (PAGER_ENV_VARS.has(name) && !pagerIsPlain(value))
|
|
806
|
+
this.add("shell.program-launcher-option");
|
|
807
|
+
return true;
|
|
808
|
+
}
|
|
809
|
+
return false;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* For wrappers, returns the wrapped argv to keep checking. Returns "stop"
|
|
813
|
+
* when the wrapper's payload was handed off as a nested script. Returns
|
|
814
|
+
* undefined for ordinary programs.
|
|
815
|
+
*/
|
|
816
|
+
unwrap(name, args, depth) {
|
|
817
|
+
switch (name) {
|
|
818
|
+
case "sudo":
|
|
819
|
+
case "doas":
|
|
820
|
+
return skipOptions(args, new Set([
|
|
821
|
+
"-u", "-g", "-C", "-h", "-p", "-r", "-t", "-T", "-U", "-D", "-R", "--user", "--group", "--host", "--prompt",
|
|
822
|
+
"--role", "--type", "--close-from", "--chdir", "--chroot", "--login-class", "--other-user", "--command-timeout",
|
|
823
|
+
]));
|
|
824
|
+
case "time":
|
|
825
|
+
return skipOptions(args, new Set(["-f", "--format", "-o", "--output"]));
|
|
826
|
+
case "setsid":
|
|
827
|
+
return skipOptions(args, new Set());
|
|
828
|
+
case "strace": {
|
|
829
|
+
// strace writes to a pipe when the -o value starts with | or !.
|
|
830
|
+
args.forEach((arg, i) => {
|
|
831
|
+
const value = arg === "-o" ? args[i + 1] : longValue(arg, "--output", args, i) ?? (/^-o./.test(arg) ? arg.slice(2) : undefined);
|
|
832
|
+
if (value !== undefined && /^[|!]/.test(value))
|
|
833
|
+
this.nestedScript(value.slice(1), depth + 1);
|
|
834
|
+
});
|
|
835
|
+
return skipOptions(args, STRACE_VALUE_OPTIONS);
|
|
836
|
+
}
|
|
837
|
+
case "ltrace":
|
|
838
|
+
return skipOptions(args, LTRACE_VALUE_OPTIONS);
|
|
839
|
+
case "flock": {
|
|
840
|
+
// flock [options] FILE COMMAND... | flock [options] FILE -c COMMAND | flock [options] FD
|
|
841
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
842
|
+
const arg = args[i];
|
|
843
|
+
const command = arg === "-c" ? args[i + 1] : longValue(arg, "--command", args, i);
|
|
844
|
+
if (command !== undefined) {
|
|
845
|
+
this.nestedScript(command, depth + 1);
|
|
846
|
+
return "stop";
|
|
847
|
+
}
|
|
848
|
+
if (["-w", "--wait", "--timeout", "-E", "--conflict-exit-code"].includes(arg)) {
|
|
849
|
+
i += 1;
|
|
850
|
+
continue;
|
|
851
|
+
}
|
|
852
|
+
if (arg.startsWith("-"))
|
|
853
|
+
continue;
|
|
854
|
+
const rest = args.slice(i + 1);
|
|
855
|
+
// -c only counts directly after the lock file; anything later belongs to the command.
|
|
856
|
+
const first = rest[0];
|
|
857
|
+
if (first === "-c" || first === "--command" || first?.startsWith("--command=")) {
|
|
858
|
+
const value = first.startsWith("--command=") ? first.slice(10) : rest[1];
|
|
859
|
+
if (value !== undefined)
|
|
860
|
+
this.nestedScript(value, depth + 1);
|
|
861
|
+
return "stop";
|
|
862
|
+
}
|
|
863
|
+
return rest;
|
|
864
|
+
}
|
|
865
|
+
return "stop";
|
|
866
|
+
}
|
|
867
|
+
case "env": {
|
|
868
|
+
const rest = [];
|
|
869
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
870
|
+
const arg = args[i];
|
|
871
|
+
if (arg === "-S" || arg === "--split-string") {
|
|
872
|
+
this.nestedScript(args.slice(i + 1).join(" "), depth + 1);
|
|
873
|
+
return "stop";
|
|
874
|
+
}
|
|
875
|
+
if (arg.startsWith("-S") && arg.length > 2) {
|
|
876
|
+
this.nestedScript([arg.slice(2), ...args.slice(i + 1)].join(" "), depth + 1);
|
|
877
|
+
return "stop";
|
|
878
|
+
}
|
|
879
|
+
if (arg.startsWith("--split-string=")) {
|
|
880
|
+
this.nestedScript([arg.slice(15), ...args.slice(i + 1)].join(" "), depth + 1);
|
|
881
|
+
return "stop";
|
|
882
|
+
}
|
|
883
|
+
if (["-u", "--unset", "-C", "--chdir", "-P"].includes(arg)) {
|
|
884
|
+
i += 1;
|
|
885
|
+
continue;
|
|
886
|
+
}
|
|
887
|
+
if (arg.startsWith("-") && rest.length === 0)
|
|
888
|
+
continue;
|
|
889
|
+
rest.push(...args.slice(i));
|
|
890
|
+
break;
|
|
891
|
+
}
|
|
892
|
+
return rest;
|
|
893
|
+
}
|
|
894
|
+
case "command":
|
|
895
|
+
case "builtin":
|
|
896
|
+
if (args[0] === "-v" || args[0] === "-V")
|
|
897
|
+
return [];
|
|
898
|
+
return skipOptions(args, new Set());
|
|
899
|
+
case "exec":
|
|
900
|
+
return skipOptions(args, new Set(["-a"]));
|
|
901
|
+
case "nohup":
|
|
902
|
+
case "unbuffer":
|
|
903
|
+
case "busybox":
|
|
904
|
+
return args;
|
|
905
|
+
case "nice":
|
|
906
|
+
return skipOptions(args, new Set(["-n", "--adjustment"]));
|
|
907
|
+
case "ionice":
|
|
908
|
+
return skipOptions(args, new Set(["-c", "-n", "-p", "-P", "-u", "--class", "--classdata"]));
|
|
909
|
+
case "stdbuf":
|
|
910
|
+
return skipOptions(args, new Set(["-i", "-o", "-e", "--input", "--output", "--error"]));
|
|
911
|
+
case "chrt":
|
|
912
|
+
case "taskset":
|
|
913
|
+
return skipOptions(args, new Set()).slice(1);
|
|
914
|
+
case "timeout": {
|
|
915
|
+
const rest = skipOptions(args, new Set(["-s", "--signal", "-k", "--kill-after"]));
|
|
916
|
+
return rest.slice(1);
|
|
917
|
+
}
|
|
918
|
+
case "xargs":
|
|
919
|
+
return skipOptions(args, new Set(["-a", "--arg-file", "-d", "--delimiter", "-E", "-e", "-I", "-i", "-L", "-l", "-n", "--max-args", "-P", "--max-procs", "-s", "--max-chars"]));
|
|
920
|
+
case "watch": {
|
|
921
|
+
const rest = skipOptions(args, new Set(["-n", "--interval", "-d", "--differences", "-q", "--equexit"]));
|
|
922
|
+
this.nestedScript(rest.join(" "), depth + 1);
|
|
923
|
+
return "stop";
|
|
924
|
+
}
|
|
925
|
+
case "su":
|
|
926
|
+
case "runuser":
|
|
927
|
+
return this.switchUser(name, args, depth);
|
|
928
|
+
case "find": {
|
|
929
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
930
|
+
if (["-exec", "-execdir", "-ok", "-okdir"].includes(args[i])) {
|
|
931
|
+
const end = args.findIndex((arg, j) => j > i && (arg === ";" || arg === "+"));
|
|
932
|
+
const inner = args.slice(i + 1, end === -1 ? undefined : end);
|
|
933
|
+
const rawArgs = this.currentRawArgs;
|
|
934
|
+
this.argv(inner, depth + 1, undefined, rawArgs?.slice(i + 1, end === -1 ? undefined : end));
|
|
935
|
+
this.allTextOnly = false;
|
|
936
|
+
i = end === -1 ? args.length : end;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
return undefined;
|
|
940
|
+
}
|
|
941
|
+
default:
|
|
942
|
+
return undefined;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
/** su / runuser: check -c, --command and --session-command, and runuser's direct `-u user cmd...` form. */
|
|
946
|
+
switchUser(name, args, depth) {
|
|
947
|
+
let direct = false;
|
|
948
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
949
|
+
const arg = args[i];
|
|
950
|
+
if (arg === "--")
|
|
951
|
+
return direct ? args.slice(i + 1) : "stop";
|
|
952
|
+
const command = longValue(arg, "--command", args, i) ??
|
|
953
|
+
longValue(arg, "--session-command", args, i) ??
|
|
954
|
+
(arg === "-c" ? args[i + 1] : arg.startsWith("-c") && arg.length > 2 ? arg.slice(2) : undefined);
|
|
955
|
+
if (command !== undefined) {
|
|
956
|
+
this.nestedScript(command, depth + 1);
|
|
957
|
+
if (arg === "-c" || arg === "--command" || arg === "--session-command")
|
|
958
|
+
i += 1;
|
|
959
|
+
continue;
|
|
960
|
+
}
|
|
961
|
+
if (name === "runuser" && (arg === "-u" || arg === "--user")) {
|
|
962
|
+
direct = true;
|
|
963
|
+
i += 1;
|
|
964
|
+
continue;
|
|
965
|
+
}
|
|
966
|
+
if (["-g", "--group", "-G", "--supp-group", "-s", "--shell", "-w", "--whitelist-environment"].includes(arg)) {
|
|
967
|
+
i += 1;
|
|
968
|
+
continue;
|
|
969
|
+
}
|
|
970
|
+
if (arg.startsWith("-"))
|
|
971
|
+
continue;
|
|
972
|
+
// runuser -u USER COMMAND...: the rest is the command to run.
|
|
973
|
+
if (direct)
|
|
974
|
+
return args.slice(i);
|
|
975
|
+
}
|
|
976
|
+
return "stop";
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* Works out where a shell gets its program from: a -c string, a script
|
|
980
|
+
* file, or standard input. Checks the -c string, and standard input
|
|
981
|
+
* (heredoc or here-string) only when the shell reads its program from it.
|
|
982
|
+
*/
|
|
983
|
+
shell(args, depth, command) {
|
|
984
|
+
let wantsScript = false;
|
|
985
|
+
let fromStdin = false;
|
|
986
|
+
let scriptIndex;
|
|
987
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
988
|
+
const arg = args[i];
|
|
989
|
+
if (arg === "--") {
|
|
990
|
+
if ((wantsScript || !fromStdin) && i + 1 < args.length)
|
|
991
|
+
scriptIndex = i + 1;
|
|
992
|
+
break;
|
|
993
|
+
}
|
|
994
|
+
if (["-o", "+o", "--rcfile", "--init-file", "-O", "+O"].includes(arg)) {
|
|
995
|
+
i += 1;
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
if (/^[-+][A-Za-z]+$/.test(arg)) {
|
|
999
|
+
if (arg.startsWith("-") && arg.includes("c"))
|
|
1000
|
+
wantsScript = true;
|
|
1001
|
+
if (arg.startsWith("-") && arg.includes("s"))
|
|
1002
|
+
fromStdin = true;
|
|
1003
|
+
continue;
|
|
1004
|
+
}
|
|
1005
|
+
if (arg.startsWith("--"))
|
|
1006
|
+
continue;
|
|
1007
|
+
// With -c the first operand is the program, even when -s is also given.
|
|
1008
|
+
if (wantsScript || !fromStdin)
|
|
1009
|
+
scriptIndex = i;
|
|
1010
|
+
break;
|
|
1011
|
+
}
|
|
1012
|
+
if (wantsScript && scriptIndex !== undefined) {
|
|
1013
|
+
this.nestedScript(args[scriptIndex], depth + 1);
|
|
1014
|
+
return { scriptIndex, readsStdin: false };
|
|
1015
|
+
}
|
|
1016
|
+
if (scriptIndex !== undefined && !wantsScript)
|
|
1017
|
+
return { scriptIndex, readsStdin: false };
|
|
1018
|
+
for (const redirect of command?.redirects ?? []) {
|
|
1019
|
+
if (redirect.heredoc)
|
|
1020
|
+
this.nestedScript(redirect.heredoc.body, depth + 1);
|
|
1021
|
+
if (redirect.op === "<<<" && redirect.target)
|
|
1022
|
+
this.nestedScript(redirect.target.value, depth + 1);
|
|
1023
|
+
}
|
|
1024
|
+
return { readsStdin: true };
|
|
1025
|
+
}
|
|
1026
|
+
isTextOnly(name, args) {
|
|
1027
|
+
if (name === "git") {
|
|
1028
|
+
const parsed = parseGit(args);
|
|
1029
|
+
return parsed.launcher === false && TEXT_ONLY_GIT.has(parsed.subcommand ?? "");
|
|
1030
|
+
}
|
|
1031
|
+
return TEXT_ONLY.has(name);
|
|
1032
|
+
}
|
|
1033
|
+
programRules(name, args, depth) {
|
|
1034
|
+
const { options, operands } = splitOptions(args);
|
|
1035
|
+
const has = (...values) => options.some((option) => values.includes(option));
|
|
1036
|
+
switch (name) {
|
|
1037
|
+
case "rm": {
|
|
1038
|
+
const recursive = has("--recursive") || shortCluster(options, "r") || shortCluster(options, "R");
|
|
1039
|
+
const forced = has("--force") || shortCluster(options, "f");
|
|
1040
|
+
if (recursive && forced) {
|
|
1041
|
+
this.add(rmTargetsAreCritical(operands) ? "filesystem.rm-critical-target" : "filesystem.rm-recursive-force");
|
|
1042
|
+
}
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
case "dd":
|
|
1046
|
+
if (args.some((arg) => /^of=\/dev\//i.test(arg) && !SAFE_DEVICE.test(arg.slice(3)))) {
|
|
1047
|
+
this.add("storage.raw-device-write");
|
|
1048
|
+
}
|
|
1049
|
+
for (const arg of args)
|
|
1050
|
+
if (/^of=/i.test(arg))
|
|
1051
|
+
this.writeTarget(arg.slice(3));
|
|
1052
|
+
return;
|
|
1053
|
+
case "tee":
|
|
1054
|
+
for (const operand of operands)
|
|
1055
|
+
this.writeTarget(operand);
|
|
1056
|
+
return;
|
|
1057
|
+
case "cp":
|
|
1058
|
+
case "mv":
|
|
1059
|
+
case "install":
|
|
1060
|
+
case "ln": {
|
|
1061
|
+
const { destinations, sources, parents } = copyOperands(name, args);
|
|
1062
|
+
for (const destination of destinations) {
|
|
1063
|
+
this.writeTarget(destination);
|
|
1064
|
+
// The destination may be a directory: each source then lands inside it under its own
|
|
1065
|
+
// name, or under its whole path with `cp --parents`.
|
|
1066
|
+
for (const source of sources) {
|
|
1067
|
+
const kept = parents ? source.replace(/^\/+/, "") : source.split("/").filter(Boolean).pop() ?? "";
|
|
1068
|
+
this.writeTarget(`${destination}/${kept}`);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
// A link to a sensitive file lets a later write reach it.
|
|
1072
|
+
if (name === "ln")
|
|
1073
|
+
for (const source of sources)
|
|
1074
|
+
this.writeTarget(source);
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
case "cd":
|
|
1078
|
+
case "pushd":
|
|
1079
|
+
case "popd":
|
|
1080
|
+
this.changeDirectory(name, args);
|
|
1081
|
+
return;
|
|
1082
|
+
case "wipefs":
|
|
1083
|
+
this.add("storage.raw-device-write");
|
|
1084
|
+
return;
|
|
1085
|
+
case "diskutil":
|
|
1086
|
+
if (args.some((arg) => /^(?:erasedisk|zerodisk|secureerase)$/i.test(arg)))
|
|
1087
|
+
this.add("storage.raw-device-write");
|
|
1088
|
+
return;
|
|
1089
|
+
case "kill": {
|
|
1090
|
+
const killSignal = has("-9", "-KILL", "-SIGKILL", "-s9") ||
|
|
1091
|
+
args.some((arg, i) => ["-s", "--signal", "-n"].includes(arg) && /^(?:9|KILL|SIGKILL)$/i.test(args[i + 1] ?? ""));
|
|
1092
|
+
if (killSignal && args.includes("-1"))
|
|
1093
|
+
this.add("process.mass-kill");
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
case "pkill":
|
|
1097
|
+
case "killall":
|
|
1098
|
+
if (has("-9", "-KILL", "-SIGKILL") && operands.some((arg) => arg.includes(".*")))
|
|
1099
|
+
this.add("process.mass-kill");
|
|
1100
|
+
return;
|
|
1101
|
+
case "git":
|
|
1102
|
+
this.git(args, depth);
|
|
1103
|
+
return;
|
|
1104
|
+
case "terraform":
|
|
1105
|
+
case "tofu":
|
|
1106
|
+
case "pulumi": {
|
|
1107
|
+
const sub = operands.find((arg) => !arg.startsWith("-"));
|
|
1108
|
+
if (sub === "destroy" || (name === "pulumi" && sub === "down") || (sub === "apply" && has("-destroy", "--destroy"))) {
|
|
1109
|
+
this.add("infrastructure.destroy");
|
|
1110
|
+
}
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
case "kubectl": {
|
|
1114
|
+
const at = operands.indexOf("delete");
|
|
1115
|
+
const kind = at === -1 ? undefined : operands[at + 1];
|
|
1116
|
+
if (kind && /^(?:namespace|namespaces|ns)(?:\/|$)/i.test(kind))
|
|
1117
|
+
this.add("infrastructure.destroy");
|
|
1118
|
+
return;
|
|
1119
|
+
}
|
|
1120
|
+
case "docker":
|
|
1121
|
+
case "docker-compose":
|
|
1122
|
+
case "podman": {
|
|
1123
|
+
const pairs = operands.map((arg, i) => `${arg} ${operands[i + 1] ?? ""}`);
|
|
1124
|
+
if (pairs.includes("system prune") || pairs.includes("volume prune"))
|
|
1125
|
+
this.add("infrastructure.destroy");
|
|
1126
|
+
const composeDown = (name === "docker-compose" || operands.includes("compose")) && operands.includes("down");
|
|
1127
|
+
if (composeDown && (has("--volumes") || shortCluster(options, "v") || options.some((o) => o.startsWith("--volumes=")))) {
|
|
1128
|
+
this.add("infrastructure.destroy");
|
|
1129
|
+
}
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
case "aws":
|
|
1133
|
+
if (operands.includes("s3") && operands.includes("rm") && has("--recursive"))
|
|
1134
|
+
this.add("cloud.bulk-delete");
|
|
1135
|
+
return;
|
|
1136
|
+
case "gsutil": {
|
|
1137
|
+
const at = args.indexOf("rm");
|
|
1138
|
+
if (at !== -1 && args.slice(at + 1).some((arg) => /^-[A-Za-z]*[rR]/.test(arg)))
|
|
1139
|
+
this.add("cloud.bulk-delete");
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
case "gcloud":
|
|
1143
|
+
case "az": {
|
|
1144
|
+
const pairs = operands.map((arg, i) => `${arg} ${operands[i + 1] ?? ""}`);
|
|
1145
|
+
if (pairs.includes("projects delete") || pairs.includes("group delete"))
|
|
1146
|
+
this.add("cloud.bulk-delete");
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
case "dropdb":
|
|
1150
|
+
this.add("database.destructive-ddl");
|
|
1151
|
+
return;
|
|
1152
|
+
case "redis-cli":
|
|
1153
|
+
if (args.some((arg) => /^(?:flushall|flushdb)$/i.test(arg)))
|
|
1154
|
+
this.add("database.destructive-ddl");
|
|
1155
|
+
return;
|
|
1156
|
+
case "rg":
|
|
1157
|
+
if (optionsOutsideValues(args, RG_VALUE_OPTIONS).some((option) => option === "--pre" || option.startsWith("--pre="))) {
|
|
1158
|
+
this.add("shell.program-launcher-option");
|
|
1159
|
+
}
|
|
1160
|
+
return;
|
|
1161
|
+
case "ag":
|
|
1162
|
+
case "ack":
|
|
1163
|
+
if (options.some((option) => /^--(?:pager|output)(?:=|$)/.test(option)))
|
|
1164
|
+
this.add("shell.program-launcher-option");
|
|
1165
|
+
return;
|
|
1166
|
+
case "sort":
|
|
1167
|
+
args.forEach((arg, i) => {
|
|
1168
|
+
const value = longValue(arg, "--compress-program", args, i);
|
|
1169
|
+
if (value !== undefined && !compressorIsPlain(value))
|
|
1170
|
+
this.add("shell.program-launcher-option");
|
|
1171
|
+
});
|
|
1172
|
+
return;
|
|
1173
|
+
case "tar":
|
|
1174
|
+
case "gtar":
|
|
1175
|
+
case "bsdtar":
|
|
1176
|
+
args.forEach((arg, i) => {
|
|
1177
|
+
if (/^--(?:to-command|info-script|new-volume-script|rsh-command)(?:=|$)/.test(arg) || arg === "-F") {
|
|
1178
|
+
this.add("shell.program-launcher-option");
|
|
1179
|
+
}
|
|
1180
|
+
if (/^--checkpoint-action=.*exec/.test(arg))
|
|
1181
|
+
this.add("shell.program-launcher-option");
|
|
1182
|
+
const value = arg === "-I" ? args[i + 1] : longValue(arg, "--use-compress-program", args, i);
|
|
1183
|
+
if (value !== undefined && !compressorIsPlain(value))
|
|
1184
|
+
this.add("shell.program-launcher-option");
|
|
1185
|
+
});
|
|
1186
|
+
return;
|
|
1187
|
+
default:
|
|
1188
|
+
if (/^mkfs(?:\..+)?$/.test(name))
|
|
1189
|
+
this.add("storage.raw-device-write");
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
git(args, depth) {
|
|
1193
|
+
const parsed = parseGit(args);
|
|
1194
|
+
if (parsed.launcher)
|
|
1195
|
+
this.add("shell.program-launcher-option");
|
|
1196
|
+
// Check pager and editor commands given with -c, so their own rules apply too.
|
|
1197
|
+
for (const value of parsed.configCommands)
|
|
1198
|
+
this.nestedScript(value, depth + 1);
|
|
1199
|
+
const sub = parsed.subcommand;
|
|
1200
|
+
const rest = parsed.rest;
|
|
1201
|
+
const { options, operands } = splitOptions(rest);
|
|
1202
|
+
const has = (...values) => options.some((option) => values.includes(option));
|
|
1203
|
+
switch (sub) {
|
|
1204
|
+
case "reset":
|
|
1205
|
+
if (has("--hard"))
|
|
1206
|
+
this.add("git.discard-worktree");
|
|
1207
|
+
break;
|
|
1208
|
+
case "clean":
|
|
1209
|
+
if (has("--force") || shortCluster(options, "f"))
|
|
1210
|
+
this.add("git.discard-worktree");
|
|
1211
|
+
break;
|
|
1212
|
+
case "checkout":
|
|
1213
|
+
if (rest[0] === "--")
|
|
1214
|
+
this.add("git.discard-worktree");
|
|
1215
|
+
break;
|
|
1216
|
+
case "restore":
|
|
1217
|
+
this.add("git.discard-worktree");
|
|
1218
|
+
break;
|
|
1219
|
+
case "branch":
|
|
1220
|
+
if (shortCluster(options, "D") ||
|
|
1221
|
+
((has("--delete") || shortCluster(options, "d")) && (has("--force") || shortCluster(options, "f")))) {
|
|
1222
|
+
this.add("git.discard-worktree");
|
|
1223
|
+
}
|
|
1224
|
+
break;
|
|
1225
|
+
case "stash":
|
|
1226
|
+
if (operands[0] === "clear" || operands[0] === "drop")
|
|
1227
|
+
this.add("git.discard-worktree");
|
|
1228
|
+
break;
|
|
1229
|
+
case "push":
|
|
1230
|
+
if (has("--force") ||
|
|
1231
|
+
options.some((option) => option.startsWith("--force=")) ||
|
|
1232
|
+
shortCluster(options, "f") ||
|
|
1233
|
+
operands.some((operand) => operand.startsWith("+"))) {
|
|
1234
|
+
this.add("git.rewrite-remote");
|
|
1235
|
+
}
|
|
1236
|
+
if (options.some((option) => /^--(?:receive-pack|exec)(?:=|$)/.test(option))) {
|
|
1237
|
+
this.add("shell.program-launcher-option");
|
|
1238
|
+
}
|
|
1239
|
+
break;
|
|
1240
|
+
case "fetch":
|
|
1241
|
+
case "pull":
|
|
1242
|
+
case "ls-remote":
|
|
1243
|
+
case "archive":
|
|
1244
|
+
case "clone":
|
|
1245
|
+
if (options.some((option) => /^--(?:upload-pack|exec)(?:=|$)/.test(option)) || (sub === "clone" && has("-u"))) {
|
|
1246
|
+
this.add("shell.program-launcher-option");
|
|
1247
|
+
}
|
|
1248
|
+
break;
|
|
1249
|
+
case "grep":
|
|
1250
|
+
if (optionsOutsideValues(rest, GIT_GREP_VALUE_OPTIONS).some((option) => /^(?:-O.*|--open-files-in-pager(?:=.*)?)$/.test(option))) {
|
|
1251
|
+
this.add("shell.program-launcher-option");
|
|
1252
|
+
}
|
|
1253
|
+
break;
|
|
1254
|
+
case "config": {
|
|
1255
|
+
const positional = operandsAfterValues(rest, GIT_CONFIG_VALUE_OPTIONS).filter((operand) => !["set", "add", "replace-all"].includes(operand));
|
|
1256
|
+
const unsetting = options.some((option) => /^--(?:unset|unset-all|get|get-all|get-regexp|list|remove-section)/.test(option));
|
|
1257
|
+
const key = positional[0]?.toLowerCase() ?? "";
|
|
1258
|
+
const value = positional[1] ?? "";
|
|
1259
|
+
if (!unsetting &&
|
|
1260
|
+
positional.length >= 2 &&
|
|
1261
|
+
(GIT_EXEC_CONFIG_KEY.test(key) || (/^submodule\..+\.update$/.test(key) && value.startsWith("!")))) {
|
|
1262
|
+
this.add("shell.program-launcher-option");
|
|
1263
|
+
}
|
|
1264
|
+
break;
|
|
1265
|
+
}
|
|
1266
|
+
case "rebase":
|
|
1267
|
+
rest.forEach((arg, i) => {
|
|
1268
|
+
const value = arg === "-x" ? rest[i + 1] : /^-x./.test(arg) ? arg.slice(2) : longValue(arg, "--exec", rest, i);
|
|
1269
|
+
if (value !== undefined)
|
|
1270
|
+
this.nestedScript(value, depth + 1);
|
|
1271
|
+
});
|
|
1272
|
+
break;
|
|
1273
|
+
case "difftool":
|
|
1274
|
+
rest.forEach((arg, i) => {
|
|
1275
|
+
const value = arg === "-x" ? rest[i + 1] : /^-x./.test(arg) ? arg.slice(2) : longValue(arg, "--extcmd", rest, i);
|
|
1276
|
+
if (value !== undefined)
|
|
1277
|
+
this.nestedScript(value, depth + 1);
|
|
1278
|
+
});
|
|
1279
|
+
break;
|
|
1280
|
+
case "submodule": {
|
|
1281
|
+
const at = rest.indexOf("foreach");
|
|
1282
|
+
if (at !== -1) {
|
|
1283
|
+
const command = skipOptions(rest.slice(at + 1), new Set());
|
|
1284
|
+
this.nestedScript(command.join(" "), depth + 1);
|
|
1285
|
+
}
|
|
1286
|
+
break;
|
|
1287
|
+
}
|
|
1288
|
+
case "bisect":
|
|
1289
|
+
if (rest[0] === "run")
|
|
1290
|
+
this.argv(rest.slice(1), depth + 1);
|
|
1291
|
+
break;
|
|
1292
|
+
case "filter-branch":
|
|
1293
|
+
this.add("shell.program-launcher-option");
|
|
1294
|
+
break;
|
|
1295
|
+
default:
|
|
1296
|
+
break;
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
const GIT_CONFIG_VALUE_OPTIONS = new Set(["-f", "--file", "--blob", "--type", "-t", "--default", "--comment", "--value"]);
|
|
1301
|
+
/** Operands of a command, skipping the values of value-taking options. */
|
|
1302
|
+
function operandsAfterValues(args, takesValue) {
|
|
1303
|
+
const operands = [];
|
|
1304
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
1305
|
+
const arg = args[i];
|
|
1306
|
+
if (arg === "--") {
|
|
1307
|
+
operands.push(...args.slice(i + 1));
|
|
1308
|
+
break;
|
|
1309
|
+
}
|
|
1310
|
+
if (arg.startsWith("-") && arg !== "-") {
|
|
1311
|
+
if (takesValue.has(arg))
|
|
1312
|
+
i += 1;
|
|
1313
|
+
continue;
|
|
1314
|
+
}
|
|
1315
|
+
operands.push(arg);
|
|
1316
|
+
}
|
|
1317
|
+
return operands;
|
|
1318
|
+
}
|
|
1319
|
+
function parseFailureRule(error) {
|
|
1320
|
+
return error instanceof ShellParseError && /nesting/.test(error.message) ? "shell.excessive-nesting" : "shell.unparsed-command";
|
|
1321
|
+
}
|
|
1322
|
+
function skipOptions(args, takesValue) {
|
|
1323
|
+
let i = 0;
|
|
1324
|
+
while (i < args.length) {
|
|
1325
|
+
const arg = args[i];
|
|
1326
|
+
if (arg === "--")
|
|
1327
|
+
return args.slice(i + 1);
|
|
1328
|
+
if (!arg.startsWith("-") || arg === "-")
|
|
1329
|
+
break;
|
|
1330
|
+
i += takesValue.has(arg) ? 2 : 1;
|
|
1331
|
+
}
|
|
1332
|
+
return args.slice(i);
|
|
1333
|
+
}
|
|
1334
|
+
/** Splits `git [global options] <subcommand> [args]` and flags global options that run programs. */
|
|
1335
|
+
function parseGit(args) {
|
|
1336
|
+
let launcher = false;
|
|
1337
|
+
const configCommands = [];
|
|
1338
|
+
const config = (pair) => {
|
|
1339
|
+
if (!gitConfigPairIsSafe(pair))
|
|
1340
|
+
launcher = true;
|
|
1341
|
+
const eq = pair.indexOf("=");
|
|
1342
|
+
if (eq !== -1 && /^(?:core\.(?:pager|editor)|pager\..+|sequence\.editor)$/i.test(pair.slice(0, eq))) {
|
|
1343
|
+
configCommands.push(pair.slice(eq + 1));
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
let i = 0;
|
|
1347
|
+
while (i < args.length) {
|
|
1348
|
+
const arg = args[i];
|
|
1349
|
+
if (arg === "-c") {
|
|
1350
|
+
config(args[i + 1] ?? "");
|
|
1351
|
+
i += 2;
|
|
1352
|
+
}
|
|
1353
|
+
else if (arg.startsWith("-c") && arg.length > 2) {
|
|
1354
|
+
config(arg.slice(2));
|
|
1355
|
+
i += 1;
|
|
1356
|
+
}
|
|
1357
|
+
else if (arg === "--config-env" || arg.startsWith("--config-env=")) {
|
|
1358
|
+
launcher = true;
|
|
1359
|
+
i += arg === "--config-env" ? 2 : 1;
|
|
1360
|
+
}
|
|
1361
|
+
else if (arg.startsWith("--exec-path=")) {
|
|
1362
|
+
launcher = true;
|
|
1363
|
+
i += 1;
|
|
1364
|
+
}
|
|
1365
|
+
else if (["-C", "--git-dir", "--work-tree", "--namespace", "--super-prefix"].includes(arg)) {
|
|
1366
|
+
i += 2;
|
|
1367
|
+
}
|
|
1368
|
+
else if (arg.startsWith("-")) {
|
|
1369
|
+
i += 1;
|
|
1370
|
+
}
|
|
1371
|
+
else {
|
|
1372
|
+
break;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
return { subcommand: args[i]?.toLowerCase(), rest: args.slice(i + 1), launcher, configCommands };
|
|
1376
|
+
}
|
|
1377
|
+
function gitConfigPairIsSafe(pair) {
|
|
1378
|
+
const eq = pair.indexOf("=");
|
|
1379
|
+
const key = (eq === -1 ? pair : pair.slice(0, eq)).toLowerCase();
|
|
1380
|
+
if (GIT_SAFE_CONFIG_KEY.test(key))
|
|
1381
|
+
return true;
|
|
1382
|
+
// A pager setting is safe when it names a plain pager (or turns paging on or off).
|
|
1383
|
+
if (eq !== -1 && (key === "core.pager" || /^pager\.[a-z0-9-]+$/.test(key)))
|
|
1384
|
+
return pagerIsPlain(pair.slice(eq + 1));
|
|
1385
|
+
return false;
|
|
1386
|
+
}
|
|
1387
|
+
/** Blanks out the given [start, end) spans, keeping newlines so line structure is preserved. */
|
|
1388
|
+
function maskSpans(text, spans) {
|
|
1389
|
+
const units = text.split("");
|
|
1390
|
+
for (const [start, end] of spans) {
|
|
1391
|
+
for (let i = Math.max(0, start); i < Math.min(units.length, end); i += 1) {
|
|
1392
|
+
if (units[i] !== "\n")
|
|
1393
|
+
units[i] = " ";
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
return units.join("");
|
|
1397
|
+
}
|
|
1398
|
+
function pickRule(findings) {
|
|
1399
|
+
const ordered = RULE_ORDER.filter((id) => findings.has(id));
|
|
1400
|
+
return ordered.find((id) => RULE_INFO[id].severity === "critical") ?? ordered[0];
|
|
1401
|
+
}
|
|
1402
|
+
/** Checks a raw command line and returns every rule it matches. */
|
|
1403
|
+
function findRules(command) {
|
|
1404
|
+
const analysis = new Analysis(command);
|
|
1405
|
+
let parsed = false;
|
|
1406
|
+
try {
|
|
1407
|
+
analysis.script(parseShell(command), 0, true);
|
|
1408
|
+
parsed = true;
|
|
1409
|
+
}
|
|
1410
|
+
catch (error) {
|
|
1411
|
+
// A line the guard cannot parse is not allowed: bash may still run the part before the error.
|
|
1412
|
+
analysis.add(parseFailureRule(error));
|
|
1413
|
+
}
|
|
1414
|
+
// Pattern rules always run. Plain-text arguments are hidden from them only
|
|
1415
|
+
// when the whole line parsed and every command in it is text-only.
|
|
1416
|
+
const visible = parsed && analysis.allTextOnly ? maskSpans(command, analysis.maskable) : command;
|
|
1417
|
+
for (const text of [visible, ...analysis.extraTexts].map(patternText)) {
|
|
1418
|
+
for (const rule of PATTERN_RULES)
|
|
1419
|
+
if (rule.matches(text))
|
|
1420
|
+
analysis.add(rule.id);
|
|
1421
|
+
}
|
|
1422
|
+
return analysis.findings;
|
|
1423
|
+
}
|
|
133
1424
|
export function shellCommandFromToolCall(toolName, input) {
|
|
134
1425
|
if (!SHELL_TOOL_NAMES.has(toolName.toLowerCase()))
|
|
135
1426
|
return undefined;
|
|
@@ -154,18 +1445,11 @@ export function classifyShellToolCall(toolName, input) {
|
|
|
154
1445
|
severity: "high",
|
|
155
1446
|
};
|
|
156
1447
|
}
|
|
157
|
-
const
|
|
158
|
-
if (
|
|
1448
|
+
const match = pickRule(findRules(raw.trim()));
|
|
1449
|
+
if (!match)
|
|
159
1450
|
return { decision: "allow" };
|
|
160
|
-
const
|
|
161
|
-
return match
|
|
162
|
-
? {
|
|
163
|
-
decision: "block",
|
|
164
|
-
rule_id: match.id,
|
|
165
|
-
reason: match.reason,
|
|
166
|
-
severity: match.severity,
|
|
167
|
-
}
|
|
168
|
-
: { decision: "allow" };
|
|
1451
|
+
const info = RULE_INFO[match];
|
|
1452
|
+
return { decision: "block", rule_id: match, reason: info.reason, severity: info.severity };
|
|
169
1453
|
}
|
|
170
1454
|
export function commandGuardBlockMessage(decision) {
|
|
171
1455
|
return `Blocked by Orchestra command guard [${decision.rule_id}]: ${decision.reason} Review and run this command manually if the destructive action is intentional.`;
|