blob: 79eb9f6e749c396198ca8d6978f6be19b86d76bf [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
Alex Buynytskyyf5e605a2020-03-13 13:31:12 -070019import static android.util.apk.ApkSigningBlockUtils.CONTENT_DIGEST_CHUNKED_SHA256;
20import static android.util.apk.ApkSigningBlockUtils.CONTENT_DIGEST_CHUNKED_SHA512;
Victor Hsieh07bc80c2018-01-11 16:15:47 -080021import static android.util.apk.ApkSigningBlockUtils.CONTENT_DIGEST_VERITY_CHUNKED_SHA256;
Daniel Cashman67096e02017-12-28 12:46:33 -080022import static android.util.apk.ApkSigningBlockUtils.compareSignatureAlgorithm;
23import static android.util.apk.ApkSigningBlockUtils.getContentDigestAlgorithmJcaDigestAlgorithm;
24import static android.util.apk.ApkSigningBlockUtils.getLengthPrefixedSlice;
25import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmContentDigestAlgorithm;
26import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmJcaKeyAlgorithm;
27import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmJcaSignatureAlgorithm;
Khaled Abdelmohsenf10fc7a2020-03-02 19:02:28 +000028import static android.util.apk.ApkSigningBlockUtils.isSupportedSignatureAlgorithm;
Daniel Cashman67096e02017-12-28 12:46:33 -080029import static android.util.apk.ApkSigningBlockUtils.readLengthPrefixedByteArray;
30
31import android.os.Build;
32import android.util.ArrayMap;
33import android.util.Pair;
34
35import java.io.ByteArrayInputStream;
Daniel Cashman67096e02017-12-28 12:46:33 -080036import java.io.IOException;
37import java.io.RandomAccessFile;
38import java.nio.BufferUnderflowException;
39import java.nio.ByteBuffer;
Victor Hsieh07bc80c2018-01-11 16:15:47 -080040import java.security.DigestException;
Daniel Cashman67096e02017-12-28 12:46:33 -080041import java.security.InvalidAlgorithmParameterException;
42import java.security.InvalidKeyException;
43import java.security.KeyFactory;
44import java.security.MessageDigest;
45import java.security.NoSuchAlgorithmException;
46import java.security.PublicKey;
47import java.security.Signature;
48import java.security.SignatureException;
Dan Cashmancd4cb812018-01-02 14:55:58 -080049import java.security.cert.CertificateEncodingException;
Daniel Cashman67096e02017-12-28 12:46:33 -080050import java.security.cert.CertificateException;
51import java.security.cert.CertificateFactory;
52import java.security.cert.X509Certificate;
53import java.security.spec.AlgorithmParameterSpec;
54import java.security.spec.InvalidKeySpecException;
55import java.security.spec.X509EncodedKeySpec;
56import java.util.ArrayList;
57import java.util.Arrays;
Daniel Cashmanef054082018-03-28 15:58:14 -070058import java.util.HashSet;
Daniel Cashman67096e02017-12-28 12:46:33 -080059import java.util.List;
60import java.util.Map;
61
62/**
63 * APK Signature Scheme v3 verifier.
64 *
65 * @hide for internal use only.
66 */
67public class ApkSignatureSchemeV3Verifier {
68
69 /**
70 * ID of this signature scheme as used in X-Android-APK-Signed header used in JAR signing.
71 */
72 public static final int SF_ATTRIBUTE_ANDROID_APK_SIGNED_ID = 3;
73
74 private static final int APK_SIGNATURE_SCHEME_V3_BLOCK_ID = 0xf05368c0;
75
76 /**
77 * Returns {@code true} if the provided APK contains an APK Signature Scheme V3 signature.
78 *
79 * <p><b>NOTE: This method does not verify the signature.</b>
80 */
81 public static boolean hasSignature(String apkFile) throws IOException {
82 try (RandomAccessFile apk = new RandomAccessFile(apkFile, "r")) {
83 findSignature(apk);
84 return true;
85 } catch (SignatureNotFoundException e) {
86 return false;
87 }
88 }
89
90 /**
91 * Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
92 * associated with each signer.
93 *
94 * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v3.
95 * @throws SecurityException if the APK Signature Scheme v3 signature of this APK does not
96 * verify.
97 * @throws IOException if an I/O error occurs while reading the APK file.
98 */
99 public static VerifiedSigner verify(String apkFile)
100 throws SignatureNotFoundException, SecurityException, IOException {
101 return verify(apkFile, true);
102 }
103
104 /**
105 * Returns the certificates associated with each signer for the given APK without verification.
106 * This method is dangerous and should not be used, unless the caller is absolutely certain the
107 * APK is trusted. Specifically, verification is only done for the APK Signature Scheme v3
108 * Block while gathering signer information. The APK contents are not verified.
109 *
110 * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v3.
111 * @throws IOException if an I/O error occurs while reading the APK file.
112 */
Gavin Corkeryed521ab2019-01-31 16:59:41 +0000113 public static VerifiedSigner unsafeGetCertsWithoutVerification(String apkFile)
Daniel Cashman67096e02017-12-28 12:46:33 -0800114 throws SignatureNotFoundException, SecurityException, IOException {
115 return verify(apkFile, false);
116 }
117
118 private static VerifiedSigner verify(String apkFile, boolean verifyIntegrity)
119 throws SignatureNotFoundException, SecurityException, IOException {
120 try (RandomAccessFile apk = new RandomAccessFile(apkFile, "r")) {
121 return verify(apk, verifyIntegrity);
122 }
123 }
124
125 /**
126 * Verifies APK Signature Scheme v3 signatures of the provided APK and returns the certificates
127 * associated with each signer.
128 *
129 * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v3.
130 * @throws SecurityException if an APK Signature Scheme v3 signature of this APK does not
131 * verify.
132 * @throws IOException if an I/O error occurs while reading the APK file.
133 */
134 private static VerifiedSigner verify(RandomAccessFile apk, boolean verifyIntegrity)
135 throws SignatureNotFoundException, SecurityException, IOException {
136 SignatureInfo signatureInfo = findSignature(apk);
Victor Hsieh4acad4c2018-01-04 13:36:15 -0800137 return verify(apk, signatureInfo, verifyIntegrity);
Daniel Cashman67096e02017-12-28 12:46:33 -0800138 }
139
140 /**
141 * Returns the APK Signature Scheme v3 block contained in the provided APK file and the
142 * additional information relevant for verifying the block against the file.
143 *
144 * @throws SignatureNotFoundException if the APK is not signed using APK Signature Scheme v3.
145 * @throws IOException if an I/O error occurs while reading the APK file.
146 */
147 private static SignatureInfo findSignature(RandomAccessFile apk)
148 throws IOException, SignatureNotFoundException {
149 return ApkSigningBlockUtils.findSignature(apk, APK_SIGNATURE_SCHEME_V3_BLOCK_ID);
150 }
151
152 /**
153 * Verifies the contents of the provided APK file against the provided APK Signature Scheme v3
154 * Block.
155 *
156 * @param signatureInfo APK Signature Scheme v3 Block and information relevant for verifying it
157 * against the APK file.
158 */
159 private static VerifiedSigner verify(
Victor Hsieh4acad4c2018-01-04 13:36:15 -0800160 RandomAccessFile apk,
Daniel Cashman67096e02017-12-28 12:46:33 -0800161 SignatureInfo signatureInfo,
Victor Hsieh4ba1eea2018-03-02 14:26:19 -0800162 boolean doVerifyIntegrity) throws SecurityException, IOException {
Daniel Cashman67096e02017-12-28 12:46:33 -0800163 int signerCount = 0;
164 Map<Integer, byte[]> contentDigests = new ArrayMap<>();
165 VerifiedSigner result = null;
166 CertificateFactory certFactory;
167 try {
168 certFactory = CertificateFactory.getInstance("X.509");
169 } catch (CertificateException e) {
170 throw new RuntimeException("Failed to obtain X.509 CertificateFactory", e);
171 }
172 ByteBuffer signers;
173 try {
174 signers = getLengthPrefixedSlice(signatureInfo.signatureBlock);
175 } catch (IOException e) {
176 throw new SecurityException("Failed to read list of signers", e);
177 }
178 while (signers.hasRemaining()) {
179 try {
180 ByteBuffer signer = getLengthPrefixedSlice(signers);
181 result = verifySigner(signer, contentDigests, certFactory);
182 signerCount++;
183 } catch (PlatformNotSupportedException e) {
184 // this signer is for a different platform, ignore it.
185 continue;
186 } catch (IOException | BufferUnderflowException | SecurityException e) {
187 throw new SecurityException(
188 "Failed to parse/verify signer #" + signerCount + " block",
189 e);
190 }
191 }
192
193 if (signerCount < 1 || result == null) {
194 throw new SecurityException("No signers found");
195 }
196
197 if (signerCount != 1) {
198 throw new SecurityException("APK Signature Scheme V3 only supports one signer: "
199 + "multiple signers found.");
200 }
201
202 if (contentDigests.isEmpty()) {
203 throw new SecurityException("No content digests found");
204 }
205
206 if (doVerifyIntegrity) {
Victor Hsieh4acad4c2018-01-04 13:36:15 -0800207 ApkSigningBlockUtils.verifyIntegrity(contentDigests, apk, signatureInfo);
Daniel Cashman67096e02017-12-28 12:46:33 -0800208 }
209
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800210 if (contentDigests.containsKey(CONTENT_DIGEST_VERITY_CHUNKED_SHA256)) {
Victor Hsieh4ba1eea2018-03-02 14:26:19 -0800211 byte[] verityDigest = contentDigests.get(CONTENT_DIGEST_VERITY_CHUNKED_SHA256);
212 result.verityRootHash = ApkSigningBlockUtils.parseVerityDigestAndVerifySourceLength(
213 verityDigest, apk.length(), signatureInfo);
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800214 }
215
Alex Buynytskyyf5e605a2020-03-13 13:31:12 -0700216 if (contentDigests.containsKey(CONTENT_DIGEST_CHUNKED_SHA512)) {
217 result.digest = contentDigests.get(CONTENT_DIGEST_CHUNKED_SHA512);
218 } else if (contentDigests.containsKey(CONTENT_DIGEST_CHUNKED_SHA256)) {
219 result.digest = contentDigests.get(CONTENT_DIGEST_CHUNKED_SHA256);
220 }
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();
Daniel Cashmanef054082018-03-28 15:58:14 -0700460 HashSet<X509Certificate> certHistorySet = new HashSet<>();
Dan Cashmana656b8b2018-01-26 13:53:59 -0800461 while (porBuf.hasRemaining()) {
462 levelCount++;
Daniel Cashman67096e02017-12-28 12:46:33 -0800463 ByteBuffer level = getLengthPrefixedSlice(porBuf);
464 ByteBuffer signedData = getLengthPrefixedSlice(level);
465 int flags = level.getInt();
466 int sigAlgorithm = level.getInt();
467 byte[] signature = readLengthPrefixedByteArray(level);
468
469 if (lastCert != null) {
470 // Use previous level cert to verify current level
471 Pair<String, ? extends AlgorithmParameterSpec> sigAlgParams =
472 getSignatureAlgorithmJcaSignatureAlgorithm(lastSigAlgorithm);
473 PublicKey publicKey = lastCert.getPublicKey();
474 Signature sig = Signature.getInstance(sigAlgParams.first);
475 sig.initVerify(publicKey);
476 if (sigAlgParams.second != null) {
477 sig.setParameter(sigAlgParams.second);
478 }
479 sig.update(signedData);
480 if (!sig.verify(signature)) {
481 throw new SecurityException("Unable to verify signature of certificate #"
482 + levelCount + " using " + sigAlgParams.first + " when verifying"
483 + " Proof-of-rotation record");
484 }
485 }
486
Dan Cashman6dbf8372018-01-26 05:37:54 -0800487 signedData.rewind();
Daniel Cashman67096e02017-12-28 12:46:33 -0800488 byte[] encodedCert = readLengthPrefixedByteArray(signedData);
489 int signedSigAlgorithm = signedData.getInt();
490 if (lastCert != null && lastSigAlgorithm != signedSigAlgorithm) {
491 throw new SecurityException("Signing algorithm ID mismatch for certificate #"
492 + levelCount + " when verifying Proof-of-rotation record");
493 }
494 lastCert = (X509Certificate)
495 certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
496 lastCert = new VerbatimX509Certificate(lastCert, encodedCert);
497
498 lastSigAlgorithm = sigAlgorithm;
Daniel Cashmanef054082018-03-28 15:58:14 -0700499 if (certHistorySet.contains(lastCert)) {
500 throw new SecurityException("Encountered duplicate entries in "
501 + "Proof-of-rotation record at certificate #" + levelCount + ". All "
502 + "signing certificates should be unique");
503 }
504 certHistorySet.add(lastCert);
Daniel Cashman67096e02017-12-28 12:46:33 -0800505 certs.add(lastCert);
506 flagsList.add(flags);
Daniel Cashman67096e02017-12-28 12:46:33 -0800507 }
Dan Cashmana656b8b2018-01-26 13:53:59 -0800508 } catch (IOException | BufferUnderflowException e) {
509 throw new IOException("Failed to parse Proof-of-rotation record", e);
510 } catch (NoSuchAlgorithmException | InvalidKeyException
511 | InvalidAlgorithmParameterException | SignatureException e) {
512 throw new SecurityException(
513 "Failed to verify signature over signed data for certificate #"
514 + levelCount + " when verifying Proof-of-rotation record", e);
515 } catch (CertificateException e) {
516 throw new SecurityException("Failed to decode certificate #" + levelCount
517 + " when verifying Proof-of-rotation record", e);
Daniel Cashman67096e02017-12-28 12:46:33 -0800518 }
519 return new VerifiedProofOfRotation(certs, flagsList);
520 }
521
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800522 static byte[] getVerityRootHash(String apkPath)
523 throws IOException, SignatureNotFoundException, SecurityException {
524 try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
525 SignatureInfo signatureInfo = findSignature(apk);
526 VerifiedSigner vSigner = verify(apk, false);
527 return vSigner.verityRootHash;
528 }
529 }
530
531 static byte[] generateApkVerity(String apkPath, ByteBufferFactory bufferFactory)
532 throws IOException, SignatureNotFoundException, SecurityException, DigestException,
533 NoSuchAlgorithmException {
534 try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
535 SignatureInfo signatureInfo = findSignature(apk);
Victor Hsieh27300922018-09-28 09:31:44 -0700536 return VerityBuilder.generateApkVerity(apkPath, bufferFactory, signatureInfo);
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800537 }
538 }
539
Victor Hsieh25195132018-09-06 16:32:06 -0700540 static byte[] generateApkVerityRootHash(String apkPath)
Victor Hsieh5f761242018-01-20 10:30:12 -0800541 throws NoSuchAlgorithmException, DigestException, IOException,
542 SignatureNotFoundException {
543 try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) {
544 SignatureInfo signatureInfo = findSignature(apk);
545 VerifiedSigner vSigner = verify(apk, false);
546 if (vSigner.verityRootHash == null) {
547 return null;
548 }
Victor Hsieh27300922018-09-28 09:31:44 -0700549 return VerityBuilder.generateApkVerityRootHash(
Victor Hsieh5f761242018-01-20 10:30:12 -0800550 apk, ByteBuffer.wrap(vSigner.verityRootHash), signatureInfo);
551 }
552 }
553
Daniel Cashman67096e02017-12-28 12:46:33 -0800554 /**
555 * Verified processed proof of rotation.
556 *
557 * @hide for internal use only.
558 */
559 public static class VerifiedProofOfRotation {
560 public final List<X509Certificate> certs;
561 public final List<Integer> flagsList;
562
563 public VerifiedProofOfRotation(List<X509Certificate> certs, List<Integer> flagsList) {
564 this.certs = certs;
565 this.flagsList = flagsList;
566 }
567 }
568
569 /**
570 * Verified APK Signature Scheme v3 signer, including the proof of rotation structure.
571 *
572 * @hide for internal use only.
573 */
574 public static class VerifiedSigner {
575 public final X509Certificate[] certs;
576 public final VerifiedProofOfRotation por;
577
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800578 public byte[] verityRootHash;
Alex Buynytskyyf5e605a2020-03-13 13:31:12 -0700579 public byte[] digest;
Victor Hsieh07bc80c2018-01-11 16:15:47 -0800580
Daniel Cashman67096e02017-12-28 12:46:33 -0800581 public VerifiedSigner(X509Certificate[] certs, VerifiedProofOfRotation por) {
582 this.certs = certs;
583 this.por = por;
584 }
585
586 }
587
588 private static class PlatformNotSupportedException extends Exception {
589
590 PlatformNotSupportedException(String s) {
591 super(s);
592 }
593 }
594}