AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/31 04:54 flow patch-triage
5m Args:
null

Results:
{
  "EnableConfigs": [
    "TUN",
    "INET"
  ],
  "FocusSymbols": [
    "sk_attach_filter_kern",
    "bpf_prog_validate_classic",
    "tun_copy_filter",
    "tun_attach_filter",
    "tun_detach_filter",
    "tun_attach",
    "tun_chr_ioctl"
  ],
  "KMSANReasoning": "The patch updates the TUN driver to cache a kernel copy of classic BPF filters (struct sock_fprog_kern) to allow re-attaching filters across queue attachments without relying on the original process's address space.\n\nFrom a KMSAN perspective:\n- All stack variables (fp, fprog, fprog_kern) and heap buffers (insns) are either fully populated from copy_from_user or explicitly zeroed out with memset(fprog, 0, sizeof(*fprog)) before being saved or copied back to user space (via TUNGETFILTER).\n- Any failed copy_from_user promptly aborts and frees the temporary allocation before any uninitialized bytes can be accessed or propagated.\n- No uninitialized data or padding can be exposed to user space or used in conditional branching.\n\nFrom a KASAN/standard detectors perspective:\n- Potential risks introduced by this change include heap allocation tracking, double-free / use-after-free bugs (e.g., in error unwinding or netdev teardown with fprog_kern.filter), and locking issues (sock lock handling), which are already comprehensively detected by KASAN and LOCKDEP.\n\nTherefore, dedicated KMSAN fuzzing is not required.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch modifies TUN/TAP device driver logic and socket filter attachment handling. It introduces kernel-side caching of classic BPF filter instructions (struct sock_fprog_kern) to allow safe reattachment of filters across detached queues and distinct address spaces. It adds new helpers (bpf_prog_validate_classic and sk_attach_filter_kern) and refactors filter copying, attachment, detaching, and rollback handling upon error. Because /dev/net/tun ioctls (such as TUNATTACHFILTER and TUNSETIFF) are directly accessible from userspace in virtualized environments and the patch touches memory management, error rollback paths, and BPF validation, fuzzing is warranted to uncover any lifetime issues, memory leaks, or rollback inconsistencies.",
  "WorthFuzzing": true
}

1/1 2026/10/31 04:54 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 6bd4c0b8eb4529e17a0485d1e2c51f9231e4d988\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Sat Oct 31 04:54:44 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/drivers/net/tun.c b/drivers/net/tun.c\nindex 439565a264ee79..c121ad50f31bb3 100644\n--- a/drivers/net/tun.c\n+++ b/drivers/net/tun.c\n@@ -197,6 +197,7 @@ struct tun_struct {\n \tint\t\t\tsndbuf;\n \tstruct tap_filter\ttxflt;\n \tstruct sock_fprog\tfprog;\n+\tstruct sock_fprog_kern\tfprog_kern;\n \t/* protected by rtnl lock */\n \tbool\t\t\tfilter_attached;\n \tu32\t\t\tmsg_enable;\n@@ -726,12 +727,69 @@ static void tun_force_wake_queue(struct tun_struct *tun,\n \tspin_unlock_bh(\u0026tfile-\u003etx_ring.consumer_lock);\n }\n \n+/* Copy the filter that @argp points at into the kernel, so that it can be\n+ * installed again later, independent of the ioctl caller's address space.\n+ * @fprog_kern receives the copy, which belongs to the caller until it is\n+ * installed or freed, and @fprog receives the header, with the user pointer\n+ * kept for TUNGETFILTER.\n+ */\n+static int tun_copy_filter(struct sock_fprog __user *argp,\n+\t\t\t   struct sock_fprog *fprog,\n+\t\t\t   struct sock_fprog_kern *fprog_kern)\n+{\n+\tstruct sock_fprog fp;\n+\tstruct sock_filter *insns;\n+\tint err;\n+\n+\tif (copy_from_user(\u0026fp, argp, sizeof(fp)))\n+\t\treturn -EFAULT;\n+\n+\tif (!fp.len || fp.len \u003e BPF_MAXINSNS)\n+\t\treturn -EINVAL;\n+\n+\tinsns = kmalloc_array(fp.len, sizeof(struct sock_filter),\n+\t\t\t      GFP_KERNEL_ACCOUNT);\n+\tif (!insns)\n+\t\treturn -ENOMEM;\n+\n+\tif (copy_from_user(insns, fp.filter,\n+\t\t\t   fp.len * sizeof(struct sock_filter))) {\n+\t\tkfree(insns);\n+\t\treturn -EFAULT;\n+\t}\n+\n+\t/* The instructions are only verified when a program is built from\n+\t * them, which happens when the filter is attached to a socket. Run\n+\t * the classic verifier here as well, so that a bad program is\n+\t * refused before it is saved and before any queue is touched.\n+\t * bpf_prog_create() can still refuse the program later, when it is\n+\t * converted to eBPF or when no runtime can be selected for it; the\n+\t * attach path returns that error, and the saved program is not\n+\t * replaced.\n+\t */\n+\terr = bpf_prog_validate_classic(insns, fp.len);\n+\tif (err) {\n+\t\tkfree(insns);\n+\t\treturn err;\n+\t}\n+\n+\t/* Zero the whole header before filling it in. */\n+\tmemset(fprog, 0, sizeof(*fprog));\n+\tfprog-\u003elen = fp.len;\n+\tfprog-\u003efilter = fp.filter;\n+\tfprog_kern-\u003elen = fp.len;\n+\tfprog_kern-\u003efilter = insns;\n+\n+\treturn 0;\n+}\n+\n static int tun_attach(struct tun_struct *tun, struct file *file,\n \t\t      bool skip_filter, bool napi, bool napi_frags,\n \t\t      bool publish_tun)\n {\n \tstruct tun_file *tfile = file-\u003eprivate_data;\n \tstruct net_device *dev = tun-\u003edev;\n+\tbool rollback_filter = false;\n \tint err;\n \n \terr = security_tun_dev_attach(tfile-\u003esocket.sk, tun-\u003esecurity);\n@@ -756,10 +814,11 @@ static int tun_attach(struct tun_struct *tun, struct file *file,\n \t/* Re-attach the filter to persist device */\n \tif (!skip_filter \u0026\u0026 (tun-\u003efilter_attached == true)) {\n \t\tlock_sock(tfile-\u003esocket.sk);\n-\t\terr = sk_attach_filter(\u0026tun-\u003efprog, tfile-\u003esocket.sk);\n+\t\terr = sk_attach_filter_kern(\u0026tun-\u003efprog_kern, tfile-\u003esocket.sk);\n \t\trelease_sock(tfile-\u003esocket.sk);\n-\t\tif (!err)\n+\t\tif (err)\n \t\t\tgoto out;\n+\t\trollback_filter = true;\n \t}\n \n \tif (!tfile-\u003edetached \u0026\u0026\n@@ -821,6 +880,17 @@ static int tun_attach(struct tun_struct *tun, struct file *file,\n \tWRITE_ONCE(tun-\u003enumqueues, tun-\u003enumqueues + 1);\n \ttun_set_real_num_queues(tun);\n out:\n+\tif (err \u0026\u0026 rollback_filter) {\n+\t\t/* The filter was installed before the rest of the attach\n+\t\t * ran, so drop it again if a later step failed. Any\n+\t\t * program it replaced is already gone: this leaves the\n+\t\t * queue without a filter rather than restoring the\n+\t\t * previous one.\n+\t\t */\n+\t\tlock_sock(tfile-\u003esocket.sk);\n+\t\tsk_detach_filter(tfile-\u003esocket.sk);\n+\t\trelease_sock(tfile-\u003esocket.sk);\n+\t}\n \treturn err;\n }\n \n@@ -2406,6 +2476,7 @@ static void tun_free_netdev(struct net_device *dev)\n \tsecurity_tun_dev_free_security(tun-\u003esecurity);\n \t__tun_set_ebpf(tun, \u0026tun-\u003esteering_prog, NULL);\n \t__tun_set_ebpf(tun, \u0026tun-\u003efilter_prog, NULL);\n+\tkfree(tun-\u003efprog_kern.filter);\n }\n \n static void tun_setup(struct net_device *dev)\n@@ -3070,10 +3141,14 @@ static void tun_detach_filter(struct tun_struct *tun, int n)\n \t\trelease_sock(tfile-\u003esocket.sk);\n \t}\n \n+\tkfree(tun-\u003efprog_kern.filter);\n+\ttun-\u003efprog_kern.filter = NULL;\n+\ttun-\u003efprog_kern.len = 0;\n \ttun-\u003efilter_attached = false;\n }\n \n-static int tun_attach_filter(struct tun_struct *tun)\n+static int tun_attach_filter(struct tun_struct *tun,\n+\t\t\t     struct sock_fprog_kern *fprog_kern)\n {\n \tint i, ret = 0;\n \tstruct tun_file *tfile;\n@@ -3081,15 +3156,29 @@ static int tun_attach_filter(struct tun_struct *tun)\n \tfor (i = 0; i \u003c tun-\u003enumqueues; i++) {\n \t\ttfile = rtnl_dereference(tun-\u003etfiles[i]);\n \t\tlock_sock(tfile-\u003esocket.sk);\n-\t\tret = sk_attach_filter(\u0026tun-\u003efprog, tfile-\u003esocket.sk);\n+\t\tret = sk_attach_filter_kern(fprog_kern, tfile-\u003esocket.sk);\n \t\trelease_sock(tfile-\u003esocket.sk);\n-\t\tif (ret) {\n-\t\t\ttun_detach_filter(tun, i);\n-\t\t\treturn ret;\n-\t\t}\n+\t\tif (ret)\n+\t\t\tgoto out_detach;\n \t}\n \n \ttun-\u003efilter_attached = true;\n+\treturn 0;\n+\n+out_detach:\n+\t/* Drop the copies already installed on queues 0..i-1, which leaves\n+\t * them without a filter: their previous sk_filter, if any, was\n+\t * already replaced and released. The caller does not replace the\n+\t * saved program when this fails, so tun-\u003efprog, tun-\u003efprog_kern and\n+\t * filter_attached keep their previous values.\n+\t */\n+\twhile (i--) {\n+\t\ttfile = rtnl_dereference(tun-\u003etfiles[i]);\n+\t\tlock_sock(tfile-\u003esocket.sk);\n+\t\tsk_detach_filter(tfile-\u003esocket.sk);\n+\t\trelease_sock(tfile-\u003esocket.sk);\n+\t}\n+\n \treturn ret;\n }\n \n@@ -3424,17 +3513,31 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd,\n \t\ttun_set_sndbuf(tun);\n \t\tbreak;\n \n-\tcase TUNATTACHFILTER:\n+\tcase TUNATTACHFILTER: {\n+\t\tstruct sock_fprog_kern fprog_kern;\n+\t\tstruct sock_fprog fprog;\n+\n \t\t/* Can be set only for TAPs */\n \t\tret = -EINVAL;\n \t\tif ((tun-\u003eflags \u0026 TUN_TYPE_MASK) != IFF_TAP)\n \t\t\tbreak;\n-\t\tret = -EFAULT;\n-\t\tif (copy_from_user(\u0026tun-\u003efprog, argp, sizeof(tun-\u003efprog)))\n+\n+\t\tret = tun_copy_filter(argp, \u0026fprog, \u0026fprog_kern);\n+\t\tif (ret)\n+\t\t\tbreak;\n+\n+\t\tret = tun_attach_filter(tun, \u0026fprog_kern);\n+\t\tif (ret) {\n+\t\t\tkfree(fprog_kern.filter);\n \t\t\tbreak;\n+\t\t}\n \n-\t\tret = tun_attach_filter(tun);\n+\t\t/* Install the copy only after every queue accepted it. */\n+\t\tkfree(tun-\u003efprog_kern.filter);\n+\t\ttun-\u003efprog_kern = fprog_kern;\n+\t\ttun-\u003efprog = fprog;\n \t\tbreak;\n+\t}\n \n \tcase TUNDETACHFILTER:\n \t\t/* Can be set only for TAPs */\ndiff --git a/include/linux/filter.h b/include/linux/filter.h\nindex e0218e677a1dcd..7169c03610b445 100644\n--- a/include/linux/filter.h\n+++ b/include/linux/filter.h\n@@ -1257,8 +1257,10 @@ int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog);\n int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,\n \t\t\t      bpf_aux_classic_check_t trans, bool save_orig);\n void bpf_prog_destroy(struct bpf_prog *fp);\n+int bpf_prog_validate_classic(const struct sock_filter *insns, unsigned int len);\n \n int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk);\n+int sk_attach_filter_kern(struct sock_fprog_kern *fprog, struct sock *sk);\n int sk_attach_bpf(u32 ufd, struct sock *sk);\n int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk);\n int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk);\ndiff --git a/net/core/filter.c b/net/core/filter.c\nindex b7ac145b68b1f8..61b2d223c44563 100644\n--- a/net/core/filter.c\n+++ b/net/core/filter.c\n@@ -1476,6 +1476,32 @@ void bpf_prog_destroy(struct bpf_prog *fp)\n }\n EXPORT_SYMBOL_GPL(bpf_prog_destroy);\n \n+/**\n+ * bpf_prog_validate_classic - run the classic BPF verifier on kernel memory\n+ * @insns: instruction array\n+ * @len: number of instructions in @insns\n+ *\n+ * Run bpf_check_basics_ok() and bpf_check_classic() on a program that is\n+ * already in kernel memory, without building a struct bpf_prog.  These are\n+ * the checks bpf_prog_create() runs before it converts the program, so\n+ * callers can reject a bad program when it is configured instead of when it\n+ * is first attached to a socket.\n+ *\n+ * A program that passes here can still be refused by bpf_prog_create(), when\n+ * it is converted to eBPF or when no runtime can be selected for it.\n+ *\n+ * Return: 0 if the program passes the classic verifier, -EINVAL if it does\n+ * not, or -ENOMEM if the verifier cannot allocate its state.\n+ */\n+int bpf_prog_validate_classic(const struct sock_filter *insns, unsigned int len)\n+{\n+\tif (!bpf_check_basics_ok(insns, len))\n+\t\treturn -EINVAL;\n+\n+\treturn bpf_check_classic(insns, len);\n+}\n+EXPORT_SYMBOL_GPL(bpf_prog_validate_classic);\n+\n static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)\n {\n \tstruct sk_filter *fp, *old_fp;\n@@ -1567,6 +1593,47 @@ int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)\n }\n EXPORT_SYMBOL_GPL(sk_attach_filter);\n \n+/**\n+ * sk_attach_filter_kern - attach a classic BPF filter held in kernel memory\n+ * @fprog: program to attach, with @fprog-\u003efilter pointing at kernel memory\n+ * @sk: socket to attach the filter to\n+ *\n+ * Attach a copy of a classic BPF program that the kernel already holds, the\n+ * way sk_attach_filter() does for one that still lives in user space. The\n+ * caller must hold the socket lock; SOCK_FILTER_LOCKED is checked here.\n+ *\n+ * The program is built by bpf_prog_create(), which does not keep an original\n+ * copy of the instructions, so sk_get_filter() returns -EACCES and sock_diag\n+ * omits the filter for a socket that uses this helper.\n+ *\n+ * Return: 0 on success, or a negative errno: -EPERM if @sk has\n+ * SOCK_FILTER_LOCKED set, otherwise whatever bpf_prog_create() or\n+ * __sk_attach_prog() returned (for example -EINVAL for an invalid classic\n+ * BPF program, -ENOMEM, or -ENOTSUPP when a JIT is required but is not\n+ * available).\n+ */\n+int sk_attach_filter_kern(struct sock_fprog_kern *fprog, struct sock *sk)\n+{\n+\tstruct bpf_prog *prog;\n+\tint err;\n+\n+\tif (sock_flag(sk, SOCK_FILTER_LOCKED))\n+\t\treturn -EPERM;\n+\n+\terr = bpf_prog_create(\u0026prog, fprog);\n+\tif (err)\n+\t\treturn err;\n+\n+\terr = __sk_attach_prog(prog, sk);\n+\tif (err \u003c 0) {\n+\t\t__bpf_prog_release(prog);\n+\t\treturn err;\n+\t}\n+\n+\treturn 0;\n+}\n+EXPORT_SYMBOL_GPL(sk_attach_filter_kern);\n+\n int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)\n {\n \tstruct bpf_prog *prog = __get_filter(fprog, sk);\ndiff --git a/tools/testing/selftests/net/tun.c b/tools/testing/selftests/net/tun.c\nindex 34de2580e32eca..3730fba859a46e 100644\n--- a/tools/testing/selftests/net/tun.c\n+++ b/tools/testing/selftests/net/tun.c\n@@ -9,9 +9,11 @@\n #include \u003cstdlib.h\u003e\n #include \u003cstring.h\u003e\n #include \u003cunistd.h\u003e\n+#include \u003clinux/filter.h\u003e\n #include \u003clinux/if_tun.h\u003e\n #include \u003cnetinet/tcp.h\u003e\n #include \u003csys/ioctl.h\u003e\n+#include \u003csys/mman.h\u003e\n #include \u003csys/socket.h\u003e\n \n #include \"kselftest_harness.h\"\n@@ -548,6 +550,253 @@ TEST_F(tun, reattach_close_delete)\n \tEXPECT_EQ(tun_delete(self-\u003eifname), 0);\n }\n \n+/* accept: return skb-\u003elen.  Three instructions on purpose, so that the\n+ * length read back through TUNGETFILTER tells it apart from a rejected\n+ * program that is shorter.\n+ */\n+static const struct sock_filter filter_accept[] = {\n+\tBPF_STMT(BPF_LD | BPF_W | BPF_LEN, 0),\n+\tBPF_STMT(BPF_ALU | BPF_ADD | BPF_K, 0),\n+\tBPF_STMT(BPF_RET | BPF_A, 0),\n+};\n+\n+/* Put the instructions in an anonymous mapping, so that the test can make the\n+ * address unreadable afterwards.\n+ */\n+static void *filter_alloc(const struct sock_filter *insns, unsigned int len)\n+{\n+\tvoid *p;\n+\n+\tp = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE,\n+\t\t MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n+\tif (p == MAP_FAILED)\n+\t\treturn NULL;\n+\n+\tmemcpy(p, insns, len * sizeof(*insns));\n+\n+\treturn p;\n+}\n+\n+static int filter_attach(int fd, const struct sock_filter *insns, unsigned int len)\n+{\n+\tstruct sock_fprog fp = {\n+\t\t.len = len,\n+\t\t.filter = (struct sock_filter *)insns,\n+\t};\n+\n+\treturn ioctl(fd, TUNATTACHFILTER, (void *)\u0026fp);\n+}\n+\n+static int filter_get(int fd, struct sock_fprog *fp)\n+{\n+\treturn ioctl(fd, TUNGETFILTER, (void *)fp);\n+}\n+\n+static int tun_get_iff_flags(int fd)\n+{\n+\tstruct ifreq ifr = { 0 };\n+\n+\tif (ioctl(fd, TUNGETIFF, (void *)\u0026ifr) \u003c 0)\n+\t\treturn -1;\n+\n+\treturn ifr.ifr_flags;\n+}\n+\n+/*\n+ * A queue can be attached long after the filter was configured, from a\n+ * process that does not necessarily map the buffer the program was copied\n+ * from, so the kernel has to keep its own copy of the program.  Here the\n+ * mapping is made unreadable before the queue is attached again, and a\n+ * second queue is then attached from a fresh socket, which starts without a\n+ * filter of its own.\n+ */\n+TEST_F(tun, reattach_filter_without_user_buffer)\n+{\n+\tstruct sock_fprog gf = { 0 };\n+\tstruct ifreq ifr = { 0 };\n+\tshort flags = 0;\n+\tvoid *prog;\n+\tint fd, ret;\n+\n+\tprog = filter_alloc(filter_accept, ARRAY_SIZE(filter_accept));\n+\tASSERT_NE(prog, NULL);\n+\tASSERT_EQ(filter_attach(self-\u003efd, prog, ARRAY_SIZE(filter_accept)), 0);\n+\n+\tEXPECT_EQ(tun_detach(self-\u003efd, self-\u003eifname), 0);\n+\n+\t/* This memory is no longer readable */\n+\tASSERT_EQ(mprotect(prog, getpagesize(), PROT_NONE), 0);\n+\n+\tret = tun_attach(self-\u003efd, self-\u003eifname);\n+\tEXPECT_EQ(ret, 0);\n+\n+\tflags = tun_get_iff_flags(self-\u003efd);\n+\tEXPECT_GE(flags, 0);\n+\t/* The queue is attached again, not left disabled */\n+\tEXPECT_EQ(flags \u0026 IFF_DETACH_QUEUE, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, 0);\n+\n+\t/* The two checks below document the expected state, they cannot\n+\t * tell a reinstalled filter from no filter: tun_detach() leaves\n+\t * sk_filter alone, and TUNGETFILTER only returns the header.\n+\t */\n+\tEXPECT_EQ(filter_get(self-\u003efd, \u0026gf), 0);\n+\tEXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));\n+\n+\t/* A new queue starts without a filter, so a clear IFF_NOFILTER shows\n+\t * that the filter was installed again from the kernel copy.\n+\t */\n+\tfd = open(\"/dev/net/tun\", O_RDWR);\n+\tASSERT_GE(fd, 0);\n+\n+\tstrcpy(ifr.ifr_name, self-\u003eifname);\n+\tifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;\n+\tEXPECT_GE(ioctl(fd, TUNSETIFF, (void *)\u0026ifr), 0);\n+\n+\tflags = tun_get_iff_flags(fd);\n+\tEXPECT_GE(flags, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, 0);\n+\n+\tclose(fd);\n+\n+\tASSERT_EQ(mprotect(prog, getpagesize(), PROT_READ | PROT_WRITE), 0);\n+\tASSERT_EQ(munmap(prog, getpagesize()), 0);\n+}\n+\n+/* A new queue attached with IFF_NOFILTER must not get the filter that is\n+ * configured on the device.\n+ */\n+TEST_F(tun, attach_filter_nofilter_flag)\n+{\n+\tstruct ifreq ifr = { 0 };\n+\tshort flags = 0;\n+\tint fd;\n+\n+\tASSERT_EQ(filter_attach(self-\u003efd, filter_accept, ARRAY_SIZE(filter_accept)), 0);\n+\n+\tfd = open(\"/dev/net/tun\", O_RDWR);\n+\tASSERT_GE(fd, 0);\n+\n+\tstrcpy(ifr.ifr_name, self-\u003eifname);\n+\tifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE | IFF_NOFILTER;\n+\tEXPECT_GE(ioctl(fd, TUNSETIFF, (void *)\u0026ifr), 0);\n+\n+\tflags = tun_get_iff_flags(fd);\n+\tEXPECT_GE(flags, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, IFF_NOFILTER);\n+\n+\tclose(fd);\n+}\n+\n+/* After TUNDETACHFILTER a later attach must not install the filter again */\n+TEST_F(tun, detach_filter_clears_reattach)\n+{\n+\tshort flags = 0;\n+\n+\tASSERT_EQ(filter_attach(self-\u003efd, filter_accept, ARRAY_SIZE(filter_accept)), 0);\n+\tEXPECT_EQ(ioctl(self-\u003efd, TUNDETACHFILTER, 0), 0);\n+\n+\tflags = tun_get_iff_flags(self-\u003efd);\n+\tEXPECT_GE(flags, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, IFF_NOFILTER);\n+\n+\tEXPECT_EQ(tun_detach(self-\u003efd, self-\u003eifname), 0);\n+\tEXPECT_EQ(tun_attach(self-\u003efd, self-\u003eifname), 0);\n+\n+\tflags = tun_get_iff_flags(self-\u003efd);\n+\tEXPECT_GE(flags, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, IFF_NOFILTER);\n+}\n+\n+/* A TUNATTACHFILTER with a bad length must leave the installed program and the\n+ * filter state that TUNGETIFF reports alone.\n+ */\n+TEST_F(tun, attach_filter_bad_len_keeps_program)\n+{\n+\tstruct sock_fprog gf = { 0 };\n+\tstruct ifreq ifr = { 0 };\n+\tshort flags = 0;\n+\tint fd;\n+\n+\tASSERT_EQ(filter_attach(self-\u003efd, filter_accept, ARRAY_SIZE(filter_accept)), 0);\n+\n+\terrno = 0;\n+\tEXPECT_EQ(filter_attach(self-\u003efd, filter_accept, 0), -1);\n+\tEXPECT_EQ(errno, EINVAL);\n+\n+\tEXPECT_EQ(filter_get(self-\u003efd, \u0026gf), 0);\n+\tEXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));\n+\n+\tflags = tun_get_iff_flags(self-\u003efd);\n+\tEXPECT_GE(flags, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, 0);\n+\n+\t/* A queue attached afterwards still gets the filter, so the rejected\n+\t * ioctl left the saved program and filter_attached alone.\n+\t */\n+\tfd = open(\"/dev/net/tun\", O_RDWR);\n+\tASSERT_GE(fd, 0);\n+\n+\tstrcpy(ifr.ifr_name, self-\u003eifname);\n+\tifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;\n+\tEXPECT_GE(ioctl(fd, TUNSETIFF, (void *)\u0026ifr), 0);\n+\n+\tflags = tun_get_iff_flags(fd);\n+\tEXPECT_GE(flags, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, 0);\n+\n+\tclose(fd);\n+}\n+\n+/* A TUNATTACHFILTER with instructions that bpf_check_classic() rejects must\n+ * be refused, and must leave the program installed already in place.\n+ */\n+TEST_F(tun, attach_filter_bad_prog_keeps_program)\n+{\n+\tstruct sock_fprog gf = { 0 };\n+\tstruct sock_filter bad[] = {\n+\t\tBPF_STMT(BPF_LD | BPF_W | BPF_LEN, 0),\n+\t\tBPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 1, 0),\n+\t};\n+\tstruct ifreq ifr = { 0 };\n+\tshort flags = 0;\n+\tint fd;\n+\n+\tASSERT_EQ(filter_attach(self-\u003efd, filter_accept,\n+\t\t\t\tARRAY_SIZE(filter_accept)), 0);\n+\n+\terrno = 0;\n+\tEXPECT_EQ(filter_attach(self-\u003efd, bad, ARRAY_SIZE(bad)), -1);\n+\tEXPECT_EQ(errno, EINVAL);\n+\n+\t/* the program attached before is untouched */\n+\tEXPECT_EQ(filter_get(self-\u003efd, \u0026gf), 0);\n+\tEXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));\n+\n+\t/* IFF_NOFILTER comes from the socket's sk_filter, not from the saved\n+\t * header, so a clear flag shows the filter is still installed.\n+\t */\n+\tflags = tun_get_iff_flags(self-\u003efd);\n+\tEXPECT_GE(flags, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, 0);\n+\n+\t/* A queue attached afterwards still gets the filter, so the rejected\n+\t * program never replaced the saved one.\n+\t */\n+\tfd = open(\"/dev/net/tun\", O_RDWR);\n+\tASSERT_GE(fd, 0);\n+\n+\tstrcpy(ifr.ifr_name, self-\u003eifname);\n+\tifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;\n+\tEXPECT_GE(ioctl(fd, TUNSETIFF, (void *)\u0026ifr), 0);\n+\n+\tflags = tun_get_iff_flags(fd);\n+\tEXPECT_GE(flags, 0);\n+\tEXPECT_EQ(flags \u0026 IFF_NOFILTER, 0);\n+\n+\tclose(fd);\n+}\n+\n FIXTURE(tun_vnet_gso)\n {\n \tchar ifname[IFNAMSIZ];\n"
}

2/1 2026/10/31 04:54 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "TUN",
    "INET"
  ],
  "FocusSymbols": [
    "sk_attach_filter_kern",
    "bpf_prog_validate_classic",
    "tun_copy_filter",
    "tun_attach_filter",
    "tun_detach_filter",
    "tun_attach",
    "tun_chr_ioctl"
  ],
  "Reasoning": "The patch modifies TUN/TAP device driver logic and socket filter attachment handling. It introduces kernel-side caching of classic BPF filter instructions (struct sock_fprog_kern) to allow safe reattachment of filters across detached queues and distinct address spaces. It adds new helpers (bpf_prog_validate_classic and sk_attach_filter_kern) and refactors filter copying, attachment, detaching, and rollback handling upon error. Because /dev/net/tun ioctls (such as TUNATTACHFILTER and TUNSETIFF) are directly accessible from userspace in virtualized environments and the patch touches memory management, error rollback paths, and BPF validation, fuzzing is warranted to uncover any lifetime issues, memory leaks, or rollback inconsistencies.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 6bd4c0b8eb4529e17a0485d1e2c51f9231e4d988
Author: syz-cluster <triage@syzkaller.com>
Date:   Sat Oct 31 04:54:44 2026 +0000

    syz-cluster: applied patch under review

diff --git a/drivers/net/tun.c b/drivers/net/tun.c
index 439565a264ee79..c121ad50f31bb3 100644
--- a/drivers/net/tun.c
+++ b/drivers/net/tun.c
@@ -197,6 +197,7 @@ struct tun_struct {
 	int			sndbuf;
 	struct tap_filter	txflt;
 	struct sock_fprog	fprog;
+	struct sock_fprog_kern	fprog_kern;
 	/* protected by rtnl lock */
 	bool			filter_attached;
 	u32			msg_enable;
@@ -726,12 +727,69 @@ static void tun_force_wake_queue(struct tun_struct *tun,
 	spin_unlock_bh(&tfile->tx_ring.consumer_lock);
 }
 
+/* Copy the filter that @argp points at into the kernel, so that it can be
+ * installed again later, independent of the ioctl caller's address space.
+ * @fprog_kern receives the copy, which belongs to the caller until it is
+ * installed or freed, and @fprog receives the header, with the user pointer
+ * kept for TUNGETFILTER.
+ */
+static int tun_copy_filter(struct sock_fprog __user *argp,
+			   struct sock_fprog *fprog,
+			   struct sock_fprog_kern *fprog_kern)
+{
+	struct sock_fprog fp;
+	struct sock_filter *insns;
+	int err;
+
+	if (copy_from_user(&fp, argp, sizeof(fp)))
+		return -EFAULT;
+
+	if (!fp.len || fp.len > BPF_MAXINSNS)
+		return -EINVAL;
+
+	insns = kmalloc_array(fp.len, sizeof(struct sock_filter),
+			      GFP_KERNEL_ACCOUNT);
+	if (!insns)
+		return -ENOMEM;
+
+	if (copy_from_user(insns, fp.filter,
+			   fp.len * sizeof(struct sock_filter))) {
+		kfree(insns);
+		return -EFAULT;
+	}
+
+	/* The instructions are only verified when a program is built from
+	 * them, which happens when the filter is attached to a socket. Run
+	 * the classic verifier here as well, so that a bad program is
+	 * refused before it is saved and before any queue is touched.
+	 * bpf_prog_create() can still refuse the program later, when it is
+	 * converted to eBPF or when no runtime can be selected for it; the
+	 * attach path returns that error, and the saved program is not
+	 * replaced.
+	 */
+	err = bpf_prog_validate_classic(insns, fp.len);
+	if (err) {
+		kfree(insns);
+		return err;
+	}
+
+	/* Zero the whole header before filling it in. */
+	memset(fprog, 0, sizeof(*fprog));
+	fprog->len = fp.len;
+	fprog->filter = fp.filter;
+	fprog_kern->len = fp.len;
+	fprog_kern->filter = insns;
+
+	return 0;
+}
+
 static int tun_attach(struct tun_struct *tun, struct file *file,
 		      bool skip_filter, bool napi, bool napi_frags,
 		      bool publish_tun)
 {
 	struct tun_file *tfile = file->private_data;
 	struct net_device *dev = tun->dev;
+	bool rollback_filter = false;
 	int err;
 
 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
@@ -756,10 +814,11 @@ static int tun_attach(struct tun_struct *tun, struct file *file,
 	/* Re-attach the filter to persist device */
 	if (!skip_filter && (tun->filter_attached == true)) {
 		lock_sock(tfile->socket.sk);
-		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
+		err = sk_attach_filter_kern(&tun->fprog_kern, tfile->socket.sk);
 		release_sock(tfile->socket.sk);
-		if (!err)
+		if (err)
 			goto out;
+		rollback_filter = true;
 	}
 
 	if (!tfile->detached &&
@@ -821,6 +880,17 @@ static int tun_attach(struct tun_struct *tun, struct file *file,
 	WRITE_ONCE(tun->numqueues, tun->numqueues + 1);
 	tun_set_real_num_queues(tun);
 out:
+	if (err && rollback_filter) {
+		/* The filter was installed before the rest of the attach
+		 * ran, so drop it again if a later step failed. Any
+		 * program it replaced is already gone: this leaves the
+		 * queue without a filter rather than restoring the
+		 * previous one.
+		 */
+		lock_sock(tfile->socket.sk);
+		sk_detach_filter(tfile->socket.sk);
+		release_sock(tfile->socket.sk);
+	}
 	return err;
 }
 
@@ -2406,6 +2476,7 @@ static void tun_free_netdev(struct net_device *dev)
 	security_tun_dev_free_security(tun->security);
 	__tun_set_ebpf(tun, &tun->steering_prog, NULL);
 	__tun_set_ebpf(tun, &tun->filter_prog, NULL);
+	kfree(tun->fprog_kern.filter);
 }
 
 static void tun_setup(struct net_device *dev)
@@ -3070,10 +3141,14 @@ static void tun_detach_filter(struct tun_struct *tun, int n)
 		release_sock(tfile->socket.sk);
 	}
 
+	kfree(tun->fprog_kern.filter);
+	tun->fprog_kern.filter = NULL;
+	tun->fprog_kern.len = 0;
 	tun->filter_attached = false;
 }
 
-static int tun_attach_filter(struct tun_struct *tun)
+static int tun_attach_filter(struct tun_struct *tun,
+			     struct sock_fprog_kern *fprog_kern)
 {
 	int i, ret = 0;
 	struct tun_file *tfile;
@@ -3081,15 +3156,29 @@ static int tun_attach_filter(struct tun_struct *tun)
 	for (i = 0; i < tun->numqueues; i++) {
 		tfile = rtnl_dereference(tun->tfiles[i]);
 		lock_sock(tfile->socket.sk);
-		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
+		ret = sk_attach_filter_kern(fprog_kern, tfile->socket.sk);
 		release_sock(tfile->socket.sk);
-		if (ret) {
-			tun_detach_filter(tun, i);
-			return ret;
-		}
+		if (ret)
+			goto out_detach;
 	}
 
 	tun->filter_attached = true;
+	return 0;
+
+out_detach:
+	/* Drop the copies already installed on queues 0..i-1, which leaves
+	 * them without a filter: their previous sk_filter, if any, was
+	 * already replaced and released. The caller does not replace the
+	 * saved program when this fails, so tun->fprog, tun->fprog_kern and
+	 * filter_attached keep their previous values.
+	 */
+	while (i--) {
+		tfile = rtnl_dereference(tun->tfiles[i]);
+		lock_sock(tfile->socket.sk);
+		sk_detach_filter(tfile->socket.sk);
+		release_sock(tfile->socket.sk);
+	}
+
 	return ret;
 }
 
@@ -3424,17 +3513,31 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
 		tun_set_sndbuf(tun);
 		break;
 
-	case TUNATTACHFILTER:
+	case TUNATTACHFILTER: {
+		struct sock_fprog_kern fprog_kern;
+		struct sock_fprog fprog;
+
 		/* Can be set only for TAPs */
 		ret = -EINVAL;
 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
 			break;
-		ret = -EFAULT;
-		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
+
+		ret = tun_copy_filter(argp, &fprog, &fprog_kern);
+		if (ret)
+			break;
+
+		ret = tun_attach_filter(tun, &fprog_kern);
+		if (ret) {
+			kfree(fprog_kern.filter);
 			break;
+		}
 
-		ret = tun_attach_filter(tun);
+		/* Install the copy only after every queue accepted it. */
+		kfree(tun->fprog_kern.filter);
+		tun->fprog_kern = fprog_kern;
+		tun->fprog = fprog;
 		break;
+	}
 
 	case TUNDETACHFILTER:
 		/* Can be set only for TAPs */
diff --git a/include/linux/filter.h b/include/linux/filter.h
index e0218e677a1dcd..7169c03610b445 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -1257,8 +1257,10 @@ int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog);
 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
 			      bpf_aux_classic_check_t trans, bool save_orig);
 void bpf_prog_destroy(struct bpf_prog *fp);
+int bpf_prog_validate_classic(const struct sock_filter *insns, unsigned int len);
 
 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk);
+int sk_attach_filter_kern(struct sock_fprog_kern *fprog, struct sock *sk);
 int sk_attach_bpf(u32 ufd, struct sock *sk);
 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk);
 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk);
diff --git a/net/core/filter.c b/net/core/filter.c
index b7ac145b68b1f8..61b2d223c44563 100644
--- a/net/core/filter.c
+++ b/net/core/filter.c
@@ -1476,6 +1476,32 @@ void bpf_prog_destroy(struct bpf_prog *fp)
 }
 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
 
+/**
+ * bpf_prog_validate_classic - run the classic BPF verifier on kernel memory
+ * @insns: instruction array
+ * @len: number of instructions in @insns
+ *
+ * Run bpf_check_basics_ok() and bpf_check_classic() on a program that is
+ * already in kernel memory, without building a struct bpf_prog.  These are
+ * the checks bpf_prog_create() runs before it converts the program, so
+ * callers can reject a bad program when it is configured instead of when it
+ * is first attached to a socket.
+ *
+ * A program that passes here can still be refused by bpf_prog_create(), when
+ * it is converted to eBPF or when no runtime can be selected for it.
+ *
+ * Return: 0 if the program passes the classic verifier, -EINVAL if it does
+ * not, or -ENOMEM if the verifier cannot allocate its state.
+ */
+int bpf_prog_validate_classic(const struct sock_filter *insns, unsigned int len)
+{
+	if (!bpf_check_basics_ok(insns, len))
+		return -EINVAL;
+
+	return bpf_check_classic(insns, len);
+}
+EXPORT_SYMBOL_GPL(bpf_prog_validate_classic);
+
 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
 {
 	struct sk_filter *fp, *old_fp;
@@ -1567,6 +1593,47 @@ int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
 }
 EXPORT_SYMBOL_GPL(sk_attach_filter);
 
+/**
+ * sk_attach_filter_kern - attach a classic BPF filter held in kernel memory
+ * @fprog: program to attach, with @fprog->filter pointing at kernel memory
+ * @sk: socket to attach the filter to
+ *
+ * Attach a copy of a classic BPF program that the kernel already holds, the
+ * way sk_attach_filter() does for one that still lives in user space. The
+ * caller must hold the socket lock; SOCK_FILTER_LOCKED is checked here.
+ *
+ * The program is built by bpf_prog_create(), which does not keep an original
+ * copy of the instructions, so sk_get_filter() returns -EACCES and sock_diag
+ * omits the filter for a socket that uses this helper.
+ *
+ * Return: 0 on success, or a negative errno: -EPERM if @sk has
+ * SOCK_FILTER_LOCKED set, otherwise whatever bpf_prog_create() or
+ * __sk_attach_prog() returned (for example -EINVAL for an invalid classic
+ * BPF program, -ENOMEM, or -ENOTSUPP when a JIT is required but is not
+ * available).
+ */
+int sk_attach_filter_kern(struct sock_fprog_kern *fprog, struct sock *sk)
+{
+	struct bpf_prog *prog;
+	int err;
+
+	if (sock_flag(sk, SOCK_FILTER_LOCKED))
+		return -EPERM;
+
+	err = bpf_prog_create(&prog, fprog);
+	if (err)
+		return err;
+
+	err = __sk_attach_prog(prog, sk);
+	if (err < 0) {
+		__bpf_prog_release(prog);
+		return err;
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(sk_attach_filter_kern);
+
 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
 {
 	struct bpf_prog *prog = __get_filter(fprog, sk);
diff --git a/tools/testing/selftests/net/tun.c b/tools/testing/selftests/net/tun.c
index 34de2580e32eca..3730fba859a46e 100644
--- a/tools/testing/selftests/net/tun.c
+++ b/tools/testing/selftests/net/tun.c
@@ -9,9 +9,11 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <linux/filter.h>
 #include <linux/if_tun.h>
 #include <netinet/tcp.h>
 #include <sys/ioctl.h>
+#include <sys/mman.h>
 #include <sys/socket.h>
 
 #include "kselftest_harness.h"
@@ -548,6 +550,253 @@ TEST_F(tun, reattach_close_delete)
 	EXPECT_EQ(tun_delete(self->ifname), 0);
 }
 
+/* accept: return skb->len.  Three instructions on purpose, so that the
+ * length read back through TUNGETFILTER tells it apart from a rejected
+ * program that is shorter.
+ */
+static const struct sock_filter filter_accept[] = {
+	BPF_STMT(BPF_LD | BPF_W | BPF_LEN, 0),
+	BPF_STMT(BPF_ALU | BPF_ADD | BPF_K, 0),
+	BPF_STMT(BPF_RET | BPF_A, 0),
+};
+
+/* Put the instructions in an anonymous mapping, so that the test can make the
+ * address unreadable afterwards.
+ */
+static void *filter_alloc(const struct sock_filter *insns, unsigned int len)
+{
+	void *p;
+
+	p = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE,
+		 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+	if (p == MAP_FAILED)
+		return NULL;
+
+	memcpy(p, insns, len * sizeof(*insns));
+
+	return p;
+}
+
+static int filter_attach(int fd, const struct sock_filter *insns, unsigned int len)
+{
+	struct sock_fprog fp = {
+		.len = len,
+		.filter = (struct sock_filter *)insns,
+	};
+
+	return ioctl(fd, TUNATTACHFILTER, (void *)&fp);
+}
+
+static int filter_get(int fd, struct sock_fprog *fp)
+{
+	return ioctl(fd, TUNGETFILTER, (void *)fp);
+}
+
+static int tun_get_iff_flags(int fd)
+{
+	struct ifreq ifr = { 0 };
+
+	if (ioctl(fd, TUNGETIFF, (void *)&ifr) < 0)
+		return -1;
+
+	return ifr.ifr_flags;
+}
+
+/*
+ * A queue can be attached long after the filter was configured, from a
+ * process that does not necessarily map the buffer the program was copied
+ * from, so the kernel has to keep its own copy of the program.  Here the
+ * mapping is made unreadable before the queue is attached again, and a
+ * second queue is then attached from a fresh socket, which starts without a
+ * filter of its own.
+ */
+TEST_F(tun, reattach_filter_without_user_buffer)
+{
+	struct sock_fprog gf = { 0 };
+	struct ifreq ifr = { 0 };
+	short flags = 0;
+	void *prog;
+	int fd, ret;
+
+	prog = filter_alloc(filter_accept, ARRAY_SIZE(filter_accept));
+	ASSERT_NE(prog, NULL);
+	ASSERT_EQ(filter_attach(self->fd, prog, ARRAY_SIZE(filter_accept)), 0);
+
+	EXPECT_EQ(tun_detach(self->fd, self->ifname), 0);
+
+	/* This memory is no longer readable */
+	ASSERT_EQ(mprotect(prog, getpagesize(), PROT_NONE), 0);
+
+	ret = tun_attach(self->fd, self->ifname);
+	EXPECT_EQ(ret, 0);
+
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	/* The queue is attached again, not left disabled */
+	EXPECT_EQ(flags & IFF_DETACH_QUEUE, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	/* The two checks below document the expected state, they cannot
+	 * tell a reinstalled filter from no filter: tun_detach() leaves
+	 * sk_filter alone, and TUNGETFILTER only returns the header.
+	 */
+	EXPECT_EQ(filter_get(self->fd, &gf), 0);
+	EXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));
+
+	/* A new queue starts without a filter, so a clear IFF_NOFILTER shows
+	 * that the filter was installed again from the kernel copy.
+	 */
+	fd = open("/dev/net/tun", O_RDWR);
+	ASSERT_GE(fd, 0);
+
+	strcpy(ifr.ifr_name, self->ifname);
+	ifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;
+	EXPECT_GE(ioctl(fd, TUNSETIFF, (void *)&ifr), 0);
+
+	flags = tun_get_iff_flags(fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	close(fd);
+
+	ASSERT_EQ(mprotect(prog, getpagesize(), PROT_READ | PROT_WRITE), 0);
+	ASSERT_EQ(munmap(prog, getpagesize()), 0);
+}
+
+/* A new queue attached with IFF_NOFILTER must not get the filter that is
+ * configured on the device.
+ */
+TEST_F(tun, attach_filter_nofilter_flag)
+{
+	struct ifreq ifr = { 0 };
+	short flags = 0;
+	int fd;
+
+	ASSERT_EQ(filter_attach(self->fd, filter_accept, ARRAY_SIZE(filter_accept)), 0);
+
+	fd = open("/dev/net/tun", O_RDWR);
+	ASSERT_GE(fd, 0);
+
+	strcpy(ifr.ifr_name, self->ifname);
+	ifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE | IFF_NOFILTER;
+	EXPECT_GE(ioctl(fd, TUNSETIFF, (void *)&ifr), 0);
+
+	flags = tun_get_iff_flags(fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, IFF_NOFILTER);
+
+	close(fd);
+}
+
+/* After TUNDETACHFILTER a later attach must not install the filter again */
+TEST_F(tun, detach_filter_clears_reattach)
+{
+	short flags = 0;
+
+	ASSERT_EQ(filter_attach(self->fd, filter_accept, ARRAY_SIZE(filter_accept)), 0);
+	EXPECT_EQ(ioctl(self->fd, TUNDETACHFILTER, 0), 0);
+
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, IFF_NOFILTER);
+
+	EXPECT_EQ(tun_detach(self->fd, self->ifname), 0);
+	EXPECT_EQ(tun_attach(self->fd, self->ifname), 0);
+
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, IFF_NOFILTER);
+}
+
+/* A TUNATTACHFILTER with a bad length must leave the installed program and the
+ * filter state that TUNGETIFF reports alone.
+ */
+TEST_F(tun, attach_filter_bad_len_keeps_program)
+{
+	struct sock_fprog gf = { 0 };
+	struct ifreq ifr = { 0 };
+	short flags = 0;
+	int fd;
+
+	ASSERT_EQ(filter_attach(self->fd, filter_accept, ARRAY_SIZE(filter_accept)), 0);
+
+	errno = 0;
+	EXPECT_EQ(filter_attach(self->fd, filter_accept, 0), -1);
+	EXPECT_EQ(errno, EINVAL);
+
+	EXPECT_EQ(filter_get(self->fd, &gf), 0);
+	EXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));
+
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	/* A queue attached afterwards still gets the filter, so the rejected
+	 * ioctl left the saved program and filter_attached alone.
+	 */
+	fd = open("/dev/net/tun", O_RDWR);
+	ASSERT_GE(fd, 0);
+
+	strcpy(ifr.ifr_name, self->ifname);
+	ifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;
+	EXPECT_GE(ioctl(fd, TUNSETIFF, (void *)&ifr), 0);
+
+	flags = tun_get_iff_flags(fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	close(fd);
+}
+
+/* A TUNATTACHFILTER with instructions that bpf_check_classic() rejects must
+ * be refused, and must leave the program installed already in place.
+ */
+TEST_F(tun, attach_filter_bad_prog_keeps_program)
+{
+	struct sock_fprog gf = { 0 };
+	struct sock_filter bad[] = {
+		BPF_STMT(BPF_LD | BPF_W | BPF_LEN, 0),
+		BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 1, 0),
+	};
+	struct ifreq ifr = { 0 };
+	short flags = 0;
+	int fd;
+
+	ASSERT_EQ(filter_attach(self->fd, filter_accept,
+				ARRAY_SIZE(filter_accept)), 0);
+
+	errno = 0;
+	EXPECT_EQ(filter_attach(self->fd, bad, ARRAY_SIZE(bad)), -1);
+	EXPECT_EQ(errno, EINVAL);
+
+	/* the program attached before is untouched */
+	EXPECT_EQ(filter_get(self->fd, &gf), 0);
+	EXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));
+
+	/* IFF_NOFILTER comes from the socket's sk_filter, not from the saved
+	 * header, so a clear flag shows the filter is still installed.
+	 */
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	/* A queue attached afterwards still gets the filter, so the rejected
+	 * program never replaced the saved one.
+	 */
+	fd = open("/dev/net/tun", O_RDWR);
+	ASSERT_GE(fd, 0);
+
+	strcpy(ifr.ifr_name, self->ifname);
+	ifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;
+	EXPECT_GE(ioctl(fd, TUNSETIFF, (void *)&ifr), 0);
+
+	flags = tun_get_iff_flags(fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	close(fd);
+}
+
 FIXTURE(tun_vnet_gso)
 {
 	char ifname[IFNAMSIZ];

3/2 2026/10/31 04:54 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 9849
							output: 29
							thoughts: 917
						

Thoughts:
**Analyzing a Kernel Git Commit: Tun/Tap BPF Filter Upgrade**

Alright, let's dive into this patch. The user wants me to evaluate this git commit targeting the kernel, and I need to assess its potential implications. I'll approach this systematically.

First, I need to understand what this patch *does*. It looks like a significant upgrade to how BPF filters are handled in the `tun` driver. Specifically, it's introducing a kernel-side BPF filter storage and management system (`struct sock_fprog_kern fprog_kern`) for tun devices.

Here's the breakdown:

*   **`drivers/net/tun.c`:** This is where the core changes reside. It's adding the `fprog_kern` structure to `struct tun_struct`. There's also a new `tun_copy_filter` function that securely copies BPF instructions from user space. It performs kernel memory allocation (`kmalloc_array`), safely copies the filter instructions from user space (`copy_from_user`), and crucially, *validates* them using `bpf_prog_validate_classic`. The `tun_attach` function is being updated to use `sk_attach_filter_kern()` when attaching filters. It appears to fix a bug in the old code related to error handling and rollbacks. The new code includes proper filter detachment and freeing in `tun_free_netdev()`, `tun_detach_filter()`, and, importantly, includes error handling and rollback in `tun_attach_filter()`, which is good.  `__tun_chr_ioctl()` now leverages `tun_copy_filter` and `tun_attach_filter` in response to the `TUNATTACHFILTER` ioctl. Old kernel filters are freed, and `tun->fprog_kern` and `tun->fprog` are updated.

*   **`include/linux/filter.h`:** This is straightforward: declarations for the new functions, `bpf_prog_validate_classic` and `sk_attach_filter_kern`.

*   **`net/core/filter.c`:**  The implementations for the new functions. This is where the core BPF validation and attachment logic lives.

*   **`tools/testing/selftests/net/tun.c`:**  Excellent!  The patch includes selftests, which is a big plus.

Now, let's assess the *potential* impact from a vulnerability perspective:

1.  **Reachability:**  `/dev/net/tun` is a standard tun/tap device. This means the code is *absolutely* reachable in common environments (QEMU, cloud VMs, etc.). Syzkaller and other fuzzers extensively use tun/tap, so this is high value for fuzzing.

2.  **Fuzzing Potential:** This is *prime* fuzzing material. It touches the very core of networking (tun), packet filtering (net/core/filter), and user-kernel interaction.  I see potential issues around:
    *   **Memory Allocation:** `kmalloc_array` in `tun_copy_filter` needs scrutiny.
    *   **User Copy:** `copy_from_user` *always* demands a careful look.  This is a classic vulnerability point.
    *   **BPF Validation:** The new `bpf_prog_validate_classic` needs thorough analysis. Does it catch *all* potential BPF exploits?
    *   **Filter Attachment:** The interaction with sockets (`sk_attach_filter_kern`) is also important.
    *   **Error Rollback:** The new error handling and rollback logic is complex. It's a gold mine for potential race conditions, use-after-frees, and double-frees. The lifecycle of `fprog_kern.filter` – allocating, copying, validating, attaching, detaching, and freeing – has several spots for flaws to arise.

Finally, I need to verify configuration requirements: I'll check `drivers/net/Kconfig` or `drivers/net/Makefile` to confirm that `CONFIG_TUN` is the crucial configuration option.



4/2 2026/10/31 04:54 tool grepper
0m Args:
{
  "Expression": "tun\\.o",
  "PathPrefixes": [
    "drivers/net/Makefile"
  ]
}

Results:
{
  "Output": "drivers/net/Makefile=31=obj-$(CONFIG_NET_TEAM) += team/\ndrivers/net/Makefile:32:obj-$(CONFIG_TUN) += tun.o\ndrivers/net/Makefile-33-obj-$(CONFIG_TAP) += tap.o\n"
}

5/2 2026/10/31 04:54 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 11754
							output: 29
							thoughts: 11
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience and presented in the first person:

**Navigating the Kconfig Landscape**

Right, let's get down to brass tacks. My initial thought process is always a methodical one. We need to ascertain if `CONFIG_TUN` is enabled or even defined within the current kernel configuration. That's the logical starting point for any investigation into TUN/TAP interfaces, obviously. I'm mentally parsing the likely Kconfig files... specifically, the ones related to networking or drivers, knowing full well that they can be spread across multiple files depending on the complexity of the platform and the modularity of the relevant components. I need to quickly determine the visibility of this symbol. Is it a direct config, part of a tristate option, or conditionally compiled based on other dependencies? Finding this setting will dictate my next move. This is basic, but it establishes a firm foundation. I'm already anticipating the possibilities: Is it hardcoded, user-selectable, or perhaps subtly hidden? The Kconfig files will tell the tale.



6/2 2026/10/31 04:55 tool grepper
0m Args:
{
  "Expression": "config TUN\\b",
  "PathPrefixes": [
    "drivers/net/"
  ]
}

Results:
{
  "Output": "drivers/net/Kconfig=386=config RIONET_RX_SIZE\n--\ndrivers/net/Kconfig-390-\ndrivers/net/Kconfig:391:config TUN\ndrivers/net/Kconfig-392-\ttristate \"Universal TUN/TAP device driver support\"\n"
}

7/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 12105
							output: 34
							thoughts: 26
						

Thoughts:
Here's my take on the thought process:

**Diving into the Network Driver Configuration**

Okay, let's get down to brass tacks. I need to understand the configuration options for the network drivers. Specifically, I'm thinking I'll start by examining the `Kconfig` file within the `drivers/net/` directory. Line 391 should be a good starting point. I'll use either `read-file` or `grepper` – whatever's quickest and most efficient given the tools I have available – to pull that specific section of the configuration file. Hopefully, that will give me the contextual information I'm looking for.



8/2 2026/10/31 04:55 tool read-file
0m Args:
{
  "File": "drivers/net/Kconfig",
  "FirstLine": 390,
  "LineCount": 20
}

Results:
{
  "Contents": " 390:\t\n 391:\tconfig TUN\n 392:\t\ttristate \"Universal TUN/TAP device driver support\"\n 393:\t\tdepends on INET\n 394:\t\tselect CRC32\n 395:\t\thelp\n 396:\t\t  TUN/TAP provides packet reception and transmission for user space\n 397:\t\t  programs.  It can be viewed as a simple Point-to-Point or Ethernet\n 398:\t\t  device, which instead of receiving packets from a physical media,\n 399:\t\t  receives them from user space program and instead of sending packets\n 400:\t\t  via physical media writes them to the user space program.\n 401:\t\n 402:\t\t  When a program opens /dev/net/tun, driver creates and registers\n 403:\t\t  corresponding net device tunX or tapX.  After a program closed above\n 404:\t\t  devices, driver will automatically delete tunXX or tapXX device and\n 405:\t\t  all routes corresponding to it.\n 406:\t\n 407:\t\t  Please read \u003cfile:Documentation/networking/tuntap.rst\u003e for more\n 408:\t\t  information.\n 409:\t\n"
}

9/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 12624
							output: 29
							thoughts: 57
						

Thoughts:
**Examining the Kernel's Network Filter Configuration**

Okay, so `CONFIG_TUN` is dependent on `INET`. That's my starting point. Now, to understand how the network filter components are wired in, I need to dig into `net/core/filter.c`. I'm wondering though, is this filter module a core, always-present piece, or is it contingent on something else – specifically, is it controlled by `NET/BPF`? I need to clarify that dependency. Best bet is to check the `net/core/Makefile`, which should illuminate the conditional compilation rules and reveal how this component integrates into the build process.



10/2 2026/10/31 04:55 tool grepper
0m Args:
{
  "Expression": "filter\\.o",
  "PathPrefixes": [
    "net/core/Makefile"
  ]
}

Results:
{
  "Output": "net/core/Makefile=12=obj-y\t\t     += dev.o dev_api.o dev_addr_lists.o dst.o netevent.o \\\nnet/core/Makefile:13:\t\t\tneighbour.o rtnetlink.o utils.o link_watch.o filter.o \\\nnet/core/Makefile-14-\t\t\tsock_diag.o dev_ioctl.o tso.o sock_reuseport.o \\\n"
}

11/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 12962
							output: 33
							thoughts: 83
						

Thoughts:
Here's my thought process, as it stands:

**Navigating Kernel Networking and Filtering Logic**

Okay, so `filter.o` is being compiled into the kernel (`obj-y`) when networking (`CONFIG_NET`) is active. That makes sense, but now I need to understand how it interacts with the TUN device, especially since `CONFIG_TUN` is dependent on `CONFIG_INET`. I suspect there's a connection here. I'm going to dig into the `drivers/net/tun.c` file. Specifically, I'm looking for where those filter-related ioctls – `TUNATTACHFILTER`, `TUNDETACHFILTER`, and `TUNGETFILTER` – are actually *handled*. I need to see how the system calls reach these filter functions, and ultimately, how `tun_chr_ioctl` fits into the picture. My suspicion is that this `tun_chr_ioctl` routine is the central point for handling the ioctl calls from user-space for the TUN device.



12/2 2026/10/31 04:55 tool grepper
0m Args:
{
  "Expression": "tun_chr_ioctl",
  "PathPrefixes": [
    "drivers/net/tun.c"
  ]
}

Results:
{
  "Output": "drivers/net/tun.c=3253=static unsigned char tun_get_addr_len(unsigned short type)\n--\ndrivers/net/tun.c-3290-\ndrivers/net/tun.c:3291:static long __tun_chr_ioctl(struct file *file, unsigned int cmd,\ndrivers/net/tun.c-3292-\t\t\t    unsigned long arg, int ifreq_len)\n--\ndrivers/net/tun.c-3367-\ndrivers/net/tun.c:3368:\tnetif_info(tun, drv, tun-\u003edev, \"tun_chr_ioctl cmd %u\\n\", cmd);\ndrivers/net/tun.c-3369-\n--\ndrivers/net/tun.c-3598-\ndrivers/net/tun.c:3599:static long tun_chr_ioctl(struct file *file,\ndrivers/net/tun.c-3600-\t\t\t  unsigned int cmd, unsigned long arg)\ndrivers/net/tun.c-3601-{\ndrivers/net/tun.c:3602:\treturn __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));\ndrivers/net/tun.c-3603-}\n--\ndrivers/net/tun.c=3606=static long tun_chr_compat_ioctl(struct file *file,\n--\ndrivers/net/tun.c-3629-\t */\ndrivers/net/tun.c:3630:\treturn __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));\ndrivers/net/tun.c-3631-}\n--\ndrivers/net/tun.c=3728=static const struct file_operations tun_fops = {\n--\ndrivers/net/tun.c-3732-\t.poll\t= tun_chr_poll,\ndrivers/net/tun.c:3733:\t.unlocked_ioctl\t= tun_chr_ioctl,\ndrivers/net/tun.c-3734-#ifdef CONFIG_COMPAT\n"
}

13/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 13812
							output: 35
							thoughts: 847
						

Thoughts:
**Analyzing Potential Fuzzing Targets in the TUN Driver and BPF Filter Integration**

Okay, let's dive into this patch. My initial focus is on identifying key functions that would be worthwhile targets for fuzzing, specifically those added or modified within the tun driver and related BPF filter integration. I need to make sure I don't select any of the common ubiquitous lifecyle hot-paths, and I target specific feature logic and entrypoints.

The first step is to enumerate the functions. I see we have modifications or additions to the following:

*   In `net/core/filter.c`: `bpf_prog_validate_classic` and `sk_attach_filter_kern`.
*   In `drivers/net/tun.c`: `tun_copy_filter`, `tun_attach`, `tun_free_netdev`, `tun_detach_filter`, `tun_attach_filter`, and `__tun_chr_ioctl` (or `tun_chr_ioctl`).

Now, I need to check these against the 'FocusSymbols' guidelines for fuzzing. Are these static or global? Are they core infrastructure?

Let's start with `tun.c`. I notice `tun_copy_filter` is `static`. This is a slight concern regarding symbol visibility, but static functions in .c files often have symbols if not inlined. I need to investigate its callers and entry points.

I have a list of entry points: `__tun_chr_ioctl` (or `tun_chr_ioctl`), `tun_attach`, `tun_attach_filter`, `tun_detach_filter`, `tun_copy_filter`, `tun_free_netdev`, `sk_attach_filter_kern`, `bpf_prog_validate_classic`.

Now, let's assess them:

*   `__tun_chr_ioctl`: This is *not* ubiquitous; it's specific to `/dev/net/tun` ioctls. Good candidate.
*   `sk_attach_filter_kern`: This is *not* ubiquitous; it was just introduced. Another good one.
*   `bpf_prog_validate_classic`: Again, *not* ubiquitous. This is promising.
*   `tun_attach`: This is *not* ubiquitous; it's specific to the tun device attach. Promising.
*   `tun_attach_filter`: This is *not* ubiquitous; it's for attaching filters to tun devices. Great.
*   `tun_detach_filter`: This is *not* ubiquitous; it's for detaching filters from tun devices. Excellent.
*   `tun_copy_filter`: This is *not* ubiquitous; it's for copying and validating classic BPF filters in tun. Very relevant!

So, the vast majority of these seem to fit the bill. I'm especially interested in understanding the interaction between `tun_copy_filter` and `tun_attach`. I need to review the code more closely. Time to examine the details, focusing on lines 720 to 890 of `drivers/net/tun.c`. I'm going to read this with a fine-tooth comb.



14/2 2026/10/31 04:55 tool read-file
0m Args:
{
  "File": "drivers/net/tun.c",
  "FirstLine": 725,
  "LineCount": 80
}

Results:
{
  "Contents": " 725:\t\t\tnetif_wake_subqueue(tun-\u003edev, tfile-\u003equeue_index);\n 726:\t\tspin_unlock(\u0026tfile-\u003etx_ring.producer_lock);\n 727:\t\tspin_unlock_bh(\u0026tfile-\u003etx_ring.consumer_lock);\n 728:\t}\n 729:\t\n 730:\t/* Copy the filter that @argp points at into the kernel, so that it can be\n 731:\t * installed again later, independent of the ioctl caller's address space.\n 732:\t * @fprog_kern receives the copy, which belongs to the caller until it is\n 733:\t * installed or freed, and @fprog receives the header, with the user pointer\n 734:\t * kept for TUNGETFILTER.\n 735:\t */\n 736:\tstatic int tun_copy_filter(struct sock_fprog __user *argp,\n 737:\t\t\t\t   struct sock_fprog *fprog,\n 738:\t\t\t\t   struct sock_fprog_kern *fprog_kern)\n 739:\t{\n 740:\t\tstruct sock_fprog fp;\n 741:\t\tstruct sock_filter *insns;\n 742:\t\tint err;\n 743:\t\n 744:\t\tif (copy_from_user(\u0026fp, argp, sizeof(fp)))\n 745:\t\t\treturn -EFAULT;\n 746:\t\n 747:\t\tif (!fp.len || fp.len \u003e BPF_MAXINSNS)\n 748:\t\t\treturn -EINVAL;\n 749:\t\n 750:\t\tinsns = kmalloc_array(fp.len, sizeof(struct sock_filter),\n 751:\t\t\t\t      GFP_KERNEL_ACCOUNT);\n 752:\t\tif (!insns)\n 753:\t\t\treturn -ENOMEM;\n 754:\t\n 755:\t\tif (copy_from_user(insns, fp.filter,\n 756:\t\t\t\t   fp.len * sizeof(struct sock_filter))) {\n 757:\t\t\tkfree(insns);\n 758:\t\t\treturn -EFAULT;\n 759:\t\t}\n 760:\t\n 761:\t\t/* The instructions are only verified when a program is built from\n 762:\t\t * them, which happens when the filter is attached to a socket. Run\n 763:\t\t * the classic verifier here as well, so that a bad program is\n 764:\t\t * refused before it is saved and before any queue is touched.\n 765:\t\t * bpf_prog_create() can still refuse the program later, when it is\n 766:\t\t * converted to eBPF or when no runtime can be selected for it; the\n 767:\t\t * attach path returns that error, and the saved program is not\n 768:\t\t * replaced.\n 769:\t\t */\n 770:\t\terr = bpf_prog_validate_classic(insns, fp.len);\n 771:\t\tif (err) {\n 772:\t\t\tkfree(insns);\n 773:\t\t\treturn err;\n 774:\t\t}\n 775:\t\n 776:\t\t/* Zero the whole header before filling it in. */\n 777:\t\tmemset(fprog, 0, sizeof(*fprog));\n 778:\t\tfprog-\u003elen = fp.len;\n 779:\t\tfprog-\u003efilter = fp.filter;\n 780:\t\tfprog_kern-\u003elen = fp.len;\n 781:\t\tfprog_kern-\u003efilter = insns;\n 782:\t\n 783:\t\treturn 0;\n 784:\t}\n 785:\t\n 786:\tstatic int tun_attach(struct tun_struct *tun, struct file *file,\n 787:\t\t\t      bool skip_filter, bool napi, bool napi_frags,\n 788:\t\t\t      bool publish_tun)\n 789:\t{\n 790:\t\tstruct tun_file *tfile = file-\u003eprivate_data;\n 791:\t\tstruct net_device *dev = tun-\u003edev;\n 792:\t\tbool rollback_filter = false;\n 793:\t\tint err;\n 794:\t\n 795:\t\terr = security_tun_dev_attach(tfile-\u003esocket.sk, tun-\u003esecurity);\n 796:\t\tif (err \u003c 0)\n 797:\t\t\tgoto out;\n 798:\t\n 799:\t\terr = -EINVAL;\n 800:\t\tif (rtnl_dereference(tfile-\u003etun) \u0026\u0026 !tfile-\u003edetached)\n 801:\t\t\tgoto out;\n 802:\t\n 803:\t\terr = -EBUSY;\n 804:\t\tif (!(tun-\u003eflags \u0026 IFF_MULTI_QUEUE) \u0026\u0026 tun-\u003enumqueues == 1)\n"
}

15/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 16640
							output: 35
							thoughts: 17
						

Thoughts:
Okay, here's the summary, rendered as if I am the expert thinking it:

**Focusing on a Crucial Section**

Right, I need to zoom in on lines 805 to 895. That specific block warrants further scrutiny. I need to understand what's contained in this section; it could be the lynchpin of the entire argument. I am confident that these lines contain some very important information that I need to study very carefully.



16/2 2026/10/31 04:55 tool read-file
0m Args:
{
  "File": "drivers/net/tun.c",
  "FirstLine": 805,
  "LineCount": 85
}

Results:
{
  "Contents": " 805:\t\t\tgoto out;\n 806:\t\n 807:\t\terr = -E2BIG;\n 808:\t\tif (!tfile-\u003edetached \u0026\u0026\n 809:\t\t    tun-\u003enumqueues + tun-\u003enumdisabled == MAX_TAP_QUEUES)\n 810:\t\t\tgoto out;\n 811:\t\n 812:\t\terr = 0;\n 813:\t\n 814:\t\t/* Re-attach the filter to persist device */\n 815:\t\tif (!skip_filter \u0026\u0026 (tun-\u003efilter_attached == true)) {\n 816:\t\t\tlock_sock(tfile-\u003esocket.sk);\n 817:\t\t\terr = sk_attach_filter_kern(\u0026tun-\u003efprog_kern, tfile-\u003esocket.sk);\n 818:\t\t\trelease_sock(tfile-\u003esocket.sk);\n 819:\t\t\tif (err)\n 820:\t\t\t\tgoto out;\n 821:\t\t\trollback_filter = true;\n 822:\t\t}\n 823:\t\n 824:\t\tif (!tfile-\u003edetached \u0026\u0026\n 825:\t\t    ptr_ring_resize(\u0026tfile-\u003etx_ring, dev-\u003etx_queue_len,\n 826:\t\t\t\t    GFP_KERNEL, tun_ptr_free)) {\n 827:\t\t\terr = -ENOMEM;\n 828:\t\t\tgoto out;\n 829:\t\t}\n 830:\t\n 831:\t\tspin_lock(\u0026tfile-\u003etx_ring.consumer_lock);\n 832:\t\ttfile-\u003equeue_index = tun-\u003enumqueues;\n 833:\t\tspin_unlock(\u0026tfile-\u003etx_ring.consumer_lock);\n 834:\t\ttfile-\u003esocket.sk-\u003esk_shutdown \u0026= ~RCV_SHUTDOWN;\n 835:\t\ttun_force_wake_queue(tun, tfile);\n 836:\t\n 837:\t\tif (tfile-\u003edetached) {\n 838:\t\t\t/* Re-attach detached tfile, updating XDP queue_index */\n 839:\t\t\tWARN_ON(!xdp_rxq_info_is_reg(\u0026tfile-\u003exdp_rxq));\n 840:\t\n 841:\t\t\tif (tfile-\u003exdp_rxq.queue_index    != tfile-\u003equeue_index)\n 842:\t\t\t\ttfile-\u003exdp_rxq.queue_index = tfile-\u003equeue_index;\n 843:\t\t} else {\n 844:\t\t\t/* Setup XDP RX-queue info, for new tfile getting attached */\n 845:\t\t\terr = xdp_rxq_info_reg(\u0026tfile-\u003exdp_rxq,\n 846:\t\t\t\t\t       tun-\u003edev, tfile-\u003equeue_index, 0);\n 847:\t\t\tif (err \u003c 0)\n 848:\t\t\t\tgoto out;\n 849:\t\t\terr = xdp_rxq_info_reg_mem_model(\u0026tfile-\u003exdp_rxq,\n 850:\t\t\t\t\t\t\t MEM_TYPE_PAGE_SHARED, NULL);\n 851:\t\t\tif (err \u003c 0) {\n 852:\t\t\t\txdp_rxq_info_unreg(\u0026tfile-\u003exdp_rxq);\n 853:\t\t\t\tgoto out;\n 854:\t\t\t}\n 855:\t\t\terr = 0;\n 856:\t\t}\n 857:\t\n 858:\t\tif (tfile-\u003edetached) {\n 859:\t\t\ttun_enable_queue(tfile);\n 860:\t\t\ttun_napi_enable(tfile);\n 861:\t\t} else {\n 862:\t\t\tsock_hold(\u0026tfile-\u003esk);\n 863:\t\t\ttun_napi_init(tun, tfile, napi, napi_frags);\n 864:\t\t}\n 865:\t\n 866:\t\tif (rtnl_dereference(tun-\u003exdp_prog))\n 867:\t\t\tsock_set_flag(\u0026tfile-\u003esk, SOCK_XDP);\n 868:\t\n 869:\t\t/* device is allowed to go away first, so no need to hold extra\n 870:\t\t * refcnt.\n 871:\t\t */\n 872:\t\n 873:\t\t/* Publish tfile-\u003etun and tun-\u003etfiles only after we've fully\n 874:\t\t * initialized tfile; otherwise we risk using half-initialized\n 875:\t\t * object.\n 876:\t\t */\n 877:\t\tif (publish_tun)\n 878:\t\t\trcu_assign_pointer(tfile-\u003etun, tun);\n 879:\t\trcu_assign_pointer(tun-\u003etfiles[tun-\u003enumqueues], tfile);\n 880:\t\tWRITE_ONCE(tun-\u003enumqueues, tun-\u003enumqueues + 1);\n 881:\t\ttun_set_real_num_queues(tun);\n 882:\tout:\n 883:\t\tif (err \u0026\u0026 rollback_filter) {\n 884:\t\t\t/* The filter was installed before the rest of the attach\n 885:\t\t\t * ran, so drop it again if a later step failed. Any\n 886:\t\t\t * program it replaced is already gone: this leaves the\n 887:\t\t\t * queue without a filter rather than restoring the\n 888:\t\t\t * previous one.\n 889:\t\t\t */\n"
}

17/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 18163
							output: 32
							thoughts: 30
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Investigating `fprog_kern` Usage in `tun.c`**

Okay, so we've identified one instance of `fprog_kern` being used within `tun.c`. Now, my next immediate step is to do a more thorough check within that source file. I need to scan `tun.c` methodically to ensure I've accounted for *every* possible usage of that specific kernel filter program construct. My focus is going to be on identifying all locations, in addition to the one we know, where `fprog_kern` is referenced, initialized, or passed to any functions. This is essential, of course, for a comprehensive understanding of how the filtering logic is applied and how it might be interacting with the rest of the TUN/TAP driver code. We need to be exhaustive here, I don't want to miss anything.



18/2 2026/10/31 04:55 tool grepper
0m Args:
{
  "Expression": "fprog_kern",
  "PathPrefixes": [
    "drivers/net/tun.c"
  ]
}

Results:
{
  "Output": "drivers/net/tun.c=182=struct tun_struct {\n--\ndrivers/net/tun.c-199-\tstruct sock_fprog\tfprog;\ndrivers/net/tun.c:200:\tstruct sock_fprog_kern\tfprog_kern;\ndrivers/net/tun.c-201-\t/* protected by rtnl lock */\n--\ndrivers/net/tun.c=711=static void tun_force_wake_queue(struct tun_struct *tun,\n--\ndrivers/net/tun.c-731- * installed again later, independent of the ioctl caller's address space.\ndrivers/net/tun.c:732: * @fprog_kern receives the copy, which belongs to the caller until it is\ndrivers/net/tun.c-733- * installed or freed, and @fprog receives the header, with the user pointer\n--\ndrivers/net/tun.c=736=static int tun_copy_filter(struct sock_fprog __user *argp,\ndrivers/net/tun.c-737-\t\t\t   struct sock_fprog *fprog,\ndrivers/net/tun.c:738:\t\t\t   struct sock_fprog_kern *fprog_kern)\ndrivers/net/tun.c-739-{\n--\ndrivers/net/tun.c-779-\tfprog-\u003efilter = fp.filter;\ndrivers/net/tun.c:780:\tfprog_kern-\u003elen = fp.len;\ndrivers/net/tun.c:781:\tfprog_kern-\u003efilter = insns;\ndrivers/net/tun.c-782-\n--\ndrivers/net/tun.c=786=static int tun_attach(struct tun_struct *tun, struct file *file,\n--\ndrivers/net/tun.c-816-\t\tlock_sock(tfile-\u003esocket.sk);\ndrivers/net/tun.c:817:\t\terr = sk_attach_filter_kern(\u0026tun-\u003efprog_kern, tfile-\u003esocket.sk);\ndrivers/net/tun.c-818-\t\trelease_sock(tfile-\u003esocket.sk);\n--\ndrivers/net/tun.c=2469=static void tun_free_netdev(struct net_device *dev)\n--\ndrivers/net/tun.c-2478-\t__tun_set_ebpf(tun, \u0026tun-\u003efilter_prog, NULL);\ndrivers/net/tun.c:2479:\tkfree(tun-\u003efprog_kern.filter);\ndrivers/net/tun.c-2480-}\n--\ndrivers/net/tun.c=3132=static void tun_detach_filter(struct tun_struct *tun, int n)\n--\ndrivers/net/tun.c-3143-\ndrivers/net/tun.c:3144:\tkfree(tun-\u003efprog_kern.filter);\ndrivers/net/tun.c:3145:\ttun-\u003efprog_kern.filter = NULL;\ndrivers/net/tun.c:3146:\ttun-\u003efprog_kern.len = 0;\ndrivers/net/tun.c-3147-\ttun-\u003efilter_attached = false;\n--\ndrivers/net/tun.c=3150=static int tun_attach_filter(struct tun_struct *tun,\ndrivers/net/tun.c:3151:\t\t\t     struct sock_fprog_kern *fprog_kern)\ndrivers/net/tun.c-3152-{\n--\ndrivers/net/tun.c-3158-\t\tlock_sock(tfile-\u003esocket.sk);\ndrivers/net/tun.c:3159:\t\tret = sk_attach_filter_kern(fprog_kern, tfile-\u003esocket.sk);\ndrivers/net/tun.c-3160-\t\trelease_sock(tfile-\u003esocket.sk);\n--\ndrivers/net/tun.c-3171-\t * already replaced and released. The caller does not replace the\ndrivers/net/tun.c:3172:\t * saved program when this fails, so tun-\u003efprog, tun-\u003efprog_kern and\ndrivers/net/tun.c-3173-\t * filter_attached keep their previous values.\n--\ndrivers/net/tun.c=3291=static long __tun_chr_ioctl(struct file *file, unsigned int cmd,\n--\ndrivers/net/tun.c-3516-\tcase TUNATTACHFILTER: {\ndrivers/net/tun.c:3517:\t\tstruct sock_fprog_kern fprog_kern;\ndrivers/net/tun.c-3518-\t\tstruct sock_fprog fprog;\n--\ndrivers/net/tun.c-3524-\ndrivers/net/tun.c:3525:\t\tret = tun_copy_filter(argp, \u0026fprog, \u0026fprog_kern);\ndrivers/net/tun.c-3526-\t\tif (ret)\n--\ndrivers/net/tun.c-3528-\ndrivers/net/tun.c:3529:\t\tret = tun_attach_filter(tun, \u0026fprog_kern);\ndrivers/net/tun.c-3530-\t\tif (ret) {\ndrivers/net/tun.c:3531:\t\t\tkfree(fprog_kern.filter);\ndrivers/net/tun.c-3532-\t\t\tbreak;\n--\ndrivers/net/tun.c-3535-\t\t/* Install the copy only after every queue accepted it. */\ndrivers/net/tun.c:3536:\t\tkfree(tun-\u003efprog_kern.filter);\ndrivers/net/tun.c:3537:\t\ttun-\u003efprog_kern = fprog_kern;\ndrivers/net/tun.c-3538-\t\ttun-\u003efprog = fprog;\n"
}

19/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 19867
							output: 36
							thoughts: 27
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Diving into the `tun` Driver's Filtering**

Right, time to get my hands dirty. I'm thinking I need to refresh my memory on how the `tun` driver, specifically within `drivers/net/tun.c`, handles filtering. My initial target is to double-check the implementation details for `TUNGETFILTER` and `TUNDETACHFILTER`. I want to see how these ioctls interact with the packet processing flow. I’m betting this will be key to understanding some recent performance anomalies I've seen in our test environment. I expect there's some nuance in how these filters are applied and when they're detached that could be the root cause. This should clarify a few open questions.



20/2 2026/10/31 04:55 tool read-file
0m Args:
{
  "File": "drivers/net/tun.c",
  "FirstLine": 3530,
  "LineCount": 40
}

Results:
{
  "Contents": "3530:\t\t\tif (ret) {\n3531:\t\t\t\tkfree(fprog_kern.filter);\n3532:\t\t\t\tbreak;\n3533:\t\t\t}\n3534:\t\n3535:\t\t\t/* Install the copy only after every queue accepted it. */\n3536:\t\t\tkfree(tun-\u003efprog_kern.filter);\n3537:\t\t\ttun-\u003efprog_kern = fprog_kern;\n3538:\t\t\ttun-\u003efprog = fprog;\n3539:\t\t\tbreak;\n3540:\t\t}\n3541:\t\n3542:\t\tcase TUNDETACHFILTER:\n3543:\t\t\t/* Can be set only for TAPs */\n3544:\t\t\tret = -EINVAL;\n3545:\t\t\tif ((tun-\u003eflags \u0026 TUN_TYPE_MASK) != IFF_TAP)\n3546:\t\t\t\tbreak;\n3547:\t\t\tret = 0;\n3548:\t\t\ttun_detach_filter(tun, tun-\u003enumqueues);\n3549:\t\t\tbreak;\n3550:\t\n3551:\t\tcase TUNGETFILTER:\n3552:\t\t\tret = -EINVAL;\n3553:\t\t\tif ((tun-\u003eflags \u0026 TUN_TYPE_MASK) != IFF_TAP)\n3554:\t\t\t\tbreak;\n3555:\t\t\tret = -EFAULT;\n3556:\t\t\tif (copy_to_user(argp, \u0026tun-\u003efprog, sizeof(tun-\u003efprog)))\n3557:\t\t\t\tbreak;\n3558:\t\t\tret = 0;\n3559:\t\t\tbreak;\n3560:\t\n3561:\t\tcase TUNSETSTEERINGEBPF:\n3562:\t\t\tret = tun_set_ebpf(tun, \u0026tun-\u003esteering_prog, argp);\n3563:\t\t\tbreak;\n3564:\t\n3565:\t\tcase TUNSETFILTEREBPF:\n3566:\t\t\tret = tun_set_ebpf(tun, \u0026tun-\u003efilter_prog, argp);\n3567:\t\t\tbreak;\n3568:\t\n3569:\t\tcase TUNSETCARRIER:\n"
}

21/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 20662
							output: 29
							thoughts: 692
						

Thoughts:
**Analyzing a Critical Fix in the TUN Driver for Security Vulnerabilities**

Okay, let's break down this commit. The core of the issue revolves around how the TUN driver previously handled BPF filters passed from user space. Before this patch, `TUNATTACHFILTER` essentially took a pointer to user memory containing the filter instructions (`tun->fprog.filter`). Later, when a new queue was attached, the kernel would try to use that pointer with `sk_attach_filter`, potentially leading to a crash or security violation. Specifically, if the user space memory was invalid, inaccessible, or from a different process, we'd be trying to dereference arbitrary memory. The previous implementation also had a critical bug where a successful attachment would skip attaching the queue!

This patch completely reworks this. Now, the kernel maintains its own, validated copy of the filter instructions in kernel memory (`tun->fprog_kern`). It allocates this using `kmalloc_array`, validates the BPF code with `bpf_prog_validate_classic`, and attaches it to all queues using a new helper, `sk_attach_filter_kern`. The patch handles rollback gracefully if any queue attachment fails. It also correctly frees the allocated kernel memory in `tun_detach_filter` and `tun_free_netdev`.

This is a pretty significant change. We're looking at substantial logic updates within `drivers/net/tun.c` (the core virtual networking driver) and in the network filtering code in `net/core/filter.c`. There's new code, including the helper functions `sk_attach_filter_kern`, `bpf_prog_validate_classic`, and `tun_copy_filter`, and changes in key areas like `tun_attach`, `tun_attach_filter`, `tun_detach_filter`, `tun_free_netdev`, and `__tun_chr_ioctl`.

Given this level of change, and the fact that the TUN device is directly reachable from userspace via `/dev/net/tun` ioctls – a common target for testing – this is *absolutely* something we should be fuzzing. Syzkaller already has excellent support for `/dev/net/tun`. The new code touches kernel memory allocation, pointer lifecycle, error paths, rollback mechanisms, lock handling (with `lock_sock`), and BPF validation - all prime fuzzing targets.

Before we get started, let's verify our configuration requirements. The TUN driver itself (`CONFIG_TUN`) is, obviously, required. Digging into the code, it looks like we need `CONFIG_TUN` for the driver itself, and in `net/core/filter.c`, `CONFIG_NET` and `CONFIG_BPF` are likely also needed to support this functionality, which we can confirm by examining `net/core/Makefile` and `init/Kconfig` or `net/Kconfig`. We must verify that these are enabled before fuzzing.



22/2 2026/10/31 04:55 tool grepper
0m Args:
{
  "Expression": "config TUN\\b",
  "PathPrefixes": [
    "drivers/net/"
  ]
}

Results:
{
  "Output": "drivers/net/Kconfig=386=config RIONET_RX_SIZE\n--\ndrivers/net/Kconfig-390-\ndrivers/net/Kconfig:391:config TUN\ndrivers/net/Kconfig-392-\ttristate \"Universal TUN/TAP device driver support\"\n"
}

23/2 2026/10/31 04:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22089
							output: 250
							thoughts: 1208
						

Thoughts:
**My Analysis of TUN/TAP Socket Filtering for Fuzzing**

Alright, let's get down to brass tacks. I'm looking at how to effectively fuzz the new classic BPF filter functionality added to the TUN/TAP driver. First, I need to nail down the relevant configurations. The code depends on `CONFIG_TUN`, which in turn hinges on `CONFIG_INET`. So, `TUN` and `INET` are the key enabling configurations. I'll make sure those are explicitly set.

Next, the critical part: identifying the *right* symbols to focus on for maximum fuzzing effectiveness. I need to select specific, non-ubiquitous functions that are added or modified by this patch.

I started by listing candidate functions: `tun_copy_filter`, `tun_attach_filter`, `tun_detach_filter`, `tun_attach`, `sk_attach_filter_kern`, `bpf_prog_validate_classic`, and `__tun_chr_ioctl` (or `tun_chr_ioctl`).

Hmm, but wait! Are any of these static and potentially inlined?  A quick check confirms `__tun_chr_ioctl` is static and called by `tun_chr_ioctl` and `tun_chr_compat_ioctl`, but `tun_chr_ioctl` is the fops entrypoint. Also, `tun_attach` is static but called by `tun_set_iff` and `tun_chr_ioctl`. The rest, `tun_copy_filter`, `tun_attach_filter` and `tun_detach_filter` are static functions called by `__tun_chr_ioctl`. And importantly, `sk_attach_filter_kern` and `bpf_prog_validate_classic` are global and exported.

So, `tun_chr_ioctl` is a good inclusion, it's the ioctl handler. And definitely `sk_attach_filter_kern` and `bpf_prog_validate_classic` are important, they are the new exported APIs in `net/core/filter.c`. And for completeness, I can include those core functions modified/added in `tun.c`: `tun_copy_filter`, `tun_attach_filter`, and `tun_attach`.

Let's double-check against the FocusSymbols guidelines: Avoid ubiquitous lifecycle hot-paths; target specific feature logic and entrypoints; and handle static inline functions appropriately. This means that I'll stick with functions that specifically implement the logic being added or altered. I don't want to include stuff that will just distract the fuzzer.

Okay, so the final list of FocusSymbols is: `sk_attach_filter_kern`, `bpf_prog_validate_classic`, `tun_copy_filter`, `tun_attach_filter`, `tun_detach_filter`, `tun_attach`, and `tun_chr_ioctl`. None of these are ubiquitous; they are all specific to the TUN/TAP socket filtering and classic BPF validation logic.

Now for a quick review to ensure the reasoning is clear and concise. This patch is readily accessible via `/dev/net/tun` ioctl operations in standard QEMU virtualized environments. The patch's changes include user-controlled memory copying, memory allocation, multi-queue filter attachment/rollback, lock handling, and BPF validation. High fuzzing value here, which is confirmed as WorthFuzzing. The focus symbols are set, and the enable configurations are set to `TUN` and `INET`.

Everything checks out. I'm ready to proceed with the next step. Let's call `set-results`.



24/2 2026/10/31 04:56 tool set-results
0m Args:
{
  "EnableConfigs": [
    "TUN",
    "INET"
  ],
  "FocusSymbols": [
    "sk_attach_filter_kern",
    "bpf_prog_validate_classic",
    "tun_copy_filter",
    "tun_attach_filter",
    "tun_detach_filter",
    "tun_attach",
    "tun_chr_ioctl"
  ],
  "Reasoning": "The patch modifies TUN/TAP device driver logic and socket filter attachment handling. It introduces kernel-side caching of classic BPF filter instructions (struct sock_fprog_kern) to allow safe reattachment of filters across detached queues and distinct address spaces. It adds new helpers (bpf_prog_validate_classic and sk_attach_filter_kern) and refactors filter copying, attachment, detaching, and rollback handling upon error. Because /dev/net/tun ioctls (such as TUNATTACHFILTER and TUNSETIFF) are directly accessible from userspace in virtualized environments and the patch touches memory management, error rollback paths, and BPF validation, fuzzing is warranted to uncover any lifetime issues, memory leaks, or rollback inconsistencies.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "TUN",
    "INET"
  ],
  "FocusSymbols": [
    "sk_attach_filter_kern",
    "bpf_prog_validate_classic",
    "tun_copy_filter",
    "tun_attach_filter",
    "tun_detach_filter",
    "tun_attach",
    "tun_chr_ioctl"
  ],
  "Reasoning": "The patch modifies TUN/TAP device driver logic and socket filter attachment handling. It introduces kernel-side caching of classic BPF filter instructions (struct sock_fprog_kern) to allow safe reattachment of filters across detached queues and distinct address spaces. It adds new helpers (bpf_prog_validate_classic and sk_attach_filter_kern) and refactors filter copying, attachment, detaching, and rollback handling upon error. Because /dev/net/tun ioctls (such as TUNATTACHFILTER and TUNSETIFF) are directly accessible from userspace in virtualized environments and the patch touches memory management, error rollback paths, and BPF validation, fuzzing is warranted to uncover any lifetime issues, memory leaks, or rollback inconsistencies.",
  "WorthFuzzing": true
}

25/1 2026/10/31 04:56 action If
3m Args:
{
  "WorthFuzzing": true
}

Results:
null

26/2 2026/10/31 04:56 agent kmsan-evaluator
3m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch updates the TUN driver to cache a kernel copy of classic BPF filters (struct sock_fprog_kern) to allow re-attaching filters across queue attachments without relying on the original process's address space.\n\nFrom a KMSAN perspective:\n- All stack variables (fp, fprog, fprog_kern) and heap buffers (insns) are either fully populated from copy_from_user or explicitly zeroed out with memset(fprog, 0, sizeof(*fprog)) before being saved or copied back to user space (via TUNGETFILTER).\n- Any failed copy_from_user promptly aborts and frees the temporary allocation before any uninitialized bytes can be accessed or propagated.\n- No uninitialized data or padding can be exposed to user space or used in conditional branching.\n\nFrom a KASAN/standard detectors perspective:\n- Potential risks introduced by this change include heap allocation tracking, double-free / use-after-free bugs (e.g., in error unwinding or netdev teardown with fprog_kern.filter), and locking issues (sock lock handling), which are already comprehensively detected by KASAN and LOCKDEP.\n\nTherefore, dedicated KMSAN fuzzing is not required.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 6bd4c0b8eb4529e17a0485d1e2c51f9231e4d988
Author: syz-cluster <triage@syzkaller.com>
Date:   Sat Oct 31 04:54:44 2026 +0000

    syz-cluster: applied patch under review

diff --git a/drivers/net/tun.c b/drivers/net/tun.c
index 439565a264ee79..c121ad50f31bb3 100644
--- a/drivers/net/tun.c
+++ b/drivers/net/tun.c
@@ -197,6 +197,7 @@ struct tun_struct {
 	int			sndbuf;
 	struct tap_filter	txflt;
 	struct sock_fprog	fprog;
+	struct sock_fprog_kern	fprog_kern;
 	/* protected by rtnl lock */
 	bool			filter_attached;
 	u32			msg_enable;
@@ -726,12 +727,69 @@ static void tun_force_wake_queue(struct tun_struct *tun,
 	spin_unlock_bh(&tfile->tx_ring.consumer_lock);
 }
 
+/* Copy the filter that @argp points at into the kernel, so that it can be
+ * installed again later, independent of the ioctl caller's address space.
+ * @fprog_kern receives the copy, which belongs to the caller until it is
+ * installed or freed, and @fprog receives the header, with the user pointer
+ * kept for TUNGETFILTER.
+ */
+static int tun_copy_filter(struct sock_fprog __user *argp,
+			   struct sock_fprog *fprog,
+			   struct sock_fprog_kern *fprog_kern)
+{
+	struct sock_fprog fp;
+	struct sock_filter *insns;
+	int err;
+
+	if (copy_from_user(&fp, argp, sizeof(fp)))
+		return -EFAULT;
+
+	if (!fp.len || fp.len > BPF_MAXINSNS)
+		return -EINVAL;
+
+	insns = kmalloc_array(fp.len, sizeof(struct sock_filter),
+			      GFP_KERNEL_ACCOUNT);
+	if (!insns)
+		return -ENOMEM;
+
+	if (copy_from_user(insns, fp.filter,
+			   fp.len * sizeof(struct sock_filter))) {
+		kfree(insns);
+		return -EFAULT;
+	}
+
+	/* The instructions are only verified when a program is built from
+	 * them, which happens when the filter is attached to a socket. Run
+	 * the classic verifier here as well, so that a bad program is
+	 * refused before it is saved and before any queue is touched.
+	 * bpf_prog_create() can still refuse the program later, when it is
+	 * converted to eBPF or when no runtime can be selected for it; the
+	 * attach path returns that error, and the saved program is not
+	 * replaced.
+	 */
+	err = bpf_prog_validate_classic(insns, fp.len);
+	if (err) {
+		kfree(insns);
+		return err;
+	}
+
+	/* Zero the whole header before filling it in. */
+	memset(fprog, 0, sizeof(*fprog));
+	fprog->len = fp.len;
+	fprog->filter = fp.filter;
+	fprog_kern->len = fp.len;
+	fprog_kern->filter = insns;
+
+	return 0;
+}
+
 static int tun_attach(struct tun_struct *tun, struct file *file,
 		      bool skip_filter, bool napi, bool napi_frags,
 		      bool publish_tun)
 {
 	struct tun_file *tfile = file->private_data;
 	struct net_device *dev = tun->dev;
+	bool rollback_filter = false;
 	int err;
 
 	err = security_tun_dev_attach(tfile->socket.sk, tun->security);
@@ -756,10 +814,11 @@ static int tun_attach(struct tun_struct *tun, struct file *file,
 	/* Re-attach the filter to persist device */
 	if (!skip_filter && (tun->filter_attached == true)) {
 		lock_sock(tfile->socket.sk);
-		err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
+		err = sk_attach_filter_kern(&tun->fprog_kern, tfile->socket.sk);
 		release_sock(tfile->socket.sk);
-		if (!err)
+		if (err)
 			goto out;
+		rollback_filter = true;
 	}
 
 	if (!tfile->detached &&
@@ -821,6 +880,17 @@ static int tun_attach(struct tun_struct *tun, struct file *file,
 	WRITE_ONCE(tun->numqueues, tun->numqueues + 1);
 	tun_set_real_num_queues(tun);
 out:
+	if (err && rollback_filter) {
+		/* The filter was installed before the rest of the attach
+		 * ran, so drop it again if a later step failed. Any
+		 * program it replaced is already gone: this leaves the
+		 * queue without a filter rather than restoring the
+		 * previous one.
+		 */
+		lock_sock(tfile->socket.sk);
+		sk_detach_filter(tfile->socket.sk);
+		release_sock(tfile->socket.sk);
+	}
 	return err;
 }
 
@@ -2406,6 +2476,7 @@ static void tun_free_netdev(struct net_device *dev)
 	security_tun_dev_free_security(tun->security);
 	__tun_set_ebpf(tun, &tun->steering_prog, NULL);
 	__tun_set_ebpf(tun, &tun->filter_prog, NULL);
+	kfree(tun->fprog_kern.filter);
 }
 
 static void tun_setup(struct net_device *dev)
@@ -3070,10 +3141,14 @@ static void tun_detach_filter(struct tun_struct *tun, int n)
 		release_sock(tfile->socket.sk);
 	}
 
+	kfree(tun->fprog_kern.filter);
+	tun->fprog_kern.filter = NULL;
+	tun->fprog_kern.len = 0;
 	tun->filter_attached = false;
 }
 
-static int tun_attach_filter(struct tun_struct *tun)
+static int tun_attach_filter(struct tun_struct *tun,
+			     struct sock_fprog_kern *fprog_kern)
 {
 	int i, ret = 0;
 	struct tun_file *tfile;
@@ -3081,15 +3156,29 @@ static int tun_attach_filter(struct tun_struct *tun)
 	for (i = 0; i < tun->numqueues; i++) {
 		tfile = rtnl_dereference(tun->tfiles[i]);
 		lock_sock(tfile->socket.sk);
-		ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
+		ret = sk_attach_filter_kern(fprog_kern, tfile->socket.sk);
 		release_sock(tfile->socket.sk);
-		if (ret) {
-			tun_detach_filter(tun, i);
-			return ret;
-		}
+		if (ret)
+			goto out_detach;
 	}
 
 	tun->filter_attached = true;
+	return 0;
+
+out_detach:
+	/* Drop the copies already installed on queues 0..i-1, which leaves
+	 * them without a filter: their previous sk_filter, if any, was
+	 * already replaced and released. The caller does not replace the
+	 * saved program when this fails, so tun->fprog, tun->fprog_kern and
+	 * filter_attached keep their previous values.
+	 */
+	while (i--) {
+		tfile = rtnl_dereference(tun->tfiles[i]);
+		lock_sock(tfile->socket.sk);
+		sk_detach_filter(tfile->socket.sk);
+		release_sock(tfile->socket.sk);
+	}
+
 	return ret;
 }
 
@@ -3424,17 +3513,31 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
 		tun_set_sndbuf(tun);
 		break;
 
-	case TUNATTACHFILTER:
+	case TUNATTACHFILTER: {
+		struct sock_fprog_kern fprog_kern;
+		struct sock_fprog fprog;
+
 		/* Can be set only for TAPs */
 		ret = -EINVAL;
 		if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
 			break;
-		ret = -EFAULT;
-		if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
+
+		ret = tun_copy_filter(argp, &fprog, &fprog_kern);
+		if (ret)
+			break;
+
+		ret = tun_attach_filter(tun, &fprog_kern);
+		if (ret) {
+			kfree(fprog_kern.filter);
 			break;
+		}
 
-		ret = tun_attach_filter(tun);
+		/* Install the copy only after every queue accepted it. */
+		kfree(tun->fprog_kern.filter);
+		tun->fprog_kern = fprog_kern;
+		tun->fprog = fprog;
 		break;
+	}
 
 	case TUNDETACHFILTER:
 		/* Can be set only for TAPs */
diff --git a/include/linux/filter.h b/include/linux/filter.h
index e0218e677a1dcd..7169c03610b445 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -1257,8 +1257,10 @@ int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog);
 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
 			      bpf_aux_classic_check_t trans, bool save_orig);
 void bpf_prog_destroy(struct bpf_prog *fp);
+int bpf_prog_validate_classic(const struct sock_filter *insns, unsigned int len);
 
 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk);
+int sk_attach_filter_kern(struct sock_fprog_kern *fprog, struct sock *sk);
 int sk_attach_bpf(u32 ufd, struct sock *sk);
 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk);
 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk);
diff --git a/net/core/filter.c b/net/core/filter.c
index b7ac145b68b1f8..61b2d223c44563 100644
--- a/net/core/filter.c
+++ b/net/core/filter.c
@@ -1476,6 +1476,32 @@ void bpf_prog_destroy(struct bpf_prog *fp)
 }
 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
 
+/**
+ * bpf_prog_validate_classic - run the classic BPF verifier on kernel memory
+ * @insns: instruction array
+ * @len: number of instructions in @insns
+ *
+ * Run bpf_check_basics_ok() and bpf_check_classic() on a program that is
+ * already in kernel memory, without building a struct bpf_prog.  These are
+ * the checks bpf_prog_create() runs before it converts the program, so
+ * callers can reject a bad program when it is configured instead of when it
+ * is first attached to a socket.
+ *
+ * A program that passes here can still be refused by bpf_prog_create(), when
+ * it is converted to eBPF or when no runtime can be selected for it.
+ *
+ * Return: 0 if the program passes the classic verifier, -EINVAL if it does
+ * not, or -ENOMEM if the verifier cannot allocate its state.
+ */
+int bpf_prog_validate_classic(const struct sock_filter *insns, unsigned int len)
+{
+	if (!bpf_check_basics_ok(insns, len))
+		return -EINVAL;
+
+	return bpf_check_classic(insns, len);
+}
+EXPORT_SYMBOL_GPL(bpf_prog_validate_classic);
+
 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
 {
 	struct sk_filter *fp, *old_fp;
@@ -1567,6 +1593,47 @@ int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
 }
 EXPORT_SYMBOL_GPL(sk_attach_filter);
 
+/**
+ * sk_attach_filter_kern - attach a classic BPF filter held in kernel memory
+ * @fprog: program to attach, with @fprog->filter pointing at kernel memory
+ * @sk: socket to attach the filter to
+ *
+ * Attach a copy of a classic BPF program that the kernel already holds, the
+ * way sk_attach_filter() does for one that still lives in user space. The
+ * caller must hold the socket lock; SOCK_FILTER_LOCKED is checked here.
+ *
+ * The program is built by bpf_prog_create(), which does not keep an original
+ * copy of the instructions, so sk_get_filter() returns -EACCES and sock_diag
+ * omits the filter for a socket that uses this helper.
+ *
+ * Return: 0 on success, or a negative errno: -EPERM if @sk has
+ * SOCK_FILTER_LOCKED set, otherwise whatever bpf_prog_create() or
+ * __sk_attach_prog() returned (for example -EINVAL for an invalid classic
+ * BPF program, -ENOMEM, or -ENOTSUPP when a JIT is required but is not
+ * available).
+ */
+int sk_attach_filter_kern(struct sock_fprog_kern *fprog, struct sock *sk)
+{
+	struct bpf_prog *prog;
+	int err;
+
+	if (sock_flag(sk, SOCK_FILTER_LOCKED))
+		return -EPERM;
+
+	err = bpf_prog_create(&prog, fprog);
+	if (err)
+		return err;
+
+	err = __sk_attach_prog(prog, sk);
+	if (err < 0) {
+		__bpf_prog_release(prog);
+		return err;
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(sk_attach_filter_kern);
+
 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
 {
 	struct bpf_prog *prog = __get_filter(fprog, sk);
diff --git a/tools/testing/selftests/net/tun.c b/tools/testing/selftests/net/tun.c
index 34de2580e32eca..3730fba859a46e 100644
--- a/tools/testing/selftests/net/tun.c
+++ b/tools/testing/selftests/net/tun.c
@@ -9,9 +9,11 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <linux/filter.h>
 #include <linux/if_tun.h>
 #include <netinet/tcp.h>
 #include <sys/ioctl.h>
+#include <sys/mman.h>
 #include <sys/socket.h>
 
 #include "kselftest_harness.h"
@@ -548,6 +550,253 @@ TEST_F(tun, reattach_close_delete)
 	EXPECT_EQ(tun_delete(self->ifname), 0);
 }
 
+/* accept: return skb->len.  Three instructions on purpose, so that the
+ * length read back through TUNGETFILTER tells it apart from a rejected
+ * program that is shorter.
+ */
+static const struct sock_filter filter_accept[] = {
+	BPF_STMT(BPF_LD | BPF_W | BPF_LEN, 0),
+	BPF_STMT(BPF_ALU | BPF_ADD | BPF_K, 0),
+	BPF_STMT(BPF_RET | BPF_A, 0),
+};
+
+/* Put the instructions in an anonymous mapping, so that the test can make the
+ * address unreadable afterwards.
+ */
+static void *filter_alloc(const struct sock_filter *insns, unsigned int len)
+{
+	void *p;
+
+	p = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE,
+		 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+	if (p == MAP_FAILED)
+		return NULL;
+
+	memcpy(p, insns, len * sizeof(*insns));
+
+	return p;
+}
+
+static int filter_attach(int fd, const struct sock_filter *insns, unsigned int len)
+{
+	struct sock_fprog fp = {
+		.len = len,
+		.filter = (struct sock_filter *)insns,
+	};
+
+	return ioctl(fd, TUNATTACHFILTER, (void *)&fp);
+}
+
+static int filter_get(int fd, struct sock_fprog *fp)
+{
+	return ioctl(fd, TUNGETFILTER, (void *)fp);
+}
+
+static int tun_get_iff_flags(int fd)
+{
+	struct ifreq ifr = { 0 };
+
+	if (ioctl(fd, TUNGETIFF, (void *)&ifr) < 0)
+		return -1;
+
+	return ifr.ifr_flags;
+}
+
+/*
+ * A queue can be attached long after the filter was configured, from a
+ * process that does not necessarily map the buffer the program was copied
+ * from, so the kernel has to keep its own copy of the program.  Here the
+ * mapping is made unreadable before the queue is attached again, and a
+ * second queue is then attached from a fresh socket, which starts without a
+ * filter of its own.
+ */
+TEST_F(tun, reattach_filter_without_user_buffer)
+{
+	struct sock_fprog gf = { 0 };
+	struct ifreq ifr = { 0 };
+	short flags = 0;
+	void *prog;
+	int fd, ret;
+
+	prog = filter_alloc(filter_accept, ARRAY_SIZE(filter_accept));
+	ASSERT_NE(prog, NULL);
+	ASSERT_EQ(filter_attach(self->fd, prog, ARRAY_SIZE(filter_accept)), 0);
+
+	EXPECT_EQ(tun_detach(self->fd, self->ifname), 0);
+
+	/* This memory is no longer readable */
+	ASSERT_EQ(mprotect(prog, getpagesize(), PROT_NONE), 0);
+
+	ret = tun_attach(self->fd, self->ifname);
+	EXPECT_EQ(ret, 0);
+
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	/* The queue is attached again, not left disabled */
+	EXPECT_EQ(flags & IFF_DETACH_QUEUE, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	/* The two checks below document the expected state, they cannot
+	 * tell a reinstalled filter from no filter: tun_detach() leaves
+	 * sk_filter alone, and TUNGETFILTER only returns the header.
+	 */
+	EXPECT_EQ(filter_get(self->fd, &gf), 0);
+	EXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));
+
+	/* A new queue starts without a filter, so a clear IFF_NOFILTER shows
+	 * that the filter was installed again from the kernel copy.
+	 */
+	fd = open("/dev/net/tun", O_RDWR);
+	ASSERT_GE(fd, 0);
+
+	strcpy(ifr.ifr_name, self->ifname);
+	ifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;
+	EXPECT_GE(ioctl(fd, TUNSETIFF, (void *)&ifr), 0);
+
+	flags = tun_get_iff_flags(fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	close(fd);
+
+	ASSERT_EQ(mprotect(prog, getpagesize(), PROT_READ | PROT_WRITE), 0);
+	ASSERT_EQ(munmap(prog, getpagesize()), 0);
+}
+
+/* A new queue attached with IFF_NOFILTER must not get the filter that is
+ * configured on the device.
+ */
+TEST_F(tun, attach_filter_nofilter_flag)
+{
+	struct ifreq ifr = { 0 };
+	short flags = 0;
+	int fd;
+
+	ASSERT_EQ(filter_attach(self->fd, filter_accept, ARRAY_SIZE(filter_accept)), 0);
+
+	fd = open("/dev/net/tun", O_RDWR);
+	ASSERT_GE(fd, 0);
+
+	strcpy(ifr.ifr_name, self->ifname);
+	ifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE | IFF_NOFILTER;
+	EXPECT_GE(ioctl(fd, TUNSETIFF, (void *)&ifr), 0);
+
+	flags = tun_get_iff_flags(fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, IFF_NOFILTER);
+
+	close(fd);
+}
+
+/* After TUNDETACHFILTER a later attach must not install the filter again */
+TEST_F(tun, detach_filter_clears_reattach)
+{
+	short flags = 0;
+
+	ASSERT_EQ(filter_attach(self->fd, filter_accept, ARRAY_SIZE(filter_accept)), 0);
+	EXPECT_EQ(ioctl(self->fd, TUNDETACHFILTER, 0), 0);
+
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, IFF_NOFILTER);
+
+	EXPECT_EQ(tun_detach(self->fd, self->ifname), 0);
+	EXPECT_EQ(tun_attach(self->fd, self->ifname), 0);
+
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, IFF_NOFILTER);
+}
+
+/* A TUNATTACHFILTER with a bad length must leave the installed program and the
+ * filter state that TUNGETIFF reports alone.
+ */
+TEST_F(tun, attach_filter_bad_len_keeps_program)
+{
+	struct sock_fprog gf = { 0 };
+	struct ifreq ifr = { 0 };
+	short flags = 0;
+	int fd;
+
+	ASSERT_EQ(filter_attach(self->fd, filter_accept, ARRAY_SIZE(filter_accept)), 0);
+
+	errno = 0;
+	EXPECT_EQ(filter_attach(self->fd, filter_accept, 0), -1);
+	EXPECT_EQ(errno, EINVAL);
+
+	EXPECT_EQ(filter_get(self->fd, &gf), 0);
+	EXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));
+
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	/* A queue attached afterwards still gets the filter, so the rejected
+	 * ioctl left the saved program and filter_attached alone.
+	 */
+	fd = open("/dev/net/tun", O_RDWR);
+	ASSERT_GE(fd, 0);
+
+	strcpy(ifr.ifr_name, self->ifname);
+	ifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;
+	EXPECT_GE(ioctl(fd, TUNSETIFF, (void *)&ifr), 0);
+
+	flags = tun_get_iff_flags(fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	close(fd);
+}
+
+/* A TUNATTACHFILTER with instructions that bpf_check_classic() rejects must
+ * be refused, and must leave the program installed already in place.
+ */
+TEST_F(tun, attach_filter_bad_prog_keeps_program)
+{
+	struct sock_fprog gf = { 0 };
+	struct sock_filter bad[] = {
+		BPF_STMT(BPF_LD | BPF_W | BPF_LEN, 0),
+		BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 1, 0),
+	};
+	struct ifreq ifr = { 0 };
+	short flags = 0;
+	int fd;
+
+	ASSERT_EQ(filter_attach(self->fd, filter_accept,
+				ARRAY_SIZE(filter_accept)), 0);
+
+	errno = 0;
+	EXPECT_EQ(filter_attach(self->fd, bad, ARRAY_SIZE(bad)), -1);
+	EXPECT_EQ(errno, EINVAL);
+
+	/* the program attached before is untouched */
+	EXPECT_EQ(filter_get(self->fd, &gf), 0);
+	EXPECT_EQ(gf.len, ARRAY_SIZE(filter_accept));
+
+	/* IFF_NOFILTER comes from the socket's sk_filter, not from the saved
+	 * header, so a clear flag shows the filter is still installed.
+	 */
+	flags = tun_get_iff_flags(self->fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	/* A queue attached afterwards still gets the filter, so the rejected
+	 * program never replaced the saved one.
+	 */
+	fd = open("/dev/net/tun", O_RDWR);
+	ASSERT_GE(fd, 0);
+
+	strcpy(ifr.ifr_name, self->ifname);
+	ifr.ifr_flags = IFF_TAP | IFF_MULTI_QUEUE;
+	EXPECT_GE(ioctl(fd, TUNSETIFF, (void *)&ifr), 0);
+
+	flags = tun_get_iff_flags(fd);
+	EXPECT_GE(flags, 0);
+	EXPECT_EQ(flags & IFF_NOFILTER, 0);
+
+	close(fd);
+}
+
 FIXTURE(tun_vnet_gso)
 {
 	char ifname[IFNAMSIZ];

27/3 2026/10/31 04:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 9061
							output: 34
							thoughts: 144
						

Thoughts:
**KMSAN Fuzzing Session Evaluation**

Okay, so I need to decide if this patch series warrants its own dedicated KMSAN fuzzing session. Let's dig in. First, I need to really understand *what* the patch is changing. Right, it looks like it's in `drivers/net/tun.c`. The core issue, as I see it, is how the `tun->fprog` structure is populated. Previously, it looks like there was a direct `copy_from_user` call, which is always a red flag for potential security vulnerabilities. `copy_from_user` can be really tricky, so that needs to be the main focus of my attention.

Hold on a second... how was `tun_attach` and `TUNATTACHFILTER` working before this change? If things were functioning before, that should be easy to figure out. It will also help me understand the implications of the change. This is critical. I'm going to quickly review the surrounding code around `TUNATTACHFILTER`, `TUNGETFILTER`, and `tun_attach` in `drivers/net/tun.c` itself. This will give me the best context to determine the level of risk and if specialized fuzzing is necessary.



28/3 2026/10/31 04:56 tool grepper
0m Args:
{
  "Expression": "TUNGETFILTER|fprog",
  "PathPrefixes": [
    "drivers/net/tun.c"
  ]
}

Results:
{
  "Output": "drivers/net/tun.c=107=struct tap_filter {\n--\ndrivers/net/tun.c-120-/* A tun_file connects an open character device to a tuntap netdevice. It\ndrivers/net/tun.c:121: * also contains all socket related structures (except sock_fprog and tap_filter)\ndrivers/net/tun.c:122: * to serve as one transmit queue for tuntap device. The sock_fprog and\ndrivers/net/tun.c-123- * tap_filter were kept in tun_struct since they were used for filtering for the\n--\ndrivers/net/tun.c=182=struct tun_struct {\n--\ndrivers/net/tun.c-198-\tstruct tap_filter\ttxflt;\ndrivers/net/tun.c:199:\tstruct sock_fprog\tfprog;\ndrivers/net/tun.c:200:\tstruct sock_fprog_kern\tfprog_kern;\ndrivers/net/tun.c-201-\t/* protected by rtnl lock */\n--\ndrivers/net/tun.c=711=static void tun_force_wake_queue(struct tun_struct *tun,\n--\ndrivers/net/tun.c-731- * installed again later, independent of the ioctl caller's address space.\ndrivers/net/tun.c:732: * @fprog_kern receives the copy, which belongs to the caller until it is\ndrivers/net/tun.c:733: * installed or freed, and @fprog receives the header, with the user pointer\ndrivers/net/tun.c:734: * kept for TUNGETFILTER.\ndrivers/net/tun.c-735- */\ndrivers/net/tun.c:736:static int tun_copy_filter(struct sock_fprog __user *argp,\ndrivers/net/tun.c:737:\t\t\t   struct sock_fprog *fprog,\ndrivers/net/tun.c:738:\t\t\t   struct sock_fprog_kern *fprog_kern)\ndrivers/net/tun.c-739-{\ndrivers/net/tun.c:740:\tstruct sock_fprog fp;\ndrivers/net/tun.c-741-\tstruct sock_filter *insns;\n--\ndrivers/net/tun.c-776-\t/* Zero the whole header before filling it in. */\ndrivers/net/tun.c:777:\tmemset(fprog, 0, sizeof(*fprog));\ndrivers/net/tun.c:778:\tfprog-\u003elen = fp.len;\ndrivers/net/tun.c:779:\tfprog-\u003efilter = fp.filter;\ndrivers/net/tun.c:780:\tfprog_kern-\u003elen = fp.len;\ndrivers/net/tun.c:781:\tfprog_kern-\u003efilter = insns;\ndrivers/net/tun.c-782-\n--\ndrivers/net/tun.c=786=static int tun_attach(struct tun_struct *tun, struct file *file,\n--\ndrivers/net/tun.c-816-\t\tlock_sock(tfile-\u003esocket.sk);\ndrivers/net/tun.c:817:\t\terr = sk_attach_filter_kern(\u0026tun-\u003efprog_kern, tfile-\u003esocket.sk);\ndrivers/net/tun.c-818-\t\trelease_sock(tfile-\u003esocket.sk);\n--\ndrivers/net/tun.c=2469=static void tun_free_netdev(struct net_device *dev)\n--\ndrivers/net/tun.c-2478-\t__tun_set_ebpf(tun, \u0026tun-\u003efilter_prog, NULL);\ndrivers/net/tun.c:2479:\tkfree(tun-\u003efprog_kern.filter);\ndrivers/net/tun.c-2480-}\n--\ndrivers/net/tun.c=3132=static void tun_detach_filter(struct tun_struct *tun, int n)\n--\ndrivers/net/tun.c-3143-\ndrivers/net/tun.c:3144:\tkfree(tun-\u003efprog_kern.filter);\ndrivers/net/tun.c:3145:\ttun-\u003efprog_kern.filter = NULL;\ndrivers/net/tun.c:3146:\ttun-\u003efprog_kern.len = 0;\ndrivers/net/tun.c-3147-\ttun-\u003efilter_attached = false;\n--\ndrivers/net/tun.c=3150=static int tun_attach_filter(struct tun_struct *tun,\ndrivers/net/tun.c:3151:\t\t\t     struct sock_fprog_kern *fprog_kern)\ndrivers/net/tun.c-3152-{\n--\ndrivers/net/tun.c-3158-\t\tlock_sock(tfile-\u003esocket.sk);\ndrivers/net/tun.c:3159:\t\tret = sk_attach_filter_kern(fprog_kern, tfile-\u003esocket.sk);\ndrivers/net/tun.c-3160-\t\trelease_sock(tfile-\u003esocket.sk);\n--\ndrivers/net/tun.c-3171-\t * already replaced and released. The caller does not replace the\ndrivers/net/tun.c:3172:\t * saved program when this fails, so tun-\u003efprog, tun-\u003efprog_kern and\ndrivers/net/tun.c-3173-\t * filter_attached keep their previous values.\n--\ndrivers/net/tun.c=3291=static long __tun_chr_ioctl(struct file *file, unsigned int cmd,\n--\ndrivers/net/tun.c-3516-\tcase TUNATTACHFILTER: {\ndrivers/net/tun.c:3517:\t\tstruct sock_fprog_kern fprog_kern;\ndrivers/net/tun.c:3518:\t\tstruct sock_fprog fprog;\ndrivers/net/tun.c-3519-\n--\ndrivers/net/tun.c-3524-\ndrivers/net/tun.c:3525:\t\tret = tun_copy_filter(argp, \u0026fprog, \u0026fprog_kern);\ndrivers/net/tun.c-3526-\t\tif (ret)\n--\ndrivers/net/tun.c-3528-\ndrivers/net/tun.c:3529:\t\tret = tun_attach_filter(tun, \u0026fprog_kern);\ndrivers/net/tun.c-3530-\t\tif (ret) {\ndrivers/net/tun.c:3531:\t\t\tkfree(fprog_kern.filter);\ndrivers/net/tun.c-3532-\t\t\tbreak;\n--\ndrivers/net/tun.c-3535-\t\t/* Install the copy only after every queue accepted it. */\ndrivers/net/tun.c:3536:\t\tkfree(tun-\u003efprog_kern.filter);\ndrivers/net/tun.c:3537:\t\ttun-\u003efprog_kern = fprog_kern;\ndrivers/net/tun.c:3538:\t\ttun-\u003efprog = fprog;\ndrivers/net/tun.c-3539-\t\tbreak;\n--\ndrivers/net/tun.c-3550-\ndrivers/net/tun.c:3551:\tcase TUNGETFILTER:\ndrivers/net/tun.c-3552-\t\tret = -EINVAL;\n--\ndrivers/net/tun.c-3555-\t\tret = -EFAULT;\ndrivers/net/tun.c:3556:\t\tif (copy_to_user(argp, \u0026tun-\u003efprog, sizeof(tun-\u003efprog)))\ndrivers/net/tun.c-3557-\t\t\tbreak;\n"
}

29/3 2026/10/31 04:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 11430
							output: 36
							thoughts: 36
						

Thoughts:
Here's my analysis of the provided information, as if these are my immediate thoughts:

**Dissecting TUNGETFILTER and `tun->fprog`**

Right, let's dive into TUNGETFILTER and, specifically, the `tun->fprog` component. I want to understand how filtering is implemented within the TUN device context. My intuition tells me this is where the action is when it comes to capturing or manipulating traffic at the TUN interface, so it's a logical starting point. I'm thinking we can read and understand the filtering program related to the TUN device. I need to be sure that I am looking at the relevant parts for my investigation. So I am going to locate and verify the specific section of code that deals with this.

I'll be zeroing in on line 3550 of `drivers/net/tun.c` (or thereabouts). I know that's a key function in this driver and provides the critical interface elements that I need to analyze. I'm expecting to find the key implementation details there.



30/3 2026/10/31 04:56 tool read-file
0m Args:
{
  "File": "drivers/net/tun.c",
  "FirstLine": 3540,
  "LineCount": 35
}

Results:
{
  "Contents": "3540:\t\t}\n3541:\t\n3542:\t\tcase TUNDETACHFILTER:\n3543:\t\t\t/* Can be set only for TAPs */\n3544:\t\t\tret = -EINVAL;\n3545:\t\t\tif ((tun-\u003eflags \u0026 TUN_TYPE_MASK) != IFF_TAP)\n3546:\t\t\t\tbreak;\n3547:\t\t\tret = 0;\n3548:\t\t\ttun_detach_filter(tun, tun-\u003enumqueues);\n3549:\t\t\tbreak;\n3550:\t\n3551:\t\tcase TUNGETFILTER:\n3552:\t\t\tret = -EINVAL;\n3553:\t\t\tif ((tun-\u003eflags \u0026 TUN_TYPE_MASK) != IFF_TAP)\n3554:\t\t\t\tbreak;\n3555:\t\t\tret = -EFAULT;\n3556:\t\t\tif (copy_to_user(argp, \u0026tun-\u003efprog, sizeof(tun-\u003efprog)))\n3557:\t\t\t\tbreak;\n3558:\t\t\tret = 0;\n3559:\t\t\tbreak;\n3560:\t\n3561:\t\tcase TUNSETSTEERINGEBPF:\n3562:\t\t\tret = tun_set_ebpf(tun, \u0026tun-\u003esteering_prog, argp);\n3563:\t\t\tbreak;\n3564:\t\n3565:\t\tcase TUNSETFILTEREBPF:\n3566:\t\t\tret = tun_set_ebpf(tun, \u0026tun-\u003efilter_prog, argp);\n3567:\t\t\tbreak;\n3568:\t\n3569:\t\tcase TUNSETCARRIER:\n3570:\t\t\tret = -EFAULT;\n3571:\t\t\tif (copy_from_user(\u0026carrier, argp, sizeof(carrier)))\n3572:\t\t\t\tgoto unlock;\n3573:\t\n3574:\t\t\tret = tun_net_change_carrier(tun-\u003edev, (bool)carrier);\n"
}

31/3 2026/10/31 04:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 12231
							output: 38
							thoughts: 380
						

Thoughts:
**Analyzing the TUN/TAP Filter Implementation**

Okay, let's break this down. I'm examining the code related to the TUN/TAP filter functionality, specifically looking at how filter programs are handled. I'm starting with the `TUNGETFILTER` case. It appears that the code retrieves the filter program using `copy_to_user` from the kernel space to the user space. The initial check ensures that we're dealing with a TAP device, which makes sense. If it's not a TAP device, it exits. The code then uses `copy_to_user`, which seems appropriate for getting the data out.

Now, I'm shifting focus to `tun_copy_filter`. This function is important in understanding what is going on. Here, the header of `fprog` is zeroed out before copying filter instructions into the kernel space, which is good practice. `fprog->len` and `fprog->filter` are populated with the length and filter instructions, and kernel versions of these fields are populated with the same data.

But hold on, let me rewind and consider what this looked like *before* a particular patch. I need to understand the prior behavior of `TUNATTACHFILTER`. Now, the initial code seems to copy the filter program into kernel space, from user space, using `copy_from_user(&tun->fprog, argp, sizeof(tun->fprog))`. That seems fine. However, what *is* `struct sock_fprog`? I need to verify its definition to ensure I understand how this data is being handled. This is an important data structure, and it's essential to understand its makeup.



32/3 2026/10/31 04:56 tool grepper
0m Args:
{
  "Expression": "struct sock_fprog\\b",
  "PathPrefixes": [
    "include/uapi/linux/filter.h"
  ]
}

Results:
{
  "Output": "include/uapi/linux/filter.h=24=struct sock_filter {\t/* Filter block */\n--\ninclude/uapi/linux/filter.h-30-\ninclude/uapi/linux/filter.h:31:struct sock_fprog {\t/* Required for SO_ATTACH_FILTER. */\ninclude/uapi/linux/filter.h-32-\tunsigned short\t\tlen;\t/* Number of filter blocks */\n"
}

33/3 2026/10/31 04:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 13114
							output: 37
							thoughts: 22
						

Thoughts:
Here's a summary of my thought process, tailored for an expert like yourself:

**Diving into eBPF Filter Structures**

Okay, let's get down to brass tacks. I'm thinking we need to examine the core definitions for eBPF packet filtering. I'm heading directly to the standard kernel headers, specifically `include/uapi/linux/filter.h`. I'm starting around line 31, as that's usually where the foundational structures for BPF programs and their associated data start to be laid out. From that vantage point, I anticipate seeing the definitions of `sock_filter`, `sock_fprog`, and related structures. I want to refresh my memory on the precise layout and meaning of the `code`, `jt`, `jf`, and `k` fields within each `sock_filter` instruction. Understanding how these fields are used to encode instructions and immediate values is key to interpreting and crafting effective BPF programs. I'll be looking for any nuances or recent changes in the kernel's implementation of these structs.



34/3 2026/10/31 04:56 tool read-file
0m Args:
{
  "File": "include/uapi/linux/filter.h",
  "FirstLine": 25,
  "LineCount": 20
}

Results:
{
  "Contents": "  25:\t\t__u16\tcode;   /* Actual filter code */\n  26:\t\t__u8\tjt;\t/* Jump true */\n  27:\t\t__u8\tjf;\t/* Jump false */\n  28:\t\t__u32\tk;      /* Generic multiuse field */\n  29:\t};\n  30:\t\n  31:\tstruct sock_fprog {\t/* Required for SO_ATTACH_FILTER. */\n  32:\t\tunsigned short\t\tlen;\t/* Number of filter blocks */\n  33:\t\tstruct sock_filter __user *filter;\n  34:\t};\n  35:\t\n  36:\t/* ret - BPF_K and BPF_X also apply */\n  37:\t#define BPF_RVAL(code)  ((code) \u0026 0x18)\n  38:\t#define         BPF_A           0x10\n  39:\t\n  40:\t/* misc */\n  41:\t#define BPF_MISCOP(code) ((code) \u0026 0xf8)\n  42:\t#define         BPF_TAX         0x00\n  43:\t#define         BPF_TXA         0x80\n  44:\t\n"
}

35/3 2026/10/31 04:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 13714
							output: 37
							thoughts: 934
						

Thoughts:
**Analyzing the Socket Filter Attachment in the Linux TUN Driver**

Okay, let's break this down. I'm looking at the `struct sock_fprog` and immediately noticing that on 64-bit systems like amd64, that `unsigned short len` field is followed by 6 bytes of padding. That's a classic struct packing gotcha. Now, this patch seems to be addressing an issue related to how socket filters are attached to the TUN device. I can see the `tun_copy_filter` function is central here.

Initially, I'm taking note of `tun_copy_filter`. It copies the user-provided `sock_fprog` structure (`argp`) into a local stack variable `fp`. Critically, it then uses `kmalloc_array` to allocate memory for the filter instructions (`insns`). After validating the filter with `bpf_prog_validate_classic`, the patch *explicitly* zeroes out the contents of the `fprog` structure using `memset`. This is key. The `len` and `filter` fields of `fprog` and `fprog_kern` are then populated accordingly.

Looking at the `TUNATTACHFILTER` case, I see how `tun_copy_filter` is called, copying from the user space filter (`argp`) into the local `fprog`. And then the `fprog` *initialized on the stack* is copied to the `tun->fprog` member.

Now, I'm flashing back to the *previous* implementation. Before this patch, there was a direct `copy_from_user` from `argp` *into* `tun->fprog`. *That* could be a problem, since the user-provided structure could contain uninitialized padding (or not set padding).

So, previously, if the user didn't set padding, the padding value, whatever it was, got copied into the `tun->fprog`. This is a clear security vulnerability.

However, *now* with the patch, the local `fprog` is zeroed out before anything else is set, guaranteeing that the padding is initialized. This is the fix.

The key improvement is the explicit zeroing of the padding in the local `fprog` before any data is copied into it. It's a fundamental fix to a potential information leak or potentially to a use-after-free situation if the struct wasn't initialized. I need to make sure I'm following the whole allocation strategy for `tun` to feel truly comfortable that there aren't any other subtle issues here, though. Let's trace how the `tun` structure itself is allocated and initialized.



36/3 2026/10/31 04:56 tool grepper
0m Args:
{
  "Expression": "alloc_netdev|netdev_priv",
  "PathPrefixes": [
    "drivers/net/tun.c"
  ]
}

Results:
{
  "Output": "drivers/net/tun.c=501=static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,\n--\ndrivers/net/tun.c-503-{\ndrivers/net/tun.c:504:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-505-\tu16 ret;\n--\ndrivers/net/tun.c=667=static void tun_detach_all(struct net_device *dev)\ndrivers/net/tun.c-668-{\ndrivers/net/tun.c:669:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-670-\tstruct tun_file *tfile, *tmp;\n--\ndrivers/net/tun.c=1023=static int tun_net_init(struct net_device *dev)\ndrivers/net/tun.c-1024-{\ndrivers/net/tun.c:1025:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1026-\tstruct ifreq *ifr = tun-\u003eifr;\n--\ndrivers/net/tun.c=1077=static int tun_net_close(struct net_device *dev)\ndrivers/net/tun.c-1078-{\ndrivers/net/tun.c:1079:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1080-\tstruct tun_file *tfile;\n--\ndrivers/net/tun.c=1133=static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)\n--\ndrivers/net/tun.c-1135-\tenum skb_drop_reason drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;\ndrivers/net/tun.c:1136:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1137-\tint txq = skb-\u003equeue_mapping;\n--\ndrivers/net/tun.c=1252=static netdev_features_t tun_net_fix_features(struct net_device *dev,\n--\ndrivers/net/tun.c-1254-{\ndrivers/net/tun.c:1255:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1256-\n--\ndrivers/net/tun.c=1260=static void tun_set_headroom(struct net_device *dev, int new_hr)\ndrivers/net/tun.c-1261-{\ndrivers/net/tun.c:1262:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1263-\tsize_t max_headroom;\n--\ndrivers/net/tun.c=1276=tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)\ndrivers/net/tun.c-1277-{\ndrivers/net/tun.c:1278:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1279-\n--\ndrivers/net/tun.c=1286=static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,\n--\ndrivers/net/tun.c-1288-{\ndrivers/net/tun.c:1289:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1290-\tstruct tun_file *tfile;\n--\ndrivers/net/tun.c=1326=static int tun_net_change_carrier(struct net_device *dev, bool new_carrier)\n--\ndrivers/net/tun.c-1328-\tif (new_carrier) {\ndrivers/net/tun.c:1329:\t\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1330-\n--\ndrivers/net/tun.c=1362=static int tun_xdp_xmit(struct net_device *dev, int n,\n--\ndrivers/net/tun.c-1364-{\ndrivers/net/tun.c:1365:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1366-\tstruct tun_file *tfile;\n--\ndrivers/net/tun.c=1466=static void tun_net_initialize(struct net_device *dev)\ndrivers/net/tun.c-1467-{\ndrivers/net/tun.c:1468:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-1469-\n--\ndrivers/net/tun.c=2469=static void tun_free_netdev(struct net_device *dev)\ndrivers/net/tun.c-2470-{\ndrivers/net/tun.c:2471:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-2472-\n--\ndrivers/net/tun.c=2482=static void tun_setup(struct net_device *dev)\ndrivers/net/tun.c-2483-{\ndrivers/net/tun.c:2484:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-2485-\n--\ndrivers/net/tun.c=2525=static int tun_fill_info(struct sk_buff *skb, const struct net_device *dev)\ndrivers/net/tun.c-2526-{\ndrivers/net/tun.c:2527:\tconst struct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-2528-\tunsigned int flags = READ_ONCE(tun-\u003eflags);\n--\ndrivers/net/tun.c=2880=static ssize_t tun_flags_show(struct device *dev, struct device_attribute *attr,\n--\ndrivers/net/tun.c-2882-{\ndrivers/net/tun.c:2883:\tstruct tun_struct *tun = netdev_priv(to_net_dev(dev));\ndrivers/net/tun.c-2884-\treturn sysfs_emit(buf, \"0x%x\\n\", tun_flags(tun));\n--\ndrivers/net/tun.c=2887=static ssize_t owner_show(struct device *dev, struct device_attribute *attr,\n--\ndrivers/net/tun.c-2889-{\ndrivers/net/tun.c:2890:\tstruct tun_struct *tun = netdev_priv(to_net_dev(dev));\ndrivers/net/tun.c-2891-\treturn uid_valid(tun-\u003eowner)?\n--\ndrivers/net/tun.c=2897=static ssize_t group_show(struct device *dev, struct device_attribute *attr,\n--\ndrivers/net/tun.c-2899-{\ndrivers/net/tun.c:2900:\tstruct tun_struct *tun = netdev_priv(to_net_dev(dev));\ndrivers/net/tun.c-2901-\treturn gid_valid(tun-\u003egroup) ?\n--\ndrivers/net/tun.c=2922=static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)\n--\ndrivers/net/tun.c-2946-\t\tif ((ifr-\u003eifr_flags \u0026 IFF_TUN) \u0026\u0026 dev-\u003enetdev_ops == \u0026tun_netdev_ops)\ndrivers/net/tun.c:2947:\t\t\ttun = netdev_priv(dev);\ndrivers/net/tun.c-2948-\t\telse if ((ifr-\u003eifr_flags \u0026 IFF_TAP) \u0026\u0026 dev-\u003enetdev_ops == \u0026tap_netdev_ops)\ndrivers/net/tun.c:2949:\t\t\ttun = netdev_priv(dev);\ndrivers/net/tun.c-2950-\t\telse\n--\ndrivers/net/tun.c-3008-\ndrivers/net/tun.c:3009:\t\tdev = alloc_netdev_mqs(sizeof(struct tun_struct), name,\ndrivers/net/tun.c-3010-\t\t\t\t       NET_NAME_UNKNOWN, tun_setup, queues,\n--\ndrivers/net/tun.c-3020-\ndrivers/net/tun.c:3021:\t\ttun = netdev_priv(dev);\ndrivers/net/tun.c-3022-\t\ttun-\u003edev = dev;\n--\ndrivers/net/tun.c=3766=static int tun_get_link_ksettings(struct net_device *dev,\n--\ndrivers/net/tun.c-3768-{\ndrivers/net/tun.c:3769:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3770-\n--\ndrivers/net/tun.c=3775=static int tun_set_link_ksettings(struct net_device *dev,\n--\ndrivers/net/tun.c-3777-{\ndrivers/net/tun.c:3778:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3779-\n--\ndrivers/net/tun.c=3784=static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)\ndrivers/net/tun.c-3785-{\ndrivers/net/tun.c:3786:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3787-\n--\ndrivers/net/tun.c=3801=static u32 tun_get_msglevel(struct net_device *dev)\ndrivers/net/tun.c-3802-{\ndrivers/net/tun.c:3803:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3804-\n--\ndrivers/net/tun.c=3808=static void tun_set_msglevel(struct net_device *dev, u32 value)\ndrivers/net/tun.c-3809-{\ndrivers/net/tun.c:3810:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3811-\n--\ndrivers/net/tun.c=3815=static int tun_get_coalesce(struct net_device *dev,\n--\ndrivers/net/tun.c-3819-{\ndrivers/net/tun.c:3820:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3821-\n--\ndrivers/net/tun.c=3827=static int tun_set_coalesce(struct net_device *dev,\n--\ndrivers/net/tun.c-3831-{\ndrivers/net/tun.c:3832:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3833-\n--\ndrivers/net/tun.c=3842=static void tun_get_channels(struct net_device *dev,\n--\ndrivers/net/tun.c-3844-{\ndrivers/net/tun.c:3845:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3846-\n--\ndrivers/net/tun.c=3899=static int tun_device_event(struct notifier_block *unused,\n--\ndrivers/net/tun.c-3902-\tstruct net_device *dev = netdev_notifier_info_to_dev(ptr);\ndrivers/net/tun.c:3903:\tstruct tun_struct *tun = netdev_priv(dev);\ndrivers/net/tun.c-3904-\tint i;\n"
}

37/3 2026/10/31 04:56 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 18330
							output: 36
							thoughts: 1500
						

Thoughts:
**Analyzing the TUN/TAP Filter Mechanism**

Okay, so I'm digging into this TUN/TAP filter implementation. It seems like the core issue revolves around how the filter program (`sock_fprog`) is handled, particularly in relation to zero-initialization and potential leakage of uninitialized memory. Let's see.

First, I see that the `alloc_netdev_mqs` function allocates the net_device, and importantly, it uses `kvzalloc`. This is crucial. This means that the entire memory region allocated for the device, including its private data, is *zeroed* upon allocation. So, the `tun` struct, including `fprog` and `fprog_kern`, will start off with all bytes set to zero.

When `TUNATTACHFILTER` is called, a `struct sock_fprog fprog;` is allocated on the stack. Now, it calls `tun_copy_filter` which is where things get interesting. Inside `tun_copy_filter` there's this `memset(fprog, 0, sizeof(*fprog));`. This zeroes out the *entire* `fprog` structure on the stack *before* it's populated. This is intentional. The code then copies the user-provided filter program length and instructions into `fprog` and a kernel-space version `fprog_kern`. The kernel version holds the allocated instructions (`insns`), whereas `fprog` holds a pointer to user space.

After the filter data is copied, `__tun_chr_ioctl` is called which frees `tun->fprog_kern.filter`, and assigns it to the new `fprog_kern`. It also assigns the stack `fprog` to `tun->fprog`.

Then, if `TUNGETFILTER` is called, it copies `tun->fprog` back to user space. But since the stack based `fprog` was zeroed at the beginning of `tun_copy_filter`, this effectively means that the filter in user space *will* have its padding zeroed.

Now, here's where I start to think about edge cases. What happens if `tun_copy_filter` *isn't* called? If `TUNATTACHFILTER` is never called, and we assume we have a net device, then `tun` was allocated via `alloc_netdev_mqs`. In this case, `tun->fprog` is *already* zeroed.

What about `TUNDETACHFILTER`? The `tun_detach_filter` function does free the `tun->fprog_kern.filter`, and resets `fprog_kern`, and `filter_attached` flags, which doesn't zero the contents of `tun->fprog`. But remember, it was already either zeroed by the `alloc_netdev_mqs` call, or by a previous call to `tun_copy_filter`.

Okay, now let's go back and examine `tun_copy_filter` more closely. I need to understand how the BPF instructions are handled. Specifically, the line `insns = kmalloc_array(fp.len, sizeof(struct sock_filter), GFP_KERNEL_ACCOUNT);` and the subsequent `copy_from_user` operation. This is critical. The code allocates memory for the BPF instructions (`insns`) using `kmalloc_array`, based on a user-provided length (`fp.len`). Then, it copies the BPF instructions themselves from user space using `copy_from_user`. *All* `fp.len * sizeof(struct sock_filter)` bytes are copied. If the copy fails, `insns` is immediately freed, and -EFAULT is returned. If the copy succeeds, `insns` goes through a validation step.

The BPF instructions are passed to `bpf_prog_validate_classic`, and then `sk_attach_filter_kern`. I'll need to check the definition of `bpf_prog_validate_classic`, but I know it performs validation of the BPF instructions.

So, finally, the `bpf_prog_create` function. I'll need to grep through `net/core/filter.c` to understand exactly how this works. I must have missed something.



38/3 2026/10/31 04:57 tool grepper
0m Args:
{
  "Expression": "int bpf_prog_create\\(",
  "PathPrefixes": [
    "net/core/filter.c"
  ]
}

Results:
{
  "Output": "net/core/filter.c=1336=static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,\n--\nnet/core/filter.c-1384- */\nnet/core/filter.c:1385:int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)\nnet/core/filter.c-1386-{\n"
}

39/3 2026/10/31 04:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 20896
							output: 36
							thoughts: 22
						

Thoughts:
Okay, let's dive into this. Here's my take on understanding this `bpf_prog_create` function, as if I were analyzing it:

**Deconstructing bpf_prog_create**

Alright, I'm heading into `net/core/filter.c` to examine `bpf_prog_create`. I know this function is critical, it's where a BPF program gets born, and I need to understand its lifecycle from the ground up. I want to see how the kernel takes a raw BPF program and turns it into something executable. I'll need to dissect its inputs, the allocations it makes, the verifications it performs, and how it's ultimately linked into the system. Knowing the intricacies of this function is going to give me valuable insights into how these programs are used. I know I will need to look carefully at the interaction with the verifier, memory allocation strategies, and potential security considerations. I want to build a mental map of its execution flow.



40/3 2026/10/31 04:57 tool read-file
0m Args:
{
  "File": "net/core/filter.c",
  "FirstLine": 1380,
  "LineCount": 40
}

Results:
{
  "Contents": "1380:\t * Create a filter independent of any socket. We first run some\n1381:\t * sanity checks on it to make sure it does not explode on us later.\n1382:\t * If an error occurs or there is insufficient memory for the filter\n1383:\t * a negative errno code is returned. On success the return is zero.\n1384:\t */\n1385:\tint bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)\n1386:\t{\n1387:\t\tunsigned int fsize = bpf_classic_proglen(fprog);\n1388:\t\tstruct bpf_prog *fp;\n1389:\t\n1390:\t\t/* Make sure new filter is there and in the right amounts. */\n1391:\t\tif (!bpf_check_basics_ok(fprog-\u003efilter, fprog-\u003elen))\n1392:\t\t\treturn -EINVAL;\n1393:\t\n1394:\t\tfp = bpf_prog_alloc(bpf_prog_size(fprog-\u003elen), 0);\n1395:\t\tif (!fp)\n1396:\t\t\treturn -ENOMEM;\n1397:\t\n1398:\t\tmemcpy(fp-\u003einsns, fprog-\u003efilter, fsize);\n1399:\t\n1400:\t\tfp-\u003elen = fprog-\u003elen;\n1401:\t\t/* Since unattached filters are not copied back to user\n1402:\t\t * space through sk_get_filter(), we do not need to hold\n1403:\t\t * a copy here, and can spare us the work.\n1404:\t\t */\n1405:\t\tfp-\u003eorig_prog = NULL;\n1406:\t\n1407:\t\t/* bpf_prepare_filter() already takes care of freeing\n1408:\t\t * memory in case something goes wrong.\n1409:\t\t */\n1410:\t\tfp = bpf_prepare_filter(fp, NULL);\n1411:\t\tif (IS_ERR(fp))\n1412:\t\t\treturn PTR_ERR(fp);\n1413:\t\n1414:\t\t*pfp = fp;\n1415:\t\treturn 0;\n1416:\t}\n1417:\tEXPORT_SYMBOL_GPL(bpf_prog_create);\n1418:\t\n1419:\t/**\n"
}

41/3 2026/10/31 04:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 21790
							output: 33
							thoughts: 464
						

Thoughts:
**Analyzing BPF Program Creation and Socket Filter Retrieval**

Okay, let's break this down. I'm focusing on the interaction between BPF program creation and filter retrieval, specifically in the context of the tun driver.

First, I'm tracing the flow in `bpf_prog_create`. It seems this function copies `fsize` bytes from `fprog->filter` into `fp->insns`. The key here is that `fsize` is derived from `bpf_classic_proglen(fprog)`, which, in turn, is simply `fprog->len * sizeof(struct sock_filter)`.  This indicates the allocated space for `insns` within the `tun_copy_filter` path has been fully initialized thanks to the allocation `kmalloc_array(fp.len, sizeof(struct sock_filter), ...)` and population with `copy_from_user`. So far, so good; the initialization seems correct.

Now, my attention shifts to the distinction between `sk_attach_filter` and `sk_attach_filter_kern`, especially in relation to the kernel-mode variant. I'm looking at `sk_attach_filter_kern`.  We see `bpf_prog_create` being used here. The key here is the comment that states the program *doesn't* retain the original instruction copy. This is a crucial point. It explicitly says that `sk_get_filter()` will return `-EACCES` and `sock_diag` will omit the filter data when using this helper.

This raises the key question: What happens when the user-space calls `getsockopt(..., SO_GET_FILTER, ...)` on the tun socket (`tfile->socket.sk`)? It will be using `sk_get_filter` to retrieve the program.  Given the comment about no original copy being maintained, I anticipate that we'll encounter either an error or missing filter data. I need to dig into `sk_get_filter` in `net/core/filter.c` to confirm this. That's the next step in my analysis.



42/3 2026/10/31 04:57 tool grepper
0m Args:
{
  "Expression": "sk_get_filter",
  "PathPrefixes": [
    "net/core/filter.c"
  ]
}

Results:
{
  "Output": "net/core/filter.c=1385=int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)\n--\nnet/core/filter.c-1401-\t/* Since unattached filters are not copied back to user\nnet/core/filter.c:1402:\t * space through sk_get_filter(), we do not need to hold\nnet/core/filter.c-1403-\t * a copy here, and can spare us the work.\n--\nnet/core/filter.c=1594=EXPORT_SYMBOL_GPL(sk_attach_filter);\n--\nnet/core/filter.c-1605- * The program is built by bpf_prog_create(), which does not keep an original\nnet/core/filter.c:1606: * copy of the instructions, so sk_get_filter() returns -EACCES and sock_diag\nnet/core/filter.c-1607- * omits the filter for a socket that uses this helper.\n--\nnet/core/filter.c=11757=EXPORT_SYMBOL_GPL(sk_detach_filter);\nnet/core/filter.c-11758-\nnet/core/filter.c:11759:int sk_get_filter(struct sock *sk, sockptr_t optval, unsigned int len)\nnet/core/filter.c-11760-{\n"
}

43/3 2026/10/31 04:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23101
							output: 37
							thoughts: 21
						

Thoughts:
Here's a first-person summary, tailored for an expert in the field:

**Diving into `sk_get_filter`**

Okay, time to get my hands dirty and dive into `sk_get_filter` within `net/core/filter.c`. I need to understand exactly how the packet filter mechanism is being accessed here. I'm especially interested in how it's being retrieved, and what security considerations are in place. What specific data structures are being used in this function to interface with the BPF (Berkeley Packet Filter) code? How are the filter programs cached or optimized, if at all? I'm anticipating interactions with the socket options, likely `SO_ATTACH_FILTER`, and I'm keen to see if any access control checks are performed. I need to understand the function’s role within the larger framework of networking stack operations, particularly how this function ensures the filter isn't corrupted, improperly accessed, or causing any adverse effects on system stability or network performance. It’s critical I understand the full context of its operation.



44/3 2026/10/31 04:57 tool read-file
0m Args:
{
  "File": "net/core/filter.c",
  "FirstLine": 11759,
  "LineCount": 50
}

Results:
{
  "Contents": "11759:\tint sk_get_filter(struct sock *sk, sockptr_t optval, unsigned int len)\n11760:\t{\n11761:\t\tstruct sock_fprog_kern *fprog;\n11762:\t\tstruct sk_filter *filter;\n11763:\t\tint ret = 0;\n11764:\t\n11765:\t\tsockopt_lock_sock(sk);\n11766:\t\tfilter = rcu_dereference_protected(sk-\u003esk_filter,\n11767:\t\t\t\t\t\t   lockdep_sock_is_held(sk));\n11768:\t\tif (!filter)\n11769:\t\t\tgoto out;\n11770:\t\n11771:\t\t/* We're copying the filter that has been originally attached,\n11772:\t\t * so no conversion/decode needed anymore. eBPF programs that\n11773:\t\t * have no original program cannot be dumped through this.\n11774:\t\t */\n11775:\t\tret = -EACCES;\n11776:\t\tfprog = filter-\u003eprog-\u003eorig_prog;\n11777:\t\tif (!fprog)\n11778:\t\t\tgoto out;\n11779:\t\n11780:\t\tret = fprog-\u003elen;\n11781:\t\tif (!len)\n11782:\t\t\t/* User space only enquires number of filter blocks. */\n11783:\t\t\tgoto out;\n11784:\t\n11785:\t\tret = -EINVAL;\n11786:\t\tif (len \u003c fprog-\u003elen)\n11787:\t\t\tgoto out;\n11788:\t\n11789:\t\tret = -EFAULT;\n11790:\t\tif (copy_to_sockptr(optval, fprog-\u003efilter, bpf_classic_proglen(fprog)))\n11791:\t\t\tgoto out;\n11792:\t\n11793:\t\t/* Instead of bytes, the API requests to return the number\n11794:\t\t * of filter blocks.\n11795:\t\t */\n11796:\t\tret = fprog-\u003elen;\n11797:\tout:\n11798:\t\tsockopt_release_sock(sk);\n11799:\t\treturn ret;\n11800:\t}\n11801:\t\n11802:\t#ifdef CONFIG_INET\n11803:\tstatic void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,\n11804:\t\t\t\t\t    struct sock_reuseport *reuse,\n11805:\t\t\t\t\t    struct sock *sk, struct sk_buff *skb,\n11806:\t\t\t\t\t    struct sock *migrating_sk,\n11807:\t\t\t\t\t    u32 hash)\n11808:\t{\n"
}

45/3 2026/10/31 04:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24141
							output: 26
							thoughts: 54
						

Thoughts:
Okay, let's break this down.

**Filtering Access in the Kernel: A Quick Dive**

Alright, so I'm looking at some kernel code, specifically around network filtering, and something immediately catches my eye within the `sk_get_filter` function.  It's that crucial check: `if (!fprog) goto out; ret = -EACCES;`.  Essentially, the code's saying, "Hey, if we don't have a filter program (`fprog`), we're bailing immediately." And that bail-out is a denied access scenario. That's a classic security check, preventing unexpected behavior when a filter isn't defined.

Now, I'm thinking, where else might this concept of filtering, specifically related to socket diagnostics, come into play? I need to explore further in the diagnostic code to understand how it's used. Let's see if something like `sock_diag` is relevant here, or perhaps `sk_diag_dump_filter` might provide more context. Time to dig into those areas and see if there are similar checks or related functionalities. The connection with sock diagnostics is quite interesting and I need to explore this connection.



46/3 2026/10/31 04:57 tool grepper
0m Args:
{
  "Expression": "orig_prog",
  "PathPrefixes": [
    "net/"
  ]
}

Results:
{
  "Output": "net/core/filter.c=1157=static int bpf_prog_store_orig_filter(struct bpf_prog *fp,\n--\nnet/core/filter.c-1162-\nnet/core/filter.c:1163:\tfp-\u003eorig_prog = kmalloc_obj(*fkprog);\nnet/core/filter.c:1164:\tif (!fp-\u003eorig_prog)\nnet/core/filter.c-1165-\t\treturn -ENOMEM;\nnet/core/filter.c-1166-\nnet/core/filter.c:1167:\tfkprog = fp-\u003eorig_prog;\nnet/core/filter.c-1168-\tfkprog-\u003elen = fprog-\u003elen;\n--\nnet/core/filter.c-1172-\tif (!fkprog-\u003efilter) {\nnet/core/filter.c:1173:\t\tkfree(fp-\u003eorig_prog);\nnet/core/filter.c-1174-\t\treturn -ENOMEM;\n--\nnet/core/filter.c=1180=static void bpf_release_orig_filter(struct bpf_prog *fp)\nnet/core/filter.c-1181-{\nnet/core/filter.c:1182:\tstruct sock_fprog_kern *fprog = fp-\u003eorig_prog;\nnet/core/filter.c-1183-\n--\nnet/core/filter.c=1385=int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)\n--\nnet/core/filter.c-1404-\t */\nnet/core/filter.c:1405:\tfp-\u003eorig_prog = NULL;\nnet/core/filter.c-1406-\n--\nnet/core/filter.c=1430=int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,\n--\nnet/core/filter.c-1450-\tfp-\u003elen = fprog-\u003elen;\nnet/core/filter.c:1451:\tfp-\u003eorig_prog = NULL;\nnet/core/filter.c-1452-\n--\nnet/core/filter.c=11759=int sk_get_filter(struct sock *sk, sockptr_t optval, unsigned int len)\n--\nnet/core/filter.c-11775-\tret = -EACCES;\nnet/core/filter.c:11776:\tfprog = filter-\u003eprog-\u003eorig_prog;\nnet/core/filter.c-11777-\tif (!fprog)\n--\nnet/core/sock_diag.c=75=int sock_diag_put_filterinfo(bool may_report_filterinfo, struct sock *sk,\n--\nnet/core/sock_diag.c-93-\nnet/core/sock_diag.c:94:\tfprog = filter-\u003eprog-\u003eorig_prog;\nnet/core/sock_diag.c-95-\tif (!fprog)\n"
}

47/3 2026/10/31 04:57 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25259
							output: 35
							thoughts: 875
						

Thoughts:
**Analyzing the TUN/TAP Driver Filter Vulnerability**

Okay, so I'm looking at this TUN/TAP driver patch. The initial thought is, if `orig_prog` is `NULL`, `sock_diag` should return 0, no filter information leak there.  Then I start digging into the `TUNGETFILTER` code. Before the patch, the code was using `copy_to_user` to return the `tun->fprog`, whatever `fprog` was defined as.

The patch introduces `tun_copy_filter`. It zeroes out the `fprog` buffer, then populates it with `fp.len` and `fp.filter`. Critically, `tun->fprog` is *then* set to this zeroed and populated `fprog`. So, when `TUNGETFILTER` is called post-patch, it copies the zeroed `tun->fprog` to user space. That's good; no leak there either!

But... what happens if `tun_attach` fails? I need to consider that. Looking at the `tun_attach` changes, I see a few key things. `sk_attach_filter` is now using `tun->fprog_kern` instead of `tun->fprog`. The original code, though, *also* had a potential critical bug. It was trying to attach the filter from `tun->fprog`, which *directly* used a user-space pointer to `tun->fprog.filter`. That's a *huge* vulnerability! That user pointer only holds meaning for the process that called `TUNATTACHFILTER`. If another process attached to the tun device, or the user's memory was unmapped, `sk_attach_filter` would *either* crash or read the wrong memory.

Furthermore, in the original code, `if (!err) goto out;` - I'm realizing this means *if* the `sk_attach_filter` *succeeded*, it would jump out of the `tun_attach` function, skipping the rest of the attach sequence. That would be a major flaw in the original design. I need to confirm this by checking the code in `drivers/net/tun.c`. I need to figure out how this logic ever got through review, and confirm my suspicions!



48/3 2026/10/31 04:58 tool read-file
0m Args:
{
  "File": "drivers/net/tun.c",
  "FirstLine": 800,
  "LineCount": 50
}

Results:
{
  "Contents": " 800:\t\tif (rtnl_dereference(tfile-\u003etun) \u0026\u0026 !tfile-\u003edetached)\n 801:\t\t\tgoto out;\n 802:\t\n 803:\t\terr = -EBUSY;\n 804:\t\tif (!(tun-\u003eflags \u0026 IFF_MULTI_QUEUE) \u0026\u0026 tun-\u003enumqueues == 1)\n 805:\t\t\tgoto out;\n 806:\t\n 807:\t\terr = -E2BIG;\n 808:\t\tif (!tfile-\u003edetached \u0026\u0026\n 809:\t\t    tun-\u003enumqueues + tun-\u003enumdisabled == MAX_TAP_QUEUES)\n 810:\t\t\tgoto out;\n 811:\t\n 812:\t\terr = 0;\n 813:\t\n 814:\t\t/* Re-attach the filter to persist device */\n 815:\t\tif (!skip_filter \u0026\u0026 (tun-\u003efilter_attached == true)) {\n 816:\t\t\tlock_sock(tfile-\u003esocket.sk);\n 817:\t\t\terr = sk_attach_filter_kern(\u0026tun-\u003efprog_kern, tfile-\u003esocket.sk);\n 818:\t\t\trelease_sock(tfile-\u003esocket.sk);\n 819:\t\t\tif (err)\n 820:\t\t\t\tgoto out;\n 821:\t\t\trollback_filter = true;\n 822:\t\t}\n 823:\t\n 824:\t\tif (!tfile-\u003edetached \u0026\u0026\n 825:\t\t    ptr_ring_resize(\u0026tfile-\u003etx_ring, dev-\u003etx_queue_len,\n 826:\t\t\t\t    GFP_KERNEL, tun_ptr_free)) {\n 827:\t\t\terr = -ENOMEM;\n 828:\t\t\tgoto out;\n 829:\t\t}\n 830:\t\n 831:\t\tspin_lock(\u0026tfile-\u003etx_ring.consumer_lock);\n 832:\t\ttfile-\u003equeue_index = tun-\u003enumqueues;\n 833:\t\tspin_unlock(\u0026tfile-\u003etx_ring.consumer_lock);\n 834:\t\ttfile-\u003esocket.sk-\u003esk_shutdown \u0026= ~RCV_SHUTDOWN;\n 835:\t\ttun_force_wake_queue(tun, tfile);\n 836:\t\n 837:\t\tif (tfile-\u003edetached) {\n 838:\t\t\t/* Re-attach detached tfile, updating XDP queue_index */\n 839:\t\t\tWARN_ON(!xdp_rxq_info_is_reg(\u0026tfile-\u003exdp_rxq));\n 840:\t\n 841:\t\t\tif (tfile-\u003exdp_rxq.queue_index    != tfile-\u003equeue_index)\n 842:\t\t\t\ttfile-\u003exdp_rxq.queue_index = tfile-\u003equeue_index;\n 843:\t\t} else {\n 844:\t\t\t/* Setup XDP RX-queue info, for new tfile getting attached */\n 845:\t\t\terr = xdp_rxq_info_reg(\u0026tfile-\u003exdp_rxq,\n 846:\t\t\t\t\t       tun-\u003edev, tfile-\u003equeue_index, 0);\n 847:\t\t\tif (err \u003c 0)\n 848:\t\t\t\tgoto out;\n 849:\t\t\terr = xdp_rxq_info_reg_mem_model(\u0026tfile-\u003exdp_rxq,\n"
}

49/3 2026/10/31 04:58 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27509
							output: 32
							thoughts: 889
						

Thoughts:
**Analyzing the TUN Filter Attachment and Detachment Mechanism**

Okay, so I'm looking closely at this `tun_attach` function, and that original `if (!err) goto out;` statement was a blatant bug. If `sk_attach_filter` succeeded, it skipped the crucial queue setup. If it failed, it continued anyway! Good catch by the author with the fix of `if (err) goto out;`.

Let's now dig deeper. The `tun_attach` code also uses `rollback_filter`. Looking at the `out:` label, I see that if there's an error *and* `rollback_filter` is true, the filter gets detached. The code comments explain that this is needed because the filter was installed *before* the rest of the attach process, so if something else fails, we need to roll it back. This also means that if an earlier filter was in place, that filter is removed without it being restored.

Now, let me examine `tun_detach_filter`. The code iterates through the `tfiles` associated with the TUN device, locks the socket, detaches the filter with `sk_detach_filter`, and then releases the socket. Crucially, it also `kfree`s the `fprog_kern.filter` and resets the `fprog_kern` fields to `NULL` and `0` respectively, and also sets `filter_attached` to `false`.

Moving on to `tun_free_netdev`, I see that it calls `__tun_set_ebpf` (which I'll need to look at sometime), and also `kfree`s the `fprog_kern.filter`. This implies the filter is freed as part of netdev cleanup.

Okay, let's switch gears and check out `__tun_chr_ioctl`. Specifically, the `TUNATTACHFILTER` case. We copy the filter program from user space into `fprog_kern`, then we call `tun_attach_filter`. If *that* succeeds, only then do we copy the kernel-side copy to the main one (`tun->fprog_kern = fprog_kern;`). But before that we free the `fprog_kern.filter`.

Now, wait a minute, could there be an issue with uninitialized memory here? Let's check `fprog_kern`. Looking inside `tun_copy_filter`, if it returns 0, the code correctly initializes `fprog_kern->len = fp.len;` and `fprog_kern->filter = insns;`. So those two fields are initialized. That's a relief.
I'll need to know more about the internals of `struct sock_fprog_kern`.



50/3 2026/10/31 04:58 tool grepper
0m Args:
{
  "Expression": "struct sock_fprog_kern\\b",
  "PathPrefixes": [
    "include/"
  ]
}

Results:
{
  "Output": "include/linux/bpf.h=1988=struct bpf_prog {\n--\ninclude/linux/bpf.h-2019-\tstruct bpf_prog_aux\t*aux;\t\t/* Auxiliary fields */\ninclude/linux/bpf.h:2020:\tstruct sock_fprog_kern\t*orig_prog;\t/* Original BPF program */\ninclude/linux/bpf.h-2021-\t/* Instructions for interpreter */\n--\ninclude/linux/filter.h=736=struct compat_sock_fprog {\n--\ninclude/linux/filter.h-740-\ninclude/linux/filter.h:741:struct sock_fprog_kern {\ninclude/linux/filter.h-742-\tu16\t\t\tlen;\n--\ninclude/linux/filter.h=1253=typedef int (*bpf_aux_classic_check_t)(struct sock_filter *filter,\n--\ninclude/linux/filter.h-1255-\ninclude/linux/filter.h:1256:int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog);\ninclude/linux/filter.h-1257-int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,\n--\ninclude/linux/filter.h=1262=int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk);\ninclude/linux/filter.h:1263:int sk_attach_filter_kern(struct sock_fprog_kern *fprog, struct sock *sk);\ninclude/linux/filter.h-1264-int sk_attach_bpf(u32 ufd, struct sock *sk);\n"
}

51/3 2026/10/31 04:58 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29460
							output: 35
							thoughts: 20
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Diving into eBPF Filter Definitions**

Okay, time to get my hands dirty. I'm going to start by taking a look at `include/linux/filter.h`, specifically around line 741. I remember that's where a lot of the core structures and macros for eBPF filtering are defined. I need to refresh my memory on the layout of the `sock_filter` struct and the related instructions. I'm probably looking for something related to the definition of a specific helper function or maybe a new flag related to recent changes in the BPF verifier. I know there have been some discussions about improving performance or adding new capabilities. Let's see if this is related to what I'm looking at today.



52/3 2026/10/31 04:58 tool read-file
0m Args:
{
  "File": "include/linux/filter.h",
  "FirstLine": 735,
  "LineCount": 15
}

Results:
{
  "Contents": " 735:\t/* A struct sock_filter is architecture independent. */\n 736:\tstruct compat_sock_fprog {\n 737:\t\tu16\t\tlen;\n 738:\t\tcompat_uptr_t\tfilter;\t/* struct sock_filter * */\n 739:\t};\n 740:\t\n 741:\tstruct sock_fprog_kern {\n 742:\t\tu16\t\t\tlen;\n 743:\t\tstruct sock_filter\t*filter;\n 744:\t};\n 745:\t\n 746:\t/* Some arches need doubleword alignment for their instructions and/or data */\n 747:\t#define BPF_IMAGE_ALIGNMENT 8\n 748:\t\n 749:\tstruct bpf_binary_header {\n"
}

53/3 2026/10/31 04:58 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29908
							output: 36
							thoughts: 1382
						

Thoughts:
**Analyzing BPF Filter Handling in the TUN Driver**

Okay, so I'm digging into this TUN driver code, specifically the BPF filter handling. The `struct sock_fprog_kern` only contains `len` and `filter` - straightforward enough. Looking at `tun_copy_filter`, I see a critical `memset` at the beginning: `memset(fprog, 0, sizeof(*fprog));`. This is crucial. It's initializing the entire struct, which, given its structure, is probably meant to address potential padding issues on different architectures. Then, `fprog->len` and `fprog->filter` get populated with the user-provided values. The code initializes `fprog_kern->len` and `fprog_kern->filter` similarly.

Now, error handling is my next focus. If any of the `copy_from_user` calls fail, it returns an error and cleans up. Specifically, `-EFAULT`, `-EINVAL`, or `-ENOMEM` are returned depending on the type of error. Crucially, the code checks for various failure scenarios within `tun_copy_filter` and returns a non-zero value, which breaks the ioctl immediately. If the filter is valid, `tun_attach_filter` is called, and a subsequent free is called on the `filter` on error. After successful attachment, the old filter is freed. A crucial detail is `insns` allocation using `kmalloc_array`, ensuring that the allocated memory can be freed safely. And thankfully, if `copy_from_user` partially copies, the code catches it with `copy_from_user`'s return value. The allocated memory is immediately freed, preventing the use of a partially-copied buffer.

Now, regarding the concern about potentially leaking uninitialized memory, let's look at `TUNGETFILTER`. Here, it's copying `tun->fprog` to user space. Where does `tun->fprog` come from? Initially, `tun` is zeroed by `kvzalloc`, so that covers the initial allocation. Further, when `TUNATTACHFILTER` is called, the code *explicitly* zeros `fprog` with `memset`, ensuring that all the members are initialized *before* filling it with values from user space. The padding bytes in `tun->fprog` are explicitly zeroed. This is the critical piece that prevents leaking any uninitialized data to userspace.

Finally, I need to verify that `bpf_prog_validate_classic` doesn't read any uninitialized memory. Let's dig into `bpf_check_basics_ok` and `bpf_check_classic` to make absolutely sure.



54/3 2026/10/31 04:58 tool grepper
0m Args:
{
  "Expression": "bpf_check_basics_ok",
  "PathPrefixes": [
    "net/core/filter.c"
  ]
}

Results:
{
  "Output": "net/core/filter.c=988=static bool chk_code_allowed(u16 code_to_probe)\n--\nnet/core/filter.c-1053-\nnet/core/filter.c:1054:static bool bpf_check_basics_ok(const struct sock_filter *filter,\nnet/core/filter.c-1055-\t\t\t\tunsigned int flen)\n--\nnet/core/filter.c=1385=int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)\n--\nnet/core/filter.c-1390-\t/* Make sure new filter is there and in the right amounts. */\nnet/core/filter.c:1391:\tif (!bpf_check_basics_ok(fprog-\u003efilter, fprog-\u003elen))\nnet/core/filter.c-1392-\t\treturn -EINVAL;\n--\nnet/core/filter.c=1430=int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,\n--\nnet/core/filter.c-1437-\t/* Make sure new filter is there and in the right amounts. */\nnet/core/filter.c:1438:\tif (!bpf_check_basics_ok(fprog-\u003efilter, fprog-\u003elen))\nnet/core/filter.c-1439-\t\treturn -EINVAL;\n--\nnet/core/filter.c=1477=EXPORT_SYMBOL_GPL(bpf_prog_destroy);\n--\nnet/core/filter.c-1483- *\nnet/core/filter.c:1484: * Run bpf_check_basics_ok() and bpf_check_classic() on a program that is\nnet/core/filter.c-1485- * already in kernel memory, without building a struct bpf_prog.  These are\n--\nnet/core/filter.c=1496=int bpf_prog_validate_classic(const struct sock_filter *insns, unsigned int len)\nnet/core/filter.c-1497-{\nnet/core/filter.c:1498:\tif (!bpf_check_basics_ok(insns, len))\nnet/core/filter.c-1499-\t\treturn -EINVAL;\n--\nnet/core/filter.c=1532=struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)\n--\nnet/core/filter.c-1541-\t/* Make sure new filter is there and in the right amounts. */\nnet/core/filter.c:1542:\tif (!bpf_check_basics_ok(fprog-\u003efilter, fprog-\u003elen))\nnet/core/filter.c-1543-\t\treturn ERR_PTR(-EINVAL);\n"
}

55/3 2026/10/31 04:58 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32627
							output: 37
							thoughts: 272
						

Thoughts:
**My Analysis of the BPF Program Attachment**

Okay, so I'm diving into this BPF program attachment process, and my initial concern is ensuring everything is fundamentally sound before we even think about execution. The `bpf_check_basics_ok` function is the first line of defense; it's confirming that the filter itself isn't null, the filter length (`flen`) is sensible, and that we haven't encountered any overflow issues. Good, that's basic sanity checking done.

Next, `bpf_check_classic` seems to be responsible for the actual validation of the instruction set. This includes verifying the jump targets and the instructions themselves, making sure everything is legitimate and won't cause any unexpected behavior. I'm assuming it goes through all the instructions in the program to validate.

Crucially, I know that all the instructions (`insns`) were copied from user space. The size of this copy is determined by `fp.len * sizeof(struct sock_filter)`. This is important, as it confirms where these instructions came from. We want to be sure user space can pass instructions to kernel space securely, and that no malicious code gets executed.

Now, let's step back a moment and look at the bigger picture. I need to understand what's happening at the kernel level during attachment. `sk_attach_filter_kern` seems to be the entry point. A few checks occur, such as making sure the socket is not locked. It calls `bpf_prog_create` to attempt to create a BPF program.

Alright, the core of the attachment is then happening in `__sk_attach_prog`. This is where I want to focus. I'm immediately concerned about uninitialized memory. Does this function somehow use memory that hasn't been properly set? That could be a huge security vulnerability. I need to investigate what's happening in `__sk_attach_prog` itself.



56/3 2026/10/31 04:58 tool grepper
0m Args:
{
  "Expression": "static int __sk_attach_prog\\(",
  "PathPrefixes": [
    "net/core/filter.c"
  ]
}

Results:
{
  "Output": "net/core/filter.c=1503=EXPORT_SYMBOL_GPL(bpf_prog_validate_classic);\nnet/core/filter.c-1504-\nnet/core/filter.c:1505:static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)\nnet/core/filter.c-1506-{\n"
}

57/3 2026/10/31 04:58 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33452
							output: 36
							thoughts: 22
						

Thoughts:
Okay, let's dive into this. Here's how I'd approach summarizing the thought process, considering I'm an expert in this field:

**Diving into `__sk_attach_prog` in `net/core/filter.c`**

Alright, my immediate thought is to get my bearings. I need to refresh my memory on the specifics of `__sk_attach_prog`. What's this function doing in the context of the networking stack? It's in `net/core/filter.c`, so it's a key part of how we attach BPF programs (or older filter types) to sockets, right? I'm assuming it's the core function that orchestrates this, the one that makes the actual link.

First, I need to remember the typical call flow. Is this function called directly, or is it a helper invoked by something more high-level like `setsockopt` with a `SO_ATTACH_BPF` or equivalent? The name suggests it's an internal function, probably prefixed with `__` because it isn't meant for direct user-space interaction. I'll need to check the surrounding code to determine how the call flow is set up.

I'm expecting to see things like:

*   **Security Checks:** We *must* have proper security checks here. This is a crucial point of entry for code execution within the kernel, so validating the program, its permissions, and the context of the socket is paramount. I'll be looking closely for those.
*   **Program Validation:** Is there proper validation of the BPF/filter program itself? Memory access, register usage, and general program validity are incredibly important. I expect a thorough validation step, maybe using the BPF verifier.
*   **Socket Context Updates:** This function will need to update the internal socket data structures to point to the attached program, likely through a pointer, structure, or similar method. This includes adding the program to the socket structure to be called at the specified hook.
*   **Resource Management:** I need to look for proper resource management, particularly around memory allocation for the program's context or any auxiliary data structures. Any leaks here would be critical. It also needs to handle the existing filter if one is present, and gracefully free or replace it.
*   **Error Handling:** What kind of error handling do we have? Failure modes should be gracefully handled, reporting meaningful error codes to the user (if called from user space, that is). We want to avoid any possibility of panic or a system crash.
*   **Concurrency:** Is this function protected by any locks? Attaching/detaching filters is a highly concurrent operation. I'll be looking for locks or other synchronization mechanisms to make sure that the socket structure remains consistent, and that multiple calls don't step on each other's toes.

I'll also keep an eye out for any interactions with other parts of the filtering subsystem. Does it update any global state? Does it call into any helper functions within the BPF or legacy filter infrastructure? Understanding these interactions will be important to understand the overall architecture. I expect a modular approach, and that this code will fit within the broader BPF framework.

Finally, I'll pay close attention to the code's comments and any related documentation. They often hold valuable insights into the design decisions and the intended behavior of the function. Let's see what we've got!



58/3 2026/10/31 04:59 tool read-file
0m Args:
{
  "File": "net/core/filter.c",
  "FirstLine": 1505,
  "LineCount": 40
}

Results:
{
  "Contents": "1505:\tstatic int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)\n1506:\t{\n1507:\t\tstruct sk_filter *fp, *old_fp;\n1508:\t\n1509:\t\tfp = kmalloc_obj(*fp);\n1510:\t\tif (!fp)\n1511:\t\t\treturn -ENOMEM;\n1512:\t\n1513:\t\tfp-\u003eprog = prog;\n1514:\t\n1515:\t\tif (!__sk_filter_charge(sk, fp)) {\n1516:\t\t\tkfree(fp);\n1517:\t\t\treturn -ENOMEM;\n1518:\t\t}\n1519:\t\trefcount_set(\u0026fp-\u003erefcnt, 1);\n1520:\t\n1521:\t\told_fp = rcu_dereference_protected(sk-\u003esk_filter,\n1522:\t\t\t\t\t\t   lockdep_sock_is_held(sk));\n1523:\t\trcu_assign_pointer(sk-\u003esk_filter, fp);\n1524:\t\n1525:\t\tif (old_fp)\n1526:\t\t\tsk_filter_uncharge(sk, old_fp);\n1527:\t\n1528:\t\treturn 0;\n1529:\t}\n1530:\t\n1531:\tstatic\n1532:\tstruct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)\n1533:\t{\n1534:\t\tunsigned int fsize = bpf_classic_proglen(fprog);\n1535:\t\tstruct bpf_prog *prog;\n1536:\t\tint err;\n1537:\t\n1538:\t\tif (sock_flag(sk, SOCK_FILTER_LOCKED))\n1539:\t\t\treturn ERR_PTR(-EPERM);\n1540:\t\n1541:\t\t/* Make sure new filter is there and in the right amounts. */\n1542:\t\tif (!bpf_check_basics_ok(fprog-\u003efilter, fprog-\u003elen))\n1543:\t\t\treturn ERR_PTR(-EINVAL);\n1544:\t\n"
}

59/3 2026/10/31 04:59 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34816
							output: 31
							thoughts: 35
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Investigating Compatibility Issues in the TUN Driver**

Right, let's dive into this `__tun_chr_ioctl` function. Specifically, I need to check its interaction with the compatibility ioctl mechanism. My immediate question is: does the `tun` driver even *have* a compatibility ioctl handler defined? This is crucial because if it doesn't, we're likely dealing with a completely different problem, or we may need to develop a solution where one doesn't exist. So, the next logical step is to verify its presence (or absence). Time to dig into the driver code and see what's actually implemented.



60/3 2026/10/31 04:59 tool grepper
0m Args:
{
  "Expression": "compat_ioctl",
  "PathPrefixes": [
    "drivers/net/tun.c"
  ]
}

Results:
{
  "Output": "drivers/net/tun.c=3599=static long tun_chr_ioctl(struct file *file,\n--\ndrivers/net/tun.c-3605-#ifdef CONFIG_COMPAT\ndrivers/net/tun.c:3606:static long tun_chr_compat_ioctl(struct file *file,\ndrivers/net/tun.c-3607-\t\t\t unsigned int cmd, unsigned long arg)\n--\ndrivers/net/tun.c=3728=static const struct file_operations tun_fops = {\n--\ndrivers/net/tun.c-3734-#ifdef CONFIG_COMPAT\ndrivers/net/tun.c:3735:\t.compat_ioctl = tun_chr_compat_ioctl,\ndrivers/net/tun.c-3736-#endif\n"
}

61/3 2026/10/31 04:59 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35237
							output: 36
							thoughts: 23
						

Thoughts:
Okay, let's dive into this. Here's my take on understanding this code:

**Analyzing `tun_chr_compat_ioctl` in `drivers/net/tun.c`**

Alright, time to crack open `tun_chr_compat_ioctl` within `drivers/net/tun.c`. Given my expertise, I already have a pretty good idea what's going on here, but let's go step by step and confirm that understanding. This function is, of course, the compatibility entry point for handling `ioctl` calls to the TUN/TAP device driver, likely to ensure older applications still function. I'm thinking immediately about the potential differences and challenges involved in maintaining backwards compatibility within a driver like this one, specifically the potential need to translate between various data structures and ioctl arguments from different kernel versions.

I'll be looking to see how it handles the interaction between the user space `ioctl` calls and the internal data structures used by the TUN driver. What kind of argument validation is taking place? Is it directly manipulating kernel memory, or using more modern techniques to avoid vulnerabilities and potential issues. This compatibility layer must carefully manage the differences in ioctl numbers, argument structures and ensure that the old interfaces are translated into the new ones. There's probably a lot of clever conditional logic here. I need to keep an eye out for potential security concerns associated with backwards compatibility, especially those introduced by less-careful user-space applications. And what about the impact on performance? This whole process potentially adds overhead. I'm hoping to get a clear picture of how this compatibility is achieved efficiently. Let's see how well it's implemented. Time to read!



62/3 2026/10/31 04:59 tool read-file
0m Args:
{
  "File": "drivers/net/tun.c",
  "FirstLine": 3605,
  "LineCount": 50
}

Results:
{
  "Contents": "3605:\t#ifdef CONFIG_COMPAT\n3606:\tstatic long tun_chr_compat_ioctl(struct file *file,\n3607:\t\t\t\t unsigned int cmd, unsigned long arg)\n3608:\t{\n3609:\t\tswitch (cmd) {\n3610:\t\tcase TUNSETIFF:\n3611:\t\tcase TUNGETIFF:\n3612:\t\tcase TUNSETTXFILTER:\n3613:\t\tcase TUNGETSNDBUF:\n3614:\t\tcase TUNSETSNDBUF:\n3615:\t\tcase SIOCGIFHWADDR:\n3616:\t\tcase SIOCSIFHWADDR:\n3617:\t\t\targ = (unsigned long)compat_ptr(arg);\n3618:\t\t\tbreak;\n3619:\t\tdefault:\n3620:\t\t\targ = (compat_ulong_t)arg;\n3621:\t\t\tbreak;\n3622:\t\t}\n3623:\t\n3624:\t\t/*\n3625:\t\t * compat_ifreq is shorter than ifreq, so we must not access beyond\n3626:\t\t * the end of that structure. All fields that are used in this\n3627:\t\t * driver are compatible though, we don't need to convert the\n3628:\t\t * contents.\n3629:\t\t */\n3630:\t\treturn __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));\n3631:\t}\n3632:\t#endif /* CONFIG_COMPAT */\n3633:\t\n3634:\tstatic int tun_chr_fasync(int fd, struct file *file, int on)\n3635:\t{\n3636:\t\tstruct tun_file *tfile = file-\u003eprivate_data;\n3637:\t\tint ret;\n3638:\t\n3639:\t\tif (on) {\n3640:\t\t\tret = file_f_owner_allocate(file);\n3641:\t\t\tif (ret)\n3642:\t\t\t\tgoto out;\n3643:\t\t}\n3644:\t\n3645:\t\tif ((ret = fasync_helper(fd, file, on, \u0026tfile-\u003efasync)) \u003c 0)\n3646:\t\t\tgoto out;\n3647:\t\n3648:\t\tif (on) {\n3649:\t\t\t__f_setown(file, task_pid(current), PIDTYPE_TGID, 0);\n3650:\t\t\ttfile-\u003eflags |= TUN_FASYNC;\n3651:\t\t} else\n3652:\t\t\ttfile-\u003eflags \u0026= ~TUN_FASYNC;\n3653:\t\tret = 0;\n3654:\tout:\n"
}

63/3 2026/10/31 04:59 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36352
							output: 283
							thoughts: 2696
						

Thoughts:
**KMSAN Assessment: tun_chr_compat_ioctl Patch**

Okay, so I'm looking at this `tun_chr_compat_ioctl` code and trying to figure out if it needs KMSAN. First, the basics: this patch is about handling classic BPF filters in the kernel for TUN devices. The key is that the kernel *now* holds a copy of the filter program (`struct sock_fprog_kern`), which is validated and attached to sockets. I need to see if this introduces a risk of uninitialized memory usage or data leaks.

Let's break it down by the KMSAN criteria. Criterion 1: Kernel structures sent to userspace. In `TUNGETFILTER`, the `struct sock_fprog` structure `tun->fprog` is sent to userspace. Before this patch, the user directly manipulates `tun->fprog`. Now, the `memset` explicitly zeroes out this structure in `tun_copy_filter`. If `TUNGETFILTER` is called when no filter is attached, the `tun_struct` itself is allocated via `kvzalloc` in `alloc_netdev_mqs`, and thus, zeroed. And when `TUNDETACHFILTER` is called, `tun->fprog` is not modified, so it continues to retain the zeroed contents. No uninitialized data can leak.

Criterion 2: Conditional logic with uninitialized variables. Let's look at the introduced variables and struct fields, like `fprog_kern` and `rollback_filter`. They're *always* initialized: `fprog_kern` is zeroed by allocation, then filled. `rollback_filter` is always initialized to `false`. Branching depends on `err`, but this is properly handled and initialized at every return path. There is no condition depending on an uninitialized value.

Criterion 3: Allocation of complex data structures. The code allocates `insns` (copying from user space) and `bpf_prog`. Any failure in the user-space copy leads to immediate freeing. `bpf_prog_alloc` and `memcpy` are used to fully initialize. Everything is explicitly initialized.

Criterion 4: Bounds checks and lengths. We have checks for `fp.len` with bounds on `BPF_MAXINSNS`, and `copy_from_user` usage. Classic BPF instructions copied from userspace are validated by `bpf_prog_validate_classic` before attachment.

So, the code is very careful about initialization. I need to make sure I don't miss something. I'll double-check:

*   **Memory Management:** The patch uses `kfree` a lot. Could there be double frees, use-after-free, or memory leaks? That's heap lifecycle and KASAN/SLUB\_DEBUG will handle those.
*   **Locking/Concurrency:** We're dealing with `rtnl_lock` and socket locks (`lock_sock`). LOCKDEP's got that covered.
*   **Error Handling/Rollback:** The `rollback_filter` logic in `tun_attach`. This is covered by explicit initialization, properly controlled branching, and proper cleanup.

None of this is a *KMSAN* issue. No uninitialized memory reads or leaks of uninitialized memory. The `memset` in `tun_copy_filter` is there precisely to prevent data leakage to user space. It specifically makes `tun->fprog` zeroed before returning it via `TUNGETFILTER`. That's the key.

Let's re-state the rules: KMSAN is for detecting memory risks ONLY detected by KMSAN. If KASAN, LOCKDEP, or standard bug detectors would catch the issue, we don't need KMSAN. In addition, if stack/heap struct are zeroed/initialized before read or copy, then it doesn't need KMSAN. This patch is covered. This patch:

1.  Stores a kernel copy of the BPF filter.
2.  Adds `bpf_prog_validate_classic()` and `sk_attach_filter_kern()`.
3.  Copies user filters and zeroes `struct sock_fprog`.
4.  Has robust rollback and cleanup.

Crucially, all allocations are zeroed or initialized, and any copied user data is validated. KASAN/LOCKDEP can handle the memory management and locking issues, which is everything else that this patch touches. Therefore, the answer is NeedsKMSAN = false.



64/3 2026/10/31 05:00 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch updates the TUN driver to cache a kernel copy of classic BPF filters (struct sock_fprog_kern) to allow re-attaching filters across queue attachments without relying on the original process's address space.\n\nFrom a KMSAN perspective:\n- All stack variables (fp, fprog, fprog_kern) and heap buffers (insns) are either fully populated from copy_from_user or explicitly zeroed out with memset(fprog, 0, sizeof(*fprog)) before being saved or copied back to user space (via TUNGETFILTER).\n- Any failed copy_from_user promptly aborts and frees the temporary allocation before any uninitialized bytes can be accessed or propagated.\n- No uninitialized data or padding can be exposed to user space or used in conditional branching.\n\nFrom a KASAN/standard detectors perspective:\n- Potential risks introduced by this change include heap allocation tracking, double-free / use-after-free bugs (e.g., in error unwinding or netdev teardown with fprog_kern.filter), and locking issues (sock lock handling), which are already comprehensively detected by KASAN and LOCKDEP.\n\nTherefore, dedicated KMSAN fuzzing is not required.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch updates the TUN driver to cache a kernel copy of classic BPF filters (struct sock_fprog_kern) to allow re-attaching filters across queue attachments without relying on the original process's address space.\n\nFrom a KMSAN perspective:\n- All stack variables (fp, fprog, fprog_kern) and heap buffers (insns) are either fully populated from copy_from_user or explicitly zeroed out with memset(fprog, 0, sizeof(*fprog)) before being saved or copied back to user space (via TUNGETFILTER).\n- Any failed copy_from_user promptly aborts and frees the temporary allocation before any uninitialized bytes can be accessed or propagated.\n- No uninitialized data or padding can be exposed to user space or used in conditional branching.\n\nFrom a KASAN/standard detectors perspective:\n- Potential risks introduced by this change include heap allocation tracking, double-free / use-after-free bugs (e.g., in error unwinding or netdev teardown with fprog_kern.filter), and locking issues (sock lock handling), which are already comprehensively detected by KASAN and LOCKDEP.\n\nTherefore, dedicated KMSAN fuzzing is not required.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)