1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 //! Utilities for zip handling of APK files.
18
19 use anyhow::{ensure, Result};
20 use bytes::{Buf, BufMut};
21 use std::io::{Read, Seek};
22 use zip::ZipArchive;
23
24 #[cfg(test)]
25 use std::io::SeekFrom;
26
27 const EOCD_SIZE_WITHOUT_COMMENT: usize = 22;
28 const EOCD_CENTRAL_DIRECTORY_SIZE_FIELD_OFFSET: usize = 12;
29 const EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET: usize = 16;
30 /// End of Central Directory signature
31 const EOCD_SIGNATURE: u32 = 0x06054b50;
32 const ZIP64_MARK: u32 = 0xffffffff;
33
34 #[derive(Debug, PartialEq, Eq)]
35 pub struct ZipSections {
36 pub central_directory_offset: u32,
37 pub central_directory_size: u32,
38 pub eocd_offset: u32,
39 pub eocd_size: u32,
40 }
41
42 /// Discover the layout of a zip file.
zip_sections<R: Read + Seek>(mut reader: R) -> Result<(R, ZipSections)>43 pub fn zip_sections<R: Read + Seek>(mut reader: R) -> Result<(R, ZipSections)> {
44 // open a zip to parse EOCD
45 let archive = ZipArchive::new(reader)?;
46 let eocd_size = archive.comment().len() + EOCD_SIZE_WITHOUT_COMMENT;
47 ensure!(archive.offset() == 0, "Invalid ZIP: offset should be 0, but {}.", archive.offset());
48 // retrieve reader back
49 reader = archive.into_inner();
50 // the current position should point EOCD offset
51 let eocd_offset = reader.stream_position()? as u32;
52 let mut eocd = vec![0u8; eocd_size];
53 reader.read_exact(&mut eocd)?;
54 ensure!(
55 (&eocd[0..]).get_u32_le() == EOCD_SIGNATURE,
56 "Invalid ZIP: ZipArchive::new() should point EOCD after reading."
57 );
58 let (central_directory_size, central_directory_offset) = get_central_directory(&eocd)?;
59 ensure!(
60 central_directory_offset != ZIP64_MARK && central_directory_size != ZIP64_MARK,
61 "Unsupported ZIP: ZIP64 is not supported."
62 );
63 ensure!(
64 central_directory_offset + central_directory_size == eocd_offset,
65 "Invalid ZIP: EOCD should follow CD with no extra data or overlap."
66 );
67
68 Ok((
69 reader,
70 ZipSections {
71 central_directory_offset,
72 central_directory_size,
73 eocd_offset,
74 eocd_size: eocd_size as u32,
75 },
76 ))
77 }
78
get_central_directory(buf: &[u8]) -> Result<(u32, u32)>79 fn get_central_directory(buf: &[u8]) -> Result<(u32, u32)> {
80 ensure!(buf.len() >= EOCD_SIZE_WITHOUT_COMMENT, "Invalid EOCD size: {}", buf.len());
81 let mut buf = &buf[EOCD_CENTRAL_DIRECTORY_SIZE_FIELD_OFFSET..];
82 let size = buf.get_u32_le();
83 let offset = buf.get_u32_le();
84 Ok((size, offset))
85 }
86
87 /// Update EOCD's central_directory_offset field.
set_central_directory_offset(buf: &mut [u8], value: u32) -> Result<()>88 pub fn set_central_directory_offset(buf: &mut [u8], value: u32) -> Result<()> {
89 ensure!(buf.len() >= EOCD_SIZE_WITHOUT_COMMENT, "Invalid EOCD size: {}", buf.len());
90 (&mut buf[EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET..]).put_u32_le(value);
91 Ok(())
92 }
93
94 #[cfg(test)]
95 mod tests {
96 use super::*;
97 use crate::testing::assert_contains;
98 use byteorder::{LittleEndian, ReadBytesExt};
99 use std::fs::File;
100 use std::io::{Cursor, Write};
101 use zip::{write::FileOptions, ZipWriter};
102
create_test_zip() -> Cursor<Vec<u8>>103 fn create_test_zip() -> Cursor<Vec<u8>> {
104 let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
105 writer.start_file("testfile", FileOptions::default()).unwrap();
106 writer.write_all(b"testcontent").unwrap();
107 writer.finish().unwrap()
108 }
109
110 #[test]
test_zip_sections()111 fn test_zip_sections() {
112 let (cursor, sections) = zip_sections(create_test_zip()).unwrap();
113 assert_eq!(
114 sections.eocd_offset,
115 (cursor.get_ref().len() - EOCD_SIZE_WITHOUT_COMMENT) as u32
116 );
117 }
118
119 #[test]
test_reject_if_extra_data_between_cd_and_eocd()120 fn test_reject_if_extra_data_between_cd_and_eocd() {
121 // prepare normal zip
122 let buf = create_test_zip().into_inner();
123
124 // insert garbage between CD and EOCD.
125 // by the way, to mock zip-rs, use CD as garbage. This is implementation detail of zip-rs,
126 // which reads CD at (eocd_offset - cd_size) instead of at cd_offset from EOCD.
127 let (pre_eocd, eocd) = buf.split_at(buf.len() - EOCD_SIZE_WITHOUT_COMMENT);
128 let (_, cd_offset) = get_central_directory(eocd).unwrap();
129 let cd = &pre_eocd[cd_offset as usize..];
130
131 // ZipArchive::new() succeeds, but we should reject
132 let res = zip_sections(Cursor::new([pre_eocd, cd, eocd].concat()));
133 assert!(res.is_err());
134 assert_contains(&res.err().unwrap().to_string(), "Invalid ZIP: offset should be 0");
135 }
136
137 #[test]
test_zip_sections_with_apk()138 fn test_zip_sections_with_apk() {
139 let apk = File::open("tests/data/v3-only-with-stamp.apk").unwrap();
140 let (mut reader, sections) = zip_sections(apk).unwrap();
141
142 // Checks Central directory.
143 assert_eq!(
144 sections.central_directory_offset + sections.central_directory_size,
145 sections.eocd_offset
146 );
147
148 // Checks EOCD.
149 reader.seek(SeekFrom::Start(sections.eocd_offset as u64)).unwrap();
150 assert_eq!(reader.read_u32::<LittleEndian>().unwrap(), EOCD_SIGNATURE);
151 assert_eq!(
152 reader.metadata().unwrap().len(),
153 (sections.eocd_offset + sections.eocd_size) as u64
154 );
155 }
156 }
157