summaryrefslogtreecommitdiffstats
path: root/install
diff options
context:
space:
mode:
Diffstat (limited to 'install')
-rw-r--r--install/Android.bp3
-rw-r--r--install/adb_install.cpp9
-rw-r--r--install/asn1_decoder.cpp156
-rw-r--r--install/fuse_install.cpp9
-rw-r--r--install/include/install/fuse_install.h2
-rw-r--r--install/include/install/install.h6
-rw-r--r--install/include/install/package.h62
-rw-r--r--install/include/install/verifier.h101
-rw-r--r--install/include/install/wipe_data.h2
-rw-r--r--install/include/install/wipe_device.h2
-rw-r--r--install/include/private/asn1_decoder.h56
-rw-r--r--install/install.cpp55
-rw-r--r--install/package.cpp278
-rw-r--r--install/verifier.cpp472
-rw-r--r--install/wipe_data.cpp38
-rw-r--r--install/wipe_device.cpp2
16 files changed, 65 insertions, 1188 deletions
diff --git a/install/Android.bp b/install/Android.bp
index e239ddc4e..c59171451 100644
--- a/install/Android.bp
+++ b/install/Android.bp
@@ -105,12 +105,9 @@ cc_library_static {
srcs: [
"adb_install.cpp",
- "asn1_decoder.cpp",
"fuse_install.cpp",
"install.cpp",
- "package.cpp",
"snapshot_utils.cpp",
- "verifier.cpp",
"wipe_data.cpp",
"wipe_device.cpp",
"spl_check.cpp",
diff --git a/install/adb_install.cpp b/install/adb_install.cpp
index ee79a32c0..b12e52944 100644
--- a/install/adb_install.cpp
+++ b/install/adb_install.cpp
@@ -90,11 +90,12 @@ static bool WriteStatusToFd(MinadbdCommandStatus status, int fd) {
// Installs the package from FUSE. Returns the installation result and whether it should continue
// waiting for new commands.
-static auto AdbInstallPackageHandler(RecoveryUI* ui, InstallResult* result) {
+static auto AdbInstallPackageHandler(Device* device, InstallResult* result) {
// How long (in seconds) we wait for the package path to be ready. It doesn't need to be too long
// because the minadbd service has already issued an install command. 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.)
+ auto ui = device->GetUI();
constexpr int ADB_INSTALL_TIMEOUT = 15;
bool should_continue = true;
*result = INSTALL_ERROR;
@@ -114,7 +115,7 @@ static auto AdbInstallPackageHandler(RecoveryUI* ui, InstallResult* result) {
auto package =
Package::CreateFilePackage(FUSE_SIDELOAD_HOST_PATHNAME,
std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
- *result = InstallPackage(package.get(), FUSE_SIDELOAD_HOST_PATHNAME, false, 0, ui);
+ *result = InstallPackage(package.get(), FUSE_SIDELOAD_HOST_PATHNAME, false, 0, device);
break;
}
@@ -348,7 +349,7 @@ InstallResult ApplyFromAdb(Device* device, bool rescue_mode, Device::BuiltinActi
InstallResult install_result = INSTALL_ERROR;
std::map<MinadbdCommand, CommandFunction> command_map{
- { MinadbdCommand::kInstall, std::bind(&AdbInstallPackageHandler, ui, &install_result) },
+ { MinadbdCommand::kInstall, std::bind(&AdbInstallPackageHandler, device, &install_result) },
{ MinadbdCommand::kRebootAndroid, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootAndroid,
&install_result, reboot_action) },
{ MinadbdCommand::kRebootBootloader,
@@ -368,7 +369,7 @@ InstallResult ApplyFromAdb(Device* device, bool rescue_mode, Device::BuiltinActi
"to the device with \"adb sideload <filename>\"...\n");
} else {
command_map.emplace(MinadbdCommand::kWipeData, [&device]() {
- bool result = WipeData(device, false);
+ bool result = WipeData(device);
return std::make_pair(result, true);
});
command_map.emplace(MinadbdCommand::kNoOp, []() { return std::make_pair(true, true); });
diff --git a/install/asn1_decoder.cpp b/install/asn1_decoder.cpp
deleted file mode 100644
index 2d81a6e13..000000000
--- a/install/asn1_decoder.cpp
+++ /dev/null
@@ -1,156 +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 "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<size_t>(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_install.cpp b/install/fuse_install.cpp
index 143b5d3fb..197e1debb 100644
--- a/install/fuse_install.cpp
+++ b/install/fuse_install.cpp
@@ -146,10 +146,11 @@ static bool StartInstallPackageFuse(std::string_view path) {
return run_fuse_sideload(std::move(fuse_data_provider)) == 0;
}
-InstallResult InstallWithFuseFromPath(std::string_view path, RecoveryUI* ui) {
+InstallResult InstallWithFuseFromPath(std::string_view path, Device* device) {
// 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)
+ auto ui = device->GetUI();
pid_t child;
if ((child = fork()) == 0) {
bool status = StartInstallPackageFuse(path);
@@ -183,8 +184,8 @@ InstallResult InstallWithFuseFromPath(std::string_view path, RecoveryUI* ui) {
auto package =
Package::CreateFilePackage(FUSE_SIDELOAD_HOST_PATHNAME,
std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
- result =
- InstallPackage(package.get(), FUSE_SIDELOAD_HOST_PATHNAME, false, 0 /* retry_count */, ui);
+ result = InstallPackage(package.get(), FUSE_SIDELOAD_HOST_PATHNAME, false, 0 /* retry_count */,
+ device);
break;
}
@@ -226,7 +227,7 @@ InstallResult ApplyFromSdcard(Device* device) {
ui->Print("\n-- Install %s ...\n", path.c_str());
SetSdcardUpdateBootloaderMessage();
- auto result = InstallWithFuseFromPath(path, ui);
+ auto result = InstallWithFuseFromPath(path, device);
ensure_path_unmounted(SDCARD_ROOT);
return result;
}
diff --git a/install/include/install/fuse_install.h b/install/include/install/fuse_install.h
index 63b116aeb..29c283f40 100644
--- a/install/include/install/fuse_install.h
+++ b/install/include/install/fuse_install.h
@@ -25,6 +25,6 @@
// Starts FUSE with the package from |path| as the data source. And installs the package from
// |FUSE_SIDELOAD_HOST_PATHNAME|. The |path| can point to the location of a package zip file or a
// block map file with the prefix '@'; e.g. /sdcard/package.zip, @/cache/recovery/block.map.
-InstallResult InstallWithFuseFromPath(std::string_view path, RecoveryUI* ui);
+InstallResult InstallWithFuseFromPath(std::string_view path, Device* device);
InstallResult ApplyFromSdcard(Device* device);
diff --git a/install/include/install/install.h b/install/include/install/install.h
index bef23e9ca..0f5102f82 100644
--- a/install/include/install/install.h
+++ b/install/include/install/install.h
@@ -24,7 +24,8 @@
#include <ziparchive/zip_archive.h>
-#include "package.h"
+#include "otautil/package.h"
+#include "recovery_ui/device.h"
#include "recovery_ui/ui.h"
enum InstallResult {
@@ -49,7 +50,8 @@ enum class OtaType {
// cache partition after a successful installation if |should_wipe_cache| is true or an updater
// command asks to wipe the cache.
InstallResult InstallPackage(Package* package, const std::string_view package_id,
- bool should_wipe_cache, int retry_count, RecoveryUI* ui);
+ bool should_wipe_cache, int retry_count,
+ Device* ui);
// Verifies the package by ota keys. Returns true if the package is verified successfully,
// otherwise returns false.
diff --git a/install/include/install/package.h b/install/include/install/package.h
deleted file mode 100644
index 0b4233238..000000000
--- a/install/include/install/package.h
+++ /dev/null
@@ -1,62 +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 <stdint.h>
-
-#include <functional>
-#include <map>
-#include <memory>
-#include <string>
-#include <vector>
-
-#include <ziparchive/zip_archive.h>
-
-#include "verifier.h"
-
-enum class PackageType {
- kMemory,
- kFile,
-};
-
-// 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<Package> CreateMemoryPackage(
- const std::string& path, const std::function<void(float)>& set_progress);
- static std::unique_ptr<Package> CreateMemoryPackage(
- std::vector<uint8_t> content, const std::function<void(float)>& set_progress);
- static std::unique_ptr<Package> CreateFilePackage(const std::string& path,
- const std::function<void(float)>& set_progress);
-
- virtual ~Package() = default;
-
- virtual PackageType GetType() const = 0;
-
- virtual std::string GetPath() const = 0;
-
- // 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<void(float)> set_progress_;
-};
diff --git a/install/include/install/verifier.h b/install/include/install/verifier.h
deleted file mode 100644
index f9e947580..000000000
--- a/install/include/install/verifier.h
+++ /dev/null
@@ -1,101 +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.
- */
-
-#pragma once
-
-#include <stdint.h>
-
-#include <functional>
-#include <memory>
-#include <vector>
-
-#include <openssl/ec_key.h>
-#include <openssl/rsa.h>
-#include <openssl/sha.h>
-
-constexpr size_t MiB = 1024 * 1024;
-
-using HasherUpdateCallback = std::function<void(const uint8_t* addr, uint64_t size)>;
-
-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, RSADeleter>&& rsa_,
- std::unique_ptr<EC_KEY, ECKEYDeleter>&& 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, RSADeleter> rsa;
- std::unique_ptr<EC_KEY, ECKEYDeleter> 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<HasherUpdateCallback>& 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<Certificate>& 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, RSADeleter>& rsa);
-
-// Checks that the field size of the curve for the EC key is 256 bits.
-bool CheckECKey(const std::unique_ptr<EC_KEY, ECKEYDeleter>& 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<uint8_t>& 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<Certificate> LoadKeysFromZipfile(const std::string& zip_name);
-
-#define VERIFY_SUCCESS 0
-#define VERIFY_FAILURE 1
diff --git a/install/include/install/wipe_data.h b/install/include/install/wipe_data.h
index b34891f3d..42cad871e 100644
--- a/install/include/install/wipe_data.h
+++ b/install/include/install/wipe_data.h
@@ -27,4 +27,4 @@ struct selabel_handle;
bool WipeCache(RecoveryUI* ui, const std::function<bool()>& confirm);
// Returns true on success.
-bool WipeData(Device* device, bool convert_fbe);
+bool WipeData(Device* device);
diff --git a/install/include/install/wipe_device.h b/install/include/install/wipe_device.h
index c60b99997..903ddfdcd 100644
--- a/install/include/install/wipe_device.h
+++ b/install/include/install/wipe_device.h
@@ -19,7 +19,7 @@
#include <string>
#include <vector>
-#include "install/package.h"
+#include "otautil/package.h"
#include "recovery_ui/device.h"
// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
diff --git a/install/include/private/asn1_decoder.h b/install/include/private/asn1_decoder.h
deleted file mode 100644
index e5337d9c4..000000000
--- a/install/include/private/asn1_decoder.h
+++ /dev/null
@@ -1,56 +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 <stddef.h>
-#include <stdint.h>
-
-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/install.cpp b/install/install.cpp
index 6e74f80ab..83f3cad6b 100644
--- a/install/install.cpp
+++ b/install/install.cpp
@@ -46,13 +46,13 @@
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
-#include "install/package.h"
#include "install/spl_check.h"
-#include "install/verifier.h"
#include "install/wipe_data.h"
#include "otautil/error_code.h"
+#include "otautil/package.h"
#include "otautil/paths.h"
#include "otautil/sysutil.h"
+#include "otautil/verifier.h"
#include "private/setup_commands.h"
#include "recovery_ui/ui.h"
#include "recovery_utils/roots.h"
@@ -235,30 +235,41 @@ bool CheckPackageMetadata(const std::map<std::string, std::string>& metadata, Ot
return true;
}
-bool SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd,
- std::vector<std::string>* cmd) {
- CHECK(cmd != nullptr);
-
+static std::string ExtractPayloadProperties(ZipArchiveHandle zip) {
// 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";
ZipEntry64 properties_entry;
if (FindEntry(zip, AB_OTA_PAYLOAD_PROPERTIES, &properties_entry) != 0) {
LOG(ERROR) << "Failed to find " << AB_OTA_PAYLOAD_PROPERTIES;
- return false;
+ return {};
}
auto properties_entry_length = properties_entry.uncompressed_length;
if (properties_entry_length > std::numeric_limits<size_t>::max()) {
LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES
<< " because's uncompressed size exceeds size of address space. "
<< properties_entry_length;
- return false;
+ return {};
}
- std::vector<uint8_t> payload_properties(properties_entry_length);
+ std::string payload_properties(properties_entry_length, '\0');
int32_t err =
- ExtractToMemory(zip, &properties_entry, payload_properties.data(), properties_entry_length);
+ ExtractToMemory(zip, &properties_entry, reinterpret_cast<uint8_t*>(payload_properties.data()),
+ properties_entry_length);
if (err != 0) {
LOG(ERROR) << "Failed to extract " << AB_OTA_PAYLOAD_PROPERTIES << ": " << ErrorCodeString(err);
+ return {};
+ }
+ return payload_properties;
+}
+
+bool SetUpAbUpdateCommands(const std::string& package, ZipArchiveHandle zip, int status_fd,
+ std::vector<std::string>* 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.
+ const auto payload_properties = ExtractPayloadProperties(zip);
+ if (payload_properties.empty()) {
return false;
}
@@ -332,10 +343,20 @@ static void log_max_temperature(int* max_temperature, const std::atomic<bool>& l
}
}
+static bool PerformPowerwashIfRequired(ZipArchiveHandle zip, Device *device) {
+ const auto payload_properties = ExtractPayloadProperties(zip);
+ if (payload_properties.find("POWERWASH=1") != std::string::npos) {
+ LOG(INFO) << "Payload properties has POWERWASH=1, wiping userdata...";
+ return WipeData(device);
+ }
+ return true;
+}
+
// If the package contains an update binary, extract it and run it.
static InstallResult TryUpdateBinary(Package* package, bool* wipe_cache,
std::vector<std::string>* log_buffer, int retry_count,
- int* max_temperature, RecoveryUI* ui) {
+ int* max_temperature, Device* device) {
+ auto ui = device->GetUI();
std::map<std::string, std::string> metadata;
auto zip = package->GetZipArchiveHandle();
if (!ReadMetadataFromPackage(zip, &metadata)) {
@@ -530,13 +551,15 @@ static InstallResult TryUpdateBinary(Package* package, bool* wipe_cache,
} else {
LOG(FATAL) << "Invalid status code " << status;
}
+ PerformPowerwashIfRequired(zip, device);
return INSTALL_SUCCESS;
}
static InstallResult VerifyAndInstallPackage(Package* package, bool* wipe_cache,
std::vector<std::string>* log_buffer, int retry_count,
- int* max_temperature, RecoveryUI* ui) {
+ int* max_temperature, Device* device) {
+ auto ui = device->GetUI();
ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
// Give verification half the progress bar...
ui->SetProgressType(RecoveryUI::DETERMINATE);
@@ -554,7 +577,8 @@ static InstallResult VerifyAndInstallPackage(Package* package, bool* wipe_cache,
ui->Print("Retry attempt: %d\n", retry_count);
}
ui->SetEnableReboot(false);
- auto result = TryUpdateBinary(package, wipe_cache, log_buffer, retry_count, max_temperature, ui);
+ auto result =
+ TryUpdateBinary(package, wipe_cache, log_buffer, retry_count, max_temperature, device);
ui->SetEnableReboot(true);
ui->Print("\n");
@@ -562,7 +586,8 @@ static InstallResult VerifyAndInstallPackage(Package* package, bool* wipe_cache,
}
InstallResult InstallPackage(Package* package, const std::string_view package_id,
- bool should_wipe_cache, int retry_count, RecoveryUI* ui) {
+ bool should_wipe_cache, int retry_count, Device* device) {
+ auto ui = device->GetUI();
auto start = std::chrono::system_clock::now();
int start_temperature = GetMaxValueFromThermalZone();
@@ -584,7 +609,7 @@ InstallResult InstallPackage(Package* package, const std::string_view package_id
} else {
bool updater_wipe_cache = false;
result = VerifyAndInstallPackage(package, &updater_wipe_cache, &log_buffer, retry_count,
- &max_temperature, ui);
+ &max_temperature, device);
should_wipe_cache = should_wipe_cache || updater_wipe_cache;
}
diff --git a/install/package.cpp b/install/package.cpp
deleted file mode 100644
index 86fc0647d..000000000
--- a/install/package.cpp
+++ /dev/null
@@ -1,278 +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 "install/package.h"
-
-#include <string.h>
-#include <unistd.h>
-
-#include <android-base/file.h>
-#include <android-base/logging.h>
-#include <android-base/stringprintf.h>
-#include <android-base/unique_fd.h>
-
-#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<MemMapping> map,
- const std::function<void(float)>& set_progress);
-
- // Constructs the class from the package bytes in |content|.
- MemoryPackage(std::vector<uint8_t> content, const std::function<void(float)>& set_progress);
-
- ~MemoryPackage() override;
-
- PackageType GetType() const override {
- return PackageType::kMemory;
- }
-
- // Memory maps the package file if necessary. Initializes the start address and size of the
- // package.
- uint64_t GetPackageSize() const override {
- return package_size_;
- }
-
- std::string GetPath() const override {
- return path_;
- }
-
- bool ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) override;
-
- ZipArchiveHandle GetZipArchiveHandle() override;
-
- bool UpdateHashAtOffset(const std::vector<HasherUpdateCallback>& 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<MemMapping> map_;
- // A copy of the package content, valid only if we create the class with the exact bytes of
- // the package.
- std::vector<uint8_t> 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<void(float)>& set_progress);
-
- ~FilePackage() override;
-
- PackageType GetType() const override {
- return PackageType::kFile;
- }
-
- uint64_t GetPackageSize() const override {
- return package_size_;
- }
-
- std::string GetPath() const override {
- return path_;
- }
-
- bool ReadFullyAtOffset(uint8_t* buffer, uint64_t byte_count, uint64_t offset) override;
-
- ZipArchiveHandle GetZipArchiveHandle() override;
-
- bool UpdateHashAtOffset(const std::vector<HasherUpdateCallback>& 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> Package::CreateMemoryPackage(
- const std::string& path, const std::function<void(float)>& set_progress) {
- std::unique_ptr<MemMapping> mmap = std::make_unique<MemMapping>();
- if (!mmap->MapFile(path)) {
- LOG(ERROR) << "failed to map file";
- return nullptr;
- }
-
- return std::make_unique<MemoryPackage>(path, std::move(mmap), set_progress);
-}
-
-std::unique_ptr<Package> Package::CreateFilePackage(
- const std::string& path, const std::function<void(float)>& 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<FilePackage>(std::move(fd), file_size, path, set_progress);
-}
-
-std::unique_ptr<Package> Package::CreateMemoryPackage(
- std::vector<uint8_t> content, const std::function<void(float)>& set_progress) {
- return std::make_unique<MemoryPackage>(std::move(content), set_progress);
-}
-
-MemoryPackage::MemoryPackage(const std::string& path, std::unique_ptr<MemMapping> map,
- const std::function<void(float)>& 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<uint8_t> content,
- const std::function<void(float)>& 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<HasherUpdateCallback>& 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<uint8_t*>(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<void(float)>& 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<HasherUpdateCallback>& 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<uint64_t>(length - so_far, 16 * MiB);
- std::vector<uint8_t> 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_, false); 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
deleted file mode 100644
index 3f0260138..000000000
--- a/install/verifier.cpp
+++ /dev/null
@@ -1,472 +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 "install/verifier.h"
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <algorithm>
-#include <functional>
-#include <memory>
-#include <vector>
-
-#include <android-base/logging.h>
-#include <openssl/bio.h>
-#include <openssl/bn.h>
-#include <openssl/ecdsa.h>
-#include <openssl/evp.h>
-#include <openssl/obj_mac.h>
-#include <openssl/pem.h>
-#include <openssl/rsa.h>
-#include <ziparchive/zip_archive.h>
-
-#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<uint8_t>* sig_der) {
- CHECK(sig_der != nullptr);
- sig_der->clear();
-
- asn1_context ctx(pkcs7_der, pkcs7_der_len);
-
- std::unique_ptr<asn1_context> pkcs7_seq(ctx.asn1_sequence_get());
- if (pkcs7_seq == nullptr || !pkcs7_seq->asn1_sequence_next()) {
- return false;
- }
-
- std::unique_ptr<asn1_context> signed_data_app(pkcs7_seq->asn1_constructed_get());
- if (signed_data_app == nullptr) {
- return false;
- }
-
- std::unique_ptr<asn1_context> 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<asn1_context> sig_set(signed_data_seq->asn1_set_get());
- if (sig_set == nullptr) {
- return false;
- }
-
- std::unique_ptr<asn1_context> 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<Certificate>& 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<HasherUpdateCallback> 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<uint64_t>(signed_len - so_far, 16 * MiB);
- package->UpdateHashAtOffset(hashers, so_far, read_size);
- so_far += read_size;
-
- double f = so_far / static_cast<double>(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<uint8_t> 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<Certificate> IterateZipEntriesAndSearchForKeys(const ZipArchiveHandle& handle) {
- void* cookie;
- int32_t iter_status = StartIteration(handle, &cookie, "", "x509.pem");
- if (iter_status != 0) {
- LOG(ERROR) << "Failed to iterate over entries in the certificate zipfile: "
- << ErrorCodeString(iter_status);
- return {};
- }
-
- std::vector<Certificate> result;
-
- std::string_view name;
- ZipEntry64 entry;
- while ((iter_status = Next(cookie, &entry, &name)) == 0) {
- if (entry.uncompressed_length > std::numeric_limits<size_t>::max()) {
- LOG(ERROR) << "Failed to extract " << name
- << " because's uncompressed size exceeds size of address space. "
- << entry.uncompressed_length;
- return {};
- }
- std::vector<uint8_t> 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 " << name;
- 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 " << name;
- 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<Certificate> 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<Certificate> result = IterateZipEntriesAndSearchForKeys(handle);
- CloseArchive(handle);
- return result;
-}
-
-bool CheckRSAKey(const std::unique_ptr<RSA, RSADeleter>& 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, ECKEYDeleter>& 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<uint8_t>& pem_content, Certificate* cert) {
- std::unique_ptr<BIO, decltype(&BIO_free)> content(
- BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free);
-
- std::unique_ptr<X509, decltype(&X509_free)> 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<EVP_PKEY, decltype(&EVP_PKEY_free)> 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/install/wipe_data.cpp b/install/wipe_data.cpp
index 4eecf72c6..024c1e1d5 100644
--- a/install/wipe_data.cpp
+++ b/install/wipe_data.cpp
@@ -16,9 +16,7 @@
#include "install/wipe_data.h"
-#include <stdio.h>
#include <string.h>
-#include <sys/stat.h>
#include <functional>
#include <vector>
@@ -37,9 +35,8 @@ constexpr const char* CACHE_ROOT = "/cache";
constexpr const char* DATA_ROOT = "/data";
constexpr const char* METADATA_ROOT = "/metadata";
-static bool EraseVolume(const char* volume, RecoveryUI* ui, bool convert_fbe) {
+static bool EraseVolume(const char* volume, RecoveryUI* ui) {
bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
- bool is_data = (strcmp(volume, DATA_ROOT) == 0);
std::vector<saved_log_file> log_files;
if (is_cache) {
@@ -52,28 +49,7 @@ static bool EraseVolume(const char* volume, RecoveryUI* ui, bool convert_fbe) {
ensure_path_unmounted(volume);
- int result;
- if (is_data && convert_fbe) {
- constexpr const char* CONVERT_FBE_DIR = "/tmp/convert_fbe";
- constexpr const char* CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
- // Create convert_fbe breadcrumb file to signal init to convert to file based encryption, not
- // full disk encryption.
- if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
- PLOG(ERROR) << "Failed to mkdir " << CONVERT_FBE_DIR;
- return false;
- }
- FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
- if (!f) {
- PLOG(ERROR) << "Failed to convert to file encryption";
- return false;
- }
- fclose(f);
- result = format_volume(volume, CONVERT_FBE_DIR);
- remove(CONVERT_FBE_FILE);
- rmdir(CONVERT_FBE_DIR);
- } else {
- result = format_volume(volume);
- }
+ int result = format_volume(volume);
if (is_cache) {
RestoreLogFilesAfterFormat(log_files);
@@ -97,12 +73,12 @@ bool WipeCache(RecoveryUI* ui, const std::function<bool()>& confirm_func) {
ui->SetBackground(RecoveryUI::ERASING);
ui->SetProgressType(RecoveryUI::INDETERMINATE);
- bool success = EraseVolume("/cache", ui, false);
+ bool success = EraseVolume("/cache", ui);
ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
return success;
}
-bool WipeData(Device* device, bool convert_fbe) {
+bool WipeData(Device* device) {
RecoveryUI* ui = device->GetUI();
ui->Print("\n-- Wiping data...\n");
ui->SetBackground(RecoveryUI::ERASING);
@@ -115,13 +91,13 @@ bool WipeData(Device* device, bool convert_fbe) {
bool success = device->PreWipeData();
if (success) {
- success &= EraseVolume(DATA_ROOT, ui, convert_fbe);
+ success &= EraseVolume(DATA_ROOT, ui);
bool has_cache = volume_for_mount_point("/cache") != nullptr;
if (has_cache) {
- success &= EraseVolume(CACHE_ROOT, ui, false);
+ success &= EraseVolume(CACHE_ROOT, ui);
}
if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
- success &= EraseVolume(METADATA_ROOT, ui, false);
+ success &= EraseVolume(METADATA_ROOT, ui);
}
}
if (success) {
diff --git a/install/wipe_device.cpp b/install/wipe_device.cpp
index 915c87b45..0a525fa9b 100644
--- a/install/wipe_device.cpp
+++ b/install/wipe_device.cpp
@@ -35,7 +35,7 @@
#include "bootloader_message/bootloader_message.h"
#include "install/install.h"
-#include "install/package.h"
+#include "otautil/package.h"
#include "recovery_ui/device.h"
#include "recovery_ui/ui.h"