blob: 9ed48aa17bfd58e23933c9da7f5d609a70c85b68 [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
Jiyong Parkd02c88c2018-11-13 19:23:32 +090019#include <android-base/file.h>
Dario Freni5a259292018-08-14 17:49:00 +010020#include <android-base/logging.h>
Jiyong Park69c0f112018-11-22 20:38:05 +090021#include <android-base/scopeguard.h>
Andreas Gampe356e40c2018-12-26 10:59:57 -080022#include <android-base/strings.h>
23#include <android-base/unique_fd.h>
Jooyung Han4ef334b2021-09-27 15:28:17 +090024#include <fcntl.h>
Andreas Gampe356e40c2018-12-26 10:59:57 -080025#include <libavb/libavb.h>
Jooyung Han4ef334b2021-09-27 15:28:17 +090026#include <sys/stat.h>
27#include <sys/types.h>
28#include <unistd.h>
Nikita Ioffefe685a32020-09-10 19:02:56 +010029#include <ziparchive/zip_archive.h>
Andreas Gampe356e40c2018-12-26 10:59:57 -080030
Jooyung Han4ef334b2021-09-27 15:28:17 +090031#include <filesystem>
32#include <fstream>
33#include <span>
34
Nikita Ioffe264c4212019-09-13 16:30:17 +010035#include "apex_constants.h"
Jiyong Park5e810232019-04-01 15:24:26 +090036#include "apexd_utils.h"
Jooyung Han4ef334b2021-09-27 15:28:17 +090037#include "apexd_verity.h"
Andreas Gampe356e40c2018-12-26 10:59:57 -080038
Theotime Combesd12e76b2020-07-08 16:51:23 +000039using android::base::borrowed_fd;
Nikita Ioffe567b1c92021-03-13 02:32:05 +000040using android::base::ErrnoError;
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +010041using android::base::Error;
Andreas Gampe356e40c2018-12-26 10:59:57 -080042using android::base::ReadFullyAtOffset;
Mohammad Samiul Islam158ef972021-01-22 17:47:41 +000043using android::base::RemoveFileIfExists;
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +010044using android::base::Result;
Andreas Gampe356e40c2018-12-26 10:59:57 -080045using android::base::unique_fd;
Nikita Ioffe567b1c92021-03-13 02:32:05 +000046using ::apex::proto::ApexManifest;
Dario Freni5a259292018-08-14 17:49:00 +010047
Dario Freni5a259292018-08-14 17:49:00 +010048namespace android {
49namespace apex {
Jiyong Park69c0f112018-11-22 20:38:05 +090050namespace {
Dario Freni5a259292018-08-14 17:49:00 +010051
Jiyong Park69c0f112018-11-22 20:38:05 +090052constexpr const char* kImageFilename = "apex_payload.img";
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +000053constexpr const char* kCompressedApexFilename = "original_apex";
Jiyong Park9181a2d2018-12-27 15:14:45 +090054constexpr const char* kBundledPublicKeyFilename = "apex_pubkey";
Andreas Gampe2efadc02018-11-19 16:39:45 -080055
Theotime Combesd12e76b2020-07-08 16:51:23 +000056struct FsMagic {
57 const char* type;
58 int32_t offset;
59 int16_t len;
60 const char* magic;
61};
62constexpr const FsMagic kFsType[] = {{"f2fs", 1024, 4, "\x10\x20\xf5\xf2"},
Huang Jianan942d4e52021-08-02 15:00:02 +080063 {"ext4", 1024 + 0x38, 2, "\123\357"},
64 {"erofs", 1024, 4, "\xe2\xe1\xf5\xe0"}};
Theotime Combesd12e76b2020-07-08 16:51:23 +000065
Bart Van Asschecf037d92021-07-28 09:16:43 -070066Result<std::string> RetrieveFsType(borrowed_fd fd, uint32_t image_offset) {
Theotime Combesd12e76b2020-07-08 16:51:23 +000067 for (const auto& fs : kFsType) {
68 char buf[fs.len];
69 if (!ReadFullyAtOffset(fd, buf, fs.len, image_offset + fs.offset)) {
70 return ErrnoError() << "Couldn't read filesystem magic";
71 }
72 if (memcmp(buf, fs.magic, fs.len) == 0) {
73 return std::string(fs.type);
74 }
75 }
76 return Error() << "Couldn't find filesystem magic";
77}
78
Jooyung Han7dca50c2019-04-12 04:52:42 +090079} // namespace
80
Jooyung Han73710212021-06-02 19:29:47 +090081Result<ApexFile> ApexFile::Open(const std::string& path) {
Bart Van Asschecf037d92021-07-28 09:16:43 -070082 std::optional<uint32_t> image_offset;
Mohammad Samiul Islam40253062021-01-08 13:24:54 +000083 std::optional<size_t> image_size;
Jiyong Park69c0f112018-11-22 20:38:05 +090084 std::string manifest_content;
Jiyong Park9181a2d2018-12-27 15:14:45 +090085 std::string pubkey;
Mohammad Samiul Islam40253062021-01-08 13:24:54 +000086 std::optional<std::string> fs_type;
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +000087 ZipEntry entry;
Jiyong Park69c0f112018-11-22 20:38:05 +090088
Theotime Combesd12e76b2020-07-08 16:51:23 +000089 unique_fd fd(open(path.c_str(), O_RDONLY | O_BINARY | O_CLOEXEC));
90 if (fd < 0) {
Jooyung Han0f817622021-04-12 20:05:24 +090091 return ErrnoError() << "Failed to open package " << path << ": "
92 << "I/O error";
Theotime Combesd12e76b2020-07-08 16:51:23 +000093 }
George Burgess IVdfc059d2020-08-31 10:40:27 -070094
95 ZipArchiveHandle handle;
96 auto handle_guard =
97 android::base::make_scope_guard([&handle] { CloseArchive(handle); });
Jooyung Han3bb52272021-07-06 22:28:46 +090098 int ret = OpenArchiveFd(fd.get(), path.c_str(), &handle,
99 /*assume_ownership=*/false);
Jiyong Park8f55a212019-06-03 20:48:15 +0900100 if (ret < 0) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100101 return Error() << "Failed to open package " << path << ": "
102 << ErrorCodeString(ret);
Jiyong Park8f55a212019-06-03 20:48:15 +0900103 }
Jiyong Park69c0f112018-11-22 20:38:05 +0900104
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000105 bool is_compressed = true;
106 ret = FindEntry(handle, kCompressedApexFilename, &entry);
Jiyong Park8f55a212019-06-03 20:48:15 +0900107 if (ret < 0) {
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000108 is_compressed = false;
Jiyong Park8f55a212019-06-03 20:48:15 +0900109 }
Jiyong Park69c0f112018-11-22 20:38:05 +0900110
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000111 if (!is_compressed) {
112 // Locate the mountable image within the zipfile and store offset and size.
113 ret = FindEntry(handle, kImageFilename, &entry);
114 if (ret < 0) {
115 return Error() << "Could not find entry \"" << kImageFilename
Mohammad Samiul Islama3ec5bb2021-01-08 18:52:59 +0000116 << "\" or \"" << kCompressedApexFilename
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000117 << "\" in package " << path << ": "
118 << ErrorCodeString(ret);
119 }
120 image_offset = entry.offset;
121 image_size = entry.uncompressed_length;
122
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000123 auto fs_type_result = RetrieveFsType(fd, image_offset.value());
124 if (!fs_type_result.ok()) {
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000125 return Error() << "Failed to retrieve filesystem type for " << path
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000126 << ": " << fs_type_result.error();
Mohammad Samiul Islam7e3140c2020-11-30 16:53:11 +0000127 }
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000128 fs_type = std::move(*fs_type_result);
Theotime Combesd12e76b2020-07-08 16:51:23 +0000129 }
130
Dario Frenia277bdf2019-11-05 22:37:49 +0000131 ret = FindEntry(handle, kManifestFilenamePb, &entry);
Jiyong Park8f55a212019-06-03 20:48:15 +0900132 if (ret < 0) {
Jooyung Han43ec48f2020-05-12 12:01:05 +0900133 return Error() << "Could not find entry \"" << kManifestFilenamePb
134 << "\" in package " << path << ": " << ErrorCodeString(ret);
Jiyong Park8f55a212019-06-03 20:48:15 +0900135 }
Jiyong Park69c0f112018-11-22 20:38:05 +0900136
Jiyong Park8f55a212019-06-03 20:48:15 +0900137 uint32_t length = entry.uncompressed_length;
138 manifest_content.resize(length, '\0');
139 ret = ExtractToMemory(handle, &entry,
140 reinterpret_cast<uint8_t*>(&(manifest_content)[0]),
141 length);
142 if (ret != 0) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100143 return Error() << "Failed to extract manifest from package " << path << ": "
144 << ErrorCodeString(ret);
Jiyong Park8f55a212019-06-03 20:48:15 +0900145 }
Jiyong Park69c0f112018-11-22 20:38:05 +0900146
Jiyong Park8f55a212019-06-03 20:48:15 +0900147 ret = FindEntry(handle, kBundledPublicKeyFilename, &entry);
148 if (ret >= 0) {
Jiyong Park8f55a212019-06-03 20:48:15 +0900149 length = entry.uncompressed_length;
150 pubkey.resize(length, '\0');
Jiyong Park69c0f112018-11-22 20:38:05 +0900151 ret = ExtractToMemory(handle, &entry,
Jiyong Park8f55a212019-06-03 20:48:15 +0900152 reinterpret_cast<uint8_t*>(&(pubkey)[0]), length);
Jiyong Park69c0f112018-11-22 20:38:05 +0900153 if (ret != 0) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100154 return Error() << "Failed to extract public key from package " << path
155 << ": " << ErrorCodeString(ret);
Jiyong Park69c0f112018-11-22 20:38:05 +0900156 }
Jiyong Parkd02c88c2018-11-13 19:23:32 +0900157 }
158
Jooyung Han43ec48f2020-05-12 12:01:05 +0900159 Result<ApexManifest> manifest = ParseManifest(manifest_content);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900160 if (!manifest.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100161 return manifest.error();
Dario Freni5a259292018-08-14 17:49:00 +0100162 }
163
Nikita Ioffe0625b502021-02-25 21:37:25 +0000164 if (is_compressed && manifest->providesharedapexlibs()) {
165 return Error() << "Apex providing sharedlibs shouldn't be compressed";
166 }
167
Jiyong Parkbdf82202021-02-03 20:12:42 +0900168 // b/179211712 the stored path should be the realpath, otherwise the path we
169 // get by scanning the directory would be different from the path we get
170 // by reading /proc/mounts, if the apex file is on a symlink dir.
171 std::string realpath;
172 if (!android::base::Realpath(path, &realpath)) {
173 return ErrnoError() << "can't get realpath of " << path;
174 }
175
176 return ApexFile(realpath, image_offset, image_size, std::move(*manifest),
Jooyung Han73710212021-06-02 19:29:47 +0900177 pubkey, fs_type, is_compressed);
Dario Freni5a259292018-08-14 17:49:00 +0100178}
179
Andreas Gampe356e40c2018-12-26 10:59:57 -0800180// AVB-related code.
181
182namespace {
183
Andreas Gampe356e40c2018-12-26 10:59:57 -0800184static constexpr int kVbMetaMaxSize = 64 * 1024;
185
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000186std::string GetSalt(const AvbHashtreeDescriptor& desc,
187 const uint8_t* trailing_data) {
188 const uint8_t* desc_salt = trailing_data + desc.partition_name_len;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800189
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000190 return BytesToHex(desc_salt, desc.salt_len);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800191}
192
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000193std::string GetDigest(const AvbHashtreeDescriptor& desc,
194 const uint8_t* trailing_data) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800195 const uint8_t* desc_digest =
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000196 trailing_data + desc.partition_name_len + desc.salt_len;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800197
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000198 return BytesToHex(desc_digest, desc.root_digest_len);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800199}
200
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000201Result<std::unique_ptr<AvbFooter>> GetAvbFooter(const ApexFile& apex,
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100202 const unique_fd& fd) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800203 std::array<uint8_t, AVB_FOOTER_SIZE> footer_data;
204 auto footer = std::make_unique<AvbFooter>();
205
206 // The AVB footer is located in the last part of the image
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000207 if (!apex.GetImageOffset() || !apex.GetImageSize()) {
208 return Error() << "Cannot check avb footer without image offset and size";
209 }
210 off_t offset = apex.GetImageSize().value() + apex.GetImageOffset().value() -
211 AVB_FOOTER_SIZE;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800212 int ret = lseek(fd, offset, SEEK_SET);
213 if (ret == -1) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100214 return ErrnoError() << "Couldn't seek to AVB footer";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800215 }
216
217 ret = read(fd, footer_data.data(), AVB_FOOTER_SIZE);
218 if (ret != AVB_FOOTER_SIZE) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100219 return ErrnoError() << "Couldn't read AVB footer";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800220 }
221
222 if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_data.data(),
223 footer.get())) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100224 return Error() << "AVB footer verification failed.";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800225 }
226
227 LOG(VERBOSE) << "AVB footer verification successful.";
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100228 return footer;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800229}
230
Nikita Ioffea78f8ef2019-11-08 13:36:38 +0000231bool CompareKeys(const uint8_t* key, size_t length,
232 const std::string& public_key_content) {
233 return public_key_content.length() == length &&
234 memcmp(&public_key_content[0], key, length) == 0;
Jiyong Park9181a2d2018-12-27 15:14:45 +0900235}
236
Nikita Ioffefe685a32020-09-10 19:02:56 +0100237// Verifies correctness of vbmeta and returns public key it was signed with.
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000238Result<std::span<const uint8_t>> VerifyVbMetaSignature(const ApexFile& apex,
Nikita Ioffefe685a32020-09-10 19:02:56 +0100239 const uint8_t* data,
240 size_t length) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800241 const uint8_t* pk;
242 size_t pk_len;
243 AvbVBMetaVerifyResult res;
244
245 res = avb_vbmeta_image_verify(data, length, &pk, &pk_len);
246 switch (res) {
247 case AVB_VBMETA_VERIFY_RESULT_OK:
248 break;
249 case AVB_VBMETA_VERIFY_RESULT_OK_NOT_SIGNED:
250 case AVB_VBMETA_VERIFY_RESULT_HASH_MISMATCH:
251 case AVB_VBMETA_VERIFY_RESULT_SIGNATURE_MISMATCH:
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100252 return Error() << "Error verifying " << apex.GetPath() << ": "
253 << avb_vbmeta_verify_result_to_string(res);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800254 case AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER:
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100255 return Error() << "Error verifying " << apex.GetPath() << ": "
256 << "invalid vbmeta header";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800257 case AVB_VBMETA_VERIFY_RESULT_UNSUPPORTED_VERSION:
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100258 return Error() << "Error verifying " << apex.GetPath() << ": "
259 << "unsupported version";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800260 default:
Nikita Ioffefe685a32020-09-10 19:02:56 +0100261 return Error() << "Unknown vmbeta_image_verify return value : " << res;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800262 }
263
Nikita Ioffefe685a32020-09-10 19:02:56 +0100264 return std::span<const uint8_t>(pk, pk_len);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800265}
266
Nikita Ioffe9714fe92020-12-22 20:56:33 +0000267Result<std::unique_ptr<uint8_t[]>> VerifyVbMeta(const ApexFile& apex,
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100268 const unique_fd& fd,
Nikita Ioffefe685a32020-09-10 19:02:56 +0100269 const AvbFooter& footer,
270 const std::string& public_key) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800271 if (footer.vbmeta_size > kVbMetaMaxSize) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100272 return Errorf("VbMeta size in footer exceeds kVbMetaMaxSize.");
Andreas Gampe356e40c2018-12-26 10:59:57 -0800273 }
274
Mohammad Samiul Islam40253062021-01-08 13:24:54 +0000275 if (!apex.GetImageOffset()) {
276 return Error() << "Cannot check VbMeta size without image offset";
277 }
278
279 off_t offset = apex.GetImageOffset().value() + footer.vbmeta_offset;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800280 std::unique_ptr<uint8_t[]> vbmeta_buf(new uint8_t[footer.vbmeta_size]);
281
282 if (!ReadFullyAtOffset(fd, vbmeta_buf.get(), footer.vbmeta_size, offset)) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100283 return ErrnoError() << "Couldn't read AVB meta-data";
Andreas Gampe356e40c2018-12-26 10:59:57 -0800284 }
285
Nikita Ioffefe685a32020-09-10 19:02:56 +0100286 Result<std::span<const uint8_t>> st =
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000287 VerifyVbMetaSignature(apex, vbmeta_buf.get(), footer.vbmeta_size);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900288 if (!st.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100289 return st.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800290 }
291
Nikita Ioffefe685a32020-09-10 19:02:56 +0100292 if (!CompareKeys(st->data(), st->size(), public_key)) {
293 return Error() << "Error verifying " << apex.GetPath() << " : "
294 << "public key doesn't match the pre-installed one";
295 }
296
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100297 return vbmeta_buf;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800298}
299
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000300Result<const AvbHashtreeDescriptor*> FindDescriptor(uint8_t* vbmeta_data,
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100301 size_t vbmeta_size) {
Andreas Gampe356e40c2018-12-26 10:59:57 -0800302 const AvbDescriptor** descriptors;
303 size_t num_descriptors;
304
305 descriptors =
306 avb_descriptor_get_all(vbmeta_data, vbmeta_size, &num_descriptors);
307
Jooyung Handf858e82019-04-01 18:06:39 +0900308 // avb_descriptor_get_all() returns an internally allocated array
309 // of pointers and it needs to be avb_free()ed after using it.
310 auto guard = android::base::ScopeGuard(std::bind(avb_free, descriptors));
311
Andreas Gampe356e40c2018-12-26 10:59:57 -0800312 for (size_t i = 0; i < num_descriptors; i++) {
313 AvbDescriptor desc;
314 if (!avb_descriptor_validate_and_byteswap(descriptors[i], &desc)) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100315 return Errorf("Couldn't validate AvbDescriptor.");
Andreas Gampe356e40c2018-12-26 10:59:57 -0800316 }
317
318 if (desc.tag != AVB_DESCRIPTOR_TAG_HASHTREE) {
319 // Ignore other descriptors
320 continue;
321 }
322
Nikita Ioffed71ce1d2020-04-30 01:19:41 +0100323 // Check that hashtree descriptor actually fits into memory.
324 const uint8_t* vbmeta_end = vbmeta_data + vbmeta_size;
325 if ((uint8_t*)descriptors[i] + sizeof(AvbHashtreeDescriptor) > vbmeta_end) {
326 return Errorf("Invalid length for AvbHashtreeDescriptor");
327 }
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100328 return (const AvbHashtreeDescriptor*)descriptors[i];
Andreas Gampe356e40c2018-12-26 10:59:57 -0800329 }
330
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100331 return Errorf("Couldn't find any AVB hashtree descriptors.");
Andreas Gampe356e40c2018-12-26 10:59:57 -0800332}
333
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000334Result<std::unique_ptr<AvbHashtreeDescriptor>> VerifyDescriptor(
Andreas Gampe356e40c2018-12-26 10:59:57 -0800335 const AvbHashtreeDescriptor* desc) {
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000336 auto verified_desc = std::make_unique<AvbHashtreeDescriptor>();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800337
338 if (!avb_hashtree_descriptor_validate_and_byteswap(desc,
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000339 verified_desc.get())) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100340 return Errorf("Couldn't validate AvbDescriptor.");
Andreas Gampe356e40c2018-12-26 10:59:57 -0800341 }
342
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000343 return verified_desc;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800344}
345
346} // namespace
347
Nikita Ioffefe685a32020-09-10 19:02:56 +0100348Result<ApexVerityData> ApexFile::VerifyApexVerity(
349 const std::string& public_key) const {
Mohammad Samiul Islama3ec5bb2021-01-08 18:52:59 +0000350 if (IsCompressed()) {
351 return Error() << "Cannot verify ApexVerity of compressed APEX";
352 }
353
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000354 ApexVerityData verity_data;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800355
356 unique_fd fd(open(GetPath().c_str(), O_RDONLY | O_CLOEXEC));
357 if (fd.get() == -1) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100358 return ErrnoError() << "Failed to open " << GetPath();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800359 }
360
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000361 Result<std::unique_ptr<AvbFooter>> footer = GetAvbFooter(*this, fd);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900362 if (!footer.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100363 return footer.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800364 }
365
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100366 Result<std::unique_ptr<uint8_t[]>> vbmeta_data =
Nikita Ioffe9714fe92020-12-22 20:56:33 +0000367 VerifyVbMeta(*this, fd, **footer, public_key);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900368 if (!vbmeta_data.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100369 return vbmeta_data.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800370 }
371
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100372 Result<const AvbHashtreeDescriptor*> descriptor =
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000373 FindDescriptor(vbmeta_data->get(), (*footer)->vbmeta_size);
Bernie Innocentie3ba3ac2020-02-06 22:01:51 +0900374 if (!descriptor.ok()) {
Mohammad Samiul Islambd6ab0f2019-06-20 15:55:27 +0100375 return descriptor.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800376 }
377
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000378 Result<std::unique_ptr<AvbHashtreeDescriptor>> verified_descriptor =
379 VerifyDescriptor(*descriptor);
380 if (!verified_descriptor.ok()) {
381 return verified_descriptor.error();
Andreas Gampe356e40c2018-12-26 10:59:57 -0800382 }
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000383 verity_data.desc = std::move(*verified_descriptor);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800384
385 // This area is now safe to access, because we just verified it
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000386 const uint8_t* trailing_data =
Andreas Gampe356e40c2018-12-26 10:59:57 -0800387 (const uint8_t*)*descriptor + sizeof(AvbHashtreeDescriptor);
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000388 verity_data.hash_algorithm =
Jooyung Hanf7c8d032019-04-11 15:12:09 +0900389 reinterpret_cast<const char*>((*descriptor)->hash_algorithm);
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000390 verity_data.salt = GetSalt(*verity_data.desc, trailing_data);
391 verity_data.root_digest = GetDigest(*verity_data.desc, trailing_data);
Andreas Gampe356e40c2018-12-26 10:59:57 -0800392
Nikita Ioffe77ae4982020-12-21 21:45:43 +0000393 return verity_data;
Andreas Gampe356e40c2018-12-26 10:59:57 -0800394}
395
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000396Result<void> ApexFile::Decompress(const std::string& dest_path) const {
397 const std::string& src_path = GetPath();
398
Nikita Ioffeac1b8ba2021-04-23 00:39:38 +0100399 LOG(INFO) << "Decompressing" << src_path << " to " << dest_path;
400
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000401 // We should decompress compressed APEX files only
402 if (!IsCompressed()) {
403 return ErrnoError() << "Cannot decompress an uncompressed APEX";
404 }
405
406 // Get file descriptor of the compressed apex file
407 unique_fd src_fd(open(src_path.c_str(), O_RDONLY | O_CLOEXEC));
408 if (src_fd.get() == -1) {
409 return ErrnoError() << "Failed to open compressed APEX " << GetPath();
410 }
411
412 // Open it as a zip file
413 ZipArchiveHandle handle;
414 int ret = OpenArchiveFd(src_fd.get(), src_path.c_str(), &handle, false);
415 if (ret < 0) {
416 return Error() << "Failed to open package " << src_path << ": "
417 << ErrorCodeString(ret);
418 }
419 auto handle_guard =
420 android::base::make_scope_guard([&handle] { CloseArchive(handle); });
421
422 // Find the original apex file inside the zip and extract to dest
423 ZipEntry entry;
424 ret = FindEntry(handle, kCompressedApexFilename, &entry);
425 if (ret < 0) {
426 return Error() << "Could not find entry \"" << kCompressedApexFilename
427 << "\" in package " << src_path << ": "
428 << ErrorCodeString(ret);
429 }
430
431 // Open destination file descriptor
432 unique_fd dest_fd(
Mohammad Samiul Islamc390beb2021-01-27 13:51:51 +0000433 open(dest_path.c_str(), O_WRONLY | O_CLOEXEC | O_CREAT | O_EXCL, 0644));
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000434 if (dest_fd.get() == -1) {
435 return ErrnoError() << "Failed to open decompression destination "
Mohammad Samiul Islamc390beb2021-01-27 13:51:51 +0000436 << dest_path.c_str();
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000437 }
Mohammad Samiul Islam158ef972021-01-22 17:47:41 +0000438
439 // Prepare a guard that deletes the extracted file if anything goes wrong
440 auto decompressed_guard = android::base::make_scope_guard(
441 [&dest_path] { RemoveFileIfExists(dest_path); });
442
443 // Extract the original_apex to dest_path
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000444 ret = ExtractEntryToFile(handle, &entry, dest_fd.get());
445 if (ret < 0) {
Mohammad Samiul Islamc390beb2021-01-27 13:51:51 +0000446 return Error() << "Could not decompress to file " << dest_path << " "
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000447 << ErrorCodeString(ret);
448 }
449
Mohammad Samiul Islam158ef972021-01-22 17:47:41 +0000450 // Verification complete. Accept the decompressed file
451 decompressed_guard.Disable();
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000452 LOG(VERBOSE) << "Decompressed " << src_path << " to " << dest_path;
Mohammad Samiul Islam158ef972021-01-22 17:47:41 +0000453
Mohammad Samiul Islam11126f82020-12-23 10:20:38 +0000454 return {};
455}
456
Dario Freni5a259292018-08-14 17:49:00 +0100457} // namespace apex
458} // namespace android