Merge "Revert "Add "Unlocked device required" parameter to keys""
diff --git a/keystore/KeyStore.cpp b/keystore/KeyStore.cpp
index d9355b9..0efc4a3 100644
--- a/keystore/KeyStore.cpp
+++ b/keystore/KeyStore.cpp
@@ -28,11 +28,22 @@
 
 #include <android/hardware/keymaster/3.0/IKeymasterDevice.h>
 #include <android/security/IKeystoreService.h>
+#include <log/log_event_list.h>
+
+#include <private/android_logger.h>
 
 #include "keystore_utils.h"
 #include "permissions.h"
 #include <keystore/keystore_hidl_support.h>
 
+namespace {
+
+// Tags for audit logging. Be careful and don't log sensitive data.
+// Should be in sync with frameworks/base/core/java/android/app/admin/SecurityLogTags.logtags
+constexpr int SEC_TAG_KEY_DESTROYED = 210026;
+
+}  // anonymous namespace
+
 namespace keystore {
 
 const char* KeyStore::kOldMasterKey = ".masterkey";
@@ -381,8 +392,12 @@
         auto ret = KS_HANDLE_HIDL_ERROR(dev->deleteKey(blob2hidlVec(keyBlob)));
 
         // A device doesn't have to implement delete_key.
-        if (ret != ErrorCode::OK && ret != ErrorCode::UNIMPLEMENTED)
-            return ResponseCode::SYSTEM_ERROR;
+        bool success = ret == ErrorCode::OK || ret == ErrorCode::UNIMPLEMENTED;
+        if (__android_log_security() && uidAlias.isOk()) {
+            android_log_event_list(SEC_TAG_KEY_DESTROYED)
+                << int32_t(success) << alias << int32_t(uid) << LOG_ID_SECURITY;
+        }
+        if (!success) return ResponseCode::SYSTEM_ERROR;
     }
 
     rc =
@@ -585,11 +600,6 @@
     }
 
     auto version = getDevice(SecurityLevel::TRUSTED_ENVIRONMENT)->halVersion();
-    if (version.error != ErrorCode::OK) {
-        ALOGE("Failed to get HAL version info");
-        return false;
-    }
-
     if (keyType == kRsaKeyType) return true;  // All versions support RSA
     return keyType == kEcKeyType && version.supportsEc;
 }
diff --git a/keystore/include/keystore/keystore_hidl_support.h b/keystore/include/keystore/keystore_hidl_support.h
index 7a3723e..781b153 100644
--- a/keystore/include/keystore/keystore_hidl_support.h
+++ b/keystore/include/keystore/keystore_hidl_support.h
@@ -26,11 +26,16 @@
 #include <android/hardware/keymaster/3.0/IKeymasterDevice.h>
 #include <hardware/hw_auth_token.h>
 #include <hidl/Status.h>
+#include <keymasterV4_0/keymaster_utils.h>
 
 #include <keystore/keymaster_types.h>
 
 namespace keystore {
 
+using android::hardware::keymaster::V4_0::support::blob2hidlVec;
+using android::hardware::keymaster::V4_0::support::hidlVec2AuthToken;
+using android::hardware::keymaster::V4_0::support::authToken2HidlVec;
+
 inline static std::ostream& formatArgs(std::ostream& out) {
     return out;
 }
@@ -69,32 +74,6 @@
 #define KS_HANDLE_HIDL_ERROR(rc)                                                                   \
     ::keystore::ksHandleHidlError(rc, __FILE__, ":", __LINE__, ":", __PRETTY_FUNCTION__)
 
-inline static hidl_vec<uint8_t> blob2hidlVec(const uint8_t* data, const size_t length,
-                                             bool inPlace = true) {
-    hidl_vec<uint8_t> result;
-    if (inPlace)
-        result.setToExternal(const_cast<unsigned char*>(data), length);
-    else {
-        result.resize(length);
-        memcpy(&result[0], data, length);
-    }
-    return result;
-}
-
-inline static hidl_vec<uint8_t> blob2hidlVec(const std::string& value) {
-    hidl_vec<uint8_t> result;
-    result.setToExternal(
-        reinterpret_cast<uint8_t*>(const_cast<std::string::value_type*>(value.data())),
-        static_cast<size_t>(value.size()));
-    return result;
-}
-
-inline static hidl_vec<uint8_t> blob2hidlVec(const std::vector<uint8_t>& blob) {
-    hidl_vec<uint8_t> result;
-    result.setToExternal(const_cast<uint8_t*>(blob.data()), static_cast<size_t>(blob.size()));
-    return result;
-}
-
 template <typename T, typename OutIter>
 inline static OutIter copy_bytes_to_iterator(const T& value, OutIter dest) {
     const uint8_t* value_ptr = reinterpret_cast<const uint8_t*>(&value);
@@ -159,59 +138,6 @@
     return token;
 }
 
-inline static hidl_vec<uint8_t> authToken2HidlVec(const HardwareAuthToken& token) {
-    static_assert(1 /* version size */ + sizeof(token.challenge) + sizeof(token.userId) +
-                          sizeof(token.authenticatorId) + sizeof(token.authenticatorType) +
-                          sizeof(token.timestamp) + kHmacSize ==
-                      sizeof(hw_auth_token_t),
-                  "HardwareAuthToken content size does not match hw_auth_token_t size");
-
-    hidl_vec<uint8_t> result;
-    result.resize(sizeof(hw_auth_token_t));
-    auto pos = result.begin();
-    *pos++ = 0;  // Version byte
-    pos = copy_bytes_to_iterator(token.challenge, pos);
-    pos = copy_bytes_to_iterator(token.userId, pos);
-    pos = copy_bytes_to_iterator(token.authenticatorId, pos);
-    auto auth_type = htonl(static_cast<uint32_t>(token.authenticatorType));
-    pos = copy_bytes_to_iterator(auth_type, pos);
-    auto timestamp = htonq(token.timestamp);
-    pos = copy_bytes_to_iterator(timestamp, pos);
-    if (token.mac.size() != kHmacSize) {
-        std::fill(pos, pos + kHmacSize, 0);
-    } else {
-        std::copy(token.mac.begin(), token.mac.end(), pos);
-    }
-
-    return result;
-}
-
-inline static HardwareAuthToken hidlVec2AuthToken(const hidl_vec<uint8_t>& buffer) {
-    HardwareAuthToken token;
-    static_assert(1 /* version size */ + sizeof(token.challenge) + sizeof(token.userId) +
-                          sizeof(token.authenticatorId) + sizeof(token.authenticatorType) +
-                          sizeof(token.timestamp) + kHmacSize ==
-                      sizeof(hw_auth_token_t),
-                  "HardwareAuthToken content size does not match hw_auth_token_t size");
-
-    if (buffer.size() != sizeof(hw_auth_token_t)) return {};
-
-    auto pos = buffer.begin();
-    ++pos;  // skip first byte
-    pos = copy_bytes_from_iterator(&token.challenge, pos);
-    pos = copy_bytes_from_iterator(&token.userId, pos);
-    pos = copy_bytes_from_iterator(&token.authenticatorId, pos);
-    pos = copy_bytes_from_iterator(&token.authenticatorType, pos);
-    token.authenticatorType = static_cast<HardwareAuthenticatorType>(
-        ntohl(static_cast<uint32_t>(token.authenticatorType)));
-    pos = copy_bytes_from_iterator(&token.timestamp, pos);
-    token.timestamp = ntohq(token.timestamp);
-    token.mac.resize(kHmacSize);
-    std::copy(pos, pos + kHmacSize, token.mac.data());
-
-    return token;
-}
-
 inline std::string hidlVec2String(const hidl_vec<uint8_t>& value) {
     return std::string(reinterpret_cast<const std::string::value_type*>(&value[0]), value.size());
 }
diff --git a/keystore/key_store_service.cpp b/keystore/key_store_service.cpp
index 96d8f4d..89c31a5 100644
--- a/keystore/key_store_service.cpp
+++ b/keystore/key_store_service.cpp
@@ -25,12 +25,15 @@
 #include <algorithm>
 #include <sstream>
 
+#include <android-base/scopeguard.h>
 #include <binder/IInterface.h>
 #include <binder/IPCThreadState.h>
 #include <binder/IPermissionController.h>
 #include <binder/IServiceManager.h>
+#include <log/log_event_list.h>
 
 #include <private/android_filesystem_config.h>
+#include <private/android_logger.h>
 
 #include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
 
@@ -61,6 +64,11 @@
 constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
 const char* kTimestampFilePath = "timestamp";
 
+// Tags for audit logging. Be careful and don't log sensitive data.
+// Should be in sync with frameworks/base/core/java/android/app/admin/SecurityLogTags.logtags
+constexpr int SEC_TAG_AUTH_KEY_GENERATED = 210024;
+constexpr int SEC_TAG_KEY_IMPORTED = 210025;
+
 struct BIGNUM_Delete {
     void operator()(BIGNUM* p) const { BN_free(p); }
 };
@@ -735,6 +743,13 @@
     // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
     uid_t originalUid = IPCThreadState::self()->getCallingUid();
     uid = getEffectiveUid(uid);
+    auto logOnScopeExit = android::base::make_scope_guard([&] {
+        if (__android_log_security()) {
+            android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
+                << int32_t(*aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
+                << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
+        }
+    });
     KeyStoreServiceReturnCode rc =
         checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
     if (!rc.isOk()) {
@@ -950,6 +965,13 @@
                            int32_t* aidl_return) {
 
     uid = getEffectiveUid(uid);
+    auto logOnScopeExit = android::base::make_scope_guard([&] {
+        if (__android_log_security()) {
+            android_log_event_list(SEC_TAG_KEY_IMPORTED)
+                << int32_t(*aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
+                << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
+        }
+    });
     KeyStoreServiceReturnCode rc =
         checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
     if (!rc.isOk()) {
diff --git a/keystore/keystore.rc b/keystore/keystore.rc
index 5dac937..132039a 100644
--- a/keystore/keystore.rc
+++ b/keystore/keystore.rc
@@ -1,5 +1,5 @@
 service keystore /system/bin/keystore /data/misc/keystore
     class main
     user keystore
-    group keystore drmrpc readproc
+    group keystore drmrpc readproc log
     writepid /dev/cpuset/foreground/tasks
diff --git a/keystore/keystore_main.cpp b/keystore/keystore_main.cpp
index e1fdd3f..1ec32dd 100644
--- a/keystore/keystore_main.cpp
+++ b/keystore/keystore_main.cpp
@@ -72,7 +72,7 @@
                               << Wrapper::WrappedIKeymasterDevice::descriptor
                               << "\" with interface name \"" << name << "\"";
 
-                sp<Keymaster> kmDevice(new Wrapper(device));
+                sp<Keymaster> kmDevice(new Wrapper(device, name));
                 auto halVersion = kmDevice->halVersion();
                 SecurityLevel securityLevel = halVersion.securityLevel;
                 LOG(INFO) << "found " << Wrapper::WrappedIKeymasterDevice::descriptor
@@ -175,7 +175,7 @@
     if (!result[SecurityLevel::SOFTWARE]) {
         auto fbdev = android::keystore::makeSoftwareKeymasterDevice();
         CHECK(fbdev.get()) << "Unable to create Software Keymaster Device";
-        result[SecurityLevel::SOFTWARE] = new Keymaster3(fbdev);
+        result[SecurityLevel::SOFTWARE] = new Keymaster3(fbdev, "Software");
     }
     return result;
 }
@@ -197,8 +197,6 @@
     CHECK(configure_selinux() != -1) << "Failed to configure SELinux.";
 
     auto halVersion = kmDevices[SecurityLevel::TRUSTED_ENVIRONMENT]->halVersion();
-    CHECK(halVersion.error == keystore::ErrorCode::OK)
-        << "Error " << toString(halVersion.error) << " getting HAL version";
 
     // If the hardware is keymaster 2.0 or higher we will not allow the fallback device for import
     // or generation of keys. The fallback device is only used for legacy keys present on the
diff --git a/keystore/tests/auth_token_formatting_test.cpp b/keystore/tests/auth_token_formatting_test.cpp
index 2677718..0ecc4cc 100644
--- a/keystore/tests/auth_token_formatting_test.cpp
+++ b/keystore/tests/auth_token_formatting_test.cpp
@@ -19,6 +19,7 @@
 #include <endian.h>
 #include <hidl/HidlSupport.h>
 #include <keymaster/logger.h>
+#include <keymasterV4_0/keymaster_utils.h>
 
 #include <keystore/keymaster_types.h>
 #include <keystore/keystore_hidl_support.h>