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