blob: c05ab38bf0e02836eedd23be730f301b211117ef [file] [log] [blame]
Alice Wang5d0f89a2022-09-15 15:06:10 +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//! Algorithms used for APK Signature Scheme.
18
Alice Wangab5231f2022-09-28 12:36:48 +000019use anyhow::{ensure, Context, Result};
20use byteorder::{LittleEndian, ReadBytesExt};
Alice Wangd73d0ff2022-09-20 11:33:30 +000021use bytes::{Buf, Bytes};
Alice Wang0a293bb2022-09-19 08:41:40 +000022use num_derive::{FromPrimitive, ToPrimitive};
Alice Wangd73d0ff2022-09-20 11:33:30 +000023use num_traits::{FromPrimitive, ToPrimitive};
Alice Wang5d0f89a2022-09-15 15:06:10 +000024use openssl::hash::MessageDigest;
Alice Wanga66b5c02022-09-16 07:25:17 +000025use openssl::pkey::{self, PKey};
26use openssl::rsa::Padding;
27use openssl::sign::Verifier;
Alice Wang2ef30742022-09-19 11:59:17 +000028use serde::{Deserialize, Serialize};
Alice Wangab5231f2022-09-28 12:36:48 +000029use std::io::Read;
Alice Wang5d0f89a2022-09-15 15:06:10 +000030
Alice Wangd73d0ff2022-09-20 11:33:30 +000031use crate::bytes_ext::ReadFromBytes;
32
Alice Wang5d0f89a2022-09-15 15:06:10 +000033/// [Signature Algorithm IDs]: https://source.android.com/docs/security/apksigning/v2#signature-algorithm-ids
Alice Wang0a293bb2022-09-19 08:41:40 +000034/// [SignatureAlgorithm.java]: (tools/apksig/src/main/java/com/android/apksig/internal/apk/SignatureAlgorithm.java)
Alice Wang5d0f89a2022-09-15 15:06:10 +000035///
36/// Some of the algorithms are not implemented. See b/197052981.
Alice Wang815461f2023-01-31 12:59:00 +000037#[derive(
38 Serialize, Deserialize, Clone, Copy, Debug, Default, Eq, PartialEq, FromPrimitive, ToPrimitive,
39)]
Alice Wang5d0f89a2022-09-15 15:06:10 +000040#[repr(u32)]
41pub enum SignatureAlgorithmID {
Alice Wang0a293bb2022-09-19 08:41:40 +000042 /// RSASSA-PSS with SHA2-256 digest, SHA2-256 MGF1, 32 bytes of salt, trailer: 0xbc, content
43 /// digested using SHA2-256 in 1 MB chunks.
Alice Wang815461f2023-01-31 12:59:00 +000044 #[default]
Alice Wang5d0f89a2022-09-15 15:06:10 +000045 RsaPssWithSha256 = 0x0101,
Alice Wang0a293bb2022-09-19 08:41:40 +000046
47 /// RSASSA-PSS with SHA2-512 digest, SHA2-512 MGF1, 64 bytes of salt, trailer: 0xbc, content
48 /// digested using SHA2-512 in 1 MB chunks.
Alice Wang5d0f89a2022-09-15 15:06:10 +000049 RsaPssWithSha512 = 0x0102,
Alice Wang0a293bb2022-09-19 08:41:40 +000050
51 /// RSASSA-PKCS1-v1_5 with SHA2-256 digest, content digested using SHA2-256 in 1 MB chunks.
Alice Wang5d0f89a2022-09-15 15:06:10 +000052 RsaPkcs1V15WithSha256 = 0x0103,
Alice Wang0a293bb2022-09-19 08:41:40 +000053
54 /// RSASSA-PKCS1-v1_5 with SHA2-512 digest, content digested using SHA2-512 in 1 MB chunks.
Alice Wang5d0f89a2022-09-15 15:06:10 +000055 RsaPkcs1V15WithSha512 = 0x0104,
Alice Wang0a293bb2022-09-19 08:41:40 +000056
57 /// ECDSA with SHA2-256 digest, content digested using SHA2-256 in 1 MB chunks.
Alice Wang5d0f89a2022-09-15 15:06:10 +000058 EcdsaWithSha256 = 0x0201,
Alice Wang0a293bb2022-09-19 08:41:40 +000059
60 /// ECDSA with SHA2-512 digest, content digested using SHA2-512 in 1 MB chunks.
Alice Wang5d0f89a2022-09-15 15:06:10 +000061 EcdsaWithSha512 = 0x0202,
Alice Wang0a293bb2022-09-19 08:41:40 +000062
63 /// DSA with SHA2-256 digest, content digested using SHA2-256 in 1 MB chunks.
64 /// Signing is done deterministically according to RFC 6979.
Alice Wang5d0f89a2022-09-15 15:06:10 +000065 DsaWithSha256 = 0x0301,
Alice Wang0a293bb2022-09-19 08:41:40 +000066
67 /// RSASSA-PKCS1-v1_5 with SHA2-256 digest, content digested using SHA2-256 in 4 KB
68 /// chunks, in the same way fsverity operates. This digest and the content length
69 /// (before digestion, 8 bytes in little endian) construct the final digest.
Alice Wang5d0f89a2022-09-15 15:06:10 +000070 VerityRsaPkcs1V15WithSha256 = 0x0421,
Alice Wang0a293bb2022-09-19 08:41:40 +000071
72 /// ECDSA with SHA2-256 digest, content digested using SHA2-256 in 4 KB chunks, in the
73 /// same way fsverity operates. This digest and the content length (before digestion,
74 /// 8 bytes in little endian) construct the final digest.
Alice Wang5d0f89a2022-09-15 15:06:10 +000075 VerityEcdsaWithSha256 = 0x0423,
Alice Wang0a293bb2022-09-19 08:41:40 +000076
77 /// DSA with SHA2-256 digest, content digested using SHA2-256 in 4 KB chunks, in the
78 /// same way fsverity operates. This digest and the content length (before digestion,
79 /// 8 bytes in little endian) construct the final digest.
Alice Wang5d0f89a2022-09-15 15:06:10 +000080 VerityDsaWithSha256 = 0x0425,
81}
82
Alice Wangd73d0ff2022-09-20 11:33:30 +000083impl ReadFromBytes for Option<SignatureAlgorithmID> {
84 fn read_from_bytes(buf: &mut Bytes) -> Result<Self> {
85 Ok(SignatureAlgorithmID::from_u32(buf.get_u32_le()))
86 }
87}
88
Alice Wang5d0f89a2022-09-15 15:06:10 +000089impl SignatureAlgorithmID {
Alice Wang2ef30742022-09-19 11:59:17 +000090 /// Converts the signature algorithm ID to the corresponding u32.
91 pub fn to_u32(&self) -> u32 {
92 ToPrimitive::to_u32(self).expect("Unsupported algorithm for to_u32.")
93 }
94
Alice Wanga66b5c02022-09-16 07:25:17 +000095 pub(crate) fn new_verifier<'a>(
96 &self,
97 public_key: &'a PKey<pkey::Public>,
98 ) -> Result<Verifier<'a>> {
Andrew Scull3bae36c2022-09-21 21:55:42 +000099 ensure!(
100 !matches!(
101 self,
102 SignatureAlgorithmID::DsaWithSha256 | SignatureAlgorithmID::VerityDsaWithSha256
103 ),
Alice Wang50701022022-09-21 08:51:38 +0000104 "Algorithm '{:?}' is not supported in openssl to build this verifier (b/197052981).",
Andrew Scull3bae36c2022-09-21 21:55:42 +0000105 self
106 );
Alice Wanga66b5c02022-09-16 07:25:17 +0000107 ensure!(public_key.id() == self.pkey_id(), "Public key has the wrong ID");
108 let mut verifier = Verifier::new(self.new_message_digest(), public_key)?;
109 if public_key.id() == pkey::Id::RSA {
110 verifier.set_rsa_padding(self.rsa_padding())?;
111 }
112 Ok(verifier)
113 }
114
115 /// Returns the message digest corresponding to the signature algorithm
116 /// according to the spec [Signature Algorithm IDs].
Alice Wang1ffff622022-09-16 13:45:47 +0000117 pub(crate) fn new_message_digest(&self) -> MessageDigest {
Alice Wanga66b5c02022-09-16 07:25:17 +0000118 match self {
119 SignatureAlgorithmID::RsaPssWithSha256
120 | SignatureAlgorithmID::RsaPkcs1V15WithSha256
121 | SignatureAlgorithmID::EcdsaWithSha256
122 | SignatureAlgorithmID::DsaWithSha256
123 | SignatureAlgorithmID::VerityRsaPkcs1V15WithSha256
124 | SignatureAlgorithmID::VerityEcdsaWithSha256
125 | SignatureAlgorithmID::VerityDsaWithSha256 => MessageDigest::sha256(),
126 SignatureAlgorithmID::RsaPssWithSha512
127 | SignatureAlgorithmID::RsaPkcs1V15WithSha512
128 | SignatureAlgorithmID::EcdsaWithSha512 => MessageDigest::sha512(),
129 }
130 }
131
Alice Wang50701022022-09-21 08:51:38 +0000132 /// DSA is not directly supported in openssl today. See b/197052981.
133 pub(crate) fn is_supported(&self) -> bool {
134 !matches!(
135 self,
136 SignatureAlgorithmID::DsaWithSha256 | SignatureAlgorithmID::VerityDsaWithSha256,
137 )
138 }
139
Alice Wanga66b5c02022-09-16 07:25:17 +0000140 fn pkey_id(&self) -> pkey::Id {
141 match self {
142 SignatureAlgorithmID::RsaPssWithSha256
143 | SignatureAlgorithmID::RsaPssWithSha512
144 | SignatureAlgorithmID::RsaPkcs1V15WithSha256
145 | SignatureAlgorithmID::RsaPkcs1V15WithSha512
146 | SignatureAlgorithmID::VerityRsaPkcs1V15WithSha256 => pkey::Id::RSA,
147 SignatureAlgorithmID::EcdsaWithSha256
148 | SignatureAlgorithmID::EcdsaWithSha512
149 | SignatureAlgorithmID::VerityEcdsaWithSha256 => pkey::Id::EC,
150 SignatureAlgorithmID::DsaWithSha256 | SignatureAlgorithmID::VerityDsaWithSha256 => {
151 pkey::Id::DSA
152 }
153 }
154 }
155
156 fn rsa_padding(&self) -> Padding {
157 match self {
158 SignatureAlgorithmID::RsaPssWithSha256 | SignatureAlgorithmID::RsaPssWithSha512 => {
159 Padding::PKCS1_PSS
160 }
161 SignatureAlgorithmID::RsaPkcs1V15WithSha256
162 | SignatureAlgorithmID::VerityRsaPkcs1V15WithSha256
163 | SignatureAlgorithmID::RsaPkcs1V15WithSha512 => Padding::PKCS1,
164 SignatureAlgorithmID::EcdsaWithSha256
165 | SignatureAlgorithmID::EcdsaWithSha512
166 | SignatureAlgorithmID::VerityEcdsaWithSha256
167 | SignatureAlgorithmID::DsaWithSha256
168 | SignatureAlgorithmID::VerityDsaWithSha256 => Padding::NONE,
169 }
170 }
Alice Wang1ffff622022-09-16 13:45:47 +0000171
Alice Wangd73d0ff2022-09-20 11:33:30 +0000172 pub(crate) fn content_digest_algorithm(&self) -> ContentDigestAlgorithm {
Alice Wang1ffff622022-09-16 13:45:47 +0000173 match self {
174 SignatureAlgorithmID::RsaPssWithSha256
175 | SignatureAlgorithmID::RsaPkcs1V15WithSha256
176 | SignatureAlgorithmID::EcdsaWithSha256
177 | SignatureAlgorithmID::DsaWithSha256 => ContentDigestAlgorithm::ChunkedSha256,
178 SignatureAlgorithmID::RsaPssWithSha512
179 | SignatureAlgorithmID::RsaPkcs1V15WithSha512
180 | SignatureAlgorithmID::EcdsaWithSha512 => ContentDigestAlgorithm::ChunkedSha512,
181 SignatureAlgorithmID::VerityRsaPkcs1V15WithSha256
182 | SignatureAlgorithmID::VerityEcdsaWithSha256
183 | SignatureAlgorithmID::VerityDsaWithSha256 => {
184 ContentDigestAlgorithm::VerityChunkedSha256
185 }
186 }
187 }
Alice Wang5d0f89a2022-09-15 15:06:10 +0000188}
189
190/// The rank of the content digest algorithm in this enum is used to help pick
191/// v4 apk digest.
192/// According to APK Signature Scheme v4, [apk digest] is the first available
193/// content digest of the highest rank (rank N).
194///
195/// This rank was also used for step 3a of the v3 signature verification.
196///
197/// [apk digest]: https://source.android.com/docs/security/features/apksigning/v4#apk-digest
198/// [v3 verification]: https://source.android.com/docs/security/apksigning/v3#v3-verification
199#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
Alice Wangb1e15ca2022-09-19 11:06:11 +0000200pub(crate) enum ContentDigestAlgorithm {
Alice Wang5d0f89a2022-09-15 15:06:10 +0000201 ChunkedSha256 = 1,
202 VerityChunkedSha256,
203 ChunkedSha512,
204}
Alice Wangab5231f2022-09-28 12:36:48 +0000205
206/// Hash algorithms.
Charisee668224f2023-03-03 02:02:34 +0000207#[derive(Clone, Copy, Debug, PartialEq, Eq, FromPrimitive, ToPrimitive, Default)]
Alice Wangab5231f2022-09-28 12:36:48 +0000208#[repr(u32)]
209pub enum HashAlgorithm {
Charisee668224f2023-03-03 02:02:34 +0000210 #[default]
Alice Wangab5231f2022-09-28 12:36:48 +0000211 /// SHA-256
212 SHA256 = 1,
213}
214
215impl HashAlgorithm {
216 pub(crate) fn from_read<R: Read>(read: &mut R) -> Result<Self> {
217 let val = read.read_u32::<LittleEndian>()?;
218 Self::from_u32(val).context(format!("Unsupported hash algorithm: {}", val))
219 }
220}