Pull bpf updates from Alexei Starovoitov:
"Major changes:
- Introduce scalar evolution (SCEV) analysis in the verifier.
It infers how registers and stack slots change in a loop and lets
the verifier check bounded loops with induction variables as ranges
instead of walking every iteration. The number of processed insns
drops ten fold in programs with loops (Eduard Zingerman)
- Add 'callx' instruction: indirect call of a static BPF subprogram.
The address is taken with ld_imm64 or loaded from read-only data.
Supported by x86-64, arm64 and riscv64 JITs (Alexei Starovoitov, Pu
Lehui)
- Add unwind_goto and unwind_exit instructions, so that Rust panic or
C++ exception can run destructors of every frame it passes through.
The normal path is free of unwind code. Supported by x86-64 and
arm64 JITs (Alexei Starovoitov)
- Support programs compiled by rust-bpf: treat load and store through
a number as arena access with BPF_F_ARENA_SCALAR, accept rust names
in BTF (Alexei Starovoitov)
- Raise BPF program stack size from 512 bytes to 2 KiB on x86-64 and
arm64 (Kumar Kartikeya Dwivedi)
- Support struct, union and __int128 up to 16 bytes passed and
returned by value in BPF subprograms and kfuncs, and fix x86-64 and
arm64 trampolines for such arguments (Yonghong Song)
- Introduce a common way to attach struct_ops to a cgroup via
bpf_link. bpf_tcp_ops is the first user and mirrors TCP sock_ops
callbacks (Martin KaFai Lau, Amery Hung)
- Describe inlined functions in BTF. New kinds tell where the inline
sites are and how to fetch the arguments there.
CONFIG_DEBUG_INFO_BTF_INLINE keeps it apart from the main BTF in
.BTF.inline section or in btf_vmlinux_inline.ko (Alan Maguire)
- Fix many memory safety, lifetime and locking bugs in BPF core,
verifier, iterators, local storage, dynptr, devmap, cpumap and
seg6local (Josef Bacik, Alexei Starovoitov)
- Diff stat is dominated by selftests and by removal of
lib/test_bpf.c. Its 16k lines of instruction tests were converted
to BPF selftests that BPF CI runs on every architecture it covers
(Daniel Borkmann)
Other features and fixes:
- Add KASAN checks to memory accesses of JITed programs on x86-64
(Alexis Lothoré)
- Complete unification of helper, kfunc and subprog argument checks
in the verifier (Amery Hung)
- Add bpf_copy_from_user_mm[_str]() kfuncs (Anastasios Papagiannis)
- Various features and fixes (Daniel Borkmann):
- Add .bpf keyring for program signature verification, modelled
after dm-verity keyring, and support ML-DSA in signing tools
- Emit shorter and faster code in x86-64 JIT for patterns that
LLVM generates
- Fix various issues in gotox handling
- Let BPF LSM set xattrs at inode creation with bpf_inode_init_xattr()
(David Windsor, Daniel Borkmann)
- Use sleepable page allocation in sleepable arena paths. Fix races
between arena free, allocation and user page fault (Emil Tsalapatis)
- Switch BPF crypto from lskcipher to AES-CBC and AES-ECB libraries
(Eric Biggers)
- Add bpf_proactive_reclaim() kfunc (Hui Zhu)
- Render decl_tags in libbpf btf_dump and add tests for bpftool C
dump (Ihor Solodrai)
- Speed up tracing_multi attach on x86 (Jiri Olsa)
- Various features and fixes (Kumar Kartikeya Dwivedi):
- Add BPF_PROG_STREAM_OPEN command to read BPF streams through a
file descriptor with poll support
- Let kernel structs publish arena pointers with __arena type tag
- Fix __uninit kfunc output buffers and fastcall rewrite with
indirect stack accesses
- Refuse CO-RE relocations for signed programs
- Add enqueue_rcvq and dequeue_rcvq hooks to bpf_tcp_ops to adjust
sk_rcvlowat and avoid unnecessary wakeups (Kuniyuki Iwashima)
- Add bpf_ksock_sendto() kfunc and allow ksock connect and send from
bpf_wq (Mahe Tardy)
- Fix racy plt target update in arm64 bpf_arch_text_poke()
(Matthew Wood)
- Restructure BPF selftests Makefile as a layered build
(Mykola Lysenko)
- Speed up hash map lookups for u32 and u64 keys (Mykyta Yatsenko)
- Add signed div/mod, movsx, bswap and gotol to MIPS JITs, signed
div/mod to parisc JITs (Nicholas Dudar, Johan Almbladh)
- Fix stack overflow in build ID parser on 32-bit (Nickolai
Zeldovich)
- Add stack arguments, signed arena loads and gotox to riscv64 JIT.
Pu Lehui is now co-maintainer of riscv BPF JITs (Pu Lehui, Chen
Pei, Feng Jiang)
- Add bpf_call_rcu() and bpf_call_rcu_tasks_trace() kfuncs. Support
fetching and/or/xor atomics in arena on x86-64 (Puranjay Mohan)
- Fix flaky selftests, selftests with clang 23 and bpf-gcc
(Qiliang Yuan, KaFai Wan, Vineet Gupta)
- Fix builds broken by fatal resolve_btfids warnings, BTF generation
on ARC, and define arch_cmpxchg_local() on arc, hexagon and
openrisc (Sasha Levin)
- Reduce memory use of hash maps by up to 50% per element
(T.J. Mercier)
- Mark pointer fields of sched_ext ops arguments as trusted (Tejun
Heo)
- Remove legacy bpf_asm, bpf_dbg and bpf_jit_disasm tools (Xia Yan)
- Fix index overflow in queue and stack maps, arena range tree after
allocation failure, tail call loop after freplace detach, lost
signal in bpf_send_signal() (Yuan Chen)
- Many more fixes and cleanups"
* tag 'bpf-next-7.4' of git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next: (660 commits)
selftests/bpf: Time tc_edt from its first packet with data
selftests/bpf: Test unwind_exit of an exception callback
selftests/bpf: Tests for 32-bit scalar evolution bounds computation
bpf: Reject unwind_goto and unwind_exit in offloaded progs
bpf: Support 32-bit linear scalar evolution
bpf: Make unwind_exit of an exception callback exit in JITs
selftests/bpf: Test forbidden bpf_ksock_sendto() LSM attach
selftests/bpf: Test ksock sendto()
bpf: Add bpf_ksock_sendto() kfunc
selftests/bpf: Test unwinding from R0: R2 subprog
selftests/bpf: Add a C++ prog with exceptions
selftests/bpf: Add tests for unwind_goto and unwind_exit
bpf, arm64: Support unwind_goto and unwind_exit
bpf, x86: Support unwind_goto and unwind_exit
bpf: Add unwind_goto and unwind_exit insns
tools/bpf: Remove legacy BPF tools
bpf: Annotate data races on bpf_lru_node type
selftests/bpf: Add arena allocation race tests
bpf: Fix arena race between page free and alloc leading to incoherency
bpf: Revalidate faulted arena pages before installing user mappings
...
Pull module updates from Petr Pavlu:
- Ignore local labels and mapping symbols during module load
These symbols were already ignored during kallsyms address-to-symbol
lookups. Filter them out earlier during module loading to reduce
lookup overhead and prevent them from appearing in /proc/kallsyms.
- Fix potentially incorrect access of SetOnce<T> when setting Rust
module parameters.
- Fix a potential read of an uninitialized count when printing taint
information for unloaded modules.
- Allocate the kmod argument array using kmalloc_array() in preparation
for conversion to type-aware allocators.
- Clean up includes in linux/kmod.h
Add explicit includes of linux/umh.h to files that use usermode
helpers. Then clean up the #include list in linux/kmod.h, notably
removing the compatibility linux/umh.h include.
- Remove the error-injection.h include from linux/module.h
Add explicit includes of linux/error-injection.h to files that use
the ALLOW_ERROR_INJECTION() macro and currently rely on it being
provided indirectly via linux/module.h. Then remove the unnecessary
linux/error-injection.h include from linux/module.h.
- Replace __MODULE_STRING() with __stringify() in various drivers in
preparation for removing the former macro.
* tag 'modules-7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/modules/linux:
drivers: Replace __MODULE_STRING() with __stringify()
module: Fix uninitialized count read of unloaded taint tracking record
rust: module_param: Fix potentially incorrect access of `SetOnce<T>`
module: Remove the error-injection.h include from linux/module.h
drm/xe: Include error-injection.h for ALLOW_ERROR_INJECTION()
drm/i915: Include error-injection.h for ALLOW_ERROR_INJECTION()
syscalls: Include error-injection.h for ALLOW_ERROR_INJECTION()
net: Include error-injection.h for ALLOW_ERROR_INJECTION()
block: Include error-injection.h for ALLOW_ERROR_INJECTION()
module: Bring includes in linux/kmod.h up to date
time/jiffies: Include linux/sysctl.h for proc_int_u2k_conv_uop(), ...
umh, treewide: Explicitly include linux/umh.h where needed
modules/kmod: Allocate argv with kmalloc_array()
module/kallsyms: Ignore local labels and mapping symbols during module load
module/kallsyms: Refactor current symbol filtering into is_core_symbol()
module/kallsyms: Rename is_mapping_symbol() to is_ignored_kernel_symbol()
Pull keys updates from Jarkko Sakkinen:
"Highlight:
- Don't leak local kernel addresses (and complement the ongoing
rhashtable migration) (Kyle Zeng)
The index value for the associative array has been calculated with
the following formula:
mult_64x32_and_fold(description + type address + domain address)
By creating a sequence of dummy keys (e.g., "A", "B", "C", ...), it
is trivial to form a group of equations with a predictable hash
function, and ultimately break KASLR.
Kyle's solution is based on an ephemeral SipHash key and an atomic
64-bit counter, which is encapsulated to a key_index_id(). This
function is then used to assign identifiers for types and domains,
and since the IDs are unique for each power on, they are as unique
as memory addresses are.
With these ingredients the index value calculation can be changed
into form, which is not leaking any kernel addresses:
SipHash(description + type id + domain id)
Features and improvements:
- TPM fields were moved from trusted_key_options to the TPM backend.
They cost memory for non-TPM backends.
- A TPM trusted key now caches tpm_is_tpm2() at the root of each call
chain, and passes the result as a parameter. This decreases the
amount of I/O traffic given that tpm_is_tpm2() starts and stops the
chip via tpm_try_get_ops() and tpm_put_ops().
Bugfixes:
- A TPM trusted key corrupted the return value of a failed key
unsealing operation if the pcrlock feature was used.
- A TPM 2 trusted key allocated an off-by-four too large buffer for
the decoded ASN.1 blob coming from keyctl add trusted.
- Sometimes a TPM 2 trusted key rejected created keys based on the
TPM2_Create response size, treating them as too large. Now it
correctly checks the extracted TPM2 key blob size.
- The keyctl reject operation raced with keyctl restrict_keyring
because keyring->sem was not held in key_reject_and_link() before
accessing keyring->restrict_link.
- keyctl_describe_key() was not holding key->sem while accessing its
fields, which can lead to use-after-free of a retired key type.
- find_keyring_by_name() and procfs code were reading the UID from
key->user->uid instead of key->uid. The latter is the cached value
and is meant to protect against a use-after-free caused by keyctl
chown.
- search_process_keyrings_rcu() did not properly RCU-dereference the
authorization key payload, which could cause a null dereference if
the payload was revoked.
- keyctl_read_key() checked key->type->read without holding key->sem,
which can lead to use-after-free if the type is retired. Based on
my suggestion, this was addressed in __keyctl_read_key(), which
already did take key->sem"
* tag 'keys-v7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd:
keys/trusted_keys: reuse TPM version in option handling
security: keys: Fix comment of search_process_keyrings_rcu()
keys/trusted/tpm2: Validate TPM2_Create object sizes separately
keys/trusted_keys: move TPM-specific fields into struct trusted_key_tpm
keys: Protect the read method check against type removal
keys: Avoid owner account dereferences in /proc/keys
keys: make keyring indexes independent of kernel addresses
keys: Check the authorization payload in process keyring searches
keys: Avoid the owner account dereference in named keyring lookup
keys: Protect the type name while describing a key
KEYS: Fix key_reject_and_link() race with keyring restriction
KEYS: trusted: Fix blob allocation size in tpm2_key_decode()
keys/trusted_keys: return immediately after TPM unseal failure
Pull Landlock update from Mickaël Salaün:
"The main change adds composable Landlock controls for namespace types
and Linux capabilities, thanks to new LSM hooks (merged via the LSM
tree). A umount race condition is also fixed"
* tag 'landlock-7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/mic/linux:
landlock: Fix superblock use-after-free in release_inode()
selftests/landlock: Fix snprintf truncation checks in test files
landlock: Add documentation for capability and namespace restrictions
samples/landlock: Add capability and namespace restriction support
selftests/landlock: Add capability restriction tests
selftests/landlock: Add namespace restriction tests
landlock: Enforce capability restrictions
landlock: Enforce namespace use restrictions
landlock: Wrap per-layer access masks in struct layer_config
landlock: Rename quiet_masks to quiet_access
Pull IPE updates from Fan Wu:
- Fix an extra empty audit record on enforcement changes
ipe_audit_enforce() started an audit buffer but logged the state
change with audit_log(), which emits its own record. Ending the
unused buffer produced an additional empty AUDIT_MAC_STATUS record
every time the enforcement state was changed.
- Keep the name and token tables in sync with their enums
The audit name tables now use designated initializers, so each name
stays bound to its enum value, and static assertions on the policy
parser token tables break the build if an enum value is added without
a matching token.
- Constify token_default() and correct a comment about policy text
ownership, with no functional changes
- Fix an invalid sgid value in an audit event example in the docs
- Point the docs to the new IPE website and test suite repository
* tag 'ipe-pr-20261019' of git://git.kernel.org/pub/scm/linux/kernel/git/wufan/ipe:
ipe: update the project and test suite links
ipe: fix enforcement audit
ipe: correct policy text ownership comment
ipe: check parser token table sizes
ipe: use designated initializers for audit name tables
ipe: constify token_default()
ipe: fix invalid sgid value in audit event documentation
Pull IMA updates from Mimi Zohar:
"Cleanup:
- Update ima_audit_msg() to report errno directly, revert making it a
wrapper for ima_audit_message(), and remove ima_audit_message()
Two bug fixes when carrying the IMA measurement list across kexec:
- Restore the number of violations in the IMA measurement list
- Reject restoring IMA measurement list record(s) beyond the expected
buffer size (out-of-bounds)"
* tag 'integrity-v7.4' of git://git.kernel.org/pub/scm/linux/kernel/git/zohar/linux-integrity:
ima: reject a kexec buffer whose declared size exceeds the buffer
ima: recover number of violations after kexec
integrity: Replace integrity_audit_message() with integrity_audit_msg()
integrity: Report error code in integrity_audit_msg() call sites
Pull lsm updates from Paul Moore:
- Add LSM hooks, object blobs, and audit records for namespaces
Add the necessary bits to enable LSMs to enforce access controls on
the management of various kernel namespaces. While this pull request
does not contain any in-tree users of these hooks, the Landlock pull
request for Linux v7.4 will include Landlock support and the next
merge window will likely include SELinux support as well. Considering
the development behind these hooks, I expect that BPF LSM developers
will also be making use of the namespace hooks, if they haven't
already.
- Update the inode LSM hooks to include mount idmaps
This allows LSMs to incorporate the mount ID mapping into their
access control decisions. While there are no current in-tree users of
this, it was requested by those developing BPF LSM programs and this
pull request includes a BPF LSM selftest.
- Preserve the full 32-bit ioctl command in LSM audit records
Previously only the low 16 bits were logged, ignoring the direction
and size information in the upper 16 bits. The pull request also
includes a Landlock based selftest to verify the full 32-bit ioctl
value.
- Ensure we don't call security_backing_file_free() multiple times
Thankfully we don't have a problem with the current code base, but we
want to fix this behavior now before it becomes a problem.
- Clarify that only the current task may access current->cred
The current code is a bit misleading around safely accessing the cred
field in a task struct. Through comment and code corrections, this
pull request clarifies that only the task itself may access its cred
field.
- Add SLAB_NO_MERGE to the credential object cache
Harden the credential cache by ensuring credential objects live on
dedicated slab pages.
- Make use of safe memory zero'ing in the LSM Rust bindings
- Update the docs for the current behavior of /sys/kernel/security/lsm
- Update the docs for CONFIG_LSM and the "lsm=" command line option
- Remove unnecessary code
* tag 'lsm-pr-20261016' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/lsm:
lsm: remove redundant NULL check in security_init()
selftests/landlock: Check full ioctl commands in audit records
lsm: Preserve full ioctl commands in audit records
doc: fix LSM ordering description for /sys/kernel/security/lsm
doc: describe CONFIG_LSM and lsm= as the selection mechanism
selftests/bpf: verify mount idmaps reach inode hooks
lsm: expose mount idmaps to inode hooks
rust: lsm: replace `core::mem::zeroed` with `pin_init::zeroed`
cred: prevent slab cache merging for cred_jar
lsm: don't call security_backing_file_free() multiple times
lsm: delete duplicate assignment in lsm_prepare()
lsm: update the BUILD_BUG_ON() in audit_log_lsm_data()
lsm: add LSM_AUDIT_DATA_NS for namespace audit records
lsm: add LSM blob and hooks for namespaces
ns: Free anonymous mount namespaces via ns_common_free()
cred: clarify that task_struct::cred is only for the current task
Pull selinux updates from Paul Moore:
- Continue to improve the load time validation of SELinux policies
While SELinux policy loading remains a privileged operation, we
continue the recent trend of hardening the policy parsing and
validation code in the kernel to ensure that invalid, or poorly
formatted policies are rejected at load time.
- Correctly incorporate "neveraudit" into the xperms code
This change aligns the xperms neveraudit handling with the
conventional permission handling code, exiting early from the SELinux
auditing code when neveraudit is enabled for the domain.
- Mark the selinuxfs "status" and "policy" files immutable
These are read-only kernel/userspace interfaces that could
successfully be opened at the VFS layer through the use of
CAP_DAC_OVERRIDE. With this pull request we are marking these two
files as immutable so that the requests to open these file with write
permissions now fail at the VFS layer. This also allows us to drop
some of our mmap() checks around write permissions as the VFS will
now also handle this for us.
The existing SELinux permissions checks remain untouched.
- Convert the selinuxfs inode numbers to u64
Bring selinuxfs current with other filesystems in using u64 for inode
numbering as opposed to the architecture dependent unsigned long.
- Constify a number of the SELinux AVC function parameters
- Remove a SELinux MLS function that was no longer used
* tag 'selinux-pr-20261015' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux:
selinux: validate permissive and neveraudit map types at load
selinux: validate user MLS range and default level at load
selinux: bounds-check role and user membership bitmaps at load
selinux: check neveraudit in avc_xperms_audit_required()
selinux: bounds-check filename transition source types at load
selinux: reject duplicate symbol values during policy load
selinux: reject a policy that both rejects and allows unknown classes
selinux: constify avc function parameters
selinux: avoid 64-bit division of inode numbers
selinux: mark status and policy inodes as immutable, drop status mmap write checks
selinux: remove unused mls_setup_user_range()
selinux: convert selinuxfs inode numbers from unsigned long to u64
selinux: tighten policydb_context_isvalid() checks
Pull crypto library updates from Eric Biggers:
- Migrate the x86 and riscv optimized implementations of various AES
modes (ECB, CBC, CBC-CTS, CTR, XCTR, XTS) into lib/crypto/.
This makes the library APIs be properly accelerated on these
architectures, while still accelerating crypto_skcipher as well.
It removes a lot of redundant glue code, since the crypto API
boilerplate no longer needs to be duplicated for these architectures.
It also fixes the longstanding issue where optimizations for these
AES modes were disabled by default on these architectures.
- Optimize AES-XTS on SPARC64 using the SPARC crypto opcodes
- Move the SipHash code into lib/crypto/
- Update the ChaCha and Poly1305 functions to take size_t lengths,
resolving issues where lengths over INT_MAX were mishandled
- Make frame pointer unwinding work properly in some of the x86
assembly functions, by following the standard %rbp convention
- Add helper functions for zeroizing structs
- Make a few documentation improvements
* tag 'libcrypto-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux: (49 commits)
lib/crypto: md5: remove unused header
lib/crypto: mips/chacha: Handle lengths of 2 GiB or more
lib/crypto: arm/chacha: Handle lengths of 2 GiB or more in scalar code
lib/crypto: chacha: Use size_t length
lib/crypto: poly1305: Use size_t length
lib/crypto: x86/sha512: Follow the normal %rbp convention
lib/crypto: x86/sha256: Follow the normal %rbp convention
lib/crypto: x86/sha1: Follow the normal %rbp convention
lib/crypto: chacha20poly1305: zeroize state in __chacha20poly1305_decrypt
lib/crypto: sparc/aes-xts: Add optimization using the AES opcodes
lib: Move SipHash into lib/crypto/
lib/crypto: x86/aes-ctr: Remove some unreachable code
crypto: x86/aesni-intel - Add transitional selections
crypto: aes - Boost priority of encryption modes further
lib/crypto: x86/aes: Set RNDKEY in aes_cbc_encrypt_aesni()
lib/crypto: riscv/aes-xts: Migrate optimized code into library
lib/crypto: riscv/aes-ctr: Migrate optimized code into library
lib/crypto: riscv/aes-cbc: Migrate optimized code into library
lib/crypto: riscv/aes-ecb: Migrate optimized code into library
lib/crypto: riscv/aes: Pass key struct to assembly code
...
TPM2_Create returns outPrivate, outPublic, creationData, creationHash and
creationTicket in its response parameter area. However, only outPrivate and
outPublic are included in the trusted key blob. The size of the blob is
therefore not determined by the size of the complete response parameter
area.
tpm2_seal_trusted() currently compares the size of the complete response
parameter area against MAX_BLOB_SIZE. This can reject a valid response
when the remaining response outputs cause the entire response parameter
area to exceed MAX_BLOB_SIZE, even though the outPrivate and outPublic
TPM2B structures consumed by tpm2_key_encode() remain small enough to be
encoded in the key blob.
This is observed when creating larger trusted keys using the swtpm TPM 2.0
emulator backed by libtpms.
For example, requesting a 113-byte key succeeds, 114 fails.
~$ keyctl add trusted trusted_key1 "new 113 keyhandle=0x81000001" @u
520504613
~$ keyctl add trusted trusted_key2 "new 114 keyhandle=0x81000001" @u
add_key: Argument list too long
~$
Remove the MAX_BLOB_SIZE check on the complete response parameter area.
Instead, use the response length passed to tpm2_key_encode() to validate
that the outPrivate and outPublic TPM2B structures are fully contained
in the response before accessing them.
Previously, a response parameter area larger than MAX_BLOB_SIZE was
rejected with -E2BIG before ASN.1 encoding. With this change, if the
resulting encoded blob does not fit in payload->blob, the error returned by
asn1_encode_sequence() is propagated instead.
Also, use scope-based cleanup to simplify resource management.
Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
Link: https://lore.kernel.org/r/20260926184203.479203-1-ssrish@linux.ibm.com
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
The trusted_key_options struct contains TPM-specific fields (keyhandle,
keyauth, blobauth_len, blobauth, pcrinfo_len, pcrinfo, pcrlock, hash,
policydigest_len, policydigest, and policyhandle). This leads to the
accumulation of backend-specific fields in the generic options structure.
Define struct trusted_key_tpm and move the TPM-specific fields there. Store
a pointer to it in the private member of struct trusted_key_options.
Signed-off-by: Srish Srinivasan <ssrish@linux.ibm.com>
Reviewed-by: Stefan Berger <stefanb@linux.ibm.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Link: https://lore.kernel.org/r/20260912062950.279104-3-ssrish@linux.ibm.com
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
keyctl_read_key() checks key->type->read without holding key->sem.
A reference keeps the key alive, but does not pin the module containing
its type. A surviving RxRPC key can therefore be read while AF_RXRPC
is being unloaded:
KEYCTL_READ task Module unload and key GC
---------------- ------------------------
lookup_user_key()
permission / possession checks
load key->type
af_rxrpc_exit()
unregister_key_type()
GC: down_write(key->sem)
GC: retype to key_type_dead
GC: up_write(key->sem)
unregister_key_type() returns
free_module()
read saved type's read member
The final access can read freed module storage. The read invocation in
__keyctl_read_key() is already protected by key->sem, but the earlier
method check is outside that critical section.
Move the method check into __keyctl_read_key(), after key_validate() and
under its existing read hold on key->sem. The check and invocation then
use the same protected type for length queries and every read retry.
The GC cannot retype the key until the semaphore is released, and type
unregistration waits for that GC pass before the module can be freed.
Return -EOPNOTSUPP when validation succeeds and the type has no read
method. A temporary buffer may now be allocated before this result;
allocation and copying to userspace remain outside the semaphore.
Assisted-by: LLM
Cc: stable@vger.kernel.org # v5.10+
Fixes: d3ec10aa95 ("KEYS: Don't write out to userspace while holding key semaphore")
Suggested-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: Cen Zhang <zzzccc427@gmail.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Reviewed-by: David Howells <dhowells@redhat.com>
Link: https://lore.kernel.org/r/pm-key-management-objects-candidate-0010-v7-fc85721ff5cfb9e33ac6@gmail.com
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
The namespace filters in find_ge_key() and key_serial_next() read
key->user->uid while traversing the serial tree under key_serial_lock.
That lock keeps the key allocated, but it does not protect the separate
key_user from ownership changes.
A /proc/keys read reaches find_ge_key() through proc_keys_start(), and
key_serial_next() through proc_keys_next(). The lock stays held until
proc_keys_stop().
A successful privileged KEYCTL_CHOWN on the same key replaces key->user
under key->sem and drops the old owner's reference after releasing the
semaphore. If that was the old dynamic key_user's last reference, a
/proc/keys reader can access freed memory:
/proc/keys reader KEYCTL_CHOWN
proc_keys_start() keyctl_chown_key()
spin_lock(key_serial_lock) down_write(key->sem)
find_ge_key()
old = minkey->user
zapowner = key->user
key->user = newowner
key->uid = uid
up_write(key->sem)
key_put(key)
key_user_put(zapowner)
kfree(zapowner)
read old->uid -> use-after-free
proc_keys_stop()
spin_unlock(key_serial_lock)
Use the inline key->uid in both filters, following the approach already
used by find_keyring_by_name(). The serial-tree lock keeps the containing
key alive, so filtering no longer depends on the quota owner's lifetime.
This also uses the same owner UID as proc_keys_show() and the permission
check.
For thread keyrings, key_fsuid_changed() can update key->uid without
changing the quota owner. The filters now follow that current owner UID,
including when its namespace mapping differs from the quota owner's.
Fixes: 454804ab03 ("keys: make procfiles per-user-namespace")
Assisted-by: LLM
Suggested-by: Eric Biggers <ebiggers@kernel.org>
Signed-off-by: Cen Zhang <zzzccc427@gmail.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Link: https://lore.kernel.org/r/pm-keys-proc-owner-uid-followup-20261017-v2-8f8f34a41eb1bbb94ef0@gmail.com
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
KEYCTL_READ returns the serial numbers in a keyring in associative-array
traversal order. The first word of the index is a public, deterministic
hash of the type pointer, domain pointer and description. An unprivileged
user can therefore insert keys with known descriptions, predict their
order for each possible KASLR slide, and recover the kernel image address.
On an x86-64 build with 16 MiB alignment, 45 user keys suffice to
distinguish the candidate slides.
Remove the addresses from the whole index, not just its first hash word.
Assign each key type and domain a nonzero 64-bit ID and hash those IDs and
the description with a once-initialized SipHash key. Use the full IDs in
the later index chunks as well. Truncating or hashing the IDs there would
lose the guarantee that distinct type/domain/description tuples have a
differing index bit.
Allocate IDs lazily since private key types need not be registered. Cache
them in the index key so tree walks and copies of an existing index do not
need to dereference a type descriptor that may have been unregistered.
Keep the 32-bit chunk layout and diff_objects() bit offsets consistent,
and retain the separate root slot for keyrings used by recursive search.
The key comparison, permissions and userspace data format are unchanged;
only the address-dependent in-memory ordering is replaced.
Cc: stable@vger.kernel.org
Fixes: b2a4df200d ("KEYS: Expand the capacity of a keyring")
Assisted-by: Codex:gpt-6-astra
Signed-off-by: Kyle Zeng <kylebot@openai.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Link: https://lore.kernel.org/r/20261013231251.56170-1-kylebot@openai.com
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
An authorization payload and its saved credentials must remain valid
while search_process_keyrings_rcu() searches the requestor's keyrings.
The function validates the authorization key, then separately loads
payload.data[0] and unconditionally reads rka->cred. Validation does
not prevent request_key_auth_revoke() from clearing the payload.
A request-key helper can assume authority and fork a descendant that
inherits the authorization key. If the descendant misses in its own
keyrings, it falls back to the saved requestor credentials. Successful
target instantiation invalidates the authorization key without clearing
the payload. After the helper exits, UMH_WAIT_PROC returns to the
requester, which calls complete_request_key() and revokes that key.
With the descendant paused after validation, the paths can interleave
as follows:
1. The descendant enters search_process_keyrings_rcu() under RCU and
key_validate() succeeds.
2. The helper instantiates the target, invalidates the authorization
key, and exits.
3. The requester resumes from UMH_WAIT_PROC, calls
complete_request_key(), and revokes the authorization key.
request_key_auth_revoke() sets its payload pointer to NULL.
4. The descendant loads NULL and dereferences rka->cred.
This NULL dereference can oops the kernel. RCU delays payload disposal
but does not prevent the pointer from being cleared.
Load the payload with dereference_key_rcu() and require a non-NULL
result before validating the authorization key and searching its saved
credentials. A non-NULL payload and its credentials remain alive for
the caller's RCU read-side section; a cleared payload skips the fallback
search and follows the existing error selection.
KASAN report as below:
Oops: general protection fault, probably for non-canonical address 0xdffffc0000000005: 0000 [#1] SMP KASAN NOPTI
KASAN: null-ptr-deref in range [0x0000000000000028-0x000000000000002f]
RIP: 0010:search_process_keyrings_rcu+0x32b/0x790
Cc: stable@vger.kernel.org
Fixes: e59428f721 ("keys: Move the RCU locks outwards from the keyring search functions")
Assisted-by: LLM
Signed-off-by: Cen Zhang <zzzccc427@gmail.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Link: https://lore.kernel.org/r/pm-key-management-objects-candidate-0004-v3-598361863b76bc25d58d@gmail.com
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Named keyring lookup must keep the storage containing the owner UID
alive through the namespace mapping check. find_keyring_by_name()
reads keyring->user->uid under keyring_name_lock, but that lock protects
the keyring's name entry and allocation, not its separate key_user.
A named session-keyring join can overlap a privileged KEYCTL_CHOWN on
another CPU. If the keyring holds the last reference to its old dynamic
key_user and the ownership transfer succeeds, the following ordering is
possible:
Named join Chown
find_keyring_by_name() keyctl_chown_key()
read_lock(keyring_name_lock) down_write(key->sem)
load old keyring->user
replace key->user and key->uid
up_write(key->sem)
key_put(key)
key_user_put(old user): free
read old user->uid
read_unlock(keyring_name_lock)
Chown neither takes keyring_name_lock nor key_session_mutex, so it can
free the old account between the pointer load and the UID read. The
lookup then reads freed memory even though the keyring itself is alive.
Use keyring->uid for the mapping check. key_alloc() initializes this
inline owner UID and keyctl_chown_key() updates it on chown.
The existing name lock keeps its containing keyring allocated throughout
the check, so lookup no longer depends on the account's lifetime. This
also matches the owner UID used by the permission check.
KASAN report as below:
BUG: KASAN: slab-use-after-free in find_keyring_by_name+0x577/0x5d0
Read of size 4 at addr ffff8881128ae2ec by task keycase/500
Cc: stable@vger.kernel.org
Fixes: 2ea190d0a0 ("keys: skip keys from another user namespace")
Assisted-by: LLM
Signed-off-by: Cen Zhang <zzzccc427@gmail.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Link: https://lore.kernel.org/r/pm-key-management-objects-candidate-0002-v3-2baa8cad2bb554364e10@gmail.com
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
keyctl_describe_key() must keep the key type's name alive until
kasprintf() has consumed it. The retained key reference keeps the key
and its description alive, but does not pin the module providing its
type. The name is passed to kasprintf() without holding key->sem.
kvasprintf() uses the saved name pointer in two formatting passes, with
a GFP_KERNEL allocation between them. With AF_RXRPC=m, a task that
passes View permission before type retirement can overlap a privileged
module unload in this order:
1. KEYCTL_DESCRIBE looks up the key, saves key->type->name in the
kasprintf() arguments and completes the first formatting pass.
2. While the formatter is delayed before its second pass,
af_rxrpc_exit() calls unregister_key_type(), which removes the type
from the registry and waits for key_gc_keytype().
3. The collector takes key->sem for writing, retypes the retained key
to key_type_dead and completes retirement. Unregistration and module
exit return, allowing free_module() to release the type and name.
4. The formatter resumes its second pass and reads the saved name from
released module storage, which can fault in string().
Hold key->sem for reading across kasprintf(). The collector then cannot
retype the key or complete retirement until both formatting passes have
finished. If retirement wins the lock first, formatting uses the core
key_type_dead name instead. Release the semaphore immediately after
kasprintf(), including on allocation failure, before copying to
userspace.
Oops report as below:
BUG: unable to handle page fault for address: fffffbfff8054794
#PF: supervisor read access in kernel mode
#PF: error_code(0x0000) - not-present page
RIP: 0010:string+0x23f/0x470
Call Trace:
vsnprintf+0x330/0x1110
Cc: stable@vger.kernel.org
Fixes: aa9d443789 ("KEYS: Fix the size of the key description passed to/from userspace")
Assisted-by: LLM
Signed-off-by: Cen Zhang <zzzccc427@gmail.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Link: https://lore.kernel.org/r/pm-key-management-objects-candidate-0009-v4-6b537c5732fd957c33fa@gmail.com
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Without this fix, release_inode() (task 1) can race with a umount
operation in hook_sb_delete() (task 2). The order of operations in
which the race occurs is:
* task 2: hook_sb_delete() arrives at the end of the function, waiting
for landlock_superblock(sb)->inode_refs to become zero.
* task 1: release_inode(): does atomic_long_dec_and_test(), decrementing
inode_refs to zero.
* task 2: gets woken up through some other means, sees that inode_refs
is zero and returns. The caller is the unmount operation and proceeds
to release the superblock.
* task 1: Runs wake_up_var(&landlock_superblock(sb)->inode_refs),
*dereferencing the sb_security on the freed-up superblock*.
Notably, wake_up_var() does not dereference the pointer passed to it,
and only uses it to determine an overapproximated set of tasks to wake
up. So while it's potentially possible for an attacker to provide a
different value for that pointer, this only results in the wrong set of
tasks getting woken up, and in this scenario, no further tasks are
actually waiting.
Nevertheless, KASAN detects it as a slab-use-after-free read on
sb->s_security:
BUG: KASAN: slab-use-after-free in release_inode+0x196/0x290
Read of size 8 at addr ffff888103b6c0a8 by task repro/217
release_inode+0x196/0x290
landlock_put_object+0x71/0x90
landlock_free_rules+0x38/0xc0
landlock_put_ruleset+0x47/0x130
fop_ruleset_release+0x33/0x40
__fput+0x305/0x780
Freed by task 54:
kfree+0x11c/0x390
process_scheduled_works+0x766/0xe50
worker_thread+0x7bc/0xb20
The fix is to determine &landlock_superblock(inode->i_sb)->inode_refs only once
earlier in release_inode(), and later use that precalculated address for the
wake_up_var() call, without having to dereference through the superblock.
Cc: stable@vger.kernel.org
Fixes: cb2c7d1a17 ("landlock: Support filesystem access-control")
Assisted-by: LLM
Signed-off-by: Günther Noack <gnoack@google.com>
Link: https://patch.msgid.link/20261006105847.2541190-1-gnoack@google.com
Signed-off-by: Mickaël Salaün <mic@digikod.net>
Add Landlock enforcement for capability use via the LSM capable hook.
This lets a sandboxed process restrict which Linux capabilities it can
exercise, using LANDLOCK_PERMISSION_CAPABILITY_USE and per-capability
rules.
The check is a flat per-layer allowed-capabilities test, with no
domain-ancestry bypass, no cross-namespace discriminant, and no
dependency on the target user namespace. These categorical denials
return -EPERM, like the namespace permission introduced by the previous
commit, and they mirror its per-capability allowed and quiet masks, so
LANDLOCK_ADD_RULE_QUIET stays rejected for this rule type. Successful
capability rules and denials are traced as the previous commit
describes.
Enforce only at capability exercise time rather than modifying the
credential's capability sets. Modifying them would give capget(2) an
accurate view of usable capabilities, but no LSM other than commoncap
does so; Landlock follows that convention. A sandboxed process inside a
user namespace therefore sees all capabilities via capget(2) but
receives -EPERM when attempting to use one that is denied.
An earlier design bypassed this hook for namespace management through a
domain-ancestry comparison with the namespace creator's stored Landlock
domain. That made a Landlock decision depend on kernel namespace state,
and the ns != cred->user_ns heuristic did not accurately identify
namespace-management operations. The flat, namespace-agnostic check
instead enforces capability and namespace restrictions independently;
creating a non-user namespace requires an allowed CAP_SYS_ADMIN even
when combined with CLONE_NEWUSER in one unshare().
Cc: Christian Brauner <brauner@kernel.org>
Cc: Günther Noack <gnoack@google.com>
Cc: Paul Moore <paul@paul-moore.com>
Cc: Serge E. Hallyn <serge@hallyn.com>
Link: https://patch.msgid.link/20261014082718.1435842-5-mic@digikod.net
Signed-off-by: Mickaël Salaün <mic@digikod.net>
Add Landlock enforcement for namespace use through the LSM
namespace_init and namespace_install hooks. This lets a sandboxed
process restrict which namespace types it can create, join, or acquire a
file descriptor for, using LANDLOCK_PERMISSION_NAMESPACE_USE and
per-type rules.
Introduce the handled_permissions field in struct landlock_ruleset_attr:
each permission gates every use of a kernel-defined category (CLONE_NEW*
namespace types, CAP_* capabilities) with complete deny-by-default
coverage, so unknown member values need no validation, being denied
until a rule allows them. This UAPI extension advances the Landlock ABI
from 11 to 12.
There is no domain-ancestry bypass and no namespace-creator tracking,
only a flat per-layer allowed-types bitmask: hook_namespace_init()
covers creation through clone(2), unshare(2), open_tree(2) and
fsmount(2), and hook_namespace_install() covers setns(2). Each
permission hook maps its member mask explicitly in the shared permission
walker, which warns and denies if a future caller omits that mapping.
These categorical denials return -EPERM, matching Landlock's scope and
mount-topology denials rather than its object-access -EACCES convention.
struct permission_masks is forced to eight bytes with __packed and
__aligned because it must eventually hold both the eight namespace types
and all capabilities, and because m68k GCC otherwise packs its u64
bitfields at byte granularity, making the structure smaller than
sizeof(u64). Carrying it grows struct layer_config from 4 to 16 bytes,
so the largest 16-entry domain FAM grows from 64 to 256 bytes.
The permissions selector keeps the rule attribute self-describing:
- User space can mask it against handled_permissions, as it masks
allowed_access against handled_access_fs, so a program built against
newer headers still adds the rules an older kernel supports.
- It tells apart two attributes that share the same three-u64 layout.
Unknown member bits are ignored, so without it a mismatched rule type
would apply a capability mask as namespace types.
- It leaves room for a rule to carry several permissions, or for another
rule type to key the same permission differently.
The rule also carries a quiet_namespace_types bitmask that suppresses
audit submission for denied members without granting them. A sandbox
knowingly running a caller that probes a type it will never be granted
would otherwise flood the audit log and drown the surprising denials
that matter. Quiet is per-member rather than a coarse per-category
ruleset bit, so a sandbox can silence CLONE_NEWNET while still auditing
CLONE_NEWUTS; making it the complement of the allowed set would be
broad, could not audit a member that is neither allowed nor explicitly
quieted, and would auto-hide members added by future kernels. It is a
per-rule bitmask rather than the LANDLOCK_ADD_RULE_QUIET flag and the
ruleset quiet_access_* masks, which suit the unbounded rb-tree objects
of filesystem and network rules, so that flag is rejected here. Only
the youngest denying layer's quiet mask decides, so a parent cannot
silence a denial made by a deeper layer.
Trace the handled permission mask, every successful namespace rule, and
namespace denials. Successful effective no-ops advance the version, and
quiet denials remain trace-visible with logged=0. The denial event
takes the blockers argument of the filesystem and network events and
records the same blockers_type and blockers_access fields, so one filter
expression spans the mask-bearing denial events. Handled and rule
permission masks may contain permissions from multiple domains in one
field, so their names are domain-qualified, such as namespace.use. A
blocker is already interpreted in the domain supplied by the audit
prefix or denial event, so it retains the bare action name use, matching
existing access blockers such as read_file.
User namespace creation does not require capabilities, so Landlock can
restrict it directly. Non-user namespace types require CAP_SYS_ADMIN
before the Landlock check is reached; when the capability permission
added by the next commit is also handled, both must allow the operation.
Cc: Christian Brauner <brauner@kernel.org>
Cc: Günther Noack <gnoack@google.com>
Cc: Paul Moore <paul@paul-moore.com>
Cc: Serge E. Hallyn <serge@hallyn.com>
Link: https://patch.msgid.link/20261014082718.1435842-4-mic@digikod.net
Signed-off-by: Mickaël Salaün <mic@digikod.net>
The domain layer FAM stores struct access_masks values directly, while a
ruleset stores the equivalent single mutable value. Per-category
permissions need additional per-layer data beyond the handled-access
bitfields.
Introduce struct layer_config as the common value type. Keeping the
handled bitfields in its .handled member leaves struct access_masks as a
lightweight parameter type for functions that only need those bitfields,
while the complete layer can be snapshotted with one assignment.
At this point struct layer_config only wraps the four-byte access_masks,
so it does not grow the per-domain allocation: the maximum 16-entry FAM
remains 64 bytes.
No functional change.
Cc: Günther Noack <gnoack@google.com>
Reviewed-by: Günther Noack <gnoack@google.com>
Reviewed-by: Tingmao Wang <m@maowtm.org>
Link: https://patch.msgid.link/20261014082718.1435842-3-mic@digikod.net
Signed-off-by: Mickaël Salaün <mic@digikod.net>
The base stores the fs/net/scope quiet bitmasks in a struct access_masks
field named quiet_masks. A following commit adds the sibling struct
permission_masks field quiet_permission for capabilities and namespaces.
quiet_masks drops the access category and keeps the type half ("masks"),
while quiet_permission keeps the category and drops the type half, so
the two read as an inconsistent pair.
Rename the base field to quiet_access, giving the symmetric,
category-named pair quiet_access/quiet_permission that also matches the
UAPI handled_access_*/quiet_access_* naming. This is a
no-functional-change rename.
Cc: Günther Noack <gnoack@google.com>
Cc: Tingmao Wang <m@maowtm.org>
Reviewed-by: Tingmao Wang <m@maowtm.org>
Reviewed-by: Günther Noack <gnoack3000@gmail.com>
Link: https://patch.msgid.link/20261014082718.1435842-2-mic@digikod.net
Signed-off-by: Mickaël Salaün <mic@digikod.net>
Pull vfs idmap constification from Christian Brauner:
"This makes struct mnt_idmap const throughout the tree.
A mount's idmapping is immutable. The only thing modified after
alloc_mnt_idmap() is the reference count and that is hidden behind
mnt_idmap_get() and mnt_idmap_put(). Everything else only reads from
it. That is the same model struct cred uses and the idmapping is
sensitive enough to deserve it.
The conversion goes bottom up through the vfs{g,u}id and fs{g,u}id
helpers, the privilege checks, acl, xattr and quota and then every
inode operation that takes an idmap, so ->permission(), ->getattr(),
->setattr(), ->create(), ->mkdir(), ->mknod(), ->symlink(),
->rename(), ->tmpfile(), ->get_acl(), ->set_acl() and ->fileattr_set()
with their implementations in every filesystem, plus the LSM hooks.
struct vfsmount, struct mount_kattr and struct kstatmount store a
const pointer and nop_mnt_idmap and invalid_mnt_idmap live in rodata,
so anything that tries to modify them faults instead of silently
corrupting the initial idmapping"
* tag 'vfs-7.4-rc1.idmap' of git://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs: (27 commits)
fs: make nop_mnt_idmap and invalid_mnt_idmap const
fs: port mnt_idmap() and file_mnt_idmap() to const mnt_idmap
fs: port vfs_*() helpers to const mnt_idmap
fs: port ->setattr() to pass const mnt_idmap
fs: port ->getattr() to pass const mnt_idmap
fs: port ->create() to pass const mnt_idmap
fs: port ->symlink() to pass const mnt_idmap
fs: port ->mkdir() to pass const mnt_idmap
fs: port ->rename() to pass const mnt_idmap
fs: port ->mknod() to pass const mnt_idmap
fs: port ->tmpfile() to pass const mnt_idmap
fs: port ->get_acl() to pass const mnt_idmap
fs: port ->set_acl() to pass const mnt_idmap
fs: port ->fileattr_set() to pass const mnt_idmap
fs: port xattr to const mnt_idmap
fs: port ->permission() to pass const mnt_idmap
fs: port acl to const mnt_idmap
fs: port inode_init_owner() to const mnt_idmap
fs: port inode_owner_or_capable() to const mnt_idmap
fs: port privilege checking helpers to const mnt_idmap
...
ipe_audit_enforce() starts an audit buffer but writes the state change
with audit_log(), which logs its own record. Ending the unused buffer
then emits an extra empty AUDIT_MAC_STATUS record.
Remove the unused buffer and log the state change with audit_log()
alone.
Fixes: a68916eaed ("ipe: add permissive toggle")
Assisted-by: LLM
Signed-off-by: Fan Wu <wufan@kernel.org>
Policy text is separately allocated only when p->pkcs7 is NULL.
Correct the comment to match the existing free logic.
No functional changes.
Assisted-by: LLM
Signed-off-by: Fan Wu <wufan@kernel.org>
The parser token tables contain one entry for each enum value followed
by a terminator. Add static assertions so adding an enum value without a
corresponding token fails the build.
Assisted-by: LLM
Signed-off-by: Fan Wu <wufan@kernel.org>
The audit name tables are indexed by enum values but initialized
positionally. Adding an enum value in the middle can associate the
following names with the wrong values.
Use designated initializers to bind each name to its enum value.
No functional changes.
Assisted-by: LLM
Signed-off-by: Fan Wu <wufan@kernel.org>
tpm2_key_decode() allocates 4 bytes more than needed. The ASN.1
callbacks tpm2_key_priv() and tpm2_key_pub() provide the lengths
of TPM2B_PRIVATE and TPM2B_PUBLIC, so ctx.priv_len and ctx.pub_len
already account for the 2-byte `size` field each of those structures
starts with.
I noticed this while reviewing commit 114f00d738 ("KEYS: trusted:
Fix tpm2_load_cmd() boundary check"), which correctly reports
ctx.priv_len + ctx.pub_len as the decoded blob size [1].
Let's allocate exactly that amount, matching the data copied into
the blob.
[1] https://lore.kernel.org/linux-integrity/apfoKo-BdwaLXtkT@sgarzare-redhat/
Cc: stable@vger.kernel.org # v5.13+
Fixes: f221974525 ("security: keys: trusted: use ASN.1 TPM2 key format for the blobs")
Signed-off-by: Stefano Garzarella <sgarzare@redhat.com>
Link: https://lore.kernel.org/r/20260923173506.41519-1-sgarzare@redhat.com
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Manual merge fixup in ns_common_types.h:ns_common to work around a conflict
with the nsfs RCU grace period fix.
* lsm/dev:
lsm: remove redundant NULL check in security_init()
selftests/landlock: Check full ioctl commands in audit records
lsm: Preserve full ioctl commands in audit records
doc: fix LSM ordering description for /sys/kernel/security/lsm
doc: describe CONFIG_LSM and lsm= as the selection mechanism
selftests/bpf: verify mount idmaps reach inode hooks
lsm: expose mount idmaps to inode hooks
rust: lsm: replace `core::mem::zeroed` with `pin_init::zeroed`
cred: prevent slab cache merging for cred_jar
lsm: don't call security_backing_file_free() multiple times
lsm: delete duplicate assignment in lsm_prepare()
lsm: update the BUILD_BUG_ON() in audit_log_lsm_data()
lsm: add LSM_AUDIT_DATA_NS for namespace audit records
lsm: add LSM blob and hooks for namespaces
ns: Free anonymous mount namespaces via ns_common_free()
cred: clarify that task_struct::cred is only for the current task
ima_restore_measurement_list() parses the measurement list persisted across
kexec. It computes the parse end directly from the blob:
bufendp = buf + khdr->buffer_size;
khdr->buffer_size is a u64 read straight from the persisted buffer. The
only length checks in the function are size >= sizeof(*khdr), version == 1
and count -- none relates buffer_size to size, the actual buffer size the
caller (ima_load_kexec_buffer()) obtained from the ima-kexec-buffer region.
ima_parse_buf() bounds every field read to bufendp, so a blob whose
internal buffer_size exceeds the real size makes the parse loop read past
the end of the buffer (CWE-125).
The buffer's memory range is validated against addressable RAM by
commit cbf9c4b961 ("of: check previous kernel's ima-kexec-buffer
against memory bounds") and commit c5489d0433 ("x86/kexec: add a
sanity check on previous kernel's ima kexec buffer"), but the blob's
own declared size is never clamped to it. Reject a buffer_size larger
than size before the loop.
This is on the boot-time kexec-restore path (__init) and the buffer comes
from the previous kernel, so triggering it requires control of the
persisted buffer; it is an out-of-bounds read only.
Fixes: 94c3aac567 ("ima: on soft reboot, restore the measurement list")
Assisted-by: copilot-cli:claude-opus-4-6 frama-c
Signed-off-by: Fabrice Derepas <fabrice.derepas@canonical.com>
Signed-off-by: Mimi Zohar <zohar@linux.ibm.com>
When recovering the IMA measurement list after kexec(), currently, the
counter of violations is not restored. This causes a mismatch between
the real number of violations and the value reported by the
<securityfs>/ima/violations file.
Restore the violations counter during the IMA measurement list recovery.
This mechanism does not take into account false positives. A legit
all-zeros hash is treated as a violation.
Reported-by: Roberto Sassu <roberto.sassu@huawei.com>
Closes: https://github.com/linux-integrity/linux/issues/13
Signed-off-by: Enrico Bravi <enrico.bravi@polito.it>
Reviewed-and-tested-by: Roberto Sassu <roberto.sassu@huawei.com>
[zohar@linux.ibm.com: Fixed patch description line length]
Signed-off-by: Mimi Zohar <zohar@linux.ibm.com>
Pull Landlock fix from Mickaël Salaün:
"This fixes a Clang bug by removing an annotation, which was introduced
mostly for documentation"
* tag 'landlock-7.3-rc7' of git://git.kernel.org/pub/scm/linux/kernel/git/mic/linux:
landlock: Drop __counted_by from landlock_domain.handled_masks
With clang 22 and CONFIG_FORTIFY_SOURCE, the second
landlock_restrict_self() call hits a bogus fortify report in
inherit_ruleset():
memcpy: detected buffer overflow: 4 byte write of buffer size 0
Call Trace:
__fortify_panic
landlock_merge_ruleset
__se_sys_landlock_restrict_self
handled_masks[] lives in an anonymous struct inside the anonymous union
that overlays work_free. For such a flexible array, clang computes the
address of the __counted_by counter as the start of the array instead of
&num_layers. The bound is then read from handled_masks[0], i.e. from
the first layer's access masks, which is not a count. The same layout
crashes clang itself in a standalone test.
The annotation was added as documentation, so drop it rather than
restructure the union. Keep the information in the member comment.
Reported-by: syzbot+a0eecb22de4d821a9e5d@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=a0eecb22de4d821a9e5d
Fixes: bd3a19800d ("landlock: Add counted_by in landlock_domain")
Signed-off-by: Nguyen Ngoc Thang <ngocthang2710.1999@gmail.com>
Link: https://lore.kernel.org/r/20261010164450.194439-1-ngocthang2710.1999@gmail.com
Reviewed-by: Günther Noack <gnoack3000@gmail.com>
Reported-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com>
Reported-by: Mike Bommarito <michael.bommarito@gmail.com>
Closes: https://lore.kernel.org/r/20261009115108.17819-1-michael.bommarito@gmail.com
[mic: Rebased on master, where the array is handled_masks[], updated the
fortify report, added the clang bug link and the other reports]
Signed-off-by: Mickaël Salaün <mic@digikod.net>
Pull keys fixes from Jarkko Sakkinen:
- key_get_persistent() created a new persistent keyring if one did not
exist, but failed to set a timeout on it in an error path, preventing
GC.
Call key_set_timeout() regardless of key_link() result if a
persistent keyring was created.
- __key_create_or_update() made a copy of keyring->restrict_link before
holding keyring->sem, which could cause add_key() to be executed
against stale keyring restrictions. Fix it by copying the value only
after taking keyring->sem
* tag 'keys-v7.3-rc7' of git://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd:
KEYS: Fix add_key() race with keyring restriction
keys: finalize persistent keyring timeout after link attempt
Pull selinux fixes from Paul Moore:
- Preserve SECURITY_LSM_NATIVE_LABELS when reusing superblocks
Similar to a previous fix (see the commit description of Stephen's
fix) we need to check to see if we have already mounted/setup the
superblock passed into the security_sb_set_mnt_opts() LSM hook so we
don't mistakenly unset SECURITY_LSM_NATIVE_LABELS.
- Fix a potential AVC sequence number data race
* tag 'selinux-pr-20261005' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux:
selinux: preserve NATIVE_LABELS on already-initialized sb in set_mnt_opts
selinux: fix data race on AVC latest_notif
__key_create_or_update() snapshots keyring->restrict_link before taking
the destination keyring's semaphore. keyring_restrict() installs a
restriction while holding that semaphore.
This allows a writer to observe no restriction, wait for the keyring
owner to install a reject-all restriction and return successfully, and
then link a key using the stale NULL snapshot. The writer only needs
write permission on the destination keyring.
Move the restrict_link read after __key_link_lock() and
__key_link_begin(). The read and the subsequent restriction check are
then serialized with restriction installation by keyring->sem.
The race was reproduced on v7.2.8 in 19 executions where restriction
installation returned before the link completed. All 19 linked the key
despite the reject-all restriction. With this change, 312 executions
reached the same ordering and every add_key() call failed with -EPERM.
The issue was found by manual concurrency analysis assisted by AI-based
analysis and independently verified with a QEMU reproducer and kernel
instrumentation.
Fixes: 5ac7eace2d ("KEYS: Add a facility to restrict new links into a keyring")
Cc: stable@vger.kernel.org
Signed-off-by: 성병찬 <tjdqudcks0424@naver.com>
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Link: https://lore.kernel.org/r/20260930041802.6114-1-tjdqudcks0424@naver.com
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
When no keyring exists for the requested UID, KEYCTL_GET_PERSISTENT
creates and registers one before linking it to the requested destination.
The configured timeout is set only after the destination link succeeds.
A destination restricted with KEYCTL_RESTRICT_KEYRING makes that link fail
with -EPERM. With persistent_keyring_expiry set to 60 seconds, /proc/keys
still reports the registered keyring's expiry as "perm".
The failed call therefore leaves a quota-exempt keyring in the namespace's
hidden register, where it may remain until namespace teardown.
Rename the write-locked helper to key_get_or_create_persistent() and return
the key reference through a result parameter. Return 0 when it creates a
keyring and 1 when the retry finds an existing one. Return a negative error
on failure. Another caller may create the keyring between the initial
read-locked lookup and the retry under the write lock.
Set the timeout after permission checking and linking. Do this on success,
or on failure if the call allocated the keyring. This leaves a new keyring
collectible after failure without starting its timeout while linking is
still in progress.
Cc: stable@vger.kernel.org # v5.10+
Fixes: f36f8c75ae ("KEYS: Add per-user_namespace registers for persistent per-UID kerberos caches")
Assisted-by: LLM
Signed-off-by: Karl Mehltretter <kmehltretter@gmail.com>
Link: https://lore.kernel.org/r/20260912095440.79864-1-kmehltretter@gmail.com
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Cross-merge BPF and other fixes after downstream PR.
Conflicts:
arch/arm64/net/bpf_jit_comp.c
arch/x86/net/bpf_jit_comp.c
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
The permissive and neveraudit maps are read as ebitmaps and indexed by
type value, but their set bits are never checked. A bit that is not a
defined, non-attribute type is silently accepted. Validate every set bit
of both maps in policydb_index() with policydb_simpletype_isvalid().
Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>
user_read() reads each user's MLS range and default level but, unlike
range transitions and security contexts, never validates them.
Validate usr->range and usr->dfltlevel in user_index_check() when MLS is
enabled, once the level and category symbol tables are populated.
Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>
role->dominates, role->types and user->roles are read as ebitmaps but
their set bits are never checked against the role and type symbol
tables. A bit naming an undefined value is silently accepted, and an
out-of-range one is used to index those tables later; in particular
role_bounds_sanity_check() passes such a bit straight to sym_name(),
reading p->sym_val_to_name[] out of bounds on a crafted bounded role.
Validate the three bitmaps in policydb_index() once every symbol table
is populated (roles are read before types, so this cannot be done in
role_read()).
Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>
When an NFSv4 filesystem exported with security_label is mounted a
second time, sget_fc() returns the existing superblock and
nfs_get_root() calls security_sb_set_mnt_opts() again on it. Since the
superblock is already SB_INITIALIZED, selinux_set_mnt_opts() takes an
early exit without setting SECURITY_LSM_NATIVE_LABELS in
*set_kern_flags. nfs_get_root() then sees kflags without
SECURITY_LSM_NATIVE_LABELS set and clears NFS_CAP_SECURITY_LABEL on
the shared nfs_server, silently disabling per-file labeling for both
the new and the original mount.
Commit 3815a245b5 ("security/selinux: fix SECURITY_LSM_NATIVE_LABELS
on reused superblock") fixed the same problem in
selinux_sb_clone_mnt_opts(). The reused-superblock path for a plain
second mount now goes through sb_set_mnt_opts rather than
sb_clone_mnt_opts, so it needs the same treatment: on both
SE_SBINITIALIZED early exits, set SECURITY_LSM_NATIVE_LABELS in
*set_kern_flags when the superblock was already using
SECURITY_FS_USE_NATVE.
Cc: stable@vger.kernel.org
Closes: https://github.com/SELinuxProject/selinux-kernel/issues/69
Closes: https://github.com/SELinuxProject/selinux-kernel/issues/70
Closes: https://github.com/SELinuxProject/selinux-testsuite/issues/91
Closes: https://github.com/SELinuxProject/selinux-testsuite/issues/92
Fixes: eb9ae68650 ("SELinux: Add new labeling type native labels")
Signed-off-by: Stephen Smalley <stephen.smalley.work@gmail.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>
Since commit 5137e583ba ("lsm: cleanup the debug and console output
in lsm_init.c"), the NULL check for lsm_order_legacy in security_init()
has no effect.
So remove the check.
No functional change.
Signed-off-by: Sang-Heon Jeon <ekffu200098@gmail.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>