Merge "Add OWNERS in system/vold" am: f18a5aad56 am: db09dbafdd
am: c8240e2dd3
Change-Id: Ie400e5a087a11670ea2f46b2056dd9a659d01317
diff --git a/Android.mk b/Android.mk
index 45b3f62..e92955f 100644
--- a/Android.mk
+++ b/Android.mk
@@ -29,12 +29,16 @@
TrimTask.cpp \
Keymaster.cpp \
KeyStorage.cpp \
+ KeyUtil.cpp \
ScryptParameters.cpp \
secontext.cpp \
+ EncryptInplace.cpp \
+ MetadataCrypt.cpp \
common_c_includes := \
system/extras/f2fs_utils \
external/scrypt/lib/crypto \
+ external/f2fs-tools/include \
frameworks/native/include \
system/security/keystore \
@@ -70,6 +74,11 @@
libbatteryservice \
libavb \
+# TODO: include "cert-err34-c" once we move to Binder
+# TODO: include "cert-err58-cpp" once 36656327 is fixed
+common_local_tidy_flags := -warnings-as-errors=clang-analyzer-security*,cert-*
+common_local_tidy_checks := -*,clang-analyzer-security*,cert-*,-cert-err34-c,-cert-err58-cpp
+
vold_conlyflags := -std=c11
vold_cflags := -Werror -Wall -Wno-missing-field-initializers -Wno-unused-variable -Wno-unused-parameter
@@ -88,6 +97,9 @@
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
LOCAL_MODULE := libvold
LOCAL_CLANG := true
+LOCAL_TIDY := true
+LOCAL_TIDY_FLAGS := $(common_local_tidy_flags)
+LOCAL_TIDY_CHECKS := $(common_local_tidy_checks)
LOCAL_SRC_FILES := $(common_src_files)
LOCAL_C_INCLUDES := $(common_c_includes)
LOCAL_SHARED_LIBRARIES := $(common_shared_libraries)
@@ -104,6 +116,9 @@
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
LOCAL_MODULE := vold
LOCAL_CLANG := true
+LOCAL_TIDY := true
+LOCAL_TIDY_FLAGS := $(common_local_tidy_flags)
+LOCAL_TIDY_CHECKS := $(common_local_tidy_checks)
LOCAL_SRC_FILES := \
main.cpp \
$(common_src_files)
@@ -124,6 +139,9 @@
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
LOCAL_CLANG := true
+LOCAL_TIDY := true
+LOCAL_TIDY_FLAGS := $(common_local_tidy_flags)
+LOCAL_TIDY_CHECKS := $(common_local_tidy_checks)
LOCAL_SRC_FILES := vdc.cpp
LOCAL_MODULE := vdc
LOCAL_SHARED_LIBRARIES := libcutils libbase
@@ -137,6 +155,9 @@
LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
LOCAL_CLANG := true
+LOCAL_TIDY := true
+LOCAL_TIDY_FLAGS := $(common_local_tidy_flags)
+LOCAL_TIDY_CHECKS := $(common_local_tidy_checks)
LOCAL_SRC_FILES:= secdiscard.cpp
LOCAL_MODULE:= secdiscard
LOCAL_SHARED_LIBRARIES := libbase
diff --git a/CommandListener.cpp b/CommandListener.cpp
index c2b8310..78973db 100644
--- a/CommandListener.cpp
+++ b/CommandListener.cpp
@@ -327,8 +327,8 @@
continue;
}
- char processName[255];
- Process::getProcessName(pid, processName, sizeof(processName));
+ std::string processName;
+ Process::getProcessName(pid, processName);
if (Process::checkFileDescriptorSymLinks(pid, argv[2]) ||
Process::checkFileMaps(pid, argv[2]) ||
@@ -337,7 +337,7 @@
Process::checkSymLink(pid, argv[2], "exe")) {
char msg[1024];
- snprintf(msg, sizeof(msg), "%d %s", pid, processName);
+ snprintf(msg, sizeof(msg), "%d %s", pid, processName.c_str());
cli->sendMsg(ResponseCode::StorageUsersListResult, msg, false);
}
}
diff --git a/CryptCommandListener.cpp b/CryptCommandListener.cpp
index 094a474..779338f 100644
--- a/CryptCommandListener.cpp
+++ b/CryptCommandListener.cpp
@@ -50,6 +50,7 @@
#include "ResponseCode.h"
#include "cryptfs.h"
#include "Ext4Crypt.h"
+#include "MetadataCrypt.h"
#include "Utils.h"
#define DUMP_ARGS 0
@@ -201,6 +202,15 @@
dumpArgs(argc, argv, -1);
rc = cryptfs_crypto_complete();
} else if (subcommand == "enablecrypto") {
+ if (e4crypt_is_native()) {
+ if (argc != 5 || strcmp(argv[2], "inplace") || strcmp(argv[3], "default")
+ || strcmp(argv[4], "noui")) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError,
+ "Usage with ext4crypt: cryptfs enablecrypto inplace default noui", false);
+ return 0;
+ }
+ return sendGenericOkFailOnBool(cli, e4crypt_enable_crypto());
+ }
const char* syntax = "Usage: cryptfs enablecrypto <wipe|inplace> "
"default|password|pin|pattern [passwd] [noui]";
@@ -260,7 +270,7 @@
} else if (subcommand == "enablefilecrypto") {
if (!check_argc(cli, subcommand, argc, 2, "")) return 0;
dumpArgs(argc, argv, -1);
- rc = cryptfs_enable_file();
+ rc = e4crypt_initialize_global_de();
} else if (subcommand == "changepw") {
const char* syntax = "Usage: cryptfs changepw "
"default|password|pin|pattern [newpasswd]";
@@ -318,6 +328,9 @@
SLOGD("cryptfs mountdefaultencrypted");
dumpArgs(argc, argv, -1);
+ if (e4crypt_is_native()) {
+ return sendGenericOkFailOnBool(cli, e4crypt_mount_metadata_encrypted());
+ }
// Spawn as thread so init can issue commands back to vold without
// causing deadlock, usually as a result of prep_data_fs.
std::thread(&cryptfs_mount_default_encrypted).detach();
diff --git a/Devmapper.cpp b/Devmapper.cpp
index e56a4da..4b6942d 100644
--- a/Devmapper.cpp
+++ b/Devmapper.cpp
@@ -195,7 +195,7 @@
char *geoParams = buffer + sizeof(struct dm_ioctl);
// bps=512 spc=8 res=32 nft=2 sec=8190 mid=0xf0 spt=63 hds=64 hid=0 bspf=8 rdcl=2 infs=1 bkbs=2
- strcpy(geoParams, "0 64 63 0");
+ strlcpy(geoParams, "0 64 63 0", DEVMAPPER_BUFFER_SIZE - sizeof(struct dm_ioctl));
geoParams += strlen(geoParams) + 1;
geoParams = (char *) _align(geoParams, 8);
if (ioctl(fd, DM_DEV_SET_GEOMETRY, io)) {
diff --git a/EncryptInplace.cpp b/EncryptInplace.cpp
new file mode 100644
index 0000000..9aa2a21
--- /dev/null
+++ b/EncryptInplace.cpp
@@ -0,0 +1,656 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "EncryptInplace.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <inttypes.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <ext4_utils/ext4.h>
+#include <ext4_utils/ext4_utils.h>
+#include <f2fs_sparseblock.h>
+
+#include <algorithm>
+
+#include "cutils/properties.h"
+#define LOG_TAG "EncryptInplace"
+#include "cutils/log.h"
+#include "CheckBattery.h"
+
+// HORRIBLE HACK, FIXME
+#include "cryptfs.h"
+
+// FIXME horrible cut-and-paste code
+static inline int unix_read(int fd, void* buff, int len)
+{
+ return TEMP_FAILURE_RETRY(read(fd, buff, len));
+}
+
+static inline int unix_write(int fd, const void* buff, int len)
+{
+ return TEMP_FAILURE_RETRY(write(fd, buff, len));
+}
+
+#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
+
+/* aligned 32K writes tends to make flash happy.
+ * SD card association recommends it.
+ */
+#ifndef CONFIG_HW_DISK_ENCRYPTION
+#define BLOCKS_AT_A_TIME 8
+#else
+#define BLOCKS_AT_A_TIME 1024
+#endif
+
+struct encryptGroupsData
+{
+ int realfd;
+ int cryptofd;
+ off64_t numblocks;
+ off64_t one_pct, cur_pct, new_pct;
+ off64_t blocks_already_done, tot_numblocks;
+ off64_t used_blocks_already_done, tot_used_blocks;
+ char* real_blkdev, * crypto_blkdev;
+ int count;
+ off64_t offset;
+ char* buffer;
+ off64_t last_written_sector;
+ int completed;
+ time_t time_started;
+ int remaining_time;
+};
+
+static void update_progress(struct encryptGroupsData* data, int is_used)
+{
+ data->blocks_already_done++;
+
+ if (is_used) {
+ data->used_blocks_already_done++;
+ }
+ if (data->tot_used_blocks) {
+ data->new_pct = data->used_blocks_already_done / data->one_pct;
+ } else {
+ data->new_pct = data->blocks_already_done / data->one_pct;
+ }
+
+ if (data->new_pct > data->cur_pct) {
+ char buf[8];
+ data->cur_pct = data->new_pct;
+ snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
+ property_set("vold.encrypt_progress", buf);
+ }
+
+ if (data->cur_pct >= 5) {
+ struct timespec time_now;
+ if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
+ SLOGW("Error getting time");
+ } else {
+ double elapsed_time = difftime(time_now.tv_sec, data->time_started);
+ off64_t remaining_blocks = data->tot_used_blocks
+ - data->used_blocks_already_done;
+ int remaining_time = (int)(elapsed_time * remaining_blocks
+ / data->used_blocks_already_done);
+
+ // Change time only if not yet set, lower, or a lot higher for
+ // best user experience
+ if (data->remaining_time == -1
+ || remaining_time < data->remaining_time
+ || remaining_time > data->remaining_time + 60) {
+ char buf[8];
+ snprintf(buf, sizeof(buf), "%d", remaining_time);
+ property_set("vold.encrypt_time_remaining", buf);
+ data->remaining_time = remaining_time;
+ }
+ }
+ }
+}
+
+static void log_progress(struct encryptGroupsData const* data, bool completed)
+{
+ // Precondition - if completed data = 0 else data != 0
+
+ // Track progress so we can skip logging blocks
+ static off64_t offset = -1;
+
+ // Need to close existing 'Encrypting from' log?
+ if (completed || (offset != -1 && data->offset != offset)) {
+ SLOGI("Encrypted to sector %" PRId64,
+ offset / info.block_size * CRYPT_SECTOR_SIZE);
+ offset = -1;
+ }
+
+ // Need to start new 'Encrypting from' log?
+ if (!completed && offset != data->offset) {
+ SLOGI("Encrypting from sector %" PRId64,
+ data->offset / info.block_size * CRYPT_SECTOR_SIZE);
+ }
+
+ // Update offset
+ if (!completed) {
+ offset = data->offset + (off64_t)data->count * info.block_size;
+ }
+}
+
+static int flush_outstanding_data(struct encryptGroupsData* data)
+{
+ if (data->count == 0) {
+ return 0;
+ }
+
+ SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
+
+ if (pread64(data->realfd, data->buffer,
+ info.block_size * data->count, data->offset)
+ <= 0) {
+ SLOGE("Error reading real_blkdev %s for inplace encrypt",
+ data->real_blkdev);
+ return -1;
+ }
+
+ if (pwrite64(data->cryptofd, data->buffer,
+ info.block_size * data->count, data->offset)
+ <= 0) {
+ SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
+ data->crypto_blkdev);
+ return -1;
+ } else {
+ log_progress(data, false);
+ }
+
+ data->count = 0;
+ data->last_written_sector = (data->offset + data->count)
+ / info.block_size * CRYPT_SECTOR_SIZE - 1;
+ return 0;
+}
+
+static int encrypt_groups(struct encryptGroupsData* data)
+{
+ unsigned int i;
+ u8 *block_bitmap = 0;
+ unsigned int block;
+ off64_t ret;
+ int rc = -1;
+
+ data->buffer = (char*) malloc(info.block_size * BLOCKS_AT_A_TIME);
+ if (!data->buffer) {
+ SLOGE("Failed to allocate crypto buffer");
+ goto errout;
+ }
+
+ block_bitmap = (u8*) malloc(info.block_size);
+ if (!block_bitmap) {
+ SLOGE("failed to allocate block bitmap");
+ goto errout;
+ }
+
+ for (i = 0; i < aux_info.groups; ++i) {
+ SLOGI("Encrypting group %d", i);
+
+ u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
+ u32 block_count = std::min(info.blocks_per_group,
+ (u32)(aux_info.len_blocks - first_block));
+
+ off64_t offset = (u64)info.block_size
+ * aux_info.bg_desc[i].bg_block_bitmap;
+
+ ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
+ if (ret != (int)info.block_size) {
+ SLOGE("failed to read all of block group bitmap %d", i);
+ goto errout;
+ }
+
+ offset = (u64)info.block_size * first_block;
+
+ data->count = 0;
+
+ for (block = 0; block < block_count; block++) {
+ int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
+ 0 : bitmap_get_bit(block_bitmap, block);
+ update_progress(data, used);
+ if (used) {
+ if (data->count == 0) {
+ data->offset = offset;
+ }
+ data->count++;
+ } else {
+ if (flush_outstanding_data(data)) {
+ goto errout;
+ }
+ }
+
+ offset += info.block_size;
+
+ /* Write data if we are aligned or buffer size reached */
+ if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
+ || data->count == BLOCKS_AT_A_TIME) {
+ if (flush_outstanding_data(data)) {
+ goto errout;
+ }
+ }
+
+ if (!is_battery_ok_to_continue()) {
+ SLOGE("Stopping encryption due to low battery");
+ rc = 0;
+ goto errout;
+ }
+
+ }
+ if (flush_outstanding_data(data)) {
+ goto errout;
+ }
+ }
+
+ data->completed = 1;
+ rc = 0;
+
+errout:
+ log_progress(0, true);
+ free(data->buffer);
+ free(block_bitmap);
+ return rc;
+}
+
+static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
+ char *real_blkdev,
+ off64_t size,
+ off64_t *size_already_done,
+ off64_t tot_size,
+ off64_t previously_encrypted_upto)
+{
+ u32 i;
+ struct encryptGroupsData data;
+ int rc; // Can't initialize without causing warning -Wclobbered
+ int retries = RETRY_MOUNT_ATTEMPTS;
+ struct timespec time_started = {0};
+
+ if (previously_encrypted_upto > *size_already_done) {
+ SLOGD("Not fast encrypting since resuming part way through");
+ return -1;
+ }
+
+ memset(&data, 0, sizeof(data));
+ data.real_blkdev = real_blkdev;
+ data.crypto_blkdev = crypto_blkdev;
+
+ if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
+ SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
+ real_blkdev, errno, strerror(errno));
+ rc = -1;
+ goto errout;
+ }
+
+ // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
+ while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+ if (--retries) {
+ SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
+ crypto_blkdev, errno, strerror(errno));
+ sleep(RETRY_MOUNT_DELAY_SECONDS);
+ } else {
+ SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
+ crypto_blkdev, errno, strerror(errno));
+ rc = ENABLE_INPLACE_ERR_DEV;
+ goto errout;
+ }
+ }
+
+ if (setjmp(setjmp_env)) { // NOLINT
+ SLOGE("Reading ext4 extent caused an exception\n");
+ rc = -1;
+ goto errout;
+ }
+
+ if (read_ext(data.realfd, 0) != 0) {
+ SLOGE("Failed to read ext4 extent\n");
+ rc = -1;
+ goto errout;
+ }
+
+ data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
+ data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
+ data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
+
+ SLOGI("Encrypting ext4 filesystem in place...");
+
+ data.tot_used_blocks = data.numblocks;
+ for (i = 0; i < aux_info.groups; ++i) {
+ data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
+ }
+
+ data.one_pct = data.tot_used_blocks / 100;
+ data.cur_pct = 0;
+
+ if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
+ SLOGW("Error getting time at start");
+ // Note - continue anyway - we'll run with 0
+ }
+ data.time_started = time_started.tv_sec;
+ data.remaining_time = -1;
+
+ rc = encrypt_groups(&data);
+ if (rc) {
+ SLOGE("Error encrypting groups");
+ goto errout;
+ }
+
+ *size_already_done += data.completed ? size : data.last_written_sector;
+ rc = 0;
+
+errout:
+ close(data.realfd);
+ close(data.cryptofd);
+
+ return rc;
+}
+
+static void log_progress_f2fs(u64 block, bool completed)
+{
+ // Precondition - if completed data = 0 else data != 0
+
+ // Track progress so we can skip logging blocks
+ static u64 last_block = (u64)-1;
+
+ // Need to close existing 'Encrypting from' log?
+ if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
+ SLOGI("Encrypted to block %" PRId64, last_block);
+ last_block = -1;
+ }
+
+ // Need to start new 'Encrypting from' log?
+ if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
+ SLOGI("Encrypting from block %" PRId64, block);
+ }
+
+ // Update offset
+ if (!completed) {
+ last_block = block;
+ }
+}
+
+static int encrypt_one_block_f2fs(u64 pos, void *data)
+{
+ struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
+
+ priv_dat->blocks_already_done = pos - 1;
+ update_progress(priv_dat, 1);
+
+ off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
+
+ if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
+ SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
+ return -1;
+ }
+
+ if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
+ SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
+ return -1;
+ } else {
+ log_progress_f2fs(pos, false);
+ }
+
+ return 0;
+}
+
+static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
+ char *real_blkdev,
+ off64_t size,
+ off64_t *size_already_done,
+ off64_t tot_size,
+ off64_t previously_encrypted_upto)
+{
+ struct encryptGroupsData data;
+ struct f2fs_info *f2fs_info = NULL;
+ int rc = ENABLE_INPLACE_ERR_OTHER;
+ if (previously_encrypted_upto > *size_already_done) {
+ SLOGD("Not fast encrypting since resuming part way through");
+ return ENABLE_INPLACE_ERR_OTHER;
+ }
+ memset(&data, 0, sizeof(data));
+ data.real_blkdev = real_blkdev;
+ data.crypto_blkdev = crypto_blkdev;
+ data.realfd = -1;
+ data.cryptofd = -1;
+ if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
+ SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
+ real_blkdev);
+ goto errout;
+ }
+ if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+ SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
+ crypto_blkdev, errno, strerror(errno));
+ rc = ENABLE_INPLACE_ERR_DEV;
+ goto errout;
+ }
+
+ f2fs_info = generate_f2fs_info(data.realfd);
+ if (!f2fs_info)
+ goto errout;
+
+ data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
+ data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
+ data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
+
+ data.tot_used_blocks = get_num_blocks_used(f2fs_info);
+
+ data.one_pct = data.tot_used_blocks / 100;
+ data.cur_pct = 0;
+ data.time_started = time(NULL);
+ data.remaining_time = -1;
+
+ data.buffer = (char*) malloc(f2fs_info->block_size);
+ if (!data.buffer) {
+ SLOGE("Failed to allocate crypto buffer");
+ goto errout;
+ }
+
+ data.count = 0;
+
+ /* Currently, this either runs to completion, or hits a nonrecoverable error */
+ rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
+
+ if (rc) {
+ SLOGE("Error in running over f2fs blocks");
+ rc = ENABLE_INPLACE_ERR_OTHER;
+ goto errout;
+ }
+
+ *size_already_done += size;
+ rc = 0;
+
+errout:
+ if (rc)
+ SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
+
+ log_progress_f2fs(0, true);
+ free(f2fs_info);
+ free(data.buffer);
+ close(data.realfd);
+ close(data.cryptofd);
+
+ return rc;
+}
+
+static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
+ off64_t size, off64_t *size_already_done,
+ off64_t tot_size,
+ off64_t previously_encrypted_upto)
+{
+ int realfd, cryptofd;
+ char *buf[CRYPT_INPLACE_BUFSIZE];
+ int rc = ENABLE_INPLACE_ERR_OTHER;
+ off64_t numblocks, i, remainder;
+ off64_t one_pct, cur_pct, new_pct;
+ off64_t blocks_already_done, tot_numblocks;
+
+ if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
+ SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
+ return ENABLE_INPLACE_ERR_OTHER;
+ }
+
+ if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+ SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
+ crypto_blkdev, errno, strerror(errno));
+ close(realfd);
+ return ENABLE_INPLACE_ERR_DEV;
+ }
+
+ /* This is pretty much a simple loop of reading 4K, and writing 4K.
+ * The size passed in is the number of 512 byte sectors in the filesystem.
+ * So compute the number of whole 4K blocks we should read/write,
+ * and the remainder.
+ */
+ numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
+ remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
+ tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
+ blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
+
+ SLOGE("Encrypting filesystem in place...");
+
+ i = previously_encrypted_upto + 1 - *size_already_done;
+
+ if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
+ SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
+ goto errout;
+ }
+
+ if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
+ SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
+ goto errout;
+ }
+
+ for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
+ if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
+ SLOGE("Error reading initial sectors from real_blkdev %s for "
+ "inplace encrypt\n", crypto_blkdev);
+ goto errout;
+ }
+ if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
+ SLOGE("Error writing initial sectors to crypto_blkdev %s for "
+ "inplace encrypt\n", crypto_blkdev);
+ goto errout;
+ } else {
+ SLOGI("Encrypted 1 block at %" PRId64, i);
+ }
+ }
+
+ one_pct = tot_numblocks / 100;
+ cur_pct = 0;
+ /* process the majority of the filesystem in blocks */
+ for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
+ new_pct = (i + blocks_already_done) / one_pct;
+ if (new_pct > cur_pct) {
+ char buf[8];
+
+ cur_pct = new_pct;
+ snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
+ property_set("vold.encrypt_progress", buf);
+ }
+ if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
+ SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
+ goto errout;
+ }
+ if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
+ SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
+ goto errout;
+ } else {
+ SLOGD("Encrypted %d block at %" PRId64,
+ CRYPT_SECTORS_PER_BUFSIZE,
+ i * CRYPT_SECTORS_PER_BUFSIZE);
+ }
+
+ if (!is_battery_ok_to_continue()) {
+ SLOGE("Stopping encryption due to low battery");
+ *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
+ rc = 0;
+ goto errout;
+ }
+ }
+
+ /* Do any remaining sectors */
+ for (i=0; i<remainder; i++) {
+ if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
+ SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
+ goto errout;
+ }
+ if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
+ SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
+ goto errout;
+ } else {
+ SLOGI("Encrypted 1 block at next location");
+ }
+ }
+
+ *size_already_done += size;
+ rc = 0;
+
+errout:
+ close(realfd);
+ close(cryptofd);
+
+ return rc;
+}
+
+/* returns on of the ENABLE_INPLACE_* return codes */
+int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
+ off64_t size, off64_t *size_already_done,
+ off64_t tot_size,
+ off64_t previously_encrypted_upto)
+{
+ int rc_ext4, rc_f2fs, rc_full;
+ if (previously_encrypted_upto) {
+ SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
+ }
+
+ if (*size_already_done + size < previously_encrypted_upto) {
+ *size_already_done += size;
+ return 0;
+ }
+
+ /* TODO: identify filesystem type.
+ * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
+ * then we will drop down to cryptfs_enable_inplace_f2fs.
+ * */
+ if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
+ size, size_already_done,
+ tot_size, previously_encrypted_upto)) == 0) {
+ return 0;
+ }
+ SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
+
+ if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
+ size, size_already_done,
+ tot_size, previously_encrypted_upto)) == 0) {
+ return 0;
+ }
+ SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
+
+ rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
+ size, size_already_done, tot_size,
+ previously_encrypted_upto);
+ SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
+
+ /* Hack for b/17898962, the following is the symptom... */
+ if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
+ && rc_f2fs == ENABLE_INPLACE_ERR_DEV
+ && rc_full == ENABLE_INPLACE_ERR_DEV) {
+ return ENABLE_INPLACE_ERR_DEV;
+ }
+ return rc_full;
+}
diff --git a/EncryptInplace.h b/EncryptInplace.h
new file mode 100644
index 0000000..de5a1c5
--- /dev/null
+++ b/EncryptInplace.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _ENCRYPT_INPLACE_H
+#define _ENCRYPT_INPLACE_H
+
+#include <sys/types.h>
+
+#define CRYPT_INPLACE_BUFSIZE 4096
+#define CRYPT_SECTOR_SIZE 512
+#define RETRY_MOUNT_ATTEMPTS 10
+#define RETRY_MOUNT_DELAY_SECONDS 1
+
+int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
+ off64_t size, off64_t *size_already_done,
+ off64_t tot_size,
+ off64_t previously_encrypted_upto);
+
+#endif
diff --git a/Ext4Crypt.cpp b/Ext4Crypt.cpp
index 2d4ae89..c3e0cc3 100644
--- a/Ext4Crypt.cpp
+++ b/Ext4Crypt.cpp
@@ -17,22 +17,21 @@
#include "Ext4Crypt.h"
#include "KeyStorage.h"
+#include "KeyUtil.h"
#include "Utils.h"
#include <algorithm>
-#include <iomanip>
#include <map>
#include <set>
#include <sstream>
#include <string>
+#include <vector>
#include <dirent.h>
#include <errno.h>
#include <fcntl.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>
@@ -45,6 +44,8 @@
#define MANAGE_MISC_DIRS 0
#include <cutils/fs.h>
+#include <cutils/properties.h>
+
#include <ext4_utils/ext4_crypt.h>
#include <keyutils.h>
@@ -79,19 +80,6 @@
// TODO abolish this map, per b/26948053
std::map<userid_t, std::string> s_ce_keys;
-// ext4enc:TODO get this const from somewhere good
-const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
-
-// 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;
-};
}
static bool e4crypt_is_emulated() {
@@ -102,78 +90,6 @@
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) {
- SHA512_CTX c;
-
- SHA512_Init(&c);
- SHA512_Update(&c, key, length);
- unsigned char key_ref1[SHA512_DIGEST_LENGTH];
- SHA512_Final(key_ref1, &c);
-
- SHA512_Init(&c);
- 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);
-}
-
-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;
- }
- 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) {
- std::ostringstream o;
- o << "ext4:";
- for (unsigned char 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 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;
- }
- return true;
-}
-
-// Install password into global keyring
-// Return raw key reference for use in policy
-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;
- }
- LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
- << " in process " << getpid();
-
- return true;
-}
-
static std::string get_de_key_path(userid_t user_id) {
return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
}
@@ -273,7 +189,7 @@
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;
+ if (!android::vold::installKey(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;
@@ -298,43 +214,12 @@
return true;
}
-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;
-}
-
-static bool path_exists(const std::string& path) {
- return access(path.c_str(), F_OK) == 0;
-}
-
// 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;
- }
- 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;
-}
-
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 (!android::vold::randomKey(&de_key)) return false;
+ if (!android::vold::randomKey(&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);
@@ -344,18 +229,18 @@
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,
+ if (!android::vold::storeKeyAtomically(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,
+ if (!android::vold::storeKeyAtomically(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;
+ if (!android::vold::installKey(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;
+ if (!android::vold::installKey(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;
@@ -422,7 +307,7 @@
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;
+ 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;
}
@@ -451,28 +336,16 @@
return false;
}
- 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;
- }
-
std::string device_key_ref;
- if (!install_key(device_key, &device_key_ref)) {
- LOG(ERROR) << "Failed to install device key";
- return false;
- }
+ if (!android::vold::retrieveAndInstallKey(true,
+ device_key_path, device_key_temp, &device_key_ref)) return false;
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";
+ PLOG(ERROR) << "Cannot save key reference to:" << ref_filename;
return false;
}
+ LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
s_global_de_initialized = true;
return true;
@@ -484,7 +357,7 @@
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 (!android::vold::pathExists(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
@@ -526,31 +399,13 @@
return true;
}
-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);
-
- // Unlink the key from the keyring. Prefer unlinking to revoking or
- // invalidating, since unlinking is actually no less secure currently, and
- // it avoids bugs in certain kernel versions where the keyring key is
- // referenced from places it shouldn't be.
- if (keyctl_unlink(key_serial, device_keyring) != 0) {
- PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
- return false;
- }
- LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
- return true;
-}
-
static bool evict_ce_key(userid_t user_id) {
- s_ce_keys.erase(user_id);
+ s_ce_keys.erase(user_id);
bool success = true;
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);
+ success &= android::vold::evictKey(raw_ref);
}
s_ce_key_raw_refs.erase(user_id);
return success;
@@ -564,7 +419,8 @@
bool success = true;
std::string raw_ref;
success &= evict_ce_key(user_id);
- success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && evict_key(raw_ref);
+ success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)
+ && android::vold::evictKey(raw_ref);
s_de_key_raw_refs.erase(user_id);
auto it = s_ephemeral_users.find(user_id);
if (it != s_ephemeral_users.end()) {
@@ -574,7 +430,7 @@
success &= android::vold::destroyKey(path);
}
auto de_key_path = get_de_key_path(user_id);
- if (path_exists(de_key_path)) {
+ if (android::vold::pathExists(de_key_path)) {
success &= android::vold::destroyKey(de_key_path);
} else {
LOG(INFO) << "Not present so not erasing: " << de_key_path;
@@ -646,7 +502,7 @@
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;
+ if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
return true;
}
diff --git a/KeyStorage.cpp b/KeyStorage.cpp
index a36ac6a..b4f85f4 100644
--- a/KeyStorage.cpp
+++ b/KeyStorage.cpp
@@ -400,6 +400,10 @@
return true;
}
+bool pathExists(const std::string& path) {
+ return access(path.c_str(), F_OK) == 0;
+}
+
bool storeKey(const std::string& dir, const KeyAuthentication& auth, const std::string& key) {
if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
PLOG(ERROR) << "key mkdir " << dir;
@@ -437,6 +441,25 @@
return true;
}
+bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
+ const KeyAuthentication& auth, const std::string& key) {
+ if (pathExists(key_path)) {
+ LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
+ return false;
+ }
+ if (pathExists(tmp_path)) {
+ LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
+ destroyKey(tmp_path); // May be partially created so ignore errors
+ }
+ if (!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;
+}
+
bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, std::string* key) {
std::string version;
if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
diff --git a/KeyStorage.h b/KeyStorage.h
index bce6a99..63345f4 100644
--- a/KeyStorage.h
+++ b/KeyStorage.h
@@ -39,12 +39,22 @@
extern const KeyAuthentication kEmptyAuthentication;
+// Checks if path "path" exists.
+bool pathExists(const std::string& path);
+
// Create a directory at the named path, and store "key" in it,
// in such a way that it can only be retrieved via Keymaster and
// can be securely deleted.
// It's safe to move/rename the directory after creation.
bool storeKey(const std::string& dir, const KeyAuthentication& auth, const std::string& key);
+// Create a directory at the named path, and store "key" in it as storeKey
+// This version creates the key in "tmp_path" then atomically renames "tmp_path"
+// to "key_path" thereby ensuring that the key is either stored entirely or
+// not at all.
+bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
+ const KeyAuthentication& auth, const std::string& key);
+
// Retrieve the key from the named directory.
bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, std::string* key);
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
new file mode 100644
index 0000000..865cc11
--- /dev/null
+++ b/KeyUtil.cpp
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "KeyUtil.h"
+
+#include <iomanip>
+#include <sstream>
+#include <string>
+
+#include <openssl/sha.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <keyutils.h>
+
+#include "KeyStorage.h"
+#include "Utils.h"
+
+namespace android {
+namespace vold {
+
+bool randomKey(std::string* key) {
+ if (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;
+}
+
+// Get raw keyref - used to make keyname and to pass to ioctl
+static std::string generateKeyRef(const char* key, int length) {
+ SHA512_CTX c;
+
+ SHA512_Init(&c);
+ SHA512_Update(&c, key, length);
+ unsigned char key_ref1[SHA512_DIGEST_LENGTH];
+ SHA512_Final(key_ref1, &c);
+
+ SHA512_Init(&c);
+ 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);
+}
+
+static bool fillKey(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;
+ }
+ 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;
+}
+
+std::string keyname(const std::string& raw_ref) {
+ std::ostringstream o;
+ o << "ext4:";
+ 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 bool e4cryptKeyring(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;
+ }
+ return true;
+}
+
+// Install password into global keyring
+// Return raw key reference for use in policy
+bool installKey(const std::string& key, std::string* raw_ref) {
+ ext4_encryption_key ext4_key;
+ if (!fillKey(key, &ext4_key)) return false;
+ *raw_ref = generateKeyRef(ext4_key.raw, ext4_key.size);
+ auto ref = keyname(*raw_ref);
+ key_serial_t device_keyring;
+ if (!e4cryptKeyring(&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;
+ }
+ LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
+ << " in process " << getpid();
+
+ return true;
+}
+
+bool evictKey(const std::string& raw_ref) {
+ auto ref = keyname(raw_ref);
+ key_serial_t device_keyring;
+ if (!e4cryptKeyring(&device_keyring)) return false;
+ auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
+
+ // Unlink the key from the keyring. Prefer unlinking to revoking or
+ // invalidating, since unlinking is actually no less secure currently, and
+ // it avoids bugs in certain kernel versions where the keyring key is
+ // referenced from places it shouldn't be.
+ if (keyctl_unlink(key_serial, device_keyring) != 0) {
+ PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
+ return false;
+ }
+ LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
+ return true;
+}
+
+bool retrieveAndInstallKey(bool create_if_absent, const std::string& key_path,
+ const std::string& tmp_path, std::string* key_ref) {
+ std::string key;
+ if (pathExists(key_path)) {
+ LOG(DEBUG) << "Key exists, using: " << key_path;
+ if (!retrieveKey(key_path, kEmptyAuthentication, &key)) 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;
+ }
+
+ if (!installKey(key, key_ref)) {
+ LOG(ERROR) << "Failed to install key in " << key_path;
+ return false;
+ }
+ return true;
+}
+
+bool retrieveKey(bool create_if_absent, const std::string& key_path,
+ const std::string& tmp_path, std::string* key) {
+ if (pathExists(key_path)) {
+ LOG(DEBUG) << "Key exists, using: " << key_path;
+ if (!retrieveKey(key_path, kEmptyAuthentication, key)) 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;
+}
+
+} // namespace vold
+} // namespace android
diff --git a/KeyUtil.h b/KeyUtil.h
new file mode 100644
index 0000000..f8fb634
--- /dev/null
+++ b/KeyUtil.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_VOLD_KEYUTIL_H
+#define ANDROID_VOLD_KEYUTIL_H
+
+#include <string>
+
+namespace android {
+namespace vold {
+
+// ext4enc:TODO get this const from somewhere good
+const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
+
+// 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;
+};
+
+std::string keyname(const std::string& raw_ref);
+bool randomKey(std::string* key);
+bool installKey(const std::string& key, std::string* raw_ref);
+bool evictKey(const std::string& raw_ref);
+bool retrieveAndInstallKey(bool create_if_absent, const std::string& key_path,
+ const std::string& tmp_path, std::string* key_ref);
+bool retrieveKey(bool create_if_absent, const std::string& key_path,
+ const std::string& tmp_path, std::string* key);
+
+} // namespace vold
+} // namespace android
+
+#endif
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
new file mode 100644
index 0000000..b707549
--- /dev/null
+++ b/MetadataCrypt.cpp
@@ -0,0 +1,312 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "MetadataCrypt.h"
+
+#include <string>
+#include <thread>
+#include <vector>
+
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <linux/dm-ioctl.h>
+
+#include <android-base/logging.h>
+#include <cutils/properties.h>
+#include <fs_mgr.h>
+
+#include "AutoCloseFD.h"
+#include "EncryptInplace.h"
+#include "KeyStorage.h"
+#include "KeyUtil.h"
+#include "secontext.h"
+#include "Utils.h"
+#include "VoldUtil.h"
+
+extern struct fstab *fstab;
+#define DM_CRYPT_BUF_SIZE 4096
+#define TABLE_LOAD_RETRIES 10
+#define DEFAULT_KEY_TARGET_TYPE "default-key"
+
+static const std::string kDmNameUserdata = "userdata";
+
+static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device) {
+ // fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
+ // partitions in the fsck domain.
+ if (setexeccon(secontextFsck())) {
+ PLOG(ERROR) << "Failed to setexeccon";
+ return false;
+ }
+ auto mount_rc = fs_mgr_do_mount(fstab, const_cast<char*>(mount_point),
+ const_cast<char*>(blk_device), nullptr);
+ if (setexeccon(nullptr)) {
+ PLOG(ERROR) << "Failed to clear setexeccon";
+ return false;
+ }
+ if (mount_rc != 0) {
+ LOG(ERROR) << "fs_mgr_do_mount failed with rc " << mount_rc;
+ return false;
+ }
+ LOG(DEBUG) << "Mounted " << mount_point;
+ return true;
+}
+
+static bool read_key(bool create_if_absent, std::string* key) {
+ auto data_rec = fs_mgr_get_crypt_entry(fstab);
+ if (!data_rec) {
+ LOG(ERROR) << "Failed to get data_rec";
+ return false;
+ }
+ if (!data_rec->key_dir) {
+ LOG(ERROR) << "Failed to get key_dir";
+ return false;
+ }
+ LOG(DEBUG) << "key_dir: " << data_rec->key_dir;
+ if (!android::vold::pathExists(data_rec->key_dir)) {
+ if (mkdir(data_rec->key_dir, 0777) != 0) {
+ PLOG(ERROR) << "Unable to create: " << data_rec->key_dir;
+ return false;
+ }
+ LOG(DEBUG) << "Created: " << data_rec->key_dir;
+ }
+ std::string key_dir = data_rec->key_dir;
+ auto dir = key_dir + "/key";
+ auto temp = key_dir + "/tmp";
+ if (!android::vold::retrieveKey(create_if_absent, dir, temp, key)) return false;
+ return true;
+}
+
+static std::string default_key_params(const std::string& real_blkdev, const std::string& key) {
+ std::string hex_key;
+ if (android::vold::StrToHex(key, hex_key) != android::OK) {
+ LOG(ERROR) << "Failed to turn key to hex";
+ return "";
+ }
+ auto res = std::string() + "AES-256-XTS " + hex_key + " " + real_blkdev + " 0";
+ LOG(DEBUG) << "crypt_params: " << res;
+ return res;
+}
+
+static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t *nr_sec) {
+ AutoCloseFD dev_fd(real_blkdev, O_RDONLY);
+ if (!dev_fd) {
+ PLOG(ERROR) << "Unable to open " << real_blkdev << " to measure size";
+ return false;
+ }
+ unsigned long res;
+ // TODO: should use BLKGETSIZE64
+ get_blkdev_size(dev_fd.get(), &res);
+ if (res == 0) {
+ PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
+ return false;
+ }
+ *nr_sec = res;
+ return true;
+}
+
+static struct dm_ioctl* dm_ioctl_init(char *buffer, size_t buffer_size,
+ const std::string& dm_name) {
+ if (buffer_size < sizeof(dm_ioctl)) {
+ LOG(ERROR) << "dm_ioctl buffer too small";
+ return nullptr;
+ }
+
+ memset(buffer, 0, buffer_size);
+ struct dm_ioctl* io = (struct dm_ioctl*) buffer;
+ io->data_size = buffer_size;
+ io->data_start = sizeof(struct dm_ioctl);
+ io->version[0] = 4;
+ io->version[1] = 0;
+ io->version[2] = 0;
+ io->flags = 0;
+ dm_name.copy(io->name, sizeof(io->name));
+ return io;
+}
+
+static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec,
+ const std::string& target_type, const std::string& crypt_params,
+ std::string* crypto_blkdev) {
+ AutoCloseFD dm_fd("/dev/device-mapper", O_RDWR);
+ if (!dm_fd) {
+ PLOG(ERROR) << "Cannot open device-mapper";
+ return false;
+ }
+ alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
+ auto io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
+ if (!io || ioctl(dm_fd.get(), DM_DEV_CREATE, io) != 0) {
+ PLOG(ERROR) << "Cannot create dm-crypt device " << dm_name;
+ return false;
+ }
+
+ // Get the device status, in particular, the name of its device file
+ io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
+ if (ioctl(dm_fd.get(), DM_DEV_STATUS, io) != 0) {
+ PLOG(ERROR) << "Cannot retrieve dm-crypt device status " << dm_name;
+ return false;
+ }
+ *crypto_blkdev = std::string() + "/dev/block/dm-" + std::to_string(
+ (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00));
+
+ io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
+ unsigned long paramix = io->data_start + sizeof(struct dm_target_spec);
+ unsigned long nullix = paramix + crypt_params.size();
+ unsigned long endix = (nullix + 1 + 7) & 8; // Add room for \0 and align to 8 byte boundary
+
+ if (endix > sizeof(buffer)) {
+ LOG(ERROR) << "crypt_params too big for DM_CRYPT_BUF_SIZE";
+ return false;
+ }
+
+ io->target_count = 1;
+ auto tgt = (struct dm_target_spec *) (buffer + io->data_start);
+ tgt->status = 0;
+ tgt->sector_start = 0;
+ tgt->length = nr_sec;
+ target_type.copy(tgt->target_type, sizeof(tgt->target_type));
+ crypt_params.copy(buffer + paramix, sizeof(buffer) - paramix);
+ buffer[nullix] = '\0';
+ tgt->next = endix;
+
+ for (int i = 0; ; i++) {
+ if (ioctl(dm_fd.get(), DM_TABLE_LOAD, io) == 0) {
+ break;
+ }
+ if (i+1 >= TABLE_LOAD_RETRIES) {
+ PLOG(ERROR) << "DM_TABLE_LOAD ioctl failed";
+ return false;
+ }
+ PLOG(INFO) << "DM_TABLE_LOAD ioctl failed, retrying";
+ usleep(500000);
+ }
+
+ // Resume this device to activate it
+ io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
+ if (ioctl(dm_fd.get(), DM_DEV_SUSPEND, io)) {
+ PLOG(ERROR) << "Cannot resume dm-crypt device " << dm_name;
+ return false;
+ }
+ return true;
+}
+
+#define DATA_PREP_TIMEOUT 1000
+static bool prep_data_fs(void)
+{
+ // NOTE: post_fs_data results in init calling back around to vold, so all
+ // callers to this method must be async
+
+ /* Do the prep of the /data filesystem */
+ property_set("vold.post_fs_data_done", "0");
+ property_set("vold.decrypt", "trigger_post_fs_data");
+ LOG(DEBUG) << "Waiting for post_fs_data_done";
+
+ /* Wait a max of 50 seconds, hopefully it takes much less */
+ for (int i = 0; ; i++) {
+ char p[PROPERTY_VALUE_MAX];
+
+ property_get("vold.post_fs_data_done", p, "0");
+ if (*p == '1') {
+ LOG(INFO) << "Successful data prep";
+ return true;
+ }
+ if (i + 1 == DATA_PREP_TIMEOUT) {
+ LOG(ERROR) << "post_fs_data timed out";
+ return false;
+ }
+ usleep(50000);
+ }
+}
+
+static void async_kick_off() {
+ LOG(DEBUG) << "Asynchronously restarting framework";
+ sleep(2); // TODO: this mirrors cryptfs, but can it be made shorter?
+ property_set("vold.decrypt", "trigger_load_persist_props");
+ if (!prep_data_fs()) return;
+ /* startup service classes main and late_start */
+ property_set("vold.decrypt", "trigger_restart_framework");
+}
+
+bool e4crypt_mount_metadata_encrypted() {
+ LOG(DEBUG) << "e4crypt_mount_default_encrypted";
+ std::string key;
+ if (!read_key(false, &key)) return false;
+ auto data_rec = fs_mgr_get_crypt_entry(fstab);
+ if (!data_rec) {
+ LOG(ERROR) << "Failed to get data_rec";
+ return false;
+ }
+ uint64_t nr_sec;
+ if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
+ std::string crypto_blkdev;
+ if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
+ default_key_params(data_rec->blk_device, key), &crypto_blkdev)) return false;
+ // FIXME handle the corrupt case
+
+ LOG(DEBUG) << "Restarting filesystem for metadata encryption";
+ mount_via_fs_mgr(data_rec->mount_point, crypto_blkdev.c_str());
+ std::thread(&async_kick_off).detach();
+ return true;
+}
+
+bool e4crypt_enable_crypto() {
+ LOG(DEBUG) << "e4crypt_enable_crypto";
+ char encrypted_state[PROPERTY_VALUE_MAX];
+ property_get("ro.crypto.state", encrypted_state, "");
+ if (strcmp(encrypted_state, "")) {
+ LOG(DEBUG) << "e4crypt_enable_crypto got unexpected starting state: " << encrypted_state;
+ return false;
+ }
+
+ std::string key_ref;
+ if (!read_key(true, &key_ref)) return false;
+
+ auto data_rec = fs_mgr_get_crypt_entry(fstab);
+ if (!data_rec) {
+ LOG(ERROR) << "Failed to get data_rec";
+ return false;
+ }
+ uint64_t nr_sec;
+ if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
+
+ std::string crypto_blkdev;
+ if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
+ default_key_params(data_rec->blk_device, key_ref), &crypto_blkdev)) return false;
+
+ LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
+ off64_t size_already_done = 0;
+ auto rc = cryptfs_enable_inplace(const_cast<char *>(crypto_blkdev.c_str()),
+ data_rec->blk_device, nr_sec, &size_already_done, nr_sec, 0);
+ if (rc != 0) {
+ LOG(ERROR) << "Inplace crypto failed with code: " << rc;
+ return false;
+ }
+ if (static_cast<uint64_t>(size_already_done) != nr_sec) {
+ LOG(ERROR) << "Inplace crypto only got up to sector: " << size_already_done;
+ return false;
+ }
+ LOG(INFO) << "Inplace encryption complete";
+
+ property_set("ro.crypto.state", "encrypted");
+ property_set("ro.crypto.type", "file");
+
+ mount_via_fs_mgr(data_rec->mount_point, crypto_blkdev.c_str());
+ property_set("vold.decrypt", "trigger_reset_main");
+ std::thread(&async_kick_off).detach();
+ return true;
+}
diff --git a/MetadataCrypt.h b/MetadataCrypt.h
new file mode 100644
index 0000000..f6634ea
--- /dev/null
+++ b/MetadataCrypt.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _METADATA_CRYPT_H
+#define _METADATA_CRYPT_H
+
+bool e4crypt_mount_metadata_encrypted();
+bool e4crypt_enable_crypto();
+
+#endif
diff --git a/Process.cpp b/Process.cpp
index fd757d5..1c0f504 100644
--- a/Process.cpp
+++ b/Process.cpp
@@ -28,10 +28,17 @@
#include <signal.h>
#define LOG_TAG "ProcessKiller"
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/logging.h>
#include <cutils/log.h>
#include "Process.h"
+using android::base::ReadFileToString;
+using android::base::StringPrintf;
+
int Process::readSymLink(const char *path, char *link, size_t max) {
struct stat s;
int length;
@@ -40,10 +47,10 @@
return 0;
if ((s.st_mode & S_IFMT) != S_IFLNK)
return 0;
-
- // we have a symlink
+
+ // we have a symlink
length = readlink(path, link, max- 1);
- if (length <= 0)
+ if (length <= 0)
return 0;
link[length] = 0;
return 1;
@@ -63,16 +70,9 @@
return 0;
}
-void Process::getProcessName(int pid, char *buffer, size_t max) {
- int fd;
- snprintf(buffer, max, "/proc/%d/cmdline", pid);
- fd = open(buffer, O_RDONLY | O_CLOEXEC);
- if (fd < 0) {
- strcpy(buffer, "???");
- } else {
- int length = read(fd, buffer, max - 1);
- buffer[length] = 0;
- close(fd);
+void Process::getProcessName(int pid, std::string& out_name) {
+ if (!ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &out_name)) {
+ out_name = "???";
}
}
@@ -103,7 +103,7 @@
// append the file name, after truncating to parent directory
path[parent_length] = 0;
- strcat(path, de->d_name);
+ strlcat(path, de->d_name, PATH_MAX);
char link[PATH_MAX];
@@ -189,24 +189,24 @@
while ((de = readdir(dir))) {
int pid = getPid(de->d_name);
- char name[PATH_MAX];
-
if (pid == -1)
continue;
- getProcessName(pid, name, sizeof(name));
+
+ std::string name;
+ getProcessName(pid, name);
char openfile[PATH_MAX];
if (checkFileDescriptorSymLinks(pid, path, openfile, sizeof(openfile))) {
- SLOGE("Process %s (%d) has open file %s", name, pid, openfile);
+ SLOGE("Process %s (%d) has open file %s", name.c_str(), pid, openfile);
} else if (checkFileMaps(pid, path, openfile, sizeof(openfile))) {
- SLOGE("Process %s (%d) has open filemap for %s", name, pid, openfile);
+ SLOGE("Process %s (%d) has open filemap for %s", name.c_str(), pid, openfile);
} else if (checkSymLink(pid, path, "cwd")) {
- SLOGE("Process %s (%d) has cwd within %s", name, pid, path);
+ SLOGE("Process %s (%d) has cwd within %s", name.c_str(), pid, path);
} else if (checkSymLink(pid, path, "root")) {
- SLOGE("Process %s (%d) has chroot within %s", name, pid, path);
+ SLOGE("Process %s (%d) has chroot within %s", name.c_str(), pid, path);
} else if (checkSymLink(pid, path, "exe")) {
- SLOGE("Process %s (%d) has executable path within %s", name, pid, path);
+ SLOGE("Process %s (%d) has executable path within %s", name.c_str(), pid, path);
} else {
continue;
}
diff --git a/Process.h b/Process.h
index 62a9313..4ddbdb9 100644
--- a/Process.h
+++ b/Process.h
@@ -28,7 +28,7 @@
static int checkFileMaps(int pid, const char *path, char *openFilename, size_t max);
static int checkFileDescriptorSymLinks(int pid, const char *mountPoint);
static int checkFileDescriptorSymLinks(int pid, const char *mountPoint, char *openFilename, size_t max);
- static void getProcessName(int pid, char *buffer, size_t max);
+ static void getProcessName(int pid, std::string& out_name);
private:
static int readSymLink(const char *path, char *link, size_t max);
static int pathMatchesMountPoint(const char *path, const char *mountPoint);
diff --git a/Utils.cpp b/Utils.cpp
index 2b1cf63..15b3c0b 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -293,7 +293,7 @@
LOG(ERROR) << "Failed to setexeccon";
abort();
}
- FILE* fp = popen(cmd.c_str(), "r");
+ FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
if (setexeccon(nullptr)) {
LOG(ERROR) << "Failed to setexeccon";
abort();
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index 30914e9..4ba0c36 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -181,7 +181,7 @@
}
*createdDMDevice = true;
} else {
- strcpy(buffer, loopDevice);
+ strlcpy(buffer, loopDevice, len);
*createdDMDevice = false;
}
return 0;
@@ -932,7 +932,7 @@
cleanupDm = true;
} else {
sb.c_cipher = ASEC_SB_C_CIPHER_NONE;
- strcpy(dmDevice, loopDevice);
+ strlcpy(dmDevice, loopDevice, sizeof(dmDevice));
}
/*
@@ -1896,7 +1896,7 @@
// Create a string to compare against that has a trailing slash
int loopDirLen = strlen(VolumeManager::LOOPDIR);
char loopDir[loopDirLen + 2];
- strcpy(loopDir, VolumeManager::LOOPDIR);
+ strlcpy(loopDir, VolumeManager::LOOPDIR, sizeof(loopDir));
loopDir[loopDirLen++] = '/';
loopDir[loopDirLen] = '\0';
diff --git a/cryptfs.cpp b/cryptfs.cpp
index f2f0f18..6319362 100644
--- a/cryptfs.cpp
+++ b/cryptfs.cpp
@@ -59,6 +59,7 @@
#include "Ext4Crypt.h"
#include "f2fs_sparseblock.h"
#include "CheckBattery.h"
+#include "EncryptInplace.h"
#include "Process.h"
#include "Keymaster.h"
#include "android-base/properties.h"
@@ -1725,7 +1726,8 @@
memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
ext_crypt_ftr.fs_size = nr_sec;
ext_crypt_ftr.keysize = keysize;
- strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
+ strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
+ MAX_CRYPTO_TYPE_NAME_LEN);
return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
out_crypto_blkdev, label);
@@ -1978,610 +1980,6 @@
return rc;
}
-#define CRYPT_INPLACE_BUFSIZE 4096
-#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
-#define CRYPT_SECTOR_SIZE 512
-
-/* aligned 32K writes tends to make flash happy.
- * SD card association recommends it.
- */
-#define BLOCKS_AT_A_TIME 8
-
-struct encryptGroupsData
-{
- int realfd;
- int cryptofd;
- off64_t numblocks;
- off64_t one_pct, cur_pct, new_pct;
- off64_t blocks_already_done, tot_numblocks;
- off64_t used_blocks_already_done, tot_used_blocks;
- char* real_blkdev, * crypto_blkdev;
- int count;
- off64_t offset;
- char* buffer;
- off64_t last_written_sector;
- int completed;
- time_t time_started;
- int remaining_time;
-};
-
-static void update_progress(struct encryptGroupsData* data, int is_used)
-{
- data->blocks_already_done++;
-
- if (is_used) {
- data->used_blocks_already_done++;
- }
- if (data->tot_used_blocks) {
- data->new_pct = data->used_blocks_already_done / data->one_pct;
- } else {
- data->new_pct = data->blocks_already_done / data->one_pct;
- }
-
- if (data->new_pct > data->cur_pct) {
- char buf[8];
- data->cur_pct = data->new_pct;
- snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
- property_set("vold.encrypt_progress", buf);
- }
-
- if (data->cur_pct >= 5) {
- struct timespec time_now;
- if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
- SLOGW("Error getting time");
- } else {
- double elapsed_time = difftime(time_now.tv_sec, data->time_started);
- off64_t remaining_blocks = data->tot_used_blocks
- - data->used_blocks_already_done;
- int remaining_time = (int)(elapsed_time * remaining_blocks
- / data->used_blocks_already_done);
-
- // Change time only if not yet set, lower, or a lot higher for
- // best user experience
- if (data->remaining_time == -1
- || remaining_time < data->remaining_time
- || remaining_time > data->remaining_time + 60) {
- char buf[8];
- snprintf(buf, sizeof(buf), "%d", remaining_time);
- property_set("vold.encrypt_time_remaining", buf);
- data->remaining_time = remaining_time;
- }
- }
- }
-}
-
-static void log_progress(struct encryptGroupsData const* data, bool completed)
-{
- // Precondition - if completed data = 0 else data != 0
-
- // Track progress so we can skip logging blocks
- static off64_t offset = -1;
-
- // Need to close existing 'Encrypting from' log?
- if (completed || (offset != -1 && data->offset != offset)) {
- SLOGI("Encrypted to sector %" PRId64,
- offset / info.block_size * CRYPT_SECTOR_SIZE);
- offset = -1;
- }
-
- // Need to start new 'Encrypting from' log?
- if (!completed && offset != data->offset) {
- SLOGI("Encrypting from sector %" PRId64,
- data->offset / info.block_size * CRYPT_SECTOR_SIZE);
- }
-
- // Update offset
- if (!completed) {
- offset = data->offset + (off64_t)data->count * info.block_size;
- }
-}
-
-static int flush_outstanding_data(struct encryptGroupsData* data)
-{
- if (data->count == 0) {
- return 0;
- }
-
- SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
-
- if (pread64(data->realfd, data->buffer,
- info.block_size * data->count, data->offset)
- <= 0) {
- SLOGE("Error reading real_blkdev %s for inplace encrypt",
- data->real_blkdev);
- return -1;
- }
-
- if (pwrite64(data->cryptofd, data->buffer,
- info.block_size * data->count, data->offset)
- <= 0) {
- SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
- data->crypto_blkdev);
- return -1;
- } else {
- log_progress(data, false);
- }
-
- data->count = 0;
- data->last_written_sector = (data->offset + data->count)
- / info.block_size * CRYPT_SECTOR_SIZE - 1;
- return 0;
-}
-
-static int encrypt_groups(struct encryptGroupsData* data)
-{
- unsigned int i;
- u8 *block_bitmap = 0;
- unsigned int block;
- off64_t ret;
- int rc = -1;
-
- data->buffer = (char *)malloc(info.block_size * BLOCKS_AT_A_TIME);
- if (!data->buffer) {
- SLOGE("Failed to allocate crypto buffer");
- goto errout;
- }
-
- block_bitmap = (u8 *)malloc(info.block_size);
- if (!block_bitmap) {
- SLOGE("failed to allocate block bitmap");
- goto errout;
- }
-
- for (i = 0; i < aux_info.groups; ++i) {
- SLOGI("Encrypting group %d", i);
-
- u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
- u32 block_count = std::min(info.blocks_per_group,
- (u32)(aux_info.len_blocks - first_block));
-
- off64_t offset = (u64)info.block_size
- * aux_info.bg_desc[i].bg_block_bitmap;
-
- ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
- if (ret != (int)info.block_size) {
- SLOGE("failed to read all of block group bitmap %d", i);
- goto errout;
- }
-
- offset = (u64)info.block_size * first_block;
-
- data->count = 0;
-
- for (block = 0; block < block_count; block++) {
- int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
- 0 : bitmap_get_bit(block_bitmap, block);
- update_progress(data, used);
- if (used) {
- if (data->count == 0) {
- data->offset = offset;
- }
- data->count++;
- } else {
- if (flush_outstanding_data(data)) {
- goto errout;
- }
- }
-
- offset += info.block_size;
-
- /* Write data if we are aligned or buffer size reached */
- if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
- || data->count == BLOCKS_AT_A_TIME) {
- if (flush_outstanding_data(data)) {
- goto errout;
- }
- }
-
- if (!is_battery_ok_to_continue()) {
- SLOGE("Stopping encryption due to low battery");
- rc = 0;
- goto errout;
- }
-
- }
- if (flush_outstanding_data(data)) {
- goto errout;
- }
- }
-
- data->completed = 1;
- rc = 0;
-
-errout:
- log_progress(0, true);
- free(data->buffer);
- free(block_bitmap);
- return rc;
-}
-
-static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
- char *real_blkdev,
- off64_t size,
- off64_t *size_already_done,
- off64_t tot_size,
- off64_t previously_encrypted_upto)
-{
- u32 i;
- struct encryptGroupsData data;
- int rc; // Can't initialize without causing warning -Wclobbered
- struct timespec time_started = {0};
- int retries = RETRY_MOUNT_ATTEMPTS;
-
- if (previously_encrypted_upto > *size_already_done) {
- SLOGD("Not fast encrypting since resuming part way through");
- return -1;
- }
-
- memset(&data, 0, sizeof(data));
- data.real_blkdev = real_blkdev;
- data.crypto_blkdev = crypto_blkdev;
-
- if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
- SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
- real_blkdev, errno, strerror(errno));
- rc = -1;
- goto errout;
- }
-
- // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
- while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
- if (--retries) {
- SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
- crypto_blkdev, errno, strerror(errno));
- sleep(RETRY_MOUNT_DELAY_SECONDS);
- } else {
- SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
- crypto_blkdev, errno, strerror(errno));
- rc = ENABLE_INPLACE_ERR_DEV;
- goto errout;
- }
- }
-
- if (setjmp(setjmp_env)) {
- SLOGE("Reading ext4 extent caused an exception\n");
- rc = -1;
- goto errout;
- }
-
- if (read_ext(data.realfd, 0) != 0) {
- SLOGE("Failed to read ext4 extent\n");
- rc = -1;
- goto errout;
- }
-
- data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
- data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
- data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
-
- SLOGI("Encrypting ext4 filesystem in place...");
-
- data.tot_used_blocks = data.numblocks;
- for (i = 0; i < aux_info.groups; ++i) {
- data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
- }
-
- data.one_pct = data.tot_used_blocks / 100;
- data.cur_pct = 0;
-
- if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
- SLOGW("Error getting time at start");
- // Note - continue anyway - we'll run with 0
- }
- data.time_started = time_started.tv_sec;
- data.remaining_time = -1;
-
- rc = encrypt_groups(&data);
- if (rc) {
- SLOGE("Error encrypting groups");
- goto errout;
- }
-
- *size_already_done += data.completed ? size : data.last_written_sector;
- rc = 0;
-
-errout:
- close(data.realfd);
- close(data.cryptofd);
-
- return rc;
-}
-
-static void log_progress_f2fs(u64 block, bool completed)
-{
- // Precondition - if completed data = 0 else data != 0
-
- // Track progress so we can skip logging blocks
- static u64 last_block = (u64)-1;
-
- // Need to close existing 'Encrypting from' log?
- if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
- SLOGI("Encrypted to block %" PRId64, last_block);
- last_block = -1;
- }
-
- // Need to start new 'Encrypting from' log?
- if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
- SLOGI("Encrypting from block %" PRId64, block);
- }
-
- // Update offset
- if (!completed) {
- last_block = block;
- }
-}
-
-static int encrypt_one_block_f2fs(u64 pos, void *data)
-{
- struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
-
- priv_dat->blocks_already_done = pos - 1;
- update_progress(priv_dat, 1);
-
- off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
-
- if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
- SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
- return -1;
- }
-
- if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
- SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
- return -1;
- } else {
- log_progress_f2fs(pos, false);
- }
-
- return 0;
-}
-
-static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
- char *real_blkdev,
- off64_t size,
- off64_t *size_already_done,
- off64_t tot_size,
- off64_t previously_encrypted_upto)
-{
- struct encryptGroupsData data;
- struct f2fs_info *f2fs_info = NULL;
- int rc = ENABLE_INPLACE_ERR_OTHER;
- if (previously_encrypted_upto > *size_already_done) {
- SLOGD("Not fast encrypting since resuming part way through");
- return ENABLE_INPLACE_ERR_OTHER;
- }
- memset(&data, 0, sizeof(data));
- data.real_blkdev = real_blkdev;
- data.crypto_blkdev = crypto_blkdev;
- data.realfd = -1;
- data.cryptofd = -1;
- if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
- SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
- real_blkdev);
- goto errout;
- }
- if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
- SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
- crypto_blkdev, errno, strerror(errno));
- rc = ENABLE_INPLACE_ERR_DEV;
- goto errout;
- }
-
- f2fs_info = generate_f2fs_info(data.realfd);
- if (!f2fs_info)
- goto errout;
-
- data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
- data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
- data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
-
- data.tot_used_blocks = get_num_blocks_used(f2fs_info);
-
- data.one_pct = data.tot_used_blocks / 100;
- data.cur_pct = 0;
- data.time_started = time(NULL);
- data.remaining_time = -1;
-
- data.buffer = (char *)malloc(f2fs_info->block_size);
- if (!data.buffer) {
- SLOGE("Failed to allocate crypto buffer");
- goto errout;
- }
-
- data.count = 0;
-
- /* Currently, this either runs to completion, or hits a nonrecoverable error */
- rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
-
- if (rc) {
- SLOGE("Error in running over f2fs blocks");
- rc = ENABLE_INPLACE_ERR_OTHER;
- goto errout;
- }
-
- *size_already_done += size;
- rc = 0;
-
-errout:
- if (rc)
- SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
-
- log_progress_f2fs(0, true);
- free(f2fs_info);
- free(data.buffer);
- close(data.realfd);
- close(data.cryptofd);
-
- return rc;
-}
-
-static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
- off64_t size, off64_t *size_already_done,
- off64_t tot_size,
- off64_t previously_encrypted_upto)
-{
- int realfd, cryptofd;
- char *buf[CRYPT_INPLACE_BUFSIZE];
- int rc = ENABLE_INPLACE_ERR_OTHER;
- off64_t numblocks, i, remainder;
- off64_t one_pct, cur_pct, new_pct;
- off64_t blocks_already_done, tot_numblocks;
-
- if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
- SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
- return ENABLE_INPLACE_ERR_OTHER;
- }
-
- if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
- SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
- crypto_blkdev, errno, strerror(errno));
- close(realfd);
- return ENABLE_INPLACE_ERR_DEV;
- }
-
- /* This is pretty much a simple loop of reading 4K, and writing 4K.
- * The size passed in is the number of 512 byte sectors in the filesystem.
- * So compute the number of whole 4K blocks we should read/write,
- * and the remainder.
- */
- numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
- remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
- tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
- blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
-
- SLOGE("Encrypting filesystem in place...");
-
- i = previously_encrypted_upto + 1 - *size_already_done;
-
- if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
- SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
- goto errout;
- }
-
- if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
- SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
- goto errout;
- }
-
- for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
- if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
- SLOGE("Error reading initial sectors from real_blkdev %s for "
- "inplace encrypt\n", crypto_blkdev);
- goto errout;
- }
- if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
- SLOGE("Error writing initial sectors to crypto_blkdev %s for "
- "inplace encrypt\n", crypto_blkdev);
- goto errout;
- } else {
- SLOGI("Encrypted 1 block at %" PRId64, i);
- }
- }
-
- one_pct = tot_numblocks / 100;
- cur_pct = 0;
- /* process the majority of the filesystem in blocks */
- for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
- new_pct = (i + blocks_already_done) / one_pct;
- if (new_pct > cur_pct) {
- char buf[8];
-
- cur_pct = new_pct;
- snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
- property_set("vold.encrypt_progress", buf);
- }
- if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
- SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
- goto errout;
- }
- if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
- SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
- goto errout;
- } else {
- SLOGD("Encrypted %d block at %" PRId64,
- CRYPT_SECTORS_PER_BUFSIZE,
- i * CRYPT_SECTORS_PER_BUFSIZE);
- }
-
- if (!is_battery_ok_to_continue()) {
- SLOGE("Stopping encryption due to low battery");
- *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
- rc = 0;
- goto errout;
- }
- }
-
- /* Do any remaining sectors */
- for (i=0; i<remainder; i++) {
- if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
- SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
- goto errout;
- }
- if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
- SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
- goto errout;
- } else {
- SLOGI("Encrypted 1 block at next location");
- }
- }
-
- *size_already_done += size;
- rc = 0;
-
-errout:
- close(realfd);
- close(cryptofd);
-
- return rc;
-}
-
-/* returns on of the ENABLE_INPLACE_* return codes */
-static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
- off64_t size, off64_t *size_already_done,
- off64_t tot_size,
- off64_t previously_encrypted_upto)
-{
- int rc_ext4, rc_f2fs, rc_full;
- if (previously_encrypted_upto) {
- SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
- }
-
- if (*size_already_done + size < previously_encrypted_upto) {
- *size_already_done += size;
- return 0;
- }
-
- /* TODO: identify filesystem type.
- * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
- * then we will drop down to cryptfs_enable_inplace_f2fs.
- * */
- if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
- size, size_already_done,
- tot_size, previously_encrypted_upto)) == 0) {
- return 0;
- }
- SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
-
- if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
- size, size_already_done,
- tot_size, previously_encrypted_upto)) == 0) {
- return 0;
- }
- SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
-
- rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
- size, size_already_done, tot_size,
- previously_encrypted_upto);
- SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
-
- /* Hack for b/17898962, the following is the symptom... */
- if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
- && rc_f2fs == ENABLE_INPLACE_ERR_DEV
- && rc_full == ENABLE_INPLACE_ERR_DEV) {
- return ENABLE_INPLACE_ERR_DEV;
- }
- return rc_full;
-}
-
#define CRYPTO_ENABLE_WIPE 1
#define CRYPTO_ENABLE_INPLACE 2
@@ -3496,11 +2894,6 @@
}
}
-int cryptfs_enable_file()
-{
- return e4crypt_initialize_global_de();
-}
-
int cryptfs_isConvertibleToFBE()
{
struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
diff --git a/cryptfs.h b/cryptfs.h
index 352a576..d20d96d 100644
--- a/cryptfs.h
+++ b/cryptfs.h
@@ -237,7 +237,6 @@
int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
const unsigned char* key, int keysize, char* out_crypto_blkdev);
int cryptfs_revert_ext_volume(const char* label);
- int cryptfs_enable_file();
int cryptfs_getfield(const char *fieldname, char *value, int len);
int cryptfs_setfield(const char *fieldname, const char *value);
int cryptfs_mount_default_encrypted(void);
diff --git a/tests/Android.mk b/tests/Android.mk
index 416e621..4b6573e 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -8,8 +8,32 @@
system/core/fs_mgr/include
LOCAL_STATIC_LIBRARIES := libselinux libvold liblog libcrypto
+
LOCAL_SRC_FILES := VolumeManager_test.cpp
LOCAL_MODULE := vold_tests
LOCAL_MODULE_TAGS := eng tests
include $(BUILD_NATIVE_TEST)
+
+include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
+# LOCAL_C_INCLUDES := \
+ system/core/fs_mgr/include
+
+LOCAL_STATIC_LIBRARIES := libselinux libvold liblog libcrypto
+LOCAL_SHARED_LIBRARIES := \
+ libutils \
+ libbase \
+ libhardware \
+ libhardware_legacy \
+ libhwbinder \
+ libhidlbase \
+ libkeystore_binder \
+ android.hardware.keymaster@3.0
+
+LOCAL_SRC_FILES := CryptfsScryptHidlizationEquivalence_test.cpp
+LOCAL_MODULE := vold_cryptfs_scrypt_hidlization_equivalence_test
+LOCAL_MODULE_TAGS := eng tests
+
+include $(BUILD_NATIVE_TEST)
diff --git a/tests/CryptfsScryptHidlizationEquivalence_test.cpp b/tests/CryptfsScryptHidlizationEquivalence_test.cpp
new file mode 100644
index 0000000..91ddb2b
--- /dev/null
+++ b/tests/CryptfsScryptHidlizationEquivalence_test.cpp
@@ -0,0 +1,475 @@
+/*
+**
+** Copyright 2017, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+** http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#define LOG_TAG "scrypt_test"
+#include <log/log.h>
+
+#include <hardware/keymaster0.h>
+#include <hardware/keymaster1.h>
+#include <cstring>
+#include <gtest/gtest.h>
+
+#include "../cryptfs.h"
+#include "../Keymaster.h"
+
+#ifdef CONFIG_HW_DISK_ENCRYPTION
+#include "cryptfs_hw.h"
+#endif
+
+#define min(a, b) ((a) < (b) ? (a) : (b))
+
+/* Maximum allowed keymaster blob size. */
+#define KEYMASTER_BLOB_SIZE 2048
+
+/* Key Derivation Function algorithms */
+#define KDF_PBKDF2 1
+#define KDF_SCRYPT 2
+/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
+#define KDF_SCRYPT_KEYMASTER 5
+
+#define KEY_LEN_BYTES 16
+
+#define DEFAULT_PASSWORD "default_password"
+
+#define RSA_KEY_SIZE 2048
+#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
+#define RSA_EXPONENT 0x10001
+#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
+
+static int keymaster_init(keymaster0_device_t **keymaster0_dev,
+ keymaster1_device_t **keymaster1_dev)
+{
+ int rc;
+
+ const hw_module_t* mod;
+ rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
+ if (rc) {
+ ALOGE("could not find any keystore module");
+ goto err;
+ }
+
+ SLOGI("keymaster module name is %s", mod->name);
+ SLOGI("keymaster version is %d", mod->module_api_version);
+
+ *keymaster0_dev = NULL;
+ *keymaster1_dev = NULL;
+ if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
+ SLOGI("Found keymaster1 module, using keymaster1 API.");
+ rc = keymaster1_open(mod, keymaster1_dev);
+ } else {
+ SLOGI("Found keymaster0 module, using keymaster0 API.");
+ rc = keymaster0_open(mod, keymaster0_dev);
+ }
+
+ if (rc) {
+ ALOGE("could not open keymaster device in %s (%s)",
+ KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
+ goto err;
+ }
+
+ return 0;
+
+err:
+ *keymaster0_dev = NULL;
+ *keymaster1_dev = NULL;
+ return rc;
+}
+
+/* Should we use keymaster? */
+static int keymaster_check_compatibility_old()
+{
+ keymaster0_device_t *keymaster0_dev = 0;
+ keymaster1_device_t *keymaster1_dev = 0;
+ int rc = 0;
+
+ if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
+ SLOGE("Failed to init keymaster");
+ rc = -1;
+ goto out;
+ }
+
+ if (keymaster1_dev) {
+ rc = 1;
+ goto out;
+ }
+
+ if (!keymaster0_dev || !keymaster0_dev->common.module) {
+ rc = -1;
+ goto out;
+ }
+
+ // TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
+ // should work.
+ if (keymaster0_dev->common.module->module_api_version
+ < KEYMASTER_MODULE_API_VERSION_0_3) {
+ rc = 0;
+ goto out;
+ }
+
+ if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
+ (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
+ rc = 1;
+ }
+
+out:
+ if (keymaster1_dev) {
+ keymaster1_close(keymaster1_dev);
+ }
+ if (keymaster0_dev) {
+ keymaster0_close(keymaster0_dev);
+ }
+ return rc;
+}
+
+/* Create a new keymaster key and store it in this footer */
+static int keymaster_create_key_old(struct crypt_mnt_ftr *ftr)
+{
+ uint8_t* key = 0;
+ keymaster0_device_t *keymaster0_dev = 0;
+ keymaster1_device_t *keymaster1_dev = 0;
+
+ if (ftr->keymaster_blob_size) {
+ SLOGI("Already have key");
+ return 0;
+ }
+
+ if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
+ SLOGE("Failed to init keymaster");
+ return -1;
+ }
+
+ int rc = 0;
+ size_t key_size = 0;
+ if (keymaster1_dev) {
+ keymaster_key_param_t params[] = {
+ /* Algorithm & size specifications. Stick with RSA for now. Switch to AES later. */
+ keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
+ keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
+ keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
+
+ /* The only allowed purpose for this key is signing. */
+ keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
+
+ /* Padding & digest specifications. */
+ keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
+ keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
+
+ /* Require that the key be usable in standalone mode. File system isn't available. */
+ keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
+
+ /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
+ keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
+
+ /* Rate-limit key usage attempts, to rate-limit brute force */
+ keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
+ };
+ keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
+ keymaster_key_blob_t key_blob;
+ keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, ¶m_set,
+ &key_blob,
+ NULL /* characteristics */);
+ if (error != KM_ERROR_OK) {
+ SLOGE("Failed to generate keymaster1 key, error %d", error);
+ rc = -1;
+ goto out;
+ }
+
+ key = (uint8_t*)key_blob.key_material;
+ key_size = key_blob.key_material_size;
+ }
+ else if (keymaster0_dev) {
+ keymaster_rsa_keygen_params_t params;
+ memset(¶ms, '\0', sizeof(params));
+ params.public_exponent = RSA_EXPONENT;
+ params.modulus_size = RSA_KEY_SIZE;
+
+ if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, ¶ms,
+ &key, &key_size)) {
+ SLOGE("Failed to generate keypair");
+ rc = -1;
+ goto out;
+ }
+ } else {
+ SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
+ rc = -1;
+ goto out;
+ }
+
+ if (key_size > KEYMASTER_BLOB_SIZE) {
+ SLOGE("Keymaster key too large for crypto footer");
+ rc = -1;
+ goto out;
+ }
+
+ memcpy(ftr->keymaster_blob, key, key_size);
+ ftr->keymaster_blob_size = key_size;
+
+out:
+ if (keymaster0_dev)
+ keymaster0_close(keymaster0_dev);
+ if (keymaster1_dev)
+ keymaster1_close(keymaster1_dev);
+ free(key);
+ return rc;
+}
+
+/* This signs the given object using the keymaster key. */
+static int keymaster_sign_object_old(struct crypt_mnt_ftr *ftr,
+ const unsigned char *object,
+ const size_t object_size,
+ unsigned char **signature,
+ size_t *signature_size)
+{
+ int rc = 0;
+ keymaster0_device_t *keymaster0_dev = 0;
+ keymaster1_device_t *keymaster1_dev = 0;
+
+ unsigned char to_sign[RSA_KEY_SIZE_BYTES];
+ size_t to_sign_size = sizeof(to_sign);
+ memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
+
+ if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
+ SLOGE("Failed to init keymaster");
+ rc = -1;
+ goto out;
+ }
+
+ // To sign a message with RSA, the message must satisfy two
+ // constraints:
+ //
+ // 1. The message, when interpreted as a big-endian numeric value, must
+ // be strictly less than the public modulus of the RSA key. Note
+ // that because the most significant bit of the public modulus is
+ // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
+ // key), an n-bit message with most significant bit 0 always
+ // satisfies this requirement.
+ //
+ // 2. The message must have the same length in bits as the public
+ // modulus of the RSA key. This requirement isn't mathematically
+ // necessary, but is necessary to ensure consistency in
+ // implementations.
+ switch (ftr->kdf_type) {
+ case KDF_SCRYPT_KEYMASTER:
+ // This ensures the most significant byte of the signed message
+ // is zero. We could have zero-padded to the left instead, but
+ // this approach is slightly more robust against changes in
+ // object size. However, it's still broken (but not unusably
+ // so) because we really should be using a proper deterministic
+ // RSA padding function, such as PKCS1.
+ memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
+ SLOGI("Signing safely-padded object");
+ break;
+ default:
+ SLOGE("Unknown KDF type %d", ftr->kdf_type);
+ rc = -1;
+ goto out;
+ }
+
+ if (keymaster0_dev) {
+ keymaster_rsa_sign_params_t params;
+ params.digest_type = DIGEST_NONE;
+ params.padding_type = PADDING_NONE;
+
+ rc = keymaster0_dev->sign_data(keymaster0_dev,
+ ¶ms,
+ ftr->keymaster_blob,
+ ftr->keymaster_blob_size,
+ to_sign,
+ to_sign_size,
+ signature,
+ signature_size);
+ goto out;
+ } else if (keymaster1_dev) {
+ keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
+ keymaster_key_param_t params[] = {
+ keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
+ keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
+ };
+ keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
+ keymaster_operation_handle_t op_handle;
+ keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
+ ¶m_set, NULL /* out_params */,
+ &op_handle);
+ if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
+ // Key usage has been rate-limited. Wait a bit and try again.
+ sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
+ error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
+ ¶m_set, NULL /* out_params */,
+ &op_handle);
+ }
+ if (error != KM_ERROR_OK) {
+ SLOGE("Error starting keymaster signature transaction: %d", error);
+ rc = -1;
+ goto out;
+ }
+
+ keymaster_blob_t input = { to_sign, to_sign_size };
+ size_t input_consumed;
+ error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
+ &input, &input_consumed, NULL /* out_params */,
+ NULL /* output */);
+ if (error != KM_ERROR_OK) {
+ SLOGE("Error sending data to keymaster signature transaction: %d", error);
+ rc = -1;
+ goto out;
+ }
+ if (input_consumed != to_sign_size) {
+ // This should never happen. If it does, it's a bug in the keymaster implementation.
+ SLOGE("Keymaster update() did not consume all data.");
+ keymaster1_dev->abort(keymaster1_dev, op_handle);
+ rc = -1;
+ goto out;
+ }
+
+ keymaster_blob_t tmp_sig;
+ error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
+ NULL /* verify signature */, NULL /* out_params */,
+ &tmp_sig);
+ if (error != KM_ERROR_OK) {
+ SLOGE("Error finishing keymaster signature transaction: %d", error);
+ rc = -1;
+ goto out;
+ }
+
+ *signature = (uint8_t*)tmp_sig.data;
+ *signature_size = tmp_sig.data_length;
+ } else {
+ SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
+ rc = -1;
+ goto out;
+ }
+
+ out:
+ if (keymaster1_dev)
+ keymaster1_close(keymaster1_dev);
+ if (keymaster0_dev)
+ keymaster0_close(keymaster0_dev);
+
+ return rc;
+}
+
+
+/* Should we use keymaster? */
+static int keymaster_check_compatibility_new()
+{
+ return keymaster_compatibility_cryptfs_scrypt();
+}
+
+/* Create a new keymaster key and store it in this footer */
+static int keymaster_create_key_new(struct crypt_mnt_ftr *ftr)
+{
+ if (ftr->keymaster_blob_size) {
+ SLOGI("Already have key");
+ return 0;
+ }
+
+ int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
+ KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
+ &ftr->keymaster_blob_size);
+ if (rc) {
+ if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
+ SLOGE("Keymaster key blob to large)");
+ ftr->keymaster_blob_size = 0;
+ }
+ SLOGE("Failed to generate keypair");
+ return -1;
+ }
+ return 0;
+}
+
+/* This signs the given object using the keymaster key. */
+static int keymaster_sign_object_new(struct crypt_mnt_ftr *ftr,
+ const unsigned char *object,
+ const size_t object_size,
+ unsigned char **signature,
+ size_t *signature_size)
+{
+ unsigned char to_sign[RSA_KEY_SIZE_BYTES];
+ size_t to_sign_size = sizeof(to_sign);
+ memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
+
+ // To sign a message with RSA, the message must satisfy two
+ // constraints:
+ //
+ // 1. The message, when interpreted as a big-endian numeric value, must
+ // be strictly less than the public modulus of the RSA key. Note
+ // that because the most significant bit of the public modulus is
+ // guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
+ // key), an n-bit message with most significant bit 0 always
+ // satisfies this requirement.
+ //
+ // 2. The message must have the same length in bits as the public
+ // modulus of the RSA key. This requirement isn't mathematically
+ // necessary, but is necessary to ensure consistency in
+ // implementations.
+ switch (ftr->kdf_type) {
+ case KDF_SCRYPT_KEYMASTER:
+ // This ensures the most significant byte of the signed message
+ // is zero. We could have zero-padded to the left instead, but
+ // this approach is slightly more robust against changes in
+ // object size. However, it's still broken (but not unusably
+ // so) because we really should be using a proper deterministic
+ // RSA padding function, such as PKCS1.
+ memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
+ SLOGI("Signing safely-padded object");
+ break;
+ default:
+ SLOGE("Unknown KDF type %d", ftr->kdf_type);
+ return -1;
+ }
+ return keymaster_sign_object_for_cryptfs_scrypt(ftr->keymaster_blob, ftr->keymaster_blob_size,
+ KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign, to_sign_size, signature, signature_size);
+}
+
+namespace android {
+
+class CryptFsTest : public testing::Test {
+protected:
+ virtual void SetUp() {
+ }
+
+ virtual void TearDown() {
+ }
+};
+
+TEST_F(CryptFsTest, ScryptHidlizationEquivalenceTest) {
+ crypt_mnt_ftr ftr;
+ ftr.kdf_type = KDF_SCRYPT_KEYMASTER;
+ ftr.keymaster_blob_size = 0;
+
+ ASSERT_EQ(0, keymaster_create_key_old(&ftr));
+
+ uint8_t *sig1 = nullptr;
+ uint8_t *sig2 = nullptr;
+ size_t sig_size1 = 123456789;
+ size_t sig_size2 = 123456789;
+ uint8_t object[] = "the object";
+
+ ASSERT_EQ(1, keymaster_check_compatibility_old());
+ ASSERT_EQ(1, keymaster_check_compatibility_new());
+ ASSERT_EQ(0, keymaster_sign_object_old(&ftr, object, 10, &sig1, &sig_size1));
+ ASSERT_EQ(0, keymaster_sign_object_new(&ftr, object, 10, &sig2, &sig_size2));
+
+ ASSERT_EQ(sig_size1, sig_size2);
+ ASSERT_NE(nullptr, sig1);
+ ASSERT_NE(nullptr, sig2);
+ EXPECT_EQ(0, memcmp(sig1, sig2, sig_size1));
+ free(sig1);
+ free(sig2);
+}
+
+}