Skip to main content

aff4_image/
integrity.rs

1//! Metadata integrity over exact ZIP member bytes, never reserialized RDF.
2use super::*;
3use sha2::Sha512;
4
5/// Result of an individual integrity check. A missing reference is not a match.
6#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
7pub enum CheckOutcome {
8    /// Computed bytes match the supplied reference.
9    Match,
10    /// Computed bytes differ from the supplied reference.
11    Mismatch,
12    /// No reference was recorded.
13    Missing,
14    /// This implementation cannot perform the requested check.
15    Unsupported,
16    /// Invalid reference syntax or evidence that could not be read.
17    Unreadable,
18}
19
20/// One explicitly scoped integrity comparison.
21#[derive(Debug, Clone, serde::Serialize)]
22pub struct IntegrityCheck {
23    /// Member or evidence resource whose bytes are covered.
24    pub resource: String,
25    /// Location of the reference, or `external` for a caller-supplied digest.
26    pub reference_source: String,
27    /// Algorithm name or unsupported datatype IRI.
28    pub algorithm: String,
29    /// Recorded reference when present.
30    pub expected: Option<String>,
31    /// Independently computed value when available.
32    pub computed: Option<String>,
33    /// Comparison result.
34    pub outcome: CheckOutcome,
35    /// Diagnostic detail for declined or failed checks.
36    pub detail: Option<String>,
37}
38
39/// Metadata checks, separate from file content verification and authenticity.
40#[derive(Debug, Clone, serde::Serialize)]
41pub struct MetadataVerification {
42    /// SHA256 of information.turtle, suitable for an external evidence record.
43    pub sha256: String,
44    /// All available internal and optional external comparisons.
45    pub checks: Vec<IntegrityCheck>,
46}
47
48impl MetadataVerification {
49    /// True only when every requested check has a reference and matches.
50    /// Internal matches alone do not establish independent authenticity.
51    pub fn all_match(&self) -> bool {
52        !self.checks.is_empty() && self.checks.iter().all(|c| c.outcome == CheckOutcome::Match)
53    }
54}
55
56pub(super) fn compare(
57    resource: &str,
58    source: &str,
59    algorithm: &str,
60    expected: &str,
61    bytes: &[u8],
62) -> IntegrityCheck {
63    let computed = match algorithm {
64        "MD5" => Some(hex(&Md5::digest(bytes))),
65        "SHA1" => Some(hex(&Sha1::digest(bytes))),
66        "SHA256" => Some(hex(&Sha256::digest(bytes))),
67        "SHA512" => Some(hex(&Sha512::digest(bytes))),
68        "Blake2b" | "BLAKE2B" | "blake2b" => {
69            Some(hex(&<blake2::Blake2b512 as blake2::Digest>::digest(bytes)))
70        }
71        _ => None,
72    };
73    let (outcome, detail) = match &computed {
74        None => (
75            CheckOutcome::Unsupported,
76            Some("unsupported digest algorithm".into()),
77        ),
78        Some(value)
79            if value.len() != expected.len()
80                || !expected.bytes().all(|b| b.is_ascii_hexdigit()) =>
81        {
82            (
83                CheckOutcome::Unreadable,
84                Some("invalid hexadecimal digest".into()),
85            )
86        }
87        Some(value) if value.eq_ignore_ascii_case(expected) => (CheckOutcome::Match, None),
88        Some(_) => (CheckOutcome::Mismatch, None),
89    };
90    IntegrityCheck {
91        resource: resource.into(),
92        reference_source: source.into(),
93        algorithm: algorithm.into(),
94        expected: Some(expected.into()),
95        computed,
96        outcome,
97        detail,
98    }
99}
100
101pub(super) fn absent(resource: &str, source: &str) -> IntegrityCheck {
102    IntegrityCheck {
103        resource: resource.into(),
104        reference_source: source.into(),
105        algorithm: String::new(),
106        expected: None,
107        computed: None,
108        outcome: CheckOutcome::Missing,
109        detail: Some("no recorded digest".into()),
110    }
111}
112
113impl Container {
114    /// Verifies exact metadata bytes using draft RDF and legacy Gemino JSON hashes.
115    /// Both representations are checked when present; conflicts cannot be hidden
116    /// by preferring one. Imported metadata is checked against its RDF references.
117    /// `expected_sha256` is an independently recorded information.turtle digest.
118    /// This does not hash the ZIP archive or verify evidence streams/signatures.
119    pub fn verify_metadata(
120        &mut self,
121        expected_sha256: Option<&str>,
122    ) -> Result<MetadataVerification> {
123        let primary = member(
124            &mut self.archive,
125            "information.turtle",
126            self.limits.metadata_bytes,
127        )?;
128        let sha256 = hex(&Sha256::digest(&primary));
129        let mut checks = Vec::new();
130        if let Some(expected) = expected_sha256 {
131            checks.push(compare(
132                "information.turtle",
133                "external",
134                "SHA256",
135                expected,
136                &primary,
137            ));
138        }
139        let mut found = false;
140        if self
141            .archive
142            .index_for_name("information.turtle.hashes")
143            .is_some()
144        {
145            found = true;
146            let bytes = member(
147                &mut self.archive,
148                "information.turtle.hashes",
149                self.limits.metadata_bytes,
150            )?;
151            let mut count = 0;
152            for triple in TurtleParser::new().for_reader(bytes.as_slice()) {
153                count += 1;
154                if count > self.limits.triples {
155                    return Err(malformed("hash reference triple limit exceeded"));
156                }
157                let triple = triple.map_err(|e| malformed(format!("metadata hashes: {e}")))?;
158                let NamedOrBlankNode::NamedNode(subject) = triple.subject else {
159                    return Err(malformed("hash subject must be an IRI"));
160                };
161                let name =
162                    storage_name(&self.archive, &self.volume, subject.as_str(), self.version)?;
163                if name != "information.turtle" || !is_property(triple.predicate.as_str(), "hash") {
164                    return Err(malformed("unexpected metadata hash statement"));
165                }
166                let Term::Literal(value) = triple.object else {
167                    return Err(malformed("hash must be a typed literal"));
168                };
169                let datatype = value.datatype();
170                let algorithm = datatype
171                    .as_str()
172                    .strip_prefix(NS)
173                    .unwrap_or(datatype.as_str());
174                let mut check = compare(
175                    &name,
176                    "information.turtle.hashes",
177                    algorithm,
178                    value.value(),
179                    &primary,
180                );
181                if matches!(algorithm, "MD5" | "SHA1") {
182                    check.outcome = CheckOutcome::Unsupported;
183                    check.detail =
184                        Some("draft metadata integrity requires SHA256 or stronger".into());
185                }
186                checks.push(check);
187            }
188            if count == 0 {
189                checks.push(absent("information.turtle", "information.turtle.hashes"));
190            }
191        }
192        if self.archive.index_for_name("container.hashes").is_some() {
193            found = true;
194            let bytes = member(
195                &mut self.archive,
196                "container.hashes",
197                self.limits.metadata_bytes,
198            )?;
199            // Reject duplicate keys rather than allowing JSON's last-value wins.
200            let values: UniqueHashes = serde_json::from_slice(&bytes)
201                .map_err(|e| malformed(format!("container.hashes: {e}")))?;
202            if values.0.is_empty() {
203                checks.push(absent("information.turtle", "container.hashes"));
204            }
205            for (algorithm, expected) in values.0 {
206                checks.push(compare(
207                    "information.turtle",
208                    "container.hashes",
209                    &algorithm.to_ascii_uppercase(),
210                    &expected,
211                    &primary,
212                ));
213            }
214        }
215        if !found {
216            checks.push(absent("information.turtle", "metadata hash files"));
217        }
218        // Parse import references once; retain only primary-store hashes for
219        // members actually imported. Imported self-hashes are not trusted.
220        let mut imported_refs: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
221        if self.metadata_members.len() > 1 {
222            for triple in TurtleParser::new().for_reader(primary.as_slice()) {
223                let triple = triple.map_err(|e| malformed(e.to_string()))?;
224                if !is_property(triple.predicate.as_str(), "hash") {
225                    continue;
226                }
227                if let NamedOrBlankNode::NamedNode(subject) = triple.subject
228                    && let Ok(name) =
229                        storage_name(&self.archive, &self.volume, subject.as_str(), self.version)
230                    && name != "information.turtle"
231                    && self.metadata_members.contains_key(&name)
232                    && let Term::Literal(value) = triple.object
233                {
234                    imported_refs.entry(name).or_default().push((
235                        value.datatype().as_str().to_owned(),
236                        value.value().to_owned(),
237                    ));
238                }
239            }
240        }
241        for (name, opened_hash) in &self.metadata_members {
242            if name == "information.turtle" {
243                if sha256 != *opened_hash {
244                    return Err(malformed("metadata changed after opening"));
245                }
246                continue;
247            }
248            let bytes = member(&mut self.archive, name, self.limits.metadata_bytes)?;
249            if hex(&Sha256::digest(&bytes)) != *opened_hash {
250                return Err(malformed("metadata changed after opening"));
251            }
252            let refs = imported_refs.remove(name).unwrap_or_default();
253            if refs.is_empty() {
254                checks.push(absent(name, "RDF metadata"));
255            }
256            for (datatype, value) in refs {
257                checks.push(compare(
258                    name,
259                    "information.turtle",
260                    datatype.strip_prefix(NS).unwrap_or(&datatype),
261                    &value,
262                    &bytes,
263                ));
264            }
265        }
266        Ok(MetadataVerification { sha256, checks })
267    }
268}
269
270struct UniqueHashes(BTreeMap<String, String>);
271impl<'de> serde::Deserialize<'de> for UniqueHashes {
272    fn deserialize<D: serde::Deserializer<'de>>(
273        deserializer: D,
274    ) -> std::result::Result<Self, D::Error> {
275        struct Visitor;
276        impl<'de> serde::de::Visitor<'de> for Visitor {
277            type Value = UniqueHashes;
278            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279                f.write_str("a unique algorithm-to-digest dictionary")
280            }
281            fn visit_map<M: serde::de::MapAccess<'de>>(
282                self,
283                mut map: M,
284            ) -> std::result::Result<Self::Value, M::Error> {
285                let mut values = BTreeMap::new();
286                while let Some((key, value)) = map.next_entry::<String, String>()? {
287                    if values.insert(key.to_ascii_uppercase(), value).is_some() {
288                        return Err(serde::de::Error::custom("duplicate hash algorithm"));
289                    }
290                }
291                Ok(UniqueHashes(values))
292            }
293        }
294        deserializer.deserialize_map(Visitor)
295    }
296}