Merge changes from topic \'km_tag_allow_on_body\' am: a1433ee2f8
am: e30ca16ae0

* commit 'e30ca16ae0e41375201de9132866f5680a5d7baa':
  Add KM_TAG_ALLOW_WHILE_ON_BODY
  Add attestation support to keystore.
diff --git a/keystore/Android.mk b/keystore/Android.mk
index 04ca220..baff509 100644
--- a/keystore/Android.mk
+++ b/keystore/Android.mk
@@ -55,6 +55,9 @@
 LOCAL_MODULE := keystore
 LOCAL_MODULE_TAGS := optional
 LOCAL_INIT_RC := keystore.rc
+LOCAL_C_INCLUES := system/keymaster/
+LOCAL_CLANG := true
+LOCAL_SANITIZE := integer
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_EXECUTABLE)
 
@@ -110,6 +113,8 @@
 LOCAL_MODULE_TAGS := optional
 LOCAL_C_INCLUDES := $(LOCAL_PATH)/include $(call keystore_proto_include)
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_CLANG := true
+LOCAL_SANITIZE := integer
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/keystore/IKeystoreService.cpp b/keystore/IKeystoreService.cpp
index 466ac24..d03a011 100644
--- a/keystore/IKeystoreService.cpp
+++ b/keystore/IKeystoreService.cpp
@@ -467,11 +467,12 @@
         return ret;
     }
 
-    virtual int32_t get(const String16& name, uint8_t** item, size_t* itemLength)
+    virtual int32_t get(const String16& name, int32_t uid, uint8_t** item, size_t* itemLength)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
         data.writeString16(name);
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::GET, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("get() could not contact remote: %d\n", status);
@@ -882,11 +883,12 @@
         return ret;
     }
 
-    int64_t getmtime(const String16& name)
+    int64_t getmtime(const String16& name, int32_t uid)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
         data.writeString16(name);
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::GETMTIME, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("getmtime() could not contact remote: %d\n", status);
@@ -1012,7 +1014,7 @@
     virtual int32_t getKeyCharacteristics(const String16& name,
                                           const keymaster_blob_t* clientId,
                                           const keymaster_blob_t* appData,
-                                          KeyCharacteristics* outCharacteristics)
+                                          int32_t uid, KeyCharacteristics* outCharacteristics)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IKeystoreService::getInterfaceDescriptor());
@@ -1027,6 +1029,7 @@
         } else {
             data.writeInt32(-1);
         }
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::GET_KEY_CHARACTERISTICS,
                                              data, &reply);
         if (status != NO_ERROR) {
@@ -1077,7 +1080,7 @@
 
     virtual void exportKey(const String16& name, keymaster_key_format_t format,
                            const keymaster_blob_t* clientId,
-                           const keymaster_blob_t* appData, ExportResult* result)
+                           const keymaster_blob_t* appData, int32_t uid, ExportResult* result)
     {
         if (!result) {
             return;
@@ -1097,6 +1100,7 @@
         } else {
             data.writeInt32(-1);
         }
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::EXPORT_KEY, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("exportKey() could not contact remote: %d\n", status);
@@ -1117,7 +1121,7 @@
     virtual void begin(const sp<IBinder>& appToken, const String16& name,
                        keymaster_purpose_t purpose, bool pruneable,
                        const KeymasterArguments& params, const uint8_t* entropy,
-                       size_t entropyLength, OperationResult* result)
+                       size_t entropyLength, int32_t uid, OperationResult* result)
     {
         if (!result) {
             return;
@@ -1131,6 +1135,7 @@
         data.writeInt32(1);
         params.writeToParcel(&data);
         data.writeByteArray(entropyLength, entropy);
+        data.writeInt32(uid);
         status_t status = remote()->transact(BnKeystoreService::BEGIN, data, &reply);
         if (status != NO_ERROR) {
             ALOGD("begin() could not contact remote: %d\n", status);
@@ -1355,9 +1360,10 @@
         case GET: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
             String16 name = data.readString16();
+            int32_t uid = data.readInt32();
             void* out = NULL;
             size_t outSize = 0;
-            int32_t ret = get(name, (uint8_t**) &out, &outSize);
+            int32_t ret = get(name, uid, (uint8_t**) &out, &outSize);
             reply->writeNoException();
             if (ret == 1) {
                 reply->writeInt32(outSize);
@@ -1601,7 +1607,8 @@
         case GETMTIME: {
             CHECK_INTERFACE(IKeystoreService, data, reply);
             String16 name = data.readString16();
-            int64_t ret = getmtime(name);
+            int32_t uid = data.readInt32();
+            int64_t ret = getmtime(name, uid);
             reply->writeNoException();
             reply->writeInt64(ret);
             return NO_ERROR;
@@ -1669,8 +1676,9 @@
             String16 name = data.readString16();
             std::unique_ptr<keymaster_blob_t> clientId = readKeymasterBlob(data);
             std::unique_ptr<keymaster_blob_t> appData = readKeymasterBlob(data);
+            int32_t uid = data.readInt32();
             KeyCharacteristics outCharacteristics;
-            int ret = getKeyCharacteristics(name, clientId.get(), appData.get(),
+            int ret = getKeyCharacteristics(name, clientId.get(), appData.get(), uid,
                                             &outCharacteristics);
             reply->writeNoException();
             reply->writeInt32(ret);
@@ -1707,8 +1715,9 @@
             keymaster_key_format_t format = static_cast<keymaster_key_format_t>(data.readInt32());
             std::unique_ptr<keymaster_blob_t> clientId = readKeymasterBlob(data);
             std::unique_ptr<keymaster_blob_t> appData = readKeymasterBlob(data);
+            int32_t uid = data.readInt32();
             ExportResult result;
-            exportKey(name, format, clientId.get(), appData.get(), &result);
+            exportKey(name, format, clientId.get(), appData.get(), uid, &result);
             reply->writeNoException();
             reply->writeInt32(1);
             result.writeToParcel(reply);
@@ -1728,8 +1737,9 @@
             const uint8_t* entropy = NULL;
             size_t entropyLength = 0;
             readByteArray(data, &entropy, &entropyLength);
+            int32_t uid = data.readInt32();
             OperationResult result;
-            begin(token, name, purpose, pruneable, args, entropy, entropyLength, &result);
+            begin(token, name, purpose, pruneable, args, entropy, entropyLength, uid, &result);
             reply->writeNoException();
             reply->writeInt32(1);
             result.writeToParcel(reply);
diff --git a/keystore/blob.h b/keystore/blob.h
index 8c26b28..584e312 100644
--- a/keystore/blob.h
+++ b/keystore/blob.h
@@ -24,7 +24,7 @@
 
 #include <keystore/keystore.h>
 
-#define VALUE_SIZE      32768
+#define VALUE_SIZE 32768
 
 /* Here is the file format. There are two parts in blob.value, the secret and
  * the description. The secret is stored in ciphertext, and its original size
@@ -55,17 +55,17 @@
     uint8_t flags;
     uint8_t info;
     uint8_t vector[AES_BLOCK_SIZE];
-    uint8_t encrypted[0]; // Marks offset to encrypted data.
+    uint8_t encrypted[0];  // Marks offset to encrypted data.
     uint8_t digest[MD5_DIGEST_LENGTH];
-    uint8_t digested[0]; // Marks offset to digested data.
-    int32_t length; // in network byte order when encrypted
+    uint8_t digested[0];  // Marks offset to digested data.
+    int32_t length;       // in network byte order when encrypted
     uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
 };
 
 static const uint8_t CURRENT_BLOB_VERSION = 2;
 
 typedef enum {
-    TYPE_ANY = 0, // meta type that matches anything
+    TYPE_ANY = 0,  // meta type that matches anything
     TYPE_GENERIC = 1,
     TYPE_MASTER_KEY = 2,
     TYPE_KEY_PAIR = 3,
diff --git a/keystore/include/keystore/IKeystoreService.h b/keystore/include/keystore/IKeystoreService.h
index 1c2f6a5..64968e5 100644
--- a/keystore/include/keystore/IKeystoreService.h
+++ b/keystore/include/keystore/IKeystoreService.h
@@ -151,7 +151,7 @@
 
     virtual int32_t getState(int32_t userId) = 0;
 
-    virtual int32_t get(const String16& name, uint8_t** item, size_t* itemLength) = 0;
+    virtual int32_t get(const String16& name, int32_t uid, uint8_t** item, size_t* itemLength) = 0;
 
     virtual int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int uid,
             int32_t flags) = 0;
@@ -190,7 +190,7 @@
 
     virtual int32_t ungrant(const String16& name, int32_t granteeUid) = 0;
 
-    virtual int64_t getmtime(const String16& name) = 0;
+    virtual int64_t getmtime(const String16& name, int32_t uid) = 0;
 
     virtual int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
             int32_t destUid) = 0;
@@ -208,6 +208,7 @@
     virtual int32_t getKeyCharacteristics(const String16& name,
                                           const keymaster_blob_t* clientId,
                                           const keymaster_blob_t* appData,
+                                          int32_t uid,
                                           KeyCharacteristics* outCharacteristics) = 0;
 
     virtual int32_t importKey(const String16& name, const KeymasterArguments&  params,
@@ -217,12 +218,12 @@
 
     virtual void exportKey(const String16& name, keymaster_key_format_t format,
                            const keymaster_blob_t* clientId,
-                           const keymaster_blob_t* appData, ExportResult* result) = 0;
+                           const keymaster_blob_t* appData, int32_t uid, ExportResult* result) = 0;
 
     virtual void begin(const sp<IBinder>& apptoken, const String16& name,
                        keymaster_purpose_t purpose, bool pruneable,
                        const KeymasterArguments& params, const uint8_t* entropy,
-                       size_t entropyLength, OperationResult* result) = 0;
+                       size_t entropyLength, int32_t uid, OperationResult* result) = 0;
 
     virtual void update(const sp<IBinder>& token, const KeymasterArguments& params,
                         const uint8_t* data, size_t dataLength, OperationResult* result) = 0;
diff --git a/keystore/key_store_service.cpp b/keystore/key_store_service.cpp
index 759ef06..e02ef8b 100644
--- a/keystore/key_store_service.cpp
+++ b/keystore/key_store_service.cpp
@@ -54,16 +54,17 @@
     return mKeyStore->getState(userId);
 }
 
-int32_t KeyStoreService::get(const String16& name, uint8_t** item, size_t* itemLength) {
-    if (!checkBinderPermission(P_GET)) {
+int32_t KeyStoreService::get(const String16& name, int32_t uid, uint8_t** item,
+                             size_t* itemLength) {
+    uid_t targetUid = getEffectiveUid(uid);
+    if (!checkBinderPermission(P_GET, targetUid)) {
         return ::PERMISSION_DENIED;
     }
 
-    uid_t callingUid = IPCThreadState::self()->getCallingUid();
     String8 name8(name);
     Blob keyBlob;
 
-    ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_GENERIC);
+    ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
     if (responseCode != ::NO_ERROR) {
         *item = NULL;
         *itemLength = 0;
@@ -396,7 +397,7 @@
  */
 int32_t KeyStoreService::get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
     ExportResult result;
-    exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
+    exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, UID_SELF, &result);
     if (result.resultCode != ::NO_ERROR) {
         ALOGW("export failed: %d", result.resultCode);
         return translateResultToLegacyResult(result.resultCode);
@@ -442,15 +443,15 @@
     return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
 }
 
-int64_t KeyStoreService::getmtime(const String16& name) {
-    uid_t callingUid = IPCThreadState::self()->getCallingUid();
-    if (!checkBinderPermission(P_GET)) {
-        ALOGW("permission denied for %d: getmtime", callingUid);
+int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
+    uid_t targetUid = getEffectiveUid(uid);
+    if (!checkBinderPermission(P_GET, targetUid)) {
+        ALOGW("permission denied for %d: getmtime", targetUid);
         return -1L;
     }
 
     String8 name8(name);
-    String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
+    String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
 
     if (access(filename.string(), R_OK) == -1) {
         ALOGW("could not access %s for getmtime", filename.string());
@@ -656,20 +657,26 @@
 
 int32_t KeyStoreService::getKeyCharacteristics(const String16& name,
                                                const keymaster_blob_t* clientId,
-                                               const keymaster_blob_t* appData,
+                                               const keymaster_blob_t* appData, int32_t uid,
                                                KeyCharacteristics* outCharacteristics) {
     if (!outCharacteristics) {
         return KM_ERROR_UNEXPECTED_NULL_POINTER;
     }
 
+    uid_t targetUid = getEffectiveUid(uid);
     uid_t callingUid = IPCThreadState::self()->getCallingUid();
+    if (!is_granted_to(callingUid, targetUid)) {
+        ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
+              targetUid);
+        return ::PERMISSION_DENIED;
+    }
 
     Blob keyBlob;
     String8 name8(name);
     int rc;
 
     ResponseCode responseCode =
-        mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
+        mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
     if (responseCode != ::NO_ERROR) {
         return responseCode;
     }
@@ -747,16 +754,22 @@
 
 void KeyStoreService::exportKey(const String16& name, keymaster_key_format_t format,
                                 const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
-                                ExportResult* result) {
+                                int32_t uid, ExportResult* result) {
 
+    uid_t targetUid = getEffectiveUid(uid);
     uid_t callingUid = IPCThreadState::self()->getCallingUid();
+    if (!is_granted_to(callingUid, targetUid)) {
+        ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
+        result->resultCode = ::PERMISSION_DENIED;
+        return;
+    }
 
     Blob keyBlob;
     String8 name8(name);
     int rc;
 
     ResponseCode responseCode =
-        mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
+        mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
     if (responseCode != ::NO_ERROR) {
         result->resultCode = responseCode;
         return;
@@ -779,8 +792,14 @@
 void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name,
                             keymaster_purpose_t purpose, bool pruneable,
                             const KeymasterArguments& params, const uint8_t* entropy,
-                            size_t entropyLength, OperationResult* result) {
+                            size_t entropyLength, int32_t uid, OperationResult* result) {
     uid_t callingUid = IPCThreadState::self()->getCallingUid();
+    uid_t targetUid = getEffectiveUid(uid);
+    if (!is_granted_to(callingUid, targetUid)) {
+        ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
+        result->resultCode = ::PERMISSION_DENIED;
+        return;
+    }
     if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
         ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
         result->resultCode = ::PERMISSION_DENIED;
@@ -793,7 +812,7 @@
     Blob keyBlob;
     String8 name8(name);
     ResponseCode responseCode =
-        mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
+        mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
     if (responseCode != ::NO_ERROR) {
         result->resultCode = responseCode;
         return;
@@ -1207,7 +1226,7 @@
     return ::NO_ERROR;
 }
 
-inline bool KeyStoreService::isKeystoreUnlocked(State state) {
+bool KeyStoreService::isKeystoreUnlocked(State state) {
     switch (state) {
     case ::STATE_NO_ERROR:
         return true;
@@ -1380,7 +1399,7 @@
  * Translate a result value to a legacy return value. All keystore errors are
  * preserved and keymaster errors become SYSTEM_ERRORs
  */
-inline int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
+int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
     if (result > 0) {
         return result;
     }
@@ -1410,7 +1429,7 @@
 
     // Look up the algorithm of the key.
     KeyCharacteristics characteristics;
-    int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
+    int32_t rc = getKeyCharacteristics(name, NULL, NULL, UID_SELF, &characteristics);
     if (rc != ::NO_ERROR) {
         ALOGE("Failed to get key characteristics");
         return;
@@ -1435,7 +1454,7 @@
     sp<IBinder> appToken(new BBinder);
     sp<IBinder> token;
 
-    begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
+    begin(appToken, name, purpose, true, inArgs, NULL, 0, UID_SELF, &result);
     if (result.resultCode != ResponseCode::NO_ERROR) {
         if (result.resultCode == ::KEY_NOT_FOUND) {
             ALOGW("Key not found");
diff --git a/keystore/key_store_service.h b/keystore/key_store_service.h
index 35b8928..12a342e 100644
--- a/keystore/key_store_service.h
+++ b/keystore/key_store_service.h
@@ -35,7 +35,7 @@
 
     int32_t getState(int32_t userId);
 
-    int32_t get(const String16& name, uint8_t** item, size_t* itemLength);
+    int32_t get(const String16& name, int32_t uid, uint8_t** item, size_t* itemLength);
     int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
                    int32_t flags);
     int32_t del(const String16& name, int targetUid);
@@ -78,7 +78,7 @@
     int32_t grant(const String16& name, int32_t granteeUid);
     int32_t ungrant(const String16& name, int32_t granteeUid);
 
-    int64_t getmtime(const String16& name);
+    int64_t getmtime(const String16& name, int32_t uid);
 
     int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
                       int32_t destUid);
@@ -92,17 +92,17 @@
                         const uint8_t* entropy, size_t entropyLength, int uid, int flags,
                         KeyCharacteristics* outCharacteristics);
     int32_t getKeyCharacteristics(const String16& name, const keymaster_blob_t* clientId,
-                                  const keymaster_blob_t* appData,
+                                  const keymaster_blob_t* appData, int32_t uid,
                                   KeyCharacteristics* outCharacteristics);
     int32_t importKey(const String16& name, const KeymasterArguments& params,
                       keymaster_key_format_t format, const uint8_t* keyData, size_t keyLength,
                       int uid, int flags, KeyCharacteristics* outCharacteristics);
     void exportKey(const String16& name, keymaster_key_format_t format,
-                   const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
+                   const keymaster_blob_t* clientId, const keymaster_blob_t* appData, int32_t uid,
                    ExportResult* result);
     void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
                bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
-               size_t entropyLength, OperationResult* result);
+               size_t entropyLength, int32_t uid, OperationResult* result);
     void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
                 size_t dataLength, OperationResult* result);
     void finish(const sp<IBinder>& token, const KeymasterArguments& params,
diff --git a/keystore/keystore.cpp b/keystore/keystore.cpp
index 457a60a..90cfdb1 100644
--- a/keystore/keystore.cpp
+++ b/keystore/keystore.cpp
@@ -32,7 +32,6 @@
 const char* KeyStore::sMetaDataFile = ".metadata";
 
 const android::String16 KeyStore::sRSAKeyType("RSA");
-const android::String16 KeyStore::sECKeyType("EC");
 
 KeyStore::KeyStore(Entropy* entropy, keymaster2_device_t* device, keymaster2_device_t* fallback)
     : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback) {
diff --git a/keystore/keystore.h b/keystore/keystore.h
index 62d7294..b15d00f 100644
--- a/keystore/keystore.h
+++ b/keystore/keystore.h
@@ -111,7 +111,6 @@
     static const char* sOldMasterKey;
     static const char* sMetaDataFile;
     static const android::String16 sRSAKeyType;
-    static const android::String16 sECKeyType;
     Entropy* mEntropy;
 
     keymaster2_device_t* mDevice;
diff --git a/keystore/keystore_cli.cpp b/keystore/keystore_cli.cpp
index 34f1d9c..7f6996b 100644
--- a/keystore/keystore_cli.cpp
+++ b/keystore/keystore_cli.cpp
@@ -104,7 +104,7 @@
             int uid = -1; \
             if (argc > 3) { \
                 uid = atoi(argv[3]); \
-                fprintf(stderr, "Working with uid %d\n", uid); \
+                fprintf(stderr, "Running as uid %d\n", uid); \
             } \
             int32_t ret = service->cmd(String16(argv[2]), uid); \
             if (ret < 0) { \
@@ -117,28 +117,47 @@
         } \
     } while (0)
 
-#define STING_ARG_DATA_STDIN_PLUS_UID_PLUS_FLAGS_INT_RETURN(cmd) \
+#define SINGLE_ARG_PLUS_UID_DATA_RETURN(cmd) \
     do { \
         if (strcmp(argv[1], #cmd) == 0) { \
             if (argc < 3) { \
-                fprintf(stderr, "Usage: %s " #cmd " <name> [<uid>, <flags>]\n", argv[0]); \
+                fprintf(stderr, "Usage: %s " #cmd " <name> <uid>\n", argv[0]); \
+                return 1; \
+            } \
+            uint8_t* data; \
+            size_t dataSize; \
+            int uid = -1; \
+            if (argc > 3) { \
+                uid = atoi(argv[3]); \
+                fprintf(stderr, "Running as uid %d\n", uid); \
+            } \
+            int32_t ret = service->cmd(String16(argv[2]), uid, &data, &dataSize); \
+            if (ret < 0) { \
+                fprintf(stderr, "%s: could not connect: %d\n", argv[0], ret); \
+                return 1; \
+            } else if (ret != ::NO_ERROR) { \
+                fprintf(stderr, "%s: " #cmd ": %s (%d)\n", argv[0], responses[ret], ret); \
+                return 1; \
+            } else { \
+                fwrite(data, dataSize, 1, stdout); \
+                fflush(stdout); \
+                free(data); \
+                return 0; \
+            } \
+        } \
+    } while (0)
+
+#define STING_ARG_DATA_STDIN_INT_RETURN(cmd) \
+    do { \
+        if (strcmp(argv[1], #cmd) == 0) { \
+            if (argc < 3) { \
+                fprintf(stderr, "Usage: %s " #cmd " <name>\n", argv[0]); \
                 return 1; \
             } \
             uint8_t* data; \
             size_t dataSize; \
             read_input(&data, &dataSize); \
-            int uid = -1; \
-            if (argc > 3) { \
-                uid = atoi(argv[3]); \
-                fprintf(stderr, "Working with uid %d\n", uid); \
-            } \
-            int32_t flags = 0; \
-            if (argc > 4) { \
-                flags = int32_t(atoi(argv[4])); \
-                fprintf(stderr, "Using flags %04x\n", flags); \
-            } \
-            int32_t ret = service->cmd(String16(argv[2]), data, dataSize, uid, flags); \
-            free(data); \
+            int32_t ret = service->cmd(String16(argv[2]), data, dataSize); \
             if (ret < 0) { \
                 fprintf(stderr, "%s: could not connect: %d\n", argv[0], ret); \
                 return 1; \
@@ -162,16 +181,14 @@
             if (ret < 0) { \
                 fprintf(stderr, "%s: could not connect: %d\n", argv[0], ret); \
                 return 1; \
-            } else if (ret) { \
+            } else if (ret != ::NO_ERROR) { \
                 fprintf(stderr, "%s: " #cmd ": %s (%d)\n", argv[0], responses[ret], ret); \
                 return 1; \
-            } else if (dataSize) { \
+            } else { \
                 fwrite(data, dataSize, 1, stdout); \
                 fflush(stdout); \
                 free(data); \
                 return 0; \
-            } else { \
-                return 1; \
             } \
         } \
     } while (0)
@@ -194,39 +211,6 @@
     }
 }
 
-#define BUF_SIZE 1024
-static void read_input(uint8_t** data, size_t* dataSize) {
-    char buffer[BUF_SIZE];
-    size_t contentSize = 0;
-    char *content = (char *) malloc(sizeof(char) * BUF_SIZE);
-
-    if (content == NULL) {
-        fprintf(stderr, "read_input: failed to allocate content");
-        exit(1);
-    }
-    content[0] = '\0';
-    while (fgets(buffer, BUF_SIZE, stdin)) {
-        char *old = content;
-        contentSize += strlen(buffer);
-        content = (char *) realloc(content, contentSize);
-        if (content == NULL) {
-            fprintf(stderr, "read_input: failed to reallocate content.");
-            free(old);
-            exit(1);
-        }
-        strcat(content, buffer);
-    }
-
-    if (ferror(stdin)) {
-        free(content);
-        fprintf(stderr, "read_input: error reading from stdin.");
-        exit(1);
-    }
-
-    *data = (uint8_t*) content;
-    *dataSize = contentSize;
-}
-
 int main(int argc, char* argv[])
 {
     if (argc < 2) {
@@ -249,9 +233,9 @@
 
     SINGLE_INT_ARG_INT_RETURN(getState);
 
-    SINGLE_ARG_DATA_RETURN(get);
+    SINGLE_ARG_PLUS_UID_DATA_RETURN(get);
 
-    STING_ARG_DATA_STDIN_PLUS_UID_PLUS_FLAGS_INT_RETURN(insert);
+    // TODO: insert
 
     SINGLE_ARG_PLUS_UID_INT_RETURN(del);
 
@@ -276,7 +260,7 @@
 
     SINGLE_ARG_DATA_RETURN(get_pubkey);
 
-    SINGLE_ARG_PLUS_UID_INT_RETURN(grant);
+    // TODO: grant
 
     // TODO: ungrant
 
diff --git a/keystore/keystore_client_impl.cpp b/keystore/keystore_client_impl.cpp
index a46dfc7..c3d8f35 100644
--- a/keystore/keystore_client_impl.cpp
+++ b/keystore/keystore_client_impl.cpp
@@ -222,7 +222,7 @@
     keymaster_blob_t app_data_blob = {nullptr, 0};
     KeyCharacteristics characteristics;
     int32_t result = keystore_->getKeyCharacteristics(key_name16, &client_id_blob, &app_data_blob,
-                                                      &characteristics);
+                                                      kDefaultUID, &characteristics);
     hardware_enforced_characteristics->Reinitialize(characteristics.characteristics.hw_enforced);
     software_enforced_characteristics->Reinitialize(characteristics.characteristics.sw_enforced);
     return mapKeystoreError(result);
@@ -253,7 +253,7 @@
     keymaster_blob_t app_data_blob = {nullptr, 0};
     ExportResult export_result;
     keystore_->exportKey(key_name16, export_format, &client_id_blob, &app_data_blob,
-                         &export_result);
+                         kDefaultUID, &export_result);
     *export_data = ByteArrayAsString(export_result.exportData.get(), export_result.dataLength);
     return mapKeystoreError(export_result.resultCode);
 }
@@ -277,7 +277,7 @@
     CopyParameters(input_parameters, &input_arguments.params);
     OperationResult result;
     keystore_->begin(token, key_name16, purpose, true /*pruneable*/, input_arguments,
-                     NULL /*entropy*/, 0 /*entropyLength*/, &result);
+                     NULL /*entropy*/, 0 /*entropyLength*/, kDefaultUID, &result);
     int32_t error_code = mapKeystoreError(result.resultCode);
     if (error_code == KM_ERROR_OK) {
         *handle = getNextVirtualHandle();
diff --git a/keystore/keystore_get.cpp b/keystore/keystore_get.cpp
index 45ad415..2783816 100644
--- a/keystore/keystore_get.cpp
+++ b/keystore/keystore_get.cpp
@@ -31,7 +31,7 @@
     }
 
     size_t valueLength;
-    int32_t ret = service->get(String16(key, keyLength), value, &valueLength);
+    int32_t ret = service->get(String16(key, keyLength), -1, value, &valueLength);
     if (ret < 0) {
         return -1;
     } else if (ret != ::NO_ERROR) {
diff --git a/keystore/keystore_utils.cpp b/keystore/keystore_utils.cpp
index bfcb43a..b653dd8 100644
--- a/keystore/keystore_utils.cpp
+++ b/keystore/keystore_utils.cpp
@@ -78,8 +78,6 @@
     params->push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
     params->push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
     params->push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
-    uint64_t now = keymaster::java_time(time(NULL));
-    params->push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
 }
 
 uid_t get_app_id(uid_t uid) {
diff --git a/keystore/test-keystore b/keystore/test-keystore
index 071cfcd..3be51b3 100755
--- a/keystore/test-keystore
+++ b/keystore/test-keystore
@@ -44,7 +44,7 @@
 function run() {
     # strip out carriage returns from adb
     # strip out date/time from ls -l
-    "$@" | tr -d '\r' | sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2} +[0-9]{1,2}:[0-9]{2} //' >> $log_file
+    "$@" | tr --delete '\r' | sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2} +[0-9]{1,2}:[0-9]{2} //' >> $log_file
 }
 
 function keystore() {
@@ -53,15 +53,8 @@
     run adb shell su $user keystore_cli "$@"
 }
 
-function keystore_in() {
-    declare -r user=$1
-    declare -r input=$2
-    shift; shift
-    run adb shell "echo '$input' | su $user keystore_cli $@"
-}
-
 function list_keystore_directory() {
-    run adb shell ls -al /data/misc/keystore$@
+    run adb shell ls -al /data/misc/keystore
 }
 
 function compare() {
@@ -75,211 +68,195 @@
     # reset
     #
     log "reset keystore as system user"
-    keystore system reset
-    expect "reset: No error (1)"
+    keystore system r
+    expect "1 No error"
     list_keystore_directory
-    expect "-rw------- keystore keystore        4 .metadata"
-    expect "drwx------ keystore keystore          user_0"
 
     #
     # basic tests as system/root
     #
     log "root does not have permission to run test"
-    keystore root test
-    expect "test: Permission denied (6)"
-
+    keystore root t
+    expect "6 Permission denied"
+    
     log "but system user does"
-    keystore system test
-    expect "test: Uninitialized (3)"
+    keystore system t
+    expect "3 Uninitialized"
     list_keystore_directory
-    expect "-rw------- keystore keystore        4 .metadata"
-    expect "drwx------ keystore keystore          user_0"
 
     log "password is now bar"
-    keystore system password bar
-    expect "password: No error (1)"
-    list_keystore_directory /user_0
+    keystore system p bar
+    expect "1 No error"
+    list_keystore_directory
     expect "-rw------- keystore keystore       84 .masterkey"
-
+    
     log "no error implies initialized and unlocked"
-    keystore system test
-    expect "test: No error (1)"
-
+    keystore system t
+    expect "1 No error"
+    
     log "saw with no argument"
-    keystore system saw
+    keystore system s
+    expect "5 Protocol error"
 
     log "saw nothing"
-    keystore system saw ""
+    keystore system s ""
+    expect "1 No error"
 
     log "add key baz"
-    keystore_in system quux insert baz
-    expect "insert: No error (1)"
+    keystore system i baz quux
+    expect "1 No error"
 
     log "1000 is uid of system"
-    list_keystore_directory /user_0
+    list_keystore_directory
     expect "-rw------- keystore keystore       84 .masterkey"
     expect "-rw------- keystore keystore       52 1000_baz"
 
     log "saw baz"
-    keystore system saw
+    keystore system s ""
+    expect "1 No error"
     expect "baz"
 
     log "get baz"
-    keystore system get baz
+    keystore system g baz
+    expect "1 No error"
     expect "quux"
 
     log "root can read system user keys (as can wifi or vpn users)"
-    keystore root get baz
+    keystore root g baz
+    expect "1 No error"
     expect "quux"
 
     #
     # app user tests
     #
 
-    # u0_a0 has uid 10000, as seen below
+    # app_0 has uid 10000, as seen below
     log "other uses cannot see the system keys"
-    keystore u0_a0 get baz
-
+    keystore app_0 g baz
+    expect "7 Key not found"
+    
     log "app user cannot use reset, password, lock, unlock"
-    keystore u0_a0 reset
-    expect "reset: Permission denied (6)"
-    keystore u0_a0 password some_pass
-    expect "password: Permission denied (6)"
-    keystore u0_a0 lock
-    expect "lock: Permission denied (6)"
-    keystore u0_a0 unlock some_pass
-    expect "unlock: Permission denied (6)"
+    keystore app_0 r
+    expect "6 Permission denied"
+    keystore app_0 p
+    expect "6 Permission denied"
+    keystore app_0 l
+    expect "6 Permission denied"
+    keystore app_0 u
+    expect "6 Permission denied"
 
-    log "install u0_a0 key"
-    keystore_in u0_a0 deadbeef insert 0x
-    expect "insert: No error (1)"
-    list_keystore_directory /user_0
+    log "install app_0 key"
+    keystore app_0 i 0x deadbeef
+    expect 1 No error
+    list_keystore_directory
     expect "-rw------- keystore keystore       84 .masterkey"
     expect "-rw------- keystore keystore       52 10000_0x"
     expect "-rw------- keystore keystore       52 1000_baz"
 
     log "get with no argument"
-    keystore u0_a0 get
-    expect "Usage: keystore_cli get <name>"
-
-    log "few get tests for an app"
-    keystore u0_a0 get 0x
+    keystore app_0 g
+    expect "5 Protocol error"
+    
+    keystore app_0 g 0x
+    expect "1 No error"
     expect "deadbeef"
-
-    keystore_in u0_a0 barney insert fred
-    expect "insert: No error (1)"
-
-    keystore u0_a0 saw
+    
+    keystore app_0 i fred barney
+    expect "1 No error"
+    
+    keystore app_0 s ""
+    expect "1 No error"
     expect "0x"
     expect "fred"
 
     log "note that saw returns the suffix of prefix matches"
-    keystore u0_a0 saw fr # fred
+    keystore app_0 s fr # fred
+    expect "1 No error"
     expect "ed" # fred
 
     #
     # lock tests
     #
     log "lock the store as system"
-    keystore system lock
-    expect "lock: No error (1)"
-    keystore system test
-    expect "test: Locked (2)"
-
+    keystore system l
+    expect "1 No error"
+    keystore system t
+    expect "2 Locked"
+    
     log "saw works while locked"
-    keystore u0_a0 saw
+    keystore app_0 s ""
+    expect "1 No error"
     expect "0x"
     expect "fred"
 
-    log "...and app can read keys..."
-    keystore u0_a0 get 0x
-    expect "deadbeef"
-
-    log "...but they cannot be deleted."
-    keystore u0_a0 exist 0x
-    expect "exist: No error (1)"
-    keystore u0_a0 del_key 0x
-    expect "del_key: Key not found (7)"
+    log "...but cannot read keys..."
+    keystore app_0 g 0x
+    expect "2 Locked"
+    
+    log "...but they can be deleted."
+    keystore app_0 e 0x
+    expect "1 No error"
+    keystore app_0 d 0x
+    expect "1 No error"
+    keystore app_0 e 0x
+    expect "7 Key not found"
 
     #
     # password
     #
     log "wrong password"
-    keystore system unlock foo
-    expect "unlock: Wrong password (4 tries left) (13)"
+    keystore system u foo
+    expect "13 Wrong password (4 tries left)"
     log "right password"
-    keystore system unlock bar
-    expect "unlock: No error (1)"
-
+    keystore system u bar
+    expect "1 No error"
+    
     log "make the password foo"
-    keystore system password foo
-    expect "password: No error (1)"
-
+    keystore system p foo
+    expect "1 No error"
+    
     #
     # final reset
     #
     log "reset wipes everything for all users"
-    keystore system reset
-    expect "reset: No error (1)"
+    keystore system r
+    expect "1 No error"
     list_keystore_directory
-    expect "-rw------- keystore keystore        4 .metadata"
-    expect "drwx------ keystore keystore          user_0"
-    list_keystore_directory /user_0
-
-    keystore system test
-    expect "test: Uninitialized (3)"
-}
-
-function test_grant() {
-    log "test granting"
-    keystore system reset
-    expect "reset: No error (1)"
-    keystore system password test_pass
-    expect "password: No error (1)"
-
-    keystore_in system granted_key_value insert granted_key
-    expect "insert: No error (1)"
-  
-    # Cannot read before grant.
-    keystore u10_a0 get granted_key
     
-    # Grant and read.
-    log "System grants to u0_a1"
-    keystore system grant granted_key 10001 
-    expect "Working with uid 10001"
-    expect "grant: No error (1)"
-    keystore u0_a1 get 1000_granted_key
-    expect "granted_key_value"
+    keystore system t
+    expect "3 Uninitialized"
+
 }
 
 function test_4599735() {
     # http://b/4599735
     log "start regression test for b/4599735"
-    keystore system reset
-    expect "reset: No error (1)"
-    list_keystore_directory /user_0
+    keystore system r
+    expect "1 No error"
 
-    keystore system password foo
-    expect "password: No error (1)"
+    keystore system p foo
+    expect "1 No error"
 
-    keystore_in system quux insert baz
-    expect "insert: No error (1)"
-
-    keystore root get baz
+    keystore system i baz quux
+    expect "1 No error"
+    
+    keystore root g baz
+    expect "1 No error"
     expect "quux"
 
-    keystore system lock
-    expect "lock: No error (1)"
+    keystore system l
+    expect "1 No error"
 
-    keystore system password foo
-    expect "password: No error (1)"
+    keystore system p foo
+    expect "1 No error"
 
     log "after unlock, regression led to result of '8 Value corrupted'"
-    keystore root get baz
+    keystore root g baz
+    expect "1 No error"
     expect "quux"
 
-    keystore system reset
-    expect "reset: No error (1)"
+    keystore system r
+    expect "1 No error"
     log "end regression test for b/4599735"
 }
 
@@ -288,7 +265,6 @@
     log $tag START
     test_basic
     test_4599735
-    test_grant
     compare
     log $tag PASSED
     cleanup_output