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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use crate::audit::{audit, AuditEventType};
use crate::error::{NucleusError, Result};
use nix::sys::signal::{kill, Signal};
use nix::sys::signal::{pthread_sigmask, SigSet, SigmaskHow};
use nix::sys::wait::{waitpid, WaitStatus};
use nix::unistd::{fork, ForkResult, Pid};
use std::ffi::CString;
use tracing::{debug, error, info};
use super::runtime::Container;
impl Container {
/// Execute the target command.
///
/// This runs in the child process after fork, after all security setup is complete.
pub(super) fn exec_command(&self) -> Result<()> {
if self.config.command.is_empty() {
return Err(NucleusError::ExecError("No command specified".to_string()));
}
info!("Executing command: {:?}", self.config.command);
let program = CString::new(self.config.command[0].as_str())
.map_err(|e| NucleusError::ExecError(format!("Invalid program name: {}", e)))?;
let args: Result<Vec<CString>> = self
.config
.command
.iter()
.map(|arg| {
CString::new(arg.as_str())
.map_err(|e| NucleusError::ExecError(format!("Invalid argument: {}", e)))
})
.collect();
let args = args?;
let mut env = vec![
CString::new("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")
.map_err(|e| NucleusError::ExecError(format!("Invalid environment PATH: {}", e)))?,
CString::new("TERM=xterm")
.map_err(|e| NucleusError::ExecError(format!("Invalid environment TERM: {}", e)))?,
CString::new("HOME=/")
.map_err(|e| NucleusError::ExecError(format!("Invalid environment HOME: {}", e)))?,
];
// Pass through sd_notify socket if enabled
if self.config.sd_notify {
if let Ok(notify_socket) = std::env::var("NOTIFY_SOCKET") {
env.push(
CString::new(format!("NOTIFY_SOCKET={}", notify_socket)).map_err(|e| {
NucleusError::ExecError(format!("Invalid NOTIFY_SOCKET: {}", e))
})?,
);
}
}
// Append user-configured environment variables
for (key, value) in &self.config.environment {
env.push(CString::new(format!("{}={}", key, value)).map_err(|e| {
NucleusError::ExecError(format!(
"Invalid environment variable {}={}: {}",
key, value, e
))
})?);
}
nix::unistd::execve(&program, &args, &env)?;
Ok(())
}
/// Run as a minimal PID 1 init process inside the container.
///
/// Forks a child that execs the workload. PID 1 (this process) stays alive to:
/// - Reap zombie processes (orphaned children)
/// - Forward SIGTERM/SIGINT/SIGHUP to the workload child
/// - Exit with the workload's exit code
///
/// This prevents zombie accumulation in long-running production containers
/// and ensures clean shutdown ordering.
pub(super) fn run_as_init(&self) -> Result<()> {
info!("Starting as PID 1 init supervisor (production mode)");
audit(
&self.config.id,
&self.config.name,
AuditEventType::InitSupervisorStarted,
"PID 1 init supervisor for zombie reaping and signal forwarding",
);
match unsafe { fork() }? {
ForkResult::Parent { child } => {
// PID 1: mini-init — reap zombies and forward signals
// Set up signal forwarding to the workload child
let mut sigset = SigSet::empty();
for sig in [
Signal::SIGTERM,
Signal::SIGINT,
Signal::SIGHUP,
Signal::SIGQUIT,
Signal::SIGUSR1,
Signal::SIGUSR2,
] {
sigset.add(sig);
}
// Block forwarded signals so we can use sigtimedwait
pthread_sigmask(SigmaskHow::SIG_BLOCK, Some(&sigset), None).map_err(|e| {
NucleusError::ExecError(format!("Init: failed to block signals: {}", e))
})?;
// Spawn a thread to forward signals to the child
let child_pid = child;
let sig_thread = std::thread::spawn(move || {
while let Ok(signal) = sigset.wait() {
let _ = kill(child_pid, signal);
}
});
// Main loop: reap all children, exit when workload child exits
let workload_exit = loop {
match waitpid(Pid::from_raw(-1), None) {
Ok(WaitStatus::Exited(pid, code)) => {
if pid == child {
debug!("Init: workload child exited with code {}", code);
break code;
}
debug!("Init: reaped zombie PID {} (exit code {})", pid, code);
}
Ok(WaitStatus::Signaled(pid, signal, _)) => {
if pid == child {
let code = 128 + signal as i32;
debug!(
"Init: workload child killed by signal {:?} (exit code {})",
signal, code
);
break code;
}
debug!("Init: reaped zombie PID {} (killed by {:?})", pid, signal);
}
Err(nix::errno::Errno::ECHILD) => {
// No more children — workload must have exited
debug!("Init: no more children, exiting");
break 1;
}
Err(nix::errno::Errno::EINTR) => continue,
Err(e) => {
error!("Init: waitpid error: {}", e);
break 1;
}
_ => continue,
}
};
// Drop the signal-forwarding thread cleanly before exiting.
// It will unblock once there are no more signals to wait on.
drop(sig_thread);
std::process::exit(workload_exit);
}
ForkResult::Child => {
// Workload child: exec the target command
self.exec_command()?;
// Should never reach here
Ok(())
}
}
}
pub(super) fn enforce_no_new_privs(&self) -> Result<()> {
let ret = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) };
if ret != 0 {
return Err(NucleusError::ExecError(format!(
"Failed to set PR_SET_NO_NEW_PRIVS: {}",
std::io::Error::last_os_error()
)));
}
Ok(())
}
}