Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit ed4c49c1 authored by Yabin Cui's avatar Yabin Cui Committed by Android (Google) Code Review
Browse files

Merge "Verify wipe package when wiping A/B device in recovery." into nyc-mr1-dev

parents d0dcbddd 6faf0265
Loading
Loading
Loading
Loading
+58 −41
Original line number Diff line number Diff line
@@ -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 @@ int get_bootloader_message(bootloader_message* out) {
    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 @@ int set_bootloader_message(const bootloader_message* in) {
    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 void wait_for_device(const char* fn) {
    }
}

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;
    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;
    }
        written += wrote;
    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;
}
+18 −0
Original line number Diff line number Diff line
@@ -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 @@ struct bootloader_message {
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
+37 −23
Original line number Diff line number Diff line
@@ -70,20 +70,27 @@ static int parse_build_number(std::string str) {
    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;
        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 @@ really_install_package(const char *path, bool* wipe_cache, bool needs_mount,
        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 @@ install_package(const char* path, bool* wipe_cache, const char* install_file,
    }
    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;
}
+10 −7
Original line number Diff line number Diff line
@@ -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 @@ enum { INSTALL_SUCCESS, INSTALL_ERROR, INSTALL_CORRUPT, INSTALL_NONE, INSTALL_SK
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_
+71 −2
Original line number Diff line number Diff line
@@ -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 @@ static const struct option OPTIONS[] = {
  { "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 @@ static bool secure_wipe_partition(const std::string& partition) {
    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 @@ int main(int argc, char **argv) {
    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 @@ int main(int argc, char **argv) {
            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 @@ int main(int argc, char **argv) {
            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) {
Loading