On Thu, Oct 29, 2026 at 12:41 PM Christian Brauner <brauner at kernel.org> wrote:
>
> Currently the namespace id is allocated only after __ns_common_init()
> has called the namespace_init LSM hook. Most namespace types allocate it
> in ns_tree_add() right before the namespace is added to the namespace
> trees. So the namespace_init hook always sees an id of zero.
>
> The namespace id is the only identifier of a namespace that is never
> recycled. A bpf LSM wants to use it to track a namespace from
> namespace_init until namespace_free, e.g., by using it as the key into a
> map that associates data with the namespace. The inode number doesn't
> work for that as it is quickly recycled.
>
> So allocate the id in __ns_common_init() before calling the
> namespace_init hook. Every namespace then has its id by the time it is
> added to the namespace trees. The initial namespaces still get their
> fixed ids, either statically from NS_COMMON_INIT() or for init_net from
> ns_common_init(). So ns_tree_add() doesn't need to allocate an id
> anymore. Ids are still handed out in creation order so mnt_ns_loop()
> keeps working. Mount and ipc namespaces already allocated their id right
> after ns_common_init() anyway.
>
> If creating the namespace fails after the id has been allocated the id
> is simply never used.
>
> Landlock logs the namespace id when it denies the use of a namespace.
> For a denied namespace creation that used to be zero. Now it's the id
> that was allocated for the new namespace. That namespace never becomes
> visible to userspace but it's the same id that other LSMs see in
> namespace_init. Update the Landlock documentation and selftests
> accordingly. The selftests can't know the id of a namespace whose
> creation was denied so they only check that it isn't zero.
>
> While at it, drop ns_tree_gen_id() as it has no users left.
>
> Reproducer, 100 user and uts namespaces:
>
> bpftrace -e 'fentry:bpf_lsm_namespace_init {
> @[args.ns->ns_id ? "set" : "zero"] = count(); }' &
> for i in $(seq 100); do unshare -Uu true; done
>
> before: @[zero]: 200
> after: @[set]: 200
>
> Fixes: f675d2e95569 ("lsm: add LSM blob and hooks for namespaces")
> Cc: <stable at kernel.org> # mainline only
> Signed-off-by: Christian Brauner (Amutable) <brauner at kernel.org>
> ---
> Documentation/admin-guide/LSM/landlock.rst | 5 +++--
> Documentation/trace/events-landlock.rst | 5 +++--
> fs/namespace.c | 2 --
> include/linux/ns_common.h | 16 +++++++++-------
> include/linux/nstree.h | 18 +++---------------
> include/trace/events/landlock.h | 3 ++-
> ipc/namespace.c | 1 -
> kernel/nscommon.c | 7 +++++--
> net/core/net_namespace.c | 2 +-
> security/landlock/ns.c | 3 ++-
> tools/testing/selftests/landlock/ns_test.c | 7 +++++--
> 11 files changed, 33 insertions(+), 36 deletions(-)
See my comment in patch 6/7 as it impacts this patch.
Reviewed-by: Paul Moore <paul at paul-moore.com>
--
paul-moore.com