safe-chains 0.243.2

Auto-allow safe bash commands in agentic coding tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use crate::parse::Token;
use crate::verdict::{SafetyLevel, Verdict};

const VALUED_SHORT: &[char] = &['B', 'e', 'f', 'M', 'T'];
const SSH_FLAGS: &[&str] = &["-4", "-6", "-a", "-C", "-k", "-q", "-T", "-v", "-vv", "-vvv", "-x"];
const SSH_OPTIONS: &[&str] = &[
    "batchmode", "compression", "connectionattempts", "connecttimeout", "loglevel", "port", "serveralivecountmax", "serveraliveinterval",
    "stricthostkeychecking", "user",
];

/// Whether the line names a remote shell (`-e`, `--rsh`) that is not ssh or rsh with plain options,
/// or an `--rsync-path` that is not a plain path to rsync. rsync starts the first itself, so `-e sh`
/// with `x:foo` runs `./x` here, and the remote shell runs the second as a command line. A local
/// `--server` is refused too: it is the far side's half of a transfer, reading its options and
/// file list from standard input, so nothing on the line says what it will write.
pub(crate) fn names_a_program_to_run(tokens: &[Token]) -> bool {
    let mut words = tokens.iter().skip(1).map(Token::as_str);
    while let Some(word) = words.next() {
        if word == "--" {
            break;
        }
        if word == "--server" {
            return true;
        }
        let (is_shell, value) = if let Some(long) = word.strip_prefix("--") {
            let (name, glued) = long.split_once('=').map_or((long, None), |(name, value)| (name, Some(value)));
            if name != "rsh" && name != "rsync-path" && name != "filter" {
                continue;
            }
            let value = if glued.is_some() { glued } else { words.next() };
            if name == "filter" {
                if value.is_none_or(is_a_merge_rule) {
                    return true;
                }
                continue;
            }
            (name == "rsh", value)
        } else if let Some(cluster) = word.strip_prefix('-') {
            let Some(at) = cluster.find(VALUED_SHORT) else {
                continue;
            };
            let glued = &cluster[at + 1..];
            if cluster[at..].starts_with('f') {
                let value = if glued.is_empty() { words.next() } else { Some(glued) };
                if value.is_none_or(is_a_merge_rule) {
                    return true;
                }
                continue;
            }
            if !cluster[at..].starts_with('e') {
                if glued.is_empty() {
                    words.next();
                }
                continue;
            }
            (true, if glued.is_empty() { words.next() } else { Some(glued) })
        } else {
            continue;
        };
        let plain = match value {
            Some(value) if is_shell => remote_shell_verdict(value).is_allowed(),
            Some(value) => rsync_path_verdict(value).is_allowed(),
            None => false,
        };
        if !plain {
            return true;
        }
    }
    false
}

/// ssh or rsh, bare or in a standard bin directory, or a program named by a relative path (which
/// the executor path gate then places), followed only by options that pick the port, user,
/// verbosity and a few connection settings. ssh's `-o ProxyCommand`, `LocalCommand`, `-F` and `-S`
/// start or read something else, so they are not among them; nor is a quote, which rsync parses
/// itself.
pub(crate) fn remote_shell_is_plain(value: &str) -> bool {
    if !value
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c.is_ascii_whitespace() || matches!(c, '-' | '_' | '.' | '=' | '/' | '@'))
    {
        return false;
    }
    let mut words = value.split_ascii_whitespace();
    let Some(program) = words.next() else {
        return false;
    };
    let name = ["/bin/", "/usr/bin/", "/usr/local/bin/", "/opt/homebrew/bin/"]
        .iter()
        .find_map(|dir| program.strip_prefix(dir))
        .unwrap_or(program);
    let in_the_project = program.contains('/') && !program.starts_with('/');
    if !in_the_project && name != "ssh" && name != "rsh" {
        return false;
    }
    while let Some(word) = words.next() {
        if SSH_FLAGS.contains(&word) {
            continue;
        }
        let Some(flag) = word.get(..2) else {
            return false;
        };
        let glued = &word[2..];
        let Some(argument) = (if glued.is_empty() { words.next() } else { Some(glued) }) else {
            return false;
        };
        let fits = match flag {
            "-p" => argument.chars().all(|c| c.is_ascii_digit()),
            "-l" => !argument.starts_with('-') && argument.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')),
            "-o" => argument.split_once('=').is_some_and(|(key, setting)| {
                SSH_OPTIONS.contains(&key.to_ascii_lowercase().as_str())
                    && !setting.is_empty()
                    && setting.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
            }),
            _ => false,
        };
        if !fits {
            return false;
        }
    }
    true
}

/// The verdict on a remote shell rsync would start: ssh or rsh with plain options is allowed, and a
/// program named by a relative path is judged as the file it runs. The path is normalised first. A
/// `..` that leaves the project comes back absolute, and a frozen directory or `node_modules` is
/// still in the relative path, and neither is a program the project may run. Shared by `-e`,
/// `--rsh` and `RSYNC_RSH`, so the flag and the variable cannot disagree.
pub(crate) fn remote_shell_verdict(value: &str) -> Verdict {
    if !remote_shell_is_plain(value) {
        return Verdict::Denied;
    }
    let program = value.split_ascii_whitespace().next().unwrap_or_default();
    if program.contains('/') && !program.starts_with('/') {
        let placed = crate::pathctx::resolve(program);
        if !relative_program_stays(&placed) {
            return Verdict::Denied;
        }
        crate::engine::resolve::execute_file_verdict(&placed)
    } else {
        Verdict::Allowed(SafetyLevel::Inert)
    }
}

/// A relative program, after the working directory is joined on. Absolute means it climbed out.
/// `..` left in the spelling was not joined, so it still climbs. A frozen directory runs its own
/// code, and `node_modules/.bin` is a package's.
fn relative_program_stays(placed: &str) -> bool {
    if placed.starts_with('/') || placed.starts_with('~') {
        return false;
    }
    use crate::engine::resolve::frozen_reach::{is_frozen, is_packaged};
    placed.split('/').all(|part| part != ".." && !is_frozen(part) && !is_packaged(part))
}

/// The verdict on an `--rsync-path`: rsync, bare or in a standard bin directory, or a relative path
/// to a program named rsync, judged as the file it runs. A local copy runs it here, not on a far side.
fn rsync_path_verdict(value: &str) -> Verdict {
    let plain = value.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-' | '+'))
        && value.rsplit('/').next() == Some("rsync");
    if !plain {
        return Verdict::Denied;
    }
    if value == "rsync"
        || ["/bin/", "/usr/bin/", "/usr/local/bin/", "/opt/homebrew/bin/"]
            .iter()
            .any(|dir| value.strip_prefix(dir) == Some("rsync"))
    {
        return Verdict::Allowed(SafetyLevel::Inert);
    }
    if value.starts_with('/') {
        return Verdict::Denied;
    }
    let placed = crate::pathctx::resolve(value);
    if !relative_program_stays(&placed) {
        return Verdict::Denied;
    }
    crate::engine::resolve::execute_file_verdict(&placed)
}

/// A filter rule that reads its rules from a file: `merge`, `dir-merge`, or their short forms `.`
/// and `:`, with or without modifiers. rsync prints a line it cannot parse, and with `-` and
/// `--debug=FILTER` every line, so the file is read out.
fn is_a_merge_rule(rule: &str) -> bool {
    let rule = rule.trim_start();
    if rule.starts_with(['.', ':']) {
        return true;
    }
    let name = rule.split([' ', ',', '_']).next().unwrap_or_default();
    name.eq_ignore_ascii_case("merge") || name.eq_ignore_ascii_case("dir-merge")
}

#[cfg(test)]
mod tests {
    use super::remote_shell_is_plain;
    use crate::command_verdict_in;
    use crate::is_safe_command;
    use crate::pathctx::PathCtx;
    use proptest::prelude::*;

    /// Two levels under `$HOME`, so a normalised `../` is a sibling project. The execute band admits
    /// a sibling, which is how a relative path that climbs out was approved.
    fn in_project(cmd: &str) -> bool {
        let root = format!("{}/work/proj", std::env::var("HOME").unwrap_or_else(|_| "/Users/dev".into()));
        command_verdict_in(cmd, PathCtx { cwd: Some(root.clone()), root: Some(root), session_id: None }).is_allowed()
    }

    fn check(cmd: &str) -> bool {
        is_safe_command(cmd)
    }

    safe! {
        rsync_shell_ssh: "rsync -e ssh x:foo dst/",
        rsync_shell_long_ssh: "rsync --rsh=ssh x:foo dst/",
        rsync_shell_cluster_ssh: "rsync -avessh x:foo dst/",
        rsync_shell_env_ssh: "RSYNC_RSH=ssh rsync x:foo dst/",
        rsync_path_plain: "rsync --rsync-path=/usr/local/bin/rsync host:src/ dst/",
        rsync_path_bare: "rsync --rsync-path rsync host:src/ dst/",
        rsync_shell_ssh_with_a_port: "rsync -e 'ssh -p 22' x:foo dst/",
        rsync_shell_ssh_with_a_port_locally: "rsync -e 'ssh -p 22' src/ dst/",
        rsync_shell_ssh_in_usr_bin: "rsync -e /usr/bin/ssh x:foo dst/",
        rsync_shell_ssh_in_usr_bin_with_a_user: "rsync -e '/usr/bin/ssh -l x' x:foo dst/",
        rsync_shell_long_ssh_with_a_port: "rsync --rsh='ssh -p 22 -o BatchMode=yes' x:foo dst/",
        rsync_shell_env_ssh_with_a_port: "RSYNC_RSH='ssh -p 22' rsync x:foo dst/",
        rsync_filter_exclude: "rsync -n --filter='- *.o' src/ dst/",
        rsync_filter_spaced_exclude: "rsync -n --filter '+ *.rs' src/ dst/",
    }

    denied! {
        rsync_shell_sh: "rsync -e sh x:foo dst/",
        rsync_shell_bash: "rsync -e bash x:foo dst/",
        rsync_shell_make: "rsync -e make x:foo dst/",
        rsync_shell_long_sh: "rsync --rsh=sh x:foo dst/",
        rsync_shell_long_spaced_sh: "rsync --rsh sh x:foo dst/",
        rsync_shell_cluster_sh: "rsync -avesh x:foo dst/",
        rsync_shell_cluster_spaced_sh: "rsync -ave sh x:foo dst/",
        rsync_shell_env_sh: "RSYNC_RSH=sh rsync x:foo dst/",
        rsync_shell_env_make: "env RSYNC_RSH=make rsync x:foo dst/",
        rsync_shell_proxy_command: "rsync -e 'ssh -o ProxyCommand=id' x:foo dst/",
        rsync_shell_remote_sh: "rsync -a -M-esh src/ dst/",
        rsync_path_shell: "rsync --rsync-path='sh -c id' host:src/ dst/",
        rsync_path_spaced_shell: "rsync --rsync-path 'sudo rsync' host:src/ dst/",
        rsync_path_other_program: "rsync --rsync-path=/bin/sh host:src/ dst/",
        rsync_path_metacharacter: "rsync --rsync-path='rsync;id' host:src/ dst/",
        rsync_path_remote_option: "rsync -a -M--rsync-path=sh src/ dst/",
        rsync_local_server: "rsync --server src/ dst/",
        rsync_filter_merge: "rsync -n --filter='merge ~/.npmrc' src/ dst/",
        rsync_filter_merge_spaced: "rsync -n --filter 'merge,- ~/.aws/credentials' src/ dst/",
        rsync_filter_short_merge: "rsync -n --filter='. /etc/hosts' src/ dst/",
        rsync_filter_dir_merge: "rsync -n --filter='dir-merge,n- x' src/ dst/",
        rsync_filter_short_dir_merge: "rsync -n --filter=':n- x' src/ dst/",
        rsync_filter_underscore: "rsync -n --filter=merge_x src/ dst/",
        rsync_filter_short_flag_merge: "rsync -n -f '. x' src/ dst/",
        rsync_filter_cluster_merge: "rsync -nf. src/ dst/",
        rsync_filter_remote_merge: "rsync -n -M--filter=merge_x src/ dst/",
        rsync_filter_missing_value: "rsync -n src/ dst/ --filter",
        rsync_local_server_sender: "rsync --server --sender -vlogDtpre.iLsfxC . src/",
        rsync_local_server_after_options: "rsync -a --server src/ dst/",
        rsync_shell_ssh_with_a_config_file: "rsync -e 'ssh -p 22 -F ./cfg' x:foo dst/",
        rsync_shell_ssh_in_tmp: "rsync -e /tmp/ssh x:foo dst/",
        rsync_shell_project_program_outside: "rsync -e ../../x/ssh x:foo dst/",
        rsync_shell_project_program_with_options: "rsync -e '/tmp/x/tool -p 22' x:foo dst/",
    }

    #[test]
    fn only_ssh_or_rsh_with_plain_options_is_a_plain_remote_shell() {
        for value in [
            "ssh -o StrictHostKeyChecking=accept-new", "ssh -o User=a-b", "ssh", "rsh", "ssh -p 22", "ssh -p22 -l me", "ssh -4 -q",
            "ssh -o BatchMode=yes", "ssh -oPort=22", "/usr/bin/ssh", "./bin/tool",
        ] {
            assert!(remote_shell_is_plain(value), "{value}");
        }
        for value in [
            "sh", "bash", "make", "just", "", "ssh -o ProxyCommand=id", "ssh -oProxyCommand=id", "ssh -o LocalCommand=id", "ssh -F ./cfg",
            "ssh -S /tmp/s", "ssh 'x'", "ssh \"-p\" 2", "ssh;id", "ssh -p", "/tmp/ssh", "sshd", "ssh -o", "ssh x id",
            "ssh -o PermitLocalCommand=yes", "ssh -o User=a=b", "ssh -o User=a.b", "ssh -o User=a_b", "ssh -o User=a/b", "ssh -o User=a@b",
            "ssh -l -F", "ssh -l-F", "ssh -l -o", "ssh -l --",
        ] {
            assert!(!remote_shell_is_plain(value), "{value}");
        }
        for cmd in ["rsync -e 'ssh -l -F' x:foo dst/", "rsync -e 'ssh -l-F' x:foo dst/", "RSYNC_RSH='ssh -l -F' rsync x:foo dst/"] {
            assert!(!check(cmd), "{cmd} was approved");
        }
    }

    #[test]
    fn an_rsync_path_runs_only_rsync_from_a_standard_place_or_the_project() {
        for dir in ["/tmp/x/", "/Users/someone/bin/", "~/bin/", ".git/hooks/", "scripts/../../", "node_modules/.bin/", "../", ".jj/"] {
            for (src, dst) in [("./src/", "./dst/"), ("host:src/", "dst/")] {
                for form in [format!("--rsync-path={dir}rsync"), format!("--rsync-path {dir}rsync")] {
                    let cmd = format!("rsync {form} {src} {dst}");
                    assert!(!in_project(&cmd), "{cmd} was approved");
                }
            }
        }
        for value in ["rsync", "/usr/bin/rsync", "/opt/homebrew/bin/rsync", "bin/rsync"] {
            let cmd = format!("rsync --rsync-path={value} ./src/ ./dst/");
            assert!(in_project(&cmd), "{cmd} was refused");
        }
    }

    #[test]
    fn a_remote_shell_that_escapes_or_sits_in_a_frozen_path_is_refused() {
        for cmd in [
            "rsync -e 'scripts/../../evil' x:foo dst/", "rsync -e '.git/hooks/x' x:foo dst/", "rsync -e 'node_modules/.bin/x' x:foo dst/",
            "RSYNC_RSH=scripts/../../evil rsync x:foo dst/", "RSYNC_RSH=.git/hooks/x rsync x:foo dst/",
            "RSYNC_RSH=node_modules/.bin/x rsync x:foo dst/",
        ] {
            assert!(!in_project(cmd), "{cmd} was approved");
        }
        for name in crate::engine::resolve::regions::metadata::frozen_names() {
            let by_flag = format!("rsync -e {name}/hooks/x x:foo dst/");
            let by_var = format!("RSYNC_RSH={name}/x rsync x:foo dst/");
            assert!(!in_project(&by_flag), "{by_flag} was approved");
            assert!(!in_project(&by_var), "{by_var} was approved");
        }
        for cmd in [
            "rsync -e ./bin/tool x:foo dst/", "rsync -e sub/dir/tool x:foo dst/", "rsync -e sub/../bin/tool x:foo dst/",
            "RSYNC_RSH=./bin/tool rsync x:foo dst/",
        ] {
            assert!(in_project(cmd), "{cmd} was refused");
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn a_frozen_remote_shell_is_refused_in_either_case() {
        for name in crate::engine::resolve::regions::metadata::frozen_names() {
            let cmd = format!("rsync -e {}/hooks/x x:foo dst/", name.to_ascii_uppercase());
            assert!(!in_project(&cmd), "{cmd} was approved");
        }
        assert!(!in_project("rsync -e Node_Modules/.bin/x x:foo dst/"));
    }

    proptest! {
        /// A program rsync would start to reach a daemon is a command line in every spelling, so
        /// none of them is approved. The remote shell's spellings agree with `-e`.
        #[test]
        fn a_connect_program_is_refused_in_every_spelling(
            value in prop::sample::select(vec!["id", "cat", "echo", "sh", "make", "ssh", "rsh", "./evil"]),
            spelling in 0usize..3,
        ) {
            let line = match spelling {
                0 => format!("RSYNC_CONNECT_PROG={value} rsync rsync://x/foo dst/"),
                1 => format!("env RSYNC_CONNECT_PROG={value} rsync rsync://x/foo dst/"),
                _ => format!("export RSYNC_CONNECT_PROG={value}; rsync rsync://x/foo dst/"),
            };
            prop_assert!(!is_safe_command(&line), "{}", line);
        }

        /// However RSYNC_RSH is set, it is the same choice as `-e`.
        #[test]
        fn a_remote_shell_variable_agrees_with_its_flag_in_every_spelling(
            value in prop::sample::select(vec!["id", "cat", "echo", "sh", "make", "ssh", "rsh", "./evil", "./bin/tool"]),
            spelling in 0usize..3,
        ) {
            let via_flag = format!("rsync -e {value} ./src/ ./dst/");
            let line = match spelling {
                0 => format!("RSYNC_RSH={value} rsync ./src/ ./dst/"),
                1 => format!("env RSYNC_RSH={value} rsync ./src/ ./dst/"),
                _ => format!("export RSYNC_RSH={value}; rsync ./src/ ./dst/"),
            };
            prop_assert_eq!(is_safe_command(&line), is_safe_command(&via_flag), "{} vs {}", line, via_flag);
        }

        /// However the remote shell is spelled on the line, only ssh or rsh is approved.
        #[test]
        fn a_remote_shell_other_than_ssh_is_never_approved(
            shell in prop::sample::select(vec!["sh", "bash", "zsh", "make", "just", "python3", "x"]),
            spelling in 0usize..7,
        ) {
            let line = match spelling {
                0 => format!("rsync -e {shell} x:foo dst/"),
                1 => format!("rsync -e{shell} x:foo dst/"),
                2 => format!("rsync -ave {shell} x:foo dst/"),
                3 => format!("rsync -ave{shell} x:foo dst/"),
                4 => format!("rsync --rsh={shell} x:foo dst/"),
                5 => format!("rsync --rsh {shell} x:foo dst/"),
                _ => format!("RSYNC_RSH={shell} rsync x:foo dst/"),
            };
            prop_assert!(!is_safe_command(&line), "{}", line);
        }

        /// A relative remote shell is approved only when it still names a file inside the project
        /// after `..` is normalised. One that climbs out, or that sits under a frozen directory or
        /// `node_modules`, is refused the same way through `-e` and `RSYNC_RSH`.
        #[test]
        fn a_relative_remote_shell_is_approved_only_inside_the_project(
            case in prop::sample::select(vec![
                ("scripts/../../evil", false),
                ("scripts/foo/../../../evil", false),
                ("../../x/ssh", false),
                ("a/b/../../../evil", false),
                (".git/hooks/x", false),
                (".jj/bin/x", false),
                (".hg/hooks/x", false),
                (".sl/hooks/x", false),
                (".envrc/x", false),
                ("sub/.git/hooks/x", false),
                ("node_modules/.bin/x", false),
                ("sub/node_modules/.bin/x", false),
                ("./bin/tool", true),
                ("sub/dir/tool", true),
                ("sub/../bin/tool", true),
            ]),
            spelling in 0usize..2,
        ) {
            let (program, allowed) = case;
            let line = match spelling {
                0 => format!("rsync -e {program} x:foo dst/"),
                _ => format!("RSYNC_RSH={program} rsync x:foo dst/"),
            };
            prop_assert_eq!(in_project(&line), allowed, "{}", line);
        }

        /// ssh takes the next word after `-l` as the login name, so a value that is itself an
        /// option (`-l -F`, glued `-l-F`) is a different flag. A name may still contain a dash.
        #[test]
        fn a_login_name_that_is_an_option_is_refused(
            login in prop::sample::select(vec!["user", "me", "a-b", "a_b", "a.b", "-F", "-o", "-l", "--"]),
            glued in proptest::bool::ANY,
        ) {
            let allowed = !login.starts_with('-');
            let value = if glued { format!("ssh -l{login}") } else { format!("ssh -l {login}") };
            prop_assert_eq!(remote_shell_is_plain(&value), allowed, "{}", value);
            let line = format!("rsync -e '{value}' x:foo dst/");
            prop_assert_eq!(is_safe_command(&line), allowed, "{}", line);
        }
    }
}