Search in sources :

Example 6 with ApkFormatException

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

the class SourceStampCertificateLineage method readSigningCertificateLineage.

/**
 * Deserializes the binary representation of a SourceStampCertificateLineage. Also
 * verifies that the structure is well-formed, e.g. that the signature for each node is from its
 * parent.
 */
public static List<SigningCertificateNode> readSigningCertificateLineage(ByteBuffer inputBytes) throws IOException {
    List<SigningCertificateNode> result = new ArrayList<>();
    int nodeCount = 0;
    if (inputBytes == null || !inputBytes.hasRemaining()) {
        return null;
    }
    ApkSigningBlockUtilsLite.checkByteOrderLittleEndian(inputBytes);
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new IllegalStateException("Failed to obtain X.509 CertificateFactory", e);
    }
    // FORMAT (little endian):
    // * uint32: version code
    // * sequence of length-prefixed (uint32): nodes
    // * length-prefixed bytes: signed data
    // * length-prefixed bytes: certificate
    // * uint32: signature algorithm id
    // * uint32: flags
    // * uint32: signature algorithm id (used by to sign next cert in lineage)
    // * length-prefixed bytes: signature over above signed data
    X509Certificate lastCert = null;
    int lastSigAlgorithmId = 0;
    try {
        int version = inputBytes.getInt();
        if (version != CURRENT_VERSION) {
            // we only have one version to worry about right now, so just check it
            throw new IllegalArgumentException("Encoded SigningCertificateLineage has a version" + " different than any of which we are aware");
        }
        HashSet<X509Certificate> certHistorySet = new HashSet<>();
        while (inputBytes.hasRemaining()) {
            nodeCount++;
            ByteBuffer nodeBytes = getLengthPrefixedSlice(inputBytes);
            ByteBuffer signedData = getLengthPrefixedSlice(nodeBytes);
            int flags = nodeBytes.getInt();
            int sigAlgorithmId = nodeBytes.getInt();
            SignatureAlgorithm sigAlgorithm = SignatureAlgorithm.findById(lastSigAlgorithmId);
            byte[] signature = readLengthPrefixedByteArray(nodeBytes);
            if (lastCert != null) {
                // Use previous level cert to verify current level
                String jcaSignatureAlgorithm = sigAlgorithm.getJcaSignatureAlgorithmAndParams().getFirst();
                AlgorithmParameterSpec jcaSignatureAlgorithmParams = sigAlgorithm.getJcaSignatureAlgorithmAndParams().getSecond();
                PublicKey publicKey = lastCert.getPublicKey();
                Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
                sig.initVerify(publicKey);
                if (jcaSignatureAlgorithmParams != null) {
                    sig.setParameter(jcaSignatureAlgorithmParams);
                }
                sig.update(signedData);
                if (!sig.verify(signature)) {
                    throw new SecurityException("Unable to verify signature of certificate #" + nodeCount + " using " + jcaSignatureAlgorithm + " when verifying" + " SourceStampCertificateLineage object");
                }
            }
            signedData.rewind();
            byte[] encodedCert = readLengthPrefixedByteArray(signedData);
            int signedSigAlgorithm = signedData.getInt();
            if (lastCert != null && lastSigAlgorithmId != signedSigAlgorithm) {
                throw new SecurityException("Signing algorithm ID mismatch for certificate #" + nodeBytes + " when verifying SourceStampCertificateLineage object");
            }
            lastCert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
            lastCert = new GuaranteedEncodedFormX509Certificate(lastCert, encodedCert);
            if (certHistorySet.contains(lastCert)) {
                throw new SecurityException("Encountered duplicate entries in " + "SigningCertificateLineage at certificate #" + nodeCount + ".  All " + "signing certificates should be unique");
            }
            certHistorySet.add(lastCert);
            lastSigAlgorithmId = sigAlgorithmId;
            result.add(new SigningCertificateNode(lastCert, SignatureAlgorithm.findById(signedSigAlgorithm), SignatureAlgorithm.findById(sigAlgorithmId), signature, flags));
        }
    } catch (ApkFormatException | BufferUnderflowException e) {
        throw new IOException("Failed to parse SourceStampCertificateLineage object", e);
    } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | SignatureException e) {
        throw new SecurityException("Failed to verify signature over signed data for certificate #" + nodeCount + " when parsing SourceStampCertificateLineage object", e);
    } catch (CertificateException e) {
        throw new SecurityException("Failed to decode certificate #" + nodeCount + " when parsing SourceStampCertificateLineage object", e);
    }
    return result;
}
Also used : GuaranteedEncodedFormX509Certificate(com.android.apksig.internal.util.GuaranteedEncodedFormX509Certificate) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) SignatureAlgorithm(com.android.apksig.internal.apk.SignatureAlgorithm) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) CertificateFactory(java.security.cert.CertificateFactory) ApkFormatException(com.android.apksig.apk.ApkFormatException) BufferUnderflowException(java.nio.BufferUnderflowException) HashSet(java.util.HashSet) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) GuaranteedEncodedFormX509Certificate(com.android.apksig.internal.util.GuaranteedEncodedFormX509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 7 with ApkFormatException

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

the class SourceStampVerifier method verifySourceStampSignature.

private static void verifySourceStampSignature(byte[] data, int minSdkVersion, int maxSdkVersion, X509Certificate sourceStampCertificate, ByteBuffer signatures, ApkSignerInfo result) {
    // Parse the signatures block and identify supported signatures
    int signatureCount = 0;
    List<ApkSupportedSignature> supportedSignatures = new ArrayList<>(1);
    while (signatures.hasRemaining()) {
        signatureCount++;
        try {
            ByteBuffer signature = getLengthPrefixedSlice(signatures);
            int sigAlgorithmId = signature.getInt();
            byte[] sigBytes = readLengthPrefixedByteArray(signature);
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.findById(sigAlgorithmId);
            if (signatureAlgorithm == null) {
                result.addWarning(ApkVerificationIssue.SOURCE_STAMP_UNKNOWN_SIG_ALGORITHM, sigAlgorithmId);
                continue;
            }
            supportedSignatures.add(new ApkSupportedSignature(signatureAlgorithm, sigBytes));
        } catch (ApkFormatException | BufferUnderflowException e) {
            result.addWarning(ApkVerificationIssue.SOURCE_STAMP_MALFORMED_SIGNATURE, signatureCount);
            return;
        }
    }
    if (supportedSignatures.isEmpty()) {
        result.addWarning(ApkVerificationIssue.SOURCE_STAMP_NO_SIGNATURE);
        return;
    }
    // Verify signatures over digests using the SourceStamp's certificate.
    List<ApkSupportedSignature> signaturesToVerify;
    try {
        signaturesToVerify = getSignaturesToVerify(supportedSignatures, minSdkVersion, maxSdkVersion, true);
    } catch (NoApkSupportedSignaturesException e) {
        // To facilitate debugging capture the signature algorithms and resulting exception in
        // the warning.
        StringBuilder signatureAlgorithms = new StringBuilder();
        for (ApkSupportedSignature supportedSignature : supportedSignatures) {
            if (signatureAlgorithms.length() > 0) {
                signatureAlgorithms.append(", ");
            }
            signatureAlgorithms.append(supportedSignature.algorithm);
        }
        result.addWarning(ApkVerificationIssue.SOURCE_STAMP_NO_SUPPORTED_SIGNATURE, signatureAlgorithms.toString(), e);
        return;
    }
    for (ApkSupportedSignature signature : signaturesToVerify) {
        SignatureAlgorithm signatureAlgorithm = signature.algorithm;
        String jcaSignatureAlgorithm = signatureAlgorithm.getJcaSignatureAlgorithmAndParams().getFirst();
        AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithm.getJcaSignatureAlgorithmAndParams().getSecond();
        PublicKey publicKey = sourceStampCertificate.getPublicKey();
        try {
            Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
            sig.initVerify(publicKey);
            if (jcaSignatureAlgorithmParams != null) {
                sig.setParameter(jcaSignatureAlgorithmParams);
            }
            sig.update(data);
            byte[] sigBytes = signature.signature;
            if (!sig.verify(sigBytes)) {
                result.addWarning(ApkVerificationIssue.SOURCE_STAMP_DID_NOT_VERIFY, signatureAlgorithm);
                return;
            }
        } catch (InvalidKeyException | InvalidAlgorithmParameterException | SignatureException | NoSuchAlgorithmException e) {
            result.addWarning(ApkVerificationIssue.SOURCE_STAMP_VERIFY_EXCEPTION, signatureAlgorithm, e);
            return;
        }
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) ArrayList(java.util.ArrayList) SignatureAlgorithm(com.android.apksig.internal.apk.SignatureAlgorithm) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) ByteBuffer(java.nio.ByteBuffer) ApkSupportedSignature(com.android.apksig.internal.apk.ApkSupportedSignature) ApkFormatException(com.android.apksig.apk.ApkFormatException) ApkSupportedSignature(com.android.apksig.internal.apk.ApkSupportedSignature) Signature(java.security.Signature) NoApkSupportedSignaturesException(com.android.apksig.internal.apk.NoApkSupportedSignaturesException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 8 with ApkFormatException

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

the class SourceStampVerifier method parseSigner.

/**
 * Parses the provided signer block and populates the {@code result}.
 *
 * <p>This verifies signatures over {@code signed-data} contained in this block 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, int apkSigSchemeVersion, CertificateFactory certFactory, Map<ContentDigestAlgorithm, byte[]> apkContentDigests, Result.SignerInfo signerInfo) throws ApkFormatException {
    boolean isV2Signer = apkSigSchemeVersion == VERSION_APK_SIGNATURE_SCHEME_V2;
    // Both the V2 and V3 signer blocks contain the following:
    // * length-prefixed signed data
    // * length-prefixed sequence of length-prefixed digests:
    // * uint32: signature algorithm ID
    // * length-prefixed bytes: digest of contents
    // * length-prefixed sequence of certificates:
    // * length-prefixed bytes: X.509 certificate (ASN.1 DER encoded).
    ByteBuffer signedData = ApkSigningBlockUtilsLite.getLengthPrefixedSlice(signerBlock);
    ByteBuffer digests = ApkSigningBlockUtilsLite.getLengthPrefixedSlice(signedData);
    ByteBuffer certificates = ApkSigningBlockUtilsLite.getLengthPrefixedSlice(signedData);
    // Parse the digests block
    while (digests.hasRemaining()) {
        try {
            ByteBuffer digest = ApkSigningBlockUtilsLite.getLengthPrefixedSlice(digests);
            int sigAlgorithmId = digest.getInt();
            byte[] digestBytes = ApkSigningBlockUtilsLite.readLengthPrefixedByteArray(digest);
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.findById(sigAlgorithmId);
            if (signatureAlgorithm == null) {
                continue;
            }
            apkContentDigests.put(signatureAlgorithm.getContentDigestAlgorithm(), digestBytes);
        } catch (ApkFormatException | BufferUnderflowException e) {
            signerInfo.addVerificationWarning(isV2Signer ? ApkVerificationIssue.V2_SIG_MALFORMED_DIGEST : ApkVerificationIssue.V3_SIG_MALFORMED_DIGEST);
            return;
        }
    }
    // Parse the certificates block
    if (certificates.hasRemaining()) {
        byte[] encodedCert = ApkSigningBlockUtilsLite.readLengthPrefixedByteArray(certificates);
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
        } catch (CertificateException e) {
            signerInfo.addVerificationWarning(isV2Signer ? ApkVerificationIssue.V2_SIG_MALFORMED_CERTIFICATE : ApkVerificationIssue.V3_SIG_MALFORMED_CERTIFICATE);
            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);
        signerInfo.setSigningCertificate(certificate);
    }
    if (signerInfo.getSigningCertificate() == null) {
        signerInfo.addVerificationWarning(isV2Signer ? ApkVerificationIssue.V2_SIG_NO_CERTIFICATES : ApkVerificationIssue.V3_SIG_NO_CERTIFICATES);
        return;
    }
}
Also used : GuaranteedEncodedFormX509Certificate(com.android.apksig.internal.util.GuaranteedEncodedFormX509Certificate) ApkFormatException(com.android.apksig.apk.ApkFormatException) ByteArrayInputStream(java.io.ByteArrayInputStream) SignatureAlgorithm(com.android.apksig.internal.apk.SignatureAlgorithm) CertificateException(java.security.cert.CertificateException) ByteBuffer(java.nio.ByteBuffer) BufferUnderflowException(java.nio.BufferUnderflowException) X509Certificate(java.security.cert.X509Certificate) GuaranteedEncodedFormX509Certificate(com.android.apksig.internal.util.GuaranteedEncodedFormX509Certificate)

Example 9 with ApkFormatException

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

the class SourceStampVerifier method parseSigners.

/**
 * Parses each signer in the provided APK V2 / V3 signature block and populates corresponding
 * {@code SignerInfo} of the provided {@code result} and their {@code apkContentDigests}.
 *
 * <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 apkSignatureSchemeBlock, int apkSigSchemeVersion, Map<ContentDigestAlgorithm, byte[]> apkContentDigests, Result result) {
    boolean isV2Block = apkSigSchemeVersion == VERSION_APK_SIGNATURE_SCHEME_V2;
    // Both the V2 and V3 signature blocks contain the following:
    // * length-prefixed sequence of length-prefixed signers
    ByteBuffer signers;
    try {
        signers = ApkSigningBlockUtilsLite.getLengthPrefixedSlice(apkSignatureSchemeBlock);
    } catch (ApkFormatException e) {
        result.addVerificationWarning(isV2Block ? ApkVerificationIssue.V2_SIG_MALFORMED_SIGNERS : ApkVerificationIssue.V3_SIG_MALFORMED_SIGNERS);
        return;
    }
    if (!signers.hasRemaining()) {
        result.addVerificationWarning(isV2Block ? ApkVerificationIssue.V2_SIG_NO_SIGNERS : ApkVerificationIssue.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);
    }
    while (signers.hasRemaining()) {
        Result.SignerInfo signerInfo = new Result.SignerInfo();
        if (isV2Block) {
            result.addV2Signer(signerInfo);
        } else {
            result.addV3Signer(signerInfo);
        }
        try {
            ByteBuffer signer = ApkSigningBlockUtilsLite.getLengthPrefixedSlice(signers);
            parseSigner(signer, apkSigSchemeVersion, certFactory, apkContentDigests, signerInfo);
        } catch (ApkFormatException | BufferUnderflowException e) {
            signerInfo.addVerificationWarning(isV2Block ? ApkVerificationIssue.V2_SIG_MALFORMED_SIGNER : ApkVerificationIssue.V3_SIG_MALFORMED_SIGNER);
            return;
        }
    }
}
Also used : ApkSignerInfo(com.android.apksig.internal.apk.ApkSignerInfo) ApkFormatException(com.android.apksig.apk.ApkFormatException) CertificateException(java.security.cert.CertificateException) ByteBuffer(java.nio.ByteBuffer) CertificateFactory(java.security.cert.CertificateFactory) BufferUnderflowException(java.nio.BufferUnderflowException) ApkSigResult(com.android.apksig.internal.apk.ApkSigResult)

Example 10 with ApkFormatException

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

the class ApkSigner method getZipCentralDirectory.

private static ByteBuffer getZipCentralDirectory(DataSource apk, ApkUtils.ZipSections apkSections) throws IOException, ApkFormatException {
    long cdSizeBytes = apkSections.getZipCentralDirectorySizeBytes();
    if (cdSizeBytes > Integer.MAX_VALUE) {
        throw new ApkFormatException("ZIP Central Directory too large: " + cdSizeBytes);
    }
    long cdOffset = apkSections.getZipCentralDirectoryOffset();
    ByteBuffer cd = apk.getByteBuffer(cdOffset, (int) cdSizeBytes);
    cd.order(ByteOrder.LITTLE_ENDIAN);
    return cd;
}
Also used : ApkFormatException(com.android.apksig.apk.ApkFormatException) ByteBuffer(java.nio.ByteBuffer)

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