Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | package android.util.apk; |
| 18 | |
Victor Hsieh | 07bc80c | 2018-01-11 16:15:47 -0800 | [diff] [blame] | 19 | import static android.util.apk.ApkSigningBlockUtils.CONTENT_DIGEST_VERITY_CHUNKED_SHA256; |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 20 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_DSA_WITH_SHA256; |
| 21 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_ECDSA_WITH_SHA256; |
| 22 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_ECDSA_WITH_SHA512; |
| 23 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256; |
| 24 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512; |
| 25 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_RSA_PSS_WITH_SHA256; |
| 26 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_RSA_PSS_WITH_SHA512; |
Victor Hsieh | 4acad4c | 2018-01-04 13:36:15 -0800 | [diff] [blame] | 27 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_VERITY_DSA_WITH_SHA256; |
| 28 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_VERITY_ECDSA_WITH_SHA256; |
| 29 | import static android.util.apk.ApkSigningBlockUtils.SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256; |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 30 | import static android.util.apk.ApkSigningBlockUtils.compareSignatureAlgorithm; |
| 31 | import static android.util.apk.ApkSigningBlockUtils.getContentDigestAlgorithmJcaDigestAlgorithm; |
| 32 | import static android.util.apk.ApkSigningBlockUtils.getLengthPrefixedSlice; |
| 33 | import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmContentDigestAlgorithm; |
| 34 | import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmJcaKeyAlgorithm; |
| 35 | import static android.util.apk.ApkSigningBlockUtils.getSignatureAlgorithmJcaSignatureAlgorithm; |
| 36 | import static android.util.apk.ApkSigningBlockUtils.readLengthPrefixedByteArray; |
| 37 | |
| 38 | import android.os.Build; |
| 39 | import android.util.ArrayMap; |
| 40 | import android.util.Pair; |
| 41 | |
| 42 | import java.io.ByteArrayInputStream; |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 43 | import java.io.IOException; |
| 44 | import java.io.RandomAccessFile; |
| 45 | import java.nio.BufferUnderflowException; |
| 46 | import java.nio.ByteBuffer; |
Victor Hsieh | 07bc80c | 2018-01-11 16:15:47 -0800 | [diff] [blame] | 47 | import java.security.DigestException; |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 48 | import java.security.InvalidAlgorithmParameterException; |
| 49 | import java.security.InvalidKeyException; |
| 50 | import java.security.KeyFactory; |
| 51 | import java.security.MessageDigest; |
| 52 | import java.security.NoSuchAlgorithmException; |
| 53 | import java.security.PublicKey; |
| 54 | import java.security.Signature; |
| 55 | import java.security.SignatureException; |
Dan Cashman | cd4cb81 | 2018-01-02 14:55:58 -0800 | [diff] [blame] | 56 | import java.security.cert.CertificateEncodingException; |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 57 | import java.security.cert.CertificateException; |
| 58 | import java.security.cert.CertificateFactory; |
| 59 | import java.security.cert.X509Certificate; |
| 60 | import java.security.spec.AlgorithmParameterSpec; |
| 61 | import java.security.spec.InvalidKeySpecException; |
| 62 | import java.security.spec.X509EncodedKeySpec; |
| 63 | import java.util.ArrayList; |
| 64 | import java.util.Arrays; |
| 65 | import java.util.List; |
| 66 | import java.util.Map; |
| 67 | |
| 68 | /** |
| 69 | * APK Signature Scheme v3 verifier. |
| 70 | * |
| 71 | * @hide for internal use only. |
| 72 | */ |
| 73 | public 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 Hsieh | 4acad4c | 2018-01-04 13:36:15 -0800 | [diff] [blame] | 143 | return verify(apk, signatureInfo, verifyIntegrity); |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 144 | } |
| 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 Hsieh | 4acad4c | 2018-01-04 13:36:15 -0800 | [diff] [blame] | 166 | RandomAccessFile apk, |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 167 | SignatureInfo signatureInfo, |
| 168 | boolean doVerifyIntegrity) throws SecurityException { |
| 169 | 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 Hsieh | 4acad4c | 2018-01-04 13:36:15 -0800 | [diff] [blame] | 213 | ApkSigningBlockUtils.verifyIntegrity(contentDigests, apk, signatureInfo); |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 214 | } |
| 215 | |
Victor Hsieh | 07bc80c | 2018-01-11 16:15:47 -0800 | [diff] [blame] | 216 | if (contentDigests.containsKey(CONTENT_DIGEST_VERITY_CHUNKED_SHA256)) { |
| 217 | result.verityRootHash = contentDigests.get(CONTENT_DIGEST_VERITY_CHUNKED_SHA256); |
| 218 | } |
| 219 | |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 220 | return result; |
| 221 | } |
| 222 | |
| 223 | private static VerifiedSigner verifySigner( |
| 224 | ByteBuffer signerBlock, |
| 225 | Map<Integer, byte[]> contentDigests, |
| 226 | CertificateFactory certFactory) |
| 227 | throws SecurityException, IOException, PlatformNotSupportedException { |
| 228 | ByteBuffer signedData = getLengthPrefixedSlice(signerBlock); |
| 229 | int minSdkVersion = signerBlock.getInt(); |
| 230 | int maxSdkVersion = signerBlock.getInt(); |
| 231 | |
| 232 | if (Build.VERSION.SDK_INT < minSdkVersion || Build.VERSION.SDK_INT > maxSdkVersion) { |
| 233 | // this signature isn't meant to be used with this platform, skip it. |
| 234 | throw new PlatformNotSupportedException( |
| 235 | "Signer not supported by this platform " |
| 236 | + "version. This platform: " + Build.VERSION.SDK_INT |
| 237 | + ", signer minSdkVersion: " + minSdkVersion |
| 238 | + ", maxSdkVersion: " + maxSdkVersion); |
| 239 | } |
| 240 | |
| 241 | ByteBuffer signatures = getLengthPrefixedSlice(signerBlock); |
| 242 | byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock); |
| 243 | |
| 244 | int signatureCount = 0; |
| 245 | int bestSigAlgorithm = -1; |
| 246 | byte[] bestSigAlgorithmSignatureBytes = null; |
| 247 | List<Integer> signaturesSigAlgorithms = new ArrayList<>(); |
| 248 | while (signatures.hasRemaining()) { |
| 249 | signatureCount++; |
| 250 | try { |
| 251 | ByteBuffer signature = getLengthPrefixedSlice(signatures); |
| 252 | if (signature.remaining() < 8) { |
| 253 | throw new SecurityException("Signature record too short"); |
| 254 | } |
| 255 | int sigAlgorithm = signature.getInt(); |
| 256 | signaturesSigAlgorithms.add(sigAlgorithm); |
| 257 | if (!isSupportedSignatureAlgorithm(sigAlgorithm)) { |
| 258 | continue; |
| 259 | } |
| 260 | if ((bestSigAlgorithm == -1) |
| 261 | || (compareSignatureAlgorithm(sigAlgorithm, bestSigAlgorithm) > 0)) { |
| 262 | bestSigAlgorithm = sigAlgorithm; |
| 263 | bestSigAlgorithmSignatureBytes = readLengthPrefixedByteArray(signature); |
| 264 | } |
| 265 | } catch (IOException | BufferUnderflowException e) { |
| 266 | throw new SecurityException( |
| 267 | "Failed to parse signature record #" + signatureCount, |
| 268 | e); |
| 269 | } |
| 270 | } |
| 271 | if (bestSigAlgorithm == -1) { |
| 272 | if (signatureCount == 0) { |
| 273 | throw new SecurityException("No signatures found"); |
| 274 | } else { |
| 275 | throw new SecurityException("No supported signatures found"); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(bestSigAlgorithm); |
| 280 | Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams = |
| 281 | getSignatureAlgorithmJcaSignatureAlgorithm(bestSigAlgorithm); |
| 282 | String jcaSignatureAlgorithm = signatureAlgorithmParams.first; |
| 283 | AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second; |
| 284 | boolean sigVerified; |
| 285 | try { |
| 286 | PublicKey publicKey = |
| 287 | KeyFactory.getInstance(keyAlgorithm) |
| 288 | .generatePublic(new X509EncodedKeySpec(publicKeyBytes)); |
| 289 | Signature sig = Signature.getInstance(jcaSignatureAlgorithm); |
| 290 | sig.initVerify(publicKey); |
| 291 | if (jcaSignatureAlgorithmParams != null) { |
| 292 | sig.setParameter(jcaSignatureAlgorithmParams); |
| 293 | } |
| 294 | sig.update(signedData); |
| 295 | sigVerified = sig.verify(bestSigAlgorithmSignatureBytes); |
| 296 | } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException |
| 297 | | InvalidAlgorithmParameterException | SignatureException e) { |
| 298 | throw new SecurityException( |
| 299 | "Failed to verify " + jcaSignatureAlgorithm + " signature", e); |
| 300 | } |
| 301 | if (!sigVerified) { |
| 302 | throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify"); |
| 303 | } |
| 304 | |
| 305 | // Signature over signedData has verified. |
| 306 | |
| 307 | byte[] contentDigest = null; |
| 308 | signedData.clear(); |
| 309 | ByteBuffer digests = getLengthPrefixedSlice(signedData); |
| 310 | List<Integer> digestsSigAlgorithms = new ArrayList<>(); |
| 311 | int digestCount = 0; |
| 312 | while (digests.hasRemaining()) { |
| 313 | digestCount++; |
| 314 | try { |
| 315 | ByteBuffer digest = getLengthPrefixedSlice(digests); |
| 316 | if (digest.remaining() < 8) { |
| 317 | throw new IOException("Record too short"); |
| 318 | } |
| 319 | int sigAlgorithm = digest.getInt(); |
| 320 | digestsSigAlgorithms.add(sigAlgorithm); |
| 321 | if (sigAlgorithm == bestSigAlgorithm) { |
| 322 | contentDigest = readLengthPrefixedByteArray(digest); |
| 323 | } |
| 324 | } catch (IOException | BufferUnderflowException e) { |
| 325 | throw new IOException("Failed to parse digest record #" + digestCount, e); |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | if (!signaturesSigAlgorithms.equals(digestsSigAlgorithms)) { |
| 330 | throw new SecurityException( |
| 331 | "Signature algorithms don't match between digests and signatures records"); |
| 332 | } |
| 333 | int digestAlgorithm = getSignatureAlgorithmContentDigestAlgorithm(bestSigAlgorithm); |
| 334 | byte[] previousSignerDigest = contentDigests.put(digestAlgorithm, contentDigest); |
| 335 | if ((previousSignerDigest != null) |
| 336 | && (!MessageDigest.isEqual(previousSignerDigest, contentDigest))) { |
| 337 | throw new SecurityException( |
| 338 | getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm) |
| 339 | + " contents digest does not match the digest specified by a preceding signer"); |
| 340 | } |
| 341 | |
| 342 | ByteBuffer certificates = getLengthPrefixedSlice(signedData); |
| 343 | List<X509Certificate> certs = new ArrayList<>(); |
| 344 | int certificateCount = 0; |
| 345 | while (certificates.hasRemaining()) { |
| 346 | certificateCount++; |
| 347 | byte[] encodedCert = readLengthPrefixedByteArray(certificates); |
| 348 | X509Certificate certificate; |
| 349 | try { |
| 350 | certificate = (X509Certificate) |
| 351 | certFactory.generateCertificate(new ByteArrayInputStream(encodedCert)); |
| 352 | } catch (CertificateException e) { |
| 353 | throw new SecurityException("Failed to decode certificate #" + certificateCount, e); |
| 354 | } |
| 355 | certificate = new VerbatimX509Certificate( |
| 356 | certificate, encodedCert); |
| 357 | certs.add(certificate); |
| 358 | } |
| 359 | |
| 360 | if (certs.isEmpty()) { |
| 361 | throw new SecurityException("No certificates listed"); |
| 362 | } |
| 363 | X509Certificate mainCertificate = certs.get(0); |
| 364 | byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded(); |
| 365 | if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) { |
| 366 | throw new SecurityException( |
| 367 | "Public key mismatch between certificate and signature record"); |
| 368 | } |
| 369 | |
| 370 | int signedMinSDK = signedData.getInt(); |
| 371 | if (signedMinSDK != minSdkVersion) { |
| 372 | throw new SecurityException( |
| 373 | "minSdkVersion mismatch between signed and unsigned in v3 signer block."); |
| 374 | } |
| 375 | |
| 376 | int signedMaxSDK = signedData.getInt(); |
| 377 | if (signedMaxSDK != maxSdkVersion) { |
| 378 | throw new SecurityException( |
| 379 | "maxSdkVersion mismatch between signed and unsigned in v3 signer block."); |
| 380 | } |
| 381 | |
| 382 | ByteBuffer additionalAttrs = getLengthPrefixedSlice(signedData); |
| 383 | return verifyAdditionalAttributes(additionalAttrs, certs, certFactory); |
| 384 | } |
| 385 | |
| 386 | private static final int PROOF_OF_ROTATION_ATTR_ID = 0x3ba06f8c; |
| 387 | |
| 388 | private static VerifiedSigner verifyAdditionalAttributes(ByteBuffer attrs, |
| 389 | List<X509Certificate> certs, CertificateFactory certFactory) throws IOException { |
| 390 | X509Certificate[] certChain = certs.toArray(new X509Certificate[certs.size()]); |
| 391 | VerifiedProofOfRotation por = null; |
| 392 | |
| 393 | while (attrs.hasRemaining()) { |
| 394 | ByteBuffer attr = getLengthPrefixedSlice(attrs); |
| 395 | if (attr.remaining() < 4) { |
| 396 | throw new IOException("Remaining buffer too short to contain additional attribute " |
| 397 | + "ID. Remaining: " + attr.remaining()); |
| 398 | } |
| 399 | int id = attr.getInt(); |
| 400 | switch(id) { |
| 401 | case PROOF_OF_ROTATION_ATTR_ID: |
| 402 | if (por != null) { |
| 403 | throw new SecurityException("Encountered multiple Proof-of-rotation records" |
Dan Cashman | cd4cb81 | 2018-01-02 14:55:58 -0800 | [diff] [blame] | 404 | + " when verifying APK Signature Scheme v3 signature"); |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 405 | } |
| 406 | por = verifyProofOfRotationStruct(attr, certFactory); |
Dan Cashman | cd4cb81 | 2018-01-02 14:55:58 -0800 | [diff] [blame] | 407 | // make sure that the last certificate in the Proof-of-rotation record matches |
| 408 | // the one used to sign this APK. |
| 409 | try { |
| 410 | if (por.certs.size() > 0 |
| 411 | && !Arrays.equals(por.certs.get(por.certs.size() - 1).getEncoded(), |
| 412 | certChain[0].getEncoded())) { |
| 413 | throw new SecurityException("Terminal certificate in Proof-of-rotation" |
| 414 | + " record does not match APK signing certificate"); |
| 415 | } |
| 416 | } catch (CertificateEncodingException e) { |
| 417 | throw new SecurityException("Failed to encode certificate when comparing" |
| 418 | + " Proof-of-rotation record and signing certificate", e); |
| 419 | } |
| 420 | |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 421 | break; |
| 422 | default: |
| 423 | // not the droid we're looking for, move along, move along. |
| 424 | break; |
| 425 | } |
| 426 | } |
| 427 | return new VerifiedSigner(certChain, por); |
| 428 | } |
| 429 | |
| 430 | private static VerifiedProofOfRotation verifyProofOfRotationStruct( |
| 431 | ByteBuffer porBuf, |
| 432 | CertificateFactory certFactory) |
| 433 | throws SecurityException, IOException { |
| 434 | int levelCount = 0; |
| 435 | int lastSigAlgorithm = -1; |
| 436 | X509Certificate lastCert = null; |
| 437 | List<X509Certificate> certs = new ArrayList<>(); |
| 438 | List<Integer> flagsList = new ArrayList<>(); |
| 439 | |
| 440 | // Proof-of-rotation struct: |
Dan Cashman | a656b8b | 2018-01-26 13:53:59 -0800 | [diff] [blame^] | 441 | // A uint32 version code followed by basically a singly linked list of nodes, called levels |
| 442 | // here, each of which have the following structure: |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 443 | // * length-prefix for the entire level |
| 444 | // - length-prefixed signed data (if previous level exists) |
| 445 | // * length-prefixed X509 Certificate |
| 446 | // * uint32 signature algorithm ID describing how this signed data was signed |
| 447 | // - uint32 flags describing how to treat the cert contained in this level |
| 448 | // - uint32 signature algorithm ID to use to verify the signature of the next level. The |
| 449 | // algorithm here must match the one in the signed data section of the next level. |
| 450 | // - length-prefixed signature over the signed data in this level. The signature here |
| 451 | // is verified using the certificate from the previous level. |
| 452 | // The linking is provided by the certificate of each level signing the one of the next. |
Dan Cashman | a656b8b | 2018-01-26 13:53:59 -0800 | [diff] [blame^] | 453 | |
| 454 | try { |
| 455 | |
| 456 | // get the version code, but don't do anything with it: creator knew about all our flags |
| 457 | porBuf.getInt(); |
| 458 | while (porBuf.hasRemaining()) { |
| 459 | levelCount++; |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 460 | ByteBuffer level = getLengthPrefixedSlice(porBuf); |
| 461 | ByteBuffer signedData = getLengthPrefixedSlice(level); |
| 462 | int flags = level.getInt(); |
| 463 | int sigAlgorithm = level.getInt(); |
| 464 | byte[] signature = readLengthPrefixedByteArray(level); |
| 465 | |
| 466 | if (lastCert != null) { |
| 467 | // Use previous level cert to verify current level |
| 468 | Pair<String, ? extends AlgorithmParameterSpec> sigAlgParams = |
| 469 | getSignatureAlgorithmJcaSignatureAlgorithm(lastSigAlgorithm); |
| 470 | PublicKey publicKey = lastCert.getPublicKey(); |
| 471 | Signature sig = Signature.getInstance(sigAlgParams.first); |
| 472 | sig.initVerify(publicKey); |
| 473 | if (sigAlgParams.second != null) { |
| 474 | sig.setParameter(sigAlgParams.second); |
| 475 | } |
| 476 | sig.update(signedData); |
| 477 | if (!sig.verify(signature)) { |
| 478 | throw new SecurityException("Unable to verify signature of certificate #" |
| 479 | + levelCount + " using " + sigAlgParams.first + " when verifying" |
| 480 | + " Proof-of-rotation record"); |
| 481 | } |
| 482 | } |
| 483 | |
Dan Cashman | 6dbf837 | 2018-01-26 05:37:54 -0800 | [diff] [blame] | 484 | signedData.rewind(); |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 485 | byte[] encodedCert = readLengthPrefixedByteArray(signedData); |
| 486 | int signedSigAlgorithm = signedData.getInt(); |
| 487 | if (lastCert != null && lastSigAlgorithm != signedSigAlgorithm) { |
| 488 | throw new SecurityException("Signing algorithm ID mismatch for certificate #" |
| 489 | + levelCount + " when verifying Proof-of-rotation record"); |
| 490 | } |
| 491 | lastCert = (X509Certificate) |
| 492 | certFactory.generateCertificate(new ByteArrayInputStream(encodedCert)); |
| 493 | lastCert = new VerbatimX509Certificate(lastCert, encodedCert); |
| 494 | |
| 495 | lastSigAlgorithm = sigAlgorithm; |
| 496 | certs.add(lastCert); |
| 497 | flagsList.add(flags); |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 498 | } |
Dan Cashman | a656b8b | 2018-01-26 13:53:59 -0800 | [diff] [blame^] | 499 | } catch (IOException | BufferUnderflowException e) { |
| 500 | throw new IOException("Failed to parse Proof-of-rotation record", e); |
| 501 | } catch (NoSuchAlgorithmException | InvalidKeyException |
| 502 | | InvalidAlgorithmParameterException | SignatureException e) { |
| 503 | throw new SecurityException( |
| 504 | "Failed to verify signature over signed data for certificate #" |
| 505 | + levelCount + " when verifying Proof-of-rotation record", e); |
| 506 | } catch (CertificateException e) { |
| 507 | throw new SecurityException("Failed to decode certificate #" + levelCount |
| 508 | + " when verifying Proof-of-rotation record", e); |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 509 | } |
| 510 | return new VerifiedProofOfRotation(certs, flagsList); |
| 511 | } |
| 512 | |
Victor Hsieh | 07bc80c | 2018-01-11 16:15:47 -0800 | [diff] [blame] | 513 | static byte[] getVerityRootHash(String apkPath) |
| 514 | throws IOException, SignatureNotFoundException, SecurityException { |
| 515 | try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) { |
| 516 | SignatureInfo signatureInfo = findSignature(apk); |
| 517 | VerifiedSigner vSigner = verify(apk, false); |
| 518 | return vSigner.verityRootHash; |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | static byte[] generateApkVerity(String apkPath, ByteBufferFactory bufferFactory) |
| 523 | throws IOException, SignatureNotFoundException, SecurityException, DigestException, |
| 524 | NoSuchAlgorithmException { |
| 525 | try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) { |
| 526 | SignatureInfo signatureInfo = findSignature(apk); |
| 527 | return ApkSigningBlockUtils.generateApkVerity(apkPath, bufferFactory, signatureInfo); |
| 528 | } |
| 529 | } |
| 530 | |
Victor Hsieh | 5f76124 | 2018-01-20 10:30:12 -0800 | [diff] [blame] | 531 | static byte[] generateFsverityRootHash(String apkPath) |
| 532 | throws NoSuchAlgorithmException, DigestException, IOException, |
| 533 | SignatureNotFoundException { |
| 534 | try (RandomAccessFile apk = new RandomAccessFile(apkPath, "r")) { |
| 535 | SignatureInfo signatureInfo = findSignature(apk); |
| 536 | VerifiedSigner vSigner = verify(apk, false); |
| 537 | if (vSigner.verityRootHash == null) { |
| 538 | return null; |
| 539 | } |
| 540 | return ApkVerityBuilder.generateFsverityRootHash( |
| 541 | apk, ByteBuffer.wrap(vSigner.verityRootHash), signatureInfo); |
| 542 | } |
| 543 | } |
| 544 | |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 545 | private static boolean isSupportedSignatureAlgorithm(int sigAlgorithm) { |
| 546 | switch (sigAlgorithm) { |
| 547 | case SIGNATURE_RSA_PSS_WITH_SHA256: |
| 548 | case SIGNATURE_RSA_PSS_WITH_SHA512: |
| 549 | case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA256: |
| 550 | case SIGNATURE_RSA_PKCS1_V1_5_WITH_SHA512: |
| 551 | case SIGNATURE_ECDSA_WITH_SHA256: |
| 552 | case SIGNATURE_ECDSA_WITH_SHA512: |
| 553 | case SIGNATURE_DSA_WITH_SHA256: |
Victor Hsieh | 4acad4c | 2018-01-04 13:36:15 -0800 | [diff] [blame] | 554 | case SIGNATURE_VERITY_RSA_PKCS1_V1_5_WITH_SHA256: |
| 555 | case SIGNATURE_VERITY_ECDSA_WITH_SHA256: |
| 556 | case SIGNATURE_VERITY_DSA_WITH_SHA256: |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 557 | return true; |
| 558 | default: |
| 559 | return false; |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | /** |
| 564 | * Verified processed proof of rotation. |
| 565 | * |
| 566 | * @hide for internal use only. |
| 567 | */ |
| 568 | public static class VerifiedProofOfRotation { |
| 569 | public final List<X509Certificate> certs; |
| 570 | public final List<Integer> flagsList; |
| 571 | |
| 572 | public VerifiedProofOfRotation(List<X509Certificate> certs, List<Integer> flagsList) { |
| 573 | this.certs = certs; |
| 574 | this.flagsList = flagsList; |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | /** |
| 579 | * Verified APK Signature Scheme v3 signer, including the proof of rotation structure. |
| 580 | * |
| 581 | * @hide for internal use only. |
| 582 | */ |
| 583 | public static class VerifiedSigner { |
| 584 | public final X509Certificate[] certs; |
| 585 | public final VerifiedProofOfRotation por; |
| 586 | |
Victor Hsieh | 07bc80c | 2018-01-11 16:15:47 -0800 | [diff] [blame] | 587 | public byte[] verityRootHash; |
| 588 | |
Daniel Cashman | 67096e0 | 2017-12-28 12:46:33 -0800 | [diff] [blame] | 589 | public VerifiedSigner(X509Certificate[] certs, VerifiedProofOfRotation por) { |
| 590 | this.certs = certs; |
| 591 | this.por = por; |
| 592 | } |
| 593 | |
| 594 | } |
| 595 | |
| 596 | private static class PlatformNotSupportedException extends Exception { |
| 597 | |
| 598 | PlatformNotSupportedException(String s) { |
| 599 | super(s); |
| 600 | } |
| 601 | } |
| 602 | } |