1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//! Console and exec functionality for jails
//!
//! Provides the ability to:
//! - Execute commands inside a running jail
//! - Open an interactive console session
use crate::error::{Error, Result};
/// Validate that an environment variable key is safe for shell use.
/// Keys must start with a letter or underscore, followed by alphanumerics or underscores.
fn is_valid_env_key(key: &str) -> bool {
if key.is_empty() {
return false;
}
let mut chars = key.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
_ => return false,
}
chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
/// Escape a string for safe use in single quotes
fn shell_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', "'\\''"))
}
use crate::jail::jail_getid;
use std::fmt::Write as _;
use std::process::{Command, ExitStatus, Stdio};
/// Options for executing commands in a jail
#[derive(Debug, Clone)]
pub struct ExecOptions {
/// User to run as inside the jail
pub user: String,
/// Working directory inside the jail
pub workdir: Option<String>,
/// Environment variables to set
pub env: Vec<(String, String)>,
/// Clear environment before setting new vars (`env -i` semantics)
pub clear_env: bool,
}
impl Default for ExecOptions {
fn default() -> Self {
Self {
user: "root".to_string(),
workdir: None,
env: Vec::new(),
clear_env: false,
}
}
}
/// Execute a command inside a jail using jexec
///
/// This is the simpler approach that wraps the jexec(8) utility.
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");
// Add user flag
cmd.arg("-u").arg(&opts.user);
// Add jail ID
cmd.arg(jid.to_string());
// Build the actual command to run
// If we have a workdir or env, wrap in shell
if opts.workdir.is_some() || !opts.env.is_empty() || opts.clear_env {
cmd.arg("/bin/sh");
cmd.arg("-c");
let mut script = String::new();
let mut assignments = String::new();
// Validate every key, whether it is exported or handed to env -i
for (key, value) in &opts.env {
if !is_valid_env_key(key) {
return Err(Error::JailExecFailed(format!(
"Invalid environment variable key: '{key}'. Keys must start with a letter or underscore, followed by alphanumerics or underscores."
)));
}
let escaped = shell_quote(value);
if opts.clear_env {
if !assignments.is_empty() {
assignments.push(' ');
}
let _ = write!(assignments, "{key}={escaped}"); // fmt::Write into a String is infallible
} else {
let _ = write!(script, "export {key}={escaped}; "); // fmt::Write into a String is infallible
}
}
// Add working directory change (properly escaped)
if let Some(ref workdir) = opts.workdir {
let escaped_workdir = shell_quote(workdir);
let _ = write!(script, "cd {escaped_workdir} || exit 1; "); // fmt::Write into a String is infallible
}
script.push_str("exec ");
if opts.clear_env {
script.push_str("/usr/bin/env -i ");
if !assignments.is_empty() {
script.push_str(&assignments);
script.push(' ');
}
}
// Add the actual command
if command.is_empty() {
script.push_str("/bin/sh");
} else {
// Always quote each argument for safety
for (i, arg) in command.iter().enumerate() {
if i > 0 {
script.push(' ');
}
script.push_str(&shell_quote(arg));
}
}
cmd.arg(script);
} else {
// No workdir or env, just run the command directly
if command.is_empty() {
cmd.arg("/bin/sh");
} else {
cmd.args(command);
}
}
// Note: We pass environment through the shell script above, not here
// This ensures the env is set inside the jail, not on the host side
// Inherit stdio for interactive use
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)
}
/// Open an interactive console in a jail
///
/// This opens a login shell inside the jail.
pub fn console(jail: &str, user: &str) -> Result<ExitStatus> {
let opts = ExecOptions {
user: user.to_string(),
..Default::default()
};
// Use login shell
exec_in_jail(jail, &["-".to_string()], &opts)
}
#[cfg(test)]
mod tests;