diff --git a/nvx/src/host/config/mod.rs b/nvx/src/host/config/mod.rs index 6dae38bd6..ba2d65f41 100644 --- a/nvx/src/host/config/mod.rs +++ b/nvx/src/host/config/mod.rs @@ -18,7 +18,7 @@ use sha2::{Digest, Sha256}; use super::filesystem::{ExportPlan, ReservedTargets}; use super::network::{self, NetworkPolicy}; -use super::platform::parse_hex32; +use super::platform::{parse_hex, write_hex}; use super::runtime::{GuestPowerAction, Hypervisor, Runtime}; use crate::error::{Error, Result}; use crate::guest_restore; @@ -387,9 +387,7 @@ pub struct CaptureIdentity([u8; 32]); impl fmt::Display for CaptureIdentity { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0 - .iter() - .try_for_each(|byte| write!(formatter, "{byte:02x}")) + write_hex(formatter, &self.0) } } @@ -408,7 +406,7 @@ impl serde::Serialize for CaptureIdentity { impl<'de> serde::Deserialize<'de> for CaptureIdentity { fn deserialize>(deserializer: D) -> Result { let text = ::deserialize(deserializer)?; - parse_hex32(&text).map(Self).ok_or_else(|| { + parse_hex(&text).map(Self).ok_or_else(|| { serde::de::Error::custom(format!( "{text:?} is not a capture's identity, which is 64 hexadecimal digits" )) diff --git a/nvx/src/host/platform/linux/process.rs b/nvx/src/host/platform/linux/process.rs index 2288d33bf..52d80cb0f 100644 --- a/nvx/src/host/platform/linux/process.rs +++ b/nvx/src/host/platform/linux/process.rs @@ -8,7 +8,7 @@ use std::thread; use std::time::{Duration, Instant}; use super::BOOT_ID_PATH; -use crate::host::platform::{parse_hex_id, parse_host_id, unless_exited}; +use crate::host::platform::{parse_hex, parse_host_id, unless_exited}; use crate::host::sys::{self, Errno, PidFd}; /// Returns the start time of a live process, `None` if the process no longer exists, or an error @@ -297,7 +297,7 @@ fn pidfds_unavailable(error: &io::Error) -> bool { pub(crate) fn boot_id() -> io::Result<[u8; 16]> { let text = fs::read_to_string(BOOT_ID_PATH)?; let digits = text.trim_end().replace('-', ""); - parse_hex_id(&digits).ok_or_else(|| { + parse_hex(&digits).ok_or_else(|| { io::Error::new( io::ErrorKind::InvalidData, format!("{BOOT_ID_PATH} has an unexpected format"), diff --git a/nvx/src/host/platform/mod.rs b/nvx/src/host/platform/mod.rs index f4e00d275..c402efe31 100644 --- a/nvx/src/host/platform/mod.rs +++ b/nvx/src/host/platform/mod.rs @@ -323,27 +323,13 @@ pub(crate) fn unless_exited( if exited()? { Ok(()) } else { Err(error) } } -/// Parses exactly 32 hexadecimal digits, in either case, into the 16 bytes that they spell. -pub(crate) fn parse_hex_id(digits: &str) -> Option<[u8; 16]> { - let digits = digits.as_bytes(); - if digits.len() != 32 { - return None; - } - let mut id = [0; 16]; - for (byte, pair) in id.iter_mut().zip(digits.chunks_exact(2)) { - let nibble = |digit: u8| char::from(digit).to_digit(16); - *byte = u8::try_from(nibble(pair[0])? * 16 + nibble(pair[1])?).ok()?; - } - Some(id) -} - -/// Parses 64 hexadecimal digits, in either case, into the 32 bytes that they spell. -pub(crate) fn parse_hex32(text: &str) -> Option<[u8; 32]> { +/// Parses exactly `2 * N` hexadecimal digits, in either case, into the `N` bytes that they spell. +pub(crate) fn parse_hex(text: &str) -> Option<[u8; N]> { let digits = text.as_bytes(); - if digits.len() != 64 { + if digits.len() != 2 * N { return None; } - let mut bytes = [0; 32]; + let mut bytes = [0; N]; for (byte, pair) in bytes.iter_mut().zip(digits.chunks_exact(2)) { let nibble = |digit: u8| char::from(digit).to_digit(16); *byte = u8::try_from(nibble(pair[0])? * 16 + nibble(pair[1])?).ok()?; @@ -351,6 +337,13 @@ pub(crate) fn parse_hex32(text: &str) -> Option<[u8; 32]> { Some(bytes) } +/// Writes `bytes` as lowercase hexadecimal digits, two for each byte. +pub(crate) fn write_hex(formatter: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result { + bytes + .iter() + .try_for_each(|byte| write!(formatter, "{byte:02x}")) +} + /// Parses the identity of a host as OpenVMM reads it: 32 hexadecimal digits, in either case, /// between optional braces and surrounding whitespace, ignoring dashes, as in `/etc/machine-id` /// and the Windows machine GUID. @@ -363,7 +356,7 @@ fn parse_host_id(text: &str) -> Option<[u8; 16]> { .chars() .filter(|&character| character != '-') .collect(); - parse_hex_id(&digits) + parse_hex(&digits) } #[cfg(test)] diff --git a/nvx/src/host/platform/tests.rs b/nvx/src/host/platform/tests.rs index b004b11a7..ecba9d670 100644 --- a/nvx/src/host/platform/tests.rs +++ b/nvx/src/host/platform/tests.rs @@ -158,6 +158,39 @@ fn host_identities_are_read_as_openvmm_reads_them() { } } +#[test] +fn hexadecimal_text_is_written_in_lowercase_and_read_in_either_case() { + struct Hex<'a>(&'a [u8]); + + impl fmt::Display for Hex<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write_hex(formatter, self.0) + } + } + + let bytes = [0x00, 0x0a, 0xb1, 0xff]; + assert_eq!(Hex(&bytes).to_string(), "000ab1ff"); + assert_eq!(parse_hex::<4>("000ab1ff"), Some(bytes)); + assert_eq!(parse_hex::<4>("000AB1FF"), Some(bytes)); + // An odd, short, or long length, a digit beyond `f`, a sign, and a non-ASCII byte. + for text in [ + "000ab1f", + "000ab1", + "000ab1ff00", + "000ab1fg", + "+00ab1ff", + "000ab1\u{e9}", + "", + ] { + assert_eq!(parse_hex::<4>(text), None, "{text:?}"); + } + // The lengths of the host's identities: 32 digits for 16 bytes, 64 for 32. + assert_eq!(parse_hex::<16>(&"Ab".repeat(16)), Some([0xab; 16])); + assert_eq!(parse_hex::<16>(&"ab".repeat(32)), None); + assert_eq!(parse_hex::<32>(&"cD".repeat(32)), Some([0xcd; 32])); + assert_eq!(parse_hex::<32>(&"cd".repeat(16)), None); +} + #[cfg(any(target_os = "linux", windows))] #[test] fn the_hosts_identity_and_monotonic_time_are_read() { diff --git a/nvx/src/host/process.rs b/nvx/src/host/process.rs index 9ea3f07f5..b15a8f017 100644 --- a/nvx/src/host/process.rs +++ b/nvx/src/host/process.rs @@ -93,9 +93,7 @@ impl BootId { impl fmt::Display for BootId { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - self.0 - .iter() - .try_for_each(|byte| write!(formatter, "{byte:02x}")) + platform::write_hex(formatter, &self.0) } } @@ -111,7 +109,7 @@ impl FromStr for BootId { /// Parses the text form of a boot identity, failing with /// [`ErrorKind::Io`](crate::ErrorKind::Io) for anything other than 32 hexadecimal digits. fn from_str(text: &str) -> crate::Result { - platform::parse_hex_id(text).map(Self).ok_or_else(|| { + platform::parse_hex(text).map(Self).ok_or_else(|| { Error::io(format!( "{text:?} is not a boot identity, which is 32 hexadecimal digits" )) diff --git a/nvx/src/host/snapshot/key.rs b/nvx/src/host/snapshot/key.rs index 883bc361f..3063601a2 100644 --- a/nvx/src/host/snapshot/key.rs +++ b/nvx/src/host/snapshot/key.rs @@ -18,7 +18,7 @@ use super::manifest::{ use crate::error::{Error, Result}; use crate::guest_restore; use crate::host::config::{DiskCapture, check_setting}; -use crate::host::platform::parse_hex32; +use crate::host::platform::{parse_hex, write_hex}; use crate::host::process::BootId; use crate::host::runtime::{ ArtifactIdentity, CompatibilityIdentity, Hypervisor, MAX_IDENTITY_LEN, RuntimeIdentity, @@ -134,13 +134,6 @@ fn digest(domain: &[u8], bytes: &[u8]) -> [u8; 32] { digest.finalize().into() } -/// Writes `bytes` as lowercase hexadecimal digits. -fn write_hex(formatter: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result { - bytes - .iter() - .try_for_each(|byte| write!(formatter, "{byte:02x}")) -} - /// Declares a 32-byte identity: the domain-separated SHA-256 digest of a canonical encoding. macro_rules! identity { ($(#[$attribute:meta])* $name:ident, $what:literal) => { @@ -178,7 +171,7 @@ macro_rules! identity { /// Parses the text form of the identity, 64 hexadecimal digits, failing with /// [`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported) for anything else. fn from_str(text: &str) -> Result { - parse_hex32(text).map(Self).ok_or_else(|| { + parse_hex(text).map(Self).ok_or_else(|| { Error::unsupported(format!( concat!("{:?} is not ", $what, ", which is 64 hexadecimal digits"), text