phoebus_os/installer-rs/crates/phoebus-executor/src/personal.rs

542 lines
19 KiB
Rust

//! Per-user, unprivileged storage and initiating-user resolution.
//!
//! Personal package preferences and proactive-alert state are user data, not
//! system policy. They must be writable by a normal desktop account without
//! touching `/etc` or `/var/lib`, while system-wide defaults stay root-owned and
//! are only changed through an authenticated typed action.
//!
//! Three problems are solved here:
//!
//! 1. **Where** personal state lives: `<home>/.config/phoebus/` and
//! `<home>/.local/state/phoebus/`, each created 0700 and written 0600
//! atomically. `PHOEBUS_PERSONAL_DIR` overrides the base for tests.
//! 2. **Whose** state it is: when `sys` runs under `sudo`/`pkexec`, the
//! effective uid is root but the preferences belong to the invoking user.
//! [`initiating_uid`] resolves `PHOEBUS_UID` → `SUDO_UID` → `PKEXEC_UID` →
//! the real/effective uid, and [`UserStorage::for_uid`] resolves that user's
//! home from `/etc/passwd` rather than trusting `$HOME` (which `sudo` sets to
//! root's).
//! 3. **Ownership**: when the write runs elevated (effective root on behalf of a
//! non-root initiating user), the created directories and file are chowned
//! to the *initiating* user's uid/gid so the setting stays readable and
//! replaceable by that user. A non-root process that is not the initiating
//! user refuses to write. Paths are created component by component, reject
//! symlinks, and must stay within the resolved home, so a planted symlink
//! cannot redirect the write.
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use crate::error::{ExecError, Result};
/// The uid that initiated the command, honouring the elevation wrappers so the
/// CLI and GUI resolve the same user's storage.
pub fn initiating_uid() -> u32 {
for var in ["PHOEBUS_UID", "SUDO_UID", "PKEXEC_UID"] {
if let Ok(value) = std::env::var(var) {
if let Ok(uid) = value.trim().parse::<u32>() {
return uid;
}
}
}
effective_uid()
}
pub fn effective_uid() -> u32 {
// Read the effective uid from /proc without unsafe or a subprocess. The
// second field of `Uid:` is the effective uid.
if let Ok(status) = std::fs::read_to_string("/proc/self/status") {
for line in status.lines() {
if let Some(rest) = line.strip_prefix("Uid:") {
if let Some(effective) = rest.split_whitespace().nth(1) {
if let Ok(uid) = effective.parse::<u32>() {
return uid;
}
}
}
}
}
std::process::Command::new("id")
.arg("-u")
.output()
.ok()
.and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok())
.unwrap_or(1)
}
/// Look up a user's home directory from the passwd database. `$HOME` is not
/// trusted because `sudo`/`pkexec` rewrite it.
pub fn home_for_uid(uid: u32) -> Option<PathBuf> {
passwd_entry(uid).map(|(_, home)| home)
}
/// The user's primary group id, from the passwd database.
pub fn primary_gid_for_uid(uid: u32) -> Option<u32> {
let text = std::fs::read_to_string("/etc/passwd").ok()?;
for line in text.lines() {
let fields: Vec<&str> = line.split(':').collect();
if fields.len() >= 6 {
if let Ok(line_uid) = fields[2].parse::<u32>() {
if line_uid == uid {
return fields[3].parse::<u32>().ok();
}
}
}
}
None
}
fn passwd_entry(uid: u32) -> Option<(u32, PathBuf)> {
let text = std::fs::read_to_string("/etc/passwd").ok()?;
for line in text.lines() {
let fields: Vec<&str> = line.split(':').collect();
if fields.len() >= 6 {
if let Ok(line_uid) = fields[2].parse::<u32>() {
if line_uid == uid && !fields[5].trim().is_empty() {
return Some((line_uid, PathBuf::from(fields[5].trim())));
}
}
}
}
None
}
/// The identity that should own a user's personal files, plus the effective uid
/// of the writing process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ownership {
/// The initiating user that should own the files.
pub uid: u32,
/// The initiating user's primary gid (best effort; falls back to the uid).
pub gid: u32,
/// The effective uid of this process.
pub euid: u32,
}
impl Ownership {
pub fn for_uid(uid: u32) -> Self {
Self {
uid,
gid: primary_gid_for_uid(uid).unwrap_or(uid),
euid: effective_uid(),
}
}
/// A non-root process that is not the initiating user must not write user
/// data on their behalf.
pub fn may_write(self) -> bool {
self.euid == self.uid || self.euid == 0
}
/// Whether the created paths must be chowned to the initiating user. Only
/// root can do this.
pub fn needs_fix(self) -> bool {
self.euid == 0 && self.uid != 0
}
}
/// Chowns a freshly created path to the initiating user. Abstracted so the
/// ownership logic can be tested without requiring root.
pub trait OwnerFixer {
fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()>;
}
/// The production fixer: `chown(2)` via the standard library.
pub struct RealOwnerFixer;
impl OwnerFixer for RealOwnerFixer {
fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()> {
std::os::unix::fs::chown(path, Some(uid), Some(gid))
}
}
/// A resolved, user-owned storage location.
#[derive(Debug, Clone)]
pub struct UserStorage {
uid: u32,
base: PathBuf,
}
impl UserStorage {
/// Storage for a specific uid. `PHOEBUS_PERSONAL_DIR` overrides everything
/// (used by tests and by a caller that already resolved the user's home).
pub fn for_uid(uid: u32) -> Self {
if let Ok(dir) = std::env::var("PHOEBUS_PERSONAL_DIR") {
return Self {
uid,
base: PathBuf::from(dir),
};
}
let home = home_for_uid(uid).or_else(|| std::env::var_os("HOME").map(PathBuf::from));
let base = home.unwrap_or_else(|| PathBuf::from(format!("/tmp/phoebus-user-{uid}")));
Self { uid, base }
}
/// Storage for the user who invoked the command (through sudo/pkexec).
pub fn for_initiating_user() -> Self {
Self::for_uid(initiating_uid())
}
/// An explicit base directory, for tests and callers that already resolved
/// the user's home.
pub fn with_base(uid: u32, base: impl Into<PathBuf>) -> Self {
Self {
uid,
base: base.into(),
}
}
pub fn uid(&self) -> u32 {
self.uid
}
pub fn base(&self) -> &Path {
&self.base
}
/// The 0700 config directory for this user.
pub fn config_dir(&self) -> PathBuf {
self.base.join(".config/phoebus")
}
/// The 0700 state directory for this user.
pub fn state_dir(&self) -> PathBuf {
self.base.join(".local/state/phoebus")
}
pub fn config_file(&self, name: &str) -> PathBuf {
self.config_dir().join(name)
}
pub fn state_file(&self, name: &str) -> PathBuf {
self.state_dir().join(name)
}
/// Atomically write a 0600 file inside the given (0700) directory, owned by
/// the initiating user.
pub fn write_private(&self, dir: &Path, file: &Path, bytes: &[u8]) -> Result<()> {
let ownership = Ownership::for_uid(self.uid);
self.write_private_as(dir, file, bytes, ownership, &RealOwnerFixer)
}
/// Explicit-ownership variant, used by tests to exercise the elevated path
/// and the ownership fixer without requiring root.
pub(crate) fn write_private_as(
&self,
dir: &Path,
file: &Path,
bytes: &[u8],
ownership: Ownership,
fixer: &dyn OwnerFixer,
) -> Result<()> {
if !ownership.may_write() {
return Err(ExecError::operation(
"personal",
"write",
format!(
"refusing to write uid {} personal data as effective uid {}",
ownership.uid, ownership.euid
),
));
}
// The file must live directly inside the target directory and both must
// be within the resolved base, so a caller cannot redirect the write.
if file.parent() != Some(dir) {
return Err(ExecError::operation(
"personal",
"write",
"the destination file is not inside the target directory",
));
}
if !self.is_within_base(dir) || !self.is_within_base(file) {
return Err(ExecError::operation(
"personal",
"write",
"refusing to write outside the user's own storage",
));
}
self.create_dir_chain(dir, ownership, fixer)?;
// After creating the chain, verify the canonical directory has not
// escaped the base through a symlink.
let base =
std::fs::canonicalize(&self.base).map_err(|e| ExecError::io(self.base.clone(), e))?;
let dir_canon =
std::fs::canonicalize(dir).map_err(|e| ExecError::io(dir.to_path_buf(), e))?;
if !dir_canon.starts_with(&base) {
return Err(ExecError::operation(
"personal",
"write",
"the destination directory resolves outside the user's storage (symlink?)",
));
}
let tmp = dir.join(format!(".{}.tmp", tmp_token()));
{
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let mut fh = opts.open(&tmp).map_err(|e| ExecError::io(tmp.clone(), e))?;
fh.write_all(bytes)
.and_then(|_| fh.flush())
.and_then(|_| fh.sync_all())
.map_err(|e| ExecError::io(tmp.clone(), e))?;
}
if ownership.needs_fix() {
fixer
.fix(&tmp, ownership.uid, ownership.gid)
.map_err(|e| ExecError::io(tmp.clone(), e))?;
}
std::fs::rename(&tmp, file).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
ExecError::io(file.to_path_buf(), e)
})?;
if ownership.needs_fix() {
// rename preserves ownership; this also repairs a pre-existing file
// that was created root-owned by an older, buggy writer.
fixer
.fix(file, ownership.uid, ownership.gid)
.map_err(|e| ExecError::io(file.to_path_buf(), e))?;
}
if let Ok(dir) = std::fs::File::open(dir) {
let _ = dir.sync_all();
}
Ok(())
}
/// Lexical containment check: `path` must be `base` or below it.
fn is_within_base(&self, path: &Path) -> bool {
path.starts_with(&self.base)
}
/// Create `dir` component by component beneath `base`, rejecting symlinks
/// and non-directories, setting 0700, and chowning to the initiating user
/// when this process is elevated.
fn create_dir_chain(
&self,
dir: &Path,
ownership: Ownership,
fixer: &dyn OwnerFixer,
) -> Result<()> {
let meta = std::fs::symlink_metadata(&self.base)
.map_err(|e| ExecError::io(self.base.clone(), e))?;
if meta.file_type().is_symlink() || !meta.is_dir() {
return Err(ExecError::operation(
"personal",
"write",
"the user's home is not a real directory",
));
}
let rel = dir.strip_prefix(&self.base).map_err(|_| {
ExecError::operation(
"personal",
"write",
"the destination is not within the user's home",
)
})?;
let mut cur = self.base.clone();
for component in rel.components() {
let Component::Normal(name) = component else {
return Err(ExecError::operation(
"personal",
"write",
"the destination contains an unsafe path component",
));
};
cur = cur.join(name);
match std::fs::symlink_metadata(&cur) {
Ok(meta) if meta.file_type().is_symlink() => {
return Err(ExecError::operation(
"personal",
"write",
"refusing to follow a symlink while creating user storage",
));
}
Ok(meta) if meta.is_dir() => {
if ownership.needs_fix() {
// Repair (or confirm) ownership of an existing dir.
let _ = fixer.fix(&cur, ownership.uid, ownership.gid);
}
}
Ok(_) => {
return Err(ExecError::operation(
"personal",
"write",
"a path component of the user storage is not a directory",
));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
std::fs::create_dir(&cur).map_err(|e| ExecError::io(cur.clone(), e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&cur, std::fs::Permissions::from_mode(0o700))
.map_err(|e| ExecError::io(cur.clone(), e))?;
}
if ownership.needs_fix() {
fixer
.fix(&cur, ownership.uid, ownership.gid)
.map_err(|e| ExecError::io(cur.clone(), e))?;
}
}
Err(e) => return Err(ExecError::io(cur.clone(), e)),
}
}
Ok(())
}
}
fn tmp_token() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
format!("{nanos}-{}", std::process::id())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
/// Records ownership changes instead of performing them (the test process is
/// not root, so a real chown would fail).
#[derive(Default)]
struct RecordingFixer {
calls: RefCell<Vec<(PathBuf, u32, u32)>>,
}
impl OwnerFixer for RecordingFixer {
fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()> {
self.calls.borrow_mut().push((path.to_path_buf(), uid, gid));
Ok(())
}
}
#[test]
fn write_private_is_0600_inside_0700() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(effective_uid(), dir.path());
let cfg = storage.config_dir();
let file = storage.config_file("x.toml");
storage.write_private(&cfg, &file, b"a = 1").unwrap();
assert_eq!(
std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
0o600
);
assert_eq!(
std::fs::metadata(&cfg).unwrap().permissions().mode() & 0o777,
0o700
);
assert_eq!(std::fs::read(&file).unwrap(), b"a = 1");
}
#[test]
fn elevated_write_is_chowned_to_the_initiating_user() {
let dir = tempfile::tempdir().unwrap();
// Simulate `sudo sys`: effective root writing on behalf of a non-root
// initiating user.
let owner_uid = effective_uid() + 1;
let storage = UserStorage::with_base(owner_uid, dir.path());
let cfg = storage.config_dir();
let file = storage.config_file("prefs.toml");
let fixer = RecordingFixer::default();
storage
.write_private_as(
&cfg,
&file,
b"a = 1",
Ownership {
uid: owner_uid,
gid: owner_uid,
euid: 0,
},
&fixer,
)
.unwrap();
// The created config directory and the file were both handed to the
// initiating user, and only under that user's home.
let calls = fixer.calls.borrow();
assert!(
calls.iter().any(|(p, _, _)| p == &file),
"the file must be chowned: {calls:?}"
);
assert!(
calls.iter().any(|(p, _, _)| p == &cfg),
"the config directory must be chowned: {calls:?}"
);
assert!(
calls.iter().all(|(p, uid, gid)| p.starts_with(dir.path())
&& *uid == owner_uid
&& *gid == owner_uid),
"only paths under the home may be chowned, to the initiating user: {calls:?}"
);
// The file is readable afterwards. (A real cross-uid chown requires
// root, so the recording fixer verifies intent rather than effect.)
assert_eq!(std::fs::read(&file).unwrap(), b"a = 1");
}
#[test]
fn a_written_personal_file_is_replaceable_by_its_owner() {
let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(effective_uid(), dir.path());
let cfg = storage.config_dir();
let file = storage.config_file("x.toml");
storage.write_private(&cfg, &file, b"a = 1").unwrap();
assert_eq!(std::fs::read(&file).unwrap(), b"a = 1");
// The owner can replace it again (atomic overwrite).
storage.write_private(&cfg, &file, b"a = 2").unwrap();
assert_eq!(std::fs::read(&file).unwrap(), b"a = 2");
}
#[test]
fn a_non_root_process_cannot_write_for_another_user() {
let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(effective_uid(), dir.path());
let cfg = storage.config_dir();
let file = storage.config_file("x.toml");
let err = storage
.write_private_as(
&cfg,
&file,
b"a = 1",
Ownership {
uid: effective_uid() + 1,
gid: effective_uid() + 1,
euid: effective_uid(),
},
&RecordingFixer::default(),
)
.unwrap_err();
assert!(err.to_string().contains("refusing to write"), "{err}");
assert!(!file.exists());
}
#[test]
fn a_symlinked_component_is_refused() {
let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(effective_uid(), dir.path());
// Plant a symlink where the config directory should be.
let outside = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink(outside.path(), dir.path().join(".config")).unwrap();
let cfg = storage.config_dir();
let file = storage.config_file("x.toml");
let err = storage.write_private(&cfg, &file, b"a = 1").unwrap_err();
assert!(err.to_string().contains("symlink"), "{err}");
assert!(!outside.path().join("phoebus/x.toml").exists());
}
#[test]
fn initiator_env_resolution_order() {
let storage = UserStorage::for_uid(4242);
assert_eq!(storage.uid(), 4242);
}
}