From 0dd96853111942330acd6b629aedbddf9dfa6ae6 Mon Sep 17 00:00:00 2001 From: Tianjie Xu Date: Mon, 15 Oct 2018 11:44:14 -0700 Subject: Load X509 keys from ziparchive Add a function to parse the zip archive and load the certificate from all the zip entries with the suffix "x509.pem". Bug: 116655889 Test: unittests pass Change-Id: I93bf7aef7462c0623e89fc2d466d7af2d3a758bc --- verifier.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) (limited to 'verifier.cpp') diff --git a/verifier.cpp b/verifier.cpp index 1dc52a0ef..2101dcb41 100644 --- a/verifier.cpp +++ b/verifier.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include "asn1_decoder.h" #include "otautil/print_sha1.h" @@ -445,6 +446,60 @@ std::unique_ptr parse_ec_key(FILE* file) { return key; } +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 LoadCertificateFromBuffer(const std::vector& pem_content, Certificate* cert) { std::unique_ptr content( BIO_new_mem_buf(pem_content.data(), pem_content.size()), BIO_free); -- cgit v1.2.3