Merge "Switch *_METHOD to a more future-proof pattern." am: f3147f209c am: a786d0becd
am: 977bbeed3e

Change-Id: I62bfbff32c8f2011f8b711937d39c45be334b5de
diff --git a/keystore/auth_token_table.cpp b/keystore/auth_token_table.cpp
index 3f476cd..eea24c9 100644
--- a/keystore/auth_token_table.cpp
+++ b/keystore/auth_token_table.cpp
@@ -235,7 +235,7 @@
 
     return (token_->userId == entry.token_->userId &&
             token_->authenticatorType == entry.token_->authenticatorType &&
-            token_->authenticatorType == entry.token_->authenticatorType &&
+            token_->authenticatorId == entry.token_->authenticatorId &&
             timestamp_host_order() > entry.timestamp_host_order());
 }
 
diff --git a/keystore/blob.cpp b/keystore/blob.cpp
index a33334e..625d057 100644
--- a/keystore/blob.cpp
+++ b/keystore/blob.cpp
@@ -272,8 +272,9 @@
         return ResponseCode::VALUE_CORRUPTED;
     }
 
-    if ((isEncrypted() || isSuperEncrypted()) && (state != STATE_NO_ERROR)) {
-        return ResponseCode::LOCKED;
+    if ((isEncrypted() || isSuperEncrypted())) {
+        if (state == STATE_LOCKED) return ResponseCode::LOCKED;
+        if (state == STATE_UNINITIALIZED) return ResponseCode::UNINITIALIZED;
     }
 
     if (fileLength < offsetof(blobv3, value)) return ResponseCode::VALUE_CORRUPTED;
diff --git a/keystore/grant_store.cpp b/keystore/grant_store.cpp
index 9c2e591..2fb09c1 100644
--- a/keystore/grant_store.cpp
+++ b/keystore/grant_store.cpp
@@ -25,8 +25,10 @@
 static const char* kKeystoreGrantInfix = "_KEYSTOREGRANT_";
 static constexpr size_t kKeystoreGrantInfixLength = 15;
 
-Grant::Grant(const std::string& alias, const std::string& key_file, const uint64_t grant_no)
-        : alias_(alias), key_file_(key_file), grant_no_(grant_no) {}
+Grant::Grant(const std::string& alias, const std::string& owner_dir_name, const uid_t owner_uid,
+             const uint64_t grant_no)
+        : alias_(alias), owner_dir_name_(owner_dir_name), owner_uid_(owner_uid),
+          grant_no_(grant_no) {}
 
 static std::pair<uint64_t, std::string> parseGrantAlias(const std::string& grantAlias) {
     auto pos = grantAlias.rfind(kKeystoreGrantInfix);
@@ -39,7 +41,8 @@
     return {grant_no, wrapped_alias};
 }
 
-std::string GrantStore::put(const uid_t uid, const std::string& alias, const std::string& key_file) {
+std::string GrantStore::put(const uid_t uid, const std::string& alias,
+                            const std::string& owner_dir_name, const uid_t owner_uid) {
     std::stringstream s;
     s << alias << kKeystoreGrantInfix;
     auto& uid_grant_list = grants_[uid];
@@ -47,10 +50,12 @@
     bool success = false;
     auto iterator = std::find_if(uid_grant_list.begin(), uid_grant_list.end(),
             [&](auto& entry) {
-                return success = entry.alias_ == alias && entry.key_file_ == key_file;
+                return success = entry.alias_ == alias && entry.owner_dir_name_ == owner_dir_name
+                        && entry.owner_uid_ == owner_uid;
             });
     while (!success) {
-        std::tie(iterator, success) = uid_grant_list.emplace(alias, key_file, std::rand());
+        std::tie(iterator, success) = uid_grant_list.emplace(alias, owner_dir_name, owner_uid,
+                                                             std::rand());
     }
     s << iterator->grant_no_;
     return s.str();
@@ -70,10 +75,10 @@
     return &(*grant);
 }
 
-bool GrantStore::removeByFileName(const uid_t uid, const std::string& fileName) {
-    auto& uid_grant_list = grants_.operator[](uid);
+bool GrantStore::removeByFileAlias(const uid_t uid, const std::string& alias) {
+    auto& uid_grant_list = grants_[uid];
     for (auto i = uid_grant_list.begin(); i != uid_grant_list.end(); ++i) {
-        if (i->key_file_ == fileName) {
+        if (i->alias_ == alias) {
             uid_grant_list.erase(i);
             return true;
         }
diff --git a/keystore/grant_store.h b/keystore/grant_store.h
index 43e814e..ab03630 100644
--- a/keystore/grant_store.h
+++ b/keystore/grant_store.h
@@ -32,9 +32,11 @@
  */
 class Grant {
 public:
-    Grant(const std::string& alias, const std::string& key_file, const uint64_t grant_no);
+    Grant(const std::string& alias, const std::string& owner_dir_name, const uid_t owner_uid,
+          const uint64_t grant_no);
     std::string alias_;
-    std::string key_file_;
+    std::string owner_dir_name_;
+    uid_t owner_uid_;
     uint64_t grant_no_;
 
     operator const uint64_t&() const { return grant_no_; }
@@ -52,9 +54,10 @@
 class GrantStore {
 public:
     GrantStore() : grants_() {}
-    std::string put(const uid_t uid, const std::string& alias, const std::string& key_file);
+    std::string put(const uid_t uid, const std::string& alias, const std::string& owner_dir_name,
+                    const uid_t owner_uid);
     const Grant* get(const uid_t uid, const std::string& alias) const;
-    bool removeByFileName(const uid_t uid, const std::string& filename);
+    bool removeByFileAlias(const uid_t uid, const std::string& alias);
 
     // GrantStore is neither copyable nor movable.
     GrantStore(const GrantStore&) = delete;
diff --git a/keystore/key_store_service.cpp b/keystore/key_store_service.cpp
index abd93f1..86d7e44 100644
--- a/keystore/key_store_service.cpp
+++ b/keystore/key_store_service.cpp
@@ -526,7 +526,7 @@
         return String16();
     }
 
-    return String16(mKeyStore->addGrant(filename.string(), String8(name).string(), granteeUid).c_str());
+    return String16(mKeyStore->addGrant(String8(name).string(), granteeUid, callingUid).c_str());
 }
 
 KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
@@ -543,8 +543,8 @@
         return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
     }
 
-    return mKeyStore->removeGrant(filename.string(), granteeUid) ? ResponseCode::NO_ERROR
-                                                                 : ResponseCode::KEY_NOT_FOUND;
+    return mKeyStore->removeGrant(name8, granteeUid) ? ResponseCode::NO_ERROR
+                                                     : ResponseCode::KEY_NOT_FOUND;
 }
 
 int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
@@ -800,7 +800,26 @@
 
     KeyStoreServiceReturnCode rc =
         mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
-    if (!rc.isOk()) {
+    if (rc == ResponseCode::UNINITIALIZED) {
+        /*
+         * If we fail reading the blob because the master key is missing we try to retrieve the
+         * key characteristics from the characteristics file. This happens when auth-bound
+         * keys are used after a screen lock has been removed by the user.
+         */
+        rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
+        if (!rc.isOk()) {
+            return rc;
+        }
+        AuthorizationSet keyCharacteristics;
+        // TODO write one shot stream buffer to avoid copying (twice here)
+        std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
+                               keyBlob.getLength());
+        std::stringstream charStream(charBuffer);
+        keyCharacteristics.Deserialize(&charStream);
+
+        outCharacteristics->softwareEnforced = keyCharacteristics.hidl_data();
+        return rc;
+    } else if (!rc.isOk()) {
         return rc;
     }
 
@@ -1073,12 +1092,15 @@
     persistedCharacteristics.Subtract(teeEnforced);
     characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
 
-    result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
-                                      /*failOnTokenMissing*/ false);
+    auto authResult = getAuthToken(characteristics, 0, purpose, &authToken,
+                                   /*failOnTokenMissing*/ false);
     // If per-operation auth is needed we need to begin the operation and
     // the client will need to authorize that operation before calling
     // update. Any other auth issues stop here.
-    if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
+    if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
+        result->resultCode = authResult;
+        return;
+    }
 
     addAuthTokenToParams(&opParams, authToken);
 
@@ -1153,6 +1175,7 @@
         result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
     assert(characteristics.teeEnforced.size() == 0);
     assert(characteristics.softwareEnforced.size() == 0);
+    result->token = operationToken;
 
     if (authToken) {
         mOperationMap.setOperationAuthToken(operationToken, authToken);
@@ -1162,8 +1185,11 @@
     // 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.
-    // All fields but "token" were set in the begin operation's callback.
-    result->token = operationToken;
+    if (result->resultCode == ErrorCode::OK) {
+        result->resultCode = authResult;
+    }
+
+    // Other result fields were set in the begin operation's callback.
 }
 
 void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
diff --git a/keystore/keystore.cpp b/keystore/keystore.cpp
index ab386ad..8037335 100644
--- a/keystore/keystore.cpp
+++ b/keystore/keystore.cpp
@@ -24,6 +24,7 @@
 #include <openssl/bio.h>
 
 #include <utils/String16.h>
+#include <utils/String8.h>
 
 #include <keystore/IKeystoreService.h>
 
@@ -39,6 +40,7 @@
 const android::String16 KeyStore::sRSAKeyType("RSA");
 
 using namespace keystore;
+using android::String8;
 
 KeyStore::KeyStore(Entropy* entropy, const km_device_t& device, const km_device_t& fallback,
                    bool allowNewFallback)
@@ -414,12 +416,13 @@
     return ResponseCode::NO_ERROR;
 }
 
-std::string KeyStore::addGrant(const char* filename, const char* alias, uid_t granteeUid) {
-    return mGrants.put(granteeUid, alias, filename);
+std::string KeyStore::addGrant(const char* alias, uid_t granterUid, uid_t granteeUid) {
+    return mGrants.put(granteeUid, alias, getUserStateByUid(granterUid)->getUserDirName(),
+                       granterUid);
 }
 
-bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) {
-    return mGrants.removeByFileName(granteeUid, filename);
+bool KeyStore::removeGrant(const char* alias, uid_t granteeUid) {
+    return mGrants.removeByFileAlias(granteeUid, alias);
 }
 
 ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
@@ -502,7 +505,7 @@
     uid_t userId = get_user_id(uid);
 
     ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
-    if (responseCode == ResponseCode::NO_ERROR) {
+    if (responseCode != ResponseCode::KEY_NOT_FOUND) {
         return responseCode;
     }
 
@@ -519,7 +522,8 @@
     // They might be using a granted key.
     auto grant = mGrants.get(uid, keyName.string());
     if (!grant) return ResponseCode::KEY_NOT_FOUND;
-    filepath8 = grant->key_file_.c_str();
+    filepath8.format("%s/%s", grant->owner_dir_name_.c_str(),
+            getKeyNameForUid(String8(grant->alias_.c_str()), grant->owner_uid_, type).c_str());
 
     // It is a granted key. Try to load it.
     return get(filepath8.string(), keyBlob, type, userId);
diff --git a/keystore/keystore.h b/keystore/keystore.h
index a08508f..39761bb 100644
--- a/keystore/keystore.h
+++ b/keystore/keystore.h
@@ -87,8 +87,8 @@
     ResponseCode list(const android::String8& prefix, android::Vector<android::String16>* matches,
                       uid_t userId);
 
-    std::string addGrant(const char* filename, const char* alias, uid_t granteeUid);
-    bool removeGrant(const char* filename, uid_t granteeUid);
+    std::string addGrant(const char* alias, uid_t granterUid, uid_t granteeUid);
+    bool removeGrant(const char* alias, uid_t granteeUid);
 
     ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
                            int32_t flags);