-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcred.rs
More file actions
487 lines (450 loc) · 17.7 KB
/
Copy pathcred.rs
File metadata and controls
487 lines (450 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! linux-parity: complete
//! linux-source: vendor/linux/kernel/cred.c
//! test-origin: linux:vendor/linux/kernel/cred.c
//! Task credentials (`struct cred`) — Milestone 27.
//!
//! Implements:
//! - `Cred` — the per-task credential block (uid/gid/caps/securebits).
//! - `INIT_CRED` — the boot-time credential singleton.
//! - `prepare_creds`, `commit_creds`, `override_creds`, `revert_creds` —
//! the canonical Linux COW credential-update protocol.
//! - `current_cred` — read the calling task's effective cred.
//!
//! # COW protocol
//!
//! 1. `prepare_creds()` allocates a fresh `Cred` initialised from the current
//! cred. The caller mutates the new cred (e.g. drops a capability).
//! 2. `commit_creds(new)` swaps `current.cred = new`, refcount-decrementing
//! the old cred. Linux uses RCU to guarantee readers never see a torn
//! pointer; M27 relies on the cooperative scheduler — full RCU lands in M34.
//! 3. `override_creds(new)` saves+swaps in one step and returns the saved
//! cred so `revert_creds(old)` can restore. Used at security boundaries.
//!
//! Reference: Linux `include/linux/cred.h`, `kernel/cred.c`.
extern crate alloc;
use alloc::boxed::Box;
use core::sync::atomic::{AtomicUsize, Ordering};
use crate::kernel::capability::KernelCapT;
// ── User identifier types ────────────────────────────────────────────────────
/// Kernel user-ID. Linux: `kuid_t`. Currently identity-mapped (no user-NS
/// translation until M28).
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
pub struct KUid(pub u32);
/// Kernel group-ID. Linux: `kgid_t`.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
pub struct KGid(pub u32);
/// Sentinel "invalid" user ID — Linux `INVALID_UID`.
pub const INVALID_UID: KUid = KUid(u32::MAX);
/// Sentinel "invalid" group ID — Linux `INVALID_GID`.
pub const INVALID_GID: KGid = KGid(u32::MAX);
/// `securebits` flags — Linux `include/uapi/linux/securebits.h`.
pub mod securebits {
pub const SECURE_NOROOT: u32 = 0;
pub const SECURE_NO_SETUID_FIXUP: u32 = 2;
pub const SECURE_KEEP_CAPS: u32 = 4;
pub const SECURE_NO_CAP_AMBIENT_RAISE: u32 = 6;
}
// ── Group info ───────────────────────────────────────────────────────────────
pub const NGROUPS_MAX_INLINE: usize = 32;
/// Supplementary group list. Linux `struct group_info` uses a flexible array;
/// M27 caps the count at `NGROUPS_MAX_INLINE` which is sufficient for our
/// in-kernel users. Full dynamic sizing arrives with the user-namespace
/// gid_map work in M28.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct GroupInfo {
pub usage: u32,
pub ngroups: u32,
pub gid: [KGid; NGROUPS_MAX_INLINE],
}
impl Default for GroupInfo {
fn default() -> Self {
Self {
usage: 1,
ngroups: 0,
gid: [KGid(0); NGROUPS_MAX_INLINE],
}
}
}
// ── Cred ─────────────────────────────────────────────────────────────────────
/// Per-task credential block.
///
/// Linux `struct cred` from `include/linux/cred.h`. We reproduce the
/// observable fields; alignment-only fields (`subscribers`, `magic`,
/// `non_rcu`, `rcu`) are omitted as they have no ABI consumer in M27. The
/// `usage` refcount provides correct ownership semantics under the
/// cooperative scheduler.
///
/// # Refcounting
///
/// `usage == 0` means freed; the value is incremented by `get_cred` and
/// decremented by `put_cred`. When `put_cred` brings `usage` to 0 it
/// deallocates the box. M34 will replace the swap in `commit_creds` with
/// `rcu_assign_pointer` so concurrent readers see consistent snapshots.
#[repr(C)]
pub struct Cred {
pub usage: AtomicUsize,
/// Real UID — the UID the task was created with.
pub uid: KUid,
/// Real GID.
pub gid: KGid,
/// Saved set-user-ID.
pub suid: KUid,
/// Saved set-group-ID.
pub sgid: KGid,
/// Effective UID — the one used for permission checks.
pub euid: KUid,
/// Effective GID.
pub egid: KGid,
/// File-system UID — used for filesystem accesses (separated from euid).
pub fsuid: KUid,
/// File-system GID.
pub fsgid: KGid,
/// Inheritable capability mask.
pub cap_inheritable: KernelCapT,
/// Permitted capability mask.
pub cap_permitted: KernelCapT,
/// Effective capability mask.
pub cap_effective: KernelCapT,
/// Bounding capability set.
pub cap_bset: KernelCapT,
/// Ambient capability set (Linux 4.3+).
pub cap_ambient: KernelCapT,
/// `securebits` flags.
pub securebits: u32,
/// Supplementary groups.
pub group_info: GroupInfo,
/// Owning user namespace pointer (raw — type defined in M28).
pub user_ns: *const core::ffi::c_void,
}
// SAFETY: Cred is shared between tasks via refcount; `user_ns` is held for the
// lifetime of the credential and is released when the final cred reference is
// dropped.
unsafe impl Send for Cred {}
unsafe impl Sync for Cred {}
impl Cred {
/// Bump the refcount and return self.
#[inline]
pub fn get(&self) -> &Self {
self.usage.fetch_add(1, Ordering::Relaxed);
self
}
/// Drop a reference; if this was the last one, deallocate.
///
/// # Safety
/// `cred` must have been obtained from `prepare_creds`/`get_cred` and
/// not yet released.
pub unsafe fn put(cred: *const Cred) {
if cred.is_null() {
return;
}
// INIT_CRED is reference-counted but never freed — its pointer is
// identity-stable for the lifetime of the kernel.
if core::ptr::eq(cred, &raw const INIT_CRED as *const Cred) {
unsafe {
(*cred).usage.fetch_sub(1, Ordering::Release);
}
return;
}
let prev = unsafe { (*cred).usage.fetch_sub(1, Ordering::Release) };
if prev == 1 {
let user_ns =
unsafe { (*cred).user_ns } as *const crate::kernel::user_namespace::UserNamespace;
if !user_ns.is_null() {
unsafe { crate::kernel::user_namespace::put_user_ns(user_ns) };
}
unsafe { drop(Box::from_raw(cred as *mut Cred)) };
}
}
}
// ── INIT_CRED (boot singleton) ───────────────────────────────────────────────
/// The init task's credential block.
///
/// Root (uid=0, gid=0) with the full capability set raised, owning the static
/// init user namespace.
pub static INIT_CRED: Cred = Cred {
usage: AtomicUsize::new(usize::MAX / 2), // sticky — never freed
uid: KUid(0),
gid: KGid(0),
suid: KUid(0),
sgid: KGid(0),
euid: KUid(0),
egid: KGid(0),
fsuid: KUid(0),
fsgid: KGid(0),
cap_inheritable: KernelCapT::empty(),
cap_permitted: KernelCapT::full(),
cap_effective: KernelCapT::full(),
cap_bset: KernelCapT::full(),
cap_ambient: KernelCapT::empty(),
securebits: 0,
group_info: GroupInfo {
usage: 1,
ngroups: 0,
gid: [KGid(0); NGROUPS_MAX_INLINE],
},
user_ns: core::ptr::addr_of!(crate::kernel::user_namespace::INIT_USER_NS)
as *const core::ffi::c_void,
};
// ── current_cred / prepare_creds / commit_creds / override_creds ─────────────
/// Read the calling task's effective cred.
///
/// Returns `&INIT_CRED` if the scheduler is not yet running or the current
/// task has a null cred pointer (kernel-thread bring-up before
/// `commit_creds` ran).
pub fn current_cred() -> *const Cred {
let task = unsafe { crate::kernel::sched::get_current() };
if task.is_null() {
return &raw const INIT_CRED;
}
let p = unsafe { (*task).cred };
if p.is_null() { &raw const INIT_CRED } else { p }
}
/// Allocate a new `Cred` initialised from `current_cred()` with `usage == 1`.
///
/// Mirrors Linux `prepare_creds()` — the start of every COW credential change.
pub fn prepare_creds() -> Option<*mut Cred> {
let cur = current_cred();
if cur.is_null() {
return None;
}
let user_ns = if unsafe { (*cur).user_ns.is_null() } {
core::ptr::addr_of!(crate::kernel::user_namespace::INIT_USER_NS)
} else {
unsafe { (*cur).user_ns as *const crate::kernel::user_namespace::UserNamespace }
};
crate::kernel::user_namespace::get_user_ns(user_ns);
// Box-allocate and copy.
let new = unsafe {
let mut c: Box<Cred> = Box::new(core::mem::zeroed());
*c = Cred {
usage: AtomicUsize::new(1),
uid: (*cur).uid,
gid: (*cur).gid,
suid: (*cur).suid,
sgid: (*cur).sgid,
euid: (*cur).euid,
egid: (*cur).egid,
fsuid: (*cur).fsuid,
fsgid: (*cur).fsgid,
cap_inheritable: (*cur).cap_inheritable,
cap_permitted: (*cur).cap_permitted,
cap_effective: (*cur).cap_effective,
cap_bset: (*cur).cap_bset,
cap_ambient: (*cur).cap_ambient,
securebits: (*cur).securebits,
group_info: (*cur).group_info,
user_ns: user_ns as *const core::ffi::c_void,
};
Box::into_raw(c)
};
Some(new)
}
/// Commit `new` as the calling task's credential, releasing the old one.
///
/// Linux semantics: both `cred` and `real_cred` are updated to `new`
/// (separating real from effective is reserved for `setresuid` / file
/// capabilities — neither implemented in M27).
///
/// # Safety
/// `new` must be a unique cred pointer with `usage >= 1`.
pub fn commit_creds(new: *mut Cred) {
let task = unsafe { crate::kernel::sched::get_current() };
if task.is_null() {
// Pre-init: just drop the new cred — there's no task to update.
unsafe { Cred::put(new) };
return;
}
let old = unsafe { (*task).cred };
let old_real = unsafe { (*task).m27.real_cred };
// Bump refcount once more so cred and real_cred each own a reference.
unsafe { (*new).usage.fetch_add(1, Ordering::Relaxed) };
unsafe {
(*task).cred = new as *const Cred;
(*task).m27.real_cred = new as *const Cred;
}
// M34: replace with rcu_assign_pointer + synchronize_rcu before the puts.
unsafe {
Cred::put(old);
if !old_real.is_null() && !core::ptr::eq(old_real, old) {
Cred::put(old_real);
}
}
}
/// Atomically swap in `new` and return the previous cred so it can be
/// restored later via `revert_creds`.
///
/// Mirrors Linux `override_creds()` — used by callers that need to elevate
/// or de-privilege themselves for a single operation.
pub fn override_creds(new: *const Cred) -> *const Cred {
let task = unsafe { crate::kernel::sched::get_current() };
if task.is_null() {
return core::ptr::null();
}
let old = unsafe { (*task).cred };
if !new.is_null() {
unsafe { (*new).usage.fetch_add(1, Ordering::Relaxed) };
}
unsafe { (*task).cred = new };
old
}
/// Restore a cred previously saved by `override_creds`.
pub fn revert_creds(old: *const Cred) {
let task = unsafe { crate::kernel::sched::get_current() };
if task.is_null() {
return;
}
let cur = unsafe { (*task).cred };
unsafe { (*task).cred = old };
unsafe { Cred::put(cur) };
}
// ── copy_creds (called by copy_process) ──────────────────────────────────────
/// Initialise `child.cred` and `child.real_cred` from the parent.
///
/// Linux `copy_creds(p, clone_flags)` from `kernel/cred.c`:
/// - With `CLONE_THREAD`: the child shares the parent's cred (no copy).
/// - Without `CLONE_THREAD`: a fresh COW copy is allocated.
/// - With `CLONE_NEWUSER`: the fresh cred owns a newly-created user
/// namespace and receives the capabilities Linux grants in that namespace.
///
/// # Safety
/// `child` and `parent` must be valid TaskStruct pointers.
pub unsafe fn copy_creds(
child: *mut crate::kernel::task::TaskStruct,
parent: *mut crate::kernel::task::TaskStruct,
clone_flags: u64,
) -> Result<(), i32> {
use crate::kernel::clone::{CLONE_NEWUSER, CLONE_THREAD};
let parent_cred = unsafe { (*parent).cred };
let cred_to_use: *const Cred = if parent_cred.is_null() {
&raw const INIT_CRED
} else {
parent_cred
};
if clone_flags & CLONE_THREAD != 0 {
// Share — bump refcount twice (once for cred, once for real_cred).
unsafe {
(*cred_to_use).usage.fetch_add(2, Ordering::Relaxed);
(*child).cred = cred_to_use;
(*child).m27.real_cred = cred_to_use;
}
} else {
// COW — allocate a private copy. Linux's copy_creds() performs the
// CLONE_NEWUSER transition here, before copy_namespaces().
let parent_user_ns = if unsafe { (*cred_to_use).user_ns.is_null() } {
core::ptr::addr_of!(crate::kernel::user_namespace::INIT_USER_NS)
} else {
unsafe { (*cred_to_use).user_ns as *const crate::kernel::user_namespace::UserNamespace }
};
let user_ns = if clone_flags & CLONE_NEWUSER != 0 {
crate::kernel::user_namespace::create_user_ns(parent_user_ns)?
} else {
crate::kernel::user_namespace::get_user_ns(parent_user_ns);
parent_user_ns as *mut crate::kernel::user_namespace::UserNamespace
};
let new = unsafe {
let mut c: Box<Cred> = Box::new(core::mem::zeroed());
*c = Cred {
usage: AtomicUsize::new(2), // cred + real_cred
uid: (*cred_to_use).uid,
gid: (*cred_to_use).gid,
suid: (*cred_to_use).suid,
sgid: (*cred_to_use).sgid,
euid: (*cred_to_use).euid,
egid: (*cred_to_use).egid,
fsuid: (*cred_to_use).fsuid,
fsgid: (*cred_to_use).fsgid,
cap_inheritable: if clone_flags & CLONE_NEWUSER != 0 {
KernelCapT::empty()
} else {
(*cred_to_use).cap_inheritable
},
cap_permitted: if clone_flags & CLONE_NEWUSER != 0 {
KernelCapT::full()
} else {
(*cred_to_use).cap_permitted
},
cap_effective: if clone_flags & CLONE_NEWUSER != 0 {
KernelCapT::full()
} else {
(*cred_to_use).cap_effective
},
cap_bset: if clone_flags & CLONE_NEWUSER != 0 {
KernelCapT::full()
} else {
(*cred_to_use).cap_bset
},
cap_ambient: if clone_flags & CLONE_NEWUSER != 0 {
KernelCapT::empty()
} else {
(*cred_to_use).cap_ambient
},
securebits: if clone_flags & CLONE_NEWUSER != 0 {
0
} else {
(*cred_to_use).securebits
},
group_info: (*cred_to_use).group_info,
user_ns: user_ns as *const core::ffi::c_void,
};
Box::into_raw(c)
};
unsafe {
(*child).cred = new as *const Cred;
(*child).m27.real_cred = new as *const Cred;
}
}
Ok(())
}
// ── Tests ────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use crate::kernel::capability::CAP_SYS_ADMIN;
use crate::kernel::clone::CLONE_NEWUSER;
use crate::kernel::task::TaskStruct;
#[test]
fn init_cred_is_root_with_full_caps() {
assert_eq!(INIT_CRED.uid, KUid(0));
assert_eq!(INIT_CRED.gid, KGid(0));
assert!(INIT_CRED.cap_effective.raised(CAP_SYS_ADMIN));
assert!(INIT_CRED.cap_permitted.raised(CAP_SYS_ADMIN));
assert!(!INIT_CRED.cap_inheritable.raised(CAP_SYS_ADMIN));
}
/// test-origin: linux:vendor/linux/kernel/cred.c:copy_creds
///
/// Linux creates the child user namespace in `copy_creds()` and grants
/// that namespace a fresh root capability set. Firefox's content sandbox
/// relies on the legacy `clone(CLONE_NEWUSER, ...)` path.
#[test]
fn copy_creds_clone_newuser_creates_scoped_root_cred() {
let mut parent = unsafe { core::mem::zeroed::<TaskStruct>() };
let mut child = unsafe { core::mem::zeroed::<TaskStruct>() };
parent.cred = &raw const INIT_CRED;
unsafe { copy_creds(&mut child, &mut parent, CLONE_NEWUSER) }
.expect("CLONE_NEWUSER should create the child credential");
let child_cred = child.cred;
assert!(!child_cred.is_null());
assert_ne!(child_cred, &raw const INIT_CRED);
unsafe {
assert_ne!((*child_cred).user_ns, INIT_CRED.user_ns);
assert!((*child_cred).cap_effective.raised(CAP_SYS_ADMIN));
assert!((*child_cred).cap_permitted.raised(CAP_SYS_ADMIN));
Cred::put(child_cred);
Cred::put(child.m27.real_cred);
}
}
#[test]
fn invalid_uid_is_uint_max() {
assert_eq!(INVALID_UID.0, u32::MAX);
assert_eq!(INVALID_GID.0, u32::MAX);
}
#[test]
fn group_info_default_is_empty() {
let gi = GroupInfo::default();
assert_eq!(gi.ngroups, 0);
assert_eq!(gi.usage, 1);
}
}