On-device signing: Switch to using a TEE-backed keystore key.

We previously used a Strongbox key; but since we'll need to start
verifying the public key component with an HMAC operation on every boot,
switch to a TEE key instead, as TEE operations are much faster, and
this should help bring boot time down.

This also requires some logic to deal with keys in Strongbox on
updating devices.

Bug: 187862706
Test: TEST_MAPPING; manual upgrade test.
Change-Id: Ib99d689dbef02d2f0c34bfa4c852205b1ec680a7
Merged-In: Ib99d689dbef02d2f0c34bfa4c852205b1ec680a7
diff --git a/ondevice-signing/KeystoreKey.cpp b/ondevice-signing/KeystoreKey.cpp
index 4e59c58..453f256 100644
--- a/ondevice-signing/KeystoreKey.cpp
+++ b/ondevice-signing/KeystoreKey.cpp
@@ -136,12 +136,9 @@
         return false;
     }
 
-    auto status = mService->getSecurityLevel(SecurityLevel::STRONGBOX, &mSecurityLevel);
+    auto status = mService->getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT, &mSecurityLevel);
     if (!status.isOk()) {
-        status = mService->getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT, &mSecurityLevel);
-        if (!status.isOk()) {
-            return false;
-        }
+        return false;
     }
 
     auto descriptor = getKeyDescriptor();
@@ -150,7 +147,6 @@
     LOG(INFO) << "Trying to retrieve existing keystore key...";
     status = mService->getKeyEntry(descriptor, &keyEntryResponse);
     bool keyValid = false;
-
     if (status.isOk()) {
         // Make sure this is an early boot key
         for (const auto& auth : keyEntryResponse.metadata.authorizations) {
@@ -164,6 +160,17 @@
         if (!keyValid) {
             LOG(WARNING) << "Found invalid keystore key without MAX_BOOT_LEVEL tag";
         }
+
+        // On some earlier builds, we created this key on the Strongbox security level;
+        // we now use TEE keys instead (mostly for speed). It shouldn't matter since
+        // verified boot is protected by the TEE anyway. If the key happens to be on
+        // the wrong security level, delete it (this should happen just once).
+        if (keyEntryResponse.metadata.keySecurityLevel != SecurityLevel::TRUSTED_ENVIRONMENT) {
+            LOG(WARNING) << "Discarding key with security level: "
+                         << android::hardware::security::keymint::toString(
+                                keyEntryResponse.metadata.keySecurityLevel);
+            keyValid = false;
+        }
     }
 
     if (!keyValid) {