am 8a2c33b6: (-s ours) am 48d998cd: am aca71139: am 738d1e9d: am 1b8885ba: am 0d593526: Properly check for Blob max length

* commit '8a2c33b6f9b28e18a2a59d1fa0e11cf553a51eac':
  Properly check for Blob max length
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 f920095..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)
@@ -75,6 +76,7 @@
             ALOGE("Failed to readInplace OperationResult data");
         }
     }
+    outParams.readFromParcel(in);
 }
 
 void OperationResult::writeToParcel(Parcel* out) const {
@@ -91,6 +93,7 @@
             ALOGE("Failed to writeInplace OperationResult data.");
         }
     }
+    outParams.writeToParcel(out);
 }
 
 ExportResult::ExportResult() : resultCode(0), exportData(NULL), dataLength(0) {
@@ -213,14 +216,14 @@
             out->writeInt32(param.enumerated);
             break;
         }
-        case KM_INT:
-        case KM_INT_REP: {
+        case KM_UINT:
+        case KM_UINT_REP: {
             out->writeInt32(param.tag);
             out->writeInt32(param.integer);
             break;
         }
-        case KM_LONG:
-        case KM_LONG_REP: {
+        case KM_ULONG:
+        case KM_ULONG_REP: {
             out->writeInt32(param.tag);
             out->writeInt64(param.long_integer);
             break;
@@ -265,14 +268,14 @@
             *out = keymaster_param_enum(tag, value);
             break;
         }
-        case KM_INT:
-        case KM_INT_REP: {
+        case KM_UINT:
+        case KM_UINT_REP: {
             uint32_t value = in.readInt32();
             *out = keymaster_param_int(tag, value);
             break;
         }
-        case KM_LONG:
-        case KM_LONG_REP: {
+        case KM_ULONG:
+        case KM_ULONG_REP: {
             uint64_t value = in.readInt64();
             *out = keymaster_param_long(tag, value);
             break;
@@ -396,19 +399,20 @@
     }
 
     // test ping
-    virtual int32_t test()
+    virtual int32_t getState(int32_t userId)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
-        status_t status = remote()->transact(BnKeystoreService::TEST, data, &reply);
+        data.writeInt32(userId);
+        status_t status = remote()->transact(BnKeystoreService::GET_STATE, data, &reply);
         if (status != NO_ERROR) {
-            ALOGD("test() could not contact remote: %d\n", status);
+            ALOGD("getState() could not contact remote: %d\n", status);
             return -1;
         }
         int32_t err = reply.readExceptionCode();
         int32_t ret = reply.readInt32();
         if (err < 0) {
-            ALOGD("test() caught exception %d\n", err);
+            ALOGD("getState() caught exception %d\n", err);
             return -1;
         }
         return ret;
@@ -512,15 +516,15 @@
         return ret;
     }
 
-    virtual int32_t saw(const String16& name, int uid, Vector<String16>* matches)
+    virtual int32_t list(const String16& prefix, int uid, Vector<String16>* matches)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
-        data.writeString16(name);
+        data.writeString16(prefix);
         data.writeInt32(uid);
-        status_t status = remote()->transact(BnKeystoreService::SAW, data, &reply);
+        status_t status = remote()->transact(BnKeystoreService::LIST, data, &reply);
         if (status != NO_ERROR) {
-            ALOGD("saw() could not contact remote: %d\n", status);
+            ALOGD("list() could not contact remote: %d\n", status);
             return -1;
         }
         int32_t err = reply.readExceptionCode();
@@ -530,7 +534,7 @@
         }
         int32_t ret = reply.readInt32();
         if (err < 0) {
-            ALOGD("saw() caught exception %d\n", err);
+            ALOGD("list() caught exception %d\n", err);
             return -1;
         }
         return ret;
@@ -554,29 +558,32 @@
         return ret;
     }
 
-    virtual int32_t password(const String16& password)
+    virtual int32_t onUserPasswordChanged(int32_t userId, const String16& password)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
+        data.writeInt32(userId);
         data.writeString16(password);
-        status_t status = remote()->transact(BnKeystoreService::PASSWORD, data, &reply);
+        status_t status = remote()->transact(BnKeystoreService::ON_USER_PASSWORD_CHANGED, data,
+                                             &reply);
         if (status != NO_ERROR) {
-            ALOGD("password() could not contact remote: %d\n", status);
+            ALOGD("onUserPasswordChanged() could not contact remote: %d\n", status);
             return -1;
         }
         int32_t err = reply.readExceptionCode();
         int32_t ret = reply.readInt32();
         if (err < 0) {
-            ALOGD("password() caught exception %d\n", err);
+            ALOGD("onUserPasswordChanged() caught exception %d\n", err);
             return -1;
         }
         return ret;
     }
 
-    virtual int32_t lock()
+    virtual int32_t lock(int32_t userId)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
+        data.writeInt32(userId);
         status_t status = remote()->transact(BnKeystoreService::LOCK, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("lock() could not contact remote: %d\n", status);
@@ -591,10 +598,11 @@
         return ret;
     }
 
-    virtual int32_t unlock(const String16& password)
+    virtual int32_t unlock(int32_t userId, const String16& password)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
+        data.writeInt32(userId);
         data.writeString16(password);
         status_t status = remote()->transact(BnKeystoreService::UNLOCK, data, &reply);
         if (status != NO_ERROR) {
@@ -610,22 +618,23 @@
         return ret;
     }
 
-    virtual int32_t zero()
+    virtual bool isEmpty(int32_t userId)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
-        status_t status = remote()->transact(BnKeystoreService::ZERO, data, &reply);
+        data.writeInt32(userId);
+        status_t status = remote()->transact(BnKeystoreService::IS_EMPTY, data, &reply);
         if (status != NO_ERROR) {
-            ALOGD("zero() could not contact remote: %d\n", status);
-            return -1;
+            ALOGD("isEmpty() could not contact remote: %d\n", status);
+            return false;
         }
         int32_t err = reply.readExceptionCode();
         int32_t ret = reply.readInt32();
         if (err < 0) {
-            ALOGD("zero() caught exception %d\n", err);
-            return -1;
+            ALOGD("isEmpty() caught exception %d\n", err);
+            return false;
         }
-        return ret;
+        return ret != 0;
     }
 
     virtual int32_t generate(const String16& name, int32_t uid, int32_t keyType, int32_t keySize,
@@ -784,26 +793,6 @@
         return 0;
      }
 
-    virtual int32_t del_key(const String16& name, int uid)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
-        data.writeString16(name);
-        data.writeInt32(uid);
-        status_t status = remote()->transact(BnKeystoreService::DEL_KEY, data, &reply);
-        if (status != NO_ERROR) {
-            ALOGD("del_key() could not contact remote: %d\n", status);
-            return -1;
-        }
-        int32_t err = reply.readExceptionCode();
-        int32_t ret = reply.readInt32();
-        if (err < 0) {
-            ALOGD("del_key() caught exception %d\n", err);
-            return -1;
-        }
-        return ret;
-    }
-
     virtual int32_t grant(const String16& name, int32_t granteeUid)
     {
         Parcel data, reply;
@@ -924,64 +913,6 @@
         return ret;
     }
 
-    virtual int32_t reset_uid(int32_t uid) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
-        data.writeInt32(uid);
-        status_t status = remote()->transact(BnKeystoreService::RESET_UID, data, &reply);
-        if (status != NO_ERROR) {
-            ALOGD("reset_uid() could not contact remote: %d\n", status);
-            return -1;
-        }
-        int32_t err = reply.readExceptionCode();
-        int32_t ret = reply.readInt32();
-        if (err < 0) {
-            ALOGD("reset_uid() caught exception %d\n", err);
-            return -1;
-        }
-        return ret;
-
-    }
-
-    virtual int32_t sync_uid(int32_t sourceUid, int32_t targetUid)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
-        data.writeInt32(sourceUid);
-        data.writeInt32(targetUid);
-        status_t status = remote()->transact(BnKeystoreService::SYNC_UID, data, &reply);
-        if (status != NO_ERROR) {
-            ALOGD("sync_uid() could not contact remote: %d\n", status);
-            return -1;
-        }
-        int32_t err = reply.readExceptionCode();
-        int32_t ret = reply.readInt32();
-        if (err < 0) {
-            ALOGD("sync_uid() caught exception %d\n", err);
-            return -1;
-        }
-        return ret;
-    }
-
-    virtual int32_t password_uid(const String16& password, int32_t uid)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
-        data.writeString16(password);
-        data.writeInt32(uid);
-        status_t status = remote()->transact(BnKeystoreService::PASSWORD_UID, data, &reply);
-        if (status != NO_ERROR) {
-            ALOGD("password_uid() could not contact remote: %d\n", status);
-            return -1;
-        }
-        int32_t err = reply.readExceptionCode();
-        int32_t ret = reply.readInt32();
-        if (err < 0) {
-            ALOGD("password_uid() caught exception %d\n", err);
-            return -1;
-        }
-        return ret;
-    }
     virtual int32_t addRngEntropy(const uint8_t* buf, size_t bufLength)
     {
         Parcel data, reply;
@@ -1137,10 +1068,9 @@
     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, KeymasterArguments* outParams,
-                       OperationResult* result)
+                       size_t entropyLength, OperationResult* result)
     {
-        if (!result || !outParams) {
+        if (!result) {
             return;
         }
         Parcel data, reply;
@@ -1167,9 +1097,6 @@
         if (reply.readInt32() != 0) {
             result->readFromParcel(reply);
         }
-        if (reply.readInt32() != 0) {
-            outParams->readFromParcel(reply);
-        }
     }
 
     virtual void update(const sp<IBinder>& token, const KeymasterArguments& params,
@@ -1202,7 +1129,9 @@
     }
 
     virtual void finish(const sp<IBinder>& token, const KeymasterArguments& params,
-                        const uint8_t* signature, size_t signatureLength, OperationResult* result)
+                        const uint8_t* signature, size_t signatureLength,
+                        const uint8_t* entropy, size_t entropyLength,
+                        OperationResult* result)
     {
         if (!result) {
             return;
@@ -1213,6 +1142,7 @@
         data.writeInt32(1);
         params.writeToParcel(&data);
         data.writeByteArray(signatureLength, signature);
+        data.writeByteArray(entropyLength, entropy);
         status_t status = remote()->transact(BnKeystoreService::FINISH, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("finish() could not contact remote: %d\n", status);
@@ -1287,6 +1217,46 @@
         }
         return ret;
     };
+
+    virtual int32_t onUserAdded(int32_t userId, int32_t parentId)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
+        data.writeInt32(userId);
+        data.writeInt32(parentId);
+        status_t status = remote()->transact(BnKeystoreService::ON_USER_ADDED, data, &reply);
+        if (status != NO_ERROR) {
+            ALOGD("onUserAdded() could not contact remote: %d\n", status);
+            return -1;
+        }
+        int32_t err = reply.readExceptionCode();
+        int32_t ret = reply.readInt32();
+        if (err < 0) {
+            ALOGD("onUserAdded() caught exception %d\n", err);
+            return -1;
+        }
+        return ret;
+    }
+
+    virtual int32_t onUserRemoved(int32_t userId)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
+        data.writeInt32(userId);
+        status_t status = remote()->transact(BnKeystoreService::ON_USER_REMOVED, data, &reply);
+        if (status != NO_ERROR) {
+            ALOGD("onUserRemoved() could not contact remote: %d\n", status);
+            return -1;
+        }
+        int32_t err = reply.readExceptionCode();
+        int32_t ret = reply.readInt32();
+        if (err < 0) {
+            ALOGD("onUserRemoved() caught exception %d\n", err);
+            return -1;
+        }
+        return ret;
+    }
+
 };
 
 IMPLEMENT_META_INTERFACE(KeystoreService, "android.security.IKeystoreService");
@@ -1297,9 +1267,10 @@
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
     switch(code) {
-        case TEST: {
+        case GET_STATE: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
-            int32_t ret = test();
+            int32_t userId = data.readInt32();
+            int32_t ret = getState(userId);
             reply->writeNoException();
             reply->writeInt32(ret);
             return NO_ERROR;
@@ -1357,12 +1328,12 @@
             reply->writeInt32(ret);
             return NO_ERROR;
         } break;
-        case SAW: {
+        case LIST: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
-            String16 name = data.readString16();
+            String16 prefix = data.readString16();
             int uid = data.readInt32();
             Vector<String16> matches;
-            int32_t ret = saw(name, uid, &matches);
+            int32_t ret = list(prefix, uid, &matches);
             reply->writeNoException();
             reply->writeInt32(matches.size());
             Vector<String16>::const_iterator it = matches.begin();
@@ -1379,34 +1350,38 @@
             reply->writeInt32(ret);
             return NO_ERROR;
         } break;
-        case PASSWORD: {
+        case ON_USER_PASSWORD_CHANGED: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
+            int32_t userId = data.readInt32();
             String16 pass = data.readString16();
-            int32_t ret = password(pass);
+            int32_t ret = onUserPasswordChanged(userId, pass);
             reply->writeNoException();
             reply->writeInt32(ret);
             return NO_ERROR;
         } break;
         case LOCK: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
-            int32_t ret = lock();
+            int32_t userId = data.readInt32();
+            int32_t ret = lock(userId);
             reply->writeNoException();
             reply->writeInt32(ret);
             return NO_ERROR;
         } break;
         case UNLOCK: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
+            int32_t userId = data.readInt32();
             String16 pass = data.readString16();
-            int32_t ret = unlock(pass);
+            int32_t ret = unlock(userId, pass);
             reply->writeNoException();
             reply->writeInt32(ret);
             return NO_ERROR;
         } break;
-        case ZERO: {
+        case IS_EMPTY: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
-            int32_t ret = zero();
+            int32_t userId = data.readInt32();
+            bool ret = isEmpty(userId);
             reply->writeNoException();
-            reply->writeInt32(ret);
+            reply->writeInt32(ret ? 1 : 0);
             return NO_ERROR;
         } break;
         case GENERATE: {
@@ -1420,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();
@@ -1475,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);
             }
@@ -1525,15 +1503,6 @@
             reply->writeInt32(ret);
             return NO_ERROR;
         } break;
-        case DEL_KEY: {
-            CHECK_INTERFACE(IKeystoreService, data, reply);
-            String16 name = data.readString16();
-            int uid = data.readInt32();
-            int32_t ret = del_key(name, uid);
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        } break;
         case GRANT: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
             String16 name = data.readString16();
@@ -1587,32 +1556,6 @@
             reply->writeInt32(ret);
             return NO_ERROR;
         }
-        case RESET_UID: {
-            CHECK_INTERFACE(IKeystoreService, data, reply);
-            int32_t uid = data.readInt32();
-            int32_t ret = reset_uid(uid);
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case SYNC_UID: {
-            CHECK_INTERFACE(IKeystoreService, data, reply);
-            int32_t sourceUid = data.readInt32();
-            int32_t targetUid = data.readInt32();
-            int32_t ret = sync_uid(sourceUid, targetUid);
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
-        case PASSWORD_UID: {
-            CHECK_INTERFACE(IKeystoreService, data, reply);
-            String16 password = data.readString16();
-            int32_t uid = data.readInt32();
-            int32_t ret = password_uid(password, uid);
-            reply->writeNoException();
-            reply->writeInt32(ret);
-            return NO_ERROR;
-        }
         case ADD_RNG_ENTROPY: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
             const uint8_t* bytes = NULL;
@@ -1708,15 +1651,11 @@
             const uint8_t* entropy = NULL;
             size_t entropyLength = 0;
             readByteArray(data, &entropy, &entropyLength);
-            KeymasterArguments outArgs;
             OperationResult result;
-            begin(token, name, purpose, pruneable, args, entropy, entropyLength, &outArgs,
-                  &result);
+            begin(token, name, purpose, pruneable, args, entropy, entropyLength, &result);
             reply->writeNoException();
             reply->writeInt32(1);
             result.writeToParcel(reply);
-            reply->writeInt32(1);
-            outArgs.writeToParcel(reply);
 
             return NO_ERROR;
         }
@@ -1745,11 +1684,14 @@
             if (data.readInt32() != 0) {
                 args.readFromParcel(data);
             }
-            const uint8_t* buf = NULL;
-            size_t bufLength = 0;
-            readByteArray(data, &buf, &bufLength);
+            const uint8_t* signature = NULL;
+            size_t signatureLength = 0;
+            readByteArray(data, &signature, &signatureLength);
+            const uint8_t* entropy = NULL;
+            size_t entropyLength = 0;
+            readByteArray(data, &entropy, &entropyLength);
             OperationResult result;
-            finish(token, args, buf, bufLength, &result);
+            finish(token, args, signature, signatureLength, entropy, entropyLength,  &result);
             reply->writeNoException();
             reply->writeInt32(1);
             result.writeToParcel(reply);
@@ -1785,6 +1727,25 @@
 
             return NO_ERROR;
         }
+        case ON_USER_ADDED: {
+            CHECK_INTERFACE(IKeystoreService, data, reply);
+            int32_t userId = data.readInt32();
+            int32_t parentId = data.readInt32();
+            int32_t result = onUserAdded(userId, parentId);
+            reply->writeNoException();
+            reply->writeInt32(result);
+
+            return NO_ERROR;
+        }
+        case ON_USER_REMOVED: {
+            CHECK_INTERFACE(IKeystoreService, data, reply);
+            int32_t userId = data.readInt32();
+            int32_t result = onUserRemoved(userId);
+            reply->writeNoException();
+            reply->writeInt32(result);
+
+            return NO_ERROR;
+        }
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/keystore/auth_token_table.cpp b/keystore/auth_token_table.cpp
index de5d41d..c6e5843 100644
--- a/keystore/auth_token_table.cpp
+++ b/keystore/auth_token_table.cpp
@@ -21,7 +21,7 @@
 
 #include <algorithm>
 
-#include <keymaster/google_keymaster_utils.h>
+#include <keymaster/android_keymaster_utils.h>
 #include <keymaster/logger.h>
 
 namespace keymaster {
@@ -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 7a9cc34..24aa774 100644
--- a/keystore/auth_token_table.h
+++ b/keystore/auth_token_table.h
@@ -19,7 +19,6 @@
 
 #include <hardware/hw_auth_token.h>
 #include <keymaster/authorization_set.h>
-#include <keymaster/key_blob.h>
 
 #ifndef SYSTEM_KEYMASTER_AUTH_TOKEN_TABLE_H
 #define SYSTEM_KEYMASTER_AUTH_TOKEN_TABLE_H
@@ -71,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);
 
     /**
@@ -85,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/include/keystore/IKeystoreService.h b/keystore/include/keystore/IKeystoreService.h
index 8b5b5d3..c136dfd 100644
--- a/keystore/include/keystore/IKeystoreService.h
+++ b/keystore/include/keystore/IKeystoreService.h
@@ -42,6 +42,16 @@
     void operator()(uint8_t* p) { free(p); }
 };
 
+// struct for serializing/deserializing a list of keymaster_key_param_t's
+struct KeymasterArguments {
+    KeymasterArguments();
+    ~KeymasterArguments();
+    void readFromParcel(const Parcel& in);
+    void writeToParcel(Parcel* out) const;
+
+    std::vector<keymaster_key_param_t> params;
+};
+
 // struct for serializing the results of begin/update/finish
 struct OperationResult {
     OperationResult();
@@ -55,6 +65,7 @@
     int inputConsumed;
     std::unique_ptr<uint8_t[], MallocDeleter> data;
     size_t dataLength;
+    KeymasterArguments outParams;
 };
 
 // struct for serializing the results of export
@@ -69,16 +80,6 @@
     size_t dataLength;
 };
 
-// struct for serializing/deserializing a list of keymaster_key_param_t's
-struct KeymasterArguments {
-    KeymasterArguments();
-    ~KeymasterArguments();
-    void readFromParcel(const Parcel& in);
-    void writeToParcel(Parcel* out) const;
-
-    std::vector<keymaster_key_param_t> params;
-};
-
 // struct for serializing keymaster_key_characteristics_t's
 struct KeyCharacteristics {
     KeyCharacteristics();
@@ -98,48 +99,46 @@
 class IKeystoreService: public IInterface {
 public:
     enum {
-        TEST = IBinder::FIRST_CALL_TRANSACTION + 0,
+        GET_STATE = IBinder::FIRST_CALL_TRANSACTION + 0,
         GET = IBinder::FIRST_CALL_TRANSACTION + 1,
         INSERT = IBinder::FIRST_CALL_TRANSACTION + 2,
         DEL = IBinder::FIRST_CALL_TRANSACTION + 3,
         EXIST = IBinder::FIRST_CALL_TRANSACTION + 4,
-        SAW = IBinder::FIRST_CALL_TRANSACTION + 5,
+        LIST = IBinder::FIRST_CALL_TRANSACTION + 5,
         RESET = IBinder::FIRST_CALL_TRANSACTION + 6,
-        PASSWORD = IBinder::FIRST_CALL_TRANSACTION + 7,
+        ON_USER_PASSWORD_CHANGED = IBinder::FIRST_CALL_TRANSACTION + 7,
         LOCK = IBinder::FIRST_CALL_TRANSACTION + 8,
         UNLOCK = IBinder::FIRST_CALL_TRANSACTION + 9,
-        ZERO = IBinder::FIRST_CALL_TRANSACTION + 10,
+        IS_EMPTY = IBinder::FIRST_CALL_TRANSACTION + 10,
         GENERATE = IBinder::FIRST_CALL_TRANSACTION + 11,
         IMPORT = IBinder::FIRST_CALL_TRANSACTION + 12,
         SIGN = IBinder::FIRST_CALL_TRANSACTION + 13,
         VERIFY = IBinder::FIRST_CALL_TRANSACTION + 14,
         GET_PUBKEY = IBinder::FIRST_CALL_TRANSACTION + 15,
-        DEL_KEY = IBinder::FIRST_CALL_TRANSACTION + 16,
-        GRANT = IBinder::FIRST_CALL_TRANSACTION + 17,
-        UNGRANT = IBinder::FIRST_CALL_TRANSACTION + 18,
-        GETMTIME = IBinder::FIRST_CALL_TRANSACTION + 19,
-        DUPLICATE = IBinder::FIRST_CALL_TRANSACTION + 20,
-        IS_HARDWARE_BACKED = IBinder::FIRST_CALL_TRANSACTION + 21,
-        CLEAR_UID = IBinder::FIRST_CALL_TRANSACTION + 22,
-        RESET_UID = IBinder::FIRST_CALL_TRANSACTION + 23,
-        SYNC_UID = IBinder::FIRST_CALL_TRANSACTION + 24,
-        PASSWORD_UID = IBinder::FIRST_CALL_TRANSACTION + 25,
-        ADD_RNG_ENTROPY = IBinder::FIRST_CALL_TRANSACTION + 26,
-        GENERATE_KEY = IBinder::FIRST_CALL_TRANSACTION + 27,
-        GET_KEY_CHARACTERISTICS = IBinder::FIRST_CALL_TRANSACTION + 28,
-        IMPORT_KEY = IBinder::FIRST_CALL_TRANSACTION + 29,
-        EXPORT_KEY = IBinder::FIRST_CALL_TRANSACTION + 30,
-        BEGIN = IBinder::FIRST_CALL_TRANSACTION + 31,
-        UPDATE = IBinder::FIRST_CALL_TRANSACTION + 32,
-        FINISH = IBinder::FIRST_CALL_TRANSACTION + 33,
-        ABORT = IBinder::FIRST_CALL_TRANSACTION + 34,
-        IS_OPERATION_AUTHORIZED = IBinder::FIRST_CALL_TRANSACTION + 35,
-        ADD_AUTH_TOKEN = IBinder::FIRST_CALL_TRANSACTION + 36,
+        GRANT = IBinder::FIRST_CALL_TRANSACTION + 16,
+        UNGRANT = IBinder::FIRST_CALL_TRANSACTION + 17,
+        GETMTIME = IBinder::FIRST_CALL_TRANSACTION + 18,
+        DUPLICATE = IBinder::FIRST_CALL_TRANSACTION + 19,
+        IS_HARDWARE_BACKED = IBinder::FIRST_CALL_TRANSACTION + 20,
+        CLEAR_UID = IBinder::FIRST_CALL_TRANSACTION + 21,
+        ADD_RNG_ENTROPY = IBinder::FIRST_CALL_TRANSACTION + 22,
+        GENERATE_KEY = IBinder::FIRST_CALL_TRANSACTION + 23,
+        GET_KEY_CHARACTERISTICS = IBinder::FIRST_CALL_TRANSACTION + 24,
+        IMPORT_KEY = IBinder::FIRST_CALL_TRANSACTION + 25,
+        EXPORT_KEY = IBinder::FIRST_CALL_TRANSACTION + 26,
+        BEGIN = IBinder::FIRST_CALL_TRANSACTION + 27,
+        UPDATE = IBinder::FIRST_CALL_TRANSACTION + 28,
+        FINISH = IBinder::FIRST_CALL_TRANSACTION + 29,
+        ABORT = IBinder::FIRST_CALL_TRANSACTION + 30,
+        IS_OPERATION_AUTHORIZED = IBinder::FIRST_CALL_TRANSACTION + 31,
+        ADD_AUTH_TOKEN = IBinder::FIRST_CALL_TRANSACTION + 32,
+        ON_USER_ADDED = IBinder::FIRST_CALL_TRANSACTION + 33,
+        ON_USER_REMOVED = IBinder::FIRST_CALL_TRANSACTION + 34,
     };
 
     DECLARE_META_INTERFACE(KeystoreService);
 
-    virtual int32_t test() = 0;
+    virtual int32_t getState(int32_t userId) = 0;
 
     virtual int32_t get(const String16& name, uint8_t** item, size_t* itemLength) = 0;
 
@@ -150,17 +149,17 @@
 
     virtual int32_t exist(const String16& name, int uid) = 0;
 
-    virtual int32_t saw(const String16& name, int uid, Vector<String16>* matches) = 0;
+    virtual int32_t list(const String16& prefix, int uid, Vector<String16>* matches) = 0;
 
     virtual int32_t reset() = 0;
 
-    virtual int32_t password(const String16& password) = 0;
+    virtual int32_t onUserPasswordChanged(int32_t userId, const String16& newPassword) = 0;
 
-    virtual int32_t lock() = 0;
+    virtual int32_t lock(int32_t userId) = 0;
 
-    virtual int32_t unlock(const String16& password) = 0;
+    virtual int32_t unlock(int32_t userId, const String16& password) = 0;
 
-    virtual int32_t zero() = 0;
+    virtual bool isEmpty(int32_t userId) = 0;
 
     virtual int32_t generate(const String16& name, int32_t uid, int32_t keyType, int32_t keySize,
             int32_t flags, Vector<sp<KeystoreArg> >* args) = 0;
@@ -176,8 +175,6 @@
 
     virtual int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) = 0;
 
-    virtual int32_t del_key(const String16& name, int uid) = 0;
-
     virtual int32_t grant(const String16& name, int32_t granteeUid) = 0;
 
     virtual int32_t ungrant(const String16& name, int32_t granteeUid) = 0;
@@ -191,12 +188,6 @@
 
     virtual int32_t clear_uid(int64_t uid) = 0;
 
-    virtual int32_t reset_uid(int32_t uid) = 0;
-
-    virtual int32_t sync_uid(int32_t sourceUid, int32_t targetUid) = 0;
-
-    virtual int32_t password_uid(const String16& password, int32_t uid) = 0;
-
     virtual int32_t addRngEntropy(const uint8_t* data, size_t dataLength) = 0;
 
     virtual int32_t generateKey(const String16& name, const KeymasterArguments& params,
@@ -220,14 +211,14 @@
     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, KeymasterArguments* outParams,
-                       OperationResult* result) = 0;
+                       size_t entropyLength, OperationResult* result) = 0;
 
     virtual void update(const sp<IBinder>& token, const KeymasterArguments& params,
                         const uint8_t* data, size_t dataLength, OperationResult* result) = 0;
 
     virtual void finish(const sp<IBinder>& token, const KeymasterArguments& params,
                         const uint8_t* signature, size_t signatureLength,
+                        const uint8_t* entropy, size_t entropyLength,
                         OperationResult* result) = 0;
 
     virtual int32_t abort(const sp<IBinder>& handle) = 0;
@@ -236,6 +227,10 @@
 
     virtual int32_t addAuthToken(const uint8_t* token, size_t length) = 0;
 
+    virtual int32_t onUserAdded(int32_t userId, int32_t parentId) = 0;
+
+    virtual int32_t onUserRemoved(int32_t userId) = 0;
+
 };
 
 // ----------------------------------------------------------------------------
diff --git a/keystore/include/keystore/keystore.h b/keystore/include/keystore/keystore.h
index 32354df..dcb6032 100644
--- a/keystore/include/keystore/keystore.h
+++ b/keystore/include/keystore/keystore.h
@@ -41,6 +41,7 @@
     WRONG_PASSWORD_2  = 12,
     WRONG_PASSWORD_3  = 13, // MAX_RETRY = 4
     SIGNATURE_INVALID = 14,
+    OP_AUTH_NEEDED    = 15, // Auth is needed for this operation before it can be used.
 };
 
 /*
diff --git a/keystore/keystore.cpp b/keystore/keystore.cpp
index 2144de2..65a8ea9 100644
--- a/keystore/keystore.cpp
+++ b/keystore/keystore.cpp
@@ -43,8 +43,9 @@
 
 #include <hardware/keymaster0.h>
 
-#include <keymaster/softkeymaster.h>
 #include <keymaster/soft_keymaster_device.h>
+#include <keymaster/soft_keymaster_logger.h>
+#include <keymaster/softkeymaster.h>
 
 #include <UniquePtr.h>
 #include <utils/String8.h>
@@ -62,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,
@@ -105,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:
@@ -129,16 +141,20 @@
     return rc;
 }
 
+// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
+// logger used by SoftKeymasterDevice.
+static keymaster::SoftKeymasterLogger softkeymaster_logger;
+
 static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
     keymaster::SoftKeymasterDevice* softkeymaster =
             new keymaster::SoftKeymasterDevice();
-    // SoftKeymasterDevice is designed to make this cast safe.
-    *dev = reinterpret_cast<keymaster1_device_t*>(softkeymaster);
+    *dev = softkeymaster->keymaster_device();
+    // softkeymaster will be freed by *dev->close_device; don't delete here.
     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);
 }
 
 /***************
@@ -147,26 +163,24 @@
 
 /* Here are the permissions, actions, users, and the main function. */
 typedef enum {
-    P_TEST          = 1 << 0,
+    P_GET_STATE     = 1 << 0,
     P_GET           = 1 << 1,
     P_INSERT        = 1 << 2,
     P_DELETE        = 1 << 3,
     P_EXIST         = 1 << 4,
-    P_SAW           = 1 << 5,
+    P_LIST          = 1 << 5,
     P_RESET         = 1 << 6,
     P_PASSWORD      = 1 << 7,
     P_LOCK          = 1 << 8,
     P_UNLOCK        = 1 << 9,
-    P_ZERO          = 1 << 10,
+    P_IS_EMPTY      = 1 << 10,
     P_SIGN          = 1 << 11,
     P_VERIFY        = 1 << 12,
     P_GRANT         = 1 << 13,
     P_DUPLICATE     = 1 << 14,
     P_CLEAR_UID     = 1 << 15,
-    P_RESET_UID     = 1 << 16,
-    P_SYNC_UID      = 1 << 17,
-    P_PASSWORD_UID  = 1 << 18,
-    P_ADD_AUTH      = 1 << 19,
+    P_ADD_AUTH      = 1 << 16,
+    P_USER_CHANGED  = 1 << 17,
 } perm_t;
 
 static struct user_euid {
@@ -180,26 +194,24 @@
 
 /* perm_labels associcated with keystore_key SELinux class verbs. */
 const char *perm_labels[] = {
-    "test",
+    "get_state",
     "get",
     "insert",
     "delete",
     "exist",
-    "saw",
+    "list",
     "reset",
     "password",
     "lock",
     "unlock",
-    "zero",
+    "is_empty",
     "sign",
     "verify",
     "grant",
     "duplicate",
     "clear_uid",
-    "reset_uid",
-    "sync_uid",
-    "password_uid",
     "add_auth",
+    "user_changed",
 };
 
 static struct user_perm {
@@ -212,8 +224,8 @@
     {AID_ROOT,   static_cast<perm_t>(P_GET) },
 };
 
-static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
-        | P_VERIFY);
+static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
+                                                        | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
 
 static char *tctx;
 static int ks_is_selinux_enabled;
@@ -495,6 +507,7 @@
 public:
     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");
@@ -523,7 +536,9 @@
         mBlob = b;
     }
 
-    Blob() {}
+    Blob() {
+        memset(&mBlob, 0, sizeof(mBlob));
+    }
 
     const uint8_t* getValue() const {
         return mBlob.value;
@@ -662,6 +677,10 @@
             return SYSTEM_ERROR;
         }
 
+        if (fileLength == 0) {
+            return VALUE_CORRUPTED;
+        }
+
         if (isEncrypted() && (state != STATE_NO_ERROR)) {
             return LOCKED;
         }
@@ -771,6 +790,12 @@
         memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
     }
 
+    bool deleteMasterKey() {
+        setState(STATE_UNINITIALIZED);
+        zeroizeMasterKeysInMemory();
+        return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
+    }
+
     ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
         if (!generateMasterKey(entropy)) {
             return SYSTEM_ERROR;
@@ -873,19 +898,18 @@
     bool reset() {
         DIR* dir = opendir(getUserDirName());
         if (!dir) {
+            // If the directory doesn't exist then nothing to do.
+            if (errno == ENOENT) {
+                return true;
+            }
             ALOGW("couldn't open user directory: %s", strerror(errno));
             return false;
         }
 
         struct dirent* file;
         while ((file = readdir(dir)) != NULL) {
-            // We only care about files.
-            if (file->d_type != DT_REG) {
-                continue;
-            }
-
-            // Skip anything that starts with a "."
-            if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
+            // skip . and ..
+            if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
                 continue;
             }
 
@@ -1009,28 +1033,28 @@
         return ::NO_ERROR;
     }
 
-    State getState(uid_t uid) {
-        return getUserState(uid)->getState();
+    State getState(uid_t userId) {
+        return getUserState(userId)->getState();
     }
 
-    ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
-        UserState* userState = getUserState(uid);
+    ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
+        UserState* userState = getUserState(userId);
         return userState->initialize(pw, mEntropy);
     }
 
-    ResponseCode copyMasterKey(uid_t src, uid_t uid) {
-        UserState *userState = getUserState(uid);
-        UserState *initState = getUserState(src);
+    ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
+        UserState *userState = getUserState(dstUser);
+        UserState *initState = getUserState(srcUser);
         return userState->copyMasterKey(initState);
     }
 
-    ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
-        UserState* userState = getUserState(uid);
+    ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
+        UserState* userState = getUserState(userId);
         return userState->writeMasterKey(pw, mEntropy);
     }
 
-    ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
-        UserState* userState = getUserState(uid);
+    ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
+        UserState* userState = getUserState(userId);
         return userState->readMasterKey(pw, mEntropy);
     }
 
@@ -1049,33 +1073,56 @@
     android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
         char encoded[encode_key_length(keyName) + 1];	// add 1 for null char
         encode_key(encoded, keyName);
-        return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
+        return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
                 encoded);
     }
 
-    bool reset(uid_t uid) {
+    /*
+     * Delete entries owned by userId. If keepUnencryptedEntries is true
+     * then only encrypted entries will be removed, otherwise all entries will
+     * be removed.
+     */
+    void resetUser(uid_t userId, bool keepUnenryptedEntries) {
         android::String8 prefix("");
         android::Vector<android::String16> aliases;
-        if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
-            return ::SYSTEM_ERROR;
+        UserState* userState = getUserState(userId);
+        if (list(prefix, &aliases, userId) != ::NO_ERROR) {
+            return;
         }
-
-        UserState* userState = getUserState(uid);
         for (uint32_t i = 0; i < aliases.size(); i++) {
             android::String8 filename(aliases[i]);
             filename = android::String8::format("%s/%s", userState->getUserDirName(),
-                    getKeyName(filename).string());
-            del(filename, ::TYPE_ANY, uid);
-        }
+                                                getKeyName(filename).string());
+            bool shouldDelete = true;
+            if (keepUnenryptedEntries) {
+                Blob blob;
+                ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
 
-        userState->zeroizeMasterKeysInMemory();
-        userState->setState(STATE_UNINITIALIZED);
-        return userState->reset();
+                /* get can fail if the blob is encrypted and the state is
+                 * not unlocked, only skip deleting blobs that were loaded and
+                 * who are not encrypted. If there are blobs we fail to read for
+                 * other reasons err on the safe side and delete them since we
+                 * can't tell if they're encrypted.
+                 */
+                shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
+            }
+            if (shouldDelete) {
+                del(filename, ::TYPE_ANY, userId);
+            }
+        }
+        if (!userState->deleteMasterKey()) {
+            ALOGE("Failed to delete user %d's master key", userId);
+        }
+        if (!keepUnenryptedEntries) {
+            if(!userState->reset()) {
+                ALOGE("Failed to remove user %d's directory", userId);
+            }
+        }
     }
 
-    bool isEmpty(uid_t uid) const {
-        const UserState* userState = getUserState(uid);
-        if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
+    bool isEmpty(uid_t userId) const {
+        const UserState* userState = getUserState(userId);
+        if (userState == NULL) {
             return true;
         }
 
@@ -1104,14 +1151,14 @@
         return result;
     }
 
-    void lock(uid_t uid) {
-        UserState* userState = getUserState(uid);
+    void lock(uid_t userId) {
+        UserState* userState = getUserState(userId);
         userState->zeroizeMasterKeysInMemory();
         userState->setState(STATE_LOCKED);
     }
 
-    ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
-        UserState* userState = getUserState(uid);
+    ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
+        UserState* userState = getUserState(userId);
         ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                 userState->getState());
         if (rc != NO_ERROR) {
@@ -1124,8 +1171,8 @@
              * it must be read it again since the blob is encrypted each time
              * it's written.
              */
-            if (upgradeBlob(filename, keyBlob, version, type, uid)) {
-                if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
+            if (upgradeBlob(filename, keyBlob, version, type, userId)) {
+                if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
                         || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
                                 userState->getState())) != NO_ERROR) {
                     return rc;
@@ -1141,15 +1188,21 @@
                 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
                 && keyBlob->isFallback()) {
             ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
-                    uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
+                    userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
 
             // The HAL allowed the import, reget the key to have the "fresh"
             // version.
             if (imported == NO_ERROR) {
-                rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
+                rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
             }
         }
 
+        // 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;
@@ -1158,15 +1211,19 @@
         return rc;
     }
 
-    ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
-        UserState* userState = getUserState(uid);
+    ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
+        UserState* userState = getUserState(userId);
         return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
                 mEntropy);
     }
 
-    ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
+    ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
         Blob keyBlob;
-        ResponseCode rc = get(filename, &keyBlob, type, uid);
+        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;
         }
@@ -1195,10 +1252,10 @@
         return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
     }
 
-    ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
-            uid_t uid) {
+    ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
+            uid_t userId) {
 
-        UserState* userState = getUserState(uid);
+        UserState* userState = getUserState(userId);
         size_t n = prefix.length();
 
         DIR* dir = opendir(userState->getUserDirName());
@@ -1265,7 +1322,7 @@
         return getGrant(filename, uid) != NULL;
     }
 
-    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
+    ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
             int32_t flags) {
         uint8_t* data;
         size_t dataLength;
@@ -1300,7 +1357,7 @@
         keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
         keyBlob.setFallback(isFallback);
 
-        return put(filename, &keyBlob, uid);
+        return put(filename, &keyBlob, userId);
     }
 
     bool isHardwareBacked(const android::String16& keyType) const {
@@ -1321,8 +1378,9 @@
     ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
             const BlobType type) {
         android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
+        uid_t userId = get_user_id(uid);
 
-        ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
+        ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
         if (responseCode == NO_ERROR) {
             return responseCode;
         }
@@ -1331,7 +1389,7 @@
         uid_t euid = get_keystore_euid(uid);
         if (euid != uid) {
             filepath8 = getKeyNameForUidWithDir(keyName, euid);
-            responseCode = get(filepath8.string(), keyBlob, type, uid);
+            responseCode = get(filepath8.string(), keyBlob, type, userId);
             if (responseCode == NO_ERROR) {
                 return responseCode;
             }
@@ -1344,22 +1402,20 @@
         if (end[0] != '_' || end[1] == 0) {
             return KEY_NOT_FOUND;
         }
-        filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
+        filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
                 filename8.string());
         if (!hasGrant(filepath8.string(), uid)) {
             return responseCode;
         }
 
         // It is a granted key. Try to load it.
-        return get(filepath8.string(), keyBlob, type, uid);
+        return get(filepath8.string(), keyBlob, type, userId);
     }
 
     /**
      * Returns any existing UserState or creates it if it doesn't exist.
      */
-    UserState* getUserState(uid_t uid) {
-        uid_t userId = get_user_id(uid);
-
+    UserState* getUserState(uid_t userId) {
         for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
                 it != mMasterKeys.end(); it++) {
             UserState* state = *it;
@@ -1381,11 +1437,17 @@
     }
 
     /**
+     * Returns any existing UserState or creates it if it doesn't exist.
+     */
+    UserState* getUserStateByUid(uid_t uid) {
+        uid_t userId = get_user_id(uid);
+        return getUserState(userId);
+    }
+
+    /**
      * Returns NULL if the UserState doesn't already exist.
      */
-    const UserState* getUserState(uid_t uid) const {
-        uid_t userId = get_user_id(uid);
-
+    const UserState* getUserState(uid_t userId) const {
         for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
                 it != mMasterKeys.end(); it++) {
             UserState* state = *it;
@@ -1397,6 +1459,14 @@
         return NULL;
     }
 
+    /**
+     * Returns NULL if the UserState doesn't already exist.
+     */
+    const UserState* getUserStateByUid(uid_t uid) const {
+        uid_t userId = get_user_id(uid);
+        return getUserState(userId);
+    }
+
 private:
     static const char* sOldMasterKey;
     static const char* sMetaDataFile;
@@ -1504,7 +1574,7 @@
             return SYSTEM_ERROR;
         }
 
-        ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
+        ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
                 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
         if (rc != NO_ERROR) {
             return rc;
@@ -1547,7 +1617,7 @@
         bool upgraded = false;
 
         if (mMetaData.version == 0) {
-            UserState* userState = getUserState(0);
+            UserState* userState = getUserStateByUid(0);
 
             // Initialize first so the directory is made.
             userState->initialize();
@@ -1589,7 +1659,7 @@
                 if (end[0] != '_' || end[1] == 0) {
                     continue;
                 }
-                UserState* otherUser = getUserState(thisUid);
+                UserState* otherUser = getUserStateByUid(thisUid);
                 if (otherUser->getUserId() != 0) {
                     unlinkat(dirfd(dir), file->d_name, 0);
                 }
@@ -1636,12 +1706,12 @@
         }
     }
 
-    int32_t test() {
-        if (!checkBinderPermission(P_TEST)) {
+    int32_t getState(int32_t userId) {
+        if (!checkBinderPermission(P_GET_STATE)) {
             return ::PERMISSION_DENIED;
         }
 
-        return mKeyStore->getState(IPCThreadState::self()->getCallingUid());
+        return mKeyStore->getState(userId);
     }
 
     int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
@@ -1656,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;
@@ -1684,7 +1753,7 @@
         Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
         keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
 
-        return mKeyStore->put(filename.string(), &keyBlob, targetUid);
+        return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
     }
 
     int32_t del(const String16& name, int targetUid) {
@@ -1694,7 +1763,7 @@
         }
         String8 name8(name);
         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
-        return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
+        return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
     }
 
     int32_t exist(const String16& name, int targetUid) {
@@ -1712,15 +1781,15 @@
         return ::NO_ERROR;
     }
 
-    int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
+    int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
         targetUid = getEffectiveUid(targetUid);
-        if (!checkBinderPermission(P_SAW, targetUid)) {
+        if (!checkBinderPermission(P_LIST, targetUid)) {
             return ::PERMISSION_DENIED;
         }
         const String8 prefix8(prefix);
         String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
 
-        if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
+        if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
             return ::SYSTEM_ERROR;
         }
         return ::NO_ERROR;
@@ -1732,80 +1801,113 @@
         }
 
         uid_t callingUid = IPCThreadState::self()->getCallingUid();
-        return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
+        mKeyStore->resetUser(get_user_id(callingUid), false);
+        return ::NO_ERROR;
     }
 
-    /*
-     * Here is the history. To improve the security, the parameters to generate the
-     * master key has been changed. To make a seamless transition, we update the
-     * file using the same password when the user unlock it for the first time. If
-     * any thing goes wrong during the transition, the new file will not overwrite
-     * the old one. This avoids permanent damages of the existing data.
-     */
-    int32_t password(const String16& password) {
+    int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
         if (!checkBinderPermission(P_PASSWORD)) {
             return ::PERMISSION_DENIED;
         }
 
         const String8 password8(password);
-        uid_t callingUid = IPCThreadState::self()->getCallingUid();
+        // Flush the auth token table to prevent stale tokens from sticking
+        // around.
+        mAuthTokenTable.Clear();
 
-        switch (mKeyStore->getState(callingUid)) {
-            case ::STATE_UNINITIALIZED: {
-                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
-                return mKeyStore->initializeUser(password8, callingUid);
+        if (password.size() == 0) {
+            ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
+            mKeyStore->resetUser(userId, true);
+            return ::NO_ERROR;
+        } else {
+            switch (mKeyStore->getState(userId)) {
+                case ::STATE_UNINITIALIZED: {
+                    // generate master key, encrypt with password, write to file,
+                    // initialize mMasterKey*.
+                    return mKeyStore->initializeUser(password8, userId);
+                }
+                case ::STATE_NO_ERROR: {
+                    // rewrite master key with new password.
+                    return mKeyStore->writeMasterKey(password8, userId);
+                }
+                case ::STATE_LOCKED: {
+                    ALOGE("Changing user %d's password while locked, clearing old encryption",
+                          userId);
+                    mKeyStore->resetUser(userId, true);
+                    return mKeyStore->initializeUser(password8, userId);
+                }
             }
-            case ::STATE_NO_ERROR: {
-                // rewrite master key with new password.
-                return mKeyStore->writeMasterKey(password8, callingUid);
-            }
-            case ::STATE_LOCKED: {
-                // read master key, decrypt with password, initialize mMasterKey*.
-                return mKeyStore->readMasterKey(password8, callingUid);
-            }
+            return ::SYSTEM_ERROR;
         }
-        return ::SYSTEM_ERROR;
     }
 
-    int32_t lock() {
+    int32_t onUserAdded(int32_t userId, int32_t parentId) {
+        if (!checkBinderPermission(P_USER_CHANGED)) {
+            return ::PERMISSION_DENIED;
+        }
+
+        // Sanity check that the new user has an empty keystore.
+        if (!mKeyStore->isEmpty(userId)) {
+            ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
+        }
+        // Unconditionally clear the keystore, just to be safe.
+        mKeyStore->resetUser(userId, false);
+
+        // If the user has a parent user then use the parent's
+        // masterkey/password, otherwise there's nothing to do.
+        if (parentId != -1) {
+            return mKeyStore->copyMasterKey(parentId, userId);
+        } else {
+            return ::NO_ERROR;
+        }
+    }
+
+    int32_t onUserRemoved(int32_t userId) {
+        if (!checkBinderPermission(P_USER_CHANGED)) {
+            return ::PERMISSION_DENIED;
+        }
+
+        mKeyStore->resetUser(userId, false);
+        return ::NO_ERROR;
+    }
+
+    int32_t lock(int32_t userId) {
         if (!checkBinderPermission(P_LOCK)) {
             return ::PERMISSION_DENIED;
         }
 
-        uid_t callingUid = IPCThreadState::self()->getCallingUid();
-        State state = mKeyStore->getState(callingUid);
+        State state = mKeyStore->getState(userId);
         if (state != ::STATE_NO_ERROR) {
             ALOGD("calling lock in state: %d", state);
             return state;
         }
 
-        mKeyStore->lock(callingUid);
+        mKeyStore->lock(userId);
         return ::NO_ERROR;
     }
 
-    int32_t unlock(const String16& pw) {
+    int32_t unlock(int32_t userId, const String16& pw) {
         if (!checkBinderPermission(P_UNLOCK)) {
             return ::PERMISSION_DENIED;
         }
 
-        uid_t callingUid = IPCThreadState::self()->getCallingUid();
-        State state = mKeyStore->getState(callingUid);
+        State state = mKeyStore->getState(userId);
         if (state != ::STATE_LOCKED) {
-            ALOGD("calling unlock when not locked");
+            ALOGI("calling unlock when not locked, ignoring.");
             return state;
         }
 
         const String8 password8(pw);
-        return password(pw);
+        // read master key, decrypt with password, initialize mMasterKey*.
+        return mKeyStore->readMasterKey(password8, userId);
     }
 
-    int32_t zero() {
-        if (!checkBinderPermission(P_ZERO)) {
-            return -1;
+    bool isEmpty(int32_t userId) {
+        if (!checkBinderPermission(P_IS_EMPTY)) {
+            return false;
         }
 
-        uid_t callingUid = IPCThreadState::self()->getCallingUid();
-        return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
+        return mKeyStore->isEmpty(userId);
     }
 
     int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
@@ -1816,193 +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, 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(), 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,
@@ -2010,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);
     }
 
     /*
@@ -2056,47 +2049,18 @@
      * 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;
     }
 
-    int32_t del_key(const String16& name, int targetUid) {
-        return del(name, targetUid);
-    }
-
     int32_t grant(const String16& name, int32_t granteeUid) {
         uid_t callingUid = IPCThreadState::self()->getCallingUid();
         int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
@@ -2173,7 +2137,7 @@
             return -1L;
         }
 
-        State state = mKeyStore->getState(callingUid);
+        State state = mKeyStore->getState(get_user_id(callingUid));
         if (!isKeystoreUnlocked(state)) {
             ALOGD("calling duplicate in state: %d", state);
             return state;
@@ -2216,12 +2180,12 @@
 
         Blob keyBlob;
         ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
-                srcUid);
+                get_user_id(srcUid));
         if (responseCode != ::NO_ERROR) {
             return responseCode;
         }
 
-        return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
+        return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
     }
 
     int32_t is_hardware_backed(const String16& keyType) {
@@ -2230,73 +2194,24 @@
 
     int32_t clear_uid(int64_t targetUid64) {
         uid_t targetUid = getEffectiveUid(targetUid64);
-        if (!checkBinderPermission(P_CLEAR_UID, targetUid)) {
+        if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
             return ::PERMISSION_DENIED;
         }
 
         String8 prefix = String8::format("%u_", targetUid);
         Vector<String16> aliases;
-        if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
+        if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
             return ::SYSTEM_ERROR;
         }
 
         for (uint32_t i = 0; i < aliases.size(); i++) {
             String8 name8(aliases[i]);
             String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
-            mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
+            mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
         }
         return ::NO_ERROR;
     }
 
-    int32_t reset_uid(int32_t targetUid) {
-        targetUid = getEffectiveUid(targetUid);
-        if (!checkBinderPermission(P_RESET_UID, targetUid)) {
-            return ::PERMISSION_DENIED;
-        }
-        // Flush the auth token table to prevent stale tokens from sticking
-        // around.
-        mAuthTokenTable.Clear();
-
-        return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
-    }
-
-    int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
-        if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
-            return ::PERMISSION_DENIED;
-        }
-
-        if (sourceUid == targetUid) {
-            return ::SYSTEM_ERROR;
-        }
-
-        // Initialise user keystore with existing master key held in-memory
-        return mKeyStore->copyMasterKey(sourceUid, targetUid);
-    }
-
-    int32_t password_uid(const String16& pw, int32_t targetUid) {
-        targetUid = getEffectiveUid(targetUid);
-        if (!checkBinderPermission(P_PASSWORD, targetUid)) {
-            return ::PERMISSION_DENIED;
-        }
-        const String8 password8(pw);
-
-        switch (mKeyStore->getState(targetUid)) {
-            case ::STATE_UNINITIALIZED: {
-                // generate master key, encrypt with password, write to file, initialize mMasterKey*.
-                return mKeyStore->initializeUser(password8, targetUid);
-            }
-            case ::STATE_NO_ERROR: {
-                // rewrite master key with new password.
-                return mKeyStore->writeMasterKey(password8, targetUid);
-            }
-            case ::STATE_LOCKED: {
-                // read master key, decrypt with password, initialize mMasterKey*.
-                return mKeyStore->readMasterKey(password8, targetUid);
-            }
-        }
-        return ::SYSTEM_ERROR;
-    }
-
     int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
         const keymaster1_device_t* device = mKeyStore->getDevice();
         const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
@@ -2335,6 +2250,8 @@
 
         const keymaster1_device_t* device = mKeyStore->getDevice();
         const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
+        std::vector<keymaster_key_param_t> opParams(params.params);
+        const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
         if (device == NULL) {
             return ::SYSTEM_ERROR;
         }
@@ -2349,8 +2266,7 @@
                 rc = KM_ERROR_UNIMPLEMENTED;
             }
             if (rc == KM_ERROR_OK) {
-                rc = device->generate_key(device, params.params.data(), params.params.size(),
-                                          &blob, &out);
+                rc = device->generate_key(device, &inParams, &blob, &out);
             }
         }
         // If the HW device didn't support generate_key or generate_key failed
@@ -2365,9 +2281,7 @@
                 rc = KM_ERROR_UNIMPLEMENTED;
             }
             if (rc == KM_ERROR_OK) {
-                rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
-                                            &blob,
-                                            &out);
+                rc = fallback->generate_key(fallback, &inParams, &blob, &out);
             }
         }
 
@@ -2393,7 +2307,7 @@
 
         free(const_cast<uint8_t*>(blob.key_material));
 
-        return mKeyStore->put(filename.string(), &keyBlob, uid);
+        return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
     }
 
     int32_t getKeyCharacteristics(const String16& name,
@@ -2450,18 +2364,19 @@
 
         const keymaster1_device_t* device = mKeyStore->getDevice();
         const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
+        std::vector<keymaster_key_param_t> opParams(params.params);
+        const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
+        const keymaster_blob_t input = {keyData, keyLength};
         if (device == NULL) {
             return ::SYSTEM_ERROR;
         }
         if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
                 device->import_key != NULL) {
-            rc = device->import_key(device, params.params.data(), params.params.size(),
-                                    format, keyData, keyLength, &blob, &out);
+            rc = device->import_key(device, &inParams, format,&input, &blob, &out);
         }
         if (rc && fallback->import_key != NULL) {
             isFallback = true;
-            rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
-                                      format, keyData, keyLength, &blob, &out);
+            rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
         }
         if (out) {
             if (outCharacteristics) {
@@ -2484,7 +2399,7 @@
 
         free((void*) blob.key_material);
 
-        return mKeyStore->put(filename.string(), &keyBlob, uid);
+        return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
     }
 
     void exportKey(const String16& name, keymaster_key_format_t format,
@@ -2511,114 +2426,27 @@
             result->resultCode = KM_ERROR_UNIMPLEMENTED;
             return;
         }
-        uint8_t* ptr = NULL;
-        rc = dev->export_key(dev, format, &key, clientId, appData,
-                                             &ptr, &result->dataLength);
-        result->exportData.reset(ptr);
+        keymaster_blob_t output = {NULL, 0};
+        rc = dev->export_key(dev, format, &key, clientId, appData, &output);
+        result->exportData.reset(const_cast<uint8_t*>(output.data));
+        result->dataLength = output.data_length;
         result->resultCode = rc ? rc : ::NO_ERROR;
     }
 
-    /**
-     * Check that all keymaster_key_param_t's provided by the application are
-     * allowed. Any parameter that keystore adds itself should be disallowed here.
-     */
-    bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
-        for (auto param: params) {
-            switch (param.tag) {
-                case KM_TAG_AUTH_TOKEN:
-                    return false;
-                default:
-                    break;
-            }
-        }
-        return true;
-    }
-
-    int authorizeOperation(const keymaster_key_characteristics_t& characteristics,
-                            keymaster_operation_handle_t handle,
-                            std::vector<keymaster_key_param_t>* params,
-                            bool failOnTokenMissing=true) {
-        if (!checkAllowedOperationParams(*params)) {
-            return KM_ERROR_INVALID_ARGUMENT;
-        }
-        std::vector<keymaster_key_param_t> allCharacteristics;
-        for (size_t i = 0; i < characteristics.sw_enforced.length; i++) {
-            allCharacteristics.push_back(characteristics.sw_enforced.params[i]);
-        }
-        for (size_t i = 0; i < characteristics.hw_enforced.length; i++) {
-            allCharacteristics.push_back(characteristics.hw_enforced.params[i]);
-        }
-        // Check for auth token and add it to the param list if present.
-        const hw_auth_token_t* authToken;
-        switch (mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
-                                                  allCharacteristics.size(), handle, &authToken)) {
-        case keymaster::AuthTokenTable::OK:
-            // Auth token found.
-            params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
-                                                   reinterpret_cast<const uint8_t*>(authToken),
-                                                   sizeof(hw_auth_token_t)));
-            break;
-        case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
-            return KM_ERROR_OK;
-        case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
-        case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
-        case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
-            if (failOnTokenMissing) {
-                return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
-            }
-            break;
-        case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
-            return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
-        default:
-            return KM_ERROR_INVALID_ARGUMENT;
-        }
-        // TODO: Enforce the rest of authorization
-        return KM_ERROR_OK;
-    }
-
-    keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
-                                    const keymaster1_device_t* dev,
-                                    const std::vector<keymaster_key_param_t>& params,
-                                    keymaster_key_characteristics_t* out) {
-        UniquePtr<keymaster_blob_t> appId;
-        UniquePtr<keymaster_blob_t> appData;
-        for (auto param : params) {
-            if (param.tag == KM_TAG_APPLICATION_ID) {
-                appId.reset(new keymaster_blob_t);
-                appId->data = param.blob.data;
-                appId->data_length = param.blob.data_length;
-            } else if (param.tag == KM_TAG_APPLICATION_DATA) {
-                appData.reset(new keymaster_blob_t);
-                appData->data = param.blob.data;
-                appData->data_length = param.blob.data_length;
-            }
-        }
-        keymaster_key_characteristics_t* result = NULL;
-        if (!dev->get_key_characteristics) {
-            return KM_ERROR_UNIMPLEMENTED;
-        }
-        keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
-                                                               appData.get(), &result);
-        if (result) {
-            *out = *result;
-            free(result);
-        }
-        return error;
-    }
 
     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, KeymasterArguments* outParams, OperationResult* result) {
-        if (!result || !outParams) {
-            ALOGE("Unexpected null arguments to begin()");
-            return;
-        }
+               size_t entropyLength, OperationResult* result) {
         uid_t callingUid = IPCThreadState::self()->getCallingUid();
         if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
             ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
             result->resultCode = ::PERMISSION_DENIED;
             return;
         }
+        if (!checkAllowedOperationParams(params.params)) {
+            result->resultCode = KM_ERROR_INVALID_ARGUMENT;
+            return;
+        }
         Blob keyBlob;
         String8 name8(name);
         ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
@@ -2630,8 +2458,6 @@
         keymaster_key_blob_t key;
         key.key_material_size = keyBlob.getLength();
         key.key_material = keyBlob.getValue();
-        keymaster_key_param_t* out;
-        size_t outSize;
         keymaster_operation_handle_t handle;
         keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
         keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
@@ -2643,15 +2469,17 @@
             result->resultCode = err;
             return;
         }
-        // Don't require an auth token for the call to begin, authentication can
-        // require an operation handle. Update and finish will require the token
-        // be present and valid.
-        int32_t authResult = authorizeOperation(*characteristics, 0, &opParams,
+        const hw_auth_token_t* authToken = NULL;
+        int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
                                                 /*failOnTokenMissing*/ false);
-        if (authResult) {
-            result->resultCode = err;
+        // If per-operation auth is needed we need to begin the operation and
+        // the client will need to authorize that operation before calling
+        // update. Any other auth issues stop here.
+        if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
+            result->resultCode = authResult;
             return;
         }
+        addAuthToParams(&opParams, authToken);
         // Add entropy to the device first.
         if (entropy) {
             if (dev->add_rng_entropy) {
@@ -2664,98 +2492,197 @@
                 return;
             }
         }
-        // Don't do an auth check here, we need begin to succeed for
-        // per-operation auth. update/finish will be doing the auth checks.
-        err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
-                         &handle);
+        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);
 
         // If there are too many operations abort the oldest operation that was
         // started as pruneable and try again.
         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, params.params.data(),
-                             params.params.size(), &out, &outSize,
-                             &handle);
+            err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
         }
         if (err) {
             result->resultCode = err;
             return;
         }
-        if (out) {
-            outParams->params.assign(out, out + outSize);
-            free(out);
-        }
 
-        sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
-                                                                characteristics.release(),
+        sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev,
+                                                                appToken, characteristics.release(),
                                                                 pruneable);
-        result->resultCode = ::NO_ERROR;
+        if (authToken) {
+            mOperationMap.setOperationAuthToken(operationToken, authToken);
+        }
+        // Return the authentication lookup result. If this is a per operation
+        // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
+        // application should get an auth token using the handle before the
+        // first call to update, which will fail if keystore hasn't received the
+        // auth token.
+        result->resultCode = authResult;
         result->token = operationToken;
         result->handle = handle;
+        if (outParams.params) {
+            result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
+            free(outParams.params);
+        }
     }
 
     void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
                 size_t dataLength, OperationResult* result) {
+        if (!checkAllowedOperationParams(params.params)) {
+            result->resultCode = KM_ERROR_INVALID_ARGUMENT;
+            return;
+        }
         const keymaster1_device_t* dev;
         keymaster_operation_handle_t handle;
+        keymaster_purpose_t purpose;
+        keymaster::km_id_t keyid;
         const keymaster_key_characteristics_t* characteristics;
-        if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
+        if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
             result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
             return;
         }
-        uint8_t* output_buf = NULL;
-        size_t output_length = 0;
-        size_t consumed = 0;
         std::vector<keymaster_key_param_t> opParams(params.params);
-        int32_t authResult = authorizeOperation(*characteristics, handle, &opParams);
-        if (authResult) {
+        int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
+        if (authResult != ::NO_ERROR) {
             result->resultCode = authResult;
             return;
         }
-        keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
-                                            dataLength, &consumed, &output_buf, &output_length);
-        result->data.reset(output_buf);
-        result->dataLength = output_length;
+        keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
+        keymaster_blob_t input = {data, dataLength};
+        size_t consumed = 0;
+        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));
+        result->dataLength = output.data_length;
         result->inputConsumed = consumed;
         result->resultCode = err ? (int32_t) err : ::NO_ERROR;
+        if (outParams.params) {
+            result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
+            free(outParams.params);
+        }
     }
 
     void finish(const sp<IBinder>& token, const KeymasterArguments& params,
-                const uint8_t* signature, size_t signatureLength, OperationResult* result) {
+                const uint8_t* signature, size_t signatureLength,
+                const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
+        if (!checkAllowedOperationParams(params.params)) {
+            result->resultCode = KM_ERROR_INVALID_ARGUMENT;
+            return;
+        }
         const keymaster1_device_t* dev;
         keymaster_operation_handle_t handle;
+        keymaster_purpose_t purpose;
+        keymaster::km_id_t keyid;
         const keymaster_key_characteristics_t* characteristics;
-        if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
+        if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
             result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
             return;
         }
-        uint8_t* output_buf = NULL;
-        size_t output_length = 0;
         std::vector<keymaster_key_param_t> opParams(params.params);
-        int32_t authResult = authorizeOperation(*characteristics, handle, &opParams);
-        if (authResult) {
+        int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
+        if (authResult != ::NO_ERROR) {
             result->resultCode = authResult;
             return;
         }
-        keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
-                                            signature, signatureLength, &output_buf,
-                                            &output_length);
+        keymaster_error_t err;
+        if (entropy) {
+            if (dev->add_rng_entropy) {
+                err = dev->add_rng_entropy(dev, entropy, entropyLength);
+            } else {
+                err = KM_ERROR_UNIMPLEMENTED;
+            }
+            if (err) {
+                result->resultCode = err;
+                return;
+            }
+        }
+
+        keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
+        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);
         mAuthTokenTable.MarkCompleted(handle);
-        result->data.reset(output_buf);
-        result->dataLength = output_length;
+
+        result->data.reset(const_cast<uint8_t*>(output.data));
+        result->dataLength = output.data_length;
         result->resultCode = err ? (int32_t) err : ::NO_ERROR;
+        if (outParams.params) {
+            result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
+            free(outParams.params);
+        }
     }
 
     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);
@@ -2776,12 +2703,16 @@
         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;
+        mOperationMap.getOperationAuthToken(token, &authToken);
         std::vector<keymaster_key_param_t> ignored;
-        int32_t authResult = authorizeOperation(*characteristics, handle, &ignored);
-        return authResult == KM_ERROR_OK;
+        int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
+        return authResult == ::NO_ERROR;
     }
 
     int32_t addAuthToken(const uint8_t* token, size_t length) {
@@ -2834,6 +2765,20 @@
 
     /**
      * Check if the caller of the current binder method has the required
+     * permission and the target uid is the caller or the caller is system.
+     */
+    inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
+        uid_t callingUid = IPCThreadState::self()->getCallingUid();
+        pid_t spid = IPCThreadState::self()->getCallingPid();
+        if (!has_permission(callingUid, permission, spid)) {
+            ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
+            return false;
+        }
+        return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
+    }
+
+    /**
+     * Check if the caller of the current binder method has the required
      * permission or the target of the operation is the caller's uid. This is
      * for operation where the permission is only for cross-uid activity and all
      * uids are allowed to act on their own (ie: clearing all entries for a
@@ -2861,7 +2806,7 @@
         if (!checkBinderPermission(permission, targetUid)) {
             return ::PERMISSION_DENIED;
         }
-        State state = mKeyStore->getState(getEffectiveUid(targetUid));
+        State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
         if (checkUnlocked && !isKeystoreUnlocked(state)) {
             return state;
         }
@@ -2908,9 +2853,278 @@
         }
     }
 
+    /**
+     * Check that all keymaster_key_param_t's provided by the application are
+     * allowed. Any parameter that keystore adds itself should be disallowed here.
+     */
+    bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
+        for (auto param: params) {
+            switch (param.tag) {
+                case KM_TAG_AUTH_TOKEN:
+                    return false;
+                default:
+                    break;
+            }
+        }
+        return true;
+    }
+
+    keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
+                                    const keymaster1_device_t* dev,
+                                    const std::vector<keymaster_key_param_t>& params,
+                                    keymaster_key_characteristics_t* out) {
+        UniquePtr<keymaster_blob_t> appId;
+        UniquePtr<keymaster_blob_t> appData;
+        for (auto param : params) {
+            if (param.tag == KM_TAG_APPLICATION_ID) {
+                appId.reset(new keymaster_blob_t);
+                appId->data = param.blob.data;
+                appId->data_length = param.blob.data_length;
+            } else if (param.tag == KM_TAG_APPLICATION_DATA) {
+                appData.reset(new keymaster_blob_t);
+                appData->data = param.blob.data;
+                appData->data_length = param.blob.data_length;
+            }
+        }
+        keymaster_key_characteristics_t* result = NULL;
+        if (!dev->get_key_characteristics) {
+            return KM_ERROR_UNIMPLEMENTED;
+        }
+        keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
+                                                               appData.get(), &result);
+        if (result) {
+            *out = *result;
+            free(result);
+        }
+        return error;
+    }
+
+    /**
+     * Get the auth token for this operation from the auth token table.
+     *
+     * Returns ::NO_ERROR if the auth token was set or none was required.
+     *         ::OP_AUTH_NEEDED if it is a per op authorization, no
+     *         authorization token exists for that operation and
+     *         failOnTokenMissing is false.
+     *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
+     *         token for the operation
+     */
+    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) {
+
+        std::vector<keymaster_key_param_t> allCharacteristics;
+        for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
+            allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
+        }
+        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(), purpose, handle, authToken);
+        switch (err) {
+            case keymaster::AuthTokenTable::OK:
+            case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
+                return ::NO_ERROR;
+            case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
+            case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
+            case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
+                return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
+            case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
+                return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
+                        (int32_t) ::OP_AUTH_NEEDED;
+            default:
+                ALOGE("Unexpected FindAuthorization return value %d", err);
+                return KM_ERROR_INVALID_ARGUMENT;
+        }
+    }
+
+    inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
+                                const hw_auth_token_t* token) {
+        if (token) {
+            params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
+                                                   reinterpret_cast<const uint8_t*>(token),
+                                                   sizeof(hw_auth_token_t)));
+        }
+    }
+
+    /**
+     * Add the auth token for the operation to the param list if the operation
+     * requires authorization. Uses the cached result in the OperationMap if available
+     * otherwise gets the token from the AuthTokenTable and caches the result.
+     *
+     * Returns ::NO_ERROR if the auth token was added or not needed.
+     *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
+     *         authenticated.
+     *         KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
+     *         operation token.
+     */
+    int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
+                                          std::vector<keymaster_key_param_t>* params) {
+        const hw_auth_token_t* authToken = NULL;
+        mOperationMap.getOperationAuthToken(token, &authToken);
+        if (!authToken) {
+            const keymaster1_device_t* dev;
+            keymaster_operation_handle_t handle;
+            const keymaster_key_characteristics_t* characteristics = NULL;
+            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, purpose, &authToken);
+            if (result != ::NO_ERROR) {
+                return result;
+            }
+            if (authToken) {
+                mOperationMap.setOperationAuthToken(token, authToken);
+            }
+        }
+        addAuthToParams(params, authToken);
+        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
@@ -2930,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;
@@ -2955,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_cli.cpp b/keystore/keystore_cli.cpp
index 1e19890..a3088e4 100644
--- a/keystore/keystore_cli.cpp
+++ b/keystore/keystore_cli.cpp
@@ -76,6 +76,24 @@
         } \
     } while (0)
 
+#define SINGLE_INT_ARG_INT_RETURN(cmd) \
+    do { \
+        if (strcmp(argv[1], #cmd) == 0) { \
+            if (argc < 3) { \
+                fprintf(stderr, "Usage: %s " #cmd " <name>\n", argv[0]); \
+                return 1; \
+            } \
+            int32_t ret = service->cmd(atoi(argv[2])); \
+            if (ret < 0) { \
+                fprintf(stderr, "%s: could not connect: %d\n", argv[0], ret); \
+                return 1; \
+            } else { \
+                printf(#cmd ": %s (%d)\n", responses[ret], ret); \
+                return 0; \
+            } \
+        } \
+    } while (0)
+
 #define SINGLE_ARG_PLUS_UID_INT_RETURN(cmd) \
     do { \
         if (strcmp(argv[1], #cmd) == 0) { \
@@ -145,14 +163,14 @@
         } \
     } while (0)
 
-static int saw(sp<IKeystoreService> service, const String16& name, int uid) {
+static int list(sp<IKeystoreService> service, const String16& name, int uid) {
     Vector<String16> matches;
-    int32_t ret = service->saw(name, uid, &matches);
+    int32_t ret = service->list(name, uid, &matches);
     if (ret < 0) {
-        fprintf(stderr, "saw: could not connect: %d\n", ret);
+        fprintf(stderr, "list: could not connect: %d\n", ret);
         return 1;
     } else if (ret != ::NO_ERROR) {
-        fprintf(stderr, "saw: %s (%d)\n", responses[ret], ret);
+        fprintf(stderr, "list: %s (%d)\n", responses[ret], ret);
         return 1;
     } else {
         Vector<String16>::const_iterator it = matches.begin();
@@ -183,7 +201,7 @@
      * All the commands should return a value
      */
 
-    NO_ARG_INT_RETURN(test);
+    SINGLE_INT_ARG_INT_RETURN(getState);
 
     SINGLE_ARG_DATA_RETURN(get);
 
@@ -193,27 +211,25 @@
 
     SINGLE_ARG_PLUS_UID_INT_RETURN(exist);
 
-    if (strcmp(argv[1], "saw") == 0) {
-        return saw(service, argc < 3 ? String16("") : String16(argv[2]),
+    if (strcmp(argv[1], "list") == 0) {
+        return list(service, argc < 3 ? String16("") : String16(argv[2]),
                 argc < 4 ? -1 : atoi(argv[3]));
     }
 
     NO_ARG_INT_RETURN(reset);
 
-    SINGLE_ARG_INT_RETURN(password);
+    // TODO: notifyUserPasswordChanged
 
-    NO_ARG_INT_RETURN(lock);
+    SINGLE_INT_ARG_INT_RETURN(lock);
 
-    SINGLE_ARG_INT_RETURN(unlock);
+    // TODO: unlock
 
-    NO_ARG_INT_RETURN(zero);
+    SINGLE_INT_ARG_INT_RETURN(isEmpty);
 
     // TODO: generate
 
     SINGLE_ARG_DATA_RETURN(get_pubkey);
 
-    SINGLE_ARG_PLUS_UID_INT_RETURN(del_key);
-
     // TODO: grant
 
     // TODO: ungrant
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 e871f83..4a71922 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] = std::move(Operation(handle, dev, characteristics, appToken));
+    mMap[token] = std::move(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);
@@ -110,6 +118,25 @@
     return mLru[0];
 }
 
+bool OperationMap::getOperationAuthToken(sp<IBinder> token, const hw_auth_token_t** outToken) {
+    auto entry = mMap.find(token);
+    if (entry == mMap.end()) {
+        return false;
+    }
+    *outToken = entry->second.authToken.get();
+    return true;
+}
+
+bool OperationMap::setOperationAuthToken(sp<IBinder> token, const hw_auth_token_t* authToken) {
+    auto entry = mMap.find(token);
+    if (entry == mMap.end()) {
+        return false;
+    }
+    entry->second.authToken.reset(new hw_auth_token_t);
+    *entry->second.authToken = *authToken;
+    return true;
+}
+
 std::vector<sp<IBinder>> OperationMap::getOperationsForToken(sp<IBinder> appToken) {
     auto appEntry = mAppTokenMap.find(appToken);
     if (appEntry != mAppTokenMap.end()) {
@@ -120,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 a312528..01c4dbe 100644
--- a/keystore/operation.h
+++ b/keystore/operation.h
@@ -17,6 +17,7 @@
 #ifndef KEYSTORE_OPERATION_H_
 #define KEYSTORE_OPERATION_H_
 
+#include <hardware/hw_auth_token.h>
 #include <hardware/keymaster1.h>
 #include <binder/Binder.h>
 #include <binder/IBinder.h>
@@ -46,14 +47,19 @@
 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();
     std::vector<sp<IBinder>> getOperationsForToken(sp<IBinder> appToken);
 
@@ -62,12 +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<hw_auth_token_t> authToken;
     };
     std::map<sp<IBinder>, struct Operation> mMap;
     std::vector<sp<IBinder>> mLru;
diff --git a/keystore/tests/auth_token_table_test.cpp b/keystore/tests/auth_token_table_test.cpp
index fec7e43..b1c0f49 100644
--- a/keystore/tests/auth_token_table_test.cpp
+++ b/keystore/tests/auth_token_table_test.cpp
@@ -16,7 +16,7 @@
 
 #include <gtest/gtest.h>
 
-#include <keymaster/google_keymaster_utils.h>
+#include <keymaster/android_keymaster_utils.h>
 #include <keymaster/logger.h>
 
 #include "../auth_token_table.h"
diff --git a/softkeymaster/keymaster_openssl.cpp b/softkeymaster/keymaster_openssl.cpp
index edf4db2..6f31195 100644
--- a/softkeymaster/keymaster_openssl.cpp
+++ b/softkeymaster/keymaster_openssl.cpp
@@ -752,7 +752,8 @@
     dev->common.module = (struct hw_module_t*)module;
     dev->common.close = openssl_close;
 
-    dev->flags = KEYMASTER_SOFTWARE_ONLY;
+    dev->flags = KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE | KEYMASTER_SUPPORTS_DSA |
+                 KEYMASTER_SUPPORTS_EC;
 
     dev->generate_keypair = openssl_generate_keypair;
     dev->import_keypair = openssl_import_keypair;