uhyve 0.9.0

A specialized hypervisor for Hermit
Documentation
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::{
	collections::HashMap,
	convert::Infallible,
	fmt,
	num::{NonZero, ParseIntError, TryFromIntError},
	path::PathBuf,
	str::FromStr,
};

use byte_unit::{Byte, Unit};
use serde::Deserialize;
use thiserror::Error;

#[cfg(target_os = "linux")]
pub use crate::isolation::filemap::UhyveIoMode;

#[derive(Debug, Clone)]
pub struct Params {
	/// Guest RAM size
	pub memory_size: GuestMemorySize,

	/// Advise Transparent Hugepages
	#[cfg(target_os = "linux")]
	pub thp: bool,

	/// Advise Kernel Samepage Merging
	#[cfg(target_os = "linux")]
	pub ksm: bool,

	/// Number of guest CPUs
	pub cpu_count: CpuCount,

	/// Allows the guest to manage host CPU power state.
	///
	/// This decreases the latency for the guest, but increases latency for other processes on the same host CPU.
	/// This works best when the host CPUs are not overcommitted.
	/// The host estimates incorrect CPU usage, due to not knowing about guest idle time.
	#[cfg(target_os = "linux")]
	pub cpu_pm: bool,

	/// Create a PIT
	#[cfg(target_os = "linux")]
	pub pit: bool,

	/// GDB server port
	pub gdb_port: Option<u16>,

	/// Arguments to forward to the kernel
	pub kernel_args: Vec<String>,

	/// Mapped paths between the guest and host OS
	pub file_mapping: Vec<String>,

	/// Path to create temporary directory on
	pub tempdir: Option<PathBuf>,

	/// In case the given kernel is an Hermit image, how it should be forwarded to the (contained) kernel.
	pub hermit_image_mode: HermitImageMode,

	/// Level of file isolation to be enforced
	#[cfg(target_os = "linux")]
	pub file_isolation: FileSandboxMode,

	/// I/O mode for processing files files on the host
	#[cfg(target_os = "linux")]
	pub io_mode: UhyveIoMode,

	/// Kernel output handling
	pub output: Output,

	/// Collect run statistics
	pub stats: bool,

	/// Environment variables of the kernel
	pub env: EnvVars,

	/// Load the kernel to a random address
	pub aslr: bool,

	/// Store trace dumps in this directory
	#[cfg(feature = "instrument")]
	pub trace_dir: Option<PathBuf>,

	/// Networking configuration
	pub network: Option<NetworkMode>,
}

impl Default for Params {
	fn default() -> Self {
		Self {
			memory_size: Default::default(),
			#[cfg(target_os = "linux")]
			thp: false,
			#[cfg(target_os = "linux")]
			ksm: false,
			#[cfg(target_os = "linux")]
			pit: false,
			cpu_count: Default::default(),
			#[cfg(target_os = "linux")]
			cpu_pm: false,
			gdb_port: Default::default(),
			file_mapping: Default::default(),
			tempdir: Default::default(),
			hermit_image_mode: HermitImageMode::default(),
			#[cfg(target_os = "linux")]
			file_isolation: FileSandboxMode::default(),
			#[cfg(target_os = "linux")]
			io_mode: Default::default(),
			kernel_args: Default::default(),
			output: Default::default(),
			stats: false,
			env: EnvVars::default(),
			aslr: true,
			#[cfg(feature = "instrument")]
			trace_dir: Default::default(),
			network: None,
		}
	}
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub struct CpuCount(NonZero<u32>);

impl CpuCount {
	pub fn get(self) -> u32 {
		self.0.get()
	}
}

impl Default for CpuCount {
	fn default() -> Self {
		let default = 1.try_into().unwrap();
		Self(default)
	}
}

impl fmt::Display for CpuCount {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl TryFrom<u32> for CpuCount {
	type Error = TryFromIntError;

	fn try_from(value: u32) -> Result<Self, Self::Error> {
		value.try_into().map(Self)
	}
}

impl FromStr for CpuCount {
	type Err = ParseIntError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		let count = s.parse()?;
		Ok(Self(count))
	}
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub struct GuestMemorySize(pub(crate) Byte);

impl GuestMemorySize {
	const fn minimum() -> Byte {
		Byte::from_u64_with_unit(16, Unit::MiB).unwrap()
	}

	pub fn get(self) -> usize {
		self.0.as_u64().try_into().unwrap()
	}
}

impl Default for GuestMemorySize {
	fn default() -> Self {
		Self(Byte::from_u64_with_unit(64, Unit::MiB).unwrap())
	}
}

impl fmt::Display for GuestMemorySize {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.0.get_adjusted_unit(Unit::MiB))
	}
}

#[derive(Clone, Debug, Default)]
pub enum Output {
	#[default]
	StdIo,
	File(PathBuf),
	Buffer,
	None,
}
impl FromStr for Output {
	type Err = Infallible;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match s {
			"none" | "None" => Ok(Self::None),
			p => Ok(Self::File(p.into())),
		}
	}
}

#[derive(Error, Debug)]
pub enum InvalidGuestMemorySizeError {
	#[error(
		"Not enough guest memory. Must be at least {min:#} (is {cur:#.3})",
		min = GuestMemorySize::minimum().get_adjusted_unit(Unit::MiB),
		cur = .0.get_adjusted_unit(Unit::MiB),
	)]
	MemoryTooSmall(Byte),
	#[error(
		"Invalid amount of guest memory. Must be a multiple of 2 MiB (is {cur:#.3})",
		cur = .0.get_adjusted_unit(Unit::MiB),
	)]
	NotAHugepage(Byte),
}

impl TryFrom<Byte> for GuestMemorySize {
	type Error = InvalidGuestMemorySizeError;

	fn try_from(value: Byte) -> Result<Self, Self::Error> {
		if value < Self::minimum() {
			Err(InvalidGuestMemorySizeError::MemoryTooSmall(value))
		} else if !value
			.as_u64()
			.is_multiple_of(Byte::from_u64_with_unit(2, Unit::MiB).unwrap().as_u64())
		{
			Err(InvalidGuestMemorySizeError::NotAHugepage(value))
		} else {
			Ok(Self(value))
		}
	}
}

#[derive(Error, Debug)]
pub enum ParseByteError {
	#[error(transparent)]
	Parse(#[from] byte_unit::ParseError),

	#[error(transparent)]
	InvalidMemorySize(#[from] InvalidGuestMemorySizeError),
}

impl FromStr for GuestMemorySize {
	type Err = ParseByteError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		let requested = Byte::from_str(s)?;
		let memory_size = requested.try_into()?;
		Ok(memory_size)
	}
}

/// Configure the kernels environment variables.
#[derive(Debug, Clone, PartialEq)]
pub enum EnvVars {
	/// Pass all env vars of the host to the kernel.
	Host,
	/// Pass a certain set of env vars to the kernel.
	Set(HashMap<String, String>),
}
impl Default for EnvVars {
	fn default() -> Self {
		Self::Set(HashMap::new())
	}
}
impl<S: AsRef<str> + core::fmt::Debug + PartialEq + PartialEq<&'static str>> TryFrom<&[S]>
	for EnvVars
{
	type Error = &'static str;

	fn try_from(v: &[S]) -> Result<Self, Self::Error> {
		if v.iter().any(|i| *i == "host") {
			if v.len() != 1 {
				warn!(
					"Specifying -e host discards all other explicitly specified environment vars"
				);
			}
			return Ok(Self::Host);
		}

		Ok(Self::Set(v.iter().try_fold(
			HashMap::new(),
			|mut acc, s| {
				if let Some(split) = s.as_ref().split_once("=") {
					acc.insert(split.0.to_owned(), split.1.to_owned());
					Ok(acc)
				} else {
					Err("Invalid environment variables parameter format: Must be -e var=value")
				}
			},
		)?))
	}
}

#[derive(Debug, Clone, PartialEq)]
pub enum NetworkMode {
	Tap { name: String },
}
impl TryFrom<String> for NetworkMode {
	type Error = &'static str;

	fn try_from(netmode: String) -> Result<Self, Self::Error> {
		netmode_try_from(netmode)
	}
}
impl TryFrom<&str> for NetworkMode {
	type Error = &'static str;

	fn try_from(netmode: &str) -> Result<Self, Self::Error> {
		netmode_try_from(netmode)
	}
}
fn netmode_try_from<S: AsRef<str>>(netmode: S) -> Result<NetworkMode, &'static str> {
	if netmode.as_ref() == "tap" {
		return Ok(NetworkMode::Tap {
			name: "tap10".to_string(),
		});
	}

	let (mode, device) = netmode
		.as_ref()
		.split_once(':')
		.ok_or("invalid netmode string. Must be mode:devicename")?;
	match mode {
		"tap" => Ok(NetworkMode::Tap {
			name: device.to_string(),
		}),
		_ => Err("invalid networking mode"),
	}
}
/// Specify the way an Hermit image should be handled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HermitImageMode {
	/// Let Uhyve handle the image provision by embedding it into the file mapping
	///
	/// This supports all Hermit kernel versions and
	/// not just those which have (experimental) Hermit Image support.
	#[default]
	External,

	/// Let the Hermit kernel handle the Hermit image provision.
	///
	/// This should be faster on average, but requires an Hermit kernel that supports it
	/// and reduces the effective memory of the kernel.
	Internal,
}
impl fmt::Display for HermitImageMode {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.write_str(match self {
			Self::External => "external",
			Self::Internal => "internal",
		})
	}
}
impl FromStr for HermitImageMode {
	type Err = &'static str;
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Ok(match s.to_lowercase().as_str() {
			"external" => Self::External,
			"internal" => Self::Internal,
			_ => return Err("Unknown Hermit image mode"),
		})
	}
}

/// Enforcement strictness for file sandbox
///
/// Use None if you are using Uhyve as a library, as it is not currently
/// possible to run UhyveVm::new again if a mechanism like Landlock is enforced.
#[cfg(target_os = "linux")]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum FileSandboxMode {
	/// Do not enable filesystem isolation features.
	None,
	/// Enable filesystem isolation features on a best-effort basis.
	#[default]
	Normal,
	/// Enforce filesystem isolation strictly.
	Strict,
}

#[cfg(target_os = "linux")]
impl FromStr for FileSandboxMode {
	type Err = &'static str;
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match s.to_lowercase().as_str() {
			"none" => Ok(FileSandboxMode::None),
			"normal" => Ok(FileSandboxMode::Normal),
			"strict" => Ok(FileSandboxMode::Strict),
			_ => Err("Unknown file sandbox mode"),
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_env_vars() {
		let strings = [String::from("ASDF=asdf"), String::from("EMOJI=🤷")];

		let Ok(EnvVars::Set(map)) = EnvVars::try_from(strings.as_slice()) else {
			panic!();
		};
		assert_eq!(map.get("ASDF").unwrap(), "asdf");
		assert_eq!(map.get("EMOJI").unwrap(), "🤷");

		let env_vars = EnvVars::try_from(&["host", "OTHER=asdf"] as &[&str]).unwrap();
		assert_eq!(env_vars, EnvVars::Host);
	}

	#[test]
	#[cfg(target_os = "linux")]
	fn test_file_sandbox_mode() {
		let mut mode = FileSandboxMode::from_str("none");
		assert_eq!(mode, Ok(FileSandboxMode::None));
		mode = FileSandboxMode::from_str("normal");
		assert_eq!(mode, Ok(FileSandboxMode::Normal));
		mode = FileSandboxMode::from_str("strict");
		assert_eq!(mode, Ok(FileSandboxMode::Strict));
	}
}