Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 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 | |
Jooyung Han | 19c1d6c | 2021-08-06 14:08:16 +0900 | [diff] [blame] | 19 | // TODO(jooyung) remove this |
| 20 | #![allow(dead_code)] |
| 21 | |
Jooyung Han | 543e712 | 2021-08-11 01:48:45 +0900 | [diff] [blame] | 22 | use anyhow::{anyhow, bail, Context, Result}; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 23 | use bytes::Bytes; |
Andrew Walbran | 117cd5e | 2021-08-13 11:42:13 +0000 | [diff] [blame] | 24 | use 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 Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 28 | use std::fs::File; |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame] | 29 | use std::io::{Read, Seek}; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 30 | use std::ops::Range; |
| 31 | use std::path::Path; |
Andrew Walbran | 117cd5e | 2021-08-13 11:42:13 +0000 | [diff] [blame] | 32 | use x509_parser::{parse_x509_certificate, prelude::FromDer, x509::SubjectPublicKeyInfo}; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 33 | |
| 34 | use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes}; |
Jooyung Han | 5b4c70e | 2021-08-09 16:36:13 +0900 | [diff] [blame] | 35 | use crate::sigutil::*; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 36 | |
| 37 | pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0; |
| 38 | |
| 39 | // TODO(jooyung): get "ro.build.version.sdk" |
| 40 | const SDK_INT: u32 = 31; |
| 41 | |
| 42 | /// Data model for Signature Scheme V3 |
| 43 | /// https://source.android.com/security/apksigning/v3#verification |
| 44 | |
| 45 | type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>; |
| 46 | |
| 47 | struct Signer { |
| 48 | signed_data: LengthPrefixed<Bytes>, // not verified yet |
| 49 | min_sdk: u32, |
| 50 | max_sdk: u32, |
| 51 | signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>, |
Andrew Walbran | 117cd5e | 2021-08-13 11:42:13 +0000 | [diff] [blame] | 52 | public_key: LengthPrefixed<Bytes>, |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 53 | } |
| 54 | |
| 55 | impl Signer { |
| 56 | fn sdk_range(&self) -> Range<u32> { |
| 57 | self.min_sdk..self.max_sdk |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | struct 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 | |
| 69 | impl SignedData { |
| 70 | fn sdk_range(&self) -> Range<u32> { |
| 71 | self.min_sdk..self.max_sdk |
| 72 | } |
| 73 | } |
| 74 | |
Jooyung Han | 5b4c70e | 2021-08-09 16:36:13 +0900 | [diff] [blame] | 75 | #[derive(Debug)] |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 76 | struct Signature { |
| 77 | signature_algorithm_id: u32, |
| 78 | signature: LengthPrefixed<Bytes>, |
| 79 | } |
| 80 | |
| 81 | struct Digest { |
| 82 | signature_algorithm_id: u32, |
| 83 | digest: LengthPrefixed<Bytes>, |
| 84 | } |
| 85 | |
| 86 | type X509Certificate = Bytes; |
| 87 | type AdditionalAttributes = Bytes; |
| 88 | |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 89 | /// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the public key |
| 90 | /// associated with the signer. |
| 91 | pub fn verify<P: AsRef<Path>>(path: P) -> Result<Box<[u8]>> { |
Jooyung Han | 5d94bfc | 2021-08-06 14:07:49 +0900 | [diff] [blame] | 92 | let f = File::open(path.as_ref())?; |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame] | 93 | let mut sections = ApkSections::new(f)?; |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 94 | find_signer_and_then(&mut sections, |(signer, sections)| signer.verify(sections)) |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 95 | } |
| 96 | |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 97 | /// Finds the supported signer and execute a function on it. |
| 98 | fn find_signer_and_then<R, U, F>(sections: &mut ApkSections<R>, f: F) -> Result<U> |
| 99 | where |
| 100 | R: Read + Seek, |
| 101 | F: FnOnce((&Signer, &mut ApkSections<R>)) -> Result<U>, |
| 102 | { |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame] | 103 | let mut block = sections.find_signature(APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 104 | // parse v3 scheme block |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame] | 105 | let signers = block.read::<Signers>()?; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 106 | |
| 107 | // find supported by platform |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 108 | let supported = signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>(); |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 109 | |
| 110 | // there should be exactly one |
| 111 | if supported.len() != 1 { |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 112 | bail!( |
| 113 | "APK Signature Scheme V3 only supports one signer: {} signers found.", |
| 114 | supported.len() |
| 115 | ) |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 116 | } |
| 117 | |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 118 | // Call the supplied function |
| 119 | f((supported[0], sections)) |
| 120 | } |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 121 | |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 122 | /// Gets the public key (in DER format) that was used to sign the given APK/APEX file |
| 123 | pub fn get_public_key_der<P: AsRef<Path>>(path: P) -> Result<Box<[u8]>> { |
| 124 | let f = File::open(path.as_ref())?; |
| 125 | let mut sections = ApkSections::new(f)?; |
| 126 | find_signer_and_then(&mut sections, |(signer, _)| { |
| 127 | Ok(signer.public_key.to_vec().into_boxed_slice()) |
| 128 | }) |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 129 | } |
| 130 | |
| 131 | impl Signer { |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 132 | fn verify<R: Read + Seek>(&self, sections: &mut ApkSections<R>) -> Result<Box<[u8]>> { |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 133 | // 1. Choose the strongest supported signature algorithm ID from signatures. The strength |
| 134 | // ordering is up to each implementation/platform version. |
| 135 | let strongest: &Signature = self |
| 136 | .signatures |
| 137 | .iter() |
| 138 | .filter(|sig| is_supported_signature_algorithm(sig.signature_algorithm_id)) |
| 139 | .max_by_key(|sig| rank_signature_algorithm(sig.signature_algorithm_id).unwrap()) |
| 140 | .ok_or_else(|| anyhow!("No supported signatures found"))?; |
| 141 | |
| 142 | // 2. Verify the corresponding signature from signatures against signed data using public key. |
| 143 | // (It is now safe to parse signed data.) |
Andrew Walbran | 117cd5e | 2021-08-13 11:42:13 +0000 | [diff] [blame] | 144 | let (_, key_info) = SubjectPublicKeyInfo::from_der(self.public_key.as_ref())?; |
Jooyung Han | 543e712 | 2021-08-11 01:48:45 +0900 | [diff] [blame] | 145 | verify_signed_data(&self.signed_data, strongest, &key_info)?; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 146 | |
| 147 | // It is now safe to parse signed data. |
| 148 | let signed_data: SignedData = self.signed_data.slice(..).read()?; |
| 149 | |
| 150 | // 3. Verify the min and max SDK versions in the signed data match those specified for the |
| 151 | // signer. |
| 152 | if self.sdk_range() != signed_data.sdk_range() { |
| 153 | bail!("SDK versions mismatch between signed and unsigned in v3 signer block."); |
| 154 | } |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame] | 155 | |
| 156 | // 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is |
| 157 | // identical. (This is to prevent signature stripping/addition.) |
| 158 | if !self |
| 159 | .signatures |
| 160 | .iter() |
| 161 | .map(|sig| sig.signature_algorithm_id) |
| 162 | .eq(signed_data.digests.iter().map(|dig| dig.signature_algorithm_id)) |
| 163 | { |
| 164 | bail!("Signature algorithms don't match between digests and signatures records"); |
| 165 | } |
| 166 | |
| 167 | // 5. Compute the digest of APK contents using the same digest algorithm as the digest |
| 168 | // algorithm used by the signature algorithm. |
| 169 | let digest = signed_data |
| 170 | .digests |
| 171 | .iter() |
| 172 | .find(|&dig| dig.signature_algorithm_id == strongest.signature_algorithm_id) |
| 173 | .unwrap(); // ok to unwrap since we check if two lists are the same above |
| 174 | let computed = sections.compute_digest(digest.signature_algorithm_id)?; |
| 175 | |
| 176 | // 6. Verify that the computed digest is identical to the corresponding digest from digests. |
| 177 | if computed != digest.digest.as_ref() { |
| 178 | bail!( |
Jooyung Han | 543e712 | 2021-08-11 01:48:45 +0900 | [diff] [blame] | 179 | "Digest mismatch: computed={:?} vs expected={:?}", |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame] | 180 | to_hex_string(&computed), |
| 181 | to_hex_string(&digest.digest), |
| 182 | ); |
| 183 | } |
| 184 | |
Jooyung Han | 543e712 | 2021-08-11 01:48:45 +0900 | [diff] [blame] | 185 | // 7. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical |
| 186 | // to public key. |
| 187 | let cert = signed_data.certificates.first().context("No certificates listed")?; |
Andrew Walbran | 117cd5e | 2021-08-13 11:42:13 +0000 | [diff] [blame] | 188 | let (_, cert) = parse_x509_certificate(cert.as_ref())?; |
Jooyung Han | 543e712 | 2021-08-11 01:48:45 +0900 | [diff] [blame] | 189 | if cert.tbs_certificate.subject_pki != key_info { |
| 190 | bail!("Public key mismatch between certificate and signature record"); |
| 191 | } |
| 192 | |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 193 | // 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. |
Jiyong Park | a41535b | 2021-09-10 19:31:48 +0900 | [diff] [blame^] | 194 | Ok(self.public_key.to_vec().into_boxed_slice()) |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 195 | } |
| 196 | } |
| 197 | |
Jooyung Han | 5b4c70e | 2021-08-09 16:36:13 +0900 | [diff] [blame] | 198 | fn verify_signed_data( |
| 199 | data: &Bytes, |
| 200 | signature: &Signature, |
Andrew Walbran | 117cd5e | 2021-08-13 11:42:13 +0000 | [diff] [blame] | 201 | key_info: &SubjectPublicKeyInfo, |
Jooyung Han | 5b4c70e | 2021-08-09 16:36:13 +0900 | [diff] [blame] | 202 | ) -> Result<()> { |
Andrew Walbran | 117cd5e | 2021-08-13 11:42:13 +0000 | [diff] [blame] | 203 | let verification_alg: &dyn VerificationAlgorithm = match signature.signature_algorithm_id { |
| 204 | SIGNATURE_RSA_PSS_WITH_SHA256 => &RSA_PSS_2048_8192_SHA256, |
| 205 | SIGNATURE_RSA_PSS_WITH_SHA512 => &RSA_PSS_2048_8192_SHA512, |
| 206 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256 | SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256 => { |
| 207 | &RSA_PKCS1_2048_8192_SHA256 |
| 208 | } |
| 209 | SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512 => &RSA_PKCS1_2048_8192_SHA512, |
| 210 | SIGNATURE_ECDSA_WITH_SHA256 | SIGNATURE_VERITY_ECDSA_WITH_SHA256 => &ECDSA_P256_SHA256_ASN1, |
| 211 | // TODO(b/190343842) not implemented signature algorithm |
| 212 | SIGNATURE_ECDSA_WITH_SHA512 |
| 213 | | SIGNATURE_DSA_WITH_SHA256 |
| 214 | | SIGNATURE_VERITY_DSA_WITH_SHA256 => { |
| 215 | bail!( |
| 216 | "TODO(b/190343842) not implemented signature algorithm: {:#x}", |
| 217 | signature.signature_algorithm_id |
| 218 | ); |
| 219 | } |
| 220 | _ => bail!("Unsupported signature algorithm: {:#x}", signature.signature_algorithm_id), |
| 221 | }; |
| 222 | let key = UnparsedPublicKey::new(verification_alg, &key_info.subject_public_key); |
Jooyung Han | 5b4c70e | 2021-08-09 16:36:13 +0900 | [diff] [blame] | 223 | key.verify(data.as_ref(), signature.signature.as_ref())?; |
Jooyung Han | 12a0b70 | 2021-08-05 23:20:31 +0900 | [diff] [blame] | 224 | Ok(()) |
| 225 | } |
| 226 | |
| 227 | // ReadFromBytes implementations |
| 228 | // TODO(jooyung): add derive macro: #[derive(ReadFromBytes)] |
| 229 | |
| 230 | impl ReadFromBytes for Signer { |
| 231 | fn read_from_bytes(buf: &mut Bytes) -> Result<Self> { |
| 232 | Ok(Self { |
| 233 | signed_data: buf.read()?, |
| 234 | min_sdk: buf.read()?, |
| 235 | max_sdk: buf.read()?, |
| 236 | signatures: buf.read()?, |
| 237 | public_key: buf.read()?, |
| 238 | }) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | impl ReadFromBytes for SignedData { |
| 243 | fn read_from_bytes(buf: &mut Bytes) -> Result<Self> { |
| 244 | Ok(Self { |
| 245 | digests: buf.read()?, |
| 246 | certificates: buf.read()?, |
| 247 | min_sdk: buf.read()?, |
| 248 | max_sdk: buf.read()?, |
| 249 | additional_attributes: buf.read()?, |
| 250 | }) |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | impl ReadFromBytes for Signature { |
| 255 | fn read_from_bytes(buf: &mut Bytes) -> Result<Self> { |
| 256 | Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? }) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | impl ReadFromBytes for Digest { |
| 261 | fn read_from_bytes(buf: &mut Bytes) -> Result<Self> { |
| 262 | Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? }) |
| 263 | } |
| 264 | } |
Jooyung Han | d839785 | 2021-08-10 16:29:36 +0900 | [diff] [blame] | 265 | |
| 266 | #[inline] |
| 267 | fn to_hex_string(buf: &[u8]) -> String { |
| 268 | buf.iter().map(|b| format!("{:02X}", b)).collect() |
| 269 | } |