use serde::{Deserialize, Serialize};
use crate::policy::PolicyError;
pub const MEMORY_MIB: (u32, u32) = (256, 65_536);
pub const MAX_CPUS: u8 = 64;
pub const DEFAULT_MEMORY_MIB: u32 = 2048;
pub const DEFAULT_CPUS: u8 = 2;
const RESERVED_PARAMETERS: &[&str] = &["init=", "rdinit="];
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VmSettings {
pub image: VmImage,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memory_mib: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cpus: Option<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VmImage {
pub kernel: VmFile,
pub rootfs: VmFile,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initrd: Option<VmFile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cmdline: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VmFile {
pub path: String,
pub sha256: String,
}
impl VmSettings {
#[must_use]
pub fn memory_mib(&self) -> u32 {
self.memory_mib.unwrap_or(DEFAULT_MEMORY_MIB)
}
#[must_use]
pub fn cpus(&self) -> u8 {
self.cpus.unwrap_or(DEFAULT_CPUS)
}
#[must_use]
pub fn files(&self) -> Vec<(&'static str, &VmFile)> {
let mut out = vec![
("kernel", &self.image.kernel),
("rootfs", &self.image.rootfs),
];
if let Some(initrd) = &self.image.initrd {
out.push(("initrd", initrd));
}
out
}
}
pub(crate) fn check(settings: Option<&VmSettings>) -> Result<(), PolicyError> {
let Some(vm) = settings else {
return Ok(());
};
let bad = |field: &str, problem: String| PolicyError::Rule {
rule: format!("sandbox.vm.{field}"),
problem,
};
for (name, file) in vm.files() {
let rooted = file.path.starts_with('/') || file.path.starts_with("~/");
if !rooted || file.path.contains(['*', '?', '[', '{']) || file.path.contains("/../") {
return Err(bad(
&format!("image.{name}.path"),
format!(
"`{}` must be an absolute or `~/` path to one file, without a glob or `..`",
file.path
),
));
}
let hex = file.sha256.len() == 64
&& file
.sha256
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
if !hex {
return Err(bad(
&format!("image.{name}.sha256"),
"must be the file's SHA-256 as 64 lowercase hexadecimal digits \
(`shasum -a 256 <file>`)"
.to_owned(),
));
}
}
let memory = vm.memory_mib();
if !(MEMORY_MIB.0..=MEMORY_MIB.1).contains(&memory) {
return Err(bad(
"memory_mib",
format!("{memory} is outside {} to {}", MEMORY_MIB.0, MEMORY_MIB.1),
));
}
if !(1..=MAX_CPUS).contains(&vm.cpus()) {
return Err(bad(
"cpus",
format!("{} is outside 1 to {MAX_CPUS}", vm.cpus()),
));
}
if let Some(cmdline) = &vm.image.cmdline {
if cmdline.chars().any(char::is_control) {
return Err(bad("image.cmdline", "holds a control character".to_owned()));
}
let reserved = cmdline
.split_whitespace()
.find(|word| RESERVED_PARAMETERS.iter().any(|p| word.starts_with(p)));
if let Some(word) = reserved {
return Err(bad(
"image.cmdline",
format!("`{word}`: OpenMoat's own init must be the guest's first process"),
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use crate::policy::{Policy, PolicyError};
const KERNEL: &str = "kernel: { path: ~/vm/vmlinux, sha256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef }";
const ROOTFS: &str = "rootfs: { path: /opt/vm/rootfs.ext4, sha256: fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 }";
fn with(image_extra: &str, vm_extra: &str) -> Result<Policy, PolicyError> {
Policy::parse(&format!(
"version: 1\nsandbox:\n vm:\n image:\n {KERNEL}\n {ROOTFS}\n{image_extra}{vm_extra}"
))
}
fn rule_of(result: Result<Policy, PolicyError>) -> String {
match result {
Err(PolicyError::Rule { rule, .. }) => rule,
other => panic!("expected a rule error, got {other:?}"),
}
}
#[test]
fn a_pinned_image_reads_with_its_defaults() {
let policy = with("", "").unwrap();
let vm = policy.sandbox.unwrap().vm.unwrap();
assert_eq!((vm.memory_mib(), vm.cpus()), (2048, 2));
assert_eq!(vm.files().len(), 2);
}
#[test]
fn bad_paths_digests_sizes_and_kernel_parameters_are_refused() {
let bad_kernel = |path: &str, sha: &str| {
Policy::parse(&format!(
"version: 1\nsandbox:\n vm:\n image:\n kernel: {{ path: '{path}', sha256: '{sha}' }}\n {ROOTFS}\n"
))
};
let good = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
assert_eq!(
rule_of(bad_kernel("vm/vmlinux", good)),
"sandbox.vm.image.kernel.path"
);
assert_eq!(
rule_of(bad_kernel("/vm/*", good)),
"sandbox.vm.image.kernel.path"
);
assert_eq!(
rule_of(bad_kernel("/a/../etc/x", good)),
"sandbox.vm.image.kernel.path"
);
assert_eq!(
rule_of(bad_kernel("/vm/k", "ABC")),
"sandbox.vm.image.kernel.sha256"
);
assert_eq!(
rule_of(bad_kernel("/vm/k", &good.to_uppercase())),
"sandbox.vm.image.kernel.sha256"
);
assert_eq!(
rule_of(with("", " memory_mib: 64\n")),
"sandbox.vm.memory_mib"
);
assert_eq!(rule_of(with("", " cpus: 0\n")), "sandbox.vm.cpus");
assert_eq!(
rule_of(with(" cmdline: 'quiet init=/bin/sh'\n", "")),
"sandbox.vm.image.cmdline"
);
assert_eq!(
rule_of(with(" cmdline: 'rdinit=/x'\n", "")),
"sandbox.vm.image.cmdline"
);
assert!(with(" cmdline: 'quiet loglevel=3'\n", "").is_ok());
}
}