blob: 710c9c348a7cf3d8c516419c86f6824bc139bc57 [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//! Verifies APK Signature Scheme V3
18
Jooyung Han19c1d6c2021-08-06 14:08:16 +090019// TODO(jooyung) remove this
20#![allow(dead_code)]
21
Andrew Scullc208eb42022-05-22 16:17:52 +000022use anyhow::{anyhow, bail, ensure, Context, Result};
Jooyung Han12a0b702021-08-05 23:20:31 +090023use bytes::Bytes;
Andrew Scullc208eb42022-05-22 16:17:52 +000024use openssl::hash::MessageDigest;
25use openssl::pkey::{self, PKey};
26use openssl::rsa::Padding;
27use openssl::sign::Verifier;
Jooyung Han12a0b702021-08-05 23:20:31 +090028use std::fs::File;
Jooyung Hand8397852021-08-10 16:29:36 +090029use std::io::{Read, Seek};
Jooyung Han12a0b702021-08-05 23:20:31 +090030use std::ops::Range;
31use std::path::Path;
Andrew Walbran117cd5e2021-08-13 11:42:13 +000032use x509_parser::{parse_x509_certificate, prelude::FromDer, x509::SubjectPublicKeyInfo};
Jooyung Han12a0b702021-08-05 23:20:31 +090033
34use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
Jooyung Han5b4c70e2021-08-09 16:36:13 +090035use crate::sigutil::*;
Jooyung Han12a0b702021-08-05 23:20:31 +090036
37pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
38
39// TODO(jooyung): get "ro.build.version.sdk"
40const SDK_INT: u32 = 31;
41
42/// Data model for Signature Scheme V3
43/// https://source.android.com/security/apksigning/v3#verification
44
45type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
46
47struct Signer {
48 signed_data: LengthPrefixed<Bytes>, // not verified yet
49 min_sdk: u32,
50 max_sdk: u32,
51 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
Andrew Walbran117cd5e2021-08-13 11:42:13 +000052 public_key: LengthPrefixed<Bytes>,
Jooyung Han12a0b702021-08-05 23:20:31 +090053}
54
55impl Signer {
56 fn sdk_range(&self) -> Range<u32> {
57 self.min_sdk..self.max_sdk
58 }
59}
60
61struct SignedData {
62 digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
63 certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
64 min_sdk: u32,
65 max_sdk: u32,
66 additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
67}
68
69impl SignedData {
70 fn sdk_range(&self) -> Range<u32> {
71 self.min_sdk..self.max_sdk
72 }
73}
74
Jooyung Han5b4c70e2021-08-09 16:36:13 +090075#[derive(Debug)]
Jooyung Han12a0b702021-08-05 23:20:31 +090076struct Signature {
77 signature_algorithm_id: u32,
78 signature: LengthPrefixed<Bytes>,
79}
80
81struct Digest {
82 signature_algorithm_id: u32,
83 digest: LengthPrefixed<Bytes>,
84}
85
86type X509Certificate = Bytes;
87type AdditionalAttributes = Bytes;
88
Jiyong Parka41535b2021-09-10 19:31:48 +090089/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the public key
Andrew Scullf3fd4c62022-05-22 14:41:21 +000090/// associated with the signer in DER format.
Jiyong Parka41535b2021-09-10 19:31:48 +090091pub fn verify<P: AsRef<Path>>(path: P) -> Result<Box<[u8]>> {
Jooyung Han5d94bfc2021-08-06 14:07:49 +090092 let f = File::open(path.as_ref())?;
Jooyung Hand8397852021-08-10 16:29:36 +090093 let mut sections = ApkSections::new(f)?;
Jiyong Parka41535b2021-09-10 19:31:48 +090094 find_signer_and_then(&mut sections, |(signer, sections)| signer.verify(sections))
Jooyung Han12a0b702021-08-05 23:20:31 +090095}
96
Jiyong Parka41535b2021-09-10 19:31:48 +090097/// Finds the supported signer and execute a function on it.
98fn find_signer_and_then<R, U, F>(sections: &mut ApkSections<R>, f: F) -> Result<U>
99where
100 R: Read + Seek,
101 F: FnOnce((&Signer, &mut ApkSections<R>)) -> Result<U>,
102{
Jooyung Hand8397852021-08-10 16:29:36 +0900103 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900104 // parse v3 scheme block
Jooyung Hand8397852021-08-10 16:29:36 +0900105 let signers = block.read::<Signers>()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900106
107 // find supported by platform
Jiyong Parka41535b2021-09-10 19:31:48 +0900108 let supported = signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>();
Jooyung Han12a0b702021-08-05 23:20:31 +0900109
110 // there should be exactly one
111 if supported.len() != 1 {
Jiyong Parka41535b2021-09-10 19:31:48 +0900112 bail!(
113 "APK Signature Scheme V3 only supports one signer: {} signers found.",
114 supported.len()
115 )
Jooyung Han12a0b702021-08-05 23:20:31 +0900116 }
117
Jiyong Parka41535b2021-09-10 19:31:48 +0900118 // Call the supplied function
119 f((supported[0], sections))
120}
Jooyung Han12a0b702021-08-05 23:20:31 +0900121
Jiyong Parka41535b2021-09-10 19:31:48 +0900122/// Gets the public key (in DER format) that was used to sign the given APK/APEX file
123pub fn get_public_key_der<P: AsRef<Path>>(path: P) -> Result<Box<[u8]>> {
124 let f = File::open(path.as_ref())?;
125 let mut sections = ApkSections::new(f)?;
126 find_signer_and_then(&mut sections, |(signer, _)| {
127 Ok(signer.public_key.to_vec().into_boxed_slice())
128 })
Jooyung Han12a0b702021-08-05 23:20:31 +0900129}
130
131impl Signer {
Andrew Scull9173eb82022-06-01 09:17:14 +0000132 /// Select the signature that uses the strongest algorithm according to the preferences of the
133 /// v4 signing scheme.
134 fn strongest_signature(&self) -> Result<&Signature> {
135 Ok(self
Jooyung Han12a0b702021-08-05 23:20:31 +0900136 .signatures
137 .iter()
138 .filter(|sig| is_supported_signature_algorithm(sig.signature_algorithm_id))
139 .max_by_key(|sig| rank_signature_algorithm(sig.signature_algorithm_id).unwrap())
Andrew Scull9173eb82022-06-01 09:17:14 +0000140 .ok_or_else(|| anyhow!("No supported signatures found"))?)
141 }
142
143 fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<Box<[u8]>> {
144 // 1. Choose the strongest supported signature algorithm ID from signatures.
145 let strongest = self.strongest_signature()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900146
147 // 2. Verify the corresponding signature from signatures against signed data using public key.
148 // (It is now safe to parse signed data.)
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000149 let (_, key_info) = SubjectPublicKeyInfo::from_der(self.public_key.as_ref())?;
Jooyung Han543e7122021-08-11 01:48:45 +0900150 verify_signed_data(&self.signed_data, strongest, &key_info)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900151
152 // It is now safe to parse signed data.
153 let signed_data: SignedData = self.signed_data.slice(..).read()?;
154
155 // 3. Verify the min and max SDK versions in the signed data match those specified for the
156 // signer.
157 if self.sdk_range() != signed_data.sdk_range() {
158 bail!("SDK versions mismatch between signed and unsigned in v3 signer block.");
159 }
Jooyung Hand8397852021-08-10 16:29:36 +0900160
161 // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is
162 // identical. (This is to prevent signature stripping/addition.)
163 if !self
164 .signatures
165 .iter()
166 .map(|sig| sig.signature_algorithm_id)
167 .eq(signed_data.digests.iter().map(|dig| dig.signature_algorithm_id))
168 {
169 bail!("Signature algorithms don't match between digests and signatures records");
170 }
171
172 // 5. Compute the digest of APK contents using the same digest algorithm as the digest
173 // algorithm used by the signature algorithm.
174 let digest = signed_data
175 .digests
176 .iter()
177 .find(|&dig| dig.signature_algorithm_id == strongest.signature_algorithm_id)
178 .unwrap(); // ok to unwrap since we check if two lists are the same above
179 let computed = sections.compute_digest(digest.signature_algorithm_id)?;
180
181 // 6. Verify that the computed digest is identical to the corresponding digest from digests.
182 if computed != digest.digest.as_ref() {
183 bail!(
Jooyung Han543e7122021-08-11 01:48:45 +0900184 "Digest mismatch: computed={:?} vs expected={:?}",
Jooyung Hand8397852021-08-10 16:29:36 +0900185 to_hex_string(&computed),
186 to_hex_string(&digest.digest),
187 );
188 }
189
Jooyung Han543e7122021-08-11 01:48:45 +0900190 // 7. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical
191 // to public key.
192 let cert = signed_data.certificates.first().context("No certificates listed")?;
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000193 let (_, cert) = parse_x509_certificate(cert.as_ref())?;
Jooyung Han543e7122021-08-11 01:48:45 +0900194 if cert.tbs_certificate.subject_pki != key_info {
195 bail!("Public key mismatch between certificate and signature record");
196 }
197
Jooyung Han12a0b702021-08-05 23:20:31 +0900198 // TODO(jooyung) 8. If the proof-of-rotation attribute exists for the signer verify that the struct is valid and this signer is the last certificate in the list.
Jiyong Parka41535b2021-09-10 19:31:48 +0900199 Ok(self.public_key.to_vec().into_boxed_slice())
Jooyung Han12a0b702021-08-05 23:20:31 +0900200 }
201}
202
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900203fn verify_signed_data(
204 data: &Bytes,
205 signature: &Signature,
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000206 key_info: &SubjectPublicKeyInfo,
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900207) -> Result<()> {
Andrew Scullc208eb42022-05-22 16:17:52 +0000208 let (pkey_id, padding, digest) = match signature.signature_algorithm_id {
209 SIGNATURE_RSA_PSS_WITH_SHA256 => {
210 (pkey::Id::RSA, Padding::PKCS1_PSS, MessageDigest::sha256())
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000211 }
Andrew Scullc208eb42022-05-22 16:17:52 +0000212 SIGNATURE_RSA_PSS_WITH_SHA512 => {
213 (pkey::Id::RSA, Padding::PKCS1_PSS, MessageDigest::sha512())
214 }
215 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256 => {
216 (pkey::Id::RSA, Padding::PKCS1, MessageDigest::sha256())
217 }
218 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 => {
219 (pkey::Id::RSA, Padding::PKCS1, MessageDigest::sha512())
220 }
221 SIGNATURE_ECDSA_WITH_SHA256 | SIGNATURE_VERITY_ECDSA_WITH_SHA256 => {
222 (pkey::Id::EC, Padding::NONE, MessageDigest::sha256())
223 }
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000224 // TODO(b/190343842) not implemented signature algorithm
225 SIGNATURE_ECDSA_WITH_SHA512
226 | SIGNATURE_DSA_WITH_SHA256
227 | SIGNATURE_VERITY_DSA_WITH_SHA256 => {
228 bail!(
229 "TODO(b/190343842) not implemented signature algorithm: {:#x}",
230 signature.signature_algorithm_id
231 );
232 }
233 _ => bail!("Unsupported signature algorithm: {:#x}", signature.signature_algorithm_id),
234 };
Andrew Scullc208eb42022-05-22 16:17:52 +0000235 let key = PKey::public_key_from_der(key_info.raw)?;
236 ensure!(key.id() == pkey_id, "Public key has the wrong ID");
237 let mut verifier = Verifier::new(digest, &key)?;
238 if pkey_id == pkey::Id::RSA {
239 verifier.set_rsa_padding(padding)?;
240 }
241 verifier.update(data)?;
242 let verified = verifier.verify(&signature.signature)?;
243 ensure!(verified, "Signature is invalid ");
Jooyung Han12a0b702021-08-05 23:20:31 +0900244 Ok(())
245}
246
247// ReadFromBytes implementations
248// TODO(jooyung): add derive macro: #[derive(ReadFromBytes)]
249
250impl ReadFromBytes for Signer {
251 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
252 Ok(Self {
253 signed_data: buf.read()?,
254 min_sdk: buf.read()?,
255 max_sdk: buf.read()?,
256 signatures: buf.read()?,
257 public_key: buf.read()?,
258 })
259 }
260}
261
262impl ReadFromBytes for SignedData {
263 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
264 Ok(Self {
265 digests: buf.read()?,
266 certificates: buf.read()?,
267 min_sdk: buf.read()?,
268 max_sdk: buf.read()?,
269 additional_attributes: buf.read()?,
270 })
271 }
272}
273
274impl ReadFromBytes for Signature {
275 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
276 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
277 }
278}
279
280impl ReadFromBytes for Digest {
281 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
282 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
283 }
284}
Jooyung Hand8397852021-08-10 16:29:36 +0900285
286#[inline]
287fn to_hex_string(buf: &[u8]) -> String {
288 buf.iter().map(|b| format!("{:02X}", b)).collect()
289}