Keymaster 4.1 VTS tests

Test:  VtsHalKeymasterV4_1TargetTest
Change-Id: I488402079ebb3940e021ac1558aeee15c4b133c9
diff --git a/keymaster/4.1/vts/functional/Android.bp b/keymaster/4.1/vts/functional/Android.bp
index f5a0c9c..c2d7fa3 100644
--- a/keymaster/4.1/vts/functional/Android.bp
+++ b/keymaster/4.1/vts/functional/Android.bp
@@ -19,12 +19,24 @@
     defaults: ["VtsHalTargetTestDefaults"],
     srcs: [
         "EarlyBootKeyTest.cpp",
+        "DeviceUniqueAttestationTest.cpp",
+        "Keymaster4_1HidlTest.cpp",
+        "UnlockedDeviceRequiredTest.cpp",
     ],
     static_libs: [
         "android.hardware.keymaster@4.0",
         "android.hardware.keymaster@4.1",
-        "libkeymaster4support",
+        "libcrypto_static",
         "libkeymaster4_1support",
+        "libkeymaster4support",
+        "libkeymaster4vtstest",
     ],
-    test_suites: ["vts-core"],
+    cflags: [
+        "-Wall",
+        "-O0",
+    ],
+    test_suites: [
+        "general-tests",
+        "vts-core",
+    ],
 }
diff --git a/keymaster/4.1/vts/functional/DeviceUniqueAttestationTest.cpp b/keymaster/4.1/vts/functional/DeviceUniqueAttestationTest.cpp
new file mode 100644
index 0000000..7ea3275
--- /dev/null
+++ b/keymaster/4.1/vts/functional/DeviceUniqueAttestationTest.cpp
@@ -0,0 +1,278 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "Keymaster4_1HidlTest.h"
+
+#include <cutils/properties.h>
+
+#include <openssl/x509.h>
+
+#include <keymasterV4_1/attestation_record.h>
+#include <keymasterV4_1/authorization_set.h>
+
+namespace android::hardware::keymaster::V4_0 {
+
+bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
+    return std::equal(a.begin(), a.end(), b.begin(), b.end());
+}
+
+}  // namespace android::hardware::keymaster::V4_0
+
+namespace android::hardware::keymaster::V4_1 {
+
+inline ::std::ostream& operator<<(::std::ostream& os, Tag tag) {
+    return os << toString(tag);
+}
+
+namespace test {
+
+using std::string;
+using std::tuple;
+
+namespace {
+
+char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
+                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
+string bin2hex(const hidl_vec<uint8_t>& data) {
+    string retval;
+    retval.reserve(data.size() * 2 + 1);
+    for (uint8_t byte : data) {
+        retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
+        retval.push_back(nibble2hex[0x0F & byte]);
+    }
+    return retval;
+}
+
+struct AuthorizationSetDifferences {
+    string aName;
+    string bName;
+    AuthorizationSet aWhackB;
+    AuthorizationSet bWhackA;
+};
+
+std::ostream& operator<<(std::ostream& o, const AuthorizationSetDifferences& diffs) {
+    if (!diffs.aWhackB.empty()) {
+        o << "Set " << diffs.aName << " contains the following that " << diffs.bName << " does not"
+          << diffs.aWhackB;
+        if (!diffs.bWhackA.empty()) o << std::endl;
+    }
+
+    if (!diffs.bWhackA.empty()) {
+        o << "Set " << diffs.bName << " contains the following that " << diffs.aName << " does not"
+          << diffs.bWhackA;
+    }
+    return o;
+}
+
+// Computes and returns a \ b and b \ a ('\' is the set-difference operator, a \ b means all the
+// elements that are in a but not b, i.e. take a and whack all the elements in b) to the provided
+// stream.  The sets must be sorted.
+//
+// This provides a simple and clear view of how the two sets differ, generally much
+// easier than scrutinizing printouts of the two sets.
+AuthorizationSetDifferences difference(string aName, const AuthorizationSet& a, string bName,
+                                       const AuthorizationSet& b) {
+    AuthorizationSetDifferences diffs = {std::move(aName), std::move(bName), {}, {}};
+    std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(diffs.aWhackB));
+    std::set_difference(b.begin(), b.end(), a.begin(), a.end(), std::back_inserter(diffs.bWhackA));
+    return diffs;
+}
+
+#define DIFFERENCE(a, b) difference(#a, a, #b, b)
+
+void check_root_of_trust(const RootOfTrust& root_of_trust) {
+    char vb_meta_device_state[PROPERTY_VALUE_MAX];
+    if (property_get("ro.boot.vbmeta.device_state", vb_meta_device_state, "") == 0) return;
+
+    char vb_meta_digest[PROPERTY_VALUE_MAX];
+    EXPECT_GT(property_get("ro.boot.vbmeta.digest", vb_meta_digest, ""), 0);
+    EXPECT_EQ(vb_meta_digest, bin2hex(root_of_trust.verified_boot_hash));
+
+    // Verified boot key should be all 0's if the boot state is not verified or self signed
+    HidlBuf empty_boot_key(string(32, '\0'));
+
+    char vb_meta_bootstate[PROPERTY_VALUE_MAX];
+    auto& verified_boot_key = root_of_trust.verified_boot_key;
+    auto& verified_boot_state = root_of_trust.verified_boot_state;
+    EXPECT_GT(property_get("ro.boot.verifiedbootstate", vb_meta_bootstate, ""), 0);
+    if (!strcmp(vb_meta_bootstate, "green")) {
+        EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_VERIFIED);
+        EXPECT_NE(verified_boot_key, empty_boot_key);
+    } else if (!strcmp(vb_meta_bootstate, "yellow")) {
+        EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_SELF_SIGNED);
+        EXPECT_NE(verified_boot_key, empty_boot_key);
+    } else if (!strcmp(vb_meta_bootstate, "orange")) {
+        EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_UNVERIFIED);
+        EXPECT_EQ(verified_boot_key, empty_boot_key);
+    } else if (!strcmp(vb_meta_bootstate, "red")) {
+        EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_FAILED);
+    } else {
+        EXPECT_EQ(verified_boot_state, V4_0::KM_VERIFIED_BOOT_UNVERIFIED);
+        EXPECT_EQ(verified_boot_key, empty_boot_key);
+    }
+}
+
+void check_attestation_record(AttestationRecord attestation, const HidlBuf& challenge,
+                              AuthorizationSet expected_sw_enforced,
+                              AuthorizationSet expected_hw_enforced,
+                              SecurityLevel expected_security_level) {
+    EXPECT_EQ(41U, attestation.keymaster_version);
+    EXPECT_EQ(4U, attestation.attestation_version);
+    EXPECT_EQ(expected_security_level, attestation.attestation_security_level);
+    EXPECT_EQ(expected_security_level, attestation.keymaster_security_level);
+    EXPECT_EQ(challenge, attestation.attestation_challenge);
+
+    check_root_of_trust(attestation.root_of_trust);
+
+    // Sort all of the authorization lists, so that equality matching works.
+    expected_sw_enforced.Sort();
+    expected_hw_enforced.Sort();
+    attestation.software_enforced.Sort();
+    attestation.hardware_enforced.Sort();
+
+    EXPECT_EQ(expected_sw_enforced, attestation.software_enforced)
+            << DIFFERENCE(expected_sw_enforced, attestation.software_enforced);
+    EXPECT_EQ(expected_hw_enforced, attestation.hardware_enforced)
+            << DIFFERENCE(expected_hw_enforced, attestation.hardware_enforced);
+}
+
+}  // namespace
+
+using std::string;
+using DeviceUniqueAttestationTest = Keymaster4_1HidlTest;
+
+TEST_P(DeviceUniqueAttestationTest, StrongBoxOnly) {
+    if (SecLevel() != SecurityLevel::STRONGBOX) return;
+
+    ASSERT_EQ(ErrorCode::OK, convert(GenerateKey(AuthorizationSetBuilder()
+                                                         .Authorization(TAG_NO_AUTH_REQUIRED)
+                                                         .RsaSigningKey(2048, 65537)
+                                                         .Digest(Digest::SHA_2_256)
+                                                         .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
+                                                         .Authorization(TAG_INCLUDE_UNIQUE_ID))));
+
+    hidl_vec<hidl_vec<uint8_t>> cert_chain;
+    EXPECT_EQ(ErrorCode::UNIMPLEMENTED,
+              convert(AttestKey(
+                      AuthorizationSetBuilder()
+                              .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
+                              .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
+                              .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
+                      &cert_chain)));
+    CheckedDeleteKey();
+
+    ASSERT_EQ(ErrorCode::OK, convert(GenerateKey(AuthorizationSetBuilder()
+                                                         .Authorization(TAG_NO_AUTH_REQUIRED)
+                                                         .EcdsaSigningKey(EcCurve::P_256)
+                                                         .Digest(Digest::SHA_2_256)
+                                                         .Authorization(TAG_INCLUDE_UNIQUE_ID))));
+
+    EXPECT_EQ(ErrorCode::UNIMPLEMENTED,
+              convert(AttestKey(
+                      AuthorizationSetBuilder()
+                              .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
+                              .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
+                      &cert_chain)));
+}
+
+TEST_P(DeviceUniqueAttestationTest, Rsa) {
+    if (SecLevel() != SecurityLevel::STRONGBOX) return;
+    ASSERT_EQ(ErrorCode::OK,
+              convert(GenerateKey(AuthorizationSetBuilder()
+                                          .Authorization(TAG_NO_AUTH_REQUIRED)
+                                          .RsaSigningKey(2048, 65537)
+                                          .Digest(Digest::SHA_2_256)
+                                          .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
+                                          .Authorization(TAG_CREATION_DATETIME, 1))));
+
+    hidl_vec<hidl_vec<uint8_t>> cert_chain;
+    HidlBuf challenge("challenge");
+    HidlBuf app_id("foo");
+    EXPECT_EQ(ErrorCode::OK,
+              convert(AttestKey(AuthorizationSetBuilder()
+                                        .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
+                                        .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
+                                        .Authorization(TAG_ATTESTATION_APPLICATION_ID, app_id),
+                                &cert_chain)));
+
+    EXPECT_EQ(1U, cert_chain.size());
+    auto [err, attestation] = parse_attestation_record(cert_chain[0]);
+    EXPECT_EQ(ErrorCode::OK, err);
+
+    check_attestation_record(attestation, challenge,
+                             /* sw_enforced */
+                             AuthorizationSetBuilder()
+                                     .Authorization(TAG_CREATION_DATETIME, 1)
+                                     .Authorization(TAG_ATTESTATION_APPLICATION_ID, app_id),
+                             /* hw_enforced */
+                             AuthorizationSetBuilder()
+                                     .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
+                                     .Authorization(TAG_NO_AUTH_REQUIRED)
+                                     .RsaSigningKey(2048, 65537)
+                                     .Digest(Digest::SHA_2_256)
+                                     .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
+                                     .Authorization(TAG_ORIGIN, KeyOrigin::GENERATED)
+                                     .Authorization(TAG_OS_VERSION, os_version())
+                                     .Authorization(TAG_OS_PATCHLEVEL, os_patch_level()),
+                             SecLevel());
+}
+
+TEST_P(DeviceUniqueAttestationTest, Ecdsa) {
+    if (SecLevel() != SecurityLevel::STRONGBOX) return;
+    ASSERT_EQ(ErrorCode::OK,
+              convert(GenerateKey(AuthorizationSetBuilder()
+                                          .Authorization(TAG_NO_AUTH_REQUIRED)
+                                          .EcdsaSigningKey(256)
+                                          .Digest(Digest::SHA_2_256)
+                                          .Authorization(TAG_CREATION_DATETIME, 1))));
+
+    hidl_vec<hidl_vec<uint8_t>> cert_chain;
+    HidlBuf challenge("challenge");
+    HidlBuf app_id("foo");
+    EXPECT_EQ(ErrorCode::OK,
+              convert(AttestKey(AuthorizationSetBuilder()
+                                        .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
+                                        .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
+                                        .Authorization(TAG_ATTESTATION_APPLICATION_ID, app_id),
+                                &cert_chain)));
+
+    EXPECT_EQ(1U, cert_chain.size());
+    auto [err, attestation] = parse_attestation_record(cert_chain[0]);
+    EXPECT_EQ(ErrorCode::OK, err);
+
+    check_attestation_record(attestation, challenge,
+                             /* sw_enforced */
+                             AuthorizationSetBuilder()
+                                     .Authorization(TAG_CREATION_DATETIME, 1)
+                                     .Authorization(TAG_ATTESTATION_APPLICATION_ID, app_id),
+                             /* hw_enforced */
+                             AuthorizationSetBuilder()
+                                     .Authorization(TAG_DEVICE_UNIQUE_ATTESTATION)
+                                     .Authorization(TAG_NO_AUTH_REQUIRED)
+                                     .EcdsaSigningKey(256)
+                                     .Digest(Digest::SHA_2_256)
+                                     .Authorization(TAG_EC_CURVE, EcCurve::P_256)
+                                     .Authorization(TAG_ORIGIN, KeyOrigin::GENERATED)
+                                     .Authorization(TAG_OS_VERSION, os_version())
+                                     .Authorization(TAG_OS_PATCHLEVEL, os_patch_level()),
+                             SecLevel());
+}
+
+INSTANTIATE_KEYMASTER_4_1_HIDL_TEST(DeviceUniqueAttestationTest);
+
+}  // namespace test
+}  // namespace android::hardware::keymaster::V4_1
diff --git a/keymaster/4.1/vts/functional/EarlyBootKeyTest.cpp b/keymaster/4.1/vts/functional/EarlyBootKeyTest.cpp
index d1978a9..a26c688 100644
--- a/keymaster/4.1/vts/functional/EarlyBootKeyTest.cpp
+++ b/keymaster/4.1/vts/functional/EarlyBootKeyTest.cpp
@@ -14,8 +14,78 @@
  * limitations under the License.
  */
 
+#include "Keymaster4_1HidlTest.h"
+
+#include <keymasterV4_1/authorization_set.h>
+
 namespace android::hardware::keymaster::V4_1::test {
 
+using std::string;
 
+using EarlyBootKeyTest = Keymaster4_1HidlTest;
+
+// Because VTS tests are run on fully-booted machines, we can only run negative tests for early boot
+// keys, which cannot be created or used after /data is mounted.  This is the only test we can run
+// in the normal case.  The positive test will have to be done by the Android system, when it
+// creates/uses early boot keys during boot.  It should fail to boot if the early boot key usage
+// fails.
+TEST_P(EarlyBootKeyTest, CannotCreateEarlyBootKeys) {
+    auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
+            CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
+
+    CheckedDeleteKeyData(&aesKeyData);
+    CheckedDeleteKeyData(&hmacKeyData);
+    CheckedDeleteKeyData(&rsaKeyData);
+    CheckedDeleteKeyData(&ecdsaKeyData);
+}
+
+// This is a more comprenhensive test, but it can only be run on a machine which is still in early
+// boot stage, which no proper Android device is by the time we can run VTS.  To use this,
+// un-disable it and modify vold to remove the call to earlyBootEnded().  Running the test will end
+// early boot, so you'll have to reboot between runs.
+TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
+    // Should be able to create keys, since early boot has not ended
+    auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
+            CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
+
+    // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
+    EXPECT_TRUE(contains(aesKeyData.characteristics.hardwareEnforced, TAG_EARLY_BOOT_ONLY));
+    EXPECT_TRUE(contains(hmacKeyData.characteristics.hardwareEnforced, TAG_EARLY_BOOT_ONLY));
+    EXPECT_TRUE(contains(rsaKeyData.characteristics.hardwareEnforced, TAG_EARLY_BOOT_ONLY));
+    EXPECT_TRUE(contains(ecdsaKeyData.characteristics.hardwareEnforced, TAG_EARLY_BOOT_ONLY));
+
+    // Should be able to use keys, since early boot has not ended
+    EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
+    EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
+    EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
+    EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
+
+    // End early boot
+    Return<ErrorCode> earlyBootResult = keymaster().earlyBootEnded();
+    EXPECT_TRUE(earlyBootResult.isOk());
+    EXPECT_EQ(earlyBootResult, ErrorCode::OK);
+
+    // Should not be able to use already-created keys.
+    EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
+    EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
+    EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
+    EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
+
+    CheckedDeleteKeyData(&aesKeyData);
+    CheckedDeleteKeyData(&hmacKeyData);
+    CheckedDeleteKeyData(&rsaKeyData);
+    CheckedDeleteKeyData(&ecdsaKeyData);
+
+    // Should not be able to create new keys
+    std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
+            CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
+
+    CheckedDeleteKeyData(&aesKeyData);
+    CheckedDeleteKeyData(&hmacKeyData);
+    CheckedDeleteKeyData(&rsaKeyData);
+    CheckedDeleteKeyData(&ecdsaKeyData);
+}
+
+INSTANTIATE_KEYMASTER_4_1_HIDL_TEST(EarlyBootKeyTest);
 
 }  // namespace android::hardware::keymaster::V4_1::test
diff --git a/keymaster/4.1/vts/functional/Keymaster4_1HidlTest.cpp b/keymaster/4.1/vts/functional/Keymaster4_1HidlTest.cpp
new file mode 100644
index 0000000..efedf28
--- /dev/null
+++ b/keymaster/4.1/vts/functional/Keymaster4_1HidlTest.cpp
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "Keymaster4_1HidlTest.h"
+
+namespace android::hardware::keymaster::V4_1::test {
+
+using std::string;
+
+void Keymaster4_1HidlTest::SetUp() {
+    keymaster41_ = IKeymasterDevice::getService(GetParam());
+    InitializeKeymaster(keymaster41_);
+}
+
+auto Keymaster4_1HidlTest::ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation,
+                                          const string& message, const AuthorizationSet& in_params)
+        -> std::tuple<ErrorCode, string, AuthorizationSet /* out_params */> {
+    AuthorizationSet begin_out_params;
+    V4_0::ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params, &op_handle_);
+    AuthorizationSet out_params(std::move(begin_out_params));
+    if (result != V4_0::ErrorCode::OK) {
+        return {convert(result), {}, out_params};
+    }
+
+    string output;
+    size_t consumed = 0;
+    AuthorizationSet update_params;
+    AuthorizationSet update_out_params;
+    result = Update(op_handle_, update_params, message, &update_out_params, &output, &consumed);
+    out_params.push_back(update_out_params);
+    if (result != V4_0::ErrorCode::OK) {
+        return {convert(result), output, out_params};
+    }
+
+    string unused;
+    AuthorizationSet finish_params;
+    AuthorizationSet finish_out_params;
+    result = Finish(op_handle_, finish_params, message.substr(consumed), unused, &finish_out_params,
+                    &output);
+    op_handle_ = V4_0::test::kOpHandleSentinel;
+    out_params.push_back(finish_out_params);
+
+    return {convert(result), output, out_params};
+}
+
+}  // namespace android::hardware::keymaster::V4_1::test
diff --git a/keymaster/4.1/vts/functional/Keymaster4_1HidlTest.h b/keymaster/4.1/vts/functional/Keymaster4_1HidlTest.h
new file mode 100644
index 0000000..6332c43
--- /dev/null
+++ b/keymaster/4.1/vts/functional/Keymaster4_1HidlTest.h
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#pragma once
+
+#include <android/hardware/keymaster/4.1/IKeymasterDevice.h>
+
+#include <KeymasterHidlTest.h>
+#include <keymasterV4_1/authorization_set.h>
+
+namespace android::hardware::keymaster::V4_1::test {
+
+using V4_0::test::HidlBuf;
+
+class Keymaster4_1HidlTest : public V4_0::test::KeymasterHidlTest {
+  public:
+    using super = V4_0::test::KeymasterHidlTest;
+
+    ErrorCode convert(V4_0::ErrorCode error_code) { return static_cast<ErrorCode>(error_code); }
+
+    // These methods hide the base class versions.
+    void SetUp();
+    IKeymasterDevice& keymaster() { return *keymaster41_; };
+
+    struct KeyData {
+        HidlBuf blob;
+        KeyCharacteristics characteristics;
+    };
+
+    std::tuple<ErrorCode, KeyData> GenerateKeyData(const AuthorizationSet& keyDescription) {
+        KeyData keyData;
+        ErrorCode errorCode = convert(
+                super::GenerateKey(keyDescription, &keyData.blob, &keyData.characteristics));
+        return {errorCode, keyData};
+    }
+
+    void CheckedDeleteKeyData(KeyData* keyData) { CheckedDeleteKey(&keyData->blob); }
+
+    template <typename TagType>
+    std::tuple<KeyData /* aesKey */, KeyData /* hmacKey */, KeyData /* rsaKey */,
+               KeyData /* ecdsaKey */>
+    CreateTestKeys(TagType tagToTest, ErrorCode expectedReturn) {
+        ErrorCode errorCode;
+
+        /* AES */
+        KeyData aesKeyData;
+        std::tie(errorCode, aesKeyData) =
+                GenerateKeyData(AuthorizationSetBuilder()
+                                        .AesEncryptionKey(128)
+                                        .Authorization(tagToTest)
+                                        .BlockMode(BlockMode::ECB)
+                                        .Padding(PaddingMode::NONE)
+                                        .Authorization(TAG_NO_AUTH_REQUIRED));
+        EXPECT_EQ(expectedReturn, errorCode);
+
+        /* HMAC */
+        KeyData hmacKeyData;
+        std::tie(errorCode, hmacKeyData) =
+                GenerateKeyData(AuthorizationSetBuilder()
+                                        .HmacKey(128)
+                                        .Authorization(tagToTest)
+                                        .Digest(Digest::SHA_2_256)
+                                        .Authorization(TAG_MIN_MAC_LENGTH, 128)
+                                        .Authorization(TAG_NO_AUTH_REQUIRED));
+        EXPECT_EQ(expectedReturn, errorCode);
+
+        /* RSA */
+        KeyData rsaKeyData;
+        std::tie(errorCode, rsaKeyData) =
+                GenerateKeyData(AuthorizationSetBuilder()
+                                        .RsaSigningKey(2048, 65537)
+                                        .Authorization(tagToTest)
+                                        .Digest(Digest::NONE)
+                                        .Padding(PaddingMode::NONE)
+                                        .Authorization(TAG_NO_AUTH_REQUIRED));
+        EXPECT_EQ(expectedReturn, errorCode);
+
+        /* ECDSA */
+        KeyData ecdsaKeyData;
+        std::tie(errorCode, ecdsaKeyData) =
+                GenerateKeyData(AuthorizationSetBuilder()
+                                        .EcdsaSigningKey(256)
+                                        .Authorization(tagToTest)
+                                        .Digest(Digest::SHA_2_256)
+                                        .Authorization(TAG_NO_AUTH_REQUIRED));
+        EXPECT_EQ(expectedReturn, errorCode);
+
+        return {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData};
+    }
+
+    std::tuple<ErrorCode, std::string /* processedMessage */, AuthorizationSet /* out_params */>
+    ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation, const std::string& message,
+                   const AuthorizationSet& in_params);
+
+    ErrorCode UseAesKey(const HidlBuf& aesKeyBlob) {
+        auto [result, ciphertext, out_params] = ProcessMessage(
+                aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
+                AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
+        return result;
+    }
+
+    ErrorCode UseHmacKey(const HidlBuf& hmacKeyBlob) {
+        auto [result, mac, out_params] =
+                ProcessMessage(hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
+                               AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128));
+        return result;
+    }
+
+    ErrorCode UseRsaKey(const HidlBuf& rsaKeyBlob) {
+        std::string message(2048 / 8, 'a');
+        auto [result, signature, out_params] = ProcessMessage(
+                rsaKeyBlob, KeyPurpose::SIGN, message,
+                AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
+        return result;
+    }
+
+    ErrorCode UseEcdsaKey(const HidlBuf& ecdsaKeyBlob) {
+        auto [result, signature, out_params] =
+                ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
+                               AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
+        return result;
+    }
+
+    static std::vector<std::string> build_params() {
+        auto params = android::hardware::getAllHalInstanceNames(IKeymasterDevice::descriptor);
+        return params;
+    }
+
+  private:
+    sp<IKeymasterDevice> keymaster41_;
+};
+
+template <typename TypedTag>
+bool contains(hidl_vec<KeyParameter>& set, TypedTag typedTag) {
+    return std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
+               return param.tag == static_cast<V4_0::Tag>(typedTag);
+           }) != set.end();
+}
+
+#define INSTANTIATE_KEYMASTER_4_1_HIDL_TEST(name)                                     \
+    INSTANTIATE_TEST_SUITE_P(PerInstance, name,                                       \
+                             testing::ValuesIn(Keymaster4_1HidlTest::build_params()), \
+                             android::hardware::PrintInstanceNameToString)
+
+}  // namespace android::hardware::keymaster::V4_1::test
diff --git a/keymaster/4.1/vts/functional/UnlockedDeviceRequiredTest.cpp b/keymaster/4.1/vts/functional/UnlockedDeviceRequiredTest.cpp
new file mode 100644
index 0000000..671bbbf
--- /dev/null
+++ b/keymaster/4.1/vts/functional/UnlockedDeviceRequiredTest.cpp
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#include "Keymaster4_1HidlTest.h"
+
+#include <keymasterV4_1/authorization_set.h>
+
+namespace android::hardware::keymaster::V4_1::test {
+
+using UnlockedDeviceRequiredTest = Keymaster4_1HidlTest;
+
+// This may be a problematic test.  It can't be run repeatedly without unlocking the device in
+// between runs... and on most test devices there are no enrolled credentials so it can't be
+// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
+// device is to reboot it.  For that reason, this is disabled by default.  It can be used as part of
+// a manual test process, which includes unlocking between runs, which is why it's included here.
+// Well, that and the fact that it's the only test we can do without also making calls into the
+// Gatekeeper HAL.  We haven't written any cross-HAL tests, and don't know what all of the
+// implications might be, so that may or may not be a solution.
+//
+// TODO(swillden): Use the Gatekeeper HAL to enroll some test credentials which we can verify to get
+// an unlock auth token.  If that works, enable the improved test.
+TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
+    auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
+            CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
+
+    EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
+    EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
+    EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
+    EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
+
+    Return<ErrorCode> rc =
+            keymaster().deviceLocked(false /* passwordOnly */, {} /* verificationToken */);
+    ASSERT_TRUE(rc.isOk());
+    ASSERT_EQ(ErrorCode::OK, static_cast<ErrorCode>(rc));
+
+    EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
+    EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
+    EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
+    EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
+
+    CheckedDeleteKeyData(&aesKeyData);
+    CheckedDeleteKeyData(&hmacKeyData);
+    CheckedDeleteKeyData(&rsaKeyData);
+    CheckedDeleteKeyData(&ecdsaKeyData);
+}
+
+INSTANTIATE_KEYMASTER_4_1_HIDL_TEST(UnlockedDeviceRequiredTest);
+
+}  // namespace android::hardware::keymaster::V4_1::test