hyperlight_host/sandbox/mod.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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 58 59 60 61 62 63 64 65 66 67 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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
/*
Copyright 2024 The Hyperlight Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/// Configuration needed to establish a sandbox.
pub mod config;
/// Functionality for reading, but not modifying host functions
mod host_funcs;
/// Functionality for dealing with `Sandbox`es that contain Hypervisors
pub(crate) mod hypervisor;
/// Functionality for dealing with initialized sandboxes that can
/// call 0 or more guest functions
pub mod initialized_multi_use;
/// Functionality for dealing with initialized sandboxes that can
/// call 0 or 1 guest functions, but no more
pub mod initialized_single_use;
/// A container to leak, store and manage outb handlers for in-process
/// executions. On non-in-process executions (e.g. windows without
/// in-process mode turned on, or linux), the same container is just
/// a no-op
#[cfg(inprocess)]
pub(crate) mod leaked_outb;
/// Functionality for dealing with memory access from the VM guest
/// executable
pub(crate) mod mem_access;
/// Functionality for interacting with a sandbox's internally-stored
/// `SandboxMemoryManager`
pub(crate) mod mem_mgr;
pub(crate) mod outb;
/// Options for configuring a sandbox
mod run_options;
/// Functionality for creating uninitialized sandboxes, manipulating them,
/// and converting them to initialized sandboxes.
pub mod uninitialized;
/// Functionality for properly converting `UninitailizedSandbox`es to
/// initialized `Sandbox`es.
pub(crate) mod uninitialized_evolve;
/// Metric definitions for Sandbox module.
pub(crate) mod metrics;
use std::collections::HashMap;
/// Re-export for `SandboxConfiguration` type
pub use config::SandboxConfiguration;
/// Re-export for the `MultiUseSandbox` type
pub use initialized_multi_use::MultiUseSandbox;
/// Re-export for `SingleUseSandbox` type
pub use initialized_single_use::SingleUseSandbox;
/// Re-export for `SandboxRunOptions` type
pub use run_options::SandboxRunOptions;
use tracing::{instrument, Span};
/// Re-export for `GuestBinary` type
pub use uninitialized::GuestBinary;
/// Re-export for `UninitializedSandbox` type
pub use uninitialized::UninitializedSandbox;
use self::mem_mgr::MemMgrWrapper;
use crate::func::HyperlightFunction;
use crate::hypervisor::hypervisor_handler::HypervisorHandler;
#[cfg(target_os = "windows")]
use crate::hypervisor::windows_hypervisor_platform;
use crate::mem::shared_mem::HostSharedMemory;
// In case its not obvious why there are separate is_supported_platform and is_hypervisor_present functions its because
// Hyperlight is designed to be able to run on a host that doesn't have a hypervisor.
// In that case, the sandbox will be in process, we plan on making this a dev only feature and fixing up Linux support
// so we should review the need for this function at that time.
/// Determine if this is a supported platform for Hyperlight
///
/// Returns a boolean indicating whether this is a supported platform.
#[instrument(skip_all, parent = Span::current())]
pub fn is_supported_platform() -> bool {
#[cfg(not(target_os = "linux"))]
#[cfg(not(target_os = "windows"))]
return false;
true
}
/// Alias for the type of extra allowed syscalls.
pub type ExtraAllowedSyscall = i64;
/// A `HashMap` to map function names to `HyperlightFunction`s and their extra allowed syscalls.
///
/// Note: you cannot add extra syscalls on Windows, but the field is still present to avoid a funky
/// conditional compilation setup. This isn't a big deal as this struct isn't public facing.
#[derive(Clone, Default)]
pub(super) struct FunctionsMap(
HashMap<String, (HyperlightFunction, Option<Vec<ExtraAllowedSyscall>>)>,
);
impl FunctionsMap {
/// Insert a new entry into the map
pub(super) fn insert(
&mut self,
key: String,
value: HyperlightFunction,
extra_syscalls: Option<Vec<ExtraAllowedSyscall>>,
) {
self.0.insert(key, (value, extra_syscalls));
}
/// Get the value associated with the given key, if it exists.
pub(super) fn get(
&self,
key: &str,
) -> Option<&(HyperlightFunction, Option<Vec<ExtraAllowedSyscall>>)> {
self.0.get(key)
}
/// Get the length of the map.
fn len(&self) -> usize {
self.0.len()
}
}
impl PartialEq for FunctionsMap {
#[instrument(skip_all, parent = Span::current(), level= "Trace")]
fn eq(&self, other: &Self) -> bool {
self.len() == other.len() && self.0.keys().all(|k| other.0.contains_key(k))
}
}
impl Eq for FunctionsMap {}
/// Determine whether a suitable hypervisor is available to run
/// this sandbox.
///
// Returns a boolean indicating whether a suitable hypervisor is present.
#[instrument(skip_all, parent = Span::current())]
pub fn is_hypervisor_present() -> bool {
hypervisor::get_available_hypervisor().is_some()
}
pub(crate) trait WrapperGetter {
#[allow(dead_code)]
fn get_mgr_wrapper(&self) -> &MemMgrWrapper<HostSharedMemory>;
fn get_mgr_wrapper_mut(&mut self) -> &mut MemMgrWrapper<HostSharedMemory>;
fn get_hv_handler(&self) -> &HypervisorHandler;
#[allow(dead_code)]
fn get_hv_handler_mut(&mut self) -> &mut HypervisorHandler;
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::thread;
use crossbeam_queue::ArrayQueue;
use hyperlight_testing::simple_guest_as_string;
#[cfg(target_os = "linux")]
use super::is_hypervisor_present;
#[cfg(mshv)]
use crate::hypervisor::hyperv_linux::test_cfg::TEST_CONFIG as HYPERV_TEST_CONFIG;
#[cfg(kvm)]
use crate::hypervisor::kvm::test_cfg::TEST_CONFIG as KVM_TEST_CONFIG;
use crate::sandbox::uninitialized::GuestBinary;
use crate::sandbox_state::sandbox::EvolvableSandbox;
use crate::sandbox_state::transition::Noop;
use crate::{new_error, MultiUseSandbox, UninitializedSandbox};
#[test]
// TODO: add support for testing on WHP
#[cfg(target_os = "linux")]
fn test_is_hypervisor_present() {
// TODO: Handle requiring a stable API
cfg_if::cfg_if! {
if #[cfg(all(kvm, mshv))] {
if KVM_TEST_CONFIG.kvm_should_be_present || HYPERV_TEST_CONFIG.hyperv_should_be_present {
assert!(is_hypervisor_present());
} else {
assert!(!is_hypervisor_present());
}
} else if #[cfg(kvm)] {
if KVM_TEST_CONFIG.kvm_should_be_present {
assert!(is_hypervisor_present());
} else {
assert!(!is_hypervisor_present());
}
} else if #[cfg(mshv)] {
if HYPERV_TEST_CONFIG.hyperv_should_be_present {
assert!(is_hypervisor_present());
} else {
assert!(!is_hypervisor_present());
}
} else {
assert!(!is_hypervisor_present());
}
}
}
#[test]
fn check_create_and_use_sandbox_on_different_threads() {
let unintializedsandbox_queue = Arc::new(ArrayQueue::<UninitializedSandbox>::new(10));
let sandbox_queue = Arc::new(ArrayQueue::<MultiUseSandbox>::new(10));
for i in 0..10 {
let simple_guest_path = simple_guest_as_string().expect("Guest Binary Missing");
let unintializedsandbox = UninitializedSandbox::new(
GuestBinary::FilePath(simple_guest_path),
None,
None,
None,
)
.unwrap_or_else(|_| panic!("Failed to create UninitializedSandbox {}", i));
unintializedsandbox_queue
.push(unintializedsandbox)
.unwrap_or_else(|_| panic!("Failed to push UninitializedSandbox {}", i));
}
let thread_handles = (0..10)
.map(|i| {
let uq = unintializedsandbox_queue.clone();
let sq = sandbox_queue.clone();
thread::spawn(move || {
let uninitialized_sandbox = uq.pop().unwrap_or_else(|| {
panic!("Failed to pop UninitializedSandbox thread {}", i)
});
let host_funcs = uninitialized_sandbox
.host_funcs
.try_lock()
.map_err(|_| new_error!("Error locking"));
assert!(host_funcs.is_ok());
host_funcs
.unwrap()
.host_print(format!(
"Printing from UninitializedSandbox on Thread {}\n",
i
))
.unwrap();
let sandbox = uninitialized_sandbox
.evolve(Noop::default())
.unwrap_or_else(|_| {
panic!("Failed to initialize UninitializedSandbox thread {}", i)
});
sq.push(sandbox).unwrap_or_else(|_| {
panic!("Failed to push UninitializedSandbox thread {}", i)
})
})
})
.collect::<Vec<_>>();
for handle in thread_handles {
handle.join().unwrap();
}
let thread_handles = (0..10)
.map(|i| {
let sq = sandbox_queue.clone();
thread::spawn(move || {
let sandbox = sq
.pop()
.unwrap_or_else(|| panic!("Failed to pop Sandbox thread {}", i));
let host_funcs = sandbox
._host_funcs
.try_lock()
.map_err(|_| new_error!("Error locking"));
assert!(host_funcs.is_ok());
host_funcs
.unwrap()
.host_print(format!("Print from Sandbox on Thread {}\n", i))
.unwrap();
})
})
.collect::<Vec<_>>();
for handle in thread_handles {
handle.join().unwrap();
}
}
}