blob: fac0a7fe16e634a5abfa2adcddb15ac40de60dcf [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};
Jooyung Han12a0b702021-08-05 23:20:31 +090027use std::ops::Range;
28use 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};
Jooyung Han5b4c70e2021-08-09 16:36:13 +090032use crate::sigutil::*;
Jooyung Han12a0b702021-08-05 23:20:31 +090033
34pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
35
Alice Wang92889352022-09-16 10:42:52 +000036// TODO(b/190343842): get "ro.build.version.sdk"
Jooyung Han12a0b702021-08-05 23:20:31 +090037const SDK_INT: u32 = 31;
38
Jooyung Han12a0b702021-08-05 23:20:31 +090039type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
40
Alice Wang0cafa142022-09-23 15:17:02 +000041pub(crate) struct Signer {
Jooyung Han12a0b702021-08-05 23:20:31 +090042 signed_data: LengthPrefixed<Bytes>, // not verified yet
43 min_sdk: u32,
44 max_sdk: u32,
45 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
Alice Wanga7cac422022-09-20 13:57:32 +000046 public_key: PKey<pkey::Public>,
Jooyung Han12a0b702021-08-05 23:20:31 +090047}
48
49impl Signer {
50 fn sdk_range(&self) -> Range<u32> {
51 self.min_sdk..self.max_sdk
52 }
53}
54
55struct SignedData {
56 digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
57 certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
58 min_sdk: u32,
59 max_sdk: u32,
Alice Wang4b7c0ba2022-09-07 15:12:36 +000060 #[allow(dead_code)]
Jooyung Han12a0b702021-08-05 23:20:31 +090061 additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
62}
63
64impl SignedData {
65 fn sdk_range(&self) -> Range<u32> {
66 self.min_sdk..self.max_sdk
67 }
Alice Wangcd0fa452022-09-21 09:48:33 +000068
69 fn find_digest_by_algorithm(&self, algorithm_id: SignatureAlgorithmID) -> Result<&Digest> {
70 Ok(self
71 .digests
72 .iter()
73 .find(|&dig| dig.signature_algorithm_id == Some(algorithm_id))
74 .context(format!("Digest not found for algorithm: {:?}", algorithm_id))?)
75 }
Jooyung Han12a0b702021-08-05 23:20:31 +090076}
77
Jooyung Han5b4c70e2021-08-09 16:36:13 +090078#[derive(Debug)]
Jooyung Han12a0b702021-08-05 23:20:31 +090079struct Signature {
Alice Wangd73d0ff2022-09-20 11:33:30 +000080 /// Option is used here to allow us to ignore unsupported algorithm.
81 signature_algorithm_id: Option<SignatureAlgorithmID>,
Jooyung Han12a0b702021-08-05 23:20:31 +090082 signature: LengthPrefixed<Bytes>,
83}
84
85struct Digest {
Alice Wangd73d0ff2022-09-20 11:33:30 +000086 signature_algorithm_id: Option<SignatureAlgorithmID>,
Jooyung Han12a0b702021-08-05 23:20:31 +090087 digest: LengthPrefixed<Bytes>,
88}
89
90type X509Certificate = Bytes;
91type AdditionalAttributes = Bytes;
92
Jiyong Parka41535b2021-09-10 19:31:48 +090093/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the public key
Andrew Scullf3fd4c62022-05-22 14:41:21 +000094/// associated with the signer in DER format.
Alice Wang3c016622022-09-19 09:08:27 +000095pub fn verify<P: AsRef<Path>>(apk_path: P) -> Result<Box<[u8]>> {
96 let apk = File::open(apk_path.as_ref())?;
Alice Wang71701272022-09-20 10:03:02 +000097 let (signer, mut sections) = extract_signer_and_apk_sections(apk)?;
98 signer.verify(&mut sections)
Jiyong Parka41535b2021-09-10 19:31:48 +090099}
Jooyung Han12a0b702021-08-05 23:20:31 +0900100
Jiyong Parka41535b2021-09-10 19:31:48 +0900101/// Gets the public key (in DER format) that was used to sign the given APK/APEX file
Alice Wang3c016622022-09-19 09:08:27 +0000102pub fn get_public_key_der<P: AsRef<Path>>(apk_path: P) -> Result<Box<[u8]>> {
103 let apk = File::open(apk_path.as_ref())?;
Alice Wang71701272022-09-20 10:03:02 +0000104 let (signer, _) = extract_signer_and_apk_sections(apk)?;
105 Ok(signer.public_key.public_key_to_der()?.into_boxed_slice())
Jooyung Han12a0b702021-08-05 23:20:31 +0900106}
107
Alice Wang0cafa142022-09-23 15:17:02 +0000108pub(crate) fn extract_signer_and_apk_sections<R: Read + Seek>(
109 apk: R,
110) -> Result<(Signer, ApkSections<R>)> {
Andrew Sculla11b83a2022-06-01 09:23:13 +0000111 let mut sections = ApkSections::new(apk)?;
Alice Wang71701272022-09-20 10:03:02 +0000112 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).context(
113 "Fallback to v2 when v3 block not found is not yet implemented. See b/197052981.",
114 )?;
115 let mut supported = block
116 .read::<Signers>()?
117 .into_inner()
118 .into_iter()
119 .filter(|s| s.sdk_range().contains(&SDK_INT))
120 .collect::<Vec<_>>();
121 ensure!(
122 supported.len() == 1,
123 "APK Signature Scheme V3 only supports one signer: {} signers found.",
124 supported.len()
125 );
126 Ok((supported.pop().unwrap().into_inner(), sections))
Andrew Sculla11b83a2022-06-01 09:23:13 +0000127}
128
Jooyung Han12a0b702021-08-05 23:20:31 +0900129impl Signer {
Andrew Scull9173eb82022-06-01 09:17:14 +0000130 /// Select the signature that uses the strongest algorithm according to the preferences of the
131 /// v4 signing scheme.
132 fn strongest_signature(&self) -> Result<&Signature> {
133 Ok(self
Jooyung Han12a0b702021-08-05 23:20:31 +0900134 .signatures
135 .iter()
Alice Wang50701022022-09-21 08:51:38 +0000136 .filter(|sig| sig.signature_algorithm_id.map_or(false, |algo| algo.is_supported()))
Alice Wangd73d0ff2022-09-20 11:33:30 +0000137 .max_by_key(|sig| sig.signature_algorithm_id.unwrap().content_digest_algorithm())
Alice Wangbc4b9a92022-09-16 13:13:18 +0000138 .context("No supported signatures found")?)
Andrew Scull9173eb82022-06-01 09:17:14 +0000139 }
140
Alice Wang0cafa142022-09-23 15:17:02 +0000141 pub(crate) fn pick_v4_apk_digest(&self) -> Result<(SignatureAlgorithmID, Box<[u8]>)> {
Alice Wangcd0fa452022-09-21 09:48:33 +0000142 let strongest_algorithm_id = self
143 .strongest_signature()?
144 .signature_algorithm_id
145 .context("Strongest signature should contain a valid signature algorithm.")?;
Andrew Sculla11b83a2022-06-01 09:23:13 +0000146 let signed_data: SignedData = self.signed_data.slice(..).read()?;
Alice Wangcd0fa452022-09-21 09:48:33 +0000147 let digest = signed_data.find_digest_by_algorithm(strongest_algorithm_id)?;
148 Ok((strongest_algorithm_id, digest.digest.as_ref().to_vec().into_boxed_slice()))
Andrew Sculla11b83a2022-06-01 09:23:13 +0000149 }
150
Alice Wanga7cac422022-09-20 13:57:32 +0000151 /// Verifies the strongest signature from signatures against signed data using public key.
152 /// Returns the verified signed data.
153 fn verify_signature(&self, strongest: &Signature) -> Result<SignedData> {
154 let mut verifier = strongest
155 .signature_algorithm_id
156 .context("Unsupported algorithm")?
157 .new_verifier(&self.public_key)?;
158 verifier.update(&self.signed_data)?;
159 ensure!(verifier.verify(&strongest.signature)?, "Signature is invalid.");
160 // It is now safe to parse signed data.
161 self.signed_data.slice(..).read()
162 }
163
Alice Wangaf1d15b2022-09-09 11:09:51 +0000164 /// The steps in this method implements APK Signature Scheme v3 verification step 3.
Andrew Scull9173eb82022-06-01 09:17:14 +0000165 fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<Box<[u8]>> {
166 // 1. Choose the strongest supported signature algorithm ID from signatures.
167 let strongest = self.strongest_signature()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900168
169 // 2. Verify the corresponding signature from signatures against signed data using public key.
Alice Wanga7cac422022-09-20 13:57:32 +0000170 let verified_signed_data = self.verify_signature(strongest)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900171
172 // 3. Verify the min and max SDK versions in the signed data match those specified for the
173 // signer.
Alice Wangbc4b9a92022-09-16 13:13:18 +0000174 ensure!(
Alice Wanga7cac422022-09-20 13:57:32 +0000175 self.sdk_range() == verified_signed_data.sdk_range(),
Alice Wangbc4b9a92022-09-16 13:13:18 +0000176 "SDK versions mismatch between signed and unsigned in v3 signer block."
177 );
Jooyung Hand8397852021-08-10 16:29:36 +0900178
179 // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is
180 // identical. (This is to prevent signature stripping/addition.)
Alice Wangbc4b9a92022-09-16 13:13:18 +0000181 ensure!(
182 self.signatures
183 .iter()
184 .map(|sig| sig.signature_algorithm_id)
Alice Wanga7cac422022-09-20 13:57:32 +0000185 .eq(verified_signed_data.digests.iter().map(|dig| dig.signature_algorithm_id)),
Alice Wangbc4b9a92022-09-16 13:13:18 +0000186 "Signature algorithms don't match between digests and signatures records"
187 );
Jooyung Hand8397852021-08-10 16:29:36 +0900188
189 // 5. Compute the digest of APK contents using the same digest algorithm as the digest
190 // algorithm used by the signature algorithm.
Alice Wangcd0fa452022-09-21 09:48:33 +0000191 let digest = verified_signed_data.find_digest_by_algorithm(
192 strongest.signature_algorithm_id.context("Unsupported algorithm")?,
193 )?;
194 let computed = sections.compute_digest(digest.signature_algorithm_id.unwrap())?;
Jooyung Hand8397852021-08-10 16:29:36 +0900195
196 // 6. Verify that the computed digest is identical to the corresponding digest from digests.
Alice Wangbc4b9a92022-09-16 13:13:18 +0000197 ensure!(
198 computed == digest.digest.as_ref(),
199 "Digest mismatch: computed={:?} vs expected={:?}",
200 to_hex_string(&computed),
201 to_hex_string(&digest.digest),
202 );
Jooyung Hand8397852021-08-10 16:29:36 +0900203
Alice Wang79713d92022-07-14 15:10:03 +0000204 // 7. Verify that public key of the first certificate of certificates is identical
Jooyung Han543e7122021-08-11 01:48:45 +0900205 // to public key.
Alice Wanga7cac422022-09-20 13:57:32 +0000206 let cert = verified_signed_data.certificates.first().context("No certificates listed")?;
Alice Wang79713d92022-07-14 15:10:03 +0000207 let cert = X509::from_der(cert.as_ref())?;
Alice Wangbc4b9a92022-09-16 13:13:18 +0000208 ensure!(
Alice Wanga7cac422022-09-20 13:57:32 +0000209 cert.public_key()?.public_eq(&self.public_key),
Alice Wangbc4b9a92022-09-16 13:13:18 +0000210 "Public key mismatch between certificate and signature record"
211 );
Jooyung Han543e7122021-08-11 01:48:45 +0900212
Alice Wang92889352022-09-16 10:42:52 +0000213 // TODO(b/245914104)
214 // 8. If the proof-of-rotation attribute exists for the signer verify that the
215 // struct is valid and this signer is the last certificate in the list.
Alice Wanga7cac422022-09-20 13:57:32 +0000216 Ok(self.public_key.public_key_to_der()?.into_boxed_slice())
Jooyung Han12a0b702021-08-05 23:20:31 +0900217 }
218}
219
Jooyung Han12a0b702021-08-05 23:20:31 +0900220// ReadFromBytes implementations
Alice Wang92889352022-09-16 10:42:52 +0000221// TODO(b/190343842): add derive macro: #[derive(ReadFromBytes)]
Jooyung Han12a0b702021-08-05 23:20:31 +0900222
223impl ReadFromBytes for Signer {
224 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
225 Ok(Self {
226 signed_data: buf.read()?,
227 min_sdk: buf.read()?,
228 max_sdk: buf.read()?,
229 signatures: buf.read()?,
230 public_key: buf.read()?,
231 })
232 }
233}
234
235impl ReadFromBytes for SignedData {
236 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
237 Ok(Self {
238 digests: buf.read()?,
239 certificates: buf.read()?,
240 min_sdk: buf.read()?,
241 max_sdk: buf.read()?,
242 additional_attributes: buf.read()?,
243 })
244 }
245}
246
247impl ReadFromBytes for Signature {
248 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
249 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
250 }
251}
252
253impl ReadFromBytes for Digest {
254 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
255 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
256 }
257}
Jooyung Hand8397852021-08-10 16:29:36 +0900258
Alice Wanga7cac422022-09-20 13:57:32 +0000259impl ReadFromBytes for PKey<pkey::Public> {
260 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
261 let raw_public_key = buf.read::<LengthPrefixed<Bytes>>()?;
262 Ok(PKey::public_key_from_der(raw_public_key.as_ref())?)
263 }
264}
265
Jooyung Hand8397852021-08-10 16:29:36 +0900266#[inline]
Alice Wang98073222022-09-09 14:08:19 +0000267pub(crate) fn to_hex_string(buf: &[u8]) -> String {
Jooyung Hand8397852021-08-10 16:29:36 +0900268 buf.iter().map(|b| format!("{:02X}", b)).collect()
269}