use core::fmt;
use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};
use tokio::sync::{mpsc, oneshot};
use shep_core::signals::OperatorSignal;
use crate::channel::{ChildMessage, ShepherdMessage};
use crate::privilege::Credentials;
#[cfg(unix)]
pub use crate::handover::reap::AdoptedReaper;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExitOutcome {
pub code: Option<i32>,
pub signal: Option<i32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopSignal {
Term,
Int,
Quit,
Usr2,
Kill,
}
impl StopSignal {
#[must_use]
pub fn as_raw(self) -> i32 {
match self {
Self::Term => 15,
Self::Int => 2,
Self::Quit => 3,
Self::Usr2 => 12,
Self::Kill => 9,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogLine {
pub err: bool,
pub line: String,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum LogCtl {
Reopen {
done: oneshot::Sender<Result<(), ReopenError>>,
},
Flush {
done: oneshot::Sender<Result<(), FlushError>>,
},
#[cfg(unix)]
ReportFds {
done: oneshot::Sender<crate::handover::CarriedFds>,
},
#[cfg(unix)]
Resume,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReopenError {
pub message: String,
}
impl fmt::Display for ReopenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "could not reopen {}", self.message)
}
}
impl core::error::Error for ReopenError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlushError {
pub message: String,
}
impl fmt::Display for FlushError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "could not flush {}", self.message)
}
}
impl core::error::Error for FlushError {}
#[cfg_attr(windows, allow(dead_code))]
pub(crate) const SYMLINK_REFUSED: &str = "refusing to follow a symlink at this log path; shep \
opens log files with O_NOFOLLOW, so point out_file/err_file at the real file";
pub(crate) async fn open_log_path(
options: &mut tokio::fs::OpenOptions,
path: &Path,
) -> io::Result<tokio::fs::File> {
#[cfg(unix)]
options.custom_flags(nix::libc::O_NOFOLLOW);
options.open(path).await.map_err(name_the_symlink)
}
#[cfg(unix)]
fn name_the_symlink(error: io::Error) -> io::Error {
if error.raw_os_error() == Some(nix::libc::ELOOP) {
io::Error::new(error.kind(), SYMLINK_REFUSED)
} else {
error
}
}
#[cfg(not(unix))]
fn name_the_symlink(error: io::Error) -> io::Error {
error
}
pub(crate) fn check_log_ancestry(path: &Path) -> io::Result<()> {
#[cfg(unix)]
{
check_log_ancestry_as(path, crate::server::daemon_uid())
}
#[cfg(not(unix))]
{
let _ = path;
Ok(())
}
}
#[cfg(unix)]
const ROOT_UID: u32 = 0;
#[cfg(unix)]
const WORLD_WRITABLE: u32 = 0o002;
#[cfg(unix)]
static WARNED_LOOSE_LOG_PATHS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashSet<PathBuf>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));
#[cfg(unix)]
fn check_log_ancestry_as(path: &Path, daemon_uid: u32) -> io::Result<()> {
let Some(loose) = loose_ancestor(path, daemon_uid) else {
return Ok(());
};
if daemon_uid == ROOT_UID {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"refusing to open a log file below {}, which {}; a shepherd running as root \
writes only below directories its own user owns",
loose.path.display(),
loose.reason,
),
));
}
let first_time = WARNED_LOOSE_LOG_PATHS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(path.to_path_buf());
if first_time {
tracing::warn!(
path = %path.display(),
ancestor = %loose.path.display(),
reason = %loose.reason,
"log path sits below a directory another local user could redirect; a shepherd \
running as root would refuse to open it"
);
}
Ok(())
}
#[cfg(unix)]
#[derive(Debug, Clone, PartialEq, Eq)]
struct LooseAncestor {
path: PathBuf,
reason: LooseReason,
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LooseReason {
ForeignOwner(u32),
WorldWritable,
}
#[cfg(unix)]
impl fmt::Display for LooseReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ForeignOwner(uid) => write!(f, "is owned by uid {uid}"),
Self::WorldWritable => f.write_str("is world-writable"),
}
}
}
#[cfg(unix)]
fn loose_ancestor(path: &Path, daemon_uid: u32) -> Option<LooseAncestor> {
use std::os::unix::fs::MetadataExt as _;
path.parent()?
.ancestors()
.filter_map(|ancestor| Some((ancestor, std::fs::symlink_metadata(ancestor).ok()?)))
.find_map(|(ancestor, meta)| {
let reason = if meta.uid() != daemon_uid && meta.uid() != ROOT_UID {
LooseReason::ForeignOwner(meta.uid())
} else if meta.is_dir() && meta.mode() & WORLD_WRITABLE != 0 {
LooseReason::WorldWritable
} else {
return None;
};
Some(LooseAncestor {
path: ancestor.to_path_buf(),
reason,
})
})
}
#[derive(Debug)]
pub struct ProcIo {
pub logs: mpsc::Receiver<LogLine>,
pub from_child: mpsc::Receiver<ChildMessage>,
pub to_child: mpsc::Sender<ShepherdMessage>,
pub log_ctl: mpsc::Sender<LogCtl>,
pub to_stdin: mpsc::Sender<StdinWrite>,
}
#[derive(Debug)]
pub struct StdinWrite {
pub line: String,
pub done: oneshot::Sender<Result<(), RunnerError>>,
}
pub trait RunningProcess: Send + 'static {
fn pid(&self) -> u32;
fn wait(&mut self) -> impl core::future::Future<Output = ExitOutcome> + Send;
fn signal(&mut self, sig: StopSignal) -> Result<(), RunnerError>;
fn signal_process(&mut self, sig: OperatorSignal) -> Result<(), RunnerError> {
let _ = sig;
Err(RunnerError::SignalFailed(
"this runner cannot signal a single process".to_string(),
))
}
fn kill_tree(&mut self) -> Result<(), RunnerError>;
}
pub trait ProcessRunner: Send + Sync + 'static {
type Proc: RunningProcess;
fn spawn(&self, spec: &SpawnSpec) -> Result<(Self::Proc, ProcIo), RunnerError>;
#[must_use]
fn preflight(&self, spec: &SpawnSpec) -> Preflight {
let _ = spec;
Preflight::Unknown
}
#[cfg(unix)]
fn adopt(&self, spec: AdoptSpec) -> Result<(Self::Proc, ProcIo), RunnerError> {
let _ = spec;
Err(RunnerError::AdoptFailed(
"this runner cannot adopt a process it did not spawn".to_string(),
))
}
}
#[cfg(unix)]
#[derive(Debug)]
pub struct AdoptSpec {
pub pid: u32,
pub out_file: PathBuf,
pub err_file: PathBuf,
pub out_pipe: Option<tokio::net::unix::pipe::Receiver>,
pub err_pipe: Option<tokio::net::unix::pipe::Receiver>,
pub out_log: Option<tokio::fs::File>,
pub err_log: Option<tokio::fs::File>,
pub stdin_pipe: Option<tokio::net::unix::pipe::Sender>,
pub channel: Option<tokio::net::UnixStream>,
pub reaper: std::sync::Arc<AdoptedReaper>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Preflight {
Unknown,
Impossible(String),
Doubtful(String),
}
#[derive(Clone, PartialEq, Eq)]
pub struct SpawnSpec {
pub name: String,
pub program: String,
pub args: Vec<String>,
pub cwd: Option<PathBuf>,
pub env: BTreeMap<String, String>,
pub out_file: PathBuf,
pub err_file: PathBuf,
pub channel: bool,
pub stdin: bool,
pub credentials: Option<Credentials>,
}
impl fmt::Debug for SpawnSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SpawnSpec")
.field("name", &self.name)
.field("program", &self.program)
.field("args", &format_args!("<{} args>", self.args.len()))
.field("cwd", &self.cwd)
.field("env", &format_args!("<{} vars>", self.env.len()))
.finish_non_exhaustive()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunnerError {
SpawnFailed(String),
SignalFailed(String),
WriteFailed(String),
AdoptFailed(String),
}
impl fmt::Display for RunnerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SpawnFailed(msg) => write!(f, "process spawn failed: {msg}"),
Self::SignalFailed(msg) => write!(f, "signal delivery failed: {msg}"),
Self::WriteFailed(msg) => write!(f, "stdin write failed: {msg}"),
Self::AdoptFailed(msg) => write!(f, "process adoption failed: {msg}"),
}
}
}
impl core::error::Error for RunnerError {}
#[cfg(all(test, unix))]
mod tests {
use std::os::unix::fs::PermissionsExt as _;
use super::*;
use crate::testing::capture_logs;
const FOREIGN_UID: u32 = 65_432;
fn me() -> u32 {
nix::unistd::geteuid().as_raw()
}
fn log_path_under(dir: &tempfile::TempDir, mode: u32) -> (PathBuf, PathBuf) {
let parent = dir.path().join("logs");
std::fs::create_dir(&parent).unwrap();
std::fs::set_permissions(&parent, std::fs::Permissions::from_mode(mode)).unwrap();
let log = parent.join("web-0-out.log");
(parent, log)
}
#[test]
fn the_nearest_loose_ancestor_is_the_one_reported() {
let dir = tempfile::tempdir().unwrap();
let (parent, log) = log_path_under(&dir, 0o777);
assert_eq!(
loose_ancestor(&log, me()),
Some(LooseAncestor {
path: parent,
reason: LooseReason::WorldWritable,
})
);
}
#[test]
fn an_ancestor_owned_by_another_user_is_loose_however_tight_its_mode() {
let dir = tempfile::tempdir().unwrap();
let (parent, log) = log_path_under(&dir, 0o700);
let (daemon_uid, owner) = if me() == ROOT_UID {
std::os::unix::fs::chown(&parent, Some(FOREIGN_UID), None).unwrap();
(ROOT_UID, FOREIGN_UID)
} else {
(me() + 1, me())
};
assert_eq!(
loose_ancestor(&log, daemon_uid),
Some(LooseAncestor {
path: parent,
reason: LooseReason::ForeignOwner(owner),
})
);
}
#[test]
fn a_symlinked_component_is_judged_as_the_link_not_as_its_target() {
let dir = tempfile::tempdir().unwrap();
let link = dir.path().join("logs");
std::os::unix::fs::symlink("/usr", &link).unwrap();
let log = link.join("web-0-out.log");
let loose = loose_ancestor(&log, me() + 1).expect("a foreign-owned component is loose");
assert_eq!(
loose.path,
link,
"the link itself must be judged, not what it resolves to: blaming {} means the \
walk followed it",
loose.path.display()
);
}
#[test]
fn a_root_shepherd_refuses_where_an_unprivileged_one_warns_once() {
let dir = tempfile::tempdir().unwrap();
let (parent, log) = log_path_under(&dir, 0o777);
let refused = check_log_ancestry_as(&log, ROOT_UID)
.expect_err("a root shepherd must not open a log below a loose ancestor");
assert_eq!(refused.kind(), io::ErrorKind::PermissionDenied);
assert!(
refused.to_string().contains(&parent.display().to_string()),
"the refusal must name the ancestor an operator has to fix: {refused}"
);
let unprivileged = me() + 1;
let rendered = capture_logs(|| {
assert_eq!(check_log_ancestry_as(&log, unprivileged).ok(), Some(()));
assert_eq!(check_log_ancestry_as(&log, unprivileged).ok(), Some(()));
});
assert_eq!(
rendered.matches("log path sits below").count(),
1,
"an unprivileged shepherd warns once per path, not once per open: {rendered}"
);
}
#[test]
fn debug_redacts_env_values_and_args() {
let mut spec = SpawnSpec {
name: "web".to_string(),
program: "./srv".to_string(),
args: vec!["--token=sk-live-abc".to_string(), "--port=8080".to_string()],
cwd: None,
env: BTreeMap::new(),
out_file: PathBuf::from("/tmp/web-out.log"),
err_file: PathBuf::from("/tmp/web-err.log"),
channel: false,
stdin: false,
credentials: None,
};
spec.env.insert(
"DATABASE_URL".to_string(),
"postgres://user:hunter2@db".to_string(),
);
spec.env
.insert("API_KEY".to_string(), "sk-live-abc".to_string());
assert_eq!(
format!("{spec:?}"),
"SpawnSpec { name: \"web\", program: \"./srv\", args: <2 args>, cwd: None, \
env: <2 vars>, .. }"
);
}
}