1 /*
2  * Copyright (C) 2020 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 #define TRACE_TAG INCREMENTAL
18 
19 #include "incremental_utils.h"
20 
21 #include <android-base/endian.h>
22 #include <android-base/mapped_file.h>
23 #include <android-base/strings.h>
24 #include <ziparchive/zip_archive.h>
25 #include <ziparchive/zip_writer.h>
26 
27 #include <array>
28 #include <cinttypes>
29 #include <numeric>
30 #include <unordered_set>
31 
32 #include "adb_io.h"
33 #include "adb_trace.h"
34 #include "sysdeps.h"
35 
36 using namespace std::literals;
37 
38 namespace incremental {
39 
offsetToBlockIndex(int64_t offset)40 static constexpr inline int32_t offsetToBlockIndex(int64_t offset) {
41     return (offset & ~(kBlockSize - 1)) >> 12;
42 }
43 
verity_tree_blocks_for_file(Size fileSize)44 Size verity_tree_blocks_for_file(Size fileSize) {
45     if (fileSize == 0) {
46         return 0;
47     }
48 
49     constexpr int hash_per_block = kBlockSize / kDigestSize;
50 
51     Size total_tree_block_count = 0;
52 
53     auto block_count = 1 + (fileSize - 1) / kBlockSize;
54     auto hash_block_count = block_count;
55     for (auto i = 0; hash_block_count > 1; i++) {
56         hash_block_count = (hash_block_count + hash_per_block - 1) / hash_per_block;
57         total_tree_block_count += hash_block_count;
58     }
59     return total_tree_block_count;
60 }
61 
verity_tree_size_for_file(Size fileSize)62 Size verity_tree_size_for_file(Size fileSize) {
63     return verity_tree_blocks_for_file(fileSize) * kBlockSize;
64 }
65 
read_int32(borrowed_fd fd)66 static inline int32_t read_int32(borrowed_fd fd) {
67     int32_t result;
68     return ReadFdExactly(fd, &result, sizeof(result)) ? result : -1;
69 }
70 
skip_int(borrowed_fd fd)71 static inline int32_t skip_int(borrowed_fd fd) {
72     return adb_lseek(fd, 4, SEEK_CUR);
73 }
74 
append_int(borrowed_fd fd,std::vector<char> * bytes)75 static inline void append_int(borrowed_fd fd, std::vector<char>* bytes) {
76     int32_t le_val = read_int32(fd);
77     auto old_size = bytes->size();
78     bytes->resize(old_size + sizeof(le_val));
79     memcpy(bytes->data() + old_size, &le_val, sizeof(le_val));
80 }
81 
append_bytes_with_size(borrowed_fd fd,std::vector<char> * bytes)82 static inline void append_bytes_with_size(borrowed_fd fd, std::vector<char>* bytes) {
83     int32_t le_size = read_int32(fd);
84     if (le_size < 0) {
85         return;
86     }
87     int32_t size = int32_t(le32toh(le_size));
88     auto old_size = bytes->size();
89     bytes->resize(old_size + sizeof(le_size) + size);
90     memcpy(bytes->data() + old_size, &le_size, sizeof(le_size));
91     ReadFdExactly(fd, bytes->data() + old_size + sizeof(le_size), size);
92 }
93 
skip_bytes_with_size(borrowed_fd fd)94 static inline int32_t skip_bytes_with_size(borrowed_fd fd) {
95     int32_t le_size = read_int32(fd);
96     if (le_size < 0) {
97         return -1;
98     }
99     int32_t size = int32_t(le32toh(le_size));
100     return (int32_t)adb_lseek(fd, size, SEEK_CUR);
101 }
102 
read_id_sig_headers(borrowed_fd fd)103 std::pair<std::vector<char>, int32_t> read_id_sig_headers(borrowed_fd fd) {
104     std::vector<char> result;
105     append_int(fd, &result);              // version
106     append_bytes_with_size(fd, &result);  // hashingInfo
107     append_bytes_with_size(fd, &result);  // signingInfo
108     auto le_tree_size = read_int32(fd);
109     auto tree_size = int32_t(le32toh(le_tree_size));  // size of the verity tree
110     return {std::move(result), tree_size};
111 }
112 
skip_id_sig_headers(borrowed_fd fd)113 std::pair<off64_t, ssize_t> skip_id_sig_headers(borrowed_fd fd) {
114     skip_int(fd);                            // version
115     skip_bytes_with_size(fd);                // hashingInfo
116     auto offset = skip_bytes_with_size(fd);  // signingInfo
117     auto le_tree_size = read_int32(fd);
118     auto tree_size = int32_t(le32toh(le_tree_size));  // size of the verity tree
119     return {offset + sizeof(le_tree_size), tree_size};
120 }
121 
122 template <class T>
valueAt(borrowed_fd fd,off64_t offset)123 static T valueAt(borrowed_fd fd, off64_t offset) {
124     T t;
125     memset(&t, 0, sizeof(T));
126     if (adb_pread(fd, &t, sizeof(T), offset) != sizeof(T)) {
127         memset(&t, -1, sizeof(T));
128     }
129 
130     return t;
131 }
132 
appendBlocks(int32_t start,int count,std::vector<int32_t> * blocks)133 static void appendBlocks(int32_t start, int count, std::vector<int32_t>* blocks) {
134     if (count == 1) {
135         blocks->push_back(start);
136     } else {
137         auto oldSize = blocks->size();
138         blocks->resize(oldSize + count);
139         std::iota(blocks->begin() + oldSize, blocks->end(), start);
140     }
141 }
142 
143 template <class T>
unduplicate(std::vector<T> & v)144 static void unduplicate(std::vector<T>& v) {
145     std::unordered_set<T> uniques(v.size());
146     v.erase(std::remove_if(v.begin(), v.end(),
147                            [&uniques](T t) { return !uniques.insert(t).second; }),
148             v.end());
149 }
150 
CentralDirOffset(borrowed_fd fd,Size fileSize)151 static off64_t CentralDirOffset(borrowed_fd fd, Size fileSize) {
152     static constexpr int kZipEocdRecMinSize = 22;
153     static constexpr int32_t kZipEocdRecSig = 0x06054b50;
154     static constexpr int kZipEocdCentralDirSizeFieldOffset = 12;
155     static constexpr int kZipEocdCommentLengthFieldOffset = 20;
156 
157     int32_t sigBuf = 0;
158     off64_t eocdOffset = -1;
159     off64_t maxEocdOffset = fileSize - kZipEocdRecMinSize;
160     int16_t commentLenBuf = 0;
161 
162     // Search from the end of zip, backward to find beginning of EOCD
163     for (int16_t commentLen = 0; commentLen < fileSize; ++commentLen) {
164         sigBuf = valueAt<int32_t>(fd, maxEocdOffset - commentLen);
165         if (sigBuf == kZipEocdRecSig) {
166             commentLenBuf = valueAt<int16_t>(
167                     fd, maxEocdOffset - commentLen + kZipEocdCommentLengthFieldOffset);
168             if (commentLenBuf == commentLen) {
169                 eocdOffset = maxEocdOffset - commentLen;
170                 break;
171             }
172         }
173     }
174 
175     if (eocdOffset < 0) {
176         return -1;
177     }
178 
179     off64_t cdLen = static_cast<int64_t>(
180             valueAt<int32_t>(fd, eocdOffset + kZipEocdCentralDirSizeFieldOffset));
181 
182     return eocdOffset - cdLen;
183 }
184 
185 // Does not support APKs larger than 4GB
SignerBlockOffset(borrowed_fd fd,Size fileSize)186 static off64_t SignerBlockOffset(borrowed_fd fd, Size fileSize) {
187     static constexpr int kApkSigBlockMinSize = 32;
188     static constexpr int kApkSigBlockFooterSize = 24;
189     static constexpr int64_t APK_SIG_BLOCK_MAGIC_HI = 0x3234206b636f6c42l;
190     static constexpr int64_t APK_SIG_BLOCK_MAGIC_LO = 0x20676953204b5041l;
191 
192     off64_t cdOffset = CentralDirOffset(fd, fileSize);
193     if (cdOffset < 0) {
194         return -1;
195     }
196     // CD offset is where original signer block ends. Search backwards for magic and footer.
197     if (cdOffset < kApkSigBlockMinSize ||
198         valueAt<int64_t>(fd, cdOffset - 2 * sizeof(int64_t)) != APK_SIG_BLOCK_MAGIC_LO ||
199         valueAt<int64_t>(fd, cdOffset - sizeof(int64_t)) != APK_SIG_BLOCK_MAGIC_HI) {
200         return -1;
201     }
202     int32_t signerSizeInFooter = valueAt<int32_t>(fd, cdOffset - kApkSigBlockFooterSize);
203     off64_t signerBlockOffset = cdOffset - signerSizeInFooter - sizeof(int64_t);
204     if (signerBlockOffset < 0) {
205         return -1;
206     }
207     int32_t signerSizeInHeader = valueAt<int32_t>(fd, signerBlockOffset);
208     if (signerSizeInFooter != signerSizeInHeader) {
209         return -1;
210     }
211 
212     return signerBlockOffset;
213 }
214 
ZipPriorityBlocks(off64_t signerBlockOffset,Size fileSize)215 static std::vector<int32_t> ZipPriorityBlocks(off64_t signerBlockOffset, Size fileSize) {
216     int32_t signerBlockIndex = offsetToBlockIndex(signerBlockOffset);
217     int32_t lastBlockIndex = offsetToBlockIndex(fileSize);
218     const auto numPriorityBlocks = lastBlockIndex - signerBlockIndex + 1;
219 
220     std::vector<int32_t> zipPriorityBlocks;
221 
222     // Some magic here: most of zip libraries perform a scan for EOCD record starting at the offset
223     // of a maximum comment size from the end of the file. This means the last 65-ish KBs will be
224     // accessed first, followed by the rest of the central directory blocks. Make sure we
225     // send the data in the proper order, as central directory can be quite big by itself.
226     static constexpr auto kMaxZipCommentSize = 64 * 1024;
227     static constexpr auto kNumBlocksInEocdSearch = kMaxZipCommentSize / kBlockSize + 1;
228     if (numPriorityBlocks > kNumBlocksInEocdSearch) {
229         appendBlocks(lastBlockIndex - kNumBlocksInEocdSearch + 1, kNumBlocksInEocdSearch,
230                      &zipPriorityBlocks);
231         appendBlocks(signerBlockIndex, numPriorityBlocks - kNumBlocksInEocdSearch,
232                      &zipPriorityBlocks);
233     } else {
234         appendBlocks(signerBlockIndex, numPriorityBlocks, &zipPriorityBlocks);
235     }
236 
237     // Somehow someone keeps accessing the start of the archive, even if there's nothing really
238     // interesting there...
239     appendBlocks(0, 1, &zipPriorityBlocks);
240     return zipPriorityBlocks;
241 }
242 
openZipArchiveFd(borrowed_fd fd)243 [[maybe_unused]] static ZipArchiveHandle openZipArchiveFd(borrowed_fd fd) {
244     bool transferFdOwnership = false;
245 #ifdef _WIN32
246     //
247     // Need to create a special CRT FD here as the current one is not compatible with
248     // normal read()/write() calls that libziparchive uses.
249     // To make this work we have to create a copy of the file handle, as CRT doesn't care
250     // and closes it together with the new descriptor.
251     //
252     // Note: don't move this into a helper function, it's better to be hard to reuse because
253     //       the code is ugly and won't work unless it's a last resort.
254     //
255     auto handle = adb_get_os_handle(fd);
256     HANDLE dupedHandle;
257     if (!::DuplicateHandle(::GetCurrentProcess(), handle, ::GetCurrentProcess(), &dupedHandle, 0,
258                            false, DUPLICATE_SAME_ACCESS)) {
259         D("%s failed at DuplicateHandle: %d", __func__, (int)::GetLastError());
260         return {};
261     }
262     int osfd = _open_osfhandle((intptr_t)dupedHandle, _O_RDONLY | _O_BINARY);
263     if (osfd < 0) {
264         D("%s failed at _open_osfhandle: %d", __func__, errno);
265         ::CloseHandle(handle);
266         return {};
267     }
268     transferFdOwnership = true;
269 #else
270     int osfd = fd.get();
271 #endif
272     ZipArchiveHandle zip;
273     if (OpenArchiveFd(osfd, "apk_fd", &zip, transferFdOwnership) != 0) {
274         D("%s failed at OpenArchiveFd: %d", __func__, errno);
275 #ifdef _WIN32
276         // "_close()" is a secret WinCRT name for the regular close() function.
277         _close(osfd);
278 #endif
279         return {};
280     }
281     return zip;
282 }
283 
openZipArchive(borrowed_fd fd,Size fileSize)284 static std::pair<ZipArchiveHandle, std::unique_ptr<android::base::MappedFile>> openZipArchive(
285         borrowed_fd fd, Size fileSize) {
286 #ifndef __LP64__
287     if (fileSize >= INT_MAX) {
288         return {openZipArchiveFd(fd), nullptr};
289     }
290 #endif
291     auto mapping =
292             android::base::MappedFile::FromOsHandle(adb_get_os_handle(fd), 0, fileSize, PROT_READ);
293     if (!mapping) {
294         D("%s failed at FromOsHandle: %d", __func__, errno);
295         return {};
296     }
297     ZipArchiveHandle zip;
298     if (OpenArchiveFromMemory(mapping->data(), mapping->size(), "apk_mapping", &zip) != 0) {
299         D("%s failed at OpenArchiveFromMemory: %d", __func__, errno);
300         return {};
301     }
302     return {zip, std::move(mapping)};
303 }
304 
InstallationPriorityBlocks(borrowed_fd fd,Size fileSize)305 static std::vector<int32_t> InstallationPriorityBlocks(borrowed_fd fd, Size fileSize) {
306     static constexpr std::array<std::string_view, 3> additional_matches = {
307             "resources.arsc"sv, "AndroidManifest.xml"sv, "classes.dex"sv};
308     auto [zip, _] = openZipArchive(fd, fileSize);
309     if (!zip) {
310         return {};
311     }
312 
313     auto matcher = [](std::string_view entry_name) {
314         if (entry_name.starts_with("lib/"sv) && entry_name.ends_with(".so"sv)) {
315             return true;
316         }
317         return std::any_of(additional_matches.begin(), additional_matches.end(),
318                            [entry_name](std::string_view i) { return i == entry_name; });
319     };
320 
321     void* cookie = nullptr;
322     if (StartIteration(zip, &cookie, std::move(matcher)) != 0) {
323         D("%s failed at StartIteration: %d", __func__, errno);
324         return {};
325     }
326 
327     std::vector<int32_t> installationPriorityBlocks;
328     ZipEntry entry;
329     std::string_view entryName;
330     while (Next(cookie, &entry, &entryName) == 0) {
331         if (entryName == "classes.dex"sv) {
332             // Only the head is needed for installation
333             int32_t startBlockIndex = offsetToBlockIndex(entry.offset);
334             appendBlocks(startBlockIndex, 2, &installationPriorityBlocks);
335             D("\tadding to priority blocks: '%.*s' (%d)", (int)entryName.size(), entryName.data(),
336               2);
337         } else {
338             // Full entries are needed for installation
339             off64_t entryStartOffset = entry.offset;
340             off64_t entryEndOffset =
341                     entryStartOffset +
342                     (entry.method == kCompressStored ? entry.uncompressed_length
343                                                      : entry.compressed_length) +
344                     (entry.has_data_descriptor ? 16 /* sizeof(DataDescriptor) */ : 0);
345             int32_t startBlockIndex = offsetToBlockIndex(entryStartOffset);
346             int32_t endBlockIndex = offsetToBlockIndex(entryEndOffset);
347             int32_t numNewBlocks = endBlockIndex - startBlockIndex + 1;
348             appendBlocks(startBlockIndex, numNewBlocks, &installationPriorityBlocks);
349             D("\tadding to priority blocks: '%.*s' (%d)", (int)entryName.size(), entryName.data(),
350               numNewBlocks);
351         }
352     }
353 
354     EndIteration(cookie);
355     CloseArchive(zip);
356     return installationPriorityBlocks;
357 }
358 
PriorityBlocksForFile(const std::string & filepath,borrowed_fd fd,Size fileSize)359 std::vector<int32_t> PriorityBlocksForFile(const std::string& filepath, borrowed_fd fd,
360                                            Size fileSize) {
361     if (!android::base::EndsWithIgnoreCase(filepath, ".apk"sv)) {
362         return {};
363     }
364     off64_t signerOffset = SignerBlockOffset(fd, fileSize);
365     if (signerOffset < 0) {
366         // No signer block? not a valid APK
367         return {};
368     }
369     std::vector<int32_t> priorityBlocks = ZipPriorityBlocks(signerOffset, fileSize);
370     std::vector<int32_t> installationPriorityBlocks = InstallationPriorityBlocks(fd, fileSize);
371 
372     priorityBlocks.insert(priorityBlocks.end(), installationPriorityBlocks.begin(),
373                           installationPriorityBlocks.end());
374     unduplicate(priorityBlocks);
375     return priorityBlocks;
376 }
377 
378 }  // namespace incremental
379