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