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 const EOCD_SIZE_WITHOUT_COMMENT: usize = 22;
25 const EOCD_CENTRAL_DIRECTORY_SIZE_FIELD_OFFSET: usize = 12;
26 const EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET: usize = 16;
27 /// End of Central Directory signature
28 const EOCD_SIGNATURE: u32 = 0x06054b50;
29 const ZIP64_MARK: u32 = 0xffffffff;
30 
31 /// Information about the layout of a zip file.
32 #[derive(Debug, PartialEq, Eq)]
33 pub struct ZipSections {
34     /// Offset within the file of the central directory.
35     pub central_directory_offset: u32,
36     /// Size of the central directory.
37     pub central_directory_size: u32,
38     /// Offset within the file of end of central directory marker.
39     pub eocd_offset: u32,
40     /// Size of the end of central directory marker.
41     pub eocd_size: u32,
42 }
43 
44 /// Discover the layout of a zip file.
zip_sections<R: Read + Seek>(mut reader: R) -> Result<ZipSections>45 pub fn zip_sections<R: Read + Seek>(mut reader: R) -> Result<ZipSections> {
46     // open a zip to parse EOCD
47     let archive = ZipArchive::new(reader)?;
48     let eocd_size = archive.comment().len() + EOCD_SIZE_WITHOUT_COMMENT;
49     ensure!(archive.offset() == 0, "Invalid ZIP: offset should be 0, but {}.", archive.offset());
50     // retrieve reader back
51     reader = archive.into_inner();
52     // the current position should point EOCD offset
53     let eocd_offset = reader.stream_position()? as u32;
54     let mut eocd = vec![0u8; eocd_size];
55     reader.read_exact(&mut eocd)?;
56     ensure!(
57         (&eocd[0..]).get_u32_le() == EOCD_SIGNATURE,
58         "Invalid ZIP: ZipArchive::new() should point EOCD after reading."
59     );
60     let (central_directory_size, central_directory_offset) = get_central_directory(&eocd)?;
61     ensure!(
62         central_directory_offset != ZIP64_MARK && central_directory_size != ZIP64_MARK,
63         "Unsupported ZIP: ZIP64 is not supported."
64     );
65     ensure!(
66         central_directory_offset + central_directory_size == eocd_offset,
67         "Invalid ZIP: EOCD should follow CD with no extra data or overlap."
68     );
69 
70     Ok(ZipSections {
71         central_directory_offset,
72         central_directory_size,
73         eocd_offset,
74         eocd_size: eocd_size as u32,
75     })
76 }
77 
get_central_directory(buf: &[u8]) -> Result<(u32, u32)>78 fn get_central_directory(buf: &[u8]) -> Result<(u32, u32)> {
79     ensure!(buf.len() >= EOCD_SIZE_WITHOUT_COMMENT, "Invalid EOCD size: {}", buf.len());
80     let mut buf = &buf[EOCD_CENTRAL_DIRECTORY_SIZE_FIELD_OFFSET..];
81     let size = buf.get_u32_le();
82     let offset = buf.get_u32_le();
83     Ok((size, offset))
84 }
85 
86 /// Update EOCD's central_directory_offset field.
set_central_directory_offset(buf: &mut [u8], value: u32) -> Result<()>87 pub fn set_central_directory_offset(buf: &mut [u8], value: u32) -> Result<()> {
88     ensure!(buf.len() >= EOCD_SIZE_WITHOUT_COMMENT, "Invalid EOCD size: {}", buf.len());
89     (&mut buf[EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET..]).put_u32_le(value);
90     Ok(())
91 }
92 
93 /// Read an entire file from a .zip file into memory and return it.
read_file<R: Read + Seek>(reader: R, file_name: &str) -> Result<Vec<u8>>94 pub fn read_file<R: Read + Seek>(reader: R, file_name: &str) -> Result<Vec<u8>> {
95     let mut archive = ZipArchive::new(reader)?;
96     let mut file = archive.by_name(file_name)?;
97     let mut bytes = Vec::with_capacity(file.size() as usize);
98     file.read_to_end(&mut bytes)?;
99     Ok(bytes)
100 }
101 
102 #[cfg(test)]
103 mod tests {
104     use super::*;
105     use std::io::{Cursor, Write};
106     use zip::{write::FileOptions, ZipWriter};
107 
108     const FILE_CONTENT: &[u8] = b"testcontent";
109     const FILE_NAME: &str = "testfile";
110 
create_test_zip() -> Cursor<Vec<u8>>111     fn create_test_zip() -> Cursor<Vec<u8>> {
112         let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
113         writer.start_file(FILE_NAME, FileOptions::default()).unwrap();
114         writer.write_all(FILE_CONTENT).unwrap();
115         writer.finish().unwrap()
116     }
117 
assert_contains(haystack: &str, needle: &str)118     fn assert_contains(haystack: &str, needle: &str) {
119         assert!(haystack.contains(needle), "{} is not found in {}", needle, haystack);
120     }
121 
122     #[test]
test_zip_sections()123     fn test_zip_sections() {
124         let mut cursor = create_test_zip();
125         let sections = zip_sections(&mut cursor).unwrap();
126         assert_eq!(
127             sections.eocd_offset,
128             (cursor.get_ref().len() - EOCD_SIZE_WITHOUT_COMMENT) as u32
129         );
130     }
131 
132     #[test]
test_read_file()133     fn test_read_file() {
134         let file = read_file(create_test_zip(), FILE_NAME).unwrap();
135         assert_eq!(file.as_slice(), FILE_CONTENT);
136     }
137 
138     #[test]
test_reject_if_extra_data_between_cd_and_eocd()139     fn test_reject_if_extra_data_between_cd_and_eocd() {
140         // prepare normal zip
141         let buf = create_test_zip().into_inner();
142 
143         // insert garbage between CD and EOCD.
144         // by the way, to mock zip-rs, use CD as garbage. This is implementation detail of zip-rs,
145         // which reads CD at (eocd_offset - cd_size) instead of at cd_offset from EOCD.
146         let (pre_eocd, eocd) = buf.split_at(buf.len() - EOCD_SIZE_WITHOUT_COMMENT);
147         let (_, cd_offset) = get_central_directory(eocd).unwrap();
148         let cd = &pre_eocd[cd_offset as usize..];
149 
150         // ZipArchive::new() succeeds, but we should reject
151         let res = zip_sections(Cursor::new([pre_eocd, cd, eocd].concat()));
152         assert!(res.is_err());
153         assert_contains(&res.err().unwrap().to_string(), "Invalid ZIP: offset should be 0");
154     }
155 }
156