OSDN Git Service

[automerger] Require quotes when searching for blkid keys. am: ee5c7318d7 am: 98bb129...
[android-x86/system-vold.git] / Ext4Crypt.cpp
index a37812b..1158475 100644 (file)
 
 #include "Ext4Crypt.h"
 
+#include "KeyStorage.h"
 #include "Utils.h"
 
+#include <algorithm>
 #include <iomanip>
 #include <map>
-#include <fstream>
-#include <string>
+#include <set>
 #include <sstream>
+#include <string>
 
-#include <errno.h>
 #include <dirent.h>
-#include <sys/mount.h>
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <errno.h>
 #include <fcntl.h>
-#include <cutils/properties.h>
+#include <limits.h>
 #include <openssl/sha.h>
+#include <selinux/android.h>
+#include <stdio.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 
 #include <private/android_filesystem_config.h>
 
-#include "unencrypted_properties.h"
-#include "key_control.h"
 #include "cryptfs.h"
-#include "ext4_crypt_init_extensions.h"
+#include "ext4_crypt.h"
+#include "key_control.h"
 
-#define LOG_TAG "Ext4Crypt"
+#define EMULATED_USES_SELINUX 0
+#define MANAGE_MISC_DIRS 0
 
 #include <cutils/fs.h>
-#include <cutils/log.h>
-#include <cutils/klog.h>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 
 using android::base::StringPrintf;
+using android::vold::kEmptyAuthentication;
 
-static bool e4crypt_is_native() {
-    char value[PROPERTY_VALUE_MAX];
-    property_get("ro.crypto.type", value, "none");
-    return !strcmp(value, "file");
-}
-
-static bool e4crypt_is_emulated() {
-    return property_get_bool("persist.sys.emulate_fbe", false);
-}
+// NOTE: keep in sync with StorageManager
+static constexpr int FLAG_STORAGE_DE = 1 << 0;
+static constexpr int FLAG_STORAGE_CE = 1 << 1;
 
 namespace {
-    // Key length in bits
-    const int key_length = 128;
-    static_assert(key_length % 8 == 0,
-                  "Key length must be multiple of 8 bits");
-
-    // How long do we store passwords for?
-    const int password_max_age_seconds = 60;
-
-    // How is device encrypted
-    struct keys {
-        std::string master_key;
-        std::string password;
-        time_t expiry_time;
-    };
-    std::map<std::string, keys> s_key_store;
-    // Maps the key paths of ephemeral keys to the keys
-    std::map<std::string, std::string> s_ephemeral_user_keys;
-
-    // ext4enc:TODO get these consts from somewhere good
-    const int SHA512_LENGTH = 64;
-    const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
-
-    // ext4enc:TODO Include structure from somewhere sensible
-    // MUST be in sync with ext4_crypto.c in kernel
-    const int EXT4_MAX_KEY_SIZE = 64;
-    const int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
-    struct ext4_encryption_key {
-        uint32_t mode;
-        char raw[EXT4_MAX_KEY_SIZE];
-        uint32_t size;
-    };
-
-    namespace tag {
-        const char* magic = "magic";
-        const char* major_version = "major_version";
-        const char* minor_version = "minor_version";
-        const char* flags = "flags";
-        const char* crypt_type = "crypt_type";
-        const char* failed_decrypt_count = "failed_decrypt_count";
-        const char* crypto_type_name = "crypto_type_name";
-        const char* master_key = "master_key";
-        const char* salt = "salt";
-        const char* kdf_type = "kdf_type";
-        const char* N_factor = "N_factor";
-        const char* r_factor = "r_factor";
-        const char* p_factor = "p_factor";
-        const char* keymaster_blob = "keymaster_blob";
-        const char* scrypted_intermediate_key = "scrypted_intermediate_key";
-    }
-}
-
-static std::string e4crypt_install_key(const std::string &key);
-
-static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
-                                 UnencryptedProperties& props)
-{
-    SLOGI("Putting crypt footer");
-
-    bool success = props.Set<int>(tag::magic, crypt_ftr.magic)
-      && props.Set<int>(tag::major_version, crypt_ftr.major_version)
-      && props.Set<int>(tag::minor_version, crypt_ftr.minor_version)
-      && props.Set<int>(tag::flags, crypt_ftr.flags)
-      && props.Set<int>(tag::crypt_type, crypt_ftr.crypt_type)
-      && props.Set<int>(tag::failed_decrypt_count,
-                        crypt_ftr.failed_decrypt_count)
-      && props.Set<std::string>(tag::crypto_type_name,
-                                std::string(reinterpret_cast<const char*>(crypt_ftr.crypto_type_name)))
-      && props.Set<std::string>(tag::master_key,
-                                std::string((const char*) crypt_ftr.master_key,
-                                            crypt_ftr.keysize))
-      && props.Set<std::string>(tag::salt,
-                                std::string((const char*) crypt_ftr.salt,
-                                            SALT_LEN))
-      && props.Set<int>(tag::kdf_type, crypt_ftr.kdf_type)
-      && props.Set<int>(tag::N_factor, crypt_ftr.N_factor)
-      && props.Set<int>(tag::r_factor, crypt_ftr.r_factor)
-      && props.Set<int>(tag::p_factor, crypt_ftr.p_factor)
-      && props.Set<std::string>(tag::keymaster_blob,
-                                std::string((const char*) crypt_ftr.keymaster_blob,
-                                            crypt_ftr.keymaster_blob_size))
-      && props.Set<std::string>(tag::scrypted_intermediate_key,
-                                std::string((const char*) crypt_ftr.scrypted_intermediate_key,
-                                            SCRYPT_LEN));
-    return success ? 0 : -1;
-}
-
-static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
-                                 const UnencryptedProperties& props)
-{
-    memset(&crypt_ftr, 0, sizeof(crypt_ftr));
-    crypt_ftr.magic = props.Get<int>(tag::magic);
-    crypt_ftr.major_version = props.Get<int>(tag::major_version);
-    crypt_ftr.minor_version = props.Get<int>(tag::minor_version);
-    crypt_ftr.ftr_size = sizeof(crypt_ftr);
-    crypt_ftr.flags = props.Get<int>(tag::flags);
-    crypt_ftr.crypt_type = props.Get<int>(tag::crypt_type);
-    crypt_ftr.failed_decrypt_count = props.Get<int>(tag::failed_decrypt_count);
-    std::string crypto_type_name = props.Get<std::string>(tag::crypto_type_name);
-    strlcpy(reinterpret_cast<char*>(crypt_ftr.crypto_type_name),
-            crypto_type_name.c_str(),
-            sizeof(crypt_ftr.crypto_type_name));
-    std::string master_key = props.Get<std::string>(tag::master_key);
-    crypt_ftr.keysize = master_key.size();
-    if (crypt_ftr.keysize > sizeof(crypt_ftr.master_key)) {
-        SLOGE("Master key size too long");
-        return -1;
-    }
-    memcpy(crypt_ftr.master_key, &master_key[0], crypt_ftr.keysize);
-    std::string salt = props.Get<std::string>(tag::salt);
-    if (salt.size() != SALT_LEN) {
-        SLOGE("Salt wrong length");
-        return -1;
-    }
-    memcpy(crypt_ftr.salt, &salt[0], SALT_LEN);
-    crypt_ftr.kdf_type = props.Get<int>(tag::kdf_type);
-    crypt_ftr.N_factor = props.Get<int>(tag::N_factor);
-    crypt_ftr.r_factor = props.Get<int>(tag::r_factor);
-    crypt_ftr.p_factor = props.Get<int>(tag::p_factor);
-    std::string keymaster_blob = props.Get<std::string>(tag::keymaster_blob);
-    crypt_ftr.keymaster_blob_size = keymaster_blob.size();
-    if (crypt_ftr.keymaster_blob_size > sizeof(crypt_ftr.keymaster_blob)) {
-        SLOGE("Keymaster blob too long");
-        return -1;
-    }
-    memcpy(crypt_ftr.keymaster_blob, &keymaster_blob[0],
-           crypt_ftr.keymaster_blob_size);
-    std::string scrypted_intermediate_key = props.Get<std::string>(tag::scrypted_intermediate_key);
-    if (scrypted_intermediate_key.size() != SCRYPT_LEN) {
-        SLOGE("scrypted intermediate key wrong length");
-        return -1;
-    }
-    memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
-           SCRYPT_LEN);
-
-    return 0;
-}
-
-static UnencryptedProperties GetProps(const char* path)
-{
-    return UnencryptedProperties(path);
-}
-
-static UnencryptedProperties GetAltProps(const char* path)
-{
-    return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
-}
-
-static UnencryptedProperties GetPropsOrAltProps(const char* path)
-{
-    UnencryptedProperties props = GetProps(path);
-    if (props.OK()) {
-        return props;
-    }
-    return GetAltProps(path);
-}
-
-int e4crypt_enable(const char* path)
-{
-    // Already enabled?
-    if (s_key_store.find(path) != s_key_store.end()) {
-        return 0;
-    }
-
-    // Not an encryptable device?
-    UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
-    if (!key_props.OK()) {
-        return 0;
-    }
-
-    if (key_props.Get<std::string>(tag::master_key).empty()) {
-        crypt_mnt_ftr ftr;
-        if (cryptfs_create_default_ftr(&ftr, key_length)) {
-            SLOGE("Failed to create crypto footer");
-            return -1;
-        }
+const std::string device_key_dir = std::string() + DATA_MNT_POINT + e4crypt_unencrypted_folder;
+const std::string device_key_path = device_key_dir + "/key";
+const std::string device_key_temp = device_key_dir + "/temp";
 
-        // Scrub fields not used by ext4enc
-        ftr.persist_data_offset[0] = 0;
-        ftr.persist_data_offset[1] = 0;
-        ftr.persist_data_size = 0;
+const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
+const std::string user_key_temp = user_key_dir + "/temp";
 
-        if (put_crypt_ftr_and_key(ftr, key_props)) {
-            SLOGE("Failed to write crypto footer");
-            return -1;
-        }
+bool s_global_de_initialized = false;
 
-        crypt_mnt_ftr ftr2;
-        if (get_crypt_ftr_and_key(ftr2, key_props)) {
-            SLOGE("Failed to read crypto footer back");
-            return -1;
-        }
+// Some users are ephemeral, don't try to wipe their keys from disk
+std::set<userid_t> s_ephemeral_users;
 
-        if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
-            SLOGE("Crypto footer not correctly written");
-            return -1;
-        }
-    }
+// Map user ids to key references
+std::map<userid_t, std::string> s_de_key_raw_refs;
+std::map<userid_t, std::string> s_ce_key_raw_refs;
+// TODO abolish this map. Keys should not be long-lived in user memory, only kernel memory.
+// See b/26948053
+std::map<userid_t, std::string> s_ce_keys;
 
-    if (!UnencryptedProperties(path).Remove(properties::ref)) {
-        SLOGE("Failed to remove key ref");
-        return -1;
-    }
+// ext4enc:TODO get this const from somewhere good
+const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
 
-    return e4crypt_check_passwd(path, "");
+// ext4enc:TODO Include structure from somewhere sensible
+// MUST be in sync with ext4_crypto.c in kernel
+constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
+constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
+constexpr int EXT4_MAX_KEY_SIZE = 64;
+struct ext4_encryption_key {
+    uint32_t mode;
+    char raw[EXT4_MAX_KEY_SIZE];
+    uint32_t size;
+};
 }
 
-int e4crypt_change_password(const char* path, int crypt_type,
-                            const char* password)
-{
-    SLOGI("e4crypt_change_password");
-    auto key_props = GetProps(path).GetChild(properties::key);
-
-    crypt_mnt_ftr ftr;
-    if (get_crypt_ftr_and_key(ftr, key_props)) {
-        SLOGE("Failed to read crypto footer back");
-        return -1;
-    }
-
-    auto mki = s_key_store.find(path);
-    if (mki == s_key_store.end()) {
-        SLOGE("No stored master key - can't change password");
-        return -1;
-    }
-
-    const unsigned char* master_key_bytes
-        = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
-
-    if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
-        SLOGE("Failed to set password");
-        return -1;
-    }
-
-    ftr.crypt_type = crypt_type;
-
-    if (put_crypt_ftr_and_key(ftr, key_props)) {
-        SLOGE("Failed to write crypto footer");
-        return -1;
-    }
-
-    if (!UnencryptedProperties(path).Set(properties::is_default,
-                            crypt_type == CRYPT_TYPE_DEFAULT)) {
-        SLOGE("Failed to update default flag");
-        return -1;
-    }
-
-    return 0;
+static bool e4crypt_is_emulated() {
+    return property_get_bool("persist.sys.emulate_fbe", false);
 }
 
-int e4crypt_crypto_complete(const char* path)
-{
-    SLOGI("ext4 crypto complete called on %s", path);
-    auto key_props = GetPropsOrAltProps(path).GetChild(properties::key);
-    if (key_props.Get<std::string>(tag::master_key).empty()) {
-        SLOGI("No master key, so not ext4enc");
-        return -1;
-    }
-
-    return 0;
+static const char* escape_null(const char* value) {
+    return (value == nullptr) ? "null" : value;
 }
 
 // Get raw keyref - used to make keyname and to pass to ioctl
-static std::string generate_key_ref(const char* key, int length)
-{
+static std::string generate_key_ref(const char* key, int length) {
     SHA512_CTX c;
 
     SHA512_Init(&c);
     SHA512_Update(&c, key, length);
-    unsigned char key_ref1[SHA512_LENGTH];
+    unsigned char key_ref1[SHA512_DIGEST_LENGTH];
     SHA512_Final(key_ref1, &c);
 
     SHA512_Init(&c);
-    SHA512_Update(&c, key_ref1, SHA512_LENGTH);
-    unsigned char key_ref2[SHA512_LENGTH];
+    SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
+    unsigned char key_ref2[SHA512_DIGEST_LENGTH];
     SHA512_Final(key_ref2, &c);
 
+    static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
+                  "Hash too short for descriptor");
     return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
 }
 
-int e4crypt_check_passwd(const char* path, const char* password)
-{
-    SLOGI("e4crypt_check_password");
-    auto props = GetPropsOrAltProps(path);
-    auto key_props = props.GetChild(properties::key);
-
-    crypt_mnt_ftr ftr;
-    if (get_crypt_ftr_and_key(ftr, key_props)) {
-        SLOGE("Failed to read crypto footer back");
-        return -1;
-    }
-
-    unsigned char master_key_bytes[key_length / 8];
-    if (cryptfs_get_master_key (&ftr, password, master_key_bytes)){
-        SLOGI("Incorrect password");
-        ftr.failed_decrypt_count++;
-        if (put_crypt_ftr_and_key(ftr, key_props)) {
-            SLOGW("Failed to update failed_decrypt_count");
-        }
-        return ftr.failed_decrypt_count;
+static bool fill_key(const std::string& key, ext4_encryption_key* ext4_key) {
+    if (key.size() != EXT4_AES_256_XTS_KEY_SIZE) {
+        LOG(ERROR) << "Wrong size key " << key.size();
+        return false;
     }
-
-    if (ftr.failed_decrypt_count) {
-        ftr.failed_decrypt_count = 0;
-        if (put_crypt_ftr_and_key(ftr, key_props)) {
-            SLOGW("Failed to reset failed_decrypt_count");
-        }
-    }
-    std::string master_key(reinterpret_cast<char*>(master_key_bytes),
-                           sizeof(master_key_bytes));
-
-    struct timespec now;
-    clock_gettime(CLOCK_BOOTTIME, &now);
-    s_key_store[path] = keys{master_key, password,
-                             now.tv_sec + password_max_age_seconds};
-    auto raw_ref = e4crypt_install_key(master_key);
-    if (raw_ref.empty()) {
-        return -1;
-    }
-
-    // Save reference to key so we can set policy later
-    if (!props.Set(properties::ref, raw_ref)) {
-        SLOGE("Cannot save key reference");
-        return -1;
-    }
-
-    return 0;
-}
-
-static ext4_encryption_key fill_key(const std::string &key)
-{
-    // ext4enc:TODO Currently raw key is required to be of length
-    // sizeof(ext4_key.raw) == EXT4_MAX_KEY_SIZE, so zero pad to
-    // this length. Change when kernel bug is fixed.
-    ext4_encryption_key ext4_key = {EXT4_ENCRYPTION_MODE_AES_256_XTS,
-                                    {0},
-                                    sizeof(ext4_key.raw)};
-    memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
-    static_assert(key_length / 8 <= sizeof(ext4_key.raw),
-                  "Key too long!");
-    memcpy(ext4_key.raw, &key[0], key.size());
-    return ext4_key;
+    static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key->raw), "Key too long!");
+    ext4_key->mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
+    ext4_key->size = key.size();
+    memset(ext4_key->raw, 0, sizeof(ext4_key->raw));
+    memcpy(ext4_key->raw, key.data(), key.size());
+    return true;
 }
 
-static std::string keyname(const std::string &raw_ref)
-{
+static std::string keyname(const std::string& raw_ref) {
     std::ostringstream o;
     o << "ext4:";
-    for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
-        o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
+    for (auto i : raw_ref) {
+        o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
     }
     return o.str();
 }
 
 // Get the keyring we store all keys in
-static key_serial_t e4crypt_keyring()
-{
-    return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
-}
-
-static int e4crypt_install_key(const ext4_encryption_key &ext4_key, const std::string &ref)
-{
-    key_serial_t device_keyring = e4crypt_keyring();
-    SLOGI("Found device_keyring - id is %d", device_keyring);
-    key_serial_t key_id = add_key("logon", ref.c_str(),
-                                  (void*)&ext4_key, sizeof(ext4_key),
-                                  device_keyring);
-    if (key_id == -1) {
-        SLOGE("Failed to insert key into keyring with error %s",
-              strerror(errno));
-        return -1;
+static bool e4crypt_keyring(key_serial_t* device_keyring) {
+    *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
+    if (*device_keyring == -1) {
+        PLOG(ERROR) << "Unable to find device keyring";
+        return false;
     }
-    SLOGI("Added key %d (%s) to keyring %d in process %d",
-          key_id, ref.c_str(), device_keyring, getpid());
-    return 0;
+    return true;
 }
 
 // Install password into global keyring
 // Return raw key reference for use in policy
-static std::string e4crypt_install_key(const std::string &key)
-{
-    auto ext4_key = fill_key(key);
-    auto raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
-    auto ref = keyname(raw_ref);
-    if (e4crypt_install_key(ext4_key, ref) == -1) {
-        return "";
+static bool install_key(const std::string& key, std::string* raw_ref) {
+    ext4_encryption_key ext4_key;
+    if (!fill_key(key, &ext4_key)) return false;
+    *raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
+    auto ref = keyname(*raw_ref);
+    key_serial_t device_keyring;
+    if (!e4crypt_keyring(&device_keyring)) return false;
+    key_serial_t key_id =
+        add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
+    if (key_id == -1) {
+        PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
+        return false;
     }
-    return raw_ref;
+    LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
+               << " in process " << getpid();
+    return true;
 }
 
-int e4crypt_restart(const char* path)
-{
-    SLOGI("e4crypt_restart");
+static std::string get_de_key_path(userid_t user_id) {
+    return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
+}
 
-    int rc = 0;
+static std::string get_ce_key_directory_path(userid_t user_id) {
+    return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
+}
 
-    SLOGI("ext4 restart called on %s", path);
-    property_set("vold.decrypt", "trigger_reset_main");
-    SLOGI("Just asked init to shut down class main");
-    sleep(2);
+// Returns the keys newest first
+static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
+    auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
+    if (!dirp) {
+        PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
+        return std::vector<std::string>();
+    }
+    std::vector<std::string> result;
+    for (;;) {
+        errno = 0;
+        auto const entry = readdir(dirp.get());
+        if (!entry) {
+            if (errno) {
+                PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
+                return std::vector<std::string>();
+            }
+            break;
+        }
+        if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
+            LOG(DEBUG) << "Skipping non-key " << entry->d_name;
+            continue;
+        }
+        result.emplace_back(directory_path + "/" + entry->d_name);
+    }
+    std::sort(result.begin(), result.end());
+    std::reverse(result.begin(), result.end());
+    return result;
+}
 
-    std::string tmp_path = std::string() + path + "/tmp_mnt";
+static std::string get_ce_key_current_path(const std::string& directory_path) {
+    return directory_path + "/current";
+}
 
-    rc = wait_and_unmount(tmp_path.c_str(), true);
-    if (rc) {
-        SLOGE("umount %s failed with rc %d, msg %s",
-              tmp_path.c_str(), rc, strerror(errno));
-        return rc;
+static bool get_ce_key_new_path(const std::string& directory_path,
+                                const std::vector<std::string>& paths,
+                                std::string *ce_key_path) {
+    if (paths.empty()) {
+        *ce_key_path = get_ce_key_current_path(directory_path);
+        return true;
     }
-
-    rc = wait_and_unmount(path, true);
-    if (rc) {
-        SLOGE("umount %s failed with rc %d, msg %s",
-              path, rc, strerror(errno));
-        return rc;
+    for (unsigned int i = 0; i < UINT_MAX; i++) {
+        auto const candidate = StringPrintf("%s/cx%010u", directory_path.c_str(), i);
+        if (paths[0] < candidate) {
+            *ce_key_path = candidate;
+            return true;
+        }
     }
+    return false;
+}
 
-    return 0;
+// Discard all keys but the named one; rename it to canonical name.
+// No point in acting on errors in this; ignore them.
+static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix,
+                               const std::vector<std::string>& paths) {
+    for (auto const other_path: paths) {
+        if (other_path != to_fix) {
+            android::vold::destroyKey(other_path);
+        }
+    }
+    auto const current_path = get_ce_key_current_path(directory_path);
+    if (to_fix != current_path) {
+        LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
+        if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
+            PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
+        }
+    }
 }
 
-int e4crypt_get_password_type(const char* path)
-{
-    SLOGI("e4crypt_get_password_type");
-    return GetPropsOrAltProps(path).GetChild(properties::key)
-      .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
+static bool read_and_fixate_user_ce_key(userid_t user_id,
+                                        const android::vold::KeyAuthentication& auth,
+                                        std::string *ce_key) {
+    auto const directory_path = get_ce_key_directory_path(user_id);
+    auto const paths = get_ce_key_paths(directory_path);
+    for (auto const ce_key_path: paths) {
+        LOG(DEBUG) << "Trying user CE key " << ce_key_path;
+        if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
+            LOG(DEBUG) << "Successfully retrieved key";
+            fixate_user_ce_key(directory_path, ce_key_path, paths);
+            return true;
+        }
+    }
+    LOG(ERROR) << "Failed to find working ce key for user " << user_id;
+    return false;
 }
 
-const char* e4crypt_get_password(const char* path)
-{
-    SLOGI("e4crypt_get_password");
+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;
+    std::string ce_key;
+    if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
+    std::string ce_raw_ref;
+    if (!install_key(ce_key, &ce_raw_ref)) return false;
+    s_ce_keys[user_id] = ce_key;
+    s_ce_key_raw_refs[user_id] = ce_raw_ref;
+    LOG(DEBUG) << "Installed ce key for user " << user_id;
+    return true;
+}
 
-    auto i = s_key_store.find(path);
-    if (i == s_key_store.end()) {
-        return 0;
+static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
+    LOG(DEBUG) << "Preparing: " << dir;
+    if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
+        PLOG(ERROR) << "Failed to prepare " << dir;
+        return false;
     }
+    return true;
+}
 
-    struct timespec now;
-    clock_gettime(CLOCK_BOOTTIME, &now);
-    if (i->second.expiry_time < now.tv_sec) {
-        e4crypt_clear_password(path);
-        return 0;
+static bool destroy_dir(const std::string& dir) {
+    LOG(DEBUG) << "Destroying: " << dir;
+    if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
+        PLOG(ERROR) << "Failed to destroy " << dir;
+        return false;
     }
+    return true;
+}
 
-    return i->second.password.c_str();
+static bool random_key(std::string* key) {
+    if (android::vold::ReadRandomBytes(EXT4_AES_256_XTS_KEY_SIZE, *key) != 0) {
+        // TODO status_t plays badly with PLOG, fix it.
+        LOG(ERROR) << "Random read failed";
+        return false;
+    }
+    return true;
 }
 
-void e4crypt_clear_password(const char* path)
-{
-    SLOGI("e4crypt_clear_password");
+static bool path_exists(const std::string& path) {
+    return access(path.c_str(), F_OK) == 0;
+}
 
-    auto i = s_key_store.find(path);
-    if (i == s_key_store.end()) {
-        return;
+// NB this assumes that there is only one thread listening for crypt commands, because
+// it creates keys in a fixed location.
+static bool store_key(const std::string& key_path, const std::string& tmp_path,
+                      const android::vold::KeyAuthentication& auth, const std::string& key) {
+    if (path_exists(key_path)) {
+        LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
+        return false;
     }
-
-    memset(&i->second.password[0], 0, i->second.password.size());
-    i->second.password = std::string();
+    if (path_exists(tmp_path)) {
+        android::vold::destroyKey(tmp_path);  // May be partially created so ignore errors
+    }
+    if (!android::vold::storeKey(tmp_path, auth, key)) return false;
+    if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
+        PLOG(ERROR) << "Unable to move new key to location: " << key_path;
+        return false;
+    }
+    LOG(DEBUG) << "Created key " << key_path;
+    return true;
 }
 
-int e4crypt_get_field(const char* path, const char* fieldname,
-                      char* value, size_t len)
-{
-    auto v = GetPropsOrAltProps(path).GetChild(properties::props)
-      .Get<std::string>(fieldname);
+static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
+    std::string de_key, ce_key;
+    if (!random_key(&de_key)) return false;
+    if (!random_key(&ce_key)) return false;
+    if (create_ephemeral) {
+        // If the key should be created as ephemeral, don't store it.
+        s_ephemeral_users.insert(user_id);
+    } else {
+        auto const directory_path = get_ce_key_directory_path(user_id);
+        if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
+        auto const paths = get_ce_key_paths(directory_path);
+        std::string ce_key_path;
+        if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
+        if (!store_key(ce_key_path, user_key_temp,
+                kEmptyAuthentication, ce_key)) return false;
+        fixate_user_ce_key(directory_path, ce_key_path, paths);
+        // Write DE key second; once this is written, all is good.
+        if (!store_key(get_de_key_path(user_id), user_key_temp,
+                kEmptyAuthentication, de_key)) return false;
+    }
+    std::string de_raw_ref;
+    if (!install_key(de_key, &de_raw_ref)) return false;
+    s_de_key_raw_refs[user_id] = de_raw_ref;
+    std::string ce_raw_ref;
+    if (!install_key(ce_key, &ce_raw_ref)) return false;
+    s_ce_keys[user_id] = ce_key;
+    s_ce_key_raw_refs[user_id] = ce_raw_ref;
+    LOG(DEBUG) << "Created keys for user " << user_id;
+    return true;
+}
 
-    if (v == "") {
-        return CRYPTO_GETFIELD_ERROR_NO_FIELD;
+static bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
+                           std::string* raw_ref) {
+    auto refi = key_map.find(user_id);
+    if (refi == key_map.end()) {
+        LOG(ERROR) << "Cannot find key for " << user_id;
+        return false;
     }
+    *raw_ref = refi->second;
+    return true;
+}
 
-    if (v.length() >= len) {
-        return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
+static bool ensure_policy(const std::string& raw_ref, const std::string& path) {
+    if (e4crypt_policy_ensure(path.c_str(), raw_ref.data(), raw_ref.size()) != 0) {
+        LOG(ERROR) << "Failed to set policy on: " << path;
+        return false;
     }
-
-    strlcpy(value, v.c_str(), len);
-    return 0;
+    return true;
 }
 
-int e4crypt_set_field(const char* path, const char* fieldname,
-                      const char* value)
-{
-    return GetPropsOrAltProps(path).GetChild(properties::props)
-        .Set(fieldname, std::string(value)) ? 0 : -1;
+static bool is_numeric(const char* name) {
+    for (const char* p = name; *p != '\0'; p++) {
+        if (!isdigit(*p)) return false;
+    }
+    return true;
 }
 
-static std::string get_key_path(const char *mount_path, userid_t user_id) {
-    // ext4enc:TODO get the path properly
-    auto key_dir = StringPrintf("%s/misc/vold/user_keys", mount_path);
-    if (fs_prepare_dir(key_dir.c_str(), 0700, AID_ROOT, AID_ROOT)) {
-        PLOG(ERROR) << "Failed to prepare " << key_dir;
-        return "";
+static bool load_all_de_keys() {
+    auto de_dir = user_key_dir + "/de";
+    auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
+    if (!dirp) {
+        PLOG(ERROR) << "Unable to read de key directory";
+        return false;
+    }
+    for (;;) {
+        errno = 0;
+        auto entry = readdir(dirp.get());
+        if (!entry) {
+            if (errno) {
+                PLOG(ERROR) << "Unable to read de key directory";
+                return false;
+            }
+            break;
+        }
+        if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
+            LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
+            continue;
+        }
+        userid_t user_id = atoi(entry->d_name);
+        if (s_de_key_raw_refs.count(user_id) == 0) {
+            auto key_path = de_dir + "/" + entry->d_name;
+            std::string key;
+            if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
+            std::string raw_ref;
+            if (!install_key(key, &raw_ref)) return false;
+            s_de_key_raw_refs[user_id] = raw_ref;
+            LOG(DEBUG) << "Installed de key for user " << user_id;
+        }
     }
-    return StringPrintf("%s/%d", key_dir.c_str(), user_id);
+    // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
+    // correct policy set on them, and that no rogue ones exist.
+    return true;
 }
 
-static bool e4crypt_is_key_ephemeral(const std::string &key_path) {
-    return s_ephemeral_user_keys.find(key_path) != s_ephemeral_user_keys.end();
-}
+bool e4crypt_initialize_global_de() {
+    LOG(INFO) << "e4crypt_initialize_global_de";
 
-// ext4enc:TODO this can't be the only place keys are read from /dev/urandom
-// we should unite those places.
-static std::string e4crypt_get_key(
-    const std::string &key_path,
-    bool create_if_absent,
-    bool create_ephemeral)
-{
-    const auto ephemeral_key_it = s_ephemeral_user_keys.find(key_path);
-    if (ephemeral_key_it != s_ephemeral_user_keys.end()) {
-        return ephemeral_key_it->second;
+    if (s_global_de_initialized) {
+        LOG(INFO) << "Already initialized";
+        return true;
     }
 
-    std::string content;
-    if (android::base::ReadFileToString(key_path, &content)) {
-        if (content.size() != key_length/8) {
-            SLOGE("Wrong size key %zu in  %s", content.size(), key_path.c_str());
-            return "";
-        }
-        return content;
+    std::string device_key;
+    if (path_exists(device_key_path)) {
+        if (!android::vold::retrieveKey(device_key_path,
+                kEmptyAuthentication, &device_key)) return false;
+    } else {
+        LOG(INFO) << "Creating new key";
+        if (!random_key(&device_key)) return false;
+        if (!store_key(device_key_path, device_key_temp,
+                kEmptyAuthentication, device_key)) return false;
     }
-    if (!create_if_absent) {
-        SLOGE("No key found in %s", key_path.c_str());
-        return "";
+
+    std::string device_key_ref;
+    if (!install_key(device_key, &device_key_ref)) {
+        LOG(ERROR) << "Failed to install device key";
+        return false;
     }
-    std::ifstream urandom("/dev/urandom");
-    if (!urandom) {
-        SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
-        return "";
+
+    std::string ref_filename = std::string("/data") + e4crypt_key_ref;
+    if (!android::base::WriteStringToFile(device_key_ref, ref_filename)) {
+        PLOG(ERROR) << "Cannot save key reference";
+        return false;
+    }
+
+    s_global_de_initialized = true;
+    return true;
+}
+
+bool e4crypt_init_user0() {
+    LOG(DEBUG) << "e4crypt_init_user0";
+    if (e4crypt_is_native()) {
+        if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
+        if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
+        if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
+        if (!path_exists(get_de_key_path(0))) {
+            if (!create_and_install_user_keys(0, false)) return false;
+        }
+        // TODO: switch to loading only DE_0 here once framework makes
+        // explicit calls to install DE keys for secondary users
+        if (!load_all_de_keys()) return false;
     }
-    char key_bytes[key_length / 8];
-    errno = 0;
-    urandom.read(key_bytes, sizeof(key_bytes));
-    if (!urandom) {
-        SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
-        return "";
+    // We can only safely prepare DE storage here, since CE keys are probably
+    // entangled with user credentials.  The framework will always prepare CE
+    // storage once CE keys are installed.
+    if (!e4crypt_prepare_user_storage(nullptr, 0, 0, FLAG_STORAGE_DE)) {
+        LOG(ERROR) << "Failed to prepare user 0 storage";
+        return false;
     }
-    std::string key(key_bytes, sizeof(key_bytes));
-    if (create_ephemeral) {
-        // If the key should be created as ephemeral, store it in memory only.
-        s_ephemeral_user_keys[key_path] = key;
-    } else if (!android::base::WriteStringToFile(key, key_path)) {
-        SLOGE("Unable to write key to %s (%s)",
-                key_path.c_str(), strerror(errno));
-        return "";
+
+    // If this is a non-FBE device that recently left an emulated mode,
+    // restore user data directories to known-good state.
+    if (!e4crypt_is_native() && !e4crypt_is_emulated()) {
+        e4crypt_unlock_user_key(0, 0, "!", "!");
     }
-    return key;
+
+    return true;
 }
 
-static int e4crypt_set_user_policy(const char *mount_path, userid_t user_id,
-        std::string& path, bool create_if_absent, bool create_ephemeral) {
-    SLOGD("e4crypt_set_user_policy for %d", user_id);
-    auto user_key = e4crypt_get_key(get_key_path(mount_path, user_id),
-            create_if_absent, create_ephemeral);
-    if (user_key.empty()) {
-        return -1;
+bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
+    LOG(DEBUG) << "e4crypt_vold_create_user_key for " << user_id << " serial " << serial;
+    if (!e4crypt_is_native()) {
+        return true;
+    }
+    // FIXME test for existence of key that is not loaded yet
+    if (s_ce_key_raw_refs.count(user_id) != 0) {
+        LOG(ERROR) << "Already exists, can't e4crypt_vold_create_user_key for " << user_id
+                   << " serial " << serial;
+        // FIXME should we fail the command?
+        return true;
     }
-    auto raw_ref = e4crypt_install_key(user_key);
-    if (raw_ref.empty()) {
-        return -1;
+    if (!create_and_install_user_keys(user_id, ephemeral)) {
+        return false;
     }
-    return do_policy_set(path.c_str(), raw_ref.c_str(), raw_ref.size());
+    return true;
 }
 
-static bool is_numeric(const char *name) {
-    for (const char *p = name; *p != '\0'; p++) {
-        if (!isdigit(*p))
-            return false;
+static bool evict_key(const std::string& raw_ref) {
+    auto ref = keyname(raw_ref);
+    key_serial_t device_keyring;
+    if (!e4crypt_keyring(&device_keyring)) return false;
+    auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
+    if (keyctl_revoke(key_serial) != 0) {
+        PLOG(ERROR) << "Failed to revoke key with serial " << key_serial << " ref " << ref;
+        return false;
+    }
+    LOG(DEBUG) << "Revoked key with serial " << key_serial << " ref " << ref;
+    return true;
+}
+
+bool e4crypt_destroy_user_key(userid_t user_id) {
+    LOG(DEBUG) << "e4crypt_destroy_user_key(" << user_id << ")";
+    if (!e4crypt_is_native()) {
+        return true;
+    }
+    bool success = true;
+    s_ce_keys.erase(user_id);
+    std::string raw_ref;
+    // If we haven't loaded the CE key, no need to evict it.
+    if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
+        success &= evict_key(raw_ref);
+    }
+    s_ce_key_raw_refs.erase(user_id);
+    success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && evict_key(raw_ref);
+    s_de_key_raw_refs.erase(user_id);
+    auto it = s_ephemeral_users.find(user_id);
+    if (it != s_ephemeral_users.end()) {
+        s_ephemeral_users.erase(it);
+    } else {
+        for (auto const path: get_ce_key_paths(get_ce_key_directory_path(user_id))) {
+            success &= android::vold::destroyKey(path);
+        }
+        success &= android::vold::destroyKey(get_de_key_path(user_id));
     }
+    return success;
+}
+
+static bool emulated_lock(const std::string& path) {
+    if (chmod(path.c_str(), 0000) != 0) {
+        PLOG(ERROR) << "Failed to chmod " << path;
+        return false;
+    }
+#if EMULATED_USES_SELINUX
+    if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
+        PLOG(WARNING) << "Failed to setfilecon " << path;
+        return false;
+    }
+#endif
     return true;
 }
 
-int e4crypt_vold_set_user_crypto_policies(const char *dir)
-{
-    if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
-        return 0;
+static bool emulated_unlock(const std::string& path, mode_t mode) {
+    if (chmod(path.c_str(), mode) != 0) {
+        PLOG(ERROR) << "Failed to chmod " << path;
+        // FIXME temporary workaround for b/26713622
+        if (e4crypt_is_emulated()) return false;
     }
-    SLOGD("e4crypt_vold_set_user_crypto_policies");
-    std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
-    if (!dirp) {
-        SLOGE("Unable to read directory %s, error %s\n",
-            dir, strerror(errno));
-        return -1;
+#if EMULATED_USES_SELINUX
+    if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
+        PLOG(WARNING) << "Failed to restorecon " << path;
+        // FIXME temporary workaround for b/26713622
+        if (e4crypt_is_emulated()) return false;
     }
-    for (;;) {
-        struct dirent *result = readdir(dirp.get());
-        if (!result) {
-            // ext4enc:TODO check errno
-            break;
-        }
-        if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
-            continue; // skips user 0, which is a symlink
-        }
-        auto user_id = atoi(result->d_name);
-        auto user_dir = std::string() + dir + "/" + result->d_name;
-        // ext4enc:TODO don't hardcode /data
-        if (e4crypt_set_user_policy("/data", user_id, user_dir, false, false)) {
-            // ext4enc:TODO If this function fails, stop the boot: we must
-            // deliver on promised encryption.
-            SLOGE("Unable to set policy on %s\n", user_dir.c_str());
-        }
+#endif
+    return true;
+}
+
+static bool parse_hex(const char* hex, std::string* result) {
+    if (strcmp("!", hex) == 0) {
+        *result = "";
+        return true;
+    }
+    if (android::vold::HexToStr(hex, *result) != 0) {
+        LOG(ERROR) << "Invalid FBE hex string";  // Don't log the string for security reasons
+        return false;
     }
-    return 0;
+    return true;
 }
 
-int e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
-    SLOGD("e4crypt_vold_create_user_key(%d)", user_id);
-    // TODO: create second key for user_de data
-    if (e4crypt_get_key(
-            get_key_path(DATA_MNT_POINT, user_id), true, ephemeral).empty()) {
-        return -1;
-    } else {
-        return 0;
+bool e4crypt_add_user_key_auth(userid_t user_id, int serial, const char* token_hex,
+                          const char* secret_hex) {
+    LOG(DEBUG) << "e4crypt_add_user_key_auth " << user_id << " serial=" << serial
+               << " token_present=" << (strcmp(token_hex, "!") != 0);
+    if (!e4crypt_is_native()) return true;
+    if (s_ephemeral_users.count(user_id) != 0) return true;
+    std::string token, secret;
+    if (!parse_hex(token_hex, &token)) return false;
+    if (!parse_hex(secret_hex, &secret)) return false;
+    auto auth = secret.empty() ? kEmptyAuthentication
+                                   : android::vold::KeyAuthentication(token, secret);
+    auto it = s_ce_keys.find(user_id);
+    if (it == s_ce_keys.end()) {
+        LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
+        return false;
+    }
+    auto ce_key = it->second;
+    auto const directory_path = get_ce_key_directory_path(user_id);
+    auto const paths = get_ce_key_paths(directory_path);
+    std::string ce_key_path;
+    if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
+    if (!store_key(ce_key_path, user_key_temp, auth, ce_key)) return false;
+    return true;
+}
+
+bool e4crypt_fixate_newest_user_key_auth(userid_t user_id) {
+    LOG(DEBUG) << "e4crypt_fixate_newest_user_key_auth " << user_id;
+    if (!e4crypt_is_native()) return true;
+    auto const directory_path = get_ce_key_directory_path(user_id);
+    auto const paths = get_ce_key_paths(directory_path);
+    if (paths.empty()) {
+        LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
+        return false;
     }
+    fixate_user_ce_key(directory_path, paths[0], paths);
+    return true;
 }
 
-int e4crypt_destroy_user_key(userid_t user_id) {
-    SLOGD("e4crypt_destroy_user_key(%d)", user_id);
-    // TODO: destroy second key for user_de data
-    auto key_path = get_key_path(DATA_MNT_POINT, user_id);
-    auto key = e4crypt_get_key(key_path, false, false);
-    auto ext4_key = fill_key(key);
-    auto ref = keyname(generate_key_ref(ext4_key.raw, ext4_key.size));
-    auto key_serial = keyctl_search(e4crypt_keyring(), "logon", ref.c_str(), 0);
-    if (keyctl_revoke(key_serial) == 0) {
-        SLOGD("Revoked key with serial %ld ref %s\n", key_serial, ref.c_str());
-    } else {
-        SLOGE("Failed to revoke key with serial %ld ref %s: %s\n",
-            key_serial, ref.c_str(), strerror(errno));
-    }
-    if (e4crypt_is_key_ephemeral(key_path)) {
-        s_ephemeral_user_keys.erase(key_path);
-        return 0;
-    }
-    int pid = fork();
-    if (pid < 0) {
-        SLOGE("Unable to fork: %s", strerror(errno));
-        return -1;
-    }
-    if (pid == 0) {
-        SLOGD("Forked for secdiscard");
-        execl("/system/bin/secdiscard",
-            "/system/bin/secdiscard",
-            "--",
-            key_path.c_str(),
-            NULL);
-        SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
-            strerror(errno));
-        exit(-1);
-    }
-    // ext4enc:TODO reap the zombie
-    return 0;
-}
-
-int e4crypt_unlock_user_key(userid_t user_id, const char* token) {
+// TODO: rename to 'install' for consistency, and take flags to know which keys to install
+bool e4crypt_unlock_user_key(userid_t user_id, int serial, const char* token_hex,
+                             const char* secret_hex) {
+    LOG(DEBUG) << "e4crypt_unlock_user_key " << user_id << " serial=" << serial
+               << " token_present=" << (strcmp(token_hex, "!") != 0);
     if (e4crypt_is_native()) {
-        auto user_key = e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), false, false);
-        if (user_key.empty()) {
-            return -1;
+        if (s_ce_key_raw_refs.count(user_id) != 0) {
+            LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
+            return true;
         }
-        auto raw_ref = e4crypt_install_key(user_key);
-        if (raw_ref.empty()) {
-            return -1;
+        std::string token, secret;
+        if (!parse_hex(token_hex, &token)) return false;
+        if (!parse_hex(secret_hex, &secret)) return false;
+        android::vold::KeyAuthentication auth(token, secret);
+        if (!read_and_install_user_ce_key(user_id, auth)) {
+            LOG(ERROR) << "Couldn't read key for " << user_id;
+            return false;
         }
     } else {
         // When in emulation mode, we just use chmod. However, we also
         // unlock directories when not in emulation mode, to bring devices
         // back into a known-good state.
-        if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0771) ||
-                chmod(android::vold::BuildDataMediaPath(nullptr, user_id).c_str(), 0770) ||
-                chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0771)) {
-            PLOG(ERROR) << "Failed to unlock user " << user_id;
-            return -1;
+        if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
+            !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
+            !emulated_unlock(android::vold::BuildDataMediaCePath(nullptr, user_id), 0770) ||
+            !emulated_unlock(android::vold::BuildDataUserCePath(nullptr, user_id), 0771)) {
+            LOG(ERROR) << "Failed to unlock user " << user_id;
+            return false;
         }
     }
-
-    return 0;
+    return true;
 }
 
-int e4crypt_lock_user_key(userid_t user_id) {
+// TODO: rename to 'evict' for consistency
+bool e4crypt_lock_user_key(userid_t user_id) {
     if (e4crypt_is_native()) {
         // TODO: remove from kernel keyring
     } else if (e4crypt_is_emulated()) {
         // When in emulation mode, we just use chmod
-        if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0000) ||
-                chmod(android::vold::BuildDataMediaPath(nullptr, user_id).c_str(), 0000) ||
-                chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0000)) {
-            PLOG(ERROR) << "Failed to lock user " << user_id;
-            return -1;
+        if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
+            !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
+            !emulated_lock(android::vold::BuildDataMediaCePath(nullptr, user_id)) ||
+            !emulated_lock(android::vold::BuildDataUserCePath(nullptr, user_id))) {
+            LOG(ERROR) << "Failed to lock user " << user_id;
+            return false;
         }
     }
 
-    return 0;
+    return true;
 }
 
-int e4crypt_prepare_user_storage(const char* volume_uuid,
-                                 userid_t user_id,
-                                 int serial,
-                                 bool ephemeral) {
-    std::string system_ce_path(android::vold::BuildDataSystemCePath(user_id));
-    std::string media_ce_path(android::vold::BuildDataMediaPath(volume_uuid, user_id));
-    std::string user_ce_path(android::vold::BuildDataUserPath(volume_uuid, user_id));
-    std::string user_de_path(android::vold::BuildDataUserDePath(volume_uuid, user_id));
-
-    if (fs_prepare_dir(system_ce_path.c_str(), 0700, AID_SYSTEM, AID_SYSTEM)) {
-        PLOG(ERROR) << "Failed to prepare " << system_ce_path;
-        return -1;
-    }
-    if (fs_prepare_dir(media_ce_path.c_str(), 0770, AID_MEDIA_RW, AID_MEDIA_RW)) {
-        PLOG(ERROR) << "Failed to prepare " << media_ce_path;
-        return -1;
+bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial,
+        int flags) {
+    LOG(DEBUG) << "e4crypt_prepare_user_storage for volume " << escape_null(volume_uuid)
+               << ", user " << user_id << ", serial " << serial << ", flags " << flags;
+
+    if (flags & FLAG_STORAGE_DE) {
+        // DE_sys key
+        auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
+        auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
+        auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
+        auto foreign_de_path = android::vold::BuildDataProfilesForeignDexDePath(user_id);
+
+        // DE_n key
+        auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
+        auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
+        auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
+
+        if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
+#if MANAGE_MISC_DIRS
+        if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
+                multiuser_get_uid(user_id, AID_EVERYBODY))) return false;
+#endif
+        if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
+        if (!prepare_dir(foreign_de_path, 0773, AID_SYSTEM, AID_SYSTEM)) return false;
+
+        if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
+        if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
+        if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
+
+        // For now, FBE is only supported on internal storage
+        if (e4crypt_is_native() && volume_uuid == nullptr) {
+            std::string de_raw_ref;
+            if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_raw_ref)) return false;
+            if (!ensure_policy(de_raw_ref, system_de_path)) return false;
+            if (!ensure_policy(de_raw_ref, misc_de_path)) return false;
+            if (!ensure_policy(de_raw_ref, user_de_path)) return false;
+        }
     }
-    if (fs_prepare_dir(user_ce_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
-        PLOG(ERROR) << "Failed to prepare " << user_ce_path;
-        return -1;
+
+    if (flags & FLAG_STORAGE_CE) {
+        // CE_n key
+        auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
+        auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
+        auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
+        auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
+
+        if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
+        if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
+        if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
+        if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
+
+        // For now, FBE is only supported on internal storage
+        if (e4crypt_is_native() && volume_uuid == nullptr) {
+            std::string ce_raw_ref;
+            if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_raw_ref)) return false;
+            if (!ensure_policy(ce_raw_ref, system_ce_path)) return false;
+            if (!ensure_policy(ce_raw_ref, misc_ce_path)) return false;
+            if (!ensure_policy(ce_raw_ref, media_ce_path)) return false;
+            if (!ensure_policy(ce_raw_ref, user_ce_path)) return false;
+        }
     }
-    if (fs_prepare_dir(user_de_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
-        PLOG(ERROR) << "Failed to prepare " << user_de_path;
-        return -1;
+
+    return true;
+}
+
+bool e4crypt_destroy_user_storage(const char* volume_uuid, userid_t user_id, int flags) {
+    LOG(DEBUG) << "e4crypt_destroy_user_storage for volume " << escape_null(volume_uuid)
+               << ", user " << user_id << ", flags " << flags;
+    bool res = true;
+
+    if (flags & FLAG_STORAGE_DE) {
+        // DE_sys key
+        auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
+        auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
+        auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
+        auto foreign_de_path = android::vold::BuildDataProfilesForeignDexDePath(user_id);
+
+        // DE_n key
+        auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
+        auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
+        auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
+
+        if (volume_uuid == nullptr) {
+            res &= destroy_dir(system_legacy_path);
+#if MANAGE_MISC_DIRS
+            res &= destroy_dir(misc_legacy_path);
+#endif
+            res &= destroy_dir(profiles_de_path);
+            res &= destroy_dir(foreign_de_path);
+            res &= destroy_dir(system_de_path);
+            res &= destroy_dir(misc_de_path);
+        }
+        res &= destroy_dir(user_de_path);
     }
 
-    if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
-        if (e4crypt_set_user_policy(DATA_MNT_POINT, user_id, system_ce_path, true, ephemeral)
-                || e4crypt_set_user_policy(DATA_MNT_POINT, user_id, media_ce_path, true, ephemeral)
-                || e4crypt_set_user_policy(DATA_MNT_POINT, user_id, user_ce_path, true,
-                        ephemeral)) {
-            return -1;
+    if (flags & FLAG_STORAGE_CE) {
+        // CE_n key
+        auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
+        auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
+        auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
+        auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
+
+        if (volume_uuid == nullptr) {
+            res &= destroy_dir(system_ce_path);
+            res &= destroy_dir(misc_ce_path);
         }
+        res &= destroy_dir(media_ce_path);
+        res &= destroy_dir(user_ce_path);
     }
 
-    return 0;
+    return res;
 }