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