sk_getsockopt_peerpidfd() caps the caller's optlen at sizeof(int) but never checks that it is at least that large. sk_getsockopt() only rejects a negative optlen. So with an optlen of 0 to 3 we still allocate a pidfd via pidfd_prepare(), copy zero to three bytes of the fd number to userspace, write the short optlen back and then fd_install() the pidfd anyway. getsockopt() reports success but the caller only got part of the fd number or none of it at all. It has no sane way to find out which fd it has to close and the pidfd stays in its file descriptor table until the process exits. Calling it in a loop fills up the table. scm_pidfd_recv() deals with the same problem for SCM_PIDFD. Since put_cmsg() doesn't fail on truncation it checks the size of the control buffer itself and sets MSG_CTRUNC before it allocates a pidfd. There's no point in handing out part of a file descriptor number. So fail with EINVAL if optlen is smaller than sizeof(int) before we prepare a pidfd. Since commit e10899b2a098 ("net: add SO_PEERPIDFD_THREAD to get a thread-specific pidfd") SO_PEERPIDFD and SO_PEERPIDFD_THREAD share the helper and the latter inherited the bug, so this fixes both. Fixes: 7b26952a91cf ("net: core: add getsockopt SO_PEERPIDFD") Cc: stable@vger.kernel.org Reported-by: Sashiko Closes: https://lore.kernel.org/all/sashiko-outbox-205984@kernel.org Signed-off-by: Christian Brauner (Amutable) --- net/core/sock.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/net/core/sock.c b/net/core/sock.c index ad414878dc5ba..74a00a5e2d116 100644 --- a/net/core/sock.c +++ b/net/core/sock.c @@ -1746,8 +1746,10 @@ static int sk_getsockopt_peerpidfd(struct sock *sk, enum pid_type type, struct pid *peer_pid; int pidfd; - if (len > sizeof(pidfd)) - len = sizeof(pidfd); + /* Userspace can't close a pidfd whose number it didn't get. */ + if (len < sizeof(pidfd)) + return -EINVAL; + len = sizeof(pidfd); spin_lock(&sk->sk_peer_lock); peer_pid = get_pid(sk->sk_peer_pid[type]); -- 2.53.0