mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-02 02:37:26 -06:00
validate: a stored nested zip as the final part no longer disputes the outer directory (#8128)
* fix(validate): ignore unreachable EOCDs inside verified entry payloads (#7035) * test(validate): expect PASS for stored_nested_zip and guard payload reachability (#7035) * fix(validate): restrict dispute clearance to final entry with verified local header (#7035) * test(validate): regress non-final entry and inconsistent local header disputes (#7035) * fix(validate): require central-last entry to be physically last for dispute clearance (#7035) * test(validate): regress CD-last but physically non-last stored nested zip (#7035) * fix(validate): start ZIP64 footer span at adjacent ZIP64 EOCD record (#7035) * test(validate): regress straddling ZIP64 footer and embedded ZIP64 clearance (#7035)
This commit is contained in:
+238
-50
@@ -858,12 +858,13 @@ fn decode_zip_name<'a>(mut raw: &'a [u8], utf8: bool, extra: &'a [u8]) -> Option
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject records the reader cannot include in its central table. `by_index_raw`
|
||||
/// would parse local headers, initialize data-start caches and seek the archive;
|
||||
/// do not make directory identity depend on opening a part a second time.
|
||||
/// The walk already bounds these fields to their 16-bit lengths. Reader-rejected
|
||||
/// metadata leaves identity unknown rather than allowing a retry to invent duplicates.
|
||||
fn reader_accepts_central_record(header: &[u8], extra: &[u8], comment: &[u8], directory_start: u64) -> Option<()> {
|
||||
/// Reject records the reader cannot include in its central table, returning the resolved
|
||||
/// `(local_header_offset, compressed_size)` pair on acceptance. `by_index_raw` would parse local
|
||||
/// headers, initialize data-start caches and seek the archive; do not make directory identity
|
||||
/// depend on opening a part a second time. The walk already bounds these fields to their 16-bit
|
||||
/// lengths. Reader-rejected metadata leaves identity unknown rather than allowing a retry to
|
||||
/// invent duplicates.
|
||||
fn reader_accepts_central_record(header: &[u8], extra: &[u8], comment: &[u8], directory_start: u64) -> Option<(u64, u64)> {
|
||||
let mut local = u64::from(u32_at(header, 42)?);
|
||||
let mut compressed = u64::from(u32_at(header, 20)?);
|
||||
let mut uncompressed = u64::from(u32_at(header, 24)?);
|
||||
@@ -932,7 +933,7 @@ fn reader_accepts_central_record(header: &[u8], extra: &[u8], comment: &[u8], di
|
||||
}
|
||||
// The reader checks the final method after applying AES extra fields and the
|
||||
// final ZIP64 local offset before accepting this record into its table.
|
||||
if (method == 99 && !aes) || local >= directory_start { None } else { Some(()) }
|
||||
if (method == 99 && !aes) || local >= directory_start { None } else { Some((local, compressed)) }
|
||||
}
|
||||
|
||||
/// CP437's upper half; ASCII/control bytes in the lower half keep their byte values.
|
||||
@@ -986,15 +987,22 @@ fn reader_checked_directory<'a>(
|
||||
) -> (Option<CentralDirectory<'a>>, bool) {
|
||||
let selection = find_eocd(bytes);
|
||||
let cd = selection.as_ref().and_then(|selected| central_directory(bytes, limit, selected));
|
||||
let structural_disagreement = selection.as_ref().is_some_and(|selected| {
|
||||
let reader_matches = cd.as_ref().is_some_and(|dir| dir.consistent && directory_matches_reader(dir, zip));
|
||||
let disputed = selection.as_ref().is_some_and(|selected| {
|
||||
selected.disputed
|
||||
|| (cd.is_none()
|
||||
&& !(selected.exact_end
|
||||
&& reader_matches
|
||||
&& cd.as_ref().is_some_and(|dir| !dir.truncated && competing_footers_unreachable(bytes, selected, dir)))
|
||||
});
|
||||
let structural_disagreement = disputed
|
||||
|| selection.as_ref().is_some_and(|selected| {
|
||||
cd.is_none()
|
||||
&& selected
|
||||
.directory
|
||||
.as_ref()
|
||||
.is_some_and(|directory| usize::try_from(directory.start).ok().and_then(|start| u32_at(bytes, start)) == Some(0x0201_4B50)))
|
||||
});
|
||||
if structural_disagreement || cd.as_ref().is_some_and(|dir| !dir.consistent || !directory_matches_reader(dir, zip)) {
|
||||
.is_some_and(|directory| usize::try_from(directory.start).ok().and_then(|start| u32_at(bytes, start)) == Some(0x0201_4B50))
|
||||
});
|
||||
if structural_disagreement || cd.as_ref().is_some_and(|_| !reader_matches) {
|
||||
// A different directory or an inconsistent count can invent duplicates even when
|
||||
// decoded names and the residual agree. No finding may rely on those identities.
|
||||
acc.note("the zip central directory's selection or decoded names disagree with the reader; entry identities are unknown and dependent absence checks were skipped".to_string());
|
||||
@@ -1107,14 +1115,24 @@ impl DirectoryView {
|
||||
}
|
||||
}
|
||||
|
||||
struct EocdCandidate {
|
||||
/// Start of the footer span (the adjacent ZIP64 EOCD record when present, else the ZIP64
|
||||
/// locator 20 bytes before the EOCD when attached, else the EOCD itself).
|
||||
span_start: usize,
|
||||
/// Exclusive end of the EOCD comment (`eocd + 22 + comment_len`).
|
||||
comment_end: usize,
|
||||
directory: Option<DirectoryView>,
|
||||
}
|
||||
|
||||
struct EocdSelection {
|
||||
directory: Option<DirectoryView>,
|
||||
/// Whether the first (latest) selected candidate's comment ended at EOF.
|
||||
exact_end: bool,
|
||||
disputed: bool,
|
||||
}
|
||||
|
||||
/// The locator-targeted ZIP64 record only; never follow the reader's forward scan.
|
||||
fn zip64_directory(bytes: &[u8], eocd: usize) -> Option<DirectoryView> {
|
||||
let locator = eocd.checked_sub(20)?;
|
||||
/// Outer-file offset of an adjacent ZIP64 EOCD record referenced by `locator`.
|
||||
fn zip64_adjacent_record_start(bytes: &[u8], locator: usize) -> Option<usize> {
|
||||
if u32_at(bytes, locator)? != 0x0706_4B50 {
|
||||
return None;
|
||||
}
|
||||
@@ -1124,13 +1142,16 @@ fn zip64_directory(bytes: &[u8], eocd: usize) -> Option<DirectoryView> {
|
||||
return None;
|
||||
}
|
||||
let size = u64_at(bytes, off + 4)?;
|
||||
let count = u64_at(bytes, off + 32)?;
|
||||
let cd_off = u64_at(bytes, off + 48)?;
|
||||
// The locator is only a hint to the reader. A non-adjacent record can steer this
|
||||
// parser to a decoy; reject it rather than following the reader's forward scan.
|
||||
if size < 44
|
||||
|| size.checked_add(12)? != expected
|
||||
|| u32_at(bytes, locator + 16)? > 1
|
||||
(size >= 44 && size.checked_add(12)? == expected).then_some(off)
|
||||
}
|
||||
|
||||
/// The locator-targeted ZIP64 record only; never follow the reader's forward scan.
|
||||
fn zip64_directory(bytes: &[u8], locator: usize, off: usize) -> Option<DirectoryView> {
|
||||
let count = u64_at(bytes, off + 32)?;
|
||||
let cd_off = u64_at(bytes, off + 48)?;
|
||||
if u32_at(bytes, locator + 16)? > 1
|
||||
|| u32_at(bytes, off + 20)? != u32_at(bytes, locator + 4)?
|
||||
|| u32_at(bytes, off + 16)? != u32_at(bytes, off + 20)?
|
||||
|| u64_at(bytes, off + 24)? > count
|
||||
@@ -1142,6 +1163,198 @@ fn zip64_directory(bytes: &[u8], eocd: usize) -> Option<DirectoryView> {
|
||||
Some(DirectoryView { start: cd_off, count, zip64: true, footer_consistent: true })
|
||||
}
|
||||
|
||||
/// Inspect a single EOCD signature at `i`, advancing `last_header` backward as needed.
|
||||
/// Returns `None` when `i` is not a finder-acceptable candidate.
|
||||
fn eocd_candidate_at(bytes: &[u8], i: usize, last_header: &mut Option<usize>) -> Option<EocdCandidate> {
|
||||
const CDFH: [u8; 4] = [0x50, 0x4B, 0x01, 0x02];
|
||||
let comment_end = i.checked_add(22)?.checked_add(usize::from(u16_at(bytes, i + 20)?))?;
|
||||
if comment_end > bytes.len() {
|
||||
return None;
|
||||
}
|
||||
if last_header.is_some_and(|header| header.checked_add(4).is_none_or(|after| after > i)) {
|
||||
*last_header = bytes.get(..i)?.windows(4).rposition(|w| w == CDFH);
|
||||
}
|
||||
let total = u64::from(u16_at(bytes, i + 10)?);
|
||||
let offset = u64::from(u32_at(bytes, i + 16)?);
|
||||
let locator =
|
||||
(total == 0xFFFF || offset == 0xFFFF_FFFF).then(|| i.checked_sub(20)).flatten().filter(|&loc| u32_at(bytes, loc) == Some(0x0706_4B50));
|
||||
let (directory, span_start) = if let Some(loc) = locator {
|
||||
// An unsupported locator target is not permission to choose an earlier
|
||||
// footer: the reader may accept it by scanning. Keep identity unknown.
|
||||
match zip64_adjacent_record_start(bytes, loc) {
|
||||
Some(record_off) => (zip64_directory(bytes, loc, record_off), record_off),
|
||||
None => (None, loc),
|
||||
}
|
||||
} else {
|
||||
if total != 0
|
||||
&& (offset >= u64::try_from(i).ok()? || !last_header.is_some_and(|header| u64::try_from(header).is_ok_and(|header| header >= offset)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// read.rs uses files-on-this-disk for ZIP32, not the total field.
|
||||
let count = u64::from(u16_at(bytes, i + 8)?);
|
||||
let dir = DirectoryView {
|
||||
start: offset,
|
||||
count,
|
||||
zip64: false,
|
||||
// Disk mismatch is rejected only after spec.rs selects this footer.
|
||||
// Reject its identities rather than silently selecting an earlier one.
|
||||
footer_consistent: count == total && u16_at(bytes, i + 4)? == u16_at(bytes, i + 6)?,
|
||||
};
|
||||
(Some(dir), i)
|
||||
};
|
||||
Some(EocdCandidate { span_start, comment_end, directory })
|
||||
}
|
||||
|
||||
/// Resolve the local header's compressed size, following the local ZIP64 extra field
|
||||
/// when the 32-bit field holds the `0xFFFF_FFFF` sentinel.
|
||||
fn local_compressed_size(local_header: &[u8], local_extra: &[u8]) -> Option<u64> {
|
||||
let raw = u32_at(local_header, 18)?;
|
||||
if raw != u32::MAX {
|
||||
return Some(u64::from(raw));
|
||||
}
|
||||
let mut offset = 0usize;
|
||||
while offset < local_extra.len() {
|
||||
let tag = u16_at(local_extra, offset)?;
|
||||
let len = usize::from(u16_at(local_extra, offset + 2)?);
|
||||
offset = offset.checked_add(4)?;
|
||||
let end = offset.checked_add(len)?;
|
||||
let field = local_extra.get(offset..end)?;
|
||||
if tag == 0x0001 {
|
||||
// APPNOTE §4.5.3: local ZIP64 extra field stores uncompressed (0..8) then compressed (8..16).
|
||||
return u64_at(field, 8);
|
||||
}
|
||||
offset = end;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Verified `[data_start, data_end)` payload range for one central-directory record.
|
||||
/// Confirms local header signature, filename bytes, compression method, data-descriptor flag
|
||||
/// consistency, and compressed-size agreement (allowing zeroed local sizes when the
|
||||
/// data-descriptor flag is set), while permitting legitimate local vs central extra-field
|
||||
/// differences. Bounded strictly before the central directory.
|
||||
fn entry_payload_span(
|
||||
bytes: &[u8],
|
||||
local_offset: u64,
|
||||
compressed_size: u64,
|
||||
central_header: &[u8],
|
||||
central_name: &[u8],
|
||||
directory_start: u64,
|
||||
) -> Option<(usize, usize)> {
|
||||
let local = usize::try_from(local_offset).ok()?;
|
||||
let local_header = bytes.get(local..local.checked_add(30)?)?;
|
||||
if u32_at(local_header, 0)? != 0x0403_4B50 {
|
||||
return None;
|
||||
}
|
||||
let name_len = usize::from(u16_at(local_header, 26)?);
|
||||
let extra_len = usize::from(u16_at(local_header, 28)?);
|
||||
let name_start = local.checked_add(30)?;
|
||||
let name_end = name_start.checked_add(name_len)?;
|
||||
if bytes.get(name_start..name_end)? != central_name {
|
||||
return None;
|
||||
}
|
||||
let data_start = name_end.checked_add(extra_len)?;
|
||||
let local_extra = bytes.get(name_end..data_start)?;
|
||||
if u16_at(local_header, 8)? != u16_at(central_header, 10)? {
|
||||
return None;
|
||||
}
|
||||
let local_dd = u16_at(local_header, 6)? & 0x0008 != 0;
|
||||
let central_dd = u16_at(central_header, 8)? & 0x0008 != 0;
|
||||
if local_dd != central_dd {
|
||||
return None;
|
||||
}
|
||||
if local_dd {
|
||||
let zeroed_local = u32_at(local_header, 18)? == 0 && u32_at(local_header, 22)? == 0;
|
||||
if !zeroed_local && local_compressed_size(local_header, local_extra)? != compressed_size {
|
||||
return None;
|
||||
}
|
||||
} else if local_compressed_size(local_header, local_extra)? != compressed_size {
|
||||
return None;
|
||||
}
|
||||
let compressed = usize::try_from(compressed_size).ok()?;
|
||||
let data_end = data_start.checked_add(compressed)?;
|
||||
let cd_start = usize::try_from(directory_start).ok()?;
|
||||
(data_end <= cd_start && data_end <= bytes.len()).then_some((data_start, data_end))
|
||||
}
|
||||
|
||||
/// Verified payload interval of the final record in a complete central directory, provided it is
|
||||
/// also physically last: every preceding central record must have a verified local-header payload
|
||||
/// ending at or before this entry's local header (so no other entry extends past its payload end
|
||||
/// or overlaps it). Only that central-and-physically-last record may shield a competing earlier
|
||||
/// footer.
|
||||
fn final_entry_payload_span(bytes: &[u8], dir: &CentralDirectory) -> Option<(usize, usize)> {
|
||||
if dir.total == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut i = usize::try_from(dir.start).ok()?;
|
||||
let mut max_other_end = 0usize;
|
||||
for idx in 0..dir.total {
|
||||
if u32_at(bytes, i)? != 0x0201_4B50 {
|
||||
return None;
|
||||
}
|
||||
let name_len = usize::from(u16_at(bytes, i + 28)?);
|
||||
let extra_len = usize::from(u16_at(bytes, i + 30)?);
|
||||
let comment_len = usize::from(u16_at(bytes, i + 32)?);
|
||||
let header = bytes.get(i..i + 46)?;
|
||||
let name = bytes.get(i + 46..i + 46 + name_len)?;
|
||||
let extra = bytes.get(i + 46 + name_len..i + 46 + name_len + extra_len)?;
|
||||
let comment = bytes.get(i + 46 + name_len + extra_len..i + 46 + name_len + extra_len + comment_len)?;
|
||||
let next = i.checked_add(46 + name_len + extra_len + comment_len)?;
|
||||
bytes.get(..next)?;
|
||||
let (local, compressed) = reader_accepts_central_record(header, extra, comment, dir.start)?;
|
||||
let (data_start, data_end) = entry_payload_span(bytes, local, compressed, header, name, dir.start)?;
|
||||
if idx + 1 == dir.total {
|
||||
let local_start = usize::try_from(local).ok()?;
|
||||
return (max_other_end <= local_start).then_some((data_start, data_end));
|
||||
}
|
||||
max_other_end = max_other_end.max(data_end);
|
||||
i = next;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether every competing earlier EOCD candidate is provably unreachable: the first (latest)
|
||||
/// candidate already ends at EOF and matched the reader across its full central directory, and
|
||||
/// every disagreeing earlier candidate ends before EOF and lies entirely within the verified
|
||||
/// local-header payload of the central-and-physically-last entry (e.g. a trailing stored nested
|
||||
/// ZIP).
|
||||
fn competing_footers_unreachable(bytes: &[u8], selected: &EocdSelection, dir: &CentralDirectory) -> bool {
|
||||
const SIG: [u8; 4] = [0x50, 0x4B, 0x05, 0x06];
|
||||
const CDFH: [u8; 4] = [0x50, 0x4B, 0x01, 0x02];
|
||||
let Some(first_tuple) = selected.directory.as_ref().map(DirectoryView::tuple) else {
|
||||
return false;
|
||||
};
|
||||
let Some((payload_start, payload_end)) = final_entry_payload_span(bytes, dir) else {
|
||||
return false;
|
||||
};
|
||||
let start = bytes.len().saturating_sub(22 + 0xFFFF);
|
||||
let Some(end) = bytes.len().checked_sub(22) else {
|
||||
return false;
|
||||
};
|
||||
let mut last_header = bytes.get(..end).and_then(|prefix| prefix.windows(4).rposition(|w| w == CDFH));
|
||||
let mut seen_first = false;
|
||||
for i in (start..=end).rev() {
|
||||
if bytes.get(i..i + 4) != Some(&SIG) {
|
||||
continue;
|
||||
}
|
||||
let Some(candidate) = eocd_candidate_at(bytes, i, &mut last_header) else {
|
||||
continue;
|
||||
};
|
||||
if !seen_first {
|
||||
seen_first = true;
|
||||
continue;
|
||||
}
|
||||
if candidate.directory.as_ref().map(DirectoryView::tuple) == Some(first_tuple) {
|
||||
continue;
|
||||
}
|
||||
if candidate.comment_end >= bytes.len() || candidate.span_start < payload_start || candidate.comment_end > payload_end {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
seen_first
|
||||
}
|
||||
|
||||
/// Select in the reader's backward order, then reject competing selection tuples.
|
||||
/// Exact-comment-end remains a layout eligibility guard, never a selection rule:
|
||||
/// removing it would newly parse trailing-data archives frozen as unsupported.
|
||||
@@ -1162,44 +1375,19 @@ fn find_eocd(bytes: &[u8]) -> Option<EocdSelection> {
|
||||
}
|
||||
let comment_end = i.checked_add(22)?.checked_add(usize::from(u16_at(bytes, i + 20)?))?;
|
||||
exact_end |= comment_end == bytes.len();
|
||||
if comment_end > bytes.len() {
|
||||
let Some(candidate) = eocd_candidate_at(bytes, i, &mut last_header) else {
|
||||
continue;
|
||||
}
|
||||
if last_header.is_some_and(|header| header.checked_add(4).is_none_or(|after| after > i)) {
|
||||
last_header = bytes.get(..i)?.windows(4).rposition(|w| w == CDFH);
|
||||
}
|
||||
let total = u64::from(u16_at(bytes, i + 10)?);
|
||||
let offset = u64::from(u32_at(bytes, i + 16)?);
|
||||
let zip64 = (total == 0xFFFF || offset == 0xFFFF_FFFF) && i.checked_sub(20).and_then(|locator| u32_at(bytes, locator)) == Some(0x0706_4B50);
|
||||
let directory = if zip64 {
|
||||
// An unsupported locator target is not permission to choose an earlier
|
||||
// footer: the reader may accept it by scanning. Keep identity unknown.
|
||||
zip64_directory(bytes, i)
|
||||
} else {
|
||||
if total != 0
|
||||
&& (offset >= u64::try_from(i).ok()? || !last_header.is_some_and(|header| u64::try_from(header).is_ok_and(|header| header >= offset)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// read.rs uses files-on-this-disk for ZIP32, not the total field.
|
||||
let count = u64::from(u16_at(bytes, i + 8)?);
|
||||
Some(DirectoryView {
|
||||
start: offset,
|
||||
count,
|
||||
zip64: false,
|
||||
// Disk mismatch is rejected only after spec.rs selects this footer.
|
||||
// Reject its identities rather than silently selecting an earlier one.
|
||||
footer_consistent: count == total && u16_at(bytes, i + 4)? == u16_at(bytes, i + 6)?,
|
||||
})
|
||||
};
|
||||
if let Some(first) = selected.as_mut() {
|
||||
// No tuple can be established for an unsupported ZIP64 target. It
|
||||
// cannot certify agreement with another candidate either.
|
||||
if first.directory.as_ref().map(DirectoryView::tuple) != directory.as_ref().map(DirectoryView::tuple) || directory.is_none() {
|
||||
if first.directory.as_ref().map(DirectoryView::tuple) != candidate.directory.as_ref().map(DirectoryView::tuple)
|
||||
|| candidate.directory.is_none()
|
||||
{
|
||||
first.disputed = true;
|
||||
}
|
||||
} else {
|
||||
selected = Some(EocdSelection { directory, disputed: false });
|
||||
selected = Some(EocdSelection { directory: candidate.directory, exact_end: candidate.comment_end == bytes.len(), disputed: false });
|
||||
}
|
||||
}
|
||||
if exact_end { selected } else { None }
|
||||
|
||||
@@ -140,6 +140,42 @@ fn le16(v: &mut Vec<u8>, x: u16) {
|
||||
fn le32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
fn le64(v: &mut Vec<u8>, x: u64) {
|
||||
v.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
fn write_zip64_eocd(out: &mut Vec<u8>, count: u64, cd_size: u64, cd_off: u64) -> usize {
|
||||
let off = out.len();
|
||||
le32(out, 0x0606_4B50);
|
||||
le64(out, 44);
|
||||
le16(out, 45);
|
||||
le16(out, 45);
|
||||
le32(out, 0);
|
||||
le32(out, 0);
|
||||
le64(out, count);
|
||||
le64(out, count);
|
||||
le64(out, cd_size);
|
||||
le64(out, cd_off);
|
||||
off
|
||||
}
|
||||
fn write_zip64_locator(out: &mut Vec<u8>, z64_off: u64, total_disks: u32) -> usize {
|
||||
let off = out.len();
|
||||
le32(out, 0x0706_4B50);
|
||||
le32(out, 0);
|
||||
le64(out, z64_off);
|
||||
le32(out, total_disks);
|
||||
off
|
||||
}
|
||||
fn plain_zip64(recs: &[Rec]) -> (Vec<u8>, usize, usize) {
|
||||
let mut out = Vec::new();
|
||||
let offs = write_locals(&mut out, recs);
|
||||
let cd = out.len() as u64;
|
||||
write_cd(&mut out, recs, &offs, &all(recs.len()), 0);
|
||||
let size = out.len() as u64 - cd;
|
||||
let z64_off = write_zip64_eocd(&mut out, recs.len() as u64, size, cd);
|
||||
let loc_off = write_zip64_locator(&mut out, z64_off as u64, 1);
|
||||
write_eocd(&mut out, 0xFFFF, 0xFFFF_FFFF, 0xFFFF_FFFF);
|
||||
(out, z64_off, loc_off)
|
||||
}
|
||||
fn write_locals(out: &mut Vec<u8>, recs: &[Rec]) -> Vec<u64> {
|
||||
let mut offs = Vec::new();
|
||||
for r in recs {
|
||||
@@ -366,13 +402,7 @@ fn stored_nested_case(nested: bool) {
|
||||
assert_eq!(a.offset(), 0);
|
||||
assert_eq!(a.central_directory_start(), 4044);
|
||||
let r = run(&format!("stored nested={nested}"), &z);
|
||||
if nested {
|
||||
// The measured ambiguity-retirement run breaks frozen round21/22
|
||||
// outcomes. Keep this disclosed section-5 residual while it still binds.
|
||||
disputed("stored nested residual", &r).unwrap();
|
||||
} else {
|
||||
assert_clean(&r);
|
||||
}
|
||||
assert_clean(&r);
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip() {
|
||||
@@ -382,6 +412,353 @@ fn stored_nested_zip() {
|
||||
fn stored_no_signature_control() {
|
||||
stored_nested_case(false);
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_non_final_entry_stays_disputed() {
|
||||
// High 1: identical in shape to stored_nested_zip, but with one further ordinary part after
|
||||
// the embedded-zip entry so the embedded zip is NOT the final central-directory record.
|
||||
let inner = plain(&clean_recs(false));
|
||||
for (nested, label) in [(false, "non-final control"), (true, "non-final stored nested zip")] {
|
||||
let body = if nested { inner.clone() } else { vec![b'z'; inner.len()] };
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", body));
|
||||
recs.push(rec(b"word/extra.xml", r#"<?xml version="1.0" encoding="UTF-8"?><x/>"#));
|
||||
let z = plain(&recs);
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(z.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 7);
|
||||
assert_eq!(a.offset(), 0);
|
||||
for i in 0..a.len() {
|
||||
let mut f = a.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
}
|
||||
let r = run(label, &z);
|
||||
if nested {
|
||||
disputed(label, &r).unwrap();
|
||||
assert!(r.coverage_notes.iter().any(|n| n.contains("selection or decoded names disagree")));
|
||||
} else {
|
||||
assert_clean(&r);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_cd_last_not_physically_last_stays_disputed() {
|
||||
// Central directory lists the embedded-zip entry last while another entry's data sits
|
||||
// physically after it in the file. Clearance requires the central-last entry to also be
|
||||
// physically last, so the dispute must stay standing.
|
||||
let inner = plain(&clean_recs(false));
|
||||
for (nested, label) in [(false, "cd-last non-physical control"), (true, "cd-last not physically last stored nested zip")] {
|
||||
let body = if nested { inner.clone() } else { vec![b'z'; inner.len()] };
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", body));
|
||||
recs.push(rec(b"word/extra.xml", r#"<?xml version="1.0" encoding="UTF-8"?><x/>"#));
|
||||
let mut z = Vec::new();
|
||||
let offs = write_locals(&mut z, &recs);
|
||||
assert!(offs[6] > offs[5]);
|
||||
let cd = z.len() as u64;
|
||||
write_cd(&mut z, &recs, &offs, &[0, 1, 2, 3, 4, 6, 5], 0);
|
||||
let size = z.len() as u64 - cd;
|
||||
write_eocd(&mut z, recs.len() as u16, size as u32, cd as u32);
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(z.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 7, "{label}");
|
||||
assert_eq!(a.offset(), 0, "{label}");
|
||||
for i in 0..a.len() {
|
||||
let mut f = a.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
}
|
||||
let r = run(label, &z);
|
||||
if nested {
|
||||
disputed(label, &r).unwrap();
|
||||
assert!(r.coverage_notes.iter().any(|n| n.contains("selection or decoded names disagree")), "{label}");
|
||||
} else {
|
||||
assert_clean(&r);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_inconsistent_local_header_stays_disputed() {
|
||||
// High 2: stored_nested_zip shape with the final containing entry's local header made
|
||||
// inconsistent with its central record must keep the dispute standing (Incomplete).
|
||||
let inner = plain(&clean_recs(false));
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner.clone()));
|
||||
let base = plain(&recs);
|
||||
let local = {
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(base.as_slice())).unwrap();
|
||||
a.by_name("word/embeddings/pkg.bin").unwrap().header_start() as usize
|
||||
};
|
||||
assert_eq!(&base[local..local + 4], &[0x50, 0x4B, 0x03, 0x04]);
|
||||
|
||||
// 1. Local compressed size disagrees with central compressed size (no data-descriptor flag).
|
||||
let mut bad_size = base.clone();
|
||||
let wrong_size = (inner.len() as u32).saturating_sub(1);
|
||||
bad_size[local + 18..local + 22].copy_from_slice(&wrong_size.to_le_bytes());
|
||||
|
||||
// 2. Local filename bytes disagree with central record's name (same length, same data_start).
|
||||
let mut bad_name = base.clone();
|
||||
let name_len = u16::from_le_bytes(bad_name[local + 26..local + 28].try_into().unwrap()) as usize;
|
||||
bad_name[local + 30 + name_len - 1] = b'x';
|
||||
|
||||
// 3. Data-descriptor bit set only in local header (central flag remains 0) with zeroed local sizes.
|
||||
let mut bad_dd = base.clone();
|
||||
bad_dd[local + 6..local + 8].copy_from_slice(&0x0008u16.to_le_bytes());
|
||||
bad_dd[local + 18..local + 22].copy_from_slice(&0u32.to_le_bytes());
|
||||
bad_dd[local + 22..local + 26].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
for (label, z) in [
|
||||
("inconsistent local compressed size", bad_size),
|
||||
("inconsistent local filename", bad_name),
|
||||
("inconsistent local data-descriptor flag", bad_dd),
|
||||
] {
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(z.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 6, "{label}");
|
||||
assert_eq!(a.offset(), 0, "{label}");
|
||||
for i in 0..a.len() {
|
||||
let mut f = a.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
}
|
||||
let r = run(label, &z);
|
||||
disputed(label, &r).unwrap();
|
||||
assert!(r.coverage_notes.iter().any(|n| n.contains("selection or decoded names disagree")), "{label}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_legitimate_local_header_variants_pass() {
|
||||
// High 2 positive boundaries: data-descriptor flag with zeroed local sizes and legitimate
|
||||
// local-vs-central extra-field differences must remain accepted for the final entry.
|
||||
let inner = plain(&clean_recs(false));
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner.clone()));
|
||||
|
||||
// Variant 1: data-descriptor flag set in both local and central headers, zeroed local sizes,
|
||||
// trailing 16-byte data descriptor before the central directory.
|
||||
{
|
||||
let mut out = Vec::new();
|
||||
let mut offs = write_locals(&mut out, &recs[..recs.len() - 1]);
|
||||
let last = recs.last().unwrap();
|
||||
offs.push(out.len() as u64);
|
||||
let crc = crc32(&last.body);
|
||||
let len = last.body.len() as u32;
|
||||
le32(&mut out, 0x0403_4B50);
|
||||
le16(&mut out, 20);
|
||||
le16(&mut out, last.flags | 0x0008);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0x21);
|
||||
le32(&mut out, 0);
|
||||
le32(&mut out, 0);
|
||||
le32(&mut out, 0);
|
||||
le16(&mut out, last.name.len() as u16);
|
||||
le16(&mut out, 0);
|
||||
out.extend_from_slice(&last.name);
|
||||
out.extend_from_slice(&last.body);
|
||||
le32(&mut out, 0x0807_4B50);
|
||||
le32(&mut out, crc);
|
||||
le32(&mut out, len);
|
||||
le32(&mut out, len);
|
||||
let cd = out.len() as u64;
|
||||
let mut cd_recs = recs.clone();
|
||||
cd_recs.last_mut().unwrap().flags |= 0x0008;
|
||||
write_cd(&mut out, &cd_recs, &offs, &all(cd_recs.len()), 0);
|
||||
let size = out.len() as u64 - cd;
|
||||
write_eocd(&mut out, cd_recs.len() as u16, size as u32, cd as u32);
|
||||
assert_clean(&run("stored nested zip with data descriptor", &out));
|
||||
}
|
||||
|
||||
// Variant 2: local header carries an extra field absent from the central directory record.
|
||||
{
|
||||
let mut out = Vec::new();
|
||||
let mut offs = write_locals(&mut out, &recs[..recs.len() - 1]);
|
||||
let last = recs.last().unwrap();
|
||||
offs.push(out.len() as u64);
|
||||
let local_extra = [0xFE, 0xCA, 0x04, 0x00, 1, 2, 3, 4];
|
||||
le32(&mut out, 0x0403_4B50);
|
||||
le16(&mut out, 20);
|
||||
le16(&mut out, last.flags);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0x21);
|
||||
le32(&mut out, crc32(&last.body));
|
||||
le32(&mut out, last.body.len() as u32);
|
||||
le32(&mut out, last.body.len() as u32);
|
||||
le16(&mut out, last.name.len() as u16);
|
||||
le16(&mut out, local_extra.len() as u16);
|
||||
out.extend_from_slice(&last.name);
|
||||
out.extend_from_slice(&local_extra);
|
||||
out.extend_from_slice(&last.body);
|
||||
let cd = out.len() as u64;
|
||||
write_cd(&mut out, &recs, &offs, &all(recs.len()), 0);
|
||||
let size = out.len() as u64 - cd;
|
||||
write_eocd(&mut out, recs.len() as u16, size as u32, cd as u32);
|
||||
assert_clean(&run("stored nested zip with local-only extra field", &out));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip64_embedded_final_entry_passes() {
|
||||
// An embedded ZIP64 archive as the central-and-physically-last entry clears cleanly whether
|
||||
// its locator holds an inner-relative offset or an outer-file offset inside the payload.
|
||||
let (inner_rel, inner_z64, inner_loc) = plain_zip64(&clean_recs(false));
|
||||
assert_eq!(zip::ZipArchive::new(Cursor::new(inner_rel.as_slice())).unwrap().len(), 5);
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner_rel.clone()));
|
||||
let z_rel = plain(&recs);
|
||||
let payload_start = {
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(z_rel.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 6);
|
||||
assert_eq!(a.offset(), 0);
|
||||
a.by_name("word/embeddings/pkg.bin").unwrap().data_start() as usize
|
||||
};
|
||||
assert_clean(&run("stored nested zip64 (inner-relative locator)", &z_rel));
|
||||
|
||||
let mut inner_outer = inner_rel;
|
||||
let outer_z64 = (payload_start + inner_z64) as u64;
|
||||
inner_outer[inner_loc + 8..inner_loc + 16].copy_from_slice(&outer_z64.to_le_bytes());
|
||||
recs.pop();
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner_outer));
|
||||
let z_outer = plain(&recs);
|
||||
assert_clean(&run("stored nested zip64 (outer-adjusted record inside payload)", &z_outer));
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip64_record_outside_payload_stays_disputed() {
|
||||
// Comment B: a competing ZIP64 footer whose adjacent ZIP64 EOCD record lies outside the final
|
||||
// entry's payload (in its local-header extra field) while the locator+EOCD start at
|
||||
// payload_start must NOT clear the dispute.
|
||||
for (label, total_disks) in
|
||||
[("straddling zip64 record outside payload (valid metadata)", 1u32), ("straddling zip64 record outside payload (multi-disk locator)", 2u32)]
|
||||
{
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
let mut out = Vec::new();
|
||||
let mut offs = write_locals(&mut out, &recs);
|
||||
let pkg_local = out.len();
|
||||
offs.push(pkg_local as u64);
|
||||
let pkg_name = b"word/embeddings/pkg.bin";
|
||||
let mut local_extra = Vec::new();
|
||||
le16(&mut local_extra, 0xCAFE);
|
||||
le16(&mut local_extra, 56);
|
||||
let z64_rel_in_extra = write_zip64_eocd(&mut local_extra, 1, 46, 0);
|
||||
assert_eq!(local_extra.len(), 60);
|
||||
let payload_start = pkg_local + 30 + pkg_name.len() + local_extra.len();
|
||||
let z64_outer_off = pkg_local + 30 + pkg_name.len() + z64_rel_in_extra;
|
||||
assert_eq!(z64_outer_off + 56, payload_start);
|
||||
|
||||
let mut payload = Vec::new();
|
||||
write_zip64_locator(&mut payload, z64_outer_off as u64, total_disks);
|
||||
write_eocd(&mut payload, 0xFFFF, 0xFFFF_FFFF, 0xFFFF_FFFF);
|
||||
assert_eq!(payload.len(), 42);
|
||||
|
||||
le32(&mut out, 0x0403_4B50);
|
||||
le16(&mut out, 20);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0);
|
||||
le16(&mut out, 0x21);
|
||||
le32(&mut out, crc32(&payload));
|
||||
le32(&mut out, payload.len() as u32);
|
||||
le32(&mut out, payload.len() as u32);
|
||||
le16(&mut out, pkg_name.len() as u16);
|
||||
le16(&mut out, local_extra.len() as u16);
|
||||
out.extend_from_slice(pkg_name);
|
||||
out.extend_from_slice(&local_extra);
|
||||
assert_eq!(out.len(), payload_start);
|
||||
out.extend_from_slice(&payload);
|
||||
|
||||
recs.push(rec(pkg_name, payload));
|
||||
let cd = out.len() as u64;
|
||||
write_cd(&mut out, &recs, &offs, &all(recs.len()), 0);
|
||||
let size = out.len() as u64 - cd;
|
||||
write_eocd(&mut out, recs.len() as u16, size as u32, cd as u32);
|
||||
|
||||
let mut a = zip::ZipArchive::new(Cursor::new(out.as_slice())).unwrap();
|
||||
assert_eq!(a.len(), 6, "{label}");
|
||||
assert_eq!(a.offset(), 0, "{label}");
|
||||
for i in 0..a.len() {
|
||||
let mut f = a.by_index(i).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut buf).unwrap();
|
||||
}
|
||||
let r = run(label, &out);
|
||||
disputed(label, &r).unwrap();
|
||||
assert!(r.coverage_notes.iter().any(|n| n.contains("selection or decoded names disagree")), "{label}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn stored_nested_zip_preserves_outer_defects() {
|
||||
let inner = plain(&clean_recs(false));
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs[2] = rec(b"word/document.xml", doc(&fnref("5")));
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner));
|
||||
let z = plain(&recs);
|
||||
let r = run("stored nested outer defect", &z);
|
||||
assert_eq!(r.verdict, Verdict::Fail);
|
||||
assert_eq!(rules(&r), ["REF-NOTE@word/document.xml"]);
|
||||
assert!(r.checks_run.contains(&"PKG-DUP-ENTRY"));
|
||||
}
|
||||
#[test]
|
||||
fn stored_payload_forged_eof_eocd_stays_disputed() {
|
||||
// An inner EOCD whose comment length is forged to reach the outer EOF extends beyond
|
||||
// the entry's verified payload span and remains reachable by an exact-EOF reader.
|
||||
let mut inner = plain(&clean_recs(false));
|
||||
let mut recs = clean_recs(false);
|
||||
recs[0] = rec(
|
||||
b"[Content_Types].xml",
|
||||
ct(&[("/word/document.xml", CT_MAIN), ("/word/footnotes.xml", CT_FN), ("/word/embeddings/pkg.bin", "application/octet-stream")]),
|
||||
);
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner.clone()));
|
||||
let outer = plain(&recs);
|
||||
let inner_eocd_in_outer = 4044 - 22;
|
||||
let forged_comment = u16::try_from(outer.len() - inner_eocd_in_outer - 22).unwrap();
|
||||
let inner_eocd = inner.len() - 22;
|
||||
inner[inner_eocd + 20..inner_eocd + 22].copy_from_slice(&forged_comment.to_le_bytes());
|
||||
recs.pop();
|
||||
recs.push(rec(b"word/embeddings/pkg.bin", inner));
|
||||
let z = plain(&recs);
|
||||
let r = run("stored payload forged eof eocd", &z);
|
||||
disputed("forged eof eocd inside stored payload", &r).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn gap_eocd_outside_payload_stays_disputed() {
|
||||
// A competing EOCD placed in an unreferenced gap after the central directory is not inside
|
||||
// any entry's verified payload span, so it must keep disputing the outer footer.
|
||||
let recs = clean_recs(false);
|
||||
let mut z = Vec::new();
|
||||
let offs = write_locals(&mut z, &recs);
|
||||
let start = z.len() as u32;
|
||||
write_cd(&mut z, &recs, &offs, &all(recs.len()), 0);
|
||||
let size = z.len() as u32 - start;
|
||||
write_eocd(&mut z, (recs.len() - 1) as u16, size, start);
|
||||
write_eocd(&mut z, recs.len() as u16, size, start);
|
||||
let r = run("gap eocd outside payload", &z);
|
||||
disputed("gap eocd outside payload", &r).unwrap();
|
||||
}
|
||||
fn untyped_case(reverse: bool) {
|
||||
let mut p = with_footnotes(&["1"], &fnref("5"));
|
||||
p.put("[Content_Types].xml", ct(&[("/word/footnotes.xml", CT_FN)]));
|
||||
|
||||
Reference in New Issue
Block a user