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