* [PATCH net v9 0/2] genetlink: Reject joining multicast groups no family owns
@ 2026-11-25 14:45 Anil Kaushik
2026-11-25 14:45 ` [PATCH net v9 1/2] " Anil Kaushik
2026-11-25 14:45 ` [PATCH net v9 2/2] selftests: net: test joining genetlink " Anil Kaushik
0 siblings, 2 replies; 4+ messages in thread
From: Anil Kaushik @ 2026-11-25 14:45 UTC (permalink / raw)
To: netdev
Cc: davem, edumazet, kuba, pabeni, horms, idosch, nicolas.dichtel,
jacob.e.keller, jiri, fw, martineau, v3rdant.xiang, aliceryhl,
linux-kernel, nhorman, shuah, linux-kselftest,
anilkaushikwireless
genl_bind() lets any user join a multicast group ID that no family owns.
A family registered later can get that ID, and the socket stays a member
without a capability check. Patch 1 makes genl_bind() return -ENOENT for
such an ID. Patch 2 adds a selftest for it.
v9:
- In the selftest, find the initial network namespace with its fixed
nsfs inode number, not by comparing with PID 1, which is in the same
namespace as the test in a container (Sashiko).
- Unload drop_monitor at the end of the selftest, so that the next run
does not skip that check (Sashiko).
- Patch 1 is unchanged. The Sashiko point on it in v8, a family
unregistered during the join, is the window the commit message
describes. The fix for it was patch 2 of v5, which was not accepted.
v8: https://lore.kernel.org/netdev/20261123155503.2497063-1-anilkaushikwireless@gmail.com/
- In the selftest, read the group memberships in host byte order, so it
also works on big-endian (Sashiko).
- Skip the selftest outside the initial network namespace: the family
dump there does not list the families that are not netnsok, so it
could take one of their groups as free (Sashiko).
- Close the selftest sockets, also when a check is skipped (Sashiko).
- Skip the drop_monitor check when NET_DM gets no group ID that was
free, so it cannot pass without testing anything (Sashiko).
- Rebase on net.
v7: https://lore.kernel.org/netdev/20261116124030.1595567-1-anilkaushikwireless@gmail.com/
I used an LLM to help write and review the code, the tests and the
commit messages of this series. I checked and tested every change
myself.
Anil Kaushik (2):
genetlink: Reject joining multicast groups no family owns
selftests: net: test joining genetlink groups no family owns
include/linux/netlink.h | 3 +
include/uapi/linux/net_dropmon.h | 2 +
net/netlink/af_netlink.c | 6 +
net/netlink/genetlink.c | 5 +-
tools/testing/selftests/net/Makefile | 1 +
tools/testing/selftests/net/nl_genl_mcast.py | 128 +++++++++++++++++++
6 files changed, 144 insertions(+), 1 deletion(-)
create mode 100755 tools/testing/selftests/net/nl_genl_mcast.py
base-commit: 7b0c5f0c757cb61e28dc4128633877aaa8f6f9bd
--
2.25.1
^ permalink raw reply [flat|nested] 4+ messages in thread
* [PATCH net v9 1/2] genetlink: Reject joining multicast groups no family owns
2026-11-25 14:45 [PATCH net v9 0/2] genetlink: Reject joining multicast groups no family owns Anil Kaushik
@ 2026-11-25 14:45 ` Anil Kaushik
2026-11-25 14:45 ` [PATCH net v9 2/2] selftests: net: test joining genetlink " Anil Kaushik
1 sibling, 0 replies; 4+ messages in thread
From: Anil Kaushik @ 2026-11-25 14:45 UTC (permalink / raw)
To: netdev
Cc: davem, edumazet, kuba, pabeni, horms, idosch, nicolas.dichtel,
jacob.e.keller, jiri, fw, martineau, v3rdant.xiang, aliceryhl,
linux-kernel, nhorman, shuah, linux-kselftest,
anilkaushikwireless
genl_bind() checks the GENL_MCAST_CAP_* flags of a group only when a
family owns it. For a group ID that no family owns, it returns 0, so any
user can join it.
A family registered later can get that ID, and the socket stays a member:
nothing checks it again. An unprivileged user can join the free IDs, load
a family module with CTRL_CMD_GETFAMILY, which calls request_module(),
and then receive the notifications of a group with
GENL_MCAST_CAP_NET_ADMIN or GENL_MCAST_CAP_SYS_ADMIN. For example the
drop_monitor "events" group always gets ID 1, and is free until the
drop_monitor module is loaded.
Fix by returning -ENOENT from genl_bind() when no family owns the group.
There are no group flags to check before the family registers, so this
applies to privileged callers too: a program that joins a fixed ID such
as NET_DM_GRP_ALERT before the family is loaded no longer gets its
messages. I don't know of a program that does this. One that resolves
the family first still joins. Say so in the comments on the static
IDs.
bind() takes a mask of groups, and most IDs in it can have no owner. Such
a mask used to work, so keep it working: netlink_bind() skips an ID when
the bind callback returns -ENOENT, and joins the others. Only genl_bind()
returns -ENOENT. A skipped ID is not joined, so it is no longer in the
groups that getsockname() and NETLINK_LIST_MEMBERSHIPS report.
setsockopt() returns the error, as it asks for one group.
This does not cover a family that is unregistered between the check and
the point where the membership bit is set. Hitting it needs a
privileged module unload at the same time, and the capability check
already has the same window.
Found by the Sashiko review of the gtp multicast group fix. Tested as an
unprivileged user who joins all free IDs, then loads gtp and
drop_monitor:
Before:
joins: ok=62 EPERM=2
gtp/gtp (ID 15): member
NET_DM/events (ID 1): member
After:
joins: ok=19 ENOENT=43 EPERM=2
gtp/gtp (ID 15): not member
NET_DM/events (ID 1): not member
bind(), an owned group and free IDs: ok, member of the owned group only
genl_bind() was added, with its first capability check, in the commit
in the Fixes tag.
Link: https://lore.kernel.org/netdev/179324692107.3134.14443689892607921337@kernel.org/
Fixes: 4d54cc32112d ("mptcp: avoid lock_fast usage in accept path")
Signed-off-by: Anil Kaushik <anilkaushikwireless@gmail.com>
---
include/linux/netlink.h | 3 +++
include/uapi/linux/net_dropmon.h | 2 ++
net/netlink/af_netlink.c | 6 ++++++
net/netlink/genetlink.c | 5 ++++-
4 files changed, 15 insertions(+), 1 deletion(-)
diff --git a/include/linux/netlink.h b/include/linux/netlink.h
index 882e9c1b6c1d..b4eb873850e7 100644
--- a/include/linux/netlink.h
+++ b/include/linux/netlink.h
@@ -48,6 +48,9 @@ struct netlink_kernel_cfg {
unsigned int groups;
unsigned int flags;
void (*input)(struct sk_buff *skb);
+ /* -ENOENT means no one owns the group: bind() skips it and joins the
+ * others, setsockopt() returns the error.
+ */
int (*bind)(struct net *net, int group);
void (*unbind)(struct net *net, int group);
void (*release) (struct sock *sk, unsigned long *groups);
diff --git a/include/uapi/linux/net_dropmon.h b/include/uapi/linux/net_dropmon.h
index 87cbef48d4c7..4f2fee982c8a 100644
--- a/include/uapi/linux/net_dropmon.h
+++ b/include/uapi/linux/net_dropmon.h
@@ -58,6 +58,8 @@ enum {
/*
* Our group identifiers
+ *
+ * The group can be joined only after the NET_DM family is registered.
*/
#define NET_DM_GRP_ALERT 1
diff --git a/net/netlink/af_netlink.c b/net/netlink/af_netlink.c
index 69bb951b5fb8..ee573ba6396d 100644
--- a/net/netlink/af_netlink.c
+++ b/net/netlink/af_netlink.c
@@ -1033,6 +1033,12 @@ static int netlink_bind(struct socket *sock, struct sockaddr_unsized *addr,
err = nlk->netlink_bind(net, group + 1);
if (!err)
continue;
+ /* no one owns this group, still join the others */
+ if (err == -ENOENT) {
+ __clear_bit(group, &groups);
+ err = 0;
+ continue;
+ }
netlink_undo_bind(group, groups, sk);
return err;
}
diff --git a/net/netlink/genetlink.c b/net/netlink/genetlink.c
index 5cc1037d4917..e5d4f3c4e22a 100644
--- a/net/netlink/genetlink.c
+++ b/net/netlink/genetlink.c
@@ -85,6 +85,8 @@ static DEFINE_IDR(genl_fam_idr);
* cater to that by giving it a static family and group ID.
* Bit 18 is marked as already used since the PMCRAID driver
* did the same thing as the VFS quota code (maybe copied?)
+ * These IDs can be joined only after the family that owns them
+ * is registered.
*/
static unsigned long mc_group_start = 0x3 | BIT(GENL_ID_CTRL) |
BIT(GENL_ID_VFS_DQUOT) |
@@ -1825,7 +1827,7 @@ static int genl_bind(struct net *net, int group)
{
const struct genl_family *family;
unsigned int id;
- int ret = 0;
+ int ret = -ENOENT;
down_read(&cb_lock);
@@ -1841,6 +1843,7 @@ static int genl_bind(struct net *net, int group)
continue;
grp = &family->mcgrps[i];
+ ret = 0;
if ((grp->flags & GENL_MCAST_CAP_NET_ADMIN) &&
!ns_capable(net->user_ns, CAP_NET_ADMIN))
ret = -EPERM;
--
2.25.1
^ permalink raw reply [flat|nested] 4+ messages in thread
* [PATCH net v9 2/2] selftests: net: test joining genetlink groups no family owns
2026-11-25 14:45 [PATCH net v9 0/2] genetlink: Reject joining multicast groups no family owns Anil Kaushik
2026-11-25 14:45 ` [PATCH net v9 1/2] " Anil Kaushik
@ 2026-11-25 14:45 ` Anil Kaushik
2026-11-26 14:47 ` netdev-bot+sashiko
1 sibling, 1 reply; 4+ messages in thread
From: Anil Kaushik @ 2026-11-25 14:45 UTC (permalink / raw)
To: netdev
Cc: davem, edumazet, kuba, pabeni, horms, idosch, nicolas.dichtel,
jacob.e.keller, jiri, fw, martineau, v3rdant.xiang, aliceryhl,
linux-kernel, nhorman, shuah, linux-kselftest,
anilkaushikwireless
Check that a Generic Netlink group ID no family owns cannot be joined:
- setsockopt(NETLINK_ADD_MEMBERSHIP) on a free ID fails with ENOENT,
and still works on an owned group.
- bind() with a mask of free IDs succeeds and joins nothing. With an
owned group in the mask, it joins only that group.
- A socket bound to the free IDs is not a member of the NET_DM groups
after drop_monitor is loaded. drop_monitor is unloaded again at the
end. Skipped when NET_DM is already registered or drop_monitor is not
available.
The free IDs are found with a family dump, which only lists the families
of the current network namespace, so these checks are skipped outside
the initial one. It is found with its fixed nsfs inode number, which
also works in a container with its own PID namespace.
Suggested-by: Nicolas Dichtel <nicolas.dichtel@6wind.com>
Signed-off-by: Anil Kaushik <anilkaushikwireless@gmail.com>
---
tools/testing/selftests/net/Makefile | 1 +
tools/testing/selftests/net/nl_genl_mcast.py | 128 +++++++++++++++++++
2 files changed, 129 insertions(+)
create mode 100755 tools/testing/selftests/net/nl_genl_mcast.py
diff --git a/tools/testing/selftests/net/Makefile b/tools/testing/selftests/net/Makefile
index baea3e7f0f8f..875ce0443814 100644
--- a/tools/testing/selftests/net/Makefile
+++ b/tools/testing/selftests/net/Makefile
@@ -74,6 +74,7 @@ TEST_PROGS := \
netns-name.sh \
netns-sysctl.sh \
nk_qlease.py \
+ nl_genl_mcast.py \
nl_netdev.py \
nl_nlctrl.py \
nsh_gso.sh \
diff --git a/tools/testing/selftests/net/nl_genl_mcast.py b/tools/testing/selftests/net/nl_genl_mcast.py
new file mode 100755
index 000000000000..8bbe3d22225c
--- /dev/null
+++ b/tools/testing/selftests/net/nl_genl_mcast.py
@@ -0,0 +1,128 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+"""
+Tests for joining Generic Netlink multicast groups that no family owns.
+"""
+
+import os
+import socket
+import struct
+
+from lib.py import ksft_run, ksft_exit, ksft_eq, ksft_raises
+from lib.py import KsftSkipEx, NlctrlFamily, NlError, cmd
+
+NETLINK_GENERIC = 16
+SOL_NETLINK = 270
+NETLINK_ADD_MEMBERSHIP = 1
+NETLINK_LIST_MEMBERSHIPS = 9
+# include/uapi/linux/nsfs.h
+NET_NS_INIT_INO = 0xEFFFFFF9
+
+
+def _groups(fam):
+ """Return the multicast groups of a family as {name: id}."""
+ return {g['name']: g['id']
+ for grp in fam.get('mcast-groups', []) for g in grp.values()}
+
+
+def _free_ids(ctrl):
+ """Return the IDs in 1..32 that no family owns."""
+ # Outside init_net, the dump skips the families that are not netnsok,
+ # but their groups are still owned.
+ if os.stat('/proc/self/ns/net').st_ino != NET_NS_INIT_INO:
+ raise KsftSkipEx("not in the initial network namespace")
+
+ owned = set()
+ for fam in ctrl.getfamily({}, dump=True):
+ owned.update(_groups(fam).values())
+ free = [gid for gid in range(1, 33) if gid not in owned]
+ if not free:
+ raise KsftSkipEx("no free group ID in 1..32")
+ return free
+
+
+def _sock():
+ return socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, NETLINK_GENERIC)
+
+
+def _members(sk):
+ buf = sk.getsockopt(SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, 64)
+ # An array of u32 in host byte order
+ words = struct.unpack(f'={len(buf) // 4}I', buf)
+ return sum(w << (32 * i) for i, w in enumerate(words))
+
+
+def _bit(gid):
+ return 1 << (gid - 1)
+
+
+def _notify_id(ctrl):
+ return _groups(ctrl.getfamily({'family-name': 'nlctrl'}))['notify']
+
+
+def join_free(ctrl) -> None:
+ """setsockopt() on an ID no family owns fails with ENOENT."""
+ with _sock() as sk:
+ sk.bind((0, 0))
+ for gid in _free_ids(ctrl):
+ # ENOENT
+ with ksft_raises(FileNotFoundError):
+ sk.setsockopt(SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, gid)
+
+ notify = _notify_id(ctrl)
+ sk.setsockopt(SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, notify)
+ ksft_eq(_members(sk), _bit(notify))
+
+
+def bind_mask(ctrl) -> None:
+ """bind() skips the IDs no family owns and joins the others."""
+ free = sum(_bit(gid) for gid in _free_ids(ctrl))
+ notify = _notify_id(ctrl)
+
+ with _sock() as sk:
+ sk.bind((0, free))
+ ksft_eq(_members(sk), 0)
+
+ with _sock() as sk:
+ sk.bind((0, free | _bit(notify)))
+ ksft_eq(_members(sk), _bit(notify))
+
+
+def bind_before_family(ctrl) -> None:
+ """A free ID joined with bind() stays unjoined when a family takes it."""
+ names = [fam['family-name'] for fam in ctrl.getfamily({}, dump=True)]
+ if 'NET_DM' in names:
+ raise KsftSkipEx("NET_DM is already registered")
+
+ free = _free_ids(ctrl)
+ try:
+ with _sock() as sk:
+ sk.bind((0, sum(_bit(gid) for gid in free)))
+
+ # Looking up the family loads drop_monitor.
+ try:
+ ids = _groups(ctrl.getfamily({'family-name': 'NET_DM'}))
+ except NlError as e:
+ raise KsftSkipEx("drop_monitor is not available") from e
+
+ if not any(gid in free for gid in ids.values()):
+ raise KsftSkipEx("NET_DM got no group ID that was free")
+
+ for name, gid in ids.items():
+ ksft_eq(_members(sk) & _bit(gid), 0,
+ comment=f"member of NET_DM {name}")
+ finally:
+ # So that the next run can load it again
+ cmd("modprobe -q -r drop_monitor", fail=False)
+
+
+def main() -> None:
+ """ Ksft boiler plate main """
+ ctrl = NlctrlFamily()
+ ksft_run([join_free, bind_mask, bind_before_family], args=(ctrl, ))
+ ksft_exit()
+
+
+if __name__ == "__main__":
+ main()
--
2.25.1
^ permalink raw reply [flat|nested] 4+ messages in thread
* Re: [PATCH net v9 2/2] selftests: net: test joining genetlink groups no family owns
2026-11-25 14:45 ` [PATCH net v9 2/2] selftests: net: test joining genetlink " Anil Kaushik
@ 2026-11-26 14:47 ` netdev-bot+sashiko
0 siblings, 0 replies; 4+ messages in thread
From: netdev-bot+sashiko @ 2026-11-26 14:47 UTC (permalink / raw)
To: anilkaushikwireless
Cc: netdev, davem, edumazet, kuba, pabeni, horms, idosch,
nicolas.dichtel, jacob.e.keller, jiri, fw, martineau,
v3rdant.xiang, aliceryhl, linux-kernel, nhorman, shuah,
linux-kselftest
Thank you for your contribution! Sashiko AI review found 3 potential
issue(s) to consider.
Critical: 0 · High: 0 · Medium: 1 · Low: 2
If you believe none of the issues are legitimate, please reply to each
issue of Medium severity or higher and explain why the AI is wrong.
If any of them are legitimate and you plan to respin, please let patchwork
know by including "pw-bot: cr" as a separate line at the end of your reply
(one such reply per series is enough).
- [Medium] In bind_before_family()
(tools/testing/selftests/net/nl_genl_mcast.py), the `finally:` block…
- [Low] _free_ids() in tools/testing/selftests/net/nl_genl_mcast.py
decides it is in init_net by comparing…
- [Low] _members() in tools/testing/selftests/net/nl_genl_mcast.py calls
sk.getsockopt(SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, 64) and decodes…
--
selftests: net: test joining genetlink groups no family owns
This adds a Python selftest. It checks that Generic Netlink multicast
group IDs no family owns cannot be joined with setsockopt() or bind(). It
also checks that a socket bound to free IDs does not become a member of
the NET_DM groups once drop_monitor is loaded.
> diff --git a/tools/testing/selftests/net/nl_genl_mcast.py b/tools/testing/selftests/net/nl_genl_mcast.py
> new file mode 100755
> index 0000000000000..8bbe3d22225cf
> --- /dev/null
> +++ b/tools/testing/selftests/net/nl_genl_mcast.py
[ ... ]
> +# include/uapi/linux/nsfs.h
> +NET_NS_INIT_INO = 0xEFFFFFF9
[ ... ]
> +def _free_ids(ctrl):
> + """Return the IDs in 1..32 that no family owns."""
> + # Outside init_net, the dump skips the families that are not netnsok,
> + # but their groups are still owned.
> + if os.stat('/proc/self/ns/net').st_ino != NET_NS_INIT_INO:
> + raise KsftSkipEx("not in the initial network namespace")
[Severity: Low]
Can this check ever match on kernels older than commit 9b0240b3ccc325
("netns: use stable inode number for initial mount ns")?
That commit added NET_NS_INIT_INO to include/uapi/linux/nsfs.h. Before
it, the ns.inum of init_net was a dynamically allocated proc inode number
(PROC_DYNAMIC_FIRST and up), so this comparison never matches.
join_free(), bind_mask() and bind_before_family() all call _free_ids()
first. On those kernels all three subtests would skip, even when run in
the initial network namespace. The printed reason, "not in the initial
network namespace", would also be wrong.
The companion fix "genetlink: Reject joining multicast groups no family
owns" has a Fixes: tag, so it is a likely backport candidate for stable
trees such as 6.12, 6.6, 6.1 and 5.15. If this test is backported with
it, the fix would never be exercised there.
The commit message explains why the fixed inode number is used, but it
does not mention this limitation. Would a fallback help here? For
example, the test could compare against the inode of /proc/1/ns/net when
the fixed value is not in use. Another option is a skip message that
states the actual condition.
[ ... ]
> +def _members(sk):
> + buf = sk.getsockopt(SOL_NETLINK, NETLINK_LIST_MEMBERSHIPS, 64)
> + # An array of u32 in host byte order
> + words = struct.unpack(f'={len(buf) // 4}I', buf)
> + return sum(w << (32 * i) for i, w in enumerate(words))
[Severity: Low]
Could _members() decode uninitialised bytes when the socket has more
than 512 groups?
In netlink_getsockopt(), the NETLINK_LIST_MEMBERSHIPS case stops copying
once the user buffer is full. It then reports the full required size
anyway:
net/netlink/af_netlink.c:netlink_getsockopt() {
...
opt->optlen = ALIGN(BITS_TO_BYTES(nlk->ngroups), sizeof(u32));
...
}
do_sock_getsockopt() in net/socket.c writes this value back to user
space without clamping it. CPython's socket.getsockopt() then resizes
the returned bytes object to that length. Everything past the 64 bytes
the kernel actually wrote is left uninitialised.
For a genetlink socket, nlk->ngroups follows mc_groups_longs *
BITS_PER_LONG, and that grows on demand in genl_allocate_reserve_groups()
and genl_validate_assign_mc_groups(). If it goes above 512, the
full-value ksft_eq() checks in join_free() and bind_mask() could fail
because of garbage high bits.
Would it be safer to decode only the first min(len(buf), 64) bytes, or
to size the buffer from the returned optlen?
[ ... ]
> +def bind_before_family(ctrl) -> None:
> + """A free ID joined with bind() stays unjoined when a family takes it."""
> + names = [fam['family-name'] for fam in ctrl.getfamily({}, dump=True)]
> + if 'NET_DM' in names:
> + raise KsftSkipEx("NET_DM is already registered")
> +
> + free = _free_ids(ctrl)
> + try:
> + with _sock() as sk:
> + sk.bind((0, sum(_bit(gid) for gid in free)))
> +
> + # Looking up the family loads drop_monitor.
> + try:
> + ids = _groups(ctrl.getfamily({'family-name': 'NET_DM'}))
> + except NlError as e:
> + raise KsftSkipEx("drop_monitor is not available") from e
[ ... ]
> + finally:
> + # So that the next run can load it again
> + cmd("modprobe -q -r drop_monitor", fail=False)
[Severity: Medium]
Can this finally block turn the "drop_monitor is not available" skip into
a failure?
With shell=None, cmd() in lib/py/utils.py splits the string into a list
and runs it through subprocess.Popen() without a shell. If modprobe is
not on PATH, Popen() raises FileNotFoundError. fail=False only ignores a
non-zero exit code, not a failure to start the command.
An exception raised in a finally block replaces the pending one. The
KsftSkipEx raised when getfamily() fails with NlError is then lost.
ksft_run() catches the FileNotFoundError under except BaseException and
counts the test as a failure, with a traceback.
Without modprobe, request_module() in the kernel would also fail. That
makes the NlError path the one taken in exactly this environment. The
cleanup also runs when the test never loaded drop_monitor.
modprobe may only be in /sbin or /usr/sbin, and the test may run with a
PATH that excludes them. In that case even the success path would end in
FileNotFoundError and be reported as a failure.
Would it help to run modprobe -r only after getfamily() succeeds, or to
catch OSError around the cleanup?
--
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261125144514.2717012-1-anilkaushikwireless%40gmail.com
^ permalink raw reply [flat|nested] 4+ messages in thread
end of thread, other threads:[~2026-11-26 14:47 UTC | newest]
Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-25 14:45 [PATCH net v9 0/2] genetlink: Reject joining multicast groups no family owns Anil Kaushik
2026-11-25 14:45 ` [PATCH net v9 1/2] " Anil Kaushik
2026-11-25 14:45 ` [PATCH net v9 2/2] selftests: net: test joining genetlink " Anil Kaushik
2026-11-26 14:47 ` netdev-bot+sashiko
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®