@venizia/vulcan 0.2.0-7 → 0.2.0-9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,947 @@
1
+ import { HookConstants } from './common/index.ts';
2
+ import type { IWriteHit } from './common/index.ts';
3
+
4
+ // -----------------------------------------------------------------------------
5
+ // The remote-host guard: a Bash command that reaches a host the project has not listed asks first.
6
+ //
7
+ // Hosts are read from the command, then compared whole: exact name, or a pattern whose only wildcard is `*`
8
+ // (it stays inside host characters). A name is never searched for inside the command text, a user, a path
9
+ // or an argument - that substring match is how a trusted name once let another host through. What the guard
10
+ // cannot read (a substitution, a jump through a command, an unknown client) asks.
11
+ // -----------------------------------------------------------------------------
12
+
13
+ export interface IRemoteHostsPolicy {
14
+ /** Hosts any command may reach. */
15
+ trusted: string[];
16
+ /** Hosts that only the strict read-only forms may reach. */
17
+ readOnly: string[];
18
+ /** Where the personal trusted list lives, for the message. */
19
+ localFile?: string;
20
+ }
21
+
22
+ interface ISegment {
23
+ words: string[];
24
+ /** `$(...)` or a backtick ran inside it: what it reaches is decided at run time. */
25
+ substitution: boolean;
26
+ /** A `<` or `>` redirect: the form is not a bare read. */
27
+ redirect: boolean;
28
+ }
29
+
30
+ interface IFinding {
31
+ hosts: string[];
32
+ /** Why the target cannot be read; `undefined` when every host is known. */
33
+ unreadable?: string;
34
+ /** The whole form is one of the strict read-only forms. */
35
+ strict: boolean;
36
+ redirect: boolean;
37
+ /** The target is not a remote login: only a host the project listed matters, any other is left alone. */
38
+ listedOnly?: boolean;
39
+ /** The target is the current ambient one (a kubeconfig context): read on a host, it is that host's own. */
40
+ ambient?: boolean;
41
+ /** An ssh's remote command: it runs on the far side, and may hop on. */
42
+ remote?: string[];
43
+ }
44
+
45
+ // --- host matching ---
46
+
47
+ const WILDCARD = '*';
48
+ const PATTERN_CHARACTERS = /^[a-z0-9._*-]+$/;
49
+
50
+ /** `${VAR}` as `$VAR`: the same unexpanded token. */
51
+ const normalizeVariable = (opts: { host: string }): string =>
52
+ opts.host.replace(/^\$\{(\w+)\}$/, '$$$1');
53
+
54
+ /** Whether `host` is one of `entries`: whole-name equal, or a `*` pattern. Case-insensitive. */
55
+ export const matchesHost = (opts: { host: string; entries: string[] }): boolean => {
56
+ const host = normalizeVariable({ host: opts.host.toLowerCase() });
57
+
58
+ return opts.entries.some(entry => {
59
+ const wanted = normalizeVariable({ host: entry.toLowerCase() });
60
+
61
+ if (!wanted.includes(WILDCARD)) {
62
+ return host === wanted;
63
+ }
64
+
65
+ if (
66
+ !PATTERN_CHARACTERS.test(wanted) ||
67
+ wanted.replaceAll(WILDCARD, '').replaceAll('.', '') === ''
68
+ ) {
69
+ return false;
70
+ }
71
+
72
+ const pattern = wanted
73
+ .split(WILDCARD)
74
+ .map(part => part.replace(/[.*+?^${}()|[\]\\-]/g, '\\$&'))
75
+ .join('[a-z0-9._-]*');
76
+
77
+ return new RegExp(`^${pattern}$`).test(host);
78
+ });
79
+ };
80
+
81
+ /** The personal trusted list: one host per line, `#` starts a comment. */
82
+ export const parseTrustedList = (opts: { text: string }): string[] =>
83
+ opts.text
84
+ .split('\n')
85
+ .map(line => line.replace(/#.*$/, '').trim())
86
+ .filter(line => line !== '');
87
+
88
+ // --- reading a command ---
89
+
90
+ const SEPARATORS = new Set([';', '&', '|', '\n', '(', ')']);
91
+ const REDIRECTS = new Set(['<', '>']);
92
+
93
+ /** Shell words, split into the commands they form. Quotes are removed; a `#` word starts a comment. */
94
+ const tokenize = (opts: { command: string }): ISegment[] => {
95
+ const segments: ISegment[] = [];
96
+ let words: string[] = [];
97
+ let current = '';
98
+ let started = false;
99
+ let quote: string | undefined;
100
+ let substitution = false;
101
+ let redirect = false;
102
+ const text = opts.command;
103
+
104
+ const endWord = (): void => {
105
+ if (started) {
106
+ words.push(current);
107
+ }
108
+
109
+ current = '';
110
+ started = false;
111
+ };
112
+
113
+ const endSegment = (): void => {
114
+ endWord();
115
+
116
+ if (words.length > 0) {
117
+ segments.push({ words, substitution, redirect });
118
+ }
119
+
120
+ words = [];
121
+ substitution = false;
122
+ redirect = false;
123
+ };
124
+
125
+ for (let index = 0; index < text.length; index++) {
126
+ const char = text[index];
127
+ const next = text[index + 1];
128
+
129
+ if (quote === "'") {
130
+ if (char === "'") {
131
+ quote = undefined;
132
+ } else {
133
+ current += char;
134
+ }
135
+
136
+ continue;
137
+ }
138
+
139
+ if (quote === '"') {
140
+ if (char === '"') {
141
+ quote = undefined;
142
+ } else if (char === '\\' && next !== undefined && '"\\$`'.includes(next)) {
143
+ current += next;
144
+ index++;
145
+ } else {
146
+ substitution ||= char === '`' || (char === '$' && next === '(');
147
+ current += char;
148
+ }
149
+
150
+ continue;
151
+ }
152
+
153
+ if (char === '\\' && next !== undefined) {
154
+ if (next !== '\n') {
155
+ current += next;
156
+ started = true;
157
+ }
158
+
159
+ index++;
160
+ } else if (char === "'" || char === '"') {
161
+ quote = char;
162
+ started = true;
163
+ } else if (char === '`' || (char === '$' && next === '(')) {
164
+ substitution = true;
165
+ current += char;
166
+ started = true;
167
+ } else if (char === '#' && !started) {
168
+ while (index < text.length && text[index] !== '\n') {
169
+ index++;
170
+ }
171
+
172
+ endSegment();
173
+ } else if (char === ' ' || char === '\t' || char === '\r') {
174
+ endWord();
175
+ } else if (SEPARATORS.has(char)) {
176
+ endSegment();
177
+ } else if (REDIRECTS.has(char)) {
178
+ redirect = true;
179
+ endWord();
180
+
181
+ // Input from a file or a string is kept as a word, so a shell fed that way is seen reading it.
182
+ if (char === '<') {
183
+ words.push(char);
184
+ }
185
+ } else {
186
+ current += char;
187
+ started = true;
188
+ }
189
+ }
190
+
191
+ endSegment();
192
+
193
+ return segments;
194
+ };
195
+
196
+ const basenameOf = (opts: { word: string }): string =>
197
+ (opts.word.split('/').pop() ?? opts.word).toLowerCase();
198
+
199
+ /** The host of `[user@]host`, `ssh://user@host:port/` or `[v6]`; lowercase, no user, no port in a URL. */
200
+ const hostOf = (opts: { value: string }): string => {
201
+ const url = /^(?:ssh|scp|sftp|rsync):\/\/(?:[^@/]*@)?(\[[^\]]+\]|[^/:]+)/i.exec(opts.value);
202
+ const bare = url?.[1] ?? opts.value.slice(opts.value.lastIndexOf('@') + 1);
203
+
204
+ return bare
205
+ .replace(/^\[|\]$/g, '')
206
+ .replace(/\.$/, '')
207
+ .toLowerCase();
208
+ };
209
+
210
+ /** The host of `scheme://[user@]host[:port]/path` or `[user@]host[:port]/path`; `undefined` for a socket or nothing. */
211
+ const authorityOf = (opts: { value: string }): string | undefined => {
212
+ const rest = /[a-z][a-z0-9+.-]*:\/\/(.*)$/i.exec(opts.value)?.[1] ?? opts.value;
213
+ const host = /^(?:[^@/?#]*@)?(\[[^\]]+\]|[^/:?#\s]+)/.exec(rest)?.[1];
214
+
215
+ return host === undefined
216
+ ? undefined
217
+ : host
218
+ .replace(/^\[|\]$/g, '')
219
+ .replace(/\.$/, '')
220
+ .toLowerCase();
221
+ };
222
+
223
+ const ENVIRONMENT_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
224
+
225
+ /** Words that open a command inside a loop, a condition or a group: the command is what follows. */
226
+ const SHELL_KEYWORDS = new Set([
227
+ 'do',
228
+ 'then',
229
+ 'else',
230
+ 'elif',
231
+ 'if',
232
+ 'while',
233
+ 'until',
234
+ '!',
235
+ '{',
236
+ 'coproc',
237
+ ]);
238
+
239
+ const HTTP_CLIENTS = new Set(['curl', 'wget', 'http', 'https', 'httpie', 'xh', 'xhs']);
240
+
241
+ /** Programs that run the rest of their line; the value is the options that take an argument. */
242
+ const WRAPPERS: Record<string, Set<string>> = {
243
+ sudo: new Set(['-u', '-g', '-h', '-p', '-C', '-D', '-r', '-t', '-U']),
244
+ doas: new Set(['-u', '-C']),
245
+ env: new Set(['-u', '-C', '-S']),
246
+ time: new Set(['-f', '-o']),
247
+ nohup: new Set(),
248
+ nice: new Set(['-n']),
249
+ ionice: new Set(['-c', '-n', '-p']),
250
+ exec: new Set(['-a']),
251
+ stdbuf: new Set(['-i', '-o', '-e']),
252
+ timeout: new Set(['-s', '-k']),
253
+ setsid: new Set(),
254
+ xargs: new Set(['-I', '-n', '-P', '-d', '-E', '-s', '-L', '-a']),
255
+ watch: new Set(['-n', '--interval', '-d']),
256
+ sshpass: new Set(['-p', '-f', '-P', '-d']),
257
+ };
258
+
259
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'ash']);
260
+
261
+ /** Look a command up or describe it; running none of the words that follow. */
262
+ const LOOKUPS = new Set(['man', 'which', 'type', 'whereis', 'apropos', 'whatis', 'echo', 'printf']);
263
+
264
+ const SSH_ARGUMENT_LETTERS: Record<string, string> = {
265
+ ssh: 'BbcDEeFIiJLlmOopQRSWw',
266
+ sftp: 'BbcDFiJlOoPRSsX',
267
+ scp: 'cDFiJlOoPSX',
268
+ mosh: 'p',
269
+ 'ssh-copy-id': 'iopt',
270
+ 'ssh-keyscan': 'ptT',
271
+ };
272
+
273
+ const NETWORK_CLIENTS = new Set(['nc', 'ncat', 'netcat', 'telnet']);
274
+ const NETWORK_ARGUMENT_LETTERS = 'pswiIOTxXPZ';
275
+ const KUBERNETES_CLIENTS = new Set(['kubectl', 'helm', 'k9s', 'oc']);
276
+ const KUBERNETES_TARGET_OPTIONS = [
277
+ '--context',
278
+ '--kube-context',
279
+ '--cluster',
280
+ '--server',
281
+ '--kube-apiserver',
282
+ '-s',
283
+ ];
284
+
285
+ /** Clients whose target this guard does not parse: they always ask. */
286
+ const UNPARSED_CLIENTS =
287
+ /^(?:autossh|pssh|pscp|pslurp|prsync|parallel-ssh|parallel-scp|pdsh|clush|dbclient|plink|putty|socat|rsh|rcp|rlogin|ftp|lftp|tftp|cssh|tssh|ansible(?:-[\w-]+)?)$/;
288
+
289
+ const SENSITIVE_ASSIGNMENT =
290
+ /(?:^|[\s;&|(])(?:export\s+)?(?:git_ssh(?:_command)?|rsync_rsh|docker_host|docker_context|kubeconfig)=|core\.sshcommand/i;
291
+ const URL_HOST = /(?:ssh|scp|sftp|rsync):\/\/(?:[^@\s/'"]*@)?(\[[^\]]+\]|[^\s/:'"]+)/gi;
292
+ const DEVICE_HOST = /\/dev\/(?:tcp|udp)\/([^/\s'"]+)\//gi;
293
+
294
+ const UNSAFE_OPTION_KEYS = new Set(['proxycommand', 'localcommand', 'knownhostscommand']);
295
+
296
+ // --- the strict read-only forms ---
297
+
298
+ const LABEL = '\\w[\\w-]*';
299
+ const REMOTE_PATH = '/[\\w./-]*';
300
+ const LOCAL_PATH = '(?:\\./)?\\w[\\w-]*(?:[./][\\w-]+)*/?';
301
+ const UNIT = '[\\w@][\\w.@-]*';
302
+
303
+ const READ_ONLY_REMOTE = new RegExp(
304
+ `^(?:${[
305
+ 'uptime',
306
+ 'hostname',
307
+ 'df -h',
308
+ 'free -m',
309
+ 'docker ps(?: -a)?',
310
+ 'docker compose ps',
311
+ `ls(?: -[a-zA-Z]+)? ${REMOTE_PATH}`,
312
+ `cat ${REMOTE_PATH}`,
313
+ `tail -n \\d+ ${REMOTE_PATH}`,
314
+ `systemctl status ${UNIT}(?: --no-pager)?`,
315
+ `journalctl -u ${UNIT} -n \\d+ --no-pager`,
316
+ `docker logs --tail \\d+ ${UNIT}`,
317
+ ].join('|')})$`,
318
+ );
319
+ const COPY_SOURCE = new RegExp(`^(?:${LABEL}(?:\\.${LABEL})*@)?[^@\\s/:]+:${REMOTE_PATH}$`);
320
+ const COPY_TARGET = new RegExp(`^${LOCAL_PATH}$`);
321
+ const SCP_SAFE_FLAGS = /^-[rpqC]+$/;
322
+ const RSYNC_SAFE_FLAGS = /^-[avzrhPt]+$/;
323
+ const KUBECTL_READ_VERBS = new Set(['get', 'describe', 'logs', 'top']);
324
+ const KUBECTL_SAFE_WORD = /^[\w./=:,@-]+$/;
325
+
326
+ // --- per-client analysis ---
327
+
328
+ const unreadable = (opts: { why: string }): IFinding => ({
329
+ hosts: [],
330
+ unreadable: opts.why,
331
+ strict: false,
332
+ redirect: false,
333
+ });
334
+
335
+ interface IOptionEffect {
336
+ hosts: string[];
337
+ unreadable?: string;
338
+ }
339
+
340
+ /** What one ssh-family option means for where the connection goes. */
341
+ const optionEffect = (opts: { letter: string; value: string }): IOptionEffect => {
342
+ const { letter, value } = opts;
343
+
344
+ if (letter === 'J') {
345
+ return { hosts: value.split(',').map(jump => hostOf({ value: jump.replace(/:\d+$/, '') })) };
346
+ }
347
+
348
+ if (letter === 'F' || letter === 'S') {
349
+ return { hosts: [], unreadable: `-${letter} ${value} can redirect the connection` };
350
+ }
351
+
352
+ if (letter === 'W') {
353
+ return { hosts: [hostOf({ value: value.replace(/:\d+$/, '') })] };
354
+ }
355
+
356
+ if (letter !== 'o') {
357
+ return { hosts: [] };
358
+ }
359
+
360
+ const [key = '', ...rest] = value.split(/[=\s]+/);
361
+ const setting = rest.join('=').trim();
362
+
363
+ if (UNSAFE_OPTION_KEYS.has(key.toLowerCase())) {
364
+ return { hosts: [], unreadable: `-o ${key} runs a command` };
365
+ }
366
+
367
+ if (key.toLowerCase() === 'proxyjump' && setting.toLowerCase() !== 'none') {
368
+ return { hosts: setting.split(',').map(jump => hostOf({ value: jump.replace(/:\d+$/, '') })) };
369
+ }
370
+
371
+ return { hosts: key.toLowerCase() === 'hostname' ? [hostOf({ value: setting })] : [] };
372
+ };
373
+
374
+ /** `ssh`, `sftp`, `mosh`, `ssh-copy-id`, `ssh-keyscan`: options, then the destination, then a remote command. */
375
+ const analyzeSsh = (opts: { program: string; words: string[] }): IFinding => {
376
+ const letters = SSH_ARGUMENT_LETTERS[opts.program] ?? '';
377
+ const hosts: string[] = [];
378
+ const positionals: string[] = [];
379
+ let why: string | undefined;
380
+ let sawOption = false;
381
+ let command: string[] = [];
382
+ const keyscan = opts.program === 'ssh-keyscan';
383
+
384
+ for (let index = 1; index < opts.words.length; index++) {
385
+ const word = opts.words[index] ?? '';
386
+
387
+ if (word === '--') {
388
+ const rest = opts.words.slice(index + 1);
389
+
390
+ if (positionals.length === 0 || keyscan) {
391
+ positionals.push(...rest.slice(0, 1));
392
+ command = keyscan ? [] : rest.slice(1);
393
+ } else {
394
+ command = rest;
395
+ }
396
+
397
+ break;
398
+ }
399
+
400
+ if (word.startsWith('--') && opts.program === 'mosh') {
401
+ sawOption = true;
402
+ why ??= /^--(?:ssh|server)\b/.test(word) ? `${word.split('=')[0]} runs a command` : undefined;
403
+ continue;
404
+ }
405
+
406
+ if (word.startsWith('-') && word.length > 1) {
407
+ sawOption = true;
408
+
409
+ for (let position = 1; position < word.length; position++) {
410
+ const letter = word[position] ?? '';
411
+
412
+ if (keyscan && letter === 'f') {
413
+ why ??= '-f reads the hosts from a file';
414
+ }
415
+
416
+ if (!letters.includes(letter)) {
417
+ continue;
418
+ }
419
+
420
+ const attached = word.slice(position + 1);
421
+ const value = attached !== '' ? attached : (opts.words[++index] ?? '');
422
+ const effect = optionEffect({ letter, value });
423
+
424
+ hosts.push(...effect.hosts);
425
+ why ??= effect.unreadable;
426
+ break;
427
+ }
428
+
429
+ continue;
430
+ }
431
+
432
+ if (positionals.length === 0 || keyscan) {
433
+ positionals.push(word);
434
+ continue;
435
+ }
436
+
437
+ command = opts.words.slice(index);
438
+ break;
439
+ }
440
+
441
+ if (positionals.length === 0) {
442
+ return unreadable({ why: `${opts.program} names no destination` });
443
+ }
444
+
445
+ hosts.push(...positionals.map(positional => hostOf({ value: positional })));
446
+
447
+ return {
448
+ hosts,
449
+ ...(why === undefined ? {} : { unreadable: why }),
450
+ strict:
451
+ opts.program === 'ssh' &&
452
+ !sawOption &&
453
+ command.length > 0 &&
454
+ READ_ONLY_REMOTE.test(command.join(' ')),
455
+ redirect: false,
456
+ ...(opts.program === 'ssh' && command.length > 0 ? { remote: command } : {}),
457
+ };
458
+ };
459
+
460
+ /** `user@host:path`, `host::module` or a `scheme://` URL: the host, else `undefined` for a local path. */
461
+ const copySpecHost = (opts: { word: string }): string | undefined => {
462
+ const { word } = opts;
463
+
464
+ if (word.startsWith('-') || /^(?:\/|\.{1,2}\/|~)/.test(word)) {
465
+ return undefined;
466
+ }
467
+
468
+ if (/^(?:ssh|scp|sftp|rsync):\/\//i.test(word)) {
469
+ return hostOf({ value: word });
470
+ }
471
+
472
+ const spec = /^(?:[^@\s/:]+@)?(\[[0-9a-f:.]+\]|[^@\s/:]+):/i.exec(word);
473
+
474
+ return spec?.[1] === undefined ? undefined : hostOf({ value: spec[1] });
475
+ };
476
+
477
+ /** `-e`/`--rsh` that is a plain `ssh` (with a port or key) leaves the host as typed; anything else may add a hop. */
478
+ const PLAIN_RSH = /^ssh(?: -[pi] \S+)*$/;
479
+
480
+ /** `scp`, `rsync`, `sshfs`: every `host:path` is a host; options may add a jump or run a command. */
481
+ const analyzeCopy = (opts: { program: string; words: string[] }): IFinding => {
482
+ const hosts: string[] = [];
483
+ const positionals: string[] = [];
484
+ const flags: string[] = [];
485
+ let why: string | undefined;
486
+ const scp = opts.program === 'scp' || opts.program === 'sshfs';
487
+ const letters = SSH_ARGUMENT_LETTERS.scp ?? '';
488
+
489
+ for (let index = 1; index < opts.words.length; index++) {
490
+ const word = opts.words[index] ?? '';
491
+
492
+ if (word.startsWith('--')) {
493
+ const rsh = /^--rsh(?:=(.*))?$/.exec(word);
494
+
495
+ if (rsh !== null) {
496
+ const value = rsh[1] ?? opts.words[++index] ?? '';
497
+
498
+ why ??= PLAIN_RSH.test(value)
499
+ ? undefined
500
+ : `--rsh "${value}" can add a hop or run a command`;
501
+ }
502
+
503
+ flags.push(word);
504
+ continue;
505
+ }
506
+
507
+ if (word.startsWith('-') && word.length > 1) {
508
+ flags.push(word);
509
+
510
+ for (let position = 1; position < word.length; position++) {
511
+ const letter = word[position] ?? '';
512
+ const takesArgument = scp ? letters.includes(letter) : letter === 'e';
513
+
514
+ if (!takesArgument) {
515
+ continue;
516
+ }
517
+
518
+ const attached = word.slice(position + 1);
519
+ const value = attached !== '' ? attached : (opts.words[++index] ?? '');
520
+
521
+ if (letter === 'e') {
522
+ why ??= PLAIN_RSH.test(value)
523
+ ? undefined
524
+ : `-e "${value}" can add a hop or run a command`;
525
+ } else {
526
+ const effect = optionEffect({ letter, value });
527
+
528
+ hosts.push(...effect.hosts);
529
+ why ??= effect.unreadable;
530
+ }
531
+
532
+ break;
533
+ }
534
+
535
+ continue;
536
+ }
537
+
538
+ positionals.push(word);
539
+ }
540
+
541
+ const specs = positionals.map(positional => copySpecHost({ word: positional }));
542
+
543
+ hosts.push(...specs.flatMap(spec => (spec === undefined ? [] : [spec])));
544
+
545
+ const safe = flags.every(flag => (scp ? SCP_SAFE_FLAGS : RSYNC_SAFE_FLAGS).test(flag));
546
+ const [source = '', target = ''] = positionals;
547
+
548
+ return {
549
+ hosts,
550
+ ...(why === undefined ? {} : { unreadable: why }),
551
+ strict:
552
+ safe &&
553
+ positionals.length === 2 &&
554
+ COPY_SOURCE.test(source) &&
555
+ specs[0] !== undefined &&
556
+ specs[1] === undefined &&
557
+ COPY_TARGET.test(target),
558
+ redirect: false,
559
+ };
560
+ };
561
+
562
+ /** The value of `--name value` / `--name=value`, wherever it stands. */
563
+ const optionValues = (opts: { words: string[]; names: string[] }): string[] =>
564
+ opts.words.flatMap((word, index) => {
565
+ const name = opts.names.find(
566
+ candidate => word === candidate || word.startsWith(`${candidate}=`),
567
+ );
568
+
569
+ if (name === undefined) {
570
+ return [];
571
+ }
572
+
573
+ return [word === name ? (opts.words[index + 1] ?? '') : word.slice(name.length + 1)];
574
+ });
575
+
576
+ const analyzeKubernetes = (opts: { program: string; words: string[] }): IFinding => {
577
+ if (opts.words.some(word => word === '--kubeconfig' || word.startsWith('--kubeconfig='))) {
578
+ return unreadable({ why: '--kubeconfig points at contexts this guard cannot read' });
579
+ }
580
+
581
+ const targets = optionValues({ words: opts.words, names: KUBERNETES_TARGET_OPTIONS });
582
+
583
+ if (targets.length === 0) {
584
+ return {
585
+ ...unreadable({ why: `${opts.program} uses the current kubeconfig context` }),
586
+ ambient: true,
587
+ };
588
+ }
589
+
590
+ const hosts = targets.map(target =>
591
+ target.includes('://') ? new URL(target).hostname : target.toLowerCase(),
592
+ );
593
+ const contexts = optionValues({ words: opts.words, names: ['--context'] });
594
+ const rest: string[] = [];
595
+
596
+ for (let index = 1; index < opts.words.length; index++) {
597
+ const word = opts.words[index] ?? '';
598
+
599
+ if (word === '--context') {
600
+ index++;
601
+ } else if (!word.startsWith('--context=')) {
602
+ rest.push(word);
603
+ }
604
+ }
605
+
606
+ const [verb = ''] = rest;
607
+
608
+ return {
609
+ hosts,
610
+ strict:
611
+ opts.program === 'kubectl' &&
612
+ contexts.length === 1 &&
613
+ targets.length === 1 &&
614
+ KUBECTL_READ_VERBS.has(verb) &&
615
+ rest.every(word => KUBECTL_SAFE_WORD.test(word)),
616
+ redirect: false,
617
+ };
618
+ };
619
+
620
+ const analyzeNetwork = (opts: { words: string[] }): IFinding => {
621
+ const positionals: string[] = [];
622
+
623
+ for (let index = 1; index < opts.words.length; index++) {
624
+ const word = opts.words[index] ?? '';
625
+
626
+ if (word.startsWith('-') && word.length > 1) {
627
+ const last = word[word.length - 1] ?? '';
628
+
629
+ if (NETWORK_ARGUMENT_LETTERS.includes(last)) {
630
+ index++;
631
+ }
632
+
633
+ continue;
634
+ }
635
+
636
+ positionals.push(word);
637
+ }
638
+
639
+ return positionals.length === 0
640
+ ? unreadable({ why: 'no host to connect to' })
641
+ : { hosts: [hostOf({ value: positionals[0] ?? '' })], strict: false, redirect: false };
642
+ };
643
+
644
+ /** `curl`, `wget`, `http`: a URL or bare address names a host; only a listed one matters. */
645
+ const analyzeHttp = (opts: { words: string[] }): IFinding => {
646
+ const hosts = opts.words.slice(1).flatMap(word => {
647
+ const candidate = /\s/.test(word) ? /[a-z][a-z0-9+.-]*:\/\/\S*/i.exec(word)?.[0] : word;
648
+
649
+ if (candidate === undefined || (candidate.startsWith('-') && !candidate.includes('://'))) {
650
+ return [];
651
+ }
652
+
653
+ const host = authorityOf({ value: candidate });
654
+
655
+ return host === undefined ? [] : [host];
656
+ });
657
+
658
+ return { hosts, strict: false, redirect: false, listedOnly: true };
659
+ };
660
+
661
+ /** `-H`/`--host` name the daemon; a context or `docker context` resolves elsewhere and cannot be read. */
662
+ const analyzeDocker = (opts: { words: string[] }): IFinding => {
663
+ const hosts: string[] = [];
664
+
665
+ for (let index = 1; index < opts.words.length; index++) {
666
+ const word = opts.words[index] ?? '';
667
+
668
+ if (/^(?:-c|--context)(?:=|$)/.test(word) || word === 'context') {
669
+ return unreadable({ why: 'docker is pointed at another host or context' });
670
+ }
671
+
672
+ const long = /^--host(?:=(.*))?$/.exec(word);
673
+ const short = /^-H(.*)$/.exec(word);
674
+ const given = long ?? short;
675
+
676
+ if (given === null) {
677
+ continue;
678
+ }
679
+
680
+ const value = given[1] ?? '';
681
+ const host = authorityOf({ value: value === '' ? (opts.words[++index] ?? '') : value });
682
+
683
+ if (host !== undefined) {
684
+ hosts.push(host);
685
+ }
686
+ }
687
+
688
+ return { hosts, strict: false, redirect: false };
689
+ };
690
+
691
+ /** Whether a shell with no `-c` takes its commands from its input: no script file, or `-s`. */
692
+ const readsItsInput = (opts: { words: string[] }): boolean => {
693
+ if (opts.words.includes('<')) {
694
+ return true;
695
+ }
696
+
697
+ for (const word of opts.words.slice(1)) {
698
+ if (!word.startsWith('-')) {
699
+ return false;
700
+ }
701
+
702
+ if (/^-[a-z]*s[a-z]*$/.test(word)) {
703
+ return true;
704
+ }
705
+ }
706
+
707
+ return true;
708
+ };
709
+
710
+ const MAXIMUM_DEPTH = 4;
711
+
712
+ /** Skips a wrapper's own options (and the values its options take); the words after are its command. */
713
+ const unwrap = (opts: { program: string; words: string[] }): string[] => {
714
+ const takesValue = WRAPPERS[opts.program] ?? new Set<string>();
715
+ let index = 1;
716
+
717
+ while (index < opts.words.length) {
718
+ const word = opts.words[index] ?? '';
719
+
720
+ if (word.startsWith('-') && word.length > 1) {
721
+ index += takesValue.has(word) ? 2 : 1;
722
+ } else if (
723
+ ENVIRONMENT_ASSIGNMENT.test(word) ||
724
+ (/^\d[\w.]*$/.test(word) && opts.program !== 'sshpass')
725
+ ) {
726
+ index++;
727
+ } else {
728
+ break;
729
+ }
730
+ }
731
+
732
+ return opts.words.slice(index);
733
+ };
734
+
735
+ /** The findings of one command's words, following wrappers, `sh -c`, `eval` and `find -exec`. */
736
+ const analyzeWords = (opts: {
737
+ words: string[];
738
+ depth: number;
739
+ /** Reads a command string (`sh -c`, `eval`): the whole analysis again, one level deeper. */
740
+ recurse: (opts: { command: string; depth: number }) => IFinding[];
741
+ }): IFinding[] => {
742
+ const words = [...opts.words];
743
+
744
+ while (
745
+ words[0] !== undefined &&
746
+ (ENVIRONMENT_ASSIGNMENT.test(words[0]) || SHELL_KEYWORDS.has(words[0]))
747
+ ) {
748
+ words.shift();
749
+ }
750
+
751
+ const program = basenameOf({ word: words[0] ?? '' });
752
+
753
+ if (program === '' || LOOKUPS.has(program) || opts.depth > MAXIMUM_DEPTH) {
754
+ return opts.depth > MAXIMUM_DEPTH ? [unreadable({ why: 'the command nests too deeply' })] : [];
755
+ }
756
+
757
+ if (program === 'command' && words.some(word => word === '-v' || word === '-V')) {
758
+ return [];
759
+ }
760
+
761
+ if (program in WRAPPERS || program === 'command' || program === 'builtin') {
762
+ return analyzeWords({
763
+ words: unwrap({ program, words }),
764
+ depth: opts.depth + 1,
765
+ recurse: opts.recurse,
766
+ });
767
+ }
768
+
769
+ if (program === 'eval') {
770
+ return opts.recurse({
771
+ command: words.slice(1).join(' '),
772
+ depth: opts.depth + 1,
773
+ });
774
+ }
775
+
776
+ if (SHELLS.has(program)) {
777
+ const flag = words.findIndex((word, index) => index > 0 && /^-[a-z]*c[a-z]*$/.test(word));
778
+
779
+ if (flag !== -1) {
780
+ return opts.recurse({
781
+ command: words[flag + 1] ?? '',
782
+ depth: opts.depth + 1,
783
+ });
784
+ }
785
+
786
+ return readsItsInput({ words })
787
+ ? [unreadable({ why: `${program} runs commands it reads from its input` })]
788
+ : [];
789
+ }
790
+
791
+ if (program === 'find') {
792
+ const start = words.findIndex(word => ['-exec', '-execdir', '-ok', '-okdir'].includes(word));
793
+
794
+ if (start === -1) {
795
+ return [];
796
+ }
797
+
798
+ const tail = words.slice(start + 1);
799
+ const end = tail.findIndex(word => word === ';' || word === '+');
800
+
801
+ return analyzeWords({
802
+ words: end === -1 ? tail : tail.slice(0, end),
803
+ depth: opts.depth + 1,
804
+ recurse: opts.recurse,
805
+ });
806
+ }
807
+
808
+ if (program === 'docker') {
809
+ return [analyzeDocker({ words })];
810
+ }
811
+
812
+ if (HTTP_CLIENTS.has(program)) {
813
+ return [analyzeHttp({ words })];
814
+ }
815
+
816
+ if (program in SSH_ARGUMENT_LETTERS && program !== 'scp') {
817
+ const finding = analyzeSsh({ program, words });
818
+ const nested =
819
+ finding.remote === undefined
820
+ ? []
821
+ : opts
822
+ .recurse({ command: finding.remote.join(' '), depth: opts.depth + 1 })
823
+ .filter(inner => inner.ambient !== true);
824
+
825
+ return [finding, ...nested];
826
+ }
827
+
828
+ if (program === 'scp' || program === 'rsync' || program === 'sshfs') {
829
+ return [analyzeCopy({ program, words })];
830
+ }
831
+
832
+ if (KUBERNETES_CLIENTS.has(program)) {
833
+ return [analyzeKubernetes({ program, words })];
834
+ }
835
+
836
+ if (NETWORK_CLIENTS.has(program)) {
837
+ return [analyzeNetwork({ words })];
838
+ }
839
+
840
+ return UNPARSED_CLIENTS.test(program)
841
+ ? [unreadable({ why: `the target of ${program} is not parsed` })]
842
+ : [];
843
+ };
844
+
845
+ const analyzeCommand = (opts: { command: string; depth: number }): IFinding[] =>
846
+ tokenize({ command: opts.command }).flatMap(segment => {
847
+ const findings = analyzeWords({
848
+ words: segment.words,
849
+ depth: opts.depth,
850
+ recurse: analyzeCommand,
851
+ });
852
+
853
+ return findings.map((finding): IFinding =>
854
+ segment.substitution && (finding.hosts.length > 0 || finding.unreadable !== undefined)
855
+ ? {
856
+ ...finding,
857
+ unreadable: finding.unreadable ?? 'a substitution runs inside it',
858
+ redirect: finding.redirect || segment.redirect,
859
+ }
860
+ : { ...finding, redirect: finding.redirect || segment.redirect },
861
+ );
862
+ });
863
+
864
+ // --- the decision ---
865
+
866
+ const trustedMessage = (opts: { host: string; policy: IRemoteHostsPolicy }): string =>
867
+ `reaching '${opts.host}', which is not in remoteHosts.trusted (list it there${opts.policy.localFile === undefined ? '' : `, or in ${opts.policy.localFile} for yourself`}); a remoteHosts.readOnly host passes only the strict read-only forms`;
868
+
869
+ const readOnlyMessage = (opts: { host: string }): string =>
870
+ `'${opts.host}' is a remoteHosts.readOnly host: only a strict read-only form passes (uptime, df -h, cat <path>, scp/rsync from it, kubectl get|describe|logs|top), and this command is not one`;
871
+
872
+ /** Why each host this command reaches may not be reached without asking; empty means nothing to ask. */
873
+ export const inspectRemoteCommand = (opts: {
874
+ command: string;
875
+ policy: IRemoteHostsPolicy;
876
+ }): IWriteHit[] => {
877
+ const { command, policy } = opts;
878
+ const findings = analyzeCommand({ command, depth: 0 });
879
+ const hits: IWriteHit[] = [];
880
+ const asked = new Set<string>();
881
+
882
+ const ask = (message: string): void => {
883
+ if (!asked.has(message)) {
884
+ asked.add(message);
885
+ hits.push({ rule: 'remote-hosts', message });
886
+ }
887
+ };
888
+
889
+ for (const finding of findings) {
890
+ if (finding.unreadable !== undefined) {
891
+ ask(
892
+ `the target of this command cannot be read (${finding.unreadable}), so any host could be reached`,
893
+ );
894
+ continue;
895
+ }
896
+
897
+ for (const host of finding.hosts) {
898
+ if (matchesHost({ host, entries: policy.trusted })) {
899
+ continue;
900
+ }
901
+
902
+ if (matchesHost({ host, entries: policy.readOnly })) {
903
+ if (!finding.strict || finding.redirect) {
904
+ ask(readOnlyMessage({ host }));
905
+ }
906
+
907
+ continue;
908
+ }
909
+
910
+ if (finding.listedOnly !== true) {
911
+ ask(trustedMessage({ host, policy }));
912
+ }
913
+ }
914
+ }
915
+
916
+ const devices = [...command.matchAll(DEVICE_HOST)].map(match =>
917
+ hostOf({ value: match[1] ?? '' }),
918
+ );
919
+ const urls = [...command.matchAll(URL_HOST)].map(match => hostOf({ value: match[1] ?? '' }));
920
+
921
+ for (const host of [...devices, ...urls]) {
922
+ if (!matchesHost({ host, entries: policy.trusted })) {
923
+ ask(trustedMessage({ host, policy }));
924
+ }
925
+ }
926
+
927
+ if (SENSITIVE_ASSIGNMENT.test(command)) {
928
+ ask(
929
+ 'the target of this command cannot be read (an environment variable or git option redirects ssh, rsync, docker or kubectl)',
930
+ );
931
+ }
932
+
933
+ return hits;
934
+ };
935
+
936
+ export const buildRemoteDecision = (opts: { hits: IWriteHit[] }) => ({
937
+ hookSpecificOutput: {
938
+ hookEventName: HookConstants.PRE_TOOL_USE,
939
+ permissionDecision: HookConstants.GUARD_DECISION,
940
+ permissionDecisionReason: [
941
+ 'This command may reach a remote host the project has not listed:',
942
+ ...opts.hits.map(hit => ` - ${hit.message}`),
943
+ '',
944
+ 'Read on the host, never edit, restart or copy onto it. Produce the command and hand it over.',
945
+ ].join('\n'),
946
+ },
947
+ });