| 0/0 |
2026/07/06 21:48 |
flow |
assessment-kcsan |
1h19m
Results: map[Benign:true Explanation:The KCSAN data race report shows a conflict between `init_file` (via `get_cred`)
and `prepare_creds` on a `struct cred` object.
### Race Summary
- **Function A (Writer):** `init_file` calls `get_cred`, which eventually calls
`get_cred_many`. This function performs an in-place modification of the
`non_rcu` field (setting it to `0`) and increments the `usage` reference count.
- **Function B (Reader):** `prepare_creds` performs a `memcpy` of the entire
`struct cred` from an existing one (`old`) to a newly allocated one (`new`).
- **Variable:** The `non_rcu` field (offset `0xa8` or 168 bytes) and potentially
the `usage` field of `struct cred`.
### Synchronization Context
The race occurs between two different tasks (e.g., two threads of the same
process or a parent and child) that share the same `struct cred` object. While
`struct cred` is generally immutable once committed to a task, the `usage`
(refcount) and `non_rcu` (RCU optimization flag) fields are modified in-place.
There is no mutual exclusion (like a lock) between a thread taking a new
reference to the shared cred and another thread preparing a new set of
credentials based on it.
### Final Classification: **BENIGN**
### Reasoning
The race is structurally tolerant to stale or torn reads for the following
reasons:
1. **Overwritten Values:** In `prepare_creds`, immediately after the
`memcpy(new, old, sizeof(struct cred))`, the code explicitly initializes the
racing fields in the new copy:
```c
new->non_rcu = 0;
atomic_long_set(&new->usage, 1);
```
Any value (stale, torn, or otherwise) copied from the `old` structure for
these two fields is immediately discarded and never used.
2. **Immutability of Other Fields:** All other fields in `struct cred` (UIDs,
GIDs, capabilities, etc.) are immutable once the credential set is committed and
shared. Therefore, the `memcpy` is guaranteed to see a consistent state for all
fields that actually matter for the new credential set.
3. **Safe Overwrite of `non_rcu`:** The `non_rcu` flag is only set to `1` for
temporary, private subjective credentials (e.g., during an `access()` syscall).
Once a credential is shared (which happens during `fork` or when another thread
takes a reference), `non_rcu` is cleared to `0`. For any shared credential,
`non_rcu` is already `0`, so the write in `get_cred_many` is typically a "safe
overwrite" of the same value.
4. **Reference Integrity:** The `old` credential's lifecycle is safe because
the caller of `prepare_creds` holds a reference to it, and `get_cred` is
incrementing the reference count, not decrementing it.
### Recommended Annotations
To silence the KCSAN warning, the assignment to `non_rcu` in `get_cred_many`
could be wrapped in `data_race()` or converted to `WRITE_ONCE()`, although the
race is fundamentally harmless.
```c
/* include/linux/cred.h */
static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
{
...
data_race(nonconst_cred->non_rcu = 0);
atomic_long_add(nr, &nonconst_cred->usage);
...
}
```]
|
| 1/1 |
2026/07/06 21:48 |
action |
kernel-checkouter |
1m
Results: map[KernelSrc:/app/workdir/cache/src/701875ef0e9c78f3d8fc99156d1c63fef0f5f93a]
|
| 2/1 |
2026/07/06 21:50 |
action |
kernel-builder |
9m
Results: map[KernelObj:/app/workdir/cache/build/2d54f5b61527fafe1a608a60c88d03410c7c664e]
|
| 3/1 |
2026/07/06 21:59 |
action |
codesearch-prepare |
7m
Results: map[Index:codesearch-index]
|
| 4/1 |
2026/07/06 22:07 |
agent |
expert |
1h01m
Model:
Results:
Instruction: # KCSAN Data Race Severity Analysis Protocol
You are an expert Linux kernel concurrency engineer analyzing a Kernel
Concurrency Sanitizer (KCSAN) data race report to determine if it is
**BENIGN** or **HARMFUL**.
## 1. CLASSIFICATIONS
### **BENIGN (Truly Benign)**
The logic is sound and structurally tolerant to compiler optimizations or
stale/torn reads.
- **Diagnostics/Stats:** Reads used only for `/proc`, `/sys`, counters, or
`pr_info`.
- **Heuristic Hints:** A "hint" flag where an old value only causes a
slightly delayed update or a sub-optimal but safe fast-path.
- **Single-Writer Flag Updates:** A single writer updating flags where the
concurrent read is a simple bitwise check (e.g., `flags & MASK`). These are
historically tolerated, assuming neither "Fused Accesses" nor "Ordering
Violations" are relevant in this context.
- **Marked Reloads:** A load feeding into a `cmpxchg()` loop or checked
against a later `READ_ONCE()` reload.
- **Safe Overwrites:** Writing the same value already present.
### **HARMFUL (Logic Bug or Marking Required)**
The race causes incorrect behavior due to a synchronization failure or
because missing annotations allow the compiler to break the algorithm.
**Marking Required for Correctness:**
The algorithm is logically sound but requires annotations (`READ_ONCE()`,
`WRITE_ONCE()`, `smp_load_acquire()`, `smp_store_release()`, etc.) to be safe.
- **Fused Accesses:** The compiler might merge accesses or hoist a load out
of a loop, breaking polling/wait loops (livelocks).
- **Torn Accesses:** A large access (e.g., 64-bit on 32-bit arch) might be
split into multiple non-atomic accesses. Note that `READ_ONCE()` does **not**
guarantee atomicity for 64-bit variables on 32-bit architectures.
- **Ordering Violations:** The race breaks a "happens-before" relationship
(requires primitives with implied or explicit memory barriers).
**Logic Bugs:**
A fundamental synchronization failure. Marking accesses will **not** fix it;
the logic itself must change.
- **Pointers/Lifecycle:** The racing variable is a pointer being dereferenced
or a refcount governing object lifecycle (Use-After-Free risk).
- **Control Flow:** The variable guards a critical section, memory allocation,
or hardware command.
- **Bitfields:** Concurrent writes to different bits in the same word.
Compilers often use non-atomic read-modify-write sequences, meaning a
write to `bit_A` can "clobber" a concurrent write to `bit_B`. However,
do not blindly assume all bitfield accesses are harmful; you must prove
that a concurrent write actually clobbers another in a way that breaks
logic.
- **Complex Structures:** Races on shared lists, trees, or hashmaps.
- **Lossy Updates:** Concurrent plain RMW operations (e.g., `var++`) on
non-diagnostic variables where every increment must be preserved.
- **State Machines:** Races allowing a state machine to bypass transitions
or enter an invalid state.
- **Adjacent Unsynchronized Operations:** Consider races happening at the
same time. For example, if both threads execute `struct->has_elements = true;
list_add(node, &struct->list);`, the race on `has_elements` implies an
adjacent race on `list_head`, which is HARMFUL.
## 2. RESEARCH & ANALYSIS WORKFLOW
1. **Locate the Race:** Find the exact variables and functions in the stack
traces. Do not speculate about hypothetical compiler
behaviors or theoretical dangers (e.g., dismissing something as
"fundamentally unsafe") without tracing the actual data flow to a crash.
2. **Contextualize:** Identify held locks, RCU sections, or interrupt
contexts. Explain why the race is possible (e.g., "Thread A holds `lock`,
but Thread B is a lockless reader").
3. **Data Flow:** Follow the racing variable into its subsequent uses. If
the reader sees a stale or torn value, what branch is taken? Does it lead
to a pointer dereference or `BUG_ON()`? **You must prove harm via this
data flow.**
4. **Failure Sequencing (if HARMFUL):** Construct a two-column execution trace
demonstrating the failure.
*Example format:*
```text
CPU0 CPU1
function_a()
// lockless read
ptr = global_ptr
<PREEMPT>
function_b()
lock(&my_lock)
global_ptr = NULL
unlock(&my_lock)
kfree(ptr)
if (ptr)
*ptr = 1; // -> Use-After-Free!
```
## 3. OUTPUT FORMAT
- **Race Summary:** `[Function A]` vs `[Function B]` on `[Variable/Field]`.
- **Synchronization context:** List held locks and explain the lack of mutual
exclusion.
- **Final Classification:** **BENIGN** or **HARMFUL**.
**If BENIGN:**
- **Reasoning:** Briefly explain why the race is structurally tolerant to stale
or torn reads.
- **Recommended Annotations:** Suggest appropriate annotations (e.g.,
`READ_ONCE()`, `data_race()`).
**If HARMFUL:**
- **Failure Reasoning:** Explain and provide a two-column interleaving showing
exactly how the race leads to a failure such as corruption or kernel crash.
- **Recommended Fix (ONLY if fix is trivial):** Suggest a structural fix (e.g.,
"Hold `mapping->i_pages` lock", "Convert to `atomic_t`") or required memory
ordering annotations (e.g., "Wrap in `READ_ONCE()`", "Use
`smp_load_acquire()`").
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
The data race report is:
==================================================================
BUG: KCSAN: data-race in init_file / prepare_creds
write to 0xffff8881049530a8 of 4 bytes by task 7107 on cpu 1:
get_cred_many include/linux/cred.h:222 [inline]
get_cred include/linux/cred.h:238 [inline]
init_file+0x2d/0x1b0 fs/file_table.c:183
alloc_empty_file+0x85/0x1e0 fs/file_table.c:266
alloc_file fs/file_table.c:396 [inline]
alloc_file_pseudo+0x92/0x120 fs/file_table.c:427
__anon_inode_getfile fs/anon_inodes.c:164 [inline]
anon_inode_getfile+0xa0/0x120 fs/anon_inodes.c:202
__do_sys_perf_event_open kernel/events/core.c:14179 [inline]
__se_sys_perf_event_open+0xbf3/0x1250 kernel/events/core.c:13881
__x64_sys_perf_event_open+0x67/0x80 kernel/events/core.c:13881
x64_sys_call+0x2789/0x3020 arch/x86/include/generated/asm/syscalls_64.h:299
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x136/0x3c0 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
read to 0xffff888104953000 of 184 bytes by task 7106 on cpu 0:
prepare_creds+0x71/0x550 kernel/cred.c:192
__sys_setresgid+0x46c/0x570 kernel/sys.c:849
__do_sys_setresgid kernel/sys.c:874 [inline]
__se_sys_setresgid kernel/sys.c:872 [inline]
__x64_sys_setresgid+0x3f/0x50 kernel/sys.c:872
x64_sys_call+0x2aa1/0x3020 arch/x86/include/generated/asm/syscalls_64.h:120
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x136/0x3c0 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Reported by Kernel Concurrency Sanitizer on:
CPU: 0 UID: 0 PID: 7106 Comm: syz.3.1049 Not tainted syzkaller #0 PREEMPT(lazy)
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 05/09/2026
==================================================================
Reply: The KCSAN data race report shows a conflict between `init_file` (via `get_cred`) and `prepare_creds` on a `struct cred` object.
### Race Summary
- **Function A (Writer):** `init_file` calls `get_cred`, which eventually calls `get_cred_many`. This function performs an in-place modification of the `non_rcu` field (setting it to `0`) and increments the `usage` reference count.
- **Function B (Reader):** `prepare_creds` performs a `memcpy` of the entire `struct cred` from an existing one (`old`) to a newly allocated one (`new`).
- **Variable:** The `non_rcu` field (offset `0xa8` or 168 bytes) and potentially the `usage` field of `struct cred`.
### Synchronization Context
The race occurs between two different tasks (e.g., two threads of the same process or a parent and child) that share the same `struct cred` object. While `struct cred` is generally immutable once committed to a task, the `usage` (refcount) and `non_rcu` (RCU optimization flag) fields are modified in-place. There is no mutual exclusion (like a lock) between a thread taking a new reference to the shared cred and another thread preparing a new set of credentials based on it.
### Final Classification: **BENIGN**
### Reasoning
The race is structurally tolerant to stale or torn reads for the following reasons:
1. **Overwritten Values:** In `prepare_creds`, immediately after the `memcpy(new, old, sizeof(struct cred))`, the code explicitly initializes the racing fields in the new copy:
```c
new->non_rcu = 0;
atomic_long_set(&new->usage, 1);
```
Any value (stale, torn, or otherwise) copied from the `old` structure for these two fields is immediately discarded and never used.
2. **Immutability of Other Fields:** All other fields in `struct cred` (UIDs, GIDs, capabilities, etc.) are immutable once the credential set is committed and shared. Therefore, the `memcpy` is guaranteed to see a consistent state for all fields that actually matter for the new credential set.
3. **Safe Overwrite of `non_rcu`:** The `non_rcu` flag is only set to `1` for temporary, private subjective credentials (e.g., during an `access()` syscall). Once a credential is shared (which happens during `fork` or when another thread takes a reference), `non_rcu` is cleared to `0`. For any shared credential, `non_rcu` is already `0`, so the write in `get_cred_many` is typically a "safe overwrite" of the same value.
4. **Reference Integrity:** The `old` credential's lifecycle is safe because the caller of `prepare_creds` holds a reference to it, and `get_cred` is incrementing the reference count, not decrementing it.
### Recommended Annotations
To silence the KCSAN warning, the assignment to `non_rcu` in `get_cred_many` could be wrapped in `data_race()` or converted to `WRITE_ONCE()`, although the race is fundamentally harmless.
```c
/* include/linux/cred.h */
static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
{
...
data_race(nonconst_cred->non_rcu = 0);
atomic_long_add(nr, &nonconst_cred->usage);
...
}
```
|
| 5/2 |
2026/07/06 22:07 |
llm |
expert |
0m
Model:
Tokens:
input: 5995
output: 107
thoughts: 243
Thoughts: **Analyzing a Kernel Data Race**
Okay, so the KCSAN report just flagged a nasty data race β a write from `init_file` clashing with a read by `prepare_creds`. This needs a closer look, especially since it's touching critical credential-related data.
The report details where it's happening, which is helpful. On the write side, `init_file` is calling `get_cred` and ultimately `get_cred_many`. The write itself is targeting an address β `0xffff8881049530a8`.
On the read side, `prepare_creds` is pulling 184 bytes from `0xffff888104953000`. And since the write address is a specific offset (`0xa8`, or 168 bytes) *into* the read address, it's very likely they are using the same `struct cred` data, and something within that structure is being corrupted. This is more than a simple overlapping access; `init_file` is likely modifying something within the structure that `prepare_creds` is concurrently trying to use.
Let's dive into the code now and see what `init_file` is actually doing in `get_cred` and `get_cred_many`, and then cross-reference how `prepare_creds` accesses the cred struct at the same time. The file and line numbers provided will be key. This is going to be interesting!
|
| 6/2 |
2026/07/06 22:07 |
tool |
codesearch-dir-index |
0m
Args:
Results: map[Files:[aio.c anon_inodes.c attr.c backing-file.c bad_inode.c binfmt_elf.c binfmt_elf_fdpic.c binfmt_flat.c binfmt_misc.c binfmt_script.c bpf_fs_kfuncs.c buffer.c char_dev.c compat_binfmt_elf.c coredump.c d_path.c dax.c dcache.c direct-io.c drop_caches.c eventfd.c eventpoll.c exec.c fcntl.c fhandle.c file.c file_attr.c file_table.c filesystems.c fs-writeback.c fs_context.c fs_dirent.c fs_parser.c fs_pin.c fs_struct.c fserror.c fsopen.c init.c inode.c internal.h ioctl.c kernel_read_file.c libfs.c locks.c mbcache.c mnt_idmapping.c mount.h mpage.c namei.c namespace.c nsfs.c nullfs.c open.c pidfs.c pipe.c pnode.c pnode.h posix_acl.c proc_namespace.c read_write.c readdir.c remap_range.c select.c seq_file.c signalfd.c splice.c stack.c stat.c statfs.c super.c sync.c sysctls.c timerfd.c utimes.c xattr.c] Subdirs:[9p adfs affs afs autofs befs bfs btrfs cachefiles ceph coda configfs cramfs crypto debugfs devpts dlm ecryptfs efivarfs efs erofs exfat exportfs ext2 ext4 f2fs fat freevxfs fuse gfs2 hfs hfsplus hostfs hpfs hugetlbfs iomap isofs jbd2 jffs2 jfs kernfs lockd minix netfs nfs nfs_common nfsd nilfs2 nls notify ntfs ntfs3 ocfs2 omfs openpromfs orangefs overlayfs proc pstore qnx4 qnx6 quota ramfs resctrl romfs smb squashfs sysfs tests tracefs ubifs udf ufs unicode vboxsf verity xfs zonefs]]
|
| 7/2 |
2026/07/06 22:07 |
tool |
codesearch-dir-index |
0m
Args:
Results: map[Files:[acct.c async.c audit.c audit.h audit_fsnotify.c audit_tree.c audit_watch.c auditfilter.c auditsc.c backtracetest.c bounds.c capability.c cfi.c compat.c configs.c context_tracking.c cpu.c cpu_pm.c crash_core.c crash_core_test.c crash_dump_dm_crypt.c crash_reserve.c cred.c delayacct.c dma.c elfcorehdr.c exec_domain.c exec_state.c exit.c exit.h extable.c fail_function.c fork.c freezer.c groups.c hung_task.c iomem.c irq_work.c jump_label.c kallsyms.c kallsyms_internal.h kallsyms_selftest.c kallsyms_selftest.h kcmp.c kcov.c kexec.c kexec_core.c kexec_elf.c kexec_file.c kexec_internal.h kheaders.c kprobes.c kstack_erase.c ksyms_common.c ksysfs.c kthread.c latencytop.c module_signature.c notifier.c nscommon.c nsproxy.c nstree.c padata.c panic.c params.c pid.c pid_namespace.c pid_sysctl.h profile.c ptrace.c range.c reboot.c regset.c relay.c resource.c resource_kunit.c rseq.c scftorture.c scs.c seccomp.c signal.c smp.c smpboot.c smpboot.h softirq.c stacktrace.c static_call.c static_call_inline.c stop_machine.c sys.c sys_ni.c sysctl-test.c sysctl.c task_work.c taskstats.c torture.c tracepoint.c tsacct.c ucount.c uid16.c uid16.h umh.c up.c user-return-notifier.c user.c user_namespace.c utsname.c utsname_sysctl.c vhost_task.c vmcore_info.c watch_queue.c watchdog.c watchdog_buddy.c watchdog_perf.c workqueue.c workqueue_internal.h] Subdirs:[bpf cgroup configs debug dma entry events futex gcov irq kcsan livepatch liveupdate locking module power printk rcu sched time trace unwind]]
|
| 8/2 |
2026/07/06 22:07 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/file_table.c Name:init_file]
Results: map[SourceCode: 179: static int init_file(struct file *f, int flags, const struct cred *cred)
180: {
181: int error;
182:
183: f->f_cred = get_cred(cred);
184: error = security_file_alloc(f);
185: if (unlikely(error)) {
186: put_cred(f->f_cred);
187: return error;
188: }
189:
190: spin_lock_init(&f->f_lock);
191: /*
192: * Note that f_pos_lock is only used for files raising
193: * FMODE_ATOMIC_POS and directories. Other files such as pipes
194: * don't need it and since f_pos_lock is in a union may reuse
195: * the space for other purposes. They are expected to initialize
196: * the respective member when opening the file.
197: */
198: mutex_init(&f->f_pos_lock);
199: memset(&f->__f_path, 0, sizeof(f->f_path));
200: memset(&f->f_ra, 0, sizeof(f->f_ra));
201:
202: f->f_flags = flags;
203: f->f_mode = OPEN_FMODE(flags);
204: /*
205: * Disable permission and pre-content events for all files by default.
206: * They may be enabled later by fsnotify_open_perm_and_set_mode().
207: */
208: file_set_fsnotify_mode(f, FMODE_NONOTIFY_PERM);
209:
210: f->f_op = NULL;
211: f->f_mapping = NULL;
212: f->private_data = NULL;
213: f->f_inode = NULL;
214: f->f_owner = NULL;
215: #ifdef CONFIG_EPOLL
216: f->f_ep = NULL;
217: #endif
218:
219: f->f_iocb_flags = 0;
220: f->f_pos = 0;
221: f->f_wb_err = 0;
222: f->f_sb_err = 0;
223:
224: /*
225: * We're SLAB_TYPESAFE_BY_RCU so initialize f_ref last. While
226: * fget-rcu pattern users need to be able to handle spurious
227: * refcount bumps we should reinitialize the reused file first.
228: */
229: file_ref_init(&f->f_ref, 1);
230: return 0;
231: }
SourceFile:fs/file_table.c]
|
| 9/2 |
2026/07/06 22:07 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:prepare_creds]
Results: map[SourceCode: 165: /**
166: * prepare_creds - Prepare a new set of credentials for modification
167: *
168: * Prepare a new set of task credentials for modification. A task's creds
169: * shouldn't generally be modified directly, therefore this function is used to
170: * prepare a new copy, which the caller then modifies and then commits by
171: * calling commit_creds().
172: *
173: * Preparation involves making a copy of the objective creds for modification.
174: *
175: * Returns a pointer to the new creds-to-be if successful, NULL otherwise.
176: *
177: * Call commit_creds() or abort_creds() to clean up.
178: */
179: struct cred *prepare_creds(void)
180: {
181: struct task_struct *task = current;
182: const struct cred *old;
183: struct cred *new;
184:
185: new = kmem_cache_alloc(cred_jar, GFP_KERNEL);
186: if (!new)
187: return NULL;
188:
189: kdebug("prepare_creds() alloc %p", new);
190:
191: old = task->cred;
192: memcpy(new, old, sizeof(struct cred));
193:
194: new->non_rcu = 0;
195: atomic_long_set(&new->usage, 1);
196: get_group_info(new->group_info);
197: get_uid(new->user);
198: get_user_ns(new->user_ns);
199:
200: #ifdef CONFIG_KEYS
201: key_get(new->session_keyring);
202: key_get(new->process_keyring);
203: key_get(new->thread_keyring);
204: key_get(new->request_key_auth);
205: #endif
206:
207: #ifdef CONFIG_SECURITY
208: new->security = NULL;
209: #endif
210:
211: new->ucounts = get_ucounts(new->ucounts);
212: if (!new->ucounts)
213: goto error;
214:
215: if (security_prepare_creds(new, old, GFP_KERNEL_ACCOUNT) < 0)
216: goto error;
217:
218: return new;
219:
220: error:
221: abort_creds(new);
222: return NULL;
223: }
SourceFile:kernel/cred.c]
|
| 10/2 |
2026/07/06 22:07 |
llm |
expert |
0m
Model:
Tokens:
input: 10346
output: 36
thoughts: 323
Thoughts: **Analyzing a Potential Race Condition**
Okay, so I'm digging into this code and it looks like we have a race condition possibility between `init_file` and `prepare_creds`. I'm focusing on the interaction with credentials (`cred`).
In `init_file` (specifically line 183 of `fs/file_table.c`):
```c
f->f_cred = get_cred(cred);
```
`get_cred(cred)` is called. I know that function increments the reference count of the provided `cred` structure. That's immediately interesting, that implies some form of shared access that is governed by the use count.
Meanwhile, in `prepare_creds`:
```c
old = task->cred;
memcpy(new, old, sizeof(struct cred));
```
The action here is reading `task->cred`, copying it, from the perspective of the `prepare_creds` function it is `old`. This is where the race seems to be.
The write side of this race is happening in `init_file`, specifically the `get_cred` function.
The read is in `prepare_creds`, which is a `memcpy`.
Now, the crucial question: where is the `cred` argument to `init_file` coming from? I need to trace back. Looking at the stack trace I pulled for `init_file`, it seems to be called from `alloc_empty_file`, which in turn gets called from `alloc_file_pseudo`. I need to look into `alloc_empty_file` to understand how `cred` is being handled.
|
| 11/2 |
2026/07/06 22:08 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/file_table.c Name:alloc_empty_file]
Results: map[SourceCode: 233: /* Find an unused file structure and return a pointer to it.
234: * Returns an error pointer if some error happened, e.g., we exceed the file
235: * structures limit, run out of memory or operation is not permitted.
236: *
237: * Be very careful using this. You are responsible for
238: * getting write access to any mount that you might assign
239: * to this filp, if it is opened for write. If this is not
240: * done, the mount's writer count will be wrong
241: * and a warning at __fput() time.
242: */
243: struct file *alloc_empty_file(int flags, const struct cred *cred)
244: {
245: static long old_max;
246: struct file *f;
247: int error;
248:
249: /*
250: * Privileged users can go above max_files
251: */
252: if (unlikely(get_nr_files() >= files_stat.max_files) &&
253: !capable(CAP_SYS_ADMIN)) {
254: /*
255: * percpu_counters are inaccurate. Do an expensive check before
256: * we go and fail.
257: */
258: if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
259: goto over;
260: }
261:
262: f = kmem_cache_alloc(filp_cache, GFP_KERNEL);
263: if (unlikely(!f))
264: return ERR_PTR(-ENOMEM);
265:
266: error = init_file(f, flags, cred);
267: if (unlikely(error)) {
268: kmem_cache_free(filp_cache, f);
269: return ERR_PTR(error);
270: }
271:
272: percpu_counter_inc(&nr_files);
273:
274: return f;
275:
276: over:
277: /* Ran out of filps - report that */
278: if (get_nr_files() > old_max) {
279: pr_info("VFS: file-max limit %lu reached\n", get_max_files());
280: old_max = get_nr_files();
281: }
282: return ERR_PTR(-ENFILE);
283: }
SourceFile:fs/file_table.c]
|
| 12/2 |
2026/07/06 22:08 |
llm |
expert |
0m
Model:
Tokens:
input: 11839
output: 36
thoughts: 8
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**My Perspective on `alloc_file_pseudo`**
Alright, so I'm thinking about `alloc_file_pseudo`. Immediately, my mind jumps to the implications of creating pseudo-filesystems. The whole point, really, is to provide a standardized, manageable interface to some underlying data or functionality that doesn't neatly fit into a regular, on-disk file system paradigm. Think `/proc`, `/sys`, perhaps even some custom virtual file system implementation I've worked with in the past.
The key considerations here revolve around *abstraction* and *performance*. We're abstracting away the specifics of the data source β whether it's kernel data, device registers, or something else entirely β and presenting it as a file. The challenge, of course, is to do this efficiently. I'm immediately running through the potential overhead: the virtual inode creation, the VFS lookups, the data copy/translation layers, the whole I/O path.
I'm considering how this function interacts with the file operations structure. We need to implement `read`, `write`, `open`, `release`, and probably some other operations. Which ones are absolutely necessary? Are we going to support seeking, and if so, how? The data structures we use *within* the pseudo-file will be critical. We can't afford to be sloppy; cache invalidation will be a constant headache. I need to be careful with locking to prevent concurrency issues.
My mind flashes to potential use cases. Can this be easily adapted for something like exposing hardware registers in a user-space friendly way? How would this impact the security considerations? Do we need to worry about malicious users? What protections can we put in place to ensure that operations only happen on trusted data? Are we exposing any hidden kernel secrets? We need to really consider the potential vulnerabilities.
And from an architectural perspective, I'm thinking about scalability. How well will this pseudo-filesystem handle a large number of concurrent accesses? What happens when we have a huge data set exposed through the file? Memory usage becomes a primary concern as well as CPU cycles for data manipulation.
Essentially, I'm trying to mentally map out all the performance, security and concurrency issues that are introduced when providing a file-like abstraction to a non-file based system.
|
| 13/2 |
2026/07/06 22:08 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/file_table.c Name:alloc_file_pseudo]
Results: map[SourceCode: 415: struct file *alloc_file_pseudo(struct inode *inode, struct vfsmount *mnt,
416: const char *name, int flags,
417: const struct file_operations *fops)
418: {
419: int ret;
420: struct path path;
421: struct file *file;
422:
423: ret = alloc_path_pseudo(name, inode, mnt, &path);
424: if (ret)
425: return ERR_PTR(ret);
426:
427: file = alloc_file(&path, flags, fops);
428: if (IS_ERR(file)) {
429: ihold(inode);
430: path_put(&path);
431: return file;
432: }
433: /*
434: * Disable all fsnotify events for pseudo files by default.
435: * They may be enabled by caller with file_set_fsnotify_mode().
436: */
437: file_set_fsnotify_mode(file, FMODE_NONOTIFY);
438: return file;
439: }
SourceFile:fs/file_table.c]
|
| 14/2 |
2026/07/06 22:09 |
llm |
expert |
0m
Model:
Tokens:
input: 12763
output: 34
thoughts: 6
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Diving Deep into File Allocation**
Alright, let's break this down. When I see "alloc_file," my mind immediately jumps into the nitty-gritty of file system internals. I'm thinking about the low-level allocation strategies and how they are orchestrated.
First, I consider the fundamental requirements: How does this specific implementation handle different file sizes? Are we talking about contiguous allocation, linked allocation, indexed allocation, or something more advanced like extent-based allocation? I'm already anticipating the potential trade-offs β the speed of access versus fragmentation issues, particularly on larger file systems. The implications for I/O performance are right at the forefront of my concerns.
Then, the context becomes crucial. What specific file system are we dealing with? Is this an in-memory file system, a disk-based system (and if so, what kind of storage media: SSD, HDD, etc.)? Is it a general-purpose or a specialized file system? The file system type will, of course, drastically influence how and where it makes allocations. What are the metadata structures involved? The inode, the block maps, the directory entries β the details matter! And, critically, how are these allocations synchronized to ensure integrity, especially in the face of crashes or concurrent access? That all becomes paramount to the discussion.
I'm mentally mapping the function's parameters. Size, offset, flags... all of those things immediately make me think about the necessary checks: Do we have enough free space? Do the flags impose any restrictions on the allocation behavior (e.g., whether to allow sparse files, pre-allocation of blocks, etc.)? Are there any security considerations (permissions, ownership) that need to be addressed at this level?
Finally, the error handling and rollback strategy is going to be incredibly important. How robust is the allocation process? If the system crashes mid-allocation, how do we ensure that we don't end up with corrupted metadata or lost data blocks? I'm analyzing the allocation process for potential points of failure. The allocation and deallocation code, the logging, the journaling, and the data block handling are a critical part of the entire code.
|
| 15/2 |
2026/07/06 22:10 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/file_table.c Name:alloc_file]
Results: map[SourceCode: 384: /**
385: * alloc_file - allocate and initialize a 'struct file'
386: *
387: * @path: the (dentry, vfsmount) pair for the new file
388: * @flags: O_... flags with which the new file will be opened
389: * @fop: the 'struct file_operations' for the new file
390: */
391: static struct file *alloc_file(const struct path *path, int flags,
392: const struct file_operations *fop)
393: {
394: struct file *file;
395:
396: file = alloc_empty_file(flags, current_cred());
397: if (!IS_ERR(file))
398: file_init_path(file, path, fop);
399: return file;
400: }
SourceFile:fs/file_table.c]
|
| 16/2 |
2026/07/06 22:10 |
llm |
expert |
0m
Model:
Tokens:
input: 13568
output: 32
thoughts: 540
Thoughts: **Analyzing a Potential Race Condition in Credential Handling**
Okay, so I'm looking at this code and trying to pinpoint a potential race. The `init_file` function is called, and it's grabbing the current credentials using `current_cred()`. Inside `init_file`, line 183 shows that `f->f_cred = get_cred(cred);` is used. This calls `get_cred`, which then calls `get_cred_many`. `get_cred_many` uses `atomic_long_add(nr, &cred->usage)`, which increments the usage count of the credential. This makes perfect sense; we're increasing the reference count.
But then I see `prepare_creds`. This is where it gets interesting, as it appears to do a `memcpy(new, old, sizeof(struct cred))` to copy the credentials. And here is where I think the issue is. `old = task->cred`, so it is looking at the credentials of the task. If the tasks are the same, `old` is the same credential. This is critical.
I see that `init_file` is being called by task 7107, and `prepare_creds` is being called by task 7106. Now, if tasks 7107 and 7106 belong to the *same process* (e.g., are threads), they are sharing the same `cred` structure! This is the core of the issue.
Now, I'm thinking about the sequence: task 7107 calls `get_cred`, increments `current->cred->usage` using `atomic_long_add`, and meanwhile, task 7106 is calling `prepare_creds`, which is copying the *entire* `struct cred` structure using `memcpy`. Since `struct cred` includes the `usage` count, this copy is potentially reading the `usage` count *while* it's being incremented by the other thread. We have a classic race condition scenario. The `memcpy` could either read the `usage` count before the increment happens, after, or even during the atomic update, leading to potential corruption or missed updates. This needs to be carefully investigated.
|
| 17/2 |
2026/07/06 22:10 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/cred.h Name:cred]
Results: map[SourceCode: 92: /*
93: * The security context of a task
94: *
95: * The parts of the context break down into two categories:
96: *
97: * (1) The objective context of a task. These parts are used when some other
98: * task is attempting to affect this one.
99: *
100: * (2) The subjective context. These details are used when the task is acting
101: * upon another object, be that a file, a task, a key or whatever.
102: *
103: * Note that some members of this structure belong to both categories - the
104: * LSM security pointer for instance.
105: *
106: * A task has two security pointers. task->real_cred points to the objective
107: * context that defines that task's actual details. The objective part of this
108: * context is used whenever that task is acted upon.
109: *
110: * task->cred points to the subjective context that defines the details of how
111: * that task is going to act upon another object. This may be overridden
112: * temporarily to point to another security context, but normally points to the
113: * same context as task->real_cred.
114: */
115: struct cred {
116: atomic_long_t usage;
117: kuid_t uid; /* real UID of the task */
118: kgid_t gid; /* real GID of the task */
119: kuid_t suid; /* saved UID of the task */
120: kgid_t sgid; /* saved GID of the task */
121: kuid_t euid; /* effective UID of the task */
122: kgid_t egid; /* effective GID of the task */
123: kuid_t fsuid; /* UID for VFS ops */
124: kgid_t fsgid; /* GID for VFS ops */
125: unsigned securebits; /* SUID-less security management */
126: kernel_cap_t cap_inheritable; /* caps our children can inherit */
127: kernel_cap_t cap_permitted; /* caps we're permitted */
128: kernel_cap_t cap_effective; /* caps we can actually use */
129: kernel_cap_t cap_bset; /* capability bounding set */
130: kernel_cap_t cap_ambient; /* Ambient capability set */
131: #ifdef CONFIG_KEYS
132: unsigned char jit_keyring; /* default keyring to attach requested
133: * keys to */
134: struct key *session_keyring; /* keyring inherited over fork */
135: struct key *process_keyring; /* keyring private to this process */
136: struct key *thread_keyring; /* keyring private to this thread */
137: struct key *request_key_auth; /* assumed request_key authority */
138: #endif
139: #ifdef CONFIG_SECURITY
140: void *security; /* LSM security */
141: #endif
142: struct user_struct *user; /* real user ID subscription */
143: struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
144: struct ucounts *ucounts;
145: struct group_info *group_info; /* supplementary groups for euid/fsgid */
146: /* RCU deletion */
147: union {
148: int non_rcu; /* Can we skip RCU deletion? */
149: struct rcu_head rcu; /* RCU deletion hook */
150: };
151: } __randomize_layout;
SourceFile:include/linux/cred.h]
|
| 18/2 |
2026/07/06 22:11 |
llm |
expert |
0m
Model:
Tokens:
input: 15741
output: 30
thoughts: 93
Thoughts: **Analyzing the Credential Structure**
Okay, so I'm looking at this memory dump related to a `struct cred`, and I see the `usage` field listed right at the very beginning of the structure. Thatβs standard placement, which is helpful to confirm. Now, I have these two addresses: `0xffff8881049530a8` and `0xffff888104953000`. Based on the context, it seems `0xffff8881049530a8` is the write address, while `0xffff888104953000` is the starting address of the read operation, likely from a `memcpy`. The critical offset here is `0xa8`, which is 168 in decimal. So, it is important to check the layout of `struct cred`. Now I have everything I need to analyze this further.
|
| 19/2 |
2026/07/06 22:11 |
tool |
codesearch-struct-layout |
0m
Args: map[ContextFile:kernel/cred.c Name:cred]
Results: map[Fields:[map[Name:usage OffsetBits:0 SizeBits:64] map[Name:uid OffsetBits:64 SizeBits:32] map[Name:gid OffsetBits:96 SizeBits:32] map[Name:suid OffsetBits:128 SizeBits:32] map[Name:sgid OffsetBits:160 SizeBits:32] map[Name:euid OffsetBits:192 SizeBits:32] map[Name:egid OffsetBits:224 SizeBits:32] map[Name:fsuid OffsetBits:256 SizeBits:32] map[Name:fsgid OffsetBits:288 SizeBits:32] map[Name:securebits OffsetBits:320 SizeBits:32] map[Name:cap_inheritable OffsetBits:384 SizeBits:64] map[Name:cap_permitted OffsetBits:448 SizeBits:64] map[Name:cap_effective OffsetBits:512 SizeBits:64] map[Name:cap_bset OffsetBits:576 SizeBits:64] map[Name:cap_ambient OffsetBits:640 SizeBits:64] map[Name:jit_keyring OffsetBits:704 SizeBits:8] map[Name:session_keyring OffsetBits:768 SizeBits:64] map[Name:process_keyring OffsetBits:832 SizeBits:64] map[Name:thread_keyring OffsetBits:896 SizeBits:64] map[Name:request_key_auth OffsetBits:960 SizeBits:64] map[Name:security OffsetBits:1024 SizeBits:64] map[Name:user OffsetBits:1088 SizeBits:64] map[Name:user_ns OffsetBits:1152 SizeBits:64] map[Name:ucounts OffsetBits:1216 SizeBits:64] map[Name:group_info OffsetBits:1280 SizeBits:64] map[Name: OffsetBits:1344 SizeBits:128]]]
|
| 20/2 |
2026/07/06 22:11 |
llm |
expert |
0m
Model:
Tokens:
input: 16618
output: 35
thoughts: 234
Thoughts: **Analyzing a Memory Write**
Okay, so I'm looking at this memory write. The report tells me the write occurred at offset `0xa8`, which I immediately translate to 168 bytes. The report says it wrote 4 bytes, and the relevant `usage` field must be at offset 0, right? The key is at 168.
Now, let's see, what lives at offset 168? That's 1344 bits. Based on the layout, the last thing described is an anonymous union at this offset. Looking at the C code, it's defined as:
```c
147: union {
148: int non_rcu; /* Can we skip RCU deletion? */
149: struct rcu_head rcu; /* RCU deletion hook */
150: };
```
Wait a second...I'm getting ahead of myself, `0xa8` is indeed 168.
The report also specifies the write occurred to address `0xffff8881049530a8` and was triggered by task 7107 on CPU 1, specifically by `get_cred_many` at `include/linux/cred.h:222`. That's the critical piece of information here. I need to understand what this function is doing and how it's interacting with this specific memory location. Now, let's go check line 222 in `include/linux/cred.h` to see how it's touching the memory layout I was just reviewing.
|
| 21/2 |
2026/07/06 22:12 |
tool |
read-file |
0m
Args: map[File:include/linux/cred.h FirstLine:210 LineCount:30]
Results: map[Contents: 210: * pointer is const, this will temporarily discard the const and increment the
211: * usage count. The purpose of this is to attempt to catch at compile time the
212: * accidental alteration of a set of credentials that should be considered
213: * immutable.
214: *
215: * Returns: @cred when the references are acquired, NULL otherwise.
216: */
217: static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
218: {
219: struct cred *nonconst_cred = (struct cred *) cred;
220: if (!cred)
221: return cred;
222: nonconst_cred->non_rcu = 0;
223: atomic_long_add(nr, &nonconst_cred->usage);
224: return cred;
225: }
226:
227: /*
228: * get_cred - Get a reference on a set of credentials
229: * @cred: The credentials to reference
230: *
231: * Get a reference on the specified set of credentials. The caller must
232: * release the reference. If %NULL is passed, it is returned with no action.
233: *
234: * This is used to deal with a committed set of credentials.
235: */
236: static inline const struct cred *get_cred(const struct cred *cred)
237: {
238: return get_cred_many(cred, 1);
239: }
]
|
| 22/2 |
2026/07/06 22:12 |
llm |
expert |
0m
Model:
Tokens:
input: 17711
output: 21
thoughts: 600
Thoughts: **Analyzing the `non_rcu` Field in Credential Management**
Okay, so I'm looking at this `nonconst_cred->non_rcu = 0;` line at line 222. And the offset for `non_rcu` is 168 (0xa8). Right, so `get_cred` and `get_cred_many` both zero out this `non_rcu` field. My immediate question is *why*? What's the logic here?
`non_rcu` supposedly indicates whether a credential can be freed without requiring RCU protection. If we're taking a new reference to it, holding onto it for a potentially extended time, we should likely be using RCU for safe deallocation, hence the zeroing.
Ah, hang on a second. Credential structs are often shared, aren't they? So, multiple threads might be using the same `cred` object. If one thread calls `get_cred`, setting `non_rcu` to 0, and another thread calls `prepare_creds`, that's where things get interesting. `prepare_creds` does a `memcpy` of the entire struct cred, including `non_rcu`.
So, we're looking at a potential race condition! One thread is setting `non_rcu` to 0 via `get_cred`, and another is reading it via `memcpy` in `prepare_creds`.
Wait a minute, `prepare_creds` immediately resets `new->non_rcu = 0` anyway! This means even if `memcpy` reads the 'wrong' value (i.e. 1), it's immediately overwritten with 0.
But, `get_cred` is writing 0 to `non_rcu`. `prepare_creds` is reading `non_rcu`. If it was already zero, then it's a "Safe Overwrite". If it was 1, then `prepare_creds` might read either 0 or 1, but it sets it to 0 regardless. So there is a race, but does it matter? It seems not.
Okay, let's zoom out. Why does `get_cred_many` also set `nonconst_cred->non_rcu = 0`? If a `cred` is marked `non_rcu = 1`, that means it's a short-lived credential which doesn't need RCU when being destroyed. But if someone takes a reference to it via `get_cred`, it could outlive the current RCU grace period, and it *must* be freed safely with RCU. So, the zeroing is to guarantee that RCU is used, even if the original intent was for short-lived credentials. So we must set `non_rcu` to 0.
Now, let's track down the places where `non_rcu` is actually set to 1.
|
| 23/2 |
2026/07/06 22:13 |
tool |
grepper |
0m
Args: map[Expression:non_rcu = 1]
Results: map[Output:fs/open.c=414=static const struct cred *access_override_creds(void)
--
fs/open.c-458- */
fs/open.c:459: override_cred->non_rcu = 1;
fs/open.c-460- return override_creds(override_cred);
]
|
| 24/2 |
2026/07/06 22:13 |
llm |
expert |
0m
Model:
Tokens:
input: 19068
output: 35
thoughts: 12
Thoughts: Here's my take on the thought process, as requested:
**Diving into `fs/open.c`**
Alright, let's get down to brass tacks. I'm going to dig into `fs/open.c`. I know this is the core of how file opens are handled at the kernel level. This means I'm looking at the nitty-gritty of file descriptor allocation, permission checks, potential race conditions, and how different filesystems interact with this foundational code. I need to refresh my memory on the interactions of VFS and other layers with the file open call. I'm expecting to see calls to `dentry` structures, `inode` handling, and of course, a lot of locking primitives. I'm hoping to understand if there are any subtle inefficiencies or potential vulnerabilities lurking within the code that I'm not seeing. I should also check and see how this handles different open flags and permissions. I want to see how these low-level calls might interact with security modules.
|
| 25/2 |
2026/07/06 22:13 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/open.c Name:access_override_creds]
Results: map[SourceCode: 414: static const struct cred *access_override_creds(void)
415: {
416: struct cred *override_cred;
417:
418: override_cred = prepare_creds();
419: if (!override_cred)
420: return NULL;
421:
422: /*
423: * XXX access_need_override_creds performs checks in hopes of skipping
424: * this work. Make sure it stays in sync if making any changes in this
425: * routine.
426: */
427:
428: override_cred->fsuid = override_cred->uid;
429: override_cred->fsgid = override_cred->gid;
430:
431: if (!issecure(SECURE_NO_SETUID_FIXUP)) {
432: /* Clear the capabilities if we switch to a non-root user */
433: kuid_t root_uid = make_kuid(override_cred->user_ns, 0);
434: if (!uid_eq(override_cred->uid, root_uid))
435: cap_clear(override_cred->cap_effective);
436: else
437: override_cred->cap_effective =
438: override_cred->cap_permitted;
439: }
440:
441: /*
442: * The new set of credentials can *only* be used in
443: * task-synchronous circumstances, and does not need
444: * RCU freeing, unless somebody then takes a separate
445: * reference to it.
446: *
447: * NOTE! This is _only_ true because this credential
448: * is used purely for override_creds() that installs
449: * it as the subjective cred. Other threads will be
450: * accessing ->real_cred, not the subjective cred.
451: *
452: * If somebody _does_ make a copy of this (using the
453: * 'get_current_cred()' function), that will clear the
454: * non_rcu field, because now that other user may be
455: * expecting RCU freeing. But normal thread-synchronous
456: * cred accesses will keep things non-racy to avoid RCU
457: * freeing.
458: */
459: override_cred->non_rcu = 1;
460: return override_creds(override_cred);
461: }
SourceFile:fs/open.c]
|
| 26/2 |
2026/07/06 22:13 |
llm |
expert |
0m
Model:
Tokens:
input: 20084
output: 32
thoughts: 2690
Thoughts: **Analyzing the Race Condition in `prepare_creds` and `get_cred_many`**
Okay, so I'm looking at this KCSAN report. The comment in `access_override_creds` is interesting, particularly the context it provides around task-synchronous credentials, which are normally non-RCU managed unless there's an explicit copy or reference taken. The comment clarifies that the only place the new credentials can be used is as the subjective credential.
I see that `get_cred_many` clears the `non_rcu` field. This raises immediate concerns about a potential race, especially if two threads within the same process share a `task->cred`. If one thread calls `prepare_creds` (which copies the cred) and another calls `get_cred(current_cred())`, the shared `struct cred` is accessed concurrently.
The core of the issue seems to be the `non_rcu` flag. If one thread calls `get_cred_many`, it sets `non_rcu` to 0. `prepare_creds` then reads this, potentially during the change. Though, `prepare_creds` immediately sets `new->non_rcu = 0` *after* the `memcpy`, which suggests it should be safe. However, the data race remains, because `memcpy` can be interrupted.
I was concerned initially about `usage`, but `prepare_creds` overwrites that as well with `new->usage = 1`. This makes me think, initially, that it's benign, even if the read of `usage` is torn during the copy.
I'm thinking now about how `memcpy` works. If `memcpy` is implemented in a way that reads `non_rcu` and then `usage`, or vice versa, the torn read might happen. The fact that the writes to the two fields in `get_cred_many` are independent raises concerns, and KCSAN is indeed right.
But, is it *harmful*? If `prepare_creds` copies a "torn" value of some field, it could be bad. However, `prepare_creds` copies from `old = task->cred`. Usually, `task->cred` is supposed to be immutable once it's assigned to a task, except for the refcount (`usage`) and `non_rcu`. Since `prepare_creds` overwrites both in the copy, it looks benign. But I need to go deeper.
So, `get_cred_many` modifies `non_rcu` and `usage`. `prepare_creds` copies, then overwrites them. What if `memcpy` races with a write to *other* fields? Normally, `struct cred` is immutable.
Okay, let's look at `get_cred_many` more closely: it modifies `non_rcu` and `usage` only, and `prepare_creds` overwrites them. If the copy is racing with these operations, there's a data race on `non_rcu` and `usage`. But `prepare_creds` overwrites both. This seems benign!
I'm getting hung up on the possibility of a compiler optimization on the `memcpy`. Or that `non_rcu` and `usage` are not the only things.
I see that `non_rcu` is `int` and `usage` is `atomic_long_t`. If `memcpy` is racing with `nonconst_cred->non_rcu = 0`, it's a data race. KCSAN is correct.
I need to confirm if `memcpy` reads a value that causes some issue. `memcpy` just copies bytes. The only way it could be harmful is if the copied value is used, but it's overwritten!
Wait! I see that `prepare_creds` *also* calls `get_group_info`, `get_uid`, and `get_user_ns` after the `memcpy`. Those *do* use the values copied by `memcpy`. Are those fields modified in-place? No, they should be immutable!
So the only racing fields are `non_rcu` and `usage`. But `prepare_creds` overwrites them *after* the copy.
I should check for *other* writers to `struct cred`. It's normally modified only during preparation, or the refcounts.
`non_rcu` is a special case β it flags whether the cred is shared, and whether to avoid RCU. `get_cred` says "oops, it's being shared, so clear it". If `usage > 1`, can `non_rcu` be 1?
I see in `access_override_creds` that `
|
| 27/2 |
2026/07/06 22:14 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/fork.c Name:copy_process]
Results: map[SourceCode:1986: /*
1987: * This creates a new process as a copy of the old one,
1988: * but does not actually start it yet.
1989: *
1990: * It copies the registers, and all the appropriate
1991: * parts of the process environment (as per the clone
1992: * flags). The actual kick-off is left to the caller.
1993: */
1994: __latent_entropy struct task_struct *copy_process(
1995: struct pid *pid,
1996: int trace,
1997: int node,
1998: struct kernel_clone_args *args)
1999: {
2000: int pidfd = -1, retval;
2001: struct task_struct *p;
2002: struct multiprocess_signals delayed;
2003: struct file *pidfile = NULL;
2004: const u64 clone_flags = args->flags;
2005: struct nsproxy *nsp = current->nsproxy;
2006:
2007: /*
2008: * Don't allow sharing the root directory with processes in a different
2009: * namespace
2010: */
2011: if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
2012: return ERR_PTR(-EINVAL);
2013:
2014: if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2015: return ERR_PTR(-EINVAL);
2016:
2017: /*
2018: * Thread groups must share signals as well, and detached threads
2019: * can only be started up within the thread group.
2020: */
2021: if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
2022: return ERR_PTR(-EINVAL);
2023:
2024: /*
2025: * Shared signal handlers imply shared VM. By way of the above,
2026: * thread groups also imply shared VM. Blocking this case allows
2027: * for various simplifications in other code.
2028: */
2029: if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
2030: return ERR_PTR(-EINVAL);
2031:
2032: /*
2033: * Siblings of global init remain as zombies on exit since they are
2034: * not reaped by their parent (swapper). To solve this and to avoid
2035: * multi-rooted process trees, prevent global and container-inits
2036: * from creating siblings.
2037: */
2038: if ((clone_flags & CLONE_PARENT) &&
2039: current->signal->flags & SIGNAL_UNKILLABLE)
2040: return ERR_PTR(-EINVAL);
2041:
2042: /*
2043: * If the new process will be in a different pid or user namespace
2044: * do not allow it to share a thread group with the forking task.
2045: */
2046: if (clone_flags & CLONE_THREAD) {
2047: if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2048: (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2049: return ERR_PTR(-EINVAL);
2050: }
2051:
2052: if (clone_flags & CLONE_PIDFD) {
2053: /*
2054: * - CLONE_DETACHED is blocked so that we can potentially
2055: * reuse it later for CLONE_PIDFD.
2056: */
2057: if (clone_flags & CLONE_DETACHED)
2058: return ERR_PTR(-EINVAL);
2059: }
2060:
2061: if (clone_flags & CLONE_AUTOREAP) {
2062: if (clone_flags & CLONE_THREAD)
2063: return ERR_PTR(-EINVAL);
2064: if (clone_flags & CLONE_PARENT)
2065: return ERR_PTR(-EINVAL);
2066: if (args->exit_signal)
2067: return ERR_PTR(-EINVAL);
2068: }
2069:
2070: if ((clone_flags & CLONE_PARENT) && current->signal->autoreap)
2071: return ERR_PTR(-EINVAL);
2072:
2073: if (clone_flags & CLONE_NNP) {
2074: if (clone_flags & CLONE_THREAD)
2075: return ERR_PTR(-EINVAL);
2076: }
2077:
2078: if (clone_flags & CLONE_PIDFD_AUTOKILL) {
2079: if (!(clone_flags & CLONE_PIDFD))
2080: return ERR_PTR(-EINVAL);
2081: if (!(clone_flags & CLONE_AUTOREAP))
2082: return ERR_PTR(-EINVAL);
2083: if (clone_flags & CLONE_THREAD)
2084: return ERR_PTR(-EINVAL);
2085: /*
2086: * Without CLONE_NNP the child could escalate privileges
2087: * after being spawned, so require CAP_SYS_ADMIN.
2088: * With CLONE_NNP the child can't gain new privileges,
2089: * so allow unprivileged usage.
2090: */
2091: if (!(clone_flags & CLONE_NNP) &&
2092: !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
2093: return ERR_PTR(-EPERM);
2094: }
2095:
2096: /*
2097: * Force any signals received before this point to be delivered
2098: * before the fork happens. Collect up signals sent to multiple
2099: * processes that happen during the fork and delay them so that
2100: * they appear to happen after the fork.
2101: */
2102: sigemptyset(&delayed.signal);
2103: INIT_HLIST_NODE(&delayed.node);
2104:
2105: spin_lock_irq(¤t->sighand->siglock);
2106: if (!(clone_flags & CLONE_THREAD))
2107: hlist_add_head(&delayed.node, ¤t->signal->multiprocess);
2108: recalc_sigpending();
2109: spin_unlock_irq(¤t->sighand->siglock);
2110: retval = -ERESTARTNOINTR;
2111: if (task_sigpending(current))
2112: goto fork_out;
2113:
2114: retval = -ENOMEM;
2115: p = dup_task_struct(current, node);
2116: if (!p)
2117: goto fork_out;
2118: retval = copy_exec_state(clone_flags, p);
2119: if (retval)
2120: goto bad_fork_free;
2121: p->flags &= ~PF_KTHREAD;
2122: if (args->kthread)
2123: p->flags |= PF_KTHREAD;
2124: if (args->user_worker) {
2125: /*
2126: * Mark us a user worker, and block any signal that isn't
2127: * fatal or STOP
2128: */
2129: p->flags |= PF_USER_WORKER;
2130: siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2131: }
2132: if (args->io_thread)
2133: p->flags |= PF_IO_WORKER;
2134:
2135: if (args->name)
2136: strscpy_pad(p->comm, args->name, sizeof(p->comm));
2137:
2138: p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2139: /*
2140: * TID is cleared in mm_release() when the task exits
2141: */
2142: p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2143:
2144: ftrace_graph_init_task(p);
2145:
2146: rt_mutex_init_task(p);
2147: raw_spin_lock_init(&p->blocked_lock);
2148:
2149: lockdep_assert_irqs_enabled();
2150: #ifdef CONFIG_PROVE_LOCKING
2151: DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2152: #endif
2153: retval = copy_creds(p, clone_flags);
2154: if (retval < 0)
2155: goto bad_fork_free;
2156:
2157: retval = -EAGAIN;
2158: if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2159: if (p->real_cred->user != INIT_USER &&
2160: !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2161: goto bad_fork_cleanup_count;
2162: }
2163: current->flags &= ~PF_NPROC_EXCEEDED;
2164:
2165: /*
2166: * If multiple threads are within copy_process(), then this check
2167: * triggers too late. This doesn't hurt, the check is only there
2168: * to stop root fork bombs.
2169: */
2170: retval = -EAGAIN;
2171: if (data_race(nr_threads >= max_threads))
2172: goto bad_fork_cleanup_count;
2173:
2174: delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
2175: p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2176: p->flags |= PF_FORKNOEXEC;
2177: INIT_LIST_HEAD(&p->children);
2178: INIT_LIST_HEAD(&p->sibling);
2179: rcu_copy_process(p);
2180: p->vfork_done = NULL;
2181: spin_lock_init(&p->alloc_lock);
2182:
2183: init_sigpending(&p->pending);
2184:
2185: p->utime = p->stime = p->gtime = 0;
2186: #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2187: p->utimescaled = p->stimescaled = 0;
2188: #endif
2189: prev_cputime_init(&p->prev_cputime);
2190:
2191: #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2192: seqcount_init(&p->vtime.seqcount);
2193: p->vtime.starttime = 0;
2194: p->vtime.state = VTIME_INACTIVE;
2195: #endif
2196:
2197: #ifdef CONFIG_IO_URING
2198: p->io_uring = NULL;
2199: retval = io_uring_fork(p);
2200: if (unlikely(retval))
2201: goto bad_fork_cleanup_delayacct;
2202: retval = -EAGAIN;
2203: #endif
2204:
2205: p->default_timer_slack_ns = current->timer_slack_ns;
2206:
2207: #ifdef CONFIG_PSI
2208: p->psi_flags = 0;
2209: #endif
2210:
2211: task_io_accounting_init(&p->ioac);
2212: acct_clear_integrals(p);
2213:
2214: posix_cputimers_init(&p->posix_cputimers);
2215: tick_dep_init_task(p);
2216:
2217: p->io_context = NULL;
2218: audit_set_context(p, NULL);
2219: cgroup_fork(p);
2220: if (args->kthread) {
2221: if (!set_kthread_struct(p))
2222: goto bad_fork_cleanup_delayacct;
2223: }
2224: #ifdef CONFIG_NUMA
2225: p->mempolicy = mpol_dup(p->mempolicy);
2226: if (IS_ERR(p->mempolicy)) {
2227: retval = PTR_ERR(p->mempolicy);
2228: p->mempolicy = NULL;
2229: goto bad_fork_cleanup_delayacct;
2230: }
2231: #endif
2232: #ifdef CONFIG_CPUSETS
2233: p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2234: seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2235: #endif
2236: #ifdef CONFIG_TRACE_IRQFLAGS
2237: memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2238: p->irqtrace.hardirq_disable_ip = _THIS_IP_;
2239: p->irqtrace.softirq_enable_ip = _THIS_IP_;
2240: p->softirqs_enabled = 1;
2241: p->softirq_context = 0;
2242: #endif
2243:
2244: p->pagefault_disabled = 0;
2245:
2246: lockdep_init_task(p);
2247:
2248: p->blocked_on = NULL; /* not blocked yet */
2249: p->blocked_donor = NULL; /* nobody is boosting p yet */
2250:
2251: #ifdef CONFIG_BCACHE
2252: p->sequential_io = 0;
2253: p->sequential_io_avg = 0;
2254: #endif
2255:
2256: unwind_task_init(p);
2257:
2258: /* Perform scheduler related setup. Assign this task to a CPU. */
2259: retval = sched_fork(clone_flags, p);
2260: if (retval)
2261: goto bad_fork_cleanup_policy;
2262:
2263: retval = perf_event_init_task(p, clone_flags);
2264: if (retval)
2265: goto bad_fork_sched_cancel_fork;
2266: retval = audit_alloc(p);
2267: if (retval)
2268: goto bad_fork_cleanup_perf;
2269: /* copy all the process information */
2270: shm_init_task(p);
2271: retval = security_task_alloc(p, clone_flags);
2272: if (retval)
2273: goto bad_fork_cleanup_audit;
2274: retval = copy_semundo(clone_flags, p);
2275: if (retval)
2276: goto bad_fork_cleanup_security;
2277: retval = copy_files(clone_flags, p, args->no_files);
2278: if (retval)
2279: goto bad_fork_cleanup_semundo;
2280: retval = copy_fs(clone_flags, p);
2281: if (retval)
2282: goto bad_fork_cleanup_files;
2283: retval = copy_sighand(clone_flags, p);
2284: if (retval)
2285: goto bad_fork_cleanup_fs;
2286: retval = copy_signal(clone_flags, p);
2287: if (retval)
2288: goto bad_fork_cleanup_sighand;
2289: retval = copy_mm(clone_flags, p);
2290: if (retval)
2291: goto bad_fork_cleanup_signal;
2292: retval = copy_namespaces(clone_flags, p);
2293: if (retval)
2294: goto bad_fork_cleanup_mm;
2295: retval = copy_io(clone_flags, p);
2296: if (retval)
2297: goto bad_fork_cleanup_namespaces;
2298: retval = copy_thread(p, args);
2299: if (retval)
2300: goto bad_fork_cleanup_io;
2301:
2302: stackleak_task_init(p);
2303:
2304: if (pid != &init_struct_pid) {
2305: pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2306: args->set_tid_size);
2307: if (IS_ERR(pid)) {
2308: retval = PTR_ERR(pid);
2309: goto bad_fork_cleanup_thread;
2310: }
2311: }
2312:
2313: /*
2314: * This has to happen after we've potentially unshared the file
2315: * descriptor table (so that the pidfd doesn't leak into the child
2316: * if the fd table isn't shared).
2317: */
2318: if (clone_flags & CLONE_PIDFD) {
2319: unsigned flags = PIDFD_STALE;
2320:
2321: if (clone_flags & CLONE_THREAD)
2322: flags |= PIDFD_THREAD;
2323: if (clone_flags & CLONE_PIDFD_AUTOKILL)
2324: flags |= PIDFD_AUTOKILL;
2325:
2326: /*
2327: * Note that no task has been attached to @pid yet indicate
2328: * that via CLONE_PIDFD.
2329: */
2330: retval = pidfd_prepare(pid, flags, &pidfile);
2331: if (retval < 0)
2332: goto bad_fork_free_pid;
2333: pidfd = retval;
2334:
2335: retval = put_user(pidfd, args->pidfd);
2336: if (retval)
2337: goto bad_fork_put_pidfd;
2338: }
2339:
2340: #ifdef CONFIG_BLOCK
2341: p->plug = NULL;
2342: p->flags &= ~PF_BLOCK_TS;
2343: #endif
2344: futex_init_task(p);
2345:
2346: /*
2347: * sigaltstack should be cleared when sharing the same VM
2348: */
2349: if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2350: sas_ss_reset(p);
2351:
2352: /*
2353: * Syscall tracing and stepping should be turned off in the
2354: * child regardless of CLONE_PTRACE.
2355: */
2356: user_disable_single_step(p);
2357: clear_task_syscall_work(p, SYSCALL_TRACE);
2358: #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
2359: clear_task_syscall_work(p, SYSCALL_EMU);
2360: #endif
2361: clear_tsk_latency_tracing(p);
2362:
2363: /* ok, now we should be set up.. */
2364: p->pid = pid_nr(pid);
2365: if (clone_flags & CLONE_THREAD) {
2366: p->group_leader = current->group_leader;
2367: p->tgid = current->tgid;
2368: } else {
2369: p->group_leader = p;
2370: p->tgid = p->pid;
2371: }
2372:
2373: p->nr_dirtied = 0;
2374: p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2375: p->dirty_paused_when = 0;
2376:
2377: p->pdeath_signal = 0;
2378: p->task_works = NULL;
2379: clear_posix_cputimers_work(p);
2380:
2381: #ifdef CONFIG_KRETPROBES
2382: p->kretprobe_instances.first = NULL;
2383: #endif
2384: #ifdef CONFIG_RETHOOK
2385: p->rethooks.first = NULL;
2386: #endif
2387:
2388: /*
2389: * Ensure that the cgroup subsystem policies allow the new process to be
2390: * forked. It should be noted that the new process's css_set can be changed
2391: * between here and cgroup_post_fork() if an organisation operation is in
2392: * progress.
2393: */
2394: retval = cgroup_can_fork(p, args);
2395: if (retval)
2396: goto bad_fork_put_pidfd;
2397:
2398: /*
2399: * Now that the cgroups are pinned, re-clone the parent cgroup and put
2400: * the new task on the correct runqueue. All this *before* the task
2401: * becomes visible.
2402: *
2403: * This isn't part of ->can_fork() because while the re-cloning is
2404: * cgroup specific, it unconditionally needs to place the task on a
2405: * runqueue.
2406: */
2407: retval = sched_cgroup_fork(p, args);
2408: if (retval)
2409: goto bad_fork_cancel_cgroup;
2410:
2411: if (need_futex_hash_allocate_default(clone_flags)) {
2412: retval = futex_hash_allocate_default();
2413: if (retval)
2414: goto bad_fork_cancel_cgroup;
2415: /*
2416: * If we fail beyond this point we don't free the allocated
2417: * futex hash map. We assume that another thread will be created
2418: * and makes use of it. The hash map will be freed once the main
2419: * thread terminates.
2420: */
2421: }
2422: /*
2423: * From this point on we must avoid any synchronous user-space
2424: * communication until we take the tasklist-lock. In particular, we do
2425: * not want user-space to be able to predict the process start-time by
2426: * stalling fork(2) after we recorded the start_time but before it is
2427: * visible to the system.
2428: */
2429:
2430: p->start_time = ktime_get_ns();
2431: p->start_boottime = ktime_get_boottime_ns();
2432:
2433: /*
2434: * Make it visible to the rest of the system, but dont wake it up yet.
2435: * Need tasklist lock for parent etc handling!
2436: */
2437: write_lock_irq(&tasklist_lock);
2438:
2439: /* CLONE_PARENT re-uses the old parent */
2440: if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2441: p->real_parent = current->real_parent;
2442: p->parent_exec_id = current->parent_exec_id;
2443: if (clone_flags & CLONE_THREAD)
2444: p->exit_signal = -1;
2445: else
2446: p->exit_signal = current->group_leader->exit_signal;
2447: } else {
2448: p->real_parent = current;
2449: p->parent_exec_id = current->self_exec_id;
2450: p->exit_signal = args->exit_signal;
2451: }
2452:
2453: klp_copy_process(p);
2454:
2455: sched_core_fork(p);
2456:
2457: spin_lock(¤t->sighand->siglock);
2458:
2459: rv_task_fork(p);
2460:
2461: rseq_fork(p, clone_flags);
2462:
2463: /*
2464: * If zap_pid_ns_processes() was called after alloc_pid(), the new
2465: * child missed SIGKILL. If current is not in the same namespace,
2466: * we can't rely on fatal_signal_pending() below.
2467: */
2468: if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2469: retval = -ENOMEM;
2470: goto bad_fork_core_free;
2471: }
2472:
2473: /* Let kill terminate clone/fork in the middle */
2474: if (fatal_signal_pending(current)) {
2475: retval = -EINTR;
2476: goto bad_fork_core_free;
2477: }
2478:
2479: /* No more failure paths after this point. */
2480:
2481: /*
2482: * Copy seccomp details explicitly here, in case they were changed
2483: * before holding sighand lock.
2484: */
2485: copy_seccomp(p);
2486:
2487: if (clone_flags & CLONE_NNP)
2488: task_set_no_new_privs(p);
2489:
2490: init_task_pid_links(p);
2491: if (likely(p->pid)) {
2492: ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2493:
2494: init_task_pid(p, PIDTYPE_PID, pid);
2495: if (thread_group_leader(p)) {
2496: init_task_pid(p, PIDTYPE_TGID, pid);
2497: init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2498: init_task_pid(p, PIDTYPE_SID, task_session(current));
2499:
2500: if (is_child_reaper(pid)) {
2501: struct pid_namespace *ns = ns_of_pid(pid);
2502:
2503: ASSERT_EXCLUSIVE_WRITER(ns->child_reaper);
2504: WRITE_ONCE(ns->child_reaper, p);
2505: p->signal->flags |= SIGNAL_UNKILLABLE;
2506: }
2507: p->signal->shared_pending.signal = delayed.signal;
2508: p->signal->tty = tty_kref_get(current->signal->tty);
2509: /*
2510: * Inherit has_child_subreaper flag under the same
2511: * tasklist_lock with adding child to the process tree
2512: * for propagate_has_child_subreaper optimization.
2513: */
2514: p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2515: p->real_parent->signal->is_child_subreaper;
2516: if (clone_flags & CLONE_AUTOREAP)
2517: p->signal->autoreap = 1;
2518: list_add_tail(&p->sibling, &p->real_parent->children);
2519: list_add_tail_rcu(&p->tasks, &init_task.tasks);
2520: attach_pid(p, PIDTYPE_TGID);
2521: attach_pid(p, PIDTYPE_PGID);
2522: attach_pid(p, PIDTYPE_SID);
2523: __this_cpu_inc(process_counts);
2524: } else {
2525: current->signal->nr_threads++;
2526: current->signal->quick_threads++;
2527: atomic_inc(¤t->signal->live);
2528: refcount_inc(¤t->signal->sigcnt);
2529: task_join_group_stop(p);
2530: list_add_tail_rcu(&p->thread_node,
2531: &p->signal->thread_head);
2532: }
2533: attach_pid(p, PIDTYPE_PID);
2534: nr_threads++;
2535: }
2536: total_forks++;
2537: hlist_del_init(&delayed.node);
2538: spin_unlock(¤t->sighand->siglock);
2539: syscall_tracepoint_update(p);
2540: write_unlock_irq(&tasklist_lock);
2541:
2542: if (pidfile)
2543: fd_install(pidfd, pidfile);
2544:
2545: proc_fork_connector(p);
2546: /*
2547: * sched_ext needs @p to be associated with its cgroup in its post_fork
2548: * hook. cgroup_post_fork() should come before sched_post_fork().
2549: */
2550: cgroup_post_fork(p, args);
2551: sched_post_fork(p);
2552: perf_event_fork(p);
2553:
2554: trace_task_newtask(p, clone_flags);
2555: uprobe_copy_process(p, clone_flags);
2556: user_events_fork(p, clone_flags);
2557:
2558: copy_oom_score_adj(clone_flags, p);
2559:
2560: return p;
2561:
2562: bad_fork_core_free:
2563: sched_core_free(p);
2564: spin_unlock(¤t->sighand->siglock);
2565: write_unlock_irq(&tasklist_lock);
2566: bad_fork_cancel_cgroup:
2567: cgroup_cancel_fork(p, args);
2568: bad_fork_put_pidfd:
2569: if (clone_flags & CLONE_PIDFD) {
2570: fput(pidfile);
2571: put_unused_fd(pidfd);
2572: }
2573: bad_fork_free_pid:
2574: if (pid != &init_struct_pid)
2575: free_pid(pid);
2576: bad_fork_cleanup_thread:
2577: exit_thread(p);
2578: bad_fork_cleanup_io:
2579: if (p->io_context)
2580: exit_io_context(p);
2581: bad_fork_cleanup_namespaces:
2582: exit_nsproxy_namespaces(p);
2583: bad_fork_cleanup_mm:
2584: if (p->mm) {
2585: mm_clear_owner(p->mm, p);
2586: mmput(p->mm);
2587: }
2588: bad_fork_cleanup_signal:
2589: if (!(clone_flags & CLONE_THREAD))
2590: free_signal_struct(p->signal);
2591: bad_fork_cleanup_sighand:
2592: __cleanup_sighand(p->sighand);
2593: bad_fork_cleanup_fs:
2594: exit_fs(p); /* blocking */
2595: bad_fork_cleanup_files:
2596: exit_files(p); /* blocking */
2597: bad_fork_cleanup_semundo:
2598: exit_sem(p);
2599: bad_fork_cleanup_security:
2600: security_task_free(p);
2601: bad_fork_cleanup_audit:
2602: audit_free(p);
2603: bad_fork_cleanup_perf:
2604: perf_event_free_task(p);
2605: bad_fork_sched_cancel_fork:
2606: sched_cancel_fork(p);
2607: bad_fork_cleanup_policy:
2608: lockdep_free_task(p);
2609: #ifdef CONFIG_NUMA
2610: mpol_put(p->mempolicy);
2611: #endif
2612: bad_fork_cleanup_delayacct:
2613: io_uring_free(p);
2614: delayacct_tsk_free(p);
2615: bad_fork_cleanup_count:
2616: dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2617: exit_cred_namespaces(p);
2618: exit_creds(p);
2619: bad_fork_free:
2620: WRITE_ONCE(p->__state, TASK_DEAD);
2621: exit_task_stack_account(p);
2622: put_task_stack(p);
2623: delayed_free_task(p);
2624: fork_out:
2625: spin_lock_irq(¤t->sighand->siglock);
2626: hlist_del_init(&delayed.node);
2627: spin_unlock_irq(¤t->sighand->siglock);
2628: return ERR_PTR(retval);
2629: }
SourceFile:kernel/fork.c]
|
| 28/2 |
2026/07/06 22:14 |
llm |
expert |
0m
Model:
Tokens:
input: 33827
output: 33
thoughts: 47
Thoughts: Here's my understanding of the situation, tailored for an expert like yourself:
**Analyzing `copy_process` and Credential Handling**
Okay, so I'm looking at how a process is created, specifically focusing on the `copy_process` function. Line 2153 shows the crucial call to `copy_creds` which seems fundamental to how the new process inherits or diverges from the calling process's security context. This makes perfect sense; creating a new process is intrinsically linked to establishing its identity and capabilities.
Now, I need to dig into the `copy_creds` function itself, probably located within `kernel/cred.c`. This is where the magic (or the potential headaches, depending on the `clone_flags`) happens. I'm assuming this function handles the replication, sharing, or even the complete creation of a new set of credentials for the child process. It's likely taking the parent's credentials (`p` in the code snippet) and, based on the `clone_flags`, either copying them directly, establishing a shared reference, or creating an entirely new set. I'll need to understand the implications of different `clone_flags` on the credential copying strategy. For example, `CLONE_NEWUSER` or related flags would obviously have profound effects on this stage, right? Is this where we deal with UID and GID mappings and user namespaces? This is where security separation is being defined. This function is the pivotal point for establishing a new process's identity and its access rights.
|
| 29/2 |
2026/07/06 22:15 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:copy_creds]
Results: map[SourceCode: 254: /*
255: * Copy credentials for the new process created by fork()
256: *
257: * We share if we can, but under some circumstances we have to generate a new
258: * set.
259: *
260: * The new process gets the current process's subjective credentials as its
261: * objective and subjective credentials
262: */
263: int copy_creds(struct task_struct *p, u64 clone_flags)
264: {
265: struct cred *new;
266: int ret;
267:
268: #ifdef CONFIG_KEYS_REQUEST_CACHE
269: p->cached_requested_key = NULL;
270: #endif
271:
272: if (
273: #ifdef CONFIG_KEYS
274: !p->cred->thread_keyring &&
275: #endif
276: clone_flags & CLONE_THREAD
277: ) {
278: p->real_cred = get_cred_many(p->cred, 2);
279: kdebug("share_creds(%p{%ld})",
280: p->cred, atomic_long_read(&p->cred->usage));
281: inc_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
282: get_cred_namespaces(p);
283: return 0;
284: }
285:
286: new = prepare_creds();
287: if (!new)
288: return -ENOMEM;
289:
290: if (clone_flags & CLONE_NEWUSER) {
291: ret = create_user_ns(new);
292: if (ret < 0)
293: goto error_put;
294: ret = set_cred_ucounts(new);
295: if (ret < 0)
296: goto error_put;
297: }
298:
299: #ifdef CONFIG_KEYS
300: /* new threads get their own thread keyrings if their parent already
301: * had one */
302: if (new->thread_keyring) {
303: key_put(new->thread_keyring);
304: new->thread_keyring = NULL;
305: if (clone_flags & CLONE_THREAD)
306: install_thread_keyring_to_cred(new);
307: }
308:
309: /* The process keyring is only shared between the threads in a process;
310: * anything outside of those threads doesn't inherit.
311: */
312: if (!(clone_flags & CLONE_THREAD)) {
313: key_put(new->process_keyring);
314: new->process_keyring = NULL;
315: }
316: #endif
317:
318: p->cred = p->real_cred = get_cred(new);
319: inc_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
320: get_cred_namespaces(p);
321:
322: return 0;
323:
324: error_put:
325: put_cred(new);
326: return ret;
327: }
SourceFile:kernel/cred.c]
|
| 30/2 |
2026/07/06 22:15 |
llm |
expert |
1m
Model:
Tokens:
input: 35286
output: 34
thoughts: 3551
Thoughts: **Benign Data Race in Credential Handling**
Alright, let me walk through this. It seems we've got a potential data race with credentials, specifically involving `non_rcu` and `usage` within `struct cred`. When `CLONE_THREAD` is set, and no `thread_keyring` is present, the kernel duplicates the credentials using `get_cred_many`. Now, initially, the `cred` and `real_cred` pointers in the new thread's task structure point to the same `struct cred` as the current process's. This is where things get interesting. Since threads within the same process share this `struct cred` object, any modification by one thread (e.g., via `get_cred`) could impact another thread's operations.
The core concern revolves around potential races on the `non_rcu` and `usage` fields. The `prepare_creds` function copies the credentials using `memcpy`. Crucially, after the copy, `non_rcu` is explicitly set to 0 and the `usage` count is initialized to 1 within the new credentials. The compiler optimization here is something I considered at the start. However, `memcpy` is typically a function call, making it unlikely to be reordered with subsequent writes to the same memory. Even if reordering *did* occur, the end result would be the same β `non_rcu` would be 0 and `usage` would be 1.
The critical thing, which I've now revisited several times, is whether `memcpy` can see a partially written value. The only scenario that worries me is if `memcpy` reads something from the shared `struct cred` that is being modified concurrently by another thread, potentially leading to incorrect values copied into the new credentials. However, the data that could be concurrently modified are `non_rcu` and `usage` during `get_cred_many`.
The `get_cred_many` function itself sets `non_rcu` to 0 and adds to the `usage` count. The question is whether this creates a race during the `memcpy` operation in `prepare_creds`. On most architectures, a 32-bit write of `non_rcu` is atomic, so any partially written values are not possible. While `usage` is an `atomic_long_t`, `atomic_long_add` is atomic, and the `usage` value is overwritten by `prepare_creds`, so it's not a concern. I did consider whether there are any other fields that are modified. Based on the surrounding code, there aren't.
Now, I found a possible issue. In `access_override_creds`, a thread's credentials can temporarily override to `non_rcu = 1`. This overrides the `cred` for the calling thread and is not shared with the rest of the threads.
Here's the key: if thread A calls `override_creds` and sets `non_rcu = 1` for *its* credentials, and then another thread (thread B) attempts to get a copy, is there a race? The answer is no. `access_override_creds` sets its *own* credential's `non_rcu` field. The "old" cred (before the override) still exists for the other threads, so any operations using those still work. If thread A creates a new thread via `fork`, then `copy_creds` copies thread A's credentials into the child, which calls `get_cred`. But `get_cred` always sets `non_rcu = 0`. This is the important point. The `get_cred` function is used to create *shared* credentials, and that function *always* sets `non_rcu = 0` when it adds a reference to a `struct cred`.
With all this in mind, and the context of the KCSAN report showing the two tasks running on different CPUs, the concern must be that the tasks are concurrently writing and reading a shared `struct cred` object, but it is impossible for the `non_rcu` to be 1 since `access_override_creds` does *not* share. If it is already 0, and each thread sets it to 0, there is no issue. The `memcpy` itself can cause a data race in the eyes of KCSAN, but the value is benign. Even though `memcpy` might see a torn value of `usage`, since the destination writes to `usage`, this race can also be ignored.
Since `non_rcu` is always reset to 0 whenever a credential is shared, the race turns out to be a classic "Safe Overwrite" data race.
|
| 31/2 |
2026/07/06 22:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/cred.h Name:put_cred]
Results: map[SourceCode: 274: /*
275: * put_cred - Release a reference to a set of credentials
276: * @cred: The credentials to release
277: *
278: * Release a reference to a set of credentials, deleting them when the last ref
279: * is released. If %NULL is passed, nothing is done.
280: */
281: static inline void put_cred(const struct cred *cred)
282: {
283: put_cred_many(cred, 1);
284: }
SourceFile:include/linux/cred.h]
|
| 32/2 |
2026/07/06 22:17 |
llm |
expert |
0m
Model:
Tokens:
input: 40068
output: 36
thoughts: 8
Thoughts: Okay, here's the summary, expressed as though I'm the one thinking these thoughts, keeping in mind I'm speaking to an expert:
**Analyzing `put_cred_many`**
Alright, let's dive into this `put_cred_many` function. Thinking about it, the name itself already implies an operation involving multiple credentials, probably storing them somewhere. Immediately, I'm considering the potential scale. This likely isn't a simple insertion; we're dealing with a batch operation. Efficiency becomes a paramount concern right away. We need to be wary of any potential bottlenecks or performance cliffs. Are we talking about a database, a key-value store, or something else entirely? The underlying storage mechanism will dictate a lot of the implementation details.
I'm mentally mapping out the possible scenarios. What kind of validation is involved? Does each credential need to be individually checked for validity, or can we perform some kind of batch validation for increased speed? If we fail on one credential within the batch, what's the rollback strategy? Is it all-or-nothing, or can we attempt a partial insertion, logging the failures? Error handling is key here.
Thinking through the data structures, what's the expected format of the credentials? Are they already structured, or will we need to do some transformation on the input? The efficiency of that transformation is crucial. And how does this interact with any existing credential management system? Is this a completely isolated process, or does it need to interface with other components? I need to think about potential locking mechanisms too, if concurrency is a possibility. Considering edge cases is essential. What happens with empty lists, duplicate entries, or malformed credentials? These are all important considerations.
Furthermore, I have to think about security implications. Batch operations are often attractive targets for attackers. The implementation needs to be secure and protected from any possible exploits. The way we store the credentials must be robust.
Essentially, I'm thinking of `put_cred_many` as an optimization problem where performance, security, and data integrity are all interlinked, and each has to be considered for its impacts.
|
| 33/2 |
2026/07/06 22:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/cred.h Name:put_cred_many]
Results: map[SourceCode: 252: /**
253: * put_cred_many - Release a reference to a set of credentials
254: * @_cred: The credentials to release
255: * @nr: Number of references to release
256: *
257: * Release a reference to a set of credentials, deleting them when the last ref
258: * is released. If %NULL is passed, nothing is done.
259: *
260: * This takes a const pointer to a set of credentials because the credentials
261: * on task_struct are attached by const pointers to prevent accidental
262: * alteration of otherwise immutable credential sets.
263: */
264: static inline void put_cred_many(const struct cred *_cred, int nr)
265: {
266: struct cred *cred = (struct cred *) _cred;
267:
268: if (cred) {
269: if (atomic_long_sub_and_test(nr, &cred->usage))
270: __put_cred(cred);
271: }
272: }
SourceFile:include/linux/cred.h]
|
| 34/2 |
2026/07/06 22:17 |
llm |
expert |
0m
Model:
Tokens:
input: 40899
output: 33
thoughts: 7
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**My Deep Dive into `__put_cred` and the Kernel's Credential Handling**
Alright, let's break this down. When I see `__put_cred`, my mind immediately jumps to the heart of kernel security. It's the critical function responsible for *releasing* a credential structure. I understand it's the counterpart to functions like `get_cred` and, implicitly, `alloc_cred`. It's all about reference counting, right? I know I have to be extremely careful here. A double-free is an instant kernel panic, and a memory leak, well, that's just a time bomb.
I'm thinking about the implications. What kind of credential is being released? Is it the current process's effective credentials? The filesystem credentials? Or perhaps something more specialized like a capability set? The context is key. The kernel has a complex web of dependencies here - you have to carefully track how these credentials are used by different parts of the kernel, so you don't break something else.
I'm also considering the potential concurrency issues. This function is almost certainly called from multiple contexts β interrupt handlers, tasklets, preemption points, etc. So, the locking mechanisms are crucial. The internal locking, the spinlocks or mutexes guarding the `cred` structure itself, the global credential cache locks if applicableβthat's all going through my head. Are there potential race conditions in this path? Memory barriers? Atomic operations? I'm trying to visualize the code's execution flow.
Then I get to the actual deallocation logic. Is it a simple `kfree`? Or is there more to it, such as special handling depending on the type of credential, like clearing sensitive information to prevent information leakage after it's deallocated? What about the cache? Is there a LRU cache for credentials? This is where I go from looking at the code to remembering past kernel exploits that have involved credential vulnerabilities. This is an area where subtle bugs can be exploited.
In summary, when I see `__put_cred`, I'm not just seeing a simple memory deallocation. I see a critical component of the kernel's security architecture. I'm visualizing the reference counting, the locking, the potential race conditions, the implications for information leakage, and the many ways that this routine could be exploited. It's a key part of how the kernel manages identities, and that's never a trivial matter.
|
| 35/2 |
2026/07/06 22:18 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:__put_cred]
Results: map[SourceCode: 65: /**
66: * __put_cred - Destroy a set of credentials
67: * @cred: The record to release
68: *
69: * Destroy a set of credentials on which no references remain.
70: */
71: void __put_cred(struct cred *cred)
72: {
73: kdebug("__put_cred(%p{%ld})", cred,
74: atomic_long_read(&cred->usage));
75:
76: BUG_ON(atomic_long_read(&cred->usage) != 0);
77: BUG_ON(cred == current->cred);
78: BUG_ON(cred == current->real_cred);
79:
80: if (cred->non_rcu)
81: put_cred_rcu(&cred->rcu);
82: else
83: call_rcu(&cred->rcu, put_cred_rcu);
84: }
SourceFile:kernel/cred.c]
|
| 36/2 |
2026/07/06 22:18 |
llm |
expert |
0m
Model:
Tokens:
input: 41779
output: 35
thoughts: 138
Thoughts: **Analyzing the Credential Release Path**
Okay, so I'm diving into how `__put_cred` handles credential release. My initial thought is to trace the execution path. Ah, it uses `cred->non_rcu`. Right, I recall the intention here: it determines whether we need to employ Read-Copy Update (RCU) mechanisms or not.
If `cred->non_rcu` is set to 1, it means we can bypass the RCU and free the memory immediately. The code directly calls `put_cred_rcu`.
If `cred->non_rcu` is 0, then we do need RCU protection. `call_rcu` is invoked, which schedules the release using RCU.
Wait a second, if `non_rcu` is 1, it implies that we *don't* require RCU for this particular credential object. So, in this scenario, `put_cred_rcu` is called right away. That makes sense, because if RCU isn't required, there's no need to wait for grace periods.
Hold on... I'm a bit rusty here. Ah, right. `put_cred_rcu` *is* the RCU callback, even though it's called directly in the `non_rcu` equals 1 path. Interesting design choice, but it works. This means that we're essentially consolidating the release logic within a single function regardless of whether RCU is actually used.
Time to confirm this by going back to study the `put_cred_rcu` function directly. I should review that code block again.
|
| 37/2 |
2026/07/06 22:19 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:put_cred_rcu]
Results: map[SourceCode: 38: /*
39: * The RCU callback to actually dispose of a set of credentials
40: */
41: static void put_cred_rcu(struct rcu_head *rcu)
42: {
43: struct cred *cred = container_of(rcu, struct cred, rcu);
44:
45: kdebug("put_cred_rcu(%p)", cred);
46:
47: if (atomic_long_read(&cred->usage) != 0)
48: panic("CRED: put_cred_rcu() sees %p with usage %ld\n",
49: cred, atomic_long_read(&cred->usage));
50:
51: security_cred_free(cred);
52: key_put(cred->session_keyring);
53: key_put(cred->process_keyring);
54: key_put(cred->thread_keyring);
55: key_put(cred->request_key_auth);
56: if (cred->group_info)
57: put_group_info(cred->group_info);
58: free_uid(cred->user);
59: if (cred->ucounts)
60: put_ucounts(cred->ucounts);
61: put_user_ns(cred->user_ns);
62: kmem_cache_free(cred_jar, cred);
63: }
SourceFile:kernel/cred.c]
|
| 38/2 |
2026/07/06 22:19 |
llm |
expert |
0m
Model:
Tokens:
input: 42729
output: 34
thoughts: 686
Thoughts: **Analyzing the Credential Race Condition**
Okay, let's break this down. My initial thought is that setting `non_rcu` to 1 does, in fact, free up memory. If `non_rcu` is 1, the `cred` is freed immediately. If it's 0, it's freed after an RCU grace period. The logic in `get_cred_many` is to protect against the scenario where a `cred` started as `non_rcu = 1` but gained an external reference. In that case, RCU is needed to guarantee safe cleanup since that external reference could span an RCU grace period.
Now, I understand that if `non_rcu` is 1, the `cred` is used in a "task-synchronous" manner. This means if someone calls `get_cred`, they are potentially making it "non-task-synchronous". So, in that case, `non_rcu` MUST be cleared.
Let's revisit the race condition, then. Imagine Task A has a `non_rcu = 1` `cred`. Then Task A calls `get_cred(current->cred)` which clears `non_rcu`. Task A also calls `prepare_creds()`. This copies `current->cred`.
Ah, but if it's the SAME task, there's no race. But the report says Task 7107 and 7106 are separate tasks! How can they share a `non_rcu = 1` `cred`? Remember, `non_rcu = 1` `creds` are only created in `access_override_creds` and installed in `current->cred`. They are NOT shared via `fork()` since `copy_creds` calls `get_cred` which clears `non_rcu`. They are NOT shared via `CLONE_THREAD` because `copy_creds` calls `get_cred_many` which also clears `non_rcu`.
Therefore, a `non_rcu = 1` `cred` should NEVER be shared between tasks. So if tasks 7107 and 7106 *are* looking at the *same* `cred`, then that `cred` MUST have `non_rcu = 0` already.
Wait... if it's already 0, then the line `nonconst_cred->non_rcu = 0` is writing 0 to 0. And `memcpy` is reading 0. So the race is on writing 0 to a field that is *already* 0. This is BENIGN. It's a no-op!
Okay, just to be sure, let's check for any other ways that `non_rcu` could be set to 1. I grepped for `non_rcu = 1` and only found `fs/open.c`. Good.
Let's also double-check the other writers to `non_rcu`. `get_cred_many` sets it to 0, `prepare_creds` sets it to 0. `copy_creds` doesn't touch it directly (it calls `get_cred_many` or `prepare_creds`). Ah, what about `cred_alloc_blank`? I need to check that too... But overall, I'm fairly confident that the race condition, as described, is harmless.
|
| 39/2 |
2026/07/06 22:19 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:cred_alloc_blank]
Results: map[SourceCode: 142: /*
143: * Allocate blank credentials, such that the credentials can be filled in at a
144: * later date without risk of ENOMEM.
145: */
146: struct cred *cred_alloc_blank(void)
147: {
148: struct cred *new;
149:
150: new = kmem_cache_zalloc(cred_jar, GFP_KERNEL);
151: if (!new)
152: return NULL;
153:
154: atomic_long_set(&new->usage, 1);
155: if (security_cred_alloc_blank(new, GFP_KERNEL_ACCOUNT) < 0)
156: goto error;
157:
158: return new;
159:
160: error:
161: abort_creds(new);
162: return NULL;
163: }
SourceFile:kernel/cred.c]
|
| 40/2 |
2026/07/06 22:19 |
llm |
expert |
0m
Model:
Tokens:
input: 44499
output: 33
thoughts: 518
Thoughts: **Analyzing Credential Structure Mutability**
Okay, let's break this down systematically. `kmem_cache_zalloc` initializes everything, including `non_rcu`, to zero. So, by default, `non_rcu` is 0. I recall that it becomes 1 only within `access_override_creds` and reverts to 0 in `get_cred_many`. And like I figured, a `non_rcu = 1` credential is never shared. Thus, if the `cred` is shared, `non_rcu` is always 0. The race, then, is between the potential for `nonconst_cred->non_rcu = 0` and the `memcpy`. Since `non_rcu` is *already* 0, this is benign.
Now, what about `usage`? That's definitely changing, right? However, `prepare_creds` immediately overwrites it during the copy process. `memcpy` just copies bytes. Is there a potential that `memcpy` could grab a corrupted value of `usage` that causes issues? `usage` is an `atomic_long_t`. If it's torn, `memcpy` might copy a garbage value to `new->usage`. However, the code immediately does `atomic_long_set(&new->usage, 1)` after the copy. So, the only possibility for harm would be if code *between* the `memcpy` and `atomic_long_set` used the potentially garbage `new->usage`. Let's re-examine `prepare_creds`:
```c
192: memcpy(new, old, sizeof(struct cred));
193:
194: new->non_rcu = 0;
195: atomic_long_set(&new->usage, 1);
```
Nope, nothing in between. We're safe there.
Wait, the other fields! `memcpy` copies everything! If `old` is modified in other fields concurrently, we're in trouble! But wait... once a `struct cred` is shared, shouldn't it be immutable? Is there a concurrent writer to fields in `struct cred`? I need to verify that `struct cred` is immutable once it's shared. I need to search for writes to `uid`, `gid`, etc. Typically they're only set in `prepare_creds` or `cred_alloc_blank` *before* the credential is committed. Let's look at `commit_creds`.
|
| 41/2 |
2026/07/06 22:20 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:commit_creds]
Results: map[SourceCode: 354: /**
355: * commit_creds - Install new credentials upon the current task
356: * @new: The credentials to be assigned
357: *
358: * Install a new set of credentials to the current task, using RCU to replace
359: * the old set. Both the objective and the subjective credentials pointers are
360: * updated. This function may not be called if the subjective credentials are
361: * in an overridden state.
362: *
363: * This function eats the caller's reference to the new credentials.
364: *
365: * Always returns 0 thus allowing this function to be tail-called at the end
366: * of, say, sys_setgid().
367: */
368: int commit_creds(struct cred *new)
369: {
370: struct task_struct *task = current;
371: const struct cred *old = task->real_cred;
372:
373: kdebug("commit_creds(%p{%ld})", new,
374: atomic_long_read(&new->usage));
375:
376: BUG_ON(task->cred != old);
377: BUG_ON(atomic_long_read(&new->usage) < 1);
378:
379: get_cred(new); /* we will require a ref for the subj creds too */
380:
381: /* dumpability changes */
382: if (!uid_eq(old->euid, new->euid) ||
383: !gid_eq(old->egid, new->egid) ||
384: !uid_eq(old->fsuid, new->fsuid) ||
385: !gid_eq(old->fsgid, new->fsgid) ||
386: !cred_cap_issubset(old, new)) {
387: /* mm-less tasks share init_task's exec_state */
388: if (task->mm)
389: task_exec_state_set_dumpable(suid_dumpable);
390: task->pdeath_signal = 0;
391: /*
392: * If a task drops privileges and becomes nondumpable,
393: * the dumpability change must become visible before
394: * the credential change; otherwise, a __ptrace_may_access()
395: * racing with this change may be able to attach to a task it
396: * shouldn't be able to attach to (as if the task had dropped
397: * privileges without becoming nondumpable).
398: * Pairs with a read barrier in __ptrace_may_access().
399: */
400: smp_wmb();
401: }
402:
403: /* alter the thread keyring */
404: if (!uid_eq(new->fsuid, old->fsuid))
405: key_fsuid_changed(new);
406: if (!gid_eq(new->fsgid, old->fsgid))
407: key_fsgid_changed(new);
408:
409: /* do it
410: * RLIMIT_NPROC limits on user->processes have already been checked
411: * in set_user().
412: */
413: if (new->user != old->user || new->user_ns != old->user_ns)
414: inc_rlimit_ucounts(new->ucounts, UCOUNT_RLIMIT_NPROC, 1);
415:
416: rcu_assign_pointer(task->real_cred, new);
417: rcu_assign_pointer(task->cred, new);
418: if (new->user != old->user || new->user_ns != old->user_ns)
419: dec_rlimit_ucounts(old->ucounts, UCOUNT_RLIMIT_NPROC, 1);
420: if (new->user_ns != old->user_ns)
421: switch_cred_namespaces(old, new);
422:
423: /* send notifications */
424: if (!uid_eq(new->uid, old->uid) ||
425: !uid_eq(new->euid, old->euid) ||
426: !uid_eq(new->suid, old->suid) ||
427: !uid_eq(new->fsuid, old->fsuid))
428: proc_id_connector(task, PROC_EVENT_UID);
429:
430: if (!gid_eq(new->gid, old->gid) ||
431: !gid_eq(new->egid, old->egid) ||
432: !gid_eq(new->sgid, old->sgid) ||
433: !gid_eq(new->fsgid, old->fsgid))
434: proc_id_connector(task, PROC_EVENT_GID);
435:
436: /* release the old obj and subj refs both */
437: put_cred_many(old, 2);
438: return 0;
439: }
SourceFile:kernel/cred.c]
|
| 42/2 |
2026/07/06 22:20 |
llm |
expert |
0m
Model:
Tokens:
input: 47137
output: 24
thoughts: 118
Thoughts: **Analyzing Credential Sharing in the Kernel**
Okay, so I'm digging into this credential management code. My understanding is that `commit_creds` is fundamentally replacing pointers; it's not actually *modifying* the original `old` cred structure. That's a key point.
This means the only modifications that can happen to a shared `struct cred` are related to the `usage` counter and the `non_rcu` flag. And, if I'm following this correctly, *both* of those fields get completely overwritten during `prepare_creds`. This should make it a little more straightforward, but I have to be sure.
Therefore, the race condition I was concerned about *should* be benign in this situation, but I need to be 100% sure. I want to double-check that `non_rcu` isn't being set to 1 by anything else in the codebase. I need to make certain it's only manipulated through these mechanisms.
I will use `git log -G "non_rcu = 1"` to look for recent commits or other locations where `non_rcu` might be modified. I'll search for changes that could impact the analysis I'm currently undertaking. It's best to be thorough here.
|
| 43/2 |
2026/07/06 22:20 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:non_rcu = 1]
Results:
|
| 44/2 |
2026/07/06 22:30 |
llm |
expert |
0m
Model:
Tokens:
input: 47589
output: 64
thoughts: 15
Thoughts: Okay, here's my summary, expressed in the first person, as if these were my immediate thoughts on the matter:
**Navigating the Kernel's Landscape**
Alright, let's see... I need to find the relevant code, and I'm pretty sure it's going to be nestled deep within the kernel. Given the nature of the task, my initial instinct is to focus my search on two specific areas: the `kernel/` directory, and the `fs/` directory. The `kernel/` directory is the heart of the system, so there's a high probability of finding foundational logic there. On the other hand, filesystem interactions are often intricately tied to the behavior I'm investigating, so the `fs/` directory is also a very likely candidate. I'll start there and see what I turn up, keeping my eye out for any clues that might point me toward a more specific subdirectory or file. It's a broad starting point, but it should give me a good lay of the land to begin my investigation.
|
| 45/2 |
2026/07/06 22:31 |
tool |
git-log |
0m
Args: map[CodeRegexp:non_rcu = 1 PathPrefix:kernel/]
Results:
|
| 46/2 |
2026/07/06 22:32 |
tool |
git-log |
1m
Args: map[CodeRegexp:non_rcu = 1 PathPrefix:fs/]
Results: map[Output:d7852fbd0f04 access: avoid the RCU grace period for the temporary subjective credentials
]
|
| 47/2 |
2026/07/06 22:33 |
llm |
expert |
0m
Model:
Tokens:
input: 47936
output: 26
thoughts: 8
Thoughts: Okay, let's dive into this. Here's my take on those "thoughts":
**Analyzing the Commit**
Right, so the first thing on the agenda is to *really* look at this commit. I'm going to carefully dissect its contents, line by line if necessary. I want to understand the rationale behind the changes β the "why" and the "how." What problem was this commit trying to solve? Were there any potential trade-offs made? Were best practices adhered to? I'll be looking for any potential performance bottlenecks or subtle bugs that could be introduced. My focus will be on ensuring the code is robust, maintainable, and aligned with the project's overall architecture. I'll need to assess the level of testing performed, and identify whether any further validation is needed before this is integrated.
|
| 48/2 |
2026/07/06 22:34 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d7852fbd0f0423937fa287a598bfde188bb68c22
Author: Linus Torvalds <torvalds@linux-foundation.org>
Date: Thu Jul 11 09:54:40 2019 -0700
access: avoid the RCU grace period for the temporary subjective credentials
It turns out that 'access()' (and 'faccessat()') can cause a lot of RCU
work because it installs a temporary credential that gets allocated and
freed for each system call.
The allocation and freeing overhead is mostly benign, but because
credentials can be accessed under the RCU read lock, the freeing
involves a RCU grace period.
Which is not a huge deal normally, but if you have a lot of access()
calls, this causes a fair amount of seconday damage: instead of having a
nice alloc/free patterns that hits in hot per-CPU slab caches, you have
all those delayed free's, and on big machines with hundreds of cores,
the RCU overhead can end up being enormous.
But it turns out that all of this is entirely unnecessary. Exactly
because access() only installs the credential as the thread-local
subjective credential, the temporary cred pointer doesn't actually need
to be RCU free'd at all. Once we're done using it, we can just free it
synchronously and avoid all the RCU overhead.
So add a 'non_rcu' flag to 'struct cred', which can be set by users that
know they only use it in non-RCU context (there are other potential
users for this). We can make it a union with the rcu freeing list head
that we need for the RCU case, so this doesn't need any extra storage.
Note that this also makes 'get_current_cred()' clear the new non_rcu
flag, in case we have filesystems that take a long-term reference to the
cred and then expect the RCU delayed freeing afterwards. It's not
entirely clear that this is required, but it makes for clear semantics:
the subjective cred remains non-RCU as long as you only access it
synchronously using the thread-local accessors, but you _can_ use it as
a generic cred if you want to.
It is possible that we should just remove the whole RCU markings for
->cred entirely. Only ->real_cred is really supposed to be accessed
through RCU, and the long-term cred copies that nfs uses might want to
explicitly re-enable RCU freeing if required, rather than have
get_current_cred() do it implicitly.
But this is a "minimal semantic changes" change for the immediate
problem.
Acked-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Acked-by: Eric Dumazet <edumazet@google.com>
Acked-by: Paul E. McKenney <paulmck@linux.ibm.com>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: Jan Glauber <jglauber@marvell.com>
Cc: Jiri Kosina <jikos@kernel.org>
Cc: Jayachandran Chandrasekharan Nair <jnair@marvell.com>
Cc: Greg KH <greg@kroah.com>
Cc: Kees Cook <keescook@chromium.org>
Cc: David Howells <dhowells@redhat.com>
Cc: Miklos Szeredi <miklos@szeredi.hu>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/fs/open.c b/fs/open.c
index b5b80469b93d..a59abe3c669a 100644
--- a/fs/open.c
+++ b/fs/open.c
@@ -374,6 +374,25 @@ long do_faccessat(int dfd, const char __user *filename, int mode)
override_cred->cap_permitted;
}
+ /*
+ * The new set of credentials can *only* be used in
+ * task-synchronous circumstances, and does not need
+ * RCU freeing, unless somebody then takes a separate
+ * reference to it.
+ *
+ * NOTE! This is _only_ true because this credential
+ * is used purely for override_creds() that installs
+ * it as the subjective cred. Other threads will be
+ * accessing ->real_cred, not the subjective cred.
+ *
+ * If somebody _does_ make a copy of this (using the
+ * 'get_current_cred()' function), that will clear the
+ * non_rcu field, because now that other user may be
+ * expecting RCU freeing. But normal thread-synchronous
+ * cred accesses will keep things non-RCY.
+ */
+ override_cred->non_rcu = 1;
+
old_cred = override_creds(override_cred);
retry:
res = user_path_at(dfd, filename, lookup_flags, &path);
diff --git a/include/linux/cred.h b/include/linux/cred.h
index 7eb43a038330..f7a30e0099be 100644
--- a/include/linux/cred.h
+++ b/include/linux/cred.h
@@ -145,7 +145,11 @@ struct cred {
struct user_struct *user; /* real user ID subscription */
struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
struct group_info *group_info; /* supplementary groups for euid/fsgid */
- struct rcu_head rcu; /* RCU deletion hook */
+ /* RCU deletion */
+ union {
+ int non_rcu; /* Can we skip RCU deletion? */
+ struct rcu_head rcu; /* RCU deletion hook */
+ };
} __randomize_layout;
extern void __put_cred(struct cred *);
@@ -246,6 +250,7 @@ static inline const struct cred *get_cred(const struct cred *cred)
if (!cred)
return cred;
validate_creds(cred);
+ nonconst_cred->non_rcu = 0;
return get_new_cred(nonconst_cred);
}
@@ -257,6 +262,7 @@ static inline const struct cred *get_cred_rcu(const struct cred *cred)
if (!atomic_inc_not_zero(&nonconst_cred->usage))
return NULL;
validate_creds(cred);
+ nonconst_cred->non_rcu = 0;
return cred;
}
diff --git a/kernel/cred.c b/kernel/cred.c
index c73a87a4df13..153ae369e024 100644
--- a/kernel/cred.c
+++ b/kernel/cred.c
@@ -144,7 +144,10 @@ void __put_cred(struct cred *cred)
BUG_ON(cred == current->cred);
BUG_ON(cred == current->real_cred);
- call_rcu(&cred->rcu, put_cred_rcu);
+ if (cred->non_rcu)
+ put_cred_rcu(&cred->rcu);
+ else
+ call_rcu(&cred->rcu, put_cred_rcu);
}
EXPORT_SYMBOL(__put_cred);
@@ -256,6 +259,7 @@ struct cred *prepare_creds(void)
old = task->cred;
memcpy(new, old, sizeof(struct cred));
+ new->non_rcu = 0;
atomic_set(&new->usage, 1);
set_cred_subscribers(new, 0);
get_group_info(new->group_info);
@@ -535,7 +539,19 @@ const struct cred *override_creds(const struct cred *new)
validate_creds(old);
validate_creds(new);
- get_cred(new);
+
+ /*
+ * NOTE! This uses 'get_new_cred()' rather than 'get_cred()'.
+ *
+ * That means that we do not clear the 'non_rcu' flag, since
+ * we are only installing the cred into the thread-synchronous
+ * '->cred' pointer, not the '->real_cred' pointer that is
+ * visible to other threads under RCU.
+ *
+ * Also note that we did validate_creds() manually, not depending
+ * on the validation in 'get_cred()'.
+ */
+ get_new_cred((struct cred *)new);
alter_cred_subscribers(new, 1);
rcu_assign_pointer(current->cred, new);
alter_cred_subscribers(old, -1);
@@ -672,6 +688,7 @@ struct cred *prepare_kernel_cred(struct task_struct *daemon)
validate_creds(old);
*new = *old;
+ new->non_rcu = 0;
atomic_set(&new->usage, 1);
set_cred_subscribers(new, 0);
get_uid(new->user);
]
|
| 49/2 |
2026/07/06 22:34 |
llm |
expert |
0m
Model:
Tokens:
input: 50600
output: 35
thoughts: 1604
Thoughts: **Analyzing `override_creds` and Credential Handling in the Kernel**
Okay, so I'm looking at this diff and the function `override_creds`. The key thing is that it uses `get_new_cred()` instead of `get_cred()`. This means `non_rcu` isn't cleared immediately, which has me thinking about how this could affect multi-threaded operations and the visibility of credentials. The comments point out that `->cred` is the thread-specific credential, and `->real_cred` is the one visible to other threads under RCU. I have to think through whether `non_rcu = 1` on `current->cred` creates a potential race condition.
If a thread modifies its `->cred` to have `non_rcu = 1`, only that thread should see it because it has its own `task_struct` and thus its own `cred` and `real_cred` pointers. Typically, a thread's `real_cred` and `cred` point to the same credential structure. If a thread calls `override_creds`, it only changes its own `cred`. The other threads should not see a change.
If a thread calls `get_cred(current->cred)`, it's the same thread, no race. Likewise, if `fork()` is called, `copy_creds` will call `get_cred(p->cred)`, which clears `non_rcu`, which is fine, because it is in the same thread.
My understanding is that if there is a shared credential, `non_rcu` will be zero. Only private threads can make `non_rcu = 1`.
But wait, what about inter-process credential sharing after `fork()`? When `copy_creds` is called, `get_cred` is also called on the shared object and `non_rcu` will be cleared, so that shouldn't matter.
Now, I'm trying to think of scenarios where a shared `struct cred` might have `non_rcu = 1`. Could a thread with a `non_rcu = 1` credential use a syscall that involves credential-related operations, like `perf_event_open`? It might call `alloc_empty_file` using `current_cred()`, which, I think returns the private cred. But then the kernel calls `init_file`, which calls `get_cred(cred)` to clear `non_rcu`, so that won't work either.
I'm thinking! Task A2 cannot see Task A1's subjective cred. I thought of a possible race, where Task A2 is a child of Task A1. That won't work, because the syscall doesn't fork. Nor is it another thread of the same process.
Then I realized! `prepare_creds` reads `task->cred`. So, if Task 7106 is reading its own `cred` and Task 7107 is writing to its own, they're distinct tasks, so they have different `task_struct`s. They each have a different `cred` pointer. The race can happen when their `cred` pointers point to the same object. That would imply the object is shared, so `non_rcu = 0`. This means it would effectively be a write of zero to a zero value. This makes sense!
I should also make sure that `usage` is also not subject to races. The usage field and the `non_rcu` are the only potentially modified variables in `get_cred_many`, and `get_cred_rcu`. So, I'm checking `validate_creds`, just in case it can cause some modification when it's not set. Turns out the validation macro doesn't do anything unless `CONFIG_DEBUG_CREDENTIALS` is enabled. If it is enabled, it may read some fields. I've covered everything.
|
| 50/2 |
2026/07/06 22:35 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:include/linux/cred.h Name:validate_creds]
Results: map[SourceCode: SourceFile:]
|
| 51/2 |
2026/07/06 22:35 |
llm |
expert |
0m
Model:
Tokens:
input: 53106
output: 20
thoughts: 7
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Initial Assessment: Probable Macro Suspect**
Alright, that's what I'm thinking, based on the initial information. My instincts are immediately leaning toward this being a macro, given the likely context. The patterns, the potential automated nature⦠all of it suggests the telltale signs of a macro at work. It's a hunch, of course, and I need more data before I confirm anything. But based on the initial read, this is where my primary focus would be. I need to delve deeper into its structure to be certain.
|
| 52/2 |
2026/07/06 22:35 |
tool |
grepper |
0m
Error:
Args: map[Expression:#define validate_creds]
Results:
|
| 53/2 |
2026/07/06 22:35 |
llm |
expert |
0m
Model:
Tokens:
input: 53287
output: 34
thoughts: 18
Thoughts: Here's my thought process, as if I were considering this myself:
**Investigating Credential Structures**
Okay, I need to find the definition for this credential structure. Where would that be? Let me think...given this is Linux kernel code, the standard location for core kernel data structures like that would most likely be in the `include/linux` directory. Now, within `include/linux`, the most likely place for anything security related or dealing with user identity would be `cred.h`. So, I'll start my search there. That's the most logical first step. Hopefully, it's defined and well-commented. If not, I'll need to widen the search, but let's begin there.
|
| 54/2 |
2026/07/06 22:36 |
tool |
read-file |
0m
Args: map[File:include/linux/cred.h FirstLine:1 LineCount:100]
Results: map[Contents: 1: /* SPDX-License-Identifier: GPL-2.0-or-later */
2: /* Credentials management - see Documentation/security/credentials.rst
3: *
4: * Copyright (C) 2008 Red Hat, Inc. All Rights Reserved.
5: * Written by David Howells (dhowells@redhat.com)
6: */
7:
8: #ifndef _LINUX_CRED_H
9: #define _LINUX_CRED_H
10:
11: #include <linux/capability.h>
12: #include <linux/init.h>
13: #include <linux/key.h>
14: #include <linux/atomic.h>
15: #include <linux/refcount.h>
16: #include <linux/uidgid.h>
17: #include <linux/sched.h>
18: #include <linux/sched/user.h>
19:
20: struct cred;
21: struct inode;
22:
23: extern struct task_struct init_task;
24:
25: /*
26: * COW Supplementary groups list
27: */
28: struct group_info {
29: refcount_t usage;
30: int ngroups;
31: kgid_t gid[];
32: } __randomize_layout;
33:
34: /**
35: * get_group_info - Get a reference to a group info structure
36: * @gi: The group info to reference
37: *
38: * This gets a reference to a set of supplementary groups.
39: *
40: * If the caller is accessing a task's credentials, they must hold the RCU read
41: * lock when reading.
42: *
43: * Returns: @gi
44: */
45: static inline struct group_info *get_group_info(struct group_info *gi)
46: {
47: refcount_inc(&gi->usage);
48: return gi;
49: }
50:
51: /**
52: * put_group_info - Release a reference to a group info structure
53: * @group_info: The group info to release
54: */
55: #define put_group_info(group_info) \
56: do { \
57: if (refcount_dec_and_test(&(group_info)->usage)) \
58: groups_free(group_info); \
59: } while (0)
60:
61: #ifdef CONFIG_MULTIUSER
62: extern struct group_info *groups_alloc(int);
63: extern void groups_free(struct group_info *);
64:
65: extern int in_group_p(kgid_t);
66: extern int in_egroup_p(kgid_t);
67: extern int groups_search(const struct group_info *, kgid_t);
68:
69: extern int set_current_groups(struct group_info *);
70: extern void set_groups(struct cred *, struct group_info *);
71: extern bool may_setgroups(void);
72: extern void groups_sort(struct group_info *);
73: #else
74: static inline void groups_free(struct group_info *group_info)
75: {
76: }
77:
78: static inline int in_group_p(kgid_t grp)
79: {
80: return 1;
81: }
82: static inline int in_egroup_p(kgid_t grp)
83: {
84: return 1;
85: }
86: static inline int groups_search(const struct group_info *group_info, kgid_t grp)
87: {
88: return 1;
89: }
90: #endif
91:
92: /*
93: * The security context of a task
94: *
95: * The parts of the context break down into two categories:
96: *
97: * (1) The objective context of a task. These parts are used when some other
98: * task is attempting to affect this one.
99: *
100: * (2) The subjective context. These details are used when the task is acting
]
|
| 55/2 |
2026/07/06 22:36 |
llm |
expert |
0m
Model:
Tokens:
input: 54787
output: 31
thoughts: 16
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Checking for the Credential Validation Function**
Alright, let's get down to it. I need to figure out where this credential validation is happening in this code. My immediate thought is to perform a thorough search. I'll initiate a search for the function or method named `validate_creds`. Given my experience, a full-file search is the most efficient way to locate where this critical piece of the security puzzle is implemented and referenced. I need to understand its context and how it's being used. Let's see what that search turns up.
|
| 56/2 |
2026/07/06 22:37 |
tool |
grepper |
0m
Error:
Args: map[Expression:validate_creds PathPrefix:include/linux/cred.h]
Results:
|
| 57/2 |
2026/07/06 22:37 |
llm |
expert |
0m
Model:
Tokens:
input: 54981
output: 30
thoughts: 186
Thoughts: **Tracing the `non_rcu` Field**
Okay, so I was looking for the `non_rcu` field, expecting it to be right there in `include/linux/cred.h`. Huh, that's odd, it wasn't there? I could have sworn I saw it in the `git show` output related to `cred.h`. Maybe it was removed later in the project history. Let's dig deeper.
Right, time to re-examine that `git show` output carefully. Okay, here it is: the lines from the `git show` output clearly show `nonconst_cred->non_rcu = 0;` being added within the `get_cred` function. This makes more sense now. I should search for `get_cred` instead in `include/linux/cred.h` and try to trace this down. That will certainly clear things up.
|
| 58/2 |
2026/07/06 22:37 |
tool |
grepper |
0m
Args: map[Expression:get_cred PathPrefix:include/linux/cred.h]
Results: map[Output:include/linux/cred.h=191=DEFINE_CLASS(override_creds,
--
include/linux/cred.h-201-/**
include/linux/cred.h:202: * get_cred_many - Get references on a set of credentials
include/linux/cred.h-203- * @cred: The credentials to reference
--
include/linux/cred.h-216- */
include/linux/cred.h:217:static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
include/linux/cred.h-218-{
--
include/linux/cred.h-227-/*
include/linux/cred.h:228: * get_cred - Get a reference on a set of credentials
include/linux/cred.h-229- * @cred: The credentials to reference
--
include/linux/cred.h-235- */
include/linux/cred.h:236:static inline const struct cred *get_cred(const struct cred *cred)
include/linux/cred.h-237-{
include/linux/cred.h:238: return get_cred_many(cred, 1);
include/linux/cred.h-239-}
include/linux/cred.h-240-
include/linux/cred.h:241:static inline const struct cred *get_cred_rcu(const struct cred *cred)
include/linux/cred.h-242-{
--
include/linux/cred.h=291=DEFINE_FREE(put_cred, struct cred *, if (!IS_ERR_OR_NULL(_T)) put_cred(_T))
--
include/linux/cred.h-317- *
include/linux/cred.h:318: * The result of this function should not be passed directly to get_cred();
include/linux/cred.h-319- * rather get_task_cred() should be used instead.
--
include/linux/cred.h-331-#define get_current_cred() \
include/linux/cred.h:332: (get_cred(current_cred()))
include/linux/cred.h-333-
]
|
| 59/2 |
2026/07/06 22:37 |
llm |
expert |
0m
Model:
Tokens:
input: 55945
output: 35
thoughts: 22
Thoughts: Here's my take on those thoughts, tailored for an expert audience:
**Diving into Credential Handling**
Alright, let's zero in on `get_cred_many` within `include/linux/cred.h`. My immediate instinct is to dissect its purpose and implementation within the broader security context of the kernel. I'm thinking about the implications of *multiple* credential acquisition β what scenarios necessitate it? Is it a performance optimization for concurrent processes or a mechanism for more complex permission schemes? Understanding the motivations behind `get_cred_many` is key to gauging its potential vulnerabilities and ensuring it aligns with the principle of least privilege. I need to consider potential race conditions, atomicity guarantees, and any implications regarding credential propagation. I want to see if it supports any specific types of credentials or if it's a general-purpose mechanism. I'm already anticipating the typical questions: how is this related to user namespaces, security modules like SELinux or AppArmor, and if it interacts with capabilities in any interesting way. My next step will be to thoroughly review the surrounding code, considering access control, reference counting, and any associated locking mechanisms to understand the integrity and security of the credential handling process.
|
| 60/2 |
2026/07/06 22:37 |
tool |
read-file |
0m
Args: map[File:include/linux/cred.h FirstLine:217 LineCount:20]
Results: map[Contents: 217: static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
218: {
219: struct cred *nonconst_cred = (struct cred *) cred;
220: if (!cred)
221: return cred;
222: nonconst_cred->non_rcu = 0;
223: atomic_long_add(nr, &nonconst_cred->usage);
224: return cred;
225: }
226:
227: /*
228: * get_cred - Get a reference on a set of credentials
229: * @cred: The credentials to reference
230: *
231: * Get a reference on the specified set of credentials. The caller must
232: * release the reference. If %NULL is passed, it is returned with no action.
233: *
234: * This is used to deal with a committed set of credentials.
235: */
236: static inline const struct cred *get_cred(const struct cred *cred)
]
|
| 61/2 |
2026/07/06 22:38 |
llm |
expert |
0m
Model:
Tokens:
input: 56570
output: 153
thoughts: 195
Thoughts: **Analyzing the Credential Data Race**
Okay, so there's no `validate_creds` function present here, which is interesting. It seems to have been removed at some point. But, as things stand, the current code snippet I'm looking at only seems to modify `non_rcu` and `usage` within the `struct cred` structure.
This immediately brings up a potential data race between `get_cred_many`, which is *writing* to those two fields, and `prepare_creds`, which is *reading* the entire `struct cred` through a `memcpy` operation.
However, after a closer look, it seems benign. `prepare_creds` immediately *overwrites* both `non_rcu` and `usage` in the copy it makes. And, as far as I can see, these two are the only fields being modified in the source `struct cred`. Therefore, regardless of the values `get_cred_many` sets, `prepare_creds` will overwrite them. `non_rcu` is likely zero to begin with, and the `usage` value read is effectively ignored, which makes this race harmless.
I should double-check, though, to make absolutely sure. It's best to be thorough. I'm going to run `codeexpert` now to see if there are any other fields that could be modified within that `struct cred` context. Safety first.
|
| 62/2 |
2026/07/06 22:38 |
tool |
codeexpert |
28m
Args: map[Question:In the Linux kernel, are there any fields in 'struct cred' that are modified in-place after the credentials have been committed (i.e., assigned to a task's 'real_cred' or 'cred' pointers), other than 'usage' and 'non_rcu'?
Specifically, I am looking for potential data races when 'prepare_creds' calls 'memcpy(new, old, sizeof(struct cred))' while another thread is calling 'get_cred(old)'.
If only 'usage' and 'non_rcu' are modified, and 'prepare_creds' overwrites them in the copy, is the race benign?]
Results: map[Answer:In the Linux kernel, `struct cred` is designed to be **immutable** once it has been committed to a task (i.e., assigned to `task->real_cred` or `task->cred`). This immutability is enforced by the credential API, which requires callers to prepare a new copy of the credentials, modify the copy, and then commit it.
### In-place Modifications
The only fields in `struct cred` that are modified in-place after the credentials have been committed are:
1. **`usage`**: This is an `atomic_long_t` used for reference counting. It is modified by `get_cred()`, `put_cred()`, and their variants.
2. **`non_rcu`**: This is an `int` (part of a union with `rcu_head`) used as an optimization flag to indicate whether the credential can be freed synchronously without waiting for an RCU grace period. It is modified (set to `0`) by `get_cred_many()` and `get_cred_rcu()` to ensure that once a credential is shared, it is freed via RCU.
All other fields, including UIDs, GIDs, capabilities, and pointers to other structures (like `user_struct`, `group_info`, `keyrings`, and `security`), are only modified on a "new" `struct cred` that has been allocated (e.g., via `prepare_creds()`) but not yet committed.
### Data Race in `prepare_creds`
The race you identified occurs in `prepare_creds()` (defined in `kernel/cred.c`):
```c
new = kmem_cache_alloc(cred_jar, GFP_KERNEL);
...
old = task->cred;
memcpy(new, old, sizeof(struct cred));
new->non_rcu = 0;
atomic_long_set(&new->usage, 1);
```
While `memcpy` is copying the bytes from `old` to `new`, another thread might be concurrently calling `get_cred(old)`, which performs:
```c
nonconst_cred->non_rcu = 0;
atomic_long_add(nr, &nonconst_cred->usage);
```
### Is the race benign?
**Yes, the race is benign.**
Even if `memcpy` picks up an inconsistent or "torn" value for `usage` or `non_rcu` because they were being modified concurrently, it does not matter. `prepare_creds()` immediately overwrites these fields in the `new` structure:
* `new->non_rcu = 0;`
* `atomic_long_set(&new->usage, 1);`
The values copied by `memcpy` for these two fields are never used. Since no other fields in `old` are modified in-place, `memcpy` is guaranteed to pick up a consistent state for all other fields (which are immutable).
The `old` credential itself is protected from being freed during this operation because the caller (`current`) holds a reference to it via `task->cred`.
### Summary of Field Handling
* **Pointers (`user`, `group_info`, etc.)**: `prepare_creds` copies the pointers via `memcpy` and then increments the reference counts of the underlying objects (e.g., `get_uid(new->user)`). The pointers themselves in `old` never change.
* **LSM Security (`security`)**: The `security` pointer is copied by `memcpy`, but then `new->security` is set to `NULL` and reallocated/repopulated via `security_prepare_creds(new, old, ...)`. This allows LSMs to safely copy their private data.
* **RCU Head (`rcu`)**: The `rcu_head` is only used when the credential's `usage` reaches zero. Since `prepare_creds` operates on a live task's credentials (`usage >= 1`), the `rcu_head` is not in use.]
|
| 63/3 |
2026/07/06 22:38 |
agent |
codeexpert |
28m
Model:
Instruction:
You are a capable Linux kernel developer tasked with researching complex questions
about kernel source code. You will be given a concrete question, and need to provide
a concrete answer.
Use tools extensively while researching the question. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search ('grepper') or
directory listing ('codesearch-dir-index'), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Do NOT use 'git-log' to search for the presence or existence of files in the
repository. 'git-log' is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad 'git-log' queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a 'git-log' tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
Prefer calling several tools at the same time to save round-trips.
Prompt: In the Linux kernel, are there any fields in 'struct cred' that are modified in-place after the credentials have been committed (i.e., assigned to a task's 'real_cred' or 'cred' pointers), other than 'usage' and 'non_rcu'?
Specifically, I am looking for potential data races when 'prepare_creds' calls 'memcpy(new, old, sizeof(struct cred))' while another thread is calling 'get_cred(old)'.
If only 'usage' and 'non_rcu' are modified, and 'prepare_creds' overwrites them in the copy, is the race benign?
Reply: In the Linux kernel, `struct cred` is designed to be **immutable** once it has been committed to a task (i.e., assigned to `task->real_cred` or `task->cred`). This immutability is enforced by the credential API, which requires callers to prepare a new copy of the credentials, modify the copy, and then commit it.
### In-place Modifications
The only fields in `struct cred` that are modified in-place after the credentials have been committed are:
1. **`usage`**: This is an `atomic_long_t` used for reference counting. It is modified by `get_cred()`, `put_cred()`, and their variants.
2. **`non_rcu`**: This is an `int` (part of a union with `rcu_head`) used as an optimization flag to indicate whether the credential can be freed synchronously without waiting for an RCU grace period. It is modified (set to `0`) by `get_cred_many()` and `get_cred_rcu()` to ensure that once a credential is shared, it is freed via RCU.
All other fields, including UIDs, GIDs, capabilities, and pointers to other structures (like `user_struct`, `group_info`, `keyrings`, and `security`), are only modified on a "new" `struct cred` that has been allocated (e.g., via `prepare_creds()`) but not yet committed.
### Data Race in `prepare_creds`
The race you identified occurs in `prepare_creds()` (defined in `kernel/cred.c`):
```c
new = kmem_cache_alloc(cred_jar, GFP_KERNEL);
...
old = task->cred;
memcpy(new, old, sizeof(struct cred));
new->non_rcu = 0;
atomic_long_set(&new->usage, 1);
```
While `memcpy` is copying the bytes from `old` to `new`, another thread might be concurrently calling `get_cred(old)`, which performs:
```c
nonconst_cred->non_rcu = 0;
atomic_long_add(nr, &nonconst_cred->usage);
```
### Is the race benign?
**Yes, the race is benign.**
Even if `memcpy` picks up an inconsistent or "torn" value for `usage` or `non_rcu` because they were being modified concurrently, it does not matter. `prepare_creds()` immediately overwrites these fields in the `new` structure:
* `new->non_rcu = 0;`
* `atomic_long_set(&new->usage, 1);`
The values copied by `memcpy` for these two fields are never used. Since no other fields in `old` are modified in-place, `memcpy` is guaranteed to pick up a consistent state for all other fields (which are immutable).
The `old` credential itself is protected from being freed during this operation because the caller (`current`) holds a reference to it via `task->cred`.
### Summary of Field Handling
* **Pointers (`user`, `group_info`, etc.)**: `prepare_creds` copies the pointers via `memcpy` and then increments the reference counts of the underlying objects (e.g., `get_uid(new->user)`). The pointers themselves in `old` never change.
* **LSM Security (`security`)**: The `security` pointer is copied by `memcpy`, but then `new->security` is set to `NULL` and reallocated/repopulated via `security_prepare_creds(new, old, ...)`. This allows LSMs to safely copy their private data.
* **RCU Head (`rcu`)**: The `rcu_head` is only used when the credential's `usage` reaches zero. Since `prepare_creds` operates on a live task's credentials (`usage >= 1`), the `rcu_head` is not in use.
|
| 64/4 |
2026/07/06 22:38 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 3767
output: 17
thoughts: 119
Thoughts: **Analyzing Potential Data Races in the Linux Kernel's `struct cred`**
Okay, so I'm being asked to delve into potential data race scenarios within the `struct cred` structure in the Linux kernel. The user is specifically concerned about fields that are modified in-place *after* the `cred` has been assigned to a task, excluding the standard `usage` and `non_rcu` fields, which are typically managed with atomics or RCU. This makes sense; these two are likely well-understood. The focus is likely to be on less obvious fields.
I also need to address a specific race: the interplay between `prepare_creds`, which frequently involves a `memcpy` of the `cred` structure, and `get_cred`, which increments the `usage` count. This sounds like the core concern, and the user is wanting me to assess whether this is safe.
So, first things first. I need to get my hands dirty and find the definitive definition of `struct cred` in the kernel source code. I need to refresh my memory on all the member fields and how they're intended to be used. I will need to look through the surrounding code. Then, I can start to think about the possible data races or concurrency issues on a deeper level.
|
| 65/4 |
2026/07/06 22:38 |
tool |
grepper |
0m
Args: map[Expression:struct cred \{]
Results: map[Output:include/linux/cred.h=86=static inline int groups_search(const struct group_info *group_info, kgid_t grp)
--
include/linux/cred.h-114- */
include/linux/cred.h:115:struct cred {
include/linux/cred.h-116- atomic_long_t usage;
--
tools/testing/selftests/bpf/progs/test_deny_namespace.c=8=typedef struct { unsigned long long val; } kernel_cap_t;
tools/testing/selftests/bpf/progs/test_deny_namespace.c-9-
tools/testing/selftests/bpf/progs/test_deny_namespace.c:10:struct cred {
tools/testing/selftests/bpf/progs/test_deny_namespace.c-11- kernel_cap_t cap_effective;
]
|
| 66/4 |
2026/07/06 22:39 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4406
output: 35
thoughts: 24
Thoughts: Here's my analysis of the provided information, as if these were my internal thoughts:
**Dissecting the `struct cred` Definition**
Alright, let's dive right in. The kernel's security credentials, represented by the `struct cred`, are defined, as expected, within `include/linux/cred.h`. My immediate instinct is to crack open that header file and take a look at the structure itself. I'll need to understand the composition of this critical data structure, as I already know it represents a process's security context. Knowing precisely what information is stored within `struct cred` β the User ID (UID), Group ID (GID), Supplementary GIDs, perhaps security attributes like SELinux labels or AppArmor profiles (depending on the kernel configuration), and certainly reference counts β is the key to understanding how the kernel enforces permissions and access control. This is the foundation upon which so many security mechanisms are built, so a thorough understanding is paramount. From there I will want to trace calls and understand how the information gets populated in various circumstances.
|
| 67/4 |
2026/07/06 22:39 |
tool |
read-file |
0m
Args: map[File:include/linux/cred.h FirstLine:115 LineCount:50]
Results: map[Contents: 115: struct cred {
116: atomic_long_t usage;
117: kuid_t uid; /* real UID of the task */
118: kgid_t gid; /* real GID of the task */
119: kuid_t suid; /* saved UID of the task */
120: kgid_t sgid; /* saved GID of the task */
121: kuid_t euid; /* effective UID of the task */
122: kgid_t egid; /* effective GID of the task */
123: kuid_t fsuid; /* UID for VFS ops */
124: kgid_t fsgid; /* GID for VFS ops */
125: unsigned securebits; /* SUID-less security management */
126: kernel_cap_t cap_inheritable; /* caps our children can inherit */
127: kernel_cap_t cap_permitted; /* caps we're permitted */
128: kernel_cap_t cap_effective; /* caps we can actually use */
129: kernel_cap_t cap_bset; /* capability bounding set */
130: kernel_cap_t cap_ambient; /* Ambient capability set */
131: #ifdef CONFIG_KEYS
132: unsigned char jit_keyring; /* default keyring to attach requested
133: * keys to */
134: struct key *session_keyring; /* keyring inherited over fork */
135: struct key *process_keyring; /* keyring private to this process */
136: struct key *thread_keyring; /* keyring private to this thread */
137: struct key *request_key_auth; /* assumed request_key authority */
138: #endif
139: #ifdef CONFIG_SECURITY
140: void *security; /* LSM security */
141: #endif
142: struct user_struct *user; /* real user ID subscription */
143: struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
144: struct ucounts *ucounts;
145: struct group_info *group_info; /* supplementary groups for euid/fsgid */
146: /* RCU deletion */
147: union {
148: int non_rcu; /* Can we skip RCU deletion? */
149: struct rcu_head rcu; /* RCU deletion hook */
150: };
151: } __randomize_layout;
152:
153: extern void __put_cred(struct cred *);
154: extern void exit_creds(struct task_struct *);
155: extern int copy_creds(struct task_struct *, u64);
156: extern const struct cred *get_task_cred(struct task_struct *);
157: extern struct cred *cred_alloc_blank(void);
158: extern struct cred *prepare_creds(void);
159: extern struct cred *prepare_exec_creds(void);
160: extern int commit_creds(struct cred *);
161: extern void abort_creds(struct cred *);
162: extern struct cred *prepare_kernel_cred(struct task_struct *);
163: static inline const struct cred *kernel_cred(void)
164: {
]
|
| 68/4 |
2026/07/06 22:39 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 5651
output: 33
thoughts: 110
Thoughts: **Analyzing Credential Immutability**
Okay, so the user's raising a concern about potential in-place modifications after a credential set is committed, focusing specifically on `usage` (an `atomic_long_t`) and `non_rcu`, which is interestingly part of a union with `rcu_head`. This makes me think they're digging into the nuances of how these credentials are managed.
My immediate assumption is that, ideally, a `struct cred` should remain immutable after it's assigned to a task. The common exception, of course, is the reference count, which is designed to be modified. They're clearly looking for any violations of this immutability principle.
To get a better understanding of what might be happening, I'll need to dive into the `prepare_creds` function in `kernel/cred.c`. This is where the credential preparation takes place, and where in-place modification would be most likely. I need to understand what state it prepares and what, if anything, might be adjusted after a new cred is in use.
|
| 69/4 |
2026/07/06 22:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:prepare_creds]
Results: map[SourceCode: 165: /**
166: * prepare_creds - Prepare a new set of credentials for modification
167: *
168: * Prepare a new set of task credentials for modification. A task's creds
169: * shouldn't generally be modified directly, therefore this function is used to
170: * prepare a new copy, which the caller then modifies and then commits by
171: * calling commit_creds().
172: *
173: * Preparation involves making a copy of the objective creds for modification.
174: *
175: * Returns a pointer to the new creds-to-be if successful, NULL otherwise.
176: *
177: * Call commit_creds() or abort_creds() to clean up.
178: */
179: struct cred *prepare_creds(void)
180: {
181: struct task_struct *task = current;
182: const struct cred *old;
183: struct cred *new;
184:
185: new = kmem_cache_alloc(cred_jar, GFP_KERNEL);
186: if (!new)
187: return NULL;
188:
189: kdebug("prepare_creds() alloc %p", new);
190:
191: old = task->cred;
192: memcpy(new, old, sizeof(struct cred));
193:
194: new->non_rcu = 0;
195: atomic_long_set(&new->usage, 1);
196: get_group_info(new->group_info);
197: get_uid(new->user);
198: get_user_ns(new->user_ns);
199:
200: #ifdef CONFIG_KEYS
201: key_get(new->session_keyring);
202: key_get(new->process_keyring);
203: key_get(new->thread_keyring);
204: key_get(new->request_key_auth);
205: #endif
206:
207: #ifdef CONFIG_SECURITY
208: new->security = NULL;
209: #endif
210:
211: new->ucounts = get_ucounts(new->ucounts);
212: if (!new->ucounts)
213: goto error;
214:
215: if (security_prepare_creds(new, old, GFP_KERNEL_ACCOUNT) < 0)
216: goto error;
217:
218: return new;
219:
220: error:
221: abort_creds(new);
222: return NULL;
223: }
SourceFile:kernel/cred.c]
|
| 70/4 |
2026/07/06 22:40 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6864
output: 34
thoughts: 156
Thoughts: **My Credential Cloning and Usage Tracking Process**
Okay, so I'm looking at this `prepare_creds` function and how it handles credential copying. Line 192, the `memcpy`, immediately catches my eye. It's essentially duplicating the entire `struct cred` structure from `old` to `new`. `old` is, of course, the task's existing credentials, `task->cred`.
Right after, I see that this newly created `new` credential's `non_rcu` field gets set to 0. More importantly, I see that the `new` credential's usage count, `new->usage`, gets initialized to 1 using `atomic_long_set`. This is crucial: any external references to the original `old` credential will increment `old->usage` through the `get_cred` function. This makes sense; we want to track references and prevent premature freeing of credentials still in use by other parts of the system.
Now, I'm pretty certain that `get_cred` is declared in `include/linux/cred.h`. It must increment the usage counter on the `cred` structure being passed to it, so that there's not a race condition when the `old` cred is used by another task. We need to make sure that the system correctly tracks who is using these credentials. This all seems pretty standard for managing shared resources and ensuring memory safety in a multithreaded environment.
|
| 71/4 |
2026/07/06 22:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/cred.h Name:get_cred]
Results: map[SourceCode: 227: /*
228: * get_cred - Get a reference on a set of credentials
229: * @cred: The credentials to reference
230: *
231: * Get a reference on the specified set of credentials. The caller must
232: * release the reference. If %NULL is passed, it is returned with no action.
233: *
234: * This is used to deal with a committed set of credentials.
235: */
236: static inline const struct cred *get_cred(const struct cred *cred)
237: {
238: return get_cred_many(cred, 1);
239: }
SourceFile:include/linux/cred.h]
|
| 72/4 |
2026/07/06 22:40 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7589
output: 36
thoughts: 8
Thoughts: Okay, here's the summary, assuming I'm the one having these thoughts and that the user is an expert.
**Analyzing the `get_cred_many` Function**
Alright, let's break this down. The core of this problem seems to revolve around the functionality of `get_cred_many`. I need to understand its purpose and behavior thoroughly. I'm thinking about the edge cases immediately, of course. What happens if it's fed bad data? Does it handle concurrency effectively? Error handling has to be bulletproof here. What are the dependencies? Are there external services or libraries? I should scrutinize those interactions for potential bottlenecks or vulnerabilities. Specifically, I need to know where it's pulling the "credentials" from. Are we talking about database calls, API requests, or perhaps local files? The access method drastically changes the efficiency, and security implications. I'll need to focus on what happens if one credential retrieval fails - how gracefully does it handle that and prevent it from derailing the entire process? I also need to assess the underlying data structures it uses, particularly if it's caching any retrieved data; what are the cache invalidation strategies to avoid stale information? Memory footprint matters too, especially if this function is called frequently. The goal is to identify points of optimization or, even worse, potential vulnerabilities. My priority is to figure out if it's doing the job securely and efficiently.
|
| 73/4 |
2026/07/06 22:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/cred.h Name:get_cred_many]
Results: map[SourceCode: 201: /**
202: * get_cred_many - Get references on a set of credentials
203: * @cred: The credentials to reference
204: * @nr: Number of references to acquire
205: *
206: * Get references on the specified set of credentials. The caller must release
207: * all acquired reference. If %NULL is passed, it is returned with no action.
208: *
209: * This is used to deal with a committed set of credentials. Although the
210: * pointer is const, this will temporarily discard the const and increment the
211: * usage count. The purpose of this is to attempt to catch at compile time the
212: * accidental alteration of a set of credentials that should be considered
213: * immutable.
214: *
215: * Returns: @cred when the references are acquired, NULL otherwise.
216: */
217: static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
218: {
219: struct cred *nonconst_cred = (struct cred *) cred;
220: if (!cred)
221: return cred;
222: nonconst_cred->non_rcu = 0;
223: atomic_long_add(nr, &nonconst_cred->usage);
224: return cred;
225: }
SourceFile:include/linux/cred.h]
|
| 74/4 |
2026/07/06 22:40 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 8356
output: 33
thoughts: 491
Thoughts: **Analyzing Potential Race Conditions in Credential Handling**
Okay, so I'm looking at how credentials are handled, specifically focusing on potential race conditions. It looks like `get_cred_many` initializes `non_rcu` to zero and then increments the `usage` counter:
```c
nonconst_cred->non_rcu = 0;
atomic_long_add(nr, &nonconst_cred->usage);
```
My initial thought is, why is `non_rcu` being set to zero *every* time? Is that necessary? Then I immediately think about `prepare_creds`. It uses `memcpy` to copy the `struct cred`, which is concerning. If another thread is concurrently calling `get_cred(old)` while `prepare_creds` is doing `memcpy`, there's a race between `memcpy` and incrementing usage.
However, it copies the old `struct cred` into the new one, but *then* immediately overwrites the relevant fields in `new`:
```c
new->non_rcu = 0;
atomic_long_set(&new->usage, 1);
```
So, even if `memcpy` picks up an inconsistent state in `old`, it's irrelevant for the *new* credential, because those fields are reset. Good, that takes care of the immediate concern.
But this brings up a larger question: Are there *any other* fields within `struct cred` that are modified in-place? If so, `memcpy` might grab an inconsistent value if there's no atomic update, or if the field is being updated in multiple steps. More importantly, if `prepare_creds` copies a value that's about to change, or is in the middle of being changed, we're in trouble.
Then I remind myself, that `struct cred` is *supposed* to be immutable, right? The only fields that should be modified are `usage` and `non_rcu`. So, the question then becomes: are there other places where this invariant is violated? Let's check for any in-place modifications to fields within `struct cred`. Specifically, I need to search for assignments where the `cred` is not newly allocated, as happens in `prepare_creds`, `cred_alloc_blank`, and so on.
Thinking further, this is often handled by `const struct cred *` to *prevent* modification. That's good practice. I see `get_cred_many` uses an explicit cast to remove the `const` - let's focus on that too.
So the search terms are: instances of casts of `(struct cred *)` and places where a `const struct cred *` is actually modified.
Also, don't forget to look at `commit_creds`.
|
| 75/4 |
2026/07/06 22:41 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:commit_creds]
Results: map[SourceCode: 354: /**
355: * commit_creds - Install new credentials upon the current task
356: * @new: The credentials to be assigned
357: *
358: * Install a new set of credentials to the current task, using RCU to replace
359: * the old set. Both the objective and the subjective credentials pointers are
360: * updated. This function may not be called if the subjective credentials are
361: * in an overridden state.
362: *
363: * This function eats the caller's reference to the new credentials.
364: *
365: * Always returns 0 thus allowing this function to be tail-called at the end
366: * of, say, sys_setgid().
367: */
368: int commit_creds(struct cred *new)
369: {
370: struct task_struct *task = current;
371: const struct cred *old = task->real_cred;
372:
373: kdebug("commit_creds(%p{%ld})", new,
374: atomic_long_read(&new->usage));
375:
376: BUG_ON(task->cred != old);
377: BUG_ON(atomic_long_read(&new->usage) < 1);
378:
379: get_cred(new); /* we will require a ref for the subj creds too */
380:
381: /* dumpability changes */
382: if (!uid_eq(old->euid, new->euid) ||
383: !gid_eq(old->egid, new->egid) ||
384: !uid_eq(old->fsuid, new->fsuid) ||
385: !gid_eq(old->fsgid, new->fsgid) ||
386: !cred_cap_issubset(old, new)) {
387: /* mm-less tasks share init_task's exec_state */
388: if (task->mm)
389: task_exec_state_set_dumpable(suid_dumpable);
390: task->pdeath_signal = 0;
391: /*
392: * If a task drops privileges and becomes nondumpable,
393: * the dumpability change must become visible before
394: * the credential change; otherwise, a __ptrace_may_access()
395: * racing with this change may be able to attach to a task it
396: * shouldn't be able to attach to (as if the task had dropped
397: * privileges without becoming nondumpable).
398: * Pairs with a read barrier in __ptrace_may_access().
399: */
400: smp_wmb();
401: }
402:
403: /* alter the thread keyring */
404: if (!uid_eq(new->fsuid, old->fsuid))
405: key_fsuid_changed(new);
406: if (!gid_eq(new->fsgid, old->fsgid))
407: key_fsgid_changed(new);
408:
409: /* do it
410: * RLIMIT_NPROC limits on user->processes have already been checked
411: * in set_user().
412: */
413: if (new->user != old->user || new->user_ns != old->user_ns)
414: inc_rlimit_ucounts(new->ucounts, UCOUNT_RLIMIT_NPROC, 1);
415:
416: rcu_assign_pointer(task->real_cred, new);
417: rcu_assign_pointer(task->cred, new);
418: if (new->user != old->user || new->user_ns != old->user_ns)
419: dec_rlimit_ucounts(old->ucounts, UCOUNT_RLIMIT_NPROC, 1);
420: if (new->user_ns != old->user_ns)
421: switch_cred_namespaces(old, new);
422:
423: /* send notifications */
424: if (!uid_eq(new->uid, old->uid) ||
425: !uid_eq(new->euid, old->euid) ||
426: !uid_eq(new->suid, old->suid) ||
427: !uid_eq(new->fsuid, old->fsuid))
428: proc_id_connector(task, PROC_EVENT_UID);
429:
430: if (!gid_eq(new->gid, old->gid) ||
431: !gid_eq(new->egid, old->egid) ||
432: !gid_eq(new->sgid, old->sgid) ||
433: !gid_eq(new->fsgid, old->fsgid))
434: proc_id_connector(task, PROC_EVENT_GID);
435:
436: /* release the old obj and subj refs both */
437: put_cred_many(old, 2);
438: return 0;
439: }
SourceFile:kernel/cred.c]
|
| 76/4 |
2026/07/06 22:41 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 11013
output: 19
thoughts: 208
Thoughts: **Analyzing Credential Committing in the Kernel**
Okay, so I'm diving into how credentials get committed in the kernel, specifically focusing on `commit_creds`. The core of this function is assigning the new credentials to both `task->real_cred` and `task->cred`. Once that assignment happens, those credentials are considered "committed," right?
Now, I need to make sure I'm not missing anything. Are there any other in-place modifications happening at the same time? Let's check `jit_keyring` and other keyring-related fields.
Looking at the code for `commit_creds`, I see these lines:
```c
404: if (!uid_eq(new->fsuid, old->fsuid))
405: key_fsuid_changed(new);
406: if (!gid_eq(new->fsgid, old->fsgid))
407: key_fsgid_changed(new);
```
Interesting. These checks for `fsuid` and `fsgid` changes and the subsequent calls to `key_fsuid_changed` and `key_fsgid_changed` happen *before* the critical `rcu_assign_pointer`. That means the `new` credential structure is still private at this point, which is good to know. It avoids any potential RCU-related issues.
Next, I need to verify what the impact to `jit_keyring` will be. I'll search the code to see where it gets modified and if there's any interaction with the credential commit.
|
| 77/4 |
2026/07/06 22:41 |
tool |
grepper |
0m
Args: map[Expression:jit_keyring =]
Results: map[Output:fs/nfs/nfs4idmap.c=197=int nfs_idmap_init(void)
--
fs/nfs/nfs4idmap.c-229- cred->thread_keyring = keyring;
fs/nfs/nfs4idmap.c:230: cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
fs/nfs/nfs4idmap.c-231- id_resolver_cache = cred;
--
fs/smb/client/cifs_spnego.c=194=init_cifs_spnego(void)
--
fs/smb/client/cifs_spnego.c-231- cred->thread_keyring = keyring;
fs/smb/client/cifs_spnego.c:232: cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
fs/smb/client/cifs_spnego.c-233- spnego_cred = cred;
--
fs/smb/client/cifsacl.c=525=init_cifs_idmap(void)
--
fs/smb/client/cifsacl.c-561- cred->thread_keyring = keyring;
fs/smb/client/cifsacl.c:562: cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
fs/smb/client/cifsacl.c-563- root_cred = cred;
--
kernel/cred.c=559=struct cred *prepare_kernel_cred(struct task_struct *daemon)
--
kernel/cred.c-586- new->request_key_auth = NULL;
kernel/cred.c:587: new->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
kernel/cred.c-588-#endif
--
net/dns_resolver/dns_key.c=323=static int __init init_dns_resolver(void)
--
net/dns_resolver/dns_key.c-356- cred->thread_keyring = keyring;
net/dns_resolver/dns_key.c:357: cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
net/dns_resolver/dns_key.c-358- dns_resolver_cache = cred;
--
security/keys/keyctl.c=1405=long keyctl_set_reqkey_keyring(int reqkey_defl)
--
security/keys/keyctl.c-1446-set:
security/keys/keyctl.c:1447: new->jit_keyring = reqkey_defl;
security/keys/keyctl.c-1448- commit_creds(new);
]
|
| 78/4 |
2026/07/06 22:41 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 12319
output: 20
thoughts: 236
Thoughts: **Analyzing Potential Credential Modification Issues**
Okay, so I'm diving into `security/keys/keyctl.c` and specifically focusing on lines 1447-1448. The assignment of `new->jit_keyring = reqkey_defl` before `commit_creds(new)` is the immediate point of interest. My brain immediately jumps to the idea of looking for code that potentially modifies a committed `struct cred` elsewhere, before a `commit_creds` is done. That screams trouble. Committed credentials are *usually* `const`, so if someone's casting away the `const` qualifier and mucking about with the data, that's exactly what I'm trying to identify. It's a classic race condition and potential security hole waiting to happen.
Wait a second, there's `get_cred_many`... Let me refresh my memory of it... Ah, yes. It does exactly what I feared. Specifically, I see `struct cred *nonconst_cred = (struct cred *) cred;` being used. That cast, then the modification of `nonconst_cred->non_rcu = 0;` and the increment of `nonconst_cred->usage`! Bingo. This is definitely on the radar.
Let's not stop there, though. I'll need to broaden the search. I need to scan the codebase for *any* instance of a `(struct cred *)` cast. That should reveal all potential locations where someone might be attempting to bypass the `const` protection and fiddle with committed credentials. That will definitely help me understand the full scope of potential issues.
|
| 79/4 |
2026/07/06 22:41 |
tool |
grepper |
0m
Args: map[Expression:\(struct cred \*\)]
Results: map[Output:fs/overlayfs/super.c=1371=static int ovl_fill_super_creds(struct fs_context *fc, struct super_block *sb)
--
fs/overlayfs/super.c-1373- struct ovl_fs *ofs = sb->s_fs_info;
fs/overlayfs/super.c:1374: struct cred *creator_cred = (struct cred *)ofs->creator_cred;
fs/overlayfs/super.c-1375- struct ovl_fs_context *ctx = fc->fs_private;
--
include/linux/cred.h=115=struct cred {
--
include/linux/cred.h-152-
include/linux/cred.h:153:extern void __put_cred(struct cred *);
include/linux/cred.h-154-extern void exit_creds(struct task_struct *);
--
include/linux/cred.h=159=extern struct cred *prepare_exec_creds(void);
include/linux/cred.h:160:extern int commit_creds(struct cred *);
include/linux/cred.h:161:extern void abort_creds(struct cred *);
include/linux/cred.h-162-extern struct cred *prepare_kernel_cred(struct task_struct *);
--
include/linux/cred.h=171=extern void __init cred_init(void);
include/linux/cred.h:172:extern int set_cred_ucounts(struct cred *);
include/linux/cred.h-173-
--
include/linux/cred.h=217=static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
include/linux/cred.h-218-{
include/linux/cred.h:219: struct cred *nonconst_cred = (struct cred *) cred;
include/linux/cred.h-220- if (!cred)
--
include/linux/cred.h=241=static inline const struct cred *get_cred_rcu(const struct cred *cred)
include/linux/cred.h-242-{
include/linux/cred.h:243: struct cred *nonconst_cred = (struct cred *) cred;
include/linux/cred.h-244- if (!cred)
--
include/linux/cred.h=264=static inline void put_cred_many(const struct cred *_cred, int nr)
include/linux/cred.h-265-{
include/linux/cred.h:266: struct cred *cred = (struct cred *) _cred;
include/linux/cred.h-267-
--
include/linux/cred.h=291=DEFINE_FREE(put_cred, struct cred *, if (!IS_ERR_OR_NULL(_T)) put_cred(_T))
--
include/linux/cred.h-365-({ \
include/linux/cred.h:366: __typeof__(((struct cred *)NULL)->xxx) ___val; \
include/linux/cred.h-367- rcu_read_lock(); \
--
include/linux/nsproxy.h=61=static inline struct cred *nsset_cred(struct nsset *set)
--
include/linux/nsproxy.h-63- if (set->flags & CLONE_NEWUSER)
include/linux/nsproxy.h:64: return (struct cred *)set->cred;
include/linux/nsproxy.h-65-
--
kernel/cred.c=90=void exit_creds(struct task_struct *tsk)
--
kernel/cred.c-96-
kernel/cred.c:97: real_cred = (struct cred *) tsk->real_cred;
kernel/cred.c-98- tsk->real_cred = NULL;
kernel/cred.c-99-
kernel/cred.c:100: cred = (struct cred *) tsk->cred;
kernel/cred.c-101- tsk->cred = NULL;
--
security/keys/internal.h=145=extern struct key *get_user_session_keyring_rcu(const struct cred *);
security/keys/internal.h:146:extern int install_thread_keyring_to_cred(struct cred *);
security/keys/internal.h:147:extern int install_process_keyring_to_cred(struct cred *);
security/keys/internal.h-148-extern int install_session_keyring_to_cred(struct cred *, struct key *);
--
security/landlock/tsync.c=79=static void restrict_one_thread(struct tsync_shared_context *ctx)
--
security/landlock/tsync.c-96- */
security/landlock/tsync.c:97: cred = (struct cred *)get_cred(ctx->new_cred);
security/landlock/tsync.c-98- } else {
--
security/lsm_init.c=407=int __init security_init(void)
--
security/lsm_init.c-478-
security/lsm_init.c:479: if (lsm_cred_alloc((struct cred *)unrcu_pointer(current->cred),
security/lsm_init.c-480- GFP_KERNEL))
--
security/smack/smack_lsm.c=5319=static __init int smack_init(void)
security/smack/smack_lsm.c-5320-{
security/smack/smack_lsm.c:5321: struct cred *cred = (struct cred *) current->cred;
security/smack/smack_lsm.c-5322- struct task_smack *tsp;
]
|
| 80/4 |
2026/07/06 22:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14377
output: 38
thoughts: 111
Thoughts: **Analyzing Potential Credential Modification in Landlock's tsync.c**
Okay, let's dive into this. I'm looking at `security/landlock/tsync.c`. Specifically, line 97: `cred = (struct cred *)get_cred(ctx->new_cred);`. Hold on a second... `get_cred` is returning a `const struct cred *`. Why are they casting it to a plain `struct cred *`? That immediately raises a flag. It suggests they intend to modify the credentials in place, which, given the `const` return, is highly suspect and potentially a source of subtle, hard-to-debug issues. We really need to look closer at the implications of that cast.
Let's switch gears and go look at `restrict_one_thread` function in the same file. That's likely where this credential is being *used* - and possibly *modified*. This could get interesting.
|
| 81/4 |
2026/07/06 22:42 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:security/landlock/tsync.c Name:restrict_one_thread]
Results: map[SourceCode: SourceFile:]
|
| 82/4 |
2026/07/06 22:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14750
output: 36
thoughts: 17
Thoughts: Okay, here's the summary, assuming I'm the expert and considering the provided text:
**Static Functions: A Quick Check**
Hmm, could this be a static function situation? It's a common oversight, and if so, that's good! Before I dig into anything too complex, I'll go ahead and take a look at the file. A quick read through the relevant code will probably show me whether this is the culprit, which would be an easy fix. Let's see...
|
| 83/4 |
2026/07/06 22:42 |
tool |
read-file |
0m
Args: map[File:security/landlock/tsync.c FirstLine:79 LineCount:50]
Results: map[Contents: 79: static void restrict_one_thread(struct tsync_shared_context *ctx)
80: {
81: int err;
82: struct cred *cred = NULL;
83:
84: if (current_cred() == ctx->old_cred) {
85: /*
86: * Switch out old_cred with new_cred, if possible.
87: *
88: * In the common case, where all threads initially point to the
89: * same struct cred, this optimization avoids creating separate
90: * redundant credentials objects for each, which would all have
91: * the same contents.
92: *
93: * Note: We are intentionally dropping the const qualifier
94: * here, because it is required by commit_creds() and
95: * abort_creds().
96: */
97: cred = (struct cred *)get_cred(ctx->new_cred);
98: } else {
99: /* Else, prepare new creds and populate them. */
100: cred = prepare_creds();
101:
102: if (!cred) {
103: atomic_set(&ctx->preparation_error, -ENOMEM);
104:
105: /*
106: * Even on error, we need to adhere to the protocol and
107: * coordinate with concurrently running invocations.
108: */
109: if (atomic_dec_return(&ctx->num_preparing) == 0)
110: complete_all(&ctx->all_prepared);
111:
112: goto out;
113: }
114:
115: landlock_cred_copy(landlock_cred(cred),
116: landlock_cred(ctx->new_cred));
117: }
118:
119: /*
120: * Barrier: Wait until all threads are done preparing.
121: * After this point, we can have no more failures.
122: */
123: if (atomic_dec_return(&ctx->num_preparing) == 0)
124: complete_all(&ctx->all_prepared);
125:
126: /*
127: * Wait for signal from calling thread that it's safe to read the
128: * preparation error now and we are ready to commit (or abort).
]
|
| 84/4 |
2026/07/06 22:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 15605
output: 36
thoughts: 186
Thoughts: **My Reasoning on Credential Handling**
Okay, so I'm looking at this code and I see a comment explaining they're dropping a `const` qualifier. The reason given is that `commit_creds()` and `abort_creds()` require a non-`const` `struct cred *`. That makes sense; they need to modify the credentials in some way. Specifically, I see `ctx->new_cred` being assigned to `cred` before being passed to `commit_creds()`, which is a common pattern.
From what I can tell, `commit_creds()` itself *appears* to be relatively safe in that it doesn't seem to directly modify the data pointed to by `cred`, except potentially in regard to the `usage` field via `get_cred` and `put_cred_many`. However, I need to confirm this assumption.
Ah, but *wait*. Looking closer, I'm now noticing calls to `key_fsuid_changed(new)` and `key_fsgid_changed(new)` *within* `commit_creds()`. That changes things; there's obviously more going on than my initial assessment. I need to investigate what those functions actually *do*. I need to understand how the user and group IDs change affect the underlying credential management. That will be the key to understanding why the const qualifier is dropped. Let me dig into those functions...
|
| 85/4 |
2026/07/06 22:42 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:key_fsuid_changed]
Results: map[SourceCode: 374: /*
375: * Handle the fsuid changing.
376: */
377: void key_fsuid_changed(struct cred *new_cred)
378: {
379: /* update the ownership of the thread keyring */
380: if (new_cred->thread_keyring) {
381: down_write(&new_cred->thread_keyring->sem);
382: new_cred->thread_keyring->uid = new_cred->fsuid;
383: up_write(&new_cred->thread_keyring->sem);
384: }
385: }
SourceFile:security/keys/process_keys.c]
|
| 86/4 |
2026/07/06 22:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16343
output: 34
thoughts: 55
Thoughts: Okay, here's my interpretation of that code snippet, considering my expertise:
**Examining Credential Switching**
Alright, so I'm looking at this code and immediately keying in on a crucial point: the alteration is happening *within* the `new_cred->thread_keyring` structure, specifically affecting the `uid` field, and *not* the `new_cred` structure itself. This is critical for understanding the scope of the change. This highlights a nuanced behavior with credentials and keyrings; the credential object itself likely persists, but a specific aspect of its associated thread-local keyring is being updated.
Now, this naturally makes me think... what are the implications of this change within the broader context of credential management? The immediate question that jumps to mind is: How does this interact with `switch_cred_namespaces`? I see line 421 calls the function `switch_cred_namespaces` which takes `old` and `new` credentials as arguments. The interaction between namespace changes and these per-thread credential updates is key. Is `switch_cred_namespaces` ensuring this change is properly propagated across namespace boundaries, or is it merely handling the broader credential context switch, and this finer-grained change happens independently? The interplay between the namespace switch and this modification is something I need to fully understand.
|
| 87/4 |
2026/07/06 22:43 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:switch_cred_namespaces]
Results: map[SourceCode: 268: void switch_cred_namespaces(const struct cred *old, const struct cred *new)
269: {
270: ns_ref_active_get(new->user_ns);
271: ns_ref_active_put(old->user_ns);
272: }
SourceFile:kernel/nsproxy.c]
|
| 88/4 |
2026/07/06 22:43 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16823
output: 26
thoughts: 169
Thoughts: **Investigating Potential Credential Modification**
Okay, so I'm double-checking the code, specifically around credential handling. I didn't see any direct modifications to the `struct cred` in the initial spot I looked at, which is good.
Let's circle back to `security/keys/keyctl.c` to be absolutely sure. Right, line 1447, `new->jit_keyring = reqkey_defl;` and then line 1448, `commit_creds(new)`. Again, that's happening *before* the `commit_creds` call. We're still safe there.
Now, I need to consider a different attack vector: direct pointer manipulation. Are there any instances where someone might be casting away the `const` on `current_cred()` and then writing to `task->cred` or `task->real_cred` directly? `current_cred()` usually returns a `const struct cred *`, which is designed to prevent these kinds of modifications. However, a careless cast, like `(struct cred *)current_cred()`, could bypass that protection and allow direct write access.
So, I need to search the codebase. Let's look for instances of exactly that: `(struct cred *)current_cred()`. I need to track down any potential places where that's happening, because if it *is* happening, it's a huge red flag and needs immediate attention.
|
| 89/4 |
2026/07/06 22:43 |
tool |
grepper |
0m
Error:
Args: map[Expression:\(struct cred \*\)current_cred\(\)]
Results:
|
| 90/4 |
2026/07/06 22:44 |
llm |
codeexpert |
1m
Model:
Tokens:
input: 17343
output: 23
thoughts: 12
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm an expert in this field, presented as a first-person summary:
**Considering Credential Retrieval in the Current Context**
Right, so I'm thinking about how to get the credentials, likely within a kernel context. The first thing that pops into my head, as a standard starting point, is to grab the current task's credentials. The most direct approach that I can think of offhand is `(struct cred *)current->cred`. This seems like a perfectly reasonable and likely valid way to access the credentials associated with the current running process. It should give me a pointer to the `cred` structure, allowing me to examine or modify the necessary security attributes. It's a fundamental element of how the kernel manages process identities and permissions, so this seems like a solid initial avenue to pursue, or at least a good starting assumption.
|
| 91/4 |
2026/07/06 22:45 |
tool |
grepper |
0m
Error:
Args: map[Expression:\(struct cred \*\)current->cred]
Results:
|
| 92/4 |
2026/07/06 22:45 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17581
output: 41
thoughts: 50
Thoughts: Okay, let me think this through.
**Analyzing Potential Credential Handling in Kernel Security**
Hmm, now that I'm revisiting this, I recall spotting something interesting in my earlier investigation. Specifically, I remember seeing a reference to `security/smack/smack_lsm.c:5321`. Let me pull that up again. Ah yes, there it is: `struct cred *cred = (struct cred *) current->cred;`. That line immediately catches my eye. It looks like the code is explicitly casting the current process's credentials into a `struct cred` pointer. This suggests a potential area where credential manipulation, or at least inspection, is happening within the Security-Enhanced Linux (SELinux) context. I'll need to dig deeper into the surrounding code in that file, and perhaps the call stack, to fully understand how these credentials are being used and potentially modified within the SELinux or Smack framework. That's a good starting point for understanding credential handling, especially in relation to the kernel's security mechanisms.
|
| 93/4 |
2026/07/06 22:46 |
tool |
read-file |
0m
Args: map[File:security/smack/smack_lsm.c FirstLine:5319 LineCount:20]
Results: map[Contents:5319: static __init int smack_init(void)
5320: {
5321: struct cred *cred = (struct cred *) current->cred;
5322: struct task_smack *tsp;
5323:
5324: smack_rule_cache = KMEM_CACHE(smack_rule, 0);
5325: if (!smack_rule_cache)
5326: return -ENOMEM;
5327:
5328: /*
5329: * Set the security state for the initial task.
5330: */
5331: tsp = smack_cred(cred);
5332: init_task_smack(tsp, &smack_known_floor, &smack_known_floor);
5333:
5334: /*
5335: * Register with LSM
5336: */
5337: security_add_hooks(smack_hooks, ARRAY_SIZE(smack_hooks), &smack_lsmid);
5338: smack_enabled = 1;
]
|
| 94/4 |
2026/07/06 22:46 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 18198
output: 36
thoughts: 362
Thoughts: **Initial Credential Setup and Potential Security Concerns**
Okay, so I'm looking at this `smack_init` function, which, of course, means we're in the `__init` stage, handling the initial credentials for a task. This is a crucial, specific setup. I'm immediately thinking, are there similar patterns elsewhere?
My mind jumps to `security/lsm_init.c`, specifically line 479, where I see another instance of credential allocation happening during initialization: `if (lsm_cred_alloc((struct cred *)unrcu_pointer(current->cred),`. That's another `__init` call. I need to be thorough; I'm going to look more carefully for other usages of this `(struct cred *)` pattern.
I'm checking `include/linux/cred.h` to see if there are any macros or inline functions that could be playing a role in this casting. And, bingo, here's `get_cred_rcu`.
```c
241: static inline const struct cred *get_cred_rcu(const struct cred *cred)
242: {
243: struct cred *nonconst_cred = (struct cred *) cred;
244: if (!cred)
245: return cred;
246: if (!atomic_long_inc_not_zero(&nonconst_cred->usage))
247: return NULL;
248: nonconst_cred->non_rcu = 0;
249: return cred;
250: }
```
Okay, `get_cred_rcu`, which also seems to be doing the cast. I'm focusing on the interaction with `usage` and `non_rcu`. I'm starting to get a sense of how these credentials are managed.
I need to expand my search. What about `set_cred_ucounts`?
```c
include/linux/cred.h:172:extern int set_cred_ucounts(struct cred *);
```
Let me see the definition of this function. I need to understand how user counts are being set up.
|
| 95/4 |
2026/07/06 22:46 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:set_cred_ucounts]
Results: map[SourceCode: 513: int set_cred_ucounts(struct cred *new)
514: {
515: struct ucounts *new_ucounts, *old_ucounts = new->ucounts;
516:
517: /*
518: * This optimization is needed because alloc_ucounts() uses locks
519: * for table lookups.
520: */
521: if (old_ucounts->ns == new->user_ns && uid_eq(old_ucounts->uid, new->uid))
522: return 0;
523:
524: if (!(new_ucounts = alloc_ucounts(new->user_ns, new->uid)))
525: return -EAGAIN;
526:
527: new->ucounts = new_ucounts;
528: put_ucounts(old_ucounts);
529:
530: return 0;
531: }
SourceFile:kernel/cred.c]
|
| 96/4 |
2026/07/06 22:46 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 19411
output: 36
thoughts: 33
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing Credential Preparation Flow**
Okay, so I'm tracing back how credentials are being prepared. This seems to be initiated, at least indirectly, from `prepare_creds`. I need to confirm the exact call path. Is it coming via `security_prepare_creds` or is it being called somewhere else entirely? Let's check the call graph to see the initiating calls for `prepare_creds`, to find the root cause of this credential preparation. I need to understand the entry points.
|
| 97/4 |
2026/07/06 22:47 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:kernel/cred.c Name:set_cred_ucounts]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__sys_setresuid SourceFile:kernel/sys.c SourceLine:771] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__sys_setreuid SourceFile:kernel/sys.c SourceLine:623] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__sys_setuid SourceFile:kernel/sys.c SourceLine:686] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:begin_new_exec SourceFile:fs/exec.c SourceLine:1265] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:copy_creds SourceFile:kernel/cred.c SourceLine:294] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:ksys_unshare SourceFile:kernel/fork.c SourceLine:3274] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:userns_install SourceFile:kernel/user_namespace.c SourceLine:1371]] TruncatedOutput:false]
|
| 98/4 |
2026/07/06 22:47 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 19959
output: 43
thoughts: 574
Thoughts: **My Analysis of Credential Races**
Okay, so the user's raising a good point about potential races involving credential structures. The core of the issue seems to be around `prepare_creds` and its interaction with concurrent modifications, specifically the `memcpy` involved in copying the old credentials (`old`) to the new one (`new`). The typical pattern is that a new credential is prepared, then a series of operations are performed on it, and *then* it's committed with `commit_creds`. This is the context for the user's question, as indicated by examples like `__sys_setuid`.
My initial thought was to quickly identify fields that are modified *after* `commit_creds`, which might be a problem, but it appears the user's concerns are happening before that stage. They've specifically flagged `usage` and `non_rcu`. I'm already aware that `usage` is modified by `get_cred` and `put_cred`, and `non_rcu` by `get_cred_many` and `get_cred_rcu`.
Let me think⦠any other fields that could cause problems? I need to consider potential in-place modifications. The `security` field immediately comes to mind; LSMs might be touching it directly. I'll need to check the relevant `security/security.c` code to be sure.
But let's think about this: the primary concern appears to be `prepare_creds`' `memcpy`. So, even if `get_cred(old)` is running concurrently and only touches `usage` or `non_rcu`, it seems fine since `prepare_creds` will overwrite them in `new` anyway. The real problem is if `memcpy` reads those fields *while* they are being changed. The race on these fields is harmless for `new` because it's overwritten immediately. The question here is if `memcpy` is reading a corrupted value, or triggering any other problems.
Okay, so `memcpy` isn't atomic, and while reading a word being written to should be fine on most architectures (it will read either the old or the new value as long as it's word-aligned), I'm working with `usage`, an `atomic_long_t`. That's usually a `long`, so it *should* be fine in the race.
Wait, hold on... `struct cred` has `__randomize_layout`! That's a huge factor I nearly missed.
```c
151: } __randomize_layout;
```
The field order is *not* fixed! This means other fields could be scattered, and if they're modified in-place, we could have a much bigger problem.
So, are there any other fields modified in-place? I need to consider `keyring` fields: `session_keyring`, `process_keyring`, and `thread_keyring`. They're all pointers, and are they ever modified directly within a cred? Typically, keyring changes involve preparing a *new* `struct cred`. Let me trace where `install_thread_keyring_to_cred` is called, because it takes a `struct cred *`. That should give me a good indication.
|
| 99/4 |
2026/07/06 22:47 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:security/keys/process_keys.c Name:install_thread_keyring_to_cred]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:copy_creds SourceFile:kernel/cred.c SourceLine:306] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:install_thread_keyring SourceFile:security/keys/process_keys.c SourceLine:253] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:keyctl_set_reqkey_keyring SourceFile:security/keys/keyctl.c SourceLine:1421]] TruncatedOutput:false]
|
| 100/4 |
2026/07/06 22:48 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21450
output: 28
thoughts: 193
Thoughts: **Analyzing Credential Handling in Kernel Security**
Okay, let's break this down. I'm looking at how thread keyrings are installed, specifically the `install_thread_keyring` function. The first thing that jumps out is that it's using a *new* credential structure, `new`, obtained through `prepare_creds()`. If that fails, it returns an error. If successful, it then tries to install the keyring to the credential via `install_thread_keyring_to_cred()`. If that fails, the credential is aborted with `abort_creds()` and the error code returned. Finally, if all that goes well, the new credentials are committed using `commit_creds()`. So, standard credential lifecycle stuff: prepare, install/modify, commit, or abort. And yes, it's operating on a *new* credential, not an existing one. That's good to keep in mind.
Now, I need to understand how other kernel functions handle credentials. Let's shift our focus to `request_key_auth`, I need to check how it handles pointers.
Since I'm in security context, I'm thinking, are there any potential type-safety vulnerabilities, like const-correctness issues, lurking around? I'm going to look for any instances of casting to a credential pointer, `(struct cred *)`, particularly within the `security/` directory and also in `kernel/`, to get a broader view of potential issues. I need to make sure we're not inadvertently bypassing const restrictions or making unsafe assumptions about credential mutability.
|
| 101/4 |
2026/07/06 22:48 |
tool |
grepper |
0m
Args: map[Expression:\(struct cred \*\) PathPrefix:security/]
Results: map[Output:security/keys/internal.h=145=extern struct key *get_user_session_keyring_rcu(const struct cred *);
security/keys/internal.h:146:extern int install_thread_keyring_to_cred(struct cred *);
security/keys/internal.h:147:extern int install_process_keyring_to_cred(struct cred *);
security/keys/internal.h-148-extern int install_session_keyring_to_cred(struct cred *, struct key *);
--
security/landlock/tsync.c=79=static void restrict_one_thread(struct tsync_shared_context *ctx)
--
security/landlock/tsync.c-96- */
security/landlock/tsync.c:97: cred = (struct cred *)get_cred(ctx->new_cred);
security/landlock/tsync.c-98- } else {
--
security/lsm_init.c=407=int __init security_init(void)
--
security/lsm_init.c-478-
security/lsm_init.c:479: if (lsm_cred_alloc((struct cred *)unrcu_pointer(current->cred),
security/lsm_init.c-480- GFP_KERNEL))
--
security/smack/smack_lsm.c=5319=static __init int smack_init(void)
security/smack/smack_lsm.c-5320-{
security/smack/smack_lsm.c:5321: struct cred *cred = (struct cred *) current->cred;
security/smack/smack_lsm.c-5322- struct task_smack *tsp;
]
|
| 102/4 |
2026/07/06 22:48 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 22456
output: 36
thoughts: 1235
Thoughts: **Analyzing Potential In-Place Modifications of `struct cred`**
Okay, so the initial concern is whether the `security` field in `struct cred` can be modified in-place after being committed. I know LSMs store data in `cred->security`, and that pointer itself is usually allocated in `prepare_creds`. The key question is whether any LSM *modifies* the contents of `cred->security` after a credential is committed. If this happens and `prepare_creds` uses `memcpy` of the `struct cred`, it's just copying the pointer initially. The worry is if the *contents* of what `security` points to are changed because `security_prepare_creds` will likely copy these contents, and an inconsistent state might be observed.
However, the user's question focuses on fields within `struct cred`. Let me re-examine the struct definition. Okay, here's the struct again:
```c
struct cred {
atomic_long_t usage;
kuid_t uid; /* real UID of the task */
kgid_t gid; /* real GID of the task */
...
void *security; /* LSM security */
...
union {
int non_rcu; /* Can we skip RCU deletion? */
struct rcu_head rcu; /* RCU deletion hook */
};
} __randomize_layout;
```
It seems like `usage` and `non_rcu` are the only candidates as they are immediately overwritten in `new`. I found something interesting in `get_cred_many`:
```c
nonconst_cred->non_rcu = 0;
atomic_long_add(nr, &nonconst_cred->usage);
```
Why does it set `non_rcu = 0`? If `non_rcu` was 1, it means this cred was not supposed to be freed via RCU (maybe it's a temporary one or something). However, once someone takes a reference to it, it might be passed around and eventually `put_cred` will be called from a context that requires RCU. Actually, `non_rcu` is used to optimize `put_cred`.
If `prepare_creds` copies `old` to `new`, and `old` is a committed cred, then `old->usage` should be at least 1 (the task itself holds a reference). If another thread calls `get_cred(old)`, it increments `old->usage`.
Are there other fields? I see `ucounts`. In `prepare_creds`:
```c
new->ucounts = get_ucounts(new->ucounts);
```
Wait, it first copies `old->ucounts` via `memcpy`, then calls `get_ucounts` on it. `get_ucounts` increments a reference count in the `struct ucounts` object, not in `struct cred`. The same seems to be happening with `group_info` and `user`.
Thus, the pointers themselves aren't being modified in-place within `old`.
I'll search for all assignments to fields of a `struct cred` pointer that is not named `new`. However, I'll restrict my search to `atomic_t` or similar fields as a starting point. Only `usage` is atomic. `non_rcu` is just an `int` and it's modified in `get_cred_many` and `get_cred_rcu`.
Are there any other fields that are modified? I'll look for `->jit_keyring =` and other fields. I already looked for `jit_keyring`.
What about `cap_` fields? They are `kernel_cap_t`. They are usually modified in `prepare_creds` before `commit_creds`.
Ultimately, the point of the `cred` API is the immutability of credentials once committed. Any in-place modification would be a bug. I should also check `put_cred`.
|
| 103/4 |
2026/07/06 22:48 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/cred.h Name:put_cred_many]
Results: map[SourceCode: 252: /**
253: * put_cred_many - Release a reference to a set of credentials
254: * @_cred: The credentials to release
255: * @nr: Number of references to release
256: *
257: * Release a reference to a set of credentials, deleting them when the last ref
258: * is released. If %NULL is passed, nothing is done.
259: *
260: * This takes a const pointer to a set of credentials because the credentials
261: * on task_struct are attached by const pointers to prevent accidental
262: * alteration of otherwise immutable credential sets.
263: */
264: static inline void put_cred_many(const struct cred *_cred, int nr)
265: {
266: struct cred *cred = (struct cred *) _cred;
267:
268: if (cred) {
269: if (atomic_long_sub_and_test(nr, &cred->usage))
270: __put_cred(cred);
271: }
272: }
SourceFile:include/linux/cred.h]
|
| 104/4 |
2026/07/06 22:48 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24960
output: 20
thoughts: 147
Thoughts: **My Credential System Analysis**
Okay, so `put_cred_many` seems pretty straightforward; it's just touching the `usage` count. That's good, keeps things simple. Now, let me think about `__put_cred`. Ah, right, that's called when `usage` hits zero. At that point, ideally, nobody else should be *actively* using the credential data, except perhaps through RCU. `__put_cred` should be handling any potential RCU issues though, so that's probably covered.
Wait, I should confirm I haven't missed any other field modifications. Let me quickly double-check `get_cred_rcu`. Okay, yes, itβs just `usage` and `non_rcu` there as well. Good, good. Keeping things focused helps maintain sanity in this codebase.
Alright, let's broaden the scope a bit. Are there any other functions, anywhere, that take a `const struct cred *` argument and then do a cast to `struct cred *` within `kernel/cred.c`? Gotta be vigilant about potential aliasing or const-correctness issues. Time to do a quick search for `(struct cred *)` in `kernel/cred.c`. Let's see what that turns up.
|
| 105/4 |
2026/07/06 22:49 |
tool |
read-file |
0m
Error:
Args:
|
| 106/4 |
2026/07/06 22:49 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 25423
output: 24
thoughts: 23
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Kernel Credential Investigation: Initial Approach**
Alright, let's dive in. I need to understand what's going on with these kernel credentials. I'm going to leverage my usual workflow. First step, I'll reach for `codesearch-file-index`. It's my go-to for quickly navigating the source code, especially when I'm looking at a specific file like `kernel/cred.c`. This tool is invaluable; it allows me to zero in on specific functions and quickly see how they are defined and how they are used. By using the index, I can gain a high-level view of the landscape before drilling down. I expect to be able to identify the key functions related to credential management right away with this technique. Time to get started!
|
| 107/4 |
2026/07/06 22:50 |
tool |
codesearch-file-index |
0m
Args: map[SourceFile:kernel/cred.c]
Results: map[Entities:[map[Kind:function Name:__put_cred] map[Kind:function Name:abort_creds] map[Kind:function Name:commit_creds] map[Kind:function Name:copy_creds] map[Kind:function Name:cred_alloc_blank] map[Kind:function Name:cred_cap_issubset] map[Kind:function Name:cred_fscmp] map[Kind:function Name:cred_init] map[Kind:function Name:exit_creds] map[Kind:function Name:get_task_cred] map[Kind:function Name:prepare_creds] map[Kind:function Name:prepare_exec_creds] map[Kind:function Name:prepare_kernel_cred] map[Kind:function Name:put_cred_rcu] map[Kind:function Name:set_create_files_as] map[Kind:function Name:set_cred_ucounts] map[Kind:function Name:set_security_override] map[Kind:global_variable Name:__UNIQUE_ID_addressable___put_cred_806] map[Kind:global_variable Name:__UNIQUE_ID_addressable_abort_creds_827] map[Kind:global_variable Name:__UNIQUE_ID_addressable_commit_creds_825] map[Kind:global_variable Name:__UNIQUE_ID_addressable_cred_fscmp_828] map[Kind:global_variable Name:__UNIQUE_ID_addressable_get_task_cred_810] map[Kind:global_variable Name:__UNIQUE_ID_addressable_prepare_creds_812] map[Kind:global_variable Name:__UNIQUE_ID_addressable_prepare_kernel_cred_831] map[Kind:global_variable Name:__UNIQUE_ID_addressable_set_create_files_as_833] map[Kind:global_variable Name:__UNIQUE_ID_addressable_set_security_override_832] map[Kind:global_variable Name:__gendwarfksyms_ptr___put_cred] map[Kind:global_variable Name:__gendwarfksyms_ptr_abort_creds] map[Kind:global_variable Name:__gendwarfksyms_ptr_commit_creds] map[Kind:global_variable Name:__gendwarfksyms_ptr_cred_fscmp] map[Kind:global_variable Name:__gendwarfksyms_ptr_get_task_cred] map[Kind:global_variable Name:__gendwarfksyms_ptr_prepare_creds] map[Kind:global_variable Name:__gendwarfksyms_ptr_prepare_kernel_cred] map[Kind:global_variable Name:__gendwarfksyms_ptr_set_create_files_as] map[Kind:global_variable Name:__gendwarfksyms_ptr_set_security_override]]]
|
| 108/4 |
2026/07/06 22:50 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 26442
output: 34
thoughts: 21
Thoughts: Okay, let's dive into this. Here's my thought process on this:
**Examining Security Overrides and File Creation**
Alright, the objective is pretty clear. I need to take a look at how security overrides and file creation are handled. Specifically, I should check the functions or methods related to `set_security_override` and `set_create_files_as`. My focus is likely to be on how they interact, and potentially where the checks and balances are within that code. Are there any known vulnerabilities associated with those functions? Are the implementations secure? What are the potential consequences of misusing these particular tools? It's all about ensuring the integrity of the process and identifying any potential holes in the design or implementation, and how they relate to the bigger picture.
|
| 109/4 |
2026/07/06 22:50 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:set_security_override]
Results: map[SourceCode: 610: /**
611: * set_security_override - Set the security ID in a set of credentials
612: * @new: The credentials to alter
613: * @secid: The LSM security ID to set
614: *
615: * Set the LSM security ID in a set of credentials so that the subjective
616: * security is overridden when an alternative set of credentials is used.
617: */
618: int set_security_override(struct cred *new, u32 secid)
619: {
620: return security_kernel_act_as(new, secid);
621: }
SourceFile:kernel/cred.c]
|
| 110/4 |
2026/07/06 22:50 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 26873
output: 36
thoughts: 10
Thoughts: Okay, here's the summary, rendered as your thoughts as an expert:
**Reflecting on File Creation Methods**
Right, let's consider this `set_create_files_as` thing. It's a pretty fundamental decision, actually. What are the core implications for the system if we configure file creation behavior this way? Specifically, I need to consider security, and performance. I need to balance the need for ease of use with the need for security, if that's possible. Are there any default behaviors, and how can they be customized? What happens if this conflicts with other settings? What are the edge cases? What's the best way to handle errors and potential failures? And how do we ensure it all plays nicely with different storage backends? Is this a global setting, or can it be overridden? The devil is always in the details, so I need to dig deep into this one. It feels like this touches a key aspect of the core engine, so a shallow approach is not going to cut it.
|
| 111/4 |
2026/07/06 22:50 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:set_create_files_as]
Results: map[SourceCode: 624: /**
625: * set_create_files_as - Set the LSM file create context in a set of credentials
626: * @new: The credentials to alter
627: * @inode: The inode to take the context from
628: *
629: * Change the LSM file creation context in a set of credentials to be the same
630: * as the object context of the specified inode, so that the new inodes have
631: * the same MAC context as that inode.
632: */
633: int set_create_files_as(struct cred *new, struct inode *inode)
634: {
635: if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
636: return -EINVAL;
637: new->fsuid = inode->i_uid;
638: new->fsgid = inode->i_gid;
639: return security_kernel_create_files_as(new, inode);
640: }
SourceFile:kernel/cred.c]
|
| 112/4 |
2026/07/06 22:51 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 27453
output: 20
thoughts: 1154
Thoughts: **Analyzing Credential Modification in the Linux Kernel**
Okay, so I'm trying to figure out if any fields in the `struct cred` are modified *after* the credentials have been committed, aside from the obvious ones like `usage` and potentially `non_rcu` during RCU cleanup. I already know that most of the core identity and capability fields are set *before* credentials are committed, in functions like `prepare_creds` and `set_create_files_as`. I checked the common suspects: the UIDs, GIDs, capabilities (`cap_*`), and the various keyrings (`jit_keyring`, `session_keyring`, `process_keyring`, `thread_keyring`, `request_key_auth`). I've also checked `security`, `user`, `user_ns`, `ucounts`, and `group_info` - all handled early in credential preparation.
I've been systematically going through the `struct cred` definition in the kernel code. Let's see, what else could there be... I've got to be thorough here.
I need to confirm my understanding and make sure I haven't missed anything. I've already confirmed that things like `uid`, `gid`, `euid`, `egid`, `fsuid`, `fsgid`, `securebits`, and the capability sets are initialized on *new* credentials. Similarly, I know that `jit_keyring`, the different keyrings, and the LSM security context are set before commitment. The `user`, `user_ns`, `ucounts`, and `group_info` fields are also set up before the credentials are committed.
I think I need to double-check my previous thoughts on `request_key_auth`. It's a pointer to a `key` structure. Is it only set up during credential preparation?
Ok, time to search the codebase and see how `request_key_auth` is actually *assigned* and modified. That's the key to answering the question correctly.
|
| 113/4 |
2026/07/06 22:51 |
tool |
grepper |
0m
Args: map[Expression:request_key_auth =]
Results: map[Output:kernel/cred.c=559=struct cred *prepare_kernel_cred(struct task_struct *daemon)
--
kernel/cred.c-585- new->thread_keyring = NULL;
kernel/cred.c:586: new->request_key_auth = NULL;
kernel/cred.c-587- new->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
--
kernel/user_namespace.c=44=static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns)
--
kernel/user_namespace.c-56- key_put(cred->request_key_auth);
kernel/user_namespace.c:57: cred->request_key_auth = NULL;
kernel/user_namespace.c-58-#endif
--
security/keys/keyctl.c=1150=static int keyctl_change_reqkey_auth(struct key *key)
--
security/keys/keyctl.c-1158- key_put(new->request_key_auth);
security/keys/keyctl.c:1159: new->request_key_auth = key_get(key);
security/keys/keyctl.c-1160-
--
security/keys/request_key_auth.c=26=static void request_key_auth_rcu_disposal(struct rcu_head *);
--
security/keys/request_key_auth.c-30- */
security/keys/request_key_auth.c:31:struct key_type key_type_request_key_auth = {
security/keys/request_key_auth.c-32- .name = ".request_key_auth",
]
|
| 114/4 |
2026/07/06 22:51 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 29501
output: 25
thoughts: 1288
Thoughts: **Analyzing Potential Data Races in Credential Copying**
Okay, so I'm digging into how credentials are handled in the Linux kernel, specifically focusing on potential data races when copying credentials with `prepare_creds`. The user's question brings up a crucial point about the immutability of `struct cred` after it's committed, and I'm homing in on the interaction between `memcpy` in `prepare_creds` and concurrent calls to `get_cred`.
First, I looked at how credentials get modified. I quickly noticed in `keyctl_change_reqkey_auth` and `set_cred_user_ns` that modifications usually happen on *new* credentials (`new`), especially when user namespaces are involved. Specifically in `set_cred_user_ns`, the old credential's keyrings are explicitly released, and then reset to `NULL`. The `user_ns` is also replaced. Then, `create_user_ns` calls this to make a new cred. This seems to happen after `unshare_userns` or `copy_creds` call `prepare_creds` to make a copy.
The kernel's design seems to be very strict: once a credential is committed, it's pretty much set in stone. The user already pointed out the exceptions: `usage` and `non_rcu`. So, the question is, *are* there other fields potentially at risk during a `memcpy` copy from `old` to `new` when another thread might be incrementing `old->usage` with `get_cred(old)`?
The `prepare_creds` function itself sets these fields. It uses `memcpy(new, old, sizeof(struct cred))` but *immediately* overwrites `new->non_rcu = 0` and `atomic_long_set(&new->usage, 1)`. That means that any "intermediate" values copied into `new` for `usage` and `non_rcu` are promptly overwritten. Since the values copied are never read from `new` before the overwrite, the race condition regarding `old`'s `usage` and `non_rcu` is benign *for the new credential being created*.
But I need to be more thorough. Are there *other* fields that could be modified concurrently that I haven't accounted for? I went hunting through the code to check for any in-place modifications to the `cred` structure.
Then I paused. Wait! `non_rcu` is in a union with `rcu_head`! If `non_rcu` is 0, which `prepare_creds` always sets, then `rcu_head` *might* be used. But when would `rcu_head` be used? It's used during the actual freeing of the cred structure, when `usage` reaches zero. `prepare_creds` is operating on `task->cred`, and that means `usage > 0` right? So, `rcu` should *not* be in use at the time. Therefore, no issue there.
But, I must keep checking! What about the case where the *original* `old` credential is being freed while `prepare_creds` is running? The kernel provides some protection for `task->cred` by the nature of how `prepare_creds` is called. `prepare_creds` uses `task->cred`, where `task` is `current`. Since the caller is `current`, the current task is holding a reference to its own `cred`. This means `old` *can't* be freed while `prepare_creds` is running, so there's no race.
Okay, another angle. What if another thread *just* calls `get_cred(old)`? Well, that's just an increment of `usage`. That's fine β the copy in `prepare_creds` happens, and the new `new->usage` is set to 1 anyway, as expected.
I *think* I've covered all the obvious points but to be absolutely sure, I'm going to scan the entire `security/` directory looking for places where `cred->security` is modified in-place, just to be certain that no LSM shenanigans are causing problems. This should be an exhaustive check for potential data races.
|
| 115/4 |
2026/07/06 22:52 |
tool |
grepper |
0m
Args: map[Expression:->security = PathPrefix:security/]
Results: map[Output:security/security.c=2802=void security_task_free(struct task_struct *task)
--
security/security.c-2806- kfree(task->security);
security/security.c:2807: task->security = NULL;
security/security.c-2808-}
--
security/security.c=2839=void security_cred_free(struct cred *cred)
--
security/security.c-2844- */
security/security.c:2845: if (unlikely(cred->security == NULL))
security/security.c-2846- return;
--
security/security.c-2850- kfree(cred->security);
security/security.c:2851: cred->security = NULL;
security/security.c-2852-}
--
security/security.c=3416=void security_msg_msg_free(struct msg_msg *msg)
--
security/security.c-3419- kfree(msg->security);
security/security.c:3420: msg->security = NULL;
security/security.c-3421-}
--
security/security.c=3450=void security_msg_queue_free(struct kern_ipc_perm *msq)
--
security/security.c-3453- kfree(msq->security);
security/security.c:3454: msq->security = NULL;
security/security.c-3455-}
--
security/security.c=3553=void security_shm_free(struct kern_ipc_perm *shp)
--
security/security.c-3556- kfree(shp->security);
security/security.c:3557: shp->security = NULL;
security/security.c-3558-}
--
security/security.c=3637=void security_sem_free(struct kern_ipc_perm *sma)
--
security/security.c-3640- kfree(sma->security);
security/security.c:3641: sma->security = NULL;
security/security.c-3642-}
--
security/security.c=5156=void security_key_free(struct key *key)
--
security/security.c-5158- kfree(key->security);
security/security.c:5159: key->security = NULL;
security/security.c-5160-}
--
security/security.c=5450=void security_bpf_map_free(struct bpf_map *map)
--
security/security.c-5453- kfree(map->security);
security/security.c:5454: map->security = NULL;
security/security.c-5455-}
--
security/security.c=5463=void security_bpf_prog_free(struct bpf_prog *prog)
--
security/security.c-5466- kfree(prog->aux->security);
security/security.c:5467: prog->aux->security = NULL;
security/security.c-5468-}
--
security/security.c=5476=void security_bpf_token_free(struct bpf_token *token)
--
security/security.c-5479- kfree(token->security);
security/security.c:5480: token->security = NULL;
security/security.c-5481-}
--
security/security.c=5600=int security_perf_event_alloc(struct perf_event *event)
--
security/security.c-5611- kfree(event->security);
security/security.c:5612: event->security = NULL;
security/security.c-5613- }
--
security/security.c=5623=void security_perf_event_free(struct perf_event *event)
--
security/security.c-5625- kfree(event->security);
security/security.c:5626: event->security = NULL;
security/security.c-5627-}
--
security/selinux/hooks.c=2836=static int selinux_fs_context_submount(struct fs_context *fc,
--
security/selinux/hooks.c-2858- opts->defcontext_sid = sbsec->def_sid;
security/selinux/hooks.c:2859: fc->security = opts;
security/selinux/hooks.c-2860- return 0;
--
security/selinux/hooks.c=2863=static int selinux_fs_context_dup(struct fs_context *fc,
--
security/selinux/hooks.c-2870-
security/selinux/hooks.c:2871: fc->security = kmemdup(src, sizeof(*src), GFP_KERNEL);
security/selinux/hooks.c-2872- return fc->security ? 0 : -ENOMEM;
--
security/selinux/xfrm.c=338=int selinux_xfrm_state_alloc_acquire(struct xfrm_state *x,
--
security/selinux/xfrm.c-368-
security/selinux/xfrm.c:369: x->security = ctx;
security/selinux/xfrm.c-370- atomic_inc(&selinux_xfrm_refcount);
--
security/smack/smack_lsm.c=618=static int smack_fs_context_submount(struct fs_context *fc,
--
security/smack/smack_lsm.c-627- return -ENOMEM;
security/smack/smack_lsm.c:628: fc->security = ctx;
security/smack/smack_lsm.c-629-
--
security/smack/smack_lsm.c=668=static int smack_fs_context_dup(struct fs_context *fc,
--
security/smack/smack_lsm.c-675-
security/smack/smack_lsm.c:676: fc->security = kzalloc_obj(struct smack_mnt_opts);
security/smack/smack_lsm.c-677- if (!fc->security)
]
|
| 116/4 |
2026/07/06 22:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 33384
output: 40
thoughts: 1548
Thoughts: **Analyzing Credential Security and Data Handling**
Okay, so I'm focusing on the credential structures and how their security aspects are handled, specifically looking for potential vulnerabilities when data is copied or modified. I've been noticing that `security` pointers are often set to `NULL` during free operations or on other objects like `fc`, `x`, and `msg`.
My first thought is to check `security_prepare_creds`. Looking at the `security_prepare_creds` function and `lsm_cred_alloc`, I see that `cred->security` is allocated using a cache. In `prepare_creds`, the `memcpy` operation copies `old->security` to `new->security`, but then `new->security = NULL;` is called. Afterwards `security_prepare_creds(new, old, ...)` is invoked. So it looks like the `security` pointer in the `new` credential is being handled correctly because it's allocated, copied, and then the original pointer is set to `NULL`.
Now, I need to check if there are other fields that could cause issues. What about `ucounts`? The `new->ucounts` field is copied from the `old->ucounts` via `memcpy`. The `get_ucounts` function increments the refcount of the `ucounts` object. My concern here is if `old->ucounts` has been changed in-place, then the `new->ucounts` might be wrong. However, `old->ucounts` is only changed in `set_cred_ucounts`, and that's only called on the *new* credentials.
To be thorough, I have to consider other fields within `struct cred`. I'll review the full struct definition in `include/linux/cred.h`. (Actually, I've already reviewed it.) I see all the fields and I can see the alignment of data is randomized, so I must check if `__randomize_layout` could cause issues with `memcpy`. But no, `memcpy` simply copies the bytes, so as long as the size of the structure is correct, there won't be issues.
Are there any other fields that could be modified? I recall `jit_keyring` being present. There was this code snippet:
```c
security/keys/keyctl.c:1447: new->jit_keyring = reqkey_defl;
security/keys/keyctl.c-1448- commit_creds(new);
```
So, are there any other places where `jit_keyring` might be modified *without* going through `prepare_creds`? I re-check my previous `grepper` output and find one missed match:
```
fs/nfs/nfs4idmap.c:230: cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
```
Okay, I need to investigate `fs/nfs/nfs4idmap.c` now.
|
| 117/4 |
2026/07/06 22:52 |
tool |
read-file |
0m
Args: map[File:fs/nfs/nfs4idmap.c FirstLine:210 LineCount:30]
Results: map[Contents: 210: keyring = keyring_alloc(".id_resolver",
211: GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
212: (KEY_POS_ALL & ~KEY_POS_SETATTR) |
213: KEY_USR_VIEW | KEY_USR_READ,
214: KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
215: if (IS_ERR(keyring)) {
216: ret = PTR_ERR(keyring);
217: goto failed_put_cred;
218: }
219:
220: ret = register_key_type(&key_type_id_resolver);
221: if (ret < 0)
222: goto failed_put_key;
223:
224: ret = register_key_type(&key_type_id_resolver_legacy);
225: if (ret < 0)
226: goto failed_reg_legacy;
227:
228: set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags);
229: cred->thread_keyring = keyring;
230: cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
231: id_resolver_cache = cred;
232: return 0;
233:
234: failed_reg_legacy:
235: unregister_key_type(&key_type_id_resolver);
236: failed_put_key:
237: key_put(keyring);
238: failed_put_cred:
239: put_cred(cred);
]
|
| 118/4 |
2026/07/06 22:52 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 36122
output: 36
thoughts: 1280
Thoughts: **In-Place Credential Modification Analysis**
Okay, so I'm diving into this `cred` structure business. The user's question, as I understand it, centers around whether fields within a `struct cred`, specifically the `real_cred` or `cred` pointers of a task, are modified in-place after being assigned to a task. I had a quick look at the initialization of the `id_resolver_cache` cred, but that's a red herring; it's a global and isn't assigned to a task in the normal sense.
Initially, it seemed like the answer was no, nothing is modified. But let's dig deeper. The key here are the functions that handle credential manipulation: `get_cred_many`, `put_cred_many`, and `get_cred_rcu`. After carefully reviewing these, the only fields that are actually *modified in place* on an assigned credential are `usage` (an atomic counter) and `non_rcu`.
Specifically, `get_cred_many` and `get_cred_rcu` explicitly set `non_rcu` to 0. And both of these functions modify the `usage` field. It's clear that `non_rcu` being set in this way is a direct, in-place modification of a committed credential.
The `__put_cred` function is also important to consider. It uses the `non_rcu` value to determine how to release the credential, either directly or via `call_rcu`, but the crucial point is that this will happen only when `usage` reaches 0. I had to think about whether the `call_rcu` would be modifying the `cred->rcu` field while another thread has a pointer to the same `cred` struct, but because the task has a reference (usage > 0), I concluded that isn't possible, because the `prepare_creds` function is only ever called on `task->cred`. So, the only concurrent modifications to a `cred` structure being used by `prepare_creds` will be due to `get_cred` operations (increasing usage, setting `non_rcu=0`) or `put_cred` operations (decreasing usage) -- and only these functions modify `usage` and `non_rcu`.
I had to remember the potential for LSMs (like SELinux or AppArmor) to have internal state in the `cred->security` field, which they might modify. However, the user specifically asked about fields *within* the `struct cred`. Even though `security` *is* a field in `struct cred`, it's a pointer, and we aren't talking about modifying the pointer itself, just the pointee.
So, I confirmed that `usage` and `non_rcu` are the *only* fields ever modified in place. I re-checked `get_cred_many`, `put_cred_many`, and `get_cred_rcu` to be absolutely certain. The search through `include/linux/cred.h` confirmed my analysis: those functions are the only game in town.
|
| 119/4 |
2026/07/06 22:53 |
tool |
read-file |
0m
Args: map[File:include/linux/cred.h FirstLine:200 LineCount:100]
Results: map[Contents: 200:
201: /**
202: * get_cred_many - Get references on a set of credentials
203: * @cred: The credentials to reference
204: * @nr: Number of references to acquire
205: *
206: * Get references on the specified set of credentials. The caller must release
207: * all acquired reference. If %NULL is passed, it is returned with no action.
208: *
209: * This is used to deal with a committed set of credentials. Although the
210: * pointer is const, this will temporarily discard the const and increment the
211: * usage count. The purpose of this is to attempt to catch at compile time the
212: * accidental alteration of a set of credentials that should be considered
213: * immutable.
214: *
215: * Returns: @cred when the references are acquired, NULL otherwise.
216: */
217: static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
218: {
219: struct cred *nonconst_cred = (struct cred *) cred;
220: if (!cred)
221: return cred;
222: nonconst_cred->non_rcu = 0;
223: atomic_long_add(nr, &nonconst_cred->usage);
224: return cred;
225: }
226:
227: /*
228: * get_cred - Get a reference on a set of credentials
229: * @cred: The credentials to reference
230: *
231: * Get a reference on the specified set of credentials. The caller must
232: * release the reference. If %NULL is passed, it is returned with no action.
233: *
234: * This is used to deal with a committed set of credentials.
235: */
236: static inline const struct cred *get_cred(const struct cred *cred)
237: {
238: return get_cred_many(cred, 1);
239: }
240:
241: static inline const struct cred *get_cred_rcu(const struct cred *cred)
242: {
243: struct cred *nonconst_cred = (struct cred *) cred;
244: if (!cred)
245: return NULL;
246: if (!atomic_long_inc_not_zero(&nonconst_cred->usage))
247: return NULL;
248: nonconst_cred->non_rcu = 0;
249: return cred;
250: }
251:
252: /**
253: * put_cred_many - Release a reference to a set of credentials
254: * @_cred: The credentials to release
255: * @nr: Number of references to release
256: *
257: * Release a reference to a set of credentials, deleting them when the last ref
258: * is released. If %NULL is passed, nothing is done.
259: *
260: * This takes a const pointer to a set of credentials because the credentials
261: * on task_struct are attached by const pointers to prevent accidental
262: * alteration of otherwise immutable credential sets.
263: */
264: static inline void put_cred_many(const struct cred *_cred, int nr)
265: {
266: struct cred *cred = (struct cred *) _cred;
267:
268: if (cred) {
269: if (atomic_long_sub_and_test(nr, &cred->usage))
270: __put_cred(cred);
271: }
272: }
273:
274: /*
275: * put_cred - Release a reference to a set of credentials
276: * @cred: The credentials to release
277: *
278: * Release a reference to a set of credentials, deleting them when the last ref
279: * is released. If %NULL is passed, nothing is done.
280: */
281: static inline void put_cred(const struct cred *cred)
282: {
283: put_cred_many(cred, 1);
284: }
285:
286: DEFINE_CLASS(prepare_creds,
287: struct cred *,
288: if (_T) put_cred(_T),
289: prepare_creds(), void)
290:
291: DEFINE_FREE(put_cred, struct cred *, if (!IS_ERR_OR_NULL(_T)) put_cred(_T))
292:
293: /**
294: * current_cred - Access the current task's subjective credentials
295: *
296: * Access the subjective credentials of the current task. RCU-safe,
297: * since nobody else can modify it.
298: */
299: #define current_cred() \
]
|
| 120/4 |
2026/07/06 22:53 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 39580
output: 35
thoughts: 471
Thoughts: **Analyzing Credential Copying in Linux Kernel**
Okay, so I was looking into the credential handling in the kernel, specifically the `prepare_creds` function and how it copies credentials. The comment in `current_cred()` caught my eye: it explicitly states that the committed credentials are *not* supposed to be modified. This is key.
Now, I was initially worried about a potential race condition with `memcpy` if `old->usage` were changing during the copy. I considered the scenario where `prepare_creds` does a `memcpy` of the entire `struct cred`. Because `usage` is an `atomic_long_t`, which is likely a 64-bit integer on most modern systems. The concern was that `memcpy` *could* copy this in 32-bit chunks, resulting in a garbage value for the usage count.
However, after a closer look, it seems I was overly cautious. `prepare_creds` immediately calls `atomic_long_set(&new->usage, 1)` after the `memcpy`. Therefore, any "garbage" from the `memcpy` is immediately overwritten with a correct value. The same logic applies to `non_rcu`, which is an `int` and is also explicitly set to `0` right after the copy. This eliminates any possible data corruption due to the `memcpy` race.
I started to wonder if there were any other fields which could be affected by this race, but I have searched and haven't found any.
Then I considered the layout of the `struct cred`. What if `usage` and `non_rcu` were near the end of the struct, or even somewhere in the middle? The `memcpy` would still copy them regardless.
Finally, the thing that I need to investigate is the LSM hooks. `security_prepare_creds` gets called with `new` and `old`. The signature shows that the old credentials are declared as `const struct cred *old`. I need to ensure that the LSM hooks don't modify the `old` credentials because it would be a violation of the function signature. If they did, they would have to cast away the `const`, which is a code smell. So, I will investigate the `security_prepare_creds` function in `security/security.c` to confirm this.
|
| 121/4 |
2026/07/06 22:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:security/security.c Name:security_prepare_creds]
Results: map[SourceCode:2854: /**
2855: * security_prepare_creds() - Prepare a new set of credentials
2856: * @new: new credentials
2857: * @old: original credentials
2858: * @gfp: gfp flags
2859: *
2860: * Prepare a new set of credentials by copying the data from the old set.
2861: *
2862: * Return: Returns 0 on success, negative values on failure.
2863: */
2864: int security_prepare_creds(struct cred *new, const struct cred *old, gfp_t gfp)
2865: {
2866: int rc = lsm_cred_alloc(new, gfp);
2867:
2868: if (rc)
2869: return rc;
2870:
2871: rc = call_int_hook(cred_prepare, new, old, gfp);
2872: if (unlikely(rc))
2873: security_cred_free(new);
2874: return rc;
2875: }
SourceFile:security/security.c]
|
| 122/4 |
2026/07/06 22:54 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 40916
output: 19
thoughts: 23
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:
**Analyzing the Credential Preparation Process**
Alright, so the system's triggered the `cred_prepare` hook. That's my starting point. Now, I need to understand what's *actually* happening here. My primary line of inquiry will be to identify which Linux Security Modules (LSMs) have registered handlers for this hook. I need to get a clear picture of which modules are going to exert influence on the credential preparation stage. The more I understand the landscape of modules hooking into this event the better. This will enable a more nuanced understanding of the system's policy decisions. Knowing the specific LSM implementations present is essential before I can even begin to debug effectively. I'm going to start by pulling up my tools to check which LSMs are involved.
|
| 123/4 |
2026/07/06 22:55 |
tool |
grepper |
0m
Error:
Args: map[Expression:\.cred_prepare =]
Results:
|
| 124/4 |
2026/07/06 22:55 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 41156
output: 19
thoughts: 58
Thoughts: Okay, let me think this through.
**Analyzing the Credential Preparation Hook**
Hmm, where should I begin? Right, I need to get a clear picture of this `cred_prepare` function. My instinct is to locate the definition first. The fastest way to get to the root of things is usually to identify the function name, so I'll start with a search for its exact definition. Let me try `LSM_HOOK(int, 0, cred_prepare)` to pinpoint where it's declared. That should get me the exact signature and context, and from there, the implementations should be relatively easy to find.
Wait a second, there might be a faster method. Since I'm familiar with the naming conventions, perhaps I can directly search for the underlying symbol. Yes, I'll bypass the macro. Instead of the hook, I will search for the core function, which should be named something like `_cred_prepare`. That's likely the symbol I'm looking for. That should lead me directly to the heart of the matter.
|
| 125/4 |
2026/07/06 22:56 |
tool |
grepper |
0m
Args: map[Expression:_cred_prepare\(]
Results: map[Output:security/apparmor/lsm.c=86=static int apparmor_cred_alloc_blank(struct cred *cred, gfp_t gfp)
--
security/apparmor/lsm.c-94- */
security/apparmor/lsm.c:95:static int apparmor_cred_prepare(struct cred *new, const struct cred *old,
security/apparmor/lsm.c-96- gfp_t gfp)
--
security/landlock/cred.c=19=static void hook_cred_transfer(struct cred *const new,
--
security/landlock/cred.c-28-
security/landlock/cred.c:29:static int hook_cred_prepare(struct cred *const new,
security/landlock/cred.c-30- const struct cred *const old, const gfp_t gfp)
--
security/selinux/hooks.c=4277=static int selinux_task_alloc(struct task_struct *task,
--
security/selinux/hooks.c-4290- */
security/selinux/hooks.c:4291:static int selinux_cred_prepare(struct cred *new, const struct cred *old,
security/selinux/hooks.c-4292- gfp_t gfp)
--
security/smack/smack_lsm.c=2100=static void smack_cred_free(struct cred *cred)
--
security/smack/smack_lsm.c-2123- */
security/smack/smack_lsm.c:2124:static int smack_cred_prepare(struct cred *new, const struct cred *old,
security/smack/smack_lsm.c-2125- gfp_t gfp)
--
security/tomoyo/tomoyo.c=17=struct tomoyo_domain_info *tomoyo_domain(void)
--
security/tomoyo/tomoyo.c-36- */
security/tomoyo/tomoyo.c:37:static int tomoyo_cred_prepare(struct cred *new, const struct cred *old,
security/tomoyo/tomoyo.c-38- gfp_t gfp)
]
|
| 126/4 |
2026/07/06 22:56 |
llm |
codeexpert |
1m
Model:
Tokens:
input: 42021
output: 40
thoughts: 13
Thoughts: Okay, let's dive into this. Here's my take on those thoughts, as if they're mine:
**Checking `selinux_cred_prepare`**
Right, time to get my hands dirty. My instinct is telling me to zero in on `selinux_cred_prepare`. It's a key function, and almost certainly critical for the correct context transitions we are looking for. I want to double-check its behavior, look for any potential gotchas or edge cases, and ensure it's playing nicely within the broader security module. Understanding its exact mechanics will inform my analysis of the overall process flow, and expose whether there's an opportunity for a vulnerability, or a misconfiguration. Itβs the starting point for understanding context preparation, so let's see whatβs going on. I'm especially interested in how it interacts with the current security context and the target context. Gotta make sure everything lines up.
|
| 127/4 |
2026/07/06 22:57 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:security/selinux/hooks.c Name:selinux_cred_prepare]
Results: map[SourceCode:4288: /*
4289: * prepare a new set of credentials for modification
4290: */
4291: static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4292: gfp_t gfp)
4293: {
4294: const struct cred_security_struct *old_crsec = selinux_cred(old);
4295: struct cred_security_struct *crsec = selinux_cred(new);
4296:
4297: *crsec = *old_crsec;
4298: return 0;
4299: }
SourceFile:security/selinux/hooks.c]
|
| 128/4 |
2026/07/06 22:57 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 42483
output: 39
thoughts: 19
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Security Context Deep Dive**
Hmm, it's simply copying the security structure, right? Nothing particularly groundbreaking there β efficient, but not necessarily insightful. I'd need more context to say if it's the right choice. But it's just grabbing that struct and moving it around.
Now, that's making me wonder... what about `apparmor_cred_prepare`? Is this code path interacting with AppArmor at all? It's essential to understand if there's any implicit interaction with AppArmor here, especially since it concerns credential preparation. I need to figure out if it's potentially missing a hook, or if this is bypassing a critical security check somewhere. I need to confirm whether AppArmor is in play and fully accounted for. I need to track down how this interacts with the policy enforcement.
|
| 129/4 |
2026/07/06 22:58 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:security/apparmor/lsm.c Name:apparmor_cred_prepare]
Results: map[SourceCode: SourceFile:]
|
| 130/4 |
2026/07/06 22:58 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 42755
output: 36
thoughts: 6
Thoughts: Okay, I'm ready. Here's a summary as if it's my own thought process, assuming I'm an expert in my field:
**Initial Assessment and Processing**
Alright, I'll dive in. I see "I'll read it" - that's the starting point. It's a simple instruction, a directive to engage with the material. This is where the work begins. I'm going to read the content, and then the real analysis starts. I'll read it not just for surface-level comprehension, but with a critical eye, looking for nuances, implications, and how it aligns with, or challenges, established theories and practices within my area of expertise. I'll be forming hypotheses as I go.
|
| 131/4 |
2026/07/06 22:58 |
tool |
read-file |
0m
Args: map[File:security/apparmor/lsm.c FirstLine:95 LineCount:10]
Results: map[Contents: 95: static int apparmor_cred_prepare(struct cred *new, const struct cred *old,
96: gfp_t gfp)
97: {
98: set_cred_label(new, aa_get_newest_label(cred_label(old)));
99: return 0;
100: }
101:
102: /*
103: * transfer the apparmor data to a blank set of creds
104: */
]
|
| 132/4 |
2026/07/06 22:59 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 43104
output: 42
thoughts: 40
Thoughts: Here's my take on the thought process:
**Analyzing Potential Refcount Issues**
Okay, so I'm digging into this code and trying to pinpoint where a potential refcount misstep could occur. My initial focus is on this `aa_get_newest_label` function. It seems like it *might* be incrementing the reference count for the label it returns. But the crucial thing here is that it's not actually modifying the `old` variable in any way. That's good β avoids at least one obvious source of a problem. But that doesn't necessarily mean we're completely safe.
Now, I need to widen the lens. I need to know where else a refcount could be getting botched. The real threat could lie elsewhere. Next, Iβm thinking about `smack_cred_prepare`. Itβs probably a good place to look for subtle refcount errors, so I'll need to check the code there to see if refcounts are being handled correctly. This one seems like a possible area of concern that I'll need to scrutinize more carefully.
|
| 133/4 |
2026/07/06 22:59 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:security/smack/smack_lsm.c Name:smack_cred_prepare]
Results: map[SourceCode: SourceFile:]
|
| 134/4 |
2026/07/06 22:59 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 43439
output: 41
thoughts: 6
Thoughts: Okay, I'm ready. Here's a summary as if it's my own thought process, assuming I'm an expert in my field:
**Initial Assessment and Processing**
Alright, I'll dive in. I see "I'll read it" - that's the starting point. It's a simple instruction, a directive to engage with the material. This is where the work begins. I'm going to read the content, and then the real analysis starts. I'll read it not just for surface-level comprehension, but with a critical eye, looking for nuances, implications, and how it aligns with, or challenges, established theories and practices within my area of expertise. I'll be forming hypotheses as I go.
|
| 135/4 |
2026/07/06 22:59 |
tool |
read-file |
0m
Args: map[File:security/smack/smack_lsm.c FirstLine:2124 LineCount:10]
Results: map[Contents:2124: static int smack_cred_prepare(struct cred *new, const struct cred *old,
2125: gfp_t gfp)
2126: {
2127: struct task_smack *old_tsp = smack_cred(old);
2128: struct task_smack *new_tsp = smack_cred(new);
2129: int rc;
2130:
2131: init_task_smack(new_tsp, old_tsp->smk_task, old_tsp->smk_task);
2132:
2133: rc = smk_copy_rules(&new_tsp->smk_rules, &old_tsp->smk_rules, gfp);
]
|
| 136/4 |
2026/07/06 22:59 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 43850
output: 40
thoughts: 734
Thoughts: **Analyzing the Credential Copy Race**
Okay, so I'm revisiting this `memcpy` race condition again, specifically the one that involves copying `old` credentials to `new`. It seems my initial assumption that only `usage` and `non_rcu` are modified in-place within `old` is, in fact, correct. That's a good starting point.
Now, let's break down that `memcpy` line again:
```c
memcpy(new, old, sizeof(struct cred));
```
The core concern, as I recall, is what can happen if `old->usage` is being modified concurrently by another CPU running `get_cred(old)`. That function in turn calls `get_cred_many(old, 1)`. Within that call, we have these crucial lines:
```c
nonconst_cred->non_rcu = 0;
atomic_long_add(nr, &nonconst_cred->usage);
```
So `non_rcu = 0` is a straightforward store, and `atomic_long_add` is, well, atomic.
So, if `memcpy` is happening while this is running, what are the possible scenarios?
- `non_rcu` could be read as either 1 or 0 during the `memcpy`.
- `usage` could hold its original value, the updated value, or even a 'torn' value, assuming the architecture permits it and `memcpy` doesn't use atomic reads.
But, and this is the crucial part, in `prepare_creds`, the copied values are immediately overwritten by these lines:
```c
new->non_rcu = 0;
atomic_long_set(&new->usage, 1);
```
This is excellent! Anything potentially inconsistent copied into `new` is immediately discarded. Therefore, the race seems benign for `new`. So, that potential race is a non-issue.
But, am I missing something? Are there *any* other fields that might be modified in `old` concurrently?
I've already looked at the pointers β `user`, `group_info`, `ucounts`, `user_ns`, `keyrings`, and `security`. They are all handled by reference counting β increments on the *objects* they point to, not by modifying the pointers themselves within `old`. So those are safe.
Wait, what about `key_fsuid_changed`? I know that's called...
```c
void key_fsuid_changed(struct cred *new_cred)
{
/* update the ownership of the thread keyring */
if (new_cred->thread_keyring) {
down_write(&new_cred->thread_keyring->sem);
new_cred->thread_keyring->uid = new_cred->fsuid;
up_write(&new_cred->thread_keyring->sem);
}
}
```
This is called in `commit_creds`... on `new`, but `new` isn't yet assigned to `task->cred`. And it looks like I need to pay close attention to the order of operations in `commit_creds`:
```c
if (!uid_eq(new->fsuid, old->fsuid))
key_fsuid_changed(new);
...
rcu_assign_pointer(task->real_cred, new);
```
Aha! `key_fsuid_changed` is *before* `rcu_assign_pointer`. This is critical. `new` is still private, and the modifications it makes don't impact what will be assigned to the task's credential.
Are we done? Is there any other place? I know how tricky this can be...
What about `keyctl_session_to_parent`? That's notoriously difficult. Let's make sure it's not involved.
|
| 137/4 |
2026/07/06 23:00 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:security/keys/keyctl.c Name:keyctl_session_to_parent]
Results: map[SourceCode:1626: /*
1627: * Attempt to install the calling process's session keyring on the process's
1628: * parent process.
1629: *
1630: * The keyring must exist and must grant the caller LINK permission, and the
1631: * parent process must be single-threaded and must have the same effective
1632: * ownership as this process and mustn't be SUID/SGID.
1633: *
1634: * The keyring will be emplaced on the parent when it next resumes userspace.
1635: *
1636: * If successful, 0 will be returned.
1637: */
1638: long keyctl_session_to_parent(void)
1639: {
1640: struct task_struct *me, *parent;
1641: const struct cred *mycred, *pcred;
1642: struct callback_head *newwork, *oldwork;
1643: key_ref_t keyring_r;
1644: struct cred *cred;
1645: int ret;
1646:
1647: keyring_r = lookup_user_key(KEY_SPEC_SESSION_KEYRING, 0, KEY_NEED_LINK);
1648: if (IS_ERR(keyring_r))
1649: return PTR_ERR(keyring_r);
1650:
1651: ret = -ENOMEM;
1652:
1653: /* our parent is going to need a new cred struct, a new tgcred struct
1654: * and new security data, so we allocate them here to prevent ENOMEM in
1655: * our parent */
1656: cred = cred_alloc_blank();
1657: if (!cred)
1658: goto error_keyring;
1659: newwork = &cred->rcu;
1660:
1661: cred->session_keyring = key_ref_to_ptr(keyring_r);
1662: keyring_r = NULL;
1663: init_task_work(newwork, key_change_session_keyring);
1664:
1665: me = current;
1666: rcu_read_lock();
1667: write_lock_irq(&tasklist_lock);
1668:
1669: ret = -EPERM;
1670: oldwork = NULL;
1671: parent = rcu_dereference_protected(me->real_parent,
1672: lockdep_is_held(&tasklist_lock));
1673:
1674: /* the parent mustn't be init and mustn't be a kernel thread */
1675: if (parent->pid <= 1 || !parent->mm)
1676: goto unlock;
1677:
1678: /* the parent must be single threaded */
1679: if (!thread_group_empty(parent))
1680: goto unlock;
1681:
1682: /* the parent and the child must have different session keyrings or
1683: * there's no point */
1684: mycred = current_cred();
1685: pcred = __task_cred(parent);
1686: if (mycred == pcred ||
1687: mycred->session_keyring == pcred->session_keyring) {
1688: ret = 0;
1689: goto unlock;
1690: }
1691:
1692: /* the parent must have the same effective ownership and mustn't be
1693: * SUID/SGID */
1694: if (!uid_eq(pcred->uid, mycred->euid) ||
1695: !uid_eq(pcred->euid, mycred->euid) ||
1696: !uid_eq(pcred->suid, mycred->euid) ||
1697: !gid_eq(pcred->gid, mycred->egid) ||
1698: !gid_eq(pcred->egid, mycred->egid) ||
1699: !gid_eq(pcred->sgid, mycred->egid))
1700: goto unlock;
1701:
1702: /* the keyrings must have the same UID */
1703: if ((pcred->session_keyring &&
1704: !uid_eq(pcred->session_keyring->uid, mycred->euid)) ||
1705: !uid_eq(mycred->session_keyring->uid, mycred->euid))
1706: goto unlock;
1707:
1708: /* cancel an already pending keyring replacement */
1709: oldwork = task_work_cancel_func(parent, key_change_session_keyring);
1710:
1711: /* the replacement session keyring is applied just prior to userspace
1712: * restarting */
1713: ret = task_work_add(parent, newwork, TWA_RESUME);
1714: if (!ret)
1715: newwork = NULL;
1716: unlock:
1717: write_unlock_irq(&tasklist_lock);
1718: rcu_read_unlock();
1719: if (oldwork)
1720: put_cred(container_of(oldwork, struct cred, rcu));
1721: if (newwork)
1722: put_cred(cred);
1723: return ret;
1724:
1725: error_keyring:
1726: key_ref_put(keyring_r);
1727: return ret;
1728: }
SourceFile:security/keys/keyctl.c]
|
| 138/4 |
2026/07/06 23:00 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 47107
output: 40
thoughts: 55
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience:
**Analyzing Credential Modification in a Parent Process**
Alright, so the core of this seems to be about modifying the parent process's credentials, specifically using `task_work_add`. I know that means we're scheduling a task to run, likely asynchronously, which is interesting. The key here is that `key_change_session_keyring` will be executing within the *parent's* context. That's not always obvious, and it changes things fundamentally compared to other scenarios. I need to be sure I'm following the security implications of that. Given this method of credential change, I need to know the risks involved. This also means I need to double-check that this is safe and there are no race conditions. Let's dig into `key_change_session_keyring` to see *exactly* what's happening. I need to fully understand how that function interacts with the keyring structures and what safeguards are in place.
|
| 139/4 |
2026/07/06 23:01 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:security/keys/keyctl.c Name:key_change_session_keyring]
Results: map[SourceCode: 907: /*
908: * Replace a process's session keyring on behalf of one of its children when
909: * the target process is about to resume userspace execution.
910: */
911: void key_change_session_keyring(struct callback_head *twork)
912: {
913: const struct cred *old = current_cred();
914: struct cred *new = container_of(twork, struct cred, rcu);
915:
916: if (unlikely(current->flags & PF_EXITING)) {
917: put_cred(new);
918: return;
919: }
920:
921: /* If get_ucounts fails more bits are needed in the refcount */
922: if (unlikely(!get_ucounts(old->ucounts))) {
923: WARN_ONCE(1, "In %s get_ucounts failed\n", __func__);
924: put_cred(new);
925: return;
926: }
927:
928: new-> uid = old-> uid;
929: new-> euid = old-> euid;
930: new-> suid = old-> suid;
931: new->fsuid = old->fsuid;
932: new-> gid = old-> gid;
933: new-> egid = old-> egid;
934: new-> sgid = old-> sgid;
935: new->fsgid = old->fsgid;
936: new->user = get_uid(old->user);
937: new->ucounts = old->ucounts;
938: new->user_ns = get_user_ns(old->user_ns);
939: new->group_info = get_group_info(old->group_info);
940:
941: new->securebits = old->securebits;
942: new->cap_inheritable = old->cap_inheritable;
943: new->cap_permitted = old->cap_permitted;
944: new->cap_effective = old->cap_effective;
945: new->cap_ambient = old->cap_ambient;
946: new->cap_bset = old->cap_bset;
947:
948: new->jit_keyring = old->jit_keyring;
949: new->thread_keyring = key_get(old->thread_keyring);
950: new->process_keyring = key_get(old->process_keyring);
951:
952: security_transfer_creds(new, old);
953:
954: commit_creds(new);
955: }
SourceFile:security/keys/process_keys.c]
|
| 140/4 |
2026/07/06 23:01 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 48272
output: 19
thoughts: 785
Thoughts: **Analyzing Credential Handling in the Kernel**
Okay, let me break down what's happening here with these credentials. The code flow first creates a *new* credential and then uses `commit_creds(new)`. But, it skips `prepare_creds()` directly, which is a bit unusual. Instead, the `cred` is allocated in `keyctl_session_to_parent` through `cred_alloc_blank()`. It then populates this new credential from the *old* one, which is essentially the current credential of the parent process, using `current_cred()`.
Since we're within the parent's context, the *old* credential reflects the parent's state. Crucially, the *new* credential remains private until `commit_creds(new)` is called. That gives me a little peace of mind.
Now, my initial hunch is that only the `usage` and `non_rcu` fields are modified *in-place*. I should double-check for any other fields that get touched and whether they're properly handled. The `rcu` field is part of a union with `non_rcu`. `rcu` is utilized when `non_rcu` is 0. However, `rcu` is used only when the credential is being freed.
Let's see: `get_cred_many` sets `non_rcu = 0`. So, if `non_rcu` was 1, it's now 0. If `non_rcu` was 1, it meant the credential could be freed without RCU, but now someone else has a reference to the credential. It might be freed later in a context requiring RCU. Setting it to 0 is the safe thing to do.
Okay, is there a race between `memcpy` and `non_rcu = 0`? No, if `memcpy` sees `non_rcu` as 1, the subsequent setting to 0 in `prepare_creds` is fine. If `memcpy` sees 0 and `prepare_creds` also sets it to 0, it's fine too.
What about `usage`? If `memcpy` sees a torn `usage` value, then setting it to 1 is safe.
The only scenario that would be a problem is if some *other* field is modified in-place *and* isn't subsequently overwritten in `prepare_creds`. But let's see. `prepare_creds` *does* overwrite:
* `non_rcu`
* `usage`
* `security`
* `ucounts`
Wait, it doesn't overwrite `uid`, `gid`, etc. The values copied by `memcpy` are kept. But, those values aren't supposed to change in the *old* credential anyway, so we should be okay.
And what about `group_info`, `user`, and `user_ns`? Lines of code make calls to `get_group_info(new->group_info)`, `get_uid(new->user)`, `get_user_ns(new->user_ns)`. These utilize the values copied by `memcpy`. If `old->group_info` were changed in-place, then the pointer `new->group_info` might point to a freed object or cause other issues. However, `old->group_info` is *not* changed in-place.
Now I should verify if `group_info` is ever changed in-place, so I will search the entire kernel code, excluding `prepare_creds` and similar functions to make sure there are no issues.
|
| 141/4 |
2026/07/06 23:01 |
tool |
grepper |
0m
Args: map[Expression:->group_info =]
Results: map[Output:fs/nfs/dir.c=3217=void nfs_access_add_cache(struct inode *inode, struct nfs_access_entry *set,
--
fs/nfs/dir.c-3225- cache->fsgid = cred->fsgid;
fs/nfs/dir.c:3226: cache->group_info = get_group_info(cred->group_info);
fs/nfs/dir.c-3227- cache->mask = set->mask;
--
fs/nfsd/filecache.c=80=nfsd_match_cred(const struct cred *c1, const struct cred *c2)
--
fs/nfsd/filecache.c-87- return false;
fs/nfsd/filecache.c:88: if (c1->group_info == NULL || c2->group_info == NULL)
fs/nfsd/filecache.c:89: return c1->group_info == c2->group_info;
fs/nfsd/filecache.c-90- if (c1->group_info->ngroups != c2->group_info->ngroups)
--
kernel/groups.c=118=void set_groups(struct cred *new, struct group_info *group_info)
--
kernel/groups.c-121- get_group_info(group_info);
kernel/groups.c:122: new->group_info = group_info;
kernel/groups.c-123-}
--
net/sunrpc/auth_unix.c=80=unx_match(struct auth_cred *acred, struct rpc_cred *cred, int flags)
--
net/sunrpc/auth_unix.c-94- groups = UNX_NGROUPS;
net/sunrpc/auth_unix.c:95: if (cred->cr_cred->group_info == NULL)
net/sunrpc/auth_unix.c-96- return groups == 0;
]
|
| 142/4 |
2026/07/06 23:02 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 50380
output: 34
thoughts: 1321
Thoughts: **My Analysis of Credential Modification in the Linux Kernel**
Okay, let's break this down. My main focus here is understanding how credentials (`struct cred`) are modified and committed in the Linux kernel, specifically concerning potential race conditions and data integrity, particularly around `memcpy` in `prepare_creds`.
First, I examined the `set_groups` function. It takes a new `struct cred *new` and a `group_info` pointer. The key here is that it operates on the *new* credential structure before it's committed, consistent with the `prepare_creds` pattern. I then confirmed this pattern by looking at `__sys_setgroups`. `set_groups` is called on a newly prepared credential, after the call to `prepare_creds`, which returns a `new` cred, so this follows the pattern.
I then did the same analysis for `set_user`, and I observed the same thing: changes are made on the `new` credential, before commitment.
The consistent pattern is modification on a "new" credential before it's made active.
My primary question is whether any fields are modified in-place after credential commitment. The pattern suggests no, and I'll confirm that.
Next, I looked for exceptions to this pattern and identified `usage` and `non_rcu`. These are special fields. I'm going to revisit those. I also need to verify that there are no other `atomic_t` fields or special data structures. I checked the struct definition again, and other than `kuid_t`, `kgid_t`, `unsigned`, `kernel_cap_t` and pointers, there are no special types. The `kernel_cap_t` struct contains a `__u32` array and could be a potential concern, but it's not modified in-place.
My primary takeaway: the credential API seems designed to maintain the immutability of committed credentials. All modification functions use the `prepare_creds -> modify new -> commit_creds` flow, meaning that changes only occur on the copy.
**Answering the User's Questions:**
1. **Are any fields modified in-place after being committed (other than `usage` and `non_rcu`)?** Based on my review, no. The design enforces the immutability of committed credentials. All modifications are done to the `new` credential within the `prepare_creds` flow. The only exceptions are `usage` (reference count) and `non_rcu` (RCU optimization).
2. **Is the race between `prepare_creds`'s `memcpy` and `get_cred` benign?** Yes, it is. The `memcpy` could grab partially-written `usage` and `non_rcu` fields, but `prepare_creds` immediately sets these to their correct initial values (`usage = 1`, `non_rcu = 0`) *after* the `memcpy`. So, even if the copy is torn, the kernel sets the values immediately afterward and the partially written values are never used.
I also checked to make sure that the `memcpy` is not slow enough to let another thread free the `old` cred. `prepare_creds` is called by `current`, and `current` holds a reference to `old`, so this is protected. I also confirmed `prepare_creds` always uses `current->cred`.
I then looked at `prepare_kernel_cred`, and the analysis is the same. `old` is protected by `get_task_cred` or `get_cred(&init_cred)`, and the `usage` and `non_rcu` fields are overwritten.
So, the conclusion is: the copy is protected and the partially written fields from the source are overwritten, so no issue.
I then went back to `non_rcu` to see where it comes from. It's in `include/linux/cred.h`. It's related to bypassing RCU grace periods in some cases, but once "shared" via `get_cred`, RCU must be used.
I think I'll go check the history of `non_rcu`, just in case there were any known issues.
|
| 143/4 |
2026/07/06 23:03 |
tool |
git-log |
0m
Args: map[CodeRegexp:non_rcu PathPrefix:include/linux/cred.h]
Results: map[Output:d7852fbd0f04 access: avoid the RCU grace period for the temporary subjective credentials
]
|
| 144/4 |
2026/07/06 23:03 |
llm |
codeexpert |
1m
Model:
Tokens:
input: 52678
output: 26
thoughts: 7
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert user and presented in the first person:
**Analyzing the Commit**
Right, let's dive into that commit. I need to quickly assess the changes, understand the rationale behind them, and anticipate any potential implications. My initial scan will be for the obvious: any breaking changes, performance bottlenecks, or security vulnerabilities that might jump out. Then I'll focus on the architecture and design: does this align with the project's overall strategy and best practices? Are there any unexpected dependencies introduced? Is the code clean, well-commented, and testable? The ideal scenario is a commit that clearly addresses a specific issue or implements a defined feature, with concise and relevant commit messages. A deep dive is sometimes necessary, especially for complex algorithms or refactoring efforts, but first, I need a quick high-level overview to get my bearings and frame my more detailed analysis. I can't wait to see if itβs well-structured and follows the defined coding standards.
|
| 145/4 |
2026/07/06 23:05 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d7852fbd0f0423937fa287a598bfde188bb68c22
Author: Linus Torvalds <torvalds@linux-foundation.org>
Date: Thu Jul 11 09:54:40 2019 -0700
access: avoid the RCU grace period for the temporary subjective credentials
It turns out that 'access()' (and 'faccessat()') can cause a lot of RCU
work because it installs a temporary credential that gets allocated and
freed for each system call.
The allocation and freeing overhead is mostly benign, but because
credentials can be accessed under the RCU read lock, the freeing
involves a RCU grace period.
Which is not a huge deal normally, but if you have a lot of access()
calls, this causes a fair amount of seconday damage: instead of having a
nice alloc/free patterns that hits in hot per-CPU slab caches, you have
all those delayed free's, and on big machines with hundreds of cores,
the RCU overhead can end up being enormous.
But it turns out that all of this is entirely unnecessary. Exactly
because access() only installs the credential as the thread-local
subjective credential, the temporary cred pointer doesn't actually need
to be RCU free'd at all. Once we're done using it, we can just free it
synchronously and avoid all the RCU overhead.
So add a 'non_rcu' flag to 'struct cred', which can be set by users that
know they only use it in non-RCU context (there are other potential
users for this). We can make it a union with the rcu freeing list head
that we need for the RCU case, so this doesn't need any extra storage.
Note that this also makes 'get_current_cred()' clear the new non_rcu
flag, in case we have filesystems that take a long-term reference to the
cred and then expect the RCU delayed freeing afterwards. It's not
entirely clear that this is required, but it makes for clear semantics:
the subjective cred remains non-RCU as long as you only access it
synchronously using the thread-local accessors, but you _can_ use it as
a generic cred if you want to.
It is possible that we should just remove the whole RCU markings for
->cred entirely. Only ->real_cred is really supposed to be accessed
through RCU, and the long-term cred copies that nfs uses might want to
explicitly re-enable RCU freeing if required, rather than have
get_current_cred() do it implicitly.
But this is a "minimal semantic changes" change for the immediate
problem.
Acked-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Acked-by: Eric Dumazet <edumazet@google.com>
Acked-by: Paul E. McKenney <paulmck@linux.ibm.com>
Cc: Oleg Nesterov <oleg@redhat.com>
Cc: Jan Glauber <jglauber@marvell.com>
Cc: Jiri Kosina <jikos@kernel.org>
Cc: Jayachandran Chandrasekharan Nair <jnair@marvell.com>
Cc: Greg KH <greg@kroah.com>
Cc: Kees Cook <keescook@chromium.org>
Cc: David Howells <dhowells@redhat.com>
Cc: Miklos Szeredi <miklos@szeredi.hu>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/fs/open.c b/fs/open.c
index b5b80469b93d..a59abe3c669a 100644
--- a/fs/open.c
+++ b/fs/open.c
@@ -374,6 +374,25 @@ long do_faccessat(int dfd, const char __user *filename, int mode)
override_cred->cap_permitted;
}
+ /*
+ * The new set of credentials can *only* be used in
+ * task-synchronous circumstances, and does not need
+ * RCU freeing, unless somebody then takes a separate
+ * reference to it.
+ *
+ * NOTE! This is _only_ true because this credential
+ * is used purely for override_creds() that installs
+ * it as the subjective cred. Other threads will be
+ * accessing ->real_cred, not the subjective cred.
+ *
+ * If somebody _does_ make a copy of this (using the
+ * 'get_current_cred()' function), that will clear the
+ * non_rcu field, because now that other user may be
+ * expecting RCU freeing. But normal thread-synchronous
+ * cred accesses will keep things non-RCY.
+ */
+ override_cred->non_rcu = 1;
+
old_cred = override_creds(override_cred);
retry:
res = user_path_at(dfd, filename, lookup_flags, &path);
diff --git a/include/linux/cred.h b/include/linux/cred.h
index 7eb43a038330..f7a30e0099be 100644
--- a/include/linux/cred.h
+++ b/include/linux/cred.h
@@ -145,7 +145,11 @@ struct cred {
struct user_struct *user; /* real user ID subscription */
struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
struct group_info *group_info; /* supplementary groups for euid/fsgid */
- struct rcu_head rcu; /* RCU deletion hook */
+ /* RCU deletion */
+ union {
+ int non_rcu; /* Can we skip RCU deletion? */
+ struct rcu_head rcu; /* RCU deletion hook */
+ };
} __randomize_layout;
extern void __put_cred(struct cred *);
@@ -246,6 +250,7 @@ static inline const struct cred *get_cred(const struct cred *cred)
if (!cred)
return cred;
validate_creds(cred);
+ nonconst_cred->non_rcu = 0;
return get_new_cred(nonconst_cred);
}
@@ -257,6 +262,7 @@ static inline const struct cred *get_cred_rcu(const struct cred *cred)
if (!atomic_inc_not_zero(&nonconst_cred->usage))
return NULL;
validate_creds(cred);
+ nonconst_cred->non_rcu = 0;
return cred;
}
diff --git a/kernel/cred.c b/kernel/cred.c
index c73a87a4df13..153ae369e024 100644
--- a/kernel/cred.c
+++ b/kernel/cred.c
@@ -144,7 +144,10 @@ void __put_cred(struct cred *cred)
BUG_ON(cred == current->cred);
BUG_ON(cred == current->real_cred);
- call_rcu(&cred->rcu, put_cred_rcu);
+ if (cred->non_rcu)
+ put_cred_rcu(&cred->rcu);
+ else
+ call_rcu(&cred->rcu, put_cred_rcu);
}
EXPORT_SYMBOL(__put_cred);
@@ -256,6 +259,7 @@ struct cred *prepare_creds(void)
old = task->cred;
memcpy(new, old, sizeof(struct cred));
+ new->non_rcu = 0;
atomic_set(&new->usage, 1);
set_cred_subscribers(new, 0);
get_group_info(new->group_info);
@@ -535,7 +539,19 @@ const struct cred *override_creds(const struct cred *new)
validate_creds(old);
validate_creds(new);
- get_cred(new);
+
+ /*
+ * NOTE! This uses 'get_new_cred()' rather than 'get_cred()'.
+ *
+ * That means that we do not clear the 'non_rcu' flag, since
+ * we are only installing the cred into the thread-synchronous
+ * '->cred' pointer, not the '->real_cred' pointer that is
+ * visible to other threads under RCU.
+ *
+ * Also note that we did validate_creds() manually, not depending
+ * on the validation in 'get_cred()'.
+ */
+ get_new_cred((struct cred *)new);
alter_cred_subscribers(new, 1);
rcu_assign_pointer(current->cred, new);
alter_cred_subscribers(old, -1);
@@ -672,6 +688,7 @@ struct cred *prepare_kernel_cred(struct task_struct *daemon)
validate_creds(old);
*new = *old;
+ new->non_rcu = 0;
atomic_set(&new->usage, 1);
set_cred_subscribers(new, 0);
get_uid(new->user);
]
|
| 146/4 |
2026/07/06 23:05 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 55386
output: 31
thoughts: 793
Thoughts: **My Analysis of `struct cred` Immutability**
Okay, so I've been digging into the `struct cred` data structure and its modification patterns, specifically focusing on in-place updates after commitment. My initial findings are pretty clear: `non_rcu` *is* indeed modified in-place by `get_cred` and `get_cred_rcu`, which is important to remember. It gets reset in `prepare_creds`, which got me wondering if there were any other fields added later I had missed.
I've already re-checked the current `struct cred` definition, and I already looked at `ucounts` because I remember it was added later. `set_cred_ucounts` is only called on *new* creds, so it's not a concern here.
Then I thought about `jit_keyring`, an `unsigned char`. But again, that's only modified in `keyctl_set_reqkey_keyring`, and the code uses `prepare_creds` which results in a new cred.
So, I'm pretty confident now. It's essentially designed to be immutable once committed. The only fields I see that are modified in-place are the `usage` (reference count) and the `non_rcu` flag for RCU optimizations. The functions `get_cred`, `get_cred_many`, and `get_cred_rcu` are the culprits performing these in-place modifications, as expected.
`prepare_creds` does a full `memcpy` of the `struct cred`, including both `usage` and `non_rcu`. However, immediately after the copy, `prepare_creds` overwrites `new->usage` and `new->non_rcu` with fresh values (1 and 0, respectively). This is important because any inconsistent values copied in during the race are immediately discarded!
Other fields like `uid`, `gid`, `cap_*`, and pointers to other objects such as `user`, `group_info`, `keyrings`, and `security` are only ever modified on "new" credentials.
I did have a thought about that `security` field though. LSMs might modify the memory pointed to by `cred->security` *after* the initial assignment. However, `prepare_creds` correctly handles this via the `security_prepare_creds(new, old, ...)` function, allowing them to perform a proper copy of their internal state. It's not a direct, in-place modification of the `struct cred` member itself. It even sets the `security` pointer to NULL before reallocating. Looking at the code confirms this: `new->security = NULL` and then `security_prepare_creds()`.
So, the summary is this: no other fields are modified in-place after initial commitment other than `usage` and `non_rcu`. The race condition between `memcpy` and `get_cred` is benign because of the immediate overwriting that occurs.
Just to be absolutely sure, I'll run `grepper` and search for any other `atomic_t` fields in the `struct cred` definition, just to be on the safe side. Can't be too careful!
|
| 147/4 |
2026/07/06 23:06 |
tool |
grepper |
0m
Args: map[Expression:atomic.*usage; PathPrefix:include/linux/cred.h]
Results: map[Output:include/linux/cred.h=115=struct cred {
include/linux/cred.h:116: atomic_long_t usage;
include/linux/cred.h-117- kuid_t uid; /* real UID of the task */
]
|
| 148/4 |
2026/07/06 23:06 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 56983
output: 881
thoughts: 119
Thoughts: **RCU Head Analysis**
Okay, so I'm looking at this. The key thing here is `usage`. That's the core focus. Now, I'm thinking... What about `rcu_head`? Right, it's a `struct`. Here's the definition:
```c
struct rcu_head {
struct rcu_head *next;
void (*func)(struct rcu_head *head);
};
```
I recall that `call_rcu` modifies that, right? Yes. But `call_rcu` is *only* called when `usage` is equal to 0. And then there's `prepare_creds`, that's called on a cred with `usage` being 1 or greater. Okay, that's the logic I needed to solidify my understanding. I've got it. I'm ready to provide the answer.
|
| 149/2 |
2026/07/06 23:06 |
llm |
expert |
0m
Model:
Tokens:
input: 58116
output: 34
thoughts: 433
Thoughts: **Analyzing the Credential Race Condition**
Okay, so the initial analysis suggests there's nothing malicious in this race condition, that it's benign. But let me dig deeper, I need to be absolutely sure. The function `get_cred_many` sets `non_rcu` to 0. Right. So, regardless of whether `non_rcu` was initially 1 or 0, it *becomes* 0. If it was 1, and `prepare_creds` reads it, it temporarily copies the 1 value to the `new->non_rcu` field. But then the overwrite to 0 happens, and effectively, `new->non_rcu` is 0, so no value is leaked.
If `non_rcu` was originally 1, that signifies that `old` cred was a temporary subjective cred, likely from `access_override_creds`. Now, what if Task A has this temporary cred, and Task B is reading it? Wait a second, Task B can't actually see Task A's subjective cred, as the subjective credential is assigned to the `current->cred` field. It only sees Task A's `real_cred`. And `real_cred` can never have `non_rcu = 1`.
Let me just quickly check that. Right, `access_override_creds` *only* modifies `current->cred`. It doesn't touch `current->real_cred` at all. So, the `real_cred` stays untouched. Excellent.
Now, if Task B calls `get_task_cred(Task A)`, it does something like this:
```c
struct cred *get_task_cred(struct task_struct *task)
{
const struct cred *cred;
struct cred *nonconst_cred;
rcu_read_lock();
do {
cred = rcu_dereference(task->real_cred);
nonconst_cred = (struct cred *) cred;
} while (!atomic_long_inc_not_zero(&nonconst_cred->usage));
rcu_read_unlock();
return nonconst_cred;
}
```
Wait, hold on, does `get_task_cred` clear `non_rcu` at all? Hmmm, I need to check the current code for `get_task_cred` to confirm. That's the critical point I need to verify.
|
| 150/2 |
2026/07/06 23:07 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/cred.c Name:get_task_cred]
Results: map[SourceCode: 116: /**
117: * get_task_cred - Get another task's objective credentials
118: * @task: The task to query
119: *
120: * Get the objective credentials of a task, pinning them so that they can't go
121: * away. Accessing a task's credentials directly is not permitted.
122: *
123: * The caller must also make sure task doesn't get deleted, either by holding a
124: * ref on task or by holding tasklist_lock to prevent it from being unlinked.
125: */
126: const struct cred *get_task_cred(struct task_struct *task)
127: {
128: const struct cred *cred;
129:
130: rcu_read_lock();
131:
132: do {
133: cred = __task_cred((task));
134: BUG_ON(!cred);
135: } while (!get_cred_rcu(cred));
136:
137: rcu_read_unlock();
138: return cred;
139: }
SourceFile:kernel/cred.c]
|
| 151/2 |
2026/07/06 23:07 |
llm |
expert |
0m
Model:
Tokens:
input: 59482
output: 28
thoughts: 546
Thoughts: **Analyzing the Credential Structure and Potential Data Races**
Okay, so I'm digging into this credential management code. It's calling `get_cred_rcu(cred)`. Let's look at that function. It increments the usage count and importantly, it clears the `non_rcu` flag.
Right, so any credential shared through `get_task_cred` will have its `non_rcu` cleared too. This confirms my initial understanding: the `struct cred` is essentially immutable, *except* for the `usage` count and `non_rcu` field. `prepare_creds` creates a *copy* but then overwrites those two fields in the copy. The race, then, is solely on `usage` and `non_rcu`. Since the overwrite happens immediately, the race should be benign.
But I should double-check about `non_rcu`. Is it typically 0 already? Yes, it *is* zero by default. It's only 1 in that specific scenario that the cred is *not* shared. And if it's not shared, there's no race. If it *is* shared, then it must have been shared via `get_cred` or similar, which will have already cleared `non_rcu`. So a shared credential *always* has `non_rcu` as 0. Therefore, the `nonconst_cred->non_rcu = 0` is writing a zero to a zero.
This is definitively benign. We're not introducing a data race.
To appease KCSAN, I think the best solution is to use `data_race()` around the `memcpy` or the `non_rcu = 0` assignment. Using `READ_ONCE` isn't as straightforward with a `memcpy`.
Wait, `get_cred_many` is in a header file and used *everywhere*. But `prepare_creds` is only in `kernel/cred.c`. Time to see if there are already any `data_race` annotations in `cred.c`.
|
| 152/2 |
2026/07/06 23:07 |
tool |
grepper |
0m
Error:
Args: map[Expression:data_race PathPrefix:kernel/cred.c]
Results:
|
| 153/2 |
2026/07/06 23:07 |
llm |
expert |
0m
Model:
Tokens:
input: 60521
output: 15
thoughts: 1121
Thoughts: **Benign Data Race Analysis**
Okay, let's break this down. I've got two tasks, 7107 and 7106, both accessing the same `struct cred` object. It's safe to assume they're threads within the same process, sharing the `current->cred`. The key point of contention is the `non_rcu` field. Task 7107 writes to it, setting it to 0 (`init_file` -> `get_cred` -> `get_cred_many`), while Task 7106 reads it via `memcpy` during `prepare_creds`.
My initial thought is that it's benign, but I need to make absolutely sure. The race is on `non_rcu`, which is an `int` (4 bytes). KCSAN picked this up, specifically. The key is in that KCSAN report: `write to 0xffff8881049530a8 of 4 bytes`. I checked the offsets and verified that `0xa8` is the offset of `non_rcu`.
I need to confirm whether `non_rcu`'s use as part of a union with `rcu_head` changes anything. In a 64-bit system, `struct rcu_head` is likely 16 bytes, with `non_rcu` residing in the same memory location as the start of `rcu_head`. If `non_rcu` is 0, the `rcu_head` is used later, specifically when the `usage` count reaches 0. But, while `usage > 0`, the `rcu_head` isn't touched. So, racing on `non_rcu` doesn't affect the integrity of `rcu_head` or the critical sections it protects.
Therefore, the race on `non_rcu` is safe. I'm reasonably confident in this assessment.
I considered annotations and whether `data_race()` would be suitable. I think the better approach is to annotate in `get_cred_many`, where the intentional overwrite takes place. However, that would simply mark it as a safe race. The kernel already has many "Safe Overwrite" races anyway.
I considered whether this race could lead to failures. Could a torn read of `non_rcu` cause `prepare_creds` to go wrong? No, because `new->non_rcu` is set to 0 immediately afterwards, which would be either 0 or corrupted and rewritten.
I checked for compiler optimizations that would change the outcome. Could the compiler reorder the assignment of `new->non_rcu = 0` before the `memcpy`? That would eliminate the race, but it is not possible as two writes to the same memory can not be reordered. Could the compiler optimize `memcpy` and the assignment together, and avoid copying `non_rcu` entirely? Yes, that is a valid optimization that actually avoids the race and still ensures `new->non_rcu` is 0, and that's likely the case!
So, the race is BENIGN, it doesn't matter because of the nature of the operations involved.
|
| 154/2 |
2026/07/06 23:08 |
tool |
set-results |
0m
Args:
Results:
|
| 155/2 |
2026/07/06 23:08 |
llm |
expert |
0m
Model:
Tokens:
input: 62363
output: 818
thoughts: 165
Thoughts: **Benign Data Race Analysis: The Final Word**
Alright, the deep dive is done. After meticulously going over the code, I've concluded β and I'm quite confident in this assessment, given my expertise β that the data race here is, ultimately, benign. Let's break down why.
The crux of the issue lies between `get_cred_many()` and `prepare_creds()`. `get_cred_many()` is writing to `non_rcu` and `usage`, while `prepare_creds()` is reading the *entire* `struct cred` using a `memcpy()`. The concern, of course, is that `memcpy()` might pick up incomplete or inconsistent data, a classic race condition scenario.
However, and this is the critical point, `prepare_creds()` immediately clobbers *both* `non_rcu` and `usage` in the new credential copy. It's a fresh start. Whatever stale or partially updated values `memcpy()` might have grabbed are immediately discarded. We're essentially guaranteed a clean slate with those fields in the new copy.
Furthermore, and this adds another layer of confidence, once a `struct cred` is shared, it's essentially immutable. The only exception to this immutability are these two specific fields: `non_rcu` and `usage`. But even with those fields, it gets better. For shared credentials, `non_rcu` is *already* zero. So, the write in `get_cred_many()` is effectively a "safe overwrite" of the same value. It's not modifying state, just re-asserting it.
Therefore, no valid sequence of operations can cause this race to result in a memory corruption or observable incorrect behavior.
I'm ready to provide the final response based on this analysis.
|
| 156/1 |
2026/07/06 23:08 |
action |
format-explanation |
0m
Results: map[Explanation:The KCSAN data race report shows a conflict between `init_file` (via `get_cred`)
and `prepare_creds` on a `struct cred` object.
### Race Summary
- **Function A (Writer):** `init_file` calls `get_cred`, which eventually calls
`get_cred_many`. This function performs an in-place modification of the
`non_rcu` field (setting it to `0`) and increments the `usage` reference count.
- **Function B (Reader):** `prepare_creds` performs a `memcpy` of the entire
`struct cred` from an existing one (`old`) to a newly allocated one (`new`).
- **Variable:** The `non_rcu` field (offset `0xa8` or 168 bytes) and potentially
the `usage` field of `struct cred`.
### Synchronization Context
The race occurs between two different tasks (e.g., two threads of the same
process or a parent and child) that share the same `struct cred` object. While
`struct cred` is generally immutable once committed to a task, the `usage`
(refcount) and `non_rcu` (RCU optimization flag) fields are modified in-place.
There is no mutual exclusion (like a lock) between a thread taking a new
reference to the shared cred and another thread preparing a new set of
credentials based on it.
### Final Classification: **BENIGN**
### Reasoning
The race is structurally tolerant to stale or torn reads for the following
reasons:
1. **Overwritten Values:** In `prepare_creds`, immediately after the
`memcpy(new, old, sizeof(struct cred))`, the code explicitly initializes the
racing fields in the new copy:
```c
new->non_rcu = 0;
atomic_long_set(&new->usage, 1);
```
Any value (stale, torn, or otherwise) copied from the `old` structure for
these two fields is immediately discarded and never used.
2. **Immutability of Other Fields:** All other fields in `struct cred` (UIDs,
GIDs, capabilities, etc.) are immutable once the credential set is committed and
shared. Therefore, the `memcpy` is guaranteed to see a consistent state for all
fields that actually matter for the new credential set.
3. **Safe Overwrite of `non_rcu`:** The `non_rcu` flag is only set to `1` for
temporary, private subjective credentials (e.g., during an `access()` syscall).
Once a credential is shared (which happens during `fork` or when another thread
takes a reference), `non_rcu` is cleared to `0`. For any shared credential,
`non_rcu` is already `0`, so the write in `get_cred_many` is typically a "safe
overwrite" of the same value.
4. **Reference Integrity:** The `old` credential's lifecycle is safe because
the caller of `prepare_creds` holds a reference to it, and `get_cred` is
incrementing the reference count, not decrementing it.
### Recommended Annotations
To silence the KCSAN warning, the assignment to `non_rcu` in `get_cred_many`
could be wrapped in `data_race()` or converted to `WRITE_ONCE()`, although the
race is fundamentally harmless.
```c
/* include/linux/cred.h */
static inline const struct cred *get_cred_many(const struct cred *cred, int nr)
{
...
data_race(nonconst_cred->non_rcu = 0);
atomic_long_add(nr, &nonconst_cred->usage);
...
}
```]
|