Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2022 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 | //! API for APK Signature Scheme [v4]. |
| 18 | //! |
| 19 | //! [v4]: https://source.android.com/security/apksigning/v4 |
| 20 | |
Alice Wang | 1bf3d78 | 2022-09-28 07:56:36 +0000 | [diff] [blame] | 21 | use anyhow::{anyhow, bail, ensure, Context, Result}; |
| 22 | use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; |
| 23 | use num_derive::{FromPrimitive, ToPrimitive}; |
| 24 | use num_traits::{FromPrimitive, ToPrimitive}; |
| 25 | use std::fs; |
| 26 | use std::io::{copy, Cursor, Read, Seek, SeekFrom, Write}; |
| 27 | use std::path::Path; |
Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 28 | |
| 29 | use crate::algorithms::SignatureAlgorithmID; |
Alice Wang | 1bf3d78 | 2022-09-28 07:56:36 +0000 | [diff] [blame] | 30 | use crate::hashtree::*; |
Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 31 | use crate::v3::extract_signer_and_apk_sections; |
| 32 | |
| 33 | /// Gets the v4 [apk_digest]. If `verify` is true, we verify that digest computed |
| 34 | /// with the extracted algorithm is equal to the digest extracted directly from apk. |
| 35 | /// Otherwise, the extracted digest will be returned directly. |
| 36 | /// |
| 37 | /// [apk_digest]: https://source.android.com/docs/security/apksigning/v4#apk-digest |
| 38 | pub fn get_apk_digest<R: Read + Seek>( |
| 39 | apk: R, |
| 40 | verify: bool, |
| 41 | ) -> Result<(SignatureAlgorithmID, Box<[u8]>)> { |
| 42 | let (signer, mut sections) = extract_signer_and_apk_sections(apk)?; |
Alice Wang | f27626a | 2022-09-27 12:36:22 +0000 | [diff] [blame] | 43 | let strongest_algorithm_id = signer |
| 44 | .strongest_signature()? |
| 45 | .signature_algorithm_id |
| 46 | .context("Strongest signature should contain a valid signature algorithm.")?; |
| 47 | let extracted_digest = signer.find_digest_by_algorithm(strongest_algorithm_id)?; |
Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 48 | if verify { |
Alice Wang | f27626a | 2022-09-27 12:36:22 +0000 | [diff] [blame] | 49 | let computed_digest = sections.compute_digest(strongest_algorithm_id)?; |
Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 50 | ensure!( |
| 51 | computed_digest == extracted_digest.as_ref(), |
| 52 | "Computed digest does not match the extracted digest." |
| 53 | ); |
| 54 | } |
Alice Wang | f27626a | 2022-09-27 12:36:22 +0000 | [diff] [blame] | 55 | Ok((strongest_algorithm_id, extracted_digest)) |
Alice Wang | 0cafa14 | 2022-09-23 15:17:02 +0000 | [diff] [blame] | 56 | } |
Alice Wang | 1bf3d78 | 2022-09-28 07:56:36 +0000 | [diff] [blame] | 57 | |
| 58 | /// `V4Signature` provides access to the various fields in an idsig file. |
| 59 | #[derive(Default)] |
| 60 | pub struct V4Signature<R: Read + Seek> { |
| 61 | /// Version of the header. Should be 2. |
| 62 | pub version: Version, |
| 63 | /// Provides access to the information about how the APK is hashed. |
| 64 | pub hashing_info: HashingInfo, |
| 65 | /// Provides access to the information that can be used to verify this file |
| 66 | pub signing_info: SigningInfo, |
| 67 | /// Total size of the merkle tree |
| 68 | pub merkle_tree_size: u32, |
| 69 | /// Offset of the merkle tree in the idsig file |
| 70 | pub merkle_tree_offset: u64, |
| 71 | |
| 72 | // Provides access to the underlying data |
| 73 | data: R, |
| 74 | } |
| 75 | |
| 76 | /// `HashingInfo` provides information about how the APK is hashed. |
| 77 | #[derive(Default)] |
| 78 | pub struct HashingInfo { |
| 79 | /// Hash algorithm used when creating the merkle tree for the APK. |
| 80 | pub hash_algorithm: HashAlgorithm, |
| 81 | /// The log size of a block used when creating the merkle tree. 12 if 4k block was used. |
| 82 | pub log2_blocksize: u8, |
| 83 | /// The salt used when creating the merkle tree. 32 bytes max. |
| 84 | pub salt: Box<[u8]>, |
| 85 | /// The root hash of the merkle tree created. |
| 86 | pub raw_root_hash: Box<[u8]>, |
| 87 | } |
| 88 | |
| 89 | /// `SigningInfo` provides information that can be used to verify the idsig file. |
| 90 | #[derive(Default)] |
| 91 | pub struct SigningInfo { |
| 92 | /// Digest of the APK that this idsig file is for. |
| 93 | pub apk_digest: Box<[u8]>, |
| 94 | /// Certificate of the signer that signed this idsig file. ASN.1 DER form. |
| 95 | pub x509_certificate: Box<[u8]>, |
| 96 | /// A free-form binary data |
| 97 | pub additional_data: Box<[u8]>, |
| 98 | /// Public key of the signer in ASN.1 DER form. This must match the `x509_certificate` field. |
| 99 | pub public_key: Box<[u8]>, |
| 100 | /// Signature algorithm used to sign this file. |
| 101 | pub signature_algorithm_id: SignatureAlgorithmID, |
| 102 | /// The signature of this file. |
| 103 | pub signature: Box<[u8]>, |
| 104 | } |
| 105 | |
| 106 | /// Version of the idsig file format |
| 107 | #[derive(Debug, PartialEq, Eq, FromPrimitive, ToPrimitive)] |
| 108 | #[repr(u32)] |
| 109 | pub enum Version { |
| 110 | /// Version 2, the only supported version. |
| 111 | V2 = 2, |
| 112 | } |
| 113 | |
| 114 | impl Version { |
| 115 | fn from(val: u32) -> Result<Version> { |
| 116 | Self::from_u32(val).ok_or_else(|| anyhow!("{} is an unsupported version", val)) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | impl Default for Version { |
| 121 | fn default() -> Self { |
| 122 | Version::V2 |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// Hash algorithm that can be used for idsig file. |
| 127 | #[derive(Debug, PartialEq, Eq, FromPrimitive, ToPrimitive)] |
| 128 | #[repr(u32)] |
| 129 | pub enum HashAlgorithm { |
| 130 | /// SHA2-256 |
| 131 | SHA256 = 1, |
| 132 | } |
| 133 | |
| 134 | impl HashAlgorithm { |
| 135 | fn from(val: u32) -> Result<HashAlgorithm> { |
| 136 | Self::from_u32(val).ok_or_else(|| anyhow!("{} is an unsupported hash algorithm", val)) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | impl Default for HashAlgorithm { |
| 141 | fn default() -> Self { |
| 142 | HashAlgorithm::SHA256 |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | impl V4Signature<fs::File> { |
| 147 | /// Creates a `V4Signature` struct from the given idsig path. |
| 148 | pub fn from_idsig_path<P: AsRef<Path>>(idsig_path: P) -> Result<Self> { |
| 149 | let idsig = fs::File::open(idsig_path).context("Cannot find idsig file")?; |
| 150 | Self::from_idsig(idsig) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | impl<R: Read + Seek> V4Signature<R> { |
| 155 | /// Consumes a stream for an idsig file into a `V4Signature` struct. |
| 156 | pub fn from_idsig(mut r: R) -> Result<V4Signature<R>> { |
| 157 | Ok(V4Signature { |
| 158 | version: Version::from(r.read_u32::<LittleEndian>()?)?, |
| 159 | hashing_info: HashingInfo::from(&mut r)?, |
| 160 | signing_info: SigningInfo::from(&mut r)?, |
| 161 | merkle_tree_size: r.read_u32::<LittleEndian>()?, |
| 162 | merkle_tree_offset: r.stream_position()?, |
| 163 | data: r, |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | /// Read a stream for an APK file and creates a corresponding `V4Signature` struct that digests |
| 168 | /// the APK file. Note that the signing is not done. |
| 169 | pub fn create( |
| 170 | mut apk: &mut R, |
| 171 | block_size: usize, |
| 172 | salt: &[u8], |
| 173 | algorithm: HashAlgorithm, |
| 174 | ) -> Result<V4Signature<Cursor<Vec<u8>>>> { |
| 175 | // Determine the size of the apk |
| 176 | let start = apk.stream_position()?; |
| 177 | let size = apk.seek(SeekFrom::End(0))? as usize; |
| 178 | apk.seek(SeekFrom::Start(start))?; |
| 179 | |
| 180 | // Create hash tree (and root hash) |
| 181 | let algorithm = match algorithm { |
| 182 | HashAlgorithm::SHA256 => openssl::hash::MessageDigest::sha256(), |
| 183 | }; |
| 184 | let hash_tree = HashTree::from(&mut apk, size, salt, block_size, algorithm)?; |
| 185 | |
| 186 | let mut ret = V4Signature { |
| 187 | version: Version::default(), |
| 188 | hashing_info: HashingInfo::default(), |
| 189 | signing_info: SigningInfo::default(), |
| 190 | merkle_tree_size: hash_tree.tree.len() as u32, |
| 191 | merkle_tree_offset: 0, // merkle tree starts from the beginning of `data` |
| 192 | data: Cursor::new(hash_tree.tree), |
| 193 | }; |
| 194 | ret.hashing_info.raw_root_hash = hash_tree.root_hash.into_boxed_slice(); |
| 195 | ret.hashing_info.log2_blocksize = log2(block_size); |
| 196 | |
| 197 | apk.seek(SeekFrom::Start(start))?; |
| 198 | let (signature_algorithm_id, apk_digest) = get_apk_digest(apk, /*verify=*/ false)?; |
| 199 | ret.signing_info.signature_algorithm_id = signature_algorithm_id; |
| 200 | ret.signing_info.apk_digest = apk_digest; |
| 201 | // TODO(jiyong): add a signature to the signing_info struct |
| 202 | |
| 203 | Ok(ret) |
| 204 | } |
| 205 | |
| 206 | /// Writes the data into a writer |
| 207 | pub fn write_into<W: Write + Seek>(&mut self, mut w: &mut W) -> Result<()> { |
| 208 | // Writes the header part |
| 209 | w.write_u32::<LittleEndian>(self.version.to_u32().unwrap())?; |
| 210 | self.hashing_info.write_into(&mut w)?; |
| 211 | self.signing_info.write_into(&mut w)?; |
| 212 | w.write_u32::<LittleEndian>(self.merkle_tree_size)?; |
| 213 | |
| 214 | // Writes the merkle tree |
| 215 | self.data.seek(SeekFrom::Start(self.merkle_tree_offset))?; |
| 216 | let copied_size = copy(&mut self.data, &mut w)?; |
| 217 | if copied_size != self.merkle_tree_size as u64 { |
| 218 | bail!( |
| 219 | "merkle tree is {} bytes, but only {} bytes are written.", |
| 220 | self.merkle_tree_size, |
| 221 | copied_size |
| 222 | ); |
| 223 | } |
| 224 | Ok(()) |
| 225 | } |
| 226 | |
| 227 | /// Returns the bytes that represents the merkle tree |
| 228 | pub fn merkle_tree(&mut self) -> Result<Vec<u8>> { |
| 229 | self.data.seek(SeekFrom::Start(self.merkle_tree_offset))?; |
| 230 | let mut out = Vec::new(); |
| 231 | self.data.read_to_end(&mut out)?; |
| 232 | Ok(out) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | impl HashingInfo { |
| 237 | fn from(mut r: &mut dyn Read) -> Result<HashingInfo> { |
| 238 | // Size of the entire hashing_info struct. We don't need this because each variable-sized |
| 239 | // fields in the struct are also length encoded. |
| 240 | r.read_u32::<LittleEndian>()?; |
| 241 | Ok(HashingInfo { |
| 242 | hash_algorithm: HashAlgorithm::from(r.read_u32::<LittleEndian>()?)?, |
| 243 | log2_blocksize: r.read_u8()?, |
| 244 | salt: read_sized_array(&mut r)?, |
| 245 | raw_root_hash: read_sized_array(&mut r)?, |
| 246 | }) |
| 247 | } |
| 248 | |
| 249 | fn write_into<W: Write + Seek>(&self, mut w: &mut W) -> Result<()> { |
| 250 | let start = w.stream_position()?; |
| 251 | // Size of the entire hashing_info struct. Since we don't know the size yet, fill the place |
| 252 | // with 0. The exact size will then be written below. |
| 253 | w.write_u32::<LittleEndian>(0)?; |
| 254 | |
| 255 | w.write_u32::<LittleEndian>(self.hash_algorithm.to_u32().unwrap())?; |
| 256 | w.write_u8(self.log2_blocksize)?; |
| 257 | write_sized_array(&mut w, &self.salt)?; |
| 258 | write_sized_array(&mut w, &self.raw_root_hash)?; |
| 259 | |
| 260 | // Determine the size of hashing_info, and write it in front of the struct where the value |
| 261 | // was initialized to zero. |
| 262 | let end = w.stream_position()?; |
| 263 | let size = end - start - std::mem::size_of::<u32>() as u64; |
| 264 | w.seek(SeekFrom::Start(start))?; |
| 265 | w.write_u32::<LittleEndian>(size as u32)?; |
| 266 | w.seek(SeekFrom::Start(end))?; |
| 267 | Ok(()) |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | impl SigningInfo { |
| 272 | fn from(mut r: &mut dyn Read) -> Result<SigningInfo> { |
| 273 | // Size of the entire signing_info struct. We don't need this because each variable-sized |
| 274 | // fields in the struct are also length encoded. |
| 275 | r.read_u32::<LittleEndian>()?; |
| 276 | Ok(SigningInfo { |
| 277 | apk_digest: read_sized_array(&mut r)?, |
| 278 | x509_certificate: read_sized_array(&mut r)?, |
| 279 | additional_data: read_sized_array(&mut r)?, |
| 280 | public_key: read_sized_array(&mut r)?, |
| 281 | signature_algorithm_id: SignatureAlgorithmID::from_u32(r.read_u32::<LittleEndian>()?) |
| 282 | .context("Unsupported signature algorithm")?, |
| 283 | signature: read_sized_array(&mut r)?, |
| 284 | }) |
| 285 | } |
| 286 | |
| 287 | fn write_into<W: Write + Seek>(&self, mut w: &mut W) -> Result<()> { |
| 288 | let start = w.stream_position()?; |
| 289 | // Size of the entire signing_info struct. Since we don't know the size yet, fill the place |
| 290 | // with 0. The exact size will then be written below. |
| 291 | w.write_u32::<LittleEndian>(0)?; |
| 292 | |
| 293 | write_sized_array(&mut w, &self.apk_digest)?; |
| 294 | write_sized_array(&mut w, &self.x509_certificate)?; |
| 295 | write_sized_array(&mut w, &self.additional_data)?; |
| 296 | write_sized_array(&mut w, &self.public_key)?; |
| 297 | w.write_u32::<LittleEndian>(self.signature_algorithm_id.to_u32())?; |
| 298 | write_sized_array(&mut w, &self.signature)?; |
| 299 | |
| 300 | // Determine the size of signing_info, and write it in front of the struct where the value |
| 301 | // was initialized to zero. |
| 302 | let end = w.stream_position()?; |
| 303 | let size = end - start - std::mem::size_of::<u32>() as u64; |
| 304 | w.seek(SeekFrom::Start(start))?; |
| 305 | w.write_u32::<LittleEndian>(size as u32)?; |
| 306 | w.seek(SeekFrom::Start(end))?; |
| 307 | Ok(()) |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | fn read_sized_array(r: &mut dyn Read) -> Result<Box<[u8]>> { |
| 312 | let size = r.read_u32::<LittleEndian>()?; |
| 313 | let mut data = vec![0; size as usize]; |
| 314 | r.read_exact(&mut data)?; |
| 315 | Ok(data.into_boxed_slice()) |
| 316 | } |
| 317 | |
| 318 | fn write_sized_array(w: &mut dyn Write, data: &[u8]) -> Result<()> { |
| 319 | w.write_u32::<LittleEndian>(data.len() as u32)?; |
| 320 | Ok(w.write_all(data)?) |
| 321 | } |
| 322 | |
| 323 | fn log2(n: usize) -> u8 { |
| 324 | let num_bits = std::mem::size_of::<usize>() * 8; |
| 325 | (num_bits as u32 - n.leading_zeros() - 1) as u8 |
| 326 | } |
| 327 | |
| 328 | #[cfg(test)] |
| 329 | mod tests { |
| 330 | use super::*; |
| 331 | use std::io::Cursor; |
| 332 | |
| 333 | const TEST_APK_PATH: &str = "tests/data/v4-digest-v3-Sha256withEC.apk"; |
| 334 | |
| 335 | fn hexstring_from(s: &[u8]) -> String { |
| 336 | s.iter().map(|byte| format!("{:02x}", byte)).reduce(|i, j| i + &j).unwrap_or_default() |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn parse_idsig_file() { |
| 341 | let parsed = V4Signature::from_idsig_path(format!("{}.idsig", TEST_APK_PATH)).unwrap(); |
| 342 | |
| 343 | assert_eq!(Version::V2, parsed.version); |
| 344 | |
| 345 | let hi = parsed.hashing_info; |
| 346 | assert_eq!(HashAlgorithm::SHA256, hi.hash_algorithm); |
| 347 | assert_eq!(12, hi.log2_blocksize); |
| 348 | assert_eq!("", hexstring_from(hi.salt.as_ref())); |
| 349 | assert_eq!( |
| 350 | "77f063b48b63f846690fa76450a8d3b61a295b6158f50592e873f76dbeeb0201", |
| 351 | hexstring_from(hi.raw_root_hash.as_ref()) |
| 352 | ); |
| 353 | |
| 354 | let si = parsed.signing_info; |
| 355 | assert_eq!( |
| 356 | "c02fe2eddeb3078801828b930de546ea4f98d37fb98b40c7c7ed169b0d713583", |
| 357 | hexstring_from(si.apk_digest.as_ref()) |
| 358 | ); |
| 359 | assert_eq!("", hexstring_from(si.additional_data.as_ref())); |
| 360 | assert_eq!( |
| 361 | "3046022100fb6383ba300dc7e1e6931a25b381398a16e5575baefd82afd12ba88660d9a6\ |
| 362 | 4c022100ebdcae13ab18c4e30bf6ae634462e526367e1ba26c2647a1d87a0f42843fc128", |
| 363 | hexstring_from(si.signature.as_ref()) |
| 364 | ); |
| 365 | assert_eq!(SignatureAlgorithmID::EcdsaWithSha256, si.signature_algorithm_id); |
| 366 | |
| 367 | assert_eq!(4096, parsed.merkle_tree_size); |
| 368 | assert_eq!(648, parsed.merkle_tree_offset); |
| 369 | } |
| 370 | |
| 371 | /// Parse an idsig file into V4Signature and write it. The written date must be the same as |
| 372 | /// the input file. |
| 373 | #[test] |
| 374 | fn parse_and_compose() { |
| 375 | let idsig_path = format!("{}.idsig", TEST_APK_PATH); |
| 376 | let mut v4_signature = V4Signature::from_idsig_path(&idsig_path).unwrap(); |
| 377 | |
| 378 | let mut output = Cursor::new(Vec::new()); |
| 379 | v4_signature.write_into(&mut output).unwrap(); |
| 380 | |
| 381 | assert_eq!(fs::read(&idsig_path).unwrap(), output.get_ref().as_slice()); |
| 382 | } |
| 383 | |
| 384 | /// Create V4Signature by hashing an APK. Merkle tree and the root hash should be the same |
| 385 | /// as those in the idsig file created by the signapk tool. |
| 386 | #[test] |
| 387 | fn digest_from_apk() { |
| 388 | let mut input = Cursor::new(include_bytes!("../tests/data/v4-digest-v3-Sha256withEC.apk")); |
| 389 | let mut created = |
| 390 | V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap(); |
| 391 | |
| 392 | let mut golden = V4Signature::from_idsig_path(format!("{}.idsig", TEST_APK_PATH)).unwrap(); |
| 393 | |
| 394 | // Compare the root hash |
| 395 | assert_eq!( |
| 396 | created.hashing_info.raw_root_hash.as_ref(), |
| 397 | golden.hashing_info.raw_root_hash.as_ref() |
| 398 | ); |
| 399 | |
| 400 | // Compare the merkle tree |
| 401 | assert_eq!( |
| 402 | created.merkle_tree().unwrap().as_slice(), |
| 403 | golden.merkle_tree().unwrap().as_slice() |
| 404 | ); |
| 405 | } |
| 406 | } |