blob: 5e513a7b89d0c133f25d4f63d1f8beb50881b0b1 [file] [log] [blame]
Jooyung Han5d94bfc2021-08-06 14:07:49 +09001/*
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
Alice Wanged79eab2022-09-08 11:16:31 +000017//! Utilities for zip handling of APK files.
Jooyung Han5d94bfc2021-08-06 14:07:49 +090018
Alice Wangbc4b9a92022-09-16 13:13:18 +000019use anyhow::{ensure, Result};
Jooyung Hand8397852021-08-10 16:29:36 +090020use bytes::{Buf, BufMut};
Chris Wailes738be142023-02-14 16:06:32 -080021use std::io::{Read, Seek};
Jooyung Han5d94bfc2021-08-06 14:07:49 +090022use zip::ZipArchive;
23
Chris Wailes738be142023-02-14 16:06:32 -080024#[cfg(test)]
25use std::io::SeekFrom;
26
Alice Wanged79eab2022-09-08 11:16:31 +000027const EOCD_SIZE_WITHOUT_COMMENT: usize = 22;
Jooyung Hancee6de62021-08-11 15:52:07 +090028const EOCD_CENTRAL_DIRECTORY_SIZE_FIELD_OFFSET: usize = 12;
Jooyung Han5d94bfc2021-08-06 14:07:49 +090029const EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET: usize = 16;
Alice Wanged79eab2022-09-08 11:16:31 +000030/// End of Central Directory signature
31const EOCD_SIGNATURE: u32 = 0x06054b50;
Jooyung Hancee6de62021-08-11 15:52:07 +090032const ZIP64_MARK: u32 = 0xffffffff;
Jooyung Han5d94bfc2021-08-06 14:07:49 +090033
Chris Wailes6f5a9b52022-08-11 15:01:54 -070034#[derive(Debug, PartialEq, Eq)]
Jooyung Han5d94bfc2021-08-06 14:07:49 +090035pub 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.
43pub 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)?;
Alice Wanged79eab2022-09-08 11:16:31 +000046 let eocd_size = archive.comment().len() + EOCD_SIZE_WITHOUT_COMMENT;
Alice Wangbc4b9a92022-09-16 13:13:18 +000047 ensure!(archive.offset() == 0, "Invalid ZIP: offset should be 0, but {}.", archive.offset());
Jooyung Han5d94bfc2021-08-06 14:07:49 +090048 // retrieve reader back
49 reader = archive.into_inner();
50 // the current position should point EOCD offset
Chris Wailes738be142023-02-14 16:06:32 -080051 let eocd_offset = reader.stream_position()? as u32;
Charisee96113f32023-01-26 09:00:42 +000052 let mut eocd = vec![0u8; eocd_size];
Jooyung Han5d94bfc2021-08-06 14:07:49 +090053 reader.read_exact(&mut eocd)?;
Alice Wangbc4b9a92022-09-16 13:13:18 +000054 ensure!(
55 (&eocd[0..]).get_u32_le() == EOCD_SIGNATURE,
56 "Invalid ZIP: ZipArchive::new() should point EOCD after reading."
57 );
Jooyung Hancee6de62021-08-11 15:52:07 +090058 let (central_directory_size, central_directory_offset) = get_central_directory(&eocd)?;
Alice Wangbc4b9a92022-09-16 13:13:18 +000059 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 );
Jooyung Hancee6de62021-08-11 15:52:07 +090067
Jooyung Han5d94bfc2021-08-06 14:07:49 +090068 Ok((
69 reader,
70 ZipSections {
71 central_directory_offset,
72 central_directory_size,
Jooyung Hancee6de62021-08-11 15:52:07 +090073 eocd_offset,
Jooyung Han5d94bfc2021-08-06 14:07:49 +090074 eocd_size: eocd_size as u32,
75 },
76 ))
77}
78
Jooyung Hancee6de62021-08-11 15:52:07 +090079fn get_central_directory(buf: &[u8]) -> Result<(u32, u32)> {
Alice Wangbc4b9a92022-09-16 13:13:18 +000080 ensure!(buf.len() >= EOCD_SIZE_WITHOUT_COMMENT, "Invalid EOCD size: {}", buf.len());
Jooyung Hancee6de62021-08-11 15:52:07 +090081 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))
Jooyung Han5d94bfc2021-08-06 14:07:49 +090085}
Jooyung Hand8397852021-08-10 16:29:36 +090086
87/// Update EOCD's central_directory_offset field.
88pub fn set_central_directory_offset(buf: &mut [u8], value: u32) -> Result<()> {
Alice Wangbc4b9a92022-09-16 13:13:18 +000089 ensure!(buf.len() >= EOCD_SIZE_WITHOUT_COMMENT, "Invalid EOCD size: {}", buf.len());
Jooyung Hand8397852021-08-10 16:29:36 +090090 (&mut buf[EOCD_CENTRAL_DIRECTORY_OFFSET_FIELD_OFFSET..]).put_u32_le(value);
91 Ok(())
92}
Jooyung Hancee6de62021-08-11 15:52:07 +090093
94#[cfg(test)]
95mod tests {
96 use super::*;
Andrew Walbran117cd5e2021-08-13 11:42:13 +000097 use crate::testing::assert_contains;
Alice Wanged79eab2022-09-08 11:16:31 +000098 use byteorder::{LittleEndian, ReadBytesExt};
99 use std::fs::File;
Jooyung Hancee6de62021-08-11 15:52:07 +0900100 use std::io::{Cursor, Write};
101 use zip::{write::FileOptions, ZipWriter};
102
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]
111 fn test_zip_sections() {
112 let (cursor, sections) = zip_sections(create_test_zip()).unwrap();
Alice Wanged79eab2022-09-08 11:16:31 +0000113 assert_eq!(
114 sections.eocd_offset,
115 (cursor.get_ref().len() - EOCD_SIZE_WITHOUT_COMMENT) as u32
116 );
Jooyung Hancee6de62021-08-11 15:52:07 +0900117 }
118
119 #[test]
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.
Alice Wanged79eab2022-09-08 11:16:31 +0000127 let (pre_eocd, eocd) = buf.split_at(buf.len() - EOCD_SIZE_WITHOUT_COMMENT);
Jooyung Hancee6de62021-08-11 15:52:07 +0900128 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());
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000134 assert_contains(&res.err().unwrap().to_string(), "Invalid ZIP: offset should be 0");
Jooyung Hancee6de62021-08-11 15:52:07 +0900135 }
Alice Wanged79eab2022-09-08 11:16:31 +0000136
137 #[test]
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 }
Jooyung Hancee6de62021-08-11 15:52:07 +0900156}