use std::collections::BTreeSet;
use std::ffi::{OsStr, OsString};
use openmoat_core::boundary::RunEnvironment;
use openmoat_core::{Policy, RunEnv, SecretSource};
use openmoat_hosts::Host;
use crate::render::clean;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mode {
pub scrubbed: bool,
pub why: String,
}
impl Mode {
pub fn choose(choice: Option<RunEnv>, strict: Option<&str>, flag: bool) -> Self {
let (scrubbed, why) = match (strict, flag, choice) {
(Some(asks), _, _) => (
true,
format!("{asks} requires `require.run: full-boundary`"),
),
(None, true, _) => (true, "`openmoat run --scrub-env`".to_owned()),
(None, false, Some(env)) => (
env == RunEnv::Scrubbed,
format!("`sandbox.env: {}` in your policy", name(env)),
),
(None, false, None) => (
RunEnv::DEFAULT == RunEnv::Scrubbed,
format!("the default (`sandbox.env: {}`)", name(RunEnv::DEFAULT)),
),
};
Self { scrubbed, why }
}
}
fn name(env: RunEnv) -> &'static str {
match env {
RunEnv::Inherited => "inherited",
RunEnv::Scrubbed => "scrubbed",
}
}
pub fn brokered(policy: &Policy) -> Vec<(String, String)> {
let mut pairs: Vec<(String, String)> = policy
.secrets
.iter()
.filter_map(|s| match &s.source {
SecretSource::Env(name) => Some((name.clone(), s.placeholder())),
_ => None,
})
.collect();
pairs.sort();
pairs.dedup_by(|a, b| a.0 == b.0);
pairs
}
pub fn apply(
command: &mut std::process::Command,
(allowed, mode, brokered): (&Allowed, &Mode, &[(String, String)]),
verbose: bool,
) -> RunEnvironment {
let set_by_run: Vec<OsString> = command
.get_envs()
.map(|(name, _)| name.to_owned())
.collect();
let inherited = || std::env::vars_os().map(|(name, _)| name);
let withheld = withheld(inherited(), allowed, &|name| {
set_by_run.iter().any(|set| set == name)
});
if mode.scrubbed {
for name in &withheld {
command.env_remove(name);
}
}
if let Some(line) = notice(&withheld, mode.scrubbed) {
eprintln!("{line}");
}
if verbose && let Some(line) = list(&withheld, mode.scrubbed) {
eprintln!("{line}");
}
record(mode, inherited(), &withheld, brokered)
}
pub fn record(
mode: &Mode,
inherited: impl IntoIterator<Item = OsString>,
withheld: &[OsString],
brokered: &[(String, String)],
) -> RunEnvironment {
let text = |names: &[OsString]| shown(names);
let passed = if mode.scrubbed {
let mut names: Vec<OsString> = inherited
.into_iter()
.filter(|n| !withheld.contains(n) && !brokered.iter().any(|(b, _)| n == b.as_str()))
.collect();
names.sort();
names.dedup();
text(&names)
} else {
Vec::new()
};
RunEnvironment {
scrubbed: mode.scrubbed,
why: mode.why.clone(),
passed,
withheld: if mode.scrubbed {
text(withheld)
} else {
Vec::new()
},
brokered: brokered.iter().map(|(name, _)| name.clone()).collect(),
}
}
const BASE: &[&str] = &[
"PATH",
"HOME",
"USER",
"LOGNAME",
"SHELL",
"PWD",
"OLDPWD",
"SHLVL",
"_",
"TERM",
"TERM_PROGRAM",
"TERM_PROGRAM_VERSION",
"COLORTERM",
"COLUMNS",
"LINES",
"NO_COLOR",
"FORCE_COLOR",
"CLICOLOR",
"LANG",
"LANGUAGE",
"LC_ALL",
"LC_ADDRESS",
"LC_COLLATE",
"LC_CTYPE",
"LC_IDENTIFICATION",
"LC_MEASUREMENT",
"LC_MESSAGES",
"LC_MONETARY",
"LC_NAME",
"LC_NUMERIC",
"LC_PAPER",
"LC_TELEPHONE",
"LC_TIME",
"TZ",
"TMPDIR",
"TEMP",
"TMP",
"EDITOR",
"VISUAL",
"PAGER",
"XDG_CACHE_HOME",
"XDG_CONFIG_DIRS",
"XDG_CONFIG_HOME",
"XDG_DATA_DIRS",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"XDG_STATE_HOME",
"JAVA_HOME",
"GOPATH",
"GOROOT",
"GOBIN",
"CARGO_HOME",
"RUSTUP_HOME",
"RUSTUP_TOOLCHAIN",
"NVM_DIR",
"NVM_BIN",
"PYENV_ROOT",
"VIRTUAL_ENV",
"CONDA_PREFIX",
"CONDA_DEFAULT_ENV",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"MANPATH",
"INFOPATH",
"LESS",
"GPG_TTY",
crate::home::ENV,
];
const SHOWN: usize = 3;
const CREDENTIAL_WORDS: &[&str] = &[
"APIKEY",
"AUTH",
"COOKIE",
"CREDENTIAL",
"CREDENTIALS",
"KEY",
"PASS",
"PASSPHRASE",
"PASSWD",
"PASSWORD",
"PAT",
"PRIVATE",
"SECRET",
"SECRETS",
"TOKEN",
];
fn looks_like_credential(name: &str) -> bool {
let upper = name.to_ascii_uppercase();
upper.starts_with("AWS_")
|| upper
.split('_')
.any(|part| CREDENTIAL_WORDS.contains(&part))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Allowed(BTreeSet<String>);
impl Allowed {
pub fn new(platform: &[&str], host: Option<Host>, policy: &Policy, flags: &[String]) -> Self {
let mut names: BTreeSet<String> = BASE
.iter()
.chain(platform)
.map(|n| (*n).to_owned())
.collect();
names.extend(policy.sandbox.iter().flat_map(|s| s.env_allow.clone()));
names.extend(flags.iter().cloned());
let mut allowed = Self(names);
if let Some(host) = host {
allowed.add_host(host);
}
allowed
}
pub fn add_host(&mut self, host: Host) {
self.0
.extend(host_names(host).into_iter().map(str::to_owned));
}
fn holds(&self, name: &OsStr) -> bool {
name.to_str().is_some_and(|n| self.0.contains(n))
}
}
pub fn host_names(host: Host) -> Vec<&'static str> {
let spec = host.spec();
let dir = spec
.install
.as_ref()
.map(|i| i.dir_variable)
.into_iter()
.chain(spec.detect.as_ref().map(|d| d.dir_variable));
spec.run_env
.iter()
.copied()
.chain(dir)
.filter(|n| !n.is_empty())
.collect()
}
pub fn withheld(
inherited: impl IntoIterator<Item = OsString>,
allowed: &Allowed,
set_by_run: &dyn Fn(&OsStr) -> bool,
) -> Vec<OsString> {
let mut names: Vec<OsString> = inherited
.into_iter()
.filter(|name| !allowed.holds(name) && !set_by_run(name))
.collect();
names.sort();
names.dedup();
names
}
fn shown(names: &[OsString]) -> Vec<String> {
names
.iter()
.map(|n| clean(&n.to_string_lossy()).to_string())
.collect()
}
pub fn notice(names: &[OsString], scrubbed: bool) -> Option<String> {
if scrubbed {
return (!names.is_empty()).then(|| {
format!(
"moat run: {} inherited variables withheld from the agent (--verbose names them; \
`--env NAME` or `sandbox.env_allow` in your policy passes one on)",
names.len()
)
});
}
let credentials: Vec<String> = shown(names)
.into_iter()
.filter(|n| looks_like_credential(n))
.collect();
let first = credentials.first()?;
let more = credentials.len().saturating_sub(SHOWN);
let listed = credentials
.get(1..SHOWN.min(credentials.len()))
.unwrap_or_default()
.iter()
.fold(first.clone(), |all, n| format!("{all}, {n}"));
let tail = if more > 0 {
format!(" and {more} more")
} else {
String::new()
};
Some(format!(
"moat run: {} inherited variables that look like credentials reach the agent \
({listed}{tail}); `sandbox.env: scrubbed` in your policy or `--scrub-env` withholds them",
credentials.len()
))
}
pub fn doctor_line(names: &[OsString], scrubbed: bool) -> String {
let what = if scrubbed {
"withholds from the agent"
} else {
"would withhold with `sandbox.env: scrubbed`"
};
if names.is_empty() {
return format!("run environment `openmoat run` {what}: nothing here");
}
format!(
"run environment `openmoat run` {what} (names only, each agent's own excepted): {}",
shown(names).join(", ")
)
}
pub fn list(names: &[OsString], scrubbed: bool) -> Option<String> {
let verb = if scrubbed {
"withheld"
} else {
"would be withheld"
};
(!names.is_empty()).then(|| format!(" {verb} (names only): {}", shown(names).join(", ")))
}
#[cfg(test)]
mod tests;