virtmgr: Set O_CLOEXEC on inherited FDs
virtmgr inherits two FDs from the parent. These must have O_CLOEXEC
disabled to survive the fork/exec but it should be re-enabled
immediately after to avoid acidentally leaking them any further.
Bug: 245727626
Test: atest -p packages/modules/Virtualization:avf-presubmit
Change-Id: I8642e21480be1c8ef04d252b0429d3df13485288
diff --git a/virtualizationservice/src/virtmgr.rs b/virtualizationservice/src/virtmgr.rs
index 90b4789..5616097 100644
--- a/virtualizationservice/src/virtmgr.rs
+++ b/virtualizationservice/src/virtmgr.rs
@@ -30,6 +30,7 @@
use rpcbinder::{FileDescriptorTransportMode, RpcServer};
use std::os::unix::io::{FromRawFd, OwnedFd, RawFd};
use clap::Parser;
+use nix::fcntl::{fcntl, F_GETFD, F_SETFD, FdFlag};
use nix::unistd::{Pid, Uid};
use std::os::unix::raw::{pid_t, uid_t};
@@ -66,8 +67,12 @@
fn take_fd_ownership(raw_fd: RawFd, owned_fds: &mut Vec<RawFd>) -> Result<OwnedFd, anyhow::Error> {
// Basic check that the integer value does correspond to a file descriptor.
- nix::fcntl::fcntl(raw_fd, nix::fcntl::F_GETFD)
- .with_context(|| format!("Invalid file descriptor {raw_fd}"))?;
+ fcntl(raw_fd, F_GETFD).with_context(|| format!("Invalid file descriptor {raw_fd}"))?;
+
+ // The file descriptor had CLOEXEC disabled to be inherited from the parent.
+ // Re-enable it to make sure it is not accidentally inherited further.
+ fcntl(raw_fd, F_SETFD(FdFlag::FD_CLOEXEC))
+ .with_context(|| format!("Could not set CLOEXEC on file descriptor {raw_fd}"))?;
// Creating OwnedFd for stdio FDs is not safe.
if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) {