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