Skip to content

Commit f79c94d

Browse files
Jonathan Woollett-Lightpb8o
Jonathan Woollett-Light
authored andcommitted
Improve robustness of sanitize_process()
The previous approach was to iterate through the known attached file descriptors, we now instead iterate through and attempt to close all possible attached file descriptors. This offers a more robust and safe implementation. This fixes a bug which arises in Rust versions >=1.65.0 from a file descriptor being closed twice. Signed-off-by: Jonathan Woollett-Light <[email protected]>
1 parent b754e65 commit f79c94d

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

src/jailer/src/main.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -354,16 +354,13 @@ pub fn readln_special<T: AsRef<Path>>(file_path: &T) -> Result<String> {
354354
fn sanitize_process() {
355355
// First thing to do is make sure we don't keep any inherited FDs
356356
// other that IN, OUT and ERR.
357-
if let Ok(mut paths) = fs::read_dir("/proc/self/fd") {
358-
while let Some(Ok(path)) = paths.next() {
359-
let file_name = path.file_name();
360-
let fd_str = file_name.to_str().unwrap_or("0");
361-
let fd = fd_str.parse::<i32>().unwrap_or(0);
362-
363-
if fd > 2 {
364-
// SAFETY: Safe because close() cannot fail when passed a valid parameter.
365-
unsafe { libc::close(fd) };
366-
}
357+
// SAFETY: Always safe.
358+
let fd_limit = i32::try_from(unsafe { libc::sysconf(libc::_SC_OPEN_MAX) }).unwrap();
359+
// Close all file descriptors excluding 0 (STDIN), 1 (STDOUT) and 2 (STDERR).
360+
for fd in 3..fd_limit {
361+
// SAFETY: Safe because close() cannot fail when passed a valid parameter.
362+
unsafe {
363+
libc::close(fd);
367364
}
368365
}
369366

0 commit comments

Comments
 (0)