blob: ba21ccb808fcebc685e72a08d416012fcbb6c3ed [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);
109 md.update(DEFAULT_SALT);
110 md.update(verityBlock);
111 md.update(apkDigest);
112 return md.digest();
113 }
114
115 private static void calculateFsveritySignatureInternal(
116 RandomAccessFile apk, SignatureInfo signatureInfo, ByteBuffer treeOutput,
117 ByteBuffer rootHashOutput, ByteBuffer headerOutput, ByteBuffer extensionsOutput)
118 throws IOException, NoSuchAlgorithmException, DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700119 assertSigningBlockAlignedAndHasFullPages(signatureInfo);
120
121 long signingBlockSize =
122 signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset;
123 long dataSize = apk.length() - signingBlockSize - ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE;
124 int[] levelOffset = calculateVerityLevelOffset(dataSize);
Victor Hsieh3271d042017-10-24 15:46:32 -0700125
Victor Hsieh3051d782018-01-12 08:28:03 -0800126 if (treeOutput != null) {
127 byte[] apkRootHash = generateApkVerityTree(apk, signatureInfo, DEFAULT_SALT,
128 levelOffset, treeOutput);
129 if (rootHashOutput != null) {
130 rootHashOutput.put(apkRootHash);
131 }
132 }
Victor Hsieh3271d042017-10-24 15:46:32 -0700133
Victor Hsieh3051d782018-01-12 08:28:03 -0800134 if (headerOutput != null) {
Victor Hsiehd48e9542018-01-24 12:06:43 -0800135 headerOutput.order(ByteOrder.LITTLE_ENDIAN);
Victor Hsieh3051d782018-01-12 08:28:03 -0800136 generateFsverityHeader(headerOutput, apk.length(), levelOffset.length - 1,
137 DEFAULT_SALT);
138 }
Victor Hsieh3271d042017-10-24 15:46:32 -0700139
Victor Hsieh3051d782018-01-12 08:28:03 -0800140 if (extensionsOutput != null) {
Victor Hsiehd48e9542018-01-24 12:06:43 -0800141 extensionsOutput.order(ByteOrder.LITTLE_ENDIAN);
Victor Hsieh3051d782018-01-12 08:28:03 -0800142 generateFsverityExtensions(extensionsOutput, signatureInfo.apkSigningBlockOffset,
143 signingBlockSize, signatureInfo.eocdOffset);
144 }
Victor Hsieh3271d042017-10-24 15:46:32 -0700145 }
146
147 /**
148 * A helper class to consume and digest data by block continuously, and write into a buffer.
149 */
150 private static class BufferedDigester implements DataDigester {
151 /** Amount of the data to digest in each cycle before writting out the digest. */
152 private static final int BUFFER_SIZE = CHUNK_SIZE_BYTES;
153
154 /**
155 * Amount of data the {@link MessageDigest} has consumed since the last reset. This must be
156 * always less than BUFFER_SIZE since {@link MessageDigest} is reset whenever it has
157 * consumed BUFFER_SIZE of data.
158 */
159 private int mBytesDigestedSinceReset;
160
161 /** The final output {@link ByteBuffer} to write the digest to sequentially. */
162 private final ByteBuffer mOutput;
163
164 private final MessageDigest mMd;
Victor Hsiehdef64f22017-11-08 10:25:11 -0800165 private final byte[] mDigestBuffer = new byte[DIGEST_SIZE_BYTES];
Victor Hsieh3271d042017-10-24 15:46:32 -0700166 private final byte[] mSalt;
167
168 private BufferedDigester(byte[] salt, ByteBuffer output) throws NoSuchAlgorithmException {
169 mSalt = salt;
170 mOutput = output.slice();
171 mMd = MessageDigest.getInstance(JCA_DIGEST_ALGORITHM);
172 mMd.update(mSalt);
173 mBytesDigestedSinceReset = 0;
174 }
175
176 /**
177 * Consumes and digests data up to BUFFER_SIZE (may continue from the previous remaining),
178 * then writes the final digest to the output buffer. Repeat until all data are consumed.
179 * If the last consumption is not enough for BUFFER_SIZE, the state will stay and future
180 * consumption will continuous from there.
181 */
182 @Override
Victor Hsiehdef64f22017-11-08 10:25:11 -0800183 public void consume(ByteBuffer buffer) throws DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700184 int offset = buffer.position();
185 int remaining = buffer.remaining();
186 while (remaining > 0) {
187 int allowance = (int) Math.min(remaining, BUFFER_SIZE - mBytesDigestedSinceReset);
Victor Hsiehdef64f22017-11-08 10:25:11 -0800188 // Optimization: set the buffer limit to avoid allocating a new ByteBuffer object.
189 buffer.limit(buffer.position() + allowance);
190 mMd.update(buffer);
Victor Hsieh3271d042017-10-24 15:46:32 -0700191 offset += allowance;
192 remaining -= allowance;
193 mBytesDigestedSinceReset += allowance;
194
195 if (mBytesDigestedSinceReset == BUFFER_SIZE) {
Victor Hsiehdef64f22017-11-08 10:25:11 -0800196 mMd.digest(mDigestBuffer, 0, mDigestBuffer.length);
197 mOutput.put(mDigestBuffer);
198 // After digest, MessageDigest resets automatically, so no need to reset again.
Victor Hsieh3271d042017-10-24 15:46:32 -0700199 mMd.update(mSalt);
200 mBytesDigestedSinceReset = 0;
201 }
202 }
203 }
204
205 /** Finish the current digestion if any. */
206 @Override
Victor Hsiehdef64f22017-11-08 10:25:11 -0800207 public void finish() throws DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700208 if (mBytesDigestedSinceReset == 0) {
209 return;
210 }
Victor Hsiehdef64f22017-11-08 10:25:11 -0800211 mMd.digest(mDigestBuffer, 0, mDigestBuffer.length);
212 mOutput.put(mDigestBuffer);
Victor Hsieh3271d042017-10-24 15:46:32 -0700213 }
214
215 private void fillUpLastOutputChunk() {
Victor Hsiehb62a64e2018-01-19 12:46:23 -0800216 int lastBlockSize = (int) (mOutput.position() % BUFFER_SIZE);
217 if (lastBlockSize == 0) {
Victor Hsieh3271d042017-10-24 15:46:32 -0700218 return;
219 }
Victor Hsiehb62a64e2018-01-19 12:46:23 -0800220 mOutput.put(ByteBuffer.allocate(BUFFER_SIZE - lastBlockSize));
Victor Hsieh3271d042017-10-24 15:46:32 -0700221 }
222 }
223
224 /**
225 * Digest the source by chunk in the given range. If the last chunk is not a full chunk,
226 * digest the remaining.
227 */
228 private static void consumeByChunk(DataDigester digester, DataSource source, int chunkSize)
Victor Hsiehdef64f22017-11-08 10:25:11 -0800229 throws IOException, DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700230 long inputRemaining = source.size();
231 long inputOffset = 0;
232 while (inputRemaining > 0) {
233 int size = (int) Math.min(inputRemaining, chunkSize);
234 source.feedIntoDataDigester(digester, inputOffset, size);
235 inputOffset += size;
236 inputRemaining -= size;
237 }
238 }
239
240 // Rationale: 1) 1 MB should fit in memory space on all devices. 2) It is not too granular
241 // thus the syscall overhead is not too big.
242 private static final int MMAP_REGION_SIZE_BYTES = 1024 * 1024;
243
244 private static void generateApkVerityDigestAtLeafLevel(RandomAccessFile apk,
245 SignatureInfo signatureInfo, byte[] salt, ByteBuffer output)
Victor Hsiehdef64f22017-11-08 10:25:11 -0800246 throws IOException, NoSuchAlgorithmException, DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700247 BufferedDigester digester = new BufferedDigester(salt, output);
248
249 // 1. Digest from the beginning of the file, until APK Signing Block is reached.
250 consumeByChunk(digester,
251 new MemoryMappedFileDataSource(apk.getFD(), 0, signatureInfo.apkSigningBlockOffset),
252 MMAP_REGION_SIZE_BYTES);
253
254 // 2. Skip APK Signing Block and continue digesting, until the Central Directory offset
255 // field in EoCD is reached.
256 long eocdCdOffsetFieldPosition =
257 signatureInfo.eocdOffset + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET;
258 consumeByChunk(digester,
259 new MemoryMappedFileDataSource(apk.getFD(), signatureInfo.centralDirOffset,
260 eocdCdOffsetFieldPosition - signatureInfo.centralDirOffset),
261 MMAP_REGION_SIZE_BYTES);
262
Victor Hsieh3051d782018-01-12 08:28:03 -0800263 // 3. Consume offset of Signing Block as an alternative EoCD.
Victor Hsieh3271d042017-10-24 15:46:32 -0700264 ByteBuffer alternativeCentralDirOffset = ByteBuffer.allocate(
265 ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE).order(ByteOrder.LITTLE_ENDIAN);
266 alternativeCentralDirOffset.putInt(Math.toIntExact(signatureInfo.apkSigningBlockOffset));
267 alternativeCentralDirOffset.flip();
268 digester.consume(alternativeCentralDirOffset);
269
270 // 4. Read from end of the Central Directory offset field in EoCD to the end of the file.
271 long offsetAfterEocdCdOffsetField =
272 eocdCdOffsetFieldPosition + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE;
273 consumeByChunk(digester,
274 new MemoryMappedFileDataSource(apk.getFD(), offsetAfterEocdCdOffsetField,
275 apk.length() - offsetAfterEocdCdOffsetField),
276 MMAP_REGION_SIZE_BYTES);
277 digester.finish();
278
279 // 5. Fill up the rest of buffer with 0s.
280 digester.fillUpLastOutputChunk();
281 }
282
283 private static byte[] generateApkVerityTree(RandomAccessFile apk, SignatureInfo signatureInfo,
284 byte[] salt, int[] levelOffset, ByteBuffer output)
Victor Hsiehdef64f22017-11-08 10:25:11 -0800285 throws IOException, NoSuchAlgorithmException, DigestException {
Victor Hsieh3271d042017-10-24 15:46:32 -0700286 // 1. Digest the apk to generate the leaf level hashes.
287 generateApkVerityDigestAtLeafLevel(apk, signatureInfo, salt, slice(output,
288 levelOffset[levelOffset.length - 2], levelOffset[levelOffset.length - 1]));
289
290 // 2. Digest the lower level hashes bottom up.
291 for (int level = levelOffset.length - 3; level >= 0; level--) {
292 ByteBuffer inputBuffer = slice(output, levelOffset[level + 1], levelOffset[level + 2]);
293 ByteBuffer outputBuffer = slice(output, levelOffset[level], levelOffset[level + 1]);
294
295 DataSource source = new ByteBufferDataSource(inputBuffer);
296 BufferedDigester digester = new BufferedDigester(salt, outputBuffer);
297 consumeByChunk(digester, source, CHUNK_SIZE_BYTES);
298 digester.finish();
299
300 digester.fillUpLastOutputChunk();
301 }
302
303 // 3. Digest the first block (i.e. first level) to generate the root hash.
304 byte[] rootHash = new byte[DIGEST_SIZE_BYTES];
305 BufferedDigester digester = new BufferedDigester(salt, ByteBuffer.wrap(rootHash));
306 digester.consume(slice(output, 0, CHUNK_SIZE_BYTES));
Victor Hsieh4385fe42017-11-08 10:44:20 -0800307 digester.finish();
Victor Hsieh3271d042017-10-24 15:46:32 -0700308 return rootHash;
309 }
310
Victor Hsiehd48e9542018-01-24 12:06:43 -0800311 private static void bufferPut(ByteBuffer buffer, byte value) {
312 // FIXME(b/72459251): buffer.put(value) does NOT work surprisingly. The position() after put
313 // does NOT even change. This hack workaround the problem, but the root cause remains
314 // unkonwn yet. This seems only happen when it goes through the apk install flow on my
315 // setup.
316 buffer.put(new byte[] { value });
317 }
318
Victor Hsieh3051d782018-01-12 08:28:03 -0800319 private static ByteBuffer generateFsverityHeader(ByteBuffer buffer, long fileSize, int depth,
320 byte[] salt) {
Victor Hsieh3271d042017-10-24 15:46:32 -0700321 if (salt.length != 8) {
322 throw new IllegalArgumentException("salt is not 8 bytes long");
323 }
324
Victor Hsieh3051d782018-01-12 08:28:03 -0800325 // TODO(b/30972906): update the reference when there is a better one in public.
Victor Hsieh3271d042017-10-24 15:46:32 -0700326 buffer.put("TrueBrew".getBytes()); // magic
Victor Hsieh3051d782018-01-12 08:28:03 -0800327
Victor Hsiehd48e9542018-01-24 12:06:43 -0800328 bufferPut(buffer, (byte) 1); // major version
329 bufferPut(buffer, (byte) 0); // minor version
330 bufferPut(buffer, (byte) 12); // log2(block-size): log2(4096)
331 bufferPut(buffer, (byte) 7); // log2(leaves-per-node): log2(4096 / 32)
Victor Hsieh3271d042017-10-24 15:46:32 -0700332
Victor Hsiehd48e9542018-01-24 12:06:43 -0800333 buffer.putShort((short) 1); // meta algorithm, SHA256_MODE == 1
334 buffer.putShort((short) 1); // data algorithm, SHA256_MODE == 1
Victor Hsieh3051d782018-01-12 08:28:03 -0800335
Victor Hsiehd48e9542018-01-24 12:06:43 -0800336 buffer.putInt(0x1); // flags, 0x1: has extension
337 buffer.putInt(0); // reserved
Victor Hsieh3051d782018-01-12 08:28:03 -0800338
Victor Hsiehd48e9542018-01-24 12:06:43 -0800339 buffer.putLong(fileSize); // original file size
Victor Hsieh3051d782018-01-12 08:28:03 -0800340
Victor Hsiehd48e9542018-01-24 12:06:43 -0800341 bufferPut(buffer, (byte) 0); // auth block offset, disabled here
342 bufferPut(buffer, (byte) 2); // extension count
343 buffer.put(salt); // salt (8 bytes)
344 // skip(buffer, 22); // reserved
Victor Hsieh3271d042017-10-24 15:46:32 -0700345
346 buffer.rewind();
347 return buffer;
348 }
349
Victor Hsieh3051d782018-01-12 08:28:03 -0800350 private static ByteBuffer generateFsverityExtensions(ByteBuffer buffer, long signingBlockOffset,
351 long signingBlockSize, long eocdOffset) {
352 // Snapshot of the FSVerity structs (subject to change once upstreamed).
353 //
Victor Hsieh3051d782018-01-12 08:28:03 -0800354 // struct fsverity_extension {
355 // __le16 length;
356 // u8 type;
357 // u8 reserved[5];
358 // };
359 //
360 // struct fsverity_extension_elide {
361 // __le64 offset;
362 // __le64 length;
363 // }
364 //
365 // struct fsverity_extension_patch {
366 // __le64 offset;
367 // u8 length;
368 // u8 reserved[7];
369 // u8 databytes[];
370 // };
371
Victor Hsieh3051d782018-01-12 08:28:03 -0800372 final int kSizeOfFsverityExtensionHeader = 8;
373
374 {
375 // struct fsverity_extension #1
376 final int kSizeOfFsverityElidedExtension = 16;
377
378 buffer.putShort((short) // total size of extension, padded to 64-bit alignment
379 (kSizeOfFsverityExtensionHeader + kSizeOfFsverityElidedExtension));
380 buffer.put((byte) 0); // ID of elide extension
381 skip(buffer, 5); // reserved
382
383 // struct fsverity_extension_elide
384 buffer.putLong(signingBlockOffset);
385 buffer.putLong(signingBlockSize);
386 }
387
388 {
389 // struct fsverity_extension #2
390 final int kSizeOfFsverityPatchExtension =
391 8 + // offset size
392 1 + // size of length from offset (up to 255)
393 7 + // reserved
394 ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE;
395 final int kPadding = (int) divideRoundup(kSizeOfFsverityPatchExtension % 8, 8);
396
397 buffer.putShort((short) // total size of extension, padded to 64-bit alignment
398 (kSizeOfFsverityExtensionHeader + kSizeOfFsverityPatchExtension + kPadding));
399 buffer.put((byte) 1); // ID of patch extension
400 skip(buffer, 5); // reserved
401
402 // struct fsverity_extension_patch
403 buffer.putLong(eocdOffset); // offset
404 buffer.put((byte) ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE); // length
405 skip(buffer, 7); // reserved
406 buffer.putInt(Math.toIntExact(signingBlockOffset)); // databytes
407
408 // There are extra kPadding bytes of 0s here, included in the total size field of the
409 // extension header. The output ByteBuffer is assumed to be initialized to 0.
410 }
411
412 buffer.rewind();
413 return buffer;
Victor Hsieh3271d042017-10-24 15:46:32 -0700414 }
415
416 /**
417 * Returns an array of summed area table of level size in the verity tree. In other words, the
418 * returned array is offset of each level in the verity tree file format, plus an additional
419 * offset of the next non-existing level (i.e. end of the last level + 1). Thus the array size
420 * is level + 1. Thus, the returned array is guarantee to have at least 2 elements.
421 */
422 private static int[] calculateVerityLevelOffset(long fileSize) {
423 ArrayList<Long> levelSize = new ArrayList<>();
424 while (true) {
425 long levelDigestSize = divideRoundup(fileSize, CHUNK_SIZE_BYTES) * DIGEST_SIZE_BYTES;
426 long chunksSize = CHUNK_SIZE_BYTES * divideRoundup(levelDigestSize, CHUNK_SIZE_BYTES);
427 levelSize.add(chunksSize);
428 if (levelDigestSize <= CHUNK_SIZE_BYTES) {
429 break;
430 }
431 fileSize = levelDigestSize;
432 }
433
434 // Reverse and convert to summed area table.
435 int[] levelOffset = new int[levelSize.size() + 1];
436 levelOffset[0] = 0;
437 for (int i = 0; i < levelSize.size(); i++) {
438 // We don't support verity tree if it is larger then Integer.MAX_VALUE.
439 levelOffset[i + 1] = levelOffset[i]
440 + Math.toIntExact(levelSize.get(levelSize.size() - i - 1));
441 }
442 return levelOffset;
443 }
444
445 private static void assertSigningBlockAlignedAndHasFullPages(SignatureInfo signatureInfo) {
446 if (signatureInfo.apkSigningBlockOffset % CHUNK_SIZE_BYTES != 0) {
447 throw new IllegalArgumentException(
448 "APK Signing Block does not start at the page boundary: "
449 + signatureInfo.apkSigningBlockOffset);
450 }
451
452 if ((signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset)
453 % CHUNK_SIZE_BYTES != 0) {
454 throw new IllegalArgumentException(
455 "Size of APK Signing Block is not a multiple of 4096: "
456 + (signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset));
457 }
458 }
459
460 /** Returns a slice of the buffer which shares content with the provided buffer. */
461 private static ByteBuffer slice(ByteBuffer buffer, int begin, int end) {
462 ByteBuffer b = buffer.duplicate();
463 b.position(0); // to ensure position <= limit invariant.
464 b.limit(end);
465 b.position(begin);
466 return b.slice();
467 }
468
Victor Hsieh3051d782018-01-12 08:28:03 -0800469 /** Skip the {@code ByteBuffer} position by {@code bytes}. */
470 private static void skip(ByteBuffer buffer, int bytes) {
471 buffer.position(buffer.position() + bytes);
472 }
473
Victor Hsieh3271d042017-10-24 15:46:32 -0700474 /** Divides a number and round up to the closest integer. */
475 private static long divideRoundup(long dividend, long divisor) {
476 return (dividend + divisor - 1) / divisor;
477 }
478}