1 /*
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 //!
19 //! [v3 verification]: https://source.android.com/security/apksigning/v3#verification
20
21 use anyhow::{ensure, Context, Result};
22 use bytes::Bytes;
23 use openssl::pkey::{self, PKey};
24 use openssl::x509::X509;
25 use std::fs::File;
26 use std::io::{Read, Seek};
27 use std::ops::RangeInclusive;
28 use std::path::Path;
29
30 use crate::algorithms::SignatureAlgorithmID;
31 use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
32 use crate::sigutil::ApkSections;
33
34 pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
35
36 type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
37
38 #[derive(Debug)]
39 pub(crate) struct Signer {
40 signed_data: LengthPrefixed<Bytes>, // not verified yet
41 min_sdk: u32,
42 max_sdk: u32,
43 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
44 public_key: PKey<pkey::Public>,
45 }
46
47 /// Contains the signed data part of an APK v3 signature.
48 #[derive(Debug)]
49 pub struct SignedData {
50 digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
51 certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
52 min_sdk: u32,
53 max_sdk: u32,
54 #[allow(dead_code)]
55 additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
56 }
57
58 #[derive(Debug)]
59 pub(crate) struct Signature {
60 /// Option is used here to allow us to ignore unsupported algorithm.
61 pub(crate) signature_algorithm_id: Option<SignatureAlgorithmID>,
62 signature: LengthPrefixed<Bytes>,
63 }
64
65 #[derive(Debug)]
66 struct Digest {
67 signature_algorithm_id: Option<SignatureAlgorithmID>,
68 digest: LengthPrefixed<Bytes>,
69 }
70
71 type X509Certificate = Bytes;
72 type AdditionalAttributes = Bytes;
73
74 /// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the SignedData from
75 /// the signature.
verify<P: AsRef<Path>>(apk_path: P, current_sdk: u32) -> Result<SignedData>76 pub fn verify<P: AsRef<Path>>(apk_path: P, current_sdk: u32) -> Result<SignedData> {
77 let apk = File::open(apk_path.as_ref())?;
78 let (signer, mut sections) = extract_signer_and_apk_sections(apk, current_sdk)?;
79 signer.verify(&mut sections)
80 }
81
82 /// Extracts the SignedData from the signature of the given APK. (The signature is not verified.)
extract_signed_data<P: AsRef<Path>>(apk_path: P, current_sdk: u32) -> Result<SignedData>83 pub fn extract_signed_data<P: AsRef<Path>>(apk_path: P, current_sdk: u32) -> Result<SignedData> {
84 let apk = File::open(apk_path.as_ref())?;
85 let (signer, _) = extract_signer_and_apk_sections(apk, current_sdk)?;
86 signer.parse_signed_data()
87 }
88
extract_signer_and_apk_sections<R: Read + Seek>( apk: R, current_sdk: u32, ) -> Result<(Signer, ApkSections<R>)>89 pub(crate) fn extract_signer_and_apk_sections<R: Read + Seek>(
90 apk: R,
91 current_sdk: u32,
92 ) -> Result<(Signer, ApkSections<R>)> {
93 let mut sections = ApkSections::new(apk)?;
94 let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID).context(
95 "Fallback to v2 when v3 block not found is not yet implemented.", // b/197052981
96 )?;
97 let signers = block.read::<Signers>()?.into_inner();
98 let mut supported =
99 signers.into_iter().filter(|s| s.sdk_range().contains(¤t_sdk)).collect::<Vec<_>>();
100 ensure!(
101 supported.len() == 1,
102 "APK Signature Scheme V3 only supports one signer: {} signers found.",
103 supported.len()
104 );
105 Ok((supported.pop().unwrap().into_inner(), sections))
106 }
107
108 impl Signer {
sdk_range(&self) -> RangeInclusive<u32>109 fn sdk_range(&self) -> RangeInclusive<u32> {
110 self.min_sdk..=self.max_sdk
111 }
112
113 /// Selects the signature that has the strongest supported `SignatureAlgorithmID`.
114 /// The strongest signature is used in both v3 verification and v4 apk digest computation.
strongest_signature(&self) -> Result<&Signature>115 pub(crate) fn strongest_signature(&self) -> Result<&Signature> {
116 Ok(self
117 .signatures
118 .iter()
119 .filter(|sig| sig.signature_algorithm_id.map_or(false, |algo| algo.is_supported()))
120 .max_by_key(|sig| sig.signature_algorithm_id.unwrap().content_digest_algorithm())
121 .context("No supported APK signatures found; DSA is not supported")?)
122 }
123
find_digest_by_algorithm( &self, algorithm_id: SignatureAlgorithmID, ) -> Result<Box<[u8]>>124 pub(crate) fn find_digest_by_algorithm(
125 &self,
126 algorithm_id: SignatureAlgorithmID,
127 ) -> Result<Box<[u8]>> {
128 let signed_data: SignedData = self.signed_data.slice(..).read()?;
129 let digest = signed_data.find_digest_by_algorithm(algorithm_id)?;
130 Ok(digest.digest.as_ref().to_vec().into_boxed_slice())
131 }
132
133 /// Verifies a signature over the signed data using the public key.
verify_signature(&self, signature: &Signature) -> Result<()>134 fn verify_signature(&self, signature: &Signature) -> Result<()> {
135 let mut verifier = signature
136 .signature_algorithm_id
137 .context("Unsupported algorithm")?
138 .new_verifier(&self.public_key)?;
139 verifier.update(&self.signed_data)?;
140 ensure!(verifier.verify(&signature.signature)?, "Signature is invalid.");
141 Ok(())
142 }
143
144 /// Returns the signed data, converted from bytes.
parse_signed_data(&self) -> Result<SignedData>145 fn parse_signed_data(&self) -> Result<SignedData> {
146 self.signed_data.slice(..).read()
147 }
148
149 /// The steps in this method implements APK Signature Scheme v3 verification step 3.
verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<SignedData>150 fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<SignedData> {
151 // 1. Choose the strongest supported signature algorithm ID from signatures.
152 let strongest = self.strongest_signature()?;
153
154 // 2. Verify the corresponding signature from signatures against signed data using public
155 // key.
156 self.verify_signature(strongest)?;
157
158 // It is now safe to parse signed data.
159 let verified_signed_data = self.parse_signed_data()?;
160
161 // 3. Verify the min and max SDK versions in the signed data match those specified for the
162 // signer.
163 ensure!(
164 self.sdk_range() == verified_signed_data.sdk_range(),
165 "SDK versions mismatch between signed and unsigned in v3 signer block."
166 );
167
168 // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is
169 // identical. (This is to prevent signature stripping/addition.)
170 ensure!(
171 self.signatures
172 .iter()
173 .map(|sig| sig.signature_algorithm_id)
174 .eq(verified_signed_data.digests.iter().map(|dig| dig.signature_algorithm_id)),
175 "Signature algorithms don't match between digests and signatures records"
176 );
177
178 // 5. Compute the digest of APK contents using the same digest algorithm as the digest
179 // algorithm used by the signature algorithm.
180 let digest = verified_signed_data.find_digest_by_algorithm(
181 strongest.signature_algorithm_id.context("Unsupported algorithm")?,
182 )?;
183 let computed = sections.compute_digest(digest.signature_algorithm_id.unwrap())?;
184
185 // 6. Verify that the computed digest is identical to the corresponding digest from digests.
186 ensure!(
187 computed == digest.digest.as_ref(),
188 "Digest mismatch: computed={:?} vs expected={:?}",
189 hex::encode(&computed),
190 hex::encode(digest.digest.as_ref()),
191 );
192
193 // 7. Verify that public key of the first certificate of certificates is identical to public
194 // key.
195 let cert = X509::from_der(verified_signed_data.first_certificate_der()?)?;
196 ensure!(
197 cert.public_key()?.public_eq(&self.public_key),
198 "Public key mismatch between certificate and signature record"
199 );
200
201 // TODO(b/245914104)
202 // 8. If the proof-of-rotation attribute exists for the signer verify that the
203 // struct is valid and this signer is the last certificate in the list.
204
205 Ok(verified_signed_data)
206 }
207 }
208
209 impl SignedData {
210 /// Returns the first X.509 certificate in the signed data, encoded in DER form. (All other
211 /// certificates are ignored for v3; this certificate describes the public key that was actually
212 /// used to sign the APK.)
first_certificate_der(&self) -> Result<&[u8]>213 pub fn first_certificate_der(&self) -> Result<&[u8]> {
214 Ok(self.certificates.first().context("No certificates listed")?)
215 }
216
sdk_range(&self) -> RangeInclusive<u32>217 fn sdk_range(&self) -> RangeInclusive<u32> {
218 self.min_sdk..=self.max_sdk
219 }
220
find_digest_by_algorithm(&self, algorithm_id: SignatureAlgorithmID) -> Result<&Digest>221 fn find_digest_by_algorithm(&self, algorithm_id: SignatureAlgorithmID) -> Result<&Digest> {
222 Ok(self
223 .digests
224 .iter()
225 .find(|&dig| dig.signature_algorithm_id == Some(algorithm_id))
226 .context(format!("Digest not found for algorithm: {:?}", algorithm_id))?)
227 }
228 }
229
230 // ReadFromBytes implementations
231 // TODO(b/190343842): add derive macro: #[derive(ReadFromBytes)]
232
233 impl ReadFromBytes for Signer {
read_from_bytes(buf: &mut Bytes) -> Result<Self>234 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
235 Ok(Self {
236 signed_data: buf.read()?,
237 min_sdk: buf.read()?,
238 max_sdk: buf.read()?,
239 signatures: buf.read()?,
240 public_key: buf.read()?,
241 })
242 }
243 }
244
245 impl ReadFromBytes for SignedData {
read_from_bytes(buf: &mut Bytes) -> Result<Self>246 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
247 Ok(Self {
248 digests: buf.read()?,
249 certificates: buf.read()?,
250 min_sdk: buf.read()?,
251 max_sdk: buf.read()?,
252 additional_attributes: buf.read()?,
253 })
254 }
255 }
256
257 impl ReadFromBytes for Signature {
read_from_bytes(buf: &mut Bytes) -> Result<Self>258 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
259 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
260 }
261 }
262
263 impl ReadFromBytes for Digest {
read_from_bytes(buf: &mut Bytes) -> Result<Self>264 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
265 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
266 }
267 }
268
269 impl ReadFromBytes for PKey<pkey::Public> {
read_from_bytes(buf: &mut Bytes) -> Result<Self>270 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
271 let raw_public_key = buf.read::<LengthPrefixed<Bytes>>()?;
272 Ok(PKey::public_key_from_der(raw_public_key.as_ref())?)
273 }
274 }
275