use std::{ffi::CString, path::Path};
use super::{ffi, sysctl_signed, sysctl_string, sysctl_u64};
use crate::{
Result,
bench::BenchFacts,
disk::Disk,
gpu::Gpu,
readiness::{DataDirTuning, Fact, MemLock, Tuning},
security::{Lockdown, Posture, Tpm, TpmVersion},
sensors::{SensorKind, Temperature, plausible},
};
const MAX_SENSORS: usize = 4096;
const MAX_ZONES: usize = 64;
fn celsius(deci_kelvin: i64) -> Option<f32> {
let c = deci_kelvin as f32 / 10.0 - 273.15;
(deci_kelvin > 0 && plausible(c)).then_some(c)
}
fn ik(name: &str) -> Option<f32> {
let name = CString::new(name).ok()?;
celsius(sysctl_signed(&name).ok()?)
}
pub(crate) fn temperatures() -> Result<Vec<Temperature>> {
let cpus = super::count(c"hw.ncpu").unwrap_or(1).min(MAX_SENSORS);
let mut out = Vec::new();
for n in 0..cpus {
let Some(c) = ik(&format!("dev.cpu.{n}.temperature")) else {
continue;
};
out.push(Temperature {
label: format!("cpu{n}"),
kind: SensorKind::Cpu,
celsius: c,
high: None,
critical: ik(&format!("dev.cpu.{n}.coretemp.tjmax")),
});
}
for n in 0..MAX_ZONES {
let Some(c) = ik(&format!("hw.acpi.thermal.tz{n}.temperature")) else {
break;
};
out.push(Temperature {
label: format!("tz{n}"),
kind: SensorKind::Other,
celsius: c,
high: ik(&format!("hw.acpi.thermal.tz{n}._HOT")),
critical: ik(&format!("hw.acpi.thermal.tz{n}._CRT")),
});
}
Ok(out)
}
pub(crate) fn gpus() -> Result<Vec<Gpu>> {
Err(super::unsupported("graphics adapters"))
}
fn clock_name(timecounter: &str) -> String {
match timecounter {
t if t == "TSC" || t.starts_with("TSC-") => "tsc".to_owned(),
"HPET" => "hpet".to_owned(),
"ACPI-fast" | "ACPI-safe" => "acpi_pm".to_owned(),
"i8254" => "pit".to_owned(),
"kvmclock" => "kvm-clock".to_owned(),
"XENTIMER" => "xen".to_owned(),
other => other.to_ascii_lowercase(),
}
}
fn clock_source() -> Option<String> {
sysctl_string(c"kern.timecounter.hardware").map(|t| clock_name(&t))
}
fn fact_of(name: &'static core::ffi::CStr) -> Fact<u64> {
match super::sysctl_int(name) {
Ok(n) => Fact::Value(n),
Err(e) => Fact::Unknown(e.into_error("setting", name).to_string()),
}
}
fn backlog() -> Fact<(u64, Option<u64>)> {
match super::sysctl_int(c"kern.ipc.soacceptqueue") {
Ok(n) => Fact::Value((n, None)),
Err(_) => match fact_of(c"kern.ipc.somaxconn") {
Fact::Value(n) => Fact::Value((n, None)),
Fact::Unknown(why) => Fact::Unknown(why),
Fact::Skip => Fact::Skip,
},
}
}
fn ports() -> Fact<(u32, u32)> {
let read = |name| {
super::sysctl_int(name)
.ok()
.and_then(|n| u32::try_from(n).ok())
};
match (
read(c"net.inet.ip.portrange.first"),
read(c"net.inet.ip.portrange.last"),
) {
(Some(a), Some(b)) => Fact::Value((a.min(b), a.max(b))),
_ => Fact::Unknown("net.inet.ip.portrange could not be read".to_owned()),
}
}
fn memlock() -> Fact<MemLock> {
match super::rlimit(ffi::RLIMIT_MEMLOCK, "locked-memory limit") {
Ok(lim) => Fact::Value(MemLock::Limit {
soft: super::limit_value(lim.cur),
}),
Err(e) => Fact::Unknown(e.to_string()),
}
}
pub(crate) fn tuning() -> Tuning {
Tuning {
files_system: fact_of(c"kern.maxfiles"),
files_process: fact_of(c"kern.maxfilesperproc"),
memlock: memlock(),
backlog: backlog(),
ports: ports(),
clock_source: match clock_source() {
Some(name) => Fact::Value(name),
None => Fact::Unknown("kern.timecounter.hardware could not be read".to_owned()),
},
..Tuning::default()
}
}
fn atime_of(flags: u64) -> &'static str {
if flags & ffi::MNT_NOATIME != 0 {
"noatime"
} else {
"strictatime"
}
}
pub(crate) fn data_dir_tuning(path: &Path, _disk: &Disk) -> DataDirTuning {
let mut buf = [0u8; super::disk::PATH_MAX];
let atime = match super::disk::c_path(path, &mut buf) {
Ok(c) => match super::disk::statfs(c) {
Ok(st) => Fact::Value(atime_of(st.flags).to_owned()),
Err(code) => Fact::Unknown(super::os_error("mount flags", "statfs", code).to_string()),
},
Err(e) => Fact::Unknown(e.to_string()),
};
DataDirTuning {
atime,
scheduler: Fact::Skip,
}
}
fn aslr() -> Option<bool> {
sysctl_u64(c"kern.elf64.aslr.enable").map(|n| n != 0)
}
pub(crate) fn bench_facts() -> BenchFacts {
BenchFacts {
smt: sysctl_u64(c"kern.smp.threads_per_core")
.filter(|&n| n > 0)
.map(|n| n > 1),
clock_source: clock_source(),
aslr: aslr(),
..BenchFacts::default()
}
}
fn lockdown(securelevel: i64) -> Lockdown {
if securelevel >= 1 {
Lockdown::Integrity
} else {
Lockdown::Off
}
}
fn device_exists(name: &core::ffi::CStr) -> bool {
let mut mib = [0; 8];
super::name_to_mib(name, &mut mib).is_ok()
}
pub(crate) fn posture() -> Posture {
let tpm = (device_exists(c"dev.tpmcrb.0") || device_exists(c"dev.tpmtis.0")).then_some(Tpm {
version: TpmVersion::V2_0,
});
let firewall = (sysctl_u64(c"net.inet.ip.fw.enable") == Some(1)).then_some(true);
Posture {
aslr: aslr(),
kernel_lockdown: sysctl_signed(c"kern.securelevel").ok().map(lockdown),
tpm,
firewall,
..Posture::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Error;
#[test]
fn test_report_freebsd_clock_names() {
assert_eq!(clock_name("TSC-low"), "tsc");
assert_eq!(clock_name("TSC"), "tsc");
assert_eq!(clock_name("HPET"), "hpet");
assert_eq!(clock_name("ACPI-fast"), "acpi_pm");
assert_eq!(clock_name("i8254"), "pit");
assert_eq!(clock_name("kvmclock"), "kvm-clock");
assert_eq!(clock_name("Hyper-V"), "hyper-v");
assert!(crate::bench::slow_clock(&clock_name("ACPI-safe")));
assert!(!crate::bench::slow_clock(&clock_name("TSC-low")));
}
#[test]
fn test_report_freebsd_conversions() {
assert_eq!(celsius(3231).map(|c| (c * 10.0).round()), Some(500.0));
assert_eq!(celsius(0), None);
assert_eq!(celsius(-1), None);
assert_eq!(celsius(100_000), None, "not plausible");
assert_eq!(atime_of(ffi::MNT_NOATIME | ffi::MNT_LOCAL), "noatime");
assert_eq!(atime_of(ffi::MNT_LOCAL), "strictatime");
assert_eq!(lockdown(-1), Lockdown::Off);
assert_eq!(lockdown(0), Lockdown::Off);
assert_eq!(lockdown(2), Lockdown::Integrity);
}
#[test]
fn test_report_freebsd_live_settings() {
let t = tuning();
assert!(matches!(t.files_system, Fact::Value(n) if n > 0));
assert!(matches!(t.files_process, Fact::Value(n) if n > 0));
assert!(matches!(t.backlog, Fact::Value((n, None)) if n > 0));
assert!(matches!(t.ports, Fact::Value((a, b)) if a <= b && b <= 65_535));
assert!(matches!(t.clock_source, Fact::Value(_)));
assert!(matches!(t.memlock, Fact::Value(_)));
assert!(matches!(t.swappiness, Fact::Skip));
let root = crate::disk::of(Path::new("/")).unwrap();
let d = data_dir_tuning(Path::new("/"), &root);
assert!(matches!(d.atime, Fact::Value(_)));
assert!(matches!(d.scheduler, Fact::Skip));
let b = bench_facts();
assert!(b.clock_source.is_some());
let p = posture();
assert!(p.kernel_lockdown.is_some());
assert!(temperatures().is_ok());
assert!(matches!(gpus(), Err(Error::Unsupported { .. })));
}
}