[PATCH bpf v2 2/2] selftests/bpf: Exercise negative optlen in cgroup getsockopt hook

From: Junseo Lim

Date: Tue Aug 11 2026 - 10:29:05 EST


Add a cgroup getsockopt selftest that sets ctx->optlen to -1. Use
TCP_ZEROCOPY_RECEIVE to exercise the kernel-buffer getsockopt hook.

The userspace-visible result is -EFAULT on both patched and unpatched
kernels, so the return value alone cannot distinguish the bug. The test
still exercises the kernel-buffer getsockopt path with a negative
ctx->optlen, which reproduces the hardened usercopy warning on unpatched
kernels.

Signed-off-by: Junseo Lim <zirajs7@xxxxxxxxx>
---
Adding the selftest to sockopt_test triggered the problematic path, but
detecting the broken behavior was not trivial because getsockopt()
returned -EFAULT on both patched and unpatched kernels. The selftest
mainly serves as a reproducer for the hardened usercopy warning.

.../selftests/bpf/prog_tests/sockopt.c | 22 +++++++++++++++++++
1 file changed, 22 insertions(+)

diff --git a/tools/testing/selftests/bpf/prog_tests/sockopt.c b/tools/testing/selftests/bpf/prog_tests/sockopt.c
index eaac83a7f388..3834dcf0f9dd 100644
--- a/tools/testing/selftests/bpf/prog_tests/sockopt.c
+++ b/tools/testing/selftests/bpf/prog_tests/sockopt.c
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-2.0
+#include <linux/tcp.h>
#include <test_progs.h>
#include <io_uring/mini_liburing.h>
#include "cgroup_helpers.h"
@@ -283,6 +284,27 @@ static struct sockopt_test {
.error = EFAULT_GETSOCKOPT,
.io_uring_support = true,
},
+ {
+ .descr = "getsockopt: deny negative ctx->optlen in TCP_ZEROCOPY_RECEIVE",
+ .insns = {
+ /* ctx->optlen = -1 */
+ BPF_MOV64_IMM(BPF_REG_0, -1),
+ BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_0,
+ offsetof(struct bpf_sockopt, optlen)),
+
+ /* return 1 */
+ BPF_MOV64_IMM(BPF_REG_0, 1),
+ BPF_EXIT_INSN(),
+ },
+ .attach_type = BPF_CGROUP_GETSOCKOPT,
+ .expected_attach_type = BPF_CGROUP_GETSOCKOPT,
+
+ .get_level = IPPROTO_TCP,
+ .get_optname = TCP_ZEROCOPY_RECEIVE,
+ .get_optlen = sizeof(struct tcp_zerocopy_receive),
+
+ .error = EFAULT_GETSOCKOPT,
+ },
{
.descr = "getsockopt: ignore >PAGE_SIZE optlen",
.insns = {
--
2.55.0