OperationResult implements Parcelable interface
am: 9ec9270dbb

Change-Id: I707158d096b064dd85a7e07efbb1456eae0a00f5
diff --git a/keystore-engine/Android.mk b/keystore-engine/Android.mk
index 1f5d903..b4ba269 100644
--- a/keystore-engine/Android.mk
+++ b/keystore-engine/Android.mk
@@ -16,33 +16,10 @@
 
 include $(CLEAR_VARS)
 
+LOCAL_MODULE := libkeystore-engine
 
-ifneq (,$(wildcard $(TOP)/external/boringssl/flavor.mk))
-	include $(TOP)/external/boringssl/flavor.mk
-else
-	include $(TOP)/external/openssl/flavor.mk
-endif
-ifeq ($(OPENSSL_FLAVOR),BoringSSL)
-  LOCAL_MODULE := libkeystore-engine
-
-  LOCAL_SRC_FILES := \
+LOCAL_SRC_FILES := \
 	android_engine.cpp
-else
-  LOCAL_MODULE := libkeystore
-
-  LOCAL_MODULE_RELATIVE_PATH := ssl/engines
-
-  LOCAL_SRC_FILES := \
-	eng_keystore.cpp \
-	keyhandle.cpp \
-	ecdsa_meth.cpp \
-	dsa_meth.cpp \
-	rsa_meth.cpp
-
-  LOCAL_C_INCLUDES += \
-	external/openssl/include \
-	external/openssl
-endif
 
 LOCAL_MODULE_TAGS := optional
 LOCAL_CFLAGS := -fvisibility=hidden -Wall -Werror
diff --git a/keystore-engine/dsa_meth.cpp b/keystore-engine/dsa_meth.cpp
deleted file mode 100644
index 3788364..0000000
--- a/keystore-engine/dsa_meth.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include <UniquePtr.h>
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "OpenSSL-keystore-dsa"
-#include <cutils/log.h>
-
-#include <binder/IServiceManager.h>
-#include <keystore/IKeystoreService.h>
-
-#include <openssl/dsa.h>
-#include <openssl/engine.h>
-
-#include "methods.h"
-
-
-using namespace android;
-
-struct DSA_SIG_Delete {
-    void operator()(DSA_SIG* p) const {
-        DSA_SIG_free(p);
-    }
-};
-typedef UniquePtr<DSA_SIG, struct DSA_SIG_Delete> Unique_DSA_SIG;
-
-static DSA_SIG* keystore_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) {
-    ALOGV("keystore_dsa_do_sign(%p, %d, %p)", dgst, dlen, dsa);
-
-    uint8_t* key_id = reinterpret_cast<uint8_t*>(DSA_get_ex_data(dsa, dsa_key_handle));
-    if (key_id == NULL) {
-        ALOGE("key had no key_id!");
-        return 0;
-    }
-
-    sp<IServiceManager> sm = defaultServiceManager();
-    sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
-    sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
-
-    if (service == NULL) {
-        ALOGE("could not contact keystore");
-        return 0;
-    }
-
-    int num = DSA_size(dsa);
-
-    uint8_t* reply = NULL;
-    size_t replyLen;
-    int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), dgst,
-            dlen, &reply, &replyLen);
-    if (ret < 0) {
-        ALOGW("There was an error during dsa_do_sign: could not connect");
-        return 0;
-    } else if (ret != 0) {
-        ALOGW("Error during sign from keystore: %d", ret);
-        return 0;
-    } else if (replyLen <= 0) {
-        ALOGW("No valid signature returned");
-        return 0;
-    } else if (replyLen > (size_t) num) {
-        ALOGW("Signature is too large");
-        return 0;
-    }
-
-    Unique_DSA_SIG dsa_sig(d2i_DSA_SIG(NULL,
-            const_cast<const unsigned char**>(reinterpret_cast<unsigned char**>(&reply)),
-            replyLen));
-    if (dsa_sig.get() == NULL) {
-        ALOGW("conversion from DER to DSA_SIG failed");
-        return 0;
-    }
-
-    ALOGV("keystore_dsa_do_sign(%p, %d, %p) => returning %p len %zu", dgst, dlen, dsa,
-            dsa_sig.get(), replyLen);
-    return dsa_sig.release();
-}
-
-static DSA_METHOD keystore_dsa_meth = {
-        kKeystoreEngineId, /* name */
-        keystore_dsa_do_sign, /* dsa_do_sign */
-        NULL, /* dsa_sign_setup */
-        NULL, /* dsa_do_verify */
-        NULL, /* dsa_mod_exp */
-        NULL, /* bn_mod_exp */
-        NULL, /* init */
-        NULL, /* finish */
-        0, /* flags */
-        NULL, /* app_data */
-        NULL, /* dsa_paramgen */
-        NULL, /* dsa_keygen */
-};
-
-static int register_dsa_methods() {
-    const DSA_METHOD* dsa_meth = DSA_OpenSSL();
-
-    keystore_dsa_meth.dsa_do_verify = dsa_meth->dsa_do_verify;
-
-    return 1;
-}
-
-int dsa_pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) {
-    Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey));
-    if (!DSA_set_ex_data(dsa.get(), dsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) {
-        ALOGW("Could not set ex_data for loaded DSA key");
-        return 0;
-    }
-
-    DSA_set_method(dsa.get(), &keystore_dsa_meth);
-
-    /*
-     * "DSA_set_ENGINE()" should probably be an OpenSSL API. Since it isn't,
-     * and EVP_PKEY_free() calls ENGINE_finish(), we need to call ENGINE_init()
-     * here.
-     */
-    ENGINE_init(e);
-    dsa->engine = e;
-
-    return 1;
-}
-
-int dsa_register(ENGINE* e) {
-    if (!ENGINE_set_DSA(e, &keystore_dsa_meth)
-            || !register_dsa_methods()) {
-        ALOGE("Could not set up keystore DSA methods");
-        return 0;
-    }
-
-    return 1;
-}
diff --git a/keystore-engine/ecdsa_meth.cpp b/keystore-engine/ecdsa_meth.cpp
deleted file mode 100644
index 48f178d..0000000
--- a/keystore-engine/ecdsa_meth.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include <UniquePtr.h>
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "OpenSSL-keystore-ecdsa"
-#include <cutils/log.h>
-
-#include <binder/IServiceManager.h>
-#include <keystore/IKeystoreService.h>
-
-#include <openssl/ecdsa.h>
-#include <openssl/engine.h>
-
-// TODO replace this with real OpenSSL API when it exists
-#include "crypto/ec/ec_lcl.h"
-#include "crypto/ecdsa/ecs_locl.h"
-
-#include "methods.h"
-
-
-using namespace android;
-
-struct ECDSA_SIG_Delete {
-    void operator()(ECDSA_SIG* p) const {
-        ECDSA_SIG_free(p);
-    }
-};
-typedef UniquePtr<ECDSA_SIG, struct ECDSA_SIG_Delete> Unique_ECDSA_SIG;
-
-static ECDSA_SIG* keystore_ecdsa_do_sign(const unsigned char *dgst, int dlen,
-        const BIGNUM*, const BIGNUM*, EC_KEY *eckey) {
-    ALOGV("keystore_ecdsa_do_sign(%p, %d, %p)", dgst, dlen, eckey);
-
-    uint8_t* key_id = reinterpret_cast<uint8_t*>(EC_KEY_get_key_method_data(eckey,
-                ex_data_dup, ex_data_free, ex_data_clear_free));
-    if (key_id == NULL) {
-        ALOGE("key had no key_id!");
-        return 0;
-    }
-
-    sp<IServiceManager> sm = defaultServiceManager();
-    sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
-    sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
-
-    if (service == NULL) {
-        ALOGE("could not contact keystore");
-        return 0;
-    }
-
-    int num = ECDSA_size(eckey);
-
-    uint8_t* reply = NULL;
-    size_t replyLen;
-    int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), dgst,
-            dlen, &reply, &replyLen);
-    if (ret < 0) {
-        ALOGW("There was an error during dsa_do_sign: could not connect");
-        return 0;
-    } else if (ret != 0) {
-        ALOGW("Error during sign from keystore: %d", ret);
-        return 0;
-    } else if (replyLen <= 0) {
-        ALOGW("No valid signature returned");
-        return 0;
-    } else if (replyLen > (size_t) num) {
-        ALOGW("Signature is too large");
-        return 0;
-    }
-
-    Unique_ECDSA_SIG ecdsa_sig(d2i_ECDSA_SIG(NULL,
-            const_cast<const unsigned char**>(reinterpret_cast<unsigned char**>(&reply)),
-            replyLen));
-    if (ecdsa_sig.get() == NULL) {
-        ALOGW("conversion from DER to ECDSA_SIG failed");
-        return 0;
-    }
-
-    ALOGV("keystore_ecdsa_do_sign(%p, %d, %p) => returning %p len %zu", dgst, dlen, eckey,
-            ecdsa_sig.get(), replyLen);
-    return ecdsa_sig.release();
-}
-
-static ECDSA_METHOD keystore_ecdsa_meth = {
-        kKeystoreEngineId, /* name */
-        keystore_ecdsa_do_sign, /* ecdsa_do_sign */
-        NULL, /* ecdsa_sign_setup */
-        NULL, /* ecdsa_do_verify */
-        0, /* flags */
-        NULL, /* app_data */
-};
-
-static int register_ecdsa_methods() {
-    const ECDSA_METHOD* ecdsa_meth = ECDSA_OpenSSL();
-
-    keystore_ecdsa_meth.ecdsa_do_verify = ecdsa_meth->ecdsa_do_verify;
-
-    return 1;
-}
-
-int ecdsa_pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) {
-    Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
-    void* oldData = EC_KEY_insert_key_method_data(eckey.get(),
-            reinterpret_cast<void*>(strdup(key_id)), ex_data_dup, ex_data_free,
-            ex_data_clear_free);
-    if (oldData != NULL) {
-        free(oldData);
-    }
-
-    ECDSA_set_method(eckey.get(), &keystore_ecdsa_meth);
-
-    /*
-     * "ECDSA_set_ENGINE()" should probably be an OpenSSL API. Since it isn't,
-     * and EC_KEY_free() calls ENGINE_finish(), we need to call ENGINE_init()
-     * here.
-     */
-    ECDSA_DATA *ecdsa = ecdsa_check(eckey.get());
-    ENGINE_init(e);
-    ecdsa->engine = e;
-
-    return 1;
-}
-
-int ecdsa_register(ENGINE* e) {
-    if (!ENGINE_set_ECDSA(e, &keystore_ecdsa_meth)
-            || !register_ecdsa_methods()) {
-        ALOGE("Could not set up keystore ECDSA methods");
-        return 0;
-    }
-
-    return 1;
-}
diff --git a/keystore-engine/eng_keystore.cpp b/keystore-engine/eng_keystore.cpp
deleted file mode 100644
index 6feb0f9..0000000
--- a/keystore-engine/eng_keystore.cpp
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * Copyright 2012 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include <UniquePtr.h>
-
-#include <sys/socket.h>
-#include <stdarg.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <openssl/dsa.h>
-#include <openssl/engine.h>
-#include <openssl/ec.h>
-#include <openssl/evp.h>
-#include <openssl/objects.h>
-#include <openssl/rsa.h>
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "OpenSSL-keystore"
-#include <cutils/log.h>
-
-#include <binder/IServiceManager.h>
-#include <keystore/keystore.h>
-#include <keystore/IKeystoreService.h>
-
-#include "methods.h"
-
-using namespace android;
-
-#define DYNAMIC_ENGINE
-const char* kKeystoreEngineId = "keystore";
-static const char* kKeystoreEngineDesc = "Android keystore engine";
-
-
-/*
- * ex_data index for keystore's key alias.
- */
-int rsa_key_handle;
-int dsa_key_handle;
-
-
-/*
- * Only initialize the *_key_handle once.
- */
-static pthread_once_t key_handle_control = PTHREAD_ONCE_INIT;
-
-/**
- * Many OpenSSL APIs take ownership of an argument on success but don't free the argument
- * on failure. This means we need to tell our scoped pointers when we've transferred ownership,
- * without triggering a warning by not using the result of release().
- */
-#define OWNERSHIP_TRANSFERRED(obj) \
-    typeof (obj.release()) _dummy __attribute__((unused)) = obj.release()
-
-
-struct ENGINE_Delete {
-    void operator()(ENGINE* p) const {
-        ENGINE_free(p);
-    }
-};
-typedef UniquePtr<ENGINE, ENGINE_Delete> Unique_ENGINE;
-
-struct EVP_PKEY_Delete {
-    void operator()(EVP_PKEY* p) const {
-        EVP_PKEY_free(p);
-    }
-};
-typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
-
-/**
- * Called to initialize RSA's ex_data for the key_id handle. This should
- * only be called when protected by a lock.
- */
-static void init_key_handle() {
-    rsa_key_handle = RSA_get_ex_new_index(0, NULL, keyhandle_new, keyhandle_dup, keyhandle_free);
-    dsa_key_handle = DSA_get_ex_new_index(0, NULL, keyhandle_new, keyhandle_dup, keyhandle_free);
-}
-
-static EVP_PKEY* keystore_loadkey(ENGINE* e, const char* key_id, UI_METHOD* ui_method,
-        void* callback_data) {
-#if LOG_NDEBUG
-    (void)ui_method;
-    (void)callback_data;
-#else
-    ALOGV("keystore_loadkey(%p, \"%s\", %p, %p)", e, key_id, ui_method, callback_data);
-#endif
-
-    sp<IServiceManager> sm = defaultServiceManager();
-    sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
-    sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
-
-    if (service == NULL) {
-        ALOGE("could not contact keystore");
-        return 0;
-    }
-
-    uint8_t *pubkey = NULL;
-    size_t pubkeyLen;
-    int32_t ret = service->get_pubkey(String16(key_id), &pubkey, &pubkeyLen);
-    if (ret < 0) {
-        ALOGW("could not contact keystore");
-        free(pubkey);
-        return NULL;
-    } else if (ret != 0) {
-        ALOGW("keystore reports error: %d", ret);
-        free(pubkey);
-        return NULL;
-    }
-
-    const unsigned char* tmp = reinterpret_cast<const unsigned char*>(pubkey);
-    Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, pubkeyLen));
-    free(pubkey);
-    if (pkey.get() == NULL) {
-        ALOGW("Cannot convert pubkey");
-        return NULL;
-    }
-
-    switch (EVP_PKEY_type(pkey->type)) {
-    case EVP_PKEY_DSA: {
-        dsa_pkey_setup(e, pkey.get(), key_id);
-        break;
-    }
-    case EVP_PKEY_RSA: {
-        rsa_pkey_setup(e, pkey.get(), key_id);
-        break;
-    }
-    case EVP_PKEY_EC: {
-        ecdsa_pkey_setup(e, pkey.get(), key_id);
-        break;
-    }
-    default:
-        ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type));
-        return NULL;
-    }
-
-    return pkey.release();
-}
-
-static const ENGINE_CMD_DEFN keystore_cmd_defns[] = {
-    {0, NULL, NULL, 0}
-};
-
-static int keystore_engine_setup(ENGINE* e) {
-    ALOGV("keystore_engine_setup");
-
-    if (!ENGINE_set_id(e, kKeystoreEngineId)
-            || !ENGINE_set_name(e, kKeystoreEngineDesc)
-            || !ENGINE_set_load_privkey_function(e, keystore_loadkey)
-            || !ENGINE_set_load_pubkey_function(e, keystore_loadkey)
-            || !ENGINE_set_flags(e, 0)
-            || !ENGINE_set_cmd_defns(e, keystore_cmd_defns)) {
-        ALOGE("Could not set up keystore engine");
-        return 0;
-    }
-
-    /* We need a handle in the keys types as well for keygen if it's not already initialized. */
-    pthread_once(&key_handle_control, init_key_handle);
-    if ((rsa_key_handle < 0) || (dsa_key_handle < 0)) {
-        ALOGE("Could not set up ex_data index");
-        return 0;
-    }
-
-    if (!dsa_register(e)) {
-        ALOGE("DSA registration failed");
-        return 0;
-    } else if (!ecdsa_register(e)) {
-        ALOGE("ECDSA registration failed");
-        return 0;
-    } else if (!rsa_register(e)) {
-        ALOGE("RSA registration failed");
-        return 0;
-    }
-
-    return 1;
-}
-
-ENGINE* ENGINE_keystore() {
-    ALOGV("ENGINE_keystore");
-
-    Unique_ENGINE engine(ENGINE_new());
-    if (engine.get() == NULL) {
-        return NULL;
-    }
-
-    if (!keystore_engine_setup(engine.get())) {
-        return NULL;
-    }
-
-    return engine.release();
-}
-
-static int keystore_bind_fn(ENGINE *e, const char *id) {
-    ALOGV("keystore_bind_fn");
-
-    if (!id) {
-        return 0;
-    }
-
-    if (strcmp(id, kKeystoreEngineId)) {
-        return 0;
-    }
-
-    if (!keystore_engine_setup(e)) {
-        return 0;
-    }
-
-    return 1;
-}
-
-extern "C" {
-#undef OPENSSL_EXPORT
-#define OPENSSL_EXPORT extern __attribute__ ((visibility ("default")))
-
-IMPLEMENT_DYNAMIC_CHECK_FN()
-IMPLEMENT_DYNAMIC_BIND_FN(keystore_bind_fn)
-};
diff --git a/keystore-engine/keyhandle.cpp b/keystore-engine/keyhandle.cpp
deleted file mode 100644
index aeba896..0000000
--- a/keystore-engine/keyhandle.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright 2012 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include <openssl/engine.h>
-
-#include <string.h>
-
-/**
- * Makes sure the ex_data for the keyhandle is initially set to NULL.
- */
-int keyhandle_new(void*, void*, CRYPTO_EX_DATA* ad, int idx, long, void*) {
-    return CRYPTO_set_ex_data(ad, idx, NULL);
-}
-
-/**
- * Frees a previously allocated keyhandle stored in ex_data.
- */
-void keyhandle_free(void *, void *ptr, CRYPTO_EX_DATA*, int, long, void*) {
-    char* keyhandle = reinterpret_cast<char*>(ptr);
-    if (keyhandle != NULL) {
-        free(keyhandle);
-    }
-}
-
-/**
- * Duplicates a keyhandle stored in ex_data in case we copy a key.
- */
-int keyhandle_dup(CRYPTO_EX_DATA* to, CRYPTO_EX_DATA*, void *ptrRef, int idx, long, void *) {
-    // This appears to be a bug in OpenSSL.
-    void** ptr = reinterpret_cast<void**>(ptrRef);
-    char* keyhandle = reinterpret_cast<char*>(*ptr);
-    if (keyhandle != NULL) {
-        char* keyhandle_copy = strdup(keyhandle);
-        *ptr = keyhandle_copy;
-
-        // Call this in case OpenSSL is fixed in the future.
-        (void) CRYPTO_set_ex_data(to, idx, keyhandle_copy);
-    }
-    return 1;
-}
-
-void *ex_data_dup(void *data) {
-    char* keyhandle = reinterpret_cast<char*>(data);
-    return strdup(keyhandle);
-}
-
-void ex_data_free(void *data) {
-    char* keyhandle = reinterpret_cast<char*>(data);
-    free(keyhandle);
-}
-
-void ex_data_clear_free(void *data) {
-    char* keyhandle = reinterpret_cast<char*>(data);
-    memset(data, '\0', strlen(keyhandle));
-    free(keyhandle);
-}
diff --git a/keystore-engine/rsa_meth.cpp b/keystore-engine/rsa_meth.cpp
deleted file mode 100644
index 74dfa5c..0000000
--- a/keystore-engine/rsa_meth.cpp
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright 2012 The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include <UniquePtr.h>
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "OpenSSL-keystore-rsa"
-#include <cutils/log.h>
-
-#include <binder/IServiceManager.h>
-#include <keystore/IKeystoreService.h>
-
-#include <openssl/rsa.h>
-#include <openssl/engine.h>
-
-#include "methods.h"
-
-
-using namespace android;
-
-
-int keystore_rsa_priv_enc(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
-        int padding) {
-    ALOGV("keystore_rsa_priv_enc(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding);
-
-    int num = RSA_size(rsa);
-    UniquePtr<uint8_t> padded(new uint8_t[num]);
-    if (padded.get() == NULL) {
-        ALOGE("could not allocate padded signature");
-        return 0;
-    }
-
-    switch (padding) {
-    case RSA_PKCS1_PADDING:
-        if (!RSA_padding_add_PKCS1_type_1(padded.get(), num, from, flen)) {
-            return 0;
-        }
-        break;
-    case RSA_X931_PADDING:
-        if (!RSA_padding_add_X931(padded.get(), num, from, flen)) {
-            return 0;
-        }
-        break;
-    case RSA_NO_PADDING:
-        if (!RSA_padding_add_none(padded.get(), num, from, flen)) {
-            return 0;
-        }
-        break;
-    default:
-        ALOGE("Unknown padding type: %d", padding);
-        return 0;
-    }
-
-    uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle));
-    if (key_id == NULL) {
-        ALOGE("key had no key_id!");
-        return 0;
-    }
-
-    sp<IServiceManager> sm = defaultServiceManager();
-    sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
-    sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
-
-    if (service == NULL) {
-        ALOGE("could not contact keystore");
-        return 0;
-    }
-
-    uint8_t* reply = NULL;
-    size_t replyLen;
-    int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), padded.get(),
-            num, &reply, &replyLen);
-    if (ret < 0) {
-        ALOGW("There was an error during signing: could not connect");
-        free(reply);
-        return 0;
-    } else if (ret != 0) {
-        ALOGW("Error during signing from keystore: %d", ret);
-        free(reply);
-        return 0;
-    } else if (replyLen <= 0) {
-        ALOGW("No valid signature returned");
-        return 0;
-    }
-
-    memcpy(to, reply, replyLen);
-    free(reply);
-
-    ALOGV("rsa=%p keystore_rsa_priv_enc => returning %p len %llu", rsa, to,
-            (unsigned long long) replyLen);
-    return static_cast<int>(replyLen);
-}
-
-int keystore_rsa_priv_dec(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
-        int padding) {
-    ALOGV("keystore_rsa_priv_dec(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding);
-
-    uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle));
-    if (key_id == NULL) {
-        ALOGE("key had no key_id!");
-        return 0;
-    }
-
-    sp<IServiceManager> sm = defaultServiceManager();
-    sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
-    sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
-
-    if (service == NULL) {
-        ALOGE("could not contact keystore");
-        return 0;
-    }
-
-    int num = RSA_size(rsa);
-
-    uint8_t* reply = NULL;
-    size_t replyLen;
-    int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), from,
-            flen, &reply, &replyLen);
-    if (ret < 0) {
-        ALOGW("There was an error during rsa_mod_exp: could not connect");
-        return 0;
-    } else if (ret != 0) {
-        ALOGW("Error during sign from keystore: %d", ret);
-        return 0;
-    } else if (replyLen <= 0) {
-        ALOGW("No valid signature returned");
-        return 0;
-    }
-
-    /* Trim off the top zero if it's there */
-    uint8_t* alignedReply;
-    if (*reply == 0x00) {
-        alignedReply = reply + 1;
-        replyLen--;
-    } else {
-        alignedReply = reply;
-    }
-
-    int outSize;
-    switch (padding) {
-    case RSA_PKCS1_PADDING:
-        outSize = RSA_padding_check_PKCS1_type_2(to, num, alignedReply, replyLen, num);
-        break;
-    case RSA_X931_PADDING:
-        outSize = RSA_padding_check_X931(to, num, alignedReply, replyLen, num);
-        break;
-    case RSA_NO_PADDING:
-        outSize = RSA_padding_check_none(to, num, alignedReply, replyLen, num);
-        break;
-    default:
-        ALOGE("Unknown padding type: %d", padding);
-        outSize = -1;
-        break;
-    }
-
-    free(reply);
-
-    ALOGV("rsa=%p keystore_rsa_priv_dec => returning %p len %d", rsa, to, outSize);
-    return outSize;
-}
-
-static RSA_METHOD keystore_rsa_meth = {
-        kKeystoreEngineId,
-        NULL, /* rsa_pub_enc (wrap) */
-        NULL, /* rsa_pub_dec (verification) */
-        keystore_rsa_priv_enc, /* rsa_priv_enc (signing) */
-        keystore_rsa_priv_dec, /* rsa_priv_dec (unwrap) */
-        NULL, /* rsa_mod_exp */
-        NULL, /* bn_mod_exp */
-        NULL, /* init */
-        NULL, /* finish */
-        RSA_FLAG_EXT_PKEY | RSA_FLAG_NO_BLINDING, /* flags */
-        NULL, /* app_data */
-        NULL, /* rsa_sign */
-        NULL, /* rsa_verify */
-        NULL, /* rsa_keygen */
-};
-
-static int register_rsa_methods() {
-    const RSA_METHOD* rsa_meth = RSA_PKCS1_SSLeay();
-
-    keystore_rsa_meth.rsa_pub_enc = rsa_meth->rsa_pub_enc;
-    keystore_rsa_meth.rsa_pub_dec = rsa_meth->rsa_pub_dec;
-    keystore_rsa_meth.rsa_mod_exp = rsa_meth->rsa_mod_exp;
-    keystore_rsa_meth.bn_mod_exp = rsa_meth->bn_mod_exp;
-
-    return 1;
-}
-
-int rsa_pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) {
-    Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
-    if (!RSA_set_ex_data(rsa.get(), rsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) {
-        ALOGW("Could not set ex_data for loaded RSA key");
-        return 0;
-    }
-
-    RSA_set_method(rsa.get(), &keystore_rsa_meth);
-    RSA_blinding_off(rsa.get());
-
-    /*
-     * "RSA_set_ENGINE()" should probably be an OpenSSL API. Since it isn't,
-     * and EVP_PKEY_free() calls ENGINE_finish(), we need to call ENGINE_init()
-     * here.
-     */
-    ENGINE_init(e);
-    rsa->engine = e;
-    rsa->flags |= RSA_FLAG_EXT_PKEY;
-
-    return 1;
-}
-
-int rsa_register(ENGINE* e) {
-    if (!ENGINE_set_RSA(e, &keystore_rsa_meth)
-            || !register_rsa_methods()) {
-        ALOGE("Could not set up keystore RSA methods");
-        return 0;
-    }
-
-    return 1;
-}
diff --git a/keystore/Android.mk b/keystore/Android.mk
index 059bfd4..f17d5eb 100644
--- a/keystore/Android.mk
+++ b/keystore/Android.mk
@@ -55,6 +55,9 @@
 LOCAL_MODULE := keystore
 LOCAL_MODULE_TAGS := optional
 LOCAL_INIT_RC := keystore.rc
+LOCAL_C_INCLUES := system/keymaster/
+LOCAL_CLANG := true
+LOCAL_SANITIZE := integer
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_EXECUTABLE)
 
@@ -111,6 +114,8 @@
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/include $(call keystore_proto_include)
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
 LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbinder
+LOCAL_CLANG := true
+LOCAL_SANITIZE := integer
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/keystore/IKeystoreService.cpp b/keystore/IKeystoreService.cpp
index 6507f79..5bc6a1e 100644
--- a/keystore/IKeystoreService.cpp
+++ b/keystore/IKeystoreService.cpp
@@ -272,7 +272,6 @@
     out->writeInt32(chain.entry_count);
     for (size_t i = 0; i < chain.entry_count; ++i) {
         if (chain.entries[i].data) {
-            out->writeInt32(1); // Tell Java side that object is not NULL
             out->writeInt32(chain.entries[i].data_length);
             void* buf = out->writeInplace(chain.entries[i].data_length);
             if (buf) {
@@ -484,11 +483,12 @@
         return ret;
     }
 
-    virtual int32_t get(const String16& name, uint8_t** item, size_t* itemLength)
+    virtual int32_t get(const String16& name, int32_t uid, uint8_t** item, size_t* itemLength)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
         data.writeString16(name);
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::GET, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("get() could not contact remote: %d\n", status);
@@ -899,11 +899,12 @@
         return ret;
     }
 
-    int64_t getmtime(const String16& name)
+    int64_t getmtime(const String16& name, int32_t uid)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
         data.writeString16(name);
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::GETMTIME, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("getmtime() could not contact remote: %d\n", status);
@@ -1029,7 +1030,7 @@
     virtual int32_t getKeyCharacteristics(const String16& name,
                                           const keymaster_blob_t* clientId,
                                           const keymaster_blob_t* appData,
-                                          KeyCharacteristics* outCharacteristics)
+                                          int32_t uid, KeyCharacteristics* outCharacteristics)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
@@ -1044,6 +1045,7 @@
         } else {
             data.writeInt32(-1);
         }
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::GET_KEY_CHARACTERISTICS,
                                              data, &reply);
         if (status != NO_ERROR) {
@@ -1094,7 +1096,7 @@
 
     virtual void exportKey(const String16& name, keymaster_key_format_t format,
                            const keymaster_blob_t* clientId,
-                           const keymaster_blob_t* appData, ExportResult* result)
+                           const keymaster_blob_t* appData, int32_t uid, ExportResult* result)
     {
         if (!result) {
             return;
@@ -1114,6 +1116,7 @@
         } else {
             data.writeInt32(-1);
         }
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::EXPORT_KEY, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("exportKey() could not contact remote: %d\n", status);
@@ -1134,7 +1137,7 @@
     virtual void begin(const sp<IBinder>& appToken, const String16& name,
                        keymaster_purpose_t purpose, bool pruneable,
                        const KeymasterArguments& params, const uint8_t* entropy,
-                       size_t entropyLength, OperationResult* result)
+                       size_t entropyLength, int32_t uid, OperationResult* result)
     {
         if (!result) {
             return;
@@ -1148,6 +1151,7 @@
         data.writeInt32(1);
         params.writeToParcel(&data);
         data.writeByteArray(entropyLength, entropy);
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::BEGIN, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("begin() could not contact remote: %d\n", status);
@@ -1369,9 +1373,10 @@
         case GET: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
             String16 name = data.readString16();
+            int32_t uid = data.readInt32();
             void* out = NULL;
             size_t outSize = 0;
-            int32_t ret = get(name, (uint8_t**) &out, &outSize);
+            int32_t ret = get(name, uid, (uint8_t**) &out, &outSize);
             reply->writeNoException();
             if (ret == 1) {
                 reply->writeInt32(outSize);
@@ -1615,7 +1620,8 @@
         case GETMTIME: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
             String16 name = data.readString16();
-            int64_t ret = getmtime(name);
+            int32_t uid = data.readInt32();
+            int64_t ret = getmtime(name, uid);
             reply->writeNoException();
             reply->writeInt64(ret);
             return NO_ERROR;
@@ -1683,8 +1689,9 @@
             String16 name = data.readString16();
             std::unique_ptr<keymaster_blob_t> clientId = readKeymasterBlob(data);
             std::unique_ptr<keymaster_blob_t> appData = readKeymasterBlob(data);
+            int32_t uid = data.readInt32();
             KeyCharacteristics outCharacteristics;
-            int ret = getKeyCharacteristics(name, clientId.get(), appData.get(),
+            int ret = getKeyCharacteristics(name, clientId.get(), appData.get(), uid,
                                             &outCharacteristics);
             reply->writeNoException();
             reply->writeInt32(ret);
@@ -1721,8 +1728,9 @@
             keymaster_key_format_t format = static_cast<keymaster_key_format_t>(data.readInt32());
             std::unique_ptr<keymaster_blob_t> clientId = readKeymasterBlob(data);
             std::unique_ptr<keymaster_blob_t> appData = readKeymasterBlob(data);
+            int32_t uid = data.readInt32();
             ExportResult result;
-            exportKey(name, format, clientId.get(), appData.get(), &result);
+            exportKey(name, format, clientId.get(), appData.get(), uid, &result);
             reply->writeNoException();
             reply->writeInt32(1);
             result.writeToParcel(reply);
@@ -1742,8 +1750,9 @@
             const uint8_t* entropy = NULL;
             size_t entropyLength = 0;
             readByteArray(data, &entropy, &entropyLength);
+            int32_t uid = data.readInt32();
             OperationResult result;
-            begin(token, name, purpose, pruneable, args, entropy, entropyLength, &result);
+            begin(token, name, purpose, pruneable, args, entropy, entropyLength, uid, &result);
             reply->writeNoException();
             reply->writeParcelable(result);
 
@@ -1834,6 +1843,22 @@
 
             return NO_ERROR;
         }
+        case ATTEST_KEY: {
+            CHECK_INTERFACE(IKeystoreService, data, reply);
+            String16 name = data.readString16();
+            KeymasterArguments params;
+            if (data.readInt32() != 0) {
+                params.readFromParcel(data);
+            }
+            KeymasterCertificateChain chain;
+            int ret = attestKey(name, params, &chain);
+            reply->writeNoException();
+            reply->writeInt32(ret);
+            reply->writeInt32(1);
+            chain.writeToParcel(reply);
+
+            return NO_ERROR;
+        }
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/keystore/blob.h b/keystore/blob.h
index 95610ad..3fa71ef 100644
--- a/keystore/blob.h
+++ b/keystore/blob.h
@@ -24,7 +24,7 @@
 
 #include <keystore/keystore.h>
 
-#define VALUE_SIZE      32768
+#define VALUE_SIZE 32768
 
 /* Here is the file format. There are two parts in blob.value, the secret and
  * the description. The secret is stored in ciphertext, and its original size
@@ -55,17 +55,17 @@
     uint8_t flags;
     uint8_t info;
     uint8_t vector[AES_BLOCK_SIZE];
-    uint8_t encrypted[0]; // Marks offset to encrypted data.
+    uint8_t encrypted[0];  // Marks offset to encrypted data.
     uint8_t digest[MD5_DIGEST_LENGTH];
-    uint8_t digested[0]; // Marks offset to digested data.
-    int32_t length; // in network byte order when encrypted
+    uint8_t digested[0];  // Marks offset to digested data.
+    int32_t length;       // in network byte order when encrypted
     uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
 };
 
 static const uint8_t CURRENT_BLOB_VERSION = 2;
 
 typedef enum {
-    TYPE_ANY = 0, // meta type that matches anything
+    TYPE_ANY = 0,  // meta type that matches anything
     TYPE_GENERIC = 1,
     TYPE_MASTER_KEY = 2,
     TYPE_KEY_PAIR = 3,
diff --git a/keystore/include/keystore/IKeystoreService.h b/keystore/include/keystore/IKeystoreService.h
index 6655e72..dbd6e25 100644
--- a/keystore/include/keystore/IKeystoreService.h
+++ b/keystore/include/keystore/IKeystoreService.h
@@ -153,7 +153,7 @@
 
     virtual int32_t getState(int32_t userId) = 0;
 
-    virtual int32_t get(const String16& name, uint8_t** item, size_t* itemLength) = 0;
+    virtual int32_t get(const String16& name, int32_t uid, uint8_t** item, size_t* itemLength) = 0;
 
     virtual int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int uid,
             int32_t flags) = 0;
@@ -192,7 +192,7 @@
 
     virtual int32_t ungrant(const String16& name, int32_t granteeUid) = 0;
 
-    virtual int64_t getmtime(const String16& name) = 0;
+    virtual int64_t getmtime(const String16& name, int32_t uid) = 0;
 
     virtual int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
             int32_t destUid) = 0;
@@ -210,6 +210,7 @@
     virtual int32_t getKeyCharacteristics(const String16& name,
                                           const keymaster_blob_t* clientId,
                                           const keymaster_blob_t* appData,
+                                          int32_t uid,
                                           KeyCharacteristics* outCharacteristics) = 0;
 
     virtual int32_t importKey(const String16& name, const KeymasterArguments&  params,
@@ -219,12 +220,12 @@
 
     virtual void exportKey(const String16& name, keymaster_key_format_t format,
                            const keymaster_blob_t* clientId,
-                           const keymaster_blob_t* appData, ExportResult* result) = 0;
+                           const keymaster_blob_t* appData, int32_t uid, ExportResult* result) = 0;
 
     virtual void begin(const sp<IBinder>& apptoken, const String16& name,
                        keymaster_purpose_t purpose, bool pruneable,
                        const KeymasterArguments& params, const uint8_t* entropy,
-                       size_t entropyLength, OperationResult* result) = 0;
+                       size_t entropyLength, int32_t uid, OperationResult* result) = 0;
 
     virtual void update(const sp<IBinder>& token, const KeymasterArguments& params,
                         const uint8_t* data, size_t dataLength, OperationResult* result) = 0;
diff --git a/keystore/key_store_service.cpp b/keystore/key_store_service.cpp
index e3df13a..329898b 100644
--- a/keystore/key_store_service.cpp
+++ b/keystore/key_store_service.cpp
@@ -30,6 +30,11 @@
 #include "defaults.h"
 #include "keystore_utils.h"
 
+using keymaster::AuthorizationSet;
+using keymaster::AuthorizationSetBuilder;
+using keymaster::TAG_APPLICATION_DATA;
+using keymaster::TAG_APPLICATION_ID;
+
 namespace android {
 
 const size_t MAX_OPERATIONS = 15;
@@ -39,6 +44,10 @@
 };
 typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
 
+struct Malloc_Delete {
+    void operator()(uint8_t* p) const { free(p); }
+};
+
 void KeyStoreService::binderDied(const wp<IBinder>& who) {
     auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
     for (const auto& token : operations) {
@@ -54,16 +63,17 @@
     return mKeyStore->getState(userId);
 }
 
-int32_t KeyStoreService::get(const String16& name, uint8_t** item, size_t* itemLength) {
-    if (!checkBinderPermission(P_GET)) {
+int32_t KeyStoreService::get(const String16& name, int32_t uid, uint8_t** item,
+                             size_t* itemLength) {
+    uid_t targetUid = getEffectiveUid(uid);
+    if (!checkBinderPermission(P_GET, targetUid)) {
         return ::PERMISSION_DENIED;
     }
 
-    uid_t callingUid = IPCThreadState::self()->getCallingUid();
     String8 name8(name);
     Blob keyBlob;
 
-    ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_GENERIC);
+    ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
     if (responseCode != ::NO_ERROR) {
         *item = NULL;
         *itemLength = 0;
@@ -396,7 +406,7 @@
  */
 int32_t KeyStoreService::get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
     ExportResult result;
-    exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
+    exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, UID_SELF, &result);
     if (result.resultCode != ::NO_ERROR) {
         ALOGW("export failed: %d", result.resultCode);
         return translateResultToLegacyResult(result.resultCode);
@@ -442,15 +452,15 @@
     return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
 }
 
-int64_t KeyStoreService::getmtime(const String16& name) {
-    uid_t callingUid = IPCThreadState::self()->getCallingUid();
-    if (!checkBinderPermission(P_GET)) {
-        ALOGW("permission denied for %d: getmtime", callingUid);
+int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
+    uid_t targetUid = getEffectiveUid(uid);
+    if (!checkBinderPermission(P_GET, targetUid)) {
+        ALOGW("permission denied for %d: getmtime", targetUid);
         return -1L;
     }
 
     String8 name8(name);
-    String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
+    String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
 
     if (access(filename.string(), R_OK) == -1) {
         ALOGW("could not access %s for getmtime", filename.string());
@@ -656,33 +666,52 @@
 
 int32_t KeyStoreService::getKeyCharacteristics(const String16& name,
                                                const keymaster_blob_t* clientId,
-                                               const keymaster_blob_t* appData,
+                                               const keymaster_blob_t* appData, int32_t uid,
                                                KeyCharacteristics* outCharacteristics) {
     if (!outCharacteristics) {
         return KM_ERROR_UNEXPECTED_NULL_POINTER;
     }
 
+    uid_t targetUid = getEffectiveUid(uid);
     uid_t callingUid = IPCThreadState::self()->getCallingUid();
+    if (!is_granted_to(callingUid, targetUid)) {
+        ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
+              targetUid);
+        return ::PERMISSION_DENIED;
+    }
 
     Blob keyBlob;
     String8 name8(name);
     int rc;
 
     ResponseCode responseCode =
-        mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
+        mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
     if (responseCode != ::NO_ERROR) {
         return responseCode;
     }
-    keymaster_key_blob_t key;
-    key.key_material_size = keyBlob.getLength();
-    key.key_material = keyBlob.getValue();
+    keymaster_key_blob_t key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
     auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
-    keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
+    keymaster_key_characteristics_t out = {};
     if (!dev->get_key_characteristics) {
         ALOGE("device does not implement get_key_characteristics");
         return KM_ERROR_UNIMPLEMENTED;
     }
     rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
+    if (rc == KM_ERROR_KEY_REQUIRES_UPGRADE) {
+        AuthorizationSet upgradeParams;
+        if (clientId && clientId->data && clientId->data_length) {
+            upgradeParams.push_back(TAG_APPLICATION_ID, *clientId);
+        }
+        if (appData && appData->data && appData->data_length) {
+            upgradeParams.push_back(TAG_APPLICATION_DATA, *appData);
+        }
+        rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
+        if (rc != ::NO_ERROR) {
+            return rc;
+        }
+        key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
+        rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
+    }
     if (rc != KM_ERROR_OK) {
         return rc;
     }
@@ -747,16 +776,22 @@
 
 void KeyStoreService::exportKey(const String16& name, keymaster_key_format_t format,
                                 const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
-                                ExportResult* result) {
+                                int32_t uid, ExportResult* result) {
 
+    uid_t targetUid = getEffectiveUid(uid);
     uid_t callingUid = IPCThreadState::self()->getCallingUid();
+    if (!is_granted_to(callingUid, targetUid)) {
+        ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
+        result->resultCode = ::PERMISSION_DENIED;
+        return;
+    }
 
     Blob keyBlob;
     String8 name8(name);
     int rc;
 
     ResponseCode responseCode =
-        mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
+        mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
     if (responseCode != ::NO_ERROR) {
         result->resultCode = responseCode;
         return;
@@ -779,8 +814,14 @@
 void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name,
                             keymaster_purpose_t purpose, bool pruneable,
                             const KeymasterArguments& params, const uint8_t* entropy,
-                            size_t entropyLength, OperationResult* result) {
+                            size_t entropyLength, int32_t uid, OperationResult* result) {
     uid_t callingUid = IPCThreadState::self()->getCallingUid();
+    uid_t targetUid = getEffectiveUid(uid);
+    if (!is_granted_to(callingUid, targetUid)) {
+        ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
+        result->resultCode = ::PERMISSION_DENIED;
+        return;
+    }
     if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
         ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
         result->resultCode = ::PERMISSION_DENIED;
@@ -793,7 +834,7 @@
     Blob keyBlob;
     String8 name8(name);
     ResponseCode responseCode =
-        mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
+        mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
     if (responseCode != ::NO_ERROR) {
         result->resultCode = responseCode;
         return;
@@ -808,6 +849,16 @@
     Unique_keymaster_key_characteristics characteristics;
     characteristics.reset(new keymaster_key_characteristics_t);
     err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
+    if (err == KM_ERROR_KEY_REQUIRES_UPGRADE) {
+        int32_t rc = upgradeKeyBlob(name, targetUid,
+                                    AuthorizationSet(opParams.data(), opParams.size()), &keyBlob);
+        if (rc != ::NO_ERROR) {
+            result->resultCode = rc;
+            return;
+        }
+        key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
+        err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
+    }
     if (err) {
         result->resultCode = err;
         return;
@@ -1207,7 +1258,7 @@
     return ::NO_ERROR;
 }
 
-inline bool KeyStoreService::isKeystoreUnlocked(State state) {
+bool KeyStoreService::isKeystoreUnlocked(State state) {
     switch (state) {
     case ::STATE_NO_ERROR:
         return true;
@@ -1380,7 +1431,7 @@
  * Translate a result value to a legacy return value. All keystore errors are
  * preserved and keymaster errors become SYSTEM_ERRORs
  */
-inline int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
+int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
     if (result > 0) {
         return result;
     }
@@ -1410,7 +1461,7 @@
 
     // Look up the algorithm of the key.
     KeyCharacteristics characteristics;
-    int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
+    int32_t rc = getKeyCharacteristics(name, NULL, NULL, UID_SELF, &characteristics);
     if (rc != ::NO_ERROR) {
         ALOGE("Failed to get key characteristics");
         return;
@@ -1435,7 +1486,7 @@
     sp<IBinder> appToken(new BBinder);
     sp<IBinder> token;
 
-    begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
+    begin(appToken, name, purpose, true, inArgs, NULL, 0, UID_SELF, &result);
     if (result.resultCode != ResponseCode::NO_ERROR) {
         if (result.resultCode == ::KEY_NOT_FOUND) {
             ALOGW("Key not found");
@@ -1485,4 +1536,45 @@
     return ::NO_ERROR;
 }
 
+int32_t KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
+                                        const AuthorizationSet& params, Blob* blob) {
+    // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
+    String8 name8(name);
+    ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
+    if (responseCode != ::NO_ERROR) {
+        return responseCode;
+    }
+
+    keymaster_key_blob_t key = {blob->getValue(), static_cast<size_t>(blob->getLength())};
+    auto* dev = mKeyStore->getDeviceForBlob(*blob);
+    keymaster_key_blob_t upgraded_key;
+    int32_t rc = dev->upgrade_key(dev, &key, &params, &upgraded_key);
+    if (rc != KM_ERROR_OK) {
+        return rc;
+    }
+    UniquePtr<uint8_t, Malloc_Delete> upgraded_key_deleter(
+        const_cast<uint8_t*>(upgraded_key.key_material));
+
+    rc = del(name, uid);
+    if (rc != ::NO_ERROR) {
+        return rc;
+    }
+
+    String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
+    Blob newBlob(upgraded_key.key_material, upgraded_key.key_material_size, nullptr /* info */,
+                 0 /* infoLength */, ::TYPE_KEYMASTER_10);
+    newBlob.setFallback(blob->isFallback());
+    newBlob.setEncrypted(blob->isEncrypted());
+
+    rc = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
+
+    // Re-read blob for caller.  We can't use newBlob because writing it modified it.
+    responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
+    if (responseCode != ::NO_ERROR) {
+        return responseCode;
+    }
+
+    return rc;
+}
+
 }  // namespace android
diff --git a/keystore/key_store_service.h b/keystore/key_store_service.h
index 3efae47..40b188d 100644
--- a/keystore/key_store_service.h
+++ b/keystore/key_store_service.h
@@ -19,6 +19,8 @@
 
 #include <keystore/IKeystoreService.h>
 
+#include <keymaster/authorization_set.h>
+
 #include "auth_token_table.h"
 #include "keystore.h"
 #include "keystore_keymaster_enforcement.h"
@@ -35,7 +37,7 @@
 
     int32_t getState(int32_t userId);
 
-    int32_t get(const String16& name, uint8_t** item, size_t* itemLength);
+    int32_t get(const String16& name, int32_t uid, uint8_t** item, size_t* itemLength);
     int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
                    int32_t flags);
     int32_t del(const String16& name, int targetUid);
@@ -78,7 +80,7 @@
     int32_t grant(const String16& name, int32_t granteeUid);
     int32_t ungrant(const String16& name, int32_t granteeUid);
 
-    int64_t getmtime(const String16& name);
+    int64_t getmtime(const String16& name, int32_t uid);
 
     int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
                       int32_t destUid);
@@ -92,17 +94,17 @@
                         const uint8_t* entropy, size_t entropyLength, int uid, int flags,
                         KeyCharacteristics* outCharacteristics);
     int32_t getKeyCharacteristics(const String16& name, const keymaster_blob_t* clientId,
-                                  const keymaster_blob_t* appData,
+                                  const keymaster_blob_t* appData, int32_t uid,
                                   KeyCharacteristics* outCharacteristics);
     int32_t importKey(const String16& name, const KeymasterArguments& params,
                       keymaster_key_format_t format, const uint8_t* keyData, size_t keyLength,
                       int uid, int flags, KeyCharacteristics* outCharacteristics);
     void exportKey(const String16& name, keymaster_key_format_t format,
-                   const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
+                   const keymaster_blob_t* clientId, const keymaster_blob_t* appData, int32_t uid,
                    ExportResult* result);
     void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
                bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
-               size_t entropyLength, OperationResult* result);
+               size_t entropyLength, int32_t uid, OperationResult* result);
     void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
                 size_t dataLength, OperationResult* result);
     void finish(const sp<IBinder>& token, const KeymasterArguments& params,
@@ -222,6 +224,17 @@
                                uint8_t** out, size_t* outLength, const uint8_t* signature,
                                size_t signatureLength, keymaster_purpose_t purpose);
 
+    /**
+     * Upgrade a key blob under alias "name", returning the new blob in "blob".  If "blob"
+     * previously contained data, it will be overwritten.
+     *
+     * Returns ::NO_ERROR if the key was upgraded successfully.
+     *         KM_ERROR_VERSION_MISMATCH if called on a key whose patch level is greater than or
+     *         equal to the current system patch level.
+     */
+    int32_t upgradeKeyBlob(const String16& name, uid_t targetUid,
+                           const keymaster::AuthorizationSet& params, Blob* blob);
+
     ::KeyStore* mKeyStore;
     OperationMap mOperationMap;
     keymaster::AuthTokenTable mAuthTokenTable;
diff --git a/keystore/keystore.cpp b/keystore/keystore.cpp
index 3c87fd5..6ec8ce5 100644
--- a/keystore/keystore.cpp
+++ b/keystore/keystore.cpp
@@ -32,7 +32,6 @@
 const char* KeyStore::sMetaDataFile = ".metadata";
 
 const android::String16 KeyStore::sRSAKeyType("RSA");
-const android::String16 KeyStore::sECKeyType("EC");
 
 KeyStore::KeyStore(Entropy* entropy, keymaster2_device_t* device, keymaster2_device_t* fallback)
     : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback) {
diff --git a/keystore/keystore.h b/keystore/keystore.h
index 62d7294..b15d00f 100644
--- a/keystore/keystore.h
+++ b/keystore/keystore.h
@@ -111,7 +111,6 @@
     static const char* sOldMasterKey;
     static const char* sMetaDataFile;
     static const android::String16 sRSAKeyType;
-    static const android::String16 sECKeyType;
     Entropy* mEntropy;
 
     keymaster2_device_t* mDevice;
diff --git a/keystore/keystore.rc b/keystore/keystore.rc
index a887594..5dac937 100644
--- a/keystore/keystore.rc
+++ b/keystore/keystore.rc
@@ -2,3 +2,4 @@
     class main
     user keystore
     group keystore drmrpc readproc
+    writepid /dev/cpuset/foreground/tasks
diff --git a/keystore/keystore_cli.cpp b/keystore/keystore_cli.cpp
index bf6f4a0..d9781e0 100644
--- a/keystore/keystore_cli.cpp
+++ b/keystore/keystore_cli.cpp
@@ -104,7 +104,7 @@
             int uid = -1; \
             if (argc > 3) { \
                 uid = atoi(argv[3]); \
-                fprintf(stderr, "Working with uid %d\n", uid); \
+                fprintf(stderr, "Running as uid %d\n", uid); \
             } \
             int32_t ret = service->cmd(String16(argv[2]), uid); \
             if (ret < 0) { \
@@ -117,28 +117,47 @@
         } \
     } while (0)
 
-#define STING_ARG_DATA_STDIN_PLUS_UID_PLUS_FLAGS_INT_RETURN(cmd) \
+#define SINGLE_ARG_PLUS_UID_DATA_RETURN(cmd) \
     do { \
         if (strcmp(argv[1], #cmd) == 0) { \
             if (argc < 3) { \
-                fprintf(stderr, "Usage: %s " #cmd " <name> [<uid>, <flags>]\n", argv[0]); \
+                fprintf(stderr, "Usage: %s " #cmd " <name> <uid>\n", argv[0]); \
+                return 1; \
+            } \
+            uint8_t* data; \
+            size_t dataSize; \
+            int uid = -1; \
+            if (argc > 3) { \
+                uid = atoi(argv[3]); \
+                fprintf(stderr, "Running as uid %d\n", uid); \
+            } \
+            int32_t ret = service->cmd(String16(argv[2]), uid, &data, &dataSize); \
+            if (ret < 0) { \
+                fprintf(stderr, "%s: could not connect: %d\n", argv[0], ret); \
+                return 1; \
+            } else if (ret != ::NO_ERROR) { \
+                fprintf(stderr, "%s: " #cmd ": %s (%d)\n", argv[0], responses[ret], ret); \
+                return 1; \
+            } else { \
+                fwrite(data, dataSize, 1, stdout); \
+                fflush(stdout); \
+                free(data); \
+                return 0; \
+            } \
+        } \
+    } while (0)
+
+#define STING_ARG_DATA_STDIN_INT_RETURN(cmd) \
+    do { \
+        if (strcmp(argv[1], #cmd) == 0) { \
+            if (argc < 3) { \
+                fprintf(stderr, "Usage: %s " #cmd " <name>\n", argv[0]); \
                 return 1; \
             } \
             uint8_t* data; \
             size_t dataSize; \
             read_input(&data, &dataSize); \
-            int uid = -1; \
-            if (argc > 3) { \
-                uid = atoi(argv[3]); \
-                fprintf(stderr, "Working with uid %d\n", uid); \
-            } \
-            int32_t flags = 0; \
-            if (argc > 4) { \
-                flags = int32_t(atoi(argv[4])); \
-                fprintf(stderr, "Using flags %04x\n", flags); \
-            } \
-            int32_t ret = service->cmd(String16(argv[2]), data, dataSize, uid, flags); \
-            free(data); \
+            int32_t ret = service->cmd(String16(argv[2]), data, dataSize); \
             if (ret < 0) { \
                 fprintf(stderr, "%s: could not connect: %d\n", argv[0], ret); \
                 return 1; \
@@ -162,16 +181,14 @@
             if (ret < 0) { \
                 fprintf(stderr, "%s: could not connect: %d\n", argv[0], ret); \
                 return 1; \
-            } else if (ret) { \
+            } else if (ret != ::NO_ERROR) { \
                 fprintf(stderr, "%s: " #cmd ": %s (%d)\n", argv[0], responses[ret], ret); \
                 return 1; \
-            } else if (dataSize) { \
+            } else { \
                 fwrite(data, dataSize, 1, stdout); \
                 fflush(stdout); \
                 free(data); \
                 return 0; \
-            } else { \
-                return 1; \
             } \
         } \
     } while (0)
@@ -194,39 +211,6 @@
     }
 }
 
-#define BUF_SIZE 1024
-static void read_input(uint8_t** data, size_t* dataSize) {
-    char buffer[BUF_SIZE];
-    size_t contentSize = 0;
-    char *content = (char *) malloc(sizeof(char) * BUF_SIZE);
-
-    if (content == NULL) {
-        fprintf(stderr, "read_input: failed to allocate content");
-        exit(1);
-    }
-    content[0] = '\0';
-    while (fgets(buffer, BUF_SIZE, stdin)) {
-        char *old = content;
-        contentSize += strlen(buffer);
-        content = (char *) realloc(content, contentSize);
-        if (content == NULL) {
-            fprintf(stderr, "read_input: failed to reallocate content.");
-            free(old);
-            exit(1);
-        }
-        strcat(content, buffer);
-    }
-
-    if (ferror(stdin)) {
-        free(content);
-        fprintf(stderr, "read_input: error reading from stdin.");
-        exit(1);
-    }
-
-    *data = (uint8_t*) content;
-    *dataSize = contentSize;
-}
-
 int main(int argc, char* argv[])
 {
     if (argc < 2) {
@@ -249,9 +233,9 @@
 
     SINGLE_INT_ARG_INT_RETURN(getState);
 
-    SINGLE_ARG_DATA_RETURN(get);
+    SINGLE_ARG_PLUS_UID_DATA_RETURN(get);
 
-    STING_ARG_DATA_STDIN_PLUS_UID_PLUS_FLAGS_INT_RETURN(insert);
+    // TODO: insert
 
     SINGLE_ARG_PLUS_UID_INT_RETURN(del);
 
@@ -276,7 +260,7 @@
 
     SINGLE_ARG_DATA_RETURN(get_pubkey);
 
-    SINGLE_ARG_PLUS_UID_INT_RETURN(grant);
+    // TODO: grant
 
     // TODO: ungrant
 
diff --git a/keystore/keystore_client_impl.cpp b/keystore/keystore_client_impl.cpp
index a46dfc7..c3d8f35 100644
--- a/keystore/keystore_client_impl.cpp
+++ b/keystore/keystore_client_impl.cpp
@@ -222,7 +222,7 @@
     keymaster_blob_t app_data_blob = {nullptr, 0};
     KeyCharacteristics characteristics;
     int32_t result = keystore_->getKeyCharacteristics(key_name16, &client_id_blob, &app_data_blob,
-                                                      &characteristics);
+                                                      kDefaultUID, &characteristics);
     hardware_enforced_characteristics->Reinitialize(characteristics.characteristics.hw_enforced);
     software_enforced_characteristics->Reinitialize(characteristics.characteristics.sw_enforced);
     return mapKeystoreError(result);
@@ -253,7 +253,7 @@
     keymaster_blob_t app_data_blob = {nullptr, 0};
     ExportResult export_result;
     keystore_->exportKey(key_name16, export_format, &client_id_blob, &app_data_blob,
-                         &export_result);
+                         kDefaultUID, &export_result);
     *export_data = ByteArrayAsString(export_result.exportData.get(), export_result.dataLength);
     return mapKeystoreError(export_result.resultCode);
 }
@@ -277,7 +277,7 @@
     CopyParameters(input_parameters, &input_arguments.params);
     OperationResult result;
     keystore_->begin(token, key_name16, purpose, true /*pruneable*/, input_arguments,
-                     NULL /*entropy*/, 0 /*entropyLength*/, &result);
+                     NULL /*entropy*/, 0 /*entropyLength*/, kDefaultUID, &result);
     int32_t error_code = mapKeystoreError(result.resultCode);
     if (error_code == KM_ERROR_OK) {
         *handle = getNextVirtualHandle();
diff --git a/keystore/keystore_get.cpp b/keystore/keystore_get.cpp
index 45ad415..2783816 100644
--- a/keystore/keystore_get.cpp
+++ b/keystore/keystore_get.cpp
@@ -31,7 +31,7 @@
     }
 
     size_t valueLength;
-    int32_t ret = service->get(String16(key, keyLength), value, &valueLength);
+    int32_t ret = service->get(String16(key, keyLength), -1, value, &valueLength);
     if (ret < 0) {
         return -1;
     } else if (ret != ::NO_ERROR) {
diff --git a/keystore/keystore_main.cpp b/keystore/keystore_main.cpp
index a2b75f6..e84fb37 100644
--- a/keystore/keystore_main.cpp
+++ b/keystore/keystore_main.cpp
@@ -17,6 +17,7 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "keystore"
 
+#include <keymaster/keymaster_configuration.h>
 #include <keymaster/soft_keymaster_device.h>
 #include <keymaster/soft_keymaster_logger.h>
 
@@ -36,8 +37,24 @@
  * user-defined password. To keep things simple, buffers are always larger than
  * the maximum space we needed, so boundary checks on buffers are omitted. */
 
+using keymaster::AuthorizationSet;
+using keymaster::AuthorizationSetBuilder;
 using keymaster::SoftKeymasterDevice;
 
+static int configure_keymaster_devices(keymaster2_device_t* main, keymaster2_device_t* fallback) {
+    keymaster_error_t error = keymaster::ConfigureDevice(main);
+    if (error != KM_ERROR_OK) {
+        return -1;
+    }
+
+    error = keymaster::ConfigureDevice(fallback);
+    if (error != KM_ERROR_OK) {
+        return -1;
+    }
+
+    return 0;
+}
+
 static int keymaster0_device_initialize(const hw_module_t* mod, keymaster2_device_t** dev) {
     assert(mod->module_api_version < KEYMASTER_MODULE_API_VERSION_1_0);
     ALOGI("Found keymaster0 module %s, version %x", mod->name, mod->module_api_version);
@@ -199,6 +216,11 @@
         return 1;
     }
 
+    if (configure_keymaster_devices(dev, fallback)) {
+        ALOGE("Keymaster devices could not be configured; exiting");
+        return 1;
+    }
+
     if (configure_selinux() == -1) {
         return -1;
     }
diff --git a/keystore/keystore_utils.cpp b/keystore/keystore_utils.cpp
index bfcb43a..4617afd 100644
--- a/keystore/keystore_utils.cpp
+++ b/keystore/keystore_utils.cpp
@@ -51,6 +51,10 @@
         data += n;
         remaining -= n;
     }
+    if (TEMP_FAILURE_RETRY(fsync(fd)) == -1) {
+        ALOGW("fsync failed: %s", strerror(errno));
+        return -1;
+    }
     return size;
 }
 
@@ -78,8 +82,6 @@
     params->push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
     params->push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
     params->push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
-    uint64_t now = keymaster::java_time(time(NULL));
-    params->push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
 }
 
 uid_t get_app_id(uid_t uid) {
diff --git a/keystore/test-keystore b/keystore/test-keystore
index 071cfcd..3be51b3 100755
--- a/keystore/test-keystore
+++ b/keystore/test-keystore
@@ -44,7 +44,7 @@
 function run() {
     # strip out carriage returns from adb
     # strip out date/time from ls -l
-    "$@" | tr -d '\r' | sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2} +[0-9]{1,2}:[0-9]{2} //' >> $log_file
+    "$@" | tr --delete '\r' | sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2} +[0-9]{1,2}:[0-9]{2} //' >> $log_file
 }
 
 function keystore() {
@@ -53,15 +53,8 @@
     run adb shell su $user keystore_cli "$@"
 }
 
-function keystore_in() {
-    declare -r user=$1
-    declare -r input=$2
-    shift; shift
-    run adb shell "echo '$input' | su $user keystore_cli $@"
-}
-
 function list_keystore_directory() {
-    run adb shell ls -al /data/misc/keystore$@
+    run adb shell ls -al /data/misc/keystore
 }
 
 function compare() {
@@ -75,211 +68,195 @@
     # reset
     #
     log "reset keystore as system user"
-    keystore system reset
-    expect "reset: No error (1)"
+    keystore system r
+    expect "1 No error"
     list_keystore_directory
-    expect "-rw------- keystore keystore        4 .metadata"
-    expect "drwx------ keystore keystore          user_0"
 
     #
     # basic tests as system/root
     #
     log "root does not have permission to run test"
-    keystore root test
-    expect "test: Permission denied (6)"
-
+    keystore root t
+    expect "6 Permission denied"
+    
     log "but system user does"
-    keystore system test
-    expect "test: Uninitialized (3)"
+    keystore system t
+    expect "3 Uninitialized"
     list_keystore_directory
-    expect "-rw------- keystore keystore        4 .metadata"
-    expect "drwx------ keystore keystore          user_0"
 
     log "password is now bar"
-    keystore system password bar
-    expect "password: No error (1)"
-    list_keystore_directory /user_0
+    keystore system p bar
+    expect "1 No error"
+    list_keystore_directory
     expect "-rw------- keystore keystore       84 .masterkey"
-
+    
     log "no error implies initialized and unlocked"
-    keystore system test
-    expect "test: No error (1)"
-
+    keystore system t
+    expect "1 No error"
+    
     log "saw with no argument"
-    keystore system saw
+    keystore system s
+    expect "5 Protocol error"
 
     log "saw nothing"
-    keystore system saw ""
+    keystore system s ""
+    expect "1 No error"
 
     log "add key baz"
-    keystore_in system quux insert baz
-    expect "insert: No error (1)"
+    keystore system i baz quux
+    expect "1 No error"
 
     log "1000 is uid of system"
-    list_keystore_directory /user_0
+    list_keystore_directory
     expect "-rw------- keystore keystore       84 .masterkey"
     expect "-rw------- keystore keystore       52 1000_baz"
 
     log "saw baz"
-    keystore system saw
+    keystore system s ""
+    expect "1 No error"
     expect "baz"
 
     log "get baz"
-    keystore system get baz
+    keystore system g baz
+    expect "1 No error"
     expect "quux"
 
     log "root can read system user keys (as can wifi or vpn users)"
-    keystore root get baz
+    keystore root g baz
+    expect "1 No error"
     expect "quux"
 
     #
     # app user tests
     #
 
-    # u0_a0 has uid 10000, as seen below
+    # app_0 has uid 10000, as seen below
     log "other uses cannot see the system keys"
-    keystore u0_a0 get baz
-
+    keystore app_0 g baz
+    expect "7 Key not found"
+    
     log "app user cannot use reset, password, lock, unlock"
-    keystore u0_a0 reset
-    expect "reset: Permission denied (6)"
-    keystore u0_a0 password some_pass
-    expect "password: Permission denied (6)"
-    keystore u0_a0 lock
-    expect "lock: Permission denied (6)"
-    keystore u0_a0 unlock some_pass
-    expect "unlock: Permission denied (6)"
+    keystore app_0 r
+    expect "6 Permission denied"
+    keystore app_0 p
+    expect "6 Permission denied"
+    keystore app_0 l
+    expect "6 Permission denied"
+    keystore app_0 u
+    expect "6 Permission denied"
 
-    log "install u0_a0 key"
-    keystore_in u0_a0 deadbeef insert 0x
-    expect "insert: No error (1)"
-    list_keystore_directory /user_0
+    log "install app_0 key"
+    keystore app_0 i 0x deadbeef
+    expect 1 No error
+    list_keystore_directory
     expect "-rw------- keystore keystore       84 .masterkey"
     expect "-rw------- keystore keystore       52 10000_0x"
     expect "-rw------- keystore keystore       52 1000_baz"
 
     log "get with no argument"
-    keystore u0_a0 get
-    expect "Usage: keystore_cli get <name>"
-
-    log "few get tests for an app"
-    keystore u0_a0 get 0x
+    keystore app_0 g
+    expect "5 Protocol error"
+    
+    keystore app_0 g 0x
+    expect "1 No error"
     expect "deadbeef"
-
-    keystore_in u0_a0 barney insert fred
-    expect "insert: No error (1)"
-
-    keystore u0_a0 saw
+    
+    keystore app_0 i fred barney
+    expect "1 No error"
+    
+    keystore app_0 s ""
+    expect "1 No error"
     expect "0x"
     expect "fred"
 
     log "note that saw returns the suffix of prefix matches"
-    keystore u0_a0 saw fr # fred
+    keystore app_0 s fr # fred
+    expect "1 No error"
     expect "ed" # fred
 
     #
     # lock tests
     #
     log "lock the store as system"
-    keystore system lock
-    expect "lock: No error (1)"
-    keystore system test
-    expect "test: Locked (2)"
-
+    keystore system l
+    expect "1 No error"
+    keystore system t
+    expect "2 Locked"
+    
     log "saw works while locked"
-    keystore u0_a0 saw
+    keystore app_0 s ""
+    expect "1 No error"
     expect "0x"
     expect "fred"
 
-    log "...and app can read keys..."
-    keystore u0_a0 get 0x
-    expect "deadbeef"
-
-    log "...but they cannot be deleted."
-    keystore u0_a0 exist 0x
-    expect "exist: No error (1)"
-    keystore u0_a0 del_key 0x
-    expect "del_key: Key not found (7)"
+    log "...but cannot read keys..."
+    keystore app_0 g 0x
+    expect "2 Locked"
+    
+    log "...but they can be deleted."
+    keystore app_0 e 0x
+    expect "1 No error"
+    keystore app_0 d 0x
+    expect "1 No error"
+    keystore app_0 e 0x
+    expect "7 Key not found"
 
     #
     # password
     #
     log "wrong password"
-    keystore system unlock foo
-    expect "unlock: Wrong password (4 tries left) (13)"
+    keystore system u foo
+    expect "13 Wrong password (4 tries left)"
     log "right password"
-    keystore system unlock bar
-    expect "unlock: No error (1)"
-
+    keystore system u bar
+    expect "1 No error"
+    
     log "make the password foo"
-    keystore system password foo
-    expect "password: No error (1)"
-
+    keystore system p foo
+    expect "1 No error"
+    
     #
     # final reset
     #
     log "reset wipes everything for all users"
-    keystore system reset
-    expect "reset: No error (1)"
+    keystore system r
+    expect "1 No error"
     list_keystore_directory
-    expect "-rw------- keystore keystore        4 .metadata"
-    expect "drwx------ keystore keystore          user_0"
-    list_keystore_directory /user_0
-
-    keystore system test
-    expect "test: Uninitialized (3)"
-}
-
-function test_grant() {
-    log "test granting"
-    keystore system reset
-    expect "reset: No error (1)"
-    keystore system password test_pass
-    expect "password: No error (1)"
-
-    keystore_in system granted_key_value insert granted_key
-    expect "insert: No error (1)"
-  
-    # Cannot read before grant.
-    keystore u10_a0 get granted_key
     
-    # Grant and read.
-    log "System grants to u0_a1"
-    keystore system grant granted_key 10001 
-    expect "Working with uid 10001"
-    expect "grant: No error (1)"
-    keystore u0_a1 get 1000_granted_key
-    expect "granted_key_value"
+    keystore system t
+    expect "3 Uninitialized"
+
 }
 
 function test_4599735() {
     # http://b/4599735
     log "start regression test for b/4599735"
-    keystore system reset
-    expect "reset: No error (1)"
-    list_keystore_directory /user_0
+    keystore system r
+    expect "1 No error"
 
-    keystore system password foo
-    expect "password: No error (1)"
+    keystore system p foo
+    expect "1 No error"
 
-    keystore_in system quux insert baz
-    expect "insert: No error (1)"
-
-    keystore root get baz
+    keystore system i baz quux
+    expect "1 No error"
+    
+    keystore root g baz
+    expect "1 No error"
     expect "quux"
 
-    keystore system lock
-    expect "lock: No error (1)"
+    keystore system l
+    expect "1 No error"
 
-    keystore system password foo
-    expect "password: No error (1)"
+    keystore system p foo
+    expect "1 No error"
 
     log "after unlock, regression led to result of '8 Value corrupted'"
-    keystore root get baz
+    keystore root g baz
+    expect "1 No error"
     expect "quux"
 
-    keystore system reset
-    expect "reset: No error (1)"
+    keystore system r
+    expect "1 No error"
     log "end regression test for b/4599735"
 }
 
@@ -288,7 +265,6 @@
     log $tag START
     test_basic
     test_4599735
-    test_grant
     compare
     log $tag PASSED
     cleanup_output
diff --git a/keystore/tests/Android.mk b/keystore/tests/Android.mk
index be8c426..8126c94 100644
--- a/keystore/tests/Android.mk
+++ b/keystore/tests/Android.mk
@@ -22,10 +22,12 @@
 LOCAL_MULTILIB := 32
 endif
 LOCAL_CFLAGS := -Wall -Wextra -Werror
-LOCAL_SRC_FILES := auth_token_table_test.cpp
-LOCAL_MODULE := auth_token_table_test
+LOCAL_SRC_FILES := \
+	auth_token_table_test.cpp
+LOCAL_MODULE := keystore_unit_tests
+LOCAL_MODULE_TAGS := test
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-LOCAL_STATIC_LIBRARIES := libgtest_main libkeystore_test
+LOCAL_STATIC_LIBRARIES := libgtest_main libkeystore_test liblog
 LOCAL_SHARED_LIBRARIES := libkeymaster_messages
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_NATIVE_TEST)
diff --git a/keystore/tests/Makefile b/keystore/tests/Makefile
index 5c1117f..2720b0f 100644
--- a/keystore/tests/Makefile
+++ b/keystore/tests/Makefile
@@ -31,7 +31,7 @@
 COMPILER_SPECIFIC_ARGS=-std=c++0x -fprofile-arcs
 endif
 
-CPPFLAGS=$(INCLUDES) -g -O0 -MD
+CPPFLAGS=$(INCLUDES) -g -O0 -MD -DHOST_BUILD
 CXXFLAGS=-Wall -Werror -Wno-unused -Winit-self -Wpointer-arith	-Wunused-parameter \
         -Werror=sign-compare -Wmissing-declarations -ftest-coverage -fno-permissive \
 	-Wno-deprecated-declarations -fno-exceptions -DKEYMASTER_NAME_TAGS \
@@ -46,7 +46,14 @@
 # file here (not headers).
 CPPSRCS=\
 	../auth_token_table.cpp \
-	auth_token_table_test.cpp
+	auth_token_table_test.cpp \
+	gtest_main.cpp \
+	$(KEYMASTER)/authorization_set.cpp \
+	$(KEYMASTER)/keymaster_tags.cpp \
+	$(KEYMASTER)/logger.cpp \
+	$(KEYMASTER)/serializable.cpp
+
+CCSRCS=$(GTEST)/src/gtest-all.cc
 
 # This list of binaries determes what gets built and run.  Add each new test binary here.
 BINARIES=\
@@ -60,10 +67,13 @@
 
 run: $(BINARIES:=.run)
 
+GTEST_OBJS = $(GTEST)/src/gtest-all.o gtest_main.o
+
 auth_token_table_test: auth_token_table_test.o \
 	../auth_token_table.o \
-	$(GTEST)/src/gtest-all.o \
+	$(GTEST_OBJS) \
 	$(KEYMASTER)/authorization_set.o \
+	$(KEYMASTER)/keymaster_tags.o \
 	$(KEYMASTER)/logger.o \
 	$(KEYMASTER)/serializable.o
 
diff --git a/keystore/tests/auth_token_table_test.cpp b/keystore/tests/auth_token_table_test.cpp
index b1c0f49..1b31cf5 100644
--- a/keystore/tests/auth_token_table_test.cpp
+++ b/keystore/tests/auth_token_table_test.cpp
@@ -23,11 +23,6 @@
 
 using std::vector;
 
-int main(int argc, char** argv) {
-    ::testing::InitGoogleTest(&argc, argv);
-    int result = RUN_ALL_TESTS();
-}
-
 inline bool operator==(const hw_auth_token_t& a, const hw_auth_token_t& b) {
     return (memcmp(&a, &b, sizeof(a)) == 0);
 }
@@ -109,24 +104,24 @@
 
     const hw_auth_token_t* found;
 
-    ASSERT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0, &found));
+    ASSERT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(1U, found->user_id);
     EXPECT_EQ(2U, found->authenticator_id);
 
-    ASSERT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), 0, &found));
+    ASSERT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(1U, found->user_id);
     EXPECT_EQ(2U, found->authenticator_id);
 
-    ASSERT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), 0, &found));
+    ASSERT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(3U, found->user_id);
     EXPECT_EQ(4U, found->authenticator_id);
 
-    ASSERT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(4), 0, &found));
+    ASSERT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(4), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(3U, found->user_id);
     EXPECT_EQ(4U, found->authenticator_id);
 
     ASSERT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(5), 0, &found));
+              table.FindAuthorization(make_set(5), KM_PURPOSE_SIGN, 0, &found));
 }
 
 TEST(AuthTokenTableTest, FlushTable) {
@@ -140,9 +135,9 @@
 
     // All three should be in the table.
     EXPECT_EQ(3U, table.size());
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), KM_PURPOSE_SIGN, 0, &found));
 
     table.Clear();
     EXPECT_EQ(0U, table.size());
@@ -159,32 +154,32 @@
 
     // All three should be in the table.
     EXPECT_EQ(3U, table.size());
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), KM_PURPOSE_SIGN, 0, &found));
 
     table.AddAuthenticationToken(make_token(4));
 
     // Oldest should be gone.
     EXPECT_EQ(3U, table.size());
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(1), 0, &found));
+              table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0, &found));
 
     // Others should be there, including the new one (4).  Search for it first, then the others, so
     // 4 becomes the least recently used.
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(4), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(4), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), KM_PURPOSE_SIGN, 0, &found));
 
     table.AddAuthenticationToken(make_token(5));
 
     // 5 should have replaced 4.
     EXPECT_EQ(3U, table.size());
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(4), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(5), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), 0, &found));
+              table.FindAuthorization(make_set(4), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(5), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), KM_PURPOSE_SIGN, 0, &found));
 
     table.AddAuthenticationToken(make_token(6));
     table.AddAuthenticationToken(make_token(7));
@@ -192,12 +187,12 @@
     // 2 and 5 should be gone
     EXPECT_EQ(3U, table.size());
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(2), 0, &found));
+              table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(5), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(6), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(7), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), 0, &found));
+              table.FindAuthorization(make_set(5), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(6), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(7), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(3), KM_PURPOSE_SIGN, 0, &found));
 
     table.AddAuthenticationToken(make_token(8));
     table.AddAuthenticationToken(make_token(9));
@@ -206,22 +201,23 @@
     // Only the three most recent should be there.
     EXPECT_EQ(3U, table.size());
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(1), 0, &found));
+              table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(2), 0, &found));
+              table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(3), 0, &found));
+              table.FindAuthorization(make_set(3), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(4), 0, &found));
+              table.FindAuthorization(make_set(4), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(5), 0, &found));
+              table.FindAuthorization(make_set(5), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(6), 0, &found));
+              table.FindAuthorization(make_set(6), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(7), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(8), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(9), 0, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(10), 0, &found));
+              table.FindAuthorization(make_set(7), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(8), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(9), KM_PURPOSE_SIGN, 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(make_set(10), KM_PURPOSE_SIGN, 0, &found));
 }
 
 TEST(AuthTokenTableTest, AuthenticationNotRequired) {
@@ -229,8 +225,9 @@
     const hw_auth_token_t* found;
 
     EXPECT_EQ(AuthTokenTable::AUTH_NOT_REQUIRED,
-              table.FindAuthorization(AuthorizationSetBuilder().Authorization(TAG_NO_AUTH_REQUIRED),
-                                      0 /* no challenge */, &found));
+              table.FindAuthorization(
+                  AuthorizationSetBuilder().Authorization(TAG_NO_AUTH_REQUIRED).build(),
+                  KM_PURPOSE_SIGN, 0 /* no challenge */, &found));
 }
 
 TEST(AuthTokenTableTest, OperationHandleNotFound) {
@@ -239,14 +236,15 @@
 
     table.AddAuthenticationToken(make_token(1, 0, 1, 5));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(1, 0 /* no timeout */),
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
                                       2 /* non-matching challenge */, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1, 0 /* no timeout */),
-                                                          1 /* matching challenge */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      1 /* matching challenge */, &found));
     table.MarkCompleted(1);
-    EXPECT_EQ(
-        AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-        table.FindAuthorization(make_set(1, 0 /* no timeout */), 1 /* used challenge */, &found));
+    EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      1 /* used challenge */, &found));
 }
 
 TEST(AuthTokenTableTest, OperationHandleRequired) {
@@ -254,9 +252,9 @@
     const hw_auth_token_t* found;
 
     table.AddAuthenticationToken(make_token(1));
-    EXPECT_EQ(
-        AuthTokenTable::OP_HANDLE_REQUIRED,
-        table.FindAuthorization(make_set(1, 0 /* no timeout */), 0 /* no op handle */, &found));
+    EXPECT_EQ(AuthTokenTable::OP_HANDLE_REQUIRED,
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      0 /* no op handle */, &found));
 }
 
 TEST(AuthTokenTableTest, AuthSidChanged) {
@@ -265,7 +263,8 @@
 
     table.AddAuthenticationToken(make_token(1, 3, /* op handle */ 1));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_WRONG_SID,
-              table.FindAuthorization(make_set(2, 0 /* no timeout */), 1 /* op handle */, &found));
+              table.FindAuthorization(make_set(2, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      1 /* op handle */, &found));
 }
 
 TEST(AuthTokenTableTest, TokenExpired) {
@@ -281,13 +280,18 @@
     // expired.  An additional check of the secure timestamp (in the token) will be made by
     // keymaster when the found token is passed to it.
     table.AddAuthenticationToken(make_token(1, 0));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(key_info, 0 /* no op handle */, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(key_info, 0 /* no op handle */, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(key_info, 0 /* no op handle */, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(key_info, 0 /* no op handle */, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(key_info, 0 /* no op handle */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(key_info, KM_PURPOSE_SIGN, 0 /* no op handle */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(key_info, KM_PURPOSE_SIGN, 0 /* no op handle */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(key_info, KM_PURPOSE_SIGN, 0 /* no op handle */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(key_info, KM_PURPOSE_SIGN, 0 /* no op handle */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(key_info, KM_PURPOSE_SIGN, 0 /* no op handle */, &found));
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_EXPIRED,
-              table.FindAuthorization(key_info, 0 /* no op handle */, &found));
+              table.FindAuthorization(key_info, KM_PURPOSE_SIGN, 0 /* no op handle */, &found));
 }
 
 TEST(AuthTokenTableTest, MarkNonexistentEntryCompleted) {
@@ -305,7 +309,7 @@
     table.AddAuthenticationToken(make_token(1, 0, 0, 0));
     table.AddAuthenticationToken(make_token(1, 0, 0, 1));
     EXPECT_EQ(1U, table.size());
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(1U, ntoh(found->timestamp));
 
     // Add a third token, this with a different RSID.  It should not be superseded.
@@ -316,9 +320,9 @@
     table.AddAuthenticationToken(make_token(1, 0, 0, 3));
     table.AddAuthenticationToken(make_token(2, 0, 0, 4));
     EXPECT_EQ(2U, table.size());
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(3U, ntoh(found->timestamp));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), 0, &found));
+    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0, &found));
     EXPECT_EQ(4U, ntoh(found->timestamp));
 
     // Add another, this one with a challenge value.  It should supersede the old one since it is
@@ -334,10 +338,12 @@
     // Should be able to find each of them, by specifying their challenge, with a key that is not
     // timed (timed keys don't care about challenges).
     EXPECT_EQ(AuthTokenTable::OK,
-              table.FindAuthorization(make_set(1, 0 /* no timeout*/), 1 /* challenge */, &found));
+              table.FindAuthorization(make_set(1, 0 /* no timeout*/), KM_PURPOSE_SIGN,
+                                      1 /* challenge */, &found));
     EXPECT_EQ(5U, ntoh(found->timestamp));
     EXPECT_EQ(AuthTokenTable::OK,
-              table.FindAuthorization(make_set(1, 0 /* no timeout */), 2 /* challenge */, &found));
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      2 /* challenge */, &found));
     EXPECT_EQ(6U, ntoh(found->timestamp));
 
     // Add another, without a challenge, and the same timestamp as the last one.  This new one
@@ -345,7 +351,8 @@
     // since it seems unlikely to occur in practice.
     table.AddAuthenticationToken(make_token(1, 0, 0, 6));
     EXPECT_EQ(4U, table.size());
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0 /* challenge */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0 /* challenge */, &found));
     EXPECT_EQ(6U, ntoh(found->timestamp));
 
     // Add another without a challenge but an increased timestamp. This should supersede the
@@ -353,9 +360,11 @@
     table.AddAuthenticationToken(make_token(1, 0, 0, 7));
     EXPECT_EQ(4U, table.size());
     EXPECT_EQ(AuthTokenTable::OK,
-              table.FindAuthorization(make_set(1, 0 /* no timeout */), 2 /* challenge */, &found));
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      2 /* challenge */, &found));
     EXPECT_EQ(6U, ntoh(found->timestamp));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0 /* challenge */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0 /* challenge */, &found));
     EXPECT_EQ(7U, ntoh(found->timestamp));
 
     // Mark the entry with challenge 2 as complete.  Since there's a newer challenge-free entry, the
@@ -363,8 +372,10 @@
     table.MarkCompleted(2);
     EXPECT_EQ(3U, table.size());
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(1, 0 /* no timeout */), 2 /* challenge */, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0 /* challenge */, &found));
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      2 /* challenge */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0 /* challenge */, &found));
     EXPECT_EQ(7U, ntoh(found->timestamp));
 
     // Add another SID 1 entry with a challenge.  It supersedes the previous SID 1 entry with
@@ -373,15 +384,18 @@
     EXPECT_EQ(3U, table.size());
 
     EXPECT_EQ(AuthTokenTable::OK,
-              table.FindAuthorization(make_set(1, 0 /* no timeout */), 1 /* challenge */, &found));
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      1 /* challenge */, &found));
     EXPECT_EQ(5U, ntoh(found->timestamp));
 
     EXPECT_EQ(AuthTokenTable::OK,
-              table.FindAuthorization(make_set(1, 0 /* no timeout */), 3 /* challenge */, &found));
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      3 /* challenge */, &found));
     EXPECT_EQ(8U, ntoh(found->timestamp));
 
     // SID 2 entry is still there.
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(2), 0 /* challenge */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(make_set(2), KM_PURPOSE_SIGN, 0 /* challenge */, &found));
     EXPECT_EQ(4U, ntoh(found->timestamp));
 
     // Mark the entry with challenge 3 as complete.  Since the older challenge 1 entry is
@@ -390,10 +404,12 @@
     EXPECT_EQ(3U, table.size());
 
     EXPECT_EQ(AuthTokenTable::OK,
-              table.FindAuthorization(make_set(1, 0 /* no timeout */), 1 /* challenge */, &found));
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      1 /* challenge */, &found));
     EXPECT_EQ(5U, ntoh(found->timestamp));
 
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0 /* challenge */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0 /* challenge */, &found));
     EXPECT_EQ(8U, ntoh(found->timestamp));
 
     // Mark the entry with challenge 1 as complete.  Since there's a newer one (with challenge 3,
@@ -401,8 +417,10 @@
     table.MarkCompleted(1);
     EXPECT_EQ(2U, table.size());
     EXPECT_EQ(AuthTokenTable::AUTH_TOKEN_NOT_FOUND,
-              table.FindAuthorization(make_set(1, 0 /* no timeout */), 1 /* challenge */, &found));
-    EXPECT_EQ(AuthTokenTable::OK, table.FindAuthorization(make_set(1), 0 /* challenge */, &found));
+              table.FindAuthorization(make_set(1, 0 /* no timeout */), KM_PURPOSE_SIGN,
+                                      1 /* challenge */, &found));
+    EXPECT_EQ(AuthTokenTable::OK,
+              table.FindAuthorization(make_set(1), KM_PURPOSE_SIGN, 0 /* challenge */, &found));
     EXPECT_EQ(8U, ntoh(found->timestamp));
 }
 
diff --git a/keystore/tests/gtest_main.cpp b/keystore/tests/gtest_main.cpp
new file mode 100644
index 0000000..4db0ec8
--- /dev/null
+++ b/keystore/tests/gtest_main.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2015 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 <gtest/gtest.h>
+int main(int argc, char** argv) {
+    ::testing::InitGoogleTest(&argc, argv);
+    return RUN_ALL_TESTS();
+}