blob: 6a7ce324710c9478b1a53e3a2a85283c4d11d64d [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 Wangaf1d15b2022-09-09 11:09:51 +000019use anyhow::{anyhow, bail, 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};
Andrew Scullc208eb42022-05-22 16:17:52 +000022use openssl::hash::{DigestBytes, Hasher, MessageDigest};
Jooyung Hand8397852021-08-10 16:29:36 +090023use std::cmp::min;
Alice Wangaf1d15b2022-09-09 11:09:51 +000024use std::io::{self, Cursor, ErrorKind, Read, Seek, SeekFrom, Take};
Jooyung Han5d94bfc2021-08-06 14:07:49 +090025
Jooyung Hand8397852021-08-10 16:29:36 +090026use crate::ziputil::{set_central_directory_offset, zip_sections};
Jooyung Han12a0b702021-08-05 23:20:31 +090027
28const APK_SIG_BLOCK_MIN_SIZE: u32 = 32;
29const APK_SIG_BLOCK_MAGIC: u128 = 0x3234206b636f6c4220676953204b5041;
30
31// TODO(jooyung): introduce type
Jooyung Han5b4c70e2021-08-09 16:36:13 +090032pub const SIGNATURE_RSA_PSS_WITH_SHA256: u32 = 0x0101;
33pub const SIGNATURE_RSA_PSS_WITH_SHA512: u32 = 0x0102;
34pub const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0103;
35pub const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: u32 = 0x0104;
36pub const SIGNATURE_ECDSA_WITH_SHA256: u32 = 0x0201;
37pub const SIGNATURE_ECDSA_WITH_SHA512: u32 = 0x0202;
38pub const SIGNATURE_DSA_WITH_SHA256: u32 = 0x0301;
39pub const SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0421;
40pub const SIGNATURE_VERITY_ECDSA_WITH_SHA256: u32 = 0x0423;
41pub const SIGNATURE_VERITY_DSA_WITH_SHA256: u32 = 0x0425;
Jooyung Han12a0b702021-08-05 23:20:31 +090042
43// TODO(jooyung): introduce type
44const CONTENT_DIGEST_CHUNKED_SHA256: u32 = 1;
45const CONTENT_DIGEST_CHUNKED_SHA512: u32 = 2;
46const CONTENT_DIGEST_VERITY_CHUNKED_SHA256: u32 = 3;
47#[allow(unused)]
48const CONTENT_DIGEST_SHA256: u32 = 4;
49
Jooyung Hand8397852021-08-10 16:29:36 +090050const CHUNK_SIZE_BYTES: u64 = 1024 * 1024;
51
Alice Wanged79eab2022-09-08 11:16:31 +000052/// The [APK structure] has four major sections:
53///
54/// | Zip contents | APK Signing Block | Central directory | EOCD(End of Central Directory) |
55///
56/// This structure contains the offset/size information of all the sections except the Zip contents.
57///
58/// [APK structure]: https://source.android.com/docs/security/apksigning/v2#apk-signing-block
Jooyung Hand8397852021-08-10 16:29:36 +090059pub struct ApkSections<R> {
60 inner: R,
61 signing_block_offset: u32,
62 signing_block_size: u32,
63 central_directory_offset: u32,
64 central_directory_size: u32,
65 eocd_offset: u32,
66 eocd_size: u32,
Jooyung Han12a0b702021-08-05 23:20:31 +090067}
68
Jooyung Hand8397852021-08-10 16:29:36 +090069impl<R: Read + Seek> ApkSections<R> {
70 pub fn new(reader: R) -> Result<ApkSections<R>> {
Andrew Walbran117cd5e2021-08-13 11:42:13 +000071 let (mut reader, zip_sections) = zip_sections(reader)?;
Jooyung Hand8397852021-08-10 16:29:36 +090072 let (signing_block_offset, signing_block_size) =
Andrew Walbran117cd5e2021-08-13 11:42:13 +000073 find_signing_block(&mut reader, zip_sections.central_directory_offset)?;
Jooyung Hand8397852021-08-10 16:29:36 +090074 Ok(ApkSections {
Andrew Walbran117cd5e2021-08-13 11:42:13 +000075 inner: reader,
Jooyung Hand8397852021-08-10 16:29:36 +090076 signing_block_offset,
77 signing_block_size,
78 central_directory_offset: zip_sections.central_directory_offset,
79 central_directory_size: zip_sections.central_directory_size,
80 eocd_offset: zip_sections.eocd_offset,
81 eocd_size: zip_sections.eocd_size,
82 })
83 }
Jooyung Han5d94bfc2021-08-06 14:07:49 +090084
Jooyung Hand8397852021-08-10 16:29:36 +090085 /// Returns the APK Signature Scheme block contained in the provided file for the given ID
86 /// and the additional information relevant for verifying the block against the file.
87 pub fn find_signature(&mut self, block_id: u32) -> Result<Bytes> {
88 let signing_block = self.bytes(self.signing_block_offset, self.signing_block_size)?;
Jooyung Hand8397852021-08-10 16:29:36 +090089 find_signature_scheme_block(Bytes::from(signing_block), block_id)
90 }
Jooyung Han12a0b702021-08-05 23:20:31 +090091
Jooyung Hand8397852021-08-10 16:29:36 +090092 /// Computes digest with "signature algorithm" over APK contents, central directory, and EOCD.
93 /// 1. The digest of each chunk is computed over the concatenation of byte 0xa5, the chunk’s
94 /// length in bytes (little-endian uint32), and the chunk’s contents.
95 /// 2. The top-level digest is computed over the concatenation of byte 0x5a, the number of
96 /// chunks (little-endian uint32), and the concatenation of digests of the chunks in the
97 /// order the chunks appear in the APK.
98 /// (see https://source.android.com/security/apksigning/v2#integrity-protected-contents)
99 pub fn compute_digest(&mut self, signature_algorithm_id: u32) -> Result<Vec<u8>> {
100 let digester = Digester::new(signature_algorithm_id)?;
101
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000102 let mut digests_of_chunks = BytesMut::new();
Jooyung Hand8397852021-08-10 16:29:36 +0900103 let mut chunk_count = 0u32;
104 let mut chunk = vec![0u8; CHUNK_SIZE_BYTES as usize];
105 for data in &[
106 ApkSections::zip_entries,
107 ApkSections::central_directory,
108 ApkSections::eocd_for_verification,
109 ] {
110 let mut data = data(self)?;
111 while data.limit() > 0 {
112 let chunk_size = min(CHUNK_SIZE_BYTES, data.limit());
Chris Wailes641fc4a2021-12-01 15:03:21 -0800113 let slice = &mut chunk[..(chunk_size as usize)];
114 data.read_exact(slice)?;
Jooyung Hand8397852021-08-10 16:29:36 +0900115 digests_of_chunks.put_slice(
Andrew Scullc208eb42022-05-22 16:17:52 +0000116 digester.digest(slice, CHUNK_HEADER_MID, chunk_size as u32)?.as_ref(),
Jooyung Hand8397852021-08-10 16:29:36 +0900117 );
118 chunk_count += 1;
119 }
120 }
Andrew Scullc208eb42022-05-22 16:17:52 +0000121 Ok(digester.digest(&digests_of_chunks, CHUNK_HEADER_TOP, chunk_count)?.as_ref().into())
Jooyung Hand8397852021-08-10 16:29:36 +0900122 }
123
124 fn zip_entries(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
125 scoped_read(&mut self.inner, 0, self.signing_block_offset as u64)
126 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000127
Jooyung Hand8397852021-08-10 16:29:36 +0900128 fn central_directory(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
129 scoped_read(
130 &mut self.inner,
131 self.central_directory_offset as u64,
132 self.central_directory_size as u64,
133 )
134 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000135
Jooyung Hand8397852021-08-10 16:29:36 +0900136 fn eocd_for_verification(&mut self) -> Result<Take<Box<dyn Read + '_>>> {
137 let mut eocd = self.bytes(self.eocd_offset, self.eocd_size)?;
138 // Protection of section 4 (ZIP End of Central Directory) is complicated by the section
139 // containing the offset of ZIP Central Directory. The offset changes when the size of the
140 // APK Signing Block changes, for instance, when a new signature is added. Thus, when
141 // computing digest over the ZIP End of Central Directory, the field containing the offset
142 // of ZIP Central Directory must be treated as containing the offset of the APK Signing
143 // Block.
144 set_central_directory_offset(&mut eocd, self.signing_block_offset)?;
145 Ok(Read::take(Box::new(Cursor::new(eocd)), self.eocd_size as u64))
146 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000147
Jooyung Hand8397852021-08-10 16:29:36 +0900148 fn bytes(&mut self, offset: u32, size: u32) -> Result<Vec<u8>> {
149 self.inner.seek(SeekFrom::Start(offset as u64))?;
150 let mut buf = vec![0u8; size as usize];
151 self.inner.read_exact(&mut buf)?;
152 Ok(buf)
153 }
154}
155
156fn scoped_read<'a, R: Read + Seek>(
157 src: &'a mut R,
158 offset: u64,
159 size: u64,
160) -> Result<Take<Box<dyn Read + 'a>>> {
161 src.seek(SeekFrom::Start(offset))?;
162 Ok(Read::take(Box::new(src), size))
163}
164
165struct Digester {
Andrew Scullc208eb42022-05-22 16:17:52 +0000166 algorithm: MessageDigest,
Jooyung Hand8397852021-08-10 16:29:36 +0900167}
168
169const CHUNK_HEADER_TOP: &[u8] = &[0x5a];
170const CHUNK_HEADER_MID: &[u8] = &[0xa5];
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000171
Jooyung Hand8397852021-08-10 16:29:36 +0900172impl Digester {
173 fn new(signature_algorithm_id: u32) -> Result<Digester> {
174 let digest_algorithm_id = to_content_digest_algorithm(signature_algorithm_id)?;
175 let algorithm = match digest_algorithm_id {
Andrew Scullc208eb42022-05-22 16:17:52 +0000176 CONTENT_DIGEST_CHUNKED_SHA256 => MessageDigest::sha256(),
177 CONTENT_DIGEST_CHUNKED_SHA512 => MessageDigest::sha512(),
Jooyung Hand8397852021-08-10 16:29:36 +0900178 // TODO(jooyung): implement
179 CONTENT_DIGEST_VERITY_CHUNKED_SHA256 => {
180 bail!("TODO(b/190343842): CONTENT_DIGEST_VERITY_CHUNKED_SHA256: not implemented")
181 }
182 _ => bail!("Unknown digest algorithm: {}", digest_algorithm_id),
183 };
184 Ok(Digester { algorithm })
185 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000186
Jooyung Hand8397852021-08-10 16:29:36 +0900187 // v2/v3 digests are computed after prepending "header" byte and "size" info.
Andrew Scullc208eb42022-05-22 16:17:52 +0000188 fn digest(&self, data: &[u8], header: &[u8], size: u32) -> Result<DigestBytes> {
Alice Wang98073222022-09-09 14:08:19 +0000189 let mut hasher = Hasher::new(self.algorithm)?;
190 hasher.update(header)?;
191 hasher.update(&size.to_le_bytes())?;
192 hasher.update(data)?;
193 Ok(hasher.finish()?)
Jooyung Hand8397852021-08-10 16:29:36 +0900194 }
Jooyung Han12a0b702021-08-05 23:20:31 +0900195}
196
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900197fn find_signing_block<T: Read + Seek>(
Jooyung Han12a0b702021-08-05 23:20:31 +0900198 reader: &mut T,
199 central_directory_offset: u32,
Jooyung Hand8397852021-08-10 16:29:36 +0900200) -> Result<(u32, u32)> {
Jooyung Han12a0b702021-08-05 23:20:31 +0900201 // FORMAT:
202 // OFFSET DATA TYPE DESCRIPTION
203 // * @+0 bytes uint64: size in bytes (excluding this field)
204 // * @+8 bytes payload
205 // * @-24 bytes uint64: size in bytes (same as the one above)
206 // * @-16 bytes uint128: magic
Alice Wangaf1d15b2022-09-09 11:09:51 +0000207 ensure!(
208 central_directory_offset >= APK_SIG_BLOCK_MIN_SIZE,
209 "APK too small for APK Signing Block. ZIP Central Directory offset: {}",
210 central_directory_offset
211 );
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900212 reader.seek(SeekFrom::Start((central_directory_offset - 24) as u64))?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900213 let size_in_footer = reader.read_u64::<LittleEndian>()? as u32;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000214 ensure!(
215 reader.read_u128::<LittleEndian>()? == APK_SIG_BLOCK_MAGIC,
216 "No APK Signing Block before ZIP Central Directory"
217 );
Jooyung Han12a0b702021-08-05 23:20:31 +0900218 let total_size = size_in_footer + 8;
219 let signing_block_offset = central_directory_offset
220 .checked_sub(total_size)
221 .ok_or_else(|| anyhow!("APK Signing Block size out of range: {}", size_in_footer))?;
Jooyung Han5d94bfc2021-08-06 14:07:49 +0900222 reader.seek(SeekFrom::Start(signing_block_offset as u64))?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900223 let size_in_header = reader.read_u64::<LittleEndian>()? as u32;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000224 // This corresponds to APK Signature Scheme v3 verification step 1a.
225 ensure!(
226 size_in_header == size_in_footer,
227 "APK Signing Block sizes in header and footer do not match: {} vs {}",
228 size_in_header,
229 size_in_footer
230 );
Jooyung Hand8397852021-08-10 16:29:36 +0900231 Ok((signing_block_offset, total_size))
Jooyung Han12a0b702021-08-05 23:20:31 +0900232}
233
234fn find_signature_scheme_block(buf: Bytes, block_id: u32) -> Result<Bytes> {
235 // FORMAT:
236 // OFFSET DATA TYPE DESCRIPTION
237 // * @+0 bytes uint64: size in bytes (excluding this field)
238 // * @+8 bytes pairs
239 // * @-24 bytes uint64: size in bytes (same as the one above)
240 // * @-16 bytes uint128: magic
241 let mut pairs = buf.slice(8..(buf.len() - 24));
242 let mut entry_count = 0;
243 while pairs.has_remaining() {
244 entry_count += 1;
Alice Wangaf1d15b2022-09-09 11:09:51 +0000245 ensure!(
246 pairs.remaining() >= 8,
247 "Insufficient data to read size of APK Signing Block entry #{}",
248 entry_count
249 );
Jooyung Han12a0b702021-08-05 23:20:31 +0900250 let length = pairs.get_u64_le();
251 let mut pair = pairs.split_to(length as usize);
252 let id = pair.get_u32_le();
253 if id == block_id {
254 return Ok(pair);
255 }
256 }
Alice Wangaf1d15b2022-09-09 11:09:51 +0000257 let context =
258 format!("No APK Signature Scheme block in APK Signing Block with ID: {}", block_id);
259 Err(Error::new(io::Error::from(ErrorKind::NotFound)).context(context))
Jooyung Han12a0b702021-08-05 23:20:31 +0900260}
261
262pub fn is_supported_signature_algorithm(algorithm_id: u32) -> bool {
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900263 matches!(
264 algorithm_id,
Jooyung Han12a0b702021-08-05 23:20:31 +0900265 SIGNATURE_RSA_PSS_WITH_SHA256
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900266 | SIGNATURE_RSA_PSS_WITH_SHA512
267 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256
268 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512
269 | SIGNATURE_ECDSA_WITH_SHA256
270 | SIGNATURE_ECDSA_WITH_SHA512
271 | SIGNATURE_DSA_WITH_SHA256
272 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256
273 | SIGNATURE_VERITY_ECDSA_WITH_SHA256
274 | SIGNATURE_VERITY_DSA_WITH_SHA256
275 )
Jooyung Han12a0b702021-08-05 23:20:31 +0900276}
277
278fn to_content_digest_algorithm(algorithm_id: u32) -> Result<u32> {
279 match algorithm_id {
280 SIGNATURE_RSA_PSS_WITH_SHA256
281 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256
282 | SIGNATURE_ECDSA_WITH_SHA256
283 | SIGNATURE_DSA_WITH_SHA256 => Ok(CONTENT_DIGEST_CHUNKED_SHA256),
284 SIGNATURE_RSA_PSS_WITH_SHA512
285 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512
286 | SIGNATURE_ECDSA_WITH_SHA512 => Ok(CONTENT_DIGEST_CHUNKED_SHA512),
287 SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256
288 | SIGNATURE_VERITY_ECDSA_WITH_SHA256
289 | SIGNATURE_VERITY_DSA_WITH_SHA256 => Ok(CONTENT_DIGEST_VERITY_CHUNKED_SHA256),
290 _ => bail!("Unknown signature algorithm: {}", algorithm_id),
291 }
292}
293
Alice Wanga94ba172022-09-08 15:25:31 +0000294/// This method is used to help pick v4 apk digest. According to APK Signature
295/// Scheme v4, apk digest is the first available content digest of the highest
296/// rank (rank N).
297///
298/// This rank was also used for step 3a of the v3 signature verification.
299///
300/// [v3 verification]: https://source.android.com/docs/security/apksigning/v3#v3-verification
301pub fn get_signature_algorithm_rank(algo: u32) -> Result<u32> {
302 let content_digest = to_content_digest_algorithm(algo)?;
303 match content_digest {
Jooyung Han12a0b702021-08-05 23:20:31 +0900304 CONTENT_DIGEST_CHUNKED_SHA256 => Ok(0),
305 CONTENT_DIGEST_VERITY_CHUNKED_SHA256 => Ok(1),
306 CONTENT_DIGEST_CHUNKED_SHA512 => Ok(2),
Alice Wanga94ba172022-09-08 15:25:31 +0000307 _ => bail!("Unknown digest algorithm: {}", content_digest),
Jooyung Han12a0b702021-08-05 23:20:31 +0900308 }
309}
Alice Wanged79eab2022-09-08 11:16:31 +0000310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use byteorder::LittleEndian;
315 use std::fs::File;
316 use std::mem::size_of_val;
317
Alice Wangaf1d15b2022-09-09 11:09:51 +0000318 use crate::v3::{to_hex_string, APK_SIGNATURE_SCHEME_V3_BLOCK_ID};
Alice Wang98073222022-09-09 14:08:19 +0000319
Alice Wanged79eab2022-09-08 11:16:31 +0000320 const CENTRAL_DIRECTORY_HEADER_SIGNATURE: u32 = 0x02014b50;
321
322 #[test]
323 fn test_apk_sections() {
324 let apk_file = File::open("tests/data/v3-only-with-ecdsa-sha512-p521.apk").unwrap();
325 let apk_sections = ApkSections::new(apk_file).unwrap();
326 let mut reader = &apk_sections.inner;
327
328 // Checks APK Signing Block.
329 assert_eq!(
330 apk_sections.signing_block_offset + apk_sections.signing_block_size,
331 apk_sections.central_directory_offset
332 );
333 let apk_signature_offset = SeekFrom::Start(
334 apk_sections.central_directory_offset as u64 - size_of_val(&APK_SIG_BLOCK_MAGIC) as u64,
335 );
336 reader.seek(apk_signature_offset).unwrap();
337 assert_eq!(reader.read_u128::<LittleEndian>().unwrap(), APK_SIG_BLOCK_MAGIC);
338
339 // Checks Central directory.
340 assert_eq!(reader.read_u32::<LittleEndian>().unwrap(), CENTRAL_DIRECTORY_HEADER_SIGNATURE);
341 assert_eq!(
342 apk_sections.central_directory_offset + apk_sections.central_directory_size,
343 apk_sections.eocd_offset
344 );
345
346 // Checks EOCD.
347 assert_eq!(
348 reader.metadata().unwrap().len(),
349 (apk_sections.eocd_offset + apk_sections.eocd_size) as u64
350 );
351 }
Alice Wang98073222022-09-09 14:08:19 +0000352
353 #[test]
354 fn test_apk_digest() {
355 let apk_file = File::open("tests/data/v3-only-with-dsa-sha256-1024.apk").unwrap();
356 let mut apk_sections = ApkSections::new(apk_file).unwrap();
357 let digest = apk_sections.compute_digest(SIGNATURE_DSA_WITH_SHA256).unwrap();
358 assert_eq!(
359 "0DF2426EA33AEDAF495D88E5BE0C6A1663FF0A81C5ED12D5B2929AE4B4300F2F",
360 to_hex_string(&digest[..])
361 );
362 }
Alice Wangaf1d15b2022-09-09 11:09:51 +0000363
364 #[test]
365 fn test_apk_sections_cannot_find_signature() {
366 let apk_file = File::open("tests/data/v2-only-two-signers.apk").unwrap();
367 let mut apk_sections = ApkSections::new(apk_file).unwrap();
368 let result = apk_sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID);
369
370 assert!(result.is_err());
371 let error = result.unwrap_err();
372 assert_eq!(error.downcast_ref::<io::Error>().unwrap().kind(), ErrorKind::NotFound);
373 assert!(
374 error.to_string().contains(&APK_SIGNATURE_SCHEME_V3_BLOCK_ID.to_string()),
375 "Error should contain the block ID: {}",
376 error
377 );
378 }
379
380 #[test]
381 fn test_apk_sections_find_signature() {
382 let apk_file = File::open("tests/data/v3-only-with-dsa-sha256-1024.apk").unwrap();
383 let mut apk_sections = ApkSections::new(apk_file).unwrap();
384 let signature = apk_sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).unwrap();
385
386 let expected_v3_signature_block_size = 1289; // Only for this specific APK
387 assert_eq!(signature.len(), expected_v3_signature_block_size);
388 }
Alice Wanged79eab2022-09-08 11:16:31 +0000389}