diff options
-rw-r--r-- | Android.mk | 14 | ||||
-rw-r--r-- | default_recovery_ui.c | 65 | ||||
-rw-r--r-- | install.c | 34 | ||||
-rw-r--r-- | minui/graphics.c | 1 | ||||
-rw-r--r-- | minui/minui.h | 16 | ||||
-rw-r--r-- | recovery.c | 103 | ||||
-rw-r--r-- | recovery_ui.h | 76 | ||||
-rw-r--r-- | res/images/icon_error.png | bin | 9616 -> 15259 bytes | |||
-rw-r--r-- | res/images/icon_firmware_install.png | bin | 11986 -> 17871 bytes | |||
-rw-r--r-- | res/images/icon_installing.png | bin | 10138 -> 15871 bytes | |||
-rw-r--r-- | roots.c | 1 | ||||
-rw-r--r-- | ui.c | 11 | ||||
-rw-r--r-- | updater/Android.mk | 38 | ||||
-rw-r--r-- | updater/updater.c | 6 | ||||
-rw-r--r-- | verifier.c | 439 | ||||
-rw-r--r-- | verifier.h | 12 |
16 files changed, 415 insertions, 401 deletions
diff --git a/Android.mk b/Android.mk index ecf26401f..deec80ae4 100644 --- a/Android.mk +++ b/Android.mk @@ -1,11 +1,11 @@ +ifneq ($(TARGET_SIMULATOR),true) +ifeq ($(TARGET_ARCH),arm) + LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) commands_recovery_local_path := $(LOCAL_PATH) -ifneq ($(TARGET_SIMULATOR),true) -ifeq ($(TARGET_ARCH),arm) - LOCAL_SRC_FILES := \ recovery.c \ bootloader.c \ @@ -31,7 +31,13 @@ LOCAL_CFLAGS += -DRECOVERY_API_VERSION=$(RECOVERY_API_VERSION) LOCAL_MODULE_TAGS := eng -LOCAL_STATIC_LIBRARIES := libminzip libunz libmtdutils libmincrypt +LOCAL_STATIC_LIBRARIES := +ifeq ($(TARGET_RECOVERY_UI_LIB),) + LOCAL_SRC_FILES += default_recovery_ui.c +else + LOCAL_STATIC_LIBRARIES += $(TARGET_RECOVERY_UI_LIB) +endif +LOCAL_STATIC_LIBRARIES += libminzip libunz libmtdutils libmincrypt LOCAL_STATIC_LIBRARIES += libminui libpixelflinger_static libpng libcutils LOCAL_STATIC_LIBRARIES += libstdc++ libc diff --git a/default_recovery_ui.c b/default_recovery_ui.c new file mode 100644 index 000000000..d4e620403 --- /dev/null +++ b/default_recovery_ui.c @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2009 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 <linux/input.h> + +#include "recovery_ui.h" +#include "common.h" + +char* MENU_HEADERS[] = { "Android system recovery utility", + "", + NULL }; + +char* MENU_ITEMS[] = { "reboot system now", + "apply sdcard:update.zip", + "wipe data/factory reset", + "wipe cache partition", + NULL }; + +int device_toggle_display(volatile char* key_pressed, int key_code) { + return key_code == KEY_HOME; +} + +int device_reboot_now(volatile char* key_pressed, int key_code) { + return 0; +} + +int device_handle_key(int key_code, int visible) { + if (visible) { + switch (key_code) { + case KEY_DOWN: + case KEY_VOLUMEDOWN: + return HIGHLIGHT_DOWN; + + case KEY_UP: + case KEY_VOLUMEUP: + return HIGHLIGHT_UP; + + case KEY_ENTER: + return SELECT_ITEM; + } + } + + return NO_ACTION; +} + +int device_perform_action(int which) { + return which; +} + +int device_wipe_data() { + return 0; +} @@ -234,20 +234,8 @@ try_update_binary(const char *path, ZipArchive *zip) { } static int -handle_update_package(const char *path, ZipArchive *zip, - const RSAPublicKey *keys, int numKeys) +handle_update_package(const char *path, ZipArchive *zip) { - // Give verification half the progress bar... - ui_print("Verifying update package...\n"); - ui_show_progress( - VERIFICATION_PROGRESS_FRACTION, - VERIFICATION_PROGRESS_TIME); - - if (!verify_jar_signature(zip, keys, numKeys)) { - LOGE("Verification failed\n"); - return INSTALL_CORRUPT; - } - // Update should take the rest of the progress bar. ui_print("Installing update...\n"); @@ -360,10 +348,25 @@ install_package(const char *root_path) } LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE); + // Give verification half the progress bar... + ui_print("Verifying update package...\n"); + ui_show_progress( + VERIFICATION_PROGRESS_FRACTION, + VERIFICATION_PROGRESS_TIME); + + int err; + err = verify_file(path, loadedKeys, numKeys); + free(loadedKeys); + LOGI("verify_file returned %d\n", err); + if (err != VERIFY_SUCCESS) { + LOGE("signature verification failed\n"); + return INSTALL_CORRUPT; + } + /* Try to open the package. */ ZipArchive zip; - int err = mzOpenZipArchive(path, &zip); + err = mzOpenZipArchive(path, &zip); if (err != 0) { LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad"); return INSTALL_CORRUPT; @@ -371,8 +374,7 @@ install_package(const char *root_path) /* Verify and install the contents of the package. */ - int status = handle_update_package(path, &zip, loadedKeys, numKeys); + int status = handle_update_package(path, &zip); mzCloseZipArchive(&zip); - free(loadedKeys); return status; } diff --git a/minui/graphics.c b/minui/graphics.c index 06c5fdfcd..adbfc09da 100644 --- a/minui/graphics.c +++ b/minui/graphics.c @@ -115,6 +115,7 @@ static void set_active_framebuffer(unsigned n) if (n > 1) return; vi.yres_virtual = vi.yres * 2; vi.yoffset = n * vi.yres; + vi.bits_per_pixel = 16; if (ioctl(gr_fb_fd, FBIOPUT_VSCREENINFO, &vi) < 0) { perror("active fb swap failed"); } diff --git a/minui/minui.h b/minui/minui.h index 80b47a47f..567d42157 100644 --- a/minui/minui.h +++ b/minui/minui.h @@ -41,22 +41,6 @@ unsigned int gr_get_height(gr_surface surface); // see http://www.mjmwired.net/kernel/Documentation/input/ for info. struct input_event; -// Dream-specific key codes -#define KEY_DREAM_HOME 102 // = KEY_HOME -#define KEY_DREAM_RED 107 // = KEY_END -#define KEY_DREAM_VOLUMEDOWN 114 // = KEY_VOLUMEDOWN -#define KEY_DREAM_VOLUMEUP 115 // = KEY_VOLUMEUP -#define KEY_DREAM_SYM 127 // = KEY_COMPOSE -#define KEY_DREAM_MENU 139 // = KEY_MENU -#define KEY_DREAM_BACK 158 // = KEY_BACK -#define KEY_DREAM_FOCUS 211 // = KEY_HP (light touch on camera) -#define KEY_DREAM_CAMERA 212 // = KEY_CAMERA -#define KEY_DREAM_AT 215 // = KEY_EMAIL -#define KEY_DREAM_GREEN 231 -#define KEY_DREAM_FATTOUCH 258 // = BTN_2 ??? -#define KEY_DREAM_BALL 272 // = BTN_MOUSE -#define KEY_DREAM_TOUCH 330 // = BTN_TOUCH - int ev_init(void); void ev_exit(void); int ev_get(struct input_event *ev, unsigned dont_wait); diff --git a/recovery.c b/recovery.c index 0ff5d94d0..33cbc13d8 100644 --- a/recovery.c +++ b/recovery.c @@ -36,6 +36,7 @@ #include "minui/minui.h" #include "minzip/DirUtil.h" #include "roots.h" +#include "recovery_ui.h" static const struct option OPTIONS[] = { { "send_intent", required_argument, NULL, 's' }, @@ -206,6 +207,15 @@ get_args(int *argc, char ***argv) { set_bootloader_message(&boot); } +static void +set_sdcard_update_bootloader_message() +{ + struct bootloader_message boot; + memset(&boot, 0, sizeof(boot)); + strlcpy(boot.command, "boot-recovery", sizeof(boot.command)); + strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery)); + set_bootloader_message(&boot); +} // clear the recovery command and prepare to boot a (hopefully working) system, // copy our log file to cache as well (for the system to read), and @@ -272,26 +282,25 @@ erase_root(const char *root) static void prompt_and_wait() { - char* headers[] = { "Android system recovery <" + char* title[] = { "Android system recovery <" EXPAND(RECOVERY_API_VERSION) "e>", - "", - "Use trackball to highlight;", - "click to select.", - "", - NULL }; - - // these constants correspond to elements of the items[] list. -#define ITEM_REBOOT 0 -#define ITEM_APPLY_SDCARD 1 -#define ITEM_WIPE_DATA 2 -#define ITEM_WIPE_CACHE 3 - char* items[] = { "reboot system now [Home+Back]", - "apply sdcard:update.zip [Alt+S]", - "wipe data/factory reset [Alt+W]", - "wipe cache partition", + "", NULL }; - ui_start_menu(headers, items); + // count the number of lines in our title, plus the + // product-provided headers. + int count = 0; + char** p; + for (p = title; *p; ++p, ++count); + for (p = MENU_HEADERS; *p; ++p, ++count); + + char** headers = malloc((count+1) * sizeof(char*)); + char** h = headers; + for (p = title; *p; ++p, ++h) *h = *p; + for (p = MENU_HEADERS; *p; ++p, ++h) *h = *p; + *h = NULL; + + ui_start_menu(headers, MENU_ITEMS); int selected = 0; int chosen_item = -1; @@ -299,29 +308,28 @@ prompt_and_wait() ui_reset_progress(); for (;;) { int key = ui_wait_key(); - int alt = ui_key_pressed(KEY_LEFTALT) || ui_key_pressed(KEY_RIGHTALT); int visible = ui_text_visible(); - if (key == KEY_DREAM_BACK && ui_key_pressed(KEY_DREAM_HOME)) { - // Wait for the keys to be released, to avoid triggering - // special boot modes (like coming back into recovery!). - while (ui_key_pressed(KEY_DREAM_BACK) || - ui_key_pressed(KEY_DREAM_HOME)) { - usleep(1000); + int action = device_handle_key(key, visible); + + if (action < 0) { + switch (action) { + case HIGHLIGHT_UP: + --selected; + selected = ui_menu_select(selected); + break; + case HIGHLIGHT_DOWN: + ++selected; + selected = ui_menu_select(selected); + break; + case SELECT_ITEM: + chosen_item = selected; + break; + case NO_ACTION: + break; } - chosen_item = ITEM_REBOOT; - } else if (alt && key == KEY_W) { - chosen_item = ITEM_WIPE_DATA; - } else if (alt && key == KEY_S) { - chosen_item = ITEM_APPLY_SDCARD; - } else if ((key == KEY_DOWN || key == KEY_VOLUMEDOWN) && visible) { - ++selected; - selected = ui_menu_select(selected); - } else if ((key == KEY_UP || key == KEY_VOLUMEUP) && visible) { - --selected; - selected = ui_menu_select(selected); - } else if (key == BTN_MOUSE && visible) { - chosen_item = selected; + } else { + chosen_item = action; } if (chosen_item >= 0) { @@ -329,12 +337,18 @@ prompt_and_wait() // on the screen. ui_end_menu(); + // device-specific code may take some action here. It may + // return one of the core actions handled in the switch + // statement below. + chosen_item = device_perform_action(chosen_item); + switch (chosen_item) { case ITEM_REBOOT: return; case ITEM_WIPE_DATA: ui_print("\n-- Wiping data...\n"); + device_wipe_data(); erase_root("DATA:"); erase_root("CACHE:"); ui_print("Data wipe complete.\n"); @@ -350,6 +364,7 @@ prompt_and_wait() case ITEM_APPLY_SDCARD: ui_print("\n-- Install from sdcard...\n"); + set_sdcard_update_bootloader_message(); int status = install_package(SDCARD_PACKAGE_FILE); if (status != INSTALL_SUCCESS) { ui_set_background(BACKGROUND_ICON_ERROR); @@ -358,8 +373,8 @@ prompt_and_wait() return; // reboot if logs aren't visible } else { if (firmware_update_pending()) { - ui_print("\nReboot via home+back or menu\n" - "to complete installation.\n"); + ui_print("\nReboot via menu to complete\n" + "installation.\n"); } else { ui_print("\nInstall from sdcard complete.\n"); } @@ -369,7 +384,7 @@ prompt_and_wait() // if we didn't return from this function to reboot, show // the menu again. - ui_start_menu(headers, items); + ui_start_menu(headers, MENU_ITEMS); selected = 0; chosen_item = -1; @@ -435,10 +450,14 @@ main(int argc, char **argv) if (update_package != NULL) { status = install_package(update_package); if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n"); - } else if (wipe_data || wipe_cache) { - if (wipe_data && erase_root("DATA:")) status = INSTALL_ERROR; + } else if (wipe_data) { + if (device_wipe_data()) status = INSTALL_ERROR; + if (erase_root("DATA:")) status = INSTALL_ERROR; if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR; if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n"); + } else if (wipe_cache) { + if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR; + if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n"); } else { status = INSTALL_ERROR; // No command specified } diff --git a/recovery_ui.h b/recovery_ui.h new file mode 100644 index 000000000..8818ef303 --- /dev/null +++ b/recovery_ui.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2009 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 _RECOVERY_UI_H +#define _RECOVERY_UI_H + +// Called in the input thread when a new key (key_code) is pressed. +// *key_pressed is an array of KEY_MAX+1 bytes indicating which other +// keys are already pressed. Return true if the text display should +// be toggled. +extern int device_toggle_display(volatile char* key_pressed, int key_code); + +// Called in the input thread when a new key (key_code) is pressed. +// *key_pressed is an array of KEY_MAX+1 bytes indicating which other +// keys are already pressed. Return true if the device should reboot +// immediately. +extern int device_reboot_now(volatile char* key_pressed, int key_code); + +// Called from the main thread when recovery is waiting for input and +// a key is pressed. key is the code of the key pressed; visible is +// true if the recovery menu is being shown. Implementations can call +// ui_key_pressed() to discover if other keys are being held down. +// Return one of the defined constants below in order to: +// +// - move the menu highlight (HIGHLIGHT_*) +// - invoke the highlighted item (SELECT_ITEM) +// - do nothing (NO_ACTION) +// - invoke a specific action (a menu position: any non-negative number) +extern int device_handle_key(int key, int visible); + +// Perform a recovery action selected from the menu. 'which' will be +// the item number of the selected menu item, or a non-negative number +// returned from device_handle_key(). The menu will be hidden when +// this is called; implementations can call ui_print() to print +// information to the screen. +extern int device_perform_action(int which); + +// Called when we do a wipe data/factory reset operation (either via a +// reboot from the main system with the --wipe_data flag, or when the +// user boots into recovery manually and selects the option from the +// menu.) Can perform whatever device-specific wiping actions are +// needed. Return 0 on success. The userdata and cache partitions +// are erased after this returns (whether it returns success or not). +int device_wipe_data(); + +#define NO_ACTION -1 + +#define HIGHLIGHT_UP -2 +#define HIGHLIGHT_DOWN -3 +#define SELECT_ITEM -4 + +#define ITEM_REBOOT 0 +#define ITEM_APPLY_SDCARD 1 +#define ITEM_WIPE_DATA 2 +#define ITEM_WIPE_CACHE 3 + +// Header text to display above the main menu. +extern char* MENU_HEADERS[]; + +// Text of menu items. +extern char* MENU_ITEMS[]; + +#endif diff --git a/res/images/icon_error.png b/res/images/icon_error.png Binary files differindex 7064c2e23..6cb71c0b3 100644 --- a/res/images/icon_error.png +++ b/res/images/icon_error.png diff --git a/res/images/icon_firmware_install.png b/res/images/icon_firmware_install.png Binary files differindex ee2afac5d..8bfe77589 100644 --- a/res/images/icon_firmware_install.png +++ b/res/images/icon_firmware_install.png diff --git a/res/images/icon_installing.png b/res/images/icon_installing.png Binary files differindex f24f2e33f..1aeb9d959 100644 --- a/res/images/icon_installing.png +++ b/res/images/icon_installing.png @@ -52,6 +52,7 @@ static RootInfo g_roots[] = { { "RECOVERY:", g_mtd_device, NULL, "recovery", "/", g_raw }, { "SDCARD:", "/dev/block/mmcblk0p1", "/dev/block/mmcblk0", NULL, "/sdcard", "vfat" }, { "SYSTEM:", g_mtd_device, NULL, "system", "/system", "yaffs2" }, + { "MBM:", g_mtd_device, NULL, "mbm", NULL, g_raw }, { "TMP:", NULL, NULL, NULL, "/tmp", NULL }, }; #define NUM_ROOTS (sizeof(g_roots) / sizeof(g_roots[0])) @@ -27,6 +27,7 @@ #include "common.h" #include "minui/minui.h" +#include "recovery_ui.h" #define MAX_COLS 64 #define MAX_ROWS 32 @@ -307,20 +308,14 @@ static void *input_thread(void *cookie) } pthread_mutex_unlock(&key_queue_mutex); - // Alt+L or Home+End: toggle log display - int alt = key_pressed[KEY_LEFTALT] || key_pressed[KEY_RIGHTALT]; - if ((alt && ev.code == KEY_L && ev.value > 0) || - (key_pressed[KEY_HOME] && ev.code == KEY_END && ev.value > 0)) { + if (ev.value > 0 && device_toggle_display(key_pressed, ev.code)) { pthread_mutex_lock(&gUpdateMutex); show_text = !show_text; update_screen_locked(); pthread_mutex_unlock(&gUpdateMutex); } - // Green+Menu+Red: reboot immediately - if (ev.code == KEY_DREAM_RED && - key_pressed[KEY_DREAM_MENU] && - key_pressed[KEY_DREAM_GREEN]) { + if (ev.value > 0 && device_reboot_now(key_pressed, ev.code)) { reboot(RB_AUTOBOOT); } } diff --git a/updater/Android.mk b/updater/Android.mk index 897b9d74c..d4a4e332d 100644 --- a/updater/Android.mk +++ b/updater/Android.mk @@ -18,11 +18,47 @@ LOCAL_MODULE_TAGS := eng LOCAL_SRC_FILES := $(updater_src_files) -LOCAL_STATIC_LIBRARIES := libapplypatch libedify libmtdutils libminzip libz +LOCAL_STATIC_LIBRARIES := $(TARGET_RECOVERY_UPDATER_LIBS) $(TARGET_RECOVERY_UPDATER_EXTRA_LIBS) +LOCAL_STATIC_LIBRARIES += libapplypatch libedify libmtdutils libminzip libz LOCAL_STATIC_LIBRARIES += libmincrypt libbz LOCAL_STATIC_LIBRARIES += libcutils libstdc++ libc LOCAL_C_INCLUDES += $(LOCAL_PATH)/.. +# Each library in TARGET_RECOVERY_UPDATER_LIBS should have a function +# named "Register_<libname>()". Here we emit a little C function that +# gets #included by updater.c. It calls all those registration +# functions. + +# Devices can also add libraries to TARGET_RECOVERY_UPDATER_EXTRA_LIBS. +# These libs are also linked in with updater, but we don't try to call +# any sort of registration function for these. Use this variable for +# any subsidiary static libraries required for your registered +# extension libs. + +inc := $(call intermediates-dir-for,PACKAGING,updater_extensions)/register.inc + +# During the first pass of reading the makefiles, we dump the list of +# extension libs to a temp file, then copy that to the ".list" file if +# it is different than the existing .list (if any). The register.inc +# file then uses the .list as a prerequisite, so it is only rebuilt +# (and updater.o recompiled) when the list of extension libs changes. + +junk := $(shell mkdir -p $(dir $(inc));\ + echo $(TARGET_RECOVERY_UPDATER_LIBS) > $(inc).temp;\ + diff -q $(inc).temp $(inc).list || cp -f $(inc).temp $(inc).list) + +$(inc) : libs := $(TARGET_RECOVERY_UPDATER_LIBS) +$(inc) : $(inc).list + $(hide) mkdir -p $(dir $@) + $(hide) echo "" > $@ + $(hide) $(foreach lib,$(libs),echo "extern void Register_$(lib)(void);" >> $@) + $(hide) echo "void RegisterDeviceExtensions() {" >> $@ + $(hide) $(foreach lib,$(libs),echo " Register_$(lib)();" >> $@) + $(hide) echo "}" >> $@ + +$(call intermediates-dir-for,EXECUTABLES,updater)/updater.o : $(inc) +LOCAL_C_INCLUDES += $(dir $(inc)) + LOCAL_MODULE := updater LOCAL_FORCE_STATIC_EXECUTABLE := true diff --git a/updater/updater.c b/updater/updater.c index 31d93ae96..1aa277c7f 100644 --- a/updater/updater.c +++ b/updater/updater.c @@ -23,6 +23,11 @@ #include "install.h" #include "minzip/Zip.h" +// Generated by the makefile, this function defines the +// RegisterDeviceExtensions() function, which calls all the +// registration functions for device-specific extensions. +#include "register.inc" + // Where in the package we expect to find the edify script to execute. // (Note it's "updateR-script", not the older "update-script".) #define SCRIPT_NAME "META-INF/com/google/android/updater-script" @@ -76,6 +81,7 @@ int main(int argc, char** argv) { RegisterBuiltins(); RegisterInstallFunctions(); + RegisterDeviceExtensions(); FinishRegistration(); // Parse the script. diff --git a/verifier.c b/verifier.c index 1180ae8d0..f2491a14a 100644 --- a/verifier.c +++ b/verifier.c @@ -17,345 +17,168 @@ #include "common.h" #include "verifier.h" -#include "minzip/Zip.h" #include "mincrypt/rsa.h" #include "mincrypt/sha.h" -#include <netinet/in.h> /* required for resolv.h */ -#include <resolv.h> /* for base64 codec */ #include <string.h> - -/* Return an allocated buffer with the contents of a zip file entry. */ -static char *slurpEntry(const ZipArchive *pArchive, const ZipEntry *pEntry) { - if (!mzIsZipEntryIntact(pArchive, pEntry)) { - UnterminatedString fn = mzGetZipEntryFileName(pEntry); - LOGE("Invalid %.*s\n", fn.len, fn.str); - return NULL; +#include <stdio.h> +#include <errno.h> + +// Look for an RSA signature embedded in the .ZIP file comment given +// the path to the zip. Verify it matches one of the given public +// keys. +// +// Return VERIFY_SUCCESS, VERIFY_FAILURE (if any error is encountered +// or no key matches the signature). + +int verify_file(const char* path, const RSAPublicKey *pKeys, unsigned int numKeys) { + ui_set_progress(0.0); + + FILE* f = fopen(path, "rb"); + if (f == NULL) { + LOGE("failed to open %s (%s)\n", path, strerror(errno)); + return VERIFY_FAILURE; } - int len = mzGetZipEntryUncompLen(pEntry); - char *buf = malloc(len + 1); - if (buf == NULL) { - UnterminatedString fn = mzGetZipEntryFileName(pEntry); - LOGE("Can't allocate %d bytes for %.*s\n", len, fn.len, fn.str); - return NULL; + // An archive with a whole-file signature will end in six bytes: + // + // $ff $ff (2-byte comment size) (2-byte signature start) + // + // (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 + + if (fseek(f, -FOOTER_SIZE, SEEK_END) != 0) { + LOGE("failed to seek in %s (%s)\n", path, strerror(errno)); + fclose(f); + return VERIFY_FAILURE; } - if (!mzReadZipEntry(pArchive, pEntry, buf, len)) { - UnterminatedString fn = mzGetZipEntryFileName(pEntry); - LOGE("Can't read %.*s\n", fn.len, fn.str); - free(buf); - return NULL; + unsigned char footer[FOOTER_SIZE]; + if (fread(footer, 1, FOOTER_SIZE, f) != FOOTER_SIZE) { + LOGE("failed to read footer from %s (%s)\n", path, strerror(errno)); + fclose(f); + return VERIFY_FAILURE; } - buf[len] = '\0'; - return buf; -} - - -struct DigestContext { - SHA_CTX digest; - unsigned *doneBytes; - unsigned totalBytes; -}; - - -/* mzProcessZipEntryContents callback to update an SHA-1 hash context. */ -static bool updateHash(const unsigned char *data, int dataLen, void *cookie) { - struct DigestContext *context = (struct DigestContext *) cookie; - SHA_update(&context->digest, data, dataLen); - if (context->doneBytes != NULL) { - *context->doneBytes += dataLen; - if (context->totalBytes > 0) { - ui_set_progress(*context->doneBytes * 1.0 / context->totalBytes); - } + if (footer[2] != 0xff || footer[3] != 0xff) { + fclose(f); + return VERIFY_FAILURE; } - return true; -} + int comment_size = footer[4] + (footer[5] << 8); + int signature_start = footer[0] + (footer[1] << 8); + LOGI("comment is %d bytes; signature %d bytes from end\n", + comment_size, signature_start); -/* Get the SHA-1 digest of a zip file entry. */ -static bool digestEntry(const ZipArchive *pArchive, const ZipEntry *pEntry, - unsigned *doneBytes, unsigned totalBytes, - uint8_t digest[SHA_DIGEST_SIZE]) { - struct DigestContext context; - SHA_init(&context.digest); - context.doneBytes = doneBytes; - context.totalBytes = totalBytes; - if (!mzProcessZipEntryContents(pArchive, pEntry, updateHash, &context)) { - UnterminatedString fn = mzGetZipEntryFileName(pEntry); - LOGE("Can't digest %.*s\n", fn.len, fn.str); - return false; + if (signature_start - FOOTER_SIZE < RSANUMBYTES) { + // "signature" block isn't big enough to contain an RSA block. + LOGE("signature is too short\n"); + fclose(f); + return VERIFY_FAILURE; } - memcpy(digest, SHA_final(&context.digest), SHA_DIGEST_SIZE); - -#ifdef LOG_VERBOSE - UnterminatedString fn = mzGetZipEntryFileName(pEntry); - char base64[SHA_DIGEST_SIZE * 3]; - b64_ntop(digest, SHA_DIGEST_SIZE, base64, sizeof(base64)); - LOGV("sha1(%.*s) = %s\n", fn.len, fn.str, base64); -#endif - - return true; -} - - -/* Find a /META-INF/xxx.SF signature file signed by a matching xxx.RSA file. */ -static const ZipEntry *verifySignature(const ZipArchive *pArchive, - const RSAPublicKey *pKeys, unsigned int numKeys) { - static const char prefix[] = "META-INF/"; - static const char rsa[] = ".RSA", sf[] = ".SF"; - - unsigned int i, j; - for (i = 0; i < mzZipEntryCount(pArchive); ++i) { - const ZipEntry *rsaEntry = mzGetZipEntryAt(pArchive, i); - UnterminatedString rsaName = mzGetZipEntryFileName(rsaEntry); - int rsaLen = mzGetZipEntryUncompLen(rsaEntry); - if (rsaLen >= RSANUMBYTES && rsaName.len > sizeof(prefix) && - !strncmp(rsaName.str, prefix, sizeof(prefix) - 1) && - !strncmp(rsaName.str + rsaName.len - sizeof(rsa) + 1, - rsa, sizeof(rsa) - 1)) { - char *sfName = malloc(rsaName.len - sizeof(rsa) + sizeof(sf) + 1); - if (sfName == NULL) { - LOGE("Can't allocate %d bytes for filename\n", rsaName.len); - continue; - } +#define EOCD_HEADER_SIZE 22 - /* Replace .RSA with .SF */ - strncpy(sfName, rsaName.str, rsaName.len - sizeof(rsa) + 1); - strcpy(sfName + rsaName.len - sizeof(rsa) + 1, sf); - const ZipEntry *sfEntry = mzFindZipEntry(pArchive, sfName); + // The end-of-central-directory record is 22 bytes plus any + // comment length. + size_t eocd_size = comment_size + EOCD_HEADER_SIZE; - if (sfEntry == NULL) { - LOGW("Missing signature file %s\n", sfName); - free(sfName); - continue; - } - - free(sfName); - - uint8_t sfDigest[SHA_DIGEST_SIZE]; - if (!digestEntry(pArchive, sfEntry, NULL, 0, sfDigest)) continue; - - char *rsaBuf = slurpEntry(pArchive, rsaEntry); - if (rsaBuf == NULL) continue; - - /* Try to verify the signature with all the keys. */ - uint8_t *sig = (uint8_t *) rsaBuf + rsaLen - RSANUMBYTES; - for (j = 0; j < numKeys; ++j) { - if (RSA_verify(&pKeys[j], sig, RSANUMBYTES, sfDigest)) { - free(rsaBuf); - LOGI("Verified %.*s\n", rsaName.len, rsaName.str); - return sfEntry; - } - } - - free(rsaBuf); - LOGW("Can't verify %.*s\n", rsaName.len, rsaName.str); - } + if (fseek(f, -eocd_size, SEEK_END) != 0) { + LOGE("failed to seek in %s (%s)\n", path, strerror(errno)); + fclose(f); + return VERIFY_FAILURE; } - LOGE("No signature (%d files)\n", mzZipEntryCount(pArchive)); - return NULL; -} - - -/* Verify /META-INF/MANIFEST.MF against the digest in a signature file. */ -static const ZipEntry *verifyManifest(const ZipArchive *pArchive, - const ZipEntry *sfEntry) { - static const char prefix[] = "SHA1-Digest-Manifest: ", eol[] = "\r\n"; - uint8_t expected[SHA_DIGEST_SIZE + 3], actual[SHA_DIGEST_SIZE]; - - char *sfBuf = slurpEntry(pArchive, sfEntry); - if (sfBuf == NULL) return NULL; - - char *line, *save; - for (line = strtok_r(sfBuf, eol, &save); line != NULL; - line = strtok_r(NULL, eol, &save)) { - if (!strncasecmp(prefix, line, sizeof(prefix) - 1)) { - UnterminatedString fn = mzGetZipEntryFileName(sfEntry); - const char *digest = line + sizeof(prefix) - 1; - int n = b64_pton(digest, expected, sizeof(expected)); - if (n != SHA_DIGEST_SIZE) { - LOGE("Invalid base64 in %.*s: %s (%d)\n", - fn.len, fn.str, digest, n); - line = NULL; - } - break; - } + // 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 = ftell(f) + EOCD_HEADER_SIZE - 2; + + unsigned char* eocd = malloc(eocd_size); + if (eocd == NULL) { + LOGE("malloc for EOCD record failed\n"); + fclose(f); + return VERIFY_FAILURE; } - - free(sfBuf); - - if (line == NULL) { - LOGE("No digest manifest in signature file\n"); - return false; + if (fread(eocd, 1, eocd_size, f) != eocd_size) { + LOGE("failed to read eocd from %s (%s)\n", path, strerror(errno)); + fclose(f); + return VERIFY_FAILURE; } - const char *mfName = "META-INF/MANIFEST.MF"; - const ZipEntry *mfEntry = mzFindZipEntry(pArchive, mfName); - if (mfEntry == NULL) { - LOGE("No manifest file %s\n", mfName); - return NULL; + // 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) { + LOGE("signature length doesn't match EOCD marker\n"); + fclose(f); + return VERIFY_FAILURE; } - if (!digestEntry(pArchive, mfEntry, NULL, 0, actual)) return NULL; - if (memcmp(expected, actual, SHA_DIGEST_SIZE)) { - UnterminatedString fn = mzGetZipEntryFileName(sfEntry); - LOGE("Wrong digest for %s in %.*s\n", mfName, fn.len, fn.str); - return NULL; + int i; + for (i = 4; i < eocd_size-3; ++i) { + if (eocd[i ] == 0x50 && eocd[i+1] == 0x4b && + eocd[i+2] == 0x05 && eocd[i+1] == 0x06) { + // if the sequence $50 $4b $05 $06 appears anywhere after + // the real one, minzip will find the later (wrong) one, + // which could be exploitable. Fail verification if + // this sequence occurs anywhere after the real one. + LOGE("EOCD marker occurs after start of EOCD\n"); + fclose(f); + return VERIFY_FAILURE; + } } - LOGI("Verified %s\n", mfName); - return mfEntry; -} - - -/* Verify all the files in a Zip archive against the manifest. */ -static bool verifyArchive(const ZipArchive *pArchive, const ZipEntry *mfEntry) { - static const char namePrefix[] = "Name: "; - static const char contPrefix[] = " "; // Continuation of the filename - static const char digestPrefix[] = "SHA1-Digest: "; - static const char eol[] = "\r\n"; +#define BUFFER_SIZE 4096 - char *mfBuf = slurpEntry(pArchive, mfEntry); - if (mfBuf == NULL) return false; - - /* we're using calloc() here, so the initial state of the array is false */ - bool *unverified = (bool *) calloc(mzZipEntryCount(pArchive), sizeof(bool)); - if (unverified == NULL) { - LOGE("Can't allocate valid flags\n"); - free(mfBuf); - return false; + SHA_CTX ctx; + SHA_init(&ctx); + unsigned char* buffer = malloc(BUFFER_SIZE); + if (buffer == NULL) { + LOGE("failed to alloc memory for sha1 buffer\n"); + fclose(f); + return VERIFY_FAILURE; } - /* Mark all the files in the archive that need to be verified. - * As we scan the manifest and check signatures, we'll unset these flags. - * At the end, we'll make sure that all the flags are unset. - */ - - unsigned i, totalBytes = 0; - for (i = 0; i < mzZipEntryCount(pArchive); ++i) { - const ZipEntry *entry = mzGetZipEntryAt(pArchive, i); - UnterminatedString fn = mzGetZipEntryFileName(entry); - int len = mzGetZipEntryUncompLen(entry); - - // Don't validate: directories, the manifest, *.RSA, and *.SF. - - if (entry == mfEntry) { - LOGV("Skipping manifest %.*s\n", fn.len, fn.str); - } else if (fn.len > 0 && fn.str[fn.len-1] == '/' && len == 0) { - LOGV("Skipping directory %.*s\n", fn.len, fn.str); - } else if (!strncasecmp(fn.str, "META-INF/", 9) && ( - !strncasecmp(fn.str + fn.len - 4, ".RSA", 4) || - !strncasecmp(fn.str + fn.len - 3, ".SF", 3))) { - LOGV("Skipping signature %.*s\n", fn.len, fn.str); - } else { - unverified[i] = true; - totalBytes += len; + double frac = -1.0; + size_t so_far = 0; + fseek(f, 0, SEEK_SET); + while (so_far < signed_len) { + int size = BUFFER_SIZE; + if (signed_len - so_far < size) size = signed_len - so_far; + if (fread(buffer, 1, size, f) != size) { + LOGE("failed to read data from %s (%s)\n", path, strerror(errno)); + fclose(f); + return VERIFY_FAILURE; } - } - - unsigned doneBytes = 0; - char *line, *save, *name = NULL; - for (line = strtok_r(mfBuf, eol, &save); line != NULL; - line = strtok_r(NULL, eol, &save)) { - if (!strncasecmp(line, namePrefix, sizeof(namePrefix) - 1)) { - // "Name:" introducing a new stanza - if (name != NULL) { - LOGE("No digest:\n %s\n", name); - break; - } - - name = strdup(line + sizeof(namePrefix) - 1); - if (name == NULL) { - LOGE("Can't copy filename in %s\n", line); - break; - } - } else if (!strncasecmp(line, contPrefix, sizeof(contPrefix) - 1)) { - // Continuing a long name (nothing else should be continued) - const char *tail = line + sizeof(contPrefix) - 1; - if (name == NULL) { - LOGE("Unexpected continuation:\n %s\n", tail); - } - - char *concat; - if (asprintf(&concat, "%s%s", name, tail) < 0) { - LOGE("Can't append continuation %s\n", tail); - break; - } - free(name); - name = concat; - } else if (!strncasecmp(line, digestPrefix, sizeof(digestPrefix) - 1)) { - // "Digest:" supplying a hash code for the current stanza - const char *base64 = line + sizeof(digestPrefix) - 1; - if (name == NULL) { - LOGE("Unexpected digest:\n %s\n", base64); - break; - } - - const ZipEntry *entry = mzFindZipEntry(pArchive, name); - if (entry == NULL) { - LOGE("Missing file:\n %s\n", name); - break; - } - if (!mzIsZipEntryIntact(pArchive, entry)) { - LOGE("Corrupt file:\n %s\n", name); - break; - } - if (!unverified[mzGetZipEntryIndex(pArchive, entry)]) { - LOGE("Unexpected file:\n %s\n", name); - break; - } - - uint8_t expected[SHA_DIGEST_SIZE + 3], actual[SHA_DIGEST_SIZE]; - int n = b64_pton(base64, expected, sizeof(expected)); - if (n != SHA_DIGEST_SIZE) { - LOGE("Invalid base64:\n %s\n %s\n", name, base64); - break; - } - - if (!digestEntry(pArchive, entry, &doneBytes, totalBytes, actual) || - memcmp(expected, actual, SHA_DIGEST_SIZE) != 0) { - LOGE("Wrong digest:\n %s\n", name); - break; - } - - LOGI("Verified %s\n", name); - unverified[mzGetZipEntryIndex(pArchive, entry)] = false; - free(name); - name = NULL; + SHA_update(&ctx, buffer, size); + so_far += size; + double f = so_far / (double)signed_len; + if (f > frac + 0.02 || size == so_far) { + ui_set_progress(f); + frac = f; } } - - if (name != NULL) free(name); - free(mfBuf); - - for (i = 0; i < mzZipEntryCount(pArchive) && !unverified[i]; ++i) ; - free(unverified); - - // This means we didn't get to the end of the manifest successfully. - if (line != NULL) return false; - - if (i < mzZipEntryCount(pArchive)) { - const ZipEntry *entry = mzGetZipEntryAt(pArchive, i); - UnterminatedString fn = mzGetZipEntryFileName(entry); - LOGE("No digest for %.*s\n", fn.len, fn.str); - return false; + fclose(f); + free(buffer); + + const uint8_t* sha1 = SHA_final(&ctx); + for (i = 0; i < numKeys; ++i) { + // The 6 bytes is the "$ff $ff (signature_start) (comment_size)" that + // the signing tool appends after the signature itself. + if (RSA_verify(pKeys+i, eocd + eocd_size - 6 - RSANUMBYTES, + RSANUMBYTES, sha1)) { + LOGI("whole-file signature verified\n"); + free(eocd); + return VERIFY_SUCCESS; + } } - - return true; -} - - -bool verify_jar_signature(const ZipArchive *pArchive, - const RSAPublicKey *pKeys, int numKeys) { - const ZipEntry *sfEntry = verifySignature(pArchive, pKeys, numKeys); - if (sfEntry == NULL) return false; - - const ZipEntry *mfEntry = verifyManifest(pArchive, sfEntry); - if (mfEntry == NULL) return false; - - return verifyArchive(pArchive, mfEntry); + free(eocd); + LOGE("failed to verify whole-file signature\n"); + return VERIFY_FAILURE; } diff --git a/verifier.h b/verifier.h index d784dce4c..1bdfca6dd 100644 --- a/verifier.h +++ b/verifier.h @@ -17,14 +17,14 @@ #ifndef _RECOVERY_VERIFIER_H #define _RECOVERY_VERIFIER_H -#include "minzip/Zip.h" #include "mincrypt/rsa.h" -/* - * Check the digital signature (as applied by jarsigner) on a Zip archive. - * Every file in the archive must be signed by one of the supplied RSA keys. +/* Look in the file for a signature footer, and verify that it + * matches one of the given keys. Return one of the constants below. */ -bool verify_jar_signature(const ZipArchive *pArchive, - const RSAPublicKey *pKeys, int numKeys); +int verify_file(const char* path, const RSAPublicKey *pKeys, unsigned int numKeys); + +#define VERIFY_SUCCESS 0 +#define VERIFY_FAILURE 1 #endif /* _RECOVERY_VERIFIER_H */ |