ext4crypt: support wrappedkey for FBE

Qualcomm devices use a special `wrappedkey` mode for FBE. This is ported
from CAF
https://source.codeaurora.org/quic/la/platform/system/vold/commit/?h=LA.UM.7.8.r4-01000-SDM710.0&id=9229262d893a8592f7bc1b4e8a8dab7aad8df68c,
originally by folks at Mokee for vold
https://mokeedev.review/c/MoKee/android_system_vold/+/34102.

This patch ports the above changes to `ext4crypt`, which we can use in
recovery. Note that since we do not have `fs_mgr` in the recovery, we
cannot read the `wrappedkey` flag from fstab. Instead, similar to
`fbe.contents`, we use a special property `fbe.data.wrappedkey` to
indicate support for wrappedkey mode. Devices that need to use this
should set this property to `true` to activate corresponding code.

Change-Id: I79c2855d577156670b45c10c7c7b1fcd9fece8d9
diff --git a/crypto/ext4crypt/Ext4CryptPie.cpp b/crypto/ext4crypt/Ext4CryptPie.cpp
index d6ea531..d76ca24 100644
--- a/crypto/ext4crypt/Ext4CryptPie.cpp
+++ b/crypto/ext4crypt/Ext4CryptPie.cpp
@@ -16,6 +16,7 @@
 
 #include "Ext4CryptPie.h"
 
+#include "Keymaster4.h"
 #include "KeyStorage4.h"
 #include "KeyUtil.h"
 #include "Utils.h"
@@ -68,6 +69,8 @@
 using android::base::WriteStringToFile;
 using android::vold::kEmptyAuthentication;
 using android::vold::KeyBuffer;
+using android::vold::Keymaster;
+using android::hardware::keymaster::V4_0::KeyFormat;
 
 // Store main DE raw ref / policy
 std::string de_raw_ref;
@@ -204,12 +207,42 @@
     return false;
 }
 
+static bool is_wrapped_key_supported_common(const std::string& mount_point) {
+    LOG(DEBUG) << "Determining wrapped-key support for " << mount_point;
+    std::string wrapped_key_supported = android::base::GetProperty("fbe.data.wrappedkey", "false");
+    LOG(DEBUG) << "fbe.data.wrappedkey = " << wrapped_key_supported;
+    if (mount_point == DATA_MNT_POINT && wrapped_key_supported == "true") {
+        LOG(DEBUG) << "Wrapped key supported on " << mount_point;
+        return true;
+    } else {
+        return false;
+    }
+}
+
+bool is_wrapped_key_supported() {
+    return is_wrapped_key_supported_common(DATA_MNT_POINT);
+}
+
+bool is_wrapped_key_supported_external() {
+    return false;
+}
+
 static bool read_and_install_user_ce_key(userid_t user_id,
                                          const android::vold::KeyAuthentication& auth) {
     if (s_ce_key_raw_refs.count(user_id) != 0) return true;
     KeyBuffer ce_key;
     if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
     std::string ce_raw_ref;
+
+    if (is_wrapped_key_supported()) {
+        KeyBuffer ephemeral_wrapped_key;
+        if (!getEphemeralWrappedKey(KeyFormat::RAW, ce_key, &ephemeral_wrapped_key)) {
+           LOG(ERROR) << "Failed to export ce key";
+           return false;
+        }
+
+        ce_key = std::move(ephemeral_wrapped_key);
+    }
     if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
     s_ce_keys[user_id] = std::move(ce_key);
     s_ce_key_raw_refs[user_id] = ce_raw_ref;
@@ -335,6 +368,14 @@
             KeyBuffer key;
             if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
             std::string raw_ref;
+            if (is_wrapped_key_supported()) {
+                KeyBuffer ephemeral_wrapped_key;
+                if (!getEphemeralWrappedKey(KeyFormat::RAW, key, &ephemeral_wrapped_key)) {
+                   LOG(ERROR) << "Failed to export de_key in create_and_install_user_keys";
+                   return false;
+                }
+                key = std::move(ephemeral_wrapped_key);
+            }
             if (!android::vold::installKey(key, &raw_ref)) return false;
             s_de_key_raw_refs[user_id] = raw_ref;
             LOG(DEBUG) << "Installed de key for user " << user_id << std::endl;
@@ -347,6 +388,7 @@
 
 bool e4crypt_initialize_global_de() {
     LOG(INFO) << "e4crypt_initialize_global_de" << std::endl;
+    bool wrapped_key_supported = false;
 
     if (s_global_de_initialized) {
         LOG(INFO) << "Already initialized" << std::endl;
@@ -354,9 +396,10 @@
     }
 
     PolicyKeyRef device_ref;
+    wrapped_key_supported = is_wrapped_key_supported();
     LOG(INFO) << "calling retrieveAndInstallKey\n";
     if (!android::vold::retrieveAndInstallKey(true, kEmptyAuthentication, device_key_path,
-                                              device_key_temp, &device_ref.key_raw_ref))
+                                              device_key_temp, &device_ref.key_raw_ref, wrapped_key_supported))
         return false;
     get_data_file_encryption_modes(&device_ref);
 
@@ -535,6 +578,7 @@
                                   PolicyKeyRef* key_ref) {
     auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
     std::string secdiscardable_hash;
+    bool wrapped_key_supported = false;
     if (android::vold::pathExists(secdiscardable_path)) {
         if (!android::vold::readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
             return false;
@@ -552,8 +596,9 @@
         return false;
     }
     android::vold::KeyAuthentication auth("", secdiscardable_hash);
+    wrapped_key_supported = is_wrapped_key_supported_external();
     if (!android::vold::retrieveAndInstallKey(true, auth, key_path, key_path + "_tmp",
-                                              &key_ref->key_raw_ref))
+                                              &key_ref->key_raw_ref, wrapped_key_supported))
         return false;
     key_ref->contents_mode =
         android::base::GetProperty("ro.crypto.volume.contents_mode", "aes-256-xts");
diff --git a/crypto/ext4crypt/Ext4CryptPie.h b/crypto/ext4crypt/Ext4CryptPie.h
index 6e2afa5..d6d6ecf 100644
--- a/crypto/ext4crypt/Ext4CryptPie.h
+++ b/crypto/ext4crypt/Ext4CryptPie.h
@@ -38,5 +38,8 @@
 
 bool e4crypt_destroy_volume_keys(const std::string& volume_uuid);*/
 
+bool is_wrapped_key_supported();
+bool is_wrapped_key_supported_external();
+
 bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
                            std::string* raw_ref);
diff --git a/crypto/ext4crypt/KeyStorage4.cpp b/crypto/ext4crypt/KeyStorage4.cpp
index 28efdf1..cab88a1 100644
--- a/crypto/ext4crypt/KeyStorage4.cpp
+++ b/crypto/ext4crypt/KeyStorage4.cpp
@@ -66,6 +66,7 @@
 static constexpr size_t STRETCHED_BYTES = 1 << 6;
 
 static constexpr uint32_t AUTH_TIMEOUT = 30;  // Seconds
+constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
 
 static const char* kCurrentVersion = "1";
 static const char* kRmPath = "/system/bin/rm";
@@ -131,6 +132,45 @@
     return keymaster.generateKey(paramBuilder, key);
 }
 
+bool generateWrappedKey(userid_t user_id, KeyType key_type,
+                                     KeyBuffer* key) {
+    Keymaster keymaster;
+    if (!keymaster) return false;
+    *key = KeyBuffer(EXT4_AES_256_XTS_KEY_SIZE);
+    std::string key_temp;
+    auto paramBuilder = km::AuthorizationSetBuilder()
+                               .AesEncryptionKey(AES_KEY_BYTES * 8)
+                               .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
+                               .Authorization(km::TAG_USER_ID, user_id);
+    km::KeyParameter param1;
+    param1.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_FBE_ICE);
+    param1.f.boolValue = true;
+    paramBuilder.push_back(param1);
+    km::KeyParameter param2;
+    if ((key_type == KeyType::DE_USER) || (key_type == KeyType::DE_SYS)) {
+        param2.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_KEY_TYPE);
+        param2.f.integer = 0;
+    } else if (key_type == KeyType::CE_USER) {
+        param2.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_KEY_TYPE);
+        param2.f.integer = 1;
+    }
+    paramBuilder.push_back(param2);
+    if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
+    *key = KeyBuffer(key_temp.size());
+    memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
+    return true;
+}
+
+bool getEphemeralWrappedKey(km::KeyFormat format, KeyBuffer& kmKey, KeyBuffer* key) {
+    std::string key_temp;
+    Keymaster keymaster;
+    if (!keymaster) return false;
+    if (!keymaster.exportKey(format, kmKey, "!", "!", &key_temp)) return false;
+    *key = KeyBuffer(key_temp.size());
+    memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
+    return true;
+}
+
 static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
     const KeyAuthentication& auth, const std::string& appId) {
     auto paramBuilder = km::AuthorizationSetBuilder()
diff --git a/crypto/ext4crypt/KeyStorage4.h b/crypto/ext4crypt/KeyStorage4.h
index 35ff65e..f74865f 100644
--- a/crypto/ext4crypt/KeyStorage4.h
+++ b/crypto/ext4crypt/KeyStorage4.h
@@ -17,13 +17,17 @@
 #ifndef ANDROID_TWRP_KEYSTORAGE_H
 #define ANDROID_TWRP_KEYSTORAGE_H
 
+#include "Keymaster4.h"
 #include "KeyBuffer.h"
+#include <ext4_utils/ext4_crypt.h>
 
 #include <string>
 
 namespace android {
 namespace vold {
 
+namespace km = ::android::hardware::keymaster::V4_0;
+
 // Represents the information needed to decrypt a disk encryption key.
 // If "token" is nonempty, it is passed in as a required Gatekeeper auth token.
 // If "token" and "secret" are nonempty, "secret" is appended to the application-specific
@@ -39,6 +43,12 @@
     const std::string secret;
 };
 
+enum class KeyType {
+    DE_SYS,
+    DE_USER,
+    CE_USER
+};
+
 extern const KeyAuthentication kEmptyAuthentication;
 
 // Checks if path "path" exists.
@@ -67,6 +77,9 @@
 bool destroyKey(const std::string& dir);
 
 bool runSecdiscardSingle(const std::string& file);
+
+bool generateWrappedKey(userid_t user_id, KeyType key_type, KeyBuffer* key);
+bool getEphemeralWrappedKey(km::KeyFormat format, KeyBuffer& kmKey, KeyBuffer* key);
 }  // namespace vold
 }  // namespace android
 
diff --git a/crypto/ext4crypt/KeyUtil.cpp b/crypto/ext4crypt/KeyUtil.cpp
index 946c6cf..3dc0500 100644
--- a/crypto/ext4crypt/KeyUtil.cpp
+++ b/crypto/ext4crypt/KeyUtil.cpp
@@ -27,6 +27,7 @@
 #include <keyutils.h>
 
 #include "KeyStorage4.h"
+#include "Ext4CryptPie.h"
 #include "Utils.h"
 
 #include <iostream>
@@ -35,6 +36,11 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#define MAX_USER_ID 0xFFFFFFFF
+
+using android::hardware::keymaster::V4_0::KeyFormat;
+using android::vold::KeyType;
+
 namespace android {
 namespace vold {
 
@@ -128,7 +134,14 @@
     ext4_encryption_key &ext4_key = *reinterpret_cast<ext4_encryption_key*>(ext4KeyBuffer.data());
 
     if (!fillKey(key, &ext4_key)) return false;
-    *raw_ref = generateKeyRef(ext4_key.raw, ext4_key.size);
+    if (is_wrapped_key_supported()) {
+        /* When wrapped key is supported, only the first 32 bytes are
+           the same per boot. The second 32 bytes can change as the ephemeral
+           key is different. */
+        *raw_ref = generateKeyRef(ext4_key.raw, (ext4_key.size)/2);
+    } else {
+        *raw_ref = generateKeyRef(ext4_key.raw, ext4_key.size);
+    }
     key_serial_t device_keyring;
     if (!e4cryptKeyring(&device_keyring)) return false;
     for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
@@ -171,7 +184,7 @@
 
 bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
                            const std::string& key_path, const std::string& tmp_path,
-                           std::string* key_ref) {
+                           std::string* key_ref, bool wrapped_key_supported) {
     KeyBuffer key;
     if (pathExists(key_path)) {
         LOG(DEBUG) << "Key exists, using: " << key_path << std::endl;
@@ -182,10 +195,23 @@
            return false;
         }
         LOG(INFO) << "Creating new key in " << key_path << std::endl;
-        if (!randomKey(&key)) return false;
+        if (wrapped_key_supported) {
+            if(!generateWrappedKey(MAX_USER_ID, KeyType::DE_SYS, &key)) return false;
+        } else {
+            if (!randomKey(&key)) return false;
+        }
         if (!storeKeyAtomically(key_path, tmp_path, key_authentication, key)) return false;
     }
 
+    if (wrapped_key_supported) {
+        KeyBuffer ephemeral_wrapped_key;
+        if (!getEphemeralWrappedKey(KeyFormat::RAW, key, &ephemeral_wrapped_key)) {
+            LOG(ERROR) << "Failed to export key in retrieveAndInstallKey";
+            return false;
+        }
+        key = std::move(ephemeral_wrapped_key);
+    }
+
     if (!installKey(key, key_ref)) {
         LOG(ERROR) << "Failed to install key in " << key_path << std::endl;
         return false;
diff --git a/crypto/ext4crypt/KeyUtil.h b/crypto/ext4crypt/KeyUtil.h
index d5ad69f..46a3124 100644
--- a/crypto/ext4crypt/KeyUtil.h
+++ b/crypto/ext4crypt/KeyUtil.h
@@ -19,6 +19,7 @@
 
 #include "KeyBuffer.h"
 #include "KeyStorage4.h"
+#include "Keymaster4.h"
 
 #include <string>
 #include <memory>
@@ -31,7 +32,7 @@
 bool evictKey(const std::string& raw_ref);
 bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
                            const std::string& key_path, const std::string& tmp_path,
-                           std::string* key_ref);
+                           std::string* key_ref, bool wrapped_key_supported);
 bool retrieveKey(bool create_if_absent, const std::string& key_path,
                  const std::string& tmp_path, KeyBuffer* key);
 
diff --git a/crypto/ext4crypt/Keymaster4.cpp b/crypto/ext4crypt/Keymaster4.cpp
index cebe1f1..e5c059a 100644
--- a/crypto/ext4crypt/Keymaster4.cpp
+++ b/crypto/ext4crypt/Keymaster4.cpp
@@ -142,6 +142,32 @@
     return true;
 }
 
+bool Keymaster::exportKey(km::KeyFormat format, KeyBuffer& kmKey, const std::string& clientId,
+                          const std::string& appData, std::string* key) {
+    auto kmKeyBlob = km::support::blob2hidlVec(std::string(kmKey.data(), kmKey.size()));
+    auto emptyAssign = NULL;
+    auto kmClientId = (clientId == "!") ? emptyAssign: km::support::blob2hidlVec(clientId);
+    auto kmAppData = (appData == "!") ? emptyAssign: km::support::blob2hidlVec(appData);
+    km::ErrorCode km_error;
+    auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& exportedKeyBlob) {
+        km_error = ret;
+        if (km_error != km::ErrorCode::OK) return;
+        if(key)
+            key->assign(reinterpret_cast<const char*>(&exportedKeyBlob[0]),
+                            exportedKeyBlob.size());
+    };
+    auto error = mDevice->exportKey(format, kmKeyBlob, kmClientId, kmAppData, hidlCb);
+    if (!error.isOk()) {
+        LOG(ERROR) << "export_key failed: " << error.description();
+        return false;
+    }
+    if (km_error != km::ErrorCode::OK) {
+        LOG(ERROR) << "export_key failed, code " << int32_t(km_error);
+        return false;
+    }
+    return true;
+}
+
 bool Keymaster::deleteKey(const std::string& key) {
     LOG(ERROR) << "not actually deleting key\n";
     return true;
diff --git a/crypto/ext4crypt/Keymaster4.h b/crypto/ext4crypt/Keymaster4.h
index 37bff4e..14c230b 100644
--- a/crypto/ext4crypt/Keymaster4.h
+++ b/crypto/ext4crypt/Keymaster4.h
@@ -102,6 +102,9 @@
     explicit operator bool() { return mDevice.get() != nullptr; }
     // Generate a key in the keymaster from the given params.
     bool generateKey(const km::AuthorizationSet& inParams, std::string* key);
+    // Export a key from keymaster.
+    bool exportKey(km::KeyFormat format, KeyBuffer& kmKey, const std::string& clientId,
+                   const std::string& appData, std::string* key);
     // If the keymaster supports it, permanently delete a key.
     bool deleteKey(const std::string& key);
     // Replace stored key blob in response to KM_ERROR_KEY_REQUIRES_UPGRADE.