blob: 7b899676d76730dd3d6737187aa31f2579e5508e [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;
Victor Hsiehdef64f22017-11-08 10:25:11 -080023import java.security.DigestException;
Victor Hsieh3271d042017-10-24 15:46:32 -070024import java.security.MessageDigest;
25import java.security.NoSuchAlgorithmException;
26import java.util.ArrayList;
27
28/**
29 * ApkVerityBuilder builds the APK verity tree and the verity header, which will be used by the
30 * kernel to verity the APK content on access.
31 *
32 * <p>Unlike a regular Merkle tree, APK verity tree does not cover the content fully. Due to
33 * the existing APK format, it has to skip APK Signing Block and also has some special treatment for
34 * the "Central Directory offset" field of ZIP End of Central Directory.
35 *
36 * @hide
37 */
38abstract class ApkVerityBuilder {
39 private ApkVerityBuilder() {}
40
41 private static final int CHUNK_SIZE_BYTES = 4096; // Typical Linux block size
42 private static final int DIGEST_SIZE_BYTES = 32; // SHA-256 size
43 private static final int FSVERITY_HEADER_SIZE_BYTES = 64;
44 private static final int ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE = 4;
45 private static final int ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET = 16;
46 private static final String JCA_DIGEST_ALGORITHM = "SHA-256";
47 private static final byte[] DEFAULT_SALT = new byte[8];
48
49 static class ApkVerityResult {
50 public final ByteBuffer fsverityData;
51 public final byte[] rootHash;
52
53 ApkVerityResult(ByteBuffer fsverityData, byte[] rootHash) {
54 this.fsverityData = fsverityData;
55 this.rootHash = rootHash;
56 }
57 }
58
59 /**
60 * Generates fsverity metadata and the Merkle tree into the {@link ByteBuffer} created by the
61 * {@link ByteBufferFactory}. The bytes layout in the buffer will be used by the kernel and is
62 * ready to be appended to the target file to set up fsverity. For fsverity to work, this data
63 * must be placed at the next page boundary, and the caller must add additional padding in that
64 * case.
65 *
66 * @return ApkVerityResult containing the fsverity data and the root hash of the Merkle tree.
67 */
68 static ApkVerityResult generateApkVerity(RandomAccessFile apk,
69 SignatureInfo signatureInfo, ByteBufferFactory bufferFactory)
Victor Hsiehdef64f22017-11-08 10:25:11 -080070 throws IOException, SecurityException, NoSuchAlgorithmException, DigestException {
Victor Hsieh3051d782018-01-12 08:28:03 -080071 long signingBlockSize =
72 signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset;
Victor Hsiehd48e9542018-01-24 12:06:43 -080073 long dataSize = apk.length() - signingBlockSize;
Victor Hsieh3051d782018-01-12 08:28:03 -080074 int[] levelOffset = calculateVerityLevelOffset(dataSize);
75
76 ByteBuffer output = bufferFactory.create(
77 CHUNK_SIZE_BYTES + // fsverity header + extensions + padding
78 levelOffset[levelOffset.length - 1]); // Merkle tree size
79 output.order(ByteOrder.LITTLE_ENDIAN);
80
81 ByteBuffer header = slice(output, 0, FSVERITY_HEADER_SIZE_BYTES);
82 ByteBuffer extensions = slice(output, FSVERITY_HEADER_SIZE_BYTES, CHUNK_SIZE_BYTES);
83 ByteBuffer tree = slice(output, CHUNK_SIZE_BYTES, output.limit());
84 byte[] apkDigestBytes = new byte[DIGEST_SIZE_BYTES];
85 ByteBuffer apkDigest = ByteBuffer.wrap(apkDigestBytes);
86 apkDigest.order(ByteOrder.LITTLE_ENDIAN);
87
88 calculateFsveritySignatureInternal(apk, signatureInfo, tree, apkDigest, header, extensions);
89
90 output.rewind();
91 return new ApkVerityResult(output, apkDigestBytes);
92 }
93
94 /**
95 * Calculates the fsverity root hash for integrity measurement. This needs to be consistent to
96 * what kernel returns.
97 */
98 static byte[] generateFsverityRootHash(RandomAccessFile apk, ByteBuffer apkDigest,
99 SignatureInfo signatureInfo)
100 throws NoSuchAlgorithmException, DigestException, IOException {
101 ByteBuffer verityBlock = ByteBuffer.allocate(CHUNK_SIZE_BYTES)
102 .order(ByteOrder.LITTLE_ENDIAN);
103 ByteBuffer header = slice(verityBlock, 0, FSVERITY_HEADER_SIZE_BYTES);
104 ByteBuffer extensions = slice(verityBlock, FSVERITY_HEADER_SIZE_BYTES, CHUNK_SIZE_BYTES);
105
106 calculateFsveritySignatureInternal(apk, signatureInfo, null, null, header, extensions);
107
108 MessageDigest md = MessageDigest.getInstance(JCA_DIGEST_ALGORITHM);
Victor Hsieh21203232018-01-29 15:10:56 -0800109 md.update(header);
110 md.update(extensions);
Victor Hsieh3051d782018-01-12 08:28:03 -0800111 md.update(apkDigest);
112 return md.digest();
113 }
114
Victor Hsieh21203232018-01-29 15:10:56 -0800115 /**
116 * Internal method to generate various parts of FSVerity constructs, including the header,
117 * extensions, Merkle tree, and the tree's root hash. The output buffer is flipped to the
118 * generated data size and is readey for consuming.
119 */
Victor Hsieh3051d782018-01-12 08:28:03 -0800120 private static void calculateFsveritySignatureInternal(
121 RandomAccessFile apk, SignatureInfo signatureInfo, ByteBuffer treeOutput,
122 ByteBuffer rootHashOutput, ByteBuffer headerOutput, ByteBuffer extensionsOutput)
123 throws IOException, NoSuchAlgorithmException, DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700124 assertSigningBlockAlignedAndHasFullPages(signatureInfo);
Victor Hsieh3271d042017-10-24 15:46:32 -0700125 long signingBlockSize =
126 signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset;
127 long dataSize = apk.length() - signingBlockSize - ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE;
128 int[] levelOffset = calculateVerityLevelOffset(dataSize);
Victor Hsieh3271d042017-10-24 15:46:32 -0700129
Victor Hsieh3051d782018-01-12 08:28:03 -0800130 if (treeOutput != null) {
131 byte[] apkRootHash = generateApkVerityTree(apk, signatureInfo, DEFAULT_SALT,
132 levelOffset, treeOutput);
133 if (rootHashOutput != null) {
134 rootHashOutput.put(apkRootHash);
Victor Hsieh21203232018-01-29 15:10:56 -0800135 rootHashOutput.flip();
Victor Hsieh3051d782018-01-12 08:28:03 -0800136 }
137 }
Victor Hsieh3271d042017-10-24 15:46:32 -0700138
Victor Hsieh3051d782018-01-12 08:28:03 -0800139 if (headerOutput != null) {
Victor Hsiehd48e9542018-01-24 12:06:43 -0800140 headerOutput.order(ByteOrder.LITTLE_ENDIAN);
Victor Hsieh3051d782018-01-12 08:28:03 -0800141 generateFsverityHeader(headerOutput, apk.length(), levelOffset.length - 1,
142 DEFAULT_SALT);
143 }
Victor Hsieh3271d042017-10-24 15:46:32 -0700144
Victor Hsieh3051d782018-01-12 08:28:03 -0800145 if (extensionsOutput != null) {
Victor Hsiehd48e9542018-01-24 12:06:43 -0800146 extensionsOutput.order(ByteOrder.LITTLE_ENDIAN);
Victor Hsieh3051d782018-01-12 08:28:03 -0800147 generateFsverityExtensions(extensionsOutput, signatureInfo.apkSigningBlockOffset,
148 signingBlockSize, signatureInfo.eocdOffset);
149 }
Victor Hsieh3271d042017-10-24 15:46:32 -0700150 }
151
152 /**
153 * A helper class to consume and digest data by block continuously, and write into a buffer.
154 */
155 private static class BufferedDigester implements DataDigester {
156 /** Amount of the data to digest in each cycle before writting out the digest. */
157 private static final int BUFFER_SIZE = CHUNK_SIZE_BYTES;
158
159 /**
160 * Amount of data the {@link MessageDigest} has consumed since the last reset. This must be
161 * always less than BUFFER_SIZE since {@link MessageDigest} is reset whenever it has
162 * consumed BUFFER_SIZE of data.
163 */
164 private int mBytesDigestedSinceReset;
165
166 /** The final output {@link ByteBuffer} to write the digest to sequentially. */
167 private final ByteBuffer mOutput;
168
169 private final MessageDigest mMd;
Victor Hsiehdef64f22017-11-08 10:25:11 -0800170 private final byte[] mDigestBuffer = new byte[DIGEST_SIZE_BYTES];
Victor Hsieh3271d042017-10-24 15:46:32 -0700171 private final byte[] mSalt;
172
173 private BufferedDigester(byte[] salt, ByteBuffer output) throws NoSuchAlgorithmException {
174 mSalt = salt;
175 mOutput = output.slice();
176 mMd = MessageDigest.getInstance(JCA_DIGEST_ALGORITHM);
177 mMd.update(mSalt);
178 mBytesDigestedSinceReset = 0;
179 }
180
181 /**
182 * Consumes and digests data up to BUFFER_SIZE (may continue from the previous remaining),
183 * then writes the final digest to the output buffer. Repeat until all data are consumed.
184 * If the last consumption is not enough for BUFFER_SIZE, the state will stay and future
185 * consumption will continuous from there.
186 */
187 @Override
Victor Hsiehdef64f22017-11-08 10:25:11 -0800188 public void consume(ByteBuffer buffer) throws DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700189 int offset = buffer.position();
190 int remaining = buffer.remaining();
191 while (remaining > 0) {
192 int allowance = (int) Math.min(remaining, BUFFER_SIZE - mBytesDigestedSinceReset);
Victor Hsiehdef64f22017-11-08 10:25:11 -0800193 // Optimization: set the buffer limit to avoid allocating a new ByteBuffer object.
194 buffer.limit(buffer.position() + allowance);
195 mMd.update(buffer);
Victor Hsieh3271d042017-10-24 15:46:32 -0700196 offset += allowance;
197 remaining -= allowance;
198 mBytesDigestedSinceReset += allowance;
199
200 if (mBytesDigestedSinceReset == BUFFER_SIZE) {
Victor Hsiehdef64f22017-11-08 10:25:11 -0800201 mMd.digest(mDigestBuffer, 0, mDigestBuffer.length);
202 mOutput.put(mDigestBuffer);
203 // After digest, MessageDigest resets automatically, so no need to reset again.
Victor Hsieh3271d042017-10-24 15:46:32 -0700204 mMd.update(mSalt);
205 mBytesDigestedSinceReset = 0;
206 }
207 }
208 }
209
Victor Hsieh3a0032f2018-02-20 15:22:28 -0800210 public void assertEmptyBuffer() throws DigestException {
211 if (mBytesDigestedSinceReset != 0) {
212 throw new IllegalStateException("Buffer is not empty: " + mBytesDigestedSinceReset);
Victor Hsieh3271d042017-10-24 15:46:32 -0700213 }
Victor Hsieh3271d042017-10-24 15:46:32 -0700214 }
215
216 private void fillUpLastOutputChunk() {
Victor Hsiehb62a64e2018-01-19 12:46:23 -0800217 int lastBlockSize = (int) (mOutput.position() % BUFFER_SIZE);
218 if (lastBlockSize == 0) {
Victor Hsieh3271d042017-10-24 15:46:32 -0700219 return;
220 }
Victor Hsiehb62a64e2018-01-19 12:46:23 -0800221 mOutput.put(ByteBuffer.allocate(BUFFER_SIZE - lastBlockSize));
Victor Hsieh3271d042017-10-24 15:46:32 -0700222 }
223 }
224
225 /**
226 * Digest the source by chunk in the given range. If the last chunk is not a full chunk,
227 * digest the remaining.
228 */
229 private static void consumeByChunk(DataDigester digester, DataSource source, int chunkSize)
Victor Hsiehdef64f22017-11-08 10:25:11 -0800230 throws IOException, DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700231 long inputRemaining = source.size();
232 long inputOffset = 0;
233 while (inputRemaining > 0) {
234 int size = (int) Math.min(inputRemaining, chunkSize);
235 source.feedIntoDataDigester(digester, inputOffset, size);
236 inputOffset += size;
237 inputRemaining -= size;
238 }
239 }
240
241 // Rationale: 1) 1 MB should fit in memory space on all devices. 2) It is not too granular
242 // thus the syscall overhead is not too big.
243 private static final int MMAP_REGION_SIZE_BYTES = 1024 * 1024;
244
245 private static void generateApkVerityDigestAtLeafLevel(RandomAccessFile apk,
246 SignatureInfo signatureInfo, byte[] salt, ByteBuffer output)
Victor Hsiehdef64f22017-11-08 10:25:11 -0800247 throws IOException, NoSuchAlgorithmException, DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700248 BufferedDigester digester = new BufferedDigester(salt, output);
249
250 // 1. Digest from the beginning of the file, until APK Signing Block is reached.
251 consumeByChunk(digester,
252 new MemoryMappedFileDataSource(apk.getFD(), 0, signatureInfo.apkSigningBlockOffset),
253 MMAP_REGION_SIZE_BYTES);
254
255 // 2. Skip APK Signing Block and continue digesting, until the Central Directory offset
256 // field in EoCD is reached.
257 long eocdCdOffsetFieldPosition =
258 signatureInfo.eocdOffset + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET;
259 consumeByChunk(digester,
260 new MemoryMappedFileDataSource(apk.getFD(), signatureInfo.centralDirOffset,
261 eocdCdOffsetFieldPosition - signatureInfo.centralDirOffset),
262 MMAP_REGION_SIZE_BYTES);
263
Victor Hsieh3051d782018-01-12 08:28:03 -0800264 // 3. Consume offset of Signing Block as an alternative EoCD.
Victor Hsieh3271d042017-10-24 15:46:32 -0700265 ByteBuffer alternativeCentralDirOffset = ByteBuffer.allocate(
266 ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE).order(ByteOrder.LITTLE_ENDIAN);
267 alternativeCentralDirOffset.putInt(Math.toIntExact(signatureInfo.apkSigningBlockOffset));
268 alternativeCentralDirOffset.flip();
269 digester.consume(alternativeCentralDirOffset);
270
271 // 4. Read from end of the Central Directory offset field in EoCD to the end of the file.
272 long offsetAfterEocdCdOffsetField =
273 eocdCdOffsetFieldPosition + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE;
274 consumeByChunk(digester,
275 new MemoryMappedFileDataSource(apk.getFD(), offsetAfterEocdCdOffsetField,
276 apk.length() - offsetAfterEocdCdOffsetField),
277 MMAP_REGION_SIZE_BYTES);
Victor Hsieh3271d042017-10-24 15:46:32 -0700278
Victor Hsieh3a0032f2018-02-20 15:22:28 -0800279 // 5. Pad 0s up to the nearest 4096-byte block before hashing.
280 int lastIncompleteChunkSize = (int) (apk.length() % CHUNK_SIZE_BYTES);
281 if (lastIncompleteChunkSize != 0) {
282 digester.consume(ByteBuffer.allocate(CHUNK_SIZE_BYTES - lastIncompleteChunkSize));
283 }
284 digester.assertEmptyBuffer();
285
286 // 6. Fill up the rest of buffer with 0s.
Victor Hsieh3271d042017-10-24 15:46:32 -0700287 digester.fillUpLastOutputChunk();
288 }
289
290 private static byte[] generateApkVerityTree(RandomAccessFile apk, SignatureInfo signatureInfo,
291 byte[] salt, int[] levelOffset, ByteBuffer output)
Victor Hsiehdef64f22017-11-08 10:25:11 -0800292 throws IOException, NoSuchAlgorithmException, DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700293 // 1. Digest the apk to generate the leaf level hashes.
294 generateApkVerityDigestAtLeafLevel(apk, signatureInfo, salt, slice(output,
295 levelOffset[levelOffset.length - 2], levelOffset[levelOffset.length - 1]));
296
297 // 2. Digest the lower level hashes bottom up.
298 for (int level = levelOffset.length - 3; level >= 0; level--) {
299 ByteBuffer inputBuffer = slice(output, levelOffset[level + 1], levelOffset[level + 2]);
300 ByteBuffer outputBuffer = slice(output, levelOffset[level], levelOffset[level + 1]);
301
302 DataSource source = new ByteBufferDataSource(inputBuffer);
303 BufferedDigester digester = new BufferedDigester(salt, outputBuffer);
304 consumeByChunk(digester, source, CHUNK_SIZE_BYTES);
Victor Hsieh3a0032f2018-02-20 15:22:28 -0800305 digester.assertEmptyBuffer();
Victor Hsieh3271d042017-10-24 15:46:32 -0700306 digester.fillUpLastOutputChunk();
307 }
308
309 // 3. Digest the first block (i.e. first level) to generate the root hash.
310 byte[] rootHash = new byte[DIGEST_SIZE_BYTES];
311 BufferedDigester digester = new BufferedDigester(salt, ByteBuffer.wrap(rootHash));
312 digester.consume(slice(output, 0, CHUNK_SIZE_BYTES));
Victor Hsieh3a0032f2018-02-20 15:22:28 -0800313 digester.assertEmptyBuffer();
Victor Hsieh3271d042017-10-24 15:46:32 -0700314 return rootHash;
315 }
316
Victor Hsieh3051d782018-01-12 08:28:03 -0800317 private static ByteBuffer generateFsverityHeader(ByteBuffer buffer, long fileSize, int depth,
318 byte[] salt) {
Victor Hsieh3271d042017-10-24 15:46:32 -0700319 if (salt.length != 8) {
320 throw new IllegalArgumentException("salt is not 8 bytes long");
321 }
322
Victor Hsieh3051d782018-01-12 08:28:03 -0800323 // TODO(b/30972906): update the reference when there is a better one in public.
Victor Hsieh3271d042017-10-24 15:46:32 -0700324 buffer.put("TrueBrew".getBytes()); // magic
Victor Hsieh3051d782018-01-12 08:28:03 -0800325
Victor Hsieh2c8fbd62018-01-25 16:08:58 -0800326 buffer.put((byte) 1); // major version
327 buffer.put((byte) 0); // minor version
328 buffer.put((byte) 12); // log2(block-size): log2(4096)
329 buffer.put((byte) 7); // log2(leaves-per-node): log2(4096 / 32)
Victor Hsieh3271d042017-10-24 15:46:32 -0700330
Victor Hsiehd48e9542018-01-24 12:06:43 -0800331 buffer.putShort((short) 1); // meta algorithm, SHA256_MODE == 1
332 buffer.putShort((short) 1); // data algorithm, SHA256_MODE == 1
Victor Hsieh3051d782018-01-12 08:28:03 -0800333
Victor Hsiehd48e9542018-01-24 12:06:43 -0800334 buffer.putInt(0x1); // flags, 0x1: has extension
335 buffer.putInt(0); // reserved
Victor Hsieh3051d782018-01-12 08:28:03 -0800336
Victor Hsiehd48e9542018-01-24 12:06:43 -0800337 buffer.putLong(fileSize); // original file size
Victor Hsieh3051d782018-01-12 08:28:03 -0800338
Victor Hsieh2c8fbd62018-01-25 16:08:58 -0800339 buffer.put((byte) 0); // auth block offset, disabled here
340 buffer.put((byte) 2); // extension count
Victor Hsiehd48e9542018-01-24 12:06:43 -0800341 buffer.put(salt); // salt (8 bytes)
Victor Hsieh21203232018-01-29 15:10:56 -0800342 skip(buffer, 22); // reserved
Victor Hsieh3271d042017-10-24 15:46:32 -0700343
Victor Hsieh21203232018-01-29 15:10:56 -0800344 buffer.flip();
Victor Hsieh3271d042017-10-24 15:46:32 -0700345 return buffer;
346 }
347
Victor Hsieh3051d782018-01-12 08:28:03 -0800348 private static ByteBuffer generateFsverityExtensions(ByteBuffer buffer, long signingBlockOffset,
349 long signingBlockSize, long eocdOffset) {
350 // Snapshot of the FSVerity structs (subject to change once upstreamed).
351 //
Victor Hsieh3051d782018-01-12 08:28:03 -0800352 // struct fsverity_extension {
353 // __le16 length;
354 // u8 type;
355 // u8 reserved[5];
356 // };
357 //
358 // struct fsverity_extension_elide {
359 // __le64 offset;
360 // __le64 length;
361 // }
362 //
363 // struct fsverity_extension_patch {
364 // __le64 offset;
365 // u8 length;
366 // u8 reserved[7];
367 // u8 databytes[];
368 // };
369
Victor Hsieh3051d782018-01-12 08:28:03 -0800370 final int kSizeOfFsverityExtensionHeader = 8;
371
372 {
373 // struct fsverity_extension #1
374 final int kSizeOfFsverityElidedExtension = 16;
375
376 buffer.putShort((short) // total size of extension, padded to 64-bit alignment
377 (kSizeOfFsverityExtensionHeader + kSizeOfFsverityElidedExtension));
378 buffer.put((byte) 0); // ID of elide extension
379 skip(buffer, 5); // reserved
380
381 // struct fsverity_extension_elide
382 buffer.putLong(signingBlockOffset);
383 buffer.putLong(signingBlockSize);
384 }
385
386 {
387 // struct fsverity_extension #2
388 final int kSizeOfFsverityPatchExtension =
389 8 + // offset size
390 1 + // size of length from offset (up to 255)
391 7 + // reserved
392 ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE;
393 final int kPadding = (int) divideRoundup(kSizeOfFsverityPatchExtension % 8, 8);
394
395 buffer.putShort((short) // total size of extension, padded to 64-bit alignment
396 (kSizeOfFsverityExtensionHeader + kSizeOfFsverityPatchExtension + kPadding));
397 buffer.put((byte) 1); // ID of patch extension
398 skip(buffer, 5); // reserved
399
400 // struct fsverity_extension_patch
401 buffer.putLong(eocdOffset); // offset
402 buffer.put((byte) ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE); // length
403 skip(buffer, 7); // reserved
404 buffer.putInt(Math.toIntExact(signingBlockOffset)); // databytes
Victor Hsieh21203232018-01-29 15:10:56 -0800405 skip(buffer, kPadding); // padding
Victor Hsieh3051d782018-01-12 08:28:03 -0800406 }
407
Victor Hsieh21203232018-01-29 15:10:56 -0800408 buffer.flip();
Victor Hsieh3051d782018-01-12 08:28:03 -0800409 return buffer;
Victor Hsieh3271d042017-10-24 15:46:32 -0700410 }
411
412 /**
413 * Returns an array of summed area table of level size in the verity tree. In other words, the
414 * returned array is offset of each level in the verity tree file format, plus an additional
415 * offset of the next non-existing level (i.e. end of the last level + 1). Thus the array size
416 * is level + 1. Thus, the returned array is guarantee to have at least 2 elements.
417 */
418 private static int[] calculateVerityLevelOffset(long fileSize) {
419 ArrayList<Long> levelSize = new ArrayList<>();
420 while (true) {
421 long levelDigestSize = divideRoundup(fileSize, CHUNK_SIZE_BYTES) * DIGEST_SIZE_BYTES;
422 long chunksSize = CHUNK_SIZE_BYTES * divideRoundup(levelDigestSize, CHUNK_SIZE_BYTES);
423 levelSize.add(chunksSize);
424 if (levelDigestSize <= CHUNK_SIZE_BYTES) {
425 break;
426 }
427 fileSize = levelDigestSize;
428 }
429
430 // Reverse and convert to summed area table.
431 int[] levelOffset = new int[levelSize.size() + 1];
432 levelOffset[0] = 0;
433 for (int i = 0; i < levelSize.size(); i++) {
434 // We don't support verity tree if it is larger then Integer.MAX_VALUE.
435 levelOffset[i + 1] = levelOffset[i]
436 + Math.toIntExact(levelSize.get(levelSize.size() - i - 1));
437 }
438 return levelOffset;
439 }
440
441 private static void assertSigningBlockAlignedAndHasFullPages(SignatureInfo signatureInfo) {
442 if (signatureInfo.apkSigningBlockOffset % CHUNK_SIZE_BYTES != 0) {
443 throw new IllegalArgumentException(
444 "APK Signing Block does not start at the page boundary: "
445 + signatureInfo.apkSigningBlockOffset);
446 }
447
448 if ((signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset)
449 % CHUNK_SIZE_BYTES != 0) {
450 throw new IllegalArgumentException(
451 "Size of APK Signing Block is not a multiple of 4096: "
452 + (signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset));
453 }
454 }
455
456 /** Returns a slice of the buffer which shares content with the provided buffer. */
457 private static ByteBuffer slice(ByteBuffer buffer, int begin, int end) {
458 ByteBuffer b = buffer.duplicate();
459 b.position(0); // to ensure position <= limit invariant.
460 b.limit(end);
461 b.position(begin);
462 return b.slice();
463 }
464
Victor Hsieh3051d782018-01-12 08:28:03 -0800465 /** Skip the {@code ByteBuffer} position by {@code bytes}. */
466 private static void skip(ByteBuffer buffer, int bytes) {
467 buffer.position(buffer.position() + bytes);
468 }
469
Victor Hsieh3271d042017-10-24 15:46:32 -0700470 /** Divides a number and round up to the closest integer. */
471 private static long divideRoundup(long dividend, long divisor) {
472 return (dividend + divisor - 1) / divisor;
473 }
474}