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",
];
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
}
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
}
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)
}
}
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))
}
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)
}
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::*;
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! {
#[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);
}
#[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);
}
#[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);
}
#[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);
}
#[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);
}
}
}