blob: 91043ab11a1877522ca7e47f9db5a7c20472826d [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 Han12a0b702021-08-05 23:20:31 +090022use anyhow::{anyhow, bail, Result};
23use bytes::Bytes;
24use std::fs::File;
25use std::ops::Range;
26use std::path::Path;
27
28use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
Jooyung Han5b4c70e2021-08-09 16:36:13 +090029use crate::sigutil::*;
Jooyung Han12a0b702021-08-05 23:20:31 +090030
31pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
32
33// TODO(jooyung): get "ro.build.version.sdk"
34const SDK_INT: u32 = 31;
35
36/// Data model for Signature Scheme V3
37/// https://source.android.com/security/apksigning/v3#verification
38
39type 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>>>,
Jooyung Han5b4c70e2021-08-09 16:36:13 +090046 public_key: LengthPrefixed<SubjectPublicKeyInfo>,
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,
60 additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
61}
62
63impl SignedData {
64 fn sdk_range(&self) -> Range<u32> {
65 self.min_sdk..self.max_sdk
66 }
67}
68
Jooyung Han5b4c70e2021-08-09 16:36:13 +090069#[derive(Debug)]
Jooyung Han12a0b702021-08-05 23:20:31 +090070struct Signature {
71 signature_algorithm_id: u32,
72 signature: LengthPrefixed<Bytes>,
73}
74
75struct Digest {
76 signature_algorithm_id: u32,
77 digest: LengthPrefixed<Bytes>,
78}
79
Jooyung Han5b4c70e2021-08-09 16:36:13 +090080type SubjectPublicKeyInfo = Bytes;
Jooyung Han12a0b702021-08-05 23:20:31 +090081type X509Certificate = Bytes;
82type AdditionalAttributes = Bytes;
83
84/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
85/// associated with each signer.
86pub fn verify<P: AsRef<Path>>(path: P) -> Result<()> {
Jooyung Han5d94bfc2021-08-06 14:07:49 +090087 let f = File::open(path.as_ref())?;
88 let signature = find_signature(f, APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
Jooyung Han12a0b702021-08-05 23:20:31 +090089 verify_signature(&signature.signature_block)?;
90 Ok(())
91}
92
93/// Verifies the contents of the provided APK file against the provided APK Signature Scheme v3
94/// Block.
95fn verify_signature(block: &Bytes) -> Result<()> {
96 // parse v3 scheme block
97 let signers = block.slice(..).read::<Signers>()?;
98
99 // find supported by platform
100 let mut supported =
101 signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>();
102
103 // there should be exactly one
104 if supported.len() != 1 {
105 bail!("APK Signature Scheme V3 only supports one signer: {} signers found.", signers.len())
106 }
107
108 // and it should be verified
109 supported.pop().unwrap().verify()?;
110
111 Ok(())
112}
113
114impl Signer {
115 fn verify(&self) -> Result<()> {
116 // 1. Choose the strongest supported signature algorithm ID from signatures. The strength
117 // ordering is up to each implementation/platform version.
118 let strongest: &Signature = self
119 .signatures
120 .iter()
121 .filter(|sig| is_supported_signature_algorithm(sig.signature_algorithm_id))
122 .max_by_key(|sig| rank_signature_algorithm(sig.signature_algorithm_id).unwrap())
123 .ok_or_else(|| anyhow!("No supported signatures found"))?;
124
125 // 2. Verify the corresponding signature from signatures against signed data using public key.
126 // (It is now safe to parse signed data.)
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900127 verify_signed_data(&self.signed_data, strongest, &self.public_key)?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900128
129 // It is now safe to parse signed data.
130 let signed_data: SignedData = self.signed_data.slice(..).read()?;
131
132 // 3. Verify the min and max SDK versions in the signed data match those specified for the
133 // signer.
134 if self.sdk_range() != signed_data.sdk_range() {
135 bail!("SDK versions mismatch between signed and unsigned in v3 signer block.");
136 }
137 // TODO(jooyung) 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
138 // TODO(jooyung) 5. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
139 // TODO(jooyung) 6. Verify that the computed digest is identical to the corresponding digest from digests.
140 // TODO(jooyung) 7. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
141 // 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.
142 Ok(())
143 }
144}
145
Jooyung Han5b4c70e2021-08-09 16:36:13 +0900146fn verify_signed_data(
147 data: &Bytes,
148 signature: &Signature,
149 public_key: &SubjectPublicKeyInfo,
150) -> Result<()> {
151 use ring::signature;
152 let (_, key_info) = x509_parser::x509::SubjectPublicKeyInfo::from_der(public_key.as_ref())?;
153 let verification_alg: &dyn signature::VerificationAlgorithm =
154 match signature.signature_algorithm_id {
155 SIGNATURE_RSA_PSS_WITH_SHA256 => &signature::RSA_PSS_2048_8192_SHA256,
156 SIGNATURE_RSA_PSS_WITH_SHA512 => &signature::RSA_PSS_2048_8192_SHA512,
157 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256 => {
158 &signature::RSA_PKCS1_2048_8192_SHA256
159 }
160 SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 => &signature::RSA_PKCS1_2048_8192_SHA512,
161 SIGNATURE_ECDSA_WITH_SHA256 | SIGNATURE_VERITY_ECDSA_WITH_SHA256 => {
162 &signature::ECDSA_P256_SHA256_ASN1
163 }
164 // TODO(b/190343842) not implemented signature algorithm
165 SIGNATURE_ECDSA_WITH_SHA512
166 | SIGNATURE_DSA_WITH_SHA256
167 | SIGNATURE_VERITY_DSA_WITH_SHA256 => {
168 bail!(
169 "TODO(b/190343842) not implemented signature algorithm: {:#x}",
170 signature.signature_algorithm_id
171 );
172 }
173 _ => bail!("Unsupported signature algorithm: {:#x}", signature.signature_algorithm_id),
174 };
175 let key = signature::UnparsedPublicKey::new(verification_alg, key_info.subject_public_key.data);
176 key.verify(data.as_ref(), signature.signature.as_ref())?;
Jooyung Han12a0b702021-08-05 23:20:31 +0900177 Ok(())
178}
179
180// ReadFromBytes implementations
181// TODO(jooyung): add derive macro: #[derive(ReadFromBytes)]
182
183impl ReadFromBytes for Signer {
184 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
185 Ok(Self {
186 signed_data: buf.read()?,
187 min_sdk: buf.read()?,
188 max_sdk: buf.read()?,
189 signatures: buf.read()?,
190 public_key: buf.read()?,
191 })
192 }
193}
194
195impl ReadFromBytes for SignedData {
196 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
197 Ok(Self {
198 digests: buf.read()?,
199 certificates: buf.read()?,
200 min_sdk: buf.read()?,
201 max_sdk: buf.read()?,
202 additional_attributes: buf.read()?,
203 })
204 }
205}
206
207impl ReadFromBytes for Signature {
208 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
209 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
210 }
211}
212
213impl ReadFromBytes for Digest {
214 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
215 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
216 }
217}