blob: a47b4c5956d0a8bd424e0d4ba43a0b1b2cf9cccf [file] [log] [blame]
Jooyung Han12a0b702021-08-05 23:20:31 +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
17//! Utilities for Signature Verification
18
Alice Wang5d0f89a2022-09-15 15:06:10 +000019use anyhow::{anyhow, ensure, Error, Result};
Alan Stokes068f6d42023-10-09 10:13:03 +010020use apkzip::{set_central_directory_offset, zip_sections};
Jooyung Han12a0b702021-08-05 23:20:31 +090021use byteorder::{LittleEndian, ReadBytesExt};
Andrew Walbran117cd5e2021-08-13 11:42:13 +000022use bytes::{Buf, BufMut, Bytes, BytesMut};
Andrew Scullc208eb42022-05-22 16:17:52 +000023use openssl::hash::{DigestBytes, Hasher, MessageDigest};
Jooyung Hand8397852021-08-10 16:29:36 +090024use std::cmp::min;
Alice Wangaf1d15b2022-09-09 11:09:51 +000025use std::io::{self, Cursor, ErrorKind, Read, Seek, SeekFrom, Take};
Jooyung Han5d94bfc2021-08-06 14:07:49 +090026
Alice Wang5d0f89a2022-09-15 15:06:10 +000027use crate::algorithms::SignatureAlgorithmID;
Jooyung Han12a0b702021-08-05 23:20:31 +090028
29const APK_SIG_BLOCK_MIN_SIZE: u32 = 32;
30const APK_SIG_BLOCK_MAGIC: u128 = 0x3234206b636f6c4220676953204b5041;
31
Jooyung Hand8397852021-08-10 16:29:36 +090032const CHUNK_SIZE_BYTES: u64 = 1024 * 1024;
Alice Wang2ef30742022-09-19 11:59:17 +000033const CHUNK_HEADER_TOP: &[u8] = &[0x5a];
34const CHUNK_HEADER_MID: &[u8] = &[0xa5];
Jooyung Hand8397852021-08-10 16:29:36 +090035
Alice Wanged79eab2022-09-08 11:16:31 +000036/// The [APK structure] has four major sections:
37///
38/// | Zip contents | APK Signing Block | Central directory | EOCD(End of Central Directory) |
39///
40/// This structure contains the offset/size information of all the sections except the Zip contents.
41///
42/// [APK structure]: https://source.android.com/docs/security/apksigning/v2#apk-signing-block
Jooyung Hand8397852021-08-10 16:29:36 +090043pub struct ApkSections<R> {
44 inner: R,
45 signing_block_offset: u32,
46 signing_block_size: u32,
47 central_directory_offset: u32,
48 central_directory_size: u32,
49 eocd_offset: u32,
50 eocd_size: u32,
Jooyung Han12a0b702021-08-05 23:20:31 +090051}
52
Jooyung Hand8397852021-08-10 16:29:36 +090053impl<R: Read + Seek> ApkSections<R> {
Alan Stokesaa2fa5c2023-10-11 16:13:57 +010054 pub fn new(mut reader: R) -> Result<ApkSections<R>> {
55 let zip_sections = zip_sections(&mut reader)?;
Jooyung Hand8397852021-08-10 16:29:36 +090056 let (signing_block_offset, signing_block_size) =
Andrew Walbran117cd5e2021-08-13 11:42:13 +000057 find_signing_block(&mut reader, zip_sections.central_directory_offset)?;
Jooyung Hand8397852021-08-10 16:29:36 +090058 Ok(ApkSections {
Andrew Walbran117cd5e2021-08-13 11:42:13 +000059 inner: reader,
Jooyung Hand8397852021-08-10 16:29:36 +090060 signing_block_offset,
61 signing_block_size,
62 central_directory_offset: zip_sections.central_directory_offset,
63 central_directory_size: zip_sections.central_directory_size,
64 eocd_offset: zip_sections.eocd_offset,
65 eocd_size: zip_sections.eocd_size,
66 })
67 }
Jooyung Han5d94bfc2021-08-06 14:07:49 +090068
Jooyung Hand8397852021-08-10 16:29:36 +090069 /// Returns the APK Signature Scheme block contained in the provided file for the given ID
70 /// and the additional information relevant for verifying the block against the file.
71 pub fn find_signature(&mut self, block_id: u32) -> Result<Bytes> {
72 let signing_block = self.bytes(self.signing_block_offset, self.signing_block_size)?;
Jooyung Hand8397852021-08-10 16:29:36 +090073 find_signature_scheme_block(Bytes::from(signing_block), block_id)
74 }
Jooyung Han12a0b702021-08-05 23:20:31 +090075
Jooyung Hand8397852021-08-10 16:29:36 +090076 /// Computes digest with "signature algorithm" over APK contents, central directory, and EOCD.
77 /// 1. The digest of each chunk is computed over the concatenation of byte 0xa5, the chunk’s
78 /// length in bytes (little-endian uint32), and the chunk’s contents.
79 /// 2. The top-level digest is computed over the concatenation of byte 0x5a, the number of
80 /// chunks (little-endian uint32), and the concatenation of digests of the chunks in the
81 /// order the chunks appear in the APK.
Chris Wailes63b67d72024-08-19 16:23:21 -070082 ///
Jooyung Hand8397852021-08-10 16:29:36 +090083 /// (see https://source.android.com/security/apksigning/v2#integrity-protected-contents)
Alice Wang62353c52022-09-19 12:47:20 +000084 pub(crate) fn compute_digest(
85 &mut self,
86 signature_algorithm_id: SignatureAlgorithmID,
87 ) -> Result<Vec<u8>> {
Alice Wang1ffff622022-09-16 13:45:47 +000088 let digester = Digester { message_digest: signature_algorithm_id.new_message_digest() };
Andrew Walbran117cd5e2021-08-13 11:42:13 +000089 let mut digests_of_chunks = BytesMut::new();
Jooyung Hand8397852021-08-10 16:29:36 +090090 let mut chunk_count = 0u32;
91 let mut chunk = vec![0u8; CHUNK_SIZE_BYTES as usize];
92 for data in &[
93 ApkSections::zip_entries,
94 ApkSections::central_directory,
95 ApkSections::eocd_for_verification,
96 ] {
97 let mut data = data(self)?;
98 while data.limit() > 0 {
99 let chunk_size = min(CHUNK_SIZE_BYTES, data.limit());
Chris Wailes641fc4a2021-12-01 15:03:21 -0800100 let slice = &mut chunk[..(chunk_size as usize)];
101 data.read_exact(slice)?;
Jooyung Hand8397852021-08-10 16:29:36 +0900102 digests_of_chunks.put_slice(
Andrew Scullc208eb42022-05-22 16:17:52 +0000103 digester.digest(slice, CHUNK_HEADER_MID, chunk_size as u32)?.as_ref(),
Jooyung Hand8397852021-08-10 16:29:36 +0900104 );
105 chunk_count += 1;
106 }
107 }
Andrew Scullc208eb42022-05-22 16:17:52 +0000108 Ok(digester.digest(&digests_of_chunks, CHUNK_HEADER_TOP, chunk_count)?.as_ref().into())
Jooyung Hand8397852021-08-10 16:29:36 +0900109 }
110
111 fn zip_entries(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
112 scoped_read(&mut self.inner, 0, self.signing_block_offset as u64)
113 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000114
Jooyung Hand8397852021-08-10 16:29:36 +0900115 fn central_directory(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
116 scoped_read(
117 &mut self.inner,
118 self.central_directory_offset as u64,
119 self.central_directory_size as u64,
120 )
121 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000122
Jooyung Hand8397852021-08-10 16:29:36 +0900123 fn eocd_for_verification(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
124 let mut eocd = self.bytes(self.eocd_offset, self.eocd_size)?;
125 // Protection of section 4 (ZIP End of Central Directory) is complicated by the section
126 // containing the offset of ZIP Central Directory. The offset changes when the size of the
127 // APK Signing Block changes, for instance, when a new signature is added. Thus, when
128 // computing digest over the ZIP End of Central Directory, the field containing the offset
129 // of ZIP Central Directory must be treated as containing the offset of the APK Signing
130 // Block.
131 set_central_directory_offset(&mut eocd, self.signing_block_offset)?;
132 Ok(Read::take(Box::new(Cursor::new(eocd)), self.eocd_size as u64))
133 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000134
Jooyung Hand8397852021-08-10 16:29:36 +0900135 fn bytes(&mut self, offset: u32, size: u32) -> Result<Vec<u8>> {
136 self.inner.seek(SeekFrom::Start(offset as u64))?;
137 let mut buf = vec![0u8; size as usize];
138 self.inner.read_exact(&mut buf)?;
139 Ok(buf)
140 }
141}
142
143fn scoped_read<'a, R: Read + Seek>(
144 src: &'a mut R,
145 offset: u64,
146 size: u64,
147) -> Result<Take<Box<dyn Read + 'a>>> {
148 src.seek(SeekFrom::Start(offset))?;
149 Ok(Read::take(Box::new(src), size))
150}
151
152struct Digester {
Alice Wang5d0f89a2022-09-15 15:06:10 +0000153 message_digest: MessageDigest,
Jooyung Hand8397852021-08-10 16:29:36 +0900154}
155
Jooyung Hand8397852021-08-10 16:29:36 +0900156impl Digester {
Jooyung Hand8397852021-08-10 16:29:36 +0900157 // v2/v3 digests are computed after prepending "header" byte and "size" info.
Andrew Scullc208eb42022-05-22 16:17:52 +0000158 fn digest(&self, data: &[u8], header: &[u8], size: u32) -> Result<DigestBytes> {
Alice Wang5d0f89a2022-09-15 15:06:10 +0000159 let mut hasher = Hasher::new(self.message_digest)?;
Alice Wang98073222022-09-09 14:08:19 +0000160 hasher.update(header)?;
161 hasher.update(&size.to_le_bytes())?;
162 hasher.update(data)?;
163 Ok(hasher.finish()?)
Jooyung Hand8397852021-08-10 16:29:36 +0900164 }
Jooyung Han12a0b702021-08-05 23:20:31 +0900165}
166
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900167fn find_signing_block<T: Read + Seek>(
Jooyung Han12a0b702021-08-05 23:20:31 +0900168 reader: &mut T,
169 central_directory_offset: u32,
Jooyung Hand8397852021-08-10 16:29:36 +0900170) -> Result<(u32, u32)> {
Jooyung Han12a0b702021-08-05 23:20:31 +0900171 // FORMAT:
172 // OFFSET DATA TYPE DESCRIPTION
173 // * @+0 bytes uint64: size in bytes (excluding this field)
174 // * @+8 bytes payload
175 // * @-24 bytes uint64: size in bytes (same as the one above)
176 // * @-16 bytes uint128: magic
Alice Wangaf1d15b2022-09-09 11:09:51 +0000177 ensure!(
178 central_directory_offset >= APK_SIG_BLOCK_MIN_SIZE,
179 "APK too small for APK Signing Block. ZIP Central Directory offset: {}",
180 central_directory_offset
181 );
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900182 reader.seek(SeekFrom::Start((central_directory_offset - 24) as u64))?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900183 let size_in_footer = reader.read_u64::<LittleEndian>()? as u32;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000184 ensure!(
185 reader.read_u128::<LittleEndian>()? == APK_SIG_BLOCK_MAGIC,
186 "No APK Signing Block before ZIP Central Directory"
187 );
Jooyung Han12a0b702021-08-05 23:20:31 +0900188 let total_size = size_in_footer + 8;
189 let signing_block_offset = central_directory_offset
190 .checked_sub(total_size)
191 .ok_or_else(|| anyhow!("APK Signing Block size out of range: {}", size_in_footer))?;
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900192 reader.seek(SeekFrom::Start(signing_block_offset as u64))?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900193 let size_in_header = reader.read_u64::<LittleEndian>()? as u32;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000194 // This corresponds to APK Signature Scheme v3 verification step 1a.
195 ensure!(
196 size_in_header == size_in_footer,
197 "APK Signing Block sizes in header and footer do not match: {} vs {}",
198 size_in_header,
199 size_in_footer
200 );
Jooyung Hand8397852021-08-10 16:29:36 +0900201 Ok((signing_block_offset, total_size))
Jooyung Han12a0b702021-08-05 23:20:31 +0900202}
203
204fn find_signature_scheme_block(buf: Bytes, block_id: u32) -> Result<Bytes> {
205 // FORMAT:
206 // OFFSET DATA TYPE DESCRIPTION
207 // * @+0 bytes uint64: size in bytes (excluding this field)
208 // * @+8 bytes pairs
209 // * @-24 bytes uint64: size in bytes (same as the one above)
210 // * @-16 bytes uint128: magic
211 let mut pairs = buf.slice(8..(buf.len() - 24));
212 let mut entry_count = 0;
213 while pairs.has_remaining() {
214 entry_count += 1;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000215 ensure!(
216 pairs.remaining() >= 8,
217 "Insufficient data to read size of APK Signing Block entry #{}",
218 entry_count
219 );
Jooyung Han12a0b702021-08-05 23:20:31 +0900220 let length = pairs.get_u64_le();
221 let mut pair = pairs.split_to(length as usize);
222 let id = pair.get_u32_le();
223 if id == block_id {
224 return Ok(pair);
225 }
226 }
Alice Wangaf1d15b2022-09-09 11:09:51 +0000227 let context =
228 format!("No APK Signature Scheme block in APK Signing Block with ID: {}", block_id);
229 Err(Error::new(io::Error::from(ErrorKind::NotFound)).context(context))
Jooyung Han12a0b702021-08-05 23:20:31 +0900230}
231
Alice Wanged79eab2022-09-08 11:16:31 +0000232#[cfg(test)]
233mod tests {
234 use super::*;
235 use byteorder::LittleEndian;
236 use std::fs::File;
237 use std::mem::size_of_val;
238
Tanmoy Mollik40ff8032022-11-25 15:00:04 +0000239 use crate::v3::APK_SIGNATURE_SCHEME_V3_BLOCK_ID;
Alice Wang98073222022-09-09 14:08:19 +0000240
Alice Wanged79eab2022-09-08 11:16:31 +0000241 const CENTRAL_DIRECTORY_HEADER_SIGNATURE: u32 = 0x02014b50;
242
243 #[test]
244 fn test_apk_sections() {
245 let apk_file = File::open("tests/data/v3-only-with-ecdsa-sha512-p521.apk").unwrap();
246 let apk_sections = ApkSections::new(apk_file).unwrap();
247 let mut reader = &apk_sections.inner;
248
249 // Checks APK Signing Block.
250 assert_eq!(
251 apk_sections.signing_block_offset + apk_sections.signing_block_size,
252 apk_sections.central_directory_offset
253 );
254 let apk_signature_offset = SeekFrom::Start(
255 apk_sections.central_directory_offset as u64 - size_of_val(&APK_SIG_BLOCK_MAGIC) as u64,
256 );
257 reader.seek(apk_signature_offset).unwrap();
258 assert_eq!(reader.read_u128::<LittleEndian>().unwrap(), APK_SIG_BLOCK_MAGIC);
259
260 // Checks Central directory.
261 assert_eq!(reader.read_u32::<LittleEndian>().unwrap(), CENTRAL_DIRECTORY_HEADER_SIGNATURE);
262 assert_eq!(
263 apk_sections.central_directory_offset + apk_sections.central_directory_size,
264 apk_sections.eocd_offset
265 );
266
267 // Checks EOCD.
268 assert_eq!(
269 reader.metadata().unwrap().len(),
270 (apk_sections.eocd_offset + apk_sections.eocd_size) as u64
271 );
272 }
Alice Wang98073222022-09-09 14:08:19 +0000273
274 #[test]
275 fn test_apk_digest() {
276 let apk_file = File::open("tests/data/v3-only-with-dsa-sha256-1024.apk").unwrap();
277 let mut apk_sections = ApkSections::new(apk_file).unwrap();
Alice Wang62353c52022-09-19 12:47:20 +0000278 let digest = apk_sections.compute_digest(SignatureAlgorithmID::DsaWithSha256).unwrap();
Alice Wang98073222022-09-09 14:08:19 +0000279 assert_eq!(
Tanmoy Mollik40ff8032022-11-25 15:00:04 +0000280 "0df2426ea33aedaf495d88e5be0c6a1663ff0a81c5ed12d5b2929ae4b4300f2f",
281 hex::encode(&digest[..])
Alice Wang98073222022-09-09 14:08:19 +0000282 );
283 }
Alice Wangaf1d15b2022-09-09 11:09:51 +0000284
285 #[test]
286 fn test_apk_sections_cannot_find_signature() {
287 let apk_file = File::open("tests/data/v2-only-two-signers.apk").unwrap();
288 let mut apk_sections = ApkSections::new(apk_file).unwrap();
289 let result = apk_sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID);
290
291 assert!(result.is_err());
292 let error = result.unwrap_err();
293 assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), ErrorKind::NotFound);
294 assert!(
295 error.to_string().contains(&APK_SIGNATURE_SCHEME_V3_BLOCK_ID.to_string()),
296 "Error should contain the block ID: {}",
297 error
298 );
299 }
300
301 #[test]
302 fn test_apk_sections_find_signature() {
303 let apk_file = File::open("tests/data/v3-only-with-dsa-sha256-1024.apk").unwrap();
304 let mut apk_sections = ApkSections::new(apk_file).unwrap();
305 let signature = apk_sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).unwrap();
306
307 let expected_v3_signature_block_size = 1289; // Only for this specific APK
308 assert_eq!(signature.len(), expected_v3_signature_block_size);
309 }
Alice Wanged79eab2022-09-08 11:16:31 +0000310}