use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, SystemTime};
use anyhow::{Context as _, Result, bail, ensure};
use openmoat_core::{Policy, SecretCommand, SecretCommandHome};
use serde::Deserialize;
use zeroize::Zeroizing;
use super::copy::Copy;
use super::{Place, program};
#[cfg(not(unix))]
mod other;
#[cfg(unix)]
mod unix;
#[cfg(not(unix))]
use other as platform;
#[cfg(unix)]
use unix as platform;
const TIME_LIMIT: Duration = Duration::from_secs(30);
const MAX_OUTPUT: usize = 64 * 1024;
const MIN_ANSWER: Duration = Duration::from_secs(10);
#[cfg(unix)]
const PASSED: &[&str] = &["USER", "LOGNAME", "LANG", "LC_ALL", "TMPDIR", "TZ"];
#[cfg(windows)]
const PASSED: &[&str] = &[
"SystemRoot",
"windir",
"USERNAME",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"ProgramData",
"TEMP",
"TMP",
];
#[cfg(not(any(unix, windows)))]
const PASSED: &[&str] = &[];
pub struct Program {
id: String,
path: PathBuf,
#[cfg_attr(
not(unix),
expect(dead_code, reason = "only Unix sets a program's argv[0]")
)]
written: String,
args: Vec<String>,
copy: Copy,
interpreter: Option<(PathBuf, String)>,
home: PathBuf,
lifetime: Duration,
refresh_before: Duration,
time_limit: Duration,
}
pub struct Answer {
pub value: Zeroizing<String>,
pub lifetime: Duration,
pub masked: Vec<Zeroizing<String>>,
}
impl super::Fetch for Program {
fn id(&self) -> &str {
Program::id(self)
}
fn refresh_before(&self) -> Duration {
Program::refresh_before(self)
}
fn time_limit(&self) -> Duration {
Program::time_limit(self)
}
fn fetch(&self) -> Result<Answer> {
Program::fetch(self)
}
}
impl Program {
pub fn prepare(
id: &str,
source: &SecretCommand,
policy: &Policy,
place: &Place<'_>,
) -> Result<Self> {
let home = place.home;
let written = match source.program().strip_prefix("~/") {
Some(rest) => format!("{home}/{rest}"),
None => source.program().to_owned(),
};
let checked = program::check(&written, policy, home, place.writable)?;
let copy = Copy::make(&checked.path, id, place.state)?;
let interpreter = checked
.interpreter
.map(|path| program::digest(&path).map(|digest| (path, digest)))
.transpose()?;
Ok(Self {
id: id.to_owned(),
path: checked.path,
written,
args: source.run.iter().skip(1).cloned().collect(),
copy,
interpreter,
home: program_home(id, source.home, place)?,
lifetime: Duration::from_secs(source.lifetime_secs()),
refresh_before: Duration::from_secs(source.refresh_before_secs()),
time_limit: TIME_LIMIT,
})
}
#[cfg(test)]
#[cfg_attr(
not(unix),
expect(dead_code, reason = "the stand-in programs are Unix scripts")
)]
pub fn with_time_limit(self, time_limit: Duration) -> Self {
Self { time_limit, ..self }
}
pub fn id(&self) -> &str {
&self.id
}
pub fn refresh_before(&self) -> Duration {
self.refresh_before
}
pub fn time_limit(&self) -> Duration {
self.time_limit
}
pub fn fetch(&self) -> Result<Answer> {
let pinned = std::iter::once((&self.path, self.copy.digest()))
.chain(self.interpreter.iter().map(|(p, d)| (p, d.as_str())));
for (path, digest) in pinned {
ensure!(
program::digest(path)? == digest,
"{} changed since the proxy started; restart `openmoat proxy` to use the new one",
path.display()
);
}
self.copy.verify()?;
let out = self.run()?;
let unix_now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
parse(&out, self.lifetime, unix_now)
}
fn command(&self) -> Command {
let mut command = Command::new(self.copy.path());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt as _;
command.arg0(&self.written).process_group(0);
}
command
.current_dir(fixed_dir())
.args(&self.args)
.env_clear()
.env("HOME", &self.home)
.env("PATH", search_path())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
#[cfg(windows)]
command.env("USERPROFILE", &self.home);
for name in PASSED {
if let Some(value) = std::env::var_os(name) {
command.env(name, value);
}
}
command
}
fn run(&self) -> Result<Zeroizing<Vec<u8>>> {
let shown = self.path.display();
let mut child = spawn(&mut self.command()).with_context(|| format!("starting {shown}"))?;
match platform::collect(&mut child, self.time_limit) {
Outcome::Done(status, out) => {
ensure!(status.success(), "{shown} failed ({status})");
Ok(out)
}
Outcome::TooMuch => bail!("{shown} printed more than {} KiB", MAX_OUTPUT / 1024),
Outcome::Late => bail!(
"{shown} did not finish within {}s, or something it started kept its output \
open; it was ended",
self.time_limit.as_secs()
),
Outcome::Broken(error) => Err(error).with_context(|| format!("reading {shown}")),
}
}
}
enum Outcome {
Done(std::process::ExitStatus, Zeroizing<Vec<u8>>),
TooMuch,
Late,
Broken(std::io::Error),
}
fn spawn(command: &mut Command) -> std::io::Result<std::process::Child> {
let mut tries = 0;
loop {
match command.spawn() {
Err(e) if e.kind() == std::io::ErrorKind::ExecutableFileBusy && tries < 10 => {
tries += 1;
std::thread::sleep(Duration::from_millis(50));
}
other => return other,
}
}
}
fn program_home(id: &str, home: SecretCommandHome, place: &Place<'_>) -> Result<PathBuf> {
if home == SecretCommandHome::User {
return Ok(PathBuf::from(place.home));
}
let dir = place.state.join("secret-homes").join(id);
crate::home::create_private_dir(&dir)?;
Ok(dir)
}
fn fixed_dir() -> PathBuf {
#[cfg(windows)]
if let Some(root) = std::env::var_os("SystemRoot") {
return PathBuf::from(root);
}
PathBuf::from("/")
}
fn search_path() -> std::ffi::OsString {
let mut dirs: Vec<PathBuf> = Vec::new();
#[cfg(unix)]
dirs.extend(["/usr/bin", "/bin", "/usr/sbin", "/sbin"].map(PathBuf::from));
#[cfg(windows)]
{
if let Some(root) = std::env::var_os("SystemRoot") {
let root = PathBuf::from(root);
dirs.extend([root.join("System32"), root]);
}
}
std::env::join_paths(dirs).unwrap_or_default()
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Json {
value: String,
#[serde(default)]
expires_at: Option<u64>,
#[serde(default)]
expires_in: Option<u64>,
}
pub(super) fn parse(out: &[u8], lifetime: Duration, now: u64) -> Result<Answer> {
let text = std::str::from_utf8(out)
.ok()
.context("the program's output is not UTF-8")?;
let text = text.trim_end_matches(['\r', '\n']);
let (value, said) = if text.trim_start().starts_with('{') {
let json: Json = serde_json::from_str(text).ok().context(
"the program printed JSON that is not {\"value\": …} with an optional \
\"expires_at\" or \"expires_in\"",
)?;
let said = match (json.expires_at, json.expires_in) {
(Some(_), Some(_)) => bail!("the program's JSON has both expires_at and expires_in"),
(Some(at), None) => Some(at.saturating_sub(now)),
(None, Some(secs)) => Some(secs),
(None, None) => None,
};
(Zeroizing::new(json.value), said)
} else {
(Zeroizing::new(text.to_owned()), None)
};
ensure!(!value.is_empty(), "the program printed no value");
ensure!(
!value.chars().any(char::is_control),
"the program's value contains a control character"
);
let lifetime = said.map_or(lifetime, |s| lifetime.min(Duration::from_secs(s)));
ensure!(
lifetime >= MIN_ANSWER,
"the program's value expires in less than {}s",
MIN_ANSWER.as_secs()
);
Ok(Answer {
value,
lifetime,
masked: Vec::new(),
})
}
#[cfg(test)]
mod tests;