Re: [PATCH net 1/2] net: don't leak pidfds through a short SO_PEERPIDFD optlen

From
Alexander Mikhalitsyn <hidden>
Date
2026-11-17 16:39:23
Also in
linux-fsdevel, stable
Reply to
Christian Brauner, 2026-11-17
On Tue, 2026-11-17 at 16:25 +0100, Christian Brauner wrote:
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: <redacted>
Reported-by: Sashiko <sashiko-bot@kernel.org>
Closes: https://lore.kernel.org/all/sashiko-outbox-205984@kernel.org (local)
Ugh, I wonder how I didn't notice this before... :(

Thanks, Christian!

Reviewed-by: Alexander Mikhalitsyn <redacted>
quoted hunk ↗ jump to hunk
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
---
 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]);
Thread (5 messages) 5 messages, 2 authors, last reply 5h ago
Keyboard shortcuts
hback out one level
jnext message in thread / next series-diff position
kprevious message in thread / previous series-diff position
ldrill in
Escclose help / fold thread tree
?toggle this help