blob: 75551dbf8254b7c9bd1dc47531d1e49646cdf425 [file] [log] [blame]
Jooyung Han12a0b702021-08-05 23:20:31 +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
17//! Verifies APK Signature Scheme V3
18
19use anyhow::{anyhow, bail, Result};
20use bytes::Bytes;
21use std::fs::File;
22use std::ops::Range;
23use std::path::Path;
24
25use crate::bytes_ext::{BytesExt, LengthPrefixed, ReadFromBytes};
26use crate::sigutil::{find_signature, is_supported_signature_algorithm, rank_signature_algorithm};
27
28pub const APK_SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
29
30// TODO(jooyung): get "ro.build.version.sdk"
31const SDK_INT: u32 = 31;
32
33/// Data model for Signature Scheme V3
34/// https://source.android.com/security/apksigning/v3#verification
35
36type Signers = LengthPrefixed<Vec<LengthPrefixed<Signer>>>;
37
38struct Signer {
39 signed_data: LengthPrefixed<Bytes>, // not verified yet
40 min_sdk: u32,
41 max_sdk: u32,
42 signatures: LengthPrefixed<Vec<LengthPrefixed<Signature>>>,
43 public_key: LengthPrefixed<Bytes>,
44}
45
46impl Signer {
47 fn sdk_range(&self) -> Range<u32> {
48 self.min_sdk..self.max_sdk
49 }
50}
51
52struct SignedData {
53 digests: LengthPrefixed<Vec<LengthPrefixed<Digest>>>,
54 certificates: LengthPrefixed<Vec<LengthPrefixed<X509Certificate>>>,
55 min_sdk: u32,
56 max_sdk: u32,
57 additional_attributes: LengthPrefixed<Vec<LengthPrefixed<AdditionalAttributes>>>,
58}
59
60impl SignedData {
61 fn sdk_range(&self) -> Range<u32> {
62 self.min_sdk..self.max_sdk
63 }
64}
65
66struct Signature {
67 signature_algorithm_id: u32,
68 signature: LengthPrefixed<Bytes>,
69}
70
71struct Digest {
72 signature_algorithm_id: u32,
73 digest: LengthPrefixed<Bytes>,
74}
75
76type X509Certificate = Bytes;
77type AdditionalAttributes = Bytes;
78
79/// Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
80/// associated with each signer.
81pub fn verify<P: AsRef<Path>>(path: P) -> Result<()> {
82 let mut f = File::open(path.as_ref())?;
83 let signature = find_signature(&mut f, APK_SIGNATURE_SCHEME_V3_BLOCK_ID)?;
84 verify_signature(&signature.signature_block)?;
85 Ok(())
86}
87
88/// Verifies the contents of the provided APK file against the provided APK Signature Scheme v3
89/// Block.
90fn verify_signature(block: &Bytes) -> Result<()> {
91 // parse v3 scheme block
92 let signers = block.slice(..).read::<Signers>()?;
93
94 // find supported by platform
95 let mut supported =
96 signers.iter().filter(|s| s.sdk_range().contains(&SDK_INT)).collect::<Vec<_>>();
97
98 // there should be exactly one
99 if supported.len() != 1 {
100 bail!("APK Signature Scheme V3 only supports one signer: {} signers found.", signers.len())
101 }
102
103 // and it should be verified
104 supported.pop().unwrap().verify()?;
105
106 Ok(())
107}
108
109impl Signer {
110 fn verify(&self) -> Result<()> {
111 // 1. Choose the strongest supported signature algorithm ID from signatures. The strength
112 // ordering is up to each implementation/platform version.
113 let strongest: &Signature = self
114 .signatures
115 .iter()
116 .filter(|sig| is_supported_signature_algorithm(sig.signature_algorithm_id))
117 .max_by_key(|sig| rank_signature_algorithm(sig.signature_algorithm_id).unwrap())
118 .ok_or_else(|| anyhow!("No supported signatures found"))?;
119
120 // 2. Verify the corresponding signature from signatures against signed data using public key.
121 // (It is now safe to parse signed data.)
122 verify_data(&self.signed_data, strongest, &self.public_key)?;
123
124 // It is now safe to parse signed data.
125 let signed_data: SignedData = self.signed_data.slice(..).read()?;
126
127 // 3. Verify the min and max SDK versions in the signed data match those specified for the
128 // signer.
129 if self.sdk_range() != signed_data.sdk_range() {
130 bail!("SDK versions mismatch between signed and unsigned in v3 signer block.");
131 }
132 // TODO(jooyung) 4. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
133 // TODO(jooyung) 5. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
134 // TODO(jooyung) 6. Verify that the computed digest is identical to the corresponding digest from digests.
135 // TODO(jooyung) 7. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
136 // TODO(jooyung) 8. If the proof-of-rotation attribute exists for the signer verify that the struct is valid and this signer is the last certificate in the list.
137 Ok(())
138 }
139}
140
141fn verify_data(_data: &Bytes, _signature: &Signature, _public_key: &Bytes) -> Result<()> {
142 // TODO(jooyung): verify signed_data with signature/public key
143 Ok(())
144}
145
146// ReadFromBytes implementations
147// TODO(jooyung): add derive macro: #[derive(ReadFromBytes)]
148
149impl ReadFromBytes for Signer {
150 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
151 Ok(Self {
152 signed_data: buf.read()?,
153 min_sdk: buf.read()?,
154 max_sdk: buf.read()?,
155 signatures: buf.read()?,
156 public_key: buf.read()?,
157 })
158 }
159}
160
161impl ReadFromBytes for SignedData {
162 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
163 Ok(Self {
164 digests: buf.read()?,
165 certificates: buf.read()?,
166 min_sdk: buf.read()?,
167 max_sdk: buf.read()?,
168 additional_attributes: buf.read()?,
169 })
170 }
171}
172
173impl ReadFromBytes for Signature {
174 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
175 Ok(Signature { signature_algorithm_id: buf.read()?, signature: buf.read()? })
176 }
177}
178
179impl ReadFromBytes for Digest {
180 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
181 Ok(Self { signature_algorithm_id: buf.read()?, digest: buf.read()? })
182 }
183}