blob: 2f9ce94d60aa532dc3d45c0231f8d6697595a776 [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;
Andrew Walbran117cd5e2021-08-13 11:42:13 +000024use ring::signature::{
25 UnparsedPublicKey, VerificationAlgorithm, ECDSA_P256_SHA256_ASN1, RSA_PKCS1_2048_8192_SHA256,
26 RSA_PKCS1_2048_8192_SHA512, RSA_PSS_2048_8192_SHA256, RSA_PSS_2048_8192_SHA512,
27};
Jooyung Han12a0b702021-08-05 23:20:31 +090028use std::fs::File;
Jooyung Hand8397852021-08-10 16:29:36 +090029use std::io::{Read, Seek};
Jooyung Han12a0b702021-08-05 23:20:31 +090030use std::ops::Range;
31use std::path::Path;
Andrew Walbran117cd5e2021-08-13 11:42:13 +000032use x509_parser::{parse_x509_certificate, prelude::FromDer, x509::SubjectPublicKeyInfo};
Jooyung Han12a0b702021-08-05 23:20:31 +090033
34use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
Jooyung Han5b4c70e2021-08-09 16:36:13 +090035use crate::sigutil::*;
Jooyung Han12a0b702021-08-05 23:20:31 +090036
37pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
38
39// TODO(jooyung): get "ro.build.version.sdk"
40const SDK_INT: u32 = 31;
41
42/// Data model for Signature Scheme V3
43/// https://source.android.com/security/apksigning/v3#verification
44
45type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
46
47struct Signer {
48 signed_data: LengthPrefixed<Bytes>, // not verified yet
49 min_sdk: u32,
50 max_sdk: u32,
51 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
Andrew Walbran117cd5e2021-08-13 11:42:13 +000052 public_key: LengthPrefixed<Bytes>,
Jooyung Han12a0b702021-08-05 23:20:31 +090053}
54
55impl Signer {
56 fn sdk_range(&self) -> Range<u32> {
57 self.min_sdk..self.max_sdk
58 }
59}
60
61struct SignedData {
62 digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
63 certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
64 min_sdk: u32,
65 max_sdk: u32,
66 additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
67}
68
69impl SignedData {
70 fn sdk_range(&self) -> Range<u32> {
71 self.min_sdk..self.max_sdk
72 }
73}
74
Jooyung Han5b4c70e2021-08-09 16:36:13 +090075#[derive(Debug)]
Jooyung Han12a0b702021-08-05 23:20:31 +090076struct Signature {
77 signature_algorithm_id: u32,
78 signature: LengthPrefixed<Bytes>,
79}
80
81struct Digest {
82 signature_algorithm_id: u32,
83 digest: LengthPrefixed<Bytes>,
84}
85
86type X509Certificate = Bytes;
87type AdditionalAttributes = Bytes;
88
89/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
90/// associated with each signer.
91pub fn verify<P: AsRef<Path>>(path: P) -> Result<()> {
Jooyung Han5d94bfc2021-08-06 14:07:49 +090092 let f = File::open(path.as_ref())?;
Jooyung Hand8397852021-08-10 16:29:36 +090093 let mut sections = ApkSections::new(f)?;
94 verify_signature(&mut sections)?;
Jooyung Han12a0b702021-08-05 23:20:31 +090095 Ok(())
96}
97
98/// Verifies the contents of the provided APK file against the provided APK Signature Scheme v3
99/// Block.
Jooyung Hand8397852021-08-10 16:29:36 +0900100fn verify_signature<R: Read + Seek>(sections: &mut ApkSections<R>) -> Result<()> {
101 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
102
Jooyung Han12a0b702021-08-05 23:20:31 +0900103 // parse v3 scheme block
Jooyung Hand8397852021-08-10 16:29:36 +0900104 let signers = block.read::<Signers>()?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900105
106 // find supported by platform
107 let mut supported =
108 signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>();
109
110 // there should be exactly one
111 if supported.len() != 1 {
112 bail!("APK Signature Scheme V3 only supports one signer: {} signers found.", signers.len())
113 }
114
115 // and it should be verified
Jooyung Hand8397852021-08-10 16:29:36 +0900116 supported.pop().unwrap().verify(sections)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900117
118 Ok(())
119}
120
121impl Signer {
Jooyung Hand8397852021-08-10 16:29:36 +0900122 fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<()> {
Jooyung Han12a0b702021-08-05 23:20:31 +0900123 // 1. Choose the strongest supported signature algorithm ID from signatures. The strength
124 // ordering is up to each implementation/platform version.
125 let strongest: &Signature = self
126 .signatures
127 .iter()
128 .filter(|sig| is_supported_signature_algorithm(sig.signature_algorithm_id))
129 .max_by_key(|sig| rank_signature_algorithm(sig.signature_algorithm_id).unwrap())
130 .ok_or_else(|| anyhow!("No supported signatures found"))?;
131
132 // 2. Verify the corresponding signature from signatures against signed data using public key.
133 // (It is now safe to parse signed data.)
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000134 let (_, key_info) = SubjectPublicKeyInfo::from_der(self.public_key.as_ref())?;
Jooyung Han543e7122021-08-11 01:48:45 +0900135 verify_signed_data(&self.signed_data, strongest, &key_info)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900136
137 // It is now safe to parse signed data.
138 let signed_data: SignedData = self.signed_data.slice(..).read()?;
139
140 // 3. Verify the min and max SDK versions in the signed data match those specified for the
141 // signer.
142 if self.sdk_range() != signed_data.sdk_range() {
143 bail!("SDK versions mismatch between signed and unsigned in v3 signer block.");
144 }
Jooyung Hand8397852021-08-10 16:29:36 +0900145
146 // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is
147 // identical. (This is to prevent signature stripping/addition.)
148 if !self
149 .signatures
150 .iter()
151 .map(|sig| sig.signature_algorithm_id)
152 .eq(signed_data.digests.iter().map(|dig| dig.signature_algorithm_id))
153 {
154 bail!("Signature algorithms don't match between digests and signatures records");
155 }
156
157 // 5. Compute the digest of APK contents using the same digest algorithm as the digest
158 // algorithm used by the signature algorithm.
159 let digest = signed_data
160 .digests
161 .iter()
162 .find(|&dig| dig.signature_algorithm_id == strongest.signature_algorithm_id)
163 .unwrap(); // ok to unwrap since we check if two lists are the same above
164 let computed = sections.compute_digest(digest.signature_algorithm_id)?;
165
166 // 6. Verify that the computed digest is identical to the corresponding digest from digests.
167 if computed != digest.digest.as_ref() {
168 bail!(
Jooyung Han543e7122021-08-11 01:48:45 +0900169 "Digest mismatch: computed={:?} vs expected={:?}",
Jooyung Hand8397852021-08-10 16:29:36 +0900170 to_hex_string(&computed),
171 to_hex_string(&digest.digest),
172 );
173 }
174
Jooyung Han543e7122021-08-11 01:48:45 +0900175 // 7. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical
176 // to public key.
177 let cert = signed_data.certificates.first().context("No certificates listed")?;
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000178 let (_, cert) = parse_x509_certificate(cert.as_ref())?;
Jooyung Han543e7122021-08-11 01:48:45 +0900179 if cert.tbs_certificate.subject_pki != key_info {
180 bail!("Public key mismatch between certificate and signature record");
181 }
182
Jooyung Han12a0b702021-08-05 23:20:31 +0900183 // 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.
184 Ok(())
185 }
186}
187
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900188fn verify_signed_data(
189 data: &Bytes,
190 signature: &Signature,
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000191 key_info: &SubjectPublicKeyInfo,
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900192) -> Result<()> {
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000193 let verification_alg: &dyn VerificationAlgorithm = match signature.signature_algorithm_id {
194 SIGNATURE_RSA_PSS_WITH_SHA256 => &RSA_PSS_2048_8192_SHA256,
195 SIGNATURE_RSA_PSS_WITH_SHA512 => &RSA_PSS_2048_8192_SHA512,
196 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256 => {
197 &RSA_PKCS1_2048_8192_SHA256
198 }
199 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 => &RSA_PKCS1_2048_8192_SHA512,
200 SIGNATURE_ECDSA_WITH_SHA256 | SIGNATURE_VERITY_ECDSA_WITH_SHA256 => &ECDSA_P256_SHA256_ASN1,
201 // TODO(b/190343842) not implemented signature algorithm
202 SIGNATURE_ECDSA_WITH_SHA512
203 | SIGNATURE_DSA_WITH_SHA256
204 | SIGNATURE_VERITY_DSA_WITH_SHA256 => {
205 bail!(
206 "TODO(b/190343842) not implemented signature algorithm: {:#x}",
207 signature.signature_algorithm_id
208 );
209 }
210 _ => bail!("Unsupported signature algorithm: {:#x}", signature.signature_algorithm_id),
211 };
212 let key = UnparsedPublicKey::new(verification_alg, &key_info.subject_public_key);
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900213 key.verify(data.as_ref(), signature.signature.as_ref())?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900214 Ok(())
215}
216
217// ReadFromBytes implementations
218// TODO(jooyung): add derive macro: #[derive(ReadFromBytes)]
219
220impl ReadFromBytes for Signer {
221 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
222 Ok(Self {
223 signed_data: buf.read()?,
224 min_sdk: buf.read()?,
225 max_sdk: buf.read()?,
226 signatures: buf.read()?,
227 public_key: buf.read()?,
228 })
229 }
230}
231
232impl ReadFromBytes for SignedData {
233 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
234 Ok(Self {
235 digests: buf.read()?,
236 certificates: buf.read()?,
237 min_sdk: buf.read()?,
238 max_sdk: buf.read()?,
239 additional_attributes: buf.read()?,
240 })
241 }
242}
243
244impl ReadFromBytes for Signature {
245 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
246 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
247 }
248}
249
250impl ReadFromBytes for Digest {
251 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
252 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
253 }
254}
Jooyung Hand8397852021-08-10 16:29:36 +0900255
256#[inline]
257fn to_hex_string(buf: &[u8]) -> String {
258 buf.iter().map(|b| format!("{:02X}", b)).collect()
259}