blob: ea6d63abcbc7ade672a8db70a2c1e04eebfbb28d [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};
Jooyung Han12a0b702021-08-05 23:20:31 +090020use byteorder::{LittleEndian, ReadBytesExt};
Andrew Walbran117cd5e2021-08-13 11:42:13 +000021use bytes::{Buf, BufMut, Bytes, BytesMut};
Alice Wang5d0f89a2022-09-15 15:06:10 +000022use num_traits::FromPrimitive;
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 Hand8397852021-08-10 16:29:36 +090028use crate::ziputil::{set_central_directory_offset, zip_sections};
Jooyung Han12a0b702021-08-05 23:20:31 +090029
30const APK_SIG_BLOCK_MIN_SIZE: u32 = 32;
31const APK_SIG_BLOCK_MAGIC: u128 = 0x3234206b636f6c4220676953204b5041;
32
Alice Wang5d0f89a2022-09-15 15:06:10 +000033// TODO(b/246254355): Migrates usages of raw signature algorithm id to the enum.
Jooyung Han5b4c70e2021-08-09 16:36:13 +090034pub const SIGNATURE_RSA_PSS_WITH_SHA256: u32 = 0x0101;
35pub const SIGNATURE_RSA_PSS_WITH_SHA512: u32 = 0x0102;
36pub const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0103;
37pub const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: u32 = 0x0104;
38pub const SIGNATURE_ECDSA_WITH_SHA256: u32 = 0x0201;
39pub const SIGNATURE_ECDSA_WITH_SHA512: u32 = 0x0202;
40pub const SIGNATURE_DSA_WITH_SHA256: u32 = 0x0301;
41pub const SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0421;
42pub const SIGNATURE_VERITY_ECDSA_WITH_SHA256: u32 = 0x0423;
43pub const SIGNATURE_VERITY_DSA_WITH_SHA256: u32 = 0x0425;
Jooyung Han12a0b702021-08-05 23:20:31 +090044
Jooyung Hand8397852021-08-10 16:29:36 +090045const CHUNK_SIZE_BYTES: u64 = 1024 * 1024;
46
Alice Wanged79eab2022-09-08 11:16:31 +000047/// The [APK structure] has four major sections:
48///
49/// | Zip contents | APK Signing Block | Central directory | EOCD(End of Central Directory) |
50///
51/// This structure contains the offset/size information of all the sections except the Zip contents.
52///
53/// [APK structure]: https://source.android.com/docs/security/apksigning/v2#apk-signing-block
Jooyung Hand8397852021-08-10 16:29:36 +090054pub struct ApkSections<R> {
55 inner: R,
56 signing_block_offset: u32,
57 signing_block_size: u32,
58 central_directory_offset: u32,
59 central_directory_size: u32,
60 eocd_offset: u32,
61 eocd_size: u32,
Jooyung Han12a0b702021-08-05 23:20:31 +090062}
63
Jooyung Hand8397852021-08-10 16:29:36 +090064impl<R: Read + Seek> ApkSections<R> {
65 pub fn new(reader: R) -> Result<ApkSections<R>> {
Andrew Walbran117cd5e2021-08-13 11:42:13 +000066 let (mut reader, zip_sections) = zip_sections(reader)?;
Jooyung Hand8397852021-08-10 16:29:36 +090067 let (signing_block_offset, signing_block_size) =
Andrew Walbran117cd5e2021-08-13 11:42:13 +000068 find_signing_block(&mut reader, zip_sections.central_directory_offset)?;
Jooyung Hand8397852021-08-10 16:29:36 +090069 Ok(ApkSections {
Andrew Walbran117cd5e2021-08-13 11:42:13 +000070 inner: reader,
Jooyung Hand8397852021-08-10 16:29:36 +090071 signing_block_offset,
72 signing_block_size,
73 central_directory_offset: zip_sections.central_directory_offset,
74 central_directory_size: zip_sections.central_directory_size,
75 eocd_offset: zip_sections.eocd_offset,
76 eocd_size: zip_sections.eocd_size,
77 })
78 }
Jooyung Han5d94bfc2021-08-06 14:07:49 +090079
Jooyung Hand8397852021-08-10 16:29:36 +090080 /// Returns the APK Signature Scheme block contained in the provided file for the given ID
81 /// and the additional information relevant for verifying the block against the file.
82 pub fn find_signature(&mut self, block_id: u32) -> Result<Bytes> {
83 let signing_block = self.bytes(self.signing_block_offset, self.signing_block_size)?;
Jooyung Hand8397852021-08-10 16:29:36 +090084 find_signature_scheme_block(Bytes::from(signing_block), block_id)
85 }
Jooyung Han12a0b702021-08-05 23:20:31 +090086
Jooyung Hand8397852021-08-10 16:29:36 +090087 /// Computes digest with "signature algorithm" over APK contents, central directory, and EOCD.
88 /// 1. The digest of each chunk is computed over the concatenation of byte 0xa5, the chunk’s
89 /// length in bytes (little-endian uint32), and the chunk’s contents.
90 /// 2. The top-level digest is computed over the concatenation of byte 0x5a, the number of
91 /// chunks (little-endian uint32), and the concatenation of digests of the chunks in the
92 /// order the chunks appear in the APK.
93 /// (see https://source.android.com/security/apksigning/v2#integrity-protected-contents)
94 pub fn compute_digest(&mut self, signature_algorithm_id: u32) -> Result<Vec<u8>> {
Alice Wang5d0f89a2022-09-15 15:06:10 +000095 // TODO(b/246254355): Passes the enum SignatureAlgorithmID directly to this method.
96 let signature_algorithm_id = SignatureAlgorithmID::from_u32(signature_algorithm_id)
97 .ok_or_else(|| anyhow!("Unsupported algorithm ID: {}", signature_algorithm_id))?;
Jooyung Hand8397852021-08-10 16:29:36 +090098 let digester = Digester::new(signature_algorithm_id)?;
99
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000100 let mut digests_of_chunks = BytesMut::new();
Jooyung Hand8397852021-08-10 16:29:36 +0900101 let mut chunk_count = 0u32;
102 let mut chunk = vec![0u8; CHUNK_SIZE_BYTES as usize];
103 for data in &[
104 ApkSections::zip_entries,
105 ApkSections::central_directory,
106 ApkSections::eocd_for_verification,
107 ] {
108 let mut data = data(self)?;
109 while data.limit() > 0 {
110 let chunk_size = min(CHUNK_SIZE_BYTES, data.limit());
Chris Wailes641fc4a2021-12-01 15:03:21 -0800111 let slice = &mut chunk[..(chunk_size as usize)];
112 data.read_exact(slice)?;
Jooyung Hand8397852021-08-10 16:29:36 +0900113 digests_of_chunks.put_slice(
Andrew Scullc208eb42022-05-22 16:17:52 +0000114 digester.digest(slice, CHUNK_HEADER_MID, chunk_size as u32)?.as_ref(),
Jooyung Hand8397852021-08-10 16:29:36 +0900115 );
116 chunk_count += 1;
117 }
118 }
Andrew Scullc208eb42022-05-22 16:17:52 +0000119 Ok(digester.digest(&digests_of_chunks, CHUNK_HEADER_TOP, chunk_count)?.as_ref().into())
Jooyung Hand8397852021-08-10 16:29:36 +0900120 }
121
122 fn zip_entries(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
123 scoped_read(&mut self.inner, 0, self.signing_block_offset as u64)
124 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000125
Jooyung Hand8397852021-08-10 16:29:36 +0900126 fn central_directory(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
127 scoped_read(
128 &mut self.inner,
129 self.central_directory_offset as u64,
130 self.central_directory_size as u64,
131 )
132 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000133
Jooyung Hand8397852021-08-10 16:29:36 +0900134 fn eocd_for_verification(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
135 let mut eocd = self.bytes(self.eocd_offset, self.eocd_size)?;
136 // Protection of section 4 (ZIP End of Central Directory) is complicated by the section
137 // containing the offset of ZIP Central Directory. The offset changes when the size of the
138 // APK Signing Block changes, for instance, when a new signature is added. Thus, when
139 // computing digest over the ZIP End of Central Directory, the field containing the offset
140 // of ZIP Central Directory must be treated as containing the offset of the APK Signing
141 // Block.
142 set_central_directory_offset(&mut eocd, self.signing_block_offset)?;
143 Ok(Read::take(Box::new(Cursor::new(eocd)), self.eocd_size as u64))
144 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000145
Jooyung Hand8397852021-08-10 16:29:36 +0900146 fn bytes(&mut self, offset: u32, size: u32) -> Result<Vec<u8>> {
147 self.inner.seek(SeekFrom::Start(offset as u64))?;
148 let mut buf = vec![0u8; size as usize];
149 self.inner.read_exact(&mut buf)?;
150 Ok(buf)
151 }
152}
153
154fn scoped_read<'a, R: Read + Seek>(
155 src: &'a mut R,
156 offset: u64,
157 size: u64,
158) -> Result<Take<Box<dyn Read + 'a>>> {
159 src.seek(SeekFrom::Start(offset))?;
160 Ok(Read::take(Box::new(src), size))
161}
162
163struct Digester {
Alice Wang5d0f89a2022-09-15 15:06:10 +0000164 message_digest: MessageDigest,
Jooyung Hand8397852021-08-10 16:29:36 +0900165}
166
167const CHUNK_HEADER_TOP: &[u8] = &[0x5a];
168const CHUNK_HEADER_MID: &[u8] = &[0xa5];
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000169
Jooyung Hand8397852021-08-10 16:29:36 +0900170impl Digester {
Alice Wang5d0f89a2022-09-15 15:06:10 +0000171 fn new(signature_algorithm_id: SignatureAlgorithmID) -> Result<Digester> {
172 let message_digest =
173 signature_algorithm_id.to_content_digest_algorithm().new_message_digest()?;
174 Ok(Digester { message_digest })
Jooyung Hand8397852021-08-10 16:29:36 +0900175 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000176
Jooyung Hand8397852021-08-10 16:29:36 +0900177 // v2/v3 digests are computed after prepending "header" byte and "size" info.
Andrew Scullc208eb42022-05-22 16:17:52 +0000178 fn digest(&self, data: &[u8], header: &[u8], size: u32) -> Result<DigestBytes> {
Alice Wang5d0f89a2022-09-15 15:06:10 +0000179 let mut hasher = Hasher::new(self.message_digest)?;
Alice Wang98073222022-09-09 14:08:19 +0000180 hasher.update(header)?;
181 hasher.update(&size.to_le_bytes())?;
182 hasher.update(data)?;
183 Ok(hasher.finish()?)
Jooyung Hand8397852021-08-10 16:29:36 +0900184 }
Jooyung Han12a0b702021-08-05 23:20:31 +0900185}
186
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900187fn find_signing_block<T: Read + Seek>(
Jooyung Han12a0b702021-08-05 23:20:31 +0900188 reader: &mut T,
189 central_directory_offset: u32,
Jooyung Hand8397852021-08-10 16:29:36 +0900190) -> Result<(u32, u32)> {
Jooyung Han12a0b702021-08-05 23:20:31 +0900191 // FORMAT:
192 // OFFSET DATA TYPE DESCRIPTION
193 // * @+0 bytes uint64: size in bytes (excluding this field)
194 // * @+8 bytes payload
195 // * @-24 bytes uint64: size in bytes (same as the one above)
196 // * @-16 bytes uint128: magic
Alice Wangaf1d15b2022-09-09 11:09:51 +0000197 ensure!(
198 central_directory_offset >= APK_SIG_BLOCK_MIN_SIZE,
199 "APK too small for APK Signing Block. ZIP Central Directory offset: {}",
200 central_directory_offset
201 );
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900202 reader.seek(SeekFrom::Start((central_directory_offset - 24) as u64))?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900203 let size_in_footer = reader.read_u64::<LittleEndian>()? as u32;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000204 ensure!(
205 reader.read_u128::<LittleEndian>()? == APK_SIG_BLOCK_MAGIC,
206 "No APK Signing Block before ZIP Central Directory"
207 );
Jooyung Han12a0b702021-08-05 23:20:31 +0900208 let total_size = size_in_footer + 8;
209 let signing_block_offset = central_directory_offset
210 .checked_sub(total_size)
211 .ok_or_else(|| anyhow!("APK Signing Block size out of range: {}", size_in_footer))?;
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900212 reader.seek(SeekFrom::Start(signing_block_offset as u64))?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900213 let size_in_header = reader.read_u64::<LittleEndian>()? as u32;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000214 // This corresponds to APK Signature Scheme v3 verification step 1a.
215 ensure!(
216 size_in_header == size_in_footer,
217 "APK Signing Block sizes in header and footer do not match: {} vs {}",
218 size_in_header,
219 size_in_footer
220 );
Jooyung Hand8397852021-08-10 16:29:36 +0900221 Ok((signing_block_offset, total_size))
Jooyung Han12a0b702021-08-05 23:20:31 +0900222}
223
224fn find_signature_scheme_block(buf: Bytes, block_id: u32) -> Result<Bytes> {
225 // FORMAT:
226 // OFFSET DATA TYPE DESCRIPTION
227 // * @+0 bytes uint64: size in bytes (excluding this field)
228 // * @+8 bytes pairs
229 // * @-24 bytes uint64: size in bytes (same as the one above)
230 // * @-16 bytes uint128: magic
231 let mut pairs = buf.slice(8..(buf.len() - 24));
232 let mut entry_count = 0;
233 while pairs.has_remaining() {
234 entry_count += 1;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000235 ensure!(
236 pairs.remaining() >= 8,
237 "Insufficient data to read size of APK Signing Block entry #{}",
238 entry_count
239 );
Jooyung Han12a0b702021-08-05 23:20:31 +0900240 let length = pairs.get_u64_le();
241 let mut pair = pairs.split_to(length as usize);
242 let id = pair.get_u32_le();
243 if id == block_id {
244 return Ok(pair);
245 }
246 }
Alice Wangaf1d15b2022-09-09 11:09:51 +0000247 let context =
248 format!("No APK Signature Scheme block in APK Signing Block with ID: {}", block_id);
249 Err(Error::new(io::Error::from(ErrorKind::NotFound)).context(context))
Jooyung Han12a0b702021-08-05 23:20:31 +0900250}
251
Alice Wanged79eab2022-09-08 11:16:31 +0000252#[cfg(test)]
253mod tests {
254 use super::*;
255 use byteorder::LittleEndian;
256 use std::fs::File;
257 use std::mem::size_of_val;
258
Alice Wangaf1d15b2022-09-09 11:09:51 +0000259 use crate::v3::{to_hex_string, APK_SIGNATURE_SCHEME_V3_BLOCK_ID};
Alice Wang98073222022-09-09 14:08:19 +0000260
Alice Wanged79eab2022-09-08 11:16:31 +0000261 const CENTRAL_DIRECTORY_HEADER_SIGNATURE: u32 = 0x02014b50;
262
263 #[test]
264 fn test_apk_sections() {
265 let apk_file = File::open("tests/data/v3-only-with-ecdsa-sha512-p521.apk").unwrap();
266 let apk_sections = ApkSections::new(apk_file).unwrap();
267 let mut reader = &apk_sections.inner;
268
269 // Checks APK Signing Block.
270 assert_eq!(
271 apk_sections.signing_block_offset + apk_sections.signing_block_size,
272 apk_sections.central_directory_offset
273 );
274 let apk_signature_offset = SeekFrom::Start(
275 apk_sections.central_directory_offset as u64 - size_of_val(&APK_SIG_BLOCK_MAGIC) as u64,
276 );
277 reader.seek(apk_signature_offset).unwrap();
278 assert_eq!(reader.read_u128::<LittleEndian>().unwrap(), APK_SIG_BLOCK_MAGIC);
279
280 // Checks Central directory.
281 assert_eq!(reader.read_u32::<LittleEndian>().unwrap(), CENTRAL_DIRECTORY_HEADER_SIGNATURE);
282 assert_eq!(
283 apk_sections.central_directory_offset + apk_sections.central_directory_size,
284 apk_sections.eocd_offset
285 );
286
287 // Checks EOCD.
288 assert_eq!(
289 reader.metadata().unwrap().len(),
290 (apk_sections.eocd_offset + apk_sections.eocd_size) as u64
291 );
292 }
Alice Wang98073222022-09-09 14:08:19 +0000293
294 #[test]
295 fn test_apk_digest() {
296 let apk_file = File::open("tests/data/v3-only-with-dsa-sha256-1024.apk").unwrap();
297 let mut apk_sections = ApkSections::new(apk_file).unwrap();
298 let digest = apk_sections.compute_digest(SIGNATURE_DSA_WITH_SHA256).unwrap();
299 assert_eq!(
300 "0DF2426EA33AEDAF495D88E5BE0C6A1663FF0A81C5ED12D5B2929AE4B4300F2F",
301 to_hex_string(&digest[..])
302 );
303 }
Alice Wangaf1d15b2022-09-09 11:09:51 +0000304
305 #[test]
306 fn test_apk_sections_cannot_find_signature() {
307 let apk_file = File::open("tests/data/v2-only-two-signers.apk").unwrap();
308 let mut apk_sections = ApkSections::new(apk_file).unwrap();
309 let result = apk_sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID);
310
311 assert!(result.is_err());
312 let error = result.unwrap_err();
313 assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), ErrorKind::NotFound);
314 assert!(
315 error.to_string().contains(&APK_SIGNATURE_SCHEME_V3_BLOCK_ID.to_string()),
316 "Error should contain the block ID: {}",
317 error
318 );
319 }
320
321 #[test]
322 fn test_apk_sections_find_signature() {
323 let apk_file = File::open("tests/data/v3-only-with-dsa-sha256-1024.apk").unwrap();
324 let mut apk_sections = ApkSections::new(apk_file).unwrap();
325 let signature = apk_sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).unwrap();
326
327 let expected_v3_signature_block_size = 1289; // Only for this specific APK
328 assert_eq!(signature.len(), expected_v3_signature_block_size);
329 }
Alice Wanged79eab2022-09-08 11:16:31 +0000330}