Keystore 2.0: Add run_as to keystore2_test_utils
The run_as function allows a test with sufficient privileges to run a
closure as different identity given by a tuple of UID, GID, and SELinux
context. This is infrastructure in preparation for the keystore2 vts
test.
Test: keystore2_test_utils_test
Bug: 182508302
Change-Id: Ic1923028e5bc4ca4b1112e34669d52687450fd14
diff --git a/keystore2/selinux/src/lib.rs b/keystore2/selinux/src/lib.rs
index cf6dfd3..902e9a4 100644
--- a/keystore2/selinux/src/lib.rs
+++ b/keystore2/selinux/src/lib.rs
@@ -321,6 +321,18 @@
}
}
+/// Safe wrapper around setcon.
+pub fn setcon(target: &CStr) -> std::io::Result<()> {
+ // SAFETY: `setcon` takes a const char* and only performs read accesses on it
+ // using strdup and strcmp. `setcon` does not retain a pointer to `target`
+ // and `target` outlives the call to `setcon`.
+ if unsafe { selinux::setcon(target.as_ptr()) } != 0 {
+ Err(std::io::Error::last_os_error())
+ } else {
+ Ok(())
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;