[PATCH net-next 1/2] net: add sockopt_expand_out()
From: Breno Leitao
Date: Thu Sep 10 2026 - 05:59:55 EST
Add sockopt_expand_out() to grow opt->iter_out mid-air.
It is a no-op unless the proper size outruns optlen (i.e, some
not-well-behaved userspace program calling it).
In this case, only a user buffer can be longer than optlen says, so
a kernel-backed optval keeps the bounded iterator and the callback gets
-EINVAL if it asks to grow.
This whole quirk is added to:
1) Avoid breaking userspace
2) Making the quirk explict
* Instead of protocol doing implict assumping like this.
Signed-off-by: Breno Leitao <leitao@xxxxxxxxxx>
---
include/linux/net.h | 25 +++++++++++++++++++++++++
net/socket.c | 4 ++--
2 files changed, 27 insertions(+), 2 deletions(-)
diff --git a/include/linux/net.h b/include/linux/net.h
index 470100ae710773..de0ed362b37794 100644
--- a/include/linux/net.h
+++ b/include/linux/net.h
@@ -70,6 +70,31 @@ static inline int sockopt_init_user(sockopt_t *opt, char __user *optval,
return 0;
}
+/*
+ * Grow optval to @size, for the options whose reply is sized by a count the
+ * caller left in optval rather than by optlen. Those write past optlen today
+ * and userspace relies on it.
+ *
+ * Call it before writing through opt->iter_out: it re-anchors the iterator at
+ * the head of optval. Only a user buffer can be longer than the optlen the
+ * caller declared, so a kernel-backed optval is refused with -EINVAL.
+ */
+static inline int sockopt_expand_out(sockopt_t *opt, size_t size)
+{
+ if (size <= iov_iter_count(&opt->iter_out))
+ return 0;
+
+ if (WARN_ON_ONCE(!iter_is_ubuf(&opt->iter_out)))
+ return -EINVAL;
+
+ iov_iter_ubuf(&opt->iter_out, ITER_DEST, opt->iter_out.ubuf, size);
+
+ return 0;
+}
+
+int sockptr_to_sockopt(sockopt_t *opt, sockptr_t optval, sockptr_t optlen,
+ struct kvec *kvec);
+
struct poll_table_struct;
struct pipe_inode_info;
struct inode;
diff --git a/net/socket.c b/net/socket.c
index c05d86e63abf7d..29a0f7f8e2cabe 100644
--- a/net/socket.c
+++ b/net/socket.c
@@ -2437,8 +2437,8 @@ INDIRECT_CALLABLE_DECLARE(bool tcp_bpf_bypass_getsockopt(int level,
* It is important to remember that both iov points to the same data, but,
* .iter_in is read-only and .iter_out is write-only by the protocol callbacks
*/
-static int sockptr_to_sockopt(sockopt_t *opt, sockptr_t optval,
- sockptr_t optlen, struct kvec *kvec)
+int sockptr_to_sockopt(sockopt_t *opt, sockptr_t optval,
+ sockptr_t optlen, struct kvec *kvec)
{
int koptlen;
--
2.53.0-Meta