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