blob: 434a4298cc38d4e8064901c6595e3a21c8d7c91e [file] [log] [blame]
Jiyong Park86c9b082021-06-04 19:03:48 +09001/*
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
Jiyong Parkec168e32021-08-13 10:26:34 +090017use anyhow::{anyhow, bail, Context, Result};
Alice Wang0a293bb2022-09-19 08:41:40 +000018use apkverify::{pick_v4_apk_digest, SignatureAlgorithmID};
Jiyong Parkec168e32021-08-13 10:26:34 +090019use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
20use num_derive::{FromPrimitive, ToPrimitive};
21use num_traits::{FromPrimitive, ToPrimitive};
22use std::io::{copy, Cursor, Read, Seek, SeekFrom, Write};
Jiyong Park86c9b082021-06-04 19:03:48 +090023
Jiyong Parkec168e32021-08-13 10:26:34 +090024use crate::hashtree::*;
25
26// `apksigv4` module provides routines to decode and encode the idsig file as defined in [APK
27// signature scheme v4] (https://source.android.com/security/apksigning/v4).
Jiyong Park86c9b082021-06-04 19:03:48 +090028
Jiyong Parkbde94ab2021-08-11 18:32:01 +090029/// `V4Signature` provides access to the various fields in an idsig file.
Jiyong Parkec168e32021-08-13 10:26:34 +090030#[derive(Default)]
31pub struct V4Signature<R: Read + Seek> {
Jiyong Parkbde94ab2021-08-11 18:32:01 +090032 /// Version of the header. Should be 2.
Jiyong Park86c9b082021-06-04 19:03:48 +090033 pub version: Version,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090034 /// Provides access to the information about how the APK is hashed.
Jiyong Park86c9b082021-06-04 19:03:48 +090035 pub hashing_info: HashingInfo,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090036 /// Provides access to the information that can be used to verify this file
Jiyong Park86c9b082021-06-04 19:03:48 +090037 pub signing_info: SigningInfo,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090038 /// Total size of the merkle tree
Jiyong Park86c9b082021-06-04 19:03:48 +090039 pub merkle_tree_size: u32,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090040 /// Offset of the merkle tree in the idsig file
Jiyong Park86c9b082021-06-04 19:03:48 +090041 pub merkle_tree_offset: u64,
Jiyong Parkec168e32021-08-13 10:26:34 +090042
43 // Provides access to the underlying data
44 data: R,
Jiyong Park86c9b082021-06-04 19:03:48 +090045}
46
Jiyong Parkbde94ab2021-08-11 18:32:01 +090047/// `HashingInfo` provides information about how the APK is hashed.
Jiyong Parkec168e32021-08-13 10:26:34 +090048#[derive(Default)]
Jiyong Park86c9b082021-06-04 19:03:48 +090049pub struct HashingInfo {
Jiyong Parkbde94ab2021-08-11 18:32:01 +090050 /// Hash algorithm used when creating the merkle tree for the APK.
Jiyong Park86c9b082021-06-04 19:03:48 +090051 pub hash_algorithm: HashAlgorithm,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090052 /// The log size of a block used when creating the merkle tree. 12 if 4k block was used.
Jiyong Park86c9b082021-06-04 19:03:48 +090053 pub log2_blocksize: u8,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090054 /// The salt used when creating the merkle tree. 32 bytes max.
Jiyong Park86c9b082021-06-04 19:03:48 +090055 pub salt: Box<[u8]>,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090056 /// The root hash of the merkle tree created.
Jiyong Park86c9b082021-06-04 19:03:48 +090057 pub raw_root_hash: Box<[u8]>,
58}
59
Jiyong Parkbde94ab2021-08-11 18:32:01 +090060/// `SigningInfo` provides information that can be used to verify the idsig file.
Jiyong Parkec168e32021-08-13 10:26:34 +090061#[derive(Default)]
Jiyong Park86c9b082021-06-04 19:03:48 +090062pub struct SigningInfo {
Jiyong Parkbde94ab2021-08-11 18:32:01 +090063 /// Digest of the APK that this idsig file is for.
Jiyong Park86c9b082021-06-04 19:03:48 +090064 pub apk_digest: Box<[u8]>,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090065 /// Certificate of the signer that signed this idsig file. ASN.1 DER form.
Jiyong Park86c9b082021-06-04 19:03:48 +090066 pub x509_certificate: Box<[u8]>,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090067 /// A free-form binary data
Jiyong Park86c9b082021-06-04 19:03:48 +090068 pub additional_data: Box<[u8]>,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090069 /// Public key of the signer in ASN.1 DER form. This must match the `x509_certificate` field.
Jiyong Park86c9b082021-06-04 19:03:48 +090070 pub public_key: Box<[u8]>,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090071 /// Signature algorithm used to sign this file.
Alice Wang0a293bb2022-09-19 08:41:40 +000072 pub signature_algorithm_id: SignatureAlgorithmID,
Jiyong Parkbde94ab2021-08-11 18:32:01 +090073 /// The signature of this file.
Jiyong Park86c9b082021-06-04 19:03:48 +090074 pub signature: Box<[u8]>,
75}
76
Jiyong Parkbde94ab2021-08-11 18:32:01 +090077/// Version of the idsig file format
Chris Wailes6f5a9b52022-08-11 15:01:54 -070078#[derive(Debug, PartialEq, Eq, FromPrimitive, ToPrimitive)]
Jiyong Park86c9b082021-06-04 19:03:48 +090079#[repr(u32)]
80pub enum Version {
Jiyong Parkbde94ab2021-08-11 18:32:01 +090081 /// Version 2, the only supported version.
Jiyong Park86c9b082021-06-04 19:03:48 +090082 V2 = 2,
83}
84
85impl Version {
86 fn from(val: u32) -> Result<Version> {
Jiyong Park99a35b82021-06-07 10:13:44 +090087 Self::from_u32(val).ok_or_else(|| anyhow!("{} is an unsupported version", val))
Jiyong Park86c9b082021-06-04 19:03:48 +090088 }
89}
90
Jiyong Parkec168e32021-08-13 10:26:34 +090091impl Default for Version {
92 fn default() -> Self {
93 Version::V2
94 }
95}
96
Jiyong Parkbde94ab2021-08-11 18:32:01 +090097/// Hash algorithm that can be used for idsig file.
Chris Wailes6f5a9b52022-08-11 15:01:54 -070098#[derive(Debug, PartialEq, Eq, FromPrimitive, ToPrimitive)]
Jiyong Park86c9b082021-06-04 19:03:48 +090099#[repr(u32)]
100pub enum HashAlgorithm {
Jiyong Parkbde94ab2021-08-11 18:32:01 +0900101 /// SHA2-256
Jiyong Park86c9b082021-06-04 19:03:48 +0900102 SHA256 = 1,
103}
104
105impl HashAlgorithm {
106 fn from(val: u32) -> Result<HashAlgorithm> {
Jiyong Park99a35b82021-06-07 10:13:44 +0900107 Self::from_u32(val).ok_or_else(|| anyhow!("{} is an unsupported hash algorithm", val))
Jiyong Park86c9b082021-06-04 19:03:48 +0900108 }
109}
110
Jiyong Parkec168e32021-08-13 10:26:34 +0900111impl Default for HashAlgorithm {
112 fn default() -> Self {
113 HashAlgorithm::SHA256
114 }
115}
116
Jiyong Parkec168e32021-08-13 10:26:34 +0900117impl<R: Read + Seek> V4Signature<R> {
118 /// Consumes a stream for an idsig file into a `V4Signature` struct.
119 pub fn from(mut r: R) -> Result<V4Signature<R>> {
Jiyong Park86c9b082021-06-04 19:03:48 +0900120 Ok(V4Signature {
Jiyong Parkec168e32021-08-13 10:26:34 +0900121 version: Version::from(r.read_u32::<LittleEndian>()?)?,
Jiyong Park86c9b082021-06-04 19:03:48 +0900122 hashing_info: HashingInfo::from(&mut r)?,
123 signing_info: SigningInfo::from(&mut r)?,
Jiyong Parkec168e32021-08-13 10:26:34 +0900124 merkle_tree_size: r.read_u32::<LittleEndian>()?,
Jiyong Park86c9b082021-06-04 19:03:48 +0900125 merkle_tree_offset: r.stream_position()?,
Jiyong Parkec168e32021-08-13 10:26:34 +0900126 data: r,
Jiyong Park86c9b082021-06-04 19:03:48 +0900127 })
128 }
Jiyong Parkec168e32021-08-13 10:26:34 +0900129
130 /// Read a stream for an APK file and creates a corresponding `V4Signature` struct that digests
131 /// the APK file. Note that the signing is not done.
132 pub fn create(
133 mut apk: &mut R,
134 block_size: usize,
135 salt: &[u8],
136 algorithm: HashAlgorithm,
137 ) -> Result<V4Signature<Cursor<Vec<u8>>>> {
138 // Determine the size of the apk
139 let start = apk.stream_position()?;
140 let size = apk.seek(SeekFrom::End(0))? as usize;
141 apk.seek(SeekFrom::Start(start))?;
142
143 // Create hash tree (and root hash)
144 let algorithm = match algorithm {
Andrew Scull462569d2022-05-24 10:29:19 +0000145 HashAlgorithm::SHA256 => openssl::hash::MessageDigest::sha256(),
Jiyong Parkec168e32021-08-13 10:26:34 +0900146 };
147 let hash_tree = HashTree::from(&mut apk, size, salt, block_size, algorithm)?;
148
149 let mut ret = V4Signature {
150 version: Version::default(),
151 hashing_info: HashingInfo::default(),
152 signing_info: SigningInfo::default(),
153 merkle_tree_size: hash_tree.tree.len() as u32,
154 merkle_tree_offset: 0, // merkle tree starts from the beginning of `data`
155 data: Cursor::new(hash_tree.tree),
156 };
157 ret.hashing_info.raw_root_hash = hash_tree.root_hash.into_boxed_slice();
158 ret.hashing_info.log2_blocksize = log2(block_size);
159
Andrew Scull11d53ee2022-06-01 13:38:15 +0000160 apk.seek(SeekFrom::Start(start))?;
161 let (signature_algorithm_id, apk_digest) = pick_v4_apk_digest(apk)?;
Alice Wang2ef30742022-09-19 11:59:17 +0000162 ret.signing_info.signature_algorithm_id = signature_algorithm_id;
Andrew Scull11d53ee2022-06-01 13:38:15 +0000163 ret.signing_info.apk_digest = apk_digest;
164 // TODO(jiyong): add a signature to the signing_info struct
Jiyong Parkec168e32021-08-13 10:26:34 +0900165
166 Ok(ret)
167 }
168
169 /// Writes the data into a writer
170 pub fn write_into<W: Write + Seek>(&mut self, mut w: &mut W) -> Result<()> {
171 // Writes the header part
172 w.write_u32::<LittleEndian>(self.version.to_u32().unwrap())?;
173 self.hashing_info.write_into(&mut w)?;
174 self.signing_info.write_into(&mut w)?;
175 w.write_u32::<LittleEndian>(self.merkle_tree_size)?;
176
177 // Writes the merkle tree
178 self.data.seek(SeekFrom::Start(self.merkle_tree_offset))?;
179 let copied_size = copy(&mut self.data, &mut w)?;
180 if copied_size != self.merkle_tree_size as u64 {
181 bail!(
182 "merkle tree is {} bytes, but only {} bytes are written.",
183 self.merkle_tree_size,
184 copied_size
185 );
186 }
187 Ok(())
188 }
189
190 /// Returns the bytes that represents the merkle tree
191 pub fn merkle_tree(&mut self) -> Result<Vec<u8>> {
192 self.data.seek(SeekFrom::Start(self.merkle_tree_offset))?;
193 let mut out = Vec::new();
194 self.data.read_to_end(&mut out)?;
195 Ok(out)
196 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900197}
198
199impl HashingInfo {
200 fn from(mut r: &mut dyn Read) -> Result<HashingInfo> {
Jiyong Parkec168e32021-08-13 10:26:34 +0900201 // Size of the entire hashing_info struct. We don't need this because each variable-sized
202 // fields in the struct are also length encoded.
203 r.read_u32::<LittleEndian>()?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900204 Ok(HashingInfo {
Jiyong Parkec168e32021-08-13 10:26:34 +0900205 hash_algorithm: HashAlgorithm::from(r.read_u32::<LittleEndian>()?)?,
206 log2_blocksize: r.read_u8()?,
Jiyong Park86c9b082021-06-04 19:03:48 +0900207 salt: read_sized_array(&mut r)?,
208 raw_root_hash: read_sized_array(&mut r)?,
209 })
210 }
Jiyong Parkec168e32021-08-13 10:26:34 +0900211
212 fn write_into<W: Write + Seek>(&self, mut w: &mut W) -> Result<()> {
213 let start = w.stream_position()?;
214 // Size of the entire hashing_info struct. Since we don't know the size yet, fill the place
215 // with 0. The exact size will then be written below.
216 w.write_u32::<LittleEndian>(0)?;
217
218 w.write_u32::<LittleEndian>(self.hash_algorithm.to_u32().unwrap())?;
219 w.write_u8(self.log2_blocksize)?;
220 write_sized_array(&mut w, &self.salt)?;
221 write_sized_array(&mut w, &self.raw_root_hash)?;
222
223 // Determine the size of hashing_info, and write it in front of the struct where the value
224 // was initialized to zero.
225 let end = w.stream_position()?;
226 let size = end - start - std::mem::size_of::<u32>() as u64;
227 w.seek(SeekFrom::Start(start))?;
228 w.write_u32::<LittleEndian>(size as u32)?;
229 w.seek(SeekFrom::Start(end))?;
230 Ok(())
231 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900232}
233
234impl SigningInfo {
235 fn from(mut r: &mut dyn Read) -> Result<SigningInfo> {
Jiyong Parkec168e32021-08-13 10:26:34 +0900236 // Size of the entire signing_info struct. We don't need this because each variable-sized
237 // fields in the struct are also length encoded.
238 r.read_u32::<LittleEndian>()?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900239 Ok(SigningInfo {
240 apk_digest: read_sized_array(&mut r)?,
241 x509_certificate: read_sized_array(&mut r)?,
242 additional_data: read_sized_array(&mut r)?,
243 public_key: read_sized_array(&mut r)?,
Alice Wang0a293bb2022-09-19 08:41:40 +0000244 signature_algorithm_id: SignatureAlgorithmID::from_u32(r.read_u32::<LittleEndian>()?)
245 .context("Unsupported signature algorithm")?,
Jiyong Park86c9b082021-06-04 19:03:48 +0900246 signature: read_sized_array(&mut r)?,
247 })
248 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900249
Jiyong Parkec168e32021-08-13 10:26:34 +0900250 fn write_into<W: Write + Seek>(&self, mut w: &mut W) -> Result<()> {
251 let start = w.stream_position()?;
252 // Size of the entire signing_info struct. Since we don't know the size yet, fill the place
253 // with 0. The exact size will then be written below.
254 w.write_u32::<LittleEndian>(0)?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900255
Jiyong Parkec168e32021-08-13 10:26:34 +0900256 write_sized_array(&mut w, &self.apk_digest)?;
257 write_sized_array(&mut w, &self.x509_certificate)?;
258 write_sized_array(&mut w, &self.additional_data)?;
259 write_sized_array(&mut w, &self.public_key)?;
Alice Wang2ef30742022-09-19 11:59:17 +0000260 w.write_u32::<LittleEndian>(self.signature_algorithm_id.to_u32())?;
Jiyong Parkec168e32021-08-13 10:26:34 +0900261 write_sized_array(&mut w, &self.signature)?;
262
263 // Determine the size of signing_info, and write it in front of the struct where the value
264 // was initialized to zero.
265 let end = w.stream_position()?;
266 let size = end - start - std::mem::size_of::<u32>() as u64;
267 w.seek(SeekFrom::Start(start))?;
268 w.write_u32::<LittleEndian>(size as u32)?;
269 w.seek(SeekFrom::Start(end))?;
270 Ok(())
271 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900272}
273
274fn read_sized_array(r: &mut dyn Read) -> Result<Box<[u8]>> {
Jiyong Parkec168e32021-08-13 10:26:34 +0900275 let size = r.read_u32::<LittleEndian>()?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900276 let mut data = vec![0; size as usize];
277 r.read_exact(&mut data)?;
278 Ok(data.into_boxed_slice())
279}
280
Jiyong Parkec168e32021-08-13 10:26:34 +0900281fn write_sized_array(w: &mut dyn Write, data: &[u8]) -> Result<()> {
282 w.write_u32::<LittleEndian>(data.len() as u32)?;
283 Ok(w.write_all(data)?)
284}
285
286fn log2(n: usize) -> u8 {
287 let num_bits = std::mem::size_of::<usize>() * 8;
288 (num_bits as u32 - n.leading_zeros() - 1) as u8
289}
290
Jiyong Park86c9b082021-06-04 19:03:48 +0900291#[cfg(test)]
292mod tests {
Andrew Walbran117cd5e2021-08-13 11:42:13 +0000293 use super::*;
Jiyong Park86c9b082021-06-04 19:03:48 +0900294 use std::io::Cursor;
295
Jiyong Parkbde94ab2021-08-11 18:32:01 +0900296 fn hexstring_from(s: &[u8]) -> String {
297 s.iter().map(|byte| format!("{:02x}", byte)).reduce(|i, j| i + &j).unwrap_or_default()
298 }
299
Jiyong Park86c9b082021-06-04 19:03:48 +0900300 #[test]
301 fn parse_idsig_file() {
Alice Wang0a7858c2022-09-22 11:59:21 +0000302 let idsig = Cursor::new(include_bytes!("../testdata/v4-digest-v3-Sha256withEC.apk.idsig"));
Jiyong Park86c9b082021-06-04 19:03:48 +0900303 let parsed = V4Signature::from(idsig).unwrap();
304
305 assert_eq!(Version::V2, parsed.version);
306
307 let hi = parsed.hashing_info;
308 assert_eq!(HashAlgorithm::SHA256, hi.hash_algorithm);
309 assert_eq!(12, hi.log2_blocksize);
310 assert_eq!("", hexstring_from(hi.salt.as_ref()));
311 assert_eq!(
Alice Wang0a7858c2022-09-22 11:59:21 +0000312 "77f063b48b63f846690fa76450a8d3b61a295b6158f50592e873f76dbeeb0201",
Jiyong Park86c9b082021-06-04 19:03:48 +0900313 hexstring_from(hi.raw_root_hash.as_ref())
314 );
315
316 let si = parsed.signing_info;
317 assert_eq!(
Alice Wang0a7858c2022-09-22 11:59:21 +0000318 "c02fe2eddeb3078801828b930de546ea4f98d37fb98b40c7c7ed169b0d713583",
Jiyong Park86c9b082021-06-04 19:03:48 +0900319 hexstring_from(si.apk_digest.as_ref())
320 );
321 assert_eq!("", hexstring_from(si.additional_data.as_ref()));
322 assert_eq!(
Alice Wang0a7858c2022-09-22 11:59:21 +0000323 "3046022100fb6383ba300dc7e1e6931a25b381398a16e5575baefd82afd12ba88660d9a6\
324 4c022100ebdcae13ab18c4e30bf6ae634462e526367e1ba26c2647a1d87a0f42843fc128",
Jiyong Park86c9b082021-06-04 19:03:48 +0900325 hexstring_from(si.signature.as_ref())
326 );
Alice Wang0a7858c2022-09-22 11:59:21 +0000327 assert_eq!(SignatureAlgorithmID::EcdsaWithSha256, si.signature_algorithm_id);
Jiyong Park86c9b082021-06-04 19:03:48 +0900328
Alice Wang0a7858c2022-09-22 11:59:21 +0000329 assert_eq!(4096, parsed.merkle_tree_size);
330 assert_eq!(648, parsed.merkle_tree_offset);
Jiyong Park86c9b082021-06-04 19:03:48 +0900331 }
Jiyong Parkec168e32021-08-13 10:26:34 +0900332
333 /// Parse an idsig file into V4Signature and write it. The written date must be the same as
334 /// the input file.
335 #[test]
336 fn parse_and_compose() {
Alice Wang0a7858c2022-09-22 11:59:21 +0000337 let input = Cursor::new(include_bytes!("../testdata/v4-digest-v3-Sha256withEC.apk.idsig"));
Jiyong Parkec168e32021-08-13 10:26:34 +0900338 let mut parsed = V4Signature::from(input.clone()).unwrap();
339
340 let mut output = Cursor::new(Vec::new());
341 parsed.write_into(&mut output).unwrap();
342
343 assert_eq!(input.get_ref().as_ref(), output.get_ref().as_slice());
344 }
345
346 /// Create V4Signature by hashing an APK. Merkle tree and the root hash should be the same
347 /// as those in the idsig file created by the signapk tool.
348 #[test]
349 fn digest_from_apk() {
Alice Wang0a7858c2022-09-22 11:59:21 +0000350 let mut input = Cursor::new(include_bytes!("../testdata/v4-digest-v3-Sha256withEC.apk"));
Jiyong Parkec168e32021-08-13 10:26:34 +0900351 let mut created =
352 V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
353
Alice Wang0a7858c2022-09-22 11:59:21 +0000354 let golden = Cursor::new(include_bytes!("../testdata/v4-digest-v3-Sha256withEC.apk.idsig"));
Jiyong Parkec168e32021-08-13 10:26:34 +0900355 let mut golden = V4Signature::from(golden).unwrap();
356
357 // Compare the root hash
358 assert_eq!(
359 created.hashing_info.raw_root_hash.as_ref(),
360 golden.hashing_info.raw_root_hash.as_ref()
361 );
362
363 // Compare the merkle tree
364 assert_eq!(
365 created.merkle_tree().unwrap().as_slice(),
366 golden.merkle_tree().unwrap().as_slice()
367 );
368 }
Jiyong Park86c9b082021-06-04 19:03:48 +0900369}