summaryrefslogtreecommitdiffstats
path: root/verifier.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'verifier.cpp')
-rw-r--r--verifier.cpp414
1 files changed, 166 insertions, 248 deletions
diff --git a/verifier.cpp b/verifier.cpp
index 283e04300..b6c3895ce 100644
--- a/verifier.cpp
+++ b/verifier.cpp
@@ -27,9 +27,14 @@
#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 "asn1_decoder.h"
#include "otautil/print_sha1.h"
@@ -112,19 +117,9 @@ static bool read_pkcs7(const uint8_t* pkcs7_der, size_t pkcs7_der_len,
return true;
}
-/*
- * 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. A callback function can be optionally provided for
- * posting the progress.
- *
- * Returns VERIFY_SUCCESS or VERIFY_FAILURE (if any error is encountered or no key matches the
- * signature).
- */
-int verify_file(const unsigned char* addr, size_t length, const std::vector<Certificate>& keys,
- const std::function<void(float)>& set_progress) {
- if (set_progress) {
- set_progress(0.0);
- }
+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:
//
@@ -135,13 +130,18 @@ int verify_file(const unsigned char* addr, size_t length, const std::vector<Cert
// 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;
}
- const unsigned char* footer = addr + length - FOOTER_SIZE;
+ 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";
@@ -177,9 +177,13 @@ int verify_file(const unsigned char* addr, size_t length, const std::vector<Cert
// 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.
- size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
+ uint64_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;
- const unsigned char* eocd = addr + length - eocd_size;
+ 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) {
@@ -211,24 +215,29 @@ int verify_file(const unsigned char* addr, size_t length, const std::vector<Cert
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;
- size_t so_far = 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.
- size_t size = std::min(signed_len - so_far, 16 * MiB);
-
- if (need_sha1) SHA1_Update(&sha1_ctx, addr + so_far, size);
- if (need_sha256) SHA256_Update(&sha256_ctx, addr + so_far, size);
- so_far += size;
-
- if (set_progress) {
- double f = so_far / (double)signed_len;
- if (f > frac + 0.02 || size == so_far) {
- set_progress(f);
- frac = f;
- }
+ // 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;
}
}
@@ -303,251 +312,160 @@ int verify_file(const unsigned char* addr, size_t length, const std::vector<Cert
return VERIFY_FAILURE;
}
-std::unique_ptr<RSA, RSADeleter> parse_rsa_key(FILE* file, uint32_t exponent) {
- // Read key length in words and n0inv. n0inv is a precomputed montgomery
- // parameter derived from the modulus and can be used to speed up
- // verification. n0inv is 32 bits wide here, assuming the verification logic
- // uses 32 bit arithmetic. However, BoringSSL may use a word size of 64 bits
- // internally, in which case we don't have a valid n0inv. Thus, we just
- // ignore the montgomery parameters and have BoringSSL recompute them
- // internally. If/When the speedup from using the montgomery parameters
- // becomes relevant, we can add more sophisticated code here to obtain a
- // 64-bit n0inv and initialize the montgomery parameters in the key object.
- uint32_t key_len_words = 0;
- uint32_t n0inv = 0;
- if (fscanf(file, " %i , 0x%x", &key_len_words, &n0inv) != 2) {
- return nullptr;
- }
+static std::vector<Certificate> 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 {};
+ }
- if (key_len_words > 8192 / 32) {
- LOG(ERROR) << "key length (" << key_len_words << ") too large";
- return nullptr;
+ std::vector<Certificate> result;
+
+ ZipString name;
+ ZipEntry entry;
+ while ((iter_status = Next(cookie, &entry, &name)) == 0) {
+ 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 " << std::string(name.name, name.name + name.name_length);
+ return {};
}
- // Read the modulus.
- std::unique_ptr<uint32_t[]> modulus(new uint32_t[key_len_words]);
- if (fscanf(file, " , { %u", &modulus[0]) != 1) {
- return nullptr;
- }
- for (uint32_t i = 1; i < key_len_words; ++i) {
- if (fscanf(file, " , %u", &modulus[i]) != 1) {
- return nullptr;
- }
+ 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 {};
}
- // Cconvert from little-endian array of little-endian words to big-endian
- // byte array suitable as input for BN_bin2bn.
- std::reverse((uint8_t*)modulus.get(),
- (uint8_t*)(modulus.get() + key_len_words));
-
- // The next sequence of values is the montgomery parameter R^2. Since we
- // generally don't have a valid |n0inv|, we ignore this (see comment above).
- uint32_t rr_value;
- if (fscanf(file, " } , { %u", &rr_value) != 1) {
- return nullptr;
- }
- for (uint32_t i = 1; i < key_len_words; ++i) {
- if (fscanf(file, " , %u", &rr_value) != 1) {
- return nullptr;
- }
- }
- if (fscanf(file, " } } ") != 0) {
- return nullptr;
- }
+ result.emplace_back(std::move(cert));
+ }
- // Initialize the key.
- std::unique_ptr<RSA, RSADeleter> key(RSA_new());
- if (!key) {
- return nullptr;
- }
+ if (iter_status != -1) {
+ LOG(ERROR) << "Error while iterating over zip entries: " << ErrorCodeString(iter_status);
+ return {};
+ }
- key->n = BN_bin2bn((uint8_t*)modulus.get(),
- key_len_words * sizeof(uint32_t), NULL);
- if (!key->n) {
- return nullptr;
- }
+ return result;
+}
- key->e = BN_new();
- if (!key->e || !BN_set_word(key->e, exponent)) {
- return nullptr;
- }
+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 {};
+ }
- return key;
+ std::vector<Certificate> result = IterateZipEntriesAndSearchForKeys(handle);
+ CloseArchive(handle);
+ return result;
}
-struct BNDeleter {
- void operator()(BIGNUM* bn) const {
- BN_free(bn);
+bool CheckRSAKey(const std::unique_ptr<RSA, RSADeleter>& rsa) {
+ if (!rsa) {
+ return false;
}
-};
-std::unique_ptr<EC_KEY, ECKEYDeleter> parse_ec_key(FILE* file) {
- uint32_t key_len_bytes = 0;
- if (fscanf(file, " %i", &key_len_bytes) != 1) {
- return nullptr;
- }
-
- std::unique_ptr<EC_GROUP, void (*)(EC_GROUP*)> group(
- EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1), EC_GROUP_free);
- if (!group) {
- return nullptr;
- }
+ 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) {
+ LOG(ERROR) << "Modulus should be 2048 bits long, actual: " << modulus_bits;
+ return false;
+ }
- // Verify that |key_len| matches the group order.
- if (key_len_bytes != BN_num_bytes(EC_GROUP_get0_order(group.get()))) {
- return nullptr;
- }
+ 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;
+ }
- // Read the public key coordinates. Note that the byte order in the file is
- // little-endian, so we convert to big-endian here.
- std::unique_ptr<uint8_t[]> bytes(new uint8_t[key_len_bytes]);
- std::unique_ptr<BIGNUM, BNDeleter> point[2];
- for (int i = 0; i < 2; ++i) {
- unsigned int byte = 0;
- if (fscanf(file, " , { %u", &byte) != 1) {
- return nullptr;
- }
- bytes[key_len_bytes - 1] = byte;
-
- for (size_t i = 1; i < key_len_bytes; ++i) {
- if (fscanf(file, " , %u", &byte) != 1) {
- return nullptr;
- }
- bytes[key_len_bytes - i - 1] = byte;
- }
-
- point[i].reset(BN_bin2bn(bytes.get(), key_len_bytes, nullptr));
- if (!point[i]) {
- return nullptr;
- }
-
- if (fscanf(file, " }") != 0) {
- return nullptr;
- }
- }
+ return true;
+}
- if (fscanf(file, " } ") != 0) {
- return nullptr;
- }
+bool CheckECKey(const std::unique_ptr<EC_KEY, ECKEYDeleter>& ec_key) {
+ if (!ec_key) {
+ return false;
+ }
- // Create and initialize the key.
- std::unique_ptr<EC_KEY, ECKEYDeleter> key(EC_KEY_new());
- if (!key || !EC_KEY_set_group(key.get(), group.get()) ||
- !EC_KEY_set_public_key_affine_coordinates(key.get(), point[0].get(),
- point[1].get())) {
- return nullptr;
- }
+ 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 key;
+ return true;
}
-// Reads a file containing one or more public keys as produced by
-// DumpPublicKey: this is an RSAPublicKey struct as it would appear
-// as a C source literal, eg:
-//
-// "{64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
-//
-// For key versions newer than the original 2048-bit e=3 keys
-// supported by Android, the string is preceded by a version
-// identifier, eg:
-//
-// "v2 {64,0xc926ad21,{1795090719,...,-695002876},{-857949815,...,1175080310}}"
-//
-// (Note that the braces and commas in this example are actual
-// characters the parser expects to find in the file; the ellipses
-// indicate more numbers omitted from this example.)
-//
-// The file may contain multiple keys in this format, separated by
-// commas. The last key must not be followed by a comma.
-//
-// A Certificate is a pair of an RSAPublicKey and a particular hash
-// (we support SHA-1 and SHA-256; we store the hash length to signify
-// which is being used). The hash used is implied by the version number.
-//
-// 1: 2048-bit RSA key with e=3 and SHA-1 hash
-// 2: 2048-bit RSA key with e=65537 and SHA-1 hash
-// 3: 2048-bit RSA key with e=3 and SHA-256 hash
-// 4: 2048-bit RSA key with e=65537 and SHA-256 hash
-// 5: 256-bit EC key using the NIST P-256 curve parameters and SHA-256 hash
-//
-// Returns true on success, and appends the found keys (at least one) to certs.
-// Otherwise returns false if the file failed to parse, or if it contains zero
-// keys. The contents in certs would be unspecified on failure.
-bool load_keys(const char* filename, std::vector<Certificate>& certs) {
- std::unique_ptr<FILE, decltype(&fclose)> f(fopen(filename, "re"), fclose);
- if (!f) {
- PLOG(ERROR) << "error opening " << filename;
+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;
}
- while (true) {
- certs.emplace_back(0, Certificate::KEY_TYPE_RSA, nullptr, nullptr);
- Certificate& cert = certs.back();
- uint32_t exponent = 0;
-
- char start_char;
- if (fscanf(f.get(), " %c", &start_char) != 1) return false;
- if (start_char == '{') {
- // a version 1 key has no version specifier.
- cert.key_type = Certificate::KEY_TYPE_RSA;
- exponent = 3;
- cert.hash_len = SHA_DIGEST_LENGTH;
- } else if (start_char == 'v') {
- int version;
- if (fscanf(f.get(), "%d {", &version) != 1) return false;
- switch (version) {
- case 2:
- cert.key_type = Certificate::KEY_TYPE_RSA;
- exponent = 65537;
- cert.hash_len = SHA_DIGEST_LENGTH;
- break;
- case 3:
- cert.key_type = Certificate::KEY_TYPE_RSA;
- exponent = 3;
- cert.hash_len = SHA256_DIGEST_LENGTH;
- break;
- case 4:
- cert.key_type = Certificate::KEY_TYPE_RSA;
- exponent = 65537;
- cert.hash_len = SHA256_DIGEST_LENGTH;
- break;
- case 5:
- cert.key_type = Certificate::KEY_TYPE_EC;
- cert.hash_len = SHA256_DIGEST_LENGTH;
- break;
- default:
- 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;
+ }
- if (cert.key_type == Certificate::KEY_TYPE_RSA) {
- cert.rsa = parse_rsa_key(f.get(), exponent);
- if (!cert.rsa) {
- 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;
+ }
- LOG(INFO) << "read key e=" << exponent << " hash=" << cert.hash_len;
- } else if (cert.key_type == Certificate::KEY_TYPE_EC) {
- cert.ec = parse_ec_key(f.get());
- if (!cert.ec) {
- return false;
- }
- } else {
- LOG(ERROR) << "Unknown key type " << cert.key_type;
+ 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;
}
-
- // if the line ends in a comma, this file has more keys.
- int ch = fgetc(f.get());
- if (ch == ',') {
- // more keys to come.
- continue;
- } else if (ch == EOF) {
- break;
- } else {
- LOG(ERROR) << "unexpected character between keys";
+ } 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;
}