am 2ac5cb65: (-s ours) Merge "Fix pessimizing move."

* commit '2ac5cb651b7fe67c1ceb36bfabdeac8ad2d352f2':
  Fix pessimizing move.
diff --git a/keystore/Android.mk b/keystore/Android.mk
index 9463f3d..e18b2d8 100644
--- a/keystore/Android.mk
+++ b/keystore/Android.mk
@@ -33,7 +33,8 @@
 	libutils \
 	libselinux \
 	libsoftkeymasterdevice \
-	libkeymaster_messages
+	libkeymaster_messages \
+	libkeymaster1
 LOCAL_MODULE := keystore
 LOCAL_MODULE_TAGS := optional
 LOCAL_C_INCLUES := system/keymaster/
diff --git a/keystore/IKeystoreService.cpp b/keystore/IKeystoreService.cpp
index fa71d91..8ed09c4 100644
--- a/keystore/IKeystoreService.cpp
+++ b/keystore/IKeystoreService.cpp
@@ -30,6 +30,7 @@
 
 namespace android {
 
+const ssize_t MAX_GENERATE_ARGS = 3;
 static keymaster_key_param_t* readParamList(const Parcel& in, size_t* length);
 
 KeystoreArg::KeystoreArg(const void* data, size_t len)
@@ -1394,6 +1395,9 @@
             int32_t argsPresent = data.readInt32();
             if (argsPresent == 1) {
                 ssize_t numArgs = data.readInt32();
+                if (numArgs > MAX_GENERATE_ARGS) {
+                    return BAD_VALUE;
+                }
                 if (numArgs > 0) {
                     for (size_t i = 0; i < (size_t) numArgs; i++) {
                         ssize_t inSize = data.readInt32();
@@ -1449,7 +1453,7 @@
                 reply->writeInt32(outSize);
                 void* buf = reply->writeInplace(outSize);
                 memcpy(buf, out, outSize);
-                free(out);
+                delete[] reinterpret_cast<uint8_t*>(out);
             } else {
                 reply->writeInt32(-1);
             }
diff --git a/keystore/auth_token_table.cpp b/keystore/auth_token_table.cpp
index 98731b3..c6e5843 100644
--- a/keystore/auth_token_table.cpp
+++ b/keystore/auth_token_table.cpp
@@ -60,18 +60,33 @@
     }
 }
 
-inline bool KeyRequiresAuthentication(const AuthorizationSet& key_info) {
-    return key_info.find(TAG_NO_AUTH_REQUIRED) == -1;
+inline bool is_secret_key_operation(keymaster_algorithm_t algorithm, keymaster_purpose_t purpose) {
+    if ((algorithm != KM_ALGORITHM_RSA || algorithm != KM_ALGORITHM_EC))
+        return true;
+    if (purpose == KM_PURPOSE_SIGN || purpose == KM_PURPOSE_DECRYPT)
+        return true;
+    return false;
 }
 
-inline bool KeyRequiresAuthPerOperation(const AuthorizationSet& key_info) {
-    return key_info.find(TAG_AUTH_TIMEOUT) == -1;
+inline bool KeyRequiresAuthentication(const AuthorizationSet& key_info,
+                                      keymaster_purpose_t purpose) {
+    keymaster_algorithm_t algorithm = KM_ALGORITHM_AES;
+    key_info.GetTagValue(TAG_ALGORITHM, &algorithm);
+    return is_secret_key_operation(algorithm, purpose) && key_info.find(TAG_NO_AUTH_REQUIRED) == -1;
+}
+
+inline bool KeyRequiresAuthPerOperation(const AuthorizationSet& key_info,
+                                        keymaster_purpose_t purpose) {
+    keymaster_algorithm_t algorithm = KM_ALGORITHM_AES;
+    key_info.GetTagValue(TAG_ALGORITHM, &algorithm);
+    return is_secret_key_operation(algorithm, purpose) && key_info.find(TAG_AUTH_TIMEOUT) == -1;
 }
 
 AuthTokenTable::Error AuthTokenTable::FindAuthorization(const AuthorizationSet& key_info,
+                                                        keymaster_purpose_t purpose,
                                                         keymaster_operation_handle_t op_handle,
                                                         const hw_auth_token_t** found) {
-    if (!KeyRequiresAuthentication(key_info))
+    if (!KeyRequiresAuthentication(key_info, purpose))
         return AUTH_NOT_REQUIRED;
 
     hw_authenticator_type_t auth_type = HW_AUTH_NONE;
@@ -80,7 +95,7 @@
     std::vector<uint64_t> key_sids;
     ExtractSids(key_info, &key_sids);
 
-    if (KeyRequiresAuthPerOperation(key_info))
+    if (KeyRequiresAuthPerOperation(key_info, purpose))
         return FindAuthPerOpAuthorization(key_sids, auth_type, op_handle, found);
     else
         return FindTimedAuthorization(key_sids, auth_type, key_info, found);
diff --git a/keystore/auth_token_table.h b/keystore/auth_token_table.h
index a63e2d8..24aa774 100644
--- a/keystore/auth_token_table.h
+++ b/keystore/auth_token_table.h
@@ -70,7 +70,7 @@
      *
      * The table retains ownership of the returned object.
      */
-    Error FindAuthorization(const AuthorizationSet& key_info,
+    Error FindAuthorization(const AuthorizationSet& key_info, keymaster_purpose_t purpose,
                             keymaster_operation_handle_t op_handle, const hw_auth_token_t** found);
 
     /**
@@ -84,8 +84,9 @@
      * The table retains ownership of the returned object.
      */
     Error FindAuthorization(const keymaster_key_param_t* params, size_t params_count,
-                            keymaster_operation_handle_t op_handle, const hw_auth_token_t** found) {
-        return FindAuthorization(AuthorizationSet(params, params_count), op_handle, found);
+                            keymaster_purpose_t purpose, keymaster_operation_handle_t op_handle,
+                            const hw_auth_token_t** found) {
+        return FindAuthorization(AuthorizationSet(params, params_count), purpose, op_handle, found);
     }
 
     /**
diff --git a/keystore/keystore.cpp b/keystore/keystore.cpp
index 04e1863..65a8ea9 100644
--- a/keystore/keystore.cpp
+++ b/keystore/keystore.cpp
@@ -63,8 +63,11 @@
 
 #include <selinux/android.h>
 
+#include <sstream>
+
 #include "auth_token_table.h"
 #include "defaults.h"
+#include "keystore_keymaster_enforcement.h"
 #include "operation.h"
 
 /* KeyStore is a secured storage for key-value pairs. In this implementation,
@@ -106,23 +109,31 @@
 };
 typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
 
-static int keymaster_device_initialize(keymaster0_device_t** dev) {
+static int keymaster_device_initialize(keymaster1_device_t** dev) {
     int rc;
 
     const hw_module_t* mod;
+    keymaster::SoftKeymasterDevice* softkeymaster = NULL;
     rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
     if (rc) {
         ALOGE("could not find any keystore module");
         goto out;
     }
 
-    rc = keymaster0_open(mod, dev);
+    rc = mod->methods->open(mod, KEYSTORE_KEYMASTER, reinterpret_cast<struct hw_device_t**>(dev));
     if (rc) {
         ALOGE("could not open keymaster device in %s (%s)",
             KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
         goto out;
     }
 
+    // Wrap older hardware modules with a softkeymaster adapter.
+    if ((*dev)->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0) {
+        return 0;
+    }
+    softkeymaster =
+            new keymaster::SoftKeymasterDevice(reinterpret_cast<keymaster0_device_t*>(*dev));
+    *dev = softkeymaster->keymaster_device();
     return 0;
 
 out:
@@ -142,8 +153,8 @@
     return 0;
 }
 
-static void keymaster_device_release(keymaster0_device_t* dev) {
-    keymaster0_close(dev);
+static void keymaster_device_release(keymaster1_device_t* dev) {
+    dev->common.close(&dev->common);
 }
 
 /***************
@@ -494,8 +505,17 @@
 
 class Blob {
 public:
-    Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
+    Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
             BlobType type) {
+        memset(&mBlob, 0, sizeof(mBlob));
+        if (valueLength > VALUE_SIZE) {
+            valueLength = VALUE_SIZE;
+            ALOGW("Provided blob length too large");
+        }
+        if (infoLength + valueLength > VALUE_SIZE) {
+            infoLength = VALUE_SIZE - valueLength;
+            ALOGW("Provided info length too large");
+        }
         mBlob.length = valueLength;
         memcpy(mBlob.value, value, valueLength);
 
@@ -516,7 +536,9 @@
         mBlob = b;
     }
 
-    Blob() {}
+    Blob() {
+        memset(&mBlob, 0, sizeof(mBlob));
+    }
 
     const uint8_t* getValue() const {
         return mBlob.value;
@@ -655,6 +677,10 @@
             return SYSTEM_ERROR;
         }
 
+        if (fileLength == 0) {
+            return VALUE_CORRUPTED;
+        }
+
         if (isEncrypted() && (state != STATE_NO_ERROR)) {
             return LOCKED;
         }
@@ -1171,6 +1197,12 @@
             }
         }
 
+        // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
+        if (keyBlob->getType() == TYPE_KEY_PAIR) {
+            keyBlob->setType(TYPE_KEYMASTER_10);
+            rc = this->put(filename, keyBlob, userId);
+        }
+
         if (type != TYPE_ANY && keyBlob->getType() != type) {
             ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
             return KEY_NOT_FOUND;
@@ -1188,6 +1220,10 @@
     ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
         Blob keyBlob;
         ResponseCode rc = get(filename, &keyBlob, type, userId);
+        if (rc == ::VALUE_CORRUPTED) {
+            // The file is corrupt, the best we can do is rm it.
+            return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
+        }
         if (rc != ::NO_ERROR) {
             return rc;
         }
@@ -1690,7 +1726,6 @@
         ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
                 TYPE_GENERIC);
         if (responseCode != ::NO_ERROR) {
-            ALOGW("Could not read %s", name8.string());
             *item = NULL;
             *itemLength = 0;
             return responseCode;
@@ -1883,194 +1918,114 @@
         if (result != ::NO_ERROR) {
             return result;
         }
-        uint8_t* data;
-        size_t dataLength;
-        int rc;
-        bool isFallback = false;
 
-        const keymaster1_device_t* device = mKeyStore->getDevice();
-        const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
-        if (device == NULL) {
-            return ::SYSTEM_ERROR;
-        }
+        KeymasterArguments params;
+        addLegacyKeyAuthorizations(params.params, keyType);
 
-        if (device->generate_keypair == NULL) {
-            return ::SYSTEM_ERROR;
-        }
-
-        if (keyType == EVP_PKEY_DSA) {
-            keymaster_dsa_keygen_params_t dsa_params;
-            memset(&dsa_params, '\0', sizeof(dsa_params));
-
-            if (keySize == -1) {
-                keySize = DSA_DEFAULT_KEY_SIZE;
-            } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
-                    || keySize > DSA_MAX_KEY_SIZE) {
-                ALOGI("invalid key size %d", keySize);
-                return ::SYSTEM_ERROR;
-            }
-            dsa_params.key_size = keySize;
-
-            if (args->size() == 3) {
-                sp<KeystoreArg> gArg = args->itemAt(0);
-                sp<KeystoreArg> pArg = args->itemAt(1);
-                sp<KeystoreArg> qArg = args->itemAt(2);
-
-                if (gArg != NULL && pArg != NULL && qArg != NULL) {
-                    dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
-                    dsa_params.generator_len = gArg->size();
-
-                    dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
-                    dsa_params.prime_p_len = pArg->size();
-
-                    dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
-                    dsa_params.prime_q_len = qArg->size();
-                } else {
-                    ALOGI("not all DSA parameters were read");
+        switch (keyType) {
+            case EVP_PKEY_EC: {
+                params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
+                if (keySize == -1) {
+                    keySize = EC_DEFAULT_KEY_SIZE;
+                } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
+                    ALOGI("invalid key size %d", keySize);
                     return ::SYSTEM_ERROR;
                 }
-            } else if (args->size() != 0) {
-                ALOGI("DSA args must be 3");
-                return ::SYSTEM_ERROR;
+                params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
+                break;
             }
-
-            if (isKeyTypeSupported(device, TYPE_DSA)) {
-                rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
-            } else {
-                isFallback = true;
-                rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
-                                                &dataLength);
-            }
-        } else if (keyType == EVP_PKEY_EC) {
-            keymaster_ec_keygen_params_t ec_params;
-            memset(&ec_params, '\0', sizeof(ec_params));
-
-            if (keySize == -1) {
-                keySize = EC_DEFAULT_KEY_SIZE;
-            } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
-                ALOGI("invalid key size %d", keySize);
-                return ::SYSTEM_ERROR;
-            }
-            ec_params.field_size = keySize;
-
-            if (isKeyTypeSupported(device, TYPE_EC)) {
-                rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
-            } else {
-                isFallback = true;
-                rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
-            }
-        } else if (keyType == EVP_PKEY_RSA) {
-            keymaster_rsa_keygen_params_t rsa_params;
-            memset(&rsa_params, '\0', sizeof(rsa_params));
-            rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
-
-            if (keySize == -1) {
-                keySize = RSA_DEFAULT_KEY_SIZE;
-            } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
-                ALOGI("invalid key size %d", keySize);
-                return ::SYSTEM_ERROR;
-            }
-            rsa_params.modulus_size = keySize;
-
-            if (args->size() > 1) {
-                ALOGI("invalid number of arguments: %zu", args->size());
-                return ::SYSTEM_ERROR;
-            } else if (args->size() == 1) {
-                sp<KeystoreArg> pubExpBlob = args->itemAt(0);
-                if (pubExpBlob != NULL) {
-                    Unique_BIGNUM pubExpBn(
-                            BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
-                                    pubExpBlob->size(), NULL));
-                    if (pubExpBn.get() == NULL) {
-                        ALOGI("Could not convert public exponent to BN");
-                        return ::SYSTEM_ERROR;
-                    }
-                    unsigned long pubExp = BN_get_word(pubExpBn.get());
-                    if (pubExp == 0xFFFFFFFFL) {
-                        ALOGI("cannot represent public exponent as a long value");
-                        return ::SYSTEM_ERROR;
-                    }
-                    rsa_params.public_exponent = pubExp;
+            case EVP_PKEY_RSA: {
+                params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
+                if (keySize == -1) {
+                    keySize = RSA_DEFAULT_KEY_SIZE;
+                } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
+                    ALOGI("invalid key size %d", keySize);
+                    return ::SYSTEM_ERROR;
                 }
+                params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
+                unsigned long exponent = RSA_DEFAULT_EXPONENT;
+                if (args->size() > 1) {
+                    ALOGI("invalid number of arguments: %zu", args->size());
+                    return ::SYSTEM_ERROR;
+                } else if (args->size() == 1) {
+                    sp<KeystoreArg> expArg = args->itemAt(0);
+                    if (expArg != NULL) {
+                        Unique_BIGNUM pubExpBn(
+                                BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
+                                          expArg->size(), NULL));
+                        if (pubExpBn.get() == NULL) {
+                            ALOGI("Could not convert public exponent to BN");
+                            return ::SYSTEM_ERROR;
+                        }
+                        exponent = BN_get_word(pubExpBn.get());
+                        if (exponent == 0xFFFFFFFFL) {
+                            ALOGW("cannot represent public exponent as a long value");
+                            return ::SYSTEM_ERROR;
+                        }
+                    } else {
+                        ALOGW("public exponent not read");
+                        return ::SYSTEM_ERROR;
+                    }
+                }
+                params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
+                                                             exponent));
+                break;
             }
-
-            rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
-        } else {
-            ALOGW("Unsupported key type %d", keyType);
-            rc = -1;
+            default: {
+                ALOGW("Unsupported key type %d", keyType);
+                return ::SYSTEM_ERROR;
+            }
         }
 
-        if (rc) {
-            return ::SYSTEM_ERROR;
+        int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
+                                 /*outCharacteristics*/ NULL);
+        if (rc != ::NO_ERROR) {
+            ALOGW("generate failed: %d", rc);
         }
-
-        String8 name8(name);
-        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
-
-        Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
-        free(data);
-
-        keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
-        keyBlob.setFallback(isFallback);
-
-        return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
+        return translateResultToLegacyResult(rc);
     }
 
     int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
             int32_t flags) {
-        targetUid = getEffectiveUid(targetUid);
-        int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
-                                                       flags & KEYSTORE_FLAG_ENCRYPTED);
-        if (result != ::NO_ERROR) {
-            return result;
-        }
-        String8 name8(name);
-        String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
+        const uint8_t* ptr = data;
 
-        return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
-                                    flags);
+        Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
+        if (!pkcs8.get()) {
+            return ::SYSTEM_ERROR;
+        }
+        Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
+        if (!pkey.get()) {
+            return ::SYSTEM_ERROR;
+        }
+        int type = EVP_PKEY_type(pkey->type);
+        KeymasterArguments params;
+        addLegacyKeyAuthorizations(params.params, type);
+        switch (type) {
+            case EVP_PKEY_RSA:
+                params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
+                break;
+            case EVP_PKEY_EC:
+                params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
+                                                             KM_ALGORITHM_EC));
+                break;
+            default:
+                ALOGW("Unsupported key type %d", type);
+                return ::SYSTEM_ERROR;
+        }
+        int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
+                               /*outCharacteristics*/ NULL);
+        if (rc != ::NO_ERROR) {
+            ALOGW("importKey failed: %d", rc);
+        }
+        return translateResultToLegacyResult(rc);
     }
 
     int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
-            size_t* outLength) {
+                 size_t* outLength) {
         if (!checkBinderPermission(P_SIGN)) {
             return ::PERMISSION_DENIED;
         }
-
-        uid_t callingUid = IPCThreadState::self()->getCallingUid();
-        Blob keyBlob;
-        String8 name8(name);
-
-        ALOGV("sign %s from uid %d", name8.string(), callingUid);
-
-        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
-                ::TYPE_KEY_PAIR);
-        if (responseCode != ::NO_ERROR) {
-            return responseCode;
-        }
-
-        const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
-        if (device == NULL) {
-            ALOGE("no keymaster device; cannot sign");
-            return ::SYSTEM_ERROR;
-        }
-
-        if (device->sign_data == NULL) {
-            ALOGE("device doesn't implement signing");
-            return ::SYSTEM_ERROR;
-        }
-
-        keymaster_rsa_sign_params_t params;
-        params.digest_type = DIGEST_NONE;
-        params.padding_type = PADDING_NONE;
-        int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
-                length, out, outLength);
-        if (rc) {
-            ALOGW("device couldn't sign data");
-            return ::SYSTEM_ERROR;
-        }
-
-        return ::NO_ERROR;
+        return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
     }
 
     int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
@@ -2078,38 +2033,8 @@
         if (!checkBinderPermission(P_VERIFY)) {
             return ::PERMISSION_DENIED;
         }
-
-        uid_t callingUid = IPCThreadState::self()->getCallingUid();
-        Blob keyBlob;
-        String8 name8(name);
-        int rc;
-
-        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
-                TYPE_KEY_PAIR);
-        if (responseCode != ::NO_ERROR) {
-            return responseCode;
-        }
-
-        const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
-        if (device == NULL) {
-            return ::SYSTEM_ERROR;
-        }
-
-        if (device->verify_data == NULL) {
-            return ::SYSTEM_ERROR;
-        }
-
-        keymaster_rsa_sign_params_t params;
-        params.digest_type = DIGEST_NONE;
-        params.padding_type = PADDING_NONE;
-
-        rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
-                dataLength, signature, signatureLength);
-        if (rc) {
-            return ::SYSTEM_ERROR;
-        } else {
-            return ::NO_ERROR;
-        }
+        return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
+                                 KM_PURPOSE_VERIFY);
     }
 
     /*
@@ -2124,40 +2049,15 @@
      * intentions are.
      */
     int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
-        uid_t callingUid = IPCThreadState::self()->getCallingUid();
-        if (!checkBinderPermission(P_GET)) {
-            ALOGW("permission denied for %d: get_pubkey", callingUid);
-            return ::PERMISSION_DENIED;
+        ExportResult result;
+        exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
+        if (result.resultCode != ::NO_ERROR) {
+            ALOGW("export failed: %d", result.resultCode);
+            return translateResultToLegacyResult(result.resultCode);
         }
 
-        Blob keyBlob;
-        String8 name8(name);
-
-        ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
-
-        ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
-                TYPE_KEY_PAIR);
-        if (responseCode != ::NO_ERROR) {
-            return responseCode;
-        }
-
-        const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
-        if (device == NULL) {
-            return ::SYSTEM_ERROR;
-        }
-
-        if (device->get_keypair_public == NULL) {
-            ALOGE("device has no get_keypair_public implementation!");
-            return ::SYSTEM_ERROR;
-        }
-
-        int rc;
-        rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
-                pubkeyLength);
-        if (rc) {
-            return ::SYSTEM_ERROR;
-        }
-
+        *pubkey = result.exportData.release();
+        *pubkeyLength = result.dataLength;
         return ::NO_ERROR;
     }
 
@@ -2570,7 +2470,7 @@
             return;
         }
         const hw_auth_token_t* authToken = NULL;
-        int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
+        int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
                                                 /*failOnTokenMissing*/ false);
         // If per-operation auth is needed we need to begin the operation and
         // the client will need to authorize that operation before calling
@@ -2593,6 +2493,27 @@
             }
         }
         keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
+
+        // Create a keyid for this key.
+        keymaster::km_id_t keyid;
+        if (!enforcement_policy.CreateKeyId(key, &keyid)) {
+            ALOGE("Failed to create a key ID for authorization checking.");
+            result->resultCode = KM_ERROR_UNKNOWN_ERROR;
+            return;
+        }
+
+        // Check that all key authorization policy requirements are met.
+        keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
+        key_auths.push_back(characteristics->sw_enforced);
+        keymaster::AuthorizationSet operation_params(inParams);
+        err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
+                                                    0 /* op_handle */,
+                                                    true /* is_begin_operation */);
+        if (err) {
+            result->resultCode = err;
+            return;
+        }
+
         keymaster_key_param_set_t outParams = {NULL, 0};
         err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
 
@@ -2601,7 +2522,16 @@
         while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
             sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
             ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
-            if (abort(oldest) != ::NO_ERROR) {
+
+            // We mostly ignore errors from abort() below because all we care about is whether at
+            // least one pruneable operation has been removed.
+            size_t op_count_before = mOperationMap.getPruneableOperationCount();
+            int abort_error = abort(oldest);
+            size_t op_count_after = mOperationMap.getPruneableOperationCount();
+            if (op_count_after >= op_count_before) {
+                // Failed to create space for a new operation. Bail to avoid an infinite loop.
+                ALOGE("Failed to remove pruneable operation %p, error: %d",
+                      oldest.get(), abort_error);
                 break;
             }
             err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
@@ -2611,8 +2541,8 @@
             return;
         }
 
-        sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
-                                                                characteristics.release(),
+        sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
+                                                                appToken, characteristics.release(),
                                                                 pruneable);
         if (authToken) {
             mOperationMap.setOperationAuthToken(operationToken, authToken);
@@ -2639,7 +2569,10 @@
         }
         const keymaster1_device_t* dev;
         keymaster_operation_handle_t handle;
-        if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
+        keymaster_purpose_t purpose;
+        keymaster::km_id_t keyid;
+        const keymaster_key_characteristics_t* characteristics;
+        if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
             result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
             return;
         }
@@ -2655,6 +2588,18 @@
         keymaster_blob_t output = {NULL, 0};
         keymaster_key_param_set_t outParams = {NULL, 0};
 
+        // Check that all key authorization policy requirements are met.
+        keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
+        key_auths.push_back(characteristics->sw_enforced);
+        keymaster::AuthorizationSet operation_params(inParams);
+        result->resultCode =
+                enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths,
+                                                      operation_params, handle,
+                                                      false /* is_begin_operation */);
+        if (result->resultCode) {
+            return;
+        }
+
         keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
                                             &output);
         result->data.reset(const_cast<uint8_t*>(output.data));
@@ -2676,7 +2621,10 @@
         }
         const keymaster1_device_t* dev;
         keymaster_operation_handle_t handle;
-        if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
+        keymaster_purpose_t purpose;
+        keymaster::km_id_t keyid;
+        const keymaster_key_characteristics_t* characteristics;
+        if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
             result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
             return;
         }
@@ -2703,6 +2651,18 @@
         keymaster_blob_t input = {signature, signatureLength};
         keymaster_blob_t output = {NULL, 0};
         keymaster_key_param_set_t outParams = {NULL, 0};
+
+        // Check that all key authorization policy requirements are met.
+        keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
+        key_auths.push_back(characteristics->sw_enforced);
+        keymaster::AuthorizationSet operation_params(inParams);
+        err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
+                                                    handle, false /* is_begin_operation */);
+        if (err) {
+            result->resultCode = err;
+            return;
+        }
+
         err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
         // Remove the operation regardless of the result
         mOperationMap.removeOperation(token);
@@ -2720,7 +2680,9 @@
     int32_t abort(const sp<IBinder>& token) {
         const keymaster1_device_t* dev;
         keymaster_operation_handle_t handle;
-        if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
+        keymaster_purpose_t purpose;
+        keymaster::km_id_t keyid;
+        if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
             return KM_ERROR_INVALID_OPERATION_HANDLE;
         }
         mOperationMap.removeOperation(token);
@@ -2741,7 +2703,9 @@
         const keymaster1_device_t* dev;
         keymaster_operation_handle_t handle;
         const keymaster_key_characteristics_t* characteristics;
-        if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
+        keymaster_purpose_t purpose;
+        keymaster::km_id_t keyid;
+        if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
             return false;
         }
         const hw_auth_token_t* authToken = NULL;
@@ -2947,6 +2911,7 @@
      */
     int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
                          keymaster_operation_handle_t handle,
+                         keymaster_purpose_t purpose,
                          const hw_auth_token_t** authToken,
                          bool failOnTokenMissing = true) {
 
@@ -2957,9 +2922,8 @@
         for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
             allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
         }
-        keymaster::AuthTokenTable::Error err =
-                mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
-                                                  allCharacteristics.size(), handle, authToken);
+        keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
+                allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
         switch (err) {
             case keymaster::AuthTokenTable::OK:
             case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
@@ -3005,10 +2969,13 @@
             const keymaster1_device_t* dev;
             keymaster_operation_handle_t handle;
             const keymaster_key_characteristics_t* characteristics = NULL;
-            if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
+            keymaster_purpose_t purpose;
+            keymaster::km_id_t keyid;
+            if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev,
+                                            &characteristics)) {
                 return KM_ERROR_INVALID_OPERATION_HANDLE;
             }
-            int32_t result = getAuthToken(characteristics, handle, &authToken);
+            int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
             if (result != ::NO_ERROR) {
                 return result;
             }
@@ -3020,9 +2987,144 @@
         return ::NO_ERROR;
     }
 
+    /**
+     * Translate a result value to a legacy return value. All keystore errors are
+     * preserved and keymaster errors become SYSTEM_ERRORs
+     */
+    inline int32_t translateResultToLegacyResult(int32_t result) {
+        if (result > 0) {
+            return result;
+        }
+        return ::SYSTEM_ERROR;
+    }
+
+    void addLegacyKeyAuthorizations(std::vector<keymaster_key_param_t>& params, int keyType) {
+        params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
+        params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
+        params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
+        params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
+        params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
+        if (keyType == EVP_PKEY_RSA) {
+            params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
+            params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
+            params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_PSS));
+            params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_RSA_OAEP));
+        }
+        params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
+        params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_MD5));
+        params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA1));
+        params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_224));
+        params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_256));
+        params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_384));
+        params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_SHA_2_512));
+        params.push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
+        params.push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
+        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));
+    }
+
+    keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
+        for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
+            if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
+                return &characteristics->hw_enforced.params[i];
+            }
+        }
+        for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
+            if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
+                return &characteristics->sw_enforced.params[i];
+            }
+        }
+        return NULL;
+    }
+
+    void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
+        // All legacy keys are DIGEST_NONE/PAD_NONE.
+        params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
+        params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
+
+        // Look up the algorithm of the key.
+        KeyCharacteristics characteristics;
+        int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
+        if (rc != ::NO_ERROR) {
+            ALOGE("Failed to get key characteristics");
+            return;
+        }
+        keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
+        if (!algorithm) {
+            ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
+            return;
+        }
+        params.push_back(*algorithm);
+    }
+
+    int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
+                              uint8_t** out, size_t* outLength, const uint8_t* signature,
+                              size_t signatureLength, keymaster_purpose_t purpose) {
+
+        std::basic_stringstream<uint8_t> outBuffer;
+        OperationResult result;
+        KeymasterArguments inArgs;
+        addLegacyBeginParams(name, inArgs.params);
+        sp<IBinder> appToken(new BBinder);
+        sp<IBinder> token;
+
+        begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
+        if (result.resultCode != ResponseCode::NO_ERROR) {
+            if (result.resultCode == ::KEY_NOT_FOUND) {
+                ALOGW("Key not found");
+            } else {
+                ALOGW("Error in begin: %d", result.resultCode);
+            }
+            return translateResultToLegacyResult(result.resultCode);
+        }
+        inArgs.params.clear();
+        token = result.token;
+        size_t consumed = 0;
+        size_t lastConsumed = 0;
+        do {
+            update(token, inArgs, data + consumed, length - consumed, &result);
+            if (result.resultCode != ResponseCode::NO_ERROR) {
+                ALOGW("Error in update: %d", result.resultCode);
+                return translateResultToLegacyResult(result.resultCode);
+            }
+            if (out) {
+                outBuffer.write(result.data.get(), result.dataLength);
+            }
+            lastConsumed = result.inputConsumed;
+            consumed += lastConsumed;
+        } while (consumed < length && lastConsumed > 0);
+
+        if (consumed != length) {
+            ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
+            return ::SYSTEM_ERROR;
+        }
+
+        finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
+        if (result.resultCode != ResponseCode::NO_ERROR) {
+            ALOGW("Error in finish: %d", result.resultCode);
+            return translateResultToLegacyResult(result.resultCode);
+        }
+        if (out) {
+            outBuffer.write(result.data.get(), result.dataLength);
+        }
+
+        if (out) {
+            auto buf = outBuffer.str();
+            *out = new uint8_t[buf.size()];
+            memcpy(*out, buf.c_str(), buf.size());
+            *outLength = buf.size();
+        }
+
+        return ::NO_ERROR;
+    }
+
     ::KeyStore* mKeyStore;
     OperationMap mOperationMap;
     keymaster::AuthTokenTable mAuthTokenTable;
+    KeystoreKeymasterEnforcement enforcement_policy;
 };
 
 }; // namespace android
@@ -3042,7 +3144,7 @@
         return 1;
     }
 
-    keymaster0_device_t* dev;
+    keymaster1_device_t* dev;
     if (keymaster_device_initialize(&dev)) {
         ALOGE("keystore keymaster could not be initialized; exiting");
         return 1;
@@ -3067,7 +3169,7 @@
         ALOGI("SELinux: Keystore SELinux is disabled.\n");
     }
 
-    KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
+    KeyStore keyStore(&entropy, dev, fallback);
     keyStore.initialize();
     android::sp<android::IServiceManager> sm = android::defaultServiceManager();
     android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
diff --git a/keystore/keystore_keymaster_enforcement.h b/keystore/keystore_keymaster_enforcement.h
new file mode 100644
index 0000000..d20d7a6
--- /dev/null
+++ b/keystore/keystore_keymaster_enforcement.h
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+
+#ifndef KEYSTORE_KEYMASTER_ENFORCEMENT_H_
+#define KEYSTORE_KEYMASTER_ENFORCEMENT_H_
+
+#include <time.h>
+
+#include <keymaster/keymaster_enforcement.h>
+
+/**
+ * This is a specialization of the KeymasterEnforcement class to be used by Keystore to enforce
+ * keymaster requirements on all key operation.
+ */
+class KeystoreKeymasterEnforcement : public keymaster::KeymasterEnforcement {
+  public:
+    KeystoreKeymasterEnforcement() : KeymasterEnforcement(64, 64) {}
+
+    uint32_t get_current_time() const override {
+        struct timespec tp;
+        int err = clock_gettime(CLOCK_MONOTONIC, &tp);
+        if (err || tp.tv_sec < 0)
+            return 0;
+        return static_cast<uint32_t>(tp.tv_sec);
+    }
+
+    bool activation_date_valid(uint64_t activation_date) const override {
+        time_t now = time(NULL);
+        if (now == static_cast<time_t>(-1)) {
+            // Failed to obtain current time -- fail safe: activation_date hasn't yet occurred.
+            return false;
+        } else if (now < 0) {
+            // Current time is prior to start of the epoch -- activation_date hasn't yet occurred.
+            return false;
+        }
+
+        // time(NULL) returns seconds since epoch and "loses" milliseconds information. We thus add
+        // 999 ms to now_date to avoid a situation where an activation_date of up to 999ms in the
+        // past may still be considered to still be in the future. This can be removed once
+        // time(NULL) is replaced by a millisecond-precise source of time.
+        uint64_t now_date = static_cast<uint64_t>(now) * 1000 + 999;
+        return now_date >= activation_date;
+    }
+
+    bool expiration_date_passed(uint64_t expiration_date) const override {
+        time_t now = time(NULL);
+        if (now == static_cast<time_t>(-1)) {
+            // Failed to obtain current time -- fail safe: expiration_date has passed.
+            return true;
+        } else if (now < 0) {
+            // Current time is prior to start of the epoch: expiration_date hasn't yet occurred.
+            return false;
+        }
+
+        // time(NULL) returns seconds since epoch and "loses" milliseconds information. As a result,
+        // expiration_date of up to 999 ms in the past may still be considered in the future. This
+        // is OK.
+        uint64_t now_date = static_cast<uint64_t>(now) * 1000;
+        return now_date > expiration_date;
+    }
+
+    bool auth_token_timed_out(const hw_auth_token_t&, uint32_t) const {
+        // Assume the token has not timed out, because AuthTokenTable would not have returned it if
+        // the timeout were past.  Secure hardware will also check timeouts if it supports them.
+        return false;
+    }
+
+    bool ValidateTokenSignature(const hw_auth_token_t&) const override {
+        // Non-secure world cannot validate token signatures because it doesn't have access to the
+        // signing key. Assume the token is good.
+        return true;
+    }
+};
+
+#endif  // KEYSTORE_KEYMASTER_ENFORCEMENT_H_
diff --git a/keystore/operation.cpp b/keystore/operation.cpp
index c77552e..3b381c4 100644
--- a/keystore/operation.cpp
+++ b/keystore/operation.cpp
@@ -25,12 +25,13 @@
 }
 
 sp<IBinder> OperationMap::addOperation(keymaster_operation_handle_t handle,
+                                       uint64_t keyid, keymaster_purpose_t purpose,
                                        const keymaster1_device_t* dev,
                                        sp<IBinder> appToken,
                                        keymaster_key_characteristics_t* characteristics,
                                        bool pruneable) {
     sp<IBinder> token = new BBinder();
-    mMap[token] = Operation(handle, dev, characteristics, appToken);
+    mMap[token] = Operation(handle, keyid, purpose, dev, characteristics, appToken);
     if (pruneable) {
         mLru.push_back(token);
     }
@@ -42,6 +43,7 @@
 }
 
 bool OperationMap::getOperation(sp<IBinder> token, keymaster_operation_handle_t* outHandle,
+                                uint64_t* outKeyid, keymaster_purpose_t* outPurpose,
                                 const keymaster1_device_t** outDevice,
                                 const keymaster_key_characteristics_t** outCharacteristics) {
     if (!outHandle || !outDevice) {
@@ -54,6 +56,8 @@
     updateLru(token);
 
     *outHandle = entry->second.handle;
+    *outKeyid = entry->second.keyid;
+    *outPurpose = entry->second.purpose;
     *outDevice = entry->second.device;
     if (outCharacteristics) {
         *outCharacteristics = entry->second.characteristics.get();
@@ -99,10 +103,14 @@
     }
 }
 
-bool OperationMap::hasPruneableOperation() {
+bool OperationMap::hasPruneableOperation() const {
     return mLru.size() != 0;
 }
 
+size_t OperationMap::getPruneableOperationCount() const {
+    return mLru.size();
+}
+
 sp<IBinder> OperationMap::getOldestPruneableOperation() {
     if (!hasPruneableOperation()) {
         return sp<IBinder>(NULL);
@@ -115,11 +123,7 @@
     if (entry == mMap.end()) {
         return false;
     }
-    if (entry->second.authToken.get() != NULL) {
-        *outToken = *entry->second.authToken;
-    } else {
-        *outToken = NULL;
-    }
+    *outToken = entry->second.authToken.get();
     return true;
 }
 
@@ -128,8 +132,8 @@
     if (entry == mMap.end()) {
         return false;
     }
-    entry->second.authToken.reset(new const hw_auth_token_t*);
-    *entry->second.authToken = authToken;
+    entry->second.authToken.reset(new hw_auth_token_t);
+    *entry->second.authToken = *authToken;
     return true;
 }
 
@@ -143,10 +147,14 @@
 }
 
 OperationMap::Operation::Operation(keymaster_operation_handle_t handle_,
+                                   uint64_t keyid_,
+                                   keymaster_purpose_t purpose_,
                                    const keymaster1_device_t* device_,
                                    keymaster_key_characteristics_t* characteristics_,
                                    sp<IBinder> appToken_)
     : handle(handle_),
+      keyid(keyid_),
+      purpose(purpose_),
       device(device_),
       characteristics(characteristics_),
       appToken(appToken_) {
diff --git a/keystore/operation.h b/keystore/operation.h
index fb9583f..01c4dbe 100644
--- a/keystore/operation.h
+++ b/keystore/operation.h
@@ -47,14 +47,17 @@
 class OperationMap {
 public:
     OperationMap(IBinder::DeathRecipient* deathRecipient);
-    sp<IBinder> addOperation(keymaster_operation_handle_t handle,
-                             const keymaster1_device_t* dev, sp<IBinder> appToken,
-                             keymaster_key_characteristics_t* characteristics, bool pruneable);
+    sp<IBinder> addOperation(keymaster_operation_handle_t handle, uint64_t keyid,
+                             keymaster_purpose_t purpose, const keymaster1_device_t* dev,
+                             sp<IBinder> appToken, keymaster_key_characteristics_t* characteristics,
+                             bool pruneable);
     bool getOperation(sp<IBinder> token, keymaster_operation_handle_t* outHandle,
+                      uint64_t* outKeyid, keymaster_purpose_t* outPurpose,
                       const keymaster1_device_t** outDev,
                       const keymaster_key_characteristics_t** outCharacteristics);
     bool removeOperation(sp<IBinder> token);
-    bool hasPruneableOperation();
+    bool hasPruneableOperation() const;
+    size_t getPruneableOperationCount() const;
     bool getOperationAuthToken(sp<IBinder> token, const hw_auth_token_t** outToken);
     bool setOperationAuthToken(sp<IBinder> token, const hw_auth_token_t* authToken);
     sp<IBinder> getOldestPruneableOperation();
@@ -65,13 +68,16 @@
     void removeOperationTracking(sp<IBinder> token, sp<IBinder> appToken);
     struct Operation {
         Operation();
-        Operation(keymaster_operation_handle_t handle, const keymaster1_device_t* device,
+        Operation(keymaster_operation_handle_t handle, uint64_t keyid, keymaster_purpose_t purpose,
+                  const keymaster1_device_t* device,
                   keymaster_key_characteristics_t* characteristics, sp<IBinder> appToken);
         keymaster_operation_handle_t handle;
+        uint64_t keyid;
+        keymaster_purpose_t purpose;
         const keymaster1_device_t* device;
         Unique_keymaster_key_characteristics characteristics;
         sp<IBinder> appToken;
-        std::unique_ptr<const hw_auth_token_t*> authToken;
+        std::unique_ptr<hw_auth_token_t> authToken;
     };
     std::map<sp<IBinder>, struct Operation> mMap;
     std::vector<sp<IBinder>> mLru;