blob: d1f59c691d269d49cdcd6e72505cda14ee9829f9 [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
Jooyung Han543e7122021-08-11 01:48:45 +090022use anyhow::{anyhow, bail, Context, Result};
Jooyung Han12a0b702021-08-05 23:20:31 +090023use bytes::Bytes;
24use std::fs::File;
Jooyung Hand8397852021-08-10 16:29:36 +090025use std::io::{Read, Seek};
Jooyung Han12a0b702021-08-05 23:20:31 +090026use std::ops::Range;
27use std::path::Path;
Joel Galenson834b1772021-08-11 07:57:10 -070028use x509_parser::{prelude::FromDer, x509};
Jooyung Han12a0b702021-08-05 23:20:31 +090029
30use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
Jooyung Han5b4c70e2021-08-09 16:36:13 +090031use crate::sigutil::*;
Jooyung Han12a0b702021-08-05 23:20:31 +090032
33pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
34
35// TODO(jooyung): get "ro.build.version.sdk"
36const SDK_INT: u32 = 31;
37
38/// Data model for Signature Scheme V3
39/// https://source.android.com/security/apksigning/v3#verification
40
41type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
42
43struct Signer {
44 signed_data: LengthPrefixed<Bytes>, // not verified yet
45 min_sdk: u32,
46 max_sdk: u32,
47 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
Jooyung Han5b4c70e2021-08-09 16:36:13 +090048 public_key: LengthPrefixed<SubjectPublicKeyInfo>,
Jooyung Han12a0b702021-08-05 23:20:31 +090049}
50
51impl Signer {
52 fn sdk_range(&self) -> Range<u32> {
53 self.min_sdk..self.max_sdk
54 }
55}
56
57struct SignedData {
58 digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
59 certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
60 min_sdk: u32,
61 max_sdk: u32,
62 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 {
73 signature_algorithm_id: u32,
74 signature: LengthPrefixed<Bytes>,
75}
76
77struct Digest {
78 signature_algorithm_id: u32,
79 digest: LengthPrefixed<Bytes>,
80}
81
Jooyung Han5b4c70e2021-08-09 16:36:13 +090082type SubjectPublicKeyInfo = Bytes;
Jooyung Han12a0b702021-08-05 23:20:31 +090083type X509Certificate = Bytes;
84type AdditionalAttributes = Bytes;
85
86/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
87/// associated with each signer.
88pub fn verify<P: AsRef<Path>>(path: P) -> Result<()> {
Jooyung Han5d94bfc2021-08-06 14:07:49 +090089 let f = File::open(path.as_ref())?;
Jooyung Hand8397852021-08-10 16:29:36 +090090 let mut sections = ApkSections::new(f)?;
91 verify_signature(&mut sections)?;
Jooyung Han12a0b702021-08-05 23:20:31 +090092 Ok(())
93}
94
95/// Verifies the contents of the provided APK file against the provided APK Signature Scheme v3
96/// Block.
Jooyung Hand8397852021-08-10 16:29:36 +090097fn verify_signature<R: Read + Seek>(sections: &mut ApkSections<R>) -> Result<()> {
98 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
99
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
104 let mut supported =
105 signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>();
106
107 // there should be exactly one
108 if supported.len() != 1 {
109 bail!("APK Signature Scheme V3 only supports one signer: {} signers found.", signers.len())
110 }
111
112 // and it should be verified
Jooyung Hand8397852021-08-10 16:29:36 +0900113 supported.pop().unwrap().verify(sections)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900114
115 Ok(())
116}
117
118impl Signer {
Jooyung Hand8397852021-08-10 16:29:36 +0900119 fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<()> {
Jooyung Han12a0b702021-08-05 23:20:31 +0900120 // 1. Choose the strongest supported signature algorithm ID from signatures. The strength
121 // ordering is up to each implementation/platform version.
122 let strongest: &Signature = self
123 .signatures
124 .iter()
125 .filter(|sig| is_supported_signature_algorithm(sig.signature_algorithm_id))
126 .max_by_key(|sig| rank_signature_algorithm(sig.signature_algorithm_id).unwrap())
127 .ok_or_else(|| anyhow!("No supported signatures found"))?;
128
129 // 2. Verify the corresponding signature from signatures against signed data using public key.
130 // (It is now safe to parse signed data.)
Jooyung Han543e7122021-08-11 01:48:45 +0900131 let (_, key_info) = x509::SubjectPublicKeyInfo::from_der(self.public_key.as_ref())?;
132 verify_signed_data(&self.signed_data, strongest, &key_info)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900133
134 // It is now safe to parse signed data.
135 let signed_data: SignedData = self.signed_data.slice(..).read()?;
136
137 // 3. Verify the min and max SDK versions in the signed data match those specified for the
138 // signer.
139 if self.sdk_range() != signed_data.sdk_range() {
140 bail!("SDK versions mismatch between signed and unsigned in v3 signer block.");
141 }
Jooyung Hand8397852021-08-10 16:29:36 +0900142
143 // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is
144 // identical. (This is to prevent signature stripping/addition.)
145 if !self
146 .signatures
147 .iter()
148 .map(|sig| sig.signature_algorithm_id)
149 .eq(signed_data.digests.iter().map(|dig| dig.signature_algorithm_id))
150 {
151 bail!("Signature algorithms don't match between digests and signatures records");
152 }
153
154 // 5. Compute the digest of APK contents using the same digest algorithm as the digest
155 // algorithm used by the signature algorithm.
156 let digest = signed_data
157 .digests
158 .iter()
159 .find(|&dig| dig.signature_algorithm_id == strongest.signature_algorithm_id)
160 .unwrap(); // ok to unwrap since we check if two lists are the same above
161 let computed = sections.compute_digest(digest.signature_algorithm_id)?;
162
163 // 6. Verify that the computed digest is identical to the corresponding digest from digests.
164 if computed != digest.digest.as_ref() {
165 bail!(
Jooyung Han543e7122021-08-11 01:48:45 +0900166 "Digest mismatch: computed={:?} vs expected={:?}",
Jooyung Hand8397852021-08-10 16:29:36 +0900167 to_hex_string(&computed),
168 to_hex_string(&digest.digest),
169 );
170 }
171
Jooyung Han543e7122021-08-11 01:48:45 +0900172 // 7. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical
173 // to public key.
174 let cert = signed_data.certificates.first().context("No certificates listed")?;
175 let (_, cert) = x509_parser::parse_x509_certificate(cert.as_ref())?;
176 if cert.tbs_certificate.subject_pki != key_info {
177 bail!("Public key mismatch between certificate and signature record");
178 }
179
Jooyung Han12a0b702021-08-05 23:20:31 +0900180 // 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.
181 Ok(())
182 }
183}
184
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900185fn verify_signed_data(
186 data: &Bytes,
187 signature: &Signature,
Jooyung Han543e7122021-08-11 01:48:45 +0900188 key_info: &x509::SubjectPublicKeyInfo,
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900189) -> Result<()> {
190 use ring::signature;
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900191 let verification_alg: &dyn signature::VerificationAlgorithm =
192 match signature.signature_algorithm_id {
193 SIGNATURE_RSA_PSS_WITH_SHA256 => &signature::RSA_PSS_2048_8192_SHA256,
194 SIGNATURE_RSA_PSS_WITH_SHA512 => &signature::RSA_PSS_2048_8192_SHA512,
195 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256 => {
196 &signature::RSA_PKCS1_2048_8192_SHA256
197 }
198 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 => &signature::RSA_PKCS1_2048_8192_SHA512,
199 SIGNATURE_ECDSA_WITH_SHA256 | SIGNATURE_VERITY_ECDSA_WITH_SHA256 => {
200 &signature::ECDSA_P256_SHA256_ASN1
201 }
202 // TODO(b/190343842) not implemented signature algorithm
203 SIGNATURE_ECDSA_WITH_SHA512
204 | SIGNATURE_DSA_WITH_SHA256
205 | SIGNATURE_VERITY_DSA_WITH_SHA256 => {
206 bail!(
207 "TODO(b/190343842) not implemented signature algorithm: {:#x}",
208 signature.signature_algorithm_id
209 );
210 }
211 _ => bail!("Unsupported signature algorithm: {:#x}", signature.signature_algorithm_id),
212 };
Jooyung Han543e7122021-08-11 01:48:45 +0900213 let key = signature::UnparsedPublicKey::new(verification_alg, &key_info.subject_public_key);
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900214 key.verify(data.as_ref(), signature.signature.as_ref())?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900215 Ok(())
216}
217
218// ReadFromBytes implementations
219// TODO(jooyung): add derive macro: #[derive(ReadFromBytes)]
220
221impl ReadFromBytes for Signer {
222 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
223 Ok(Self {
224 signed_data: buf.read()?,
225 min_sdk: buf.read()?,
226 max_sdk: buf.read()?,
227 signatures: buf.read()?,
228 public_key: buf.read()?,
229 })
230 }
231}
232
233impl ReadFromBytes for SignedData {
234 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
235 Ok(Self {
236 digests: buf.read()?,
237 certificates: buf.read()?,
238 min_sdk: buf.read()?,
239 max_sdk: buf.read()?,
240 additional_attributes: buf.read()?,
241 })
242 }
243}
244
245impl ReadFromBytes for Signature {
246 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
247 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
248 }
249}
250
251impl ReadFromBytes for Digest {
252 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
253 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
254 }
255}
Jooyung Hand8397852021-08-10 16:29:36 +0900256
257#[inline]
258fn to_hex_string(buf: &[u8]) -> String {
259 buf.iter().map(|b| format!("{:02X}", b)).collect()
260}