blob: a3e738b77304af8310a697bee64593792ae9159b [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
41struct Signer {
42 signed_data: LengthPrefixed<Bytes>, // not verified yet
43 min_sdk: u32,
44 max_sdk: u32,
45 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
Andrew Walbran117cd5e2021-08-13 11:42:13 +000046 public_key: LengthPrefixed<Bytes>,
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 }
68}
69
Jooyung Han5b4c70e2021-08-09 16:36:13 +090070#[derive(Debug)]
Jooyung Han12a0b702021-08-05 23:20:31 +090071struct Signature {
Alice Wangd73d0ff2022-09-20 11:33:30 +000072 /// Option is used here to allow us to ignore unsupported algorithm.
73 signature_algorithm_id: Option<SignatureAlgorithmID>,
Jooyung Han12a0b702021-08-05 23:20:31 +090074 signature: LengthPrefixed<Bytes>,
75}
76
77struct Digest {
Alice Wangd73d0ff2022-09-20 11:33:30 +000078 signature_algorithm_id: Option<SignatureAlgorithmID>,
Jooyung Han12a0b702021-08-05 23:20:31 +090079 digest: LengthPrefixed<Bytes>,
80}
81
82type X509Certificate = Bytes;
83type AdditionalAttributes = Bytes;
84
Jiyong Parka41535b2021-09-10 19:31:48 +090085/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the public key
Andrew Scullf3fd4c62022-05-22 14:41:21 +000086/// associated with the signer in DER format.
Alice Wang3c016622022-09-19 09:08:27 +000087pub fn verify<P: AsRef<Path>>(apk_path: P) -> Result<Box<[u8]>> {
88 let apk = File::open(apk_path.as_ref())?;
89 let mut sections = ApkSections::new(apk)?;
Jiyong Parka41535b2021-09-10 19:31:48 +090090 find_signer_and_then(&mut sections, |(signer, sections)| signer.verify(sections))
Jooyung Han12a0b702021-08-05 23:20:31 +090091}
92
Jiyong Parka41535b2021-09-10 19:31:48 +090093/// Finds the supported signer and execute a function on it.
94fn find_signer_and_then<R, U, F>(sections: &mut ApkSections<R>, f: F) -> Result<U>
95where
96 R: Read + Seek,
97 F: FnOnce((&Signer, &mut ApkSections<R>)) -> Result<U>,
98{
Jooyung Hand8397852021-08-10 16:29:36 +090099 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900100 // parse v3 scheme block
Jooyung Hand8397852021-08-10 16:29:36 +0900101 let signers = block.read::<Signers>()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900102
103 // find supported by platform
Jiyong Parka41535b2021-09-10 19:31:48 +0900104 let supported = signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>();
Jooyung Han12a0b702021-08-05 23:20:31 +0900105
106 // there should be exactly one
Alice Wangbc4b9a92022-09-16 13:13:18 +0000107 ensure!(
108 supported.len() == 1,
109 "APK Signature Scheme V3 only supports one signer: {} signers found.",
110 supported.len()
111 );
Jooyung Han12a0b702021-08-05 23:20:31 +0900112
Jiyong Parka41535b2021-09-10 19:31:48 +0900113 // Call the supplied function
114 f((supported[0], sections))
115}
Jooyung Han12a0b702021-08-05 23:20:31 +0900116
Jiyong Parka41535b2021-09-10 19:31:48 +0900117/// Gets the public key (in DER format) that was used to sign the given APK/APEX file
Alice Wang3c016622022-09-19 09:08:27 +0000118pub fn get_public_key_der<P: AsRef<Path>>(apk_path: P) -> Result<Box<[u8]>> {
119 let apk = File::open(apk_path.as_ref())?;
120 let mut sections = ApkSections::new(apk)?;
Jiyong Parka41535b2021-09-10 19:31:48 +0900121 find_signer_and_then(&mut sections, |(signer, _)| {
122 Ok(signer.public_key.to_vec().into_boxed_slice())
123 })
Jooyung Han12a0b702021-08-05 23:20:31 +0900124}
125
Alice Wanga94ba172022-09-08 15:25:31 +0000126/// Gets the v4 [apk_digest].
127///
128/// [apk_digest]: https://source.android.com/docs/security/apksigning/v4#apk-digest
Alice Wang2ef30742022-09-19 11:59:17 +0000129pub fn pick_v4_apk_digest<R: Read + Seek>(apk: R) -> Result<(SignatureAlgorithmID, Box<[u8]>)> {
Andrew Sculla11b83a2022-06-01 09:23:13 +0000130 let mut sections = ApkSections::new(apk)?;
131 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
132 let signers = block.read::<Signers>()?;
Alice Wanga94ba172022-09-08 15:25:31 +0000133 ensure!(signers.len() == 1, "should only have one signer");
Andrew Sculla11b83a2022-06-01 09:23:13 +0000134 signers[0].pick_v4_apk_digest()
135}
136
Jooyung Han12a0b702021-08-05 23:20:31 +0900137impl Signer {
Andrew Scull9173eb82022-06-01 09:17:14 +0000138 /// Select the signature that uses the strongest algorithm according to the preferences of the
139 /// v4 signing scheme.
140 fn strongest_signature(&self) -> Result<&Signature> {
141 Ok(self
Jooyung Han12a0b702021-08-05 23:20:31 +0900142 .signatures
143 .iter()
Alice Wangd73d0ff2022-09-20 11:33:30 +0000144 .filter(|sig| sig.signature_algorithm_id.is_some())
145 .max_by_key(|sig| sig.signature_algorithm_id.unwrap().content_digest_algorithm())
Alice Wangbc4b9a92022-09-16 13:13:18 +0000146 .context("No supported signatures found")?)
Andrew Scull9173eb82022-06-01 09:17:14 +0000147 }
148
Alice Wang2ef30742022-09-19 11:59:17 +0000149 fn pick_v4_apk_digest(&self) -> Result<(SignatureAlgorithmID, Box<[u8]>)> {
Andrew Sculla11b83a2022-06-01 09:23:13 +0000150 let strongest = self.strongest_signature()?;
151 let signed_data: SignedData = self.signed_data.slice(..).read()?;
152 let digest = signed_data
153 .digests
154 .iter()
155 .find(|&dig| dig.signature_algorithm_id == strongest.signature_algorithm_id)
Alice Wangbc4b9a92022-09-16 13:13:18 +0000156 .context("Digest not found")?;
Alice Wangd73d0ff2022-09-20 11:33:30 +0000157 Ok((
158 digest.signature_algorithm_id.context("Unsupported algorithm")?,
159 digest.digest.as_ref().to_vec().into_boxed_slice(),
160 ))
Andrew Sculla11b83a2022-06-01 09:23:13 +0000161 }
162
Alice Wangaf1d15b2022-09-09 11:09:51 +0000163 /// The steps in this method implements APK Signature Scheme v3 verification step 3.
Andrew Scull9173eb82022-06-01 09:17:14 +0000164 fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<Box<[u8]>> {
165 // 1. Choose the strongest supported signature algorithm ID from signatures.
166 let strongest = self.strongest_signature()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900167
168 // 2. Verify the corresponding signature from signatures against signed data using public key.
169 // (It is now safe to parse signed data.)
Alice Wang79713d92022-07-14 15:10:03 +0000170 let public_key = PKey::public_key_from_der(self.public_key.as_ref())?;
171 verify_signed_data(&self.signed_data, strongest, &public_key)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900172
173 // It is now safe to parse signed data.
174 let signed_data: SignedData = self.signed_data.slice(..).read()?;
175
176 // 3. Verify the min and max SDK versions in the signed data match those specified for the
177 // signer.
Alice Wangbc4b9a92022-09-16 13:13:18 +0000178 ensure!(
179 self.sdk_range() == signed_data.sdk_range(),
180 "SDK versions mismatch between signed and unsigned in v3 signer block."
181 );
Jooyung Hand8397852021-08-10 16:29:36 +0900182
183 // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is
184 // identical. (This is to prevent signature stripping/addition.)
Alice Wangbc4b9a92022-09-16 13:13:18 +0000185 ensure!(
186 self.signatures
187 .iter()
188 .map(|sig| sig.signature_algorithm_id)
189 .eq(signed_data.digests.iter().map(|dig| dig.signature_algorithm_id)),
190 "Signature algorithms don't match between digests and signatures records"
191 );
Jooyung Hand8397852021-08-10 16:29:36 +0900192
193 // 5. Compute the digest of APK contents using the same digest algorithm as the digest
194 // algorithm used by the signature algorithm.
195 let digest = signed_data
196 .digests
197 .iter()
198 .find(|&dig| dig.signature_algorithm_id == strongest.signature_algorithm_id)
199 .unwrap(); // ok to unwrap since we check if two lists are the same above
Alice Wangd73d0ff2022-09-20 11:33:30 +0000200 let computed = sections
201 .compute_digest(digest.signature_algorithm_id.context("Unsupported algorithm")?)?;
Jooyung Hand8397852021-08-10 16:29:36 +0900202
203 // 6. Verify that the computed digest is identical to the corresponding digest from digests.
Alice Wangbc4b9a92022-09-16 13:13:18 +0000204 ensure!(
205 computed == digest.digest.as_ref(),
206 "Digest mismatch: computed={:?} vs expected={:?}",
207 to_hex_string(&computed),
208 to_hex_string(&digest.digest),
209 );
Jooyung Hand8397852021-08-10 16:29:36 +0900210
Alice Wang79713d92022-07-14 15:10:03 +0000211 // 7. Verify that public key of the first certificate of certificates is identical
Jooyung Han543e7122021-08-11 01:48:45 +0900212 // to public key.
213 let cert = signed_data.certificates.first().context("No certificates listed")?;
Alice Wang79713d92022-07-14 15:10:03 +0000214 let cert = X509::from_der(cert.as_ref())?;
Alice Wangbc4b9a92022-09-16 13:13:18 +0000215 ensure!(
216 cert.public_key()?.public_eq(&public_key),
217 "Public key mismatch between certificate and signature record"
218 );
Jooyung Han543e7122021-08-11 01:48:45 +0900219
Alice Wang92889352022-09-16 10:42:52 +0000220 // TODO(b/245914104)
221 // 8. If the proof-of-rotation attribute exists for the signer verify that the
222 // struct is valid and this signer is the last certificate in the list.
Jiyong Parka41535b2021-09-10 19:31:48 +0900223 Ok(self.public_key.to_vec().into_boxed_slice())
Jooyung Han12a0b702021-08-05 23:20:31 +0900224 }
225}
226
Alice Wanga66b5c02022-09-16 07:25:17 +0000227fn verify_signed_data(
228 data: &Bytes,
229 signature: &Signature,
230 public_key: &PKey<pkey::Public>,
231) -> Result<()> {
Alice Wangd73d0ff2022-09-20 11:33:30 +0000232 let mut verifier = signature
233 .signature_algorithm_id
Alice Wanga66b5c02022-09-16 07:25:17 +0000234 .context("Unsupported algorithm")?
235 .new_verifier(public_key)?;
Andrew Scullc208eb42022-05-22 16:17:52 +0000236 verifier.update(data)?;
237 let verified = verifier.verify(&signature.signature)?;
238 ensure!(verified, "Signature is invalid ");
Jooyung Han12a0b702021-08-05 23:20:31 +0900239 Ok(())
240}
241
242// ReadFromBytes implementations
Alice Wang92889352022-09-16 10:42:52 +0000243// TODO(b/190343842): add derive macro: #[derive(ReadFromBytes)]
Jooyung Han12a0b702021-08-05 23:20:31 +0900244
245impl ReadFromBytes for Signer {
246 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
247 Ok(Self {
248 signed_data: buf.read()?,
249 min_sdk: buf.read()?,
250 max_sdk: buf.read()?,
251 signatures: buf.read()?,
252 public_key: buf.read()?,
253 })
254 }
255}
256
257impl ReadFromBytes for SignedData {
258 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
259 Ok(Self {
260 digests: buf.read()?,
261 certificates: buf.read()?,
262 min_sdk: buf.read()?,
263 max_sdk: buf.read()?,
264 additional_attributes: buf.read()?,
265 })
266 }
267}
268
269impl ReadFromBytes for Signature {
270 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
271 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
272 }
273}
274
275impl ReadFromBytes for Digest {
276 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
277 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
278 }
279}
Jooyung Hand8397852021-08-10 16:29:36 +0900280
281#[inline]
Alice Wang98073222022-09-09 14:08:19 +0000282pub(crate) fn to_hex_string(buf: &[u8]) -> String {
Jooyung Hand8397852021-08-10 16:29:36 +0900283 buf.iter().map(|b| format!("{:02X}", b)).collect()
284}