Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 2 additions & 41 deletions dstack/dstack-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1562,46 +1562,6 @@ pub fn image_hash_from_sha256sum(checksum_file: &[u8]) -> [u8; 32] {
sha256(checksum_file)
}

pub fn sha256sum_entry_hash(checksum_file: &[u8], filename: &str) -> Result<[u8; 32], String> {
let text = std::str::from_utf8(checksum_file)
.map_err(|e| format!("sha256sum.txt is not valid UTF-8: {e}"))?;
let mut found = None;
for (line_no, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() {
continue;
}
let mut parts = line.split_whitespace();
let Some(hash_hex) = parts.next() else {
continue;
};
let Some(path) = parts.next() else {
return Err(format!(
"sha256sum.txt line {} is missing filename",
line_no + 1
));
};
if path != filename {
continue;
}
if found.is_some() {
return Err(format!(
"sha256sum.txt contains duplicate {filename} entries"
));
}
let hash = hex::decode(hash_hex)
.map_err(|e| format!("sha256sum.txt {filename} hash is not valid hex: {e}"))?;
let hash: [u8; 32] = hash.try_into().map_err(|hash: Vec<u8>| {
format!(
"sha256sum.txt {filename} hash has invalid length {}, expected 32",
hash.len()
)
})?;
found = Some(hash);
}
found.ok_or_else(|| format!("sha256sum.txt is missing {filename}"))
}

pub fn verify_measurement_material(
os_image_hash: &[u8],
checksum_file: &[u8],
Expand All @@ -1615,7 +1575,7 @@ pub fn verify_measurement_material(
hex::encode(image_hash_from_sha256sum(checksum_file))
));
}
let expected_measurement_hash = sha256sum_entry_hash(checksum_file, filename)?;
let expected_measurement_hash = sha256sum::entry_hash(checksum_file, filename)?;
let actual_measurement_hash = sha256(measurement);
if expected_measurement_hash != actual_measurement_hash {
return Err(format!(
Expand Down Expand Up @@ -2484,6 +2444,7 @@ pub struct ImageInfo {
}

pub mod mr_config;
pub mod sha256sum;
pub mod shared_filenames;
pub mod version;

Expand Down
142 changes: 142 additions & 0 deletions dstack/dstack-types/src/sha256sum.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// SPDX-FileCopyrightText: © 2026 Phala Network <dstack@phala.network>
//
// SPDX-License-Identifier: Apache-2.0

//! Parser for `sha256sum.txt`, the file whose digest is `os_image_hash`.
//!
//! The file is the only thing binding `os_image_hash` to the bytes that get
//! measured, so every consumer must read it exactly the same way. We generate
//! it ourselves with `sha256sum <files>` (`os/image/assemble.sh`), so only that
//! output shape is accepted: one `<lowercase sha256> <name>\n` line per file.
//! Everything else GNU `sha256sum` understands -- binary-mode `*name`,
//! `\`-escaped lines, paths -- is rejected rather than interpreted.

/// One `sha256sum.txt` entry: a file name and the digest it is bound to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub hash: [u8; 32],
pub name: String,
}

pub fn parse(checksum_file: &[u8]) -> Result<Vec<Entry>, String> {
let body = std::str::from_utf8(checksum_file)
.ok()
.and_then(|text| text.strip_suffix('\n'))
.ok_or("sha256sum.txt is not newline-terminated text")?;
let mut entries: Vec<Entry> = Vec::new();
for (index, line) in body.split('\n').enumerate() {
let line_no = index + 1;
let entry = parse_line(line).ok_or_else(|| {
format!("sha256sum.txt line {line_no} is not `<lowercase sha256> <file name>`")
})?;
if entries.iter().any(|e| e.name == entry.name) {
return Err(format!(
"sha256sum.txt line {line_no} repeats {}",
entry.name
));
}
entries.push(entry);
}
Ok(entries)
}

pub fn entry_hash(checksum_file: &[u8], filename: &str) -> Result<[u8; 32], String> {
parse(checksum_file)?
.into_iter()
.find(|entry| entry.name == filename)
.map(|entry| entry.hash)
.ok_or_else(|| format!("sha256sum.txt is missing {filename}"))
}

fn parse_line(line: &str) -> Option<Entry> {
let (hash_hex, name) = line.split_once(" ")?;
if !hash_hex
.bytes()
.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
|| !is_valid_name(name)
{
return None;
}
let mut hash = [0; 32];
hex::decode_to_slice(hash_hex, &mut hash).ok()?;
Some(Entry {
hash,
name: name.into(),
})
}

/// A file in the image root, e.g. `bzImage` or `measurement.tdx.cbor`. The
/// manifest cannot list itself: its digest is the image identity.
fn is_valid_name(name: &str) -> bool {
name.starts_with(|c: char| c.is_ascii_alphanumeric())
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
&& name != "sha256sum.txt"
}

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

const DIGEST: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

#[test]
fn accepts_sha256sum_output() {
let names = [
"ovmf.fd",
"bzImage",
"initramfs.cpio.gz",
"metadata.json",
"measurement.aws.replay.json",
"rootfs_v2-x86",
];
let doc: String = names.iter().map(|n| format!("{DIGEST} {n}\n")).collect();
let entries = parse(doc.as_bytes()).unwrap();
assert_eq!(
entries.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
names
);
assert_eq!(hex::encode(entries[0].hash), DIGEST);
assert_eq!(entry_hash(doc.as_bytes(), "bzImage"), Ok(entries[1].hash));
assert!(entry_hash(doc.as_bytes(), "missing").is_err());
}

#[test]
fn rejects_anything_else() {
let upper = DIGEST.to_uppercase();
for doc in [
String::new(),
"\n".into(),
format!("{DIGEST} bzImage"),
format!("{DIGEST} bzImage\n\n"),
format!("\n{DIGEST} bzImage\n"),
format!("{DIGEST} bzImage\r\n"),
format!("{DIGEST} bzImage\n{DIGEST} bzImage\n"),
format!("{upper} bzImage\n"),
format!("{} bzImage\n", &DIGEST[2..]),
format!("{DIGEST}00 bzImage\n"),
format!("{DIGEST} bzImage\n"),
format!("{DIGEST} *bzImage\n"),
format!("\\{DIGEST} bzImage\n"),
format!("{DIGEST} bzImage\n"),
format!("{DIGEST} bzImage junk\n"),
format!("{DIGEST} bz Image\n"),
format!("{DIGEST} \n"),
format!("{DIGEST} ./bzImage\n"),
format!("{DIGEST} ../bzImage\n"),
format!("{DIGEST} sub/bzImage\n"),
format!("{DIGEST} /bzImage\n"),
format!("{DIGEST} .\n"),
format!("{DIGEST} ..\n"),
format!("{DIGEST} .hidden\n"),
format!("{DIGEST} -rf\n"),
format!("{DIGEST} bz*Image\n"),
format!("{DIGEST} bzImage\u{200b}\n"),
format!("{DIGEST} sha256sum.txt\n"),
] {
assert!(parse(doc.as_bytes()).is_err(), "accepted {doc:?}");
}
assert!(parse(b"\xff\n").is_err());
}
}
Loading
Loading