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