Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit adb0627c authored by Victor Hsieh's avatar Victor Hsieh Committed by Android (Google) Code Review
Browse files

Merge changes I70a8fc39,I80bbbd88

* changes:
  VerityUtilsTest: add a test case of external signature
  Provide a method to verify a PKCS#7 signature
parents 9031e838 2a685c85
Loading
Loading
Loading
Loading
+11 −0
Original line number Diff line number Diff line
{
  "presubmit": [
    {
      "name": "FrameworksCoreTests",
      "options": [
        {
          "include-filter": "com.android.internal.security."
        },
        {
          "include-annotation": "android.platform.test.annotations.Presubmit"
        }
      ]
    },
    {
      "name": "ApkVerityTest",
      "file_patterns": ["VerityUtils\\.java"]
+116 −0
Original line number Diff line number Diff line
@@ -23,10 +23,28 @@ import android.system.Os;
import android.system.OsConstants;
import android.util.Slog;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import com.android.internal.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import com.android.internal.org.bouncycastle.cms.CMSException;
import com.android.internal.org.bouncycastle.cms.CMSProcessableByteArray;
import com.android.internal.org.bouncycastle.cms.CMSSignedData;
import com.android.internal.org.bouncycastle.cms.SignerInformation;
import com.android.internal.org.bouncycastle.cms.SignerInformationVerifier;
import com.android.internal.org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import com.android.internal.org.bouncycastle.operator.OperatorCreationException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/** Provides fsverity related operations. */
public abstract class VerityUtils {
@@ -90,6 +108,91 @@ public abstract class VerityUtils {
        return (retval == 1);
    }

    /**
     * Verifies the signature over the fs-verity digest using the provided certificate.
     *
     * This method should only be used by any existing fs-verity use cases that require
     * PKCS#7 signature verification, if backward compatibility is necessary.
     *
     * Since PKCS#7 is too flexible, for the current specific need, only specific configuration
     * will be accepted:
     * <ul>
     *   <li>Must use SHA256 as the digest algorithm
     *   <li>Must use rsaEncryption as signature algorithm
     *   <li>Must be detached / without content
     *   <li>Must not include any signed or unsigned attributes
     * </ul>
     *
     * It is up to the caller to provide an appropriate/trusted certificate.
     *
     * @param signatureBlock byte array of a PKCS#7 detached signature
     * @param digest fs-verity digest with the common configuration using sha256
     * @param derCertInputStream an input stream of a X.509 certificate in DER
     * @return whether the verification succeeds
     */
    public static boolean verifyPkcs7DetachedSignature(@NonNull byte[] signatureBlock,
            @NonNull byte[] digest, @NonNull InputStream derCertInputStream) {
        if (digest.length != 32) {
            Slog.w(TAG, "Only sha256 is currently supported");
            return false;
        }

        try {
            CMSSignedData signedData = new CMSSignedData(
                    new CMSProcessableByteArray(toFormattedDigest(digest)),
                    signatureBlock);

            if (!signedData.isDetachedSignature()) {
                Slog.w(TAG, "Expect only detached siganture");
                return false;
            }
            if (!signedData.getCertificates().getMatches(null).isEmpty()) {
                Slog.w(TAG, "Expect no certificate in signature");
                return false;
            }
            if (!signedData.getCRLs().getMatches(null).isEmpty()) {
                Slog.w(TAG, "Expect no CRL in signature");
                return false;
            }

            X509Certificate trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(derCertInputStream);
            SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder()
                    .build(trustedCert);

            // Verify any signature with the trusted certificate.
            for (SignerInformation si : signedData.getSignerInfos().getSigners()) {
                // To be the most strict while dealing with the complicated PKCS#7 signature, reject
                // everything we don't need.
                if (si.getSignedAttributes() != null && si.getSignedAttributes().size() > 0) {
                    Slog.w(TAG, "Unexpected signed attributes");
                    return false;
                }
                if (si.getUnsignedAttributes() != null && si.getUnsignedAttributes().size() > 0) {
                    Slog.w(TAG, "Unexpected unsigned attributes");
                    return false;
                }
                if (!NISTObjectIdentifiers.id_sha256.getId().equals(si.getDigestAlgOID())) {
                    Slog.w(TAG, "Unsupported digest algorithm OID: " + si.getDigestAlgOID());
                    return false;
                }
                if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(si.getEncryptionAlgOID())) {
                    Slog.w(TAG, "Unsupported encryption algorithm OID: "
                            + si.getEncryptionAlgOID());
                    return false;
                }

                if (si.verify(verifier)) {
                    return true;
                }
            }
            return false;
        } catch (CertificateException | CMSException | OperatorCreationException e) {
            Slog.w(TAG, "Error occurred during the PKCS#7 signature verification", e);
        }
        return false;
    }

    /**
     * Returns fs-verity digest for the file if enabled, otherwise returns null. The digest is a
     * hash of root hash of fs-verity's Merkle tree with extra metadata.
@@ -110,6 +213,19 @@ public abstract class VerityUtils {
        return result;
    }

    /** @hide */
    @VisibleForTesting
    public static byte[] toFormattedDigest(byte[] digest) {
        // Construct fsverity_formatted_digest used in fs-verity's built-in signature verification.
        ByteBuffer buffer = ByteBuffer.allocate(12 + digest.length); // struct size + sha256 size
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.put("FSVerity".getBytes(StandardCharsets.US_ASCII));
        buffer.putShort((short) 1); // FS_VERITY_HASH_ALG_SHA256
        buffer.putShort((short) digest.length);
        buffer.put(digest);
        return buffer.array();
    }

    private static native int enableFsverityNative(@NonNull String filePath,
            @NonNull byte[] pkcs7Signature);
    private static native int measureFsverityNative(@NonNull String filePath,
+1 −0
Original line number Diff line number Diff line
@@ -82,6 +82,7 @@ android_test {

    resource_dirs: ["res"],
    resource_zips: [":FrameworksCoreTests_apks_as_resources"],
    java_resources: [":ApkVerityTestCertDer"],

    data: [
        ":BstatsTestApp",
+672 B

File added.

No diff preview for this file type.

+46 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.security;

import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.operator.ContentSigner;

import java.io.OutputStream;

/** A wrapper class of ContentSigner */
class ContentSignerWrapper implements ContentSigner {
    private final ContentSigner mSigner;

    ContentSignerWrapper(ContentSigner wrapped) {
        mSigner = wrapped;
    }

    @Override
    public AlgorithmIdentifier getAlgorithmIdentifier() {
        return mSigner.getAlgorithmIdentifier();
    }

    @Override
    public OutputStream getOutputStream() {
        return mSigner.getOutputStream();
    }

    @Override
    public byte[] getSignature() {
        return mSigner.getSignature();
    }
}
Loading