Debian Codegraph @

core/java/com/android/internal/security/VerityUtils.java

raw symbols SCIP
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 com.android.internal.security;
18
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.os.Build;
22 import android.os.SystemProperties;
23 import android.system.Os;
24 import android.system.OsConstants;
25 import android.util.Slog;
26
27 import com.android.internal.annotations.VisibleForTesting;
28 import com.android.internal.org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
29 import com.android.internal.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
30 import com.android.internal.org.bouncycastle.cms.CMSException;
31 import com.android.internal.org.bouncycastle.cms.CMSProcessableByteArray;
32 import com.android.internal.org.bouncycastle.cms.CMSSignedData;
33 import com.android.internal.org.bouncycastle.cms.SignerInformation;
34 import com.android.internal.org.bouncycastle.cms.SignerInformationVerifier;
35 import com.android.internal.org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
36 import com.android.internal.org.bouncycastle.operator.OperatorCreationException;
37
38 import java.io.File;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.nio.ByteBuffer;
42 import java.nio.ByteOrder;
43 import java.nio.charset.StandardCharsets;
44 import java.nio.file.Files;
45 import java.nio.file.Path;
46 import java.nio.file.Paths;
47 import java.security.cert.CertificateException;
48 import java.security.cert.CertificateFactory;
49 import java.security.cert.X509Certificate;
50
51 /** Provides fsverity related operations. */
52 public abstract class VerityUtils {
53 private static final String TAG = "VerityUtils";
54
55 /**
56 * File extension of the signature file. For example, foo.apk.fsv_sig is the signature file of
57 * foo.apk.
58 */
59 public static final String FSVERITY_SIGNATURE_FILE_EXTENSION = ".fsv_sig";
60
61 /** The maximum size of signature file. This is just to avoid potential abuse. */
62 private static final int MAX_SIGNATURE_FILE_SIZE_BYTES = 8192;
63
64 /** SHA256 hash size. */
65 private static final int HASH_SIZE_BYTES = 32;
66
67 public static boolean isFsVeritySupported() {
68 return Build.VERSION.DEVICE_INITIAL_SDK_INT >= Build.VERSION_CODES.R
69 || SystemProperties.getInt("ro.apk_verity.mode", 0) == 2;
70 }
71
72 /** Returns true if the given file looks like containing an fs-verity signature. */
73 public static boolean isFsveritySignatureFile(File file) {
74 return file.getName().endsWith(FSVERITY_SIGNATURE_FILE_EXTENSION);
75 }
76
77 /** Returns the fs-verity signature file path of the given file. */
78 public static String getFsveritySignatureFilePath(String filePath) {
79 return filePath + FSVERITY_SIGNATURE_FILE_EXTENSION;
80 }
81
82 /** Enables fs-verity for the file with an optional PKCS#7 detached signature file. */
83 public static void setUpFsverity(@NonNull String filePath, @Nullable String signaturePath)
84 throws IOException {
85 byte[] rawSignature = null;
86 if (signaturePath != null) {
87 Path path = Paths.get(signaturePath);
88 if (Files.size(path) > MAX_SIGNATURE_FILE_SIZE_BYTES) {
89 throw new SecurityException("Signature file is unexpectedly large: "
90 + signaturePath);
91 }
92 rawSignature = Files.readAllBytes(path);
93 }
94 setUpFsverity(filePath, rawSignature);
95 }
96
97 /** Enables fs-verity for the file with an optional PKCS#7 detached signature bytes. */
98 public static void setUpFsverity(@NonNull String filePath, @Nullable byte[] pkcs7Signature)
99 throws IOException {
100 // This will fail if the public key is not already in .fs-verity kernel keyring.
101 int errno = enableFsverityNative(filePath, pkcs7Signature);
102 if (errno != 0) {
103 throw new IOException("Failed to enable fs-verity on " + filePath + ": "
104 + Os.strerror(errno));
105 }
106 }
107
108 /** Returns whether the file has fs-verity enabled. */
109 public static boolean hasFsverity(@NonNull String filePath) {
110 int retval = statxForFsverityNative(filePath);
111 if (retval < 0) {
112 Slog.e(TAG, "Failed to check whether fs-verity is enabled, errno " + -retval + ": "
113 + filePath);
114 return false;
115 }
116 return (retval == 1);
117 }
118
119 /**
120 * Verifies the signature over the fs-verity digest using the provided certificate.
121 *
122 * This method should only be used by any existing fs-verity use cases that require
123 * PKCS#7 signature verification, if backward compatibility is necessary.
124 *
125 * Since PKCS#7 is too flexible, for the current specific need, only specific configuration
126 * will be accepted:
127 * <ul>
128 * <li>Must use SHA256 as the digest algorithm
129 * <li>Must use rsaEncryption as signature algorithm
130 * <li>Must be detached / without content
131 * <li>Must not include any signed or unsigned attributes
132 * </ul>
133 *
134 * It is up to the caller to provide an appropriate/trusted certificate.
135 *
136 * @param signatureBlock byte array of a PKCS#7 detached signature
137 * @param digest fs-verity digest with the common configuration using sha256
138 * @param derCertInputStream an input stream of a X.509 certificate in DER
139 * @return whether the verification succeeds
140 */
141 public static boolean verifyPkcs7DetachedSignature(@NonNull byte[] signatureBlock,
142 @NonNull byte[] digest, @NonNull InputStream derCertInputStream) {
143 if (digest.length != 32) {
144 Slog.w(TAG, "Only sha256 is currently supported");
145 return false;
146 }
147
148 try {
149 CMSSignedData signedData = new CMSSignedData(
150 new CMSProcessableByteArray(toFormattedDigest(digest)),
151 signatureBlock);
152
153 if (!signedData.isDetachedSignature()) {
154 Slog.w(TAG, "Expect only detached siganture");
155 return false;
156 }
157 if (!signedData.getCertificates().getMatches(null).isEmpty()) {
158 Slog.w(TAG, "Expect no certificate in signature");
159 return false;
160 }
161 if (!signedData.getCRLs().getMatches(null).isEmpty()) {
162 Slog.w(TAG, "Expect no CRL in signature");
163 return false;
164 }
165
166 X509Certificate trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
167 .generateCertificate(derCertInputStream);
168 SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder()
169 .build(trustedCert);
170
171 // Verify any signature with the trusted certificate.
172 for (SignerInformation si : signedData.getSignerInfos().getSigners()) {
173 // To be the most strict while dealing with the complicated PKCS#7 signature, reject
174 // everything we don't need.
175 if (si.getSignedAttributes() != null && si.getSignedAttributes().size() > 0) {
176 Slog.w(TAG, "Unexpected signed attributes");
177 return false;
178 }
179 if (si.getUnsignedAttributes() != null && si.getUnsignedAttributes().size() > 0) {
180 Slog.w(TAG, "Unexpected unsigned attributes");
181 return false;
182 }
183 if (!NISTObjectIdentifiers.id_sha256.getId().equals(si.getDigestAlgOID())) {
184 Slog.w(TAG, "Unsupported digest algorithm OID: " + si.getDigestAlgOID());
185 return false;
186 }
187 if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(si.getEncryptionAlgOID())) {
188 Slog.w(TAG, "Unsupported encryption algorithm OID: "
189 + si.getEncryptionAlgOID());
190 return false;
191 }
192
193 if (si.verify(verifier)) {
194 return true;
195 }
196 }
197 return false;
198 } catch (CertificateException | CMSException | OperatorCreationException e) {
199 Slog.w(TAG, "Error occurred during the PKCS#7 signature verification", e);
200 }
201 return false;
202 }
203
204 /**
205 * Returns fs-verity digest for the file if enabled, otherwise returns null. The digest is a
206 * hash of root hash of fs-verity's Merkle tree with extra metadata.
207 *
208 * @see <a href="https://www.kernel.org/doc/html/latest/filesystems/fsverity.html#file-digest-computation">
209 * File digest computation in Linux kernel documentation</a>
210 * @return Bytes of fs-verity digest
211 */
212 public static byte[] getFsverityDigest(@NonNull String filePath) {
213 byte[] result = new byte[HASH_SIZE_BYTES];
214 int retval = measureFsverityNative(filePath, result);
215 if (retval < 0) {
216 if (retval != -OsConstants.ENODATA) {
217 Slog.e(TAG, "Failed to measure fs-verity, errno " + -retval + ": " + filePath);
218 }
219 return null;
220 }
221 return result;
222 }
223
224 /** @hide */
225 @VisibleForTesting
226 public static byte[] toFormattedDigest(byte[] digest) {
227 // Construct fsverity_formatted_digest used in fs-verity's built-in signature verification.
228 ByteBuffer buffer = ByteBuffer.allocate(12 + digest.length); // struct size + sha256 size
229 buffer.order(ByteOrder.LITTLE_ENDIAN);
230 buffer.put("FSVerity".getBytes(StandardCharsets.US_ASCII));
231 buffer.putShort((short) 1); // FS_VERITY_HASH_ALG_SHA256
232 buffer.putShort((short) digest.length);
233 buffer.put(digest);
234 return buffer.array();
235 }
236
237 private static native int enableFsverityNative(@NonNull String filePath,
238 @Nullable byte[] pkcs7Signature);
239 private static native int measureFsverityNative(@NonNull String filePath,
240 @NonNull byte[] digest);
241 private static native int statxForFsverityNative(@NonNull String filePath);
242 }