blob: 8a8ad73b9064f08035c9387c0383dcd2d94fce68 [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
Alice Wangaf1d15b2022-09-09 11:09:51 +000018//!
19//! [v3 verification]: https://source.android.com/security/apksigning/v3#verification
Jooyung Han12a0b702021-08-05 23:20:31 +090020
Alice Wangbc4b9a92022-09-16 13:13:18 +000021use anyhow::{ensure, Context, Result};
Jooyung Han12a0b702021-08-05 23:20:31 +090022use bytes::Bytes;
Andrew Scullc208eb42022-05-22 16:17:52 +000023use openssl::pkey::{self, PKey};
Alice Wang79713d92022-07-14 15:10:03 +000024use openssl::x509::X509;
Jooyung Han12a0b702021-08-05 23:20:31 +090025use std::fs::File;
Jooyung Hand8397852021-08-10 16:29:36 +090026use std::io::{Read, Seek};
Alan Stokes25f69362023-03-06 16:51:54 +000027use std::ops::RangeInclusive;
Jooyung Han12a0b702021-08-05 23:20:31 +090028use std::path::Path;
29
Alice Wang5d0f89a2022-09-15 15:06:10 +000030use crate::algorithms::SignatureAlgorithmID;
Jooyung Han12a0b702021-08-05 23:20:31 +090031use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
Alan Stokes068f6d42023-10-09 10:13:03 +010032use crate::sigutil::ApkSections;
Jooyung Han12a0b702021-08-05 23:20:31 +090033
34pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
35
Jooyung Han12a0b702021-08-05 23:20:31 +090036type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
37
Alan Stokes25f69362023-03-06 16:51:54 +000038#[derive(Debug)]
Alice Wang0cafa142022-09-23 15:17:02 +000039pub(crate) struct Signer {
Jooyung Han12a0b702021-08-05 23:20:31 +090040 signed_data: LengthPrefixed<Bytes>, // not verified yet
41 min_sdk: u32,
42 max_sdk: u32,
43 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
Alice Wanga7cac422022-09-20 13:57:32 +000044 public_key: PKey<pkey::Public>,
Jooyung Han12a0b702021-08-05 23:20:31 +090045}
46
47impl Signer {
Alan Stokes25f69362023-03-06 16:51:54 +000048 fn sdk_range(&self) -> RangeInclusive<u32> {
49 self.min_sdk..=self.max_sdk
Jooyung Han12a0b702021-08-05 23:20:31 +090050 }
51}
52
53struct SignedData {
54 digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
55 certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
56 min_sdk: u32,
57 max_sdk: u32,
Alice Wang4b7c0ba2022-09-07 15:12:36 +000058 #[allow(dead_code)]
Jooyung Han12a0b702021-08-05 23:20:31 +090059 additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
60}
61
62impl SignedData {
Alan Stokes25f69362023-03-06 16:51:54 +000063 fn sdk_range(&self) -> RangeInclusive<u32> {
64 self.min_sdk..=self.max_sdk
Jooyung Han12a0b702021-08-05 23:20:31 +090065 }
Alice Wangcd0fa452022-09-21 09:48:33 +000066
67 fn find_digest_by_algorithm(&self, algorithm_id: SignatureAlgorithmID) -> Result<&Digest> {
68 Ok(self
69 .digests
70 .iter()
71 .find(|&dig| dig.signature_algorithm_id == Some(algorithm_id))
72 .context(format!("Digest not found for algorithm: {:?}", algorithm_id))?)
73 }
Jooyung Han12a0b702021-08-05 23:20:31 +090074}
75
Jooyung Han5b4c70e2021-08-09 16:36:13 +090076#[derive(Debug)]
Alice Wangf27626a2022-09-27 12:36:22 +000077pub(crate) struct Signature {
Alice Wangd73d0ff2022-09-20 11:33:30 +000078 /// Option is used here to allow us to ignore unsupported algorithm.
Alice Wangf27626a2022-09-27 12:36:22 +000079 pub(crate) signature_algorithm_id: Option<SignatureAlgorithmID>,
Jooyung Han12a0b702021-08-05 23:20:31 +090080 signature: LengthPrefixed<Bytes>,
81}
82
83struct Digest {
Alice Wangd73d0ff2022-09-20 11:33:30 +000084 signature_algorithm_id: Option<SignatureAlgorithmID>,
Jooyung Han12a0b702021-08-05 23:20:31 +090085 digest: LengthPrefixed<Bytes>,
86}
87
88type X509Certificate = Bytes;
89type AdditionalAttributes = Bytes;
90
Jiyong Parka41535b2021-09-10 19:31:48 +090091/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the public key
Andrew Scullf3fd4c62022-05-22 14:41:21 +000092/// associated with the signer in DER format.
Alan Stokes25f69362023-03-06 16:51:54 +000093pub fn verify<P: AsRef<Path>>(apk_path: P, current_sdk: u32) -> Result<Box<[u8]>> {
Alice Wang3c016622022-09-19 09:08:27 +000094 let apk = File::open(apk_path.as_ref())?;
Alan Stokes25f69362023-03-06 16:51:54 +000095 let (signer, mut sections) = extract_signer_and_apk_sections(apk, current_sdk)?;
Alice Wang71701272022-09-20 10:03:02 +000096 signer.verify(&mut sections)
Jiyong Parka41535b2021-09-10 19:31:48 +090097}
Jooyung Han12a0b702021-08-05 23:20:31 +090098
Jiyong Parka41535b2021-09-10 19:31:48 +090099/// Gets the public key (in DER format) that was used to sign the given APK/APEX file
Alan Stokes25f69362023-03-06 16:51:54 +0000100pub fn get_public_key_der<P: AsRef<Path>>(apk_path: P, current_sdk: u32) -> Result<Box<[u8]>> {
Alice Wang3c016622022-09-19 09:08:27 +0000101 let apk = File::open(apk_path.as_ref())?;
Alan Stokes25f69362023-03-06 16:51:54 +0000102 let (signer, _) = extract_signer_and_apk_sections(apk, current_sdk)?;
Alice Wang71701272022-09-20 10:03:02 +0000103 Ok(signer.public_key.public_key_to_der()?.into_boxed_slice())
Jooyung Han12a0b702021-08-05 23:20:31 +0900104}
105
Alice Wang0cafa142022-09-23 15:17:02 +0000106pub(crate) fn extract_signer_and_apk_sections<R: Read + Seek>(
107 apk: R,
Alan Stokes25f69362023-03-06 16:51:54 +0000108 current_sdk: u32,
Alice Wang0cafa142022-09-23 15:17:02 +0000109) -> Result<(Signer, ApkSections<R>)> {
Andrew Sculla11b83a2022-06-01 09:23:13 +0000110 let mut sections = ApkSections::new(apk)?;
Alice Wang71701272022-09-20 10:03:02 +0000111 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).context(
Alan Stokesa6876992023-01-20 12:26:25 +0000112 "Fallback to v2 when v3 block not found is not yet implemented.", // b/197052981
Alice Wang71701272022-09-20 10:03:02 +0000113 )?;
Alan Stokes25f69362023-03-06 16:51:54 +0000114 let signers = block.read::<Signers>()?.into_inner();
115 let mut supported =
116 signers.into_iter().filter(|s| s.sdk_range().contains(&current_sdk)).collect::<Vec<_>>();
Alice Wang71701272022-09-20 10:03:02 +0000117 ensure!(
118 supported.len() == 1,
119 "APK Signature Scheme V3 only supports one signer: {} signers found.",
120 supported.len()
121 );
122 Ok((supported.pop().unwrap().into_inner(), sections))
Andrew Sculla11b83a2022-06-01 09:23:13 +0000123}
124
Jooyung Han12a0b702021-08-05 23:20:31 +0900125impl Signer {
Alice Wangf27626a2022-09-27 12:36:22 +0000126 /// Selects the signature that has the strongest supported `SignatureAlgorithmID`.
127 /// The strongest signature is used in both v3 verification and v4 apk digest computation.
128 pub(crate) fn strongest_signature(&self) -> Result<&Signature> {
Andrew Scull9173eb82022-06-01 09:17:14 +0000129 Ok(self
Jooyung Han12a0b702021-08-05 23:20:31 +0900130 .signatures
131 .iter()
Alice Wang50701022022-09-21 08:51:38 +0000132 .filter(|sig| sig.signature_algorithm_id.map_or(false, |algo| algo.is_supported()))
Alice Wangd73d0ff2022-09-20 11:33:30 +0000133 .max_by_key(|sig| sig.signature_algorithm_id.unwrap().content_digest_algorithm())
Alan Stokesa6876992023-01-20 12:26:25 +0000134 .context("No supported APK signatures found; DSA is not supported")?)
Andrew Scull9173eb82022-06-01 09:17:14 +0000135 }
136
Alice Wangf27626a2022-09-27 12:36:22 +0000137 pub(crate) fn find_digest_by_algorithm(
138 &self,
139 algorithm_id: SignatureAlgorithmID,
140 ) -> Result<Box<[u8]>> {
Andrew Sculla11b83a2022-06-01 09:23:13 +0000141 let signed_data: SignedData = self.signed_data.slice(..).read()?;
Alice Wangf27626a2022-09-27 12:36:22 +0000142 let digest = signed_data.find_digest_by_algorithm(algorithm_id)?;
143 Ok(digest.digest.as_ref().to_vec().into_boxed_slice())
Andrew Sculla11b83a2022-06-01 09:23:13 +0000144 }
145
Alice Wanga7cac422022-09-20 13:57:32 +0000146 /// Verifies the strongest signature from signatures against signed data using public key.
147 /// Returns the verified signed data.
148 fn verify_signature(&self, strongest: &Signature) -> Result<SignedData> {
149 let mut verifier = strongest
150 .signature_algorithm_id
151 .context("Unsupported algorithm")?
152 .new_verifier(&self.public_key)?;
153 verifier.update(&self.signed_data)?;
154 ensure!(verifier.verify(&strongest.signature)?, "Signature is invalid.");
155 // It is now safe to parse signed data.
156 self.signed_data.slice(..).read()
157 }
158
Alice Wangaf1d15b2022-09-09 11:09:51 +0000159 /// The steps in this method implements APK Signature Scheme v3 verification step 3.
Andrew Scull9173eb82022-06-01 09:17:14 +0000160 fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<Box<[u8]>> {
161 // 1. Choose the strongest supported signature algorithm ID from signatures.
162 let strongest = self.strongest_signature()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900163
Alan Stokes068f6d42023-10-09 10:13:03 +0100164 // 2. Verify the corresponding signature from signatures against signed data using public
165 // key.
Alice Wanga7cac422022-09-20 13:57:32 +0000166 let verified_signed_data = self.verify_signature(strongest)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900167
168 // 3. Verify the min and max SDK versions in the signed data match those specified for the
169 // signer.
Alice Wangbc4b9a92022-09-16 13:13:18 +0000170 ensure!(
Alice Wanga7cac422022-09-20 13:57:32 +0000171 self.sdk_range() == verified_signed_data.sdk_range(),
Alice Wangbc4b9a92022-09-16 13:13:18 +0000172 "SDK versions mismatch between signed and unsigned in v3 signer block."
173 );
Jooyung Hand8397852021-08-10 16:29:36 +0900174
175 // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is
176 // identical. (This is to prevent signature stripping/addition.)
Alice Wangbc4b9a92022-09-16 13:13:18 +0000177 ensure!(
178 self.signatures
179 .iter()
180 .map(|sig| sig.signature_algorithm_id)
Alice Wanga7cac422022-09-20 13:57:32 +0000181 .eq(verified_signed_data.digests.iter().map(|dig| dig.signature_algorithm_id)),
Alice Wangbc4b9a92022-09-16 13:13:18 +0000182 "Signature algorithms don't match between digests and signatures records"
183 );
Jooyung Hand8397852021-08-10 16:29:36 +0900184
185 // 5. Compute the digest of APK contents using the same digest algorithm as the digest
186 // algorithm used by the signature algorithm.
Alice Wangcd0fa452022-09-21 09:48:33 +0000187 let digest = verified_signed_data.find_digest_by_algorithm(
188 strongest.signature_algorithm_id.context("Unsupported algorithm")?,
189 )?;
190 let computed = sections.compute_digest(digest.signature_algorithm_id.unwrap())?;
Jooyung Hand8397852021-08-10 16:29:36 +0900191
192 // 6. Verify that the computed digest is identical to the corresponding digest from digests.
Alice Wangbc4b9a92022-09-16 13:13:18 +0000193 ensure!(
194 computed == digest.digest.as_ref(),
195 "Digest mismatch: computed={:?} vs expected={:?}",
Tanmoy Mollik40ff8032022-11-25 15:00:04 +0000196 hex::encode(&computed),
197 hex::encode(digest.digest.as_ref()),
Alice Wangbc4b9a92022-09-16 13:13:18 +0000198 );
Jooyung Hand8397852021-08-10 16:29:36 +0900199
Alan Stokes068f6d42023-10-09 10:13:03 +0100200 // 7. Verify that public key of the first certificate of certificates is identical to public
201 // key.
Alice Wanga7cac422022-09-20 13:57:32 +0000202 let cert = verified_signed_data.certificates.first().context("No certificates listed")?;
Alice Wang79713d92022-07-14 15:10:03 +0000203 let cert = X509::from_der(cert.as_ref())?;
Alice Wangbc4b9a92022-09-16 13:13:18 +0000204 ensure!(
Alice Wanga7cac422022-09-20 13:57:32 +0000205 cert.public_key()?.public_eq(&self.public_key),
Alice Wangbc4b9a92022-09-16 13:13:18 +0000206 "Public key mismatch between certificate and signature record"
207 );
Jooyung Han543e7122021-08-11 01:48:45 +0900208
Alice Wang92889352022-09-16 10:42:52 +0000209 // TODO(b/245914104)
210 // 8. If the proof-of-rotation attribute exists for the signer verify that the
211 // struct is valid and this signer is the last certificate in the list.
Alice Wanga7cac422022-09-20 13:57:32 +0000212 Ok(self.public_key.public_key_to_der()?.into_boxed_slice())
Jooyung Han12a0b702021-08-05 23:20:31 +0900213 }
214}
215
Jooyung Han12a0b702021-08-05 23:20:31 +0900216// ReadFromBytes implementations
Alice Wang92889352022-09-16 10:42:52 +0000217// TODO(b/190343842): add derive macro: #[derive(ReadFromBytes)]
Jooyung Han12a0b702021-08-05 23:20:31 +0900218
219impl ReadFromBytes for Signer {
220 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
221 Ok(Self {
222 signed_data: buf.read()?,
223 min_sdk: buf.read()?,
224 max_sdk: buf.read()?,
225 signatures: buf.read()?,
226 public_key: buf.read()?,
227 })
228 }
229}
230
231impl ReadFromBytes for SignedData {
232 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
233 Ok(Self {
234 digests: buf.read()?,
235 certificates: buf.read()?,
236 min_sdk: buf.read()?,
237 max_sdk: buf.read()?,
238 additional_attributes: buf.read()?,
239 })
240 }
241}
242
243impl ReadFromBytes for Signature {
244 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
245 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
246 }
247}
248
249impl ReadFromBytes for Digest {
250 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
251 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
252 }
253}
Jooyung Hand8397852021-08-10 16:29:36 +0900254
Alice Wanga7cac422022-09-20 13:57:32 +0000255impl ReadFromBytes for PKey<pkey::Public> {
256 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
257 let raw_public_key = buf.read::<LengthPrefixed<Bytes>>()?;
258 Ok(PKey::public_key_from_der(raw_public_key.as_ref())?)
259 }
260}