blob: d65d42659f975ac5479fbb31f9c1431d5dbe853f [file] [log] [blame]
Dario Freni5a259292018-08-14 17:49:00 +01001/*
2 * Copyright (C) 2018 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
Jiyong Park69c0f112018-11-22 20:38:05 +090017#include "apex_file.h"
Andreas Gampe356e40c2018-12-26 10:59:57 -080018
19#include <fcntl.h>
20#include <sys/stat.h>
21#include <sys/types.h>
22#include <unistd.h>
23
Jiyong Park5e810232019-04-01 15:24:26 +090024#include <filesystem>
Andreas Gampe356e40c2018-12-26 10:59:57 -080025#include <fstream>
Nikita Ioffefe685a32020-09-10 19:02:56 +010026#include <span>
Jiyong Park69c0f112018-11-22 20:38:05 +090027
Jiyong Parkd02c88c2018-11-13 19:23:32 +090028#include <android-base/file.h>
Dario Freni5a259292018-08-14 17:49:00 +010029#include <android-base/logging.h>
Jiyong Park69c0f112018-11-22 20:38:05 +090030#include <android-base/scopeguard.h>
Andreas Gampe356e40c2018-12-26 10:59:57 -080031#include <android-base/strings.h>
32#include <android-base/unique_fd.h>
33#include <libavb/libavb.h>
Nikita Ioffefe685a32020-09-10 19:02:56 +010034#include <ziparchive/zip_archive.h>
Andreas Gampe356e40c2018-12-26 10:59:57 -080035
Nikita Ioffe264c4212019-09-13 16:30:17 +010036#include "apex_constants.h"
Jiyong Park5e810232019-04-01 15:24:26 +090037#include "apexd_utils.h"
Andreas Gampe356e40c2018-12-26 10:59:57 -080038
Theotime Combesd12e76b2020-07-08 16:51:23 +000039using android::base::borrowed_fd;
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +010040using android::base::Error;
Andreas Gampe356e40c2018-12-26 10:59:57 -080041using android::base::ReadFullyAtOffset;
Mohammad Samiul Islam158ef972021-01-22 17:47:41 +000042using android::base::RemoveFileIfExists;
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +010043using android::base::Result;
Andreas Gampe356e40c2018-12-26 10:59:57 -080044using android::base::unique_fd;
Dario Freni5a259292018-08-14 17:49:00 +010045
Dario Freni5a259292018-08-14 17:49:00 +010046namespace android {
47namespace apex {
Jiyong Park69c0f112018-11-22 20:38:05 +090048namespace {
Dario Freni5a259292018-08-14 17:49:00 +010049
Jiyong Park69c0f112018-11-22 20:38:05 +090050constexpr const char* kImageFilename = "apex_payload.img";
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +000051constexpr const char* kCompressedApexFilename = "original_apex";
Jiyong Park9181a2d2018-12-27 15:14:45 +090052constexpr const char* kBundledPublicKeyFilename = "apex_pubkey";
Andreas Gampe2efadc02018-11-19 16:39:45 -080053
Theotime Combesd12e76b2020-07-08 16:51:23 +000054struct FsMagic {
55 const char* type;
56 int32_t offset;
57 int16_t len;
58 const char* magic;
59};
60constexpr const FsMagic kFsType[] = {{"f2fs", 1024, 4, "\x10\x20\xf5\xf2"},
61 {"ext4", 1024 + 0x38, 2, "\123\357"}};
62
63Result<std::string> RetrieveFsType(borrowed_fd fd, int32_t image_offset) {
64 for (const auto& fs : kFsType) {
65 char buf[fs.len];
66 if (!ReadFullyAtOffset(fd, buf, fs.len, image_offset + fs.offset)) {
67 return ErrnoError() << "Couldn't read filesystem magic";
68 }
69 if (memcmp(buf, fs.magic, fs.len) == 0) {
70 return std::string(fs.type);
71 }
72 }
73 return Error() << "Couldn't find filesystem magic";
74}
75
Jooyung Han7dca50c2019-04-12 04:52:42 +090076} // namespace
77
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +010078Result<ApexFile> ApexFile::Open(const std::string& path) {
Mohammad Samiul Islam40253062021-01-08 13:24:54 +000079 std::optional<int32_t> image_offset;
80 std::optional<size_t> image_size;
Jiyong Park69c0f112018-11-22 20:38:05 +090081 std::string manifest_content;
Jiyong Park9181a2d2018-12-27 15:14:45 +090082 std::string pubkey;
Mohammad Samiul Islam40253062021-01-08 13:24:54 +000083 std::optional<std::string> fs_type;
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +000084 ZipEntry entry;
Jiyong Park69c0f112018-11-22 20:38:05 +090085
Theotime Combesd12e76b2020-07-08 16:51:23 +000086 unique_fd fd(open(path.c_str(), O_RDONLY | O_BINARY | O_CLOEXEC));
87 if (fd < 0) {
88 return Error() << "Failed to open package " << path << ": "
89 << "I/O error";
90 }
George Burgess IVdfc059d2020-08-31 10:40:27 -070091
92 ZipArchiveHandle handle;
93 auto handle_guard =
94 android::base::make_scope_guard([&handle] { CloseArchive(handle); });
Theotime Combesd12e76b2020-07-08 16:51:23 +000095 int ret = OpenArchiveFd(fd.get(), path.c_str(), &handle, false);
Jiyong Park8f55a212019-06-03 20:48:15 +090096 if (ret < 0) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +010097 return Error() << "Failed to open package " << path << ": "
98 << ErrorCodeString(ret);
Jiyong Park8f55a212019-06-03 20:48:15 +090099 }
Jiyong Park69c0f112018-11-22 20:38:05 +0900100
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000101 bool is_compressed = true;
102 ret = FindEntry(handle, kCompressedApexFilename, &entry);
Jiyong Park8f55a212019-06-03 20:48:15 +0900103 if (ret < 0) {
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000104 is_compressed = false;
Jiyong Park8f55a212019-06-03 20:48:15 +0900105 }
Jiyong Park69c0f112018-11-22 20:38:05 +0900106
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000107 if (!is_compressed) {
108 // Locate the mountable image within the zipfile and store offset and size.
109 ret = FindEntry(handle, kImageFilename, &entry);
110 if (ret < 0) {
111 return Error() << "Could not find entry \"" << kImageFilename
Mohammad Samiul Islama3ec5bb2021-01-08 18:52:59 +0000112 << "\" or \"" << kCompressedApexFilename
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000113 << "\" in package " << path << ": "
114 << ErrorCodeString(ret);
115 }
116 image_offset = entry.offset;
117 image_size = entry.uncompressed_length;
118
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000119 auto fs_type_result = RetrieveFsType(fd, image_offset.value());
120 if (!fs_type_result.ok()) {
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000121 return Error() << "Failed to retrieve filesystem type for " << path
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000122 << ": " << fs_type_result.error();
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000123 }
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000124 fs_type = std::move(*fs_type_result);
Theotime Combesd12e76b2020-07-08 16:51:23 +0000125 }
126
Dario Frenia277bdf2019-11-05 22:37:49 +0000127 ret = FindEntry(handle, kManifestFilenamePb, &entry);
Jiyong Park8f55a212019-06-03 20:48:15 +0900128 if (ret < 0) {
Jooyung Han43ec48f2020-05-12 12:01:05 +0900129 return Error() << "Could not find entry \"" << kManifestFilenamePb
130 << "\" in package " << path << ": " << ErrorCodeString(ret);
Jiyong Park8f55a212019-06-03 20:48:15 +0900131 }
Jiyong Park69c0f112018-11-22 20:38:05 +0900132
Jiyong Park8f55a212019-06-03 20:48:15 +0900133 uint32_t length = entry.uncompressed_length;
134 manifest_content.resize(length, '\0');
135 ret = ExtractToMemory(handle, &entry,
136 reinterpret_cast<uint8_t*>(&(manifest_content)[0]),
137 length);
138 if (ret != 0) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100139 return Error() << "Failed to extract manifest from package " << path << ": "
140 << ErrorCodeString(ret);
Jiyong Park8f55a212019-06-03 20:48:15 +0900141 }
Jiyong Park69c0f112018-11-22 20:38:05 +0900142
Jiyong Park8f55a212019-06-03 20:48:15 +0900143 ret = FindEntry(handle, kBundledPublicKeyFilename, &entry);
144 if (ret >= 0) {
Jiyong Park8f55a212019-06-03 20:48:15 +0900145 length = entry.uncompressed_length;
146 pubkey.resize(length, '\0');
Jiyong Park69c0f112018-11-22 20:38:05 +0900147 ret = ExtractToMemory(handle, &entry,
Jiyong Park8f55a212019-06-03 20:48:15 +0900148 reinterpret_cast<uint8_t*>(&(pubkey)[0]), length);
Jiyong Park69c0f112018-11-22 20:38:05 +0900149 if (ret != 0) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100150 return Error() << "Failed to extract public key from package " << path
151 << ": " << ErrorCodeString(ret);
Jiyong Park69c0f112018-11-22 20:38:05 +0900152 }
Jiyong Parkd02c88c2018-11-13 19:23:32 +0900153 }
154
Jooyung Han43ec48f2020-05-12 12:01:05 +0900155 Result<ApexManifest> manifest = ParseManifest(manifest_content);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900156 if (!manifest.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100157 return manifest.error();
Dario Freni5a259292018-08-14 17:49:00 +0100158 }
159
Jooyung Han43ec48f2020-05-12 12:01:05 +0900160 return ApexFile(path, image_offset, image_size, std::move(*manifest), pubkey,
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000161 fs_type, is_compressed);
Dario Freni5a259292018-08-14 17:49:00 +0100162}
163
Andreas Gampe356e40c2018-12-26 10:59:57 -0800164// AVB-related code.
165
166namespace {
167
Andreas Gampe356e40c2018-12-26 10:59:57 -0800168static constexpr int kVbMetaMaxSize = 64 * 1024;
169
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000170std::string BytesToHex(const uint8_t* bytes, size_t bytes_len) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800171 std::ostringstream s;
172
173 s << std::hex << std::setfill('0');
174 for (size_t i = 0; i < bytes_len; i++) {
175 s << std::setw(2) << static_cast<int>(bytes[i]);
176 }
177 return s.str();
178}
179
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000180std::string GetSalt(const AvbHashtreeDescriptor& desc,
181 const uint8_t* trailing_data) {
182 const uint8_t* desc_salt = trailing_data + desc.partition_name_len;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800183
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000184 return BytesToHex(desc_salt, desc.salt_len);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800185}
186
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000187std::string GetDigest(const AvbHashtreeDescriptor& desc,
188 const uint8_t* trailing_data) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800189 const uint8_t* desc_digest =
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000190 trailing_data + desc.partition_name_len + desc.salt_len;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800191
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000192 return BytesToHex(desc_digest, desc.root_digest_len);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800193}
194
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000195Result<std::unique_ptr<AvbFooter>> GetAvbFooter(const ApexFile& apex,
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100196 const unique_fd& fd) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800197 std::array<uint8_t, AVB_FOOTER_SIZE> footer_data;
198 auto footer = std::make_unique<AvbFooter>();
199
200 // The AVB footer is located in the last part of the image
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000201 if (!apex.GetImageOffset() || !apex.GetImageSize()) {
202 return Error() << "Cannot check avb footer without image offset and size";
203 }
204 off_t offset = apex.GetImageSize().value() + apex.GetImageOffset().value() -
205 AVB_FOOTER_SIZE;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800206 int ret = lseek(fd, offset, SEEK_SET);
207 if (ret == -1) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100208 return ErrnoError() << "Couldn't seek to AVB footer";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800209 }
210
211 ret = read(fd, footer_data.data(), AVB_FOOTER_SIZE);
212 if (ret != AVB_FOOTER_SIZE) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100213 return ErrnoError() << "Couldn't read AVB footer";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800214 }
215
216 if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_data.data(),
217 footer.get())) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100218 return Error() << "AVB footer verification failed.";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800219 }
220
221 LOG(VERBOSE) << "AVB footer verification successful.";
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100222 return footer;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800223}
224
Nikita Ioffea78f8ef2019-11-08 13:36:38 +0000225bool CompareKeys(const uint8_t* key, size_t length,
226 const std::string& public_key_content) {
227 return public_key_content.length() == length &&
228 memcmp(&public_key_content[0], key, length) == 0;
Jiyong Park9181a2d2018-12-27 15:14:45 +0900229}
230
Nikita Ioffefe685a32020-09-10 19:02:56 +0100231// Verifies correctness of vbmeta and returns public key it was signed with.
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000232Result<std::span<const uint8_t>> VerifyVbMetaSignature(const ApexFile& apex,
Nikita Ioffefe685a32020-09-10 19:02:56 +0100233 const uint8_t* data,
234 size_t length) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800235 const uint8_t* pk;
236 size_t pk_len;
237 AvbVBMetaVerifyResult res;
238
239 res = avb_vbmeta_image_verify(data, length, &pk, &pk_len);
240 switch (res) {
241 case AVB_VBMETA_VERIFY_RESULT_OK:
242 break;
243 case AVB_VBMETA_VERIFY_RESULT_OK_NOT_SIGNED:
244 case AVB_VBMETA_VERIFY_RESULT_HASH_MISMATCH:
245 case AVB_VBMETA_VERIFY_RESULT_SIGNATURE_MISMATCH:
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100246 return Error() << "Error verifying " << apex.GetPath() << ": "
247 << avb_vbmeta_verify_result_to_string(res);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800248 case AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER:
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100249 return Error() << "Error verifying " << apex.GetPath() << ": "
250 << "invalid vbmeta header";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800251 case AVB_VBMETA_VERIFY_RESULT_UNSUPPORTED_VERSION:
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100252 return Error() << "Error verifying " << apex.GetPath() << ": "
253 << "unsupported version";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800254 default:
Nikita Ioffefe685a32020-09-10 19:02:56 +0100255 return Error() << "Unknown vmbeta_image_verify return value : " << res;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800256 }
257
Nikita Ioffefe685a32020-09-10 19:02:56 +0100258 return std::span<const uint8_t>(pk, pk_len);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800259}
260
Nikita Ioffe9714fe92020-12-22 20:56:33 +0000261Result<std::unique_ptr<uint8_t[]>> VerifyVbMeta(const ApexFile& apex,
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100262 const unique_fd& fd,
Nikita Ioffefe685a32020-09-10 19:02:56 +0100263 const AvbFooter& footer,
264 const std::string& public_key) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800265 if (footer.vbmeta_size > kVbMetaMaxSize) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100266 return Errorf("VbMeta size in footer exceeds kVbMetaMaxSize.");
Andreas Gampe356e40c2018-12-26 10:59:57 -0800267 }
268
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000269 if (!apex.GetImageOffset()) {
270 return Error() << "Cannot check VbMeta size without image offset";
271 }
272
273 off_t offset = apex.GetImageOffset().value() + footer.vbmeta_offset;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800274 std::unique_ptr<uint8_t[]> vbmeta_buf(new uint8_t[footer.vbmeta_size]);
275
276 if (!ReadFullyAtOffset(fd, vbmeta_buf.get(), footer.vbmeta_size, offset)) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100277 return ErrnoError() << "Couldn't read AVB meta-data";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800278 }
279
Nikita Ioffefe685a32020-09-10 19:02:56 +0100280 Result<std::span<const uint8_t>> st =
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000281 VerifyVbMetaSignature(apex, vbmeta_buf.get(), footer.vbmeta_size);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900282 if (!st.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100283 return st.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800284 }
285
Nikita Ioffefe685a32020-09-10 19:02:56 +0100286 if (!CompareKeys(st->data(), st->size(), public_key)) {
287 return Error() << "Error verifying " << apex.GetPath() << " : "
288 << "public key doesn't match the pre-installed one";
289 }
290
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100291 return vbmeta_buf;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800292}
293
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000294Result<const AvbHashtreeDescriptor*> FindDescriptor(uint8_t* vbmeta_data,
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100295 size_t vbmeta_size) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800296 const AvbDescriptor** descriptors;
297 size_t num_descriptors;
298
299 descriptors =
300 avb_descriptor_get_all(vbmeta_data, vbmeta_size, &num_descriptors);
301
Jooyung Handf858e82019-04-01 18:06:39 +0900302 // avb_descriptor_get_all() returns an internally allocated array
303 // of pointers and it needs to be avb_free()ed after using it.
304 auto guard = android::base::ScopeGuard(std::bind(avb_free, descriptors));
305
Andreas Gampe356e40c2018-12-26 10:59:57 -0800306 for (size_t i = 0; i < num_descriptors; i++) {
307 AvbDescriptor desc;
308 if (!avb_descriptor_validate_and_byteswap(descriptors[i], &desc)) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100309 return Errorf("Couldn't validate AvbDescriptor.");
Andreas Gampe356e40c2018-12-26 10:59:57 -0800310 }
311
312 if (desc.tag != AVB_DESCRIPTOR_TAG_HASHTREE) {
313 // Ignore other descriptors
314 continue;
315 }
316
Nikita Ioffed71ce1d2020-04-30 01:19:41 +0100317 // Check that hashtree descriptor actually fits into memory.
318 const uint8_t* vbmeta_end = vbmeta_data + vbmeta_size;
319 if ((uint8_t*)descriptors[i] + sizeof(AvbHashtreeDescriptor) > vbmeta_end) {
320 return Errorf("Invalid length for AvbHashtreeDescriptor");
321 }
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100322 return (const AvbHashtreeDescriptor*)descriptors[i];
Andreas Gampe356e40c2018-12-26 10:59:57 -0800323 }
324
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100325 return Errorf("Couldn't find any AVB hashtree descriptors.");
Andreas Gampe356e40c2018-12-26 10:59:57 -0800326}
327
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000328Result<std::unique_ptr<AvbHashtreeDescriptor>> VerifyDescriptor(
Andreas Gampe356e40c2018-12-26 10:59:57 -0800329 const AvbHashtreeDescriptor* desc) {
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000330 auto verified_desc = std::make_unique<AvbHashtreeDescriptor>();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800331
332 if (!avb_hashtree_descriptor_validate_and_byteswap(desc,
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000333 verified_desc.get())) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100334 return Errorf("Couldn't validate AvbDescriptor.");
Andreas Gampe356e40c2018-12-26 10:59:57 -0800335 }
336
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000337 return verified_desc;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800338}
339
340} // namespace
341
Nikita Ioffefe685a32020-09-10 19:02:56 +0100342Result<ApexVerityData> ApexFile::VerifyApexVerity(
343 const std::string& public_key) const {
Mohammad Samiul Islama3ec5bb2021-01-08 18:52:59 +0000344 if (IsCompressed()) {
345 return Error() << "Cannot verify ApexVerity of compressed APEX";
346 }
347
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000348 ApexVerityData verity_data;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800349
350 unique_fd fd(open(GetPath().c_str(), O_RDONLY | O_CLOEXEC));
351 if (fd.get() == -1) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100352 return ErrnoError() << "Failed to open " << GetPath();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800353 }
354
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000355 Result<std::unique_ptr<AvbFooter>> footer = GetAvbFooter(*this, fd);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900356 if (!footer.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100357 return footer.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800358 }
359
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100360 Result<std::unique_ptr<uint8_t[]>> vbmeta_data =
Nikita Ioffe9714fe92020-12-22 20:56:33 +0000361 VerifyVbMeta(*this, fd, **footer, public_key);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900362 if (!vbmeta_data.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100363 return vbmeta_data.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800364 }
365
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100366 Result<const AvbHashtreeDescriptor*> descriptor =
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000367 FindDescriptor(vbmeta_data->get(), (*footer)->vbmeta_size);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900368 if (!descriptor.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100369 return descriptor.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800370 }
371
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000372 Result<std::unique_ptr<AvbHashtreeDescriptor>> verified_descriptor =
373 VerifyDescriptor(*descriptor);
374 if (!verified_descriptor.ok()) {
375 return verified_descriptor.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800376 }
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000377 verity_data.desc = std::move(*verified_descriptor);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800378
379 // This area is now safe to access, because we just verified it
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000380 const uint8_t* trailing_data =
Andreas Gampe356e40c2018-12-26 10:59:57 -0800381 (const uint8_t*)*descriptor + sizeof(AvbHashtreeDescriptor);
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000382 verity_data.hash_algorithm =
Jooyung Hanf7c8d032019-04-11 15:12:09 +0900383 reinterpret_cast<const char*>((*descriptor)->hash_algorithm);
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000384 verity_data.salt = GetSalt(*verity_data.desc, trailing_data);
385 verity_data.root_digest = GetDigest(*verity_data.desc, trailing_data);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800386
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000387 return verity_data;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800388}
389
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000390Result<void> ApexFile::Decompress(const std::string& dest_path) const {
391 const std::string& src_path = GetPath();
392
393 // We should decompress compressed APEX files only
394 if (!IsCompressed()) {
395 return ErrnoError() << "Cannot decompress an uncompressed APEX";
396 }
397
398 // Get file descriptor of the compressed apex file
399 unique_fd src_fd(open(src_path.c_str(), O_RDONLY | O_CLOEXEC));
400 if (src_fd.get() == -1) {
401 return ErrnoError() << "Failed to open compressed APEX " << GetPath();
402 }
403
404 // Open it as a zip file
405 ZipArchiveHandle handle;
406 int ret = OpenArchiveFd(src_fd.get(), src_path.c_str(), &handle, false);
407 if (ret < 0) {
408 return Error() << "Failed to open package " << src_path << ": "
409 << ErrorCodeString(ret);
410 }
411 auto handle_guard =
412 android::base::make_scope_guard([&handle] { CloseArchive(handle); });
413
414 // Find the original apex file inside the zip and extract to dest
415 ZipEntry entry;
416 ret = FindEntry(handle, kCompressedApexFilename, &entry);
417 if (ret < 0) {
418 return Error() << "Could not find entry \"" << kCompressedApexFilename
419 << "\" in package " << src_path << ": "
420 << ErrorCodeString(ret);
421 }
422
423 // Open destination file descriptor
424 unique_fd dest_fd(
425 open(dest_path.c_str(), O_WRONLY | O_CLOEXEC | O_CREAT, 0644));
426 if (dest_fd.get() == -1) {
427 return ErrnoError() << "Failed to open decompression destination "
428 << GetPath();
429 }
Mohammad Samiul Islam158ef972021-01-22 17:47:41 +0000430
431 // Prepare a guard that deletes the extracted file if anything goes wrong
432 auto decompressed_guard = android::base::make_scope_guard(
433 [&dest_path] { RemoveFileIfExists(dest_path); });
434
435 // Extract the original_apex to dest_path
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000436 ret = ExtractEntryToFile(handle, &entry, dest_fd.get());
437 if (ret < 0) {
438 return Error() << "Could not decompress to file " << dest_path
439 << ErrorCodeString(ret);
440 }
441
Mohammad Samiul Islam158ef972021-01-22 17:47:41 +0000442 // Post decompression verification
443 auto decompressed_apex = ApexFile::Open(dest_path);
444 if (!decompressed_apex.ok()) {
445 return Error() << "Could not open decompressed APEX: "
446 << decompressed_apex.error();
447 }
448 if (GetBundledPublicKey() != decompressed_apex->GetBundledPublicKey()) {
449 return Error()
450 << "Public key of compressed APEX is different than original APEX";
451 }
452
453 // Verification complete. Accept the decompressed file
454 decompressed_guard.Disable();
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000455 LOG(VERBOSE) << "Decompressed " << src_path << " to " << dest_path;
Mohammad Samiul Islam158ef972021-01-22 17:47:41 +0000456
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000457 return {};
458}
459
Dario Freni5a259292018-08-14 17:49:00 +0100460} // namespace apex
461} // namespace android