[automerger skipped] Block and wait for /dev/block/loop<N> to appear in case it was created asynchronously. am: 5ba8aeaa80 -s ours
am skip reason: Change-Id Id8616804bba622226ca21b8eff0d3eb577b4b7e0 with SHA-1 1dd5c4f787 is in history
Change-Id: I30e748f7983e661ba2abd9bbd2ec12dc453b1eb1
diff --git a/.clang-format b/.clang-format
deleted file mode 100644
index ae4a451..0000000
--- a/.clang-format
+++ /dev/null
@@ -1,11 +0,0 @@
-BasedOnStyle: Google
-AccessModifierOffset: -2
-AllowShortFunctionsOnASingleLine: Inline
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 4
-PointerAlignment: Left
-TabWidth: 4
-UseTab: Never
-PenaltyExcessCharacter: 32
diff --git a/.clang-format b/.clang-format
new file mode 120000
index 0000000..ddcf5a2
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1 @@
+../../build/soong/scripts/system-clang-format
\ No newline at end of file
diff --git a/Android.bp b/Android.bp
index 1045dc2..81a2f0f 100644
--- a/Android.bp
+++ b/Android.bp
@@ -30,6 +30,8 @@
static_libs: [
"libavb",
"libbootloader_message",
+ "libdm",
+ "libext2_uuid",
"libfec",
"libfec_rs",
"libfs_avb",
@@ -41,6 +43,7 @@
shared_libs: [
"android.hardware.keymaster@3.0",
"android.hardware.keymaster@4.0",
+ "android.hardware.keymaster@4.1",
"android.hardware.boot@1.0",
"libbase",
"libbinder",
@@ -50,12 +53,12 @@
"libdiskconfig",
"libext4_utils",
"libf2fs_sparseblock",
- "libfscrypt",
"libhardware",
"libhardware_legacy",
+ "libincfs",
"libhidlbase",
- "libhwbinder",
"libkeymaster4support",
+ "libkeymaster4_1support",
"libkeyutils",
"liblog",
"liblogwrap",
@@ -78,13 +81,20 @@
],
aidl: {
local_include_dirs: ["binder"],
- include_dirs: ["frameworks/native/aidl/binder"],
+ include_dirs: [
+ "frameworks/native/aidl/binder",
+ "frameworks/base/core/java",
+ ],
export_aidl_headers: true,
},
+ whole_static_libs: [
+ "libincremental_aidl-cpp",
+ ],
}
cc_library_headers {
name: "libvold_headers",
+ recovery_available: true,
export_include_dirs: ["."],
}
@@ -101,6 +111,7 @@
"Benchmark.cpp",
"CheckEncryption.cpp",
"Checkpoint.cpp",
+ "CryptoType.cpp",
"Devmapper.cpp",
"EncryptInplace.cpp",
"FileDeviceUtils.cpp",
@@ -119,6 +130,7 @@
"ScryptParameters.cpp",
"Utils.cpp",
"VoldNativeService.cpp",
+ "VoldNativeServiceValidation.cpp",
"VoldUtil.cpp",
"VolumeManager.cpp",
"cryptfs.cpp",
@@ -131,8 +143,9 @@
"model/ObbVolume.cpp",
"model/PrivateVolume.cpp",
"model/PublicVolume.cpp",
- "model/VolumeBase.cpp",
"model/StubVolume.cpp",
+ "model/VolumeBase.cpp",
+ "model/VolumeEncryption.cpp",
],
product_variables: {
arc: {
@@ -189,7 +202,6 @@
shared_libs: [
"android.hardware.health.storage@1.0",
- "libhidltransport",
],
}
@@ -224,11 +236,12 @@
"android.hardware.keymaster@3.0",
"android.hardware.keymaster@4.0",
+ "android.hardware.keymaster@4.1",
"libhardware",
"libhardware_legacy",
"libhidlbase",
- "libhwbinder",
"libkeymaster4support",
+ "libkeymaster4_1support",
],
}
@@ -267,6 +280,5 @@
"binder/android/os/IVoldListener.aidl",
"binder/android/os/IVoldTaskListener.aidl",
],
+ path: "binder",
}
-
-subdirs = ["tests"]
diff --git a/Benchmark.cpp b/Benchmark.cpp
index b0a3b85..0770da7 100644
--- a/Benchmark.cpp
+++ b/Benchmark.cpp
@@ -23,8 +23,8 @@
#include <android-base/logging.h>
#include <cutils/iosched_policy.h>
-#include <hardware_legacy/power.h>
#include <private/android_filesystem_config.h>
+#include <wakelock/wakelock.h>
#include <thread>
@@ -181,7 +181,7 @@
void Benchmark(const std::string& path,
const android::sp<android::os::IVoldTaskListener>& listener) {
std::lock_guard<std::mutex> lock(kBenchmarkLock);
- acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+ android::wakelock::WakeLock wl{kWakeLock};
PerformanceBoost boost;
android::os::PersistableBundle extras;
@@ -190,8 +190,6 @@
if (listener) {
listener->onFinished(res, extras);
}
-
- release_wake_lock(kWakeLock);
}
} // namespace vold
diff --git a/Checkpoint.cpp b/Checkpoint.cpp
index 3f688f8..df5fc88 100644
--- a/Checkpoint.cpp
+++ b/Checkpoint.cpp
@@ -61,6 +61,16 @@
namespace {
const std::string kMetadataCPFile = "/metadata/vold/checkpoint";
+binder::Status error(const std::string& msg) {
+ PLOG(ERROR) << msg;
+ return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
+}
+
+binder::Status error(int error, const std::string& msg) {
+ LOG(ERROR) << msg;
+ return binder::Status::fromServiceSpecificError(error, String8(msg.c_str()));
+}
+
bool setBowState(std::string const& block_device, std::string const& state) {
std::string bow_device = fs_mgr_find_bow_device(block_device);
if (bow_device.empty()) return false;
@@ -112,7 +122,11 @@
}
Status cp_startCheckpoint(int retry) {
- if (retry < -1) return Status::fromExceptionCode(EINVAL, "Retry count must be more than -1");
+ bool result;
+ if (!cp_supportsCheckpoint(result).isOk() || !result)
+ return error(ENOTSUP, "Checkpoints not supported");
+
+ if (retry < -1) return error(EINVAL, "Retry count must be more than -1");
std::string content = std::to_string(retry + 1);
if (retry == -1) {
sp<IBootControl> module = IBootControl::getService();
@@ -123,16 +137,24 @@
}
}
if (!android::base::WriteStringToFile(content, kMetadataCPFile))
- return Status::fromExceptionCode(errno, "Failed to write checkpoint file");
+ return error("Failed to write checkpoint file");
return Status::ok();
}
namespace {
volatile bool isCheckpointing = false;
+
+volatile bool needsCheckpointWasCalled = false;
+
+// Protects isCheckpointing, needsCheckpointWasCalled and code that makes decisions based on status
+// of isCheckpointing
+std::mutex isCheckpointingLock;
}
Status cp_commitChanges() {
+ std::lock_guard<std::mutex> lock(isCheckpointingLock);
+
if (!isCheckpointing) {
return Status::ok();
}
@@ -145,11 +167,13 @@
if (module) {
CommandResult cr;
module->markBootSuccessful([&cr](CommandResult result) { cr = result; });
- if (!cr.success) {
- std::string msg = "Error marking booted successfully: " + std::string(cr.errMsg);
- return Status::fromExceptionCode(EINVAL, String8(msg.c_str()));
- }
+ if (!cr.success)
+ return error(EINVAL, "Error marking booted successfully: " + std::string(cr.errMsg));
LOG(INFO) << "Marked slot as booted successfully.";
+ // Clears the warm reset flag for next reboot.
+ if (!SetProperty("ota.warm_reset", "0")) {
+ LOG(WARNING) << "Failed to reset the warm reset flag";
+ }
}
// Must take action for list of mounted checkpointed things here
// To do this, we walk the list of mounted file systems.
@@ -159,7 +183,7 @@
Fstab mounts;
if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
- return Status::fromExceptionCode(EINVAL, "Failed to get /proc/mounts");
+ return error(EINVAL, "Failed to get /proc/mounts");
}
// Walk mounted file systems
@@ -172,19 +196,20 @@
std::string options = mount_rec.fs_options + ",checkpoint=enable";
if (mount(mount_rec.blk_device.c_str(), mount_rec.mount_point.c_str(), "none",
MS_REMOUNT | fstab_rec->flags, options.c_str())) {
- return Status::fromExceptionCode(EINVAL, "Failed to remount");
+ return error(EINVAL, "Failed to remount");
}
}
} else if (fstab_rec->fs_mgr_flags.checkpoint_blk) {
if (!setBowState(mount_rec.blk_device, "2"))
- return Status::fromExceptionCode(EINVAL, "Failed to set bow state");
+ return error(EINVAL, "Failed to set bow state");
}
}
SetProperty("vold.checkpoint_committed", "1");
LOG(INFO) << "Checkpoint has been committed.";
isCheckpointing = false;
if (!android::base::RemoveFileIfExists(kMetadataCPFile, &err_str))
- return Status::fromExceptionCode(errno, err_str.c_str());
+ return error(err_str.c_str());
+
return Status::ok();
}
@@ -244,10 +269,11 @@
}
bool cp_needsCheckpoint() {
+ std::lock_guard<std::mutex> lock(isCheckpointingLock);
+
// Make sure we only return true during boot. See b/138952436 for discussion
- static bool called_once = false;
- if (called_once) return isCheckpointing;
- called_once = true;
+ if (needsCheckpointWasCalled) return isCheckpointing;
+ needsCheckpointWasCalled = true;
bool ret;
std::string content;
@@ -294,13 +320,13 @@
uint64_t free_bytes = 0;
if (is_fs_cp) {
statvfs(mnt_pnt.c_str(), &data);
- free_bytes = data.f_bavail * data.f_frsize;
+ free_bytes = ((uint64_t) data.f_bavail) * data.f_frsize;
} else {
std::string bow_device = fs_mgr_find_bow_device(blk_device);
if (!bow_device.empty()) {
std::string content;
if (android::base::ReadFileToString(bow_device + "/bow/free", &content)) {
- free_bytes = std::strtoul(content.c_str(), NULL, 10);
+ free_bytes = std::strtoull(content.c_str(), NULL, 10);
}
}
}
@@ -324,13 +350,14 @@
Status cp_prepareCheckpoint() {
// Log to notify CTS - see b/137924328 for context
LOG(INFO) << "cp_prepareCheckpoint called";
+ std::lock_guard<std::mutex> lock(isCheckpointingLock);
if (!isCheckpointing) {
return Status::ok();
}
Fstab mounts;
if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
- return Status::fromExceptionCode(EINVAL, "Failed to get /proc/mounts");
+ return error(EINVAL, "Failed to get /proc/mounts");
}
for (const auto& mount_rec : mounts) {
@@ -590,10 +617,7 @@
LOG(INFO) << action << " checkpoint on " << blockDevice;
base::unique_fd device_fd(open(blockDevice.c_str(), O_RDWR | O_CLOEXEC));
- if (device_fd < 0) {
- PLOG(ERROR) << "Cannot open " << blockDevice;
- return Status::fromExceptionCode(errno, ("Cannot open " + blockDevice).c_str());
- }
+ if (device_fd < 0) return error("Cannot open " + blockDevice);
log_sector_v1_0 original_ls;
read(device_fd, reinterpret_cast<char*>(&original_ls), sizeof(original_ls));
@@ -601,8 +625,7 @@
validating = false;
action = "Restoring";
} else if (original_ls.magic != kMagic) {
- LOG(ERROR) << "No magic";
- return Status::fromExceptionCode(EINVAL, "No magic");
+ return error(EINVAL, "No magic");
}
LOG(INFO) << action << " " << original_ls.sequence << " log sectors";
@@ -616,23 +639,18 @@
used_sectors[0] = false;
if (ls.magic != kMagic && (ls.magic != kPartialRestoreMagic || validating)) {
- LOG(ERROR) << "No magic!";
- status = Status::fromExceptionCode(EINVAL, "No magic");
+ status = error(EINVAL, "No magic");
break;
}
if (ls.block_size != original_ls.block_size) {
- LOG(ERROR) << "Block size mismatch!";
- status = Status::fromExceptionCode(EINVAL, "Block size mismatch");
+ status = error(EINVAL, "Block size mismatch");
break;
}
if ((int)ls.sequence != sequence) {
- LOG(ERROR) << "Expecting log sector " << sequence << " but got " << ls.sequence;
- status = Status::fromExceptionCode(
- EINVAL, ("Expecting log sector " + std::to_string(sequence) + " but got " +
- std::to_string(ls.sequence))
- .c_str());
+ status = error(EINVAL, "Expecting log sector " + std::to_string(sequence) +
+ " but got " + std::to_string(ls.sequence));
break;
}
@@ -653,8 +671,7 @@
}
if (le->checksum && checksum != le->checksum) {
- LOG(ERROR) << "Checksums don't match " << std::hex << checksum;
- status = Status::fromExceptionCode(EINVAL, "Checksums don't match");
+ status = error(EINVAL, "Checksums don't match");
break;
}
@@ -664,8 +681,7 @@
restoreSector(device_fd, used_sectors, ls_buffer, le, buffer);
restore_count++;
if (restore_limit && restore_count >= restore_limit) {
- LOG(WARNING) << "Hit the test limit";
- status = Status::fromExceptionCode(EAGAIN, "Hit the test limit");
+ status = error(EAGAIN, "Hit the test limit");
break;
}
}
@@ -703,23 +719,26 @@
// If the file doesn't exist, we aren't managing a checkpoint retry counter
if (result != 0) return Status::ok();
- if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) {
- PLOG(ERROR) << "Failed to read checkpoint file";
- return Status::fromExceptionCode(errno, "Failed to read checkpoint file");
- }
+ if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent))
+ return error("Failed to read checkpoint file");
std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" "));
if (!android::base::ParseInt(retryContent, &retry))
- return Status::fromExceptionCode(EINVAL, "Could not parse retry count");
+ return error(EINVAL, "Could not parse retry count");
if (retry > 0) {
retry--;
newContent = std::to_string(retry);
if (!android::base::WriteStringToFile(newContent, kMetadataCPFile))
- return Status::fromExceptionCode(errno, "Could not write checkpoint file");
+ return error("Could not write checkpoint file");
}
return Status::ok();
}
+void cp_resetCheckpoint() {
+ std::lock_guard<std::mutex> lock(isCheckpointingLock);
+ needsCheckpointWasCalled = false;
+}
+
} // namespace vold
} // namespace android
diff --git a/Checkpoint.h b/Checkpoint.h
index 63ead83..c1fb2b7 100644
--- a/Checkpoint.h
+++ b/Checkpoint.h
@@ -45,6 +45,7 @@
android::binder::Status cp_markBootAttempt();
+void cp_resetCheckpoint();
} // namespace vold
} // namespace android
diff --git a/CryptoType.cpp b/CryptoType.cpp
new file mode 100644
index 0000000..155848e
--- /dev/null
+++ b/CryptoType.cpp
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2020 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 "CryptoType.h"
+
+#include <string.h>
+
+#include <android-base/logging.h>
+#include <cutils/properties.h>
+
+namespace android {
+namespace vold {
+
+const CryptoType& lookup_crypto_algorithm(const CryptoType table[], int table_len,
+ const CryptoType& default_alg, const char* property) {
+ char paramstr[PROPERTY_VALUE_MAX];
+
+ property_get(property, paramstr, default_alg.get_config_name());
+ for (int i = 0; i < table_len; i++) {
+ if (strcmp(paramstr, table[i].get_config_name()) == 0) {
+ return table[i];
+ }
+ }
+ LOG(ERROR) << "Invalid name (" << paramstr << ") for " << property << ". Defaulting to "
+ << default_alg.get_config_name() << ".";
+ return default_alg;
+}
+
+} // namespace vold
+} // namespace android
diff --git a/CryptoType.h b/CryptoType.h
new file mode 100644
index 0000000..7ec419b
--- /dev/null
+++ b/CryptoType.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#pragma once
+
+#include <stdlib.h>
+
+namespace android {
+namespace vold {
+
+// Struct representing an encryption algorithm supported by vold.
+// "config_name" represents the name we give the algorithm in
+// read-only properties and fstab files
+// "kernel_name" is the name we present to the Linux kernel
+// "keysize" is the size of the key in bytes.
+struct CryptoType {
+ // We should only be constructing CryptoTypes as part of
+ // supported_crypto_types[]. We do it via this pseudo-builder pattern,
+ // which isn't pure or fully protected as a concession to being able to
+ // do it all at compile time. Add new CryptoTypes in
+ // supported_crypto_types[] below.
+ constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
+ constexpr CryptoType set_keysize(size_t size) const {
+ return CryptoType(this->config_name, this->kernel_name, size);
+ }
+ constexpr CryptoType set_config_name(const char* property) const {
+ return CryptoType(property, this->kernel_name, this->keysize);
+ }
+ constexpr CryptoType set_kernel_name(const char* crypto) const {
+ return CryptoType(this->config_name, crypto, this->keysize);
+ }
+
+ constexpr const char* get_config_name() const { return config_name; }
+ constexpr const char* get_kernel_name() const { return kernel_name; }
+ constexpr size_t get_keysize() const { return keysize; }
+
+ private:
+ const char* config_name;
+ const char* kernel_name;
+ size_t keysize;
+
+ constexpr CryptoType(const char* property, const char* crypto, size_t ksize)
+ : config_name(property), kernel_name(crypto), keysize(ksize) {}
+};
+
+// Use the named android property to look up a type from the table
+// If the property is not set or matches no table entry, return the default.
+const CryptoType& lookup_crypto_algorithm(const CryptoType table[], int table_len,
+ const CryptoType& default_alg, const char* property);
+
+// Some useful types
+
+constexpr CryptoType invalid_crypto_type = CryptoType();
+
+constexpr CryptoType aes_256_xts = CryptoType()
+ .set_config_name("aes-256-xts")
+ .set_kernel_name("aes-xts-plain64")
+ .set_keysize(64);
+
+constexpr CryptoType adiantum = CryptoType()
+ .set_config_name("adiantum")
+ .set_kernel_name("xchacha12,aes-adiantum-plain64")
+ .set_keysize(32);
+
+// Support compile-time validation of a crypto type table
+
+template <typename T, size_t N>
+constexpr size_t array_length(T (&)[N]) {
+ return N;
+}
+
+constexpr bool isValidCryptoType(size_t max_keylen, const CryptoType& crypto_type) {
+ return ((crypto_type.get_config_name() != nullptr) &&
+ (crypto_type.get_kernel_name() != nullptr) &&
+ (crypto_type.get_keysize() <= max_keylen));
+}
+
+// Confirms that all supported_crypto_types have a small enough keysize and
+// had both set_config_name() and set_kernel_name() called.
+// Note in C++11 that constexpr functions can only have a single line.
+// So our code is a bit convoluted (using recursion instead of a loop),
+// but it's asserting at compile time that all of our key lengths are valid.
+constexpr bool validateSupportedCryptoTypes(size_t max_keylen, const CryptoType types[],
+ size_t len) {
+ return len == 0 || (isValidCryptoType(max_keylen, types[len - 1]) &&
+ validateSupportedCryptoTypes(max_keylen, types, len - 1));
+}
+
+} // namespace vold
+} // namespace android
diff --git a/Devmapper.cpp b/Devmapper.cpp
index b42467c..d55d92d 100644
--- a/Devmapper.cpp
+++ b/Devmapper.cpp
@@ -23,7 +23,6 @@
#include <string.h>
#include <unistd.h>
-#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
@@ -32,239 +31,72 @@
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
+#include <libdm/dm.h>
#include <utils/Trace.h>
#include "Devmapper.h"
-#define DEVMAPPER_BUFFER_SIZE 4096
-
using android::base::StringPrintf;
+using namespace android::dm;
static const char* kVoldPrefix = "vold:";
-void Devmapper::ioctlInit(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
- memset(io, 0, dataSize);
- io->data_size = dataSize;
- io->data_start = sizeof(struct dm_ioctl);
- io->version[0] = 4;
- io->version[1] = 0;
- io->version[2] = 0;
- io->flags = flags;
- if (name) {
- size_t ret = strlcpy(io->name, name, sizeof(io->name));
- if (ret >= sizeof(io->name)) abort();
- }
-}
-
int Devmapper::create(const char* name_raw, const char* loopFile, const char* key,
unsigned long numSectors, char* ubuffer, size_t len) {
+ auto& dm = DeviceMapper::Instance();
auto name_string = StringPrintf("%s%s", kVoldPrefix, name_raw);
- const char* name = name_string.c_str();
- char* buffer = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
- if (!buffer) {
- PLOG(ERROR) << "Failed malloc";
+ DmTable table;
+ table.Emplace<DmTargetCrypt>(0, numSectors, "twofish", key, 0, loopFile, 0);
+
+ if (!dm.CreateDevice(name_string, table)) {
+ LOG(ERROR) << "Failed to create device-mapper device " << name_string;
return -1;
}
- int fd;
- if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
- PLOG(ERROR) << "Failed open";
- free(buffer);
+ std::string path;
+ if (!dm.GetDmDevicePathByName(name_string, &path)) {
+ LOG(ERROR) << "Failed to get device-mapper device path for " << name_string;
return -1;
}
-
- struct dm_ioctl* io = (struct dm_ioctl*)buffer;
-
- // Create the DM device
- ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-
- if (ioctl(fd, DM_DEV_CREATE, io)) {
- PLOG(ERROR) << "Failed DM_DEV_CREATE";
- free(buffer);
- close(fd);
- return -1;
- }
-
- // Set the legacy geometry
- ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-
- 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
- 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)) {
- PLOG(ERROR) << "Failed DM_DEV_SET_GEOMETRY";
- free(buffer);
- close(fd);
- return -1;
- }
-
- // Retrieve the device number we were allocated
- ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
- if (ioctl(fd, DM_DEV_STATUS, io)) {
- PLOG(ERROR) << "Failed DM_DEV_STATUS";
- free(buffer);
- close(fd);
- return -1;
- }
-
- unsigned minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
- snprintf(ubuffer, len, "/dev/block/dm-%u", minor);
-
- // Load the table
- struct dm_target_spec* tgt;
- tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
-
- ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, DM_STATUS_TABLE_FLAG);
- io->target_count = 1;
- tgt->status = 0;
-
- tgt->sector_start = 0;
- tgt->length = numSectors;
-
- strlcpy(tgt->target_type, "crypt", sizeof(tgt->target_type));
-
- char* cryptParams = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
- snprintf(cryptParams,
- DEVMAPPER_BUFFER_SIZE - (sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec)),
- "twofish %s 0 %s 0", key, loopFile);
- cryptParams += strlen(cryptParams) + 1;
- cryptParams = (char*)_align(cryptParams, 8);
- tgt->next = cryptParams - buffer;
-
- if (ioctl(fd, DM_TABLE_LOAD, io)) {
- PLOG(ERROR) << "Failed DM_TABLE_LOAD";
- free(buffer);
- close(fd);
- return -1;
- }
-
- // Resume the new table
- ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-
- if (ioctl(fd, DM_DEV_SUSPEND, io)) {
- PLOG(ERROR) << "Failed DM_DEV_SUSPEND";
- free(buffer);
- close(fd);
- return -1;
- }
-
- free(buffer);
-
- close(fd);
+ snprintf(ubuffer, len, "%s", path.c_str());
return 0;
}
int Devmapper::destroy(const char* name_raw) {
+ auto& dm = DeviceMapper::Instance();
+
auto name_string = StringPrintf("%s%s", kVoldPrefix, name_raw);
- const char* name = name_string.c_str();
-
- char* buffer = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
- if (!buffer) {
- PLOG(ERROR) << "Failed malloc";
- return -1;
- }
-
- int fd;
- if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
- PLOG(ERROR) << "Failed open";
- free(buffer);
- return -1;
- }
-
- struct dm_ioctl* io = (struct dm_ioctl*)buffer;
-
- // Create the DM device
- ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-
- if (ioctl(fd, DM_DEV_REMOVE, io)) {
+ if (!dm.DeleteDevice(name_string)) {
if (errno != ENXIO) {
PLOG(ERROR) << "Failed DM_DEV_REMOVE";
}
- free(buffer);
- close(fd);
return -1;
}
-
- free(buffer);
- close(fd);
return 0;
}
int Devmapper::destroyAll() {
ATRACE_NAME("Devmapper::destroyAll");
- char* buffer = (char*)malloc(1024 * 64);
- if (!buffer) {
- PLOG(ERROR) << "Failed malloc";
- return -1;
- }
- memset(buffer, 0, (1024 * 64));
- char* buffer2 = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
- if (!buffer2) {
- PLOG(ERROR) << "Failed malloc";
- free(buffer);
+ auto& dm = DeviceMapper::Instance();
+ std::vector<DeviceMapper::DmBlockDevice> devices;
+ if (!dm.GetAvailableDevices(&devices)) {
+ LOG(ERROR) << "Failed to get dm devices";
return -1;
}
- int fd;
- if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
- PLOG(ERROR) << "Failed open";
- free(buffer);
- free(buffer2);
- return -1;
- }
-
- struct dm_ioctl* io = (struct dm_ioctl*)buffer;
- ioctlInit(io, (1024 * 64), NULL, 0);
-
- if (ioctl(fd, DM_LIST_DEVICES, io)) {
- PLOG(ERROR) << "Failed DM_LIST_DEVICES";
- free(buffer);
- free(buffer2);
- close(fd);
- return -1;
- }
-
- struct dm_name_list* n = (struct dm_name_list*)(((char*)buffer) + io->data_start);
- if (!n->dev) {
- free(buffer);
- free(buffer2);
- close(fd);
- return 0;
- }
-
- unsigned nxt = 0;
- do {
- n = (struct dm_name_list*)(((char*)n) + nxt);
- auto name = std::string(n->name);
- if (android::base::StartsWith(name, kVoldPrefix)) {
- LOG(DEBUG) << "Tearing down stale dm device named " << name;
-
- memset(buffer2, 0, DEVMAPPER_BUFFER_SIZE);
- struct dm_ioctl* io2 = (struct dm_ioctl*)buffer2;
- ioctlInit(io2, DEVMAPPER_BUFFER_SIZE, n->name, 0);
- if (ioctl(fd, DM_DEV_REMOVE, io2)) {
+ for (const auto& device : devices) {
+ if (android::base::StartsWith(device.name(), kVoldPrefix)) {
+ LOG(DEBUG) << "Tearing down stale dm device named " << device.name();
+ if (!dm.DeleteDevice(device.name())) {
if (errno != ENXIO) {
- PLOG(WARNING) << "Failed to destroy dm device named " << name;
+ PLOG(WARNING) << "Failed to destroy dm device named " << device.name();
}
}
} else {
- LOG(DEBUG) << "Found unmanaged dm device named " << name;
+ LOG(DEBUG) << "Found unmanaged dm device named " << device.name();
}
- nxt = n->next;
- } while (nxt);
-
- free(buffer);
- free(buffer2);
- close(fd);
+ }
return 0;
}
-
-void* Devmapper::_align(void* ptr, unsigned int a) {
- unsigned long agn = --a;
-
- return (void*)(((unsigned long)ptr + agn) & ~agn);
-}
diff --git a/Devmapper.h b/Devmapper.h
index b1f6dfa..9d4896e 100644
--- a/Devmapper.h
+++ b/Devmapper.h
@@ -26,10 +26,6 @@
unsigned long numSectors, char* buffer, size_t len);
static int destroy(const char* name);
static int destroyAll();
-
- private:
- static void* _align(void* ptr, unsigned int a);
- static void ioctlInit(struct dm_ioctl* io, size_t data_size, const char* name, unsigned flags);
};
#endif
diff --git a/EncryptInplace.cpp b/EncryptInplace.cpp
index 3755718..9d304da 100644
--- a/EncryptInplace.cpp
+++ b/EncryptInplace.cpp
@@ -391,6 +391,8 @@
struct encryptGroupsData data;
struct f2fs_info* f2fs_info = NULL;
int rc = ENABLE_INPLACE_ERR_OTHER;
+ struct timespec time_started = {0};
+
if (previously_encrypted_upto > *size_already_done) {
LOG(DEBUG) << "Not fast encrypting since resuming part way through";
return ENABLE_INPLACE_ERR_OTHER;
@@ -423,9 +425,14 @@
data.one_pct = data.tot_used_blocks / 100;
data.cur_pct = 0;
- data.time_started = time(NULL);
+ if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
+ LOG(WARNING) << "Error getting time at start";
+ // Note - continue anyway - we'll run with 0
+ }
+ data.time_started = time_started.tv_sec;
data.remaining_time = -1;
+
data.buffer = (char*)malloc(f2fs_info->block_size);
if (!data.buffer) {
LOG(ERROR) << "Failed to allocate crypto buffer";
diff --git a/EncryptInplace.h b/EncryptInplace.h
index bf0c314..a2b46cf 100644
--- a/EncryptInplace.h
+++ b/EncryptInplace.h
@@ -24,6 +24,11 @@
#define RETRY_MOUNT_ATTEMPTS 10
#define RETRY_MOUNT_DELAY_SECONDS 1
+/* Return values for cryptfs_enable_inplace() */
+#define ENABLE_INPLACE_OK 0
+#define ENABLE_INPLACE_ERR_OTHER (-1)
+#define ENABLE_INPLACE_ERR_DEV (-2) /* crypto_blkdev issue */
+
int cryptfs_enable_inplace(const char* crypto_blkdev, const char* real_blkdev, off64_t size,
off64_t* size_already_done, off64_t tot_size,
off64_t previously_encrypted_upto, bool set_progress_properties);
diff --git a/FsCrypt.cpp b/FsCrypt.cpp
index 07560e0..aa66c01 100644
--- a/FsCrypt.cpp
+++ b/FsCrypt.cpp
@@ -23,6 +23,7 @@
#include <algorithm>
#include <map>
+#include <optional>
#include <set>
#include <sstream>
#include <string>
@@ -42,8 +43,6 @@
#include "android/os/IVold.h"
-#include "cryptfs.h"
-
#define EMULATED_USES_SELINUX 0
#define MANAGE_MISC_DIRS 0
@@ -57,22 +56,22 @@
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
#include <android-base/unique_fd.h>
using android::base::StringPrintf;
using android::fs_mgr::GetEntryForMountPoint;
+using android::vold::BuildDataPath;
using android::vold::kEmptyAuthentication;
using android::vold::KeyBuffer;
+using android::vold::KeyGeneration;
+using android::vold::retrieveKey;
+using android::vold::retrieveOrGenerateKey;
using android::vold::writeStringToFile;
+using namespace android::fscrypt;
namespace {
-struct PolicyKeyRef {
- std::string contents_mode;
- std::string filenames_mode;
- std::string key_raw_ref;
-};
-
const std::string device_key_dir = std::string() + DATA_MNT_POINT + fscrypt_unencrypted_folder;
const std::string device_key_path = device_key_dir + "/key";
const std::string device_key_temp = device_key_dir + "/temp";
@@ -84,19 +83,20 @@
const std::string systemwide_volume_key_dir =
std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
-bool s_systemwide_keys_initialized = false;
-
// Some users are ephemeral, don't try to wipe their keys from disk
std::set<userid_t> s_ephemeral_users;
-// Map user ids to key references
-std::map<userid_t, std::string> s_de_key_raw_refs;
-std::map<userid_t, std::string> s_ce_key_raw_refs;
-// TODO abolish this map, per b/26948053
-std::map<userid_t, KeyBuffer> s_ce_keys;
+// Map user ids to encryption policies
+std::map<userid_t, EncryptionPolicy> s_de_policies;
+std::map<userid_t, EncryptionPolicy> s_ce_policies;
} // namespace
+// Returns KeyGeneration suitable for key as described in EncryptionOptions
+static KeyGeneration makeGen(const EncryptionOptions& options) {
+ return KeyGeneration{FSCRYPT_MAX_KEY_SIZE, true, options.use_hw_wrapped_key};
+}
+
static bool fscrypt_is_emulated() {
return property_get_bool("persist.sys.emulate_fbe", false);
}
@@ -189,7 +189,7 @@
auto const paths = get_ce_key_paths(directory_path);
for (auto const ce_key_path : paths) {
LOG(DEBUG) << "Trying user CE key " << ce_key_path;
- if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
+ if (retrieveKey(ce_key_path, auth, ce_key)) {
LOG(DEBUG) << "Successfully retrieved key";
fixate_user_ce_key(directory_path, ce_key_path, paths);
return true;
@@ -199,15 +199,64 @@
return false;
}
+// Retrieve the options to use for encryption policies on the /data filesystem.
+static bool get_data_file_encryption_options(EncryptionOptions* options) {
+ auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
+ if (entry == nullptr) {
+ LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
+ return false;
+ }
+ if (!ParseOptions(entry->encryption_options, options)) {
+ LOG(ERROR) << "Unable to parse encryption options for " << DATA_MNT_POINT ": "
+ << entry->encryption_options;
+ return false;
+ }
+ return true;
+}
+
+static bool install_storage_key(const std::string& mountpoint, const EncryptionOptions& options,
+ const KeyBuffer& key, EncryptionPolicy* policy) {
+ KeyBuffer ephemeral_wrapped_key;
+ if (options.use_hw_wrapped_key) {
+ if (!exportWrappedStorageKey(key, &ephemeral_wrapped_key)) {
+ LOG(ERROR) << "Failed to get ephemeral wrapped key";
+ return false;
+ }
+ }
+ return installKey(mountpoint, options, options.use_hw_wrapped_key ? ephemeral_wrapped_key : key,
+ policy);
+}
+
+// Retrieve the options to use for encryption policies on adoptable storage.
+static bool get_volume_file_encryption_options(EncryptionOptions* options) {
+ // If we give the empty string, libfscrypt will use the default (currently XTS)
+ auto contents_mode = android::base::GetProperty("ro.crypto.volume.contents_mode", "");
+ // HEH as default was always a mistake. Use the libfscrypt default (CTS)
+ // for devices launching on versions above Android 10.
+ auto first_api_level = GetFirstApiLevel();
+ constexpr uint64_t pre_gki_level = 29;
+ auto filenames_mode =
+ android::base::GetProperty("ro.crypto.volume.filenames_mode",
+ first_api_level > pre_gki_level ? "" : "aes-256-heh");
+ auto options_string = android::base::GetProperty("ro.crypto.volume.options",
+ contents_mode + ":" + filenames_mode);
+ if (!ParseOptionsForApiLevel(first_api_level, options_string, options)) {
+ LOG(ERROR) << "Unable to parse volume encryption options: " << options_string;
+ return false;
+ }
+ return true;
+}
+
static bool read_and_install_user_ce_key(userid_t user_id,
const android::vold::KeyAuthentication& auth) {
- if (s_ce_key_raw_refs.count(user_id) != 0) return true;
+ if (s_ce_policies.count(user_id) != 0) return true;
+ EncryptionOptions options;
+ if (!get_data_file_encryption_options(&options)) return false;
KeyBuffer ce_key;
if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
- std::string ce_raw_ref;
- if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
- s_ce_keys[user_id] = std::move(ce_key);
- s_ce_key_raw_refs[user_id] = ce_raw_ref;
+ EncryptionPolicy ce_policy;
+ if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
+ s_ce_policies[user_id] = ce_policy;
LOG(DEBUG) << "Installed ce key for user " << user_id;
return true;
}
@@ -233,9 +282,11 @@
// NB this assumes that there is only one thread listening for crypt commands, because
// it creates keys in a fixed location.
static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
+ EncryptionOptions options;
+ if (!get_data_file_encryption_options(&options)) return false;
KeyBuffer de_key, ce_key;
- if (!android::vold::randomKey(&de_key)) return false;
- if (!android::vold::randomKey(&ce_key)) return false;
+ if (!generateStorageKey(makeGen(options), &de_key)) return false;
+ if (!generateStorageKey(makeGen(options), &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);
@@ -254,43 +305,27 @@
kEmptyAuthentication, de_key))
return false;
}
- std::string de_raw_ref;
- 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 (!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;
+ EncryptionPolicy de_policy;
+ if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
+ s_de_policies[user_id] = de_policy;
+ EncryptionPolicy ce_policy;
+ if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
+ s_ce_policies[user_id] = ce_policy;
LOG(DEBUG) << "Created keys for user " << user_id;
return true;
}
-static bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
- std::string* raw_ref) {
+static bool lookup_policy(const std::map<userid_t, EncryptionPolicy>& key_map, userid_t user_id,
+ EncryptionPolicy* policy) {
auto refi = key_map.find(user_id);
if (refi == key_map.end()) {
LOG(DEBUG) << "Cannot find key for " << user_id;
return false;
}
- *raw_ref = refi->second;
+ *policy = refi->second;
return true;
}
-static void get_data_file_encryption_modes(PolicyKeyRef* key_ref) {
- auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
- if (entry == nullptr) {
- return;
- }
- key_ref->contents_mode = entry->file_contents_mode;
- key_ref->filenames_mode = entry->file_names_mode;
-}
-
-static bool ensure_policy(const PolicyKeyRef& key_ref, const std::string& path) {
- return fscrypt_policy_ensure(path.c_str(), key_ref.key_raw_ref.data(),
- key_ref.key_raw_ref.size(), key_ref.contents_mode.c_str(),
- key_ref.filenames_mode.c_str()) == 0;
-}
-
static bool is_numeric(const char* name) {
for (const char* p = name; *p != '\0'; p++) {
if (!isdigit(*p)) return false;
@@ -299,6 +334,8 @@
}
static bool load_all_de_keys() {
+ EncryptionOptions options;
+ if (!get_data_file_encryption_options(&options)) return false;
auto de_dir = user_key_dir + "/de";
auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
if (!dirp) {
@@ -320,53 +357,70 @@
continue;
}
userid_t user_id = std::stoi(entry->d_name);
- if (s_de_key_raw_refs.count(user_id) == 0) {
- auto key_path = de_dir + "/" + entry->d_name;
- KeyBuffer key;
- if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
- std::string raw_ref;
- 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;
+ auto key_path = de_dir + "/" + entry->d_name;
+ KeyBuffer de_key;
+ if (!retrieveKey(key_path, kEmptyAuthentication, &de_key)) return false;
+ EncryptionPolicy de_policy;
+ if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
+ auto ret = s_de_policies.insert({user_id, de_policy});
+ if (!ret.second && ret.first->second != de_policy) {
+ LOG(ERROR) << "DE policy for user" << user_id << " changed";
+ return false;
}
+ LOG(DEBUG) << "Installed de key for user " << user_id;
}
// fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
// correct policy set on them, and that no rogue ones exist.
return true;
}
+// Attempt to reinstall CE keys for users that we think are unlocked.
+static bool try_reload_ce_keys() {
+ for (const auto& it : s_ce_policies) {
+ if (!android::vold::reloadKeyFromSessionKeyring(DATA_MNT_POINT, it.second)) {
+ LOG(ERROR) << "Failed to load CE key from session keyring for user " << it.first;
+ return false;
+ }
+ }
+ return true;
+}
+
bool fscrypt_initialize_systemwide_keys() {
LOG(INFO) << "fscrypt_initialize_systemwide_keys";
- if (s_systemwide_keys_initialized) {
- LOG(INFO) << "Already initialized";
- return true;
- }
+ EncryptionOptions options;
+ if (!get_data_file_encryption_options(&options)) return false;
- PolicyKeyRef device_ref;
- if (!android::vold::retrieveAndInstallKey(true, kEmptyAuthentication, device_key_path,
- device_key_temp, &device_ref.key_raw_ref))
+ KeyBuffer device_key;
+ if (!retrieveOrGenerateKey(device_key_path, device_key_temp, kEmptyAuthentication,
+ makeGen(options), &device_key))
return false;
- get_data_file_encryption_modes(&device_ref);
- std::string modestring = device_ref.contents_mode + ":" + device_ref.filenames_mode;
- std::string mode_filename = std::string("/data") + fscrypt_key_mode;
- if (!android::vold::writeStringToFile(modestring, mode_filename)) return false;
+ EncryptionPolicy device_policy;
+ if (!install_storage_key(DATA_MNT_POINT, options, device_key, &device_policy)) return false;
- std::string ref_filename = std::string("/data") + fscrypt_key_ref;
- if (!android::vold::writeStringToFile(device_ref.key_raw_ref, ref_filename)) return false;
+ std::string options_string;
+ if (!OptionsToString(device_policy.options, &options_string)) {
+ LOG(ERROR) << "Unable to serialize options";
+ return false;
+ }
+ std::string options_filename = std::string(DATA_MNT_POINT) + fscrypt_key_mode;
+ if (!android::vold::writeStringToFile(options_string, options_filename)) return false;
+
+ std::string ref_filename = std::string(DATA_MNT_POINT) + fscrypt_key_ref;
+ if (!android::vold::writeStringToFile(device_policy.key_raw_ref, ref_filename)) return false;
LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
KeyBuffer per_boot_key;
- if (!android::vold::randomKey(&per_boot_key)) return false;
- std::string per_boot_raw_ref;
- if (!android::vold::installKey(per_boot_key, &per_boot_raw_ref)) return false;
+ if (!generateStorageKey(makeGen(options), &per_boot_key)) return false;
+ EncryptionPolicy per_boot_policy;
+ if (!install_storage_key(DATA_MNT_POINT, options, per_boot_key, &per_boot_policy)) return false;
std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
- if (!android::vold::writeStringToFile(per_boot_raw_ref, per_boot_ref_filename)) return false;
+ if (!android::vold::writeStringToFile(per_boot_policy.key_raw_ref, per_boot_ref_filename))
+ return false;
LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
if (!android::vold::FsyncDirectory(device_key_dir)) return false;
- s_systemwide_keys_initialized = true;
return true;
}
@@ -397,6 +451,13 @@
fscrypt_unlock_user_key(0, 0, "!", "!");
}
+ // In some scenarios (e.g. userspace reboot) we might unmount userdata
+ // without doing a hard reboot. If CE keys were stored in fs keyring then
+ // they will be lost after unmount. Attempt to re-install them.
+ if (fscrypt_is_native() && android::vold::isFsKeyringSupported()) {
+ if (!try_reload_ce_keys()) return false;
+ }
+
return true;
}
@@ -406,7 +467,7 @@
return true;
}
// FIXME test for existence of key that is not loaded yet
- if (s_ce_key_raw_refs.count(user_id) != 0) {
+ if (s_ce_policies.count(user_id) != 0) {
LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
<< " serial " << serial;
// FIXME should we fail the command?
@@ -418,25 +479,36 @@
return true;
}
-static void drop_caches() {
- // Clean any dirty pages (otherwise they won't be dropped).
+// "Lock" all encrypted directories whose key has been removed. This is needed
+// in the case where the keys are being put in the session keyring (rather in
+// the newer filesystem-level keyrings), because removing a key from the session
+// keyring doesn't affect inodes in the kernel's inode cache whose per-file key
+// was already set up. So to remove the per-file keys and make the files
+// "appear encrypted", these inodes must be evicted.
+//
+// To do this, sync() to clean all dirty inodes, then drop all reclaimable slab
+// objects systemwide. This is overkill, but it's the best available method
+// currently. Don't use drop_caches mode "3" because that also evicts pagecache
+// for in-use files; all files relevant here are already closed and sync'ed.
+static void drop_caches_if_needed() {
+ if (android::vold::isFsKeyringSupported()) {
+ return;
+ }
sync();
- // Drop inode and page caches.
- if (!writeStringToFile("3", "/proc/sys/vm/drop_caches")) {
+ if (!writeStringToFile("2", "/proc/sys/vm/drop_caches")) {
PLOG(ERROR) << "Failed to drop caches during key eviction";
}
}
static bool evict_ce_key(userid_t user_id) {
- s_ce_keys.erase(user_id);
bool success = true;
- std::string raw_ref;
+ EncryptionPolicy policy;
// 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 &= android::vold::evictKey(raw_ref);
- drop_caches();
+ if (lookup_policy(s_ce_policies, user_id, &policy)) {
+ success &= android::vold::evictKey(DATA_MNT_POINT, policy);
+ drop_caches_if_needed();
}
- s_ce_key_raw_refs.erase(user_id);
+ s_ce_policies.erase(user_id);
return success;
}
@@ -446,11 +518,11 @@
return true;
}
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) && android::vold::evictKey(raw_ref);
- s_de_key_raw_refs.erase(user_id);
+ EncryptionPolicy de_policy;
+ success &= lookup_policy(s_de_policies, user_id, &de_policy) &&
+ android::vold::evictKey(DATA_MNT_POINT, de_policy);
+ s_de_policies.erase(user_id);
auto it = s_ephemeral_users.find(user_id);
if (it != s_ephemeral_users.end()) {
s_ephemeral_users.erase(it);
@@ -510,6 +582,18 @@
return true;
}
+static std::optional<android::vold::KeyAuthentication> authentication_from_hex(
+ const std::string& token_hex, const std::string& secret_hex) {
+ std::string token, secret;
+ if (!parse_hex(token_hex, &token)) return std::optional<android::vold::KeyAuthentication>();
+ if (!parse_hex(secret_hex, &secret)) return std::optional<android::vold::KeyAuthentication>();
+ if (secret.empty()) {
+ return kEmptyAuthentication;
+ } else {
+ return android::vold::KeyAuthentication(token, secret);
+ }
+}
+
static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
}
@@ -519,7 +603,7 @@
}
static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
- PolicyKeyRef* key_ref) {
+ EncryptionPolicy* policy) {
auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
std::string secdiscardable_hash;
if (android::vold::pathExists(secdiscardable_path)) {
@@ -539,13 +623,13 @@
return false;
}
android::vold::KeyAuthentication auth("", secdiscardable_hash);
- if (!android::vold::retrieveAndInstallKey(true, auth, key_path, key_path + "_tmp",
- &key_ref->key_raw_ref))
+
+ EncryptionOptions options;
+ if (!get_volume_file_encryption_options(&options)) return false;
+ KeyBuffer key;
+ if (!retrieveOrGenerateKey(key_path, key_path + "_tmp", auth, makeGen(options), &key))
return false;
- key_ref->contents_mode =
- android::base::GetProperty("ro.crypto.volume.contents_mode", "aes-256-xts");
- key_ref->filenames_mode =
- android::base::GetProperty("ro.crypto.volume.filenames_mode", "aes-256-heh");
+ if (!install_storage_key(BuildDataPath(volume_uuid), options, key, policy)) return false;
return true;
}
@@ -555,30 +639,51 @@
return android::vold::destroyKey(path);
}
+static bool fscrypt_rewrap_user_key(userid_t user_id, int serial,
+ const android::vold::KeyAuthentication& retrieve_auth,
+ const android::vold::KeyAuthentication& store_auth) {
+ if (s_ephemeral_users.count(user_id) != 0) return true;
+ auto const directory_path = get_ce_key_directory_path(user_id);
+ KeyBuffer ce_key;
+ std::string ce_key_current_path = get_ce_key_current_path(directory_path);
+ if (retrieveKey(ce_key_current_path, retrieve_auth, &ce_key)) {
+ LOG(DEBUG) << "Successfully retrieved key";
+ // TODO(147732812): Remove this once Locksettingservice is fixed.
+ // Currently it calls fscrypt_clear_user_key_auth with a secret when lockscreen is
+ // changed from swipe to none or vice-versa
+ } else if (retrieveKey(ce_key_current_path, kEmptyAuthentication, &ce_key)) {
+ LOG(DEBUG) << "Successfully retrieved key with empty auth";
+ } else {
+ LOG(ERROR) << "Failed to retrieve key for user " << user_id;
+ return false;
+ }
+ auto const paths = get_ce_key_paths(directory_path);
+ std::string ce_key_path;
+ if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
+ if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, store_auth, ce_key))
+ return false;
+ if (!android::vold::FsyncDirectory(directory_path)) return false;
+ return true;
+}
+
bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
const std::string& secret_hex) {
LOG(DEBUG) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial
<< " token_present=" << (token_hex != "!");
if (!fscrypt_is_native()) return true;
- if (s_ephemeral_users.count(user_id) != 0) return true;
- std::string token, secret;
- if (!parse_hex(token_hex, &token)) return false;
- if (!parse_hex(secret_hex, &secret)) return false;
- auto auth =
- secret.empty() ? kEmptyAuthentication : android::vold::KeyAuthentication(token, secret);
- auto it = s_ce_keys.find(user_id);
- if (it == s_ce_keys.end()) {
- LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
- return false;
- }
- const auto& ce_key = it->second;
- auto const directory_path = get_ce_key_directory_path(user_id);
- auto const paths = get_ce_key_paths(directory_path);
- std::string ce_key_path;
- if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
- if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
- if (!android::vold::FsyncDirectory(directory_path)) return false;
- return true;
+ auto auth = authentication_from_hex(token_hex, secret_hex);
+ if (!auth) return false;
+ return fscrypt_rewrap_user_key(user_id, serial, kEmptyAuthentication, *auth);
+}
+
+bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
+ const std::string& secret_hex) {
+ LOG(DEBUG) << "fscrypt_clear_user_key_auth " << user_id << " serial=" << serial
+ << " token_present=" << (token_hex != "!");
+ if (!fscrypt_is_native()) return true;
+ auto auth = authentication_from_hex(token_hex, secret_hex);
+ if (!auth) return false;
+ return fscrypt_rewrap_user_key(user_id, serial, *auth, kEmptyAuthentication);
}
bool fscrypt_fixate_newest_user_key_auth(userid_t user_id) {
@@ -601,15 +706,13 @@
LOG(DEBUG) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial
<< " token_present=" << (token_hex != "!");
if (fscrypt_is_native()) {
- if (s_ce_key_raw_refs.count(user_id) != 0) {
+ if (s_ce_policies.count(user_id) != 0) {
LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
return true;
}
- std::string token, secret;
- if (!parse_hex(token_hex, &token)) return false;
- if (!parse_hex(secret_hex, &secret)) return false;
- android::vold::KeyAuthentication auth(token, secret);
- if (!read_and_install_user_ce_key(user_id, auth)) {
+ auto auth = authentication_from_hex(token_hex, secret_hex);
+ if (!auth) return false;
+ if (!read_and_install_user_ce_key(user_id, *auth)) {
LOG(ERROR) << "Couldn't read key for " << user_id;
return false;
}
@@ -691,17 +794,16 @@
if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
if (fscrypt_is_native()) {
- PolicyKeyRef de_ref;
+ EncryptionPolicy de_policy;
if (volume_uuid.empty()) {
- if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_ref.key_raw_ref)) return false;
- get_data_file_encryption_modes(&de_ref);
- if (!ensure_policy(de_ref, system_de_path)) return false;
- if (!ensure_policy(de_ref, misc_de_path)) return false;
- if (!ensure_policy(de_ref, vendor_de_path)) return false;
+ if (!lookup_policy(s_de_policies, user_id, &de_policy)) return false;
+ if (!EnsurePolicy(de_policy, system_de_path)) return false;
+ if (!EnsurePolicy(de_policy, misc_de_path)) return false;
+ if (!EnsurePolicy(de_policy, vendor_de_path)) return false;
} else {
- if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_ref)) return false;
+ if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_policy)) return false;
}
- if (!ensure_policy(de_ref, user_de_path)) return false;
+ if (!EnsurePolicy(de_policy, user_de_path)) return false;
}
}
@@ -722,19 +824,17 @@
if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
if (fscrypt_is_native()) {
- PolicyKeyRef ce_ref;
+ EncryptionPolicy ce_policy;
if (volume_uuid.empty()) {
- if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_ref.key_raw_ref)) return false;
- get_data_file_encryption_modes(&ce_ref);
- if (!ensure_policy(ce_ref, system_ce_path)) return false;
- if (!ensure_policy(ce_ref, misc_ce_path)) return false;
- if (!ensure_policy(ce_ref, vendor_ce_path)) return false;
-
+ if (!lookup_policy(s_ce_policies, user_id, &ce_policy)) return false;
+ if (!EnsurePolicy(ce_policy, system_ce_path)) return false;
+ if (!EnsurePolicy(ce_policy, misc_ce_path)) return false;
+ if (!EnsurePolicy(ce_policy, vendor_ce_path)) return false;
} else {
- if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_ref)) return false;
+ if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_policy)) return false;
}
- if (!ensure_policy(ce_ref, media_ce_path)) return false;
- if (!ensure_policy(ce_ref, user_ce_path)) return false;
+ if (!EnsurePolicy(ce_policy, media_ce_path)) return false;
+ if (!EnsurePolicy(ce_policy, user_ce_path)) return false;
}
if (volume_uuid.empty()) {
diff --git a/FsCrypt.h b/FsCrypt.h
index 03ec2e1..641991a 100644
--- a/FsCrypt.h
+++ b/FsCrypt.h
@@ -25,6 +25,8 @@
bool fscrypt_destroy_user_key(userid_t user_id);
bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token,
const std::string& secret);
+bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& token,
+ const std::string& secret);
bool fscrypt_fixate_newest_user_key_auth(userid_t user_id);
bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& token,
diff --git a/IdleMaint.cpp b/IdleMaint.cpp
index bca22f6..2b5a8f1 100644
--- a/IdleMaint.cpp
+++ b/IdleMaint.cpp
@@ -29,8 +29,8 @@
#include <android-base/strings.h>
#include <android/hardware/health/storage/1.0/IStorage.h>
#include <fs_mgr.h>
-#include <hardware_legacy/power.h>
#include <private/android_filesystem_config.h>
+#include <wakelock/wakelock.h>
#include <dirent.h>
#include <fcntl.h>
@@ -145,7 +145,7 @@
}
void Trim(const android::sp<android::os::IVoldTaskListener>& listener) {
- acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+ android::wakelock::WakeLock wl{kWakeLock};
// Collect both fstab and vold volumes
std::list<std::string> paths;
@@ -195,7 +195,6 @@
listener->onFinished(0, extras);
}
- release_wake_lock(kWakeLock);
}
static bool waitForGc(const std::list<std::string>& paths) {
@@ -370,7 +369,7 @@
LOG(DEBUG) << "idle maintenance started";
- acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+ android::wakelock::WakeLock wl{kWakeLock};
std::list<std::string> paths;
addFromFstab(&paths, PathTypes::kBlkDevice);
@@ -400,13 +399,11 @@
LOG(DEBUG) << "idle maintenance completed";
- release_wake_lock(kWakeLock);
-
return android::OK;
}
int AbortIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
- acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+ android::wakelock::WakeLock wl{kWakeLock};
std::unique_lock<std::mutex> lk(cv_m);
if (idle_maint_stat != IdleMaintStats::kStopped) {
@@ -424,8 +421,6 @@
listener->onFinished(0, extras);
}
- release_wake_lock(kWakeLock);
-
LOG(DEBUG) << "idle maintenance stopped";
return android::OK;
diff --git a/KeyStorage.cpp b/KeyStorage.cpp
index 0290086..951536b 100644
--- a/KeyStorage.cpp
+++ b/KeyStorage.cpp
@@ -16,10 +16,10 @@
#include "KeyStorage.h"
+#include "Checkpoint.h"
#include "Keymaster.h"
#include "ScryptParameters.h"
#include "Utils.h"
-#include "Checkpoint.h"
#include <thread>
#include <vector>
@@ -37,14 +37,14 @@
#include <android-base/file.h>
#include <android-base/logging.h>
-#include <android-base/unique_fd.h>
#include <android-base/properties.h>
+#include <android-base/unique_fd.h>
#include <cutils/properties.h>
#include <hardware/hw_auth_token.h>
-#include <keymasterV4_0/authorization_set.h>
-#include <keymasterV4_0/keymaster_utils.h>
+#include <keymasterV4_1/authorization_set.h>
+#include <keymasterV4_1/keymaster_utils.h>
extern "C" {
@@ -122,11 +122,42 @@
return false;
}
const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
- paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id);
+ auto user_id = at->user_id; // Make a copy because at->user_id is unaligned.
+ paramBuilder.Authorization(km::TAG_USER_SECURE_ID, user_id);
paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
}
- return keymaster.generateKey(paramBuilder, key);
+
+ auto paramsWithRollback = paramBuilder;
+ paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
+
+ // Generate rollback-resistant key if possible.
+ return keymaster.generateKey(paramsWithRollback, key) ||
+ keymaster.generateKey(paramBuilder, key);
+}
+
+bool generateWrappedStorageKey(KeyBuffer* key) {
+ Keymaster keymaster;
+ if (!keymaster) return false;
+ std::string key_temp;
+ auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
+ paramBuilder.Authorization(km::TAG_ROLLBACK_RESISTANCE);
+ paramBuilder.Authorization(km::TAG_STORAGE_KEY);
+ if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
+ *key = KeyBuffer(key_temp.size());
+ memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
+ return true;
+}
+
+bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
+ Keymaster keymaster;
+ if (!keymaster) return false;
+ std::string key_temp;
+
+ if (!keymaster.exportKey(kmKey, &key_temp)) return false;
+ *key = KeyBuffer(key_temp.size());
+ memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
+ return true;
}
static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
diff --git a/KeyStorage.h b/KeyStorage.h
index 276b6b9..f9d3ec6 100644
--- a/KeyStorage.h
+++ b/KeyStorage.h
@@ -68,6 +68,11 @@
bool destroyKey(const std::string& dir);
bool runSecdiscardSingle(const std::string& file);
+
+// Generate wrapped storage key using keymaster. Uses STORAGE_KEY tag in keymaster.
+bool generateWrappedStorageKey(KeyBuffer* key);
+// Export the per-boot boot wrapped storage key using keymaster.
+bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key);
} // namespace vold
} // namespace android
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
index 12cae9b..3359699 100644
--- a/KeyUtil.cpp
+++ b/KeyUtil.cpp
@@ -16,27 +16,32 @@
#include "KeyUtil.h"
-#include <linux/fs.h>
#include <iomanip>
#include <sstream>
#include <string>
+#include <fcntl.h>
+#include <linux/fscrypt.h>
#include <openssl/sha.h>
+#include <sys/ioctl.h>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <keyutils.h>
+#include <fscrypt_uapi.h>
#include "KeyStorage.h"
#include "Utils.h"
namespace android {
namespace vold {
-constexpr int FS_AES_256_XTS_KEY_SIZE = 64;
+const KeyGeneration neverGen() {
+ return KeyGeneration{0, false, false};
+}
-bool randomKey(KeyBuffer* key) {
- *key = KeyBuffer(FS_AES_256_XTS_KEY_SIZE);
+static bool randomKey(size_t size, KeyBuffer* key) {
+ *key = KeyBuffer(size);
if (ReadRandomBytes(key->size(), key->data()) != 0) {
// TODO status_t plays badly with PLOG, fix it.
LOG(ERROR) << "Random read failed";
@@ -45,6 +50,55 @@
return true;
}
+bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key) {
+ if (!gen.allow_gen) return false;
+ if (gen.use_hw_wrapped_key) {
+ if (gen.keysize != FSCRYPT_MAX_KEY_SIZE) {
+ LOG(ERROR) << "Cannot generate a wrapped key " << gen.keysize << " bytes long";
+ return false;
+ }
+ return generateWrappedStorageKey(key);
+ } else {
+ return randomKey(gen.keysize, key);
+ }
+}
+
+// Return true if the kernel supports the ioctls to add/remove fscrypt keys
+// directly to/from the filesystem.
+bool isFsKeyringSupported(void) {
+ static bool initialized = false;
+ static bool supported;
+
+ if (!initialized) {
+ android::base::unique_fd fd(open("/data", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
+
+ // FS_IOC_ADD_ENCRYPTION_KEY with a NULL argument will fail with ENOTTY
+ // if the ioctl isn't supported. Otherwise it will fail with another
+ // error code such as EFAULT.
+ errno = 0;
+ (void)ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, NULL);
+ if (errno == ENOTTY) {
+ LOG(INFO) << "Kernel doesn't support FS_IOC_ADD_ENCRYPTION_KEY. Falling back to "
+ "session keyring";
+ supported = false;
+ } else {
+ if (errno != EFAULT) {
+ PLOG(WARNING) << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY";
+ }
+ LOG(DEBUG) << "Detected support for FS_IOC_ADD_ENCRYPTION_KEY";
+ supported = true;
+ }
+ // There's no need to check for FS_IOC_REMOVE_ENCRYPTION_KEY, since it's
+ // guaranteed to be available if FS_IOC_ADD_ENCRYPTION_KEY is. There's
+ // also no need to check for support on external volumes separately from
+ // /data, since either the kernel supports the ioctls on all
+ // fscrypt-capable filesystems or it doesn't.
+
+ initialized = true;
+ }
+ return supported;
+}
+
// Get raw keyref - used to make keyname and to pass to ioctl
static std::string generateKeyRef(const uint8_t* key, int length) {
SHA512_CTX c;
@@ -59,35 +113,39 @@
unsigned char key_ref2[SHA512_DIGEST_LENGTH];
SHA512_Final(key_ref2, &c);
- static_assert(FS_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH, "Hash too short for descriptor");
- return std::string((char*)key_ref2, FS_KEY_DESCRIPTOR_SIZE);
+ static_assert(FSCRYPT_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
+ "Hash too short for descriptor");
+ return std::string((char*)key_ref2, FSCRYPT_KEY_DESCRIPTOR_SIZE);
}
static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
- if (key.size() != FS_AES_256_XTS_KEY_SIZE) {
+ if (key.size() != FSCRYPT_MAX_KEY_SIZE) {
LOG(ERROR) << "Wrong size key " << key.size();
return false;
}
- static_assert(FS_AES_256_XTS_KEY_SIZE <= sizeof(fs_key->raw), "Key too long!");
- fs_key->mode = FS_ENCRYPTION_MODE_AES_256_XTS;
- fs_key->size = key.size();
- memset(fs_key->raw, 0, sizeof(fs_key->raw));
+ static_assert(FSCRYPT_MAX_KEY_SIZE == sizeof(fs_key->raw), "Mismatch of max key sizes");
+ fs_key->mode = 0; // unused by kernel
memcpy(fs_key->raw, key.data(), key.size());
+ fs_key->size = key.size();
return true;
}
static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
-static std::string keyname(const std::string& prefix, const std::string& raw_ref) {
+static std::string keyrefstring(const std::string& raw_ref) {
std::ostringstream o;
- o << prefix << ":";
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 std::string buildLegacyKeyName(const std::string& prefix, const std::string& raw_ref) {
+ return prefix + ":" + keyrefstring(raw_ref);
+}
+
+// Get the ID of the keyring we store all fscrypt keys in when the kernel is too
+// old to support FS_IOC_ADD_ENCRYPTION_KEY and FS_IOC_REMOVE_ENCRYPTION_KEY.
static bool fscryptKeyring(key_serial_t* device_keyring) {
*device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
if (*device_keyring == -1) {
@@ -97,19 +155,17 @@
return true;
}
-// Install password into global keyring
-// Return raw key reference for use in policy
-bool installKey(const KeyBuffer& key, std::string* raw_ref) {
+// Add an encryption key of type "logon" to the global session keyring.
+static bool installKeyLegacy(const KeyBuffer& key, const std::string& raw_ref) {
// Place fscrypt_key into automatically zeroing buffer.
KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
if (!fillKey(key, &fs_key)) return false;
- *raw_ref = generateKeyRef(fs_key.raw, fs_key.size);
key_serial_t device_keyring;
if (!fscryptKeyring(&device_keyring)) return false;
for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
- auto ref = keyname(*name_prefix, *raw_ref);
+ auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
key_serial_t key_id =
add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
if (key_id == -1) {
@@ -122,12 +178,146 @@
return true;
}
-bool evictKey(const std::string& raw_ref) {
+// Installs fscrypt-provisioning key into session level kernel keyring.
+// This allows for the given key to be installed back into filesystem keyring.
+// For more context see reloadKeyFromSessionKeyring.
+static bool installProvisioningKey(const KeyBuffer& key, const std::string& ref,
+ const fscrypt_key_specifier& key_spec) {
+ key_serial_t device_keyring;
+ if (!fscryptKeyring(&device_keyring)) return false;
+
+ // Place fscrypt_provisioning_key_payload into automatically zeroing buffer.
+ KeyBuffer buf(sizeof(fscrypt_provisioning_key_payload) + key.size(), 0);
+ fscrypt_provisioning_key_payload& provisioning_key =
+ *reinterpret_cast<fscrypt_provisioning_key_payload*>(buf.data());
+ memcpy(provisioning_key.raw, key.data(), key.size());
+ provisioning_key.type = key_spec.type;
+
+ key_serial_t key_id = add_key("fscrypt-provisioning", ref.c_str(), (void*)&provisioning_key,
+ buf.size(), device_keyring);
+ if (key_id == -1) {
+ PLOG(ERROR) << "Failed to insert fscrypt-provisioning key for " << ref
+ << " into session keyring";
+ return false;
+ }
+ LOG(DEBUG) << "Added fscrypt-provisioning key for " << ref << " to session keyring";
+ return true;
+}
+
+// Build a struct fscrypt_key_specifier for use in the key management ioctls.
+static bool buildKeySpecifier(fscrypt_key_specifier* spec, const EncryptionPolicy& policy) {
+ switch (policy.options.version) {
+ case 1:
+ if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
+ LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
+ << policy.key_raw_ref.size();
+ return false;
+ }
+ spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
+ memcpy(spec->u.descriptor, policy.key_raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
+ return true;
+ case 2:
+ if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
+ LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
+ << policy.key_raw_ref.size();
+ return false;
+ }
+ spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
+ memcpy(spec->u.identifier, policy.key_raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
+ return true;
+ default:
+ LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version;
+ return false;
+ }
+}
+
+// Installs key into keyring of a filesystem mounted on |mountpoint|.
+//
+// It's callers responsibility to fill key specifier, and either arg->raw or arg->key_id.
+//
+// In case arg->key_spec.type equals to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER
+// arg->key_spec.u.identifier will be populated with raw key reference generated
+// by kernel.
+//
+// For documentation on difference between arg->raw and arg->key_id see
+// https://www.kernel.org/doc/html/latest/filesystems/fscrypt.html#fs-ioc-add-encryption-key
+static bool installFsKeyringKey(const std::string& mountpoint, const EncryptionOptions& options,
+ fscrypt_add_key_arg* arg) {
+ if (options.use_hw_wrapped_key) arg->flags |= FSCRYPT_ADD_KEY_FLAG_WRAPPED;
+
+ android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
+ if (fd == -1) {
+ PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
+ return false;
+ }
+
+ if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
+ PLOG(ERROR) << "Failed to install fscrypt key to " << mountpoint;
+ return false;
+ }
+
+ return true;
+}
+
+bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
+ const KeyBuffer& key, EncryptionPolicy* policy) {
+ policy->options = options;
+ // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
+ // have to copy the raw key into it.
+ KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
+ struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
+
+ // Initialize the "key specifier", which is like a name for the key.
+ switch (options.version) {
+ case 1:
+ // A key for a v1 policy is specified by an arbitrary 8-byte
+ // "descriptor", which must be provided by userspace. We use the
+ // first 8 bytes from the double SHA-512 of the key itself.
+ policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
+ if (!isFsKeyringSupported()) {
+ return installKeyLegacy(key, policy->key_raw_ref);
+ }
+ if (!buildKeySpecifier(&arg->key_spec, *policy)) {
+ return false;
+ }
+ break;
+ case 2:
+ // A key for a v2 policy is specified by an 16-byte "identifier",
+ // which is a cryptographic hash of the key itself which the kernel
+ // computes and returns. Any user-provided value is ignored; we
+ // just need to set the specifier type to indicate that we're adding
+ // this type of key.
+ arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
+ break;
+ default:
+ LOG(ERROR) << "Invalid encryption policy version: " << options.version;
+ return false;
+ }
+
+ arg->raw_size = key.size();
+ memcpy(arg->raw, key.data(), key.size());
+
+ if (!installFsKeyringKey(mountpoint, options, arg)) return false;
+
+ if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
+ // Retrieve the key identifier that the kernel computed.
+ policy->key_raw_ref =
+ std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
+ }
+ std::string ref = keyrefstring(policy->key_raw_ref);
+ LOG(DEBUG) << "Installed fscrypt key with ref " << ref << " to " << mountpoint;
+
+ if (!installProvisioningKey(key, ref, arg->key_spec)) return false;
+ return true;
+}
+
+// Remove an encryption key of type "logon" from the global session keyring.
+static bool evictKeyLegacy(const std::string& raw_ref) {
key_serial_t device_keyring;
if (!fscryptKeyring(&device_keyring)) return false;
bool success = true;
for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
- auto ref = keyname(*name_prefix, raw_ref);
+ auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
// Unlink the key from the keyring. Prefer unlinking to revoking or
@@ -144,46 +334,107 @@
return success;
}
-bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
- const std::string& key_path, const std::string& tmp_path,
- std::string* key_ref) {
- KeyBuffer key;
- if (pathExists(key_path)) {
- LOG(DEBUG) << "Key exists, using: " << key_path;
- if (!retrieveKey(key_path, key_authentication, &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, key_authentication, key)) return false;
+static bool evictProvisioningKey(const std::string& ref) {
+ key_serial_t device_keyring;
+ if (!fscryptKeyring(&device_keyring)) {
+ return false;
}
- if (!installKey(key, key_ref)) {
- LOG(ERROR) << "Failed to install key in " << key_path;
+ auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
+ if (key_serial == -1 && errno != ENOKEY) {
+ PLOG(ERROR) << "Error searching session keyring for fscrypt-provisioning key for " << ref;
+ return false;
+ }
+
+ if (key_serial != -1 && keyctl_unlink(key_serial, device_keyring) != 0) {
+ PLOG(ERROR) << "Failed to unlink fscrypt-provisioning key for " << ref
+ << " from session keyring";
return false;
}
return true;
}
-bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
- KeyBuffer* key, bool keepOld) {
+bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy) {
+ if (policy.options.version == 1 && !isFsKeyringSupported()) {
+ return evictKeyLegacy(policy.key_raw_ref);
+ }
+
+ android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
+ if (fd == -1) {
+ PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
+ return false;
+ }
+
+ struct fscrypt_remove_key_arg arg;
+ memset(&arg, 0, sizeof(arg));
+
+ if (!buildKeySpecifier(&arg.key_spec, policy)) {
+ return false;
+ }
+
+ std::string ref = keyrefstring(policy.key_raw_ref);
+
+ if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
+ PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
+ return false;
+ }
+
+ LOG(DEBUG) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
+ if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
+ // Should never happen because keys are only added/removed as root.
+ LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
+ } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
+ LOG(ERROR) << "Files still open after removing key with ref " << ref
+ << ". These files were not locked!";
+ }
+
+ if (!evictProvisioningKey(ref)) return false;
+ return true;
+}
+
+bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
+ const KeyAuthentication& key_authentication, const KeyGeneration& gen,
+ KeyBuffer* key, bool keepOld) {
if (pathExists(key_path)) {
LOG(DEBUG) << "Key exists, using: " << key_path;
- if (!retrieveKey(key_path, kEmptyAuthentication, key, keepOld)) return false;
+ if (!retrieveKey(key_path, key_authentication, key, keepOld)) return false;
} else {
- if (!create_if_absent) {
+ if (!gen.allow_gen) {
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 (!generateStorageKey(gen, key)) return false;
+ if (!storeKeyAtomically(key_path, tmp_path, key_authentication, *key)) return false;
}
return true;
}
+bool reloadKeyFromSessionKeyring(const std::string& mountpoint, const EncryptionPolicy& policy) {
+ key_serial_t device_keyring;
+ if (!fscryptKeyring(&device_keyring)) {
+ return false;
+ }
+
+ std::string ref = keyrefstring(policy.key_raw_ref);
+ auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
+ if (key_serial == -1) {
+ PLOG(ERROR) << "Failed to find fscrypt-provisioning key for " << ref
+ << " in session keyring";
+ return false;
+ }
+
+ LOG(DEBUG) << "Installing fscrypt-provisioning key for " << ref << " back into " << mountpoint
+ << " fs-keyring";
+
+ struct fscrypt_add_key_arg arg;
+ memset(&arg, 0, sizeof(arg));
+ if (!buildKeySpecifier(&arg.key_spec, policy)) return false;
+ arg.key_id = key_serial;
+ if (!installFsKeyringKey(mountpoint, policy.options, &arg)) return false;
+
+ return true;
+}
+
} // namespace vold
} // namespace android
diff --git a/KeyUtil.h b/KeyUtil.h
index 7ee6725..23278c1 100644
--- a/KeyUtil.h
+++ b/KeyUtil.h
@@ -20,20 +20,67 @@
#include "KeyBuffer.h"
#include "KeyStorage.h"
+#include <fscrypt/fscrypt.h>
+
#include <memory>
#include <string>
namespace android {
namespace vold {
-bool randomKey(KeyBuffer* key);
-bool installKey(const KeyBuffer& key, std::string* raw_ref);
-bool evictKey(const std::string& raw_ref);
-bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
- const std::string& key_path, const std::string& tmp_path,
- std::string* key_ref);
-bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
- KeyBuffer* key, bool keepOld = true);
+using namespace android::fscrypt;
+
+// Description of how to generate a key when needed.
+struct KeyGeneration {
+ size_t keysize;
+ bool allow_gen;
+ bool use_hw_wrapped_key;
+};
+
+// Generate a key as specified in KeyGeneration
+bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key);
+
+// Returns a key with allow_gen false so generateStorageKey returns false;
+// this is used to indicate to retrieveOrGenerateKey that a key should not
+// be generated.
+const KeyGeneration neverGen();
+
+bool isFsKeyringSupported(void);
+
+// Install a file-based encryption key to the kernel, for use by encrypted files
+// on the specified filesystem using the specified encryption policy version.
+//
+// For v1 policies, we use FS_IOC_ADD_ENCRYPTION_KEY if the kernel supports it.
+// Otherwise we add the key to the global session keyring as a "logon" key.
+//
+// For v2 policies, we always use FS_IOC_ADD_ENCRYPTION_KEY; it's the only way
+// the kernel supports.
+//
+// If kernel supports FS_IOC_ADD_ENCRYPTION_KEY, also installs key of
+// fscrypt-provisioning type to the global session keyring. This makes it
+// possible to unmount and then remount mountpoint without losing the file-based
+// key.
+//
+// Returns %true on success, %false on failure. On success also sets *policy
+// to the EncryptionPolicy used to refer to this key.
+bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
+ const KeyBuffer& key, EncryptionPolicy* policy);
+
+// Evict a file-based encryption key from the kernel.
+//
+// This undoes the effect of installKey().
+//
+// If the kernel doesn't support the filesystem-level keyring, the caller is
+// responsible for dropping caches.
+bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy);
+
+bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
+ const KeyAuthentication& key_authentication, const KeyGeneration& gen,
+ KeyBuffer* key, bool keepOld = true);
+
+// Re-installs a file-based encryption key of fscrypt-provisioning type from the
+// global session keyring back into fs keyring of the mountpoint.
+bool reloadKeyFromSessionKeyring(const std::string& mountpoint, const EncryptionPolicy& policy);
} // namespace vold
} // namespace android
diff --git a/Keymaster.cpp b/Keymaster.cpp
index aad4387..c3f2912 100644
--- a/Keymaster.cpp
+++ b/Keymaster.cpp
@@ -17,8 +17,8 @@
#include "Keymaster.h"
#include <android-base/logging.h>
-#include <keymasterV4_0/authorization_set.h>
-#include <keymasterV4_0/keymaster_utils.h>
+#include <keymasterV4_1/authorization_set.h>
+#include <keymasterV4_1/keymaster_utils.h>
namespace android {
namespace vold {
@@ -138,6 +138,27 @@
return true;
}
+bool Keymaster::exportKey(const KeyBuffer& kmKey, std::string* key) {
+ auto kmKeyBlob = km::support::blob2hidlVec(std::string(kmKey.data(), kmKey.size()));
+ km::ErrorCode km_error;
+ auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& exportedKeyBlob) {
+ km_error = ret;
+ if (km_error != km::ErrorCode::OK) return;
+ if (key)
+ key->assign(reinterpret_cast<const char*>(&exportedKeyBlob[0]), exportedKeyBlob.size());
+ };
+ auto error = mDevice->exportKey(km::KeyFormat::RAW, kmKeyBlob, {}, {}, hidlCb);
+ if (!error.isOk()) {
+ LOG(ERROR) << "export_key failed: " << error.description();
+ return false;
+ }
+ if (km_error != km::ErrorCode::OK) {
+ LOG(ERROR) << "export_key failed, code " << int32_t(km_error);
+ return false;
+ }
+ return true;
+}
+
bool Keymaster::deleteKey(const std::string& key) {
auto keyBlob = km::support::blob2hidlVec(key);
auto error = mDevice->deleteKey(keyBlob);
@@ -207,6 +228,17 @@
return mDevice->halVersion().securityLevel != km::SecurityLevel::SOFTWARE;
}
+void Keymaster::earlyBootEnded() {
+ auto error = mDevice->earlyBootEnded();
+ if (!error.isOk()) {
+ LOG(ERROR) << "earlyBootEnded failed: " << error.description();
+ }
+ km::V4_1_ErrorCode km_error = error;
+ if (km_error != km::V4_1_ErrorCode::OK && km_error != km::V4_1_ErrorCode::UNIMPLEMENTED) {
+ LOG(ERROR) << "Error reporting early boot ending to keymaster: " << int32_t(km_error);
+ }
+}
+
} // namespace vold
} // namespace android
diff --git a/Keymaster.h b/Keymaster.h
index 42a2b5d..ea102f5 100644
--- a/Keymaster.h
+++ b/Keymaster.h
@@ -24,13 +24,25 @@
#include <utility>
#include <android-base/macros.h>
-#include <keymasterV4_0/Keymaster.h>
-#include <keymasterV4_0/authorization_set.h>
+#include <keymasterV4_1/Keymaster.h>
+#include <keymasterV4_1/authorization_set.h>
namespace android {
namespace vold {
-namespace km = ::android::hardware::keymaster::V4_0;
+namespace km {
+
+using namespace ::android::hardware::keymaster::V4_1;
+
+// Surprisingly -- to me, at least -- this is totally fine. You can re-define symbols that were
+// brought in via a using directive (the "using namespace") above. In general this seems like a
+// dangerous thing to rely on, but in this case its implications are simple and straightforward:
+// km::ErrorCode refers to the 4.0 ErrorCode, though we pull everything else from 4.1.
+using ErrorCode = ::android::hardware::keymaster::V4_0::ErrorCode;
+using V4_1_ErrorCode = ::android::hardware::keymaster::V4_1::ErrorCode;
+
+} // namespace km
+
using KmDevice = km::support::Keymaster;
// C++ wrappers to the Keymaster hidl interface.
@@ -102,6 +114,8 @@
explicit operator bool() { return mDevice.get() != nullptr; }
// Generate a key in the keymaster from the given params.
bool generateKey(const km::AuthorizationSet& inParams, std::string* key);
+ // Exports a keymaster key with STORAGE_KEY tag wrapped with a per-boot ephemeral key
+ bool exportKey(const KeyBuffer& kmKey, std::string* key);
// If the keymaster supports it, permanently delete a key.
bool deleteKey(const std::string& key);
// Replace stored key blob in response to KM_ERROR_KEY_REQUIRES_UPGRADE.
@@ -114,6 +128,10 @@
km::AuthorizationSet* outParams);
bool isSecure();
+ // Tell Keymaster that early boot has ended and early boot-only keys can no longer be created or
+ // used.
+ void earlyBootEnded();
+
private:
std::unique_ptr<KmDevice> mDevice;
DISALLOW_COPY_AND_ASSIGN(Keymaster);
diff --git a/Loop.cpp b/Loop.cpp
index f5d2481..9fa876c 100644
--- a/Loop.cpp
+++ b/Loop.cpp
@@ -32,12 +32,12 @@
#include <linux/kdev_t.h>
#include <chrono>
-#include <thread>
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
+#include <fs_mgr/file_wait.h>
#include <utils/Trace.h>
#include "Loop.h"
@@ -51,22 +51,6 @@
static const char* kVoldPrefix = "vold:";
static constexpr size_t kLoopDeviceRetryAttempts = 3u;
-static bool wait_for_file(const std::string& filename,
- const std::chrono::milliseconds relative_timeout) {
- auto start_time = std::chrono::steady_clock::now();
-
- while (true) {
- int rv = access(filename.c_str(), F_OK);
- if (!rv || errno != ENOENT) return true;
-
- std::this_thread::sleep_for(50ms);
-
- auto now = std::chrono::steady_clock::now();
- auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
- if (time_elapsed > relative_timeout) return false;
- }
-}
-
int Loop::create(const std::string& target, std::string& out_device) {
unique_fd ctl_fd(open("/dev/loop-control", O_RDWR | O_CLOEXEC));
if (ctl_fd.get() == -1) {
@@ -94,12 +78,10 @@
PLOG(ERROR) << "Failed to open " << target;
return -errno;
}
-
- if (!wait_for_file(out_device, 2s)) {
+ if (!android::fs_mgr::WaitForFile(out_device, 2s)) {
LOG(ERROR) << "Failed to find " << out_device;
return -ENOENT;
}
-
unique_fd device_fd(open(out_device.c_str(), O_RDWR | O_CLOEXEC));
if (device_fd.get() == -1) {
PLOG(ERROR) << "Failed to open " << out_device;
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
index 35cf3e2..8227e74 100644
--- a/MetadataCrypt.cpp
+++ b/MetadataCrypt.cpp
@@ -23,21 +23,21 @@
#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/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
+#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <cutils/fs.h>
#include <fs_mgr.h>
+#include <libdm/dm.h>
#include "Checkpoint.h"
+#include "CryptoType.h"
#include "EncryptInplace.h"
#include "KeyStorage.h"
#include "KeyUtil.h"
@@ -45,20 +45,56 @@
#include "Utils.h"
#include "VoldUtil.h"
-#define DM_CRYPT_BUF_SIZE 4096
#define TABLE_LOAD_RETRIES 10
-#define DEFAULT_KEY_TARGET_TYPE "default-key"
+
+namespace android {
+namespace vold {
using android::fs_mgr::FstabEntry;
using android::fs_mgr::GetEntryForMountPoint;
using android::vold::KeyBuffer;
+using namespace android::dm;
+
+// Parsed from metadata options
+struct CryptoOptions {
+ struct CryptoType cipher = invalid_crypto_type;
+ bool is_legacy = false;
+ bool set_dun = true; // Non-legacy driver always sets DUN
+ bool use_hw_wrapped_key = false;
+};
static const std::string kDmNameUserdata = "userdata";
static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
+// The first entry in this table is the default crypto type.
+constexpr CryptoType supported_crypto_types[] = {aes_256_xts, adiantum};
+
+static_assert(validateSupportedCryptoTypes(64, supported_crypto_types,
+ array_length(supported_crypto_types)),
+ "We have a CryptoType which was incompletely constructed.");
+
+constexpr CryptoType legacy_aes_256_xts =
+ CryptoType().set_config_name("aes-256-xts").set_kernel_name("AES-256-XTS").set_keysize(64);
+
+static_assert(isValidCryptoType(64, legacy_aes_256_xts),
+ "We have a CryptoType which was incompletely constructed.");
+
+// Returns KeyGeneration suitable for key as described in CryptoOptions
+const KeyGeneration makeGen(const CryptoOptions& options) {
+ return KeyGeneration{options.cipher.get_keysize(), true, options.use_hw_wrapped_key};
+}
+
static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device) {
+ // We're about to mount data not verified by verified boot. Tell Keymaster that early boot has
+ // ended.
+ //
+ // TODO(paulcrowley): Make a Keymaster singleton or something, so we don't have to repeatedly
+ // open and initialize the service.
+ ::android::vold::Keymaster keymaster;
+ keymaster.earlyBootEnded();
+
// fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
// partitions in the fsck domain.
if (setexeccon(android::vold::sFsckContext)) {
@@ -80,9 +116,6 @@
return true;
}
-namespace android {
-namespace vold {
-
// Note: It is possible to orphan a key if it is removed before deleting
// Update this once keymaster APIs change, and we have a proper commit.
static void commit_key(const std::string& dir) {
@@ -108,20 +141,20 @@
LOG(INFO) << "Old Key deleted: " << dir;
}
-static bool read_key(const FstabEntry& data_rec, bool create_if_absent, KeyBuffer* key) {
- if (data_rec.key_dir.empty()) {
- LOG(ERROR) << "Failed to get key_dir";
+static bool read_key(const std::string& metadata_key_dir, const KeyGeneration& gen,
+ KeyBuffer* key) {
+ if (metadata_key_dir.empty()) {
+ LOG(ERROR) << "Failed to get metadata_key_dir";
return false;
}
- std::string key_dir = data_rec.key_dir;
std::string sKey;
- auto dir = key_dir + "/key";
- LOG(DEBUG) << "key_dir/key: " << dir;
+ auto dir = metadata_key_dir + "/key";
+ LOG(DEBUG) << "metadata_key_dir/key: " << dir;
if (fs_mkdirs(dir.c_str(), 0700)) {
PLOG(ERROR) << "Creating directories: " << dir;
return false;
}
- auto temp = key_dir + "/tmp";
+ auto temp = metadata_key_dir + "/tmp";
auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
/* If we have a leftover upgraded key, delete it.
* We either failed an update and must return to the old key,
@@ -131,31 +164,18 @@
Keymaster keymaster;
if (pathExists(newKeyPath)) {
if (!android::base::ReadFileToString(newKeyPath, &sKey))
- LOG(ERROR) << "Failed to read old key: " << dir;
+ LOG(ERROR) << "Failed to read incomplete key: " << dir;
else if (!keymaster.deleteKey(sKey))
- LOG(ERROR) << "Old key deletion failed, continuing anyway: " << dir;
+ LOG(ERROR) << "Incomplete key deletion failed, continuing anyway: " << dir;
else
unlink(newKeyPath.c_str());
}
bool needs_cp = cp_needsCheckpoint();
- if (!android::vold::retrieveKey(create_if_absent, dir, temp, key, needs_cp)) return false;
+ if (!retrieveOrGenerateKey(dir, temp, kEmptyAuthentication, gen, key, needs_cp)) return false;
if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
return true;
}
-} // namespace vold
-} // namespace android
-
-static KeyBuffer default_key_params(const std::string& real_blkdev, const KeyBuffer& key) {
- KeyBuffer hex_key;
- if (android::vold::StrToHex(key, hex_key) != android::OK) {
- LOG(ERROR) << "Failed to turn key to hex";
- return KeyBuffer();
- }
- auto res = KeyBuffer() + "AES-256-XTS " + hex_key + " " + real_blkdev.c_str() + " 0";
- return res;
-}
-
static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) {
if (android::vold::GetBlockDev512Sectors(real_blkdev, nr_sec) != android::OK) {
PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
@@ -164,112 +184,137 @@
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;
+static bool create_crypto_blk_dev(const std::string& dm_name, const std::string& blk_device,
+ const KeyBuffer& key, const CryptoOptions& options,
+ std::string* crypto_blkdev, uint64_t* nr_sec) {
+ if (!get_number_of_sectors(blk_device, nr_sec)) return false;
+ // TODO(paulcrowley): don't hardcode that DmTargetDefaultKey uses 4096-byte
+ // sectors
+ *nr_sec &= ~7;
+
+ KeyBuffer module_key;
+ if (options.use_hw_wrapped_key) {
+ if (!exportWrappedStorageKey(key, &module_key)) {
+ LOG(ERROR) << "Failed to get ephemeral wrapped key";
+ return false;
+ }
+ } else {
+ module_key = key;
}
- 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 KeyBuffer& crypt_params,
- std::string* crypto_blkdev) {
- android::base::unique_fd dm_fd(
- TEMP_FAILURE_RETRY(open("/dev/device-mapper", O_RDWR | O_CLOEXEC, 0)));
- if (dm_fd == -1) {
- PLOG(ERROR) << "Cannot open device-mapper";
+ KeyBuffer hex_key_buffer;
+ if (android::vold::StrToHex(module_key, hex_key_buffer) != android::OK) {
+ LOG(ERROR) << "Failed to turn key to hex";
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;
- }
+ std::string hex_key(hex_key_buffer.data(), hex_key_buffer.size());
- // 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));
+ auto target = std::make_unique<DmTargetDefaultKey>(0, *nr_sec, options.cipher.get_kernel_name(),
+ hex_key, blk_device, 0);
+ if (options.is_legacy) target->SetIsLegacy();
+ if (options.set_dun) target->SetSetDun();
+ if (options.use_hw_wrapped_key) target->SetWrappedKeyV0();
- io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
- size_t paramix = io->data_start + sizeof(struct dm_target_spec);
- size_t nullix = paramix + crypt_params.size();
- size_t endix = (nullix + 1 + 7) & 8; // Add room for \0 and align to 8 byte boundary
+ DmTable table;
+ table.AddTarget(std::move(target));
- 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));
- memcpy(buffer + paramix, crypt_params.data(),
- std::min(crypt_params.size(), sizeof(buffer) - paramix));
- buffer[nullix] = '\0';
- tgt->next = endix;
-
+ auto& dm = DeviceMapper::Instance();
for (int i = 0;; i++) {
- if (ioctl(dm_fd.get(), DM_TABLE_LOAD, io) == 0) {
+ if (dm.CreateDevice(dm_name, table)) {
break;
}
if (i + 1 >= TABLE_LOAD_RETRIES) {
- PLOG(ERROR) << "DM_TABLE_LOAD ioctl failed";
+ PLOG(ERROR) << "Could not create default-key device " << dm_name;
return false;
}
- PLOG(INFO) << "DM_TABLE_LOAD ioctl failed, retrying";
+ PLOG(INFO) << "Could not create default-key device, 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;
+ if (!dm.GetDmDevicePathByName(dm_name, crypto_blkdev)) {
+ LOG(ERROR) << "Cannot retrieve default-key device status " << dm_name;
return false;
}
return true;
}
+static const CryptoType& lookup_cipher(const std::string& cipher_name) {
+ if (cipher_name.empty()) return supported_crypto_types[0];
+ for (size_t i = 0; i < array_length(supported_crypto_types); i++) {
+ if (cipher_name == supported_crypto_types[i].get_config_name()) {
+ return supported_crypto_types[i];
+ }
+ }
+ return invalid_crypto_type;
+}
+
+static bool parse_options(const std::string& options_string, CryptoOptions* options) {
+ auto parts = android::base::Split(options_string, ":");
+ if (parts.size() < 1 || parts.size() > 2) {
+ LOG(ERROR) << "Invalid metadata encryption option: " << options_string;
+ return false;
+ }
+ std::string cipher_name = parts[0];
+ options->cipher = lookup_cipher(cipher_name);
+ if (options->cipher.get_kernel_name() == nullptr) {
+ LOG(ERROR) << "No metadata cipher named " << cipher_name << " found";
+ return false;
+ }
+
+ if (parts.size() == 2) {
+ if (parts[1] == "wrappedkey_v0") {
+ options->use_hw_wrapped_key = true;
+ } else {
+ LOG(ERROR) << "Invalid metadata encryption flag: " << parts[1];
+ return false;
+ }
+ }
+ return true;
+}
+
bool fscrypt_mount_metadata_encrypted(const std::string& blk_device, const std::string& mount_point,
bool needs_encrypt) {
LOG(DEBUG) << "fscrypt_mount_metadata_encrypted: " << mount_point << " " << needs_encrypt;
auto encrypted_state = android::base::GetProperty("ro.crypto.state", "");
- if (encrypted_state != "") {
+ if (encrypted_state != "" && encrypted_state != "encrypted") {
LOG(DEBUG) << "fscrypt_enable_crypto got unexpected starting state: " << encrypted_state;
return false;
}
auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
if (!data_rec) {
- LOG(ERROR) << "Failed to get data_rec";
+ LOG(ERROR) << "Failed to get data_rec for " << mount_point;
return false;
}
+
+ bool is_legacy;
+ if (!DmTargetDefaultKey::IsLegacy(&is_legacy)) return false;
+
+ CryptoOptions options;
+ if (is_legacy) {
+ if (!data_rec->metadata_encryption.empty()) {
+ LOG(ERROR) << "metadata_encryption options cannot be set in legacy mode";
+ return false;
+ }
+ options.cipher = legacy_aes_256_xts;
+ options.is_legacy = true;
+ options.set_dun = android::base::GetBoolProperty("ro.crypto.set_dun", false);
+ if (!options.set_dun && data_rec->fs_mgr_flags.checkpoint_blk) {
+ LOG(ERROR)
+ << "Block checkpoints and metadata encryption require ro.crypto.set_dun option";
+ return false;
+ }
+ } else {
+ if (!parse_options(data_rec->metadata_encryption, &options)) return false;
+ }
+
+ auto gen = needs_encrypt ? makeGen(options) : neverGen();
KeyBuffer key;
- if (!read_key(*data_rec, needs_encrypt, &key)) return false;
- uint64_t nr_sec;
- if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
+ if (!read_key(data_rec->metadata_key_dir, gen, &key)) return false;
+
std::string crypto_blkdev;
- if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
- default_key_params(blk_device, key), &crypto_blkdev))
+ uint64_t nr_sec;
+ if (!create_crypto_blk_dev(kDmNameUserdata, blk_device, key, options, &crypto_blkdev, &nr_sec))
return false;
// FIXME handle the corrupt case
@@ -290,6 +335,31 @@
}
LOG(DEBUG) << "Mounting metadata-encrypted filesystem:" << mount_point;
- mount_via_fs_mgr(data_rec->mount_point.c_str(), crypto_blkdev.c_str());
+ mount_via_fs_mgr(mount_point.c_str(), crypto_blkdev.c_str());
return true;
}
+
+static bool get_volume_options(CryptoOptions* options) {
+ return parse_options(android::base::GetProperty("ro.crypto.volume.metadata.encryption", ""),
+ options);
+}
+
+bool defaultkey_volume_keygen(KeyGeneration* gen) {
+ CryptoOptions options;
+ if (!get_volume_options(&options)) return false;
+ *gen = makeGen(options);
+ return true;
+}
+
+bool defaultkey_setup_ext_volume(const std::string& label, const std::string& blk_device,
+ const KeyBuffer& key, std::string* out_crypto_blkdev) {
+ LOG(DEBUG) << "defaultkey_setup_ext_volume: " << label << " " << blk_device;
+
+ CryptoOptions options;
+ if (!get_volume_options(&options)) return false;
+ uint64_t nr_sec;
+ return create_crypto_blk_dev(label, blk_device, key, options, out_crypto_blkdev, &nr_sec);
+}
+
+} // namespace vold
+} // namespace android
diff --git a/MetadataCrypt.h b/MetadataCrypt.h
index cd0f5e5..dc68e7c 100644
--- a/MetadataCrypt.h
+++ b/MetadataCrypt.h
@@ -19,7 +19,21 @@
#include <string>
+#include "KeyBuffer.h"
+#include "KeyUtil.h"
+
+namespace android {
+namespace vold {
+
bool fscrypt_mount_metadata_encrypted(const std::string& block_device,
const std::string& mount_point, bool needs_encrypt);
+bool defaultkey_volume_keygen(KeyGeneration* gen);
+
+bool defaultkey_setup_ext_volume(const std::string& label, const std::string& blk_device,
+ const android::vold::KeyBuffer& key,
+ std::string* out_crypto_blkdev);
+
+} // namespace vold
+} // namespace android
#endif
diff --git a/MoveStorage.cpp b/MoveStorage.cpp
index 79a47ae..2447cce 100644
--- a/MoveStorage.cpp
+++ b/MoveStorage.cpp
@@ -21,8 +21,8 @@
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
-#include <hardware_legacy/power.h>
#include <private/android_filesystem_config.h>
+#include <wakelock/wakelock.h>
#include <thread>
@@ -258,15 +258,13 @@
void MoveStorage(const std::shared_ptr<VolumeBase>& from, const std::shared_ptr<VolumeBase>& to,
const android::sp<android::os::IVoldTaskListener>& listener) {
- acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+ android::wakelock::WakeLock wl{kWakeLock};
android::os::PersistableBundle extras;
status_t res = moveStorageInternal(from, to, listener);
if (listener) {
listener->onFinished(res, extras);
}
-
- release_wake_lock(kWakeLock);
}
} // namespace vold
diff --git a/OWNERS b/OWNERS
index 4e45284..bab0ef6 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,3 +1,6 @@
jsharkey@android.com
paulcrowley@google.com
paullawrence@google.com
+ebiggers@google.com
+drosen@google.com
+zezeozue@google.com
diff --git a/Utils.cpp b/Utils.cpp
index df50658..1616d80 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -43,6 +43,7 @@
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <sys/wait.h>
+#include <unistd.h>
#include <list>
#include <mutex>
diff --git a/VoldNativeService.cpp b/VoldNativeService.cpp
index 7f7f289..e894909 100644
--- a/VoldNativeService.cpp
+++ b/VoldNativeService.cpp
@@ -17,18 +17,22 @@
#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
#include "VoldNativeService.h"
+
#include "Benchmark.h"
#include "CheckEncryption.h"
-#include "IdleMaint.h"
-#include "MoveStorage.h"
-#include "Process.h"
-#include "VolumeManager.h"
-
#include "Checkpoint.h"
#include "FsCrypt.h"
+#include "IdleMaint.h"
#include "MetadataCrypt.h"
+#include "MoveStorage.h"
+#include "Process.h"
+#include "VoldNativeServiceValidation.h"
+#include "VoldUtil.h"
+#include "VolumeManager.h"
#include "cryptfs.h"
+#include "incfs_ndk.h"
+
#include <fstream>
#include <thread>
@@ -42,6 +46,7 @@
using android::base::StringPrintf;
using std::endl;
+using namespace std::literals;
namespace android {
namespace vold {
@@ -50,14 +55,6 @@
constexpr const char* kDump = "android.permission.DUMP";
-static binder::Status ok() {
- return binder::Status::ok();
-}
-
-static binder::Status exception(uint32_t code, const std::string& msg) {
- return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
-}
-
static binder::Status error(const std::string& msg) {
PLOG(ERROR) << msg;
return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
@@ -79,85 +76,17 @@
}
}
-binder::Status checkPermission(const char* permission) {
- pid_t pid;
- uid_t uid;
-
- if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
- reinterpret_cast<int32_t*>(&uid))) {
- return ok();
- } else {
- return exception(binder::Status::EX_SECURITY,
- StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
- }
-}
-
-binder::Status checkUid(uid_t expectedUid) {
- uid_t uid = IPCThreadState::self()->getCallingUid();
- if (uid == expectedUid || uid == AID_ROOT) {
- return ok();
- } else {
- return exception(binder::Status::EX_SECURITY,
- StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
- }
-}
-
-binder::Status checkArgumentId(const std::string& id) {
- if (id.empty()) {
- return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing ID");
- }
- for (const char& c : id) {
- if (!std::isalnum(c) && c != ':' && c != ',') {
- return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("ID %s is malformed", id.c_str()));
- }
- }
- return ok();
-}
-
-binder::Status checkArgumentPath(const std::string& path) {
- if (path.empty()) {
- return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
- }
- if (path[0] != '/') {
- return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("Path %s is relative", path.c_str()));
- }
- if ((path + '/').find("/../") != std::string::npos) {
- return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("Path %s is shady", path.c_str()));
- }
- for (const char& c : path) {
- if (c == '\0' || c == '\n') {
- return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("Path %s is malformed", path.c_str()));
- }
- }
- return ok();
-}
-
-binder::Status checkArgumentHex(const std::string& hex) {
- // Empty hex strings are allowed
- for (const char& c : hex) {
- if (!std::isxdigit(c) && c != ':' && c != '-') {
- return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("Hex %s is malformed", hex.c_str()));
- }
- }
- return ok();
-}
-
-#define ENFORCE_UID(uid) \
- { \
- binder::Status status = checkUid((uid)); \
- if (!status.isOk()) { \
- return status; \
- } \
+#define ENFORCE_SYSTEM_OR_ROOT \
+ { \
+ binder::Status status = CheckUidOrRoot(AID_SYSTEM); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
}
#define CHECK_ARGUMENT_ID(id) \
{ \
- binder::Status status = checkArgumentId((id)); \
+ binder::Status status = CheckArgumentId((id)); \
if (!status.isOk()) { \
return status; \
} \
@@ -165,7 +94,7 @@
#define CHECK_ARGUMENT_PATH(path) \
{ \
- binder::Status status = checkArgumentPath((path)); \
+ binder::Status status = CheckArgumentPath((path)); \
if (!status.isOk()) { \
return status; \
} \
@@ -173,7 +102,7 @@
#define CHECK_ARGUMENT_HEX(hex) \
{ \
- binder::Status status = checkArgumentHex((hex)); \
+ binder::Status status = CheckArgumentHex((hex)); \
if (!status.isOk()) { \
return status; \
} \
@@ -203,7 +132,7 @@
status_t VoldNativeService::dump(int fd, const Vector<String16>& /* args */) {
auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
- const binder::Status dump_permission = checkPermission(kDump);
+ const binder::Status dump_permission = CheckPermission(kDump);
if (!dump_permission.isOk()) {
out << dump_permission.toString8() << endl;
return PERMISSION_DENIED;
@@ -211,66 +140,65 @@
ACQUIRE_LOCK;
out << "vold is happy!" << endl;
- out.flush();
return NO_ERROR;
}
binder::Status VoldNativeService::setListener(
const android::sp<android::os::IVoldListener>& listener) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
VolumeManager::Instance()->setListener(listener);
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::monitor() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
// Simply acquire/release each lock for watchdog
{ ACQUIRE_LOCK; }
{ ACQUIRE_CRYPT_LOCK; }
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::reset() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->reset());
}
binder::Status VoldNativeService::shutdown() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->shutdown());
}
binder::Status VoldNativeService::onUserAdded(int32_t userId, int32_t userSerial) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->onUserAdded(userId, userSerial));
}
binder::Status VoldNativeService::onUserRemoved(int32_t userId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->onUserRemoved(userId));
}
binder::Status VoldNativeService::onUserStarted(int32_t userId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->onUserStarted(userId));
}
binder::Status VoldNativeService::onUserStopped(int32_t userId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->onUserStopped(userId));
@@ -278,16 +206,16 @@
binder::Status VoldNativeService::addAppIds(const std::vector<std::string>& packageNames,
const std::vector<int32_t>& appIds) {
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::addSandboxIds(const std::vector<int32_t>& appIds,
const std::vector<std::string>& sandboxIds) {
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::onSecureKeyguardStateChanged(bool isShowing) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->onSecureKeyguardStateChanged(isShowing));
@@ -295,7 +223,7 @@
binder::Status VoldNativeService::partition(const std::string& diskId, int32_t partitionType,
int32_t ratio) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(diskId);
ACQUIRE_LOCK;
@@ -317,7 +245,7 @@
binder::Status VoldNativeService::forgetPartition(const std::string& partGuid,
const std::string& fsUuid) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_HEX(partGuid);
CHECK_ARGUMENT_HEX(fsUuid);
ACQUIRE_LOCK;
@@ -327,7 +255,7 @@
binder::Status VoldNativeService::mount(const std::string& volId, int32_t mountFlags,
int32_t mountUserId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(volId);
ACQUIRE_LOCK;
@@ -353,7 +281,7 @@
}
binder::Status VoldNativeService::unmount(const std::string& volId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(volId);
ACQUIRE_LOCK;
@@ -365,7 +293,7 @@
}
binder::Status VoldNativeService::format(const std::string& volId, const std::string& fsType) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(volId);
ACQUIRE_LOCK;
@@ -395,12 +323,12 @@
return error("Volume " + volId + " missing path");
}
}
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::benchmark(
const std::string& volId, const android::sp<android::os::IVoldTaskListener>& listener) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(volId);
ACQUIRE_LOCK;
@@ -409,11 +337,11 @@
if (!status.isOk()) return status;
std::thread([=]() { android::vold::Benchmark(path, listener); }).detach();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::checkEncryption(const std::string& volId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(volId);
ACQUIRE_LOCK;
@@ -426,7 +354,7 @@
binder::Status VoldNativeService::moveStorage(
const std::string& fromVolId, const std::string& toVolId,
const android::sp<android::os::IVoldTaskListener>& listener) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(fromVolId);
CHECK_ARGUMENT_ID(toVolId);
ACQUIRE_LOCK;
@@ -440,18 +368,18 @@
}
std::thread([=]() { android::vold::MoveStorage(fromVol, toVol, listener); }).detach();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::remountUid(int32_t uid, int32_t remountMode) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->remountUid(uid, remountMode));
}
binder::Status VoldNativeService::mkdirs(const std::string& path) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_PATH(path);
ACQUIRE_LOCK;
@@ -461,7 +389,7 @@
binder::Status VoldNativeService::createObb(const std::string& sourcePath,
const std::string& sourceKey, int32_t ownerGid,
std::string* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_PATH(sourcePath);
CHECK_ARGUMENT_HEX(sourceKey);
ACQUIRE_LOCK;
@@ -471,7 +399,7 @@
}
binder::Status VoldNativeService::destroyObb(const std::string& volId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(volId);
ACQUIRE_LOCK;
@@ -481,7 +409,7 @@
binder::Status VoldNativeService::createStubVolume(
const std::string& sourcePath, const std::string& mountPath, const std::string& fsType,
const std::string& fsUuid, const std::string& fsLabel, std::string* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_PATH(sourcePath);
CHECK_ARGUMENT_PATH(mountPath);
CHECK_ARGUMENT_HEX(fsUuid);
@@ -494,7 +422,7 @@
}
binder::Status VoldNativeService::destroyStubVolume(const std::string& volId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_ID(volId);
ACQUIRE_LOCK;
@@ -503,41 +431,41 @@
binder::Status VoldNativeService::fstrim(
int32_t fstrimFlags, const android::sp<android::os::IVoldTaskListener>& listener) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
std::thread([=]() { android::vold::Trim(listener); }).detach();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::runIdleMaint(
const android::sp<android::os::IVoldTaskListener>& listener) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
std::thread([=]() { android::vold::RunIdleMaint(listener); }).detach();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::abortIdleMaint(
const android::sp<android::os::IVoldTaskListener>& listener) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
std::thread([=]() { android::vold::AbortIdleMaint(listener); }).detach();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::mountAppFuse(int32_t uid, int32_t mountId,
android::base::unique_fd* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->mountAppFuse(uid, mountId, _aidl_return));
}
binder::Status VoldNativeService::unmountAppFuse(int32_t uid, int32_t mountId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translate(VolumeManager::Instance()->unmountAppFuse(uid, mountId));
@@ -546,7 +474,7 @@
binder::Status VoldNativeService::openAppFuseFile(int32_t uid, int32_t mountId, int32_t fileId,
int32_t flags,
android::base::unique_fd* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
int fd = VolumeManager::Instance()->openAppFuseFile(uid, mountId, fileId, flags);
@@ -557,32 +485,32 @@
}
*_aidl_return = android::base::unique_fd(fd);
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::fdeCheckPassword(const std::string& password) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translate(cryptfs_check_passwd(password.c_str()));
}
binder::Status VoldNativeService::fdeRestart() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
// 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_restart).detach();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::fdeComplete(int32_t* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
*_aidl_return = cryptfs_crypto_complete();
- return ok();
+ return Ok();
}
static int fdeEnableInternal(int32_t passwordType, const std::string& password,
@@ -609,7 +537,7 @@
binder::Status VoldNativeService::fdeEnable(int32_t passwordType, const std::string& password,
int32_t encryptionFlags) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
LOG(DEBUG) << "fdeEnable(" << passwordType << ", *, " << encryptionFlags << ")";
@@ -622,26 +550,26 @@
// Spawn as thread so init can issue commands back to vold without
// causing deadlock, usually as a result of prep_data_fs.
std::thread(&fdeEnableInternal, passwordType, password, encryptionFlags).detach();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::fdeChangePassword(int32_t passwordType,
const std::string& password) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translate(cryptfs_changepw(passwordType, password.c_str()));
}
binder::Status VoldNativeService::fdeVerifyPassword(const std::string& password) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translate(cryptfs_verify_passwd(password.c_str()));
}
binder::Status VoldNativeService::fdeGetField(const std::string& key, std::string* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
char buf[PROPERTY_VALUE_MAX];
@@ -649,53 +577,53 @@
return error(StringPrintf("Failed to read field %s", key.c_str()));
} else {
*_aidl_return = buf;
- return ok();
+ return Ok();
}
}
binder::Status VoldNativeService::fdeSetField(const std::string& key, const std::string& value) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translate(cryptfs_setfield(key.c_str(), value.c_str()));
}
binder::Status VoldNativeService::fdeGetPasswordType(int32_t* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
*_aidl_return = cryptfs_get_password_type();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::fdeGetPassword(std::string* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
const char* res = cryptfs_get_password();
if (res != nullptr) {
*_aidl_return = res;
}
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::fdeClearPassword() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
cryptfs_clear_password();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::fbeEnable() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translateBool(fscrypt_initialize_systemwide_keys());
}
binder::Status VoldNativeService::mountDefaultEncrypted() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
if (!fscrypt_is_native()) {
@@ -703,27 +631,27 @@
// causing deadlock, usually as a result of prep_data_fs.
std::thread(&cryptfs_mount_default_encrypted).detach();
}
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::initUser0() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translateBool(fscrypt_init_user0());
}
binder::Status VoldNativeService::isConvertibleToFbe(bool* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
*_aidl_return = cryptfs_isConvertibleToFBE() != 0;
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::mountFstab(const std::string& blkDevice,
const std::string& mountPoint) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, false));
@@ -731,21 +659,21 @@
binder::Status VoldNativeService::encryptFstab(const std::string& blkDevice,
const std::string& mountPoint) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, true));
}
binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial, bool ephemeral) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translateBool(fscrypt_vold_create_user_key(userId, userSerial, ephemeral));
}
binder::Status VoldNativeService::destroyUserKey(int32_t userId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translateBool(fscrypt_destroy_user_key(userId));
@@ -754,14 +682,23 @@
binder::Status VoldNativeService::addUserKeyAuth(int32_t userId, int32_t userSerial,
const std::string& token,
const std::string& secret) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translateBool(fscrypt_add_user_key_auth(userId, userSerial, token, secret));
}
+binder::Status VoldNativeService::clearUserKeyAuth(int32_t userId, int32_t userSerial,
+ const std::string& token,
+ const std::string& secret) {
+ ENFORCE_SYSTEM_OR_ROOT;
+ ACQUIRE_CRYPT_LOCK;
+
+ return translateBool(fscrypt_clear_user_key_auth(userId, userSerial, token, secret));
+}
+
binder::Status VoldNativeService::fixateNewestUserKeyAuth(int32_t userId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translateBool(fscrypt_fixate_newest_user_key_auth(userId));
@@ -770,23 +707,23 @@
binder::Status VoldNativeService::unlockUserKey(int32_t userId, int32_t userSerial,
const std::string& token,
const std::string& secret) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translateBool(fscrypt_unlock_user_key(userId, userSerial, token, secret));
}
binder::Status VoldNativeService::lockUserKey(int32_t userId) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_CRYPT_LOCK;
return translateBool(fscrypt_lock_user_key(userId));
}
-binder::Status VoldNativeService::prepareUserStorage(const std::unique_ptr<std::string>& uuid,
+binder::Status VoldNativeService::prepareUserStorage(const std::optional<std::string>& uuid,
int32_t userId, int32_t userSerial,
int32_t flags) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
std::string empty_string = "";
auto uuid_ = uuid ? *uuid : empty_string;
CHECK_ARGUMENT_HEX(uuid_);
@@ -795,9 +732,9 @@
return translateBool(fscrypt_prepare_user_storage(uuid_, userId, userSerial, flags));
}
-binder::Status VoldNativeService::destroyUserStorage(const std::unique_ptr<std::string>& uuid,
+binder::Status VoldNativeService::destroyUserStorage(const std::optional<std::string>& uuid,
int32_t userId, int32_t flags) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
std::string empty_string = "";
auto uuid_ = uuid ? *uuid : empty_string;
CHECK_ARGUMENT_HEX(uuid_);
@@ -809,54 +746,54 @@
binder::Status VoldNativeService::prepareSandboxForApp(const std::string& packageName,
int32_t appId, const std::string& sandboxId,
int32_t userId) {
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::destroySandboxForApp(const std::string& packageName,
const std::string& sandboxId,
int32_t userId) {
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::startCheckpoint(int32_t retry) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return cp_startCheckpoint(retry);
}
binder::Status VoldNativeService::needsRollback(bool* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
*_aidl_return = cp_needsRollback();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::needsCheckpoint(bool* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
*_aidl_return = cp_needsCheckpoint();
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::commitChanges() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return cp_commitChanges();
}
binder::Status VoldNativeService::prepareCheckpoint() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return cp_prepareCheckpoint();
}
binder::Status VoldNativeService::restoreCheckpoint(const std::string& mountPoint) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_PATH(mountPoint);
ACQUIRE_LOCK;
@@ -864,7 +801,7 @@
}
binder::Status VoldNativeService::restoreCheckpointPart(const std::string& mountPoint, int count) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
CHECK_ARGUMENT_PATH(mountPoint);
ACQUIRE_LOCK;
@@ -872,40 +809,94 @@
}
binder::Status VoldNativeService::markBootAttempt() {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return cp_markBootAttempt();
}
binder::Status VoldNativeService::abortChanges(const std::string& message, bool retry) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
cp_abortChanges(message, retry);
- return ok();
+ return Ok();
}
binder::Status VoldNativeService::supportsCheckpoint(bool* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return cp_supportsCheckpoint(*_aidl_return);
}
binder::Status VoldNativeService::supportsBlockCheckpoint(bool* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return cp_supportsBlockCheckpoint(*_aidl_return);
}
binder::Status VoldNativeService::supportsFileCheckpoint(bool* _aidl_return) {
- ENFORCE_UID(AID_SYSTEM);
+ ENFORCE_SYSTEM_OR_ROOT;
ACQUIRE_LOCK;
return cp_supportsFileCheckpoint(*_aidl_return);
}
+binder::Status VoldNativeService::resetCheckpoint() {
+ ENFORCE_SYSTEM_OR_ROOT;
+ ACQUIRE_LOCK;
+
+ cp_resetCheckpoint();
+ return Ok();
+}
+
+binder::Status VoldNativeService::incFsEnabled(bool* _aidl_return) {
+ ENFORCE_SYSTEM_OR_ROOT;
+
+ *_aidl_return = IncFs_IsEnabled();
+ return Ok();
+}
+
+binder::Status VoldNativeService::mountIncFs(
+ const std::string& backingPath, const std::string& targetDir, int32_t flags,
+ ::android::os::incremental::IncrementalFileSystemControlParcel* _aidl_return) {
+ ENFORCE_SYSTEM_OR_ROOT;
+ CHECK_ARGUMENT_PATH(backingPath);
+ CHECK_ARGUMENT_PATH(targetDir);
+
+ auto result = IncFs_Mount(backingPath.c_str(), targetDir.c_str(),
+ {.flags = IncFsMountFlags(flags),
+ .defaultReadTimeoutMs = INCFS_DEFAULT_READ_TIMEOUT_MS,
+ .readLogBufferPages = 4});
+ if (result.cmd < 0) {
+ return translate(result.cmd);
+ }
+ using unique_fd = ::android::base::unique_fd;
+ _aidl_return->cmd.emplace(unique_fd(result.cmd));
+ _aidl_return->pendingReads.emplace(unique_fd(result.pendingReads));
+ if (result.logs >= 0) {
+ _aidl_return->log.emplace(unique_fd(result.logs));
+ }
+ return Ok();
+}
+
+binder::Status VoldNativeService::unmountIncFs(const std::string& dir) {
+ ENFORCE_SYSTEM_OR_ROOT;
+ CHECK_ARGUMENT_PATH(dir);
+
+ return translate(IncFs_Unmount(dir.c_str()));
+}
+
+binder::Status VoldNativeService::bindMount(const std::string& sourceDir,
+ const std::string& targetDir) {
+ ENFORCE_SYSTEM_OR_ROOT;
+ CHECK_ARGUMENT_PATH(sourceDir);
+ CHECK_ARGUMENT_PATH(targetDir);
+
+ return translate(IncFs_BindMount(sourceDir.c_str(), targetDir.c_str()));
+}
+
} // namespace vold
} // namespace android
diff --git a/VoldNativeService.h b/VoldNativeService.h
index 07a0b9f..4578dc0 100644
--- a/VoldNativeService.h
+++ b/VoldNativeService.h
@@ -112,15 +112,17 @@
binder::Status addUserKeyAuth(int32_t userId, int32_t userSerial, const std::string& token,
const std::string& secret);
+ binder::Status clearUserKeyAuth(int32_t userId, int32_t userSerial, const std::string& token,
+ const std::string& secret);
binder::Status fixateNewestUserKeyAuth(int32_t userId);
binder::Status unlockUserKey(int32_t userId, int32_t userSerial, const std::string& token,
const std::string& secret);
binder::Status lockUserKey(int32_t userId);
- binder::Status prepareUserStorage(const std::unique_ptr<std::string>& uuid, int32_t userId,
+ binder::Status prepareUserStorage(const std::optional<std::string>& uuid, int32_t userId,
int32_t userSerial, int32_t flags);
- binder::Status destroyUserStorage(const std::unique_ptr<std::string>& uuid, int32_t userId,
+ binder::Status destroyUserStorage(const std::optional<std::string>& uuid, int32_t userId,
int32_t flags);
binder::Status prepareSandboxForApp(const std::string& packageName, int32_t appId,
@@ -140,6 +142,14 @@
binder::Status supportsCheckpoint(bool* _aidl_return);
binder::Status supportsBlockCheckpoint(bool* _aidl_return);
binder::Status supportsFileCheckpoint(bool* _aidl_return);
+ binder::Status resetCheckpoint();
+
+ binder::Status incFsEnabled(bool* _aidl_return) override;
+ binder::Status mountIncFs(
+ const std::string& backingPath, const std::string& targetDir, int32_t flags,
+ ::android::os::incremental::IncrementalFileSystemControlParcel* _aidl_return) override;
+ binder::Status unmountIncFs(const std::string& dir) override;
+ binder::Status bindMount(const std::string& sourceDir, const std::string& targetDir) override;
};
} // namespace vold
diff --git a/VoldNativeServiceValidation.cpp b/VoldNativeServiceValidation.cpp
new file mode 100644
index 0000000..61d8981
--- /dev/null
+++ b/VoldNativeServiceValidation.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2020 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 "VoldNativeServiceValidation.h"
+
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <private/android_filesystem_config.h>
+
+#include <cctype>
+#include <string_view>
+
+using android::base::StringPrintf;
+using namespace std::literals;
+
+namespace android::vold {
+
+binder::Status Ok() {
+ return binder::Status::ok();
+}
+
+binder::Status Exception(uint32_t code, const std::string& msg) {
+ return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
+}
+
+binder::Status CheckPermission(const char* permission) {
+ pid_t pid;
+ uid_t uid;
+
+ if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
+ reinterpret_cast<int32_t*>(&uid))) {
+ return Ok();
+ } else {
+ return Exception(binder::Status::EX_SECURITY,
+ StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
+ }
+}
+
+binder::Status CheckUidOrRoot(uid_t expectedUid) {
+ uid_t uid = IPCThreadState::self()->getCallingUid();
+ if (uid == expectedUid || uid == AID_ROOT) {
+ return Ok();
+ } else {
+ return Exception(binder::Status::EX_SECURITY,
+ StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
+ }
+}
+
+binder::Status CheckArgumentId(const std::string& id) {
+ if (id.empty()) {
+ return Exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing ID");
+ }
+ for (const char& c : id) {
+ if (!std::isalnum(c) && c != ':' && c != ',') {
+ return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+ StringPrintf("ID %s is malformed", id.c_str()));
+ }
+ }
+ return Ok();
+}
+
+binder::Status CheckArgumentPath(const std::string& path) {
+ if (path.empty()) {
+ return Exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
+ }
+ if (path[0] != '/') {
+ return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+ StringPrintf("Path %s is relative", path.c_str()));
+ }
+ if (path.find("/../"sv) != path.npos || android::base::EndsWith(path, "/.."sv)) {
+ return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+ StringPrintf("Path %s is shady", path.c_str()));
+ }
+ for (const char& c : path) {
+ if (c == '\0' || c == '\n') {
+ return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+ StringPrintf("Path %s is malformed", path.c_str()));
+ }
+ }
+ return Ok();
+}
+
+binder::Status CheckArgumentHex(const std::string& hex) {
+ // Empty hex strings are allowed
+ for (const char& c : hex) {
+ if (!std::isxdigit(c) && c != ':' && c != '-') {
+ return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+ StringPrintf("Hex %s is malformed", hex.c_str()));
+ }
+ }
+ return Ok();
+}
+
+} // namespace android::vold
diff --git a/VoldNativeServiceValidation.h b/VoldNativeServiceValidation.h
new file mode 100644
index 0000000..d2fc9e0
--- /dev/null
+++ b/VoldNativeServiceValidation.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#pragma once
+
+#include <binder/Status.h>
+
+#include <string>
+
+#include <stdint.h>
+#include <sys/types.h>
+
+namespace android::vold {
+
+binder::Status Ok();
+binder::Status Exception(uint32_t code, const std::string& msg);
+
+binder::Status CheckPermission(const char* permission);
+binder::Status CheckUidOrRoot(uid_t expectedUid);
+binder::Status CheckArgumentId(const std::string& id);
+binder::Status CheckArgumentPath(const std::string& path);
+binder::Status CheckArgumentHex(const std::string& hex);
+
+} // namespace android::vold
diff --git a/VoldUtil.h b/VoldUtil.h
index 173c598..ce6b411 100644
--- a/VoldUtil.h
+++ b/VoldUtil.h
@@ -17,8 +17,7 @@
#pragma once
#include <fstab/fstab.h>
-#include <sys/cdefs.h>
extern android::fs_mgr::Fstab fstab_default;
-#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
+#define DATA_MNT_POINT "/data"
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index 44bff5a..f860eef 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -62,7 +62,6 @@
#include "VoldNativeService.h"
#include "VoldUtil.h"
#include "VolumeManager.h"
-#include "cryptfs.h"
#include "fs/Ext4.h"
#include "fs/Vfat.h"
#include "model/EmulatedVolume.h"
diff --git a/binder/android/os/IVold.aidl b/binder/android/os/IVold.aidl
index 03fe258..63a30e4 100644
--- a/binder/android/os/IVold.aidl
+++ b/binder/android/os/IVold.aidl
@@ -16,6 +16,7 @@
package android.os;
+import android.os.incremental.IncrementalFileSystemControlParcel;
import android.os.IVoldListener;
import android.os.IVoldTaskListener;
@@ -89,6 +90,8 @@
void addUserKeyAuth(int userId, int userSerial, @utf8InCpp String token,
@utf8InCpp String secret);
+ void clearUserKeyAuth(int userId, int userSerial, @utf8InCpp String token,
+ @utf8InCpp String secret);
void fixateNewestUserKeyAuth(int userId);
void unlockUserKey(int userId, int userSerial, @utf8InCpp String token,
@@ -116,6 +119,7 @@
boolean supportsCheckpoint();
boolean supportsBlockCheckpoint();
boolean supportsFileCheckpoint();
+ void resetCheckpoint();
@utf8InCpp String createStubVolume(@utf8InCpp String sourcePath,
@utf8InCpp String mountPath, @utf8InCpp String fsType,
@@ -124,6 +128,11 @@
FileDescriptor openAppFuseFile(int uid, int mountId, int fileId, int flags);
+ boolean incFsEnabled();
+ IncrementalFileSystemControlParcel mountIncFs(@utf8InCpp String backingPath, @utf8InCpp String targetDir, int flags);
+ void unmountIncFs(@utf8InCpp String dir);
+ void bindMount(@utf8InCpp String sourceDir, @utf8InCpp String targetDir);
+
const int ENCRYPTION_FLAG_NO_UI = 4;
const int ENCRYPTION_STATE_NONE = 1;
diff --git a/cryptfs.cpp b/cryptfs.cpp
index 07617e9..5c075ac 100644
--- a/cryptfs.cpp
+++ b/cryptfs.cpp
@@ -14,17 +14,12 @@
* limitations under the License.
*/
-/* TO DO:
- * 1. Perhaps keep several copies of the encrypted key, in case something
- * goes horribly wrong?
- *
- */
-
#define LOG_TAG "Cryptfs"
#include "cryptfs.h"
#include "Checkpoint.h"
+#include "CryptoType.h"
#include "EncryptInplace.h"
#include "FsCrypt.h"
#include "Keymaster.h"
@@ -37,6 +32,7 @@
#include <android-base/parseint.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
#include <bootloader_message/bootloader_message.h>
#include <cutils/android_reboot.h>
#include <cutils/properties.h>
@@ -44,25 +40,25 @@
#include <f2fs_sparseblock.h>
#include <fs_mgr.h>
#include <fscrypt/fscrypt.h>
-#include <hardware_legacy/power.h>
+#include <libdm/dm.h>
#include <log/log.h>
#include <logwrap/logwrap.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <selinux/selinux.h>
+#include <wakelock/wakelock.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <libgen.h>
-#include <linux/dm-ioctl.h>
#include <linux/kdev_t.h>
#include <math.h>
+#include <mntent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/stat.h>
@@ -78,11 +74,193 @@
using android::base::ParseUint;
using android::base::StringPrintf;
using android::fs_mgr::GetEntryForMountPoint;
+using android::vold::CryptoType;
+using android::vold::KeyBuffer;
+using android::vold::KeyGeneration;
+using namespace android::dm;
using namespace std::chrono_literals;
-#define UNUSED __attribute__((unused))
+/* The current cryptfs version */
+#define CURRENT_MAJOR_VERSION 1
+#define CURRENT_MINOR_VERSION 3
-#define DM_CRYPT_BUF_SIZE 4096
+#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
+#define CRYPT_PERSIST_DATA_SIZE 0x1000
+
+#define MAX_CRYPTO_TYPE_NAME_LEN 64
+
+#define MAX_KEY_LEN 48
+#define SALT_LEN 16
+#define SCRYPT_LEN 32
+
+/* definitions of flags in the structure below */
+#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
+#define CRYPT_ENCRYPTION_IN_PROGRESS \
+ 0x2 /* Encryption partially completed, \
+ encrypted_upto valid*/
+#define CRYPT_INCONSISTENT_STATE \
+ 0x4 /* Set when starting encryption, clear when \
+ exit cleanly, either through success or \
+ correctly marked partial encryption */
+#define CRYPT_DATA_CORRUPT \
+ 0x8 /* Set when encryption is fine, but the \
+ underlying volume is corrupt */
+#define CRYPT_FORCE_ENCRYPTION \
+ 0x10 /* Set when it is time to encrypt this \
+ volume on boot. Everything in this \
+ structure is set up correctly as \
+ though device is encrypted except \
+ that the master key is encrypted with the \
+ default password. */
+#define CRYPT_FORCE_COMPLETE \
+ 0x20 /* Set when the above encryption cycle is \
+ complete. On next cryptkeeper entry, match \
+ the password. If it matches fix the master \
+ key and remove this flag. */
+
+/* Allowed values for type in the structure below */
+#define CRYPT_TYPE_PASSWORD \
+ 0 /* master_key is encrypted with a password \
+ * Must be zero to be compatible with pre-L \
+ * devices where type is always password.*/
+#define CRYPT_TYPE_DEFAULT \
+ 1 /* master_key is encrypted with default \
+ * password */
+#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
+#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
+#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
+
+#define CRYPT_MNT_MAGIC 0xD0B5B1C4
+#define PERSIST_DATA_MAGIC 0xE950CD44
+
+/* 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
+
+/* Maximum allowed keymaster blob size. */
+#define KEYMASTER_BLOB_SIZE 2048
+
+/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
+#define __le8 unsigned char
+
+#if !defined(SHA256_DIGEST_LENGTH)
+#define SHA256_DIGEST_LENGTH 32
+#endif
+
+/* This structure starts 16,384 bytes before the end of a hardware
+ * partition that is encrypted, or in a separate partition. It's location
+ * is specified by a property set in init.<device>.rc.
+ * The structure allocates 48 bytes for a key, but the real key size is
+ * specified in the struct. Currently, the code is hardcoded to use 128
+ * bit keys.
+ * The fields after salt are only valid in rev 1.1 and later stuctures.
+ * Obviously, the filesystem does not include the last 16 kbytes
+ * of the partition if the crypt_mnt_ftr lives at the end of the
+ * partition.
+ */
+
+struct crypt_mnt_ftr {
+ __le32 magic; /* See above */
+ __le16 major_version;
+ __le16 minor_version;
+ __le32 ftr_size; /* in bytes, not including key following */
+ __le32 flags; /* See above */
+ __le32 keysize; /* in bytes */
+ __le32 crypt_type; /* how master_key is encrypted. Must be a
+ * CRYPT_TYPE_XXX value */
+ __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
+ __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
+ mount, set to 0 on successful mount */
+ unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
+ needed to decrypt this
+ partition, null terminated */
+ __le32 spare2; /* ignored */
+ unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
+ unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
+ __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
+ * on device with that info, either the footer of the
+ * real_blkdevice or the metadata partition. */
+
+ __le32 persist_data_size; /* The number of bytes allocated to each copy of the
+ * persistent data table*/
+
+ __le8 kdf_type; /* The key derivation function used. */
+
+ /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
+ __le8 N_factor; /* (1 << N) */
+ __le8 r_factor; /* (1 << r) */
+ __le8 p_factor; /* (1 << p) */
+ __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
+ we have to stop (e.g. power low) this is the last
+ encrypted 512 byte sector.*/
+ __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
+ set, hash of first block, used
+ to validate before continuing*/
+
+ /* key_master key, used to sign the derived key which is then used to generate
+ * the intermediate key
+ * This key should be used for no other purposes! We use this key to sign unpadded
+ * data, which is acceptable but only if the key is not reused elsewhere. */
+ __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
+ __le32 keymaster_blob_size;
+
+ /* Store scrypt of salted intermediate key. When decryption fails, we can
+ check if this matches, and if it does, we know that the problem is with the
+ drive, and there is no point in asking the user for more passwords.
+
+ Note that if any part of this structure is corrupt, this will not match and
+ we will continue to believe the user entered the wrong password. In that
+ case the only solution is for the user to enter a password enough times to
+ force a wipe.
+
+ Note also that there is no need to worry about migration. If this data is
+ wrong, we simply won't recognise a right password, and will continue to
+ prompt. On the first password change, this value will be populated and
+ then we will be OK.
+ */
+ unsigned char scrypted_intermediate_key[SCRYPT_LEN];
+
+ /* sha of this structure with this element set to zero
+ Used when encrypting on reboot to validate structure before doing something
+ fatal
+ */
+ unsigned char sha256[SHA256_DIGEST_LENGTH];
+};
+
+/* Persistant data that should be available before decryption.
+ * Things like airplane mode, locale and timezone are kept
+ * here and can be retrieved by the CryptKeeper UI to properly
+ * configure the phone before asking for the password
+ * This is only valid if the major and minor version above
+ * is set to 1.1 or higher.
+ *
+ * This is a 4K structure. There are 2 copies, and the code alternates
+ * writing one and then clearing the previous one. The reading
+ * code reads the first valid copy it finds, based on the magic number.
+ * The absolute offset to the first of the two copies is kept in rev 1.1
+ * and higher crypt_mnt_ftr structures.
+ */
+struct crypt_persist_entry {
+ char key[PROPERTY_KEY_MAX];
+ char val[PROPERTY_VALUE_MAX];
+};
+
+/* Should be exactly 4K in size */
+struct crypt_persist_data {
+ __le32 persist_magic;
+ __le32 persist_valid_entries;
+ __le32 persist_spare[30];
+ struct crypt_persist_entry persist_entry[0];
+};
+
+static int wait_and_unmount(const char* mountpoint, bool kill);
+
+typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
+ void* params);
+
+#define UNUSED __attribute__((unused))
#define HASH_COUNT 2000
@@ -123,6 +301,32 @@
static int master_key_saved = 0;
static struct crypt_persist_data* persist_data = NULL;
+constexpr CryptoType aes_128_cbc = CryptoType()
+ .set_config_name("AES-128-CBC")
+ .set_kernel_name("aes-cbc-essiv:sha256")
+ .set_keysize(16);
+
+constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
+
+static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
+ array_length(supported_crypto_types)),
+ "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
+ "incompletely constructed.");
+
+static const CryptoType& get_crypto_type() {
+ // We only want to parse this read-only property once. But we need to wait
+ // until the system is initialized before we can read it. So we use a static
+ // scoped within this function to get it only once.
+ static CryptoType crypto_type =
+ lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
+ aes_128_cbc, "ro.crypto.fde_algorithm");
+ return crypto_type;
+}
+
+const KeyGeneration cryptfs_get_keygen() {
+ return KeyGeneration{get_crypto_type().get_keysize(), true, false};
+}
+
/* Should we use keymaster? */
static int keymaster_check_compatibility() {
return keymaster_compatibility_cryptfs_scrypt();
@@ -253,131 +457,6 @@
return;
}
-static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
- memset(io, 0, dataSize);
- io->data_size = dataSize;
- io->data_start = sizeof(struct dm_ioctl);
- io->version[0] = 4;
- io->version[1] = 0;
- io->version[2] = 0;
- io->flags = flags;
- if (name) {
- strlcpy(io->name, name, sizeof(io->name));
- }
-}
-
-namespace {
-
-struct CryptoType;
-
-// Use to get the CryptoType in use on this device.
-const CryptoType& get_crypto_type();
-
-struct CryptoType {
- // We should only be constructing CryptoTypes as part of
- // supported_crypto_types[]. We do it via this pseudo-builder pattern,
- // which isn't pure or fully protected as a concession to being able to
- // do it all at compile time. Add new CryptoTypes in
- // supported_crypto_types[] below.
- constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
- constexpr CryptoType set_keysize(uint32_t size) const {
- return CryptoType(this->property_name, this->crypto_name, size);
- }
- constexpr CryptoType set_property_name(const char* property) const {
- return CryptoType(property, this->crypto_name, this->keysize);
- }
- constexpr CryptoType set_crypto_name(const char* crypto) const {
- return CryptoType(this->property_name, crypto, this->keysize);
- }
-
- constexpr const char* get_property_name() const { return property_name; }
- constexpr const char* get_crypto_name() const { return crypto_name; }
- constexpr uint32_t get_keysize() const { return keysize; }
-
- private:
- const char* property_name;
- const char* crypto_name;
- uint32_t keysize;
-
- constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
- : property_name(property), crypto_name(crypto), keysize(ksize) {}
- friend const CryptoType& get_crypto_type();
- static const CryptoType& get_device_crypto_algorithm();
-};
-
-// We only want to parse this read-only property once. But we need to wait
-// until the system is initialized before we can read it. So we use a static
-// scoped within this function to get it only once.
-const CryptoType& get_crypto_type() {
- static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
- return crypto_type;
-}
-
-constexpr CryptoType default_crypto_type = CryptoType()
- .set_property_name("AES-128-CBC")
- .set_crypto_name("aes-cbc-essiv:sha256")
- .set_keysize(16);
-
-constexpr CryptoType supported_crypto_types[] = {
- default_crypto_type,
- CryptoType()
- .set_property_name("adiantum")
- .set_crypto_name("xchacha12,aes-adiantum-plain64")
- .set_keysize(32),
- // Add new CryptoTypes here. Order is not important.
-};
-
-// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
-// We confirm all supported_crypto_types have a small enough keysize and
-// had both set_property_name() and set_crypto_name() called.
-
-template <typename T, size_t N>
-constexpr size_t array_length(T (&)[N]) {
- return N;
-}
-
-constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
- return (index >= array_length(supported_crypto_types));
-}
-
-constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
- return ((crypto_type.get_property_name() != nullptr) &&
- (crypto_type.get_crypto_name() != nullptr) &&
- (crypto_type.get_keysize() <= MAX_KEY_LEN));
-}
-
-// Note in C++11 that constexpr functions can only have a single line.
-// So our code is a bit convoluted (using recursion instead of a loop),
-// but it's asserting at compile time that all of our key lengths are valid.
-constexpr bool validateSupportedCryptoTypes(size_t index) {
- return indexOutOfBoundsForCryptoTypes(index) ||
- (isValidCryptoType(supported_crypto_types[index]) &&
- validateSupportedCryptoTypes(index + 1));
-}
-
-static_assert(validateSupportedCryptoTypes(0),
- "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
- "incompletely constructed.");
-// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
-
-// Don't call this directly, use get_crypto_type(), which caches this result.
-const CryptoType& CryptoType::get_device_crypto_algorithm() {
- constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
- char paramstr[PROPERTY_VALUE_MAX];
-
- property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
- for (auto const& ctype : supported_crypto_types) {
- if (strcmp(paramstr, ctype.get_property_name()) == 0) {
- return ctype;
- }
- }
- ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
- default_crypto_type.get_property_name());
- return default_crypto_type;
-}
-
-} // namespace
-
/**
* Gets the default device scrypt parameters for key derivation time tuning.
* The parameters should lead to about one second derivation time for the
@@ -397,14 +476,6 @@
ftr->p_factor = pf;
}
-uint32_t cryptfs_get_keysize() {
- return get_crypto_type().get_keysize();
-}
-
-const char* cryptfs_get_crypto_name() {
- return get_crypto_type().get_crypto_name();
-}
-
static uint64_t get_fs_size(const char* dev) {
int fd, block_size;
struct ext4_super_block sb;
@@ -973,109 +1044,12 @@
master_key_ascii[a] = '\0';
}
-static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
- const unsigned char* master_key, const char* real_blk_name,
- const char* name, int fd, const char* extra_params) {
- alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
- struct dm_ioctl* io;
- struct dm_target_spec* tgt;
- char* crypt_params;
- // We need two ASCII characters to represent each byte, and need space for
- // the '\0' terminator.
- char master_key_ascii[MAX_KEY_LEN * 2 + 1];
- size_t buff_offset;
- int i;
-
- io = (struct dm_ioctl*)buffer;
-
- /* Load the mapping table for this device */
- tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
-
- ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
- io->target_count = 1;
- tgt->status = 0;
- tgt->sector_start = 0;
- tgt->length = crypt_ftr->fs_size;
- strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
-
- crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
- convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
-
- buff_offset = crypt_params - buffer;
- SLOGI(
- "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
- name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
- extra_params);
- snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
- crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
- crypt_params += strlen(crypt_params) + 1;
- crypt_params =
- (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
- tgt->next = crypt_params - buffer;
-
- for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
- if (!ioctl(fd, DM_TABLE_LOAD, io)) {
- break;
- }
- usleep(500000);
- }
-
- if (i == TABLE_LOAD_RETRIES) {
- /* We failed to load the table, return an error */
- return -1;
- } else {
- return i + 1;
- }
-}
-
-static int get_dm_crypt_version(int fd, const char* name, int* version) {
- char buffer[DM_CRYPT_BUF_SIZE];
- struct dm_ioctl* io;
- struct dm_target_versions* v;
-
- io = (struct dm_ioctl*)buffer;
-
- ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
-
- if (ioctl(fd, DM_LIST_VERSIONS, io)) {
- return -1;
- }
-
- /* Iterate over the returned versions, looking for name of "crypt".
- * When found, get and return the version.
- */
- v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
- while (v->next) {
- if (!strcmp(v->name, "crypt")) {
- /* We found the crypt driver, return the version, and get out */
- version[0] = v->version[0];
- version[1] = v->version[1];
- version[2] = v->version[2];
- return 0;
- }
- v = (struct dm_target_versions*)(((char*)v) + v->next);
- }
-
- return -1;
-}
-
-static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
- if (extra_params_vec.empty()) return "";
- std::string extra_params = std::to_string(extra_params_vec.size());
- for (const auto& p : extra_params_vec) {
- extra_params.append(" ");
- extra_params.append(p);
- }
- return extra_params;
-}
-
/*
* If the ro.crypto.fde_sector_size system property is set, append the
* parameters to make dm-crypt use the specified crypto sector size and round
* the crypto device size down to a crypto sector boundary.
*/
-static int add_sector_size_param(std::vector<std::string>* extra_params_vec,
- struct crypt_mnt_ftr* ftr) {
+static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
char value[PROPERTY_VALUE_MAX];
@@ -1089,12 +1063,11 @@
return -1;
}
- std::string param = StringPrintf("sector_size:%u", sector_size);
- extra_params_vec->push_back(std::move(param));
+ target->SetSectorSize(sector_size);
// With this option, IVs will match the sector numbering, instead
// of being hard-coded to being based on 512-byte sectors.
- extra_params_vec->emplace_back("iv_large_sectors");
+ target->SetIvLargeSectors();
// Round the crypto device size down to a crypto sector boundary.
ftr->fs_size &= ~((sector_size / 512) - 1);
@@ -1103,114 +1076,67 @@
}
static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
- const char* real_blk_name, char* crypto_blk_name, const char* name,
- uint32_t flags) {
- char buffer[DM_CRYPT_BUF_SIZE];
- struct dm_ioctl* io;
- unsigned int minor;
- int fd = 0;
- int err;
- int retval = -1;
- int version[3];
- int load_count;
- std::vector<std::string> extra_params_vec;
+ const char* real_blk_name, std::string* crypto_blk_name,
+ const char* name, uint32_t flags) {
+ auto& dm = DeviceMapper::Instance();
- if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
- SLOGE("Cannot open device-mapper\n");
- goto errout;
- }
+ // We need two ASCII characters to represent each byte, and need space for
+ // the '\0' terminator.
+ char master_key_ascii[MAX_KEY_LEN * 2 + 1];
+ convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
- io = (struct dm_ioctl*)buffer;
+ auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
+ (const char*)crypt_ftr->crypto_type_name,
+ master_key_ascii, 0, real_blk_name, 0);
+ target->AllowDiscards();
- ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
- err = ioctl(fd, DM_DEV_CREATE, io);
- if (err) {
- SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
- goto errout;
- }
-
- /* Get the device status, in particular, the name of it's device file */
- ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
- if (ioctl(fd, DM_DEV_STATUS, io)) {
- SLOGE("Cannot retrieve dm-crypt device status\n");
- goto errout;
- }
- minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
- snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
-
- if (!get_dm_crypt_version(fd, name, version)) {
- /* Support for allow_discards was added in version 1.11.0 */
- if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
- extra_params_vec.emplace_back("allow_discards");
- }
- }
if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
- extra_params_vec.emplace_back("allow_encrypt_override");
+ target->AllowEncryptOverride();
}
- if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
+ if (add_sector_size_param(target.get(), crypt_ftr)) {
SLOGE("Error processing dm-crypt sector size param\n");
- goto errout;
+ return -1;
}
- load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
- extra_params_as_string(extra_params_vec).c_str());
- if (load_count < 0) {
+
+ DmTable table;
+ table.AddTarget(std::move(target));
+
+ int load_count = 1;
+ while (load_count < TABLE_LOAD_RETRIES) {
+ if (dm.CreateDevice(name, table)) {
+ break;
+ }
+ load_count++;
+ }
+
+ if (load_count >= TABLE_LOAD_RETRIES) {
SLOGE("Cannot load dm-crypt mapping table.\n");
- goto errout;
- } else if (load_count > 1) {
+ return -1;
+ }
+ if (load_count > 1) {
SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
}
- /* Resume this device to activate it */
- ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
-
- if (ioctl(fd, DM_DEV_SUSPEND, io)) {
- SLOGE("Cannot resume the dm-crypt device\n");
- goto errout;
+ if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
+ SLOGE("Cannot determine dm-crypt path for %s.\n", name);
+ return -1;
}
/* Ensure the dm device has been created before returning. */
- if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
+ if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
// WaitForFile generates a suitable log message
- goto errout;
+ return -1;
}
-
- /* We made it here with no errors. Woot! */
- retval = 0;
-
-errout:
- close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
-
- return retval;
+ return 0;
}
-static int delete_crypto_blk_dev(const char* name) {
- int fd;
- char buffer[DM_CRYPT_BUF_SIZE];
- struct dm_ioctl* io;
- int retval = -1;
- int err;
-
- if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
- SLOGE("Cannot open device-mapper\n");
- goto errout;
+static int delete_crypto_blk_dev(const std::string& name) {
+ auto& dm = DeviceMapper::Instance();
+ if (!dm.DeleteDevice(name)) {
+ SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
+ return -1;
}
-
- io = (struct dm_ioctl*)buffer;
-
- ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
- err = ioctl(fd, DM_DEV_REMOVE, io);
- if (err) {
- SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
- goto errout;
- }
-
- /* We made it here with no errors. Woot! */
- retval = 0;
-
-errout:
- close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
-
- return retval;
+ return 0;
}
static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
@@ -1456,8 +1382,46 @@
return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
}
-int wait_and_unmount(const char* mountpoint, bool kill) {
+static void ensure_subdirectory_unmounted(const char *prefix) {
+ std::vector<std::string> umount_points;
+ std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
+ if (!mnts) {
+ SLOGW("could not read mount files");
+ return;
+ }
+
+ //Find sudirectory mount point
+ mntent* mentry;
+ std::string top_directory(prefix);
+ if (!android::base::EndsWith(prefix, "/")) {
+ top_directory = top_directory + "/";
+ }
+ while ((mentry = getmntent(mnts.get())) != nullptr) {
+ if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
+ continue;
+ }
+
+ if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
+ SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
+ umount_points.push_back(mentry->mnt_dir);
+ }
+ }
+
+ //Sort by path length to umount longest path first
+ std::sort(std::begin(umount_points), std::end(umount_points),
+ [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
+
+ for (std::string& mount_point : umount_points) {
+ umount(mount_point.c_str());
+ SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
+ }
+}
+
+static int wait_and_unmount(const char* mountpoint, bool kill) {
int i, err, rc;
+
+ // Subdirectory mount will cause a failure of umount.
+ ensure_subdirectory_unmounted(mountpoint);
#define WAIT_UNMOUNT_COUNT 20
/* Now umount the tmpfs filesystem */
@@ -1762,7 +1726,7 @@
static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
const char* mount_point, const char* label) {
unsigned char decrypted_master_key[MAX_KEY_LEN];
- char crypto_blkdev[MAXPATHLEN];
+ std::string crypto_blkdev;
std::string real_blkdev;
char tmp_mount_point[64];
unsigned int orig_failed_decrypt_count;
@@ -1791,7 +1755,7 @@
// Create crypto block device - all (non fatal) code paths
// need it
- if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
+ if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
label, 0)) {
SLOGE("Error creating decrypted block device\n");
rc = -1;
@@ -1815,7 +1779,8 @@
* the footer, not the key. */
snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
mkdir(tmp_mount_point, 0755);
- if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
+ if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
+ const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
SLOGE("Error temp mounting decrypted block device\n");
delete_crypto_blk_dev(label);
@@ -1837,7 +1802,7 @@
/* Save the name of the crypto block device
* so we can mount it when restarting the framework. */
- property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
+ property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
/* Also save a the master key so we can reencrypted the key
* the key when we want to change the password on it. */
@@ -1894,11 +1859,15 @@
* storage volume. The incoming partition has no crypto header/footer,
* as any metadata is been stored in a separate, small partition. We
* assume it must be using our same crypt type and keysize.
- *
- * out_crypto_blkdev must be MAXPATHLEN.
*/
-int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
- char* out_crypto_blkdev) {
+int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
+ std::string* out_crypto_blkdev) {
+ auto crypto_type = get_crypto_type();
+ if (key.size() != crypto_type.get_keysize()) {
+ SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
+ crypto_type.get_keysize());
+ return -1;
+ }
uint64_t nr_sec = 0;
if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
@@ -1908,23 +1877,16 @@
struct crypt_mnt_ftr ext_crypt_ftr;
memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
ext_crypt_ftr.fs_size = nr_sec;
- ext_crypt_ftr.keysize = cryptfs_get_keysize();
- strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
+ ext_crypt_ftr.keysize = crypto_type.get_keysize();
+ strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
MAX_CRYPTO_TYPE_NAME_LEN);
uint32_t flags = 0;
if (fscrypt_is_native() &&
android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
- return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
-}
-
-/*
- * Called by vold when it's asked to unmount an encrypted external
- * storage volume.
- */
-int cryptfs_revert_ext_volume(const char* label) {
- return delete_crypto_blk_dev((char*)label);
+ return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
+ real_blkdev, out_crypto_blkdev, label, flags);
}
int cryptfs_crypto_complete(void) {
@@ -2050,7 +2012,7 @@
}
/* Initialize a crypt_mnt_ftr structure. The keysize is
- * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
+ * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
* Presumably, at a minimum, the caller will update the
* filesystem size and crypto_type_name after calling this function.
*/
@@ -2062,7 +2024,7 @@
ftr->major_version = CURRENT_MAJOR_VERSION;
ftr->minor_version = CURRENT_MINOR_VERSION;
ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
- ftr->keysize = cryptfs_get_keysize();
+ ftr->keysize = get_crypto_type().get_keysize();
switch (keymaster_check_compatibility()) {
case 1:
@@ -2116,8 +2078,8 @@
return 0;
}
-static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
- char* real_blkdev, int previously_encrypted_upto) {
+static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
+ const char* real_blkdev, int previously_encrypted_upto) {
off64_t cur_encryption_done = 0, tot_encryption_size = 0;
int rc = -1;
@@ -2152,7 +2114,7 @@
}
int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
- char crypto_blkdev[MAXPATHLEN];
+ std::string crypto_blkdev;
std::string real_blkdev;
unsigned char decrypted_master_key[MAX_KEY_LEN];
int rc = -1, i;
@@ -2165,6 +2127,7 @@
off64_t previously_encrypted_upto = 0;
bool rebootEncryption = false;
bool onlyCreateHeader = false;
+ std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
@@ -2231,7 +2194,7 @@
* wants to keep the screen on, it can grab a full wakelock.
*/
snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
- acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
+ wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
/* The init files are setup to stop the class main and late start when
* vold sets trigger_shutdown_framework.
@@ -2264,6 +2227,7 @@
* /data, set a property saying we're doing inplace encryption,
* and restart the framework.
*/
+ wait_and_unmount(DATA_MNT_POINT, true);
if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
goto error_shutting_down;
}
@@ -2304,7 +2268,7 @@
crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
}
crypt_ftr.crypt_type = crypt_type;
- strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
+ strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
MAX_CRYPTO_TYPE_NAME_LEN);
/* Make an encrypted master key */
@@ -2359,14 +2323,14 @@
}
decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
- create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
+ create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
CRYPTO_BLOCK_DEVICE, 0);
/* If we are continuing, check checksums match */
rc = 0;
if (previously_encrypted_upto) {
__le8 hash_first_block[SHA256_DIGEST_LENGTH];
- rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
+ rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
if (!rc &&
memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
@@ -2376,13 +2340,13 @@
}
if (!rc) {
- rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
+ rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
previously_encrypted_upto);
}
/* Calculate checksum if we are not finished */
if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
- rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
+ rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
if (rc) {
SLOGE("Error calculating checksum for continuing encryption");
rc = -1;
@@ -2411,7 +2375,7 @@
/* default encryption - continue first boot sequence */
property_set("ro.crypto.state", "encrypted");
property_set("ro.crypto.type", "block");
- release_wake_lock(lockid);
+ wakeLock.reset(nullptr);
if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
// Bring up cryptkeeper that will check the password and set it
property_set("vold.decrypt", "trigger_shutdown_framework");
@@ -2448,7 +2412,6 @@
} else {
/* set property to trigger dialog */
property_set("vold.encrypt_progress", "error_partially_encrypted");
- release_wake_lock(lockid);
}
return -1;
}
@@ -2458,14 +2421,10 @@
* Set the property and return. Hope the framework can deal with it.
*/
property_set("vold.encrypt_progress", "error_reboot_failed");
- release_wake_lock(lockid);
return rc;
error_unencrypted:
property_set("vold.encrypt_progress", "error_not_encrypted");
- if (lockid[0]) {
- release_wake_lock(lockid);
- }
return -1;
error_shutting_down:
@@ -2480,9 +2439,6 @@
/* shouldn't get here */
property_set("vold.encrypt_progress", "error_shutting_down");
- if (lockid[0]) {
- release_wake_lock(lockid);
- }
return -1;
}
diff --git a/cryptfs.h b/cryptfs.h
index 692d7ee..872806e 100644
--- a/cryptfs.h
+++ b/cryptfs.h
@@ -17,17 +17,7 @@
#ifndef ANDROID_VOLD_CRYPTFS_H
#define ANDROID_VOLD_CRYPTFS_H
-/* This structure starts 16,384 bytes before the end of a hardware
- * partition that is encrypted, or in a separate partition. It's location
- * is specified by a property set in init.<device>.rc.
- * The structure allocates 48 bytes for a key, but the real key size is
- * specified in the struct. Currently, the code is hardcoded to use 128
- * bit keys.
- * The fields after salt are only valid in rev 1.1 and later stuctures.
- * Obviously, the filesystem does not include the last 16 kbytes
- * of the partition if the crypt_mnt_ftr lives at the end of the
- * partition.
- */
+#include <string>
#include <linux/types.h>
#include <stdbool.h>
@@ -35,171 +25,10 @@
#include <cutils/properties.h>
-/* The current cryptfs version */
-#define CURRENT_MAJOR_VERSION 1
-#define CURRENT_MINOR_VERSION 3
+#include "KeyBuffer.h"
+#include "KeyUtil.h"
#define CRYPT_FOOTER_OFFSET 0x4000
-#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
-#define CRYPT_PERSIST_DATA_SIZE 0x1000
-
-#define MAX_CRYPTO_TYPE_NAME_LEN 64
-
-#define MAX_KEY_LEN 48
-#define SALT_LEN 16
-#define SCRYPT_LEN 32
-
-/* definitions of flags in the structure below */
-#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
-#define CRYPT_ENCRYPTION_IN_PROGRESS \
- 0x2 /* Encryption partially completed, \
- encrypted_upto valid*/
-#define CRYPT_INCONSISTENT_STATE \
- 0x4 /* Set when starting encryption, clear when \
- exit cleanly, either through success or \
- correctly marked partial encryption */
-#define CRYPT_DATA_CORRUPT \
- 0x8 /* Set when encryption is fine, but the \
- underlying volume is corrupt */
-#define CRYPT_FORCE_ENCRYPTION \
- 0x10 /* Set when it is time to encrypt this \
- volume on boot. Everything in this \
- structure is set up correctly as \
- though device is encrypted except \
- that the master key is encrypted with the \
- default password. */
-#define CRYPT_FORCE_COMPLETE \
- 0x20 /* Set when the above encryption cycle is \
- complete. On next cryptkeeper entry, match \
- the password. If it matches fix the master \
- key and remove this flag. */
-
-/* Allowed values for type in the structure below */
-#define CRYPT_TYPE_PASSWORD \
- 0 /* master_key is encrypted with a password \
- * Must be zero to be compatible with pre-L \
- * devices where type is always password.*/
-#define CRYPT_TYPE_DEFAULT \
- 1 /* master_key is encrypted with default \
- * password */
-#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
-#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
-#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
-
-#define CRYPT_MNT_MAGIC 0xD0B5B1C4
-#define PERSIST_DATA_MAGIC 0xE950CD44
-
-/* 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
-
-/* Maximum allowed keymaster blob size. */
-#define KEYMASTER_BLOB_SIZE 2048
-
-/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
-#define __le8 unsigned char
-
-#if !defined(SHA256_DIGEST_LENGTH)
-#define SHA256_DIGEST_LENGTH 32
-#endif
-
-struct crypt_mnt_ftr {
- __le32 magic; /* See above */
- __le16 major_version;
- __le16 minor_version;
- __le32 ftr_size; /* in bytes, not including key following */
- __le32 flags; /* See above */
- __le32 keysize; /* in bytes */
- __le32 crypt_type; /* how master_key is encrypted. Must be a
- * CRYPT_TYPE_XXX value */
- __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
- __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
- mount, set to 0 on successful mount */
- unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
- needed to decrypt this
- partition, null terminated */
- __le32 spare2; /* ignored */
- unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
- unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
- __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
- * on device with that info, either the footer of the
- * real_blkdevice or the metadata partition. */
-
- __le32 persist_data_size; /* The number of bytes allocated to each copy of the
- * persistent data table*/
-
- __le8 kdf_type; /* The key derivation function used. */
-
- /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
- __le8 N_factor; /* (1 << N) */
- __le8 r_factor; /* (1 << r) */
- __le8 p_factor; /* (1 << p) */
- __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
- we have to stop (e.g. power low) this is the last
- encrypted 512 byte sector.*/
- __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
- set, hash of first block, used
- to validate before continuing*/
-
- /* key_master key, used to sign the derived key which is then used to generate
- * the intermediate key
- * This key should be used for no other purposes! We use this key to sign unpadded
- * data, which is acceptable but only if the key is not reused elsewhere. */
- __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
- __le32 keymaster_blob_size;
-
- /* Store scrypt of salted intermediate key. When decryption fails, we can
- check if this matches, and if it does, we know that the problem is with the
- drive, and there is no point in asking the user for more passwords.
-
- Note that if any part of this structure is corrupt, this will not match and
- we will continue to believe the user entered the wrong password. In that
- case the only solution is for the user to enter a password enough times to
- force a wipe.
-
- Note also that there is no need to worry about migration. If this data is
- wrong, we simply won't recognise a right password, and will continue to
- prompt. On the first password change, this value will be populated and
- then we will be OK.
- */
- unsigned char scrypted_intermediate_key[SCRYPT_LEN];
-
- /* sha of this structure with this element set to zero
- Used when encrypting on reboot to validate structure before doing something
- fatal
- */
- unsigned char sha256[SHA256_DIGEST_LENGTH];
-};
-
-/* Persistant data that should be available before decryption.
- * Things like airplane mode, locale and timezone are kept
- * here and can be retrieved by the CryptKeeper UI to properly
- * configure the phone before asking for the password
- * This is only valid if the major and minor version above
- * is set to 1.1 or higher.
- *
- * This is a 4K structure. There are 2 copies, and the code alternates
- * writing one and then clearing the previous one. The reading
- * code reads the first valid copy it finds, based on the magic number.
- * The absolute offset to the first of the two copies is kept in rev 1.1
- * and higher crypt_mnt_ftr structures.
- */
-struct crypt_persist_entry {
- char key[PROPERTY_KEY_MAX];
- char val[PROPERTY_VALUE_MAX];
-};
-
-/* Should be exactly 4K in size */
-struct crypt_persist_data {
- __le32 persist_magic;
- __le32 persist_valid_entries;
- __le32 persist_spare[30];
- struct crypt_persist_entry persist_entry[0];
-};
-
-#define DATA_MNT_POINT "/data"
/* Return values for cryptfs_crypto_complete */
#define CRYPTO_COMPLETE_NOT_ENCRYPTED 1
@@ -209,11 +38,6 @@
#define CRYPTO_COMPLETE_INCONSISTENT (-3)
#define CRYPTO_COMPLETE_CORRUPT (-4)
-/* Return values for cryptfs_enable_inplace*() */
-#define ENABLE_INPLACE_OK 0
-#define ENABLE_INPLACE_ERR_OTHER (-1)
-#define ENABLE_INPLACE_ERR_DEV (-2) /* crypto_blkdev issue */
-
/* Return values for cryptfs_getfield */
#define CRYPTO_GETFIELD_OK 0
#define CRYPTO_GETFIELD_ERROR_NO_FIELD (-1)
@@ -231,11 +55,8 @@
#define PERSIST_DEL_KEY_ERROR_OTHER (-1)
#define PERSIST_DEL_KEY_ERROR_NO_FIELD (-2)
+// Exposed for testing only
int match_multi_entry(const char* key, const char* field, unsigned index);
-int wait_and_unmount(const char* mountpoint, bool kill);
-
-typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
- void* params);
int cryptfs_crypto_complete(void);
int cryptfs_check_passwd(const char* pw);
@@ -244,9 +65,8 @@
int cryptfs_enable(int type, const char* passwd, int no_ui);
int cryptfs_changepw(int type, const char* newpw);
int cryptfs_enable_default(int no_ui);
-int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
- char* out_crypto_blkdev);
-int cryptfs_revert_ext_volume(const char* label);
+int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
+ const android::vold::KeyBuffer& key, std::string* out_crypto_blkdev);
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);
@@ -254,8 +74,6 @@
const char* cryptfs_get_password(void);
void cryptfs_clear_password(void);
int cryptfs_isConvertibleToFBE(void);
-
-uint32_t cryptfs_get_keysize();
-const char* cryptfs_get_crypto_name();
+const android::vold::KeyGeneration cryptfs_get_keygen();
#endif /* ANDROID_VOLD_CRYPTFS_H */
diff --git a/fs/Exfat.cpp b/fs/Exfat.cpp
index c624eb9..34f1024 100644
--- a/fs/Exfat.cpp
+++ b/fs/Exfat.cpp
@@ -41,6 +41,7 @@
status_t Check(const std::string& source) {
std::vector<std::string> cmd;
cmd.push_back(kFsckPath);
+ cmd.push_back("-a");
cmd.push_back(source);
int rc = ForkExecvp(cmd, nullptr, sFsckUntrustedContext);
diff --git a/fs/Ext4.cpp b/fs/Ext4.cpp
index 0059233..8bb930d 100644
--- a/fs/Ext4.cpp
+++ b/fs/Ext4.cpp
@@ -171,6 +171,14 @@
cmd.push_back("-M");
cmd.push_back(target);
+ bool needs_casefold = android::base::GetBoolProperty("ro.emulated_storage.casefold", false);
+ bool needs_projid = android::base::GetBoolProperty("ro.emulated_storage.projid", false);
+
+ if (needs_projid) {
+ cmd.push_back("-I");
+ cmd.push_back("512");
+ }
+
std::string options("has_journal");
if (android::base::GetBoolProperty("vold.has_quota", false)) {
options += ",quota";
@@ -178,10 +186,21 @@
if (fscrypt_is_native()) {
options += ",encrypt";
}
+ if (needs_casefold) {
+ options += ",casefold";
+ }
cmd.push_back("-O");
cmd.push_back(options);
+ if (needs_casefold || needs_projid) {
+ cmd.push_back("-E");
+ std::string extopts = "";
+ if (needs_casefold) extopts += "encoding=utf8,";
+ if (needs_projid) extopts += "quotatype=prjquota,";
+ cmd.push_back(extopts);
+ }
+
cmd.push_back(source);
if (numSectors) {
diff --git a/fscrypt_uapi.h b/fscrypt_uapi.h
new file mode 100644
index 0000000..3cda96e
--- /dev/null
+++ b/fscrypt_uapi.h
@@ -0,0 +1,27 @@
+#ifndef _UAPI_LINUX_FSCRYPT_VOLD_H
+#define _UAPI_LINUX_FSCRYPT_VOLD_H
+
+#include <linux/fscrypt.h>
+#include <linux/types.h>
+
+#define FSCRYPT_ADD_KEY_FLAG_WRAPPED 0x01
+
+struct sys_fscrypt_add_key_arg {
+ struct fscrypt_key_specifier key_spec;
+ __u32 raw_size;
+ __u32 key_id;
+ __u32 __reserved[7];
+ __u32 flags;
+ __u8 raw[];
+};
+
+struct sys_fscrypt_provisioning_key_payload {
+ __u32 type;
+ __u32 __reserved;
+ __u8 raw[];
+};
+
+#define fscrypt_add_key_arg sys_fscrypt_add_key_arg
+#define fscrypt_provisioning_key_payload sys_fscrypt_provisioning_key_payload
+
+#endif //_UAPI_LINUX_FSCRYPT_VOLD_H
diff --git a/main.cpp b/main.cpp
index 27a701b..ebe5510 100644
--- a/main.cpp
+++ b/main.cpp
@@ -20,7 +20,6 @@
#include "VoldNativeService.h"
#include "VoldUtil.h"
#include "VolumeManager.h"
-#include "cryptfs.h"
#include "model/Disk.h"
#include "sehandle.h"
@@ -152,6 +151,7 @@
{"blkid_untrusted_context", required_argument, 0, 'B'},
{"fsck_context", required_argument, 0, 'f'},
{"fsck_untrusted_context", required_argument, 0, 'F'},
+ {nullptr, 0, nullptr, 0},
};
int c;
diff --git a/model/Disk.cpp b/model/Disk.cpp
index b66c336..6a6585e 100644
--- a/model/Disk.cpp
+++ b/model/Disk.cpp
@@ -20,6 +20,7 @@
#include "PublicVolume.h"
#include "Utils.h"
#include "VolumeBase.h"
+#include "VolumeEncryption.h"
#include "VolumeManager.h"
#include <android-base/file.h>
@@ -30,8 +31,6 @@
#include <android-base/strings.h>
#include <fscrypt/fscrypt.h>
-#include "cryptfs.h"
-
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
@@ -216,7 +215,8 @@
LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
- auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
+ auto keyBuffer = KeyBuffer(keyRaw.begin(), keyRaw.end());
+ auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyBuffer));
if (mJustPartitioned) {
LOG(DEBUG) << "Device just partitioned; silently formatting";
vol->setSilent(true);
@@ -504,11 +504,12 @@
return -EIO;
}
- std::string keyRaw;
- if (ReadRandomBytes(cryptfs_get_keysize(), keyRaw) != OK) {
+ KeyBuffer key;
+ if (!generate_volume_key(&key)) {
LOG(ERROR) << "Failed to generate key";
return -EIO;
}
+ std::string keyRaw(key.begin(), key.end());
std::string partGuid;
StrToHex(partGuidRaw, partGuid);
diff --git a/model/PrivateVolume.cpp b/model/PrivateVolume.cpp
index de2a09f..fd3daea 100644
--- a/model/PrivateVolume.cpp
+++ b/model/PrivateVolume.cpp
@@ -17,14 +17,15 @@
#include "PrivateVolume.h"
#include "EmulatedVolume.h"
#include "Utils.h"
+#include "VolumeEncryption.h"
#include "VolumeManager.h"
-#include "cryptfs.h"
#include "fs/Ext4.h"
#include "fs/F2fs.h"
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <cutils/fs.h>
+#include <libdm/dm.h>
#include <private/android_filesystem_config.h>
#include <fcntl.h>
@@ -43,7 +44,7 @@
static const unsigned int kMajorBlockMmc = 179;
-PrivateVolume::PrivateVolume(dev_t device, const std::string& keyRaw)
+PrivateVolume::PrivateVolume(dev_t device, const KeyBuffer& keyRaw)
: VolumeBase(Type::kPrivate), mRawDevice(device), mKeyRaw(keyRaw) {
setId(StringPrintf("private:%u,%u", major(device), minor(device)));
mRawDevPath = StringPrintf("/dev/block/vold/%s", getId().c_str());
@@ -64,23 +65,18 @@
if (CreateDeviceNode(mRawDevPath, mRawDevice)) {
return -EIO;
}
- if (mKeyRaw.size() != cryptfs_get_keysize()) {
- PLOG(ERROR) << getId() << " Raw keysize " << mKeyRaw.size()
- << " does not match crypt keysize " << cryptfs_get_keysize();
+
+ // Recover from stale vold by tearing down any old mappings
+ auto& dm = dm::DeviceMapper::Instance();
+ if (!dm.DeleteDeviceIfExists(getId())) {
+ PLOG(ERROR) << "Cannot remove dm device " << getId();
return -EIO;
}
- // Recover from stale vold by tearing down any old mappings
- cryptfs_revert_ext_volume(getId().c_str());
-
// TODO: figure out better SELinux labels for private volumes
- unsigned char* key = (unsigned char*)mKeyRaw.data();
- char crypto_blkdev[MAXPATHLEN];
- int res = cryptfs_setup_ext_volume(getId().c_str(), mRawDevPath.c_str(), key, crypto_blkdev);
- mDmDevPath = crypto_blkdev;
- if (res != 0) {
- PLOG(ERROR) << getId() << " failed to setup cryptfs";
+ if (!setup_ext_volume(getId(), mRawDevPath, mKeyRaw, &mDmDevPath)) {
+ LOG(ERROR) << getId() << " failed to setup metadata encryption";
return -EIO;
}
@@ -88,8 +84,10 @@
}
status_t PrivateVolume::doDestroy() {
- if (cryptfs_revert_ext_volume(getId().c_str())) {
- LOG(ERROR) << getId() << " failed to revert cryptfs";
+ auto& dm = dm::DeviceMapper::Instance();
+ if (!dm.DeleteDevice(getId())) {
+ PLOG(ERROR) << "Cannot remove dm device " << getId();
+ return -EIO;
}
return DestroyDeviceNode(mRawDevPath);
}
diff --git a/model/PrivateVolume.h b/model/PrivateVolume.h
index cb8e75d..819632b 100644
--- a/model/PrivateVolume.h
+++ b/model/PrivateVolume.h
@@ -37,7 +37,7 @@
*/
class PrivateVolume : public VolumeBase {
public:
- PrivateVolume(dev_t device, const std::string& keyRaw);
+ PrivateVolume(dev_t device, const KeyBuffer& keyRaw);
virtual ~PrivateVolume();
const std::string& getFsType() const { return mFsType; };
const std::string& getRawDevPath() const { return mRawDevPath; };
@@ -63,7 +63,7 @@
std::string mPath;
/* Encryption key as raw bytes */
- std::string mKeyRaw;
+ KeyBuffer mKeyRaw;
/* Filesystem type */
std::string mFsType;
diff --git a/model/VolumeEncryption.cpp b/model/VolumeEncryption.cpp
new file mode 100644
index 0000000..5b0e73d
--- /dev/null
+++ b/model/VolumeEncryption.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2020 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 "VolumeEncryption.h"
+
+#include <string>
+
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+
+#include "KeyBuffer.h"
+#include "KeyUtil.h"
+#include "MetadataCrypt.h"
+#include "cryptfs.h"
+
+namespace android {
+namespace vold {
+
+enum class VolumeMethod { kFailed, kCrypt, kDefaultKey };
+
+static VolumeMethod lookup_volume_method() {
+ constexpr uint64_t pre_gki_level = 29;
+ auto first_api_level =
+ android::base::GetUintProperty<uint64_t>("ro.product.first_api_level", 0);
+ auto method = android::base::GetProperty("ro.crypto.volume.metadata.method", "default");
+ if (method == "default") {
+ return first_api_level > pre_gki_level ? VolumeMethod::kDefaultKey : VolumeMethod::kCrypt;
+ } else if (method == "dm-default-key") {
+ return VolumeMethod::kDefaultKey;
+ } else if (method == "dm-crypt") {
+ if (first_api_level > pre_gki_level) {
+ LOG(ERROR) << "volume encryption method dm-crypt cannot be used, "
+ "ro.product.first_api_level = "
+ << first_api_level;
+ return VolumeMethod::kFailed;
+ }
+ return VolumeMethod::kCrypt;
+ } else {
+ LOG(ERROR) << "Unknown volume encryption method: " << method;
+ return VolumeMethod::kFailed;
+ }
+}
+
+static VolumeMethod volume_method() {
+ static VolumeMethod method = lookup_volume_method();
+ return method;
+}
+
+bool generate_volume_key(android::vold::KeyBuffer* key) {
+ KeyGeneration gen;
+ switch (volume_method()) {
+ case VolumeMethod::kFailed:
+ LOG(ERROR) << "Volume encryption setup failed";
+ return false;
+ case VolumeMethod::kCrypt:
+ gen = cryptfs_get_keygen();
+ break;
+ case VolumeMethod::kDefaultKey:
+ if (!defaultkey_volume_keygen(&gen)) return false;
+ break;
+ }
+ if (!generateStorageKey(gen, key)) return false;
+ return true;
+}
+
+bool setup_ext_volume(const std::string& label, const std::string& blk_device,
+ const android::vold::KeyBuffer& key, std::string* out_crypto_blkdev) {
+ switch (volume_method()) {
+ case VolumeMethod::kFailed:
+ LOG(ERROR) << "Volume encryption setup failed";
+ return false;
+ case VolumeMethod::kCrypt:
+ return cryptfs_setup_ext_volume(label.c_str(), blk_device.c_str(), key,
+ out_crypto_blkdev) == 0;
+ case VolumeMethod::kDefaultKey:
+ return defaultkey_setup_ext_volume(label, blk_device, key, out_crypto_blkdev);
+ }
+}
+
+} // namespace vold
+} // namespace android
diff --git a/model/VolumeEncryption.h b/model/VolumeEncryption.h
new file mode 100644
index 0000000..d06c12b
--- /dev/null
+++ b/model/VolumeEncryption.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#pragma once
+
+#include <string>
+
+#include "KeyBuffer.h"
+
+namespace android {
+namespace vold {
+
+bool generate_volume_key(android::vold::KeyBuffer* key);
+
+bool setup_ext_volume(const std::string& label, const std::string& blk_device,
+ const android::vold::KeyBuffer& key, std::string* out_crypto_blkdev);
+
+} // namespace vold
+} // namespace android
diff --git a/tests/Android.bp b/tests/Android.bp
index a070178..b90de3a 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -6,9 +6,10 @@
],
srcs: [
- "CryptfsScryptHidlizationEquivalence_test.cpp",
"Utils_test.cpp",
+ "VoldNativeServiceValidation_test.cpp",
"cryptfs_test.cpp",
],
static_libs: ["libvold"],
+ shared_libs: ["libbinder"]
}
diff --git a/tests/CryptfsScryptHidlizationEquivalence_test.cpp b/tests/CryptfsScryptHidlizationEquivalence_test.cpp
deleted file mode 100644
index 72170e3..0000000
--- a/tests/CryptfsScryptHidlizationEquivalence_test.cpp
+++ /dev/null
@@ -1,450 +0,0 @@
-/*
-**
-** 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 <gtest/gtest.h>
-#include <hardware/keymaster0.h>
-#include <hardware/keymaster1.h>
-#include <cstring>
-
-#include "../Keymaster.h"
-#include "../cryptfs.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();
-}
-
-#if 0
-/* 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;
-}
-#endif
-
-/* 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;
- }
- if (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) != KeymasterSignResult::ok)
- return -1;
- return 0;
-}
-
-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);
-}
-
-} // namespace android
diff --git a/tests/VoldNativeServiceValidation_test.cpp b/tests/VoldNativeServiceValidation_test.cpp
new file mode 100644
index 0000000..b057b82
--- /dev/null
+++ b/tests/VoldNativeServiceValidation_test.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2020 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 "../VoldNativeServiceValidation.h"
+
+#include <gtest/gtest.h>
+
+#include <string_view>
+
+using namespace std::literals;
+
+namespace android::vold {
+
+class VoldNativeServiceValidationTest : public testing::Test {};
+
+TEST_F(VoldNativeServiceValidationTest, CheckArgumentPathTest) {
+ EXPECT_TRUE(CheckArgumentPath("/").isOk());
+ EXPECT_TRUE(CheckArgumentPath("/1/2").isOk());
+ EXPECT_TRUE(CheckArgumentPath("/1/2/").isOk());
+ EXPECT_TRUE(CheckArgumentPath("/1/2/./3").isOk());
+ EXPECT_TRUE(CheckArgumentPath("/1/2/./3/.").isOk());
+ EXPECT_TRUE(CheckArgumentPath(
+ "/very long path with some/ spaces and quite/ uncommon names /in\1 it/")
+ .isOk());
+
+ EXPECT_FALSE(CheckArgumentPath("").isOk());
+ EXPECT_FALSE(CheckArgumentPath("relative/path").isOk());
+ EXPECT_FALSE(CheckArgumentPath("../data/..").isOk());
+ EXPECT_FALSE(CheckArgumentPath("/../data/..").isOk());
+ EXPECT_FALSE(CheckArgumentPath("/data/../system").isOk());
+ EXPECT_FALSE(CheckArgumentPath("/data/..trick/../system").isOk());
+ EXPECT_FALSE(CheckArgumentPath("/data/..").isOk());
+ EXPECT_FALSE(CheckArgumentPath("/data/././../apex").isOk());
+ EXPECT_FALSE(CheckArgumentPath(std::string("/data/strange\0one"sv)).isOk());
+ EXPECT_FALSE(CheckArgumentPath(std::string("/data/strange\ntwo"sv)).isOk());
+}
+
+} // namespace android::vold
diff --git a/vdc.cpp b/vdc.cpp
index f05d2af..a6a3fb0 100644
--- a/vdc.cpp
+++ b/vdc.cpp
@@ -32,6 +32,7 @@
#include <android-base/logging.h>
#include <android-base/parseint.h>
+#include <android-base/strings.h>
#include <android-base/stringprintf.h>
#include <binder/IServiceManager.h>
#include <binder/Status.h>
@@ -55,9 +56,10 @@
return res;
}
-static void checkStatus(android::binder::Status status) {
+static void checkStatus(std::vector<std::string>& cmd, android::binder::Status status) {
if (status.isOk()) return;
- LOG(ERROR) << "Failed: " << status.toString8().string();
+ std::string command = ::android::base::Join(cmd, " ");
+ LOG(ERROR) << "Command: " << command << " Failed: " << status.toString8().string();
exit(ENOTTY);
}
@@ -88,63 +90,68 @@
auto vold = android::interface_cast<android::os::IVold>(binder);
if (args[0] == "cryptfs" && args[1] == "enablefilecrypto") {
- checkStatus(vold->fbeEnable());
+ checkStatus(args, vold->fbeEnable());
} else if (args[0] == "cryptfs" && args[1] == "init_user0") {
- checkStatus(vold->initUser0());
+ checkStatus(args, vold->initUser0());
} else if (args[0] == "cryptfs" && args[1] == "enablecrypto") {
int passwordType = android::os::IVold::PASSWORD_TYPE_DEFAULT;
int encryptionFlags = android::os::IVold::ENCRYPTION_FLAG_NO_UI;
- checkStatus(vold->fdeEnable(passwordType, "", encryptionFlags));
+ checkStatus(args, vold->fdeEnable(passwordType, "", encryptionFlags));
} else if (args[0] == "cryptfs" && args[1] == "mountdefaultencrypted") {
- checkStatus(vold->mountDefaultEncrypted());
+ checkStatus(args, vold->mountDefaultEncrypted());
} else if (args[0] == "volume" && args[1] == "shutdown") {
- checkStatus(vold->shutdown());
+ checkStatus(args, vold->shutdown());
+ } else if (args[0] == "volume" && args[1] == "reset") {
+ checkStatus(args, vold->reset());
} else if (args[0] == "cryptfs" && args[1] == "checkEncryption" && args.size() == 3) {
- checkStatus(vold->checkEncryption(args[2]));
+ checkStatus(args, vold->checkEncryption(args[2]));
} else if (args[0] == "cryptfs" && args[1] == "mountFstab" && args.size() == 4) {
- checkStatus(vold->mountFstab(args[2], args[3]));
+ checkStatus(args, vold->mountFstab(args[2], args[3]));
} else if (args[0] == "cryptfs" && args[1] == "encryptFstab" && args.size() == 4) {
- checkStatus(vold->encryptFstab(args[2], args[3]));
+ checkStatus(args, vold->encryptFstab(args[2], args[3]));
} else if (args[0] == "checkpoint" && args[1] == "supportsCheckpoint" && args.size() == 2) {
bool supported = false;
- checkStatus(vold->supportsCheckpoint(&supported));
+ checkStatus(args, vold->supportsCheckpoint(&supported));
return supported ? 1 : 0;
- } else if (args[0] == "checkpoint" && args[1] == "supportsBlockCheckpoint" && args.size() == 2) {
+ } else if (args[0] == "checkpoint" && args[1] == "supportsBlockCheckpoint" &&
+ args.size() == 2) {
bool supported = false;
- checkStatus(vold->supportsBlockCheckpoint(&supported));
+ checkStatus(args, vold->supportsBlockCheckpoint(&supported));
return supported ? 1 : 0;
} else if (args[0] == "checkpoint" && args[1] == "supportsFileCheckpoint" && args.size() == 2) {
bool supported = false;
- checkStatus(vold->supportsFileCheckpoint(&supported));
+ checkStatus(args, vold->supportsFileCheckpoint(&supported));
return supported ? 1 : 0;
} else if (args[0] == "checkpoint" && args[1] == "startCheckpoint" && args.size() == 3) {
int retry;
if (!android::base::ParseInt(args[2], &retry)) exit(EINVAL);
- checkStatus(vold->startCheckpoint(retry));
+ checkStatus(args, vold->startCheckpoint(retry));
} else if (args[0] == "checkpoint" && args[1] == "needsCheckpoint" && args.size() == 2) {
bool enabled = false;
- checkStatus(vold->needsCheckpoint(&enabled));
+ checkStatus(args, vold->needsCheckpoint(&enabled));
return enabled ? 1 : 0;
} else if (args[0] == "checkpoint" && args[1] == "needsRollback" && args.size() == 2) {
bool enabled = false;
- checkStatus(vold->needsRollback(&enabled));
+ checkStatus(args, vold->needsRollback(&enabled));
return enabled ? 1 : 0;
} else if (args[0] == "checkpoint" && args[1] == "commitChanges" && args.size() == 2) {
- checkStatus(vold->commitChanges());
+ checkStatus(args, vold->commitChanges());
} else if (args[0] == "checkpoint" && args[1] == "prepareCheckpoint" && args.size() == 2) {
- checkStatus(vold->prepareCheckpoint());
+ checkStatus(args, vold->prepareCheckpoint());
} else if (args[0] == "checkpoint" && args[1] == "restoreCheckpoint" && args.size() == 3) {
- checkStatus(vold->restoreCheckpoint(args[2]));
+ checkStatus(args, vold->restoreCheckpoint(args[2]));
} else if (args[0] == "checkpoint" && args[1] == "restoreCheckpointPart" && args.size() == 4) {
int count;
if (!android::base::ParseInt(args[3], &count)) exit(EINVAL);
- checkStatus(vold->restoreCheckpointPart(args[2], count));
+ checkStatus(args, vold->restoreCheckpointPart(args[2], count));
} else if (args[0] == "checkpoint" && args[1] == "markBootAttempt" && args.size() == 2) {
- checkStatus(vold->markBootAttempt());
+ checkStatus(args, vold->markBootAttempt());
} else if (args[0] == "checkpoint" && args[1] == "abortChanges" && args.size() == 4) {
int retry;
if (!android::base::ParseInt(args[2], &retry)) exit(EINVAL);
- checkStatus(vold->abortChanges(args[2], retry != 0));
+ checkStatus(args, vold->abortChanges(args[2], retry != 0));
+ } else if (args[0] == "checkpoint" && args[1] == "resetCheckpoint") {
+ checkStatus(args, vold->resetCheckpoint());
} else {
LOG(ERROR) << "Raw commands are no longer supported";
exit(EINVAL);
diff --git a/vold_prepare_subdirs.cpp b/vold_prepare_subdirs.cpp
index a620edd..d624d73 100644
--- a/vold_prepare_subdirs.cpp
+++ b/vold_prepare_subdirs.cpp
@@ -120,6 +120,31 @@
}
}
+static bool prepare_apex_subdirs(struct selabel_handle* sehandle, const std::string& path) {
+ if (!prepare_dir(sehandle, 0711, 0, 0, path + "/apexdata")) return false;
+
+ auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir("/apex"), closedir);
+ if (!dirp) {
+ PLOG(ERROR) << "Unable to open apex directory";
+ return false;
+ }
+ struct dirent* entry;
+ while ((entry = readdir(dirp.get())) != nullptr) {
+ if (entry->d_type != DT_DIR) continue;
+
+ const char* name = entry->d_name;
+ // skip any starting with "."
+ if (name[0] == '.') continue;
+
+ if (strchr(name, '@') != NULL) continue;
+
+ if (!prepare_dir(sehandle, 0771, AID_ROOT, AID_SYSTEM, path + "/apexdata/" + name)) {
+ return false;
+ }
+ }
+ return true;
+}
+
static bool prepare_subdirs(const std::string& volume_uuid, int user_id, int flags) {
struct selabel_handle* sehandle = selinux_android_file_context_handle();
@@ -129,6 +154,9 @@
if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/vold")) return false;
if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/storaged")) return false;
if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/rollback")) return false;
+ // TODO: Return false if this returns false once sure this should succeed.
+ prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/apexrollback");
+ prepare_apex_subdirs(sehandle, misc_de_path);
auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, vendor_de_path + "/fpdata")) {
@@ -144,6 +172,9 @@
if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/vold")) return false;
if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/storaged")) return false;
if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/rollback")) return false;
+ // TODO: Return false if this returns false once sure this should succeed.
+ prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/apexrollback");
+ prepare_apex_subdirs(sehandle, misc_ce_path);
auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, system_ce_path + "/backup")) {