Skip to content

Commit

Permalink
feat(landlock): introduce landlock
Browse files Browse the repository at this point in the history
Enabled by default on Linux. Managed by the class UhyveLandlockWrapper,
Landlock is enforced after all paths that it requires to function
are enumerated in UhyveVm::new, right before the kernel is loaded
in UhyveVm::load_kernel. Some tests were modified accordingly, as
UhyveVm objects can't be reused.
  • Loading branch information
n0toose committed Jan 10, 2025
1 parent da4b63e commit c045ed7
Show file tree
Hide file tree
Showing 11 changed files with 318 additions and 80 deletions.
32 changes: 32 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ hermit-entry = { version = "0.10", features = ["loader"] }
libc = "0.2"
log = "0.4"
mac_address = "1.1"
thiserror = "2.0"
time = "0.3"
tun-tap = { version = "0.1.3", default-features = false }
uhyve-interface = { version = "0.1.1", path = "uhyve-interface", features = ["std"] }
Expand All @@ -65,11 +64,13 @@ vm-fdt = "0.3"
tempfile = "3.15.0"
uuid = { version = "1.11.0", features = ["fast-rng", "v4"]}
clean-path = "0.2.1"
thiserror = "2.0.9"

[target.'cfg(target_os = "linux")'.dependencies]
kvm-bindings = "0.10"
kvm-ioctls = "0.19"
vmm-sys-util = "0.12"
landlock = "0.4.1"

[target.'cfg(target_os = "macos")'.dependencies]
burst = "0.0"
Expand Down
1 change: 1 addition & 0 deletions src/bin/uhyve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ fn run_uhyve() -> i32 {
println!("{stats}");
}
}

res.code
}

Expand Down
75 changes: 9 additions & 66 deletions src/isolation/filemap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@ use std::{
collections::HashMap,
ffi::{CString, OsString},
fs::canonicalize,
io::ErrorKind,
os::unix::ffi::OsStrExt,
path::{absolute, PathBuf},
path::PathBuf,
};

use clean_path::clean;
use tempfile::TempDir;
use uuid::Uuid;

use crate::isolation::tempdir::create_temp_dir;
use crate::isolation::{split_guest_and_host_path, tempdir::create_temp_dir};

/// Wrapper around a `HashMap` to map guest paths to arbitrary host paths.
#[derive(Debug)]
Expand All @@ -29,32 +28,13 @@ impl UhyveFileMap {
files: mappings
.iter()
.map(String::as_str)
.map(Self::split_guest_and_host_path)
.map(split_guest_and_host_path)
.map(Result::unwrap)
.collect(),
tempdir: create_temp_dir(),
}
}

/// Separates a string of the format "./host_dir/host_path.txt:guest_path.txt"
/// into a guest_path (String) and host_path (OsString) respectively.
///
/// * `mapping` - A mapping of the format `./host_path.txt:guest.txt`.
fn split_guest_and_host_path(mapping: &str) -> Result<(String, OsString), ErrorKind> {
let mut mappingiter: std::str::Split<'_, &str> = mapping.split(":");
let host_str = mappingiter.next().ok_or(ErrorKind::InvalidInput)?;
let guest_str = mappingiter.next().ok_or(ErrorKind::InvalidInput)?;

// TODO: Replace clean-path in favor of Path::normalize_lexically, which has not
// been implemented yet. See: https://github.com/rust-lang/libs-team/issues/396
let host_path = canonicalize(host_str)
.map_or_else(|_| clean(absolute(host_str).unwrap()), clean)
.into();
let guest_path: String = clean(guest_str).display().to_string();

Ok((guest_path, host_path))
}

/// Returns the host_path on the host filesystem given a requested guest_path, if it exists.
///
/// * `guest_path` - The guest path that is to be looked up in the map.
Expand Down Expand Up @@ -88,7 +68,6 @@ impl UhyveFileMap {
let guest_path_remainder = requested_guest_pathbuf
.strip_prefix(searched_parent_guest)
.unwrap();

host_path.push(guest_path_remainder);

// Handles symbolic links.
Expand All @@ -103,6 +82,12 @@ impl UhyveFileMap {
}
}

/// Returns the path to the temporary directory.
#[cfg(target_os = "linux")]
pub fn get_temp_dir(&self) -> Option<&str> {
self.tempdir.path().to_str()
}

/// Inserts an opened temporary file into the file map. Returns a CString so that
/// the file can be directly used by [crate::hypercall::open].
///
Expand All @@ -123,48 +108,6 @@ impl UhyveFileMap {
mod tests {
use super::*;

#[test]
fn test_split_guest_and_host_path() {
let host_guest_strings = [
"./host_string.txt:guest_string.txt",
"/home/user/host_string.txt:guest_string.md.txt",
"host_string.txt:this_does_exist.txt:should_not_exist.txt",
"host_string.txt:test/..//guest_string.txt",
];

// We will use `host_string.txt` for all tests checking canonicalization.
let mut fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
fixture_path.push("host_string.txt");

// Mind the inverted order.
let results = [
(
String::from("guest_string.txt"),
fixture_path.clone().into(),
),
(
String::from("guest_string.md.txt"),
OsString::from("/home/user/host_string.txt"),
),
(
String::from("this_does_exist.txt"),
fixture_path.clone().into(),
),
(String::from("guest_string.txt"), fixture_path.into()),
];

for (i, host_and_guest_string) in host_guest_strings
.into_iter()
.map(UhyveFileMap::split_guest_and_host_path)
.enumerate()
{
assert_eq!(
host_and_guest_string.expect("Result is an error!"),
results[i]
);
}
}

#[test]
fn test_uhyvefilemap() {
// Our files are in `$CARGO_MANIFEST_DIR/data/fixtures/fs`.
Expand Down
120 changes: 120 additions & 0 deletions src/isolation/landlock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
use std::{ffi::OsString, path::PathBuf, vec::Vec};

use landlock::{
Access, AccessFs, PathBeneath, PathFd, PathFdError, RestrictionStatus, Ruleset, RulesetAttr,
RulesetCreatedAttr, RulesetError, ABI,
};
use thiserror::Error;

use crate::isolation::split_guest_and_host_path;

/// Contains types of errors that may occur during Landlock's initialization.
#[derive(Debug, Error)]
pub enum RestrictError {
#[error(transparent)]
Ruleset(#[from] RulesetError),
#[error(transparent)]
AddRule(#[from] PathFdError),
}

/// Interface for Landlock crate.
#[derive(Clone, Debug)]
pub struct UhyveLandlockWrapper {
rw_paths: Vec<String>,
ro_paths: Vec<String>,
}

impl UhyveLandlockWrapper {
pub fn new(
mappings: &[String],
uhyve_rw_paths: &mut Vec<String>,
uhyve_ro_paths: &[String],
) -> UhyveLandlockWrapper {
#[cfg(not(target_os = "linux"))]
compile_error!("Landlock is only available on Linux.");

// TODO: Check whether host OS (Linux, of course) actually supports Landlock.
// TODO: Introduce parameter that lets the user manually disable Landlock.
// TODO: Reduce code repetition (wrt. `crate::isolation::filemap`).
// TODO: What to do with files that don't exist yet?
let mut rw_paths: Vec<String> = mappings
.iter()
.map(String::as_str)
.map(split_guest_and_host_path)
.map(Result::unwrap)
.map(|(guest_path, host_path)| (guest_path, host_path).1)
.map(Self::get_parent_directory)
.collect();
rw_paths.append(uhyve_rw_paths);

UhyveLandlockWrapper {
rw_paths,
ro_paths: uhyve_ro_paths.to_vec(),
}
}

pub fn apply_landlock_restrictions(&self) {
{
let _status = match Self::enforce_landlock(self) {
Ok(status) => status,
Err(error) => panic!("Unable to initialize Landlock: {error:?}"),
};
}
}

/// If the file does not exist, we add the parent directory instead. This might have practical
/// security implications, however, combined with the other security measures implemented into
/// Uhyve, this should be fine.
///
/// TODO: Inform the user in the docs.
/// TODO: Make the amount of iterations configurable.
pub fn get_parent_directory(host_path: OsString) -> String {
let iterations = 2;
let mut host_pathbuf: PathBuf = host_path.into();
for _i in 0..iterations {
if !host_pathbuf.exists() {
warn!("Mapped file {:#?} not found. Popping...", host_pathbuf);
host_pathbuf.pop();
continue;
}
debug!("Adding {:#?} to Landlock", host_pathbuf);
return host_pathbuf.to_str().unwrap().to_owned();
}
panic!(
"The mapped file's parent directory wasn't found within {} iteration(s).",
iterations
);
}

/// Initializes Landlock by providing R/W-access to user-defined and
/// Uhyve-defined paths.
pub fn enforce_landlock(&self) -> Result<RestrictionStatus, RestrictError> {
// This should be incremented regularly.
let abi = ABI::V5;
// Used for explicitly whitelisted files (read & write).
let access_all: landlock::BitFlags<AccessFs, u64> = AccessFs::from_all(abi);
// Used for the kernel itself, as well as "system directories" that we only read from.
let access_read: landlock::BitFlags<AccessFs, u64> = AccessFs::from_read(abi);

Ok(Ruleset::default()
.handle_access(access_all)?
.create()?
.add_rules(
self.rw_paths
.as_slice()
.iter()
.map::<Result<_, RestrictError>, _>(|p| {
Ok(PathBeneath::new(PathFd::new(p)?, access_all))
}),
)?
.add_rules(
self.ro_paths
.as_slice()
.iter()
.map::<Result<_, RestrictError>, _>(|p| {
Ok(PathBeneath::new(PathFd::new(p)?, access_read))
}),
)?
.restrict_self()?)
}
}
69 changes: 69 additions & 0 deletions src/isolation/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,71 @@
pub mod filemap;
#[cfg(target_os = "linux")]
pub mod landlock;
pub mod tempdir;

use std::{ffi::OsString, fs::canonicalize, io::ErrorKind, path::absolute};

use clean_path::clean;

/// Separates a string of the format "./host_dir/host_path.txt:guest_path.txt"
/// into a guest_path (String) and host_path (OsString) respectively.
///
/// * `mapping` - A mapping of the format `./host_path.txt:guest.txt`.
fn split_guest_and_host_path(mapping: &str) -> Result<(String, OsString), ErrorKind> {
let mut mappingiter: std::str::Split<'_, &str> = mapping.split(":");
let host_str = mappingiter.next().ok_or(ErrorKind::InvalidInput)?;
let guest_str = mappingiter.next().ok_or(ErrorKind::InvalidInput)?;

// TODO: Replace clean-path in favor of Path::normalize_lexically, which has not
// been implemented yet. See: https://github.com/rust-lang/libs-team/issues/396
let host_path = canonicalize(host_str)
.map_or_else(|_| clean(absolute(host_str).unwrap()), clean)
.into();
let guest_path: String = clean(guest_str).display().to_string();

Ok((guest_path, host_path))
}

#[test]
fn test_split_guest_and_host_path() {
use std::path::PathBuf;

let host_guest_strings = [
"./host_string.txt:guest_string.txt",
"/home/user/host_string.txt:guest_string.md.txt",
"host_string.txt:this_does_exist.txt:should_not_exist.txt",
"host_string.txt:test/..//guest_string.txt",
];

// We will use `host_string.txt` for all tests checking canonicalization.
let mut fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
fixture_path.push("host_string.txt");

// Mind the inverted order.
let results = [
(
String::from("guest_string.txt"),
fixture_path.clone().into(),
),
(
String::from("guest_string.md.txt"),
OsString::from("/home/user/host_string.txt"),
),
(
String::from("this_does_exist.txt"),
fixture_path.clone().into(),
),
(String::from("guest_string.txt"), fixture_path.into()),
];

for (i, host_and_guest_string) in host_guest_strings
.into_iter()
.map(split_guest_and_host_path)
.enumerate()
{
assert_eq!(
host_and_guest_string.expect("Result is an error!"),
results[i]
);
}
}
Loading

0 comments on commit c045ed7

Please sign in to comment.