blob: 4431bcef1ff4a4880750db49137aec7816829bad [file] [log] [blame]
Daniel Cashman67096e02017-12-28 12:46:33 -08001/*
2 * Copyright (C) 2018 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
17package android.util.apk;
18
Victor Hsieh07bc80c2018-01-11 16:15:47 -080019import static android.util.apk.ApkSigningBlockUtils.CONTENT_DIGEST_VERITY_CHUNKED_SHA256;
Daniel Cashman67096e02017-12-28 12:46:33 -080020import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_DSA_WITH_SHA256;
21import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_ECDSA_WITH_SHA256;
22import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_ECDSA_WITH_SHA512;
23import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256;
24import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512;
25import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_RSA_PSS_WITH_SHA256;
26import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_RSA_PSS_WITH_SHA512;
Victor Hsieh4acad4c2018-01-04 13:36:15 -080027import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_VERITY_DSA_WITH_SHA256;
28import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_VERITY_ECDSA_WITH_SHA256;
29import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256;
Daniel Cashman67096e02017-12-28 12:46:33 -080030import static android.util.apk.ApkSigningBlockUtils.compareSignatureAlgorithm;
31import static android.util.apk.ApkSigningBlockUtils.getContentDigestAlgorithmJcaDigestAlgorithm;
32import static android.util.apk.ApkSigningBlockUtils.getLengthPrefixedSlice;
33import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmContentDigestAlgorithm;
34import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmJcaKeyAlgorithm;
35import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmJcaSignatureAlgorithm;
36import static android.util.apk.ApkSigningBlockUtils.readLengthPrefixedByteArray;
37
38import android.os.Build;
39import android.util.ArrayMap;
40import android.util.Pair;
41
42import java.io.ByteArrayInputStream;
Daniel Cashman67096e02017-12-28 12:46:33 -080043import java.io.IOException;
44import java.io.RandomAccessFile;
45import java.nio.BufferUnderflowException;
46import java.nio.ByteBuffer;
Victor Hsieh07bc80c2018-01-11 16:15:47 -080047import java.security.DigestException;
Daniel Cashman67096e02017-12-28 12:46:33 -080048import java.security.InvalidAlgorithmParameterException;
49import java.security.InvalidKeyException;
50import java.security.KeyFactory;
51import java.security.MessageDigest;
52import java.security.NoSuchAlgorithmException;
53import java.security.PublicKey;
54import java.security.Signature;
55import java.security.SignatureException;
Dan Cashmancd4cb812018-01-02 14:55:58 -080056import java.security.cert.CertificateEncodingException;
Daniel Cashman67096e02017-12-28 12:46:33 -080057import java.security.cert.CertificateException;
58import java.security.cert.CertificateFactory;
59import java.security.cert.X509Certificate;
60import java.security.spec.AlgorithmParameterSpec;
61import java.security.spec.InvalidKeySpecException;
62import java.security.spec.X509EncodedKeySpec;
63import java.util.ArrayList;
64import java.util.Arrays;
65import java.util.List;
66import java.util.Map;
67
68/**
69 * APK Signature Scheme v3 verifier.
70 *
71 * @hide for internal use only.
72 */
73public class ApkSignatureSchemeV3Verifier {
74
75 /**
76 * ID of this signature scheme as used in X-Android-APK-Signed header used in JAR signing.
77 */
78 public static final int SF_ATTRIBUTE_ANDROID_APK_SIGNED_ID = 3;
79
80 private static final int APK_SIGNATURE_SCHEME_V3_BLOCK_ID = 0xf05368c0;
81
82 /**
83 * Returns {@code true} if the provided APK contains an APK Signature Scheme V3 signature.
84 *
85 * <p><b>NOTE: This method does not verify the signature.</b>
86 */
87 public static boolean hasSignature(String apkFile) throws IOException {
88 try (RandomAccessFile apk = new RandomAccessFile(apkFile, "r")) {
89 findSignature(apk);
90 return true;
91 } catch (SignatureNotFoundException e) {
92 return false;
93 }
94 }
95
96 /**
97 * Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
98 * associated with each signer.
99 *
100 * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v3.
101 * @throws SecurityException if the APK Signature Scheme v3 signature of this APK does not
102 * verify.
103 * @throws IOException if an I/O error occurs while reading the APK file.
104 */
105 public static VerifiedSigner verify(String apkFile)
106 throws SignatureNotFoundException, SecurityException, IOException {
107 return verify(apkFile, true);
108 }
109
110 /**
111 * Returns the certificates associated with each signer for the given APK without verification.
112 * This method is dangerous and should not be used, unless the caller is absolutely certain the
113 * APK is trusted. Specifically, verification is only done for the APK Signature Scheme v3
114 * Block while gathering signer information. The APK contents are not verified.
115 *
116 * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v3.
117 * @throws IOException if an I/O error occurs while reading the APK file.
118 */
119 public static VerifiedSigner plsCertsNoVerifyOnlyCerts(String apkFile)
120 throws SignatureNotFoundException, SecurityException, IOException {
121 return verify(apkFile, false);
122 }
123
124 private static VerifiedSigner verify(String apkFile, boolean verifyIntegrity)
125 throws SignatureNotFoundException, SecurityException, IOException {
126 try (RandomAccessFile apk = new RandomAccessFile(apkFile, "r")) {
127 return verify(apk, verifyIntegrity);
128 }
129 }
130
131 /**
132 * Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
133 * associated with each signer.
134 *
135 * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v3.
136 * @throws SecurityException if an APK Signature Scheme v3 signature of this APK does not
137 * verify.
138 * @throws IOException if an I/O error occurs while reading the APK file.
139 */
140 private static VerifiedSigner verify(RandomAccessFile apk, boolean verifyIntegrity)
141 throws SignatureNotFoundException, SecurityException, IOException {
142 SignatureInfo signatureInfo = findSignature(apk);
Victor Hsieh4acad4c2018-01-04 13:36:15 -0800143 return verify(apk, signatureInfo, verifyIntegrity);
Daniel Cashman67096e02017-12-28 12:46:33 -0800144 }
145
146 /**
147 * Returns the APK Signature Scheme v3 block contained in the provided APK file and the
148 * additional information relevant for verifying the block against the file.
149 *
150 * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v3.
151 * @throws IOException if an I/O error occurs while reading the APK file.
152 */
153 private static SignatureInfo findSignature(RandomAccessFile apk)
154 throws IOException, SignatureNotFoundException {
155 return ApkSigningBlockUtils.findSignature(apk, APK_SIGNATURE_SCHEME_V3_BLOCK_ID);
156 }
157
158 /**
159 * Verifies the contents of the provided APK file against the provided APK Signature Scheme v3
160 * Block.
161 *
162 * @param signatureInfo APK Signature Scheme v3 Block and information relevant for verifying it
163 * against the APK file.
164 */
165 private static VerifiedSigner verify(
Victor Hsieh4acad4c2018-01-04 13:36:15 -0800166 RandomAccessFile apk,
Daniel Cashman67096e02017-12-28 12:46:33 -0800167 SignatureInfo signatureInfo,
Victor Hsieh4ba1eea2018-03-02 14:26:19 -0800168 boolean doVerifyIntegrity) throws SecurityException, IOException {
Daniel Cashman67096e02017-12-28 12:46:33 -0800169 int signerCount = 0;
170 Map<Integer, byte[]> contentDigests = new ArrayMap<>();
171 VerifiedSigner result = null;
172 CertificateFactory certFactory;
173 try {
174 certFactory = CertificateFactory.getInstance("X.509");
175 } catch (CertificateException e) {
176 throw new RuntimeException("Failed to obtain X.509 CertificateFactory", e);
177 }
178 ByteBuffer signers;
179 try {
180 signers = getLengthPrefixedSlice(signatureInfo.signatureBlock);
181 } catch (IOException e) {
182 throw new SecurityException("Failed to read list of signers", e);
183 }
184 while (signers.hasRemaining()) {
185 try {
186 ByteBuffer signer = getLengthPrefixedSlice(signers);
187 result = verifySigner(signer, contentDigests, certFactory);
188 signerCount++;
189 } catch (PlatformNotSupportedException e) {
190 // this signer is for a different platform, ignore it.
191 continue;
192 } catch (IOException | BufferUnderflowException | SecurityException e) {
193 throw new SecurityException(
194 "Failed to parse/verify signer #" + signerCount + " block",
195 e);
196 }
197 }
198
199 if (signerCount < 1 || result == null) {
200 throw new SecurityException("No signers found");
201 }
202
203 if (signerCount != 1) {
204 throw new SecurityException("APK Signature Scheme V3 only supports one signer: "
205 + "multiple signers found.");
206 }
207
208 if (contentDigests.isEmpty()) {
209 throw new SecurityException("No content digests found");
210 }
211
212 if (doVerifyIntegrity) {
Victor Hsieh4acad4c2018-01-04 13:36:15 -0800213 ApkSigningBlockUtils.verifyIntegrity(contentDigests, apk, signatureInfo);
Daniel Cashman67096e02017-12-28 12:46:33 -0800214 }
215
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800216 if (contentDigests.containsKey(CONTENT_DIGEST_VERITY_CHUNKED_SHA256)) {
Victor Hsieh4ba1eea2018-03-02 14:26:19 -0800217 byte[] verityDigest = contentDigests.get(CONTENT_DIGEST_VERITY_CHUNKED_SHA256);
218 result.verityRootHash = ApkSigningBlockUtils.parseVerityDigestAndVerifySourceLength(
219 verityDigest, apk.length(), signatureInfo);
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800220 }
221
Daniel Cashman67096e02017-12-28 12:46:33 -0800222 return result;
223 }
224
225 private static VerifiedSigner verifySigner(
226 ByteBuffer signerBlock,
227 Map<Integer, byte[]> contentDigests,
228 CertificateFactory certFactory)
229 throws SecurityException, IOException, PlatformNotSupportedException {
230 ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
231 int minSdkVersion = signerBlock.getInt();
232 int maxSdkVersion = signerBlock.getInt();
233
234 if (Build.VERSION.SDK_INT < minSdkVersion || Build.VERSION.SDK_INT > maxSdkVersion) {
235 // this signature isn't meant to be used with this platform, skip it.
236 throw new PlatformNotSupportedException(
237 "Signer not supported by this platform "
238 + "version. This platform: " + Build.VERSION.SDK_INT
239 + ", signer minSdkVersion: " + minSdkVersion
240 + ", maxSdkVersion: " + maxSdkVersion);
241 }
242
243 ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
244 byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
245
246 int signatureCount = 0;
247 int bestSigAlgorithm = -1;
248 byte[] bestSigAlgorithmSignatureBytes = null;
249 List<Integer> signaturesSigAlgorithms = new ArrayList<>();
250 while (signatures.hasRemaining()) {
251 signatureCount++;
252 try {
253 ByteBuffer signature = getLengthPrefixedSlice(signatures);
254 if (signature.remaining() < 8) {
255 throw new SecurityException("Signature record too short");
256 }
257 int sigAlgorithm = signature.getInt();
258 signaturesSigAlgorithms.add(sigAlgorithm);
259 if (!isSupportedSignatureAlgorithm(sigAlgorithm)) {
260 continue;
261 }
262 if ((bestSigAlgorithm == -1)
263 || (compareSignatureAlgorithm(sigAlgorithm, bestSigAlgorithm) > 0)) {
264 bestSigAlgorithm = sigAlgorithm;
265 bestSigAlgorithmSignatureBytes = readLengthPrefixedByteArray(signature);
266 }
267 } catch (IOException | BufferUnderflowException e) {
268 throw new SecurityException(
269 "Failed to parse signature record #" + signatureCount,
270 e);
271 }
272 }
273 if (bestSigAlgorithm == -1) {
274 if (signatureCount == 0) {
275 throw new SecurityException("No signatures found");
276 } else {
277 throw new SecurityException("No supported signatures found");
278 }
279 }
280
281 String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(bestSigAlgorithm);
282 Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams =
283 getSignatureAlgorithmJcaSignatureAlgorithm(bestSigAlgorithm);
284 String jcaSignatureAlgorithm = signatureAlgorithmParams.first;
285 AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second;
286 boolean sigVerified;
287 try {
288 PublicKey publicKey =
289 KeyFactory.getInstance(keyAlgorithm)
290 .generatePublic(new X509EncodedKeySpec(publicKeyBytes));
291 Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
292 sig.initVerify(publicKey);
293 if (jcaSignatureAlgorithmParams != null) {
294 sig.setParameter(jcaSignatureAlgorithmParams);
295 }
296 sig.update(signedData);
297 sigVerified = sig.verify(bestSigAlgorithmSignatureBytes);
298 } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException
299 | InvalidAlgorithmParameterException | SignatureException e) {
300 throw new SecurityException(
301 "Failed to verify " + jcaSignatureAlgorithm + " signature", e);
302 }
303 if (!sigVerified) {
304 throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify");
305 }
306
307 // Signature over signedData has verified.
308
309 byte[] contentDigest = null;
310 signedData.clear();
311 ByteBuffer digests = getLengthPrefixedSlice(signedData);
312 List<Integer> digestsSigAlgorithms = new ArrayList<>();
313 int digestCount = 0;
314 while (digests.hasRemaining()) {
315 digestCount++;
316 try {
317 ByteBuffer digest = getLengthPrefixedSlice(digests);
318 if (digest.remaining() < 8) {
319 throw new IOException("Record too short");
320 }
321 int sigAlgorithm = digest.getInt();
322 digestsSigAlgorithms.add(sigAlgorithm);
323 if (sigAlgorithm == bestSigAlgorithm) {
324 contentDigest = readLengthPrefixedByteArray(digest);
325 }
326 } catch (IOException | BufferUnderflowException e) {
327 throw new IOException("Failed to parse digest record #" + digestCount, e);
328 }
329 }
330
331 if (!signaturesSigAlgorithms.equals(digestsSigAlgorithms)) {
332 throw new SecurityException(
333 "Signature algorithms don't match between digests and signatures records");
334 }
335 int digestAlgorithm = getSignatureAlgorithmContentDigestAlgorithm(bestSigAlgorithm);
336 byte[] previousSignerDigest = contentDigests.put(digestAlgorithm, contentDigest);
337 if ((previousSignerDigest != null)
338 && (!MessageDigest.isEqual(previousSignerDigest, contentDigest))) {
339 throw new SecurityException(
340 getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm)
341 + " contents digest does not match the digest specified by a preceding signer");
342 }
343
344 ByteBuffer certificates = getLengthPrefixedSlice(signedData);
345 List<X509Certificate> certs = new ArrayList<>();
346 int certificateCount = 0;
347 while (certificates.hasRemaining()) {
348 certificateCount++;
349 byte[] encodedCert = readLengthPrefixedByteArray(certificates);
350 X509Certificate certificate;
351 try {
352 certificate = (X509Certificate)
353 certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
354 } catch (CertificateException e) {
355 throw new SecurityException("Failed to decode certificate #" + certificateCount, e);
356 }
357 certificate = new VerbatimX509Certificate(
358 certificate, encodedCert);
359 certs.add(certificate);
360 }
361
362 if (certs.isEmpty()) {
363 throw new SecurityException("No certificates listed");
364 }
365 X509Certificate mainCertificate = certs.get(0);
366 byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
367 if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
368 throw new SecurityException(
369 "Public key mismatch between certificate and signature record");
370 }
371
372 int signedMinSDK = signedData.getInt();
373 if (signedMinSDK != minSdkVersion) {
374 throw new SecurityException(
375 "minSdkVersion mismatch between signed and unsigned in v3 signer block.");
376 }
377
378 int signedMaxSDK = signedData.getInt();
379 if (signedMaxSDK != maxSdkVersion) {
380 throw new SecurityException(
381 "maxSdkVersion mismatch between signed and unsigned in v3 signer block.");
382 }
383
384 ByteBuffer additionalAttrs = getLengthPrefixedSlice(signedData);
385 return verifyAdditionalAttributes(additionalAttrs, certs, certFactory);
386 }
387
388 private static final int PROOF_OF_ROTATION_ATTR_ID = 0x3ba06f8c;
389
390 private static VerifiedSigner verifyAdditionalAttributes(ByteBuffer attrs,
391 List<X509Certificate> certs, CertificateFactory certFactory) throws IOException {
392 X509Certificate[] certChain = certs.toArray(new X509Certificate[certs.size()]);
393 VerifiedProofOfRotation por = null;
394
395 while (attrs.hasRemaining()) {
396 ByteBuffer attr = getLengthPrefixedSlice(attrs);
397 if (attr.remaining() < 4) {
398 throw new IOException("Remaining buffer too short to contain additional attribute "
399 + "ID. Remaining: " + attr.remaining());
400 }
401 int id = attr.getInt();
402 switch(id) {
403 case PROOF_OF_ROTATION_ATTR_ID:
404 if (por != null) {
405 throw new SecurityException("Encountered multiple Proof-of-rotation records"
Dan Cashmancd4cb812018-01-02 14:55:58 -0800406 + " when verifying APK Signature Scheme v3 signature");
Daniel Cashman67096e02017-12-28 12:46:33 -0800407 }
408 por = verifyProofOfRotationStruct(attr, certFactory);
Dan Cashmancd4cb812018-01-02 14:55:58 -0800409 // make sure that the last certificate in the Proof-of-rotation record matches
410 // the one used to sign this APK.
411 try {
412 if (por.certs.size() > 0
413 && !Arrays.equals(por.certs.get(por.certs.size() - 1).getEncoded(),
414 certChain[0].getEncoded())) {
415 throw new SecurityException("Terminal certificate in Proof-of-rotation"
416 + " record does not match APK signing certificate");
417 }
418 } catch (CertificateEncodingException e) {
419 throw new SecurityException("Failed to encode certificate when comparing"
420 + " Proof-of-rotation record and signing certificate", e);
421 }
422
Daniel Cashman67096e02017-12-28 12:46:33 -0800423 break;
424 default:
425 // not the droid we're looking for, move along, move along.
426 break;
427 }
428 }
429 return new VerifiedSigner(certChain, por);
430 }
431
432 private static VerifiedProofOfRotation verifyProofOfRotationStruct(
433 ByteBuffer porBuf,
434 CertificateFactory certFactory)
435 throws SecurityException, IOException {
436 int levelCount = 0;
437 int lastSigAlgorithm = -1;
438 X509Certificate lastCert = null;
439 List<X509Certificate> certs = new ArrayList<>();
440 List<Integer> flagsList = new ArrayList<>();
441
442 // Proof-of-rotation struct:
Dan Cashmana656b8b2018-01-26 13:53:59 -0800443 // A uint32 version code followed by basically a singly linked list of nodes, called levels
444 // here, each of which have the following structure:
Daniel Cashman67096e02017-12-28 12:46:33 -0800445 // * length-prefix for the entire level
446 // - length-prefixed signed data (if previous level exists)
447 // * length-prefixed X509 Certificate
448 // * uint32 signature algorithm ID describing how this signed data was signed
449 // - uint32 flags describing how to treat the cert contained in this level
450 // - uint32 signature algorithm ID to use to verify the signature of the next level. The
451 // algorithm here must match the one in the signed data section of the next level.
452 // - length-prefixed signature over the signed data in this level. The signature here
453 // is verified using the certificate from the previous level.
454 // The linking is provided by the certificate of each level signing the one of the next.
Dan Cashmana656b8b2018-01-26 13:53:59 -0800455
456 try {
457
458 // get the version code, but don't do anything with it: creator knew about all our flags
459 porBuf.getInt();
460 while (porBuf.hasRemaining()) {
461 levelCount++;
Daniel Cashman67096e02017-12-28 12:46:33 -0800462 ByteBuffer level = getLengthPrefixedSlice(porBuf);
463 ByteBuffer signedData = getLengthPrefixedSlice(level);
464 int flags = level.getInt();
465 int sigAlgorithm = level.getInt();
466 byte[] signature = readLengthPrefixedByteArray(level);
467
468 if (lastCert != null) {
469 // Use previous level cert to verify current level
470 Pair<String, ? extends AlgorithmParameterSpec> sigAlgParams =
471 getSignatureAlgorithmJcaSignatureAlgorithm(lastSigAlgorithm);
472 PublicKey publicKey = lastCert.getPublicKey();
473 Signature sig = Signature.getInstance(sigAlgParams.first);
474 sig.initVerify(publicKey);
475 if (sigAlgParams.second != null) {
476 sig.setParameter(sigAlgParams.second);
477 }
478 sig.update(signedData);
479 if (!sig.verify(signature)) {
480 throw new SecurityException("Unable to verify signature of certificate #"
481 + levelCount + " using " + sigAlgParams.first + " when verifying"
482 + " Proof-of-rotation record");
483 }
484 }
485
Dan Cashman6dbf8372018-01-26 05:37:54 -0800486 signedData.rewind();
Daniel Cashman67096e02017-12-28 12:46:33 -0800487 byte[] encodedCert = readLengthPrefixedByteArray(signedData);
488 int signedSigAlgorithm = signedData.getInt();
489 if (lastCert != null && lastSigAlgorithm != signedSigAlgorithm) {
490 throw new SecurityException("Signing algorithm ID mismatch for certificate #"
491 + levelCount + " when verifying Proof-of-rotation record");
492 }
493 lastCert = (X509Certificate)
494 certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
495 lastCert = new VerbatimX509Certificate(lastCert, encodedCert);
496
497 lastSigAlgorithm = sigAlgorithm;
498 certs.add(lastCert);
499 flagsList.add(flags);
Daniel Cashman67096e02017-12-28 12:46:33 -0800500 }
Dan Cashmana656b8b2018-01-26 13:53:59 -0800501 } catch (IOException | BufferUnderflowException e) {
502 throw new IOException("Failed to parse Proof-of-rotation record", e);
503 } catch (NoSuchAlgorithmException | InvalidKeyException
504 | InvalidAlgorithmParameterException | SignatureException e) {
505 throw new SecurityException(
506 "Failed to verify signature over signed data for certificate #"
507 + levelCount + " when verifying Proof-of-rotation record", e);
508 } catch (CertificateException e) {
509 throw new SecurityException("Failed to decode certificate #" + levelCount
510 + " when verifying Proof-of-rotation record", e);
Daniel Cashman67096e02017-12-28 12:46:33 -0800511 }
512 return new VerifiedProofOfRotation(certs, flagsList);
513 }
514
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800515 static byte[] getVerityRootHash(String apkPath)
516 throws IOException, SignatureNotFoundException, SecurityException {
517 try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
518 SignatureInfo signatureInfo = findSignature(apk);
519 VerifiedSigner vSigner = verify(apk, false);
520 return vSigner.verityRootHash;
521 }
522 }
523
524 static byte[] generateApkVerity(String apkPath, ByteBufferFactory bufferFactory)
525 throws IOException, SignatureNotFoundException, SecurityException, DigestException,
526 NoSuchAlgorithmException {
527 try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
528 SignatureInfo signatureInfo = findSignature(apk);
529 return ApkSigningBlockUtils.generateApkVerity(apkPath, bufferFactory, signatureInfo);
530 }
531 }
532
Victor Hsieh5f761242018-01-20 10:30:12 -0800533 static byte[] generateFsverityRootHash(String apkPath)
534 throws NoSuchAlgorithmException, DigestException, IOException,
535 SignatureNotFoundException {
536 try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
537 SignatureInfo signatureInfo = findSignature(apk);
538 VerifiedSigner vSigner = verify(apk, false);
539 if (vSigner.verityRootHash == null) {
540 return null;
541 }
542 return ApkVerityBuilder.generateFsverityRootHash(
543 apk, ByteBuffer.wrap(vSigner.verityRootHash), signatureInfo);
544 }
545 }
546
Daniel Cashman67096e02017-12-28 12:46:33 -0800547 private static boolean isSupportedSignatureAlgorithm(int sigAlgorithm) {
548 switch (sigAlgorithm) {
549 case SIGNATURE_RSA_PSS_WITH_SHA256:
550 case SIGNATURE_RSA_PSS_WITH_SHA512:
551 case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256:
552 case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512:
553 case SIGNATURE_ECDSA_WITH_SHA256:
554 case SIGNATURE_ECDSA_WITH_SHA512:
555 case SIGNATURE_DSA_WITH_SHA256:
Victor Hsieh4acad4c2018-01-04 13:36:15 -0800556 case SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256:
557 case SIGNATURE_VERITY_ECDSA_WITH_SHA256:
558 case SIGNATURE_VERITY_DSA_WITH_SHA256:
Daniel Cashman67096e02017-12-28 12:46:33 -0800559 return true;
560 default:
561 return false;
562 }
563 }
564
565 /**
566 * Verified processed proof of rotation.
567 *
568 * @hide for internal use only.
569 */
570 public static class VerifiedProofOfRotation {
571 public final List<X509Certificate> certs;
572 public final List<Integer> flagsList;
573
574 public VerifiedProofOfRotation(List<X509Certificate> certs, List<Integer> flagsList) {
575 this.certs = certs;
576 this.flagsList = flagsList;
577 }
578 }
579
580 /**
581 * Verified APK Signature Scheme v3 signer, including the proof of rotation structure.
582 *
583 * @hide for internal use only.
584 */
585 public static class VerifiedSigner {
586 public final X509Certificate[] certs;
587 public final VerifiedProofOfRotation por;
588
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800589 public byte[] verityRootHash;
590
Daniel Cashman67096e02017-12-28 12:46:33 -0800591 public VerifiedSigner(X509Certificate[] certs, VerifiedProofOfRotation por) {
592 this.certs = certs;
593 this.por = por;
594 }
595
596 }
597
598 private static class PlatformNotSupportedException extends Exception {
599
600 PlatformNotSupportedException(String s) {
601 super(s);
602 }
603 }
604}