vold: Support Storage keys for FBE

To prevent keys from being compromised if an attacker
acquires read access to kernel memory, some inline
encryption hardware supports protecting the keys in
hardware without software having access to or the
ability to set the plaintext keys.  Instead, software
only sees "wrapped keys", which may differ on every boot.

'wrappedkey_v0' fileencryption flag is used to denote
that the device supports inline encryption hardware that
supports this feature. On such devices keymaster is used
to generate keys with STORAGE_KEY tag and export a
per-boot ephemerally wrapped storage key to install it in
the kernel.

The wrapped key framework in the linux kernel ensures the
wrapped key is provided to the inline encryption hardware
where it is unwrapped and the file contents key is derived
to encrypt contents without revealing the plaintext key in
the clear.

Test: FBE validation with Fscrypt v2 + inline crypt + wrapped
key changes kernel.

Bug: 147733587

Change-Id: I1f0de61b56534ec1df9baef075acb74bacd00758
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
index acd5b59..76ea9eb 100644
--- a/MetadataCrypt.cpp
+++ b/MetadataCrypt.cpp
@@ -113,6 +113,23 @@
     LOG(INFO) << "Old Key deleted: " << dir;
 }
 
+static bool retrieveMetadataKey(bool create_if_absent, const std::string& key_path,
+                                const std::string& tmp_path, KeyBuffer* key, bool keepOld) {
+    if (pathExists(key_path)) {
+        LOG(DEBUG) << "Key exists, using: " << key_path;
+        if (!retrieveKey(key_path, kEmptyAuthentication, key, keepOld)) return false;
+    } else {
+        if (!create_if_absent) {
+            LOG(ERROR) << "No key found in " << key_path;
+            return false;
+        }
+        LOG(INFO) << "Creating new key in " << key_path;
+        if (!randomKey(key)) return false;
+        if (!storeKeyAtomically(key_path, tmp_path, kEmptyAuthentication, *key)) return false;
+    }
+    return true;
+}
+
 static bool read_key(const FstabEntry& data_rec, bool create_if_absent, KeyBuffer* key) {
     if (data_rec.metadata_key_dir.empty()) {
         LOG(ERROR) << "Failed to get metadata_key_dir";
@@ -143,9 +160,7 @@
             unlink(newKeyPath.c_str());
     }
     bool needs_cp = cp_needsCheckpoint();
-    if (!android::vold::retrieveKey(create_if_absent, kEmptyAuthentication, dir, temp, key,
-                                    needs_cp))
-        return false;
+    if (!retrieveMetadataKey(create_if_absent, dir, temp, key, needs_cp)) return false;
     if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
     return true;
 }