blob: e77ad7719f8547d4e5c04184b219e218c563f9a5 [file] [log] [blame]
Alice Wang0cafa142022-09-23 15:17:02 +00001/*
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 Wang1bf3d782022-09-28 07:56:36 +000021use anyhow::{anyhow, bail, ensure, Context, Result};
22use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
23use num_derive::{FromPrimitive, ToPrimitive};
24use num_traits::{FromPrimitive, ToPrimitive};
25use std::fs;
26use std::io::{copy, Cursor, Read, Seek, SeekFrom, Write};
27use std::path::Path;
Alice Wang0cafa142022-09-23 15:17:02 +000028
Alice Wangab5231f2022-09-28 12:36:48 +000029use crate::algorithms::{HashAlgorithm, SignatureAlgorithmID};
Alice Wang1bf3d782022-09-28 07:56:36 +000030use crate::hashtree::*;
Alice Wang0cafa142022-09-23 15:17:02 +000031use 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
38pub 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 Wangf27626a2022-09-27 12:36:22 +000043 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 Wang0cafa142022-09-23 15:17:02 +000048 if verify {
Alice Wangf27626a2022-09-27 12:36:22 +000049 let computed_digest = sections.compute_digest(strongest_algorithm_id)?;
Alice Wang0cafa142022-09-23 15:17:02 +000050 ensure!(
51 computed_digest == extracted_digest.as_ref(),
52 "Computed digest does not match the extracted digest."
53 );
54 }
Alice Wangf27626a2022-09-27 12:36:22 +000055 Ok((strongest_algorithm_id, extracted_digest))
Alice Wang0cafa142022-09-23 15:17:02 +000056}
Alice Wang1bf3d782022-09-28 07:56:36 +000057
58/// `V4Signature` provides access to the various fields in an idsig file.
59#[derive(Default)]
60pub 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)]
78pub 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)]
91pub 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
Charisee668224f2023-03-03 02:02:34 +0000107#[derive(Debug, PartialEq, Eq, FromPrimitive, ToPrimitive, Default)]
Alice Wang1bf3d782022-09-28 07:56:36 +0000108#[repr(u32)]
109pub enum Version {
Charisee668224f2023-03-03 02:02:34 +0000110 #[default]
Alice Wang1bf3d782022-09-28 07:56:36 +0000111 /// Version 2, the only supported version.
112 V2 = 2,
113}
114
115impl Version {
116 fn from(val: u32) -> Result<Version> {
117 Self::from_u32(val).ok_or_else(|| anyhow!("{} is an unsupported version", val))
118 }
119}
120
Alice Wang1bf3d782022-09-28 07:56:36 +0000121impl V4Signature<fs::File> {
122 /// Creates a `V4Signature` struct from the given idsig path.
123 pub fn from_idsig_path<P: AsRef<Path>>(idsig_path: P) -> Result<Self> {
124 let idsig = fs::File::open(idsig_path).context("Cannot find idsig file")?;
125 Self::from_idsig(idsig)
126 }
127}
128
129impl<R: Read + Seek> V4Signature<R> {
130 /// Consumes a stream for an idsig file into a `V4Signature` struct.
131 pub fn from_idsig(mut r: R) -> Result<V4Signature<R>> {
132 Ok(V4Signature {
133 version: Version::from(r.read_u32::<LittleEndian>()?)?,
134 hashing_info: HashingInfo::from(&mut r)?,
135 signing_info: SigningInfo::from(&mut r)?,
136 merkle_tree_size: r.read_u32::<LittleEndian>()?,
137 merkle_tree_offset: r.stream_position()?,
138 data: r,
139 })
140 }
141
142 /// Read a stream for an APK file and creates a corresponding `V4Signature` struct that digests
143 /// the APK file. Note that the signing is not done.
Nikita Ioffef1ce9872022-12-09 13:31:59 +0000144 /// Important: callers of this function are expected to verify the validity of the passed |apk|.
145 /// To be more specific, they should check that |apk| corresponds to a regular file, as calling
146 /// lseek on directory fds is not defined in the standard, and on ext4 it will return (off_t)-1
147 /// (see: https://bugzilla.kernel.org/show_bug.cgi?id=200043), which will result in this
148 /// function OOMing.
Alice Wang1bf3d782022-09-28 07:56:36 +0000149 pub fn create(
150 mut apk: &mut R,
151 block_size: usize,
152 salt: &[u8],
153 algorithm: HashAlgorithm,
154 ) -> Result<V4Signature<Cursor<Vec<u8>>>> {
155 // Determine the size of the apk
156 let start = apk.stream_position()?;
157 let size = apk.seek(SeekFrom::End(0))? as usize;
158 apk.seek(SeekFrom::Start(start))?;
159
160 // Create hash tree (and root hash)
161 let algorithm = match algorithm {
162 HashAlgorithm::SHA256 => openssl::hash::MessageDigest::sha256(),
163 };
164 let hash_tree = HashTree::from(&mut apk, size, salt, block_size, algorithm)?;
165
166 let mut ret = V4Signature {
167 version: Version::default(),
168 hashing_info: HashingInfo::default(),
169 signing_info: SigningInfo::default(),
170 merkle_tree_size: hash_tree.tree.len() as u32,
171 merkle_tree_offset: 0, // merkle tree starts from the beginning of `data`
172 data: Cursor::new(hash_tree.tree),
173 };
174 ret.hashing_info.raw_root_hash = hash_tree.root_hash.into_boxed_slice();
175 ret.hashing_info.log2_blocksize = log2(block_size);
176
177 apk.seek(SeekFrom::Start(start))?;
178 let (signature_algorithm_id, apk_digest) = get_apk_digest(apk, /*verify=*/ false)?;
179 ret.signing_info.signature_algorithm_id = signature_algorithm_id;
180 ret.signing_info.apk_digest = apk_digest;
181 // TODO(jiyong): add a signature to the signing_info struct
182
183 Ok(ret)
184 }
185
186 /// Writes the data into a writer
187 pub fn write_into<W: Write + Seek>(&mut self, mut w: &mut W) -> Result<()> {
188 // Writes the header part
189 w.write_u32::<LittleEndian>(self.version.to_u32().unwrap())?;
190 self.hashing_info.write_into(&mut w)?;
191 self.signing_info.write_into(&mut w)?;
192 w.write_u32::<LittleEndian>(self.merkle_tree_size)?;
193
194 // Writes the merkle tree
195 self.data.seek(SeekFrom::Start(self.merkle_tree_offset))?;
196 let copied_size = copy(&mut self.data, &mut w)?;
197 if copied_size != self.merkle_tree_size as u64 {
198 bail!(
199 "merkle tree is {} bytes, but only {} bytes are written.",
200 self.merkle_tree_size,
201 copied_size
202 );
203 }
204 Ok(())
205 }
206
207 /// Returns the bytes that represents the merkle tree
208 pub fn merkle_tree(&mut self) -> Result<Vec<u8>> {
209 self.data.seek(SeekFrom::Start(self.merkle_tree_offset))?;
210 let mut out = Vec::new();
211 self.data.read_to_end(&mut out)?;
212 Ok(out)
213 }
214}
215
216impl HashingInfo {
217 fn from(mut r: &mut dyn Read) -> Result<HashingInfo> {
218 // Size of the entire hashing_info struct. We don't need this because each variable-sized
219 // fields in the struct are also length encoded.
220 r.read_u32::<LittleEndian>()?;
221 Ok(HashingInfo {
Alice Wangab5231f2022-09-28 12:36:48 +0000222 hash_algorithm: HashAlgorithm::from_read(&mut r)?,
Alice Wang1bf3d782022-09-28 07:56:36 +0000223 log2_blocksize: r.read_u8()?,
224 salt: read_sized_array(&mut r)?,
225 raw_root_hash: read_sized_array(&mut r)?,
226 })
227 }
228
229 fn write_into<W: Write + Seek>(&self, mut w: &mut W) -> Result<()> {
230 let start = w.stream_position()?;
231 // Size of the entire hashing_info struct. Since we don't know the size yet, fill the place
232 // with 0. The exact size will then be written below.
233 w.write_u32::<LittleEndian>(0)?;
234
235 w.write_u32::<LittleEndian>(self.hash_algorithm.to_u32().unwrap())?;
236 w.write_u8(self.log2_blocksize)?;
237 write_sized_array(&mut w, &self.salt)?;
238 write_sized_array(&mut w, &self.raw_root_hash)?;
239
240 // Determine the size of hashing_info, and write it in front of the struct where the value
241 // was initialized to zero.
242 let end = w.stream_position()?;
243 let size = end - start - std::mem::size_of::<u32>() as u64;
244 w.seek(SeekFrom::Start(start))?;
245 w.write_u32::<LittleEndian>(size as u32)?;
246 w.seek(SeekFrom::Start(end))?;
247 Ok(())
248 }
249}
250
251impl SigningInfo {
252 fn from(mut r: &mut dyn Read) -> Result<SigningInfo> {
253 // Size of the entire signing_info struct. We don't need this because each variable-sized
254 // fields in the struct are also length encoded.
255 r.read_u32::<LittleEndian>()?;
256 Ok(SigningInfo {
257 apk_digest: read_sized_array(&mut r)?,
258 x509_certificate: read_sized_array(&mut r)?,
259 additional_data: read_sized_array(&mut r)?,
260 public_key: read_sized_array(&mut r)?,
261 signature_algorithm_id: SignatureAlgorithmID::from_u32(r.read_u32::<LittleEndian>()?)
262 .context("Unsupported signature algorithm")?,
263 signature: read_sized_array(&mut r)?,
264 })
265 }
266
267 fn write_into<W: Write + Seek>(&self, mut w: &mut W) -> Result<()> {
268 let start = w.stream_position()?;
269 // Size of the entire signing_info struct. Since we don't know the size yet, fill the place
270 // with 0. The exact size will then be written below.
271 w.write_u32::<LittleEndian>(0)?;
272
273 write_sized_array(&mut w, &self.apk_digest)?;
274 write_sized_array(&mut w, &self.x509_certificate)?;
275 write_sized_array(&mut w, &self.additional_data)?;
276 write_sized_array(&mut w, &self.public_key)?;
277 w.write_u32::<LittleEndian>(self.signature_algorithm_id.to_u32())?;
278 write_sized_array(&mut w, &self.signature)?;
279
280 // Determine the size of signing_info, and write it in front of the struct where the value
281 // was initialized to zero.
282 let end = w.stream_position()?;
283 let size = end - start - std::mem::size_of::<u32>() as u64;
284 w.seek(SeekFrom::Start(start))?;
285 w.write_u32::<LittleEndian>(size as u32)?;
286 w.seek(SeekFrom::Start(end))?;
287 Ok(())
288 }
289}
290
291fn read_sized_array(r: &mut dyn Read) -> Result<Box<[u8]>> {
292 let size = r.read_u32::<LittleEndian>()?;
293 let mut data = vec![0; size as usize];
294 r.read_exact(&mut data)?;
295 Ok(data.into_boxed_slice())
296}
297
298fn write_sized_array(w: &mut dyn Write, data: &[u8]) -> Result<()> {
299 w.write_u32::<LittleEndian>(data.len() as u32)?;
300 Ok(w.write_all(data)?)
301}
302
303fn log2(n: usize) -> u8 {
304 let num_bits = std::mem::size_of::<usize>() * 8;
305 (num_bits as u32 - n.leading_zeros() - 1) as u8
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311 use std::io::Cursor;
312
313 const TEST_APK_PATH: &str = "tests/data/v4-digest-v3-Sha256withEC.apk";
314
Alice Wang1bf3d782022-09-28 07:56:36 +0000315 #[test]
316 fn parse_idsig_file() {
317 let parsed = V4Signature::from_idsig_path(format!("{}.idsig", TEST_APK_PATH)).unwrap();
318
319 assert_eq!(Version::V2, parsed.version);
320
321 let hi = parsed.hashing_info;
322 assert_eq!(HashAlgorithm::SHA256, hi.hash_algorithm);
323 assert_eq!(12, hi.log2_blocksize);
Tanmoy Mollik554fc5a2022-10-14 15:33:58 +0200324 assert_eq!("", hex::encode(hi.salt.as_ref()));
Alice Wang1bf3d782022-09-28 07:56:36 +0000325 assert_eq!(
326 "77f063b48b63f846690fa76450a8d3b61a295b6158f50592e873f76dbeeb0201",
Tanmoy Mollik554fc5a2022-10-14 15:33:58 +0200327 hex::encode(hi.raw_root_hash.as_ref())
Alice Wang1bf3d782022-09-28 07:56:36 +0000328 );
329
330 let si = parsed.signing_info;
331 assert_eq!(
332 "c02fe2eddeb3078801828b930de546ea4f98d37fb98b40c7c7ed169b0d713583",
Tanmoy Mollik554fc5a2022-10-14 15:33:58 +0200333 hex::encode(si.apk_digest.as_ref())
Alice Wang1bf3d782022-09-28 07:56:36 +0000334 );
Tanmoy Mollik554fc5a2022-10-14 15:33:58 +0200335 assert_eq!("", hex::encode(si.additional_data.as_ref()));
Alice Wang1bf3d782022-09-28 07:56:36 +0000336 assert_eq!(
337 "3046022100fb6383ba300dc7e1e6931a25b381398a16e5575baefd82afd12ba88660d9a6\
338 4c022100ebdcae13ab18c4e30bf6ae634462e526367e1ba26c2647a1d87a0f42843fc128",
Tanmoy Mollik554fc5a2022-10-14 15:33:58 +0200339 hex::encode(si.signature.as_ref())
Alice Wang1bf3d782022-09-28 07:56:36 +0000340 );
341 assert_eq!(SignatureAlgorithmID::EcdsaWithSha256, si.signature_algorithm_id);
342
343 assert_eq!(4096, parsed.merkle_tree_size);
344 assert_eq!(648, parsed.merkle_tree_offset);
345 }
346
347 /// Parse an idsig file into V4Signature and write it. The written date must be the same as
348 /// the input file.
349 #[test]
350 fn parse_and_compose() {
351 let idsig_path = format!("{}.idsig", TEST_APK_PATH);
352 let mut v4_signature = V4Signature::from_idsig_path(&idsig_path).unwrap();
353
354 let mut output = Cursor::new(Vec::new());
355 v4_signature.write_into(&mut output).unwrap();
356
357 assert_eq!(fs::read(&idsig_path).unwrap(), output.get_ref().as_slice());
358 }
359
360 /// Create V4Signature by hashing an APK. Merkle tree and the root hash should be the same
361 /// as those in the idsig file created by the signapk tool.
362 #[test]
363 fn digest_from_apk() {
364 let mut input = Cursor::new(include_bytes!("../tests/data/v4-digest-v3-Sha256withEC.apk"));
365 let mut created =
366 V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
367
368 let mut golden = V4Signature::from_idsig_path(format!("{}.idsig", TEST_APK_PATH)).unwrap();
369
370 // Compare the root hash
371 assert_eq!(
372 created.hashing_info.raw_root_hash.as_ref(),
373 golden.hashing_info.raw_root_hash.as_ref()
374 );
375
376 // Compare the merkle tree
377 assert_eq!(
378 created.merkle_tree().unwrap().as_slice(),
379 golden.merkle_tree().unwrap().as_slice()
380 );
381 }
382}