Struct linux_keyutils::Key

source ·
pub struct Key(_);
Expand description

A key corresponding to a specific real ID.

Generally you will either create or obtain a Key via the KeyRing interface. Since keys must be linked with a keyring to be valid.

For example:

use linux_keyutils::{Key, KeyRing, KeyRingIdentifier, KeyError};
use zeroize::Zeroize;

// Name of my program's key
const KEYNAME: &'static str = "my-process-key";

// Locate the key in the process keyring and update the secret
fn update_secret<T: AsRef<[u8]> + Zeroize>(data: &T) -> Result<(), KeyError> {
    // Get the current process keyring
    let ring = KeyRing::from_special_id(KeyRingIdentifier::Process, false)?;

    // Locate the key we previously created
    let key = ring.search(KEYNAME)?;

    // Change the data it contains
    key.update(data)?;
    Ok(())
}

Implementations§

Initialize a new Key object from the provided ID

Examples found in repository?
src/keyring.rs (line 94)
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
    pub fn add_key<D: AsRef<str> + ?Sized, S: AsRef<[u8]> + ?Sized>(
        &self,
        description: &D,
        secret: &S,
    ) -> Result<Key, KeyError> {
        let id = ffi::add_key(
            KeyType::User,
            self.id.as_raw_id() as libc::c_ulong,
            description.as_ref(),
            Some(secret.as_ref()),
        )?;
        Ok(Key::from_id(id))
    }

    /// Search for a key in the keyring tree, starting with this keyring as the head,
    /// returning its ID.
    ///
    /// The search is performed breadth-first and recursively.
    ///
    /// The source keyring must grant search permission to the caller. When
    /// performing the recursive search, only keyrings that grant the caller search
    /// permission will be searched. Only keys with for which the caller has
    /// search permission can be found.
    ///
    /// If the key is found, its ID is returned as the function result.
    pub fn search<D: AsRef<str> + ?Sized>(&self, description: &D) -> Result<Key, KeyError> {
        // The provided description must be properly null terminated for the kernel
        let description =
            CString::new(description.as_ref()).or(Err(KeyError::InvalidDescription))?;

        // Perform the raw syscall and validate that the result is a valid ID
        let id: KeySerialId = ffi::keyctl!(
            KeyCtlOperation::Search,
            self.id.as_raw_id() as libc::c_ulong,
            Into::<&'static CStr>::into(KeyType::User).as_ptr() as _,
            description.as_ptr() as _,
            0
        )?
        .try_into()
        .or(Err(KeyError::InvalidIdentifier))?;

        // Construct a key object from the ID
        Ok(Key::from_id(id))
    }
More examples
Hide additional examples
src/links.rs (line 68)
64
65
66
67
68
69
70
71
72
    pub(crate) fn from_id(id: KeySerialId) -> Result<Self, KeyError> {
        let metadata = Metadata::from_id(id)?;
        let node = match metadata.get_type() {
            KeyType::KeyRing => Self::KeyRing(KeyRing::from_id(id)),
            KeyType::User => Self::Key(Key::from_id(id)),
            _ => return Err(KeyError::OperationNotSupported),
        };
        Ok(node)
    }

Obtain a copy of the ID of this key

Examples found in repository?
src/keyring.rs (line 176)
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    pub fn link_key(&self, key: Key) -> Result<(), KeyError> {
        _ = ffi::keyctl!(
            KeyCtlOperation::Link,
            key.get_id().as_raw_id() as _,
            self.id.as_raw_id() as libc::c_ulong
        )?;
        Ok(())
    }

    /// Unlink a key from this keyring.
    ///
    /// If the key is not currently linked into the keyring, an error results. If the
    /// last link to a key is removed, then that key will be scheduled for destruction.
    ///
    /// The caller must have write permission on the keyring from which the key is being
    /// removed.
    pub fn unlink_key(&self, key: Key) -> Result<(), KeyError> {
        _ = ffi::keyctl!(
            KeyCtlOperation::Unlink,
            key.get_id().as_raw_id() as _,
            self.id.as_raw_id() as libc::c_ulong
        )?;
        Ok(())
    }

Obtain information describing the attributes of this key.

The key must grant the caller view permission.

Examples found in repository?
src/key.rs (line 38)
37
38
39
40
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let info = self.metadata().map_err(|_| fmt::Error::default())?;
        write!(f, "Key({:?})", info)
    }

Read the payload data of a key into a provided mutable slice.

The returned usize is the number of bytes read into the slice.

The key must either grant the caller read permission, or grant the caller search permission when searched for from the process keyrings (i.e., the key is possessed).

Read the payload data of a key, returning a newly allocated vector.

The key must either grant the caller read permission, or grant the caller search permission when searched for from the process keyrings (i.e., the key is possessed).

Update a key’s data payload.

The caller must have write permission on the key specified and the key type must support updating.

A negatively instantiated key (see the description of Key::reject) can be positively instantiated with this operation.

Change the permissions of the key with the ID provided

If the caller doesn’t have the CAP_SYS_ADMIN capability, it can change permissions only only for the keys it owns. (More precisely: the caller’s filesystem UID must match the UID of the key.)

Change the ownership (user and group ID) of a key.

For the UID to be changed, or for the GID to be changed to a group the caller is not a member of, the caller must have the CAP_SYS_ADMIN capability (see capabilities(7)).

If the UID is to be changed, the new user must have sufficient quota to accept the key. The quota deduction will be removed from the old user to the new user should the UID be changed.

Set a timeout on a key.

Specifying the timeout value as 0 clears any existing timeout on the key.

The /proc/keys file displays the remaining time until each key will expire. (This is the only method of discovering the timeout on a key.)

The caller must either have the setattr permission on the key or hold an instantiation authorization token for the key.

The key and any links to the key will be automatically garbage collected after the timeout expires. Subsequent attempts to access the key will then fail with the error EKEYEXPIRED.

This operation cannot be used to set timeouts on revoked, expired, or negatively instantiated keys.

Revoke this key. Similar to Key::reject just without the timeout.

The key is scheduled for garbage collection; it will no longer be findable, and will be unavailable for further operations. Further attempts to use the key will fail with the error EKEYREVOKED.

The caller must have write or setattr permission on the key.

Mark a key as negatively instantiated and set an expiration timer on the key.

This will prevent others from retrieving the key in further searches. And they will receive a EKEYREJECTED error when performing the search.

Similar to Key::revoke but with a timeout.

Mark a key as invalid.

To invalidate a key, the caller must have search permission on the key.

This operation marks the key as invalid and schedules immediate garbage collection. The garbage collector removes the invali‐ dated key from all keyrings and deletes the key when its refer‐ ence count reaches zero. After this operation, the key will be ignored by all searches, even if it is not yet deleted.

Keys that are marked invalid become invisible to normal key oper‐ ations immediately, though they are still visible in /proc/keys (marked with an ‘i’ flag) until they are actually removed.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.