dsh-remote-go 0.2.0 → 0.3.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.
- package/README.md +11 -3
- package/{client.js → dist/client.js} +7710 -8182
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/{src → dist/src}/constants.js +30 -56
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The building blocks every model-facing tool shares: the one redaction path a result crosses, the
|
|
3
|
+
* projection helpers, and the result/error vocabulary the kernel renders.
|
|
4
|
+
*
|
|
5
|
+
* The tools are separate modules (`tools.ts` owns the list and the reveal entry, `tools-report.ts`
|
|
6
|
+
* the diagnosis report, `tools-exec.ts` the remote command) but they must agree about two things:
|
|
7
|
+
* nothing leaves through a projection that skipped redaction, and a failure is always a structured
|
|
8
|
+
* result the model can report instead of a throw. Owning those here is what keeps a third tool from
|
|
9
|
+
* growing a second, quietly weaker copy.
|
|
10
|
+
*
|
|
11
|
+
* Everything in this module is pure: no transport, no timers, no disk.
|
|
12
|
+
*/
|
|
13
|
+
import { isRemoteGoError, toErrorView } from './errors.js';
|
|
14
|
+
import { redactText } from './redact.js';
|
|
15
|
+
import { messageOf } from './util.js';
|
|
16
|
+
/** Shape limits: one free-text field never carries more than this many characters. */
|
|
17
|
+
export const TEXT_LIMIT = 400;
|
|
18
|
+
export const ADDRESS_LIMIT = 200;
|
|
19
|
+
export const NAME_LIMIT = 120;
|
|
20
|
+
export const ID_LIMIT = 120;
|
|
21
|
+
/** A model-facing id or phase code is shorter than a sentence. */
|
|
22
|
+
export const CODE_LIMIT = 60;
|
|
23
|
+
export const ANSI_RE = /\u001B\[[0-9;]*[A-Za-z]/g;
|
|
24
|
+
export const CONTROL_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;
|
|
25
|
+
/**
|
|
26
|
+
* Host identifiers that must never leave a tool. `redactText` covers tokens, passwords,
|
|
27
|
+
* private-key blocks and home directories, but not these two — and a connect failure's `detail`
|
|
28
|
+
* carries them verbatim: `prompts.js` builds the first-use fingerprint prompt (120s timeout,
|
|
29
|
+
* `first-use` is the default policy) and `ssh.js` builds the host-key-changed one, while `auth`
|
|
30
|
+
* failures quote the configured key file.
|
|
31
|
+
*
|
|
32
|
+
* The fingerprint pattern is a flat quantifier, and key paths are found by scanning whitespace-
|
|
33
|
+
* separated tokens (see `isKeyPath`): a nested `(?:[^\s]*[\\/])?` path pattern backtracks
|
|
34
|
+
* quadratically on a long separator-free token, and `address` has no length limit upstream.
|
|
35
|
+
*/
|
|
36
|
+
const FINGERPRINT_RE = /\bSHA256:[A-Za-z0-9+/=]+/gi;
|
|
37
|
+
const TOKEN_RE = /[^\s"'`]+/g;
|
|
38
|
+
const PATH_SEPARATOR_RE = /[\\/]+/;
|
|
39
|
+
const KEY_FILE_SUFFIX_RE = /\.(?:pem|key|ppk)$/i;
|
|
40
|
+
/** `id_rsa`, `id_ed25519`, and the backup/copy spellings a failure line quotes (`id_rsa.bak`). */
|
|
41
|
+
const KEY_FILE_NAME_RE = /^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.[a-z0-9]+)?$/i;
|
|
42
|
+
/** OpenSSH host keys are private key files too, and their names carry no `.pem`/`.key` suffix. */
|
|
43
|
+
const HOST_KEY_NAME_RE = /^ssh_host_[a-z0-9]+_key(?:\.[a-z0-9]+)?$/i;
|
|
44
|
+
/** Sentence punctuation that ends on the path: `could not read D:\keys\prod.ppk: ENOENT`. */
|
|
45
|
+
const TRAILING_PUNCTUATION_RE = /[.,;:)\]}>"'…。,、)】»]+$/;
|
|
46
|
+
export const ERROR_SCHEMA = {
|
|
47
|
+
type: 'object',
|
|
48
|
+
properties: {
|
|
49
|
+
code: { type: 'string', description: 'Stable error code, e.g. INTERNAL or INVALID_INPUT.' },
|
|
50
|
+
message: { type: 'string', description: 'What failed, in Chinese and English, already redacted.' },
|
|
51
|
+
retryable: { type: 'boolean', description: 'Whether trying again can succeed.' },
|
|
52
|
+
hint: { type: 'string', description: 'One next step for the user.' },
|
|
53
|
+
},
|
|
54
|
+
required: ['code', 'message'],
|
|
55
|
+
additionalProperties: false,
|
|
56
|
+
};
|
|
57
|
+
export function truncate(text, limit) {
|
|
58
|
+
const points = Array.from(text);
|
|
59
|
+
if (points.length <= limit)
|
|
60
|
+
return text;
|
|
61
|
+
return `${points.slice(0, Math.max(0, limit - 1)).join('')}…`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Whether one token names a private-key location. `.ssh` must be a whole path segment, so a host
|
|
65
|
+
* name like `box.ssh.example.com` stays readable; a `.pem` / `.key` / `.ppk` file or an OpenSSH
|
|
66
|
+
* `id_*` key counts too, because those are the key files a failed connect quotes.
|
|
67
|
+
*/
|
|
68
|
+
function isKeyPath(token) {
|
|
69
|
+
// The trailing punctuation belongs to the sentence, not to the path: without this trim a message
|
|
70
|
+
// like `could not read D:\keys\prod.ppk: ENOENT` would keep its key path.
|
|
71
|
+
const lowered = token.replace(TRAILING_PUNCTUATION_RE, '').toLowerCase();
|
|
72
|
+
const segments = lowered.split(PATH_SEPARATOR_RE);
|
|
73
|
+
if (segments.includes('.ssh'))
|
|
74
|
+
return true;
|
|
75
|
+
if (KEY_FILE_SUFFIX_RE.test(lowered))
|
|
76
|
+
return true;
|
|
77
|
+
const name = segments[segments.length - 1] ?? '';
|
|
78
|
+
return KEY_FILE_NAME_RE.test(name) || HOST_KEY_NAME_RE.test(name);
|
|
79
|
+
}
|
|
80
|
+
/** Replace host identifiers: the whole `SHA256:<base64>` token (prefix included) and key paths. */
|
|
81
|
+
export function redactHostSecrets(text) {
|
|
82
|
+
return text
|
|
83
|
+
.replace(FINGERPRINT_RE, '<fingerprint redacted>')
|
|
84
|
+
.replace(TOKEN_RE, (token) => (isKeyPath(token) ? '<private-key path>' : token));
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Redact and shorten one free-text value. A value that is not a non-empty string is dropped, so a
|
|
88
|
+
* projected field is either a bounded redacted string or absent — never `undefined` in the result.
|
|
89
|
+
*
|
|
90
|
+
* The input is cut before any regular expression runs: a host field is caller- or remote-controlled
|
|
91
|
+
* (an address in hosts.json, a remote error line) and this projection is synchronous, so its cost
|
|
92
|
+
* must not scale with a field nobody will even see past the first few hundred characters.
|
|
93
|
+
*/
|
|
94
|
+
export function safeText(value, limit = TEXT_LIMIT) {
|
|
95
|
+
if (typeof value !== 'string')
|
|
96
|
+
return null;
|
|
97
|
+
const bounded = value.slice(0, Math.max(limit * 4, 1024));
|
|
98
|
+
const cleaned = redactHostSecrets(redactText(bounded.replace(ANSI_RE, '').replace(CONTROL_RE, ''))).trim();
|
|
99
|
+
if (cleaned === '')
|
|
100
|
+
return null;
|
|
101
|
+
return truncate(cleaned, limit);
|
|
102
|
+
}
|
|
103
|
+
/** A bilingual line the way the Client renders it: Chinese first, English after. */
|
|
104
|
+
export function pairText(pair) {
|
|
105
|
+
const zh = typeof pair?.zh === 'string' ? pair.zh.trim() : '';
|
|
106
|
+
const en = typeof pair?.en === 'string' ? pair.en.trim() : '';
|
|
107
|
+
if (zh !== '' && en !== '')
|
|
108
|
+
return `${zh} / ${en}`;
|
|
109
|
+
return zh !== '' ? zh : en;
|
|
110
|
+
}
|
|
111
|
+
/** Error codes read as one vocabulary: the tools own UPPER_SNAKE, service codes are converted. */
|
|
112
|
+
export function upperCode(code) {
|
|
113
|
+
const text = typeof code === 'string' && code !== '' ? code : 'internal';
|
|
114
|
+
return text.replaceAll('-', '_').toUpperCase();
|
|
115
|
+
}
|
|
116
|
+
export function toolError(code, message, options = {}) {
|
|
117
|
+
const out = { code, message: safeText(message, TEXT_LIMIT) ?? code };
|
|
118
|
+
if (typeof options.retryable === 'boolean')
|
|
119
|
+
out.retryable = options.retryable;
|
|
120
|
+
const hint = safeText(options.hint, TEXT_LIMIT);
|
|
121
|
+
if (hint !== null)
|
|
122
|
+
out.hint = hint;
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Turn anything the service throws into a structured result, so a broken store or an unknown host
|
|
127
|
+
* id is an answer the model can report instead of a throw. Only a defect this module cannot
|
|
128
|
+
* describe would throw.
|
|
129
|
+
*/
|
|
130
|
+
export function serviceError(error) {
|
|
131
|
+
if (isRemoteGoError(error)) {
|
|
132
|
+
const view = toErrorView(error);
|
|
133
|
+
const next = Array.isArray(view.nextSteps) ? view.nextSteps : [];
|
|
134
|
+
return toolError(upperCode(view.code), pairText(view.detail), {
|
|
135
|
+
retryable: view.retryable === true,
|
|
136
|
+
hint: pairText(next[0]),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return toolError('INTERNAL', `插件内部异常 / internal plugin error: ${messageOf(error)}`, {
|
|
140
|
+
retryable: true,
|
|
141
|
+
hint: '重试一次;若仍失败请查看 DSH 日志。 / Retry once; if it keeps failing, check the DSH log.',
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/** One failure line: the code plus the bilingual reason, redacted and bounded. */
|
|
145
|
+
export function describeViewError(error) {
|
|
146
|
+
if (!error || typeof error !== 'object')
|
|
147
|
+
return null;
|
|
148
|
+
const code = safeText(error.code, CODE_LIMIT) ?? 'error';
|
|
149
|
+
const reason = safeText(pairText(error.detail), TEXT_LIMIT);
|
|
150
|
+
return reason === null ? code : `${code}: ${reason}`;
|
|
151
|
+
}
|
|
152
|
+
export function renderText(lines) {
|
|
153
|
+
return [{ type: 'text', text: lines.join('\n') }];
|
|
154
|
+
}
|
|
155
|
+
/** The one failure line a tool's `render` prints: the code plus the hint, or a generic fallback. */
|
|
156
|
+
export function renderFailure(value) {
|
|
157
|
+
const result = (value ?? {});
|
|
158
|
+
const error = (result.error ?? null);
|
|
159
|
+
if (!error || typeof error !== 'object')
|
|
160
|
+
return 'error';
|
|
161
|
+
const text = `${error.code ?? 'error'}: ${error.message ?? ''}`.trim();
|
|
162
|
+
return error.hint ? `${text} — ${error.hint}` : text;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The live view of one host, or `null` when the composition cannot answer. A snapshot that throws
|
|
166
|
+
* is the same "no answer" case: a projection must never take the tool down with it.
|
|
167
|
+
*/
|
|
168
|
+
export function hostViewOf(service, id) {
|
|
169
|
+
try {
|
|
170
|
+
const state = service?.snapshot?.();
|
|
171
|
+
const views = Array.isArray(state?.hosts) ? state.hosts : [];
|
|
172
|
+
for (const view of views)
|
|
173
|
+
if (view?.id === id)
|
|
174
|
+
return view;
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
// swallow-ok: a broken snapshot is answered as "the host is unknown" by the caller
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The read-mode command policy of `remote_exec`: which commands may run when the caller did not ask
|
|
3
|
+
* for write mode.
|
|
4
|
+
*
|
|
5
|
+
* Why this is its own module: it is the one part of `remote_exec` that is a security decision rather
|
|
6
|
+
* than plumbing, so it is reviewed, tested and reasoned about on its own. It depends on nothing —
|
|
7
|
+
* a command string in, the offending token (or `null`) out — which also means the tool module stays
|
|
8
|
+
* a projection layer.
|
|
9
|
+
*
|
|
10
|
+
* Why it is a best effort: a POSIX shell is Turing-complete (quoting, builtins, globbing, `$(…)`,
|
|
11
|
+
* aliases, wrapper scripts on the remote PATH), so no word list can prove a command is read-only.
|
|
12
|
+
* This stops accidents and the obvious prompt-injection shapes; it is not a sandbox. The real
|
|
13
|
+
* boundary is that commands only run on a host the human already connected, plus the write switch in
|
|
14
|
+
* the plugin config.
|
|
15
|
+
*
|
|
16
|
+
* Two rules keep the list honest as programs gain flags:
|
|
17
|
+
* - a program that can mutate through an ordinary operand is not allowlisted at all (`date`,
|
|
18
|
+
* `hostname`), because no token list tells the read form from the write form;
|
|
19
|
+
* - the programs that mutate through an option are narrowed per token, and the long options are
|
|
20
|
+
* matched by **prefix**, because glibc's `getopt_long` accepts any unambiguous abbreviation
|
|
21
|
+
* (`file --comp` reaches `--compile`, `journalctl --rot` reaches `--rotate`).
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* The programs read mode may run. Every entry is an inspection tool that does not normally write;
|
|
25
|
+
* `systemctl`, `journalctl`, `file`, `ss`, `df` and `ps` are additionally narrowed by the guards
|
|
26
|
+
* below. `date` and `hostname` are deliberately absent: both are settable through an ordinary
|
|
27
|
+
* operand (`date 010100002020`, `hostname attacker`), and no word list tells the two forms apart.
|
|
28
|
+
*/
|
|
29
|
+
const READ_PROGRAMS = new Set([
|
|
30
|
+
'ls',
|
|
31
|
+
'cat',
|
|
32
|
+
'head',
|
|
33
|
+
'tail',
|
|
34
|
+
'wc',
|
|
35
|
+
'grep',
|
|
36
|
+
'egrep',
|
|
37
|
+
'fgrep',
|
|
38
|
+
'stat',
|
|
39
|
+
'file',
|
|
40
|
+
'du',
|
|
41
|
+
'df',
|
|
42
|
+
'free',
|
|
43
|
+
'ps',
|
|
44
|
+
'pgrep',
|
|
45
|
+
'uptime',
|
|
46
|
+
'uname',
|
|
47
|
+
'whoami',
|
|
48
|
+
'id',
|
|
49
|
+
'pwd',
|
|
50
|
+
'which',
|
|
51
|
+
'echo',
|
|
52
|
+
'printf',
|
|
53
|
+
'ss',
|
|
54
|
+
'netstat',
|
|
55
|
+
'lsof',
|
|
56
|
+
'journalctl',
|
|
57
|
+
'systemctl',
|
|
58
|
+
]);
|
|
59
|
+
/** The only `systemctl` verbs read mode allows: each one asks the state, none changes it. */
|
|
60
|
+
const SYSTEMCTL_READ_RE = /^(?:status|is-active|is-enabled|is-failed|show|cat|list-units|list-timers|--version)$/;
|
|
61
|
+
/**
|
|
62
|
+
* The long options that turn an allowed program into a mutation, matched by **prefix**: glibc's
|
|
63
|
+
* `getopt_long` accepts any unambiguous abbreviation, so `file --comp` reaches `--compile`,
|
|
64
|
+
* `journalctl --rot` reaches `--rotate` and `ss --dia` reaches `--diag`. A token is refused when its
|
|
65
|
+
* option name is a prefix of one of these (three characters is the shortest unambiguous prefix).
|
|
66
|
+
*/
|
|
67
|
+
const DANGEROUS_LONG_OPTIONS = {
|
|
68
|
+
file: ['compile'],
|
|
69
|
+
ss: ['diag', 'kill'],
|
|
70
|
+
df: ['sync'],
|
|
71
|
+
journalctl: [
|
|
72
|
+
'vacuum-time',
|
|
73
|
+
'vacuum-size',
|
|
74
|
+
'vacuum-files',
|
|
75
|
+
'rotate',
|
|
76
|
+
'flush',
|
|
77
|
+
'sync',
|
|
78
|
+
'relinquish-var',
|
|
79
|
+
'setup-keys',
|
|
80
|
+
'update-catalog',
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* The short flags with the same effect, checked per token because a short flag can carry its
|
|
85
|
+
* argument glued to it (`-s@0`) and `file -C` takes no argument at all. `ps` has no mutating flag;
|
|
86
|
+
* what it has is the standalone `e` command modifier, which appends every process's environment —
|
|
87
|
+
* a disclosure this read surface must not offer.
|
|
88
|
+
*/
|
|
89
|
+
const DANGEROUS_SHORT_FLAGS = {
|
|
90
|
+
file: /^-[A-Za-z]*C/,
|
|
91
|
+
ss: /^-[A-Za-z]*[KD]/,
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* The two redirections that only silence a stream and cannot write anything. They are stripped
|
|
95
|
+
* before the redirect check so the everyday `ls /nope 2>/dev/null` stays usable; every other
|
|
96
|
+
* redirect operator is refused.
|
|
97
|
+
*/
|
|
98
|
+
const DEV_NULL_RE = /2?>>?\s*\/dev\/null/g;
|
|
99
|
+
const STDERR_MERGE_RE = /2>&1/g;
|
|
100
|
+
/** The separators a compound line is split on; each resulting piece needs its own allowed program. */
|
|
101
|
+
const SEGMENT_RE = /[;|]+|&&/;
|
|
102
|
+
/** The offending token of one segment, or `null` when the segment is a read. */
|
|
103
|
+
function dangerousToken(program, tokens) {
|
|
104
|
+
const longs = DANGEROUS_LONG_OPTIONS[program] ?? [];
|
|
105
|
+
for (const token of tokens.slice(1)) {
|
|
106
|
+
if (token.startsWith('--')) {
|
|
107
|
+
const name = (token.slice(2).split('=')[0] ?? '').toLowerCase();
|
|
108
|
+
if (name.length >= 3 && longs.some((option) => option.startsWith(name)))
|
|
109
|
+
return token;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (program === 'ps' && token === 'e')
|
|
113
|
+
return token;
|
|
114
|
+
const shortFlags = DANGEROUS_SHORT_FLAGS[program];
|
|
115
|
+
if (shortFlags !== undefined && shortFlags.test(token))
|
|
116
|
+
return token;
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* The read-mode policy. It returns the offending program or token, or `null` when the command is
|
|
122
|
+
* one of the shapes the allowlist accepts.
|
|
123
|
+
*
|
|
124
|
+
* The order mirrors the risk: a newline/redirect/substitution can hide a whole program behind a
|
|
125
|
+
* harmless first word, so those are found before any token is trusted. Assignments are not
|
|
126
|
+
* stripped either — `FOO=bar ls` is refused *because* its first token is not a program, which is
|
|
127
|
+
* what makes a leading `PATH=… cmd` (or any wrapper) impossible to smuggle through.
|
|
128
|
+
*/
|
|
129
|
+
export function readOnlyViolation(command) {
|
|
130
|
+
if (command.trim() === '')
|
|
131
|
+
return 'empty';
|
|
132
|
+
if (/[\n\r\u0000]/.test(command))
|
|
133
|
+
return '\\n';
|
|
134
|
+
const stripped = command.replace(DEV_NULL_RE, '').replace(STDERR_MERGE_RE, '');
|
|
135
|
+
if (stripped.includes('>'))
|
|
136
|
+
return '>';
|
|
137
|
+
// `<` is input redirection: no read command on the list needs it, and in bash it can open a TCP
|
|
138
|
+
// socket (`cat </dev/tcp/host/port`), so it is refused with the other redirect operators.
|
|
139
|
+
if (stripped.includes('<'))
|
|
140
|
+
return '<';
|
|
141
|
+
if (stripped.includes('`'))
|
|
142
|
+
return '`';
|
|
143
|
+
if (stripped.includes('$('))
|
|
144
|
+
return '$(';
|
|
145
|
+
const segments = stripped
|
|
146
|
+
.split(SEGMENT_RE)
|
|
147
|
+
.map((segment) => segment.trim())
|
|
148
|
+
.filter((segment) => segment !== '');
|
|
149
|
+
if (segments.length === 0)
|
|
150
|
+
return 'empty';
|
|
151
|
+
for (const segment of segments) {
|
|
152
|
+
// A lone `&` backgrounds the first program and runs whatever follows it: it starts a program
|
|
153
|
+
// the first token does not name, so it is a refusal (`<(` is already caught by the `<` rule).
|
|
154
|
+
if (segment.includes('&'))
|
|
155
|
+
return '&';
|
|
156
|
+
const tokens = segment.split(/\s+/);
|
|
157
|
+
const program = tokens[0];
|
|
158
|
+
if (!READ_PROGRAMS.has(program))
|
|
159
|
+
return program;
|
|
160
|
+
if (program === 'systemctl' && !SYSTEMCTL_READ_RE.test(tokens[1] ?? ''))
|
|
161
|
+
return tokens[1] ?? 'systemctl';
|
|
162
|
+
const dangerous = dangerousToken(program, tokens);
|
|
163
|
+
if (dangerous !== null)
|
|
164
|
+
return dangerous;
|
|
165
|
+
}
|
|
166
|
+
return null;
|
|
167
|
+
}
|