From ca56195e9d615e61dee67c0ffab20ca3dc22ab23 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 18:42:47 +0100 Subject: [PATCH 1/5] uapi16: fix an underflow in set_contents() set_contents() panics in a debug build when a contents object has its offset beyond its data: let mut contents = ContentsObject::new(ContentsSource::File(a)); contents.set_offset(6); contents.set_original_size(Some(5)); object.set_contents(vec![contents]); attempt to subtract with overflow The check of the file object takes the rest of the data of a contents object from its offset on as total - offset. That the offset is inside the data is only stated in a comment, since ContentsObject::check_consistency() refuses an offset beyond the data. The reader and the writer only get to the check of the file object once every contents object passed its own check, so for them it holds. But set_contents() runs the check of the file object on the fields of a contents object that failed its own check as well, and so the subtraction underflows. A release build wraps around instead and fills in a size such as 18446744073709551615, marked as filled in. So subtract with checked_sub() and refuse such a contents object with the error its own check gives. That error moves into Error::offset_beyond_data() so that both checks share it. set_contents() then fills in neither a size nor a hash for the object. The test goes through the ways to get there: an offset beyond the data with and without a size given, httpHeaders without a URL, an encoded literal, a second contents object behind one that agrees, the offset u64::MAX, and an offset set on an object a reader read. Each of them panicked in the debug build of the tests. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/decode.rs | 61 ++++++++++++++++++++++++++++++++++++-------- src/uapi16/error.rs | 13 ++++++++++ 2 files changed, 64 insertions(+), 10 deletions(-) diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index aa2334d..ce5f1ef 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -520,8 +520,11 @@ impl FileObject { let Some(total) = original.size else { continue; }; - // ContentsObject::check_consistency found the offset inside the data. - let rest = total - contents.offset; + // The offset of a contents object that passed its own check is + // inside the data. + let Some(rest) = total.checked_sub(contents.offset) else { + return Err(Error::offset_beyond_data(subject, contents.offset, total)); + }; match (self.size, data.size) { (Some(stated), _) => { if contents.offset.checked_add(stated).is_none_or(|end| end > total) { @@ -780,14 +783,7 @@ impl ContentsObject { } if let Some(total) = data.original.size { if self.offset > total { - return Err(Error::manifest( - Problem::InvalidContents, - format!( - "{}: contents offset {} is beyond the data size {}", - subject, self.offset, total - ), - ) - .at(Field::Offset)); + return Err(Error::offset_beyond_data(subject, self.offset, total)); } } Ok(data) @@ -2478,6 +2474,51 @@ mod tests { } } + /// set_contents() holds the object against its contents objects, also + /// against one whose offset is beyond its data, which its own check + /// refuses. There is no rest of the data from that offset on, and the + /// size the object has stays. + #[test] + fn set_contents_with_an_offset_beyond_the_data() { + let file = |offset: u64, original_size: u64| { + let mut contents = ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + contents.set_offset(offset); + contents.set_original_size(Some(original_size)); + contents + }; + let mut headers = ContentsObject::new(ContentsSource::Implied); + headers.set_http_headers(vec![("A".to_string(), "b".to_string())]); + headers.set_original_size(Some(0)); + headers.set_offset(1); + let mut encoded = ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())); + encoded.set_encoding(Some("gzip".to_string())); + encoded.set_original_size(Some(3)); + encoded.set_offset(4); + let whole = ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + for (size, contents) in [ + (None, vec![file(6, 5)]), + (Some(1), vec![file(6, 5)]), + (None, vec![headers]), + (None, vec![encoded]), + (None, vec![whole, file(5, 4)]), + (None, vec![file(u64::MAX, 0)]), + ] { + let mut object = FileObject::new(Name::new("x").unwrap()); + object.set_size(size); + object.set_contents(contents); + assert_eq!(object.size(), size, "{:?}", object); + assert!(!object.filled_in().contains(Field::Size), "{:?}", object); + } + // An object a reader read, with the offset set beyond the data. + let mut object = object(r#"{"name":"x","contents":[{"file":"a","originalSize":5}]}"#); + assert_eq!(object.size(), Some(5)); + let mut contents = object.take_contents(); + contents[0].set_offset(6); + object.set_contents(contents); + assert_eq!(object.size(), None); + assert!(!object.filled_in().contains(Field::Size)); + } + /// `gptFlags` holds the flags that `gptFlagNoAuto`, /// `gptFlagGrowFileSystem` and `readOnly` give one each, and the two /// agree. Where the manifest lists the feature of a field, an object diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs index b797f08..886d2c1 100644 --- a/src/uapi16/error.rs +++ b/src/uapi16/error.rs @@ -624,6 +624,19 @@ impl Error { .at(Field::Contents) } + /// A contents object of the file object `subject` names whose offset + /// `offset` is beyond the size `total` of its data. + pub(crate) fn offset_beyond_data(subject: Subject<'_>, offset: u64, total: u64) -> Error { + Error::manifest( + Problem::InvalidContents, + format!( + "{}: contents offset {} is beyond the data size {}", + subject, offset, total + ), + ) + .at(Field::Offset) + } + /// `object`, which `subject` names, states the flag of the field /// `field`, which it cannot have, see [`FileObject::unpermitted_flag`]. pub(crate) fn unpermitted_flag(object: &FileObject, field: Field, subject: Subject<'_>) -> Error { From e1573d4c3b2e17129625fc629f38765950db2fe3 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 16:59:06 +0100 Subject: [PATCH 2/5] uapi16: add eq_ignore_filled_in() The derived == of FileObject, RootObject, InodeAttributes and ContentsObject compares the FilledIn marks too. A file object read from {"name":"e","size":0} and one built with set_size(Some(0)) set_sha256(Some(Sha256::EMPTY)) return the same from every getter but compare unequal. The reader filled in the hash of no data and marked it as filled in while the built object states it. Their Debug output differs only in filled_in. The marks matter to the writer though. Under "features": ["size"] the writer refuses the built object with UnlistedFeature because it states a sha256 the manifest doesn't record. The read object is written just fine because the writer leaves the filled-in hash out. So a == b currently means the same record and the same verdict from the writer and we keep it that way. Instead, add eq_ignore_filled_in() to all four types. It compares what the getters return and ignores the marks. The name follows str::eq_ignore_ascii_case(). Each method names every field when it destructures the object, so a field that is added later breaks the build until it is compared. The test builds every object with all of its fields named and changes them one at a time. Document on the types and on FilledIn that == includes the marks and point to eq_ignore_filled_in(). The fixture test can use it now. So with_stated_xattrs() goes and so does the fixture edit that took the hash of no data out of the empty file of the special case. That record is back to what systemd-manifest wrote. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/object.rs | 327 ++++++++++++++++++ src/uapi16/tests/fixtures.rs | 52 +-- .../tests/fixtures/special/Uapi16Manifest | 2 +- 3 files changed, 356 insertions(+), 25 deletions(-) diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 6263daf..35e6f47 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -794,6 +794,15 @@ impl FlagStates { filled_in }) } + + /// Whether `other` says the same of every flag: set, cleared or not + /// known. Which flags a reader filled in does not count. + pub(crate) fn eq_ignore_filled_in(&self, other: &FlagStates) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let FlagStates { stated, set, filled: _ } = self; + *stated == other.stated && *set == other.set + } } /// The fields of an object of a manifest that a reader filled in, which @@ -818,6 +827,13 @@ impl FlagStates { /// manifest fills them in again. The contents objects of a file object /// fill in again what follows from them when they are set, see /// [`FileObject::set_contents`]. +/// +/// `==` of the objects compares these marks too. Equal objects are the +/// same record, and a writer writes or refuses them alike. An object with a +/// value a reader filled in is not equal to one with the same value set. +/// [`FileObject::eq_ignore_filled_in`], [`RootObject::eq_ignore_filled_in`], +/// [`InodeAttributes::eq_ignore_filled_in`] and +/// [`ContentsObject::eq_ignore_filled_in`] compare the values alone. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct FilledIn(u16); @@ -1092,6 +1108,10 @@ pub enum ContentsSource { /// and hashes are those of the data as it is stored, the original ones /// those of the decoded data. The file object's data is the part of the /// decoded data that starts at `offset`. +/// +/// `==` compares which values a reader filled in as well, see +/// [`FilledIn`]. [`ContentsObject::eq_ignore_filled_in`] compares the +/// values alone. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct ContentsObject { @@ -1243,6 +1263,33 @@ impl ContentsObject { self.filled_in } + /// Whether `other` has the same values: what the getters return. Unlike + /// `==` it leaves out which values a reader filled in, see + /// [`FilledIn`]. + pub fn eq_ignore_filled_in(&self, other: &ContentsObject) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let ContentsObject { + source, + http_headers, + encoding, + encoded_size, + encoded_sha256, + original_size, + original_sha256, + offset, + filled_in: _, + } = self; + *source == other.source + && *http_headers == other.http_headers + && *encoding == other.encoding + && *encoded_size == other.encoded_size + && *encoded_sha256 == other.encoded_sha256 + && *original_size == other.original_size + && *original_sha256 == other.original_sha256 + && *offset == other.offset + } + /// Drops the sizes and hashes a reader filled in, which follow from the /// other fields: they are None, and none is noted as filled in. fn drop_filled_in(&mut self) { @@ -1277,6 +1324,10 @@ impl ContentsObject { /// `chattr(1)` changes, have a field each, such as `flagImmutable`. Only /// regular files and directories have them, the root directory among /// them. +/// +/// `==` compares which values a reader filled in as well, see +/// [`FilledIn`]. [`InodeAttributes::eq_ignore_filled_in`] compares the +/// values alone. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct InodeAttributes { @@ -1485,6 +1536,35 @@ impl InodeAttributes { self.filled_in.union(self.flags.filled_in()) } + /// Whether `other` has the same values: what the getters return. Unlike + /// `==` it leaves out which values a reader filled in, see + /// [`FilledIn`]. + pub fn eq_ignore_filled_in(&self, other: &InodeAttributes) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let InodeAttributes { + mode, + uid, + gid, + user_name, + group_name, + mtime_nsec, + user_xattrs, + read_only, + flags, + filled_in: _, + } = self; + *mode == other.mode + && *uid == other.uid + && *gid == other.gid + && *user_name == other.user_name + && *group_name == other.group_name + && *mtime_nsec == other.mtime_nsec + && *user_xattrs == other.user_xattrs + && *read_only == other.read_only + && flags.eq_ignore_filled_in(&other.flags) + } + /// The modification time, if the attributes have one. pub fn mtime(&self) -> Option { self.mtime_nsec.map(|nsec| UNIX_EPOCH + Duration::from_nanos(nsec)) @@ -1613,6 +1693,10 @@ impl InodeAttributes { /// [`InodeAttributes::read_only()`]. Only regular files and directories /// have DOS attributes, and the root directory has none: the root /// directory of FAT has no directory entry to keep them in. +/// +/// `==` compares which values a reader filled in as well, see +/// [`FilledIn`]. [`FileObject::eq_ignore_filled_in`] compares the values +/// alone. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FileObject { @@ -1836,6 +1920,67 @@ impl FileObject { .union(self.inode.filled_in()) } + /// Whether `other` has the same values: what the getters return, those + /// of the contents objects and of the inode attributes among them. + /// Unlike `==` it leaves out which values a reader filled in, see + /// [`FilledIn`]. + /// + /// ``` + /// use uapi16::{FileObject, Name, Object, Reader, Sha256}; + /// + /// let manifest = concat!( + /// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", + /// "\x1e{\"name\":\"e\",\"size\":0}\n", + /// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + /// ); + /// let mut reader = Reader::open(manifest.as_bytes())?; + /// let Some(Object::File(read)) = reader.next().transpose()? else { + /// panic!("no file object"); + /// }; + /// // The reader filled in the hash of no data for the size 0. + /// let mut set = FileObject::new(Name::new("e")?); + /// set.set_size(Some(0)); + /// set.set_sha256(Some(Sha256::EMPTY)); + /// assert!(read.eq_ignore_filled_in(&set)); + /// assert_ne!(*read, set); + /// # Ok::<(), Box>(()) + /// ``` + pub fn eq_ignore_filled_in(&self, other: &FileObject) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let FileObject { + name, + inode_type, + size, + sha256, + contents, + inode_token, + major, + minor, + gpt, + dos_flags, + inode, + validity, + filled_in: _, + } = self; + *name == other.name + && *inode_type == other.inode_type + && *size == other.size + && *sha256 == other.sha256 + && contents.len() == other.contents.len() + && contents + .iter() + .zip(&other.contents) + .all(|(contents, other)| contents.eq_ignore_filled_in(other)) + && *inode_token == other.inode_token + && *major == other.major + && *minor == other.minor + && *gpt == other.gpt + && dos_flags.eq_ignore_filled_in(&other.dos_flags) + && inode.eq_ignore_filled_in(&other.inode) + && *validity == other.validity + } + /// Drops the size and the hash a reader filled in, which follow from /// each other and from the contents objects: they are None, and /// neither is noted as filled in. @@ -1978,6 +2123,10 @@ impl FileObject { /// what the manifest records and the order it lists its file objects in, /// and the identity of the file system or of the partition table the file /// objects are placed in. +/// +/// `==` compares which values a reader filled in as well, see +/// [`FilledIn`]. [`RootObject::eq_ignore_filled_in`] compares the values +/// alone. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RootObject { @@ -2064,6 +2213,28 @@ impl RootObject { self.validity = validity; } + /// Whether `other` has the same values: what the getters return, those + /// of the inode attributes among them. Unlike `==` it leaves out which + /// values a reader filled in, see [`FilledIn`]. + pub fn eq_ignore_filled_in(&self, other: &RootObject) -> bool { + // Every field is named, so that a new field breaks the build here + // until it is compared. + let RootObject { + inode, + file_system, + gpt_disk_uuid, + order, + features, + validity, + } = self; + inode.eq_ignore_filled_in(&other.inode) + && *file_system == other.file_system + && *gpt_disk_uuid == other.gpt_disk_uuid + && *order == other.order + && *features == other.features + && *validity == other.validity + } + /// Whether the object has `field`, one of /// [`RootObject::FEATURE_FIELDS`]. fn has_feature_field(&self, field: Field) -> bool { @@ -2832,4 +3003,160 @@ mod tests { assert_eq!(inode.remove_user_xattr("comment"), Some(b"two".to_vec())); assert_eq!(inode.user_xattrs().map(|xattrs| xattrs.len()), Some(0)); } + + /// eq_ignore_filled_in() compares every value and none of the marks of + /// what a reader filled in, which == compares too. The objects are built + /// with every field named, so that a new field breaks the build here + /// until it has a case below. + #[test] + fn compares_the_values_without_the_marks() { + /// Checks that each of `changes`, which changes one value, makes an + /// object differ from `object` for `eq`, both ways around. + fn each_differs(object: &T, changes: &[Give], eq: fn(&T, &T) -> bool) { + assert!(eq(object, object)); + for change in changes { + let mut changed = object.clone(); + change(&mut changed); + assert!(!eq(object, &changed) && !eq(&changed, object), "{:?}", changed); + } + } + let contents = ContentsObject { + source: ContentsSource::Literal(b"hello".to_vec()), + http_headers: Vec::new(), + encoding: None, + encoded_size: Some(5), + encoded_sha256: None, + original_size: Some(5), + original_sha256: None, + offset: 0, + filled_in: FilledIn::default(), + }; + let inode = InodeAttributes { + mode: Some(Mode::new(0o644).unwrap()), + uid: Some(1), + gid: Some(2), + user_name: Some("u".into()), + group_name: Some("g".into()), + mtime_nsec: Some(3), + user_xattrs: Some(Box::default()), + read_only: Some(false), + flags: FlagStates { + stated: InodeFlags::IMMUTABLE | InodeFlags::NO_DUMP, + set: InodeFlags::IMMUTABLE, + filled: InodeFlags::default(), + }, + filled_in: FilledIn::default(), + }; + let object = FileObject { + name: Name::new("f").unwrap(), + inode_type: InodeType::Regular, + size: Some(5), + sha256: Some(Sha256::digest(b"hello")), + contents: vec![contents.clone()], + inode_token: NonZeroU64::new(1), + major: None, + minor: None, + gpt: None, + dos_flags: FlagStates { + stated: DosFlags::HIDDEN, + set: DosFlags::default(), + filled: DosFlags::default(), + }, + inode: inode.clone(), + validity: ValidityWindow::default(), + filled_in: FilledIn::default(), + }; + let root = RootObject { + inode: inode.clone(), + file_system: FileSystemIdentity::default(), + gpt_disk_uuid: None, + order: None, + features: None, + validity: ValidityWindow::default(), + }; + each_differs( + &contents, + &[ + |c| c.source = ContentsSource::Url("https://example.com/x".into()), + |c| c.http_headers = vec![("A".into(), "b".into())], + |c| c.encoding = Some("gzip".into()), + |c| c.encoded_size = None, + |c| c.encoded_sha256 = Some(Sha256::EMPTY), + |c| c.original_size = None, + |c| c.original_sha256 = Some(Sha256::EMPTY), + |c| c.offset = 1, + ], + ContentsObject::eq_ignore_filled_in, + ); + each_differs( + &inode, + &[ + |i| i.mode = None, + |i| i.uid = None, + |i| i.gid = None, + |i| i.user_name = None, + |i| i.group_name = None, + |i| i.mtime_nsec = None, + |i| i.user_xattrs = None, + |i| i.read_only = None, + // A flag not known any more, and one set instead of cleared. + |i| i.flags.put(InodeFlags::NO_DUMP, None), + |i| i.flags.put(InodeFlags::NO_DUMP, Some(true)), + ], + InodeAttributes::eq_ignore_filled_in, + ); + each_differs( + &object, + &[ + |o| o.name = Name::new("g").unwrap(), + |o| o.inode_type = InodeType::Symlink, + |o| o.size = None, + |o| o.sha256 = None, + |o| o.contents.clear(), + |o| o.contents[0].offset = 1, + |o| o.inode_token = None, + |o| o.major = Some(1), + |o| o.minor = Some(1), + |o| o.gpt = Some(Box::default()), + |o| o.dos_flags.put(DosFlags::HIDDEN, None), + |o| o.dos_flags.put(DosFlags::HIDDEN, Some(true)), + |o| o.inode.uid = None, + |o| o.validity.state = Validity::Revoked, + ], + FileObject::eq_ignore_filled_in, + ); + each_differs( + &root, + &[ + |r| r.inode.uid = None, + |r| r.file_system.label = Some("ESP".into()), + |r| r.gpt_disk_uuid = Some(Uuid::new([1; Uuid::SIZE])), + |r| r.order = Some(Order::CodePoint), + |r| r.features = Some(Features::ALL), + |r| r.validity.until_usec = Some(1), + ], + RootObject::eq_ignore_filled_in, + ); + // The same values, filled in by a reader on one side and set on the + // other. + let mut filled = contents.clone(); + filled.filled_in.insert(Field::EncodedSize); + assert!(filled.eq_ignore_filled_in(&contents) && filled != contents); + let (mut filled, mut set) = (inode.clone(), inode.clone()); + filled.filled_in.insert(Field::ReadOnly); + filled.filled_in.insert(Field::ExtendedAttributes); + filled.flags.fill_in(Features::FLAG_NO_COW, InodeType::Regular); + set.set_flag_no_cow(Some(false)); + assert!(filled.eq_ignore_filled_in(&set) && filled != set); + let (mut filled, mut set) = (object.clone(), object.clone()); + filled.filled_in.insert(Field::Size); + filled.contents[0].filled_in.insert(Field::OriginalSize); + filled.inode.filled_in.insert(Field::ReadOnly); + filled.dos_flags.fill_in(Features::FLAG_ARCHIVE, InodeType::Regular); + set.set_flag_archive(Some(false)); + assert!(filled.eq_ignore_filled_in(&set) && filled != set); + let mut filled = root.clone(); + filled.inode.filled_in.insert(Field::ExtendedAttributes); + assert!(filled.eq_ignore_filled_in(&root) && filled != root); + } } diff --git a/src/uapi16/tests/fixtures.rs b/src/uapi16/tests/fixtures.rs index a3183b4..2a9912a 100644 --- a/src/uapi16/tests/fixtures.rs +++ b/src/uapi16/tests/fixtures.rs @@ -1,12 +1,13 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! Manifests written by systemd's own tool, read and written back. They //! are copies of the fixtures of ufat, whose tests/fixtures/README.md says -//! how they were made. +//! how they were made. Only the file `empty` of the special case +//! differs: it has the hash of no data next to its size 0, as +//! systemd-manifest wrote it. -use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use uapi16::{Error, Field, FileObject, InodeType, Object, Order, Reader, RootObject, SignatureObject, Writer}; +use uapi16::{Error, FileObject, InodeType, Object, Order, Reader, RootObject, Sha256, SignatureObject, Writer}; /// A manifest read to its end: its root file object, its file objects and /// its signature objects. @@ -43,17 +44,17 @@ impl Manifest { Manifest::read(&bytes).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)) } - /// The manifest with the extended attributes a reader filled in taken - /// as ones the objects state. systemd-manifest states the empty ones, - /// which the writer leaves out and a reader fills in again. - fn with_stated_xattrs(mut self) -> Manifest { - let files = self.files.iter_mut().map(FileObject::inode_mut); - for inode in std::iter::once(self.root.inode_mut()).chain(files) { - if inode.filled_in().contains(Field::ExtendedAttributes) { - inode.set_user_xattrs(Some(BTreeMap::new())); - } - } - self + /// Whether `other` has the same objects with the same values, whatever + /// a reader filled in of them. + fn eq_ignore_filled_in(&self, other: &Manifest) -> bool { + self.root.eq_ignore_filled_in(&other.root) + && self.files.len() == other.files.len() + && self + .files + .iter() + .zip(&other.files) + .all(|(file, other)| file.eq_ignore_filled_in(other)) + && self.signatures == other.signatures } /// The manifest the writer writes for the objects. @@ -162,6 +163,9 @@ fn every_fixture_parses() { assert_eq!(readonly.inode().mode().map(u32::from), Some(0o444)); assert!(readonly.inode().is_read_only()); assert!(special.names().contains(&"sub/\u{fc}mlaut \u{221e}.txt")); + let empty = special.files.iter().find(|e| e.name() == "empty").unwrap(); + assert_eq!((empty.size(), empty.sha256()), (Some(0), Some(Sha256::EMPTY))); + assert!(empty.filled_in().is_empty()); let empty = Manifest::load("empty", "Uapi16Manifest"); assert!(empty.files.is_empty()); @@ -169,11 +173,9 @@ fn every_fixture_parses() { } /// The reader reads every manifest systemd-manifest wrote, and what the -/// writer writes for one reads back as the same manifest. That holds since -/// ufat's make-fixtures.sh took the hash of no data out of the empty file -/// of the special case: the writer leaves out a hash given next to the -/// size 0, and the reader marks the one it fills in as filled in, so the -/// objects would differ in that mark. +/// writer writes for one reads back with the same values. systemd-manifest +/// writes empty extended attributes and the hash of no data next to the +/// size 0. The writer leaves both out, and a reader fills them in again. #[test] fn reads_and_writes_back_every_fixture() { for (case, name, files, signatures) in [ @@ -194,11 +196,13 @@ fn reads_and_writes_back_every_fixture() { ); assert_eq!(read.root.order(), Some(Order::CodePoint), "{}", path.display()); let written = read.write().unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); - assert_eq!( - Manifest::read(&written).unwrap().with_stated_xattrs(), - read.with_stated_xattrs(), - "{}", - path.display() + let back = Manifest::read(&written).unwrap(); + assert!( + back.eq_ignore_filled_in(&read), + "{}:\n{:#?}\n{:#?}", + path.display(), + back, + read ); } } diff --git a/src/uapi16/tests/fixtures/special/Uapi16Manifest b/src/uapi16/tests/fixtures/special/Uapi16Manifest index 18d9767..4c4bef5 100644 --- a/src/uapi16/tests/fixtures/special/Uapi16Manifest +++ b/src/uapi16/tests/fixtures/special/Uapi16Manifest @@ -1,7 +1,7 @@ {"extendedAttributes":{"user":{}},"features":["device","gid","group-name","hardlink","mode","mtime","sha256","size","symlink","uid","user-name","user-xattr"],"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"Mixed Case.TXT","sha256":"480c2336b410f1ad5f8bf1b28944490255804b65350c527787e74ebdd511e3a4","size":7,"uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{"comment":{"text":"set by make-fixtures"}}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"a.txt","sha256":"b640e840b19d378660b32fb51ae18d67dccb4a8596a29e7bd72c1b2ae5928f41","size":6,"uid":1000,"userName":"brauner"} -{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"empty","size":0,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"empty","sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","size":0,"uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"empty dir","type":"dir","uid":1000,"userName":"brauner"} {"contents":[{"literal":"YS50eHQ="}],"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"name":"link","size":5,"type":"lnk","uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"sub","type":"dir","uid":1000,"userName":"brauner"} From a801a01888857e6404fb406cc785924798c91032 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 16:59:06 +0100 Subject: [PATCH 3/5] uapi16: check literals against their hashes Currently, the consistency checks hold a literal against the sizes the manifest gives and nothing else. Nothing hashes it. So a file object with the literal "hello" and the hash of "world" {"contents":[{"literal":"aGVsbG8="}],"name":"x","sha256":"486e..."} is written and read back without an error. Only copy_data() refuses it, with Data(HashMismatch), and only after it handed the bytes to the sink. data_location() hands out such a literal without complaint, and the promise of set_contents() that a writer refuses an object whose fields contradict each other doesn't hold. A literal is the data as it is stored. So hash it in check_consistency, which the reader and the writer share, and refuse a contradiction as Manifest(Contradiction) at Field::Literal, like the size check does: - Without an encoding the literal is held against encodedSha256 and originalSha256. With an encoding it is held against encodedSha256 only. originalSha256 is the hash of the decoded data and checking it would need decoding. - The part of an unencoded literal that is the data of the file object, from the offset on and as long as the object, is held against the hash of the object. That is the hash the object states or the one that follows from another contents object. Each literal is hashed once. ContentsObject::check_consistency() hashes it where its contents object gives a hash, and the check of the file object only hashes what that didn't cover: a literal without a hash of its own, or a part of one. The writer used to call ContentsObject::check_consistency() a second time for the check of the file object. It now keeps what the first call returned and hands it along. So FileObject::check_consistency() takes the data of the contents objects instead of a closure that computes it. The cost is linear in the size of the record, which MAX_RECORD_SIZE caps. For 32 records with a 1 MiB literal each and both hashes given, reading takes one hash of each literal more than before, about 4.5% more instructions, and writing takes one more. The new checks come after the other checks of a contents object and of a file object, so what those refused before keeps its error. This is a behavior change for readers and writers alike. A manifest with such a literal is now refused when it is read and when it is written. The tests that copied the data of such objects now expect the read to fail, and they copy the data of objects that were changed after they were read instead, which copy_data() still checks. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/content.rs | 44 +++++++++---- src/uapi16/decode.rs | 103 +++++++++++++++++++++++------ src/uapi16/refused.jsonl | 7 ++ src/uapi16/writer.rs | 138 +++++++++++++++++++++++++++++++++++++-- 4 files changed, 257 insertions(+), 35 deletions(-) diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 94ec7b1..5cf937f 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -183,7 +183,9 @@ impl FileObject { /// directory refers to. /// /// A literal is taken first, as the specification suggests: the - /// manifest carries the data itself. Otherwise the data is in the file + /// manifest carries the data itself. A reader and a writer refuse a + /// literal that does not match the hashes the manifest gives for it and + /// for the data of the object. Otherwise the data is in the file /// next to the manifest that the first contents object without an /// encoding names, or in the file of the object's own name where that /// contents object names no place. A regular file without contents @@ -267,7 +269,7 @@ impl FileObject { /// The data of the file in the literal `literal`: from `offset` on, as /// many bytes as the object says it has. An offset or a size beyond the /// literal takes all there is, which the size of the object then finds. - fn data_in_literal<'a>(&self, literal: &'a [u8], offset: u64) -> &'a [u8] { + pub(crate) fn data_in_literal<'a>(&self, literal: &'a [u8], offset: u64) -> &'a [u8] { let offset = usize::try_from(offset).unwrap_or(usize::MAX); let data = literal.get(offset..).unwrap_or(&[]); match self.size.map(usize::try_from) { @@ -1186,6 +1188,7 @@ impl DataProvider for StreamProvider { #[cfg(all(test, target_os = "linux"))] mod tests { use super::*; + use crate::error::Problem; use crate::testing::{json, manifest, read_whole, sequence, HELLO, TRAILER, WORLD}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -1693,7 +1696,14 @@ mod tests { assert_eq!(files.read(), 5); // A part of a literal is held against the hash of all of the // literal the manifest gives, as a part of a file is, unless the - // object has a hash of its own. + // object has a hash of its own. A reader refuses a literal that + // does not match a hash the manifest gives for it, so only an object + // changed after it was read gets here. + let refused = |record: &str| { + let e = read_whole(&manifest(&[record])).unwrap_err(); + (e.kind(), e.field()) + }; + let contradiction = (ErrorKind::Manifest(Problem::Contradiction), Some(Field::Literal)); for (record, data) in [ ( r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":1,"originalSha256":"#, @@ -1704,9 +1714,10 @@ mod tests { "he", ), ] { - let o = object(&format!(r#"{}"{}"}}]}}"#, record, HELLO)); + let mut o = object(&format!(r#"{}"{}"}}]}}"#, record, HELLO)); assert_eq!(copy(&o, &mut provider).unwrap(), data.as_bytes()); - let o = object(&format!(r#"{}"{}"}}]}}"#, record, WORLD)); + assert_eq!(refused(&format!(r#"{}"{}"}}]}}"#, record, WORLD)), contradiction); + o.contents[0].original_sha256 = WORLD.parse().ok(); let e = copy(&o, &mut provider).unwrap_err(); assert_eq!( facts(&e), @@ -1719,16 +1730,25 @@ mod tests { ) ); } - let o = object(&format!( - r#"{{"name":"x","size":2,"sha256":"{}","contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, - Sha256::digest(b"he"), - WORLD - )); + let record = |original: &str| { + format!( + r#"{{"name":"x","size":2,"sha256":"{}","contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, + Sha256::digest(b"he"), + original + ) + }; + assert_eq!(refused(&record(WORLD)), contradiction); + let mut o = object(&record(HELLO)); + o.contents[0].original_sha256 = WORLD.parse().ok(); assert_eq!(copy(&o, &mut provider).unwrap(), b"he"); // A literal that is not what the object says. - let o = object( - r#"{"name":"x","size":5,"contents":[{"literal":"aGVsbG8="}],"sha256":"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7"}"#, + let record = format!( + r#"{{"name":"x","size":5,"contents":[{{"literal":"aGVsbG8="}}],"sha256":"{}"}}"#, + WORLD ); + assert_eq!(refused(&record), contradiction); + let mut o = object(r#"{"name":"x","size":5,"contents":[{"literal":"aGVsbG8="}]}"#); + o.sha256 = WORLD.parse().ok(); assert_eq!(copy(&o, &mut provider).unwrap_err().kind(), hash); let mut o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#); o.size = Some(6); diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index ce5f1ef..fbba56c 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -388,7 +388,7 @@ impl Draft { } // The contents objects were checked when they were read, and hold // what follows from their fields. - let data = object.check_consistency(subject, |contents| Ok(contents.data()))?; + let data = object.check_consistency(subject, object.contents.iter().map(ContentsObject::data))?; object.fill_in_data(data); Ok(()) } @@ -483,25 +483,27 @@ impl FileObject { } } let subject = Subject::new(self, ROOT_RECORD); - if let Ok(data) = self.check_consistency(subject, |contents| Ok(contents.data())) { + if let Ok(data) = self.check_consistency(subject, self.contents.iter().map(ContentsObject::data)) { self.fill_in_data(data); } } /// Checks that the fields of the object agree with each other, as the - /// specification requires: `readOnly` and `mode`, and the size and the - /// hash of the object and those of its contents objects. `contents_data` - /// gives what each contents object says of its data: what - /// [`ContentsObject::check_consistency`] returns for it, or what its fields - /// hold once a reader checked and filled it in. Returns the size and the - /// hash of the data of the object: those it gives, and those that follow - /// from its contents objects and from each other. Whether `gptFlags` - /// agrees with the fields that give its flags one by one depends on what - /// the manifest records, see [`FileObject::check_partition_flags`]. + /// specification requires: `readOnly` and `mode`, the size and the + /// hash of the object and those of its contents objects, and the hash + /// of the object and the data in its literals. `contents_data` gives + /// what each contents object says of its data, in their order: what + /// [`ContentsObject::check_consistency`] returned for it, or what its + /// fields hold once a reader checked and filled it in. Returns the size + /// and the hash of the data of the object: those it gives, and those + /// that follow from its contents objects and from each other. Whether + /// `gptFlags` agrees with the fields that give its flags one by one + /// depends on what the manifest records, see + /// [`FileObject::check_partition_flags`]. pub(crate) fn check_consistency( &self, subject: Subject<'_>, - contents_data: impl Fn(&ContentsObject) -> Result, + contents_data: impl Iterator + Clone, ) -> Result { self.inode.check_read_only(subject)?; // The size and the hash of the object and those of its contents @@ -515,8 +517,8 @@ impl FileObject { size: self.size, sha256: self.sha256, }; - for contents in &self.contents { - let original = contents_data(contents)?.original; + for (contents, contents_data) in self.contents.iter().zip(contents_data.clone()) { + let original = contents_data.original; let Some(total) = original.size else { continue; }; @@ -566,9 +568,49 @@ impl FileObject { // What the size and the hash were given or follow from has to agree. data.reconcile() .map_err(|conflict| conflict.into_error(subject, Field::Sha256, Field::Size))?; + if let Some(sha256) = data.sha256 { + self.check_literals(sha256, contents_data, subject)?; + } Ok(data) } + /// Checks that the data of the object in each of its literals without an + /// encoding has the hash `sha256`, the one + /// [`FileObject::check_consistency`] found for the object. The data is + /// the part of the literal that [`FileObject::data_location`] takes: + /// from the offset on, as long as the object is. `contents_data` gives + /// what each contents object says of its data. A literal that is all of + /// the data and has a hash of its own was held against that hash, which + /// the hash of the object agrees with, and is not hashed again. + fn check_literals( + &self, + sha256: Sha256, + contents_data: impl Iterator, + subject: Subject<'_>, + ) -> Result<(), Error> { + for (contents, contents_data) in self.contents.iter().zip(contents_data) { + let Some(literal) = contents.literal().filter(|_| contents.encoding.is_none()) else { + continue; + }; + let part = self.data_in_literal(literal, contents.offset); + if part.len() == literal.len() && contents_data.original.sha256.is_some() { + continue; + } + if Sha256::digest(part) != sha256 { + return Err(Error::manifest( + Problem::Contradiction, + format!( + "{}: the data in literal contents does not match '{}'", + subject, + Field::Sha256 + ), + ) + .at(Field::Literal)); + } + } + Ok(()) + } + /// Checks that the attribute flags of the partition the object /// describes agree where they are given twice: all of them in /// `gptFlags`, and one each in `gptFlagNoAuto`, `gptFlagGrowFileSystem` @@ -715,8 +757,9 @@ impl ContentsObject { /// its data with what follows from them: a literal gives the size of /// the stored data, and without an encoding the stored data is the /// data. A size of 0 and the hash of no data go together. `httpHeaders` - /// come with a URL only, and the offset is inside the data. `subject` - /// names the file object the contents object belongs to. + /// come with a URL only, and the offset is inside the data. A literal + /// has the hash given for the data as it is stored. `subject` names the + /// file object the contents object belongs to. pub(crate) fn check_consistency(&self, subject: Subject<'_>) -> Result { if !self.http_headers.is_empty() && self.url().is_none() { return Err(Error::manifest( @@ -786,6 +829,23 @@ impl ContentsObject { return Err(Error::offset_beyond_data(subject, self.offset, total)); } } + // A literal is the data as it is stored. Its hash is the encoded + // hash, and without an encoding the original hash, which is the + // same by now. The original hash of an encoded literal is that of + // the decoded data, which is not checked. + if let (Some(literal), Some(sha256)) = (self.literal(), data.encoded.sha256) { + if Sha256::digest(literal) != sha256 { + let given = match self.encoded_sha256 { + Some(_) => Field::EncodedSha256, + None => Field::OriginalSha256, + }; + return Err(Error::manifest( + Problem::Contradiction, + format!("{}: literal contents do not match '{}'", subject, given), + ) + .at(Field::Literal)); + } + } Ok(data) } @@ -2396,7 +2456,7 @@ mod tests { let subject = Subject::new(object, 1); assert_eq!( object - .check_consistency(subject, |contents| contents.check_consistency(subject)) + .check_consistency(subject, object.contents.iter().map(ContentsObject::data)) .unwrap(), SizeAndHash::default() ); @@ -2408,7 +2468,7 @@ mod tests { let mut given = object.clone(); given.inode.filled_in.remove(Field::ReadOnly); let e = given - .check_consistency(Subject::new(&given, 1), |contents| Ok(contents.data())) + .check_consistency(Subject::new(&given, 1), given.contents.iter().map(ContentsObject::data)) .unwrap_err(); assert_eq!( (e.kind(), e.field()), @@ -2423,7 +2483,12 @@ mod tests { fn consistency_of_objects_not_read() { let check = |object: &FileObject| { let subject = Subject::new(object, 1); - object.check_consistency(subject, |contents| contents.check_consistency(subject)) + let contents_data = object + .contents + .iter() + .map(|contents| contents.check_consistency(subject)) + .collect::, _>>()?; + object.check_consistency(subject, contents_data.into_iter()) }; let file = |size: Option, contents: ContentsObject| { let mut object = FileObject::new(Name::new("x").unwrap()); diff --git a/src/uapi16/refused.jsonl b/src/uapi16/refused.jsonl index 4786eae..2e595d2 100644 --- a/src/uapi16/refused.jsonl +++ b/src/uapi16/refused.jsonl @@ -316,6 +316,9 @@ [["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"encodedSize\":4}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 5 bytes, not 4"] [["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"originalSize\":4}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 5 bytes, not 4"] [["@root","{\"name\":\"x\",\"size\":5,\"contents\":[{\"literal\":\"H4sIAAAAAAAAA8tIzcnJBwCGphA2BQAAAA==\",\"encoding\":\"gzip\",\"encodedSize\":24}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 25 bytes, not 24"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"originalSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents do not match 'originalSha256'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"encodedSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents do not match 'encodedSha256'"] +[["@root","{\"name\":\"x\",\"size\":5,\"contents\":[{\"literal\":\"H4sIAAAAAAAAA8tIzcnJBwCGphA2BQAAAA==\",\"encoding\":\"gzip\",\"encodedSha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents do not match 'encodedSha256'"] [["@root","{\"name\":\"x\",\"size\":3,\"contents\":[{\"file\":\"a\",\"offset\":-2}]}","@trailer"],"fieldType",1,"x","offset","manifest field 'offset' is not an unsigned integer"] [["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"offset\":6,\"originalSize\":5}]}","@trailer"],"contents",1,"x","offset","manifest object 1: contents offset 6 is beyond the data size 5"] [["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"offset\":6}]}","@trailer"],"contents",1,"x","offset","manifest object 1: contents offset 6 is beyond the data size 5"] @@ -323,6 +326,10 @@ [["@root","{\"name\":\"x\",\"size\":18446744073709551615,\"contents\":[{\"file\":\"a\",\"offset\":2,\"originalSize\":18446744073709551615}]}","@trailer"],"contradiction",1,"x","offset","manifest object 1 (x): offset 2 plus size 18446744073709551615 exceeds the contents size 18446744073709551615"] [["@root","{\"name\":\"x\",\"size\":5,\"contents\":[{\"originalSize\":4}]}","@trailer"],"contradiction",1,"x","offset","manifest object 1 (x): offset 0 plus size 5 exceeds the contents size 4"] [["@root","{\"name\":\"x\",\"size\":5,\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"contents\":[{\"file\":\"a\",\"originalSize\":5,\"originalSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","sha256","manifest object 1 (x): object and contents hashes differ"] +[["@root","{\"name\":\"x\",\"size\":5,\"sha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\",\"contents\":[{\"literal\":\"aGVsbG8=\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1 (x): the data in literal contents does not match 'sha256'"] +[["@root","{\"name\":\"x\",\"size\":2,\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"contents\":[{\"literal\":\"aGVsbG8=\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1 (x): the data in literal contents does not match 'sha256'"] +[["@root","{\"name\":\"x\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"offset\":1,\"originalSha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1 (x): the data in literal contents does not match 'sha256'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\"},{\"file\":\"a\",\"originalSize\":5,\"originalSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1 (x): the data in literal contents does not match 'sha256'"] [["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\"},{\"file\":\"/b\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name has an empty component: '/b'"] [["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"/a\"},{\"file\":\"b\",\"encoding\":\"identity\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name has an empty component: '/a'"] [["@root","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":[]}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: 'extendedAttributes' is not an object"] diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index 61840fe..11aa221 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -469,9 +469,13 @@ impl FileObject { if self.contents.len() > MAX_CONTENTS { return Err(Error::too_many_contents(subject)); } + // What each contents object says of its data. The check of the + // object below takes it from here, so that no literal is hashed + // twice. + let mut contents_data = Vec::with_capacity(self.contents.len()); for contents in &self.contents { contents.check(subject)?; - contents.check_consistency(subject)?; + contents_data.push(contents.check_consistency(subject)?); } let inode = &self.inode; inode.check_xattr_names(subject)?; @@ -496,7 +500,7 @@ impl FileObject { self.check_permitted_fields(subject)?; // The contents objects were checked above. This is for what // follows from them. - self.check_consistency(subject, |contents| contents.check_consistency(subject))?; + self.check_consistency(subject, contents_data.iter().copied())?; Ok(()) } @@ -829,7 +833,7 @@ mod tests { use crate::object::{ContentsSource, DosFlags, FatSerial, InodeFlags, Mode, Uuid}; use crate::testing::{ directory, everything, json, name, read_whole, record, recording_all, sequence, write_whole, written, Whole, - EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, + EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, WORLD, }; use crate::{Sha256, Writer}; use std::collections::BTreeMap; @@ -1613,6 +1617,22 @@ mod tests { }, Problem::InvalidContents, ), + // A literal against its hash, before the value of a field + // behind it. + ( + format!( + r#"{{"contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}],"name":"x","uid":65535}}"#, + WORLD + ), + |o| { + o.contents = vec![ContentsObject { + original_sha256: WORLD.parse().ok(), + ..ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())) + }]; + o.inode.uid = Some(65535); + }, + Problem::Contradiction, + ), // A value, before a missing name. ( r#"{"uid":65535}"#.into(), @@ -1912,7 +1932,11 @@ mod tests { fn file() -> ContentsObject { ContentsObject::new(ContentsSource::File(name("x"))) } - let cases: [(Give, Problem, Option); 17] = [ + /// The literal "hello". + fn hello() -> ContentsObject { + ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())) + } + let cases: [(Give, Problem, Option); 22] = [ // Fields the inode type does not permit. ( |o| (o.inode_type, o.size) = (InodeType::Fifo, Some(1)), @@ -2018,6 +2042,50 @@ mod tests { Problem::Contradiction, Some(Field::Offset), ), + // A literal against the hashes of its contents object, without + // and with an encoding, and against the hash of the object, all + // of the data and a part of it. + ( + |o| { + o.contents = vec![ContentsObject { + original_sha256: WORLD.parse().ok(), + ..hello() + }]; + }, + Problem::Contradiction, + Some(Field::Literal), + ), + ( + |o| { + o.contents = vec![ContentsObject { + encoded_sha256: WORLD.parse().ok(), + ..hello() + }]; + }, + Problem::Contradiction, + Some(Field::Literal), + ), + ( + |o| { + o.contents = vec![ContentsObject { + encoding: Some("gzip".into()), + encoded_sha256: WORLD.parse().ok(), + ..hello() + }]; + }, + Problem::Contradiction, + Some(Field::Literal), + ), + ( + |o| (o.sha256, o.contents) = (WORLD.parse().ok(), vec![hello()]), + Problem::Contradiction, + Some(Field::Literal), + ), + ( + |o| (o.size, o.sha256, o.contents) = (Some(2), HELLO.parse().ok(), vec![hello()]), + Problem::Contradiction, + Some(Field::Literal), + ), ]; let (root, _) = recording_all(); for (give, problem, field) in cases { @@ -2037,6 +2105,68 @@ mod tests { } } + /// A literal is the data as it is stored, so the writer refuses what a + /// reader refuses of it: a literal that does not match a hash of its + /// contents object or the hash of the object. The literal "hello" with + /// the hash of "world" was written and read back once, and only a copy + /// of its data failed. + #[test] + fn checks_literals_against_their_hashes() { + let world = Sha256::digest(b"world"); + let hello = || vec![ContentsObject::new(ContentsSource::Literal(b"hello".to_vec()))]; + let mut contents_first = FileObject::new(name("x")); + contents_first.set_contents(hello()); + contents_first.set_sha256(Some(world)); + let mut hash_first = FileObject::new(name("x")); + hash_first.set_sha256(Some(world)); + hash_first.set_contents(hello()); + let facts = |e: Error| (e.kind(), e.field(), e.record_number(), e.to_string()); + let expected = ( + ErrorKind::Manifest(Problem::Contradiction), + Some(Field::Literal), + Some(1), + "manifest object 1 (x): the data in literal contents does not match 'sha256'".to_string(), + ); + for object in [&contents_first, &hash_first] { + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + assert_eq!(facts(writer.file(object).unwrap_err()), expected, "{:?}", object); + } + let record = format!( + r#"{{"contents":[{{"literal":"aGVsbG8="}}],"name":"x","sha256":"{}"}}"#, + WORLD + ); + assert_eq!( + facts(read_whole(&sequence(&[ROOT, &record, TRAILER])).unwrap_err()), + expected + ); + // What agrees is read and written back: a literal with the hash of + // its contents object, a part of one with the hash of the object, + // one with the hash another contents object gives, and an encoded + // one, whose hash of the decoded data is not checked. + for record in [ + format!( + r#"{{"contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}],"name":"x"}}"#, + HELLO + ), + format!( + r#"{{"contents":[{{"literal":"aGVsbG8=","offset":1}}],"name":"x","sha256":"{}"}}"#, + Sha256::digest(b"ello") + ), + format!( + r#"{{"contents":[{{"literal":"aGVsbG8="}},{{"file":"a","originalSha256":"{}","originalSize":5}}],"name":"x"}}"#, + HELLO + ), + format!( + r#"{{"contents":[{{"encoding":"gzip","literal":"Z3o=","originalSha256":"{}"}}],"name":"x"}}"#, + WORLD + ), + ] { + let bytes = sequence(&[ROOT, &record, TRAILER]); + let m = read_whole(&bytes).unwrap_or_else(|e| panic!("{}: {}", record, e)); + assert_eq!(write_whole(&m).unwrap(), bytes, "{}", record); + } + } + /// An encoder appends what a writer writes, and nothing where it fails. #[test] fn encodes_what_a_writer_writes() { From 99ccb5d9497aa2effcba01b0865d1bf35c9496ef Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 17:20:49 +0100 Subject: [PATCH 4/5] uapi16: don't fill in from contents objects that contradict themselves set_contents() fills in what follows from the contents objects, as a reader does. But fill_in_from_contents() only leaves out the contents objects whose own check fails. The check of the file object then still runs on their fields as they are and fills in the size and the hash of the file from them. So set_contents() with the literal "hello", the original size 5 and the hash of "world" leaves the object with the size 5 and the hash of "world", both marked as filled in. A reader refuses the record of that object, a writer refuses the object since the previous commit, and copy_data() fails. Such a contents object is also what made set_contents() panic in a debug build. With the file "a" at offset 6 and the original size 5 the check of the file object subtracted the offset from the size and underflowed. "uapi16: fix an underflow in set_contents()" made that subtraction checked, but that only turns it into an error. The docs of fill_in_from_contents() already promise that nothing follows from fields that contradict each other. So fill in nothing for the object, neither its size nor its hash, when one of its contents objects fails its own check. Contents objects that agree with themselves are still filled in. That keeps set_contents() from taking a contents object that failed its own check into the check of the file object at all, and the checked subtraction stays as a guard. The reader doesn't have that problem. A contents object that fails its own check makes the reader refuse the whole record, and the size and the hash of an object are only filled in for a record without an error. The test holds set_contents() to what a reader reads from the same records, marks and all, and checks the case above. Running set_contents() over 707200 generated cases before and after this change gives 53034 objects that differ. Each of them has a contents object that contradicts itself, and in each the object keeps what it states and nothing more. Where the writer takes the object nothing changes, and the record it writes reads back with the values set_contents() gave it. This changes what set_contents() does, not its API. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/decode.rs | 159 ++++++++++++++++++++++++++++++++++++++++++- src/uapi16/object.rs | 11 +-- 2 files changed, 164 insertions(+), 6 deletions(-) diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index fbba56c..03c7ece 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -467,7 +467,9 @@ impl FileObject { /// Fills in what follows from the contents objects, as a reader does: /// what each of them says of its own data, and the size and the hash of /// the data of the object. Where fields contradict each other nothing - /// follows from them, and a writer refuses the object. + /// follows from them, and a writer refuses the object. So where the + /// fields of one contents object contradict each other, nothing is + /// filled in for the object, as a reader refuses its record. pub(crate) fn fill_in_from_contents(&mut self) { // The object is in no record, and what is wrong with it is not // shown, so the number of the record does not matter. @@ -477,11 +479,17 @@ impl FileObject { .iter() .map(|contents| contents.check_consistency(subject).ok()) .collect(); + let consistent = data.iter().all(Option::is_some); for (contents, data) in self.contents.iter_mut().zip(data) { if let Some(data) = data { contents.fill_in(data); } } + // A contents object that contradicts itself gives nothing for the + // object either. A reader refuses its record. + if !consistent { + return; + } let subject = Subject::new(self, ROOT_RECORD); if let Ok(data) = self.check_consistency(subject, self.contents.iter().map(ContentsObject::data)) { self.fill_in_data(data); @@ -2924,6 +2932,155 @@ mod tests { } } + /// set_contents() fills in what a reader fills in for the same record, + /// marks and all. Where the fields of a contents object contradict each + /// other, a reader refuses the record, and set_contents() fills in + /// nothing for the object: neither its size nor its hash. + #[test] + fn set_contents_fills_in_what_a_reader_does() { + let hello: Option = HELLO.parse().ok(); + let world: Option = WORLD.parse().ok(); + let literal = || ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())); + let file = || ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + let set = |size: Option, sha256: Option, contents: Vec| { + let mut object = FileObject::new(Name::new("x").unwrap()); + object.set_size(size); + object.set_sha256(sha256); + object.set_contents(contents); + object + }; + // The literal "hello" with the hash of "world" gave the object the + // size 5 and the hash of "world". + let mut contents = literal(); + contents.set_original_size(Some(5)); + contents.set_original_sha256(world); + let object = set(None, None, vec![contents]); + assert_eq!((object.size(), object.sha256()), (None, None)); + assert!(object.filled_in().is_empty() && object.contents()[0].filled_in().is_empty()); + let e = refused(&format!( + r#"{{"name":"x","contents":[{{"literal":"aGVsbG8=","originalSize":5,"originalSha256":"{}"}}]}}"#, + WORLD + )); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::Contradiction), Some(Field::Literal)) + ); + // Contents objects that agree give what a reader gives. + let he = Sha256::digest(b"he"); + for (record, object) in [ + ( + r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#.to_string(), + set(None, None, vec![literal()]), + ), + ( + format!( + r#"{{"name":"x","contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, + HELLO + ), + set( + None, + None, + vec![ContentsObject { + original_sha256: hello, + ..literal() + }], + ), + ), + ( + format!( + r#"{{"name":"x","size":2,"sha256":"{}","contents":[{{"literal":"aGVsbG8="}}]}}"#, + he + ), + set(Some(2), Some(he), vec![literal()]), + ), + ( + r#"{"name":"x","contents":[{"file":"a","offset":2,"originalSize":7}]}"#.to_string(), + set( + None, + None, + vec![ContentsObject { + offset: 2, + original_size: Some(7), + ..file() + }], + ), + ), + ( + format!( + r#"{{"name":"x","contents":[{{"file":"a","originalSize":5,"originalSha256":"{}"}},{{"literal":"aGVsbG8="}}]}}"#, + HELLO + ), + set( + None, + None, + vec![ + ContentsObject { + original_size: Some(5), + original_sha256: hello, + ..file() + }, + literal(), + ], + ), + ), + ( + r#"{"name":"x","contents":[{"file":"a","encoding":"gzip","encodedSize":3,"originalSize":5}]}"# + .to_string(), + set( + None, + None, + vec![ContentsObject { + encoding: Some("gzip".into()), + encoded_size: Some(3), + original_size: Some(5), + ..file() + }], + ), + ), + ] { + assert_eq!(object, self::object(&record), "{}", record); + } + // A contents object that contradicts itself, also next to one that + // agrees, which is filled in all the same. + for (record, contents) in [ + ( + r#"{"name":"x","contents":[{"file":"a","encodedSize":3,"originalSize":5}]}"#.to_string(), + vec![ContentsObject { + encoded_size: Some(3), + original_size: Some(5), + ..file() + }], + ), + ( + format!( + r#"{{"name":"x","contents":[{{"file":"a","originalSize":5,"originalSha256":"{}"}},{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, + HELLO, WORLD + ), + vec![ + ContentsObject { + original_size: Some(5), + original_sha256: hello, + ..file() + }, + ContentsObject { + original_sha256: world, + ..literal() + }, + ], + ), + ] { + let e = refused(&record); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::Contradiction), "{}", record); + let object = set(None, None, contents); + assert_eq!((object.size(), object.sha256()), (None, None), "{}", record); + assert!(object.filled_in().is_empty(), "{}", record); + assert!(object.contents().last().unwrap().filled_in().is_empty(), "{}", record); + if let [agrees, _] = object.contents() { + assert!(agrees.filled_in().contains(Field::EncodedSize), "{}", record); + } + } + } + #[test] fn contents_objects() { let contents = |text: &str| { diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 35e6f47..b0ea465 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -1818,11 +1818,12 @@ impl FileObject { /// Sets `contents`, and fills in what follows from them as a reader /// does, see [`FilledIn`]: what each contents object says of its own - /// data, and the size and the hash of the data of the file. What a - /// reader filled in that no longer follows is dropped, and what the - /// object states stays. A writer refuses an object whose fields - /// contradict each other, and more than [`MAX_CONTENTS`] contents - /// objects. + /// data, and the size and the hash of the data of the file. Where the + /// fields of one contents object contradict each other, the size and + /// the hash of the file are not filled in. What a reader filled in that + /// no longer follows is dropped, and what the object states stays. A + /// writer refuses an object whose fields contradict each other, and + /// more than [`MAX_CONTENTS`] contents objects. /// /// [`MAX_CONTENTS`]: crate::MAX_CONTENTS pub fn set_contents(&mut self, contents: Vec) { From 143a5260329a2d00cad8f87843239eb17b99b2f7 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Mon, 23 Nov 2026 18:55:28 +0100 Subject: [PATCH 5/5] uapi16: only fill in from contents objects a reader takes Before it fills in what follows from them, set_contents() runs ContentsObject::check_consistency() on each contents object and nothing else. A reader also checks the value of each field on its own: the URL has to be http or https, the encoding can't be empty or identity, and the names and values of HTTP header fields have rules of their own, as do the strings of a manifest. So set_contents() with the URL "ftp://example.com/x" and the original size 5 still leaves the object with the size 5 and the contents object with the encoded size 5, both marked as filled in. The same goes for the encoding "identity" on a literal and for the HTTP header field "bad name". A reader refuses the records of all three, and a writer refuses the objects. So follow the rule a reader follows and fill in only from contents objects a reader takes. set_contents() runs the checks of the values as well, and a contents object that fails them fills in nothing, for itself or for the file object, just like one that contradicts itself since the previous commit. The checks are the ones the writer already runs as a reader does, ContentsObject::check_strings() and ContentsObject::check(). The new ContentsObject::check_values() runs the two. A sweep holds set_contents() against a reader of the record with the same fields, for 2704000 generated file objects with up to two contents objects, with and without a value a reader refuses. For every record a reader takes, set_contents() gives the object the reader reads, marks and all. For every record it refuses, set_contents() fills in nothing for the object. Every contents object is filled in as a reader fills it in on its own, or not at all where a reader refuses it, and the writer takes exactly the objects whose records a reader takes. Before this change 30808 of them got a size or a hash filled in from a record a reader refuses, and 72560 had a contents object filled in that a reader refuses. Where a reader takes the record nothing changes. This changes what set_contents() does, not its API. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/decode.rs | 90 ++++++++++++++++++++++++++++++++++++++------ src/uapi16/object.rs | 15 +++++--- src/uapi16/writer.rs | 10 +++++ 3 files changed, 97 insertions(+), 18 deletions(-) diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index 03c7ece..aa90fac 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -466,10 +466,12 @@ impl FileObject { /// Fills in what follows from the contents objects, as a reader does: /// what each of them says of its own data, and the size and the hash of - /// the data of the object. Where fields contradict each other nothing - /// follows from them, and a writer refuses the object. So where the - /// fields of one contents object contradict each other, nothing is - /// filled in for the object, as a reader refuses its record. + /// the data of the object. Only a contents object a reader takes gives + /// anything: one whose values a reader takes, see + /// [`ContentsObject::check_values`], and whose fields agree with each + /// other. Where one of them does not, nothing is filled in for the + /// object either, as a reader refuses its record and a writer refuses + /// the object. pub(crate) fn fill_in_from_contents(&mut self) { // The object is in no record, and what is wrong with it is not // shown, so the number of the record does not matter. @@ -477,17 +479,22 @@ impl FileObject { let data: Vec<_> = self .contents .iter() - .map(|contents| contents.check_consistency(subject).ok()) + .map(|contents| { + contents + .check_values(subject) + .and_then(|()| contents.check_consistency(subject)) + .ok() + }) .collect(); - let consistent = data.iter().all(Option::is_some); + let taken = data.iter().all(Option::is_some); for (contents, data) in self.contents.iter_mut().zip(data) { if let Some(data) = data { contents.fill_in(data); } } - // A contents object that contradicts itself gives nothing for the - // object either. A reader refuses its record. - if !consistent { + // A contents object a reader refuses gives nothing for the object + // either. A reader refuses its record. + if !taken { return; } let subject = Subject::new(self, ROOT_RECORD); @@ -2933,9 +2940,10 @@ mod tests { } /// set_contents() fills in what a reader fills in for the same record, - /// marks and all. Where the fields of a contents object contradict each - /// other, a reader refuses the record, and set_contents() fills in - /// nothing for the object: neither its size nor its hash. + /// marks and all. Where a contents object has fields that contradict + /// each other or a value a reader refuses, a reader refuses the record, + /// and set_contents() fills in nothing for the object: neither its size + /// nor its hash. #[test] fn set_contents_fills_in_what_a_reader_does() { let hello: Option = HELLO.parse().ok(); @@ -3037,6 +3045,19 @@ mod tests { }], ), ), + ( + r#"{"name":"x","contents":[{"url":"https://example.com/x","httpHeaders":{"A":"b"},"originalSize":5}]}"# + .to_string(), + set( + None, + None, + vec![ContentsObject { + http_headers: vec![("A".into(), "b".into())], + original_size: Some(5), + ..ContentsObject::new(ContentsSource::Url("https://example.com/x".into())) + }], + ), + ), ] { assert_eq!(object, self::object(&record), "{}", record); } @@ -3079,6 +3100,51 @@ mod tests { assert!(agrees.filled_in().contains(Field::EncodedSize), "{}", record); } } + // A contents object with a value a reader refuses: a URL that is + // neither http nor https, the encoding that stands for none and a + // name that is not one of an HTTP header field. + let ftp = || ContentsObject::new(ContentsSource::Url("ftp://example.com/x".into())); + let https = || ContentsObject::new(ContentsSource::Url("https://example.com/x".into())); + for (record, contents, field) in [ + ( + r#"{"name":"x","contents":[{"url":"ftp://example.com/x","originalSize":5}]}"#, + ContentsObject { + original_size: Some(5), + ..ftp() + }, + Field::Url, + ), + ( + r#"{"name":"x","contents":[{"literal":"aGVsbG8=","encoding":"identity","originalSize":5}]}"#, + ContentsObject { + encoding: Some("identity".into()), + original_size: Some(5), + ..literal() + }, + Field::Encoding, + ), + ( + r#"{"name":"x","contents":[{"url":"https://example.com/x","httpHeaders":{"bad name":"b"},"originalSize":5}]}"#, + ContentsObject { + http_headers: vec![("bad name".into(), "b".into())], + original_size: Some(5), + ..https() + }, + Field::HttpHeaders, + ), + ] { + let e = refused(record); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::InvalidContents), Some(field)), + "{}", + record + ); + let object = set(None, None, vec![contents.clone()]); + assert_eq!((object.size(), object.sha256()), (None, None), "{}", record); + assert!(object.filled_in().is_empty(), "{}", record); + assert_eq!(object.contents(), [contents], "{}", record); + } } #[test] diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index b0ea465..e01ad81 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -1818,12 +1818,15 @@ impl FileObject { /// Sets `contents`, and fills in what follows from them as a reader /// does, see [`FilledIn`]: what each contents object says of its own - /// data, and the size and the hash of the data of the file. Where the - /// fields of one contents object contradict each other, the size and - /// the hash of the file are not filled in. What a reader filled in that - /// no longer follows is dropped, and what the object states stays. A - /// writer refuses an object whose fields contradict each other, and - /// more than [`MAX_CONTENTS`] contents objects. + /// data, and the size and the hash of the data of the file. Only a + /// contents object a reader takes gives anything. Where one has a value + /// a reader refuses, such as a URL that is neither http nor https, or + /// fields that contradict each other, nothing is filled in for it, and + /// the size and the hash of the file are not filled in either. What a + /// reader filled in that no longer follows is dropped, and what the + /// object states stays. A writer refuses an object whose fields + /// contradict each other or that has such a value, and more than + /// [`MAX_CONTENTS`] contents objects. /// /// [`MAX_CONTENTS`]: crate::MAX_CONTENTS pub fn set_contents(&mut self, contents: Vec) { diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index 11aa221..bda6bf7 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -739,6 +739,16 @@ impl ContentsObject { } } + /// Checks every value of the contents object, one of those of the file + /// object `subject` names, as a reader does: its strings, see + /// [`ContentsObject::check_strings`], and the value of every field, see + /// [`ContentsObject::check`]. [`ContentsObject::check_consistency`] + /// checks the fields against each other. + pub(crate) fn check_values(&self, subject: Subject<'_>) -> Result<(), Error> { + self.check_strings(subject)?; + self.check(subject) + } + /// The header fields in the order of their names, which is the order /// they are written in. fn sorted_headers(&self) -> Vec<&(String, String)> {