blob: 76617e1838cd31a1d34e420d208e3d0d36a6220f [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;
Alice Wang5d0f89a2022-09-15 15:06:10 +000023use num_traits::FromPrimitive;
Andrew Scullc208eb42022-05-22 16:17:52 +000024use openssl::pkey::{self, PKey};
Alice Wang79713d92022-07-14 15:10:03 +000025use openssl::x509::X509;
Jooyung Han12a0b702021-08-05 23:20:31 +090026use std::fs::File;
Jooyung Hand8397852021-08-10 16:29:36 +090027use std::io::{Read, Seek};
Jooyung Han12a0b702021-08-05 23:20:31 +090028use std::ops::Range;
29use std::path::Path;
30
Alice Wang5d0f89a2022-09-15 15:06:10 +000031use crate::algorithms::SignatureAlgorithmID;
Jooyung Han12a0b702021-08-05 23:20:31 +090032use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
Jooyung Han5b4c70e2021-08-09 16:36:13 +090033use crate::sigutil::*;
Jooyung Han12a0b702021-08-05 23:20:31 +090034
35pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
36
Alice Wang92889352022-09-16 10:42:52 +000037// TODO(b/190343842): get "ro.build.version.sdk"
Jooyung Han12a0b702021-08-05 23:20:31 +090038const SDK_INT: u32 = 31;
39
Jooyung Han12a0b702021-08-05 23:20:31 +090040type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
41
42struct Signer {
43 signed_data: LengthPrefixed<Bytes>, // not verified yet
44 min_sdk: u32,
45 max_sdk: u32,
46 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
Andrew Walbran117cd5e2021-08-13 11:42:13 +000047 public_key: LengthPrefixed<Bytes>,
Jooyung Han12a0b702021-08-05 23:20:31 +090048}
49
50impl Signer {
51 fn sdk_range(&self) -> Range<u32> {
52 self.min_sdk..self.max_sdk
53 }
54}
55
56struct SignedData {
57 digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
58 certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
59 min_sdk: u32,
60 max_sdk: u32,
Alice Wang4b7c0ba2022-09-07 15:12:36 +000061 #[allow(dead_code)]
Jooyung Han12a0b702021-08-05 23:20:31 +090062 additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
63}
64
65impl SignedData {
66 fn sdk_range(&self) -> Range<u32> {
67 self.min_sdk..self.max_sdk
68 }
69}
70
Jooyung Han5b4c70e2021-08-09 16:36:13 +090071#[derive(Debug)]
Jooyung Han12a0b702021-08-05 23:20:31 +090072struct Signature {
Alice Wang5d0f89a2022-09-15 15:06:10 +000073 /// TODO(b/246254355): Change the type of signature_algorithm_id to SignatureAlgorithmID
Jooyung Han12a0b702021-08-05 23:20:31 +090074 signature_algorithm_id: u32,
75 signature: LengthPrefixed<Bytes>,
76}
77
78struct Digest {
79 signature_algorithm_id: u32,
80 digest: LengthPrefixed<Bytes>,
81}
82
83type X509Certificate = Bytes;
84type AdditionalAttributes = Bytes;
85
Jiyong Parka41535b2021-09-10 19:31:48 +090086/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the public key
Andrew Scullf3fd4c62022-05-22 14:41:21 +000087/// associated with the signer in DER format.
Alice Wang3c016622022-09-19 09:08:27 +000088pub fn verify<P: AsRef<Path>>(apk_path: P) -> Result<Box<[u8]>> {
89 let apk = File::open(apk_path.as_ref())?;
90 let mut sections = ApkSections::new(apk)?;
Jiyong Parka41535b2021-09-10 19:31:48 +090091 find_signer_and_then(&mut sections, |(signer, sections)| signer.verify(sections))
Jooyung Han12a0b702021-08-05 23:20:31 +090092}
93
Jiyong Parka41535b2021-09-10 19:31:48 +090094/// Finds the supported signer and execute a function on it.
95fn find_signer_and_then<R, U, F>(sections: &mut ApkSections<R>, f: F) -> Result<U>
96where
97 R: Read + Seek,
98 F: FnOnce((&Signer, &mut ApkSections<R>)) -> Result<U>,
99{
Jooyung Hand8397852021-08-10 16:29:36 +0900100 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900101 // parse v3 scheme block
Jooyung Hand8397852021-08-10 16:29:36 +0900102 let signers = block.read::<Signers>()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900103
104 // find supported by platform
Jiyong Parka41535b2021-09-10 19:31:48 +0900105 let supported = signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>();
Jooyung Han12a0b702021-08-05 23:20:31 +0900106
107 // there should be exactly one
Alice Wangbc4b9a92022-09-16 13:13:18 +0000108 ensure!(
109 supported.len() == 1,
110 "APK Signature Scheme V3 only supports one signer: {} signers found.",
111 supported.len()
112 );
Jooyung Han12a0b702021-08-05 23:20:31 +0900113
Jiyong Parka41535b2021-09-10 19:31:48 +0900114 // Call the supplied function
115 f((supported[0], sections))
116}
Jooyung Han12a0b702021-08-05 23:20:31 +0900117
Jiyong Parka41535b2021-09-10 19:31:48 +0900118/// Gets the public key (in DER format) that was used to sign the given APK/APEX file
Alice Wang3c016622022-09-19 09:08:27 +0000119pub fn get_public_key_der<P: AsRef<Path>>(apk_path: P) -> Result<Box<[u8]>> {
120 let apk = File::open(apk_path.as_ref())?;
121 let mut sections = ApkSections::new(apk)?;
Jiyong Parka41535b2021-09-10 19:31:48 +0900122 find_signer_and_then(&mut sections, |(signer, _)| {
123 Ok(signer.public_key.to_vec().into_boxed_slice())
124 })
Jooyung Han12a0b702021-08-05 23:20:31 +0900125}
126
Alice Wanga94ba172022-09-08 15:25:31 +0000127/// Gets the v4 [apk_digest].
128///
129/// [apk_digest]: https://source.android.com/docs/security/apksigning/v4#apk-digest
Andrew Sculla11b83a2022-06-01 09:23:13 +0000130pub fn pick_v4_apk_digest<R: Read + Seek>(apk: R) -> Result<(u32, Box<[u8]>)> {
131 let mut sections = ApkSections::new(apk)?;
132 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
133 let signers = block.read::<Signers>()?;
Alice Wanga94ba172022-09-08 15:25:31 +0000134 ensure!(signers.len() == 1, "should only have one signer");
Andrew Sculla11b83a2022-06-01 09:23:13 +0000135 signers[0].pick_v4_apk_digest()
136}
137
Jooyung Han12a0b702021-08-05 23:20:31 +0900138impl Signer {
Andrew Scull9173eb82022-06-01 09:17:14 +0000139 /// Select the signature that uses the strongest algorithm according to the preferences of the
140 /// v4 signing scheme.
141 fn strongest_signature(&self) -> Result<&Signature> {
142 Ok(self
Jooyung Han12a0b702021-08-05 23:20:31 +0900143 .signatures
144 .iter()
Alice Wang5d0f89a2022-09-15 15:06:10 +0000145 .filter(|sig| SignatureAlgorithmID::from_u32(sig.signature_algorithm_id).is_some())
146 .max_by_key(|sig| SignatureAlgorithmID::from_u32(sig.signature_algorithm_id).unwrap())
Alice Wangbc4b9a92022-09-16 13:13:18 +0000147 .context("No supported signatures found")?)
Andrew Scull9173eb82022-06-01 09:17:14 +0000148 }
149
Andrew Sculla11b83a2022-06-01 09:23:13 +0000150 fn pick_v4_apk_digest(&self) -> Result<(u32, Box<[u8]>)> {
151 let strongest = self.strongest_signature()?;
152 let signed_data: SignedData = self.signed_data.slice(..).read()?;
153 let digest = signed_data
154 .digests
155 .iter()
156 .find(|&dig| dig.signature_algorithm_id == strongest.signature_algorithm_id)
Alice Wangbc4b9a92022-09-16 13:13:18 +0000157 .context("Digest not found")?;
Andrew Sculla11b83a2022-06-01 09:23:13 +0000158 Ok((digest.signature_algorithm_id, digest.digest.as_ref().to_vec().into_boxed_slice()))
159 }
160
Alice Wangaf1d15b2022-09-09 11:09:51 +0000161 /// The steps in this method implements APK Signature Scheme v3 verification step 3.
Andrew Scull9173eb82022-06-01 09:17:14 +0000162 fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<Box<[u8]>> {
163 // 1. Choose the strongest supported signature algorithm ID from signatures.
164 let strongest = self.strongest_signature()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900165
166 // 2. Verify the corresponding signature from signatures against signed data using public key.
167 // (It is now safe to parse signed data.)
Alice Wang79713d92022-07-14 15:10:03 +0000168 let public_key = PKey::public_key_from_der(self.public_key.as_ref())?;
169 verify_signed_data(&self.signed_data, strongest, &public_key)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900170
171 // It is now safe to parse signed data.
172 let signed_data: SignedData = self.signed_data.slice(..).read()?;
173
174 // 3. Verify the min and max SDK versions in the signed data match those specified for the
175 // signer.
Alice Wangbc4b9a92022-09-16 13:13:18 +0000176 ensure!(
177 self.sdk_range() == signed_data.sdk_range(),
178 "SDK versions mismatch between signed and unsigned in v3 signer block."
179 );
Jooyung Hand8397852021-08-10 16:29:36 +0900180
181 // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is
182 // identical. (This is to prevent signature stripping/addition.)
Alice Wangbc4b9a92022-09-16 13:13:18 +0000183 ensure!(
184 self.signatures
185 .iter()
186 .map(|sig| sig.signature_algorithm_id)
187 .eq(signed_data.digests.iter().map(|dig| dig.signature_algorithm_id)),
188 "Signature algorithms don't match between digests and signatures records"
189 );
Jooyung Hand8397852021-08-10 16:29:36 +0900190
191 // 5. Compute the digest of APK contents using the same digest algorithm as the digest
192 // algorithm used by the signature algorithm.
193 let digest = signed_data
194 .digests
195 .iter()
196 .find(|&dig| dig.signature_algorithm_id == strongest.signature_algorithm_id)
197 .unwrap(); // ok to unwrap since we check if two lists are the same above
198 let computed = sections.compute_digest(digest.signature_algorithm_id)?;
199
200 // 6. Verify that the computed digest is identical to the corresponding digest from digests.
Alice Wangbc4b9a92022-09-16 13:13:18 +0000201 ensure!(
202 computed == digest.digest.as_ref(),
203 "Digest mismatch: computed={:?} vs expected={:?}",
204 to_hex_string(&computed),
205 to_hex_string(&digest.digest),
206 );
Jooyung Hand8397852021-08-10 16:29:36 +0900207
Alice Wang79713d92022-07-14 15:10:03 +0000208 // 7. Verify that public key of the first certificate of certificates is identical
Jooyung Han543e7122021-08-11 01:48:45 +0900209 // to public key.
210 let cert = signed_data.certificates.first().context("No certificates listed")?;
Alice Wang79713d92022-07-14 15:10:03 +0000211 let cert = X509::from_der(cert.as_ref())?;
Alice Wangbc4b9a92022-09-16 13:13:18 +0000212 ensure!(
213 cert.public_key()?.public_eq(&public_key),
214 "Public key mismatch between certificate and signature record"
215 );
Jooyung Han543e7122021-08-11 01:48:45 +0900216
Alice Wang92889352022-09-16 10:42:52 +0000217 // TODO(b/245914104)
218 // 8. If the proof-of-rotation attribute exists for the signer verify that the
219 // struct is valid and this signer is the last certificate in the list.
Jiyong Parka41535b2021-09-10 19:31:48 +0900220 Ok(self.public_key.to_vec().into_boxed_slice())
Jooyung Han12a0b702021-08-05 23:20:31 +0900221 }
222}
223
Alice Wanga66b5c02022-09-16 07:25:17 +0000224fn verify_signed_data(
225 data: &Bytes,
226 signature: &Signature,
227 public_key: &PKey<pkey::Public>,
228) -> Result<()> {
229 let mut verifier = SignatureAlgorithmID::from_u32(signature.signature_algorithm_id)
230 .context("Unsupported algorithm")?
231 .new_verifier(public_key)?;
Andrew Scullc208eb42022-05-22 16:17:52 +0000232 verifier.update(data)?;
233 let verified = verifier.verify(&signature.signature)?;
234 ensure!(verified, "Signature is invalid ");
Jooyung Han12a0b702021-08-05 23:20:31 +0900235 Ok(())
236}
237
238// ReadFromBytes implementations
Alice Wang92889352022-09-16 10:42:52 +0000239// TODO(b/190343842): add derive macro: #[derive(ReadFromBytes)]
Jooyung Han12a0b702021-08-05 23:20:31 +0900240
241impl ReadFromBytes for Signer {
242 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
243 Ok(Self {
244 signed_data: buf.read()?,
245 min_sdk: buf.read()?,
246 max_sdk: buf.read()?,
247 signatures: buf.read()?,
248 public_key: buf.read()?,
249 })
250 }
251}
252
253impl ReadFromBytes for SignedData {
254 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
255 Ok(Self {
256 digests: buf.read()?,
257 certificates: buf.read()?,
258 min_sdk: buf.read()?,
259 max_sdk: buf.read()?,
260 additional_attributes: buf.read()?,
261 })
262 }
263}
264
265impl ReadFromBytes for Signature {
266 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
267 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
268 }
269}
270
271impl ReadFromBytes for Digest {
272 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
273 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
274 }
275}
Jooyung Hand8397852021-08-10 16:29:36 +0900276
277#[inline]
Alice Wang98073222022-09-09 14:08:19 +0000278pub(crate) fn to_hex_string(buf: &[u8]) -> String {
Jooyung Hand8397852021-08-10 16:29:36 +0900279 buf.iter().map(|b| format!("{:02X}", b)).collect()
280}
Alice Wanga94ba172022-09-08 15:25:31 +0000281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use std::fs::File;
286
287 #[test]
288 fn test_pick_v4_apk_digest_only_with_v3_dsa_sha256() {
289 check_v4_apk_digest(
290 "tests/data/v3-only-with-dsa-sha256-1024.apk",
291 SIGNATURE_DSA_WITH_SHA256,
292 "0DF2426EA33AEDAF495D88E5BE0C6A1663FF0A81C5ED12D5B2929AE4B4300F2F",
293 );
294 }
295
296 #[test]
297 fn test_pick_v4_apk_digest_only_with_v3_pkcs1_sha512() {
298 check_v4_apk_digest(
299 "tests/data/v3-only-with-rsa-pkcs1-sha512-1024.apk",
300 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512,
301 "9B9AE02DA60B18999BF541790F00D380006FDF0655C3C482AA0BB0AF17CF7A42\
302 ECF56B973518546C9080B2FEF83027E895ED2882BFC88EA19790BBAB29AF53B3",
303 );
304 }
305
306 fn check_v4_apk_digest(apk_filename: &str, expected_algorithm: u32, expected_digest: &str) {
307 let apk_file = File::open(apk_filename).unwrap();
308 let (signature_algorithm_id, apk_digest) = pick_v4_apk_digest(apk_file).unwrap();
309
310 assert_eq!(expected_algorithm, signature_algorithm_id);
311 assert_eq!(expected_digest, to_hex_string(apk_digest.as_ref()));
312 }
313}