Skip to content

safe select/pselect with nfds > FD_SETSIZE let the kernel write past the FdSet #2879

Open

Description

@marius-momeu

nix::sys::select::select and pselect are safe, but pass the caller's nfds to the
syscall unchecked. An FdSet holds FD_SETSIZE (1024) bits, while Linux copies
nfds bits of each set in and back out, limited only by the size of the process's fd
table. Once the process has had an fd at or above 1024 open, nfds > 1024 makes the
kernel read and overwrite memory past each FdSet, from safe code. FdSet::insert
already asserts fd < FD_SETSIZE; nfds gets no such check.

#![forbid(unsafe_code)]
use nix::fcntl::{fcntl, FcntlArg};
use nix::sys::select::{select, FdSet};
use nix::sys::time::{TimeVal, TimeValLike};

#[repr(C)]
struct Frame<'fd> { set: FdSet<'fd>, after: [u8; 256] }

fn main() {
    let (rd, _wr) = nix::unistd::pipe().unwrap();
    assert_eq!(fcntl(&rd, FcntlArg::F_DUPFD(3000)).unwrap(), 3000);
    let mut f = Box::new(Frame { set: FdSet::new(), after: [0; 256] });
    f.after[(3000 - 1024) / 8] = 1; // plain data that is fd 3000's bit to the kernel
    let mut t = TimeVal::zero();
    println!("{:?}", select(Some(3001), Some(&mut f.set), None, None, Some(&mut t)));
    assert_eq!(f.after[(3000 - 1024) / 8], 1, "select wrote past the FdSet");
}
Ok(0)
thread 'main' (82373) panicked at src/main.rs:16:5:
assertion `left == right` failed: select wrote past the FdSet
  left: 0
 right: 1

Run on nix 0.31.3 (also the current master), glibc 2.39, Linux 6.14,
rustc 1.102.0-nightly (2026-11-12).

A possible fix is to return EINVAL when nfds is outside 0..=FD_SETSIZE in both
functions.

Found by Crustify, an experimental
UB/soundness auditing agent developed at UC Berkeley and running on Claude Opus 5.5, then
manually reviewed and independently reproduced.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions