Struct linux_keyutils::KeySerialId
source · #[repr(transparent)]pub struct KeySerialId(pub i32);
Expand description
Primary kernel identifier for a key or keyring.
Tuple Fields§
§0: i32
Implementations§
source§impl KeySerialId
impl KeySerialId
sourcepub fn new(raw: i32) -> Self
pub fn new(raw: i32) -> Self
Construct from a raw i32
Examples found in repository?
src/ffi/functions.rs (lines 54-56)
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
pub(crate) fn add_key(
ktype: KeyType,
keyring: libc::c_ulong,
description: &str,
payload: Option<&[u8]>,
) -> Result<KeySerialId, KeyError> {
// Perform conversion into a c string
let description = CString::new(description).or(Err(KeyError::InvalidDescription))?;
// When creating keyrings the payload will be NULL
let (payload, plen) = match payload {
Some(p) => (p.as_ptr(), p.len()),
None => (core::ptr::null(), 0),
};
// Perform the actual system call
let res = unsafe {
libc::syscall(
libc::SYS_add_key,
Into::<&'static CStr>::into(ktype).as_ptr(),
description.as_ptr(),
payload,
plen as libc::size_t,
keyring as u32,
)
};
// Return the underlying error
if res < 0 {
return Err(KeyError::from_errno());
}
// Otherwise return the ID
Ok(KeySerialId::new(
res.try_into().or(Err(KeyError::InvalidIdentifier))?,
))
}
sourcepub fn as_raw_id(&self) -> i32
pub fn as_raw_id(&self) -> i32
Allow conversion into the raw i32 for FFI
Examples found in repository?
src/keyring.rs (line 90)
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
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))
}
/// Obtain a list of the keys/keyrings linked to this keyring.
///
/// This method allocates, but you can provide a maximum number of entries
/// to read. Each returned entry is 4 bytes.
///
/// The keyring must either grant the caller read permission, or grant
/// the caller search permission.
pub fn get_links(&self, max: usize) -> Result<Links, KeyError> {
// Allocate the requested capacity
let mut buffer = Vec::<KeySerialId>::with_capacity(max);
// Perform the read
let len = ffi::keyctl!(
KeyCtlOperation::Read,
self.id.as_raw_id() as libc::c_ulong,
buffer.as_mut_ptr() as _,
buffer.capacity() as _
)? as usize;
// Set the size of the results
unsafe {
buffer.set_len(len / core::mem::size_of::<KeySerialId>());
}
// Remap the results to complete keys
Ok(buffer
.iter()
.filter_map(|&id| LinkNode::from_id(id).ok())
.collect())
}
/// Create a link from this keyring to a key.
///
/// If a key with the same type and description is already linked in the keyring,
/// then that key is displaced from the keyring.
///
/// Before creating the link, the kernel checks the nesting of the keyrings
/// and returns appropriate errors if the link would produce a cycle or if the
/// nesting of keyrings would be too deep (The limit on the nesting of keyrings is
/// determined by the kernel constant KEYRING_SEARCH_MAX_DEPTH, defined with the
/// value 6, and is necessary to prevent overflows on the kernel stack when
/// recursively searching keyrings).
///
/// The caller must have link permission on the key being added and write
/// permission on the keyring.
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(())
}
/// Clear the contents of (i.e., unlink all keys from) this keyring.
///
/// The caller must have write permission on the keyring.
pub fn clear(&self) -> Result<(), KeyError> {
_ = ffi::keyctl!(KeyCtlOperation::Clear, self.id.as_raw_id() as libc::c_ulong)?;
Ok(())
}
More examples
src/key.rs (line 72)
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
pub fn read<T: AsMut<[u8]>>(&self, buffer: &mut T) -> Result<usize, KeyError> {
// TODO: alternate key types? Currenlty we don't support KeyType::BigKey
let len = ffi::keyctl!(
KeyCtlOperation::Read,
self.0.as_raw_id() as libc::c_ulong,
buffer.as_mut().as_mut_ptr() as _,
buffer.as_mut().len() as _
)? as usize;
Ok(len)
}
/// 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).
pub fn read_to_vec(&self) -> Result<Vec<u8>, KeyError> {
// Ensure we have enough room to write up to the maximum for a UserKey
let mut buffer = Vec::with_capacity(65536);
// Obtain the key
let len = ffi::keyctl!(
KeyCtlOperation::Read,
self.0.as_raw_id() as libc::c_ulong,
buffer.as_mut_ptr() as _,
buffer.capacity() as _
)? as usize;
// Update length
unsafe {
buffer.set_len(len);
}
Ok(buffer)
}
/// 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.
pub fn update<T: AsRef<[u8]>>(&self, update: &T) -> Result<(), KeyError> {
_ = ffi::keyctl!(
KeyCtlOperation::Update,
self.0.as_raw_id() as libc::c_ulong,
update.as_ref().as_ptr() as _,
update.as_ref().len() as _
)?;
Ok(())
}
/// 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.)
pub fn set_perms(&self, perm: KeyPermissions) -> Result<(), KeyError> {
_ = ffi::keyctl!(
KeyCtlOperation::SetPerm,
self.0.as_raw_id() as libc::c_ulong,
perm.bits() as _
)?;
Ok(())
}
/// 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.
pub fn chown(&self, uid: Option<u32>, gid: Option<u32>) -> Result<(), KeyError> {
let uid_opt = uid.unwrap_or(u32::MAX);
let gid_opt = gid.unwrap_or(u32::MAX);
_ = ffi::keyctl!(
KeyCtlOperation::Chown,
self.0.as_raw_id() as libc::c_ulong,
uid_opt as _,
gid_opt as _
)?;
Ok(())
}
/// 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.
pub fn set_timeout(&self, seconds: usize) -> Result<(), KeyError> {
_ = ffi::keyctl!(
KeyCtlOperation::SetTimeout,
self.0.as_raw_id() as libc::c_ulong,
seconds as _
)?;
Ok(())
}
/// 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.
pub fn revoke(&self) -> Result<(), KeyError> {
_ = ffi::keyctl!(KeyCtlOperation::Revoke, self.0.as_raw_id() as libc::c_ulong)?;
Ok(())
}
/// 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.
pub fn reject(&self, seconds: usize) -> Result<(), KeyError> {
_ = ffi::keyctl!(
KeyCtlOperation::Reject,
self.0.as_raw_id() as libc::c_ulong,
seconds as _,
libc::EKEYREJECTED as _
)?;
Ok(())
}
/// 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.
pub fn invalidate(&self) -> Result<(), KeyError> {
ffi::keyctl!(
KeyCtlOperation::Invalidate,
self.0.as_raw_id() as libc::c_ulong
)?;
Ok(())
}
src/metadata.rs (line 82)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
pub(crate) fn from_id(id: KeySerialId) -> Result<Self, KeyError> {
let mut result = alloc::vec![0u8; 512];
// Obtain the description from the kernel
let len = ffi::keyctl!(
KeyCtlOperation::Describe,
id.as_raw_id() as libc::c_ulong,
result.as_mut_ptr() as _,
result.len() as _
)? as usize;
// Construct the CStr first to remove the null terminator
let cs = CStr::from_bytes_with_nul(&result[..len]).or(Err(KeyError::InvalidDescription))?;
// Construct the string from the resulting data ensuring utf8 compat
let s = cs.to_str().or(Err(KeyError::InvalidDescription))?;
Self::from_str(s)
}
Trait Implementations§
source§impl Clone for KeySerialId
impl Clone for KeySerialId
source§fn clone(&self) -> KeySerialId
fn clone(&self) -> KeySerialId
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresource§impl Debug for KeySerialId
impl Debug for KeySerialId
source§impl From<KeySerialId> for i32
impl From<KeySerialId> for i32
Allow easy conversion from i32 to KeySerialId
source§fn from(id: KeySerialId) -> i32
fn from(id: KeySerialId) -> i32
Converts to this type from the input type.
source§impl PartialEq<KeySerialId> for KeySerialId
impl PartialEq<KeySerialId> for KeySerialId
source§fn eq(&self, other: &KeySerialId) -> bool
fn eq(&self, other: &KeySerialId) -> bool
This method tests for
self
and other
values to be equal, and is used
by ==
.source§impl TryFrom<u64> for KeySerialId
impl TryFrom<u64> for KeySerialId
Allow easy conversion from u64 to KeySerialId