summaryrefslogtreecommitdiff
path: root/security
AgeCommit message (Collapse)Author
24 hoursMerge branch 'headers' of git://git.infradead.org/users/willy/pagecache.gitMark Brown
# Conflicts: # net/ceph/osd_client.c
24 hoursMerge branch 'for-next-tpm' of ↵Mark Brown
https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git
3 daysMerge tag 'apparmor-pr-2026-08-26' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/jj/linux-apparmor Pull AppArmor updates from John Johansen: "The biggest functional change is Jann Horn's fix for how aparmor is doing stale cred updates after a policy replacement. apparmor: fix cred UAF caused by begin_current_label_crit_section() It moves the update to be done during task_work at the end of the syscall. One major feature is allowing policy to be compressed in userspace instead of after the fact (in kernel) if we need to hold onto it for CRIU/introspection. The other major change is to do with network mediation. It is a lot of code churn but does not do any functional changes to mediation. It moves the code around, and refactors it to use newer patterns for consistency, and in preparation for some improvements in mediation in a future patchset. Features: - support loading compressed policies - add audit mode to provide a mechanism to silence complain messages - refactor network mediation to use new patterns, and prepare to for extended inet mediation (no functional change) Cleanups: - switch website link to https - make include headers self-contained, and fix circular include - constify aa_label, aa_dfa, aa_profile, and aa_perms paraneters - mark static tables and structs as read only - drop use of _confined variant for iteration - refactory mount to use check_perms - refactor network mediation code to be together - refactor xattr attachment, to take the file path - optimize current_label_crit_section() - leverage audit_log_n_untrustedstring() when possible Bug Fixes: - initialized policy lists heads before fail path - fix deadlock in complain-mode change_hat - auditing of mount binary data - fix error debug output in fn_label_build - fix race condition in label replacement - fix unconfined user namespace restriction forced stack - fix error handling for copy_from_user in policy_update - fix out-of-bounds write when null terminating a label vec - fix integer overflow in verify_tags() bounds check - fix cred UAF caused by begin_current_label_crit_section() - use SEND_SIG_NOINFO instead of NULL in aa_audit()" * tag 'apparmor-pr-2026-08-26' of git://git.kernel.org/pub/scm/linux/kernel/git/jj/linux-apparmor: (40 commits) apparmor: policy_int make sure list heads are initialized before fail path apparmor: fix deadlock in complain-mode change_hat apparmor: constify aa_label parameters on read-only query helpers apparmor: constify aa_dfa parameters on read-only compute paths apparmor: constify aa_profile parameters on read-only compute paths apparmor: constify aa_perms parameters that are read-only apparmor: drop use of _confined variant for iteration apparmor: refactory mount to use check_perms apparmor: fix auditing of mount binary data apparmor: add audit mode to provide a mechanism to silence complain messages apparmor: mark static tables and structs as read only apparmor: fix error debug output in fn_label_build apparmor: make table entry count last enum for static tables apparmor: fix race condition in label replacement apparmor: refactor xattr attachment, to take the file path apparmor: fix unconfined user namespace restriction forced stack apparmor: reserve mediation class for packet mediation apparmor: move sock_rcv_skb() next to inet_conn_request apparmor: move netfilter functions next to the LSM network operations apparmor: refactor network socket mediation to support compatibility ...
3 daysapparmor: policy_int make sure list heads are initialized before fail pathJohn Johansen
If profile create fails before policy_init is complete the list heads are not properly initialized causing profile_free() sanity checks to trigger the following splat. AppArmor WARN aa_policy_destroy: (((!list_empty(&policy->profiles) && (&policy->profiles)->prev != ((void *) 0x122 + (0xdead000000000000UL))))): WARNING: security/apparmor/lib.c:509 at aa_policy_destroy+0x164/0x1b0 security/apparmor/lib.c:509, CPU#0: syz.0.17/5541 Modules linked in: CPU: 0 UID: 0 PID: 5541 Comm: syz.0.17 Not tainted syzkaller #0 PREEMPT(full) Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 RIP: 0010:aa_policy_destroy+0x16b/0x1b0 security/apparmor/lib.c:509 Code: 85 ed 7e 4d e8 96 bc 37 fd 5b 41 5c 41 5e 41 5f 5d e9 19 27 4e 07 cc e8 83 bc 37 fd 48 8d 3d 0c f0 d3 0b 48 c7 c6 a4 eb 38 8e <67> 48 0f b9 3a e9 04 ff ff ff e8 66 bc 37 fd 48 8d 3d ff ef d3 0b RSP: 0018:ffffc9000345eaa0 EFLAGS: 00010293 RAX: ffffffff848f530d RBX: ffff88803f734800 RCX: ffff88801af2a580 RDX: 0000000000000000 RSI: ffffffff8e38eba4 RDI: ffffffff90634320 RBP: 0000000000000000 R08: 0000000000000cc0 R09: 00000000ffffffff R10: dffffc0000000000 R11: fffffbfff1d95913 R12: dead000000000122 R13: ffff88803f734800 R14: ffff88803f734828 R15: dffffc0000000000 FS: 00007f5f6a1836c0(0000) GS:ffff88808c519000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 000055d02407b048 CR3: 0000000012aa9000 CR4: 0000000000352ef0 Call Trace: <TASK> aa_free_profile+0x9d/0x9f0 security/apparmor/policy.c:334 aa_alloc_profile+0x1e4/0x3e0 security/apparmor/policy.c:416 unpack_profile security/apparmor/policy_unpack.c:1153 [inline] aa_unpack+0x17db/0x7430 security/apparmor/policy_unpack.c:1748 aa_replace_profiles+0x226/0x2a20 security/apparmor/policy.c:1183 policy_update+0x234/0x4a0 security/apparmor/apparmorfs.c:505 profile_load+0x1cb/0x320 security/apparmor/apparmorfs.c:522 vfs_write+0x296/0xba0 fs/read_write.c:685 ksys_write+0x150/0x270 fs/read_write.c:739 do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline] do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84 entry_SYSCALL_64_after_hwframe+0x77/0x7f RIP: 0033:0x7f5f6939e0d9 Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f5f6a183028 EFLAGS: 00000246 ORIG_RAX: 0000000000000001 RAX: ffffffffffffffda RBX: 00007f5f69625fa0 RCX: 00007f5f6939e0d9 RDX: 0000000000000041 RSI: 0000200000000400 RDI: 0000000000000003 RBP: 00007f5f6a183090 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000001 R13: 00007f5f69626038 R14: 00007f5f69625fa0 R15: 00007ffe23725c18 Reported-by: syzbot+faed97c4ed43bfe7fee5@syzkaller.appspotmail.com Link: https://syzkaller.appspot.com/bug?extid=faed97c4ed43bfe7fee5 Fixes: fe6bb31f590c9 ("apparmor: split out shared policy_XXX fns to lib") Signed-off-by: John Johansen <john.johansen@canonical.com>
4 dayssecurity: Remove pagemap.h includesMatthew Wilcox (Oracle)
The security subsystem does not use the page cache. Removing just the pagemap.h includes isn't quite enough to insulate it from changes to pagemap as it's also pulled in by swap.h and hugetlb.h. Fortunately, security doesn't need either of those so we can lose all three. Now touching pagemap.h causes no rebuilds in the security subsystem. Signed-off-by: Matthew Wilcox (Oracle) <willy@infradead.org>
4 daystpm-buf: Memory-safe allocationsJarkko Sakkinen
Decouple kzalloc from buffer creation, so that a managed allocation can be used: struct tpm_buf *buf __free(kfree) buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL); if (!buf) return -ENOMEM; tpm_buf_init(buf, TPM_BUFSIZE); Alternatively, other allocations are also possible (static data, stack, etc) for example: u8 buf_data[512]; struct tpm_buf *buf = (struct tpm_buf *)buf_data; tpm_buf_init(buf, sizeof(buf_data)); This is achieved by embedding buffer's header inside the allocated blob, instead of having an outer wrapper. Reviewed-by: Stefan Berger <stefanb@linux.ibm.com> Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com> Tested-by: Srish Srinivasan <ssrish@linux.ibm.com> Message-ID: <20260522013555.1063716-1-jarkko@kernel.org> Signed-off-by: Ross Philipson <ross.philipson@oracle.com>
4 daystpm-buf: Merge TPM_BUF_BOUNDARY_ERROR and TPM_BUF_OVERFLOWJarkko Sakkinen
Merge TPM_BUF_BOUNDARY_ERROR and TPM_BUF_OVERFLOW flags into the TPM_BUF_INVALID flag, as their behavior is identical (the only difference being the associated log messages). Message-ID: <20260125192526.782202-11-jarkko@kernel.org> Signed-off-by: Jarkko Sakkinen <jarkko.sakkinen@opinsys.com> Reviewed-by: Jonathan McDowell <noodles@meta.com> Signed-off-by: Ross Philipson <ross.philipson@gmail.com>
4 daystpm: Initial step to reorganize TPM public headersRoss Philipson
Consolidate TPM1 constants in tpm_command.h and remove duplicate constants from tpm1-cmd.c. Co-developed-by: Daniel P. Smith <dpsmith@apertussolutions.com> Signed-off-by: Daniel P. Smith <dpsmith@apertussolutions.com> Co-developed-by: Alec Brown <alec.r.brown@oracle.com> Signed-off-by: Alec Brown <alec.r.brown@oracle.com> Signed-off-by: Ross Philipson <ross.philipson@gmail.com> Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org> Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
6 daysMerge tag 'for-next-keys-v7.3' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd Pull TPM update from Jarkko Sakkinen: "Just a single bug fix" * tag 'for-next-keys-v7.3' of git://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd: KEYS: trusted: Fix TPM teardown ordering
8 daysMerge tag 'landlock-7.3-rc1' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/mic/linux Pull Landlock update from Mickaël Salaün: "This improves observability with Landlock tracepoints support, which required some refactoring for dedicated domain types and common helpers shared with audit code. A LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS flag is also added to improve process-wide domain enforcement consistency. Whiteout files are now correctly handled and tested, and a few other fixes" * tag 'landlock-7.3-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/mic/linux: (34 commits) landlock: Document tracepoints selftests/landlock: Add landlock_enforce_domain trace tests selftests/landlock: Add scope and ptrace tracepoint tests selftests/landlock: Add network tracepoint tests selftests/landlock: Add filesystem tracepoint tests selftests/landlock: Add trace event test infrastructure and tests landlock: Add tracepoints for ptrace and scope denials landlock: Add landlock_deny_access_fs and landlock_deny_access_net landlock: Add tracepoints for rule checking landlock: Add landlock_enforce_domain tracepoint landlock: Add create_domain and free_domain tracepoints landlock: Add landlock_add_rule_fs and landlock_add_rule_net tracepoints landlock: Add create_ruleset and free_ruleset tracepoints landlock: Consolidate access-right and scope names in a shared header landlock: Decouple the per-denial logging decision from CONFIG_AUDIT landlock: Split denial logging from audit into common framework landlock: Split struct landlock_domain from struct landlock_ruleset landlock: Move domain query functions to domain.c landlock: Prepare ruleset and domain type split samples/landlock: Add LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS to sampler ...
8 daysKEYS: trusted: Fix TPM teardown orderingChengfeng Ye
trusted_tpm_exit() drops the TPM chip reference and frees the digest array before unregistering the trusted key type. key_type_lookup() holds key_types_sem for reading until the key operation finishes, while unregister_key_type() takes it for writing. It therefore provides the synchronization point that must precede backend teardown. The current order permits this interleaving: CPU 0 CPU 1 trusted_tpm_exit() key_type_lookup("trusted") put_device(&chip->dev) trusted_tpm_seal() kfree(digests) pcrlock() unregister_key_type() tpm_pcr_extend(..., digests) CPU 1 can consequently dereference the freed digest array. The chip can also be released before callbacks stop using it. KASAN reported: BUG: KASAN: slab-use-after-free in tpm_pcr_extend+0x1f0/0x200 Read of size 2 at addr ffff88810872d000 by task poc/89 Call Trace: tpm_pcr_extend+0x1f0/0x200 pcrlock+0x42/0x70 [trusted] trusted_tpm_seal+0x1b6/0x570 [trusted] trusted_instantiate+0x293/0x340 [trusted] __key_instantiate_and_link+0xb2/0x2b0 __key_create_or_update+0x61e/0xb50 __do_sys_add_key+0x1b8/0x310 Allocated by task 88: __kmalloc_noprof+0x1a7/0x490 do_one_initcall+0xa1/0x390 do_init_module+0x2df/0x840 Freed by task 90: kfree+0x131/0x3c0 trusted_tpm_exit+0x59/0xa0 [trusted] __do_sys_delete_module+0x346/0x510 Move unregister_key_type() before releasing either resource. This stops new lookups and waits for in-flight key operations to finish before the backend state is destroyed. Fixes: 0b6cf6b97b7e ("tpm: pass an array of tpm_extend_digest structures to tpm_pcr_extend()") Cc: stable@vger.kernel.org Signed-off-by: Chengfeng Ye <nicoyip.dev@gmail.com> Link: https://lore.kernel.org/r/20260731140925.2973492-1-nicoyip.dev@gmail.com Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org> Tested-by: Jarkko Sakkinen <jarkko@kernel.org> Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
10 daysMerge tag 'integrity-v7.3' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/zohar/linux-integrity Pull integrity updates from Mimi Zohar: - TPM initialization is sometimes delayed until deferred_probe_initcall Since ordering is not guaranteed within the same initcall level, IMA may initialize before the TPM and fall back to TPM-bypass mode. A new config option, CONFIG_IMA_INIT_LATE_SYNC, allows those building the kernel to defer IMA initialization to late_initcall_sync, accepting the integrity risk of missing early measurements in exchange for avoiding TPM-bypass mode. - The raw policy rules are now measured, as well as the complete policy, closing a gap in integrity measurement coverage * tag 'integrity-v7.3' of git://git.kernel.org/pub/scm/linux/kernel/git/zohar/linux-integrity: ima: measure userspace policy writes before parsing ima: add critical data measurement for loaded policy security: ima: rename boot_aggregate when ima is initialised at late_sync security: ima: introduce IMA_INIT_LATE_SYNC option security: lsm: allow LSMs to register for late_initcall_sync init
10 daysMerge tag 'Smack-for-7.3' of https://github.com/cschaufler/smack-nextLinus Torvalds
Pull smack updates from Casey Schaufler: - Spelling fix - Code optimization in smackfs - Fix credential mis-uses - Place limits on two of the smackfs interfaces * tag 'Smack-for-7.3' of https://github.com/cschaufler/smack-next: smack: fix cred UAF in smack_file_send_sigiotask() smack: restrict smackfs/{direct,mapped} values to 0-255 smack: deduplicate smackfs/{direct,mapped} file_operations smack: show msgrcv() subject task in audit smack: fix incorrect task context in smack_msg_queue_msgrcv security: smack: fix spelling mistake smack: simplify write handlers of sysfs entries Smack: Fix error in capability bypass
10 daysMerge tag 'lsm-pr-20260814' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/lsm Pull LSM updates from Paul Moore: - Remove task_euid() The task_euid(), and Rust counterpart, was never widely used, for good reason, and now that the only user is gone we're removing it to rid ourselves of both dead and funky code. - Documentation improvements Correct some of the kdoc comments for security_task_prctl() and clarify the rust comments on task UID accessors. - Fix a memory leak in the LSM syscall selftests * tag 'lsm-pr-20260814' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/lsm: selftests/lsm: Fix memory leak in attr_lsm_count cred: delete task_euid() rust: task: clarify comments on task UID accessors lsm: clarify security_task_prctl() hook documentation
10 daysMerge tag 'selinux-pr-20260814' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux Pull selinux updates from Paul Moore: - Convert a __get_free_page() call into a kmalloc() call We had some very old code that called out to __get_free_page() for allocating a pathname. There is no reason this couldn't be done with a call to kmalloc() so we've done the conversion and now there is one less __get_free_page() caller in the kernel. - Limit the number of retired/unknown DCCP netlink messages While DCCP is gone from the kernel, there are still userspace tools which try to talk to the kernel about DCCP sockets which were generating SELinux related log noise (unrecognized netlink message). This pull request both limits the log messages to just the first instance and also explains to the user that DCCP support has been removed. - Convert the SELinux strlcat() calls to seq_buf_XXX() calls As part of the effort to drop the strlcat() API from the kernel, the SELinux/IMA code was converted over to using seq_buf_XXX() calls. - Only calculate the SELinux IMA configuration string length once Previously each call to generate a SELinux configuration string for IMA would have to calculate the length of the string. While the contents of the string will likely change over the lifetime of the system, the length of the string will not. Calculate the string length once at boot and reuse the length value throughout the lifetime of the system. - Further validation of the SELinux policy at policy load time Perform additional sanity checks on the policy constraints and types. - Proper cleanup and error handling for selinuxfs init failures We were not properly cleaning up some state in the case where selinuxfs fails to initialize properly. It's somewhat of an academic exercise as a failure to initialize selinuxfs will cause the system to fail on boot, but it's arguably better to make sure we do things the proper way. - Various code cleanups Convert integer flags to boolean types and drop an uncessary goto from the SELinux code. * tag 'selinux-pr-20260814' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux: selinux: validate constraint expression attr and op at load time selinux: compute the IMA configuration settings string length once at boot selinux: replace strlcat() with seq_buf in selinux_ima_collect_state() selinux: suppress warning flood for retired DCCP netlink messages selinux: tighten type validation during policy load selinux: drop unnecessary goto and label from avc_alloc_node() selinux: convert int flags to bool flags in ss/services.c selinux: clean up selinuxfs resources on init failure selinux: hooks: use kmalloc() to allocate path buffer
12 dayslandlock: Add tracepoints for ptrace and scope denialsMickaël Salaün
Scope and ptrace denials follow a different code path (a domain hierarchy check) than access-right denials, so they need dedicated tracepoints with type-specific TP_PROTO arguments. Complete the denial coverage with: - landlock_deny_ptrace: ptrace access denied by a domain hierarchy mismatch. - landlock_deny_scope_signal: signal delivery denied by LANDLOCK_SCOPE_SIGNAL. - landlock_deny_scope_abstract_unix_socket: abstract unix socket access denied by LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET. TP_PROTO passes the raw kernel object (struct task_struct or struct sock) for eBPF BTF access; the comm and sun_path string fields use __print_untrusted_str() because they hold untrusted input. Unlike the deny_access events, these omit the blockers field: each maps to exactly one denial type named by the event, so the bitmask would always be zero. Like the deny_access events they carry same_exec and logged. Audit logs the task-targeted denials with generic field names (opid, ocomm), but a strongly typed trace event can use role-prefixed names (tracee_pid/tracee_comm, target_pid/target_comm) that match the mainline task-name convention (sched_process_fork's parent_comm/child_comm) and say whose name each field holds; a bare comm= would collide across events. The abstract-unix-socket event reports peer_pid instead, a tracepoint-only field with no audit counterpart. A scope or ptrace verdict compares the subject domain against the other party's domain, so each event also reports that other party's Landlock domain (tracee_domain=, target_domain=, or peer_domain=); the subject domain= alone does not let a consumer redo domain_is_scoped() or domain_ptrace(). It is reported as a scalar ID rather than a domain pointer: a domain object is immutable, but the other task can replace its credential and free the domain that credential referenced, so a stored foreign pointer could dangle before the event is consumed. The scalar ID also honors the tracepoint no-nullable-pointer rule, since the other party is frequently unsandboxed. Passing the foreign domain hierarchy object so an eBPF consumer could walk the other party's ancestry live would lengthen the RCU section on the shared denial path and needs a deferred refcount put, so it is left as a future enhancement. The relational domain-ID field (tracee_domain, target_domain, or peer_domain) is trace-only and is not added to audit records, so audit's denial format is unchanged by this series. Cc: Günther Noack <gnoack@google.com> Cc: Justin Suess <utilityemal77@gmail.com> Cc: Masami Hiramatsu <mhiramat@kernel.org> Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Cc: Steven Rostedt <rostedt@goodmis.org> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-14-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Add landlock_deny_access_fs and landlock_deny_access_netMickaël Salaün
Add per-type tracepoints emitted from landlock_log_denial() when an access is denied: landlock_deny_access_fs for filesystem denials and landlock_deny_access_net for network denials. They use the "deny_" prefix (rather than "check_") to mark that they fire only on a denial, and they complement the check_rule events by making the denial-by-absence case explicit (when no rule matches, no check_rule event fires). Unlike the audit records, these events fire regardless of the audit configuration and the domain's log flags: the user's "disable logging" intent applies to audit records, not to kernel tracing. The logged field records whether the domain's log policy would submit the denial to audit; it is the decision computed once by landlock_log_denial() and passed to both the audit and the tracing emitter, so a stateless ftrace filter can select the audit-visible denials with logged==1. TP_PROTO passes the denying hierarchy node, not the task's current domain, so domain_id reports the specific node that blocked the access, matching audit record semantics. (check_rule instead passes the current domain, which it needs to size its per-layer array.) same_exec is also passed explicitly because it is computed from the credential bitmask and is not derivable from the hierarchy pointer alone. The denial field is named blockers to match the audit record field. The filesystem path comes from the request's audit data. Its type selects which union member holds the object, exactly as dump_common_audit_data() selects it (a path, a file's path, an ioctl op's path, or a bare dentry); reading the wrong member would dereference garbage, so every reachable type has an explicit case and an unexpected one is flagged with WARN_ONCE() instead of misread. Path-backed types resolve via d_absolute_path() (as landlock_add_rule_fs does) and the bare-dentry case via dentry_path_raw(). The inode number is read defensively. A filesystem denial can carry a negative dentry (no backing inode), for example a denied creation, so the event mirrors the guard in dump_common_audit_data() and reports inode 0 rather than dereferencing a NULL inode. The sibling fs tracepoints do not need the guard: a dentry that matches a rule during an access check, or one opened to add a rule, always has a backing inode. Landlock tracepoints are reachable by unprivileged sandboxees, so a denial on a negative dentry with the event enabled must not fault the kernel. Cc: Günther Noack <gnoack@google.com> Cc: Justin Suess <utilityemal77@gmail.com> Cc: Masami Hiramatsu <mhiramat@kernel.org> Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Cc: Steven Rostedt <rostedt@goodmis.org> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-13-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Add tracepoints for rule checkingMickaël Salaün
Merge landlock_find_rule() into landlock_unmask_layers() so rule pointers stay inside the domain implementation while unmask checking gets the matched rule it needs for the check_rule tracepoint. landlock_unmask_layers() now takes a landlock_id and the domain instead of a rule pointer. A rename or link evaluates the same dentry against both renamed parents, so this path now looks the rule up once per parent; collapsing that back to a single lookup is left to a follow-up. Emit, via the per-type wrappers unmask_layers_fs() and unmask_layers_net(), the rights each matching rule grants at every domain layer. The events carry this as a dynamic per-layer array (up to LANDLOCK_MAX_NUM_LAYERS entries) reserved from the trace ring buffer, not the caller's stack, and rendered symbolically per layer. A WARN_ON_ONCE() in __trace_landlock_fill_layers() flags a rule whose layer levels fall outside the domain range or are unsorted, a cannot-happen case; the zero-filled slots keep the rendered output and the array bounds safe regardless. Setting allowed_parent2 to true for non-dom-check requests when get_inode_id() returns false preserves the pre-refactoring behavior: a negative dentry (no backing inode) has no matching rule, so the access is allowed at this path component. Before the refactoring, landlock_unmask_layers() with a NULL rule produced this result as a side effect; now the caller must set it explicitly. Name the trace-only check_rule fields so each printk label equals its ring-buffer field name and works directly as an ftrace filter: the request field is labelled access_request= and the per-layer array is named grants. Values audit also logs keep audit's label (domain=, ruleset=) so a single filter works across trace and audit. Cc: Günther Noack <gnoack@google.com> Cc: Justin Suess <utilityemal77@gmail.com> Cc: Masami Hiramatsu <mhiramat@kernel.org> Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Cc: Steven Rostedt <rostedt@goodmis.org> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-12-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Add landlock_enforce_domain tracepointMickaël Salaün
The landlock_create_domain event records that a domain was created, once, before thread-sync. It cannot tell which threads end up enforcing it: a successful landlock_restrict_self(2) with LANDLOCK_RESTRICT_SELF_TSYNC applies the domain to the caller and every eligible sibling. Creation (the operation) and enforcement (the per-thread outcome) are distinct. Add landlock_enforce_domain(domain, complete, process_wide), emitted once per thread the domain is applied to, strictly after that thread's commit_creds(), so it fires only for a thread that is enforcing the domain, never speculatively; an aborted operation emits none. The lifecycle now reads create -> enforce* -> free. The two booleans name properties, not the implementation: - complete: marks the single event that concludes the operation. It names the outcome, the set is now enforced, not which thread finishes, which the contract leaves unspecified. - process_wide: means every eligible thread of the process is covered. It is set race-free by either establishing path, thread-sync or a single-threaded process, so complete && process_wide is the whole-process-enforced guarantee. The requesting thread and source ruleset are not repeated here: they are on create_domain (joined via domain->hierarchy->id) and on the immutable domain->hierarchy->details. Source ruleset means the ruleset_id and ruleset_version recorded on create_domain, not the ruleset object, which the caller may close before enforcement. Cc: Günther Noack <gnoack@google.com> Cc: Masami Hiramatsu <mhiramat@kernel.org> Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Cc: Steven Rostedt <rostedt@goodmis.org> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-11-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Add create_domain and free_domain tracepointsMickaël Salaün
Add a landlock_create_domain tracepoint emitted from landlock_restrict_self() after the new domain is created, so a consumer can correlate the source ruleset with the resulting domain. The flags-only path (ruleset_fd == -1) creates no domain and emits no event. Move the ruleset lock acquisition from landlock_merge_ruleset() to the caller so the lock is held across both the merge and the tracepoint emission, giving an eBPF program a consistent ruleset snapshot. Release it before the thread-sync: holding ruleset->lock across landlock_restrict_sibling_threads() would deadlock a sibling blocked on the same lock. The event therefore fires before the (rare) thread-sync failure path; when that path aborts the just-created domain, the matching free_domain event fires so the create/free pair stays balanced. Add a landlock_free_domain tracepoint that fires when a domain's hierarchy node is freed. The hierarchy node is the lifecycle boundary because it represents the domain's identity and outlives the domain's access masks, which may still be active in descendant domains. A domain freed without ever being committed to a credential was never visible to user space, so free_domain is suppressed for it. This is tracked by a new landlock_log_status value, LANDLOCK_LOG_UNCOMMITTED, which is also the zero value so a hierarchy whose initialization failed defaults to not observable. A hierarchy is born UNCOMMITTED and is promoted to LANDLOCK_LOG_PENDING (or LANDLOCK_LOG_DISABLED when logging is off) right after its create_domain event fires; a thread-sync failure does not reset it, so an aborted domain that already emitted create_domain still emits the matching free_domain. Promoting right after the event, rather than at commit_creds() time, avoids a race: on a successful thread-sync the sibling threads commit the new domain in lockstep before landlock_restrict_self() returns, so the shared domain may already have moved to LANDLOCK_LOG_RECORDED through a plain store, and a late promotion would race that store and could unbalance the domain allocation and deallocation audit records. Cc: Günther Noack <gnoack@google.com> Cc: Justin Suess <utilityemal77@gmail.com> Cc: Masami Hiramatsu <mhiramat@kernel.org> Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Cc: Steven Rostedt <rostedt@goodmis.org> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-10-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Add landlock_add_rule_fs and landlock_add_rule_net tracepointsMickaël Salaün
Add tracepoints for Landlock rule addition, landlock_add_rule_fs for filesystem rules and landlock_add_rule_net for network rules, so trace consumers can correlate filesystem objects and network ports with their rulesets. Both are emitted under the ruleset lock (asserted in TP_fast_assign) so an eBPF program reads the ruleset, including the rule just inserted, in a consistent snapshot. Add a version field to struct landlock_ruleset, gated on CONFIG_TRACEPOINTS like the id field and incremented under the ruleset lock on each successful landlock_add_rule(2), including when it only extends an existing rule's access rights. It fills the existing 4-byte hole after usage, so the struct does not grow. Pairing the ruleset ID with the version lets a later restrict_self event record the exact ruleset revision merged into a domain. Resolve the filesystem rule's absolute path with d_absolute_path() rather than the d_path() audit uses: d_absolute_path() produces namespace-independent paths that do not depend on the tracer's chroot state, making trace output deterministic regardless of mount namespace configuration. Distinguish the error cases as "<too_long>" (-ENAMETOOLONG) and "<unreachable>" (anonymous files or detached mounts). Also add __trace_print_untrusted_str(), a static inline helper in the header guarded by CREATE_TRACE_POINTS: it escapes separators, quotes, backslashes, and non-printable bytes via string_escape_mem() so an untrusted string (the path here, process names in later denial events) cannot inject field separators or control characters into the ftrace text output. Cc: Christian Brauner <brauner@kernel.org> Cc: Günther Noack <gnoack@google.com> Cc: Justin Suess <utilityemal77@gmail.com> Cc: Masami Hiramatsu <mhiramat@kernel.org> Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Cc: Steven Rostedt <rostedt@goodmis.org> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-9-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Add create_ruleset and free_ruleset tracepointsMickaël Salaün
Add the first Landlock tracepoints, for ruleset lifecycle: landlock_create_ruleset fires from the landlock_create_ruleset() syscall handler, and landlock_free_ruleset fires in free_ruleset() before the ruleset is freed. These tracepoints, and the ones added by the following commits, share a common design. Rather than one polymorphic event distinguished by a status field (as audit uses a shared record type with a "status=" field), each lifecycle transition and denial type gets its own event with a type-safe TP_PROTO, giving precise ftrace filtering by event name and type-safe eBPF access. TP_PROTO passes the object pointer and the fields are read from it in TP_fast_assign, so an eBPF program reads the full object state (rules, access masks, hierarchy) via BTF from a single pointer rather than from the flattened TP_STRUCT__entry fields. The whole cost is paid only when a tracer is attached; the static branch is not taken otherwise. Trace fields carry the bare access-right and scope names (read_file), reusing the audit name tables; audit prepends the category (fs.read_file), which the trace event name already conveys. The trace header's DOC comment documents the consistency and locking guarantees these events share. create_ruleset needs no lock because the ruleset is not yet shared (its file descriptor is not yet installed). The deallocation events use the "free_" prefix, not "drop_", because they fire when the object is actually freed. Add trace.c, built for CONFIG_TRACEPOINTS, which defines CREATE_TRACE_POINTS, and extend CONFIG_SECURITY_LANDLOCK_LOG to also be selected by CONFIG_TRACEPOINTS so the common log framework is available to a tracepoints-only build. Add an id field to struct landlock_ruleset, gated on CONFIG_TRACEPOINTS and assigned from landlock_get_id_range() at creation. Only the tracepoints consume it (audit identifies domains, not rulesets), so it does not exist in an audit-only build. The Landlock ID is a stable u64 that names the ruleset across the trace stream and uses the same scheme as audit, so a ruleset can be correlated between trace and audit records. Cc: Günther Noack <gnoack@google.com> Cc: Justin Suess <utilityemal77@gmail.com> Cc: Masami Hiramatsu <mhiramat@kernel.org> Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Cc: Steven Rostedt <rostedt@goodmis.org> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-8-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Consolidate access-right and scope names in a shared headerMickaël Salaün
Audit formats denial records with per-right name strings. A following commit adds trace events that print the same access and scope masks with __print_flags() and need the same names, but a trace event header cannot include Landlock-internal headers, so the names cannot be shared from the logging unit. Define the filesystem, network, and scope names once, as the _LANDLOCK_ACCESS_FS_NAMES, _LANDLOCK_ACCESS_NET_NAMES, and _LANDLOCK_SCOPE_NAMES lists in the public Landlock header. Each entry is a _LANDLOCK_NAME_ENTRY() the consumer expands: audit maps it to a "[bit] = name" array slot for an O(1) lookup, the trace events map it to a __print_flags() { mask, name } pair. The bit value comes only from the LANDLOCK_* UAPI constant each entry references, so every bit-to-name mapping has a single source and does not depend on entry order. The shared names are unprefixed; blocker_prefix() prepends the fs./net./scope. category for audit records, so the scope names move from inline literals to the shared table too. Audit records are unchanged. No functional change. Cc: Günther Noack <gnoack@google.com> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-7-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Decouple the per-denial logging decision from CONFIG_AUDITMickaël Salaün
Until now, whether a denial is logged was decided inside landlock_audit_denial(): a per-execution flag check (log_same_exec or log_new_exec, selected by the credential's domain_exec bitmask), preceded by a LANDLOCK_LOG_DISABLED early return in landlock_log_denial() for domains an ancestor fully quieted. Factor that decision into a single is_denial_logged() helper called once by landlock_log_denial(), and pass its result to landlock_audit_denial() as a "logged" boolean. A following commit passes the same boolean to the deny tracepoints, so audit and tracing share one decision that stays correct as new log state is added, and a tracepoints-only build (CONFIG_AUDIT=n) computes it identically. Computing the logged verdict once in the shared helper makes audit and tracing apply identical filtering, so they cannot report different logged= values for the same denial as log controls grow. Move the LANDLOCK_LOG_DISABLED gate out of landlock_log_denial() into the decision so num_denials counts every denial, including those a domain quiets. This was previously masked: the only reader of num_denials is the audit "domain deallocated" record, emitted only for domains that reached LANDLOCK_LOG_RECORDED; a fully quieted domain never records, so its undercount was never observable. A following commit adds a free_domain tracepoint that reports num_denials, which needs the full count. This is not a functional change for audit: the logged decision and the audit_enabled gate are preserved, so the emitted records are identical. Cc: Günther Noack <gnoack@google.com> Link: https://patch.msgid.link/20260811094338.288094-6-mic@digikod.net Reviewed-by: Tingmao Wang <m@maowtm.org> [mic: Update copyright] Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Split denial logging from audit into common frameworkMickaël Salaün
Tracepoint emission requires the denial framework (layer identification, request validation) without depending on CONFIG_AUDIT. Separate the denial logging infrastructure from the audit-specific code by introducing a common log framework. Create CONFIG_SECURITY_LANDLOCK_LOG, enabled by default when CONFIG_AUDIT is set; a following commit extends it to CONFIG_TRACEPOINTS when the first tracepoint consumer is added. Move the common framework (the request types, the layer identification and request validation, and the landlock_log_denial() and landlock_log_free_domain() entry points) into log.c and log.h, and keep the audit-specific record formatting in audit.c. log.o is built for CONFIG_SECURITY_LANDLOCK_LOG and audit.o for CONFIG_AUDIT, so the common framework is available to a tracepoints-only build. The entry points dispatch to no-op static inline audit stubs without CONFIG_AUDIT, so the call sites stay unconditional. Rename the former landlock_log_drop_domain() to landlock_log_free_domain() to match the landlock_free_domain tracepoint added in a following commit. landlock_log_denial() counts denials even without audit, so its declaration and no-op stub are guarded by CONFIG_SECURITY_LANDLOCK_LOG, not CONFIG_AUDIT; a CONFIG_AUDIT guard would expose the stub and clash with log.c's definition in a tracepoints-only build. Widen the ID allocation (id.o and the landlock_init_id() / landlock_get_id_range() declarations) and the log-state representation (the domain_exec and log_subdomains_off credential fields, the landlock_hierarchy log fields, and the code that maintains them) from CONFIG_AUDIT to CONFIG_SECURITY_LANDLOCK_LOG, so each field and its writer share one guard and are available to tracing without audit support. Widen the denial-path state that feeds the per-denial logging decision the same way, so the "logged" verdict is computed identically whether or not CONFIG_AUDIT is set. Widening fown_layer is what keeps the file-owner-signal path valid without audit: otherwise hook_file_send_sigiotask() would leave layer_plus_one at zero, tripping the is_valid_request() canary and dropping the LANDLOCK_SCOPE_SIGNAL denial from tracing. The ruleset-level quiet_masks stays on no CONFIG guard: it is builder state validated and stored from user input, kept available so LANDLOCK_ADD_RULE_QUIET flags are accepted and ignored, not rejected, when CONFIG_SECURITY_LANDLOCK_LOG is disabled. Cc: Günther Noack <gnoack@google.com> Link: https://patch.msgid.link/20260811094338.288094-5-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Split struct landlock_domain from struct landlock_rulesetMickaël Salaün
Switch all domain users to the new struct landlock_domain type introduced by a previous commit, eliminating the conflation between mutable rulesets and immutable domains. landlock_merge_ruleset() now returns and allocates a struct landlock_domain, and the merge and inherit helpers move next to it; the former static insert_rule() is exported as landlock_store_rule() for its new caller across the translation-unit boundary. The merge destination is now a private struct landlock_domain still under construction (owned by the calling thread, not yet shared), so the merge and inherit helpers lock only the source ruleset: the previous lock of both destination and source collapses to a single mutex_lock(&src->lock). Rename the per-layer access-mask field from access_masks to handled_masks, naming it by the role it plays (the rights each layer handles) rather than by its type, paralleling the struct access_masks quiet_masks field. Drop the now domain-only fields (hierarchy, work_free, num_layers) from struct landlock_ruleset. The new struct landlock_domain field in cred.h pulls in domain.h, which includes audit.h, which previously included cred.h, forming an include cycle. Break it by having audit.h forward-declare the struct landlock_cred_security and struct landlock_hierarchy it uses instead of including cred.h. Cc: Günther Noack <gnoack@google.com> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-4-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Move domain query functions to domain.cMickaël Salaün
Grouping domain-specific code in one compilation unit reduces coupling between domain and ruleset implementations. Move the access-check functions that only operate on a domain (rule lookup, layer unmasking, layer-mask init, access-mask union) from ruleset.[ch] to domain.[ch]. They evaluate whether a domain grants a requested access during the pathwalk and network checks and do not modify the domain. The merge and inherit chain stays in ruleset.c for now because it calls the static create_ruleset() allocator; a following commit moves it once the domain type switch eliminates that dependency. No behavioral change. The functions move with unchanged signatures and bodies. Cc: Günther Noack <gnoack@google.com> Cc: Tingmao Wang <m@maowtm.org> Link: https://patch.msgid.link/20260811094338.288094-3-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
12 dayslandlock: Prepare ruleset and domain type splitMickaël Salaün
Rulesets and domains serve fundamentally different purposes: a ruleset is mutable and user-facing, created by landlock_create_ruleset(), while a domain is immutable after construction and enforced on tasks via landlock_restrict_self(). Today both are represented by struct landlock_ruleset, which conflates mutable and immutable state in a single type: the lock field is unused by domains, the hierarchy field is unused by rulesets, and lifecycle functions must handle both cases. Prepare for a clean type split by introducing two new structures: - struct landlock_rules: the red-black tree roots and rule count, shared by both rulesets and domains. Decoupling rule storage from the domain API lets the backing data structure change independently (e.g. to a hash table, cf. [1]). - struct landlock_domain: the immutable domain enforced on tasks, with no lock field because its rules and access masks are fixed once construction completes. The name reflects the role, not the internal data structure. Add the domain lifecycle helpers (landlock_get_domain(), landlock_put_domain(), landlock_put_domain_deferred()) and move domain.o from landlock-$(CONFIG_AUDIT) to landlock-y, because these are needed unconditionally, not just for audit logging. No behavioral change. The new types and lifecycle functions are not yet used by any caller. Cc: Günther Noack <gnoack@google.com> Link: https://patch.msgid.link/20250523165741.693976-1-mic@digikod.net [1] Link: https://patch.msgid.link/20260811094338.288094-2-mic@digikod.net Reviewed-by: Tingmao Wang <m@maowtm.org> [mic: Update copyright] Signed-off-by: Mickaël Salaün <mic@digikod.net>
13 daysapparmor: fix deadlock in complain-mode change_hatJohn Johansen
The use of change_hat when in complain mode can cause a deadlock when the hat doesn't exist and a new learning profile is created for the missing profile. This is because change_hat() has taken the lock to search the hat list and creating the new learning profile needs to take the lock to add it to the list. From the bug report: Originally found in 7.0.0 in LTS ubuntu 26.04 with pam_apparmor + su in complain mode set to change hats. Then verified in newest available vanilla kernel I've compiled to see if still present: 7.2-rc7 vanilla -> affected checked also some other kernels: 6.18.44 vanilla -> affected 6.12.95 with debian patches -> unaffected On systems without bug (for example 6.12.95 debian) it just prints: aa_change_hat rc=0 On systems with bug, the executable always hangs, prints nothing and becomes unkillable. (And once stuck this way, it will cause any further hat changes to also cause the changing process to get stuck) Then in syslog you can find hint about cause: kernel: INFO: task hat:3409 blocked for more than 483 seconds. kernel: Not tainted 7.2.0-rc7 #1 kernel: "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message. kernel: task:hat state:D stack:0 pid:3409 tgid:3409 ppid:2605 task_flags:0x400000 flags:0x00080800 kernel: Call Trace: kernel: <TASK> kernel: __schedule+0x48f/0xfe0 kernel: schedule+0x27/0xa0 kernel: schedule_preempt_disabled+0x15/0x30 kernel: __mutex_lock.constprop.0+0x569/0xa10 kernel: aa_new_learning_profile+0x15f/0x210 kernel: build_change_hat+0x19f/0x3b0 kernel: change_hat.isra.0+0x5dd/0xd60 kernel: aa_change_hat+0x2f3/0x710 kernel: aa_setprocattr_changehat+0x121/0x1f0 kernel: do_setattr+0x28c/0x340 kernel: apparmor_setselfattr+0x20/0x50 kernel: security_setselfattr+0xf6/0x110 kernel: __x64_sys_lsm_set_self_attr+0x53/0x90 kernel: do_syscall_64+0xdd/0x5e0 kernel: ? __mod_memcg_lruvec_state+0xfd/0x260 kernel: ? lruvec_stat_mod_folio+0x8d/0xd0 kernel: ? __folio_mod_stat+0x2d/0x90 kernel: ? map_anon_folio_pte_nopf+0xd1/0x1f0 kernel: ? do_anonymous_page+0x184/0xa10 kernel: ? __handle_mm_fault+0x805/0x870 kernel: ? count_memcg_events+0xef/0x230 kernel: ? handle_mm_fault+0x1f0/0x2f0 kernel: ? do_user_addr_fault+0x2bb/0x7b0 kernel: ? do_syscall_64+0x94/0x5e0 kernel: ? exc_page_fault+0x75/0x160 kernel: entry_SYSCALL_64_after_hwframe+0x76/0x7e kernel: RIP: 0033:0x7f815e134c8d kernel: RSP: 002b:00007fff6df94ea8 EFLAGS: 00000246 ORIG_RAX: 00000000000001cc kernel: RAX: ffffffffffffffda RBX: 0000556d8c81d040 RCX: 00007f815e134c8d kernel: RDX: 0000000000000046 RSI: 0000556d8c81d040 RDI: 0000000000000064 kernel: RBP: 00007fff6df94ef0 R08: 00007f815e212ac8 R09: 000000000000000c kernel: R10: 0000000000000000 R11: 0000000000000246 R12: 0000556d8c81d010 kernel: R13: 0000000000000026 R14: 0000000000000046 R15: 0000000000000064 kernel: </TASK> kernel: INFO: task hat:3409 is blocked on a mutex likely owned by task hat:3409. To fix the issue, lift the locking out of the core of aa_new_learning_profile(), introduce a wrapper function that takes the lock where needed, and have build_change_hat() call the core function that no longer takes the lock. In addition fix 4 other issues introduced by commit 32e92764d6f8d ("apparmor: grab ns lock and refresh when looking up changehat child profiles") - aa_get_profile_rcu() was replaced-by: aa_get_profile without the accompanying rcu_dereference_protected() - an extra aa_get_label(label) was introduced at the start of change_hat() without an accompanying aa_put_label() causing a reference count leak. - a reference count leak was introduced in the label_is_stale(label) case, where the newest profile would be leaked instead of the label passed to the function. - a potential UAF when the lookup walks up the tree with new_ns != ns the new label reference is put, and then used for the next lookup. The mutex_lock, will block replacement, and removal in the locked ns. However there are two cases where putting the reference can result in the label being freed even with the lock held. 1. the label does not have a list reference (possible for temporary or special profiles) in which case the put can trigger the cleanup. 2. the new label reference is in a different namespace, which does not have a lock held on it. This extends case 1 to also include replacement, and removal that could be occurring in the namespace new is in. Reported-by: Martin Petricek <mp@petricek.net> Link: https://lists.ubuntu.com/archives/apparmor/2026-August/014907.html Fixes: 32e92764d6f8d ("apparmor: grab ns lock and refresh when looking up changehat child profiles") Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-15landlock: Add LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVSJustin Suess
Add a landlock_restrict_self(2) flag to set the no_new_privs attribute of the calling thread only after enforcement of the ruleset: no_new_privs is set if and only if the call succeeds. This removes the need for a prior prctl(2) PR_SET_NO_NEW_PRIVS call and guarantees that a failed enforcement leaves the attribute unchanged. Because no_new_privs is set by the call itself, the no_new_privs / CAP_SYS_ADMIN requirement of landlock_restrict_self(2) is fulfilled by construction, and the related EPERM check is skipped. Unlike LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF, this flag always requires a valid ruleset: with a ruleset_fd of -1, such a call would be nothing more than a Landlock-flavored prctl(2) PR_SET_NO_NEW_PRIVS, and there is no valid use case for setting no_new_privs (possibly with LANDLOCK_RESTRICT_SELF_TSYNC) without also enforcing Landlock restrictions. Rejecting these calls also keeps the option of giving them a meaning later. The attribute is only set past the last point of failure, just before committing the new credentials. When combined with LANDLOCK_RESTRICT_SELF_TSYNC, no_new_privs is set on the sibling threads as well, in their commit phase, with the same ordering. Bump the Landlock ABI version to 11, and include the minimal related test changes to keep the tests bisectable. Cc: Mickaël Salaün <mic@digikod.net> Signed-off-by: Justin Suess <utilityemal77@gmail.com> Link: https://patch.msgid.link/20260809212459.2427878-1-utilityemal77@gmail.com Signed-off-by: Mickaël Salaün <mic@digikod.net>
2026-08-15landlock: Check landlock_restrict_self(2)'s flags before privilegesJustin Suess
landlock_restrict_self(2) currently checks the no_new_privs / CAP_SYS_ADMIN requirement before validating the flags argument. An unprivileged caller without no_new_privs thus gets EPERM even when the passed flags are invalid, hiding the EINVAL error. Move the no_new_privs / CAP_SYS_ADMIN check just after the flags check so that malformed calls consistently error out with EINVAL whatever the caller's privileges, the same way seccomp(2) validates its flags before checking no_new_privs. Update the restrict_self_checks_ordering test accordingly. Cc: Mickaël Salaün <mic@digikod.net> Signed-off-by: Justin Suess <utilityemal77@gmail.com> Link: https://patch.msgid.link/20260809154544.1253100-2-utilityemal77@gmail.com Signed-off-by: Mickaël Salaün <mic@digikod.net>
2026-08-15landlock: Require LANDLOCK_ACCESS_FS_MAKE_REG for whiteout creationGünther Noack
Whiteout objects are used in the upper layer of an OverlayFS to indicate that the file with this name does not exist in the unified view, even if it is present in one of the lower layer file systems. For the userspace implementations of OverlayFS (fuse-overlayfs), whiteout objects can be created from userspace as well: * mknod(2) with S_IFCHR and makedev(0, 0) * renameat2(2) with RENAME_WHITEOUT, creating the whiteout in the old place of the moved file. This commit guards whiteout creation in both of these cases with LANDLOCK_ACCESS_FS_MAKE_REG. Whiteout objects are *not* considered character devices and are not bound to a driver. LANDLOCK_ACCESS_FS_MAKE_REG describes the same permission class as a whiteout object: creating one is the only S_IFCHR creation that the VFS exempts from CAP_MKNOD, so it is as unprivileged as creating a regular file, while LANDLOCK_ACCESS_FS_MAKE_CHAR and LANDLOCK_ACCESS_FS_MAKE_BLOCK keep meaning the creation of devices that expose a kernel interface [1]. For the mknod(2) case, introduce a Landlock erratum. The creation of whiteout objects through mknod(2) was previously guarded using LANDLOCK_ACCESS_FS_MAKE_CHAR, and it is now guarded using LANDLOCK_ACCESS_FS_MAKE_REG. For the renameat2(2) case, fix a bug: Before this commit, renameat2(2) with RENAME_WHITEOUT would create a directory entry even when all LANDLOCK_ACCESS_FS_MAKE_* rights were denied. This does not affect normal renames within layered OverlayFS mounts: When doing a regular rename() on a mounted fuse-overlayfs, it is the fuse-overlayfs daemon that exercises renameat2() with RENAME_WHITEOUT, and only the Landlock domain of that daemon is checked there. Suggested-by: Christian Brauner <brauner@kernel.org> Suggested-by: Mickaël Salaün <mic@digikod.net> Cc: stable@vger.kernel.org Fixes: cb2c7d1a1776 ("landlock: Support filesystem access-control") Depends-on: 49c9e09d9610 ("landlock: Fix handling of disconnected directories") Depends-on: fe72ce6710cb ("landlock: Add errata documentation section") Signed-off-by: Günther Noack <gnoack@google.com> Link: https://patch.msgid.link/20260720.chow9ohYie5b@digikod.net [1] Link: https://patch.msgid.link/20260813093157.1436894-3-gnoack@google.com [mic: Record why LANDLOCK_ACCESS_FS_MAKE_REG is the matching right, and add link(2) to the user doc] Signed-off-by: Mickaël Salaün <mic@digikod.net>
2026-08-14landlock: Harden sock_is_scoped() against file-less socketsMickaël Salaün
sock_is_scoped() dereferences other->sk_socket->file->f_cred to read the peer's Landlock domain when evaluating LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET, without first checking that the peer has a backing socket and file. hook_unix_find() performs the same dereference for LANDLOCK_ACCESS_FS_RESOLVE_UNIX and does guard it. Guard it here too and treat a peer with no backing file, such as a kernel socket created by sock_create_kern(), as unscoped. This is defensive hardening, not a fix for a reachable bug. The unix_stream_connect() and unix_may_send() hooks run with the peer held under unix_state_lock() and only after the AF_UNIX core has excluded SOCK_DEAD, and no in-tree code binds a file-less AF_UNIX socket to an abstract address, so other->sk_socket->file is always valid at these call sites today. Cc: Günther Noack <gnoack@google.com> Link: https://patch.msgid.link/20260703152750.2022878-1-mic@digikod.net Signed-off-by: Mickaël Salaün <mic@digikod.net>
2026-08-10apparmor: constify aa_label parameters on read-only query helpersJohn Johansen
Several label helpers only read from their struct aa_label * arguments: they compare labels, test subset relationships, or check the mediation bitmask, all via direct field/index access. Mark those parameters const struct aa_label * to document intent and let the compiler enforce that the label is not modified. The converted functions are: - label_mediates(), label_mediates_safe() - aa_label_cmp() (and its vec_cmp() helper) - __aa_label_next_not_in_set(), aa_label_is_subset(), aa_label_is_unconfined_subset() - __aa_subj_label_is_cached() - aa_label_next_confined(), aa_label_next_in_merge() These all access the label through direct indexing or manual iterators rather than the label_for_each()/fn_for_each() macros, which are not const-correct and so gate the majority of the remaining label consumers (the print, match, and permission-check paths) from being constified. No functional change. Signed-off-by: John Johansen <john.johansen@canonical.com> Assisted-by: Claude:claude-opus-4.8
2026-08-10apparmor: constify aa_dfa parameters on read-only compute pathsJohn Johansen
Most uses of aa_dfa a read-only walking of the dfa. Have the compiler enforce this. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: constify aa_profile parameters on read-only compute pathsJohn Johansen
A number of functions take a struct aa_profile * argument that is only ever read from: they compute DFA matches or apply the profile's mode flags without modifying the profile, taking a reference on it, or touching its embedded label. Mark those parameters const struct aa_profile * to document intent and let the compiler enforce it. The converted functions are the permission "compute" path plus a few pure readers: - aa_apply_modes_to_perms(), aa_profile_match_label() - AUDIT_MODE() - aa_label_match() and its match_component()/label_compound_match()/ label_components_match() helpers (label.c) - match_component()/label_compound_match()/label_components_match()/ label_match()/change_profile_perms()/aa_xattrs_match() (domain.c) - match_iface()/match_addr_iface()/match_addr_iface_label()/ skb_match_to_sk()/skb_match_to_cmd() (af_inet.c) - aa_profile_capget(), path_flags(), profile_query_cb() The remaining aa_profile * parameters cannot be made const: the audit path stores &profile->label into the owned, refcounted apparmor_audit_data.subj_label/peer fields, and the domain/lifecycle paths take references on the profile's embedded label (aa_get_label()/aa_get_newest_label()/aa_get_profile()) or write profile fields. No functional change. Signed-off-by: John Johansen <john.johansen@canonical.com> Assisted-by: Claude:claude-opus-4.8
2026-08-10apparmor: constify aa_perms parameters that are read-onlyJohn Johansen
Several functions take a struct aa_perms * argument that is only ever read from and never modified through the pointer. Mark those parameters const struct aa_perms * to document intent and let the compiler enforce that the permission set is not mutated. The converted functions are: - aa_check_perms() - aa_do_perms() - do_perms() (af_inet) - match_label() (af_unix) - verify_perm() - aa_perms_accum() / aa_perms_accum_raw() (@addend only) No functional change. Signed-off-by: John Johansen <john.johansen@canonical.com> Assisted-by: Claude:claude-opus-4.8
2026-08-10apparmor: drop use of _confined variant for iterationJohn Johansen
In preparation for allowing unconfined to be replaced and mediate select rules drop use of the _confined variant for iteration in the mount code. The RULE_MEDIATES() check will continue to allow unconfined profile mediation to be skipped unless it is replaced and is given mount rules. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: refactory mount to use check_permsJohn Johansen
Move the mount permissions check to use the common backend aa_check_perms() to check permissions. This will make it so caching, audit, complain, logic can be handled consistently in a single place. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: fix auditing of mount binary dataJohn Johansen
AppArmor only mediates non-binary mount data, and should only audit the mount data if it is non-binary. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: add audit mode to provide a mechanism to silence complain messagesJohn Johansen
Complain messages can be very noisy and fill the logs quickly. Allow complain (allow) messages to be silenced separate from denied messages. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: mark static tables and structs as read onlyJohn Johansen
static tables, and structs that are initialized as part of their data section or during init should be read only to protect against accidental or malicous changes. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: fix error debug output in fn_label_buildJohn Johansen
checking PTR_ERROR() is not correct to just determine if any error occured, instead use the IS_ERR macro and also output the PTR_ERR as part of the debug message. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: make table entry count last enum for static tablesJohn Johansen
Instead of keeping an external define for the various tables indexed by an enum, make the size the last entry of the enum so the table size will get updated correctly with changes to the enum. Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com> Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: fix race condition in label replacementJohn Johansen
label replacement can result in the need for locking on two separate trees. Currently this is done by locking the tree to remove and then the tree to add to. For compound labels the race can result in the old label proxy pointing to the the new label that lost the race and that was not inserted in to the new tree. This does not break mediation, but it does result in a task that will not update its profile correctly on future mediation, and that will leak its refcount due to a circular reference in its proxy, resulting in a memory leak. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: refactor xattr attachment, to take the file pathJohn Johansen
The full bprm does not need to be passed into xattrs_match, so only pass in the path, and propagate the change backup the call stack until bprm is actually needed. Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com> Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: fix unconfined user namespace restriction forced stackJohn Johansen
If a task is already confined by a stack the unprivileged transition restriction on unconfined is not correctly, applied. This results in an escape if two transitions through an unconfined profile can be executed. Fix this by pushing the check into the per profile label build. The check will always be done against unconfined and result in a stack of just the unconfined component when necessary. Fixes: 2d9da9b188b8 ("apparmor: allow restricting unprivileged change_profile") Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: reserve mediation class for packet mediationJohn Johansen
Packet mediation is going to be added in the future, reserve a class for it. Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: move sock_rcv_skb() next to inet_conn_requestJohn Johansen
both of these fns are using ifdef CONFIG_NETWORK_SECMARK and related to AppArmor's secmark based mediation, so move them together. Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com> Signed-off-by: John Johansen <john.johansen@canonical.com>
2026-08-10apparmor: move netfilter functions next to the LSM network operationsJohn Johansen
Make sure all the network mediation hooks are next to each other in a logical block. This just makes it easier to read/understand the network mediation code. Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com> Signed-off-by: John Johansen <john.johansen@canonical.com>