Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | package android.util.apk; |
| 18 | |
| 19 | import java.io.IOException; |
| 20 | import java.io.RandomAccessFile; |
| 21 | import java.nio.ByteBuffer; |
| 22 | import java.nio.ByteOrder; |
Victor Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 23 | import java.security.DigestException; |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 24 | import java.security.MessageDigest; |
| 25 | import java.security.NoSuchAlgorithmException; |
| 26 | import 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 | */ |
| 38 | abstract 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 Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 70 | throws IOException, SecurityException, NoSuchAlgorithmException, DigestException { |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 71 | long signingBlockSize = |
| 72 | signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset; |
Victor Hsieh | d48e954 | 2018-01-24 12:06:43 -0800 | [diff] [blame] | 73 | long dataSize = apk.length() - signingBlockSize; |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 74 | 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 Hsieh | 2120323 | 2018-01-29 15:10:56 -0800 | [diff] [blame^] | 109 | md.update(header); |
| 110 | md.update(extensions); |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 111 | md.update(apkDigest); |
| 112 | return md.digest(); |
| 113 | } |
| 114 | |
Victor Hsieh | 2120323 | 2018-01-29 15:10:56 -0800 | [diff] [blame^] | 115 | /** |
| 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 Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 120 | private static void calculateFsveritySignatureInternal( |
| 121 | RandomAccessFile apk, SignatureInfo signatureInfo, ByteBuffer treeOutput, |
| 122 | ByteBuffer rootHashOutput, ByteBuffer headerOutput, ByteBuffer extensionsOutput) |
| 123 | throws IOException, NoSuchAlgorithmException, DigestException { |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 124 | assertSigningBlockAlignedAndHasFullPages(signatureInfo); |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 125 | 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 Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 129 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 130 | if (treeOutput != null) { |
| 131 | byte[] apkRootHash = generateApkVerityTree(apk, signatureInfo, DEFAULT_SALT, |
| 132 | levelOffset, treeOutput); |
| 133 | if (rootHashOutput != null) { |
| 134 | rootHashOutput.put(apkRootHash); |
Victor Hsieh | 2120323 | 2018-01-29 15:10:56 -0800 | [diff] [blame^] | 135 | rootHashOutput.flip(); |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 136 | } |
| 137 | } |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 138 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 139 | if (headerOutput != null) { |
Victor Hsieh | d48e954 | 2018-01-24 12:06:43 -0800 | [diff] [blame] | 140 | headerOutput.order(ByteOrder.LITTLE_ENDIAN); |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 141 | generateFsverityHeader(headerOutput, apk.length(), levelOffset.length - 1, |
| 142 | DEFAULT_SALT); |
| 143 | } |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 144 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 145 | if (extensionsOutput != null) { |
Victor Hsieh | d48e954 | 2018-01-24 12:06:43 -0800 | [diff] [blame] | 146 | extensionsOutput.order(ByteOrder.LITTLE_ENDIAN); |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 147 | generateFsverityExtensions(extensionsOutput, signatureInfo.apkSigningBlockOffset, |
| 148 | signingBlockSize, signatureInfo.eocdOffset); |
| 149 | } |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 150 | } |
| 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 Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 170 | private final byte[] mDigestBuffer = new byte[DIGEST_SIZE_BYTES]; |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 171 | 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 Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 188 | public void consume(ByteBuffer buffer) throws DigestException { |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 189 | int offset = buffer.position(); |
| 190 | int remaining = buffer.remaining(); |
| 191 | while (remaining > 0) { |
| 192 | int allowance = (int) Math.min(remaining, BUFFER_SIZE - mBytesDigestedSinceReset); |
Victor Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 193 | // Optimization: set the buffer limit to avoid allocating a new ByteBuffer object. |
| 194 | buffer.limit(buffer.position() + allowance); |
| 195 | mMd.update(buffer); |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 196 | offset += allowance; |
| 197 | remaining -= allowance; |
| 198 | mBytesDigestedSinceReset += allowance; |
| 199 | |
| 200 | if (mBytesDigestedSinceReset == BUFFER_SIZE) { |
Victor Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 201 | mMd.digest(mDigestBuffer, 0, mDigestBuffer.length); |
| 202 | mOutput.put(mDigestBuffer); |
| 203 | // After digest, MessageDigest resets automatically, so no need to reset again. |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 204 | mMd.update(mSalt); |
| 205 | mBytesDigestedSinceReset = 0; |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | /** Finish the current digestion if any. */ |
| 211 | @Override |
Victor Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 212 | public void finish() throws DigestException { |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 213 | if (mBytesDigestedSinceReset == 0) { |
| 214 | return; |
| 215 | } |
Victor Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 216 | mMd.digest(mDigestBuffer, 0, mDigestBuffer.length); |
| 217 | mOutput.put(mDigestBuffer); |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 218 | } |
| 219 | |
| 220 | private void fillUpLastOutputChunk() { |
Victor Hsieh | b62a64e | 2018-01-19 12:46:23 -0800 | [diff] [blame] | 221 | int lastBlockSize = (int) (mOutput.position() % BUFFER_SIZE); |
| 222 | if (lastBlockSize == 0) { |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 223 | return; |
| 224 | } |
Victor Hsieh | b62a64e | 2018-01-19 12:46:23 -0800 | [diff] [blame] | 225 | mOutput.put(ByteBuffer.allocate(BUFFER_SIZE - lastBlockSize)); |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 226 | } |
| 227 | } |
| 228 | |
| 229 | /** |
| 230 | * Digest the source by chunk in the given range. If the last chunk is not a full chunk, |
| 231 | * digest the remaining. |
| 232 | */ |
| 233 | private static void consumeByChunk(DataDigester digester, DataSource source, int chunkSize) |
Victor Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 234 | throws IOException, DigestException { |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 235 | long inputRemaining = source.size(); |
| 236 | long inputOffset = 0; |
| 237 | while (inputRemaining > 0) { |
| 238 | int size = (int) Math.min(inputRemaining, chunkSize); |
| 239 | source.feedIntoDataDigester(digester, inputOffset, size); |
| 240 | inputOffset += size; |
| 241 | inputRemaining -= size; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | // Rationale: 1) 1 MB should fit in memory space on all devices. 2) It is not too granular |
| 246 | // thus the syscall overhead is not too big. |
| 247 | private static final int MMAP_REGION_SIZE_BYTES = 1024 * 1024; |
| 248 | |
| 249 | private static void generateApkVerityDigestAtLeafLevel(RandomAccessFile apk, |
| 250 | SignatureInfo signatureInfo, byte[] salt, ByteBuffer output) |
Victor Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 251 | throws IOException, NoSuchAlgorithmException, DigestException { |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 252 | BufferedDigester digester = new BufferedDigester(salt, output); |
| 253 | |
| 254 | // 1. Digest from the beginning of the file, until APK Signing Block is reached. |
| 255 | consumeByChunk(digester, |
| 256 | new MemoryMappedFileDataSource(apk.getFD(), 0, signatureInfo.apkSigningBlockOffset), |
| 257 | MMAP_REGION_SIZE_BYTES); |
| 258 | |
| 259 | // 2. Skip APK Signing Block and continue digesting, until the Central Directory offset |
| 260 | // field in EoCD is reached. |
| 261 | long eocdCdOffsetFieldPosition = |
| 262 | signatureInfo.eocdOffset + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_OFFSET; |
| 263 | consumeByChunk(digester, |
| 264 | new MemoryMappedFileDataSource(apk.getFD(), signatureInfo.centralDirOffset, |
| 265 | eocdCdOffsetFieldPosition - signatureInfo.centralDirOffset), |
| 266 | MMAP_REGION_SIZE_BYTES); |
| 267 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 268 | // 3. Consume offset of Signing Block as an alternative EoCD. |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 269 | ByteBuffer alternativeCentralDirOffset = ByteBuffer.allocate( |
| 270 | ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE).order(ByteOrder.LITTLE_ENDIAN); |
| 271 | alternativeCentralDirOffset.putInt(Math.toIntExact(signatureInfo.apkSigningBlockOffset)); |
| 272 | alternativeCentralDirOffset.flip(); |
| 273 | digester.consume(alternativeCentralDirOffset); |
| 274 | |
| 275 | // 4. Read from end of the Central Directory offset field in EoCD to the end of the file. |
| 276 | long offsetAfterEocdCdOffsetField = |
| 277 | eocdCdOffsetFieldPosition + ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE; |
| 278 | consumeByChunk(digester, |
| 279 | new MemoryMappedFileDataSource(apk.getFD(), offsetAfterEocdCdOffsetField, |
| 280 | apk.length() - offsetAfterEocdCdOffsetField), |
| 281 | MMAP_REGION_SIZE_BYTES); |
| 282 | digester.finish(); |
| 283 | |
| 284 | // 5. Fill up the rest of buffer with 0s. |
| 285 | digester.fillUpLastOutputChunk(); |
| 286 | } |
| 287 | |
| 288 | private static byte[] generateApkVerityTree(RandomAccessFile apk, SignatureInfo signatureInfo, |
| 289 | byte[] salt, int[] levelOffset, ByteBuffer output) |
Victor Hsieh | def64f2 | 2017-11-08 10:25:11 -0800 | [diff] [blame] | 290 | throws IOException, NoSuchAlgorithmException, DigestException { |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 291 | // 1. Digest the apk to generate the leaf level hashes. |
| 292 | generateApkVerityDigestAtLeafLevel(apk, signatureInfo, salt, slice(output, |
| 293 | levelOffset[levelOffset.length - 2], levelOffset[levelOffset.length - 1])); |
| 294 | |
| 295 | // 2. Digest the lower level hashes bottom up. |
| 296 | for (int level = levelOffset.length - 3; level >= 0; level--) { |
| 297 | ByteBuffer inputBuffer = slice(output, levelOffset[level + 1], levelOffset[level + 2]); |
| 298 | ByteBuffer outputBuffer = slice(output, levelOffset[level], levelOffset[level + 1]); |
| 299 | |
| 300 | DataSource source = new ByteBufferDataSource(inputBuffer); |
| 301 | BufferedDigester digester = new BufferedDigester(salt, outputBuffer); |
| 302 | consumeByChunk(digester, source, CHUNK_SIZE_BYTES); |
| 303 | digester.finish(); |
| 304 | |
| 305 | digester.fillUpLastOutputChunk(); |
| 306 | } |
| 307 | |
| 308 | // 3. Digest the first block (i.e. first level) to generate the root hash. |
| 309 | byte[] rootHash = new byte[DIGEST_SIZE_BYTES]; |
| 310 | BufferedDigester digester = new BufferedDigester(salt, ByteBuffer.wrap(rootHash)); |
| 311 | digester.consume(slice(output, 0, CHUNK_SIZE_BYTES)); |
Victor Hsieh | 4385fe4 | 2017-11-08 10:44:20 -0800 | [diff] [blame] | 312 | digester.finish(); |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 313 | return rootHash; |
| 314 | } |
| 315 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 316 | private static ByteBuffer generateFsverityHeader(ByteBuffer buffer, long fileSize, int depth, |
| 317 | byte[] salt) { |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 318 | if (salt.length != 8) { |
| 319 | throw new IllegalArgumentException("salt is not 8 bytes long"); |
| 320 | } |
| 321 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 322 | // TODO(b/30972906): update the reference when there is a better one in public. |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 323 | buffer.put("TrueBrew".getBytes()); // magic |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 324 | |
Victor Hsieh | 2c8fbd6 | 2018-01-25 16:08:58 -0800 | [diff] [blame] | 325 | buffer.put((byte) 1); // major version |
| 326 | buffer.put((byte) 0); // minor version |
| 327 | buffer.put((byte) 12); // log2(block-size): log2(4096) |
| 328 | buffer.put((byte) 7); // log2(leaves-per-node): log2(4096 / 32) |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 329 | |
Victor Hsieh | d48e954 | 2018-01-24 12:06:43 -0800 | [diff] [blame] | 330 | buffer.putShort((short) 1); // meta algorithm, SHA256_MODE == 1 |
| 331 | buffer.putShort((short) 1); // data algorithm, SHA256_MODE == 1 |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 332 | |
Victor Hsieh | d48e954 | 2018-01-24 12:06:43 -0800 | [diff] [blame] | 333 | buffer.putInt(0x1); // flags, 0x1: has extension |
| 334 | buffer.putInt(0); // reserved |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 335 | |
Victor Hsieh | d48e954 | 2018-01-24 12:06:43 -0800 | [diff] [blame] | 336 | buffer.putLong(fileSize); // original file size |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 337 | |
Victor Hsieh | 2c8fbd6 | 2018-01-25 16:08:58 -0800 | [diff] [blame] | 338 | buffer.put((byte) 0); // auth block offset, disabled here |
| 339 | buffer.put((byte) 2); // extension count |
Victor Hsieh | d48e954 | 2018-01-24 12:06:43 -0800 | [diff] [blame] | 340 | buffer.put(salt); // salt (8 bytes) |
Victor Hsieh | 2120323 | 2018-01-29 15:10:56 -0800 | [diff] [blame^] | 341 | skip(buffer, 22); // reserved |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 342 | |
Victor Hsieh | 2120323 | 2018-01-29 15:10:56 -0800 | [diff] [blame^] | 343 | buffer.flip(); |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 344 | return buffer; |
| 345 | } |
| 346 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 347 | private static ByteBuffer generateFsverityExtensions(ByteBuffer buffer, long signingBlockOffset, |
| 348 | long signingBlockSize, long eocdOffset) { |
| 349 | // Snapshot of the FSVerity structs (subject to change once upstreamed). |
| 350 | // |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 351 | // struct fsverity_extension { |
| 352 | // __le16 length; |
| 353 | // u8 type; |
| 354 | // u8 reserved[5]; |
| 355 | // }; |
| 356 | // |
| 357 | // struct fsverity_extension_elide { |
| 358 | // __le64 offset; |
| 359 | // __le64 length; |
| 360 | // } |
| 361 | // |
| 362 | // struct fsverity_extension_patch { |
| 363 | // __le64 offset; |
| 364 | // u8 length; |
| 365 | // u8 reserved[7]; |
| 366 | // u8 databytes[]; |
| 367 | // }; |
| 368 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 369 | final int kSizeOfFsverityExtensionHeader = 8; |
| 370 | |
| 371 | { |
| 372 | // struct fsverity_extension #1 |
| 373 | final int kSizeOfFsverityElidedExtension = 16; |
| 374 | |
| 375 | buffer.putShort((short) // total size of extension, padded to 64-bit alignment |
| 376 | (kSizeOfFsverityExtensionHeader + kSizeOfFsverityElidedExtension)); |
| 377 | buffer.put((byte) 0); // ID of elide extension |
| 378 | skip(buffer, 5); // reserved |
| 379 | |
| 380 | // struct fsverity_extension_elide |
| 381 | buffer.putLong(signingBlockOffset); |
| 382 | buffer.putLong(signingBlockSize); |
| 383 | } |
| 384 | |
| 385 | { |
| 386 | // struct fsverity_extension #2 |
| 387 | final int kSizeOfFsverityPatchExtension = |
| 388 | 8 + // offset size |
| 389 | 1 + // size of length from offset (up to 255) |
| 390 | 7 + // reserved |
| 391 | ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE; |
| 392 | final int kPadding = (int) divideRoundup(kSizeOfFsverityPatchExtension % 8, 8); |
| 393 | |
| 394 | buffer.putShort((short) // total size of extension, padded to 64-bit alignment |
| 395 | (kSizeOfFsverityExtensionHeader + kSizeOfFsverityPatchExtension + kPadding)); |
| 396 | buffer.put((byte) 1); // ID of patch extension |
| 397 | skip(buffer, 5); // reserved |
| 398 | |
| 399 | // struct fsverity_extension_patch |
| 400 | buffer.putLong(eocdOffset); // offset |
| 401 | buffer.put((byte) ZIP_EOCD_CENTRAL_DIR_OFFSET_FIELD_SIZE); // length |
| 402 | skip(buffer, 7); // reserved |
| 403 | buffer.putInt(Math.toIntExact(signingBlockOffset)); // databytes |
Victor Hsieh | 2120323 | 2018-01-29 15:10:56 -0800 | [diff] [blame^] | 404 | skip(buffer, kPadding); // padding |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 405 | } |
| 406 | |
Victor Hsieh | 2120323 | 2018-01-29 15:10:56 -0800 | [diff] [blame^] | 407 | buffer.flip(); |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 408 | return buffer; |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 409 | } |
| 410 | |
| 411 | /** |
| 412 | * Returns an array of summed area table of level size in the verity tree. In other words, the |
| 413 | * returned array is offset of each level in the verity tree file format, plus an additional |
| 414 | * offset of the next non-existing level (i.e. end of the last level + 1). Thus the array size |
| 415 | * is level + 1. Thus, the returned array is guarantee to have at least 2 elements. |
| 416 | */ |
| 417 | private static int[] calculateVerityLevelOffset(long fileSize) { |
| 418 | ArrayList<Long> levelSize = new ArrayList<>(); |
| 419 | while (true) { |
| 420 | long levelDigestSize = divideRoundup(fileSize, CHUNK_SIZE_BYTES) * DIGEST_SIZE_BYTES; |
| 421 | long chunksSize = CHUNK_SIZE_BYTES * divideRoundup(levelDigestSize, CHUNK_SIZE_BYTES); |
| 422 | levelSize.add(chunksSize); |
| 423 | if (levelDigestSize <= CHUNK_SIZE_BYTES) { |
| 424 | break; |
| 425 | } |
| 426 | fileSize = levelDigestSize; |
| 427 | } |
| 428 | |
| 429 | // Reverse and convert to summed area table. |
| 430 | int[] levelOffset = new int[levelSize.size() + 1]; |
| 431 | levelOffset[0] = 0; |
| 432 | for (int i = 0; i < levelSize.size(); i++) { |
| 433 | // We don't support verity tree if it is larger then Integer.MAX_VALUE. |
| 434 | levelOffset[i + 1] = levelOffset[i] |
| 435 | + Math.toIntExact(levelSize.get(levelSize.size() - i - 1)); |
| 436 | } |
| 437 | return levelOffset; |
| 438 | } |
| 439 | |
| 440 | private static void assertSigningBlockAlignedAndHasFullPages(SignatureInfo signatureInfo) { |
| 441 | if (signatureInfo.apkSigningBlockOffset % CHUNK_SIZE_BYTES != 0) { |
| 442 | throw new IllegalArgumentException( |
| 443 | "APK Signing Block does not start at the page boundary: " |
| 444 | + signatureInfo.apkSigningBlockOffset); |
| 445 | } |
| 446 | |
| 447 | if ((signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset) |
| 448 | % CHUNK_SIZE_BYTES != 0) { |
| 449 | throw new IllegalArgumentException( |
| 450 | "Size of APK Signing Block is not a multiple of 4096: " |
| 451 | + (signatureInfo.centralDirOffset - signatureInfo.apkSigningBlockOffset)); |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | /** Returns a slice of the buffer which shares content with the provided buffer. */ |
| 456 | private static ByteBuffer slice(ByteBuffer buffer, int begin, int end) { |
| 457 | ByteBuffer b = buffer.duplicate(); |
| 458 | b.position(0); // to ensure position <= limit invariant. |
| 459 | b.limit(end); |
| 460 | b.position(begin); |
| 461 | return b.slice(); |
| 462 | } |
| 463 | |
Victor Hsieh | 3051d78 | 2018-01-12 08:28:03 -0800 | [diff] [blame] | 464 | /** Skip the {@code ByteBuffer} position by {@code bytes}. */ |
| 465 | private static void skip(ByteBuffer buffer, int bytes) { |
| 466 | buffer.position(buffer.position() + bytes); |
| 467 | } |
| 468 | |
Victor Hsieh | 3271d04 | 2017-10-24 15:46:32 -0700 | [diff] [blame] | 469 | /** Divides a number and round up to the closest integer. */ |
| 470 | private static long divideRoundup(long dividend, long divisor) { |
| 471 | return (dividend + divisor - 1) / divisor; |
| 472 | } |
| 473 | } |