Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 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 Signature Verification |
| 18 | |
| 19 | use anyhow::{anyhow, bail, Result}; |
| 20 | use byteorder::{LittleEndian, ReadBytesExt}; |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame^] | 21 | use bytes::{Buf, BufMut, Bytes}; |
| 22 | use ring::digest; |
| 23 | use std::cmp::min; |
| 24 | use std::io::{Cursor, Read, Seek, SeekFrom, Take}; |
Jooyung Han | 5d94bfc | 2021-08-06 14:07:49 +0900 | [diff] [blame] | 25 | |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame^] | 26 | use crate::ziputil::{set_central_directory_offset, zip_sections}; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 27 | |
| 28 | const APK_SIG_BLOCK_MIN_SIZE: u32 = 32; |
| 29 | const APK_SIG_BLOCK_MAGIC: u128 = 0x3234206b636f6c4220676953204b5041; |
| 30 | |
| 31 | // TODO(jooyung): introduce type |
Jooyung Han | 5b4c70e | 2021-08-09 16:36:13 +0900 | [diff] [blame] | 32 | pub const SIGNATURE_RSA_PSS_WITH_SHA256: u32 = 0x0101; |
| 33 | pub const SIGNATURE_RSA_PSS_WITH_SHA512: u32 = 0x0102; |
| 34 | pub const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0103; |
| 35 | pub const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: u32 = 0x0104; |
| 36 | pub const SIGNATURE_ECDSA_WITH_SHA256: u32 = 0x0201; |
| 37 | pub const SIGNATURE_ECDSA_WITH_SHA512: u32 = 0x0202; |
| 38 | pub const SIGNATURE_DSA_WITH_SHA256: u32 = 0x0301; |
| 39 | pub const SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0421; |
| 40 | pub const SIGNATURE_VERITY_ECDSA_WITH_SHA256: u32 = 0x0423; |
| 41 | pub const SIGNATURE_VERITY_DSA_WITH_SHA256: u32 = 0x0425; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 42 | |
| 43 | // TODO(jooyung): introduce type |
| 44 | const CONTENT_DIGEST_CHUNKED_SHA256: u32 = 1; |
| 45 | const CONTENT_DIGEST_CHUNKED_SHA512: u32 = 2; |
| 46 | const CONTENT_DIGEST_VERITY_CHUNKED_SHA256: u32 = 3; |
| 47 | #[allow(unused)] |
| 48 | const CONTENT_DIGEST_SHA256: u32 = 4; |
| 49 | |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame^] | 50 | const CHUNK_SIZE_BYTES: u64 = 1024 * 1024; |
| 51 | |
| 52 | pub struct ApkSections<R> { |
| 53 | inner: R, |
| 54 | signing_block_offset: u32, |
| 55 | signing_block_size: u32, |
| 56 | central_directory_offset: u32, |
| 57 | central_directory_size: u32, |
| 58 | eocd_offset: u32, |
| 59 | eocd_size: u32, |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 60 | } |
| 61 | |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame^] | 62 | impl<R: Read + Seek> ApkSections<R> { |
| 63 | pub fn new(reader: R) -> Result<ApkSections<R>> { |
| 64 | let (mut f, zip_sections) = zip_sections(reader)?; |
| 65 | let (signing_block_offset, signing_block_size) = |
| 66 | find_signing_block(&mut f, zip_sections.central_directory_offset)?; |
| 67 | Ok(ApkSections { |
| 68 | inner: f, |
| 69 | signing_block_offset, |
| 70 | signing_block_size, |
| 71 | central_directory_offset: zip_sections.central_directory_offset, |
| 72 | central_directory_size: zip_sections.central_directory_size, |
| 73 | eocd_offset: zip_sections.eocd_offset, |
| 74 | eocd_size: zip_sections.eocd_size, |
| 75 | }) |
| 76 | } |
Jooyung Han | 5d94bfc | 2021-08-06 14:07:49 +0900 | [diff] [blame] | 77 | |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame^] | 78 | /// Returns the APK Signature Scheme block contained in the provided file for the given ID |
| 79 | /// and the additional information relevant for verifying the block against the file. |
| 80 | pub fn find_signature(&mut self, block_id: u32) -> Result<Bytes> { |
| 81 | let signing_block = self.bytes(self.signing_block_offset, self.signing_block_size)?; |
| 82 | // TODO(jooyung): propagate NotFound error so that verification can fallback to V2 |
| 83 | find_signature_scheme_block(Bytes::from(signing_block), block_id) |
| 84 | } |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 85 | |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame^] | 86 | /// Computes digest with "signature algorithm" over APK contents, central directory, and EOCD. |
| 87 | /// 1. The digest of each chunk is computed over the concatenation of byte 0xa5, the chunk’s |
| 88 | /// length in bytes (little-endian uint32), and the chunk’s contents. |
| 89 | /// 2. The top-level digest is computed over the concatenation of byte 0x5a, the number of |
| 90 | /// chunks (little-endian uint32), and the concatenation of digests of the chunks in the |
| 91 | /// order the chunks appear in the APK. |
| 92 | /// (see https://source.android.com/security/apksigning/v2#integrity-protected-contents) |
| 93 | pub fn compute_digest(&mut self, signature_algorithm_id: u32) -> Result<Vec<u8>> { |
| 94 | let digester = Digester::new(signature_algorithm_id)?; |
| 95 | |
| 96 | let mut digests_of_chunks = bytes::BytesMut::new(); |
| 97 | let mut chunk_count = 0u32; |
| 98 | let mut chunk = vec![0u8; CHUNK_SIZE_BYTES as usize]; |
| 99 | for data in &[ |
| 100 | ApkSections::zip_entries, |
| 101 | ApkSections::central_directory, |
| 102 | ApkSections::eocd_for_verification, |
| 103 | ] { |
| 104 | let mut data = data(self)?; |
| 105 | while data.limit() > 0 { |
| 106 | let chunk_size = min(CHUNK_SIZE_BYTES, data.limit()); |
| 107 | let mut slice = &mut chunk[..(chunk_size as usize)]; |
| 108 | data.read_exact(&mut slice)?; |
| 109 | digests_of_chunks.put_slice( |
| 110 | digester.digest(slice, CHUNK_HEADER_MID, chunk_size as u32).as_ref(), |
| 111 | ); |
| 112 | chunk_count += 1; |
| 113 | } |
| 114 | } |
| 115 | Ok(digester.digest(&digests_of_chunks, CHUNK_HEADER_TOP, chunk_count).as_ref().into()) |
| 116 | } |
| 117 | |
| 118 | fn zip_entries(&mut self) -> Result<Take<Box<dyn Read + '_>>> { |
| 119 | scoped_read(&mut self.inner, 0, self.signing_block_offset as u64) |
| 120 | } |
| 121 | fn central_directory(&mut self) -> Result<Take<Box<dyn Read + '_>>> { |
| 122 | scoped_read( |
| 123 | &mut self.inner, |
| 124 | self.central_directory_offset as u64, |
| 125 | self.central_directory_size as u64, |
| 126 | ) |
| 127 | } |
| 128 | fn eocd_for_verification(&mut self) -> Result<Take<Box<dyn Read + '_>>> { |
| 129 | let mut eocd = self.bytes(self.eocd_offset, self.eocd_size)?; |
| 130 | // Protection of section 4 (ZIP End of Central Directory) is complicated by the section |
| 131 | // containing the offset of ZIP Central Directory. The offset changes when the size of the |
| 132 | // APK Signing Block changes, for instance, when a new signature is added. Thus, when |
| 133 | // computing digest over the ZIP End of Central Directory, the field containing the offset |
| 134 | // of ZIP Central Directory must be treated as containing the offset of the APK Signing |
| 135 | // Block. |
| 136 | set_central_directory_offset(&mut eocd, self.signing_block_offset)?; |
| 137 | Ok(Read::take(Box::new(Cursor::new(eocd)), self.eocd_size as u64)) |
| 138 | } |
| 139 | fn bytes(&mut self, offset: u32, size: u32) -> Result<Vec<u8>> { |
| 140 | self.inner.seek(SeekFrom::Start(offset as u64))?; |
| 141 | let mut buf = vec![0u8; size as usize]; |
| 142 | self.inner.read_exact(&mut buf)?; |
| 143 | Ok(buf) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | fn scoped_read<'a, R: Read + Seek>( |
| 148 | src: &'a mut R, |
| 149 | offset: u64, |
| 150 | size: u64, |
| 151 | ) -> Result<Take<Box<dyn Read + 'a>>> { |
| 152 | src.seek(SeekFrom::Start(offset))?; |
| 153 | Ok(Read::take(Box::new(src), size)) |
| 154 | } |
| 155 | |
| 156 | struct Digester { |
| 157 | algorithm: &'static digest::Algorithm, |
| 158 | } |
| 159 | |
| 160 | const CHUNK_HEADER_TOP: &[u8] = &[0x5a]; |
| 161 | const CHUNK_HEADER_MID: &[u8] = &[0xa5]; |
| 162 | impl Digester { |
| 163 | fn new(signature_algorithm_id: u32) -> Result<Digester> { |
| 164 | let digest_algorithm_id = to_content_digest_algorithm(signature_algorithm_id)?; |
| 165 | let algorithm = match digest_algorithm_id { |
| 166 | CONTENT_DIGEST_CHUNKED_SHA256 => &digest::SHA256, |
| 167 | CONTENT_DIGEST_CHUNKED_SHA512 => &digest::SHA512, |
| 168 | // TODO(jooyung): implement |
| 169 | CONTENT_DIGEST_VERITY_CHUNKED_SHA256 => { |
| 170 | bail!("TODO(b/190343842): CONTENT_DIGEST_VERITY_CHUNKED_SHA256: not implemented") |
| 171 | } |
| 172 | _ => bail!("Unknown digest algorithm: {}", digest_algorithm_id), |
| 173 | }; |
| 174 | Ok(Digester { algorithm }) |
| 175 | } |
| 176 | // v2/v3 digests are computed after prepending "header" byte and "size" info. |
| 177 | fn digest(&self, data: &[u8], header: &[u8], size: u32) -> digest::Digest { |
| 178 | let mut ctx = digest::Context::new(self.algorithm); |
| 179 | ctx.update(header); |
| 180 | ctx.update(&size.to_le_bytes()); |
| 181 | ctx.update(data); |
| 182 | ctx.finish() |
| 183 | } |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 184 | } |
| 185 | |
Jooyung Han | 5d94bfc | 2021-08-06 14:07:49 +0900 | [diff] [blame] | 186 | fn find_signing_block<T: Read + Seek>( |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 187 | reader: &mut T, |
| 188 | central_directory_offset: u32, |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame^] | 189 | ) -> Result<(u32, u32)> { |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 190 | // FORMAT: |
| 191 | // OFFSET DATA TYPE DESCRIPTION |
| 192 | // * @+0 bytes uint64: size in bytes (excluding this field) |
| 193 | // * @+8 bytes payload |
| 194 | // * @-24 bytes uint64: size in bytes (same as the one above) |
| 195 | // * @-16 bytes uint128: magic |
| 196 | if central_directory_offset < APK_SIG_BLOCK_MIN_SIZE { |
| 197 | bail!( |
| 198 | "APK too small for APK Signing Block. ZIP Central Directory offset: {}", |
| 199 | central_directory_offset |
| 200 | ); |
| 201 | } |
Jooyung Han | 5d94bfc | 2021-08-06 14:07:49 +0900 | [diff] [blame] | 202 | reader.seek(SeekFrom::Start((central_directory_offset - 24) as u64))?; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 203 | let size_in_footer = reader.read_u64::<LittleEndian>()? as u32; |
| 204 | if reader.read_u128::<LittleEndian>()? != APK_SIG_BLOCK_MAGIC { |
| 205 | bail!("No APK Signing Block before ZIP Central Directory") |
| 206 | } |
| 207 | let total_size = size_in_footer + 8; |
| 208 | let signing_block_offset = central_directory_offset |
| 209 | .checked_sub(total_size) |
| 210 | .ok_or_else(|| anyhow!("APK Signing Block size out of range: {}", size_in_footer))?; |
Jooyung Han | 5d94bfc | 2021-08-06 14:07:49 +0900 | [diff] [blame] | 211 | reader.seek(SeekFrom::Start(signing_block_offset as u64))?; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 212 | let size_in_header = reader.read_u64::<LittleEndian>()? as u32; |
| 213 | if size_in_header != size_in_footer { |
| 214 | bail!( |
| 215 | "APK Signing Block sizes in header and footer do not match: {} vs {}", |
| 216 | size_in_header, |
| 217 | size_in_footer |
| 218 | ); |
| 219 | } |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame^] | 220 | Ok((signing_block_offset, total_size)) |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 221 | } |
| 222 | |
| 223 | fn find_signature_scheme_block(buf: Bytes, block_id: u32) -> Result<Bytes> { |
| 224 | // FORMAT: |
| 225 | // OFFSET DATA TYPE DESCRIPTION |
| 226 | // * @+0 bytes uint64: size in bytes (excluding this field) |
| 227 | // * @+8 bytes pairs |
| 228 | // * @-24 bytes uint64: size in bytes (same as the one above) |
| 229 | // * @-16 bytes uint128: magic |
| 230 | let mut pairs = buf.slice(8..(buf.len() - 24)); |
| 231 | let mut entry_count = 0; |
| 232 | while pairs.has_remaining() { |
| 233 | entry_count += 1; |
| 234 | if pairs.remaining() < 8 { |
| 235 | bail!("Insufficient data to read size of APK Signing Block entry #{}", entry_count); |
| 236 | } |
| 237 | let length = pairs.get_u64_le(); |
| 238 | let mut pair = pairs.split_to(length as usize); |
| 239 | let id = pair.get_u32_le(); |
| 240 | if id == block_id { |
| 241 | return Ok(pair); |
| 242 | } |
| 243 | } |
| 244 | // TODO(jooyung): return NotFound error |
| 245 | bail!("No APK Signature Scheme block in APK Signing Block with ID: {}", block_id) |
| 246 | } |
| 247 | |
| 248 | pub fn is_supported_signature_algorithm(algorithm_id: u32) -> bool { |
Jooyung Han | 19c1d6c | 2021-08-06 14:08:16 +0900 | [diff] [blame] | 249 | matches!( |
| 250 | algorithm_id, |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 251 | SIGNATURE_RSA_PSS_WITH_SHA256 |
Jooyung Han | 19c1d6c | 2021-08-06 14:08:16 +0900 | [diff] [blame] | 252 | | SIGNATURE_RSA_PSS_WITH_SHA512 |
| 253 | | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 |
| 254 | | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 |
| 255 | | SIGNATURE_ECDSA_WITH_SHA256 |
| 256 | | SIGNATURE_ECDSA_WITH_SHA512 |
| 257 | | SIGNATURE_DSA_WITH_SHA256 |
| 258 | | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256 |
| 259 | | SIGNATURE_VERITY_ECDSA_WITH_SHA256 |
| 260 | | SIGNATURE_VERITY_DSA_WITH_SHA256 |
| 261 | ) |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 262 | } |
| 263 | |
| 264 | fn to_content_digest_algorithm(algorithm_id: u32) -> Result<u32> { |
| 265 | match algorithm_id { |
| 266 | SIGNATURE_RSA_PSS_WITH_SHA256 |
| 267 | | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 |
| 268 | | SIGNATURE_ECDSA_WITH_SHA256 |
| 269 | | SIGNATURE_DSA_WITH_SHA256 => Ok(CONTENT_DIGEST_CHUNKED_SHA256), |
| 270 | SIGNATURE_RSA_PSS_WITH_SHA512 |
| 271 | | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 |
| 272 | | SIGNATURE_ECDSA_WITH_SHA512 => Ok(CONTENT_DIGEST_CHUNKED_SHA512), |
| 273 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256 |
| 274 | | SIGNATURE_VERITY_ECDSA_WITH_SHA256 |
| 275 | | SIGNATURE_VERITY_DSA_WITH_SHA256 => Ok(CONTENT_DIGEST_VERITY_CHUNKED_SHA256), |
| 276 | _ => bail!("Unknown signature algorithm: {}", algorithm_id), |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | pub fn rank_signature_algorithm(algo: u32) -> Result<u32> { |
| 281 | rank_content_digest_algorithm(to_content_digest_algorithm(algo)?) |
| 282 | } |
| 283 | |
| 284 | fn rank_content_digest_algorithm(id: u32) -> Result<u32> { |
| 285 | match id { |
| 286 | CONTENT_DIGEST_CHUNKED_SHA256 => Ok(0), |
| 287 | CONTENT_DIGEST_VERITY_CHUNKED_SHA256 => Ok(1), |
| 288 | CONTENT_DIGEST_CHUNKED_SHA512 => Ok(2), |
| 289 | _ => bail!("Unknown digest algorithm: {}", id), |
| 290 | } |
| 291 | } |