Skip to content

Commit a76a586

Browse files
ppennaCopilot
andcommitted
cli: keep a cold run's console when OpenVMM exits before the peer check
A cold `nvx-rs run` on Linux could exit with OpenVMM's status, 0, and print none of OpenVMM's console output, with no error. The CLI test `one_shot_runs_exit_with_the_workload_or_openvmm_status` failed that way in CI run 43156460151 (job 130977435086, on #1501), and once in a local run of SL6.2b's on nvx-mshv-test. The run connects to the boot console on which OpenVMM listens, then checks the socket's original peer: its `SO_PEERCRED` PID must be OpenVMM's, and its `SO_PEERPIDFD` pidfd must not report an exit. The fake OpenVMM accepts the connection, writes its line and exits at once. When it exits between the run's `connect` and that check, the check refuses the peer as exited, and `connect_before_exit` yields to OpenVMM's exit status, dropping the connection with the output already queued in it. A real OpenVMM, too, writes its output and exits without waiting for the run to read it, so a run that stalls at that point on a loaded host loses its output silently. The console now connects with `connect_child_endpoint`, which checks the peer as `connect_endpoint` does, but accepts an original peer that has exited and has not been reaped, and still refuses a reaped one. That is safe because the run's own unreaped child keeps its PID, which no other process can reuse until the run reaps it, so a peer that holds the child's PID is the child. `PidFd::holds_its_id` tells an unreaped process from a reaped one with signal 0 through the pidfd, which fails with `ESRCH` only once the process is reaped. Every other connection, the control sessions and the restore-ready endpoint, still refuses an exited peer. Windows is unchanged: its `connect_endpoint` checks only the pipe's server process ID. Tests: `a_child_endpoint_accepts_its_exited_child_until_the_child_is_reaped` connects to a listener whose creator, the test's child, has exited and is not reaped: `connect_endpoint` refuses it, `connect_child_endpoint` accepts it and reads through it, and both refuse it once the test has reaped the creator. It shares the Python launcher of `a_transferred_listener_cannot_authenticate_its_exited_creator`, which now runs through the same helper and still reaps the creator first. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent c64e4a0 commit a76a586

5 files changed

Lines changed: 137 additions & 17 deletions

File tree

‎nvx-rs/src/host/cli/run.rs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -697,11 +697,12 @@ fn connect_running(
697697
endpoint: &str,
698698
) -> Result<Option<Box<dyn Transport>>> {
699699
let pid = launched.process.reference().pid;
700-
connect_before_exit(
701-
endpoint,
702-
|| platform::connect_endpoint(endpoint, pid, Duration::from_millis(250)),
703-
|timeout| launched.wait_status(timeout),
704-
)
700+
// On Linux, OpenVMM may write its console output and exit before the console's peer check.
701+
#[cfg(target_os = "linux")]
702+
let connect = || platform::connect_child_endpoint(endpoint, pid);
703+
#[cfg(not(target_os = "linux"))]
704+
let connect = || platform::connect_endpoint(endpoint, pid, Duration::from_millis(250));
705+
connect_before_exit(endpoint, connect, |timeout| launched.wait_status(timeout))
705706
}
706707

707708
/// Connects to the verified endpoint, or yields to the owned child's confirmed exit.

‎nvx-rs/src/host/platform/linux/endpoint.rs‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ impl ReadyListener {
139139
));
140140
}
141141
if verify_original_peer {
142-
check_original_peer(&connection)?;
142+
check_original_peer(&connection, false)?;
143143
}
144144
connection.set_nonblocking(true)?;
145145
self.connection = Some(connection);
@@ -178,7 +178,10 @@ impl ReadyListener {
178178
}
179179

180180
/// The kernel returns a descriptor of the socket's original peer, not a new lookup of its PID.
181-
fn check_original_peer(connection: &UnixStream) -> io::Result<()> {
181+
///
182+
/// A peer that has exited is refused, unless `accept_unreaped` accepts one that has not been
183+
/// reaped, which still holds its ID, as `connect_child_endpoint` requires.
184+
fn check_original_peer(connection: &UnixStream, accept_unreaped: bool) -> io::Result<()> {
182185
let peer = match getsockopt(connection, PeerPidfd) {
183186
Err(
184187
sys::Errno::ENOPROTOOPT
@@ -207,6 +210,9 @@ fn check_original_peer(connection: &UnixStream) -> io::Result<()> {
207210
}
208211
let events = descriptors[0].revents().unwrap_or(PollFlags::empty());
209212
if events.intersects(PollFlags::POLLIN | PollFlags::POLLHUP) {
213+
if accept_unreaped && sys::PidFd::from(peer).holds_its_id()? {
214+
return Ok(());
215+
}
210216
return Err(io::Error::new(
211217
io::ErrorKind::PermissionDenied,
212218
"the original socket peer exited",
@@ -261,6 +267,29 @@ pub(crate) fn connect_endpoint(
261267
endpoint: &str,
262268
expected_pid: u32,
263269
_timeout: Duration,
270+
) -> io::Result<Box<dyn Transport>> {
271+
connect_peer(endpoint, expected_pid, false)
272+
}
273+
274+
/// Connects to the endpoint that the process `child` serves, as [`connect_endpoint`] does, for a
275+
/// caller that launched `child` and has not reaped it: a cold run, whose OpenVMM may write its
276+
/// boot console's output and exit before the run checks the console's peer.
277+
///
278+
/// It accepts an original socket peer that has exited but has not been reaped, and still refuses
279+
/// a reaped one. That is safe because the caller's own unreaped child keeps its PID, which no
280+
/// other process can reuse until the caller reaps it, so a peer that holds the child's PID is the
281+
/// child. Every other connection, as [`connect_endpoint`]'s, still refuses an exited peer.
282+
#[cfg(feature = "cli")]
283+
pub(crate) fn connect_child_endpoint(endpoint: &str, child: u32) -> io::Result<Box<dyn Transport>> {
284+
connect_peer(endpoint, child, true)
285+
}
286+
287+
/// Connects to the endpoint that the process `expected_pid` serves as the socket's original peer,
288+
/// which [`check_original_peer`] checks, with `accept_unreaped`.
289+
fn connect_peer(
290+
endpoint: &str,
291+
expected_pid: u32,
292+
accept_unreaped: bool,
264293
) -> io::Result<Box<dyn Transport>> {
265294
let stream = sys::connect_nonblocking(endpoint)?;
266295
let peer = sys::peer_pid(&stream)?;
@@ -272,7 +301,7 @@ pub(crate) fn connect_endpoint(
272301
),
273302
));
274303
}
275-
check_original_peer(&stream)?;
304+
check_original_peer(&stream, accept_unreaped)?;
276305
transport_from_handle(stream.into())
277306
}
278307

‎nvx-rs/src/host/platform/linux/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ pub(crate) use self::endpoint::{
1919
};
2020
#[cfg(feature = "cli")]
2121
pub(crate) use self::endpoint::{
22-
endpoint_server_pid_until, interrupt_transfers, transport_from_handle,
22+
connect_child_endpoint, endpoint_server_pid_until, interrupt_transfers, transport_from_handle,
2323
};
2424
pub use self::identity::file_identity;
2525
pub(crate) use self::identity::{

‎nvx-rs/src/host/platform/linux/tests.rs‎

Lines changed: 70 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,72 @@ fn a_transferred_listener_cannot_authenticate_its_exited_creator() {
138138
println!("{verified} pid={pid}");
139139
return;
140140
}
141+
run_with_transferred_listener(
142+
"host::platform::linux::tests::a_transferred_listener_cannot_authenticate_its_exited_creator",
143+
true,
144+
verified,
145+
);
146+
}
147+
148+
#[cfg(feature = "cli")]
149+
#[test]
150+
fn a_child_endpoint_accepts_its_exited_child_until_the_child_is_reaped() {
151+
use std::io::Write;
152+
use std::os::fd::AsFd;
153+
use std::os::unix::net::UnixListener;
154+
155+
use nix::sys::wait::{Id, WaitPidFlag, waitid, waitpid};
156+
use nix::unistd::Pid;
157+
158+
let verified = "NVX_UNREAPED_CHILD_PEER_ACCEPTED";
159+
if let Some(pid) = std::env::var_os("NVX_TEST_TRANSFERRED_CONTROL_LISTENER") {
160+
let pid: u32 = pid.to_str().unwrap().parse().unwrap();
161+
let endpoint = std::env::var("NVX_TEST_TRANSFERRED_CONTROL_ENDPOINT").unwrap();
162+
let listener = UnixListener::from(std::io::stdin().as_fd().try_clone_to_owned().unwrap());
163+
// The listener's creator is this process's child: it exits, and only this process reaps it.
164+
let creator = Pid::from_raw(i32::try_from(pid).unwrap());
165+
waitid(
166+
Id::Pid(creator),
167+
WaitPidFlag::WEXITED | WaitPidFlag::WNOWAIT,
168+
)
169+
.unwrap();
170+
let error = connect_endpoint(&endpoint, pid, Duration::from_secs(2))
171+
.err()
172+
.expect("other connections must still refuse an exited peer");
173+
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
174+
assert!(error.to_string().contains("original socket peer exited"));
175+
drop(listener.accept().unwrap());
176+
let mut transport = connect_child_endpoint(&endpoint, pid).unwrap();
177+
let (mut peer, _) = listener.accept().unwrap();
178+
peer.write_all(b"output").unwrap();
179+
let mut output = [0; 6];
180+
let count = transport
181+
.read(&mut output, Some(Duration::from_secs(2)))
182+
.unwrap();
183+
assert_eq!(&output[..count], b"output");
184+
waitpid(creator, None).unwrap();
185+
let error = connect_child_endpoint(&endpoint, pid)
186+
.err()
187+
.expect("a reaped peer must not authenticate");
188+
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
189+
assert!(error.to_string().contains("original socket peer exited"));
190+
println!("{verified} pid={pid}");
191+
return;
192+
}
193+
run_with_transferred_listener(
194+
"host::platform::linux::tests::a_child_endpoint_accepts_its_exited_child_until_the_child_is_reaped",
195+
false,
196+
verified,
197+
);
198+
}
141199

200+
/// Runs this binary's test `test` in a Python process that a child of its own, the creator, gave
201+
/// a listener at a new socket before it exited, and checks that the test passed and printed
202+
/// `verified`. The test finds the listener on its standard input, the creator's PID in
203+
/// `NVX_TEST_TRANSFERRED_CONTROL_LISTENER`, and the socket's path in
204+
/// `NVX_TEST_TRANSFERRED_CONTROL_ENDPOINT`. The process reaps the creator first if `reap`, and
205+
/// leaves it to the test otherwise.
206+
fn run_with_transferred_listener(test: &str, reap: bool, verified: &str) {
142207
let directory = tempfile::tempdir().unwrap();
143208
let path = directory.path().join("control.sock");
144209
let mut command = Command::new("python3");
@@ -163,7 +228,8 @@ assert messages[0][:2] == (socket.SOL_SOCKET, socket.SCM_RIGHTS)
163228
descriptors = array.array("i")
164229
descriptors.frombytes(messages[0][2])
165230
assert len(descriptors) == 1
166-
assert os.waitpid(creator, 0) == (creator, 0)
231+
if sys.argv[4] == "reap":
232+
assert os.waitpid(creator, 0) == (creator, 0)
167233
os.dup2(descriptors[0], 0)
168234
if descriptors[0] != 0:
169235
os.close(descriptors[0])
@@ -174,10 +240,9 @@ os.execv(sys.argv[2], [sys.argv[2], "--exact", sys.argv[3], "--nocapture", "--te
174240
])
175241
.arg(&path)
176242
.arg(std::env::current_exe().unwrap())
177-
.arg(
178-
"host::platform::linux::tests::a_transferred_listener_cannot_authenticate_its_exited_creator",
179-
)
180-
.env(endpoint, &path)
243+
.arg(test)
244+
.arg(if reap { "reap" } else { "keep" })
245+
.env("NVX_TEST_TRANSFERRED_CONTROL_ENDPOINT", &path)
181246
.stdin(Stdio::null())
182247
.stdout(Stdio::piped())
183248
.stderr(Stdio::piped());

‎nvx-rs/src/host/sys/process.rs‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,17 +102,42 @@ impl PidFd {
102102
///
103103
/// Fails with `ESRCH` if the process has exited.
104104
pub(crate) fn kill(&self) -> io::Result<()> {
105+
self.send_signal(Signal::SIGKILL as libc::c_int)?;
106+
Ok(())
107+
}
108+
109+
/// Returns whether the process still holds its ID: it runs, or it has exited and has not
110+
/// been reaped, as signal 0 shows without signaling it. No other process can take the ID
111+
/// before the process is reaped.
112+
pub(crate) fn holds_its_id(&self) -> io::Result<bool> {
113+
match self.send_signal(0) {
114+
// Another user's process refuses the signal, but it holds its ID.
115+
Ok(()) | Err(Errno::EPERM) => Ok(true),
116+
Err(Errno::ESRCH) => Ok(false),
117+
Err(error) => Err(error.into()),
118+
}
119+
}
120+
121+
/// Sends `signal` to the process, or with 0, only checks that it could.
122+
fn send_signal(&self, signal: libc::c_int) -> Result<(), Errno> {
105123
// SAFETY: the descriptor is a valid pidfd, and a null siginfo with no flags is allowed.
106124
Errno::result(unsafe {
107125
libc::syscall(
108126
libc::SYS_pidfd_send_signal,
109127
self.0.as_raw_fd(),
110-
Signal::SIGKILL as libc::c_int,
128+
signal,
111129
ptr::null::<libc::siginfo_t>(),
112130
0,
113131
)
114-
})?;
115-
Ok(())
132+
})
133+
.map(drop)
134+
}
135+
}
136+
137+
impl From<OwnedFd> for PidFd {
138+
/// Takes `descriptor`, which must be a pidfd, such as `SO_PEERPIDFD` returns.
139+
fn from(descriptor: OwnedFd) -> Self {
140+
Self(descriptor)
116141
}
117142
}
118143

0 commit comments

Comments
 (0)