Two phases to set the password for disk encryption
am: a363036b44

* commit 'a363036b44f7f140aa9a943578f56abff5880a60':
  Two phases to set the password for disk encryption

Change-Id: Ia28823079d8c0bda220238339f28095b234a0ae5
diff --git a/CryptCommandListener.cpp b/CryptCommandListener.cpp
index 02c2701..212e774 100644
--- a/CryptCommandListener.cpp
+++ b/CryptCommandListener.cpp
@@ -413,6 +413,11 @@
         return sendGenericOkFailOnBool(cli,
                 e4crypt_destroy_user_storage(parseNull(argv[2]), atoi(argv[3]), atoi(argv[4])));
 
+    } else if (subcommand == "ensure_policy") {
+        if (!check_argc(cli, subcommand, argc, 4, "<dir> <policy>")) return 0;
+        return sendGenericOkFailOnBool(cli,
+                e4crypt_hex_policy_ensure(argv[2], argv[3]));
+
     } else {
         dumpArgs(argc, argv, -1);
         cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown cryptfs subcommand", false);
diff --git a/Ext4Crypt.cpp b/Ext4Crypt.cpp
index 1158475..3917f2f 100644
--- a/Ext4Crypt.cpp
+++ b/Ext4Crypt.cpp
@@ -39,6 +39,8 @@
 
 #include <private/android_filesystem_config.h>
 
+#include <fs_mgr.h>
+
 #include "cryptfs.h"
 #include "ext4_crypt.h"
 #include "key_control.h"
@@ -59,6 +61,9 @@
 static constexpr int FLAG_STORAGE_DE = 1 << 0;
 static constexpr int FLAG_STORAGE_CE = 1 << 1;
 
+// Vile hack to get fstab entries for file encryption type
+extern struct fstab *fstab;
+
 namespace {
 const std::string device_key_dir = std::string() + DATA_MNT_POINT + e4crypt_unencrypted_folder;
 const std::string device_key_path = device_key_dir + "/key";
@@ -94,6 +99,218 @@
 };
 }
 
+#define XATTR_NAME_ENCRYPTION_POLICY "encryption.policy"
+#define EXT4_KEYREF_DELIMITER ((char)'.')
+
+// ext4enc:TODO Include structure from somewhere sensible
+// MUST be in sync with ext4_crypto.c in kernel
+#define EXT4_KEY_DESCRIPTOR_SIZE 8
+#define EXT4_KEY_DESCRIPTOR_SIZE_HEX 17
+
+struct ext4_encryption_policy {
+    char version;
+    char contents_encryption_mode;
+    char filenames_encryption_mode;
+    char flags;
+    char master_key_descriptor[EXT4_KEY_DESCRIPTOR_SIZE];
+} __attribute__((__packed__));
+
+#define EXT4_ENCRYPTION_MODE_AES_256_XTS    1
+#define EXT4_ENCRYPTION_MODE_AES_256_CTS    4
+#define EXT4_ENCRYPTION_MODE_PRIVATE        127
+
+// ext4enc:TODO Get value from somewhere sensible
+#define EXT4_IOC_SET_ENCRYPTION_POLICY _IOR('f', 19, struct ext4_encryption_policy)
+#define EXT4_IOC_GET_ENCRYPTION_POLICY _IOW('f', 21, struct ext4_encryption_policy)
+
+#define HEX_LOOKUP "0123456789abcdef"
+
+static void policy_to_hex(const char* policy, char* hex) {
+    for (size_t i = 0, j = 0; i < EXT4_KEY_DESCRIPTOR_SIZE; i++) {
+        hex[j++] = HEX_LOOKUP[(policy[i] & 0xF0) >> 4];
+        hex[j++] = HEX_LOOKUP[policy[i] & 0x0F];
+    }
+    hex[EXT4_KEY_DESCRIPTOR_SIZE_HEX - 1] = '\0';
+}
+
+static bool is_dir_empty(const char *dirname, bool *is_empty)
+{
+    int n = 0;
+    auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(dirname), closedir);
+    if (!dirp) {
+        PLOG(ERROR) << "Unable to read directory: " << dirname;
+        return false;
+    }
+    for (;;) {
+        errno = 0;
+        auto entry = readdir(dirp.get());
+        if (!entry) {
+            if (errno) {
+                PLOG(ERROR) << "Unable to read directory: " << dirname;
+                return false;
+            }
+            break;
+        }
+        if (strcmp(entry->d_name, "lost+found") != 0) { // Skip lost+found
+            ++n;
+            if (n > 2) {
+                *is_empty = false;
+                return true;
+            }
+        }
+    }
+    *is_empty = true;
+    return true;
+}
+
+static bool e4crypt_policy_set(const char *directory, const char *policy,
+                               size_t policy_length, int contents_encryption_type) {
+    if (policy_length != EXT4_KEY_DESCRIPTOR_SIZE) {
+        LOG(ERROR) << "Policy wrong length: " << policy_length;
+        return false;
+    }
+    int fd = open(directory, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open directory " << directory;
+        return false;
+    }
+
+    ext4_encryption_policy eep;
+    eep.version = 0;
+    eep.contents_encryption_mode = contents_encryption_type;
+    eep.filenames_encryption_mode = EXT4_ENCRYPTION_MODE_AES_256_CTS;
+    eep.flags = 0;
+    memcpy(eep.master_key_descriptor, policy, EXT4_KEY_DESCRIPTOR_SIZE);
+    if (ioctl(fd, EXT4_IOC_SET_ENCRYPTION_POLICY, &eep)) {
+        PLOG(ERROR) << "Failed to set encryption policy for " << directory;
+        close(fd);
+        return false;
+    }
+    close(fd);
+
+    char policy_hex[EXT4_KEY_DESCRIPTOR_SIZE_HEX];
+    policy_to_hex(policy, policy_hex);
+    LOG(INFO) << "Policy for " << directory << " set to " << policy_hex;
+    return true;
+}
+
+static bool e4crypt_policy_get(const char *directory, char *policy,
+                               size_t policy_length, int contents_encryption_type) {
+    if (policy_length != EXT4_KEY_DESCRIPTOR_SIZE) {
+        LOG(ERROR) << "Policy wrong length: " << policy_length;
+        return false;
+    }
+
+    int fd = open(directory, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open directory " << directory;
+        return false;
+    }
+
+    ext4_encryption_policy eep;
+    memset(&eep, 0, sizeof(ext4_encryption_policy));
+    if (ioctl(fd, EXT4_IOC_GET_ENCRYPTION_POLICY, &eep) != 0) {
+        PLOG(ERROR) << "Failed to get encryption policy for " << directory;
+        close(fd);
+        return -1;
+    }
+    close(fd);
+
+    if ((eep.version != 0)
+            || (eep.contents_encryption_mode != contents_encryption_type)
+            || (eep.filenames_encryption_mode != EXT4_ENCRYPTION_MODE_AES_256_CTS)
+            || (eep.flags != 0)) {
+        LOG(ERROR) << "Failed to find matching encryption policy for " << directory;
+        return false;
+    }
+    memcpy(policy, eep.master_key_descriptor, EXT4_KEY_DESCRIPTOR_SIZE);
+
+    return true;
+}
+
+static bool e4crypt_policy_check(const char *directory, const char *policy,
+                                 size_t policy_length, int contents_encryption_type) {
+    if (policy_length != EXT4_KEY_DESCRIPTOR_SIZE) {
+        LOG(ERROR) << "Policy wrong length: " << policy_length;
+        return false;
+    }
+    char existing_policy[EXT4_KEY_DESCRIPTOR_SIZE];
+    if (!e4crypt_policy_get(directory, existing_policy, EXT4_KEY_DESCRIPTOR_SIZE,
+                            contents_encryption_type)) {
+        return false;
+    }
+    char existing_policy_hex[EXT4_KEY_DESCRIPTOR_SIZE_HEX];
+
+    policy_to_hex(existing_policy, existing_policy_hex);
+
+    if (memcmp(policy, existing_policy, EXT4_KEY_DESCRIPTOR_SIZE) != 0) {
+        char policy_hex[EXT4_KEY_DESCRIPTOR_SIZE_HEX];
+        policy_to_hex(policy, policy_hex);
+        LOG(ERROR) << "Found policy " << existing_policy_hex << " at " << directory
+                   << " which doesn't match expected value " << policy_hex;
+        return false;
+    }
+    LOG(INFO) << "Found policy " << existing_policy_hex << " at " << directory
+              << " which matches expected value";
+    return true;
+}
+
+int e4crypt_policy_ensure(const char* directory, const char* policy, int policy_length)
+{
+    static int contents_encryption_type = 0;
+    if (contents_encryption_type == 0) {
+        // Get file_encryption_type from fstab
+        struct fstab_rec *rec = fs_mgr_get_entry_for_mount_point(fstab, "/data");
+        if (rec == 0) {
+            return -1;
+        }
+
+        // Translate file_encryption_type to ext4 contents encryption type
+        switch (rec->file_encryption_type)
+        {
+        case ET_SOFTWARE:
+            contents_encryption_type = EXT4_ENCRYPTION_MODE_AES_256_XTS;
+            break;
+
+        case ET_ICE:
+            contents_encryption_type = EXT4_ENCRYPTION_MODE_PRIVATE;
+            break;
+
+        default:
+            return -1;
+        }
+    }
+
+    bool is_empty;
+    if (!is_dir_empty(directory, &is_empty)) return -1;
+    if (is_empty) {
+        if (!e4crypt_policy_set(directory, policy, policy_length,
+                                contents_encryption_type)) {
+            return -1;
+        }
+    } else {
+        if (!e4crypt_policy_check(directory, policy, policy_length,
+                                  contents_encryption_type)) {
+            return -1;
+        }
+    }
+    return 0;
+}
+
+bool e4crypt_hex_policy_ensure(const char* dir, const char* hex_policy)
+{
+    std::string hex = hex_policy;
+    if (hex.substr(0, 2) != "0x") {
+        return false;
+    }
+    std::string policy;
+    if (android::vold::HexToStr(hex.substr(2), policy)) {
+        return false;
+    }
+
+    return e4crypt_policy_ensure(dir, policy.c_str(), policy.length()) == 0;
+}
+
 static bool e4crypt_is_emulated() {
     return property_get_bool("persist.sys.emulate_fbe", false);
 }
@@ -170,6 +387,14 @@
     }
     LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
                << " in process " << getpid();
+
+    // *TODO* Remove this code when kernel is fixed - see b/28373400
+    // Kernel preserves caches across a key insertion with ext4ice, which leads
+    // to contradictory dirents
+    if (!android::base::WriteStringToFile("3", "/proc/sys/vm/drop_caches")) {
+        PLOG(ERROR) << "Failed to drop_caches";
+    }
+
     return true;
 }
 
diff --git a/Ext4Crypt.h b/Ext4Crypt.h
index 2dcc197..be6b851 100644
--- a/Ext4Crypt.h
+++ b/Ext4Crypt.h
@@ -37,5 +37,6 @@
 
 bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial, int flags);
 bool e4crypt_destroy_user_storage(const char* volume_uuid, userid_t user_id, int flags);
+bool e4crypt_hex_policy_ensure(const char* dir, const char* hex_policy);
 
 __END_DECLS