Verify wipe package when wiping A/B device in recovery.

To increase the security of wiping A/B devices, let uncrypt write
wipe package in misc partition. Then recovery verifies the wipe
package before wiping the device.

Bug: 29159185

Change-Id: I186691bab1928d3dc036bc5542abd64a81bc2168
diff --git a/bootloader.cpp b/bootloader.cpp
index d80c5e7..f6c0e93 100644
--- a/bootloader.cpp
+++ b/bootloader.cpp
@@ -25,6 +25,8 @@
 
 #include <fs_mgr.h>
 
+#include <android-base/file.h>
+
 #include "bootloader.h"
 #include "common.h"
 #include "mtdutils/mtdutils.h"
@@ -33,8 +35,8 @@
 
 static int get_bootloader_message_mtd(bootloader_message* out, const Volume* v);
 static int set_bootloader_message_mtd(const bootloader_message* in, const Volume* v);
-static int get_bootloader_message_block(bootloader_message* out, const Volume* v);
-static int set_bootloader_message_block(const bootloader_message* in, const Volume* v);
+static bool read_misc_partition(const Volume* v, size_t offset, size_t size, std::string* out);
+static bool write_misc_partition(const Volume* v, size_t offset, const std::string& in);
 
 int get_bootloader_message(bootloader_message* out) {
     Volume* v = volume_for_path("/misc");
@@ -45,12 +47,34 @@
     if (strcmp(v->fs_type, "mtd") == 0) {
         return get_bootloader_message_mtd(out, v);
     } else if (strcmp(v->fs_type, "emmc") == 0) {
-        return get_bootloader_message_block(out, v);
+        std::string s;
+        if (!read_misc_partition(v, BOOTLOADER_MESSAGE_OFFSET_IN_MISC, sizeof(bootloader_message),
+                                 &s)) {
+            return -1;
+        }
+        memcpy(out, s.data(), s.size());
+        return 0;
     }
-    LOGE("unknown misc partition fs_type \"%s\"\n", v->fs_type);
+    LOGE("Unknown misc partition fs_type \"%s\"\n", v->fs_type);
     return -1;
 }
 
+bool read_wipe_package(size_t size, std::string* out) {
+    Volume* v = volume_for_path("/misc");
+    if (v == nullptr) {
+        LOGE("Cannot load volume /misc!\n");
+        return false;
+    }
+    if (strcmp(v->fs_type, "mtd") == 0) {
+        LOGE("Read wipe package on mtd is not supported.\n");
+        return false;
+    } else if (strcmp(v->fs_type, "emmc") == 0) {
+        return read_misc_partition(v, WIPE_PACKAGE_OFFSET_IN_MISC, size, out);
+    }
+    LOGE("Unknown misc partition fs_type \"%s\"\n", v->fs_type);
+    return false;
+}
+
 int set_bootloader_message(const bootloader_message* in) {
     Volume* v = volume_for_path("/misc");
     if (v == nullptr) {
@@ -60,9 +84,11 @@
     if (strcmp(v->fs_type, "mtd") == 0) {
         return set_bootloader_message_mtd(in, v);
     } else if (strcmp(v->fs_type, "emmc") == 0) {
-        return set_bootloader_message_block(in, v);
+        std::string s(reinterpret_cast<const char*>(in), sizeof(*in));
+        bool success = write_misc_partition(v, BOOTLOADER_MESSAGE_OFFSET_IN_MISC, s);
+        return success ? 0 : -1;
     }
-    LOGE("unknown misc partition fs_type \"%s\"\n", v->fs_type);
+    LOGE("Unknown misc partition fs_type \"%s\"\n", v->fs_type);
     return -1;
 }
 
@@ -166,53 +192,44 @@
     }
 }
 
-static int get_bootloader_message_block(bootloader_message* out,
-                                        const Volume* v) {
+static bool read_misc_partition(const Volume* v, size_t offset, size_t size, std::string* out) {
     wait_for_device(v->blk_device);
-    FILE* f = fopen(v->blk_device, "rb");
-    if (f == nullptr) {
-        LOGE("failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
+    unique_fd fd(open(v->blk_device, O_RDONLY));
+    if (fd.get() == -1) {
+        LOGE("Failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-    bootloader_message temp;
-    int count = fread(&temp, sizeof(temp), 1, f);
-    if (count != 1) {
-        LOGE("failed to read \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
+    if (lseek(fd.get(), static_cast<off_t>(offset), SEEK_SET) != static_cast<off_t>(offset)) {
+        LOGE("Failed to lseek \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-    if (fclose(f) != 0) {
-        LOGE("failed to close \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
+    out->resize(size);
+    if (!android::base::ReadFully(fd.get(), &(*out)[0], size)) {
+        LOGE("Failed to read \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-    memcpy(out, &temp, sizeof(temp));
-    return 0;
+    return true;
 }
 
-static int set_bootloader_message_block(const bootloader_message* in,
-                                        const Volume* v) {
+static bool write_misc_partition(const Volume* v, size_t offset, const std::string& in) {
     wait_for_device(v->blk_device);
     unique_fd fd(open(v->blk_device, O_WRONLY | O_SYNC));
     if (fd.get() == -1) {
-        LOGE("failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
+        LOGE("Failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-
-    size_t written = 0;
-    const uint8_t* start = reinterpret_cast<const uint8_t*>(in);
-    size_t total = sizeof(*in);
-    while (written < total) {
-        ssize_t wrote = TEMP_FAILURE_RETRY(write(fd.get(), start + written, total - written));
-        if (wrote == -1) {
-            LOGE("failed to write %" PRId64 " bytes: %s\n",
-                 static_cast<off64_t>(written), strerror(errno));
-            return -1;
-        }
-        written += wrote;
+    if (lseek(fd.get(), static_cast<off_t>(offset), SEEK_SET) != static_cast<off_t>(offset)) {
+        LOGE("Failed to lseek \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
+    }
+    if (!android::base::WriteFully(fd.get(), in.data(), in.size())) {
+        LOGE("Failed to write \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
 
     if (fsync(fd.get()) == -1) {
-        LOGE("failed to fsync \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
+        LOGE("Failed to fsync \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-    return 0;
+    return true;
 }
diff --git a/bootloader.h b/bootloader.h
index 742a4ab..88d54a5 100644
--- a/bootloader.h
+++ b/bootloader.h
@@ -17,6 +17,17 @@
 #ifndef _RECOVERY_BOOTLOADER_H
 #define _RECOVERY_BOOTLOADER_H
 
+#include <stddef.h>
+
+// Spaces used by misc partition are as below:
+// 0   - 2K     Bootloader Message
+// 2K  - 16K    Used by Vendor's bootloader
+// 16K - 64K    Used by uncrypt and recovery to store wipe_package for A/B devices
+// Note that these offsets are admitted by bootloader,recovery and uncrypt, so they
+// are not configurable without changing all of them.
+static const size_t BOOTLOADER_MESSAGE_OFFSET_IN_MISC = 0;
+static const size_t WIPE_PACKAGE_OFFSET_IN_MISC = 16 * 1024;
+
 /* Bootloader Message
  *
  * This structure describes the content of a block in flash
@@ -68,4 +79,11 @@
 int get_bootloader_message(struct bootloader_message *out);
 int set_bootloader_message(const struct bootloader_message *in);
 
+#ifdef __cplusplus
+
+#include <string>
+
+bool read_wipe_package(size_t size, std::string* out);
+#endif
+
 #endif
diff --git a/install.cpp b/install.cpp
index 5a439a1..518337f 100644
--- a/install.cpp
+++ b/install.cpp
@@ -70,20 +70,27 @@
     return -1;
 }
 
-// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
-static void read_source_target_build(ZipArchive* zip, std::vector<std::string>& log_buffer) {
+bool read_metadata_from_package(ZipArchive* zip, std::string* meta_data) {
     const ZipEntry* meta_entry = mzFindZipEntry(zip, METADATA_PATH);
     if (meta_entry == nullptr) {
         LOGE("Failed to find %s in update package.\n", METADATA_PATH);
-        return;
+        return false;
     }
 
-    std::string meta_data(meta_entry->uncompLen, '\0');
-    if (!mzReadZipEntry(zip, meta_entry, &meta_data[0], meta_entry->uncompLen)) {
+    meta_data->resize(meta_entry->uncompLen, '\0');
+    if (!mzReadZipEntry(zip, meta_entry, &(*meta_data)[0], meta_entry->uncompLen)) {
         LOGE("Failed to read metadata in update package.\n");
+        return false;
+    }
+    return true;
+}
+
+// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
+static void read_source_target_build(ZipArchive* zip, std::vector<std::string>& log_buffer) {
+    std::string meta_data;
+    if (!read_metadata_from_package(zip, &meta_data)) {
         return;
     }
-
     // Examples of the pre-build and post-build strings in metadata:
     // pre-build-incremental=2943039
     // post-build-incremental=2951741
@@ -300,31 +307,16 @@
         return INSTALL_CORRUPT;
     }
 
-    // Load keys.
-    std::vector<Certificate> loadedKeys;
-    if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
-        LOGE("Failed to load keys\n");
-        return INSTALL_CORRUPT;
-    }
-    LOGI("%zu key(s) loaded from %s\n", loadedKeys.size(), PUBLIC_KEYS_FILE);
-
     // Verify package.
-    ui->Print("Verifying update package...\n");
-    auto t0 = std::chrono::system_clock::now();
-    int err = verify_file(map.addr, map.length, loadedKeys);
-    std::chrono::duration<double> 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) {
-        LOGE("signature verification failed\n");
+    if (!verify_package(map.addr, map.length)) {
         log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
-
         sysReleaseMap(&map);
         return INSTALL_CORRUPT;
     }
 
     // Try to open the package.
     ZipArchive zip;
-    err = mzOpenZipArchive(map.addr, map.length, &zip);
+    int err = mzOpenZipArchive(map.addr, map.length, &zip);
     if (err != 0) {
         LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
         log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
@@ -387,3 +379,25 @@
     }
     return result;
 }
+
+bool verify_package(const unsigned char* package_data, size_t package_size) {
+    std::vector<Certificate> loadedKeys;
+    if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
+        LOGE("Failed to load keys\n");
+        return false;
+    }
+    LOGI("%zu key(s) loaded from %s\n", loadedKeys.size(), PUBLIC_KEYS_FILE);
+
+    // Verify package.
+    ui->Print("Verifying update package...\n");
+    auto t0 = std::chrono::system_clock::now();
+    int err = verify_file(const_cast<unsigned char*>(package_data), package_size, loadedKeys);
+    std::chrono::duration<double> 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) {
+        LOGE("Signature verification failed\n");
+        LOGE("error: %d\n", kZipVerificationFailure);
+        return false;
+    }
+    return true;
+}
diff --git a/install.h b/install.h
index 66764f5..14de225 100644
--- a/install.h
+++ b/install.h
@@ -17,11 +17,10 @@
 #ifndef RECOVERY_INSTALL_H_
 #define RECOVERY_INSTALL_H_
 
-#include "common.h"
+#include <string>
 
-#ifdef __cplusplus
-extern "C" {
-#endif
+#include "common.h"
+#include "minzip/Zip.h"
 
 enum { INSTALL_SUCCESS, INSTALL_ERROR, INSTALL_CORRUPT, INSTALL_NONE, INSTALL_SKIPPED,
         INSTALL_RETRY };
@@ -31,8 +30,12 @@
 int install_package(const char* root_path, bool* wipe_cache, const char* install_file,
                     bool needs_mount, int retry_count);
 
-#ifdef __cplusplus
-}
-#endif
+// Verify the package by ota keys. Return true if the package is verified successfully,
+// otherwise return false.
+bool verify_package(const unsigned char* package_data, size_t package_size);
+
+// Read meta data file of the package, write its content in the string pointed by meta_data.
+// Return true if succeed, otherwise return false.
+bool read_metadata_from_package(ZipArchive* zip, std::string* meta_data);
 
 #endif  // RECOVERY_INSTALL_H_
diff --git a/recovery.cpp b/recovery.cpp
index 65e1a7b..6df9b6f 100644
--- a/recovery.cpp
+++ b/recovery.cpp
@@ -61,6 +61,7 @@
 #include "install.h"
 #include "minui/minui.h"
 #include "minzip/DirUtil.h"
+#include "minzip/Zip.h"
 #include "roots.h"
 #include "ui.h"
 #include "unique_fd.h"
@@ -84,6 +85,7 @@
   { "reason", required_argument, NULL, 'r' },
   { "security", no_argument, NULL, 'e'},
   { "wipe_ab", no_argument, NULL, 0 },
+  { "wipe_package_size", required_argument, NULL, 0 },
   { NULL, 0, NULL, 0 },
 };
 
@@ -904,12 +906,75 @@
     return true;
 }
 
+// Check if the wipe package matches expectation:
+// 1. verify the package.
+// 2. check metadata (ota-type, pre-device and serial number if having one).
+static bool check_wipe_package(size_t wipe_package_size) {
+    if (wipe_package_size == 0) {
+        LOGE("wipe_package_size is zero.\n");
+        return false;
+    }
+    std::string wipe_package;
+    if (!read_wipe_package(wipe_package_size, &wipe_package)) {
+        LOGE("Failed to read wipe package.\n");
+        return false;
+    }
+    if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
+                        wipe_package.size())) {
+        LOGE("Failed to verify package.\n");
+        return false;
+    }
+
+    // Extract metadata
+    ZipArchive zip;
+    int err = mzOpenZipArchive(reinterpret_cast<unsigned char*>(&wipe_package[0]),
+                               wipe_package.size(), &zip);
+    if (err != 0) {
+        LOGE("Can't open wipe package: %s\n", err != -1 ? strerror(err) : "bad");
+        return false;
+    }
+    std::string metadata;
+    if (!read_metadata_from_package(&zip, &metadata)) {
+        mzCloseZipArchive(&zip);
+        return false;
+    }
+    mzCloseZipArchive(&zip);
+
+    // Check metadata
+    std::vector<std::string> lines = android::base::Split(metadata, "\n");
+    bool ota_type_matched = false;
+    bool device_type_matched = false;
+    bool has_serial_number = false;
+    bool serial_number_matched = false;
+    for (const auto& line : lines) {
+        if (line == "ota-type=BRICK") {
+            ota_type_matched = true;
+        } else if (android::base::StartsWith(line, "pre-device=")) {
+            std::string device_type = line.substr(strlen("pre-device="));
+            char real_device_type[PROPERTY_VALUE_MAX];
+            property_get("ro.build.product", real_device_type, "");
+            device_type_matched = (device_type == real_device_type);
+        } else if (android::base::StartsWith(line, "serialno=")) {
+            std::string serial_no = line.substr(strlen("serialno="));
+            char real_serial_no[PROPERTY_VALUE_MAX];
+            property_get("ro.serialno", real_serial_no, "");
+            has_serial_number = true;
+            serial_number_matched = (serial_no == real_serial_no);
+        }
+    }
+    return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
+}
+
 // Wipe the current A/B device, with a secure wipe of all the partitions in
 // RECOVERY_WIPE.
-static bool wipe_ab_device() {
+static bool wipe_ab_device(size_t wipe_package_size) {
     ui->SetBackground(RecoveryUI::ERASING);
     ui->SetProgressType(RecoveryUI::INDETERMINATE);
 
+    if (!check_wipe_package(wipe_package_size)) {
+        LOGE("Failed to verify wipe package\n");
+        return false;
+    }
     std::string partition_list;
     if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
         LOGE("failed to read \"%s\".\n", RECOVERY_WIPE);
@@ -1418,6 +1483,7 @@
     bool should_wipe_data = false;
     bool should_wipe_cache = false;
     bool should_wipe_ab = false;
+    size_t wipe_package_size = 0;
     bool show_text = false;
     bool sideload = false;
     bool sideload_auto_reboot = false;
@@ -1455,6 +1521,9 @@
             if (strcmp(OPTIONS[option_index].name, "wipe_ab") == 0) {
                 should_wipe_ab = true;
                 break;
+            } else if (strcmp(OPTIONS[option_index].name, "wipe_package_size") == 0) {
+                android::base::ParseUint(optarg, &wipe_package_size);
+                break;
             }
             break;
         }
@@ -1597,7 +1666,7 @@
             status = INSTALL_ERROR;
         }
     } else if (should_wipe_ab) {
-        if (!wipe_ab_device()) {
+        if (!wipe_ab_device(wipe_package_size)) {
             status = INSTALL_ERROR;
         }
     } else if (sideload) {
diff --git a/uncrypt/bootloader_message_writer.cpp b/uncrypt/bootloader_message_writer.cpp
index 3bb106a..42df31e 100644
--- a/uncrypt/bootloader_message_writer.cpp
+++ b/uncrypt/bootloader_message_writer.cpp
@@ -58,7 +58,7 @@
   return record->blk_device;
 }
 
-static bool write_bootloader_message(const bootloader_message& boot, std::string* err) {
+static bool write_misc_partition(const void* p, size_t size, size_t misc_offset, std::string* err) {
   std::string misc_blk_device = get_misc_blk_device(err);
   if (misc_blk_device.empty()) {
     return false;
@@ -69,11 +69,18 @@
                                        strerror(errno));
     return false;
   }
-  if (!android::base::WriteFully(fd.get(), &boot, sizeof(boot))) {
+  if (lseek(fd.get(), static_cast<off_t>(misc_offset), SEEK_SET) !=
+      static_cast<off_t>(misc_offset)) {
+    *err = android::base::StringPrintf("failed to lseek %s: %s", misc_blk_device.c_str(),
+                                       strerror(errno));
+    return false;
+  }
+  if (!android::base::WriteFully(fd.get(), p, size)) {
     *err = android::base::StringPrintf("failed to write %s: %s", misc_blk_device.c_str(),
                                        strerror(errno));
     return false;
   }
+
   // TODO: O_SYNC and fsync duplicates each other?
   if (fsync(fd.get()) == -1) {
     *err = android::base::StringPrintf("failed to fsync %s: %s", misc_blk_device.c_str(),
@@ -83,6 +90,10 @@
   return true;
 }
 
+static bool write_bootloader_message(const bootloader_message& boot, std::string* err) {
+  return write_misc_partition(&boot, sizeof(boot), BOOTLOADER_MESSAGE_OFFSET_IN_MISC, err);
+}
+
 bool clear_bootloader_message(std::string* err) {
   bootloader_message boot = {};
   return write_bootloader_message(boot, err);
@@ -101,6 +112,11 @@
   return write_bootloader_message(boot, err);
 }
 
+bool write_wipe_package(const std::string& package_data, std::string* err) {
+  return write_misc_partition(package_data.data(), package_data.size(),
+                              WIPE_PACKAGE_OFFSET_IN_MISC, err);
+}
+
 extern "C" bool write_bootloader_message(const char* options) {
   std::string err;
   return write_bootloader_message({options}, &err);
diff --git a/uncrypt/include/bootloader_message_writer.h b/uncrypt/include/bootloader_message_writer.h
index e0ca3f4..1344bc8 100644
--- a/uncrypt/include/bootloader_message_writer.h
+++ b/uncrypt/include/bootloader_message_writer.h
@@ -24,6 +24,7 @@
 bool clear_bootloader_message(std::string* err);
 
 bool write_bootloader_message(const std::vector<std::string>& options, std::string* err);
+bool write_wipe_package(const std::string& package_data, std::string* err);
 
 #else
 #include <stdbool.h>
diff --git a/uncrypt/uncrypt.cpp b/uncrypt/uncrypt.cpp
index d7105a0..f62d132 100644
--- a/uncrypt/uncrypt.cpp
+++ b/uncrypt/uncrypt.cpp
@@ -503,14 +503,31 @@
         return false;
     }
     ALOGI("  received command: [%s] (%zu)", content.c_str(), content.size());
+    std::vector<std::string> options = android::base::Split(content, "\n");
+    std::string wipe_package;
+    for (auto& option : options) {
+        if (android::base::StartsWith(option, "--wipe_package=")) {
+            std::string path = option.substr(strlen("--wipe_package="));
+            if (!android::base::ReadFileToString(path, &wipe_package)) {
+                ALOGE("failed to read %s: %s", path.c_str(), strerror(errno));
+                return false;
+            }
+            option = android::base::StringPrintf("--wipe_package_size=%zu", wipe_package.size());
+        }
+    }
 
     // c8. setup the bcb command
     std::string err;
-    if (!write_bootloader_message({content}, &err)) {
+    if (!write_bootloader_message(options, &err)) {
         ALOGE("failed to set bootloader message: %s", err.c_str());
         write_status_to_socket(-1, socket);
         return false;
     }
+    if (!wipe_package.empty() && !write_wipe_package(wipe_package, &err)) {
+        ALOGE("failed to set wipe package: %s", err.c_str());
+        write_status_to_socket(-1, socket);
+        return false;
+    }
     // c10. send "100" status
     write_status_to_socket(100, socket);
     return true;