From 2478885f3ca47fe2c4073df1100f7bd6ad4931af Mon Sep 17 00:00:00 2001 From: xunchang Date: Fri, 22 Mar 2019 16:08:52 -0700 Subject: Move install to separate module Build libinstall as a shared library. Also drop the dependency on the global variables in common.h. Test: unit tests pass, sideload an OTA Change-Id: I30a20047768ce00689fc0e7851c1c5d712a365a0 --- Android.bp | 73 +-- adb_install.cpp | 124 ----- adb_install.h | 22 - asn1_decoder.cpp | 158 ------ asn1_decoder.h | 55 -- common.h | 1 - fsck_unshare_blocks.cpp | 2 +- fuse_sdcard_install.cpp | 206 -------- fuse_sdcard_install.h | 22 - install.cpp | 726 ------------------------- install.h | 71 --- install/Android.bp | 78 +++ install/adb_install.cpp | 128 +++++ install/asn1_decoder.cpp | 156 ++++++ install/fuse_sdcard_install.cpp | 206 ++++++++ install/include/install/adb_install.h | 21 + install/include/install/fuse_sdcard_install.h | 22 + install/include/install/install.h | 69 +++ install/include/install/package.h | 53 ++ install/include/install/verifier.h | 101 ++++ install/include/private/asn1_decoder.h | 56 ++ install/include/private/setup_commands.h | 39 ++ install/install.cpp | 730 ++++++++++++++++++++++++++ install/package.cpp | 262 +++++++++ install/verifier.cpp | 468 +++++++++++++++++ logging.cpp | 2 +- otautil/Android.bp | 11 + otautil/include/otautil/roots.h | 59 +++ otautil/roots.cpp | 285 ++++++++++ package.cpp | 262 --------- package.h | 53 -- private/install.h | 39 -- recovery.cpp | 21 +- recovery_main.cpp | 2 +- roots.cpp | 287 ---------- roots.h | 62 --- tests/Android.bp | 7 +- tests/component/install_test.cpp | 4 +- tests/component/verifier_test.cpp | 4 +- tests/unit/asn1_decoder_test.cpp | 2 +- tests/unit/package_test.cpp | 2 +- verifier.cpp | 469 ----------------- verifier.h | 109 ---- 43 files changed, 2770 insertions(+), 2759 deletions(-) delete mode 100644 adb_install.cpp delete mode 100644 adb_install.h delete mode 100644 asn1_decoder.cpp delete mode 100644 asn1_decoder.h delete mode 100644 fuse_sdcard_install.cpp delete mode 100644 fuse_sdcard_install.h delete mode 100644 install.cpp delete mode 100644 install.h create mode 100644 install/Android.bp create mode 100644 install/adb_install.cpp create mode 100644 install/asn1_decoder.cpp create mode 100644 install/fuse_sdcard_install.cpp create mode 100644 install/include/install/adb_install.h create mode 100644 install/include/install/fuse_sdcard_install.h create mode 100644 install/include/install/install.h create mode 100644 install/include/install/package.h create mode 100644 install/include/install/verifier.h create mode 100644 install/include/private/asn1_decoder.h create mode 100644 install/include/private/setup_commands.h create mode 100644 install/install.cpp create mode 100644 install/package.cpp create mode 100644 install/verifier.cpp create mode 100644 otautil/include/otautil/roots.h create mode 100644 otautil/roots.cpp delete mode 100644 package.cpp delete mode 100644 package.h delete mode 100644 private/install.h delete mode 100644 roots.cpp delete mode 100644 roots.h delete mode 100644 verifier.cpp delete mode 100644 verifier.h diff --git a/Android.bp b/Android.bp index 7b67f4077..a44a2c625 100644 --- a/Android.bp +++ b/Android.bp @@ -63,32 +63,18 @@ cc_defaults { "libbootloader_message", "libcrypto", "libcutils", - "libext4_utils", "libfs_mgr", - "libfusesideload", - "libhidl-gen-utils", - "libhidlbase", - "libhidltransport", "liblog", - "libpng", - "libselinux", - "libtinyxml2", - "libutils", - "libz", "libziparchive", ], static_libs: [ "librecovery_fastboot", "libminui", - "libpackage", - "libverifier", "libotautil", // external dependencies "libhealthhalutils", - "libvintf_recovery", - "libvintf", "libfstab", ], } @@ -102,69 +88,14 @@ cc_library_static { ], srcs: [ - "adb_install.cpp", "fsck_unshare_blocks.cpp", - "fuse_sdcard_install.cpp", - "install.cpp", "recovery.cpp", - "roots.cpp", ], shared_libs: [ + "libinstall", "librecovery_ui", ], - - include_dirs: [ - "system/vold", - ], -} - -cc_library_static { - name: "libverifier", - recovery_available: true, - - defaults: [ - "recovery_defaults", - ], - - srcs: [ - "asn1_decoder.cpp", - "verifier.cpp", - ], - - shared_libs: [ - "libbase", - "libcrypto", - "libcrypto_utils", - "libziparchive", - ], - - static_libs: [ - "libotautil", - ], -} - -cc_library_static { - name: "libpackage", - recovery_available: true, - - defaults: [ - "recovery_defaults", - ], - - srcs: [ - "package.cpp", - ], - - shared_libs: [ - "libbase", - "libcrypto", - "libziparchive", - ], - - static_libs: [ - "libotautil", - ], } cc_binary { @@ -172,6 +103,7 @@ cc_binary { recovery: true, defaults: [ + "libinstall_defaults", "librecovery_defaults", ], @@ -181,6 +113,7 @@ cc_binary { ], shared_libs: [ + "libinstall", "libminadbd_services", "librecovery_ui", ], diff --git a/adb_install.cpp b/adb_install.cpp deleted file mode 100644 index 1d19fd3a1..000000000 --- a/adb_install.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2012 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "adb_install.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "common.h" -#include "fuse_sideload.h" -#include "install.h" -#include "recovery_ui/ui.h" - -int apply_from_adb(bool* wipe_cache) { - // Save the usb state to restore after the sideload operation. - std::string usb_state = android::base::GetProperty("sys.usb.state", "none"); - // Clean up state and stop adbd. - if (usb_state != "none" && !SetUsbConfig("none")) { - LOG(ERROR) << "Failed to clear USB config"; - return INSTALL_ERROR; - } - - ui->Print( - "\n\nNow send the package you want to apply\n" - "to the device with \"adb sideload \"...\n"); - - pid_t child; - if ((child = fork()) == 0) { - execl("/system/bin/recovery", "recovery", "--adbd", nullptr); - _exit(EXIT_FAILURE); - } - - if (!SetUsbConfig("sideload")) { - LOG(ERROR) << "Failed to set usb config to sideload"; - return INSTALL_ERROR; - } - - // How long (in seconds) we wait for the host to start sending us a package, before timing out. - static constexpr int ADB_INSTALL_TIMEOUT = 300; - - // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the host connects and starts serving a - // package. Poll for its appearance. (Note that inotify doesn't work with FUSE.) - int result = INSTALL_ERROR; - int status; - bool waited = false; - for (int i = 0; i < ADB_INSTALL_TIMEOUT; ++i) { - if (waitpid(child, &status, WNOHANG) != 0) { - result = INSTALL_ERROR; - waited = true; - break; - } - - struct stat st; - if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &st) != 0) { - if (errno == ENOENT && i < ADB_INSTALL_TIMEOUT - 1) { - sleep(1); - continue; - } else { - ui->Print("\nTimed out waiting for package.\n\n"); - result = INSTALL_ERROR; - kill(child, SIGKILL); - break; - } - } - result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0); - break; - } - - if (!waited) { - // Calling stat() on this magic filename signals the minadbd subprocess to shut down. - struct stat st; - stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st); - - // TODO: there should be a way to cancel waiting for a package (by pushing some button combo on - // the device). For now you just have to 'adb sideload' a file that's not a valid package, like - // "/dev/null". - waitpid(child, &status, 0); - } - - if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { - if (WEXITSTATUS(status) == 3) { - ui->Print("\nYou need adb 1.0.32 or newer to sideload\nto this device.\n\n"); - } else if (!WIFSIGNALED(status)) { - ui->Print("\n(adbd status %d)\n", WEXITSTATUS(status)); - } - } - - // Clean up before switching to the older state, for example setting the state - // to none sets sys/class/android_usb/android0/enable to 0. - if (!SetUsbConfig("none")) { - LOG(ERROR) << "Failed to clear USB config"; - } - - if (usb_state != "none") { - if (!SetUsbConfig(usb_state)) { - LOG(ERROR) << "Failed to set USB config to " << usb_state; - } - } - - return result; -} diff --git a/adb_install.h b/adb_install.h deleted file mode 100644 index cc3ca267b..000000000 --- a/adb_install.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2012 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _ADB_INSTALL_H -#define _ADB_INSTALL_H - -int apply_from_adb(bool* wipe_cache); - -#endif diff --git a/asn1_decoder.cpp b/asn1_decoder.cpp deleted file mode 100644 index 285214f16..000000000 --- a/asn1_decoder.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (C) 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "asn1_decoder.h" - -#include - -int asn1_context::peek_byte() const { - if (length_ == 0) { - return -1; - } - return *p_; -} - -int asn1_context::get_byte() { - if (length_ == 0) { - return -1; - } - - int byte = *p_; - p_++; - length_--; - return byte; -} - -bool asn1_context::skip_bytes(size_t num_skip) { - if (length_ < num_skip) { - return false; - } - p_ += num_skip; - length_ -= num_skip; - return true; -} - -bool asn1_context::decode_length(size_t* out_len) { - int num_octets = get_byte(); - if (num_octets == -1) { - return false; - } - if ((num_octets & 0x80) == 0x00) { - *out_len = num_octets; - return true; - } - num_octets &= kMaskTag; - if (static_cast(num_octets) >= sizeof(size_t)) { - return false; - } - size_t length = 0; - for (int i = 0; i < num_octets; ++i) { - int byte = get_byte(); - if (byte == -1) { - return false; - } - length <<= 8; - length += byte; - } - *out_len = length; - return true; -} - -/** - * Returns the constructed type and advances the pointer. E.g. A0 -> 0 - */ -asn1_context* asn1_context::asn1_constructed_get() { - int type = get_byte(); - if (type == -1 || (type & kMaskConstructed) != kTagConstructed) { - return nullptr; - } - size_t length; - if (!decode_length(&length) || length > length_) { - return nullptr; - } - asn1_context* app_ctx = new asn1_context(p_, length); - app_ctx->app_type_ = type & kMaskAppType; - return app_ctx; -} - -bool asn1_context::asn1_constructed_skip_all() { - int byte = peek_byte(); - while (byte != -1 && (byte & kMaskConstructed) == kTagConstructed) { - skip_bytes(1); - size_t length; - if (!decode_length(&length) || !skip_bytes(length)) { - return false; - } - byte = peek_byte(); - } - return byte != -1; -} - -int asn1_context::asn1_constructed_type() const { - return app_type_; -} - -asn1_context* asn1_context::asn1_sequence_get() { - if ((get_byte() & kMaskTag) != kTagSequence) { - return nullptr; - } - size_t length; - if (!decode_length(&length) || length > length_) { - return nullptr; - } - return new asn1_context(p_, length); -} - -asn1_context* asn1_context::asn1_set_get() { - if ((get_byte() & kMaskTag) != kTagSet) { - return nullptr; - } - size_t length; - if (!decode_length(&length) || length > length_) { - return nullptr; - } - return new asn1_context(p_, length); -} - -bool asn1_context::asn1_sequence_next() { - size_t length; - if (get_byte() == -1 || !decode_length(&length) || !skip_bytes(length)) { - return false; - } - return true; -} - -bool asn1_context::asn1_oid_get(const uint8_t** oid, size_t* length) { - if (get_byte() != kTagOid) { - return false; - } - if (!decode_length(length) || *length == 0 || *length > length_) { - return false; - } - *oid = p_; - return true; -} - -bool asn1_context::asn1_octet_string_get(const uint8_t** octet_string, size_t* length) { - if (get_byte() != kTagOctetString) { - return false; - } - if (!decode_length(length) || *length == 0 || *length > length_) { - return false; - } - *octet_string = p_; - return true; -} diff --git a/asn1_decoder.h b/asn1_decoder.h deleted file mode 100644 index 3e992115a..000000000 --- a/asn1_decoder.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ASN1_DECODER_H_ -#define ASN1_DECODER_H_ - -#include - -class asn1_context { - public: - asn1_context(const uint8_t* buffer, size_t length) : p_(buffer), length_(length), app_type_(0) {} - int asn1_constructed_type() const; - asn1_context* asn1_constructed_get(); - bool asn1_constructed_skip_all(); - asn1_context* asn1_sequence_get(); - asn1_context* asn1_set_get(); - bool asn1_sequence_next(); - bool asn1_oid_get(const uint8_t** oid, size_t* length); - bool asn1_octet_string_get(const uint8_t** octet_string, size_t* length); - - private: - static constexpr int kMaskConstructed = 0xE0; - static constexpr int kMaskTag = 0x7F; - static constexpr int kMaskAppType = 0x1F; - - static constexpr int kTagOctetString = 0x04; - static constexpr int kTagOid = 0x06; - static constexpr int kTagSequence = 0x30; - static constexpr int kTagSet = 0x31; - static constexpr int kTagConstructed = 0xA0; - - int peek_byte() const; - int get_byte(); - bool skip_bytes(size_t num_skip); - bool decode_length(size_t* out_len); - - const uint8_t* p_; - size_t length_; - int app_type_; -}; - -#endif /* ASN1_DECODER_H_ */ diff --git a/common.h b/common.h index 38bdd526b..22b2f0a0d 100644 --- a/common.h +++ b/common.h @@ -31,7 +31,6 @@ struct selabel_handle; extern struct selabel_handle* sehandle; extern RecoveryUI* ui; -extern bool modified_flash; extern bool has_cache; // The current stage, e.g. "1/2". diff --git a/fsck_unshare_blocks.cpp b/fsck_unshare_blocks.cpp index ce6940a6b..e74f8ba6f 100644 --- a/fsck_unshare_blocks.cpp +++ b/fsck_unshare_blocks.cpp @@ -36,7 +36,7 @@ #include #include -#include "roots.h" +#include "otautil/roots.h" static constexpr const char* SYSTEM_E2FSCK_BIN = "/system/bin/e2fsck_static"; static constexpr const char* TMP_E2FSCK_BIN = "/tmp/e2fsck.bin"; diff --git a/fuse_sdcard_install.cpp b/fuse_sdcard_install.cpp deleted file mode 100644 index 1f385093f..000000000 --- a/fuse_sdcard_install.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2019 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "fuse_sdcard_install.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include - -#include "bootloader_message/bootloader_message.h" -#include "fuse_provider.h" -#include "fuse_sideload.h" -#include "install.h" -#include "roots.h" - -static constexpr const char* SDCARD_ROOT = "/sdcard"; -// How long (in seconds) we wait for the fuse-provided package file to -// appear, before timing out. -static constexpr int SDCARD_INSTALL_TIMEOUT = 10; - -// Set the BCB to reboot back into recovery (it won't resume the install from -// sdcard though). -static void SetSdcardUpdateBootloaderMessage() { - std::vector options; - std::string err; - if (!update_bootloader_message(options, &err)) { - LOG(ERROR) << "Failed to set BCB message: " << err; - } -} - -// Returns the selected filename, or an empty string. -static std::string BrowseDirectory(const std::string& path, Device* device, RecoveryUI* ui) { - ensure_path_mounted(path); - - std::unique_ptr d(opendir(path.c_str()), closedir); - if (!d) { - PLOG(ERROR) << "error opening " << path; - return ""; - } - - std::vector dirs; - std::vector entries{ "../" }; // "../" is always the first entry. - - dirent* de; - while ((de = readdir(d.get())) != nullptr) { - std::string name(de->d_name); - - if (de->d_type == DT_DIR) { - // Skip "." and ".." entries. - if (name == "." || name == "..") continue; - dirs.push_back(name + "/"); - } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) { - entries.push_back(name); - } - } - - std::sort(dirs.begin(), dirs.end()); - std::sort(entries.begin(), entries.end()); - - // Append dirs to the entries list. - entries.insert(entries.end(), dirs.begin(), dirs.end()); - - std::vector headers{ "Choose a package to install:", path }; - - size_t chosen_item = 0; - while (true) { - chosen_item = ui->ShowMenu( - headers, entries, chosen_item, true, - std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2)); - - // Return if WaitKey() was interrupted. - if (chosen_item == static_cast(RecoveryUI::KeyError::INTERRUPTED)) { - return ""; - } - - const std::string& item = entries[chosen_item]; - if (chosen_item == 0) { - // Go up but continue browsing (if the caller is BrowseDirectory). - return ""; - } - - std::string new_path = path + "/" + item; - if (new_path.back() == '/') { - // Recurse down into a subdirectory. - new_path.pop_back(); - std::string result = BrowseDirectory(new_path, device, ui); - if (!result.empty()) return result; - } else { - // Selected a zip file: return the path to the caller. - return new_path; - } - } - - // Unreachable. -} - -static bool StartSdcardFuse(const std::string& path) { - auto file_data_reader = std::make_unique(path, 65536); - - if (!file_data_reader->Valid()) { - return false; - } - - // The installation process expects to find the sdcard unmounted. Unmount it with MNT_DETACH so - // that our open file continues to work but new references see it as unmounted. - umount2("/sdcard", MNT_DETACH); - - return run_fuse_sideload(std::move(file_data_reader)) == 0; -} - -int ApplyFromSdcard(Device* device, bool* wipe_cache, RecoveryUI* ui) { - if (ensure_path_mounted(SDCARD_ROOT) != 0) { - LOG(ERROR) << "\n-- Couldn't mount " << SDCARD_ROOT << ".\n"; - return INSTALL_ERROR; - } - - std::string path = BrowseDirectory(SDCARD_ROOT, device, ui); - if (path.empty()) { - LOG(ERROR) << "\n-- No package file selected.\n"; - ensure_path_unmounted(SDCARD_ROOT); - return INSTALL_ERROR; - } - - ui->Print("\n-- Install %s ...\n", path.c_str()); - SetSdcardUpdateBootloaderMessage(); - - // We used to use fuse in a thread as opposed to a process. Since accessing - // through fuse involves going from kernel to userspace to kernel, it leads - // to deadlock when a page fault occurs. (Bug: 26313124) - pid_t child; - if ((child = fork()) == 0) { - bool status = StartSdcardFuse(path); - - _exit(status ? EXIT_SUCCESS : EXIT_FAILURE); - } - - // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child - // process is ready. - int result = INSTALL_ERROR; - int status; - bool waited = false; - for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) { - if (waitpid(child, &status, WNOHANG) == -1) { - result = INSTALL_ERROR; - waited = true; - break; - } - - struct stat sb; - if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) { - if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT - 1) { - sleep(1); - continue; - } else { - LOG(ERROR) << "Timed out waiting for the fuse-provided package."; - result = INSTALL_ERROR; - kill(child, SIGKILL); - break; - } - } - - result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0 /*retry_count*/); - break; - } - - if (!waited) { - // Calling stat() on this magic filename signals the fuse - // filesystem to shut down. - struct stat sb; - stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb); - - waitpid(child, &status, 0); - } - - if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { - LOG(ERROR) << "Error exit from the fuse process: " << WEXITSTATUS(status); - } - - ensure_path_unmounted(SDCARD_ROOT); - return result; -} diff --git a/fuse_sdcard_install.h b/fuse_sdcard_install.h deleted file mode 100644 index 345aea45b..000000000 --- a/fuse_sdcard_install.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2019 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "recovery_ui/device.h" -#include "recovery_ui/ui.h" - -int ApplyFromSdcard(Device* device, bool* wipe_cache, RecoveryUI* ui); diff --git a/install.cpp b/install.cpp deleted file mode 100644 index ffa39e46b..000000000 --- a/install.cpp +++ /dev/null @@ -1,726 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "install.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "common.h" -#include "otautil/error_code.h" -#include "otautil/paths.h" -#include "otautil/sysutil.h" -#include "otautil/thermalutil.h" -#include "package.h" -#include "private/install.h" -#include "recovery_ui/ui.h" -#include "roots.h" -#include "verifier.h" - -using namespace std::chrono_literals; - -// Default allocation of progress bar segments to operations -static constexpr int VERIFICATION_PROGRESS_TIME = 60; -static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25; - -static std::condition_variable finish_log_temperature; - -bool ReadMetadataFromPackage(ZipArchiveHandle zip, std::map* metadata) { - CHECK(metadata != nullptr); - - static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata"; - ZipString path(METADATA_PATH); - ZipEntry entry; - if (FindEntry(zip, path, &entry) != 0) { - LOG(ERROR) << "Failed to find " << METADATA_PATH; - return false; - } - - uint32_t length = entry.uncompressed_length; - std::string metadata_string(length, '\0'); - int32_t err = - ExtractToMemory(zip, &entry, reinterpret_cast(&metadata_string[0]), length); - if (err != 0) { - LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err); - return false; - } - - for (const std::string& line : android::base::Split(metadata_string, "\n")) { - size_t eq = line.find('='); - if (eq != std::string::npos) { - metadata->emplace(android::base::Trim(line.substr(0, eq)), - android::base::Trim(line.substr(eq + 1))); - } - } - - return true; -} - -// Gets the value for the given key in |metadata|. Returns an emtpy string if the key isn't -// present. -static std::string get_value(const std::map& metadata, - const std::string& key) { - const auto& it = metadata.find(key); - return (it == metadata.end()) ? "" : it->second; -} - -static std::string OtaTypeToString(OtaType type) { - switch (type) { - case OtaType::AB: - return "AB"; - case OtaType::BLOCK: - return "BLOCK"; - case OtaType::BRICK: - return "BRICK"; - } -} - -// Read the build.version.incremental of src/tgt from the metadata and log it to last_install. -static void ReadSourceTargetBuild(const std::map& metadata, - std::vector* log_buffer) { - // Examples of the pre-build and post-build strings in metadata: - // pre-build-incremental=2943039 - // post-build-incremental=2951741 - auto source_build = get_value(metadata, "pre-build-incremental"); - if (!source_build.empty()) { - log_buffer->push_back("source_build: " + source_build); - } - - auto target_build = get_value(metadata, "post-build-incremental"); - if (!target_build.empty()) { - log_buffer->push_back("target_build: " + target_build); - } -} - -// Checks the build version, fingerprint and timestamp in the metadata of the A/B package. -// Downgrading is not allowed unless explicitly enabled in the package and only for -// incremental packages. -static int CheckAbSpecificMetadata(const std::map& metadata) { - // Incremental updates should match the current build. - auto device_pre_build = android::base::GetProperty("ro.build.version.incremental", ""); - auto pkg_pre_build = get_value(metadata, "pre-build-incremental"); - if (!pkg_pre_build.empty() && pkg_pre_build != device_pre_build) { - LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " - << device_pre_build; - return INSTALL_ERROR; - } - - auto device_fingerprint = android::base::GetProperty("ro.build.fingerprint", ""); - auto pkg_pre_build_fingerprint = get_value(metadata, "pre-build"); - if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != device_fingerprint) { - LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected " - << device_fingerprint; - return INSTALL_ERROR; - } - - // Check for downgrade version. - int64_t build_timestamp = - android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits::max()); - int64_t pkg_post_timestamp = 0; - // We allow to full update to the same version we are running, in case there - // is a problem with the current copy of that version. - auto pkg_post_timestamp_string = get_value(metadata, "post-timestamp"); - if (pkg_post_timestamp_string.empty() || - !android::base::ParseInt(pkg_post_timestamp_string, &pkg_post_timestamp) || - pkg_post_timestamp < build_timestamp) { - if (get_value(metadata, "ota-downgrade") != "yes") { - LOG(ERROR) << "Update package is older than the current build, expected a build " - "newer than timestamp " - << build_timestamp << " but package has timestamp " << pkg_post_timestamp - << " and downgrade not allowed."; - return INSTALL_ERROR; - } - if (pkg_pre_build_fingerprint.empty()) { - LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed."; - return INSTALL_ERROR; - } - } - - return 0; -} - -int CheckPackageMetadata(const std::map& metadata, OtaType ota_type) { - auto package_ota_type = get_value(metadata, "ota-type"); - auto expected_ota_type = OtaTypeToString(ota_type); - if (ota_type != OtaType::AB && ota_type != OtaType::BRICK) { - LOG(INFO) << "Skip package metadata check for ota type " << expected_ota_type; - return 0; - } - - if (package_ota_type != expected_ota_type) { - LOG(ERROR) << "Unexpected ota package type, expects " << expected_ota_type << ", actual " - << package_ota_type; - return INSTALL_ERROR; - } - - auto device = android::base::GetProperty("ro.product.device", ""); - auto pkg_device = get_value(metadata, "pre-device"); - if (pkg_device != device || pkg_device.empty()) { - LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << device; - return INSTALL_ERROR; - } - - // We allow the package to not have any serialno; and we also allow it to carry multiple serial - // numbers split by "|"; e.g. serialno=serialno1|serialno2|serialno3 ... We will fail the - // verification if the device's serialno doesn't match any of these carried numbers. - auto pkg_serial_no = get_value(metadata, "serialno"); - if (!pkg_serial_no.empty()) { - auto device_serial_no = android::base::GetProperty("ro.serialno", ""); - bool serial_number_match = false; - for (const auto& number : android::base::Split(pkg_serial_no, "|")) { - if (device_serial_no == android::base::Trim(number)) { - serial_number_match = true; - } - } - if (!serial_number_match) { - LOG(ERROR) << "Package is for serial " << pkg_serial_no; - return INSTALL_ERROR; - } - } - - if (ota_type == OtaType::AB) { - return CheckAbSpecificMetadata(metadata); - } - - return 0; -} - -int SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd, - std::vector* cmd) { - CHECK(cmd != nullptr); - - // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset - // in the zip file. - static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt"; - ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES); - ZipEntry properties_entry; - if (FindEntry(zip, property_name, &properties_entry) != 0) { - LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES; - return INSTALL_CORRUPT; - } - uint32_t properties_entry_length = properties_entry.uncompressed_length; - std::vector payload_properties(properties_entry_length); - int32_t err = - ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length); - if (err != 0) { - LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err); - return INSTALL_CORRUPT; - } - - static constexpr const char* AB_OTA_PAYLOAD = "payload.bin"; - ZipString payload_name(AB_OTA_PAYLOAD); - ZipEntry payload_entry; - if (FindEntry(zip, payload_name, &payload_entry) != 0) { - LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD; - return INSTALL_CORRUPT; - } - long payload_offset = payload_entry.offset; - *cmd = { - "/system/bin/update_engine_sideload", - "--payload=file://" + package, - android::base::StringPrintf("--offset=%ld", payload_offset), - "--headers=" + std::string(payload_properties.begin(), payload_properties.end()), - android::base::StringPrintf("--status_fd=%d", status_fd), - }; - return 0; -} - -int SetUpNonAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int retry_count, - int status_fd, std::vector* cmd) { - CHECK(cmd != nullptr); - - // In non-A/B updates we extract the update binary from the package. - static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary"; - ZipString binary_name(UPDATE_BINARY_NAME); - ZipEntry binary_entry; - if (FindEntry(zip, binary_name, &binary_entry) != 0) { - LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME; - return INSTALL_CORRUPT; - } - - const std::string binary_path = Paths::Get().temporary_update_binary(); - unlink(binary_path.c_str()); - android::base::unique_fd fd( - open(binary_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0755)); - if (fd == -1) { - PLOG(ERROR) << "Failed to create " << binary_path; - return INSTALL_ERROR; - } - - int32_t error = ExtractEntryToFile(zip, &binary_entry, fd); - if (error != 0) { - LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error); - return INSTALL_ERROR; - } - - // When executing the update binary contained in the package, the arguments passed are: - // - the version number for this interface - // - an FD to which the program can write in order to update the progress bar. - // - the name of the package zip file. - // - an optional argument "retry" if this update is a retry of a failed update attempt. - *cmd = { - binary_path, - std::to_string(kRecoveryApiVersion), - std::to_string(status_fd), - package, - }; - if (retry_count > 0) { - cmd->push_back("retry"); - } - return 0; -} - -static void log_max_temperature(int* max_temperature, const std::atomic& logger_finished) { - CHECK(max_temperature != nullptr); - std::mutex mtx; - std::unique_lock lck(mtx); - while (!logger_finished.load() && - finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) { - *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone()); - } -} - -// If the package contains an update binary, extract it and run it. -static int try_update_binary(const std::string& package, ZipArchiveHandle zip, bool* wipe_cache, - std::vector* log_buffer, int retry_count, - int* max_temperature) { - std::map metadata; - if (!ReadMetadataFromPackage(zip, &metadata)) { - LOG(ERROR) << "Failed to parse metadata in the zip file"; - return INSTALL_CORRUPT; - } - - bool is_ab = android::base::GetBoolProperty("ro.build.ab_update", false); - // Verifies against the metadata in the package first. - if (int check_status = is_ab ? CheckPackageMetadata(metadata, OtaType::AB) : 0; - check_status != 0) { - log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure)); - return check_status; - } - - ReadSourceTargetBuild(metadata, log_buffer); - - // The updater in child process writes to the pipe to communicate with recovery. - android::base::unique_fd pipe_read, pipe_write; - // Explicitly disable O_CLOEXEC using 0 as the flags (last) parameter to Pipe - // so that the child updater process will recieve a non-closed fd. - if (!android::base::Pipe(&pipe_read, &pipe_write, 0)) { - PLOG(ERROR) << "Failed to create pipe for updater-recovery communication"; - return INSTALL_CORRUPT; - } - - // The updater-recovery communication protocol. - // - // progress - // fill up the next part of of the progress bar over seconds. If is - // zero, use `set_progress` commands to manually control the progress of this segment of the - // bar. - // - // set_progress - // should be between 0.0 and 1.0; sets the progress bar within the segment defined by - // the most recent progress command. - // - // ui_print - // display on the screen. - // - // wipe_cache - // a wipe of cache will be performed following a successful installation. - // - // clear_display - // turn off the text display. - // - // enable_reboot - // packages can explicitly request that they want the user to be able to reboot during - // installation (useful for debugging packages that don't exit). - // - // retry_update - // updater encounters some issue during the update. It requests a reboot to retry the same - // package automatically. - // - // log - // updater requests logging the string (e.g. cause of the failure). - // - - std::vector args; - if (int update_status = - is_ab ? SetUpAbUpdateCommands(package, zip, pipe_write.get(), &args) - : SetUpNonAbUpdateCommands(package, zip, retry_count, pipe_write.get(), &args); - update_status != 0) { - log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure)); - return update_status; - } - - pid_t pid = fork(); - if (pid == -1) { - PLOG(ERROR) << "Failed to fork update binary"; - log_buffer->push_back(android::base::StringPrintf("error: %d", kForkUpdateBinaryFailure)); - return INSTALL_ERROR; - } - - if (pid == 0) { - umask(022); - pipe_read.reset(); - - // Convert the std::string vector to a NULL-terminated char* vector suitable for execv. - auto chr_args = StringVectorToNullTerminatedArray(args); - execv(chr_args[0], chr_args.data()); - // We shouldn't use LOG/PLOG in the forked process, since they may cause the child process to - // hang. This deadlock results from an improperly copied mutex in the ui functions. - // (Bug: 34769056) - fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno)); - _exit(EXIT_FAILURE); - } - pipe_write.reset(); - - std::atomic logger_finished(false); - std::thread temperature_logger(log_max_temperature, max_temperature, std::ref(logger_finished)); - - *wipe_cache = false; - bool retry_update = false; - - char buffer[1024]; - FILE* from_child = android::base::Fdopen(std::move(pipe_read), "r"); - while (fgets(buffer, sizeof(buffer), from_child) != nullptr) { - std::string line(buffer); - size_t space = line.find_first_of(" \n"); - std::string command(line.substr(0, space)); - if (command.empty()) continue; - - // Get rid of the leading and trailing space and/or newline. - std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space)); - - if (command == "progress") { - std::vector tokens = android::base::Split(args, " "); - double fraction; - int seconds; - if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) && - android::base::ParseInt(tokens[1], &seconds)) { - ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds); - } else { - LOG(ERROR) << "invalid \"progress\" parameters: " << line; - } - } else if (command == "set_progress") { - std::vector tokens = android::base::Split(args, " "); - double fraction; - if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) { - ui->SetProgress(fraction); - } else { - LOG(ERROR) << "invalid \"set_progress\" parameters: " << line; - } - } else if (command == "ui_print") { - ui->PrintOnScreenOnly("%s\n", args.c_str()); - fflush(stdout); - } else if (command == "wipe_cache") { - *wipe_cache = true; - } else if (command == "clear_display") { - ui->SetBackground(RecoveryUI::NONE); - } else if (command == "enable_reboot") { - // packages can explicitly request that they want the user - // to be able to reboot during installation (useful for - // debugging packages that don't exit). - ui->SetEnableReboot(true); - } else if (command == "retry_update") { - retry_update = true; - } else if (command == "log") { - if (!args.empty()) { - // Save the logging request from updater and write to last_install later. - log_buffer->push_back(args); - } else { - LOG(ERROR) << "invalid \"log\" parameters: " << line; - } - } else { - LOG(ERROR) << "unknown command [" << command << "]"; - } - } - fclose(from_child); - - int status; - waitpid(pid, &status, 0); - - logger_finished.store(true); - finish_log_temperature.notify_one(); - temperature_logger.join(); - - if (retry_update) { - return INSTALL_RETRY; - } - if (WIFEXITED(status)) { - if (WEXITSTATUS(status) != EXIT_SUCCESS) { - LOG(ERROR) << "Error in " << package << " (status " << WEXITSTATUS(status) << ")"; - return INSTALL_ERROR; - } - } else if (WIFSIGNALED(status)) { - LOG(ERROR) << "Error in " << package << " (killed by signal " << WTERMSIG(status) << ")"; - return INSTALL_ERROR; - } else { - LOG(FATAL) << "Invalid status code " << status; - } - - return INSTALL_SUCCESS; -} - -// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the -// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA -// package. -bool verify_package_compatibility(ZipArchiveHandle package_zip) { - LOG(INFO) << "Verifying package compatibility..."; - - static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip"; - ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY); - ZipEntry compatibility_entry; - if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) { - LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry"; - return true; - } - - std::string zip_content(compatibility_entry.uncompressed_length, '\0'); - int32_t ret; - if ((ret = ExtractToMemory(package_zip, &compatibility_entry, - reinterpret_cast(&zip_content[0]), - compatibility_entry.uncompressed_length)) != 0) { - LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret); - return false; - } - - ZipArchiveHandle zip_handle; - ret = OpenArchiveFromMemory(static_cast(const_cast(zip_content.data())), - zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle); - if (ret != 0) { - LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret); - return false; - } - - // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents. - void* cookie; - ret = StartIteration(zip_handle, &cookie, nullptr, nullptr); - if (ret != 0) { - LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret); - CloseArchive(zip_handle); - return false; - } - std::unique_ptr guard(cookie, EndIteration); - - std::vector compatibility_info; - ZipEntry info_entry; - ZipString info_name; - while (Next(cookie, &info_entry, &info_name) == 0) { - std::string content(info_entry.uncompressed_length, '\0'); - int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast(&content[0]), - info_entry.uncompressed_length); - if (ret != 0) { - LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret); - CloseArchive(zip_handle); - return false; - } - compatibility_info.emplace_back(std::move(content)); - } - CloseArchive(zip_handle); - - // VintfObjectRecovery::CheckCompatibility returns zero on success. - std::string err; - int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err); - if (result == 0) { - return true; - } - - LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err; - return false; -} - -static int really_install_package(const std::string& path, bool* wipe_cache, bool needs_mount, - std::vector* log_buffer, int retry_count, - int* max_temperature) { - ui->SetBackground(RecoveryUI::INSTALLING_UPDATE); - ui->Print("Finding update package...\n"); - // Give verification half the progress bar... - ui->SetProgressType(RecoveryUI::DETERMINATE); - ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME); - LOG(INFO) << "Update location: " << path; - - // Map the update package into memory. - ui->Print("Opening update package...\n"); - - if (needs_mount) { - if (path[0] == '@') { - ensure_path_mounted(path.substr(1)); - } else { - ensure_path_mounted(path); - } - } - - auto package = Package::CreateMemoryPackage( - path, std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1)); - if (!package) { - log_buffer->push_back(android::base::StringPrintf("error: %d", kMapFileFailure)); - return INSTALL_CORRUPT; - } - - // Verify package. - if (!verify_package(package.get())) { - log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure)); - return INSTALL_CORRUPT; - } - - // Try to open the package. - ZipArchiveHandle zip = package->GetZipArchiveHandle(); - if (!zip) { - log_buffer->push_back(android::base::StringPrintf("error: %d", kZipOpenFailure)); - return INSTALL_CORRUPT; - } - - // Additionally verify the compatibility of the package if it's a fresh install. - if (retry_count == 0 && !verify_package_compatibility(zip)) { - log_buffer->push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure)); - return INSTALL_CORRUPT; - } - - // Verify and install the contents of the package. - ui->Print("Installing update...\n"); - if (retry_count > 0) { - ui->Print("Retry attempt: %d\n", retry_count); - } - ui->SetEnableReboot(false); - int result = try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature); - ui->SetEnableReboot(true); - ui->Print("\n"); - - return result; -} - -int install_package(const std::string& path, bool* wipe_cache, bool needs_mount, int retry_count) { - CHECK(!path.empty()); - CHECK(wipe_cache != nullptr); - - modified_flash = true; - auto start = std::chrono::system_clock::now(); - - int start_temperature = GetMaxValueFromThermalZone(); - int max_temperature = start_temperature; - - int result; - std::vector log_buffer; - if (setup_install_mounts() != 0) { - LOG(ERROR) << "failed to set up expected mounts for install; aborting"; - result = INSTALL_ERROR; - } else { - result = really_install_package(path, wipe_cache, needs_mount, &log_buffer, retry_count, - &max_temperature); - } - - // Measure the time spent to apply OTA update in seconds. - std::chrono::duration duration = std::chrono::system_clock::now() - start; - int time_total = static_cast(duration.count()); - - bool has_cache = volume_for_mount_point("/cache") != nullptr; - // Skip logging the uncrypt_status on devices without /cache. - if (has_cache) { - static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status"; - if (ensure_path_mounted(UNCRYPT_STATUS) != 0) { - LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS; - } else { - std::string uncrypt_status; - if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) { - PLOG(WARNING) << "failed to read uncrypt status"; - } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) { - LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status; - } else { - log_buffer.push_back(android::base::Trim(uncrypt_status)); - } - } - } - - // The first two lines need to be the package name and install result. - std::vector log_header = { - path, - result == INSTALL_SUCCESS ? "1" : "0", - "time_total: " + std::to_string(time_total), - "retry: " + std::to_string(retry_count), - }; - - int end_temperature = GetMaxValueFromThermalZone(); - max_temperature = std::max(end_temperature, max_temperature); - if (start_temperature > 0) { - log_buffer.push_back("temperature_start: " + std::to_string(start_temperature)); - } - if (end_temperature > 0) { - log_buffer.push_back("temperature_end: " + std::to_string(end_temperature)); - } - if (max_temperature > 0) { - log_buffer.push_back("temperature_max: " + std::to_string(max_temperature)); - } - - std::string log_content = - android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n"; - const std::string& install_file = Paths::Get().temporary_install_file(); - if (!android::base::WriteStringToFile(log_content, install_file)) { - PLOG(ERROR) << "failed to write " << install_file; - } - - // Write a copy into last_log. - LOG(INFO) << log_content; - - return result; -} - -bool verify_package(Package* package) { - static constexpr const char* CERTIFICATE_ZIP_FILE = "/system/etc/security/otacerts.zip"; - std::vector loaded_keys = LoadKeysFromZipfile(CERTIFICATE_ZIP_FILE); - if (loaded_keys.empty()) { - LOG(ERROR) << "Failed to load keys"; - return false; - } - LOG(INFO) << loaded_keys.size() << " key(s) loaded from " << CERTIFICATE_ZIP_FILE; - - // Verify package. - ui->Print("Verifying update package...\n"); - auto t0 = std::chrono::system_clock::now(); - int err = verify_file(package, loaded_keys); - std::chrono::duration duration = std::chrono::system_clock::now() - t0; - ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err); - if (err != VERIFY_SUCCESS) { - LOG(ERROR) << "Signature verification failed"; - LOG(ERROR) << "error: " << kZipVerificationFailure; - return false; - } - return true; -} diff --git a/install.h b/install.h deleted file mode 100644 index da8aa5e39..000000000 --- a/install.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef RECOVERY_INSTALL_H_ -#define RECOVERY_INSTALL_H_ - -#include - -#include -#include -#include - -#include - -#include "package.h" - -enum InstallResult { - INSTALL_SUCCESS, - INSTALL_ERROR, - INSTALL_CORRUPT, - INSTALL_NONE, - INSTALL_SKIPPED, - INSTALL_RETRY, - INSTALL_KEY_INTERRUPTED -}; - -enum class OtaType { - AB, - BLOCK, - BRICK, -}; - -// Installs the given update package. If INSTALL_SUCCESS is returned and *wipe_cache is true on -// exit, caller should wipe the cache partition. -int install_package(const std::string& package, bool* wipe_cache, bool needs_mount, - int retry_count); - -// Verifies the package by ota keys. Returns true if the package is verified successfully, -// otherwise returns false. -bool verify_package(Package* package); - -// Reads meta data file of the package; parses each line in the format "key=value"; and writes the -// result to |metadata|. Return true if succeed, otherwise return false. -bool ReadMetadataFromPackage(ZipArchiveHandle zip, std::map* metadata); - -// Reads the "recovery.wipe" entry in the zip archive returns a list of partitions to wipe. -std::vector GetWipePartitionList(Package* wipe_package); - -// Verifies the compatibility info in a Treble-compatible package. Returns true directly if the -// entry doesn't exist. -bool verify_package_compatibility(ZipArchiveHandle package_zip); - -// Checks if the the metadata in the OTA package has expected values. Returns 0 on success. -// Mandatory checks: ota-type, pre-device and serial number(if presents) -// AB OTA specific checks: pre-build version, fingerprint, timestamp. -int CheckPackageMetadata(const std::map& metadata, OtaType ota_type); - -#endif // RECOVERY_INSTALL_H_ diff --git a/install/Android.bp b/install/Android.bp new file mode 100644 index 000000000..aa47990ae --- /dev/null +++ b/install/Android.bp @@ -0,0 +1,78 @@ +// Copyright (C) 2019 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +cc_defaults { + name: "libinstall_defaults", + + defaults: [ + "recovery_defaults", + ], + + shared_libs: [ + "libbase", + "libbootloader_message", + "libcrypto", + "libext4_utils", + "libfs_mgr", + "libfusesideload", + "libhidl-gen-utils", + "libhidlbase", + "libhidltransport", + "liblog", + "libselinux", + "libtinyxml2", + "libutils", + "libz", + "libziparchive", + ], + + static_libs: [ + "libotautil", + + // external dependencies + "libvintf_recovery", + "libvintf", + "libfstab", + ], +} + +cc_library { + name: "libinstall", + recovery_available: true, + + defaults: [ + "libinstall_defaults", + ], + + srcs: [ + "adb_install.cpp", + "asn1_decoder.cpp", + "fuse_sdcard_install.cpp", + "install.cpp", + "package.cpp", + "verifier.cpp", + ], + + shared_libs: [ + "librecovery_ui", + ], + + export_include_dirs: [ + "include", + ], + + export_shared_lib_headers: [ + "librecovery_ui", + ], +} diff --git a/install/adb_install.cpp b/install/adb_install.cpp new file mode 100644 index 000000000..5296ff608 --- /dev/null +++ b/install/adb_install.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "install/adb_install.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "fuse_sideload.h" +#include "install/install.h" +#include "recovery_ui/ui.h" + +static bool SetUsbConfig(const std::string& state) { + android::base::SetProperty("sys.usb.config", state); + return android::base::WaitForProperty("sys.usb.state", state); +} + +int apply_from_adb(bool* wipe_cache, RecoveryUI* ui) { + // Save the usb state to restore after the sideload operation. + std::string usb_state = android::base::GetProperty("sys.usb.state", "none"); + // Clean up state and stop adbd. + if (usb_state != "none" && !SetUsbConfig("none")) { + LOG(ERROR) << "Failed to clear USB config"; + return INSTALL_ERROR; + } + + ui->Print( + "\n\nNow send the package you want to apply\n" + "to the device with \"adb sideload \"...\n"); + + pid_t child; + if ((child = fork()) == 0) { + execl("/system/bin/recovery", "recovery", "--adbd", nullptr); + _exit(EXIT_FAILURE); + } + + if (!SetUsbConfig("sideload")) { + LOG(ERROR) << "Failed to set usb config to sideload"; + return INSTALL_ERROR; + } + + // How long (in seconds) we wait for the host to start sending us a package, before timing out. + static constexpr int ADB_INSTALL_TIMEOUT = 300; + + // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the host connects and starts serving a + // package. Poll for its appearance. (Note that inotify doesn't work with FUSE.) + int result = INSTALL_ERROR; + int status; + bool waited = false; + for (int i = 0; i < ADB_INSTALL_TIMEOUT; ++i) { + if (waitpid(child, &status, WNOHANG) != 0) { + result = INSTALL_ERROR; + waited = true; + break; + } + + struct stat st; + if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &st) != 0) { + if (errno == ENOENT && i < ADB_INSTALL_TIMEOUT - 1) { + sleep(1); + continue; + } else { + ui->Print("\nTimed out waiting for package.\n\n"); + result = INSTALL_ERROR; + kill(child, SIGKILL); + break; + } + } + result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0, ui); + break; + } + + if (!waited) { + // Calling stat() on this magic filename signals the minadbd subprocess to shut down. + struct stat st; + stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st); + + // TODO: there should be a way to cancel waiting for a package (by pushing some button combo on + // the device). For now you just have to 'adb sideload' a file that's not a valid package, like + // "/dev/null". + waitpid(child, &status, 0); + } + + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + if (WEXITSTATUS(status) == 3) { + ui->Print("\nYou need adb 1.0.32 or newer to sideload\nto this device.\n\n"); + } else if (!WIFSIGNALED(status)) { + ui->Print("\n(adbd status %d)\n", WEXITSTATUS(status)); + } + } + + // Clean up before switching to the older state, for example setting the state + // to none sets sys/class/android_usb/android0/enable to 0. + if (!SetUsbConfig("none")) { + LOG(ERROR) << "Failed to clear USB config"; + } + + if (usb_state != "none") { + if (!SetUsbConfig(usb_state)) { + LOG(ERROR) << "Failed to set USB config to " << usb_state; + } + } + + return result; +} diff --git a/install/asn1_decoder.cpp b/install/asn1_decoder.cpp new file mode 100644 index 000000000..2d81a6e13 --- /dev/null +++ b/install/asn1_decoder.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "private/asn1_decoder.h" + +int asn1_context::peek_byte() const { + if (length_ == 0) { + return -1; + } + return *p_; +} + +int asn1_context::get_byte() { + if (length_ == 0) { + return -1; + } + + int byte = *p_; + p_++; + length_--; + return byte; +} + +bool asn1_context::skip_bytes(size_t num_skip) { + if (length_ < num_skip) { + return false; + } + p_ += num_skip; + length_ -= num_skip; + return true; +} + +bool asn1_context::decode_length(size_t* out_len) { + int num_octets = get_byte(); + if (num_octets == -1) { + return false; + } + if ((num_octets & 0x80) == 0x00) { + *out_len = num_octets; + return true; + } + num_octets &= kMaskTag; + if (static_cast(num_octets) >= sizeof(size_t)) { + return false; + } + size_t length = 0; + for (int i = 0; i < num_octets; ++i) { + int byte = get_byte(); + if (byte == -1) { + return false; + } + length <<= 8; + length += byte; + } + *out_len = length; + return true; +} + +/** + * Returns the constructed type and advances the pointer. E.g. A0 -> 0 + */ +asn1_context* asn1_context::asn1_constructed_get() { + int type = get_byte(); + if (type == -1 || (type & kMaskConstructed) != kTagConstructed) { + return nullptr; + } + size_t length; + if (!decode_length(&length) || length > length_) { + return nullptr; + } + asn1_context* app_ctx = new asn1_context(p_, length); + app_ctx->app_type_ = type & kMaskAppType; + return app_ctx; +} + +bool asn1_context::asn1_constructed_skip_all() { + int byte = peek_byte(); + while (byte != -1 && (byte & kMaskConstructed) == kTagConstructed) { + skip_bytes(1); + size_t length; + if (!decode_length(&length) || !skip_bytes(length)) { + return false; + } + byte = peek_byte(); + } + return byte != -1; +} + +int asn1_context::asn1_constructed_type() const { + return app_type_; +} + +asn1_context* asn1_context::asn1_sequence_get() { + if ((get_byte() & kMaskTag) != kTagSequence) { + return nullptr; + } + size_t length; + if (!decode_length(&length) || length > length_) { + return nullptr; + } + return new asn1_context(p_, length); +} + +asn1_context* asn1_context::asn1_set_get() { + if ((get_byte() & kMaskTag) != kTagSet) { + return nullptr; + } + size_t length; + if (!decode_length(&length) || length > length_) { + return nullptr; + } + return new asn1_context(p_, length); +} + +bool asn1_context::asn1_sequence_next() { + size_t length; + if (get_byte() == -1 || !decode_length(&length) || !skip_bytes(length)) { + return false; + } + return true; +} + +bool asn1_context::asn1_oid_get(const uint8_t** oid, size_t* length) { + if (get_byte() != kTagOid) { + return false; + } + if (!decode_length(length) || *length == 0 || *length > length_) { + return false; + } + *oid = p_; + return true; +} + +bool asn1_context::asn1_octet_string_get(const uint8_t** octet_string, size_t* length) { + if (get_byte() != kTagOctetString) { + return false; + } + if (!decode_length(length) || *length == 0 || *length > length_) { + return false; + } + *octet_string = p_; + return true; +} diff --git a/install/fuse_sdcard_install.cpp b/install/fuse_sdcard_install.cpp new file mode 100644 index 000000000..dde289f80 --- /dev/null +++ b/install/fuse_sdcard_install.cpp @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2019 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "install/fuse_sdcard_install.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "bootloader_message/bootloader_message.h" +#include "fuse_provider.h" +#include "fuse_sideload.h" +#include "install/install.h" +#include "otautil/roots.h" + +static constexpr const char* SDCARD_ROOT = "/sdcard"; +// How long (in seconds) we wait for the fuse-provided package file to +// appear, before timing out. +static constexpr int SDCARD_INSTALL_TIMEOUT = 10; + +// Set the BCB to reboot back into recovery (it won't resume the install from +// sdcard though). +static void SetSdcardUpdateBootloaderMessage() { + std::vector options; + std::string err; + if (!update_bootloader_message(options, &err)) { + LOG(ERROR) << "Failed to set BCB message: " << err; + } +} + +// Returns the selected filename, or an empty string. +static std::string BrowseDirectory(const std::string& path, Device* device, RecoveryUI* ui) { + ensure_path_mounted(path); + + std::unique_ptr d(opendir(path.c_str()), closedir); + if (!d) { + PLOG(ERROR) << "error opening " << path; + return ""; + } + + std::vector dirs; + std::vector entries{ "../" }; // "../" is always the first entry. + + dirent* de; + while ((de = readdir(d.get())) != nullptr) { + std::string name(de->d_name); + + if (de->d_type == DT_DIR) { + // Skip "." and ".." entries. + if (name == "." || name == "..") continue; + dirs.push_back(name + "/"); + } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) { + entries.push_back(name); + } + } + + std::sort(dirs.begin(), dirs.end()); + std::sort(entries.begin(), entries.end()); + + // Append dirs to the entries list. + entries.insert(entries.end(), dirs.begin(), dirs.end()); + + std::vector headers{ "Choose a package to install:", path }; + + size_t chosen_item = 0; + while (true) { + chosen_item = ui->ShowMenu( + headers, entries, chosen_item, true, + std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2)); + + // Return if WaitKey() was interrupted. + if (chosen_item == static_cast(RecoveryUI::KeyError::INTERRUPTED)) { + return ""; + } + + const std::string& item = entries[chosen_item]; + if (chosen_item == 0) { + // Go up but continue browsing (if the caller is BrowseDirectory). + return ""; + } + + std::string new_path = path + "/" + item; + if (new_path.back() == '/') { + // Recurse down into a subdirectory. + new_path.pop_back(); + std::string result = BrowseDirectory(new_path, device, ui); + if (!result.empty()) return result; + } else { + // Selected a zip file: return the path to the caller. + return new_path; + } + } + + // Unreachable. +} + +static bool StartSdcardFuse(const std::string& path) { + auto file_data_reader = std::make_unique(path, 65536); + + if (!file_data_reader->Valid()) { + return false; + } + + // The installation process expects to find the sdcard unmounted. Unmount it with MNT_DETACH so + // that our open file continues to work but new references see it as unmounted. + umount2("/sdcard", MNT_DETACH); + + return run_fuse_sideload(std::move(file_data_reader)) == 0; +} + +int ApplyFromSdcard(Device* device, bool* wipe_cache, RecoveryUI* ui) { + if (ensure_path_mounted(SDCARD_ROOT) != 0) { + LOG(ERROR) << "\n-- Couldn't mount " << SDCARD_ROOT << ".\n"; + return INSTALL_ERROR; + } + + std::string path = BrowseDirectory(SDCARD_ROOT, device, ui); + if (path.empty()) { + LOG(ERROR) << "\n-- No package file selected.\n"; + ensure_path_unmounted(SDCARD_ROOT); + return INSTALL_ERROR; + } + + ui->Print("\n-- Install %s ...\n", path.c_str()); + SetSdcardUpdateBootloaderMessage(); + + // We used to use fuse in a thread as opposed to a process. Since accessing + // through fuse involves going from kernel to userspace to kernel, it leads + // to deadlock when a page fault occurs. (Bug: 26313124) + pid_t child; + if ((child = fork()) == 0) { + bool status = StartSdcardFuse(path); + + _exit(status ? EXIT_SUCCESS : EXIT_FAILURE); + } + + // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child + // process is ready. + int result = INSTALL_ERROR; + int status; + bool waited = false; + for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) { + if (waitpid(child, &status, WNOHANG) == -1) { + result = INSTALL_ERROR; + waited = true; + break; + } + + struct stat sb; + if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) { + if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT - 1) { + sleep(1); + continue; + } else { + LOG(ERROR) << "Timed out waiting for the fuse-provided package."; + result = INSTALL_ERROR; + kill(child, SIGKILL); + break; + } + } + + result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0 /*retry_count*/, ui); + break; + } + + if (!waited) { + // Calling stat() on this magic filename signals the fuse + // filesystem to shut down. + struct stat sb; + stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb); + + waitpid(child, &status, 0); + } + + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + LOG(ERROR) << "Error exit from the fuse process: " << WEXITSTATUS(status); + } + + ensure_path_unmounted(SDCARD_ROOT); + return result; +} diff --git a/install/include/install/adb_install.h b/install/include/install/adb_install.h new file mode 100644 index 000000000..dbc824501 --- /dev/null +++ b/install/include/install/adb_install.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2012 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +int apply_from_adb(bool* wipe_cache, RecoveryUI* ui); diff --git a/install/include/install/fuse_sdcard_install.h b/install/include/install/fuse_sdcard_install.h new file mode 100644 index 000000000..345aea45b --- /dev/null +++ b/install/include/install/fuse_sdcard_install.h @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2019 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "recovery_ui/device.h" +#include "recovery_ui/ui.h" + +int ApplyFromSdcard(Device* device, bool* wipe_cache, RecoveryUI* ui); diff --git a/install/include/install/install.h b/install/include/install/install.h new file mode 100644 index 000000000..74fb3d170 --- /dev/null +++ b/install/include/install/install.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include +#include +#include + +#include + +#include "package.h" +#include "recovery_ui/ui.h" + +enum InstallResult { + INSTALL_SUCCESS, + INSTALL_ERROR, + INSTALL_CORRUPT, + INSTALL_NONE, + INSTALL_SKIPPED, + INSTALL_RETRY, + INSTALL_KEY_INTERRUPTED +}; + +enum class OtaType { + AB, + BLOCK, + BRICK, +}; + +// Installs the given update package. If INSTALL_SUCCESS is returned and *wipe_cache is true on +// exit, caller should wipe the cache partition. +int install_package(const std::string& package, bool* wipe_cache, bool needs_mount, int retry_count, + RecoveryUI* ui); + +// Verifies the package by ota keys. Returns true if the package is verified successfully, +// otherwise returns false. +bool verify_package(Package* package, RecoveryUI* ui); + +// Reads meta data file of the package; parses each line in the format "key=value"; and writes the +// result to |metadata|. Return true if succeed, otherwise return false. +bool ReadMetadataFromPackage(ZipArchiveHandle zip, std::map* metadata); + +// Reads the "recovery.wipe" entry in the zip archive returns a list of partitions to wipe. +std::vector GetWipePartitionList(Package* wipe_package); + +// Verifies the compatibility info in a Treble-compatible package. Returns true directly if the +// entry doesn't exist. +bool verify_package_compatibility(ZipArchiveHandle package_zip); + +// Checks if the the metadata in the OTA package has expected values. Returns 0 on success. +// Mandatory checks: ota-type, pre-device and serial number(if presents) +// AB OTA specific checks: pre-build version, fingerprint, timestamp. +int CheckPackageMetadata(const std::map& metadata, OtaType ota_type); diff --git a/install/include/install/package.h b/install/include/install/package.h new file mode 100644 index 000000000..cd44d10be --- /dev/null +++ b/install/include/install/package.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2019 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include + +#include "verifier.h" + +// This class serves as a wrapper for an OTA update package. It aims to provide the common +// interface for both packages loaded in memory and packages read from fd. +class Package : public VerifierInterface { + public: + static std::unique_ptr CreateMemoryPackage( + const std::string& path, const std::function& set_progress); + static std::unique_ptr CreateMemoryPackage( + std::vector content, const std::function& set_progress); + static std::unique_ptr CreateFilePackage(const std::string& path, + const std::function& set_progress); + + virtual ~Package() = default; + + // Opens the package as a zip file and returns the ZipArchiveHandle. + virtual ZipArchiveHandle GetZipArchiveHandle() = 0; + + // Updates the progress in fraction during package verification. + void SetProgress(float progress) override; + + protected: + // An optional function to update the progress. + std::function set_progress_; +}; diff --git a/install/include/install/verifier.h b/install/include/install/verifier.h new file mode 100644 index 000000000..f9e947580 --- /dev/null +++ b/install/include/install/verifier.h @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include +#include +#include + +#include +#include +#include + +constexpr size_t MiB = 1024 * 1024; + +using HasherUpdateCallback = std::function; + +struct RSADeleter { + void operator()(RSA* rsa) const { + RSA_free(rsa); + } +}; + +struct ECKEYDeleter { + void operator()(EC_KEY* ec_key) const { + EC_KEY_free(ec_key); + } +}; + +struct Certificate { + typedef enum { + KEY_TYPE_RSA, + KEY_TYPE_EC, + } KeyType; + + Certificate(int hash_len_, KeyType key_type_, std::unique_ptr&& rsa_, + std::unique_ptr&& ec_) + : hash_len(hash_len_), key_type(key_type_), rsa(std::move(rsa_)), ec(std::move(ec_)) {} + + // SHA_DIGEST_LENGTH (SHA-1) or SHA256_DIGEST_LENGTH (SHA-256) + int hash_len; + KeyType key_type; + std::unique_ptr rsa; + std::unique_ptr ec; +}; + +class VerifierInterface { + public: + virtual ~VerifierInterface() = default; + + // Returns the package size in bytes. + virtual uint64_t GetPackageSize() const = 0; + + // Reads |byte_count| data starting from |offset|, and puts the result in |buffer|. + virtual bool ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) = 0; + + // Updates the hash contexts for |length| bytes data starting from |start|. + virtual bool UpdateHashAtOffset(const std::vector& hashers, uint64_t start, + uint64_t length) = 0; + + // Updates the progress in fraction during package verification. + virtual void SetProgress(float progress) = 0; +}; + +// Looks for an RSA signature embedded in the .ZIP file comment given the path to the zip. +// Verifies that it matches one of the given public keys. Returns VERIFY_SUCCESS or +// VERIFY_FAILURE (if any error is encountered or no key matches the signature). +int verify_file(VerifierInterface* package, const std::vector& keys); + +// Checks that the RSA key has a modulus of 2048 or 4096 bits long, and public exponent is 3 or +// 65537. +bool CheckRSAKey(const std::unique_ptr& rsa); + +// Checks that the field size of the curve for the EC key is 256 bits. +bool CheckECKey(const std::unique_ptr& ec_key); + +// Parses a PEM-encoded x509 certificate from the given buffer and saves it into |cert|. Returns +// false if there is a parsing failure or the signature's encryption algorithm is not supported. +bool LoadCertificateFromBuffer(const std::vector& pem_content, Certificate* cert); + +// Iterates over the zip entries with the suffix "x509.pem" and returns a list of recognized +// certificates. Returns an empty list if we fail to parse any of the entries. +std::vector LoadKeysFromZipfile(const std::string& zip_name); + +#define VERIFY_SUCCESS 0 +#define VERIFY_FAILURE 1 diff --git a/install/include/private/asn1_decoder.h b/install/include/private/asn1_decoder.h new file mode 100644 index 000000000..e5337d9c4 --- /dev/null +++ b/install/include/private/asn1_decoder.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ASN1_DECODER_H_ +#define ASN1_DECODER_H_ + +#include +#include + +class asn1_context { + public: + asn1_context(const uint8_t* buffer, size_t length) : p_(buffer), length_(length), app_type_(0) {} + int asn1_constructed_type() const; + asn1_context* asn1_constructed_get(); + bool asn1_constructed_skip_all(); + asn1_context* asn1_sequence_get(); + asn1_context* asn1_set_get(); + bool asn1_sequence_next(); + bool asn1_oid_get(const uint8_t** oid, size_t* length); + bool asn1_octet_string_get(const uint8_t** octet_string, size_t* length); + + private: + static constexpr int kMaskConstructed = 0xE0; + static constexpr int kMaskTag = 0x7F; + static constexpr int kMaskAppType = 0x1F; + + static constexpr int kTagOctetString = 0x04; + static constexpr int kTagOid = 0x06; + static constexpr int kTagSequence = 0x30; + static constexpr int kTagSet = 0x31; + static constexpr int kTagConstructed = 0xA0; + + int peek_byte() const; + int get_byte(); + bool skip_bytes(size_t num_skip); + bool decode_length(size_t* out_len); + + const uint8_t* p_; + size_t length_; + int app_type_; +}; + +#endif /* ASN1_DECODER_H_ */ diff --git a/install/include/private/setup_commands.h b/install/include/private/setup_commands.h new file mode 100644 index 000000000..7fdc741d6 --- /dev/null +++ b/install/include/private/setup_commands.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Private headers exposed for testing purpose only. + +#pragma once + +#include +#include + +#include + +// Sets up the commands for a non-A/B update. Extracts the updater binary from the open zip archive +// |zip| located at |package|. Stores the command line that should be called into |cmd|. The +// |status_fd| is the file descriptor the child process should use to report back the progress of +// the update. +int SetUpNonAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int retry_count, + int status_fd, std::vector* cmd); + +// Sets up the commands for an A/B update. Extracts the needed entries from the open zip archive +// |zip| located at |package|. Stores the command line that should be called into |cmd|. The +// |status_fd| is the file descriptor the child process should use to report back the progress of +// the update. Note that since this applies to the sideloading flow only, it takes one less +// parameter |retry_count| than the non-A/B version. +int SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd, + std::vector* cmd); diff --git a/install/install.cpp b/install/install.cpp new file mode 100644 index 000000000..a1124c361 --- /dev/null +++ b/install/install.cpp @@ -0,0 +1,730 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "install/install.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "install/package.h" +#include "install/verifier.h" +#include "otautil/error_code.h" +#include "otautil/paths.h" +#include "otautil/roots.h" +#include "otautil/sysutil.h" +#include "otautil/thermalutil.h" +#include "private/setup_commands.h" +#include "recovery_ui/ui.h" + +using namespace std::chrono_literals; + +static constexpr int kRecoveryApiVersion = 3; +// Assert the version defined in code and in Android.mk are consistent. +static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions."); + +// Default allocation of progress bar segments to operations +static constexpr int VERIFICATION_PROGRESS_TIME = 60; +static constexpr float VERIFICATION_PROGRESS_FRACTION = 0.25; + +static std::condition_variable finish_log_temperature; + +bool ReadMetadataFromPackage(ZipArchiveHandle zip, std::map* metadata) { + CHECK(metadata != nullptr); + + static constexpr const char* METADATA_PATH = "META-INF/com/android/metadata"; + ZipString path(METADATA_PATH); + ZipEntry entry; + if (FindEntry(zip, path, &entry) != 0) { + LOG(ERROR) << "Failed to find " << METADATA_PATH; + return false; + } + + uint32_t length = entry.uncompressed_length; + std::string metadata_string(length, '\0'); + int32_t err = + ExtractToMemory(zip, &entry, reinterpret_cast(&metadata_string[0]), length); + if (err != 0) { + LOG(ERROR) << "Failed to extract " << METADATA_PATH << ": " << ErrorCodeString(err); + return false; + } + + for (const std::string& line : android::base::Split(metadata_string, "\n")) { + size_t eq = line.find('='); + if (eq != std::string::npos) { + metadata->emplace(android::base::Trim(line.substr(0, eq)), + android::base::Trim(line.substr(eq + 1))); + } + } + + return true; +} + +// Gets the value for the given key in |metadata|. Returns an emtpy string if the key isn't +// present. +static std::string get_value(const std::map& metadata, + const std::string& key) { + const auto& it = metadata.find(key); + return (it == metadata.end()) ? "" : it->second; +} + +static std::string OtaTypeToString(OtaType type) { + switch (type) { + case OtaType::AB: + return "AB"; + case OtaType::BLOCK: + return "BLOCK"; + case OtaType::BRICK: + return "BRICK"; + } +} + +// Read the build.version.incremental of src/tgt from the metadata and log it to last_install. +static void ReadSourceTargetBuild(const std::map& metadata, + std::vector* log_buffer) { + // Examples of the pre-build and post-build strings in metadata: + // pre-build-incremental=2943039 + // post-build-incremental=2951741 + auto source_build = get_value(metadata, "pre-build-incremental"); + if (!source_build.empty()) { + log_buffer->push_back("source_build: " + source_build); + } + + auto target_build = get_value(metadata, "post-build-incremental"); + if (!target_build.empty()) { + log_buffer->push_back("target_build: " + target_build); + } +} + +// Checks the build version, fingerprint and timestamp in the metadata of the A/B package. +// Downgrading is not allowed unless explicitly enabled in the package and only for +// incremental packages. +static int CheckAbSpecificMetadata(const std::map& metadata) { + // Incremental updates should match the current build. + auto device_pre_build = android::base::GetProperty("ro.build.version.incremental", ""); + auto pkg_pre_build = get_value(metadata, "pre-build-incremental"); + if (!pkg_pre_build.empty() && pkg_pre_build != device_pre_build) { + LOG(ERROR) << "Package is for source build " << pkg_pre_build << " but expected " + << device_pre_build; + return INSTALL_ERROR; + } + + auto device_fingerprint = android::base::GetProperty("ro.build.fingerprint", ""); + auto pkg_pre_build_fingerprint = get_value(metadata, "pre-build"); + if (!pkg_pre_build_fingerprint.empty() && pkg_pre_build_fingerprint != device_fingerprint) { + LOG(ERROR) << "Package is for source build " << pkg_pre_build_fingerprint << " but expected " + << device_fingerprint; + return INSTALL_ERROR; + } + + // Check for downgrade version. + int64_t build_timestamp = + android::base::GetIntProperty("ro.build.date.utc", std::numeric_limits::max()); + int64_t pkg_post_timestamp = 0; + // We allow to full update to the same version we are running, in case there + // is a problem with the current copy of that version. + auto pkg_post_timestamp_string = get_value(metadata, "post-timestamp"); + if (pkg_post_timestamp_string.empty() || + !android::base::ParseInt(pkg_post_timestamp_string, &pkg_post_timestamp) || + pkg_post_timestamp < build_timestamp) { + if (get_value(metadata, "ota-downgrade") != "yes") { + LOG(ERROR) << "Update package is older than the current build, expected a build " + "newer than timestamp " + << build_timestamp << " but package has timestamp " << pkg_post_timestamp + << " and downgrade not allowed."; + return INSTALL_ERROR; + } + if (pkg_pre_build_fingerprint.empty()) { + LOG(ERROR) << "Downgrade package must have a pre-build version set, not allowed."; + return INSTALL_ERROR; + } + } + + return 0; +} + +int CheckPackageMetadata(const std::map& metadata, OtaType ota_type) { + auto package_ota_type = get_value(metadata, "ota-type"); + auto expected_ota_type = OtaTypeToString(ota_type); + if (ota_type != OtaType::AB && ota_type != OtaType::BRICK) { + LOG(INFO) << "Skip package metadata check for ota type " << expected_ota_type; + return 0; + } + + if (package_ota_type != expected_ota_type) { + LOG(ERROR) << "Unexpected ota package type, expects " << expected_ota_type << ", actual " + << package_ota_type; + return INSTALL_ERROR; + } + + auto device = android::base::GetProperty("ro.product.device", ""); + auto pkg_device = get_value(metadata, "pre-device"); + if (pkg_device != device || pkg_device.empty()) { + LOG(ERROR) << "Package is for product " << pkg_device << " but expected " << device; + return INSTALL_ERROR; + } + + // We allow the package to not have any serialno; and we also allow it to carry multiple serial + // numbers split by "|"; e.g. serialno=serialno1|serialno2|serialno3 ... We will fail the + // verification if the device's serialno doesn't match any of these carried numbers. + auto pkg_serial_no = get_value(metadata, "serialno"); + if (!pkg_serial_no.empty()) { + auto device_serial_no = android::base::GetProperty("ro.serialno", ""); + bool serial_number_match = false; + for (const auto& number : android::base::Split(pkg_serial_no, "|")) { + if (device_serial_no == android::base::Trim(number)) { + serial_number_match = true; + } + } + if (!serial_number_match) { + LOG(ERROR) << "Package is for serial " << pkg_serial_no; + return INSTALL_ERROR; + } + } + + if (ota_type == OtaType::AB) { + return CheckAbSpecificMetadata(metadata); + } + + return 0; +} + +int SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd, + std::vector* cmd) { + CHECK(cmd != nullptr); + + // For A/B updates we extract the payload properties to a buffer and obtain the RAW payload offset + // in the zip file. + static constexpr const char* AB_OTA_PAYLOAD_PROPERTIES = "payload_properties.txt"; + ZipString property_name(AB_OTA_PAYLOAD_PROPERTIES); + ZipEntry properties_entry; + if (FindEntry(zip, property_name, &properties_entry) != 0) { + LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES; + return INSTALL_CORRUPT; + } + uint32_t properties_entry_length = properties_entry.uncompressed_length; + std::vector payload_properties(properties_entry_length); + int32_t err = + ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length); + if (err != 0) { + LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err); + return INSTALL_CORRUPT; + } + + static constexpr const char* AB_OTA_PAYLOAD = "payload.bin"; + ZipString payload_name(AB_OTA_PAYLOAD); + ZipEntry payload_entry; + if (FindEntry(zip, payload_name, &payload_entry) != 0) { + LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD; + return INSTALL_CORRUPT; + } + long payload_offset = payload_entry.offset; + *cmd = { + "/system/bin/update_engine_sideload", + "--payload=file://" + package, + android::base::StringPrintf("--offset=%ld", payload_offset), + "--headers=" + std::string(payload_properties.begin(), payload_properties.end()), + android::base::StringPrintf("--status_fd=%d", status_fd), + }; + return 0; +} + +int SetUpNonAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int retry_count, + int status_fd, std::vector* cmd) { + CHECK(cmd != nullptr); + + // In non-A/B updates we extract the update binary from the package. + static constexpr const char* UPDATE_BINARY_NAME = "META-INF/com/google/android/update-binary"; + ZipString binary_name(UPDATE_BINARY_NAME); + ZipEntry binary_entry; + if (FindEntry(zip, binary_name, &binary_entry) != 0) { + LOG(ERROR) << "Failed to find update binary " << UPDATE_BINARY_NAME; + return INSTALL_CORRUPT; + } + + const std::string binary_path = Paths::Get().temporary_update_binary(); + unlink(binary_path.c_str()); + android::base::unique_fd fd( + open(binary_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0755)); + if (fd == -1) { + PLOG(ERROR) << "Failed to create " << binary_path; + return INSTALL_ERROR; + } + + int32_t error = ExtractEntryToFile(zip, &binary_entry, fd); + if (error != 0) { + LOG(ERROR) << "Failed to extract " << UPDATE_BINARY_NAME << ": " << ErrorCodeString(error); + return INSTALL_ERROR; + } + + // When executing the update binary contained in the package, the arguments passed are: + // - the version number for this interface + // - an FD to which the program can write in order to update the progress bar. + // - the name of the package zip file. + // - an optional argument "retry" if this update is a retry of a failed update attempt. + *cmd = { + binary_path, + std::to_string(kRecoveryApiVersion), + std::to_string(status_fd), + package, + }; + if (retry_count > 0) { + cmd->push_back("retry"); + } + return 0; +} + +static void log_max_temperature(int* max_temperature, const std::atomic& logger_finished) { + CHECK(max_temperature != nullptr); + std::mutex mtx; + std::unique_lock lck(mtx); + while (!logger_finished.load() && + finish_log_temperature.wait_for(lck, 20s) == std::cv_status::timeout) { + *max_temperature = std::max(*max_temperature, GetMaxValueFromThermalZone()); + } +} + +// If the package contains an update binary, extract it and run it. +static int try_update_binary(const std::string& package, ZipArchiveHandle zip, bool* wipe_cache, + std::vector* log_buffer, int retry_count, + int* max_temperature, RecoveryUI* ui) { + std::map metadata; + if (!ReadMetadataFromPackage(zip, &metadata)) { + LOG(ERROR) << "Failed to parse metadata in the zip file"; + return INSTALL_CORRUPT; + } + + bool is_ab = android::base::GetBoolProperty("ro.build.ab_update", false); + // Verifies against the metadata in the package first. + if (int check_status = is_ab ? CheckPackageMetadata(metadata, OtaType::AB) : 0; + check_status != 0) { + log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure)); + return check_status; + } + + ReadSourceTargetBuild(metadata, log_buffer); + + // The updater in child process writes to the pipe to communicate with recovery. + android::base::unique_fd pipe_read, pipe_write; + // Explicitly disable O_CLOEXEC using 0 as the flags (last) parameter to Pipe + // so that the child updater process will recieve a non-closed fd. + if (!android::base::Pipe(&pipe_read, &pipe_write, 0)) { + PLOG(ERROR) << "Failed to create pipe for updater-recovery communication"; + return INSTALL_CORRUPT; + } + + // The updater-recovery communication protocol. + // + // progress + // fill up the next part of of the progress bar over seconds. If is + // zero, use `set_progress` commands to manually control the progress of this segment of the + // bar. + // + // set_progress + // should be between 0.0 and 1.0; sets the progress bar within the segment defined by + // the most recent progress command. + // + // ui_print + // display on the screen. + // + // wipe_cache + // a wipe of cache will be performed following a successful installation. + // + // clear_display + // turn off the text display. + // + // enable_reboot + // packages can explicitly request that they want the user to be able to reboot during + // installation (useful for debugging packages that don't exit). + // + // retry_update + // updater encounters some issue during the update. It requests a reboot to retry the same + // package automatically. + // + // log + // updater requests logging the string (e.g. cause of the failure). + // + + std::vector args; + if (int update_status = + is_ab ? SetUpAbUpdateCommands(package, zip, pipe_write.get(), &args) + : SetUpNonAbUpdateCommands(package, zip, retry_count, pipe_write.get(), &args); + update_status != 0) { + log_buffer->push_back(android::base::StringPrintf("error: %d", kUpdateBinaryCommandFailure)); + return update_status; + } + + pid_t pid = fork(); + if (pid == -1) { + PLOG(ERROR) << "Failed to fork update binary"; + log_buffer->push_back(android::base::StringPrintf("error: %d", kForkUpdateBinaryFailure)); + return INSTALL_ERROR; + } + + if (pid == 0) { + umask(022); + pipe_read.reset(); + + // Convert the std::string vector to a NULL-terminated char* vector suitable for execv. + auto chr_args = StringVectorToNullTerminatedArray(args); + execv(chr_args[0], chr_args.data()); + // We shouldn't use LOG/PLOG in the forked process, since they may cause the child process to + // hang. This deadlock results from an improperly copied mutex in the ui functions. + // (Bug: 34769056) + fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno)); + _exit(EXIT_FAILURE); + } + pipe_write.reset(); + + std::atomic logger_finished(false); + std::thread temperature_logger(log_max_temperature, max_temperature, std::ref(logger_finished)); + + *wipe_cache = false; + bool retry_update = false; + + char buffer[1024]; + FILE* from_child = android::base::Fdopen(std::move(pipe_read), "r"); + while (fgets(buffer, sizeof(buffer), from_child) != nullptr) { + std::string line(buffer); + size_t space = line.find_first_of(" \n"); + std::string command(line.substr(0, space)); + if (command.empty()) continue; + + // Get rid of the leading and trailing space and/or newline. + std::string args = space == std::string::npos ? "" : android::base::Trim(line.substr(space)); + + if (command == "progress") { + std::vector tokens = android::base::Split(args, " "); + double fraction; + int seconds; + if (tokens.size() == 2 && android::base::ParseDouble(tokens[0].c_str(), &fraction) && + android::base::ParseInt(tokens[1], &seconds)) { + ui->ShowProgress(fraction * (1 - VERIFICATION_PROGRESS_FRACTION), seconds); + } else { + LOG(ERROR) << "invalid \"progress\" parameters: " << line; + } + } else if (command == "set_progress") { + std::vector tokens = android::base::Split(args, " "); + double fraction; + if (tokens.size() == 1 && android::base::ParseDouble(tokens[0].c_str(), &fraction)) { + ui->SetProgress(fraction); + } else { + LOG(ERROR) << "invalid \"set_progress\" parameters: " << line; + } + } else if (command == "ui_print") { + ui->PrintOnScreenOnly("%s\n", args.c_str()); + fflush(stdout); + } else if (command == "wipe_cache") { + *wipe_cache = true; + } else if (command == "clear_display") { + ui->SetBackground(RecoveryUI::NONE); + } else if (command == "enable_reboot") { + // packages can explicitly request that they want the user + // to be able to reboot during installation (useful for + // debugging packages that don't exit). + ui->SetEnableReboot(true); + } else if (command == "retry_update") { + retry_update = true; + } else if (command == "log") { + if (!args.empty()) { + // Save the logging request from updater and write to last_install later. + log_buffer->push_back(args); + } else { + LOG(ERROR) << "invalid \"log\" parameters: " << line; + } + } else { + LOG(ERROR) << "unknown command [" << command << "]"; + } + } + fclose(from_child); + + int status; + waitpid(pid, &status, 0); + + logger_finished.store(true); + finish_log_temperature.notify_one(); + temperature_logger.join(); + + if (retry_update) { + return INSTALL_RETRY; + } + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) != EXIT_SUCCESS) { + LOG(ERROR) << "Error in " << package << " (status " << WEXITSTATUS(status) << ")"; + return INSTALL_ERROR; + } + } else if (WIFSIGNALED(status)) { + LOG(ERROR) << "Error in " << package << " (killed by signal " << WTERMSIG(status) << ")"; + return INSTALL_ERROR; + } else { + LOG(FATAL) << "Invalid status code " << status; + } + + return INSTALL_SUCCESS; +} + +// Verifes the compatibility info in a Treble-compatible package. Returns true directly if the +// entry doesn't exist. Note that the compatibility info is packed in a zip file inside the OTA +// package. +bool verify_package_compatibility(ZipArchiveHandle package_zip) { + LOG(INFO) << "Verifying package compatibility..."; + + static constexpr const char* COMPATIBILITY_ZIP_ENTRY = "compatibility.zip"; + ZipString compatibility_entry_name(COMPATIBILITY_ZIP_ENTRY); + ZipEntry compatibility_entry; + if (FindEntry(package_zip, compatibility_entry_name, &compatibility_entry) != 0) { + LOG(INFO) << "Package doesn't contain " << COMPATIBILITY_ZIP_ENTRY << " entry"; + return true; + } + + std::string zip_content(compatibility_entry.uncompressed_length, '\0'); + int32_t ret; + if ((ret = ExtractToMemory(package_zip, &compatibility_entry, + reinterpret_cast(&zip_content[0]), + compatibility_entry.uncompressed_length)) != 0) { + LOG(ERROR) << "Failed to read " << COMPATIBILITY_ZIP_ENTRY << ": " << ErrorCodeString(ret); + return false; + } + + ZipArchiveHandle zip_handle; + ret = OpenArchiveFromMemory(static_cast(const_cast(zip_content.data())), + zip_content.size(), COMPATIBILITY_ZIP_ENTRY, &zip_handle); + if (ret != 0) { + LOG(ERROR) << "Failed to OpenArchiveFromMemory: " << ErrorCodeString(ret); + return false; + } + + // Iterate all the entries inside COMPATIBILITY_ZIP_ENTRY and read the contents. + void* cookie; + ret = StartIteration(zip_handle, &cookie, nullptr, nullptr); + if (ret != 0) { + LOG(ERROR) << "Failed to start iterating zip entries: " << ErrorCodeString(ret); + CloseArchive(zip_handle); + return false; + } + std::unique_ptr guard(cookie, EndIteration); + + std::vector compatibility_info; + ZipEntry info_entry; + ZipString info_name; + while (Next(cookie, &info_entry, &info_name) == 0) { + std::string content(info_entry.uncompressed_length, '\0'); + int32_t ret = ExtractToMemory(zip_handle, &info_entry, reinterpret_cast(&content[0]), + info_entry.uncompressed_length); + if (ret != 0) { + LOG(ERROR) << "Failed to read " << info_name.name << ": " << ErrorCodeString(ret); + CloseArchive(zip_handle); + return false; + } + compatibility_info.emplace_back(std::move(content)); + } + CloseArchive(zip_handle); + + // VintfObjectRecovery::CheckCompatibility returns zero on success. + std::string err; + int result = android::vintf::VintfObjectRecovery::CheckCompatibility(compatibility_info, &err); + if (result == 0) { + return true; + } + + LOG(ERROR) << "Failed to verify package compatibility (result " << result << "): " << err; + return false; +} + +static int really_install_package(const std::string& path, bool* wipe_cache, bool needs_mount, + std::vector* log_buffer, int retry_count, + int* max_temperature, RecoveryUI* ui) { + ui->SetBackground(RecoveryUI::INSTALLING_UPDATE); + ui->Print("Finding update package...\n"); + // Give verification half the progress bar... + ui->SetProgressType(RecoveryUI::DETERMINATE); + ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME); + LOG(INFO) << "Update location: " << path; + + // Map the update package into memory. + ui->Print("Opening update package...\n"); + + if (needs_mount) { + if (path[0] == '@') { + ensure_path_mounted(path.substr(1)); + } else { + ensure_path_mounted(path); + } + } + + auto package = Package::CreateMemoryPackage( + path, std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1)); + if (!package) { + log_buffer->push_back(android::base::StringPrintf("error: %d", kMapFileFailure)); + return INSTALL_CORRUPT; + } + + // Verify package. + if (!verify_package(package.get(), ui)) { + log_buffer->push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure)); + return INSTALL_CORRUPT; + } + + // Try to open the package. + ZipArchiveHandle zip = package->GetZipArchiveHandle(); + if (!zip) { + log_buffer->push_back(android::base::StringPrintf("error: %d", kZipOpenFailure)); + return INSTALL_CORRUPT; + } + + // Additionally verify the compatibility of the package if it's a fresh install. + if (retry_count == 0 && !verify_package_compatibility(zip)) { + log_buffer->push_back(android::base::StringPrintf("error: %d", kPackageCompatibilityFailure)); + return INSTALL_CORRUPT; + } + + // Verify and install the contents of the package. + ui->Print("Installing update...\n"); + if (retry_count > 0) { + ui->Print("Retry attempt: %d\n", retry_count); + } + ui->SetEnableReboot(false); + int result = + try_update_binary(path, zip, wipe_cache, log_buffer, retry_count, max_temperature, ui); + ui->SetEnableReboot(true); + ui->Print("\n"); + + return result; +} + +int install_package(const std::string& path, bool* wipe_cache, bool needs_mount, int retry_count, + RecoveryUI* ui) { + CHECK(!path.empty()); + CHECK(wipe_cache != nullptr); + + auto start = std::chrono::system_clock::now(); + + int start_temperature = GetMaxValueFromThermalZone(); + int max_temperature = start_temperature; + + int result; + std::vector log_buffer; + if (setup_install_mounts() != 0) { + LOG(ERROR) << "failed to set up expected mounts for install; aborting"; + result = INSTALL_ERROR; + } else { + result = really_install_package(path, wipe_cache, needs_mount, &log_buffer, retry_count, + &max_temperature, ui); + } + + // Measure the time spent to apply OTA update in seconds. + std::chrono::duration duration = std::chrono::system_clock::now() - start; + int time_total = static_cast(duration.count()); + + bool has_cache = volume_for_mount_point("/cache") != nullptr; + // Skip logging the uncrypt_status on devices without /cache. + if (has_cache) { + static constexpr const char* UNCRYPT_STATUS = "/cache/recovery/uncrypt_status"; + if (ensure_path_mounted(UNCRYPT_STATUS) != 0) { + LOG(WARNING) << "Can't mount " << UNCRYPT_STATUS; + } else { + std::string uncrypt_status; + if (!android::base::ReadFileToString(UNCRYPT_STATUS, &uncrypt_status)) { + PLOG(WARNING) << "failed to read uncrypt status"; + } else if (!android::base::StartsWith(uncrypt_status, "uncrypt_")) { + LOG(WARNING) << "corrupted uncrypt_status: " << uncrypt_status; + } else { + log_buffer.push_back(android::base::Trim(uncrypt_status)); + } + } + } + + // The first two lines need to be the package name and install result. + std::vector log_header = { + path, + result == INSTALL_SUCCESS ? "1" : "0", + "time_total: " + std::to_string(time_total), + "retry: " + std::to_string(retry_count), + }; + + int end_temperature = GetMaxValueFromThermalZone(); + max_temperature = std::max(end_temperature, max_temperature); + if (start_temperature > 0) { + log_buffer.push_back("temperature_start: " + std::to_string(start_temperature)); + } + if (end_temperature > 0) { + log_buffer.push_back("temperature_end: " + std::to_string(end_temperature)); + } + if (max_temperature > 0) { + log_buffer.push_back("temperature_max: " + std::to_string(max_temperature)); + } + + std::string log_content = + android::base::Join(log_header, "\n") + "\n" + android::base::Join(log_buffer, "\n") + "\n"; + const std::string& install_file = Paths::Get().temporary_install_file(); + if (!android::base::WriteStringToFile(log_content, install_file)) { + PLOG(ERROR) << "failed to write " << install_file; + } + + // Write a copy into last_log. + LOG(INFO) << log_content; + + return result; +} + +bool verify_package(Package* package, RecoveryUI* ui) { + static constexpr const char* CERTIFICATE_ZIP_FILE = "/system/etc/security/otacerts.zip"; + std::vector loaded_keys = LoadKeysFromZipfile(CERTIFICATE_ZIP_FILE); + if (loaded_keys.empty()) { + LOG(ERROR) << "Failed to load keys"; + return false; + } + LOG(INFO) << loaded_keys.size() << " key(s) loaded from " << CERTIFICATE_ZIP_FILE; + + // Verify package. + ui->Print("Verifying update package...\n"); + auto t0 = std::chrono::system_clock::now(); + int err = verify_file(package, loaded_keys); + std::chrono::duration duration = std::chrono::system_clock::now() - t0; + ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err); + if (err != VERIFY_SUCCESS) { + LOG(ERROR) << "Signature verification failed"; + LOG(ERROR) << "error: " << kZipVerificationFailure; + return false; + } + return true; +} diff --git a/install/package.cpp b/install/package.cpp new file mode 100644 index 000000000..4402f4855 --- /dev/null +++ b/install/package.cpp @@ -0,0 +1,262 @@ +/* + * Copyright (C) 2019 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "install/package.h" + +#include +#include + +#include +#include +#include +#include + +#include "otautil/error_code.h" +#include "otautil/sysutil.h" + +// This class wraps the package in memory, i.e. a memory mapped package, or a package loaded +// to a string/vector. +class MemoryPackage : public Package { + public: + // Constructs the class from a file. We will memory maps the file later. + MemoryPackage(const std::string& path, std::unique_ptr map, + const std::function& set_progress); + + // Constructs the class from the package bytes in |content|. + MemoryPackage(std::vector content, const std::function& set_progress); + + ~MemoryPackage() override; + + // Memory maps the package file if necessary. Initializes the start address and size of the + // package. + uint64_t GetPackageSize() const override { + return package_size_; + } + + bool ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) override; + + ZipArchiveHandle GetZipArchiveHandle() override; + + bool UpdateHashAtOffset(const std::vector& hashers, uint64_t start, + uint64_t length) override; + + private: + const uint8_t* addr_; // Start address of the package in memory. + uint64_t package_size_; // Package size in bytes. + + // The memory mapped package. + std::unique_ptr map_; + // A copy of the package content, valid only if we create the class with the exact bytes of + // the package. + std::vector package_content_; + // The physical path to the package, empty if we create the class with the package content. + std::string path_; + + // The ZipArchiveHandle of the package. + ZipArchiveHandle zip_handle_; +}; + +void Package::SetProgress(float progress) { + if (set_progress_) { + set_progress_(progress); + } +} + +class FilePackage : public Package { + public: + FilePackage(android::base::unique_fd&& fd, uint64_t file_size, const std::string& path, + const std::function& set_progress); + + ~FilePackage() override; + + uint64_t GetPackageSize() const override { + return package_size_; + } + + bool ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) override; + + ZipArchiveHandle GetZipArchiveHandle() override; + + bool UpdateHashAtOffset(const std::vector& hashers, uint64_t start, + uint64_t length) override; + + private: + android::base::unique_fd fd_; // The underlying fd to the open package. + uint64_t package_size_; + std::string path_; // The physical path to the package. + + ZipArchiveHandle zip_handle_; +}; + +std::unique_ptr Package::CreateMemoryPackage( + const std::string& path, const std::function& set_progress) { + std::unique_ptr mmap = std::make_unique(); + if (!mmap->MapFile(path)) { + LOG(ERROR) << "failed to map file"; + return nullptr; + } + + return std::make_unique(path, std::move(mmap), set_progress); +} + +std::unique_ptr Package::CreateFilePackage( + const std::string& path, const std::function& set_progress) { + android::base::unique_fd fd(open(path.c_str(), O_RDONLY)); + if (fd == -1) { + PLOG(ERROR) << "Failed to open " << path; + return nullptr; + } + + off64_t file_size = lseek64(fd.get(), 0, SEEK_END); + if (file_size == -1) { + PLOG(ERROR) << "Failed to get the package size"; + return nullptr; + } + + return std::make_unique(std::move(fd), file_size, path, set_progress); +} + +std::unique_ptr Package::CreateMemoryPackage( + std::vector content, const std::function& set_progress) { + return std::make_unique(std::move(content), set_progress); +} + +MemoryPackage::MemoryPackage(const std::string& path, std::unique_ptr map, + const std::function& set_progress) + : map_(std::move(map)), path_(path), zip_handle_(nullptr) { + addr_ = map_->addr; + package_size_ = map_->length; + set_progress_ = set_progress; +} + +MemoryPackage::MemoryPackage(std::vector content, + const std::function& set_progress) + : package_content_(std::move(content)), zip_handle_(nullptr) { + CHECK(!package_content_.empty()); + addr_ = package_content_.data(); + package_size_ = package_content_.size(); + set_progress_ = set_progress; +} + +MemoryPackage::~MemoryPackage() { + if (zip_handle_) { + CloseArchive(zip_handle_); + } +} + +bool MemoryPackage::ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) { + if (byte_count > package_size_ || offset > package_size_ - byte_count) { + LOG(ERROR) << "Out of bound read, offset: " << offset << ", size: " << byte_count + << ", total package_size: " << package_size_; + return false; + } + memcpy(buffer, addr_ + offset, byte_count); + return true; +} + +bool MemoryPackage::UpdateHashAtOffset(const std::vector& hashers, + uint64_t start, uint64_t length) { + if (length > package_size_ || start > package_size_ - length) { + LOG(ERROR) << "Out of bound read, offset: " << start << ", size: " << length + << ", total package_size: " << package_size_; + return false; + } + + for (const auto& hasher : hashers) { + hasher(addr_ + start, length); + } + return true; +} + +ZipArchiveHandle MemoryPackage::GetZipArchiveHandle() { + if (zip_handle_) { + return zip_handle_; + } + + if (auto err = OpenArchiveFromMemory(const_cast(addr_), package_size_, path_.c_str(), + &zip_handle_); + err != 0) { + LOG(ERROR) << "Can't open package" << path_ << " : " << ErrorCodeString(err); + return nullptr; + } + + return zip_handle_; +} + +FilePackage::FilePackage(android::base::unique_fd&& fd, uint64_t file_size, const std::string& path, + const std::function& set_progress) + : fd_(std::move(fd)), package_size_(file_size), path_(path), zip_handle_(nullptr) { + set_progress_ = set_progress; +} + +FilePackage::~FilePackage() { + if (zip_handle_) { + CloseArchive(zip_handle_); + } +} + +bool FilePackage::ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) { + if (byte_count > package_size_ || offset > package_size_ - byte_count) { + LOG(ERROR) << "Out of bound read, offset: " << offset << ", size: " << byte_count + << ", total package_size: " << package_size_; + return false; + } + + if (!android::base::ReadFullyAtOffset(fd_.get(), buffer, byte_count, offset)) { + PLOG(ERROR) << "Failed to read " << byte_count << " bytes data at offset " << offset; + return false; + } + + return true; +} + +bool FilePackage::UpdateHashAtOffset(const std::vector& hashers, + uint64_t start, uint64_t length) { + if (length > package_size_ || start > package_size_ - length) { + LOG(ERROR) << "Out of bound read, offset: " << start << ", size: " << length + << ", total package_size: " << package_size_; + return false; + } + + uint64_t so_far = 0; + while (so_far < length) { + uint64_t read_size = std::min(length - so_far, 16 * MiB); + std::vector buffer(read_size); + if (!ReadFullyAtOffset(buffer.data(), read_size, start + so_far)) { + return false; + } + + for (const auto& hasher : hashers) { + hasher(buffer.data(), read_size); + } + so_far += read_size; + } + + return true; +} + +ZipArchiveHandle FilePackage::GetZipArchiveHandle() { + if (zip_handle_) { + return zip_handle_; + } + + if (auto err = OpenArchiveFd(fd_.get(), path_.c_str(), &zip_handle_); err != 0) { + LOG(ERROR) << "Can't open package" << path_ << " : " << ErrorCodeString(err); + return nullptr; + } + + return zip_handle_; +} diff --git a/install/verifier.cpp b/install/verifier.cpp new file mode 100644 index 000000000..6ba1d77c3 --- /dev/null +++ b/install/verifier.cpp @@ -0,0 +1,468 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "install/verifier.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "otautil/print_sha1.h" +#include "private/asn1_decoder.h" + +/* + * Simple version of PKCS#7 SignedData extraction. This extracts the + * signature OCTET STRING to be used for signature verification. + * + * For full details, see http://www.ietf.org/rfc/rfc3852.txt + * + * The PKCS#7 structure looks like: + * + * SEQUENCE (ContentInfo) + * OID (ContentType) + * [0] (content) + * SEQUENCE (SignedData) + * INTEGER (version CMSVersion) + * SET (DigestAlgorithmIdentifiers) + * SEQUENCE (EncapsulatedContentInfo) + * [0] (CertificateSet OPTIONAL) + * [1] (RevocationInfoChoices OPTIONAL) + * SET (SignerInfos) + * SEQUENCE (SignerInfo) + * INTEGER (CMSVersion) + * SEQUENCE (SignerIdentifier) + * SEQUENCE (DigestAlgorithmIdentifier) + * SEQUENCE (SignatureAlgorithmIdentifier) + * OCTET STRING (SignatureValue) + */ +static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len, + std::vector* sig_der) { + CHECK(sig_der != nullptr); + sig_der->clear(); + + asn1_context ctx(pkcs7_der, pkcs7_der_len); + + std::unique_ptr pkcs7_seq(ctx.asn1_sequence_get()); + if (pkcs7_seq == nullptr || !pkcs7_seq->asn1_sequence_next()) { + return false; + } + + std::unique_ptr signed_data_app(pkcs7_seq->asn1_constructed_get()); + if (signed_data_app == nullptr) { + return false; + } + + std::unique_ptr signed_data_seq(signed_data_app->asn1_sequence_get()); + if (signed_data_seq == nullptr || !signed_data_seq->asn1_sequence_next() || + !signed_data_seq->asn1_sequence_next() || !signed_data_seq->asn1_sequence_next() || + !signed_data_seq->asn1_constructed_skip_all()) { + return false; + } + + std::unique_ptr sig_set(signed_data_seq->asn1_set_get()); + if (sig_set == nullptr) { + return false; + } + + std::unique_ptr sig_seq(sig_set->asn1_sequence_get()); + if (sig_seq == nullptr || !sig_seq->asn1_sequence_next() || !sig_seq->asn1_sequence_next() || + !sig_seq->asn1_sequence_next() || !sig_seq->asn1_sequence_next()) { + return false; + } + + const uint8_t* sig_der_ptr; + size_t sig_der_length; + if (!sig_seq->asn1_octet_string_get(&sig_der_ptr, &sig_der_length)) { + return false; + } + + sig_der->resize(sig_der_length); + std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin()); + return true; +} + +int verify_file(VerifierInterface* package, const std::vector& keys) { + CHECK(package); + package->SetProgress(0.0); + + // An archive with a whole-file signature will end in six bytes: + // + // (2-byte signature start) $ff $ff (2-byte comment size) + // + // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by + // reading this footer, this tells us how far back from the end we have to start reading to find + // the whole comment. + +#define FOOTER_SIZE 6 + uint64_t length = package->GetPackageSize(); + + if (length < FOOTER_SIZE) { + LOG(ERROR) << "not big enough to contain footer"; + return VERIFY_FAILURE; + } + + uint8_t footer[FOOTER_SIZE]; + if (!package->ReadFullyAtOffset(footer, FOOTER_SIZE, length - FOOTER_SIZE)) { + LOG(ERROR) << "Failed to read footer"; + return VERIFY_FAILURE; + } + + if (footer[2] != 0xff || footer[3] != 0xff) { + LOG(ERROR) << "footer is wrong"; + return VERIFY_FAILURE; + } + + size_t comment_size = footer[4] + (footer[5] << 8); + size_t signature_start = footer[0] + (footer[1] << 8); + LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start + << " bytes from end"; + + if (signature_start > comment_size) { + LOG(ERROR) << "signature start: " << signature_start + << " is larger than comment size: " << comment_size; + return VERIFY_FAILURE; + } + + if (signature_start <= FOOTER_SIZE) { + LOG(ERROR) << "Signature start is in the footer"; + return VERIFY_FAILURE; + } + +#define EOCD_HEADER_SIZE 22 + + // The end-of-central-directory record is 22 bytes plus any comment length. + size_t eocd_size = comment_size + EOCD_HEADER_SIZE; + + if (length < eocd_size) { + LOG(ERROR) << "not big enough to contain EOCD"; + return VERIFY_FAILURE; + } + + // Determine how much of the file is covered by the signature. This is everything except the + // signature data and length, which includes all of the EOCD except for the comment length field + // (2 bytes) and the comment data. + uint64_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2; + + uint8_t eocd[eocd_size]; + if (!package->ReadFullyAtOffset(eocd, eocd_size, length - eocd_size)) { + LOG(ERROR) << "Failed to read EOCD of " << eocd_size << " bytes"; + return VERIFY_FAILURE; + } + + // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06. + if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) { + LOG(ERROR) << "signature length doesn't match EOCD marker"; + return VERIFY_FAILURE; + } + + for (size_t i = 4; i < eocd_size - 3; ++i) { + if (eocd[i] == 0x50 && eocd[i + 1] == 0x4b && eocd[i + 2] == 0x05 && eocd[i + 3] == 0x06) { + // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will + // find the later (wrong) one, which could be exploitable. Fail the verification if this + // sequence occurs anywhere after the real one. + LOG(ERROR) << "EOCD marker occurs after start of EOCD"; + return VERIFY_FAILURE; + } + } + + bool need_sha1 = false; + bool need_sha256 = false; + for (const auto& key : keys) { + switch (key.hash_len) { + case SHA_DIGEST_LENGTH: + need_sha1 = true; + break; + case SHA256_DIGEST_LENGTH: + need_sha256 = true; + break; + } + } + + SHA_CTX sha1_ctx; + SHA256_CTX sha256_ctx; + SHA1_Init(&sha1_ctx); + SHA256_Init(&sha256_ctx); + + std::vector hashers; + if (need_sha1) { + hashers.emplace_back( + std::bind(&SHA1_Update, &sha1_ctx, std::placeholders::_1, std::placeholders::_2)); + } + if (need_sha256) { + hashers.emplace_back( + std::bind(&SHA256_Update, &sha256_ctx, std::placeholders::_1, std::placeholders::_2)); + } + + double frac = -1.0; + uint64_t so_far = 0; + while (so_far < signed_len) { + // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a 1196MiB full OTA and + // 60% for an 89MiB incremental OTA. http://b/28135231. + uint64_t read_size = std::min(signed_len - so_far, 16 * MiB); + package->UpdateHashAtOffset(hashers, so_far, read_size); + so_far += read_size; + + double f = so_far / static_cast(signed_len); + if (f > frac + 0.02 || read_size == so_far) { + package->SetProgress(f); + frac = f; + } + } + + uint8_t sha1[SHA_DIGEST_LENGTH]; + SHA1_Final(sha1, &sha1_ctx); + uint8_t sha256[SHA256_DIGEST_LENGTH]; + SHA256_Final(sha256, &sha256_ctx); + + const uint8_t* signature = eocd + eocd_size - signature_start; + size_t signature_size = signature_start - FOOTER_SIZE; + + LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) + << ", length: " << signature_size << "): " << print_hex(signature, signature_size); + + std::vector sig_der; + if (!read_pkcs7(signature, signature_size, &sig_der)) { + LOG(ERROR) << "Could not find signature DER block"; + return VERIFY_FAILURE; + } + + // Check to make sure at least one of the keys matches the signature. Since any key can match, + // we need to try each before determining a verification failure has happened. + size_t i = 0; + for (const auto& key : keys) { + const uint8_t* hash; + int hash_nid; + switch (key.hash_len) { + case SHA_DIGEST_LENGTH: + hash = sha1; + hash_nid = NID_sha1; + break; + case SHA256_DIGEST_LENGTH: + hash = sha256; + hash_nid = NID_sha256; + break; + default: + continue; + } + + // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends + // after the signature itself. + if (key.key_type == Certificate::KEY_TYPE_RSA) { + if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(), + key.rsa.get())) { + LOG(INFO) << "failed to verify against RSA key " << i; + continue; + } + + LOG(INFO) << "whole-file signature verified against RSA key " << i; + return VERIFY_SUCCESS; + } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) { + if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) { + LOG(INFO) << "failed to verify against EC key " << i; + continue; + } + + LOG(INFO) << "whole-file signature verified against EC key " << i; + return VERIFY_SUCCESS; + } else { + LOG(INFO) << "Unknown key type " << key.key_type; + } + i++; + } + + if (need_sha1) { + LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH); + } + if (need_sha256) { + LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH); + } + LOG(ERROR) << "failed to verify whole-file signature"; + return VERIFY_FAILURE; +} + +static std::vector IterateZipEntriesAndSearchForKeys(const ZipArchiveHandle& handle) { + void* cookie; + ZipString suffix("x509.pem"); + int32_t iter_status = StartIteration(handle, &cookie, nullptr, &suffix); + if (iter_status != 0) { + LOG(ERROR) << "Failed to iterate over entries in the certificate zipfile: " + << ErrorCodeString(iter_status); + return {}; + } + + std::vector result; + + ZipString name; + ZipEntry entry; + while ((iter_status = Next(cookie, &entry, &name)) == 0) { + std::vector pem_content(entry.uncompressed_length); + if (int32_t extract_status = + ExtractToMemory(handle, &entry, pem_content.data(), pem_content.size()); + extract_status != 0) { + LOG(ERROR) << "Failed to extract " << std::string(name.name, name.name + name.name_length); + return {}; + } + + Certificate cert(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr); + // Aborts the parsing if we fail to load one of the key file. + if (!LoadCertificateFromBuffer(pem_content, &cert)) { + LOG(ERROR) << "Failed to load keys from " + << std::string(name.name, name.name + name.name_length); + return {}; + } + + result.emplace_back(std::move(cert)); + } + + if (iter_status != -1) { + LOG(ERROR) << "Error while iterating over zip entries: " << ErrorCodeString(iter_status); + return {}; + } + + return result; +} + +std::vector LoadKeysFromZipfile(const std::string& zip_name) { + ZipArchiveHandle handle; + if (int32_t open_status = OpenArchive(zip_name.c_str(), &handle); open_status != 0) { + LOG(ERROR) << "Failed to open " << zip_name << ": " << ErrorCodeString(open_status); + return {}; + } + + std::vector result = IterateZipEntriesAndSearchForKeys(handle); + CloseArchive(handle); + return result; +} + +bool CheckRSAKey(const std::unique_ptr& rsa) { + if (!rsa) { + return false; + } + + const BIGNUM* out_n; + const BIGNUM* out_e; + RSA_get0_key(rsa.get(), &out_n, &out_e, nullptr /* private exponent */); + auto modulus_bits = BN_num_bits(out_n); + if (modulus_bits != 2048 && modulus_bits != 4096) { + LOG(ERROR) << "Modulus should be 2048 or 4096 bits long, actual: " << modulus_bits; + return false; + } + + BN_ULONG exponent = BN_get_word(out_e); + if (exponent != 3 && exponent != 65537) { + LOG(ERROR) << "Public exponent should be 3 or 65537, actual: " << exponent; + return false; + } + + return true; +} + +bool CheckECKey(const std::unique_ptr& ec_key) { + if (!ec_key) { + return false; + } + + const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key.get()); + if (!ec_group) { + LOG(ERROR) << "Failed to get the ec_group from the ec_key"; + return false; + } + auto degree = EC_GROUP_get_degree(ec_group); + if (degree != 256) { + LOG(ERROR) << "Field size of the ec key should be 256 bits long, actual: " << degree; + return false; + } + + return true; +} + +bool LoadCertificateFromBuffer(const std::vector& pem_content, Certificate* cert) { + std::unique_ptr content( + BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free); + + std::unique_ptr x509( + PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free); + if (!x509) { + LOG(ERROR) << "Failed to read x509 certificate"; + return false; + } + + int nid = X509_get_signature_nid(x509.get()); + switch (nid) { + // SignApk has historically accepted md5WithRSA certificates, but treated them as + // sha1WithRSA anyway. Continue to do so for backwards compatibility. + case NID_md5WithRSA: + case NID_md5WithRSAEncryption: + case NID_sha1WithRSA: + case NID_sha1WithRSAEncryption: + cert->hash_len = SHA_DIGEST_LENGTH; + break; + case NID_sha256WithRSAEncryption: + case NID_ecdsa_with_SHA256: + cert->hash_len = SHA256_DIGEST_LENGTH; + break; + default: + LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid); + return false; + } + + std::unique_ptr public_key(X509_get_pubkey(x509.get()), + EVP_PKEY_free); + if (!public_key) { + LOG(ERROR) << "Failed to extract the public key from x509 certificate"; + return false; + } + + int key_type = EVP_PKEY_id(public_key.get()); + if (key_type == EVP_PKEY_RSA) { + cert->key_type = Certificate::KEY_TYPE_RSA; + cert->ec.reset(); + cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get())); + if (!cert->rsa || !CheckRSAKey(cert->rsa)) { + LOG(ERROR) << "Failed to validate the rsa key info from public key"; + return false; + } + } else if (key_type == EVP_PKEY_EC) { + cert->key_type = Certificate::KEY_TYPE_EC; + cert->rsa.reset(); + cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get())); + if (!cert->ec || !CheckECKey(cert->ec)) { + LOG(ERROR) << "Failed to validate the ec key info from the public key"; + return false; + } + } else { + LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type); + return false; + } + + return true; +} diff --git a/logging.cpp b/logging.cpp index 283d11507..48f9ec317 100644 --- a/logging.cpp +++ b/logging.cpp @@ -33,7 +33,7 @@ #include "common.h" #include "otautil/dirutil.h" #include "otautil/paths.h" -#include "roots.h" +#include "otautil/roots.h" static constexpr const char* LOG_FILE = "/cache/recovery/log"; static constexpr const char* LAST_INSTALL_FILE = "/cache/recovery/last_install"; diff --git a/otautil/Android.bp b/otautil/Android.bp index 41018dd2f..b4936c08b 100644 --- a/otautil/Android.bp +++ b/otautil/Android.bp @@ -42,12 +42,23 @@ cc_library_static { "dirutil.cpp", "mounts.cpp", "parse_install_logs.cpp", + "roots.cpp", "sysutil.cpp", "thermalutil.cpp", ], + include_dirs: [ + "system/vold", + ], + + static_libs: [ + "libfstab", + ], + shared_libs: [ "libcutils", + "libext4_utils", + "libfs_mgr", "libselinux", ], }, diff --git a/otautil/include/otautil/roots.h b/otautil/include/otautil/roots.h new file mode 100644 index 000000000..482f3d050 --- /dev/null +++ b/otautil/include/otautil/roots.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include + +using Volume = android::fs_mgr::FstabEntry; + +// Load and parse volume data from /etc/recovery.fstab. +void load_volume_table(); + +// Return the Volume* record for this mount point (or nullptr). +Volume* volume_for_mount_point(const std::string& mount_point); + +// Make sure that the volume 'path' is on is mounted. Returns 0 on +// success (volume is mounted). +int ensure_path_mounted(const std::string& path); + +// Similar to ensure_path_mounted, but allows one to specify the mount_point. +int ensure_path_mounted_at(const std::string& path, const std::string& mount_point); + +// Make sure that the volume 'path' is on is unmounted. Returns 0 on +// success (volume is unmounted); +int ensure_path_unmounted(const std::string& path); + +// Reformat the given volume (must be the mount point only, eg +// "/cache"), no paths permitted. Attempts to unmount the volume if +// it is mounted. +int format_volume(const std::string& volume); + +// Reformat the given volume (must be the mount point only, eg +// "/cache"), no paths permitted. Attempts to unmount the volume if +// it is mounted. +// Copies 'directory' to root of the newly formatted volume +int format_volume(const std::string& volume, const std::string& directory); + +// Ensure that all and only the volumes that packages expect to find +// mounted (/tmp and /cache) are mounted. Returns 0 on success. +int setup_install_mounts(); + +bool logical_partitions_mapped(); + +std::string get_system_root(); diff --git a/otautil/roots.cpp b/otautil/roots.cpp new file mode 100644 index 000000000..815d644e5 --- /dev/null +++ b/otautil/roots.cpp @@ -0,0 +1,285 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "otautil/roots.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "otautil/mounts.h" +#include "otautil/sysutil.h" + +using android::fs_mgr::Fstab; +using android::fs_mgr::FstabEntry; +using android::fs_mgr::ReadDefaultFstab; + +static Fstab fstab; + +void load_volume_table() { + if (!ReadDefaultFstab(&fstab)) { + LOG(ERROR) << "Failed to read default fstab"; + return; + } + + fstab.emplace_back(FstabEntry{ + .mount_point = "/tmp", .fs_type = "ramdisk", .blk_device = "ramdisk", .length = 0 }); + + std::cout << "recovery filesystem table" << std::endl << "=========================" << std::endl; + for (size_t i = 0; i < fstab.size(); ++i) { + const auto& entry = fstab[i]; + std::cout << " " << i << " " << entry.mount_point << " " + << " " << entry.fs_type << " " << entry.blk_device << " " << entry.length + << std::endl; + } + std::cout << std::endl; +} + +Volume* volume_for_mount_point(const std::string& mount_point) { + return android::fs_mgr::GetEntryForMountPoint(&fstab, mount_point); +} + +// Mount the volume specified by path at the given mount_point. +int ensure_path_mounted_at(const std::string& path, const std::string& mount_point) { + return android::fs_mgr::EnsurePathMounted(&fstab, path, mount_point) ? 0 : -1; +} + +int ensure_path_mounted(const std::string& path) { + // Mount at the default mount point. + return android::fs_mgr::EnsurePathMounted(&fstab, path) ? 0 : -1; +} + +int ensure_path_unmounted(const std::string& path) { + return android::fs_mgr::EnsurePathUnmounted(&fstab, path) ? 0 : -1; +} + +static int exec_cmd(const std::vector& args) { + CHECK(!args.empty()); + auto argv = StringVectorToNullTerminatedArray(args); + + pid_t child; + if ((child = fork()) == 0) { + execv(argv[0], argv.data()); + _exit(EXIT_FAILURE); + } + + int status; + waitpid(child, &status, 0); + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + LOG(ERROR) << args[0] << " failed with status " << WEXITSTATUS(status); + } + return WEXITSTATUS(status); +} + +static int64_t get_file_size(int fd, uint64_t reserve_len) { + struct stat buf; + int ret = fstat(fd, &buf); + if (ret) return 0; + + int64_t computed_size; + if (S_ISREG(buf.st_mode)) { + computed_size = buf.st_size - reserve_len; + } else if (S_ISBLK(buf.st_mode)) { + uint64_t block_device_size = get_block_device_size(fd); + if (block_device_size < reserve_len || + block_device_size > std::numeric_limits::max()) { + computed_size = 0; + } else { + computed_size = block_device_size - reserve_len; + } + } else { + computed_size = 0; + } + + return computed_size; +} + +int format_volume(const std::string& volume, const std::string& directory) { + const FstabEntry* v = android::fs_mgr::GetEntryForPath(&fstab, volume); + if (v == nullptr) { + LOG(ERROR) << "unknown volume \"" << volume << "\""; + return -1; + } + if (v->fs_type == "ramdisk") { + LOG(ERROR) << "can't format_volume \"" << volume << "\""; + return -1; + } + if (v->mount_point != volume) { + LOG(ERROR) << "can't give path \"" << volume << "\" to format_volume"; + return -1; + } + if (ensure_path_unmounted(volume) != 0) { + LOG(ERROR) << "format_volume: Failed to unmount \"" << v->mount_point << "\""; + return -1; + } + if (v->fs_type != "ext4" && v->fs_type != "f2fs") { + LOG(ERROR) << "format_volume: fs_type \"" << v->fs_type << "\" unsupported"; + return -1; + } + + // If there's a key_loc that looks like a path, it should be a block device for storing encryption + // metadata. Wipe it too. + if (!v->key_loc.empty() && v->key_loc[0] == '/') { + LOG(INFO) << "Wiping " << v->key_loc; + int fd = open(v->key_loc.c_str(), O_WRONLY | O_CREAT, 0644); + if (fd == -1) { + PLOG(ERROR) << "format_volume: Failed to open " << v->key_loc; + return -1; + } + wipe_block_device(fd, get_file_size(fd)); + close(fd); + } + + int64_t length = 0; + if (v->length > 0) { + length = v->length; + } else if (v->length < 0 || v->key_loc == "footer") { + android::base::unique_fd fd(open(v->blk_device.c_str(), O_RDONLY)); + if (fd == -1) { + PLOG(ERROR) << "format_volume: failed to open " << v->blk_device; + return -1; + } + length = get_file_size(fd.get(), v->length ? -v->length : CRYPT_FOOTER_OFFSET); + if (length <= 0) { + LOG(ERROR) << "get_file_size: invalid size " << length << " for " << v->blk_device; + return -1; + } + } + + if (v->fs_type == "ext4") { + static constexpr int kBlockSize = 4096; + std::vector mke2fs_args = { + "/system/bin/mke2fs", "-F", "-t", "ext4", "-b", std::to_string(kBlockSize), + }; + + int raid_stride = v->logical_blk_size / kBlockSize; + int raid_stripe_width = v->erase_blk_size / kBlockSize; + // stride should be the max of 8KB and logical block size + if (v->logical_blk_size != 0 && v->logical_blk_size < 8192) { + raid_stride = 8192 / kBlockSize; + } + if (v->erase_blk_size != 0 && v->logical_blk_size != 0) { + mke2fs_args.push_back("-E"); + mke2fs_args.push_back( + android::base::StringPrintf("stride=%d,stripe-width=%d", raid_stride, raid_stripe_width)); + } + mke2fs_args.push_back(v->blk_device); + if (length != 0) { + mke2fs_args.push_back(std::to_string(length / kBlockSize)); + } + + int result = exec_cmd(mke2fs_args); + if (result == 0 && !directory.empty()) { + std::vector e2fsdroid_args = { + "/system/bin/e2fsdroid", "-e", "-f", directory, "-a", volume, v->blk_device, + }; + result = exec_cmd(e2fsdroid_args); + } + + if (result != 0) { + PLOG(ERROR) << "format_volume: Failed to make ext4 on " << v->blk_device; + return -1; + } + return 0; + } + + // Has to be f2fs because we checked earlier. + static constexpr int kSectorSize = 4096; + std::vector make_f2fs_cmd = { + "/system/bin/make_f2fs", + "-g", + "android", + v->blk_device, + }; + if (length >= kSectorSize) { + make_f2fs_cmd.push_back(std::to_string(length / kSectorSize)); + } + + if (exec_cmd(make_f2fs_cmd) != 0) { + PLOG(ERROR) << "format_volume: Failed to make_f2fs on " << v->blk_device; + return -1; + } + if (!directory.empty()) { + std::vector sload_f2fs_cmd = { + "/system/bin/sload_f2fs", "-f", directory, "-t", volume, v->blk_device, + }; + if (exec_cmd(sload_f2fs_cmd) != 0) { + PLOG(ERROR) << "format_volume: Failed to sload_f2fs on " << v->blk_device; + return -1; + } + } + return 0; +} + +int format_volume(const std::string& volume) { + return format_volume(volume, ""); +} + +int setup_install_mounts() { + if (fstab.empty()) { + LOG(ERROR) << "can't set up install mounts: no fstab loaded"; + return -1; + } + for (const FstabEntry& entry : fstab) { + // We don't want to do anything with "/". + if (entry.mount_point == "/") { + continue; + } + + if (entry.mount_point == "/tmp" || entry.mount_point == "/cache") { + if (ensure_path_mounted(entry.mount_point) != 0) { + LOG(ERROR) << "Failed to mount " << entry.mount_point; + return -1; + } + } else { + if (ensure_path_unmounted(entry.mount_point) != 0) { + LOG(ERROR) << "Failed to unmount " << entry.mount_point; + return -1; + } + } + } + return 0; +} + +bool logical_partitions_mapped() { + return android::fs_mgr::LogicalPartitionsMapped(); +} + +std::string get_system_root() { + return android::fs_mgr::GetSystemRoot(); +} diff --git a/package.cpp b/package.cpp deleted file mode 100644 index 6c7289f3f..000000000 --- a/package.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (C) 2019 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "package.h" - -#include -#include - -#include -#include -#include -#include - -#include "otautil/error_code.h" -#include "otautil/sysutil.h" - -// This class wraps the package in memory, i.e. a memory mapped package, or a package loaded -// to a string/vector. -class MemoryPackage : public Package { - public: - // Constructs the class from a file. We will memory maps the file later. - MemoryPackage(const std::string& path, std::unique_ptr map, - const std::function& set_progress); - - // Constructs the class from the package bytes in |content|. - MemoryPackage(std::vector content, const std::function& set_progress); - - ~MemoryPackage() override; - - // Memory maps the package file if necessary. Initializes the start address and size of the - // package. - uint64_t GetPackageSize() const override { - return package_size_; - } - - bool ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) override; - - ZipArchiveHandle GetZipArchiveHandle() override; - - bool UpdateHashAtOffset(const std::vector& hashers, uint64_t start, - uint64_t length) override; - - private: - const uint8_t* addr_; // Start address of the package in memory. - uint64_t package_size_; // Package size in bytes. - - // The memory mapped package. - std::unique_ptr map_; - // A copy of the package content, valid only if we create the class with the exact bytes of - // the package. - std::vector package_content_; - // The physical path to the package, empty if we create the class with the package content. - std::string path_; - - // The ZipArchiveHandle of the package. - ZipArchiveHandle zip_handle_; -}; - -void Package::SetProgress(float progress) { - if (set_progress_) { - set_progress_(progress); - } -} - -class FilePackage : public Package { - public: - FilePackage(android::base::unique_fd&& fd, uint64_t file_size, const std::string& path, - const std::function& set_progress); - - ~FilePackage() override; - - uint64_t GetPackageSize() const override { - return package_size_; - } - - bool ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) override; - - ZipArchiveHandle GetZipArchiveHandle() override; - - bool UpdateHashAtOffset(const std::vector& hashers, uint64_t start, - uint64_t length) override; - - private: - android::base::unique_fd fd_; // The underlying fd to the open package. - uint64_t package_size_; - std::string path_; // The physical path to the package. - - ZipArchiveHandle zip_handle_; -}; - -std::unique_ptr Package::CreateMemoryPackage( - const std::string& path, const std::function& set_progress) { - std::unique_ptr mmap = std::make_unique(); - if (!mmap->MapFile(path)) { - LOG(ERROR) << "failed to map file"; - return nullptr; - } - - return std::make_unique(path, std::move(mmap), set_progress); -} - -std::unique_ptr Package::CreateFilePackage( - const std::string& path, const std::function& set_progress) { - android::base::unique_fd fd(open(path.c_str(), O_RDONLY)); - if (fd == -1) { - PLOG(ERROR) << "Failed to open " << path; - return nullptr; - } - - off64_t file_size = lseek64(fd.get(), 0, SEEK_END); - if (file_size == -1) { - PLOG(ERROR) << "Failed to get the package size"; - return nullptr; - } - - return std::make_unique(std::move(fd), file_size, path, set_progress); -} - -std::unique_ptr Package::CreateMemoryPackage( - std::vector content, const std::function& set_progress) { - return std::make_unique(std::move(content), set_progress); -} - -MemoryPackage::MemoryPackage(const std::string& path, std::unique_ptr map, - const std::function& set_progress) - : map_(std::move(map)), path_(path), zip_handle_(nullptr) { - addr_ = map_->addr; - package_size_ = map_->length; - set_progress_ = set_progress; -} - -MemoryPackage::MemoryPackage(std::vector content, - const std::function& set_progress) - : package_content_(std::move(content)), zip_handle_(nullptr) { - CHECK(!package_content_.empty()); - addr_ = package_content_.data(); - package_size_ = package_content_.size(); - set_progress_ = set_progress; -} - -MemoryPackage::~MemoryPackage() { - if (zip_handle_) { - CloseArchive(zip_handle_); - } -} - -bool MemoryPackage::ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) { - if (byte_count > package_size_ || offset > package_size_ - byte_count) { - LOG(ERROR) << "Out of bound read, offset: " << offset << ", size: " << byte_count - << ", total package_size: " << package_size_; - return false; - } - memcpy(buffer, addr_ + offset, byte_count); - return true; -} - -bool MemoryPackage::UpdateHashAtOffset(const std::vector& hashers, - uint64_t start, uint64_t length) { - if (length > package_size_ || start > package_size_ - length) { - LOG(ERROR) << "Out of bound read, offset: " << start << ", size: " << length - << ", total package_size: " << package_size_; - return false; - } - - for (const auto& hasher : hashers) { - hasher(addr_ + start, length); - } - return true; -} - -ZipArchiveHandle MemoryPackage::GetZipArchiveHandle() { - if (zip_handle_) { - return zip_handle_; - } - - if (auto err = OpenArchiveFromMemory(const_cast(addr_), package_size_, path_.c_str(), - &zip_handle_); - err != 0) { - LOG(ERROR) << "Can't open package" << path_ << " : " << ErrorCodeString(err); - return nullptr; - } - - return zip_handle_; -} - -FilePackage::FilePackage(android::base::unique_fd&& fd, uint64_t file_size, const std::string& path, - const std::function& set_progress) - : fd_(std::move(fd)), package_size_(file_size), path_(path), zip_handle_(nullptr) { - set_progress_ = set_progress; -} - -FilePackage::~FilePackage() { - if (zip_handle_) { - CloseArchive(zip_handle_); - } -} - -bool FilePackage::ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) { - if (byte_count > package_size_ || offset > package_size_ - byte_count) { - LOG(ERROR) << "Out of bound read, offset: " << offset << ", size: " << byte_count - << ", total package_size: " << package_size_; - return false; - } - - if (!android::base::ReadFullyAtOffset(fd_.get(), buffer, byte_count, offset)) { - PLOG(ERROR) << "Failed to read " << byte_count << " bytes data at offset " << offset; - return false; - } - - return true; -} - -bool FilePackage::UpdateHashAtOffset(const std::vector& hashers, - uint64_t start, uint64_t length) { - if (length > package_size_ || start > package_size_ - length) { - LOG(ERROR) << "Out of bound read, offset: " << start << ", size: " << length - << ", total package_size: " << package_size_; - return false; - } - - uint64_t so_far = 0; - while (so_far < length) { - uint64_t read_size = std::min(length - so_far, 16 * MiB); - std::vector buffer(read_size); - if (!ReadFullyAtOffset(buffer.data(), read_size, start + so_far)) { - return false; - } - - for (const auto& hasher : hashers) { - hasher(buffer.data(), read_size); - } - so_far += read_size; - } - - return true; -} - -ZipArchiveHandle FilePackage::GetZipArchiveHandle() { - if (zip_handle_) { - return zip_handle_; - } - - if (auto err = OpenArchiveFd(fd_.get(), path_.c_str(), &zip_handle_); err != 0) { - LOG(ERROR) << "Can't open package" << path_ << " : " << ErrorCodeString(err); - return nullptr; - } - - return zip_handle_; -} diff --git a/package.h b/package.h deleted file mode 100644 index cd44d10be..000000000 --- a/package.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2019 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#include -#include -#include -#include -#include - -#include - -#include "verifier.h" - -// This class serves as a wrapper for an OTA update package. It aims to provide the common -// interface for both packages loaded in memory and packages read from fd. -class Package : public VerifierInterface { - public: - static std::unique_ptr CreateMemoryPackage( - const std::string& path, const std::function& set_progress); - static std::unique_ptr CreateMemoryPackage( - std::vector content, const std::function& set_progress); - static std::unique_ptr CreateFilePackage(const std::string& path, - const std::function& set_progress); - - virtual ~Package() = default; - - // Opens the package as a zip file and returns the ZipArchiveHandle. - virtual ZipArchiveHandle GetZipArchiveHandle() = 0; - - // Updates the progress in fraction during package verification. - void SetProgress(float progress) override; - - protected: - // An optional function to update the progress. - std::function set_progress_; -}; diff --git a/private/install.h b/private/install.h deleted file mode 100644 index 7fdc741d6..000000000 --- a/private/install.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Private headers exposed for testing purpose only. - -#pragma once - -#include -#include - -#include - -// Sets up the commands for a non-A/B update. Extracts the updater binary from the open zip archive -// |zip| located at |package|. Stores the command line that should be called into |cmd|. The -// |status_fd| is the file descriptor the child process should use to report back the progress of -// the update. -int SetUpNonAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int retry_count, - int status_fd, std::vector* cmd); - -// Sets up the commands for an A/B update. Extracts the needed entries from the open zip archive -// |zip| located at |package|. Stores the command line that should be called into |cmd|. The -// |status_fd| is the file descriptor the child process should use to report back the progress of -// the update. Note that since this applies to the sideloading flow only, it takes one less -// parameter |retry_count| than the non-A/B version. -int SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd, - std::vector* cmd); diff --git a/recovery.cpp b/recovery.cpp index d9c1f22f5..421bc12f2 100644 --- a/recovery.cpp +++ b/recovery.cpp @@ -50,20 +50,20 @@ #include #include -#include "adb_install.h" #include "common.h" #include "fsck_unshare_blocks.h" -#include "fuse_sdcard_install.h" -#include "install.h" +#include "install/adb_install.h" +#include "install/fuse_sdcard_install.h" +#include "install/install.h" +#include "install/package.h" #include "logging.h" #include "otautil/dirutil.h" #include "otautil/error_code.h" #include "otautil/paths.h" +#include "otautil/roots.h" #include "otautil/sysutil.h" -#include "package.h" #include "recovery_ui/screen_ui.h" #include "recovery_ui/ui.h" -#include "roots.h" static constexpr const char* CACHE_LOG_DIR = "/cache/recovery"; static constexpr const char* COMMAND_FILE = "/cache/recovery/command"; @@ -79,7 +79,7 @@ static constexpr const char* METADATA_ROOT = "/metadata"; // into target_files.zip. Assert the version defined in code and in Android.mk are consistent. static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions."); -bool modified_flash = false; +static bool modified_flash = false; std::string stage; const char* reason = nullptr; @@ -439,7 +439,7 @@ static std::unique_ptr ReadWipePackage(size_t wipe_package_size) { // 1. verify the package. // 2. check metadata (ota-type, pre-device and serial number if having one). static bool CheckWipePackage(Package* wipe_package) { - if (!verify_package(wipe_package)) { + if (!verify_package(wipe_package, ui)) { LOG(ERROR) << "Failed to verify package"; return false; } @@ -693,7 +693,7 @@ static Device::BuiltinAction prompt_and_wait(Device* device, int status) { modified_flash = true; bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD); if (adb) { - status = apply_from_adb(&should_wipe_cache); + status = apply_from_adb(&should_wipe_cache, ui); } else { status = ApplyFromSdcard(device, &should_wipe_cache, ui); } @@ -1030,7 +1030,8 @@ Device::BuiltinAction start_recovery(Device* device, const std::vectorShowText(true); } - status = apply_from_adb(&should_wipe_cache); + status = apply_from_adb(&should_wipe_cache, ui); if (status == INSTALL_SUCCESS && should_wipe_cache) { if (!wipe_cache(false, device)) { status = INSTALL_ERROR; diff --git a/recovery_main.cpp b/recovery_main.cpp index 2f5a1845b..56ebe16fa 100644 --- a/recovery_main.cpp +++ b/recovery_main.cpp @@ -53,12 +53,12 @@ #include "logging.h" #include "minadbd/minadbd.h" #include "otautil/paths.h" +#include "otautil/roots.h" #include "otautil/sysutil.h" #include "recovery.h" #include "recovery_ui/device.h" #include "recovery_ui/stub_ui.h" #include "recovery_ui/ui.h" -#include "roots.h" static constexpr const char* COMMAND_FILE = "/cache/recovery/command"; static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale"; diff --git a/roots.cpp b/roots.cpp deleted file mode 100644 index c42723f0c..000000000 --- a/roots.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "roots.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "otautil/mounts.h" -#include "otautil/sysutil.h" - -using android::fs_mgr::Fstab; -using android::fs_mgr::FstabEntry; -using android::fs_mgr::ReadDefaultFstab; - -static Fstab fstab; - -void load_volume_table() { - if (!ReadDefaultFstab(&fstab)) { - LOG(ERROR) << "Failed to read default fstab"; - return; - } - - fstab.emplace_back(FstabEntry{ - .mount_point = "/tmp", .fs_type = "ramdisk", .blk_device = "ramdisk", .length = 0 }); - - std::cout << "recovery filesystem table" << std::endl << "=========================" << std::endl; - for (size_t i = 0; i < fstab.size(); ++i) { - const auto& entry = fstab[i]; - std::cout << " " << i << " " << entry.mount_point << " " - << " " << entry.fs_type << " " << entry.blk_device << " " << entry.length - << std::endl; - } - std::cout << std::endl; -} - -Volume* volume_for_mount_point(const std::string& mount_point) { - return android::fs_mgr::GetEntryForMountPoint(&fstab, mount_point); -} - -// Mount the volume specified by path at the given mount_point. -int ensure_path_mounted_at(const std::string& path, const std::string& mount_point) { - return android::fs_mgr::EnsurePathMounted(&fstab, path, mount_point) ? 0 : -1; -} - -int ensure_path_mounted(const std::string& path) { - // Mount at the default mount point. - return android::fs_mgr::EnsurePathMounted(&fstab, path) ? 0 : -1; -} - -int ensure_path_unmounted(const std::string& path) { - return android::fs_mgr::EnsurePathUnmounted(&fstab, path) ? 0 : -1; -} - -static int exec_cmd(const std::vector& args) { - CHECK(!args.empty()); - auto argv = StringVectorToNullTerminatedArray(args); - - pid_t child; - if ((child = fork()) == 0) { - execv(argv[0], argv.data()); - _exit(EXIT_FAILURE); - } - - int status; - waitpid(child, &status, 0); - if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { - LOG(ERROR) << args[0] << " failed with status " << WEXITSTATUS(status); - } - return WEXITSTATUS(status); -} - -static int64_t get_file_size(int fd, uint64_t reserve_len) { - struct stat buf; - int ret = fstat(fd, &buf); - if (ret) return 0; - - int64_t computed_size; - if (S_ISREG(buf.st_mode)) { - computed_size = buf.st_size - reserve_len; - } else if (S_ISBLK(buf.st_mode)) { - uint64_t block_device_size = get_block_device_size(fd); - if (block_device_size < reserve_len || - block_device_size > std::numeric_limits::max()) { - computed_size = 0; - } else { - computed_size = block_device_size - reserve_len; - } - } else { - computed_size = 0; - } - - return computed_size; -} - -int format_volume(const std::string& volume, const std::string& directory) { - const FstabEntry* v = android::fs_mgr::GetEntryForPath(&fstab, volume); - if (v == nullptr) { - LOG(ERROR) << "unknown volume \"" << volume << "\""; - return -1; - } - if (v->fs_type == "ramdisk") { - LOG(ERROR) << "can't format_volume \"" << volume << "\""; - return -1; - } - if (v->mount_point != volume) { - LOG(ERROR) << "can't give path \"" << volume << "\" to format_volume"; - return -1; - } - if (ensure_path_unmounted(volume) != 0) { - LOG(ERROR) << "format_volume: Failed to unmount \"" << v->mount_point << "\""; - return -1; - } - if (v->fs_type != "ext4" && v->fs_type != "f2fs") { - LOG(ERROR) << "format_volume: fs_type \"" << v->fs_type << "\" unsupported"; - return -1; - } - - // If there's a key_loc that looks like a path, it should be a block device for storing encryption - // metadata. Wipe it too. - if (!v->key_loc.empty() && v->key_loc[0] == '/') { - LOG(INFO) << "Wiping " << v->key_loc; - int fd = open(v->key_loc.c_str(), O_WRONLY | O_CREAT, 0644); - if (fd == -1) { - PLOG(ERROR) << "format_volume: Failed to open " << v->key_loc; - return -1; - } - wipe_block_device(fd, get_file_size(fd)); - close(fd); - } - - int64_t length = 0; - if (v->length > 0) { - length = v->length; - } else if (v->length < 0 || v->key_loc == "footer") { - android::base::unique_fd fd(open(v->blk_device.c_str(), O_RDONLY)); - if (fd == -1) { - PLOG(ERROR) << "format_volume: failed to open " << v->blk_device; - return -1; - } - length = - get_file_size(fd.get(), v->length ? -v->length : CRYPT_FOOTER_OFFSET); - if (length <= 0) { - LOG(ERROR) << "get_file_size: invalid size " << length << " for " - << v->blk_device; - return -1; - } - } - - if (v->fs_type == "ext4") { - static constexpr int kBlockSize = 4096; - std::vector mke2fs_args = { - "/system/bin/mke2fs", "-F", "-t", "ext4", "-b", std::to_string(kBlockSize), - }; - - int raid_stride = v->logical_blk_size / kBlockSize; - int raid_stripe_width = v->erase_blk_size / kBlockSize; - // stride should be the max of 8KB and logical block size - if (v->logical_blk_size != 0 && v->logical_blk_size < 8192) { - raid_stride = 8192 / kBlockSize; - } - if (v->erase_blk_size != 0 && v->logical_blk_size != 0) { - mke2fs_args.push_back("-E"); - mke2fs_args.push_back( - android::base::StringPrintf("stride=%d,stripe-width=%d", raid_stride, raid_stripe_width)); - } - mke2fs_args.push_back(v->blk_device); - if (length != 0) { - mke2fs_args.push_back(std::to_string(length / kBlockSize)); - } - - int result = exec_cmd(mke2fs_args); - if (result == 0 && !directory.empty()) { - std::vector e2fsdroid_args = { - "/system/bin/e2fsdroid", "-e", "-f", directory, "-a", volume, v->blk_device, - }; - result = exec_cmd(e2fsdroid_args); - } - - if (result != 0) { - PLOG(ERROR) << "format_volume: Failed to make ext4 on " << v->blk_device; - return -1; - } - return 0; - } - - // Has to be f2fs because we checked earlier. - static constexpr int kSectorSize = 4096; - std::vector make_f2fs_cmd = { - "/system/bin/make_f2fs", - "-g", - "android", - v->blk_device, - }; - if (length >= kSectorSize) { - make_f2fs_cmd.push_back(std::to_string(length / kSectorSize)); - } - - if (exec_cmd(make_f2fs_cmd) != 0) { - PLOG(ERROR) << "format_volume: Failed to make_f2fs on " << v->blk_device; - return -1; - } - if (!directory.empty()) { - std::vector sload_f2fs_cmd = { - "/system/bin/sload_f2fs", "-f", directory, "-t", volume, v->blk_device, - }; - if (exec_cmd(sload_f2fs_cmd) != 0) { - PLOG(ERROR) << "format_volume: Failed to sload_f2fs on " << v->blk_device; - return -1; - } - } - return 0; -} - -int format_volume(const std::string& volume) { - return format_volume(volume, ""); -} - -int setup_install_mounts() { - if (fstab.empty()) { - LOG(ERROR) << "can't set up install mounts: no fstab loaded"; - return -1; - } - for (const FstabEntry& entry : fstab) { - // We don't want to do anything with "/". - if (entry.mount_point == "/") { - continue; - } - - if (entry.mount_point == "/tmp" || entry.mount_point == "/cache") { - if (ensure_path_mounted(entry.mount_point) != 0) { - LOG(ERROR) << "Failed to mount " << entry.mount_point; - return -1; - } - } else { - if (ensure_path_unmounted(entry.mount_point) != 0) { - LOG(ERROR) << "Failed to unmount " << entry.mount_point; - return -1; - } - } - } - return 0; -} - -bool logical_partitions_mapped() { - return android::fs_mgr::LogicalPartitionsMapped(); -} - -std::string get_system_root() { - return android::fs_mgr::GetSystemRoot(); -} diff --git a/roots.h b/roots.h deleted file mode 100644 index 7b031a188..000000000 --- a/roots.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef RECOVERY_ROOTS_H_ -#define RECOVERY_ROOTS_H_ - -#include - -#include - -using Volume = android::fs_mgr::FstabEntry; - -// Load and parse volume data from /etc/recovery.fstab. -void load_volume_table(); - -// Return the Volume* record for this mount point (or nullptr). -Volume* volume_for_mount_point(const std::string& mount_point); - -// Make sure that the volume 'path' is on is mounted. Returns 0 on -// success (volume is mounted). -int ensure_path_mounted(const std::string& path); - -// Similar to ensure_path_mounted, but allows one to specify the mount_point. -int ensure_path_mounted_at(const std::string& path, const std::string& mount_point); - -// Make sure that the volume 'path' is on is unmounted. Returns 0 on -// success (volume is unmounted); -int ensure_path_unmounted(const std::string& path); - -// Reformat the given volume (must be the mount point only, eg -// "/cache"), no paths permitted. Attempts to unmount the volume if -// it is mounted. -int format_volume(const std::string& volume); - -// Reformat the given volume (must be the mount point only, eg -// "/cache"), no paths permitted. Attempts to unmount the volume if -// it is mounted. -// Copies 'directory' to root of the newly formatted volume -int format_volume(const std::string& volume, const std::string& directory); - -// Ensure that all and only the volumes that packages expect to find -// mounted (/tmp and /cache) are mounted. Returns 0 on success. -int setup_install_mounts(); - -bool logical_partitions_mapped(); - -std::string get_system_root(); - -#endif // RECOVERY_ROOTS_H_ diff --git a/tests/Android.bp b/tests/Android.bp index ef5919eb5..09ef716d6 100644 --- a/tests/Android.bp +++ b/tests/Android.bp @@ -76,9 +76,9 @@ libapplypatch_static_libs = [ librecovery_static_libs = [ "librecovery", "librecovery_fastboot", + "libinstall", + "librecovery_ui", "libminui", - "libpackage", - "libverifier", "libotautil", "libhealthhalutils", @@ -116,10 +116,9 @@ cc_test { ], static_libs: libapplypatch_static_libs + [ + "libinstall", "librecovery_ui", "libminui", - "libpackage", - "libverifier", "libotautil", "libupdater", "libgtest_prod", diff --git a/tests/component/install_test.cpp b/tests/component/install_test.cpp index 969805b42..385132939 100644 --- a/tests/component/install_test.cpp +++ b/tests/component/install_test.cpp @@ -32,9 +32,9 @@ #include #include -#include "install.h" +#include "install/install.h" #include "otautil/paths.h" -#include "private/install.h" +#include "private/setup_commands.h" static void BuildZipArchive(const std::map& file_map, int fd, int compression_type) { diff --git a/tests/component/verifier_test.cpp b/tests/component/verifier_test.cpp index bdb8af231..ded23c52f 100644 --- a/tests/component/verifier_test.cpp +++ b/tests/component/verifier_test.cpp @@ -35,9 +35,9 @@ #include #include "common/test_constants.h" +#include "install/package.h" +#include "install/verifier.h" #include "otautil/sysutil.h" -#include "package.h" -#include "verifier.h" using namespace std::string_literals; diff --git a/tests/unit/asn1_decoder_test.cpp b/tests/unit/asn1_decoder_test.cpp index b334a655b..d94dd4353 100644 --- a/tests/unit/asn1_decoder_test.cpp +++ b/tests/unit/asn1_decoder_test.cpp @@ -20,7 +20,7 @@ #include -#include "asn1_decoder.h" +#include "private/asn1_decoder.h" TEST(Asn1DecoderTest, Empty_Failure) { uint8_t empty[] = {}; diff --git a/tests/unit/package_test.cpp b/tests/unit/package_test.cpp index fa492d38b..a735a699e 100644 --- a/tests/unit/package_test.cpp +++ b/tests/unit/package_test.cpp @@ -26,7 +26,7 @@ #include #include "common/test_constants.h" -#include "package.h" +#include "install/package.h" class PackageTest : public ::testing::Test { protected: diff --git a/verifier.cpp b/verifier.cpp deleted file mode 100644 index 08d852b37..000000000 --- a/verifier.cpp +++ /dev/null @@ -1,469 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "verifier.h" - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "asn1_decoder.h" -#include "otautil/print_sha1.h" - -/* - * Simple version of PKCS#7 SignedData extraction. This extracts the - * signature OCTET STRING to be used for signature verification. - * - * For full details, see http://www.ietf.org/rfc/rfc3852.txt - * - * The PKCS#7 structure looks like: - * - * SEQUENCE (ContentInfo) - * OID (ContentType) - * [0] (content) - * SEQUENCE (SignedData) - * INTEGER (version CMSVersion) - * SET (DigestAlgorithmIdentifiers) - * SEQUENCE (EncapsulatedContentInfo) - * [0] (CertificateSet OPTIONAL) - * [1] (RevocationInfoChoices OPTIONAL) - * SET (SignerInfos) - * SEQUENCE (SignerInfo) - * INTEGER (CMSVersion) - * SEQUENCE (SignerIdentifier) - * SEQUENCE (DigestAlgorithmIdentifier) - * SEQUENCE (SignatureAlgorithmIdentifier) - * OCTET STRING (SignatureValue) - */ -static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len, - std::vector* sig_der) { - CHECK(sig_der != nullptr); - sig_der->clear(); - - asn1_context ctx(pkcs7_der, pkcs7_der_len); - - std::unique_ptr pkcs7_seq(ctx.asn1_sequence_get()); - if (pkcs7_seq == nullptr || !pkcs7_seq->asn1_sequence_next()) { - return false; - } - - std::unique_ptr signed_data_app(pkcs7_seq->asn1_constructed_get()); - if (signed_data_app == nullptr) { - return false; - } - - std::unique_ptr signed_data_seq(signed_data_app->asn1_sequence_get()); - if (signed_data_seq == nullptr || - !signed_data_seq->asn1_sequence_next() || - !signed_data_seq->asn1_sequence_next() || - !signed_data_seq->asn1_sequence_next() || - !signed_data_seq->asn1_constructed_skip_all()) { - return false; - } - - std::unique_ptr sig_set(signed_data_seq->asn1_set_get()); - if (sig_set == nullptr) { - return false; - } - - std::unique_ptr sig_seq(sig_set->asn1_sequence_get()); - if (sig_seq == nullptr || - !sig_seq->asn1_sequence_next() || - !sig_seq->asn1_sequence_next() || - !sig_seq->asn1_sequence_next() || - !sig_seq->asn1_sequence_next()) { - return false; - } - - const uint8_t* sig_der_ptr; - size_t sig_der_length; - if (!sig_seq->asn1_octet_string_get(&sig_der_ptr, &sig_der_length)) { - return false; - } - - sig_der->resize(sig_der_length); - std::copy(sig_der_ptr, sig_der_ptr + sig_der_length, sig_der->begin()); - return true; -} - -int verify_file(VerifierInterface* package, const std::vector& keys) { - CHECK(package); - package->SetProgress(0.0); - - // An archive with a whole-file signature will end in six bytes: - // - // (2-byte signature start) $ff $ff (2-byte comment size) - // - // (As far as the ZIP format is concerned, these are part of the archive comment.) We start by - // reading this footer, this tells us how far back from the end we have to start reading to find - // the whole comment. - -#define FOOTER_SIZE 6 - uint64_t length = package->GetPackageSize(); - - if (length < FOOTER_SIZE) { - LOG(ERROR) << "not big enough to contain footer"; - return VERIFY_FAILURE; - } - - uint8_t footer[FOOTER_SIZE]; - if (!package->ReadFullyAtOffset(footer, FOOTER_SIZE, length - FOOTER_SIZE)) { - LOG(ERROR) << "Failed to read footer"; - return VERIFY_FAILURE; - } - - if (footer[2] != 0xff || footer[3] != 0xff) { - LOG(ERROR) << "footer is wrong"; - return VERIFY_FAILURE; - } - - size_t comment_size = footer[4] + (footer[5] << 8); - size_t signature_start = footer[0] + (footer[1] << 8); - LOG(INFO) << "comment is " << comment_size << " bytes; signature is " << signature_start - << " bytes from end"; - - if (signature_start > comment_size) { - LOG(ERROR) << "signature start: " << signature_start << " is larger than comment size: " - << comment_size; - return VERIFY_FAILURE; - } - - if (signature_start <= FOOTER_SIZE) { - LOG(ERROR) << "Signature start is in the footer"; - return VERIFY_FAILURE; - } - -#define EOCD_HEADER_SIZE 22 - - // The end-of-central-directory record is 22 bytes plus any comment length. - size_t eocd_size = comment_size + EOCD_HEADER_SIZE; - - if (length < eocd_size) { - LOG(ERROR) << "not big enough to contain EOCD"; - return VERIFY_FAILURE; - } - - // Determine how much of the file is covered by the signature. This is everything except the - // signature data and length, which includes all of the EOCD except for the comment length field - // (2 bytes) and the comment data. - uint64_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2; - - uint8_t eocd[eocd_size]; - if (!package->ReadFullyAtOffset(eocd, eocd_size, length - eocd_size)) { - LOG(ERROR) << "Failed to read EOCD of " << eocd_size << " bytes"; - return VERIFY_FAILURE; - } - - // If this is really is the EOCD record, it will begin with the magic number $50 $4b $05 $06. - if (eocd[0] != 0x50 || eocd[1] != 0x4b || eocd[2] != 0x05 || eocd[3] != 0x06) { - LOG(ERROR) << "signature length doesn't match EOCD marker"; - return VERIFY_FAILURE; - } - - for (size_t i = 4; i < eocd_size-3; ++i) { - if (eocd[i] == 0x50 && eocd[i+1] == 0x4b && eocd[i+2] == 0x05 && eocd[i+3] == 0x06) { - // If the sequence $50 $4b $05 $06 appears anywhere after the real one, libziparchive will - // find the later (wrong) one, which could be exploitable. Fail the verification if this - // sequence occurs anywhere after the real one. - LOG(ERROR) << "EOCD marker occurs after start of EOCD"; - return VERIFY_FAILURE; - } - } - - bool need_sha1 = false; - bool need_sha256 = false; - for (const auto& key : keys) { - switch (key.hash_len) { - case SHA_DIGEST_LENGTH: need_sha1 = true; break; - case SHA256_DIGEST_LENGTH: need_sha256 = true; break; - } - } - - SHA_CTX sha1_ctx; - SHA256_CTX sha256_ctx; - SHA1_Init(&sha1_ctx); - SHA256_Init(&sha256_ctx); - - std::vector hashers; - if (need_sha1) { - hashers.emplace_back( - std::bind(&SHA1_Update, &sha1_ctx, std::placeholders::_1, std::placeholders::_2)); - } - if (need_sha256) { - hashers.emplace_back( - std::bind(&SHA256_Update, &sha256_ctx, std::placeholders::_1, std::placeholders::_2)); - } - - double frac = -1.0; - uint64_t so_far = 0; - while (so_far < signed_len) { - // On a Nexus 5X, experiment showed 16MiB beat 1MiB by 6% faster for a 1196MiB full OTA and - // 60% for an 89MiB incremental OTA. http://b/28135231. - uint64_t read_size = std::min(signed_len - so_far, 16 * MiB); - package->UpdateHashAtOffset(hashers, so_far, read_size); - so_far += read_size; - - double f = so_far / static_cast(signed_len); - if (f > frac + 0.02 || read_size == so_far) { - package->SetProgress(f); - frac = f; - } - } - - uint8_t sha1[SHA_DIGEST_LENGTH]; - SHA1_Final(sha1, &sha1_ctx); - uint8_t sha256[SHA256_DIGEST_LENGTH]; - SHA256_Final(sha256, &sha256_ctx); - - const uint8_t* signature = eocd + eocd_size - signature_start; - size_t signature_size = signature_start - FOOTER_SIZE; - - LOG(INFO) << "signature (offset: " << std::hex << (length - signature_start) << ", length: " - << signature_size << "): " << print_hex(signature, signature_size); - - std::vector sig_der; - if (!read_pkcs7(signature, signature_size, &sig_der)) { - LOG(ERROR) << "Could not find signature DER block"; - return VERIFY_FAILURE; - } - - // Check to make sure at least one of the keys matches the signature. Since any key can match, - // we need to try each before determining a verification failure has happened. - size_t i = 0; - for (const auto& key : keys) { - const uint8_t* hash; - int hash_nid; - switch (key.hash_len) { - case SHA_DIGEST_LENGTH: - hash = sha1; - hash_nid = NID_sha1; - break; - case SHA256_DIGEST_LENGTH: - hash = sha256; - hash_nid = NID_sha256; - break; - default: - continue; - } - - // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that the signing tool appends - // after the signature itself. - if (key.key_type == Certificate::KEY_TYPE_RSA) { - if (!RSA_verify(hash_nid, hash, key.hash_len, sig_der.data(), sig_der.size(), - key.rsa.get())) { - LOG(INFO) << "failed to verify against RSA key " << i; - continue; - } - - LOG(INFO) << "whole-file signature verified against RSA key " << i; - return VERIFY_SUCCESS; - } else if (key.key_type == Certificate::KEY_TYPE_EC && key.hash_len == SHA256_DIGEST_LENGTH) { - if (!ECDSA_verify(0, hash, key.hash_len, sig_der.data(), sig_der.size(), key.ec.get())) { - LOG(INFO) << "failed to verify against EC key " << i; - continue; - } - - LOG(INFO) << "whole-file signature verified against EC key " << i; - return VERIFY_SUCCESS; - } else { - LOG(INFO) << "Unknown key type " << key.key_type; - } - i++; - } - - if (need_sha1) { - LOG(INFO) << "SHA-1 digest: " << print_hex(sha1, SHA_DIGEST_LENGTH); - } - if (need_sha256) { - LOG(INFO) << "SHA-256 digest: " << print_hex(sha256, SHA256_DIGEST_LENGTH); - } - LOG(ERROR) << "failed to verify whole-file signature"; - return VERIFY_FAILURE; -} - -static std::vector IterateZipEntriesAndSearchForKeys(const ZipArchiveHandle& handle) { - void* cookie; - ZipString suffix("x509.pem"); - int32_t iter_status = StartIteration(handle, &cookie, nullptr, &suffix); - if (iter_status != 0) { - LOG(ERROR) << "Failed to iterate over entries in the certificate zipfile: " - << ErrorCodeString(iter_status); - return {}; - } - - std::vector result; - - ZipString name; - ZipEntry entry; - while ((iter_status = Next(cookie, &entry, &name)) == 0) { - std::vector pem_content(entry.uncompressed_length); - if (int32_t extract_status = - ExtractToMemory(handle, &entry, pem_content.data(), pem_content.size()); - extract_status != 0) { - LOG(ERROR) << "Failed to extract " << std::string(name.name, name.name + name.name_length); - return {}; - } - - Certificate cert(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr); - // Aborts the parsing if we fail to load one of the key file. - if (!LoadCertificateFromBuffer(pem_content, &cert)) { - LOG(ERROR) << "Failed to load keys from " - << std::string(name.name, name.name + name.name_length); - return {}; - } - - result.emplace_back(std::move(cert)); - } - - if (iter_status != -1) { - LOG(ERROR) << "Error while iterating over zip entries: " << ErrorCodeString(iter_status); - return {}; - } - - return result; -} - -std::vector LoadKeysFromZipfile(const std::string& zip_name) { - ZipArchiveHandle handle; - if (int32_t open_status = OpenArchive(zip_name.c_str(), &handle); open_status != 0) { - LOG(ERROR) << "Failed to open " << zip_name << ": " << ErrorCodeString(open_status); - return {}; - } - - std::vector result = IterateZipEntriesAndSearchForKeys(handle); - CloseArchive(handle); - return result; -} - -bool CheckRSAKey(const std::unique_ptr& rsa) { - if (!rsa) { - return false; - } - - const BIGNUM* out_n; - const BIGNUM* out_e; - RSA_get0_key(rsa.get(), &out_n, &out_e, nullptr /* private exponent */); - auto modulus_bits = BN_num_bits(out_n); - if (modulus_bits != 2048 && modulus_bits != 4096) { - LOG(ERROR) << "Modulus should be 2048 or 4096 bits long, actual: " << modulus_bits; - return false; - } - - BN_ULONG exponent = BN_get_word(out_e); - if (exponent != 3 && exponent != 65537) { - LOG(ERROR) << "Public exponent should be 3 or 65537, actual: " << exponent; - return false; - } - - return true; -} - -bool CheckECKey(const std::unique_ptr& ec_key) { - if (!ec_key) { - return false; - } - - const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key.get()); - if (!ec_group) { - LOG(ERROR) << "Failed to get the ec_group from the ec_key"; - return false; - } - auto degree = EC_GROUP_get_degree(ec_group); - if (degree != 256) { - LOG(ERROR) << "Field size of the ec key should be 256 bits long, actual: " << degree; - return false; - } - - return true; -} - -bool LoadCertificateFromBuffer(const std::vector& pem_content, Certificate* cert) { - std::unique_ptr content( - BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free); - - std::unique_ptr x509( - PEM_read_bio_X509(content.get(), nullptr, nullptr, nullptr), X509_free); - if (!x509) { - LOG(ERROR) << "Failed to read x509 certificate"; - return false; - } - - int nid = X509_get_signature_nid(x509.get()); - switch (nid) { - // SignApk has historically accepted md5WithRSA certificates, but treated them as - // sha1WithRSA anyway. Continue to do so for backwards compatibility. - case NID_md5WithRSA: - case NID_md5WithRSAEncryption: - case NID_sha1WithRSA: - case NID_sha1WithRSAEncryption: - cert->hash_len = SHA_DIGEST_LENGTH; - break; - case NID_sha256WithRSAEncryption: - case NID_ecdsa_with_SHA256: - cert->hash_len = SHA256_DIGEST_LENGTH; - break; - default: - LOG(ERROR) << "Unrecognized signature nid " << OBJ_nid2ln(nid); - return false; - } - - std::unique_ptr public_key(X509_get_pubkey(x509.get()), - EVP_PKEY_free); - if (!public_key) { - LOG(ERROR) << "Failed to extract the public key from x509 certificate"; - return false; - } - - int key_type = EVP_PKEY_id(public_key.get()); - if (key_type == EVP_PKEY_RSA) { - cert->key_type = Certificate::KEY_TYPE_RSA; - cert->ec.reset(); - cert->rsa.reset(EVP_PKEY_get1_RSA(public_key.get())); - if (!cert->rsa || !CheckRSAKey(cert->rsa)) { - LOG(ERROR) << "Failed to validate the rsa key info from public key"; - return false; - } - } else if (key_type == EVP_PKEY_EC) { - cert->key_type = Certificate::KEY_TYPE_EC; - cert->rsa.reset(); - cert->ec.reset(EVP_PKEY_get1_EC_KEY(public_key.get())); - if (!cert->ec || !CheckECKey(cert->ec)) { - LOG(ERROR) << "Failed to validate the ec key info from the public key"; - return false; - } - } else { - LOG(ERROR) << "Unrecognized public key type " << OBJ_nid2ln(key_type); - return false; - } - - return true; -} diff --git a/verifier.h b/verifier.h deleted file mode 100644 index ef9feaff0..000000000 --- a/verifier.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _RECOVERY_VERIFIER_H -#define _RECOVERY_VERIFIER_H - -#include - -#include -#include -#include - -#include -#include -#include - -constexpr size_t MiB = 1024 * 1024; - -using HasherUpdateCallback = std::function; - -struct RSADeleter { - void operator()(RSA* rsa) const { - RSA_free(rsa); - } -}; - -struct ECKEYDeleter { - void operator()(EC_KEY* ec_key) const { - EC_KEY_free(ec_key); - } -}; - -struct Certificate { - typedef enum { - KEY_TYPE_RSA, - KEY_TYPE_EC, - } KeyType; - - Certificate(int hash_len_, - KeyType key_type_, - std::unique_ptr&& rsa_, - std::unique_ptr&& ec_) - : hash_len(hash_len_), - key_type(key_type_), - rsa(std::move(rsa_)), - ec(std::move(ec_)) {} - - // SHA_DIGEST_LENGTH (SHA-1) or SHA256_DIGEST_LENGTH (SHA-256) - int hash_len; - KeyType key_type; - std::unique_ptr rsa; - std::unique_ptr ec; -}; - -class VerifierInterface { - public: - virtual ~VerifierInterface() = default; - - // Returns the package size in bytes. - virtual uint64_t GetPackageSize() const = 0; - - // Reads |byte_count| data starting from |offset|, and puts the result in |buffer|. - virtual bool ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) = 0; - - // Updates the hash contexts for |length| bytes data starting from |start|. - virtual bool UpdateHashAtOffset(const std::vector& hashers, uint64_t start, - uint64_t length) = 0; - - // Updates the progress in fraction during package verification. - virtual void SetProgress(float progress) = 0; -}; - -// Looks for an RSA signature embedded in the .ZIP file comment given the path to the zip. -// Verifies that it matches one of the given public keys. Returns VERIFY_SUCCESS or -// VERIFY_FAILURE (if any error is encountered or no key matches the signature). -int verify_file(VerifierInterface* package, const std::vector& keys); - -// Checks that the RSA key has a modulus of 2048 or 4096 bits long, and public exponent is 3 or -// 65537. -bool CheckRSAKey(const std::unique_ptr& rsa); - -// Checks that the field size of the curve for the EC key is 256 bits. -bool CheckECKey(const std::unique_ptr& ec_key); - -// Parses a PEM-encoded x509 certificate from the given buffer and saves it into |cert|. Returns -// false if there is a parsing failure or the signature's encryption algorithm is not supported. -bool LoadCertificateFromBuffer(const std::vector& pem_content, Certificate* cert); - -// Iterates over the zip entries with the suffix "x509.pem" and returns a list of recognized -// certificates. Returns an empty list if we fail to parse any of the entries. -std::vector LoadKeysFromZipfile(const std::string& zip_name); - -#define VERIFY_SUCCESS 0 -#define VERIFY_FAILURE 1 - -#endif /* _RECOVERY_VERIFIER_H */ -- cgit v1.2.3