blob: de3d0ddb286c72842ba08892183688de9bae0efb [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
19use anyhow::{anyhow, bail, Result};
20use byteorder::{LittleEndian, ReadBytesExt};
21use bytes::{Buf, Bytes};
22use std::io;
23use std::io::Read;
24use zip::spec::CentralDirectoryEnd as EndOfCentralDirectory;
25
26const APK_SIG_BLOCK_MIN_SIZE: u32 = 32;
27const APK_SIG_BLOCK_MAGIC: u128 = 0x3234206b636f6c4220676953204b5041;
28
29// TODO(jooyung): introduce type
30const SIGNATURE_RSA_PSS_WITH_SHA256: u32 = 0x0101;
31const SIGNATURE_RSA_PSS_WITH_SHA512: u32 = 0x0102;
32const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0103;
33const SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: u32 = 0x0104;
34const SIGNATURE_ECDSA_WITH_SHA256: u32 = 0x0201;
35const SIGNATURE_ECDSA_WITH_SHA512: u32 = 0x0202;
36const SIGNATURE_DSA_WITH_SHA256: u32 = 0x0301;
37const SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256: u32 = 0x0421;
38const SIGNATURE_VERITY_ECDSA_WITH_SHA256: u32 = 0x0423;
39const SIGNATURE_VERITY_DSA_WITH_SHA256: u32 = 0x0425;
40
41// TODO(jooyung): introduce type
42const CONTENT_DIGEST_CHUNKED_SHA256: u32 = 1;
43const CONTENT_DIGEST_CHUNKED_SHA512: u32 = 2;
44const CONTENT_DIGEST_VERITY_CHUNKED_SHA256: u32 = 3;
45#[allow(unused)]
46const CONTENT_DIGEST_SHA256: u32 = 4;
47
48pub struct SignatureInfo {
49 pub signing_block_offset: u32,
50 pub signature_block: Bytes,
51 pub eocd_offset: u32,
52 pub eocd: EndOfCentralDirectory,
53}
54
55/// Returns the APK Signature Scheme block contained in the provided file for the given ID
56/// and the additional information relevant for verifying the block against the file.
57pub fn find_signature<F: Read + io::Seek>(f: &mut F, block_id: u32) -> Result<SignatureInfo> {
58 let (eocd, eocd_offset) = EndOfCentralDirectory::find_and_parse(f)?;
59 if eocd.disk_number != eocd.disk_with_central_directory {
60 bail!("Support for multi-disk files is not implemented");
61 }
62 // TODO(jooyung): reject zip64 file
63 let (signing_block, signing_block_offset) =
64 find_signing_block(f, eocd.central_directory_offset)?;
65
66 // TODO(jooyung): propagate NotFound error so that verification can fallback to V2
67 let signature_scheme_block = find_signature_scheme_block(signing_block, block_id)?;
68 Ok(SignatureInfo {
69 signing_block_offset,
70 signature_block: signature_scheme_block,
71 eocd_offset: eocd_offset as u32,
72 eocd,
73 })
74}
75
76fn find_signing_block<T: Read + io::Seek>(
77 reader: &mut T,
78 central_directory_offset: u32,
79) -> Result<(Bytes, u32)> {
80 // FORMAT:
81 // OFFSET DATA TYPE DESCRIPTION
82 // * @+0 bytes uint64: size in bytes (excluding this field)
83 // * @+8 bytes payload
84 // * @-24 bytes uint64: size in bytes (same as the one above)
85 // * @-16 bytes uint128: magic
86 if central_directory_offset < APK_SIG_BLOCK_MIN_SIZE {
87 bail!(
88 "APK too small for APK Signing Block. ZIP Central Directory offset: {}",
89 central_directory_offset
90 );
91 }
92 reader.seek(io::SeekFrom::Start((central_directory_offset - 24) as u64))?;
93 let size_in_footer = reader.read_u64::<LittleEndian>()? as u32;
94 if reader.read_u128::<LittleEndian>()? != APK_SIG_BLOCK_MAGIC {
95 bail!("No APK Signing Block before ZIP Central Directory")
96 }
97 let total_size = size_in_footer + 8;
98 let signing_block_offset = central_directory_offset
99 .checked_sub(total_size)
100 .ok_or_else(|| anyhow!("APK Signing Block size out of range: {}", size_in_footer))?;
101 reader.seek(io::SeekFrom::Start(signing_block_offset as u64))?;
102 let size_in_header = reader.read_u64::<LittleEndian>()? as u32;
103 if size_in_header != size_in_footer {
104 bail!(
105 "APK Signing Block sizes in header and footer do not match: {} vs {}",
106 size_in_header,
107 size_in_footer
108 );
109 }
110 reader.seek(io::SeekFrom::Start(signing_block_offset as u64))?;
111 let mut buf = vec![0u8; total_size as usize];
112 reader.read_exact(&mut buf)?;
113 Ok((Bytes::from(buf), signing_block_offset))
114}
115
116fn find_signature_scheme_block(buf: Bytes, block_id: u32) -> Result<Bytes> {
117 // FORMAT:
118 // OFFSET DATA TYPE DESCRIPTION
119 // * @+0 bytes uint64: size in bytes (excluding this field)
120 // * @+8 bytes pairs
121 // * @-24 bytes uint64: size in bytes (same as the one above)
122 // * @-16 bytes uint128: magic
123 let mut pairs = buf.slice(8..(buf.len() - 24));
124 let mut entry_count = 0;
125 while pairs.has_remaining() {
126 entry_count += 1;
127 if pairs.remaining() < 8 {
128 bail!("Insufficient data to read size of APK Signing Block entry #{}", entry_count);
129 }
130 let length = pairs.get_u64_le();
131 let mut pair = pairs.split_to(length as usize);
132 let id = pair.get_u32_le();
133 if id == block_id {
134 return Ok(pair);
135 }
136 }
137 // TODO(jooyung): return NotFound error
138 bail!("No APK Signature Scheme block in APK Signing Block with ID: {}", block_id)
139}
140
141pub fn is_supported_signature_algorithm(algorithm_id: u32) -> bool {
142 match algorithm_id {
143 SIGNATURE_RSA_PSS_WITH_SHA256
144 | SIGNATURE_RSA_PSS_WITH_SHA512
145 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256
146 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512
147 | SIGNATURE_ECDSA_WITH_SHA256
148 | SIGNATURE_ECDSA_WITH_SHA512
149 | SIGNATURE_DSA_WITH_SHA256
150 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256
151 | SIGNATURE_VERITY_ECDSA_WITH_SHA256
152 | SIGNATURE_VERITY_DSA_WITH_SHA256 => true,
153 _ => false,
154 }
155}
156
157fn to_content_digest_algorithm(algorithm_id: u32) -> Result<u32> {
158 match algorithm_id {
159 SIGNATURE_RSA_PSS_WITH_SHA256
160 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256
161 | SIGNATURE_ECDSA_WITH_SHA256
162 | SIGNATURE_DSA_WITH_SHA256 => Ok(CONTENT_DIGEST_CHUNKED_SHA256),
163 SIGNATURE_RSA_PSS_WITH_SHA512
164 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512
165 | SIGNATURE_ECDSA_WITH_SHA512 => Ok(CONTENT_DIGEST_CHUNKED_SHA512),
166 SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256
167 | SIGNATURE_VERITY_ECDSA_WITH_SHA256
168 | SIGNATURE_VERITY_DSA_WITH_SHA256 => Ok(CONTENT_DIGEST_VERITY_CHUNKED_SHA256),
169 _ => bail!("Unknown signature algorithm: {}", algorithm_id),
170 }
171}
172
173pub fn rank_signature_algorithm(algo: u32) -> Result<u32> {
174 rank_content_digest_algorithm(to_content_digest_algorithm(algo)?)
175}
176
177fn rank_content_digest_algorithm(id: u32) -> Result<u32> {
178 match id {
179 CONTENT_DIGEST_CHUNKED_SHA256 => Ok(0),
180 CONTENT_DIGEST_VERITY_CHUNKED_SHA256 => Ok(1),
181 CONTENT_DIGEST_CHUNKED_SHA512 => Ok(2),
182 _ => bail!("Unknown digest algorithm: {}", id),
183 }
184}