use crate::error::{Error, Result};
use crate::jail::{jail_attach, jail_getid};
use std::ffi::CString;
use std::os::unix::process::ExitStatusExt;
use std::process::{Command, ExitStatus, Stdio};
#[derive(Debug, Clone)]
pub struct ExecOptions {
pub user: String,
pub workdir: Option<String>,
pub env: Vec<(String, String)>,
pub clear_env: bool,
}
impl Default for ExecOptions {
fn default() -> Self {
Self {
user: "root".to_string(),
workdir: None,
env: Vec::new(),
clear_env: false,
}
}
}
pub fn exec_in_jail(jail: &str, command: &[String], opts: &ExecOptions) -> Result<ExitStatus> {
let jid = jail_getid(jail)?;
let mut cmd = Command::new("/usr/sbin/jexec");
cmd.arg("-u").arg(&opts.user);
cmd.arg(jid.to_string());
if command.is_empty() {
cmd.arg("/bin/sh");
} else {
cmd.args(command);
}
if let Some(ref workdir) = opts.workdir {
cmd.current_dir(workdir);
}
if opts.clear_env {
cmd.env_clear();
}
for (key, value) in &opts.env {
cmd.env(key, value);
}
cmd.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
let status = cmd
.status()
.map_err(|e| Error::JailExecFailed(format!("Failed to execute jexec: {}", e)))?;
Ok(status)
}
pub fn console(jail: &str, user: &str) -> Result<ExitStatus> {
let opts = ExecOptions {
user: user.to_string(),
..Default::default()
};
exec_in_jail(jail, &["-".to_string()], &opts)
}
#[allow(dead_code)]
pub fn exec_in_jail_direct(
jail: &str,
command: &[String],
opts: &ExecOptions,
) -> Result<ExitStatus> {
let jid = jail_getid(jail)?;
if command.is_empty() {
return Err(Error::JailExecFailed("No command specified".to_string()));
}
match unsafe { libc::fork() } {
-1 => Err(Error::JailExecFailed("Fork failed".to_string())),
0 => {
if let Err(e) = jail_attach(jid) {
eprintln!("Failed to attach to jail: {}", e);
std::process::exit(1);
}
if opts.user != "root"
&& let Err(e) = set_user(&opts.user) {
eprintln!("Failed to set user: {}", e);
std::process::exit(1);
}
if let Some(ref workdir) = opts.workdir
&& let Err(e) = std::env::set_current_dir(workdir) {
eprintln!("Failed to change directory: {}", e);
std::process::exit(1);
}
let program = CString::new(command[0].as_str()).unwrap();
let args: Vec<CString> = command
.iter()
.map(|s| CString::new(s.as_str()).unwrap())
.collect();
let args_ptr: Vec<*const libc::c_char> = args
.iter()
.map(|s| s.as_ptr())
.chain(std::iter::once(std::ptr::null()))
.collect();
unsafe {
libc::execvp(program.as_ptr(), args_ptr.as_ptr());
}
eprintln!("Failed to exec: {}", std::io::Error::last_os_error());
std::process::exit(1);
}
pid => {
let mut status: libc::c_int = 0;
unsafe {
libc::waitpid(pid, &mut status, 0);
}
let _exit_code = if libc::WIFEXITED(status) {
libc::WEXITSTATUS(status)
} else {
1
};
Ok(std::process::ExitStatus::from_raw(status))
}
}
}
fn set_user(username: &str) -> Result<()> {
let username_c = CString::new(username)
.map_err(|_| Error::JailExecFailed("Invalid username".to_string()))?;
unsafe {
let pwd = libc::getpwnam(username_c.as_ptr());
if pwd.is_null() {
return Err(Error::JailExecFailed(format!(
"User '{}' not found",
username
)));
}
let uid = (*pwd).pw_uid;
let gid = (*pwd).pw_gid;
if libc::initgroups(username_c.as_ptr(), gid as libc::gid_t) != 0 {
return Err(Error::JailExecFailed("Failed to set groups".to_string()));
}
if libc::setgid(gid) != 0 {
return Err(Error::JailExecFailed("Failed to set GID".to_string()));
}
if libc::setuid(uid) != 0 {
return Err(Error::JailExecFailed("Failed to set UID".to_string()));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_exec_options_default() {
let opts = ExecOptions::default();
assert_eq!(opts.user, "root");
assert!(opts.workdir.is_none());
assert!(opts.env.is_empty());
}
}