378 lines
14 KiB
Rust
378 lines
14 KiB
Rust
//! User account configuration.
|
|
//!
|
|
//! Passwords are hashed immediately and only hashes travel to the target.
|
|
//! Plaintext never touches the config, the log or a command line.
|
|
|
|
use std::path::Path;
|
|
|
|
use phoebus_core::{InstallConfig, SecretString};
|
|
|
|
use crate::command::CommandSpec;
|
|
use crate::error::{ExecError, Result};
|
|
use crate::exec::Exec;
|
|
use crate::portage;
|
|
|
|
/// SHA-512 crypt hash via `openssl passwd -6 -stdin`.
|
|
pub fn hash_password(exec: &Exec, password: &SecretString) -> Result<String> {
|
|
let spec = CommandSpec::new("users_configure", "hash password", "openssl")
|
|
.args(["passwd", "-6", "-stdin"])
|
|
.stdin(password.expose().as_bytes().to_vec());
|
|
let out = exec.runner.execute(&spec)?;
|
|
let hash = out.stdout_lossy().trim().to_string();
|
|
if hash.is_empty() {
|
|
return Err(ExecError::operation(
|
|
"users_configure",
|
|
"hash password",
|
|
"empty hash",
|
|
));
|
|
}
|
|
Ok(hash)
|
|
}
|
|
|
|
fn group_exists(root: &Path, group: &str) -> bool {
|
|
let path = root.join("etc/group");
|
|
std::fs::read_to_string(path)
|
|
.map(|text| text.lines().any(|l| l.starts_with(&format!("{group}:"))))
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Create missing supplementary groups and return the subset that exists.
|
|
pub fn ensure_groups(exec: &Exec, root: &Path, groups: &[String]) -> Result<Vec<String>> {
|
|
let mut out = Vec::new();
|
|
for group in groups {
|
|
if group.is_empty() {
|
|
continue;
|
|
}
|
|
if !group_exists(root, group) {
|
|
if let Err(e) = portage::chroot(exec, root, "groupadd", &["-r", group]) {
|
|
exec.logger
|
|
.warn(format!("could not create group {group}: {e}"));
|
|
}
|
|
}
|
|
if group_exists(root, group) {
|
|
out.push(group.clone());
|
|
} else {
|
|
exec.logger
|
|
.warn(format!("group {group} not available; skipping"));
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
pub fn create(
|
|
exec: &Exec,
|
|
config: &InstallConfig,
|
|
user_password: Option<&SecretString>,
|
|
root_password: Option<&SecretString>,
|
|
) -> Result<()> {
|
|
let username = &config.user.username;
|
|
if username.is_empty() {
|
|
return Err(ExecError::operation(
|
|
"users_configure",
|
|
"create user",
|
|
"no username configured",
|
|
));
|
|
}
|
|
let root = Path::new(&exec.root);
|
|
let groups = ensure_groups(exec, root, &config.user.groups)?;
|
|
|
|
// Newly created user accounts get Zsh; root keeps Bash for system
|
|
// administration and `/bin/sh` is never changed (Bash shebangs keep
|
|
// working). The shell binary must exist in the target; otherwise
|
|
// `useradd` would create an unusable account, so fail closed.
|
|
let user_shell = phoebus_core::system::USER_LOGIN_SHELL;
|
|
assert_valid_login_shell(root, user_shell)?;
|
|
|
|
let mut args: Vec<&str> = vec!["-m", "-U", "-s", user_shell, "-c", &config.user.fullname];
|
|
let group_list = groups.join(",");
|
|
if !group_list.is_empty() {
|
|
args.push("-G");
|
|
args.push(&group_list);
|
|
}
|
|
args.push(username);
|
|
portage::chroot(exec, root, "useradd", &args)?;
|
|
|
|
if let Some(password) = user_password {
|
|
if !password.is_empty() {
|
|
let hash = hash_password(exec, password)?;
|
|
let input = format!("{username}:{hash}\n");
|
|
portage::chroot_stdin(exec, root, "chpasswd", &["-e"], input.as_bytes())?;
|
|
exec.logger.info(format!("password set for {username}"));
|
|
}
|
|
} else {
|
|
exec.logger
|
|
.warn(format!("no password set for {username} (account locked)"));
|
|
}
|
|
|
|
match root_password {
|
|
Some(password) if !password.is_empty() => {
|
|
let hash = hash_password(exec, password)?;
|
|
let input = format!("root:{hash}\n");
|
|
portage::chroot_stdin(exec, root, "chpasswd", &["-e"], input.as_bytes())?;
|
|
exec.logger.info("root password set");
|
|
}
|
|
_ => {
|
|
let _ = portage::chroot(exec, root, "passwd", &["-l", "root"]);
|
|
exec.logger
|
|
.info("root account locked (no root password supplied)");
|
|
}
|
|
}
|
|
// Root keeps Bash for administration; never change the user's shell here.
|
|
ensure_root_shell_bash(exec, root)?;
|
|
// Seed the maintained default Zsh configuration for the new user and the
|
|
// skeleton, preserving any existing custom files.
|
|
seed_default_zsh(exec, config)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Fail closed when the requested login shell is missing from the target.
|
|
/// `/bin/sh` is never touched: Bash scripts keep executing through their
|
|
/// shebangs.
|
|
fn assert_valid_login_shell(root: &Path, shell: &str) -> Result<()> {
|
|
let rel = shell.trim_start_matches('/');
|
|
if root.join(rel).exists() {
|
|
return Ok(());
|
|
}
|
|
// The shell package may not have been merged yet in a dry-run or unit
|
|
// context; only enforce when the target already has a `/bin` to check.
|
|
if root.join("bin").exists() || root.join("usr/bin").exists() {
|
|
return Err(ExecError::operation(
|
|
"users_configure",
|
|
"validate login shell",
|
|
format!("login shell {shell} is missing from the target"),
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn ensure_root_shell_bash(exec: &Exec, root: &Path) -> Result<()> {
|
|
// `chsh -s /bin/bash root` keeps root on Bash even if the helper that
|
|
// created the user defaulted elsewhere. Best-effort: a missing `chsh`
|
|
// in a minimal target must not fail the install.
|
|
match portage::chroot(
|
|
exec,
|
|
root,
|
|
"chsh",
|
|
&["-s", phoebus_core::system::ROOT_LOGIN_SHELL, "root"],
|
|
) {
|
|
Ok(()) => exec.logger.info("root login shell is /bin/bash"),
|
|
Err(e) => exec
|
|
.logger
|
|
.warn(format!("could not enforce root shell: {e}")),
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Seed `/etc/skel/.zshrc`, `/etc/zsh/zprofile` and the new user's
|
|
/// `~/.zshrc` from the maintained default, preserving existing custom files.
|
|
fn seed_default_zsh(exec: &Exec, config: &InstallConfig) -> Result<()> {
|
|
let target = exec.target();
|
|
target.write("etc/zsh/zprofile", phoebus_core::system::ZSH_ZPROFILE)?;
|
|
// Skeleton for future users; never overwrite customization.
|
|
if !target.exists("etc/skel/.zshrc") {
|
|
target.write("etc/skel/.zshrc", phoebus_core::system::ZSH_SKEL_RC)?;
|
|
}
|
|
let home_base = config.user.home.trim_end_matches('/');
|
|
// `home` defaults to `/home`, so this resolves to `/home/<user>/.zshrc`.
|
|
let user_rc = format!("{}/{}/.zshrc", home_base, config.user.username);
|
|
if !target.exists(&user_rc) {
|
|
target.write(&user_rc, phoebus_core::system::ZSH_SKEL_RC)?;
|
|
// Ownership is fixed after the user exists (best-effort in chroot).
|
|
let root = Path::new(&exec.root);
|
|
let rel = user_rc.trim_start_matches('/');
|
|
let _ = portage::chroot(
|
|
exec,
|
|
root,
|
|
"chown",
|
|
&[
|
|
&format!("{}:{}", config.user.username, config.user.username),
|
|
&format!("/{rel}"),
|
|
],
|
|
);
|
|
} else {
|
|
exec.logger
|
|
.info("preserved existing user .zshrc (no overwrite)");
|
|
}
|
|
let _ = user_rc;
|
|
exec.logger
|
|
.info("seeded default Zsh configuration (packaged plugins only)");
|
|
Ok(())
|
|
}
|
|
|
|
pub fn configure_sudo(exec: &Exec) -> Result<()> {
|
|
let target = exec.target();
|
|
target.write(
|
|
"etc/sudoers.d/10-wheel",
|
|
"# Members of the wheel group may run commands as root.\n%wheel ALL=(ALL:ALL) ALL\n",
|
|
)?;
|
|
let path = target.etc("sudoers.d/10-wheel")?;
|
|
use std::os::unix::fs::PermissionsExt;
|
|
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o440))
|
|
.map_err(|e| ExecError::io(path.clone(), e))?;
|
|
let root = Path::new(&exec.root);
|
|
if root.join("usr/sbin/visudo").exists() || root.join("sbin/visudo").exists() {
|
|
portage::chroot(exec, root, "visudo", &["-cf", "/etc/sudoers.d/10-wheel"])?;
|
|
}
|
|
exec.logger.info("sudo configured for wheel");
|
|
Ok(())
|
|
}
|
|
|
|
/// Use the same administrator group for desktop authentication as for sudo.
|
|
/// Gentoo's default polkit administrator identity is root, which cannot
|
|
/// authenticate when the installer leaves the root account locked.
|
|
pub fn configure_polkit_admin(exec: &Exec) -> Result<()> {
|
|
let target = exec.target();
|
|
target.ensure_dir_mode("etc/polkit-1", 0o755)?;
|
|
target.ensure_dir_mode("etc/polkit-1/rules.d", 0o755)?;
|
|
let path = target.write(
|
|
"etc/polkit-1/rules.d/49-phoebus-wheel-admin.rules",
|
|
"polkit.addAdminRule(function(action, subject) {\n return [\"unix-group:wheel\"];\n});\n",
|
|
)?;
|
|
use std::os::unix::fs::PermissionsExt;
|
|
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644))
|
|
.map_err(|e| ExecError::io(path, e))?;
|
|
exec.logger
|
|
.info("polkit administrator group configured as wheel");
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::command::{CommandOutput, RecordingRunner};
|
|
use crate::log::Logger;
|
|
use phoebus_core::Redactor;
|
|
|
|
fn make_exec(runner: RecordingRunner) -> Exec {
|
|
let path = tempfile::tempdir().unwrap().keep();
|
|
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
|
|
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
|
|
}
|
|
|
|
#[test]
|
|
fn password_hash_goes_over_stdin() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response(
|
|
"openssl",
|
|
CommandOutput {
|
|
status: 0,
|
|
success: true,
|
|
stdout: b"$6$abc$hash\n".to_vec(),
|
|
stderr: Vec::new(),
|
|
duration: std::time::Duration::from_millis(1),
|
|
},
|
|
);
|
|
let exec = make_exec(runner.clone());
|
|
let secret = SecretString::new("pw");
|
|
let hash = hash_password(&exec, &secret).unwrap();
|
|
assert_eq!(hash, "$6$abc$hash");
|
|
let spec = &runner.recorded()[0];
|
|
assert!(!spec.args.iter().any(|a| a.contains("pw")));
|
|
assert_eq!(spec.stdin.as_deref(), Some(b"pw".as_slice()));
|
|
}
|
|
|
|
#[test]
|
|
fn ensure_groups_creates_missing() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
// No /etc/group present -> groupadd attempted, then still missing ->
|
|
// excluded from the returned list.
|
|
let groups = vec!["render".to_string()];
|
|
let out = ensure_groups(&exec, Path::new(&exec.root), &groups).unwrap();
|
|
assert!(out.is_empty());
|
|
assert!(runner.programs().iter().any(|p| p == "chroot"));
|
|
}
|
|
|
|
#[test]
|
|
fn new_users_get_zsh_and_root_stays_on_bash() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response(
|
|
"openssl",
|
|
CommandOutput {
|
|
status: 0,
|
|
success: true,
|
|
stdout: b"$6$abc$hash\n".to_vec(),
|
|
stderr: Vec::new(),
|
|
duration: std::time::Duration::from_millis(1),
|
|
},
|
|
);
|
|
let exec = make_exec(runner.clone());
|
|
let mut cfg = InstallConfig::default();
|
|
cfg.user.username = "ada".into();
|
|
cfg.user.fullname = "Ada".into();
|
|
create(&exec, &cfg, None, None).unwrap();
|
|
let recorded: Vec<String> = runner.recorded().iter().map(|s| s.args.join(" ")).collect();
|
|
// New user gets /bin/zsh; root is forced back to /bin/bash.
|
|
assert!(
|
|
recorded
|
|
.iter()
|
|
.any(|a| a.contains("useradd") && a.contains("/bin/zsh")),
|
|
"{recorded:?}"
|
|
);
|
|
assert!(
|
|
recorded
|
|
.iter()
|
|
.any(|a| a.contains("chsh") && a.contains("/bin/bash")),
|
|
"{recorded:?}"
|
|
);
|
|
// No /bin/sh change is ever attempted.
|
|
assert!(
|
|
!recorded
|
|
.iter()
|
|
.any(|a| a.contains("/bin/sh") && a.contains("ln")),
|
|
"{recorded:?}"
|
|
);
|
|
// Default Zsh config is seeded for skel and the new user (packaged only).
|
|
let skel = std::fs::read_to_string(exec.root.join("etc/skel/.zshrc")).unwrap();
|
|
assert!(skel.contains("compinit"));
|
|
assert!(skel.contains("zsh-autosuggestions"));
|
|
let user_rc = std::fs::read_to_string(exec.root.join("home/ada/.zshrc")).unwrap();
|
|
assert!(user_rc.contains("up-line-or-beginning-search"));
|
|
// Login shells bridge Gentoo's /etc/profile (env-update, Nix).
|
|
let zprofile = std::fs::read_to_string(exec.root.join("etc/zsh/zprofile")).unwrap();
|
|
assert!(zprofile.contains("source /etc/profile"));
|
|
}
|
|
|
|
#[test]
|
|
fn existing_user_shell_files_are_preserved() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response(
|
|
"openssl",
|
|
CommandOutput {
|
|
status: 0,
|
|
success: true,
|
|
stdout: b"$6$abc$hash\n".to_vec(),
|
|
stderr: Vec::new(),
|
|
duration: std::time::Duration::from_millis(1),
|
|
},
|
|
);
|
|
let exec = make_exec(runner.clone());
|
|
std::fs::create_dir_all(exec.root.join("home/ada")).unwrap();
|
|
std::fs::write(exec.root.join("home/ada/.zshrc"), "# custom\n").unwrap();
|
|
let mut cfg = InstallConfig::default();
|
|
cfg.user.username = "ada".into();
|
|
create(&exec, &cfg, None, None).unwrap();
|
|
assert_eq!(
|
|
std::fs::read_to_string(exec.root.join("home/ada/.zshrc")).unwrap(),
|
|
"# custom\n"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn polkit_uses_wheel_for_admin_authentication() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
|
|
let exec = make_exec(RecordingRunner::new());
|
|
configure_polkit_admin(&exec).unwrap();
|
|
let path = exec
|
|
.root
|
|
.join("etc/polkit-1/rules.d/49-phoebus-wheel-admin.rules");
|
|
let rule = std::fs::read_to_string(&path).unwrap();
|
|
assert!(rule.contains("polkit.addAdminRule"));
|
|
assert!(rule.contains("unix-group:wheel"));
|
|
assert_eq!(
|
|
std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
|
|
0o644
|
|
);
|
|
}
|
|
}
|