blob: 0b9552e6afa9baa450ec44ba19e9fed6a75b1000 [file] [log] [blame]
Victor Hsieh3271d042017-10-24 15:46:32 -07001/*
2 * Copyright (C) 2017 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
17package android.util.apk;
18
19import java.io.IOException;
20import java.io.RandomAccessFile;
21import java.nio.ByteBuffer;
22import java.nio.ByteOrder;
23import java.security.MessageDigest;
24import java.security.NoSuchAlgorithmException;
25import java.util.ArrayList;
26
27/**
28 * ApkVerityBuilder builds the APK verity tree and the verity header, which will be used by the
29 * kernel to verity the APK content on access.
30 *
31 * <p>Unlike a regular Merkle tree, APK verity tree does not cover the content fully. Due to
32 * the existing APK format, it has to skip APK Signing Block and also has some special treatment for
33 * the "Central Directory offset" field of ZIP End of Central Directory.
34 *
35 * @hide
36 */
37abstract class ApkVerityBuilder {
38 private ApkVerityBuilder() {}
39
40 private static final int CHUNK_SIZE_BYTES = 4096; // Typical Linux block size
41 private static final int DIGEST_SIZE_BYTES = 32; // SHA-256 size
42 private static final int FSVERITY_HEADER_SIZE_BYTES = 64;
43 private static final int ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE = 4;
44 private static final int ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET = 16;
45 private static final String JCA_DIGEST_ALGORITHM = "SHA-256";
46 private static final byte[] DEFAULT_SALT = new byte[8];
47
48 static class ApkVerityResult {
49 public final ByteBuffer fsverityData;
50 public final byte[] rootHash;
51
52 ApkVerityResult(ByteBuffer fsverityData, byte[] rootHash) {
53 this.fsverityData = fsverityData;
54 this.rootHash = rootHash;
55 }
56 }
57
58 /**
59 * Generates fsverity metadata and the Merkle tree into the {@link ByteBuffer} created by the
60 * {@link ByteBufferFactory}. The bytes layout in the buffer will be used by the kernel and is
61 * ready to be appended to the target file to set up fsverity. For fsverity to work, this data
62 * must be placed at the next page boundary, and the caller must add additional padding in that
63 * case.
64 *
65 * @return ApkVerityResult containing the fsverity data and the root hash of the Merkle tree.
66 */
67 static ApkVerityResult generateApkVerity(RandomAccessFile apk,
68 SignatureInfo signatureInfo, ByteBufferFactory bufferFactory)
69 throws IOException, SecurityException, NoSuchAlgorithmException {
70 assertSigningBlockAlignedAndHasFullPages(signatureInfo);
71
72 long signingBlockSize =
73 signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset;
74 long dataSize = apk.length() - signingBlockSize - ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE;
75 int[] levelOffset = calculateVerityLevelOffset(dataSize);
76 ByteBuffer output = bufferFactory.create(
77 CHUNK_SIZE_BYTES + // fsverity header + extensions + padding
78 levelOffset[levelOffset.length - 1] + // Merkle tree size
79 FSVERITY_HEADER_SIZE_BYTES); // second fsverity header (verbatim copy)
80
81 // Start generating the tree from the block boundary as the kernel will expect.
82 ByteBuffer treeOutput = slice(output, CHUNK_SIZE_BYTES,
83 output.limit() - FSVERITY_HEADER_SIZE_BYTES);
84 byte[] rootHash = generateApkVerityTree(apk, signatureInfo, DEFAULT_SALT, levelOffset,
85 treeOutput);
86
87 ByteBuffer integrityHeader = generateFsverityHeader(apk.length(), DEFAULT_SALT);
88 output.put(integrityHeader);
89 output.put(generateFsverityExtensions());
90
91 integrityHeader.rewind();
92 output.put(integrityHeader);
93 output.rewind();
94 return new ApkVerityResult(output, rootHash);
95 }
96
97 /**
98 * A helper class to consume and digest data by block continuously, and write into a buffer.
99 */
100 private static class BufferedDigester implements DataDigester {
101 /** Amount of the data to digest in each cycle before writting out the digest. */
102 private static final int BUFFER_SIZE = CHUNK_SIZE_BYTES;
103
104 /**
105 * Amount of data the {@link MessageDigest} has consumed since the last reset. This must be
106 * always less than BUFFER_SIZE since {@link MessageDigest} is reset whenever it has
107 * consumed BUFFER_SIZE of data.
108 */
109 private int mBytesDigestedSinceReset;
110
111 /** The final output {@link ByteBuffer} to write the digest to sequentially. */
112 private final ByteBuffer mOutput;
113
114 private final MessageDigest mMd;
115 private final byte[] mSalt;
116
117 private BufferedDigester(byte[] salt, ByteBuffer output) throws NoSuchAlgorithmException {
118 mSalt = salt;
119 mOutput = output.slice();
120 mMd = MessageDigest.getInstance(JCA_DIGEST_ALGORITHM);
121 mMd.update(mSalt);
122 mBytesDigestedSinceReset = 0;
123 }
124
125 /**
126 * Consumes and digests data up to BUFFER_SIZE (may continue from the previous remaining),
127 * then writes the final digest to the output buffer. Repeat until all data are consumed.
128 * If the last consumption is not enough for BUFFER_SIZE, the state will stay and future
129 * consumption will continuous from there.
130 */
131 @Override
132 public void consume(ByteBuffer buffer) {
133 int offset = buffer.position();
134 int remaining = buffer.remaining();
135 while (remaining > 0) {
136 int allowance = (int) Math.min(remaining, BUFFER_SIZE - mBytesDigestedSinceReset);
137 mMd.update(slice(buffer, offset, offset + allowance));
138 offset += allowance;
139 remaining -= allowance;
140 mBytesDigestedSinceReset += allowance;
141
142 if (mBytesDigestedSinceReset == BUFFER_SIZE) {
143 byte[] digest = mMd.digest();
144 mOutput.put(digest);
145
146 mMd.reset();
147 mMd.update(mSalt);
148 mBytesDigestedSinceReset = 0;
149 }
150 }
151 }
152
153 /** Finish the current digestion if any. */
154 @Override
155 public void finish() {
156 if (mBytesDigestedSinceReset == 0) {
157 return;
158 }
159 byte[] digest = mMd.digest();
160 mOutput.put(digest);
161 }
162
163 private void fillUpLastOutputChunk() {
164 int extra = (int) (BUFFER_SIZE - mOutput.position() % BUFFER_SIZE);
165 if (extra == 0) {
166 return;
167 }
168 mOutput.put(ByteBuffer.allocate(extra));
169 }
170 }
171
172 /**
173 * Digest the source by chunk in the given range. If the last chunk is not a full chunk,
174 * digest the remaining.
175 */
176 private static void consumeByChunk(DataDigester digester, DataSource source, int chunkSize)
177 throws IOException {
178 long inputRemaining = source.size();
179 long inputOffset = 0;
180 while (inputRemaining > 0) {
181 int size = (int) Math.min(inputRemaining, chunkSize);
182 source.feedIntoDataDigester(digester, inputOffset, size);
183 inputOffset += size;
184 inputRemaining -= size;
185 }
186 }
187
188 // Rationale: 1) 1 MB should fit in memory space on all devices. 2) It is not too granular
189 // thus the syscall overhead is not too big.
190 private static final int MMAP_REGION_SIZE_BYTES = 1024 * 1024;
191
192 private static void generateApkVerityDigestAtLeafLevel(RandomAccessFile apk,
193 SignatureInfo signatureInfo, byte[] salt, ByteBuffer output)
194 throws IOException, NoSuchAlgorithmException {
195 BufferedDigester digester = new BufferedDigester(salt, output);
196
197 // 1. Digest from the beginning of the file, until APK Signing Block is reached.
198 consumeByChunk(digester,
199 new MemoryMappedFileDataSource(apk.getFD(), 0, signatureInfo.apkSigningBlockOffset),
200 MMAP_REGION_SIZE_BYTES);
201
202 // 2. Skip APK Signing Block and continue digesting, until the Central Directory offset
203 // field in EoCD is reached.
204 long eocdCdOffsetFieldPosition =
205 signatureInfo.eocdOffset + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET;
206 consumeByChunk(digester,
207 new MemoryMappedFileDataSource(apk.getFD(), signatureInfo.centralDirOffset,
208 eocdCdOffsetFieldPosition - signatureInfo.centralDirOffset),
209 MMAP_REGION_SIZE_BYTES);
210
211 // 3. Fill up the rest of buffer with 0s.
212 ByteBuffer alternativeCentralDirOffset = ByteBuffer.allocate(
213 ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE).order(ByteOrder.LITTLE_ENDIAN);
214 alternativeCentralDirOffset.putInt(Math.toIntExact(signatureInfo.apkSigningBlockOffset));
215 alternativeCentralDirOffset.flip();
216 digester.consume(alternativeCentralDirOffset);
217
218 // 4. Read from end of the Central Directory offset field in EoCD to the end of the file.
219 long offsetAfterEocdCdOffsetField =
220 eocdCdOffsetFieldPosition + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE;
221 consumeByChunk(digester,
222 new MemoryMappedFileDataSource(apk.getFD(), offsetAfterEocdCdOffsetField,
223 apk.length() - offsetAfterEocdCdOffsetField),
224 MMAP_REGION_SIZE_BYTES);
225 digester.finish();
226
227 // 5. Fill up the rest of buffer with 0s.
228 digester.fillUpLastOutputChunk();
229 }
230
231 private static byte[] generateApkVerityTree(RandomAccessFile apk, SignatureInfo signatureInfo,
232 byte[] salt, int[] levelOffset, ByteBuffer output)
233 throws IOException, NoSuchAlgorithmException {
234 // 1. Digest the apk to generate the leaf level hashes.
235 generateApkVerityDigestAtLeafLevel(apk, signatureInfo, salt, slice(output,
236 levelOffset[levelOffset.length - 2], levelOffset[levelOffset.length - 1]));
237
238 // 2. Digest the lower level hashes bottom up.
239 for (int level = levelOffset.length - 3; level >= 0; level--) {
240 ByteBuffer inputBuffer = slice(output, levelOffset[level + 1], levelOffset[level + 2]);
241 ByteBuffer outputBuffer = slice(output, levelOffset[level], levelOffset[level + 1]);
242
243 DataSource source = new ByteBufferDataSource(inputBuffer);
244 BufferedDigester digester = new BufferedDigester(salt, outputBuffer);
245 consumeByChunk(digester, source, CHUNK_SIZE_BYTES);
246 digester.finish();
247
248 digester.fillUpLastOutputChunk();
249 }
250
251 // 3. Digest the first block (i.e. first level) to generate the root hash.
252 byte[] rootHash = new byte[DIGEST_SIZE_BYTES];
253 BufferedDigester digester = new BufferedDigester(salt, ByteBuffer.wrap(rootHash));
254 digester.consume(slice(output, 0, CHUNK_SIZE_BYTES));
255 return rootHash;
256 }
257
258 private static ByteBuffer generateFsverityHeader(long fileSize, byte[] salt) {
259 if (salt.length != 8) {
260 throw new IllegalArgumentException("salt is not 8 bytes long");
261 }
262
263 ByteBuffer buffer = ByteBuffer.allocate(FSVERITY_HEADER_SIZE_BYTES);
264 buffer.order(ByteOrder.LITTLE_ENDIAN);
265
266 // TODO(b/30972906): insert a reference when there is a public one.
267 buffer.put("TrueBrew".getBytes()); // magic
268 buffer.put((byte) 1); // major version
269 buffer.put((byte) 0); // minor version
270 buffer.put((byte) 12); // log2(block-size) == log2(4096)
271 buffer.put((byte) 7); // log2(leaves-per-node) == log2(block-size / digest-size)
272 // == log2(4096 / 32)
273 buffer.putShort((short) 1); // meta algorithm, 1: SHA-256 FIXME finalize constant
274 buffer.putShort((short) 1); // data algorithm, 1: SHA-256 FIXME finalize constant
275 buffer.putInt(0x1); // flags, 0x1: has extension, FIXME also hide it
276 buffer.putInt(0); // reserved
277 buffer.putLong(fileSize); // original i_size
278 buffer.put(salt); // salt (8 bytes)
279
280 // TODO(b/30972906): Add extension.
281
282 buffer.rewind();
283 return buffer;
284 }
285
286 private static ByteBuffer generateFsverityExtensions() {
287 return ByteBuffer.allocate(64); // TODO(b/30972906): implement this.
288 }
289
290 /**
291 * Returns an array of summed area table of level size in the verity tree. In other words, the
292 * returned array is offset of each level in the verity tree file format, plus an additional
293 * offset of the next non-existing level (i.e. end of the last level + 1). Thus the array size
294 * is level + 1. Thus, the returned array is guarantee to have at least 2 elements.
295 */
296 private static int[] calculateVerityLevelOffset(long fileSize) {
297 ArrayList<Long> levelSize = new ArrayList<>();
298 while (true) {
299 long levelDigestSize = divideRoundup(fileSize, CHUNK_SIZE_BYTES) * DIGEST_SIZE_BYTES;
300 long chunksSize = CHUNK_SIZE_BYTES * divideRoundup(levelDigestSize, CHUNK_SIZE_BYTES);
301 levelSize.add(chunksSize);
302 if (levelDigestSize <= CHUNK_SIZE_BYTES) {
303 break;
304 }
305 fileSize = levelDigestSize;
306 }
307
308 // Reverse and convert to summed area table.
309 int[] levelOffset = new int[levelSize.size() + 1];
310 levelOffset[0] = 0;
311 for (int i = 0; i < levelSize.size(); i++) {
312 // We don't support verity tree if it is larger then Integer.MAX_VALUE.
313 levelOffset[i + 1] = levelOffset[i]
314 + Math.toIntExact(levelSize.get(levelSize.size() - i - 1));
315 }
316 return levelOffset;
317 }
318
319 private static void assertSigningBlockAlignedAndHasFullPages(SignatureInfo signatureInfo) {
320 if (signatureInfo.apkSigningBlockOffset % CHUNK_SIZE_BYTES != 0) {
321 throw new IllegalArgumentException(
322 "APK Signing Block does not start at the page boundary: "
323 + signatureInfo.apkSigningBlockOffset);
324 }
325
326 if ((signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset)
327 % CHUNK_SIZE_BYTES != 0) {
328 throw new IllegalArgumentException(
329 "Size of APK Signing Block is not a multiple of 4096: "
330 + (signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset));
331 }
332 }
333
334 /** Returns a slice of the buffer which shares content with the provided buffer. */
335 private static ByteBuffer slice(ByteBuffer buffer, int begin, int end) {
336 ByteBuffer b = buffer.duplicate();
337 b.position(0); // to ensure position <= limit invariant.
338 b.limit(end);
339 b.position(begin);
340 return b.slice();
341 }
342
343 /** Divides a number and round up to the closest integer. */
344 private static long divideRoundup(long dividend, long divisor) {
345 return (dividend + divisor - 1) / divisor;
346 }
347}