use core::fmt;
use std::io;
use std::path::{Path, PathBuf};
#[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";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LogOpen {
AppendCreating,
TruncateExisting,
}
#[cfg(target_os = "linux")]
const CREATE_MODE: u32 = 0o666;
pub(crate) async fn open_log_path(open: LogOpen, path: &Path) -> io::Result<tokio::fs::File> {
#[cfg(target_os = "linux")]
{
open_log_path_as(open, path, crate::server::daemon_uid()).await
}
#[cfg(not(target_os = "linux"))]
{
open_nofollow(open, path).await.map_err(name_the_symlink)
}
}
#[cfg(target_os = "linux")]
async fn open_log_path_as(
open: LogOpen,
path: &Path,
daemon_uid: u32,
) -> io::Result<tokio::fs::File> {
settle(open, path, open_resolving(open, path, daemon_uid).await).await
}
#[cfg(target_os = "linux")]
async fn open_resolving(open: LogOpen, path: &Path, daemon_uid: u32) -> io::Result<std::fs::File> {
use nix::fcntl::OFlag;
use nix::sys::stat::Mode;
let (flags, mode) = match open {
LogOpen::AppendCreating => (
OFlag::O_WRONLY | OFlag::O_APPEND | OFlag::O_CREAT,
Mode::from_bits_truncate(CREATE_MODE),
),
LogOpen::TruncateExisting => (OFlag::O_WRONLY | OFlag::O_TRUNC, Mode::empty()),
};
let flags = flags | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
let path = path.to_path_buf();
tokio::task::spawn_blocking(move || {
let resolved = super::trusted_links::resolve_parent(&path, daemon_uid)?;
crate::sys::open_resolving_no_symlinks(&resolved, flags, mode)
})
.await
.map_err(io::Error::other)?
}
#[cfg(target_os = "linux")]
async fn settle(
open: LogOpen,
path: &Path,
reported: io::Result<std::fs::File>,
) -> io::Result<tokio::fs::File> {
match reported {
Ok(file) => Ok(tokio::fs::File::from_std(file)),
Err(error)
if matches!(
error.raw_os_error(),
Some(nix::libc::ENOSYS | nix::libc::EPERM)
) =>
{
open_nofollow(open, path).await.map_err(name_the_symlink)
}
Err(error) => Err(name_the_symlink(error)),
}
}
async fn open_nofollow(open: LogOpen, path: &Path) -> io::Result<tokio::fs::File> {
let mut options = tokio::fs::OpenOptions::new();
match open {
LogOpen::AppendCreating => options.create(true).append(true),
LogOpen::TruncateExisting => options.write(true).truncate(true),
};
#[cfg(unix)]
options.custom_flags(nix::libc::O_NOFOLLOW);
options.open(path).await
}
#[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)]
pub(super) const ROOT_UID: u32 = 0;
#[cfg(unix)]
pub(super) fn is_trusted_owner(owner: u32, daemon_uid: u32) -> bool {
owner == daemon_uid || owner == ROOT_UID
}
#[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 !is_trusted_owner(meta.uid(), daemon_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,
})
})
}
#[cfg(all(test, unix))]
mod tests {
use std::io;
use super::*;
use crate::testing::capture_logs;
use super::super::testing::*;
#[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 daemon_uid = if me() == ROOT_UID {
use std::os::unix::fs::MetadataExt as _;
std::os::unix::fs::lchown(&link, Some(FOREIGN_UID), None).unwrap();
assert_eq!(
std::fs::symlink_metadata(&link).unwrap().uid(),
FOREIGN_UID,
"lchown must hand over the link itself, not what it points at"
);
ROOT_UID
} else {
me() + 1
};
let loose = loose_ancestor(&log, daemon_uid).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}"
);
}
#[cfg(target_os = "linux")]
async fn open_below_a_symlinked_parent_after(errno: i32) -> (io::Result<()>, bool) {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real");
let link = dir.path().join("logs");
std::fs::create_dir(&real).unwrap();
std::os::unix::fs::symlink(&real, &link).unwrap();
let reported = Err(io::Error::from_raw_os_error(errno));
let opened = settle(LogOpen::AppendCreating, &link.join("web-out.log"), reported)
.await
.map(drop);
(opened, real.join("web-out.log").exists())
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn an_enosys_from_the_resolving_open_falls_back_to_the_nofollow_open() {
let (opened, created) = open_below_a_symlinked_parent_after(nix::libc::ENOSYS).await;
opened.expect("the fallback open must succeed where the resolving one is unavailable");
assert!(
created,
"the fallback is the O_NOFOLLOW open, which follows the parent"
);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn an_eperm_from_the_resolving_open_falls_back_to_the_nofollow_open() {
let (opened, created) = open_below_a_symlinked_parent_after(nix::libc::EPERM).await;
opened.expect("the fallback open must succeed where the resolving one is blocked");
assert!(
created,
"the fallback is the O_NOFOLLOW open, which follows the parent"
);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn any_other_errno_from_the_resolving_open_is_not_retried() {
let (opened, created) = open_below_a_symlinked_parent_after(nix::libc::ELOOP).await;
let error = opened.expect_err("an ELOOP must be reported, not retried");
assert_eq!(error.to_string(), SYMLINK_REFUSED);
assert!(!created, "no file may land below the link");
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn a_symlinked_parent_owned_by_another_user_is_refused_on_linux() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real");
let link = dir.path().join("logs");
std::fs::create_dir(&real).unwrap();
std::os::unix::fs::symlink(&real, &link).unwrap();
let daemon_uid = if me() == ROOT_UID {
std::os::unix::fs::lchown(&link, Some(FOREIGN_UID), None).unwrap();
ROOT_UID
} else {
me() + 1
};
let error = open_log_path_as(
LogOpen::AppendCreating,
&link.join("web-out.log"),
daemon_uid,
)
.await
.expect_err("a link owned by another user must not be followed");
let rendered = error.to_string();
assert!(rendered.starts_with(SYMLINK_REFUSED), "{rendered}");
assert!(rendered.contains(&link.display().to_string()), "{rendered}");
assert_eq!(std::fs::read_dir(&real).unwrap().count(), 0);
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn a_log_path_with_a_trailing_separator_fails_and_creates_no_file() {
let dir = tempfile::tempdir().unwrap();
let mut path = dir.path().join("out").into_os_string();
path.push("/");
let error = open_log_path_as(LogOpen::AppendCreating, Path::new(&path), me())
.await
.expect_err("a path naming a directory must not open as a file");
assert_ne!(error.kind(), io::ErrorKind::NotFound, "{error}");
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
}
}