Search in sources :

Example 11 with ApkFormatException

use of com.android.apksig.apk.ApkFormatException in project apksig by venshine.

the class ApkSigner method extractPinPatterns.

/**
 * Return list of pin patterns embedded in the pin pattern asset file. If no such file, return
 * {@code null}.
 */
private static List<Hints.PatternWithRange> extractPinPatterns(List<CentralDirectoryRecord> cdRecords, DataSource lhfSection) throws IOException, ApkFormatException {
    CentralDirectoryRecord pinListCdRecord = findCdRecord(cdRecords, Hints.PIN_HINT_ASSET_ZIP_ENTRY_NAME);
    List<Hints.PatternWithRange> pinPatterns = null;
    if (pinListCdRecord != null) {
        pinPatterns = new ArrayList<>();
        byte[] patternBlob;
        try {
            patternBlob = LocalFileRecord.getUncompressedData(lhfSection, pinListCdRecord, lhfSection.size());
        } catch (ZipFormatException ex) {
            throw new ApkFormatException("Bad " + pinListCdRecord);
        }
        pinPatterns = Hints.parsePinPatterns(patternBlob);
    }
    return pinPatterns;
}
Also used : CentralDirectoryRecord(com.android.apksig.internal.zip.CentralDirectoryRecord) ApkFormatException(com.android.apksig.apk.ApkFormatException) ZipFormatException(com.android.apksig.zip.ZipFormatException)

Example 12 with ApkFormatException

use of com.android.apksig.apk.ApkFormatException in project apksig by venshine.

the class V2SourceStampVerifier method verify.

/**
 * Verifies the provided APK's SourceStamp signatures and outputs the results into the provided
 * {@code result}. APK is considered verified only if there are no errors reported in the {@code
 * result}. See {@link #verify(DataSource, ZipSections, byte[], Map, int, int)} for
 * more information about the contract of this method.
 */
private static void verify(ByteBuffer sourceStampBlock, byte[] sourceStampCertificateDigest, Map<Integer, Map<ContentDigestAlgorithm, byte[]>> signatureSchemeApkContentDigests, int minSdkVersion, int maxSdkVersion, ApkSigResult result) throws NoSuchAlgorithmException {
    ApkSignerInfo signerInfo = new ApkSignerInfo();
    result.mSigners.add(signerInfo);
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        ByteBuffer sourceStampBlockData = ApkSigningBlockUtilsLite.getLengthPrefixedSlice(sourceStampBlock);
        SourceStampVerifier.verifyV2SourceStamp(sourceStampBlockData, certFactory, signerInfo, getSignatureSchemeDigests(signatureSchemeApkContentDigests), sourceStampCertificateDigest, minSdkVersion, maxSdkVersion);
        result.verified = !result.containsErrors() && !result.containsWarnings();
    } catch (CertificateException e) {
        throw new IllegalStateException("Failed to obtain X.509 CertificateFactory", e);
    } catch (ApkFormatException | BufferUnderflowException e) {
        signerInfo.addWarning(ApkVerificationIssue.SOURCE_STAMP_MALFORMED_SIGNATURE);
    }
}
Also used : ApkFormatException(com.android.apksig.apk.ApkFormatException) ApkSignerInfo(com.android.apksig.internal.apk.ApkSignerInfo) CertificateException(java.security.cert.CertificateException) CertificateFactory(java.security.cert.CertificateFactory) ByteBuffer(java.nio.ByteBuffer) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 13 with ApkFormatException

use of com.android.apksig.apk.ApkFormatException in project apksig by venshine.

the class V3SchemeVerifier method parseSigners.

/**
 * Parses each signer in the provided APK Signature Scheme v3 block and populates corresponding
 * {@code signerInfos} of the provided {@code result}.
 *
 * <p>This verifies signatures over {@code signed-data} block contained in each signer block.
 * However, this does not verify the integrity of the rest of the APK but rather simply reports
 * the expected digests of the rest of the APK (see {@code contentDigestsToVerify}).
 *
 * <p>This method adds one or more errors to the {@code result} if a verification error is
 * expected to be encountered on an Android platform version in the
 * {@code [minSdkVersion, maxSdkVersion]} range.
 */
public static void parseSigners(ByteBuffer apkSignatureSchemeV3Block, Set<ContentDigestAlgorithm> contentDigestsToVerify, ApkSigningBlockUtils.Result result) throws NoSuchAlgorithmException {
    ByteBuffer signers;
    try {
        signers = getLengthPrefixedSlice(apkSignatureSchemeV3Block);
    } catch (ApkFormatException e) {
        result.addError(Issue.V3_SIG_MALFORMED_SIGNERS);
        return;
    }
    if (!signers.hasRemaining()) {
        result.addError(Issue.V3_SIG_NO_SIGNERS);
        return;
    }
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("Failed to obtain X.509 CertificateFactory", e);
    }
    int signerCount = 0;
    while (signers.hasRemaining()) {
        int signerIndex = signerCount;
        signerCount++;
        ApkSigningBlockUtils.Result.SignerInfo signerInfo = new ApkSigningBlockUtils.Result.SignerInfo();
        signerInfo.index = signerIndex;
        result.signers.add(signerInfo);
        try {
            ByteBuffer signer = getLengthPrefixedSlice(signers);
            parseSigner(signer, certFactory, signerInfo, contentDigestsToVerify);
        } catch (ApkFormatException | BufferUnderflowException e) {
            signerInfo.addError(Issue.V3_SIG_MALFORMED_SIGNER);
            return;
        }
    }
}
Also used : ApkFormatException(com.android.apksig.apk.ApkFormatException) CertificateException(java.security.cert.CertificateException) ApkSigningBlockUtils(com.android.apksig.internal.apk.ApkSigningBlockUtils) ByteBuffer(java.nio.ByteBuffer) CertificateFactory(java.security.cert.CertificateFactory) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 14 with ApkFormatException

use of com.android.apksig.apk.ApkFormatException in project apksig by venshine.

the class V3SchemeVerifier method parseSigner.

/**
 * Parses the provided signer block and populates the {@code result}.
 *
 * <p>This verifies signatures over {@code signed-data} contained in this block, as well as
 * the data contained therein, but does not verify the integrity of the rest of the APK. To
 * facilitate APK integrity verification, this method adds the {@code contentDigestsToVerify}.
 * These digests can then be used to verify the integrity of the APK.
 *
 * <p>This method adds one or more errors to the {@code result} if a verification error is
 * expected to be encountered on an Android platform version in the
 * {@code [minSdkVersion, maxSdkVersion]} range.
 */
private static void parseSigner(ByteBuffer signerBlock, CertificateFactory certFactory, ApkSigningBlockUtils.Result.SignerInfo result, Set<ContentDigestAlgorithm> contentDigestsToVerify) throws ApkFormatException, NoSuchAlgorithmException {
    ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
    byte[] signedDataBytes = new byte[signedData.remaining()];
    signedData.get(signedDataBytes);
    signedData.flip();
    result.signedData = signedDataBytes;
    int parsedMinSdkVersion = signerBlock.getInt();
    int parsedMaxSdkVersion = signerBlock.getInt();
    result.minSdkVersion = parsedMinSdkVersion;
    result.maxSdkVersion = parsedMaxSdkVersion;
    if (parsedMinSdkVersion < 0 || parsedMinSdkVersion > parsedMaxSdkVersion) {
        result.addError(Issue.V3_SIG_INVALID_SDK_VERSIONS, parsedMinSdkVersion, parsedMaxSdkVersion);
    }
    ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
    byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
    // Parse the signatures block and identify supported signatures
    int signatureCount = 0;
    List<ApkSigningBlockUtils.SupportedSignature> supportedSignatures = new ArrayList<>(1);
    while (signatures.hasRemaining()) {
        signatureCount++;
        try {
            ByteBuffer signature = getLengthPrefixedSlice(signatures);
            int sigAlgorithmId = signature.getInt();
            byte[] sigBytes = readLengthPrefixedByteArray(signature);
            result.signatures.add(new ApkSigningBlockUtils.Result.SignerInfo.Signature(sigAlgorithmId, sigBytes));
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.findById(sigAlgorithmId);
            if (signatureAlgorithm == null) {
                result.addWarning(Issue.V3_SIG_UNKNOWN_SIG_ALGORITHM, sigAlgorithmId);
                continue;
            }
            // TODO consider dropping deprecated signatures for v3 or modifying
            // getSignaturesToVerify (called below)
            supportedSignatures.add(new ApkSigningBlockUtils.SupportedSignature(signatureAlgorithm, sigBytes));
        } catch (ApkFormatException | BufferUnderflowException e) {
            result.addError(Issue.V3_SIG_MALFORMED_SIGNATURE, signatureCount);
            return;
        }
    }
    if (result.signatures.isEmpty()) {
        result.addError(Issue.V3_SIG_NO_SIGNATURES);
        return;
    }
    // Verify signatures over signed-data block using the public key
    List<ApkSigningBlockUtils.SupportedSignature> signaturesToVerify = null;
    try {
        signaturesToVerify = ApkSigningBlockUtils.getSignaturesToVerify(supportedSignatures, result.minSdkVersion, result.maxSdkVersion);
    } catch (ApkSigningBlockUtils.NoSupportedSignaturesException e) {
        result.addError(Issue.V3_SIG_NO_SUPPORTED_SIGNATURES);
        return;
    }
    for (ApkSigningBlockUtils.SupportedSignature signature : signaturesToVerify) {
        SignatureAlgorithm signatureAlgorithm = signature.algorithm;
        String jcaSignatureAlgorithm = signatureAlgorithm.getJcaSignatureAlgorithmAndParams().getFirst();
        AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithm.getJcaSignatureAlgorithmAndParams().getSecond();
        String keyAlgorithm = signatureAlgorithm.getJcaKeyAlgorithm();
        PublicKey publicKey;
        try {
            publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        } catch (Exception e) {
            result.addError(Issue.V3_SIG_MALFORMED_PUBLIC_KEY, e);
            return;
        }
        try {
            Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
            sig.initVerify(publicKey);
            if (jcaSignatureAlgorithmParams != null) {
                sig.setParameter(jcaSignatureAlgorithmParams);
            }
            signedData.position(0);
            sig.update(signedData);
            byte[] sigBytes = signature.signature;
            if (!sig.verify(sigBytes)) {
                result.addError(Issue.V3_SIG_DID_NOT_VERIFY, signatureAlgorithm);
                return;
            }
            result.verifiedSignatures.put(signatureAlgorithm, sigBytes);
            contentDigestsToVerify.add(signatureAlgorithm.getContentDigestAlgorithm());
        } catch (InvalidKeyException | InvalidAlgorithmParameterException | SignatureException e) {
            result.addError(Issue.V3_SIG_VERIFY_EXCEPTION, signatureAlgorithm, e);
            return;
        }
    }
    // At least one signature over signedData has verified. We can now parse signed-data.
    signedData.position(0);
    ByteBuffer digests = getLengthPrefixedSlice(signedData);
    ByteBuffer certificates = getLengthPrefixedSlice(signedData);
    int signedMinSdkVersion = signedData.getInt();
    if (signedMinSdkVersion != parsedMinSdkVersion) {
        result.addError(Issue.V3_MIN_SDK_VERSION_MISMATCH_BETWEEN_SIGNER_AND_SIGNED_DATA_RECORD, parsedMinSdkVersion, signedMinSdkVersion);
    }
    int signedMaxSdkVersion = signedData.getInt();
    if (signedMaxSdkVersion != parsedMaxSdkVersion) {
        result.addError(Issue.V3_MAX_SDK_VERSION_MISMATCH_BETWEEN_SIGNER_AND_SIGNED_DATA_RECORD, parsedMaxSdkVersion, signedMaxSdkVersion);
    }
    ByteBuffer additionalAttributes = getLengthPrefixedSlice(signedData);
    // Parse the certificates block
    int certificateIndex = -1;
    while (certificates.hasRemaining()) {
        certificateIndex++;
        byte[] encodedCert = readLengthPrefixedByteArray(certificates);
        X509Certificate certificate;
        try {
            certificate = X509CertificateUtils.generateCertificate(encodedCert, certFactory);
        } catch (CertificateException e) {
            result.addError(Issue.V3_SIG_MALFORMED_CERTIFICATE, certificateIndex, certificateIndex + 1, e);
            return;
        }
        // Wrap the cert so that the result's getEncoded returns exactly the original encoded
        // form. Without this, getEncoded may return a different form from what was stored in
        // the signature. This is because some X509Certificate(Factory) implementations
        // re-encode certificates.
        certificate = new GuaranteedEncodedFormX509Certificate(certificate, encodedCert);
        result.certs.add(certificate);
    }
    if (result.certs.isEmpty()) {
        result.addError(Issue.V3_SIG_NO_CERTIFICATES);
        return;
    }
    X509Certificate mainCertificate = result.certs.get(0);
    byte[] certificatePublicKeyBytes;
    try {
        certificatePublicKeyBytes = ApkSigningBlockUtils.encodePublicKey(mainCertificate.getPublicKey());
    } catch (InvalidKeyException e) {
        System.out.println("Caught an exception encoding the public key: " + e);
        e.printStackTrace();
        certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
    }
    if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
        result.addError(Issue.V3_SIG_PUBLIC_KEY_MISMATCH_BETWEEN_CERTIFICATE_AND_SIGNATURES_RECORD, ApkSigningBlockUtils.toHex(certificatePublicKeyBytes), ApkSigningBlockUtils.toHex(publicKeyBytes));
        return;
    }
    // Parse the digests block
    int digestCount = 0;
    while (digests.hasRemaining()) {
        digestCount++;
        try {
            ByteBuffer digest = getLengthPrefixedSlice(digests);
            int sigAlgorithmId = digest.getInt();
            byte[] digestBytes = readLengthPrefixedByteArray(digest);
            result.contentDigests.add(new ApkSigningBlockUtils.Result.SignerInfo.ContentDigest(sigAlgorithmId, digestBytes));
        } catch (ApkFormatException | BufferUnderflowException e) {
            result.addError(Issue.V3_SIG_MALFORMED_DIGEST, digestCount);
            return;
        }
    }
    List<Integer> sigAlgsFromSignaturesRecord = new ArrayList<>(result.signatures.size());
    for (ApkSigningBlockUtils.Result.SignerInfo.Signature signature : result.signatures) {
        sigAlgsFromSignaturesRecord.add(signature.getAlgorithmId());
    }
    List<Integer> sigAlgsFromDigestsRecord = new ArrayList<>(result.contentDigests.size());
    for (ApkSigningBlockUtils.Result.SignerInfo.ContentDigest digest : result.contentDigests) {
        sigAlgsFromDigestsRecord.add(digest.getSignatureAlgorithmId());
    }
    if (!sigAlgsFromSignaturesRecord.equals(sigAlgsFromDigestsRecord)) {
        result.addError(Issue.V3_SIG_SIG_ALG_MISMATCH_BETWEEN_SIGNATURES_AND_DIGESTS_RECORDS, sigAlgsFromSignaturesRecord, sigAlgsFromDigestsRecord);
        return;
    }
    // Parse the additional attributes block.
    int additionalAttributeCount = 0;
    while (additionalAttributes.hasRemaining()) {
        additionalAttributeCount++;
        try {
            ByteBuffer attribute = getLengthPrefixedSlice(additionalAttributes);
            int id = attribute.getInt();
            byte[] value = ByteBufferUtils.toByteArray(attribute);
            result.additionalAttributes.add(new ApkSigningBlockUtils.Result.SignerInfo.AdditionalAttribute(id, value));
            if (id == V3SchemeConstants.PROOF_OF_ROTATION_ATTR_ID) {
                try {
                    // SigningCertificateLineage is verified when built
                    result.signingCertificateLineage = SigningCertificateLineage.readFromV3AttributeValue(value);
                    // make sure that the last cert in the chain matches this signer cert
                    SigningCertificateLineage subLineage = result.signingCertificateLineage.getSubLineage(result.certs.get(0));
                    if (result.signingCertificateLineage.size() != subLineage.size()) {
                        result.addError(Issue.V3_SIG_POR_CERT_MISMATCH);
                    }
                } catch (SecurityException e) {
                    result.addError(Issue.V3_SIG_POR_DID_NOT_VERIFY);
                } catch (IllegalArgumentException e) {
                    result.addError(Issue.V3_SIG_POR_CERT_MISMATCH);
                } catch (Exception e) {
                    result.addError(Issue.V3_SIG_MALFORMED_LINEAGE);
                }
            } else {
                result.addWarning(Issue.V3_SIG_UNKNOWN_ADDITIONAL_ATTRIBUTE, id);
            }
        } catch (ApkFormatException | BufferUnderflowException e) {
            result.addError(Issue.V3_SIG_MALFORMED_ADDITIONAL_ATTRIBUTE, additionalAttributeCount);
            return;
        }
    }
}
Also used : GuaranteedEncodedFormX509Certificate(com.android.apksig.internal.util.GuaranteedEncodedFormX509Certificate) ArrayList(java.util.ArrayList) SignatureAlgorithm(com.android.apksig.internal.apk.SignatureAlgorithm) CertificateException(java.security.cert.CertificateException) SignatureException(java.security.SignatureException) ApkSigningBlockUtils(com.android.apksig.internal.apk.ApkSigningBlockUtils) ApkFormatException(com.android.apksig.apk.ApkFormatException) BufferUnderflowException(java.nio.BufferUnderflowException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) InvalidKeyException(java.security.InvalidKeyException) ByteBuffer(java.nio.ByteBuffer) SignatureNotFoundException(com.android.apksig.internal.apk.ApkSigningBlockUtils.SignatureNotFoundException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ApkFormatException(com.android.apksig.apk.ApkFormatException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) BufferUnderflowException(java.nio.BufferUnderflowException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) X509Certificate(java.security.cert.X509Certificate) GuaranteedEncodedFormX509Certificate(com.android.apksig.internal.util.GuaranteedEncodedFormX509Certificate) SigningCertificateLineage(com.android.apksig.SigningCertificateLineage) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 15 with ApkFormatException

use of com.android.apksig.apk.ApkFormatException in project LSPatch by LSPosed.

the class SigningExtension method onOutputZipEntriesWritten.

private void onOutputZipEntriesWritten() throws IOException {
    if (!dirty) {
        return;
    }
    // Check whether we should output an APK Signing Block which contains v2 signatures
    byte[] apkSigningBlock;
    byte[] centralDirBytes = zFile.getCentralDirectoryBytes();
    byte[] eocdBytes = zFile.getEocdBytes();
    ApkSignerEngine.OutputApkSigningBlockRequest2 addV2SignatureRequest;
    // file (as reported to this extension).
    if (cachedApkSigningBlock != null) {
        apkSigningBlock = cachedApkSigningBlock;
        addV2SignatureRequest = null;
    } else {
        DataSource centralDir = DataSources.asDataSource(ByteBuffer.wrap(centralDirBytes));
        DataSource eocd = DataSources.asDataSource(ByteBuffer.wrap(eocdBytes));
        long zipEntriesSizeBytes = zFile.getCentralDirectoryOffset() - zFile.getExtraDirectoryOffset();
        DataSource zipEntries = zFile.asDataSource(0, zipEntriesSizeBytes);
        try {
            addV2SignatureRequest = signer.outputZipSections2(zipEntries, centralDir, eocd);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | ApkFormatException | IOException e) {
            throw new IOException("Failed to generate v2 signature", e);
        }
        if (addV2SignatureRequest != null) {
            apkSigningBlock = addV2SignatureRequest.getApkSigningBlock();
            if (sdkDependencyData != null) {
                apkSigningBlock = SigningBlockUtils.addToSigningBlock(apkSigningBlock, sdkDependencyData, DEPENDENCY_INFO_BLOCK_ID);
            }
            apkSigningBlock = Bytes.concat(new byte[addV2SignatureRequest.getPaddingSizeBeforeApkSigningBlock()], apkSigningBlock);
        } else {
            apkSigningBlock = new byte[0];
            if (sdkDependencyData != null) {
                apkSigningBlock = SigningBlockUtils.addToSigningBlock(apkSigningBlock, sdkDependencyData, DEPENDENCY_INFO_BLOCK_ID);
                int paddingSize = ApkSigningBlockUtils.generateApkSigningBlockPadding(zipEntries, /* apkSigningBlockPaddingSupported */
                true).getSecond();
                apkSigningBlock = Bytes.concat(new byte[paddingSize], apkSigningBlock);
            }
        }
        cachedApkSigningBlock = apkSigningBlock;
    }
    // Insert the APK Signing Block into the output right before the ZIP Central Directory and
    // accordingly update the start offset of ZIP Central Directory in ZIP End of Central
    // Directory.
    zFile.directWrite(zFile.getCentralDirectoryOffset() - zFile.getExtraDirectoryOffset(), apkSigningBlock);
    zFile.setExtraDirectoryOffset(apkSigningBlock.length);
    if (addV2SignatureRequest != null) {
        addV2SignatureRequest.done();
    }
}
Also used : ApkFormatException(com.android.apksig.apk.ApkFormatException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) ApkSignerEngine(com.android.apksig.ApkSignerEngine) DefaultApkSignerEngine(com.android.apksig.DefaultApkSignerEngine) DataSource(com.android.apksig.util.DataSource)

Aggregations

ApkFormatException (com.android.apksig.apk.ApkFormatException)36 IOException (java.io.IOException)18 ByteBuffer (java.nio.ByteBuffer)17 ArrayList (java.util.ArrayList)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)13 BufferUnderflowException (java.nio.BufferUnderflowException)12 ZipFormatException (com.android.apksig.zip.ZipFormatException)11 CertificateException (java.security.cert.CertificateException)11 ApkSigningBlockUtils (com.android.apksig.internal.apk.ApkSigningBlockUtils)9 CentralDirectoryRecord (com.android.apksig.internal.zip.CentralDirectoryRecord)9 X509Certificate (java.security.cert.X509Certificate)9 InvalidKeyException (java.security.InvalidKeyException)7 SignatureException (java.security.SignatureException)7 CertificateFactory (java.security.cert.CertificateFactory)7 SignatureAlgorithm (com.android.apksig.internal.apk.SignatureAlgorithm)6 GuaranteedEncodedFormX509Certificate (com.android.apksig.internal.util.GuaranteedEncodedFormX509Certificate)6 HashSet (java.util.HashSet)6 ApkSigResult (com.android.apksig.internal.apk.ApkSigResult)5 DataSource (com.android.apksig.util.DataSource)5 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)5