From 10e68bf5d7896f2cb0b0a9bba87037daa336aa2d Mon Sep 17 00:00:00 2001 From: kosayoda Date: Fri, 31 Mar 2023 18:07:48 -0400 Subject: [PATCH] Prevent file descriptor leak in the spawned child After forking the child process, the file descriptors for the master and slave aren't closed since we created these descriptors ourselves (Rust sets CLOEXEC on any fds created in the stdlib). Signed-off-by: Kieran Siek --- src/process.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/process.rs b/src/process.rs index 3f8e166e..4b388bcc 100644 --- a/src/process.rs +++ b/src/process.rs @@ -7,7 +7,7 @@ use nix::libc::{STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO}; use nix::pty::{grantpt, posix_openpt, unlockpt, PtyMaster}; pub use nix::sys::{signal, wait}; use nix::sys::{stat, termios}; -use nix::unistd::{dup, dup2, fork, setsid, ForkResult, Pid}; +use nix::unistd::{close, dup, dup2, fork, setsid, ForkResult, Pid}; use std; use std::fs::File; use std::os::unix::io::{AsRawFd, FromRawFd}; @@ -97,6 +97,9 @@ impl PtyProcess { match unsafe { fork()? } { ForkResult::Child => { + // Avoid leaking master fd + close(master_fd.as_raw_fd())?; + setsid()?; // create new session with child as session leader let slave_fd = open( std::path::Path::new(&slave_name), @@ -109,6 +112,11 @@ impl PtyProcess { dup2(slave_fd, STDOUT_FILENO)?; dup2(slave_fd, STDERR_FILENO)?; + // Avoid leaking slave fd + if slave_fd > STDERR_FILENO { + close(slave_fd)?; + } + // set echo off let mut flags = termios::tcgetattr(STDIN_FILENO)?; flags.local_flags &= !termios::LocalFlags::ECHO;