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 <fcntl.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 
24 #include <filesystem>
25 #include <fstream>
26 #include <span>
27 
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/scopeguard.h>
31 #include <android-base/strings.h>
32 #include <android-base/unique_fd.h>
33 #include <libavb/libavb.h>
34 #include <ziparchive/zip_archive.h>
35 
36 #include "apex_constants.h"
37 #include "apexd_utils.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 
RetrieveFsType(borrowed_fd fd,int32_t image_offset)65 Result<std::string> RetrieveFsType(borrowed_fd fd, int32_t image_offset) {
66   for (const auto& fs : kFsType) {
67     char buf[fs.len];
68     if (!ReadFullyAtOffset(fd, buf, fs.len, image_offset + fs.offset)) {
69       return ErrnoError() << "Couldn't read filesystem magic";
70     }
71     if (memcmp(buf, fs.magic, fs.len) == 0) {
72       return std::string(fs.type);
73     }
74   }
75   return Error() << "Couldn't find filesystem magic";
76 }
77 
78 }  // namespace
79 
Open(const std::string & path)80 Result<ApexFile> ApexFile::Open(const std::string& path) {
81   std::optional<int32_t> image_offset;
82   std::optional<size_t> image_size;
83   std::string manifest_content;
84   std::string pubkey;
85   std::optional<std::string> fs_type;
86   ZipEntry entry;
87 
88   unique_fd fd(open(path.c_str(), O_RDONLY | O_BINARY | O_CLOEXEC));
89   if (fd < 0) {
90     return Error() << "Failed to open package " << path << ": "
91                    << "I/O error";
92   }
93 
94   ZipArchiveHandle handle;
95   auto handle_guard =
96       android::base::make_scope_guard([&handle] { CloseArchive(handle); });
97   int ret = OpenArchiveFd(fd.get(), path.c_str(), &handle, false);
98   if (ret < 0) {
99     return Error() << "Failed to open package " << path << ": "
100                    << ErrorCodeString(ret);
101   }
102 
103   bool is_compressed = true;
104   ret = FindEntry(handle, kCompressedApexFilename, &entry);
105   if (ret < 0) {
106     is_compressed = false;
107   }
108 
109   if (!is_compressed) {
110     // Locate the mountable image within the zipfile and store offset and size.
111     ret = FindEntry(handle, kImageFilename, &entry);
112     if (ret < 0) {
113       return Error() << "Could not find entry \"" << kImageFilename
114                      << "\" or \"" << kCompressedApexFilename
115                      << "\" in package " << path << ": "
116                      << ErrorCodeString(ret);
117     }
118     image_offset = entry.offset;
119     image_size = entry.uncompressed_length;
120 
121     auto fs_type_result = RetrieveFsType(fd, image_offset.value());
122     if (!fs_type_result.ok()) {
123       return Error() << "Failed to retrieve filesystem type for " << path
124                      << ": " << fs_type_result.error();
125     }
126     fs_type = std::move(*fs_type_result);
127   }
128 
129   ret = FindEntry(handle, kManifestFilenamePb, &entry);
130   if (ret < 0) {
131     return Error() << "Could not find entry \"" << kManifestFilenamePb
132                    << "\" in package " << path << ": " << ErrorCodeString(ret);
133   }
134 
135   uint32_t length = entry.uncompressed_length;
136   manifest_content.resize(length, '\0');
137   ret = ExtractToMemory(handle, &entry,
138                         reinterpret_cast<uint8_t*>(&(manifest_content)[0]),
139                         length);
140   if (ret != 0) {
141     return Error() << "Failed to extract manifest from package " << path << ": "
142                    << ErrorCodeString(ret);
143   }
144 
145   ret = FindEntry(handle, kBundledPublicKeyFilename, &entry);
146   if (ret >= 0) {
147     length = entry.uncompressed_length;
148     pubkey.resize(length, '\0');
149     ret = ExtractToMemory(handle, &entry,
150                           reinterpret_cast<uint8_t*>(&(pubkey)[0]), length);
151     if (ret != 0) {
152       return Error() << "Failed to extract public key from package " << path
153                      << ": " << ErrorCodeString(ret);
154     }
155   }
156 
157   Result<ApexManifest> manifest = ParseManifest(manifest_content);
158   if (!manifest.ok()) {
159     return manifest.error();
160   }
161 
162   if (is_compressed && manifest->providesharedapexlibs()) {
163     return Error() << "Apex providing sharedlibs shouldn't be compressed";
164   }
165 
166   // b/179211712 the stored path should be the realpath, otherwise the path we
167   // get by scanning the directory would be different from the path we get
168   // by reading /proc/mounts, if the apex file is on a symlink dir.
169   std::string realpath;
170   if (!android::base::Realpath(path, &realpath)) {
171     return ErrnoError() << "can't get realpath of " << path;
172   }
173 
174   return ApexFile(realpath, image_offset, image_size, std::move(*manifest),
175                   pubkey, fs_type, is_compressed);
176 }
177 
178 // AVB-related code.
179 
180 namespace {
181 
182 static constexpr int kVbMetaMaxSize = 64 * 1024;
183 
BytesToHex(const uint8_t * bytes,size_t bytes_len)184 std::string BytesToHex(const uint8_t* bytes, size_t bytes_len) {
185   std::ostringstream s;
186 
187   s << std::hex << std::setfill('0');
188   for (size_t i = 0; i < bytes_len; i++) {
189     s << std::setw(2) << static_cast<int>(bytes[i]);
190   }
191   return s.str();
192 }
193 
GetSalt(const AvbHashtreeDescriptor & desc,const uint8_t * trailing_data)194 std::string GetSalt(const AvbHashtreeDescriptor& desc,
195                     const uint8_t* trailing_data) {
196   const uint8_t* desc_salt = trailing_data + desc.partition_name_len;
197 
198   return BytesToHex(desc_salt, desc.salt_len);
199 }
200 
GetDigest(const AvbHashtreeDescriptor & desc,const uint8_t * trailing_data)201 std::string GetDigest(const AvbHashtreeDescriptor& desc,
202                       const uint8_t* trailing_data) {
203   const uint8_t* desc_digest =
204       trailing_data + desc.partition_name_len + desc.salt_len;
205 
206   return BytesToHex(desc_digest, desc.root_digest_len);
207 }
208 
GetAvbFooter(const ApexFile & apex,const unique_fd & fd)209 Result<std::unique_ptr<AvbFooter>> GetAvbFooter(const ApexFile& apex,
210                                                 const unique_fd& fd) {
211   std::array<uint8_t, AVB_FOOTER_SIZE> footer_data;
212   auto footer = std::make_unique<AvbFooter>();
213 
214   // The AVB footer is located in the last part of the image
215   if (!apex.GetImageOffset() || !apex.GetImageSize()) {
216     return Error() << "Cannot check avb footer without image offset and size";
217   }
218   off_t offset = apex.GetImageSize().value() + apex.GetImageOffset().value() -
219                  AVB_FOOTER_SIZE;
220   int ret = lseek(fd, offset, SEEK_SET);
221   if (ret == -1) {
222     return ErrnoError() << "Couldn't seek to AVB footer";
223   }
224 
225   ret = read(fd, footer_data.data(), AVB_FOOTER_SIZE);
226   if (ret != AVB_FOOTER_SIZE) {
227     return ErrnoError() << "Couldn't read AVB footer";
228   }
229 
230   if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_data.data(),
231                                         footer.get())) {
232     return Error() << "AVB footer verification failed.";
233   }
234 
235   LOG(VERBOSE) << "AVB footer verification successful.";
236   return footer;
237 }
238 
CompareKeys(const uint8_t * key,size_t length,const std::string & public_key_content)239 bool CompareKeys(const uint8_t* key, size_t length,
240                  const std::string& public_key_content) {
241   return public_key_content.length() == length &&
242          memcmp(&public_key_content[0], key, length) == 0;
243 }
244 
245 // Verifies correctness of vbmeta and returns public key it was signed with.
VerifyVbMetaSignature(const ApexFile & apex,const uint8_t * data,size_t length)246 Result<std::span<const uint8_t>> VerifyVbMetaSignature(const ApexFile& apex,
247                                                        const uint8_t* data,
248                                                        size_t length) {
249   const uint8_t* pk;
250   size_t pk_len;
251   AvbVBMetaVerifyResult res;
252 
253   res = avb_vbmeta_image_verify(data, length, &pk, &pk_len);
254   switch (res) {
255     case AVB_VBMETA_VERIFY_RESULT_OK:
256       break;
257     case AVB_VBMETA_VERIFY_RESULT_OK_NOT_SIGNED:
258     case AVB_VBMETA_VERIFY_RESULT_HASH_MISMATCH:
259     case AVB_VBMETA_VERIFY_RESULT_SIGNATURE_MISMATCH:
260       return Error() << "Error verifying " << apex.GetPath() << ": "
261                      << avb_vbmeta_verify_result_to_string(res);
262     case AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER:
263       return Error() << "Error verifying " << apex.GetPath() << ": "
264                      << "invalid vbmeta header";
265     case AVB_VBMETA_VERIFY_RESULT_UNSUPPORTED_VERSION:
266       return Error() << "Error verifying " << apex.GetPath() << ": "
267                      << "unsupported version";
268     default:
269       return Error() << "Unknown vmbeta_image_verify return value : " << res;
270   }
271 
272   return std::span<const uint8_t>(pk, pk_len);
273 }
274 
VerifyVbMeta(const ApexFile & apex,const unique_fd & fd,const AvbFooter & footer,const std::string & public_key)275 Result<std::unique_ptr<uint8_t[]>> VerifyVbMeta(const ApexFile& apex,
276                                                 const unique_fd& fd,
277                                                 const AvbFooter& footer,
278                                                 const std::string& public_key) {
279   if (footer.vbmeta_size > kVbMetaMaxSize) {
280     return Errorf("VbMeta size in footer exceeds kVbMetaMaxSize.");
281   }
282 
283   if (!apex.GetImageOffset()) {
284     return Error() << "Cannot check VbMeta size without image offset";
285   }
286 
287   off_t offset = apex.GetImageOffset().value() + footer.vbmeta_offset;
288   std::unique_ptr<uint8_t[]> vbmeta_buf(new uint8_t[footer.vbmeta_size]);
289 
290   if (!ReadFullyAtOffset(fd, vbmeta_buf.get(), footer.vbmeta_size, offset)) {
291     return ErrnoError() << "Couldn't read AVB meta-data";
292   }
293 
294   Result<std::span<const uint8_t>> st =
295       VerifyVbMetaSignature(apex, vbmeta_buf.get(), footer.vbmeta_size);
296   if (!st.ok()) {
297     return st.error();
298   }
299 
300   if (!CompareKeys(st->data(), st->size(), public_key)) {
301     return Error() << "Error verifying " << apex.GetPath() << " : "
302                    << "public key doesn't match the pre-installed one";
303   }
304 
305   return vbmeta_buf;
306 }
307 
FindDescriptor(uint8_t * vbmeta_data,size_t vbmeta_size)308 Result<const AvbHashtreeDescriptor*> FindDescriptor(uint8_t* vbmeta_data,
309                                                     size_t vbmeta_size) {
310   const AvbDescriptor** descriptors;
311   size_t num_descriptors;
312 
313   descriptors =
314       avb_descriptor_get_all(vbmeta_data, vbmeta_size, &num_descriptors);
315 
316   // avb_descriptor_get_all() returns an internally allocated array
317   // of pointers and it needs to be avb_free()ed after using it.
318   auto guard = android::base::ScopeGuard(std::bind(avb_free, descriptors));
319 
320   for (size_t i = 0; i < num_descriptors; i++) {
321     AvbDescriptor desc;
322     if (!avb_descriptor_validate_and_byteswap(descriptors[i], &desc)) {
323       return Errorf("Couldn't validate AvbDescriptor.");
324     }
325 
326     if (desc.tag != AVB_DESCRIPTOR_TAG_HASHTREE) {
327       // Ignore other descriptors
328       continue;
329     }
330 
331     // Check that hashtree descriptor actually fits into memory.
332     const uint8_t* vbmeta_end = vbmeta_data + vbmeta_size;
333     if ((uint8_t*)descriptors[i] + sizeof(AvbHashtreeDescriptor) > vbmeta_end) {
334       return Errorf("Invalid length for AvbHashtreeDescriptor");
335     }
336     return (const AvbHashtreeDescriptor*)descriptors[i];
337   }
338 
339   return Errorf("Couldn't find any AVB hashtree descriptors.");
340 }
341 
VerifyDescriptor(const AvbHashtreeDescriptor * desc)342 Result<std::unique_ptr<AvbHashtreeDescriptor>> VerifyDescriptor(
343     const AvbHashtreeDescriptor* desc) {
344   auto verified_desc = std::make_unique<AvbHashtreeDescriptor>();
345 
346   if (!avb_hashtree_descriptor_validate_and_byteswap(desc,
347                                                      verified_desc.get())) {
348     return Errorf("Couldn't validate AvbDescriptor.");
349   }
350 
351   return verified_desc;
352 }
353 
354 }  // namespace
355 
VerifyApexVerity(const std::string & public_key) const356 Result<ApexVerityData> ApexFile::VerifyApexVerity(
357     const std::string& public_key) const {
358   if (IsCompressed()) {
359     return Error() << "Cannot verify ApexVerity of compressed APEX";
360   }
361 
362   ApexVerityData verity_data;
363 
364   unique_fd fd(open(GetPath().c_str(), O_RDONLY | O_CLOEXEC));
365   if (fd.get() == -1) {
366     return ErrnoError() << "Failed to open " << GetPath();
367   }
368 
369   Result<std::unique_ptr<AvbFooter>> footer = GetAvbFooter(*this, fd);
370   if (!footer.ok()) {
371     return footer.error();
372   }
373 
374   Result<std::unique_ptr<uint8_t[]>> vbmeta_data =
375       VerifyVbMeta(*this, fd, **footer, public_key);
376   if (!vbmeta_data.ok()) {
377     return vbmeta_data.error();
378   }
379 
380   Result<const AvbHashtreeDescriptor*> descriptor =
381       FindDescriptor(vbmeta_data->get(), (*footer)->vbmeta_size);
382   if (!descriptor.ok()) {
383     return descriptor.error();
384   }
385 
386   Result<std::unique_ptr<AvbHashtreeDescriptor>> verified_descriptor =
387       VerifyDescriptor(*descriptor);
388   if (!verified_descriptor.ok()) {
389     return verified_descriptor.error();
390   }
391   verity_data.desc = std::move(*verified_descriptor);
392 
393   // This area is now safe to access, because we just verified it
394   const uint8_t* trailing_data =
395       (const uint8_t*)*descriptor + sizeof(AvbHashtreeDescriptor);
396   verity_data.hash_algorithm =
397       reinterpret_cast<const char*>((*descriptor)->hash_algorithm);
398   verity_data.salt = GetSalt(*verity_data.desc, trailing_data);
399   verity_data.root_digest = GetDigest(*verity_data.desc, trailing_data);
400 
401   return verity_data;
402 }
403 
Decompress(const std::string & dest_path) const404 Result<void> ApexFile::Decompress(const std::string& dest_path) const {
405   const std::string& src_path = GetPath();
406 
407   LOG(INFO) << "Decompressing" << src_path << " to " << dest_path;
408 
409   // We should decompress compressed APEX files only
410   if (!IsCompressed()) {
411     return ErrnoError() << "Cannot decompress an uncompressed APEX";
412   }
413 
414   // Get file descriptor of the compressed apex file
415   unique_fd src_fd(open(src_path.c_str(), O_RDONLY | O_CLOEXEC));
416   if (src_fd.get() == -1) {
417     return ErrnoError() << "Failed to open compressed APEX " << GetPath();
418   }
419 
420   // Open it as a zip file
421   ZipArchiveHandle handle;
422   int ret = OpenArchiveFd(src_fd.get(), src_path.c_str(), &handle, false);
423   if (ret < 0) {
424     return Error() << "Failed to open package " << src_path << ": "
425                    << ErrorCodeString(ret);
426   }
427   auto handle_guard =
428       android::base::make_scope_guard([&handle] { CloseArchive(handle); });
429 
430   // Find the original apex file inside the zip and extract to dest
431   ZipEntry entry;
432   ret = FindEntry(handle, kCompressedApexFilename, &entry);
433   if (ret < 0) {
434     return Error() << "Could not find entry \"" << kCompressedApexFilename
435                    << "\" in package " << src_path << ": "
436                    << ErrorCodeString(ret);
437   }
438 
439   // Open destination file descriptor
440   unique_fd dest_fd(
441       open(dest_path.c_str(), O_WRONLY | O_CLOEXEC | O_CREAT | O_EXCL, 0644));
442   if (dest_fd.get() == -1) {
443     return ErrnoError() << "Failed to open decompression destination "
444                         << dest_path.c_str();
445   }
446 
447   // Prepare a guard that deletes the extracted file if anything goes wrong
448   auto decompressed_guard = android::base::make_scope_guard(
449       [&dest_path] { RemoveFileIfExists(dest_path); });
450 
451   // Extract the original_apex to dest_path
452   ret = ExtractEntryToFile(handle, &entry, dest_fd.get());
453   if (ret < 0) {
454     return Error() << "Could not decompress to file " << dest_path << " "
455                    << ErrorCodeString(ret);
456   }
457 
458   // Verification complete. Accept the decompressed file
459   decompressed_guard.Disable();
460   LOG(VERBOSE) << "Decompressed " << src_path << " to " << dest_path;
461 
462   return {};
463 }
464 
465 }  // namespace apex
466 }  // namespace android
467