|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | + |
| 3 | +//! Credentials management. |
| 4 | +//! |
| 5 | +//! C header: [`include/linux/cred.h`](../../../../include/linux/cred.h) |
| 6 | +//! |
| 7 | +//! Reference: <https://www.kernel.org/doc/html/latest/security/credentials.html> |
| 8 | +
|
| 9 | +use crate::bindings; |
| 10 | +use core::{marker::PhantomData, mem::ManuallyDrop, ops::Deref}; |
| 11 | + |
| 12 | +/// Wraps the kernel's `struct cred`. |
| 13 | +/// |
| 14 | +/// # Invariants |
| 15 | +/// |
| 16 | +/// The pointer `Credential::ptr` is non-null and valid. Its reference count is also non-zero. |
| 17 | +pub struct Credential { |
| 18 | + pub(crate) ptr: *const bindings::cred, |
| 19 | +} |
| 20 | + |
| 21 | +impl Clone for Credential { |
| 22 | + fn clone(&self) -> Self { |
| 23 | + // SAFETY: The type invariants guarantee that `self.ptr` has a non-zero reference count. |
| 24 | + let ptr = unsafe { bindings::get_cred(self.ptr) }; |
| 25 | + |
| 26 | + // INVARIANT: We incremented the reference count to account for the new `Credential` being |
| 27 | + // created. |
| 28 | + Self { ptr } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl Drop for Credential { |
| 33 | + fn drop(&mut self) { |
| 34 | + // SAFETY: The type invariants guarantee that `ptr` has a non-zero reference count. |
| 35 | + unsafe { bindings::put_cred(self.ptr) }; |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/// A wrapper for [`Credential`] that doesn't automatically decrement the refcount when dropped. |
| 40 | +/// |
| 41 | +/// We need the wrapper because [`ManuallyDrop`] alone would allow callers to call |
| 42 | +/// [`ManuallyDrop::into_inner`]. This would allow an unsafe sequence to be triggered without |
| 43 | +/// `unsafe` blocks because it would trigger an unbalanced call to `put_cred`. |
| 44 | +/// |
| 45 | +/// # Invariants |
| 46 | +/// |
| 47 | +/// The wrapped [`Credential`] remains valid for the lifetime of the object. |
| 48 | +pub struct CredentialRef<'a> { |
| 49 | + cred: ManuallyDrop<Credential>, |
| 50 | + _p: PhantomData<&'a ()>, |
| 51 | +} |
| 52 | + |
| 53 | +impl CredentialRef<'_> { |
| 54 | + /// Constructs a new [`struct cred`] wrapper that doesn't change its reference count. |
| 55 | + /// |
| 56 | + /// # Safety |
| 57 | + /// |
| 58 | + /// The pointer `ptr` must be non-null and valid for the lifetime of the object. |
| 59 | + pub(crate) unsafe fn from_ptr(ptr: *const bindings::cred) -> Self { |
| 60 | + Self { |
| 61 | + cred: ManuallyDrop::new(Credential { ptr }), |
| 62 | + _p: PhantomData, |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl Deref for CredentialRef<'_> { |
| 68 | + type Target = Credential; |
| 69 | + |
| 70 | + fn deref(&self) -> &Self::Target { |
| 71 | + self.cred.deref() |
| 72 | + } |
| 73 | +} |
0 commit comments