2 * Copyright (c) 2015 Google, Inc.
5 #define TAG "ext4_utils"
7 #include "ext4_crypt_init_extensions.h"
15 #include <asm/ioctl.h>
16 #include <sys/syscall.h>
18 #include <sys/types.h>
20 #include <cutils/klog.h>
22 #include "unencrypted_properties.h"
24 #define XATTR_NAME_ENCRYPTION_POLICY "encryption.policy"
25 #define EXT4_KEYREF_DELIMITER ((char)'.')
27 // ext4enc:TODO Include structure from somewhere sensible
28 // MUST be in sync with ext4_crypto.c in kernel
29 #define EXT4_KEY_DESCRIPTOR_SIZE 8
30 struct ext4_encryption_policy {
32 char contents_encryption_mode;
33 char filenames_encryption_mode;
35 char master_key_descriptor[EXT4_KEY_DESCRIPTOR_SIZE];
36 } __attribute__((__packed__));
38 #define EXT4_ENCRYPTION_MODE_AES_256_XTS 1
39 #define EXT4_ENCRYPTION_MODE_AES_256_CTS 4
41 // ext4enc:TODO Get value from somewhere sensible
42 #define EXT4_IOC_SET_ENCRYPTION_POLICY \
43 _IOR('f', 19, struct ext4_encryption_policy)
45 /* Validate that all path items are available and accessible. */
46 static int is_path_valid(const char *path)
48 if (access(path, W_OK)) {
49 KLOG_ERROR(TAG, "Can't access %s: %s\n",strerror(errno), path);
56 static int is_dir_empty(const char *dirname)
62 dir = opendir(dirname);
63 while ((d = readdir(dir)) != NULL) {
64 if (strcmp(d->d_name, "lost+found") == 0) {
65 // Skip lost+found directory
74 int do_policy_set(const char *directory, const char *policy, int policy_length)
79 if (policy_length != EXT4_KEY_DESCRIPTOR_SIZE) {
80 KLOG_ERROR("Policy wrong length\n");
84 if (!is_path_valid(directory)) {
89 if (!S_ISDIR(st.st_mode)) {
90 KLOG_ERROR(TAG, "Can only set policy on a directory (%s)\n", directory);
94 if (!is_dir_empty(directory)) {
95 KLOG_ERROR(TAG, "Can only set policy on an empty directory (%s)\n",
100 int fd = open(directory, O_DIRECTORY);
102 KLOG_ERROR(TAG, "Failed to open directory (%s)\n", directory);
106 ext4_encryption_policy eep;
108 eep.contents_encryption_mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
109 eep.filenames_encryption_mode = EXT4_ENCRYPTION_MODE_AES_256_CTS;
111 memcpy(eep.master_key_descriptor, policy, EXT4_KEY_DESCRIPTOR_SIZE);
112 ret = ioctl(fd, EXT4_IOC_SET_ENCRYPTION_POLICY, &eep);
113 auto preserve_errno = errno;
117 KLOG_ERROR(TAG, "Failed to set encryption policy for %s: %s\n",
118 directory, strerror(preserve_errno));
122 KLOG_INFO(TAG, "Encryption policy for %s is set to %02x%02x%02x%02x\n",
123 directory, policy[0], policy[1], policy[2], policy[3]);
127 bool e4crypt_non_default_key(const char* dir)
129 UnencryptedProperties props(dir);
130 return props.Get<int>(properties::is_default, 1) != 1;