1 /*
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
17 #include "apex_file.h"
18
19 #include <android-base/file.h>
20 #include <android-base/logging.h>
21 #include <android-base/scopeguard.h>
22 #include <android-base/strings.h>
23 #include <android-base/unique_fd.h>
24 #include <fcntl.h>
25 #include <libavb/libavb.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 #include <ziparchive/zip_archive.h>
30
31 #include <filesystem>
32 #include <fstream>
33 #include <span>
34
35 #include "apex_constants.h"
36 #include "apexd_utils.h"
37 #include "apexd_verity.h"
38
39 using android::base::borrowed_fd;
40 using android::base::ErrnoError;
41 using android::base::Error;
42 using android::base::ReadFullyAtOffset;
43 using android::base::RemoveFileIfExists;
44 using android::base::Result;
45 using android::base::unique_fd;
46 using ::apex::proto::ApexManifest;
47
48 namespace android {
49 namespace apex {
50 namespace {
51
52 constexpr const char* kImageFilename = "apex_payload.img";
53 constexpr const char* kCompressedApexFilename = "original_apex";
54 constexpr const char* kBundledPublicKeyFilename = "apex_pubkey";
55
56 struct FsMagic {
57 const char* type;
58 int32_t offset;
59 int16_t len;
60 const char* magic;
61 };
62 constexpr const FsMagic kFsType[] = {{"f2fs", 1024, 4, "\x10\x20\xf5\xf2"},
63 {"ext4", 1024 + 0x38, 2, "\123\357"},
64 {"erofs", 1024, 4, "\xe2\xe1\xf5\xe0"}};
65
RetrieveFsType(borrowed_fd fd,uint32_t image_offset)66 Result<std::string> RetrieveFsType(borrowed_fd fd, uint32_t image_offset) {
67 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
79 } // namespace
80
Open(const std::string & path)81 Result<ApexFile> ApexFile::Open(const std::string& path) {
82 std::optional<uint32_t> image_offset;
83 std::optional<size_t> image_size;
84 std::string manifest_content;
85 std::string pubkey;
86 std::optional<std::string> fs_type;
87 ZipEntry entry;
88
89 unique_fd fd(open(path.c_str(), O_RDONLY | O_BINARY | O_CLOEXEC));
90 if (fd < 0) {
91 return ErrnoError() << "Failed to open package " << path << ": "
92 << "I/O error";
93 }
94
95 ZipArchiveHandle handle;
96 auto handle_guard =
97 android::base::make_scope_guard([&handle] { CloseArchive(handle); });
98 int ret = OpenArchiveFd(fd.get(), path.c_str(), &handle,
99 /*assume_ownership=*/false);
100 if (ret < 0) {
101 return Error() << "Failed to open package " << path << ": "
102 << ErrorCodeString(ret);
103 }
104
105 bool is_compressed = true;
106 ret = FindEntry(handle, kCompressedApexFilename, &entry);
107 if (ret < 0) {
108 is_compressed = false;
109 }
110
111 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
116 << "\" or \"" << kCompressedApexFilename
117 << "\" in package " << path << ": "
118 << ErrorCodeString(ret);
119 }
120 image_offset = entry.offset;
121 image_size = entry.uncompressed_length;
122
123 auto fs_type_result = RetrieveFsType(fd, image_offset.value());
124 if (!fs_type_result.ok()) {
125 return Error() << "Failed to retrieve filesystem type for " << path
126 << ": " << fs_type_result.error();
127 }
128 fs_type = std::move(*fs_type_result);
129 }
130
131 ret = FindEntry(handle, kManifestFilenamePb, &entry);
132 if (ret < 0) {
133 return Error() << "Could not find entry \"" << kManifestFilenamePb
134 << "\" in package " << path << ": " << ErrorCodeString(ret);
135 }
136
137 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) {
143 return Error() << "Failed to extract manifest from package " << path << ": "
144 << ErrorCodeString(ret);
145 }
146
147 ret = FindEntry(handle, kBundledPublicKeyFilename, &entry);
148 if (ret >= 0) {
149 length = entry.uncompressed_length;
150 pubkey.resize(length, '\0');
151 ret = ExtractToMemory(handle, &entry,
152 reinterpret_cast<uint8_t*>(&(pubkey)[0]), length);
153 if (ret != 0) {
154 return Error() << "Failed to extract public key from package " << path
155 << ": " << ErrorCodeString(ret);
156 }
157 }
158
159 Result<ApexManifest> manifest = ParseManifest(manifest_content);
160 if (!manifest.ok()) {
161 return manifest.error();
162 }
163
164 if (is_compressed && manifest->providesharedapexlibs()) {
165 return Error() << "Apex providing sharedlibs shouldn't be compressed";
166 }
167
168 // 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),
177 pubkey, fs_type, is_compressed);
178 }
179
180 // AVB-related code.
181
182 namespace {
183
184 static constexpr int kVbMetaMaxSize = 64 * 1024;
185
GetSalt(const AvbHashtreeDescriptor & desc,const uint8_t * trailing_data)186 std::string GetSalt(const AvbHashtreeDescriptor& desc,
187 const uint8_t* trailing_data) {
188 const uint8_t* desc_salt = trailing_data + desc.partition_name_len;
189
190 return BytesToHex(desc_salt, desc.salt_len);
191 }
192
GetDigest(const AvbHashtreeDescriptor & desc,const uint8_t * trailing_data)193 std::string GetDigest(const AvbHashtreeDescriptor& desc,
194 const uint8_t* trailing_data) {
195 const uint8_t* desc_digest =
196 trailing_data + desc.partition_name_len + desc.salt_len;
197
198 return BytesToHex(desc_digest, desc.root_digest_len);
199 }
200
GetAvbFooter(const ApexFile & apex,const unique_fd & fd)201 Result<std::unique_ptr<AvbFooter>> GetAvbFooter(const ApexFile& apex,
202 const unique_fd& fd) {
203 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
207 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;
212 int ret = lseek(fd, offset, SEEK_SET);
213 if (ret == -1) {
214 return ErrnoError() << "Couldn't seek to AVB footer";
215 }
216
217 ret = read(fd, footer_data.data(), AVB_FOOTER_SIZE);
218 if (ret != AVB_FOOTER_SIZE) {
219 return ErrnoError() << "Couldn't read AVB footer";
220 }
221
222 if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_data.data(),
223 footer.get())) {
224 return Error() << "AVB footer verification failed.";
225 }
226
227 LOG(VERBOSE) << "AVB footer verification successful.";
228 return footer;
229 }
230
CompareKeys(const uint8_t * key,size_t length,const std::string & public_key_content)231 bool 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;
235 }
236
237 // Verifies correctness of vbmeta and returns public key it was signed with.
VerifyVbMetaSignature(const ApexFile & apex,const uint8_t * data,size_t length)238 Result<std::span<const uint8_t>> VerifyVbMetaSignature(const ApexFile& apex,
239 const uint8_t* data,
240 size_t length) {
241 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:
252 return Error() << "Error verifying " << apex.GetPath() << ": "
253 << avb_vbmeta_verify_result_to_string(res);
254 case AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER:
255 return Error() << "Error verifying " << apex.GetPath() << ": "
256 << "invalid vbmeta header";
257 case AVB_VBMETA_VERIFY_RESULT_UNSUPPORTED_VERSION:
258 return Error() << "Error verifying " << apex.GetPath() << ": "
259 << "unsupported version";
260 default:
261 return Error() << "Unknown vmbeta_image_verify return value : " << res;
262 }
263
264 return std::span<const uint8_t>(pk, pk_len);
265 }
266
VerifyVbMeta(const ApexFile & apex,const unique_fd & fd,const AvbFooter & footer,const std::string & public_key)267 Result<std::unique_ptr<uint8_t[]>> VerifyVbMeta(const ApexFile& apex,
268 const unique_fd& fd,
269 const AvbFooter& footer,
270 const std::string& public_key) {
271 if (footer.vbmeta_size > kVbMetaMaxSize) {
272 return Errorf("VbMeta size in footer exceeds kVbMetaMaxSize.");
273 }
274
275 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;
280 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)) {
283 return ErrnoError() << "Couldn't read AVB meta-data";
284 }
285
286 Result<std::span<const uint8_t>> st =
287 VerifyVbMetaSignature(apex, vbmeta_buf.get(), footer.vbmeta_size);
288 if (!st.ok()) {
289 return st.error();
290 }
291
292 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
297 return vbmeta_buf;
298 }
299
FindDescriptor(uint8_t * vbmeta_data,size_t vbmeta_size)300 Result<const AvbHashtreeDescriptor*> FindDescriptor(uint8_t* vbmeta_data,
301 size_t vbmeta_size) {
302 const AvbDescriptor** descriptors;
303 size_t num_descriptors;
304
305 descriptors =
306 avb_descriptor_get_all(vbmeta_data, vbmeta_size, &num_descriptors);
307
308 // 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
312 for (size_t i = 0; i < num_descriptors; i++) {
313 AvbDescriptor desc;
314 if (!avb_descriptor_validate_and_byteswap(descriptors[i], &desc)) {
315 return Errorf("Couldn't validate AvbDescriptor.");
316 }
317
318 if (desc.tag != AVB_DESCRIPTOR_TAG_HASHTREE) {
319 // Ignore other descriptors
320 continue;
321 }
322
323 // 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 }
328 return (const AvbHashtreeDescriptor*)descriptors[i];
329 }
330
331 return Errorf("Couldn't find any AVB hashtree descriptors.");
332 }
333
VerifyDescriptor(const AvbHashtreeDescriptor * desc)334 Result<std::unique_ptr<AvbHashtreeDescriptor>> VerifyDescriptor(
335 const AvbHashtreeDescriptor* desc) {
336 auto verified_desc = std::make_unique<AvbHashtreeDescriptor>();
337
338 if (!avb_hashtree_descriptor_validate_and_byteswap(desc,
339 verified_desc.get())) {
340 return Errorf("Couldn't validate AvbDescriptor.");
341 }
342
343 return verified_desc;
344 }
345
346 } // namespace
347
VerifyApexVerity(const std::string & public_key) const348 Result<ApexVerityData> ApexFile::VerifyApexVerity(
349 const std::string& public_key) const {
350 if (IsCompressed()) {
351 return Error() << "Cannot verify ApexVerity of compressed APEX";
352 }
353
354 ApexVerityData verity_data;
355
356 unique_fd fd(open(GetPath().c_str(), O_RDONLY | O_CLOEXEC));
357 if (fd.get() == -1) {
358 return ErrnoError() << "Failed to open " << GetPath();
359 }
360
361 Result<std::unique_ptr<AvbFooter>> footer = GetAvbFooter(*this, fd);
362 if (!footer.ok()) {
363 return footer.error();
364 }
365
366 Result<std::unique_ptr<uint8_t[]>> vbmeta_data =
367 VerifyVbMeta(*this, fd, **footer, public_key);
368 if (!vbmeta_data.ok()) {
369 return vbmeta_data.error();
370 }
371
372 Result<const AvbHashtreeDescriptor*> descriptor =
373 FindDescriptor(vbmeta_data->get(), (*footer)->vbmeta_size);
374 if (!descriptor.ok()) {
375 return descriptor.error();
376 }
377
378 Result<std::unique_ptr<AvbHashtreeDescriptor>> verified_descriptor =
379 VerifyDescriptor(*descriptor);
380 if (!verified_descriptor.ok()) {
381 return verified_descriptor.error();
382 }
383 verity_data.desc = std::move(*verified_descriptor);
384
385 // This area is now safe to access, because we just verified it
386 const uint8_t* trailing_data =
387 (const uint8_t*)*descriptor + sizeof(AvbHashtreeDescriptor);
388 verity_data.hash_algorithm =
389 reinterpret_cast<const char*>((*descriptor)->hash_algorithm);
390 verity_data.salt = GetSalt(*verity_data.desc, trailing_data);
391 verity_data.root_digest = GetDigest(*verity_data.desc, trailing_data);
392
393 return verity_data;
394 }
395
Decompress(const std::string & dest_path) const396 Result<void> ApexFile::Decompress(const std::string& dest_path) const {
397 const std::string& src_path = GetPath();
398
399 LOG(INFO) << "Decompressing" << src_path << " to " << dest_path;
400
401 // 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(
433 open(dest_path.c_str(), O_WRONLY | O_CLOEXEC | O_CREAT | O_EXCL, 0644));
434 if (dest_fd.get() == -1) {
435 return ErrnoError() << "Failed to open decompression destination "
436 << dest_path.c_str();
437 }
438
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
444 ret = ExtractEntryToFile(handle, &entry, dest_fd.get());
445 if (ret < 0) {
446 return Error() << "Could not decompress to file " << dest_path << " "
447 << ErrorCodeString(ret);
448 }
449
450 // Verification complete. Accept the decompressed file
451 decompressed_guard.Disable();
452 LOG(VERBOSE) << "Decompressed " << src_path << " to " << dest_path;
453
454 return {};
455 }
456
457 } // namespace apex
458 } // namespace android
459