187 lines
6.2 KiB
Rust
187 lines
6.2 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)?;
|
|
|
|
let mut args: Vec<&str> = vec![
|
|
"-m",
|
|
"-U",
|
|
"-s",
|
|
&config.system.root_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)");
|
|
}
|
|
}
|
|
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(())
|
|
}
|
|
|
|
#[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"));
|
|
}
|
|
}
|