From 14c8c0765a2968f8605c58f27dc68dcc3b6b0807 Mon Sep 17 00:00:00 2001 From: Paul Crowley Date: Tue, 18 Sep 2018 13:30:21 -0700 Subject: [PATCH] clang-format many files. Test: Format-only changes; treehugger suffices. Change-Id: I23cde3f0bbcac13bef555d13514e922c79d5ad48 --- Benchmark.cpp | 12 +- Benchmark.h | 4 +- Devmapper.cpp | 70 +- Devmapper.h | 17 +- EncryptInplace.cpp | 122 +- Ext4Crypt.cpp | 38 +- FileDeviceUtils.cpp | 44 +- FileDeviceUtils.h | 6 +- IdleMaint.cpp | 33 +- KeyBuffer.cpp | 1 - KeyBuffer.h | 9 +- KeyStorage.cpp | 5 +- KeyUtil.cpp | 24 +- KeyUtil.h | 6 +- Loop.cpp | 26 +- Loop.h | 15 +- MetadataCrypt.cpp | 35 +- MoveStorage.cpp | 34 +- MoveStorage.h | 2 +- NetlinkHandler.cpp | 15 +- NetlinkHandler.h | 9 +- NetlinkManager.cpp | 21 +- NetlinkManager.h | 24 +- Process.cpp | 22 +- ScryptParameters.cpp | 17 +- ScryptParameters.h | 2 +- Utils.cpp | 115 +- Utils.h | 19 +- VoldUtil.cpp | 10 +- VoldUtil.h | 2 +- cryptfs.cpp | 1473 ++++++++--------- cryptfs.h | 213 +-- fs/Ext4.cpp | 31 +- fs/Ext4.h | 7 +- fs/F2fs.cpp | 7 +- fs/Vfat.cpp | 87 +- fs/Vfat.h | 5 +- hash.h | 28 +- main.cpp | 72 +- model/Disk.cpp | 219 +-- model/Disk.h | 4 +- model/EmulatedVolume.h | 6 +- model/ObbVolume.cpp | 22 +- model/ObbVolume.h | 9 +- model/PrivateVolume.cpp | 47 +- model/PrivateVolume.h | 6 +- model/PublicVolume.h | 6 +- secdiscard.cpp | 61 +- secontext.cpp | 5 +- sehandle.h | 2 +- ...yptfsScryptHidlizationEquivalence_test.cpp | 134 +- tests/Utils_test.cpp | 7 +- tests/cryptfs_test.cpp | 10 +- vdc.cpp | 17 +- 54 files changed, 1539 insertions(+), 1698 deletions(-) diff --git a/Benchmark.cpp b/Benchmark.cpp index dfe3366..7fbf92e 100644 --- a/Benchmark.cpp +++ b/Benchmark.cpp @@ -28,8 +28,8 @@ #include -#include #include +#include #include using android::base::ReadFileToString; @@ -50,12 +50,12 @@ constexpr auto kTimeout = 20s; // RAII class for boosting device performance during benchmarks. class PerformanceBoost { -private: + private: int orig_prio; int orig_ioprio; IoSchedClass orig_clazz; -public: + public: PerformanceBoost() { errno = 0; orig_prio = getpriority(PRIO_PROCESS, 0); @@ -87,8 +87,8 @@ public: }; static status_t benchmarkInternal(const std::string& rootPath, - const android::sp& listener, - android::os::PersistableBundle* extras) { + const android::sp& listener, + android::os::PersistableBundle* extras) { status_t res = 0; auto path = rootPath; @@ -179,7 +179,7 @@ static status_t benchmarkInternal(const std::string& rootPath, } void Benchmark(const std::string& path, - const android::sp& listener) { + const android::sp& listener) { std::lock_guard lock(kBenchmarkLock); acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock); diff --git a/Benchmark.h b/Benchmark.h index 4f19b01..d5882cd 100644 --- a/Benchmark.h +++ b/Benchmark.h @@ -24,8 +24,10 @@ namespace android { namespace vold { +// clang-format off void Benchmark(const std::string& path, - const android::sp& listener); + const android::sp& listener); +// clang-format on } // namespace vold } // namespace android diff --git a/Devmapper.cpp b/Devmapper.cpp index 2510771..e5c7e37 100644 --- a/Devmapper.cpp +++ b/Devmapper.cpp @@ -16,23 +16,22 @@ #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER +#include +#include #include #include -#include -#include -#include #include -#include +#include -#include #include #include +#include #include #include -#include #include +#include #include #include "Devmapper.h" @@ -43,8 +42,7 @@ using android::base::StringPrintf; static const char* kVoldPrefix = "vold:"; -void Devmapper::ioctlInit(struct dm_ioctl *io, size_t dataSize, - const char *name, unsigned flags) { +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); @@ -54,17 +52,16 @@ void Devmapper::ioctlInit(struct dm_ioctl *io, size_t dataSize, io->flags = flags; if (name) { size_t ret = strlcpy(io->name, name, sizeof(io->name)); - if (ret >= sizeof(io->name)) - abort(); + 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) { +int Devmapper::create(const char* name_raw, const char* loopFile, const char* key, + unsigned long numSectors, char* ubuffer, size_t len) { auto name_string = StringPrintf("%s%s", kVoldPrefix, name_raw); const char* name = name_string.c_str(); - char *buffer = (char *) malloc(DEVMAPPER_BUFFER_SIZE); + char* buffer = (char*)malloc(DEVMAPPER_BUFFER_SIZE); if (!buffer) { PLOG(ERROR) << "Failed malloc"; return -1; @@ -77,8 +74,8 @@ int Devmapper::create(const char *name_raw, const char *loopFile, const char *ke return -1; } - struct dm_ioctl *io = (struct dm_ioctl *) buffer; - + struct dm_ioctl* io = (struct dm_ioctl*)buffer; + // Create the DM device ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0); @@ -92,11 +89,11 @@ int Devmapper::create(const char *name_raw, const char *loopFile, const char *ke // Set the legacy geometry ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0); - char *geoParams = buffer + sizeof(struct dm_ioctl); + 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); + geoParams = (char*)_align(geoParams, 8); if (ioctl(fd, DM_DEV_SET_GEOMETRY, io)) { PLOG(ERROR) << "Failed DM_DEV_SET_GEOMETRY"; free(buffer); @@ -117,8 +114,8 @@ int Devmapper::create(const char *name_raw, const char *loopFile, const char *ke 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)]; + 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; @@ -129,12 +126,12 @@ int Devmapper::create(const char *name_raw, const char *loopFile, const char *ke strlcpy(tgt->target_type, "crypt", sizeof(tgt->target_type)); - char *cryptParams = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec); + 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); + 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); + cryptParams = (char*)_align(cryptParams, 8); tgt->next = cryptParams - buffer; if (ioctl(fd, DM_TABLE_LOAD, io)) { @@ -160,11 +157,11 @@ int Devmapper::create(const char *name_raw, const char *loopFile, const char *ke return 0; } -int Devmapper::destroy(const char *name_raw) { +int Devmapper::destroy(const char* name_raw) { auto name_string = StringPrintf("%s%s", kVoldPrefix, name_raw); const char* name = name_string.c_str(); - char *buffer = (char *) malloc(DEVMAPPER_BUFFER_SIZE); + char* buffer = (char*)malloc(DEVMAPPER_BUFFER_SIZE); if (!buffer) { PLOG(ERROR) << "Failed malloc"; return -1; @@ -177,8 +174,8 @@ int Devmapper::destroy(const char *name_raw) { return -1; } - struct dm_ioctl *io = (struct dm_ioctl *) buffer; - + struct dm_ioctl* io = (struct dm_ioctl*)buffer; + // Create the DM device ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0); @@ -198,14 +195,14 @@ int Devmapper::destroy(const char *name_raw) { int Devmapper::destroyAll() { ATRACE_NAME("Devmapper::destroyAll"); - char *buffer = (char *) malloc(1024 * 64); + 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); + char* buffer2 = (char*)malloc(DEVMAPPER_BUFFER_SIZE); if (!buffer2) { PLOG(ERROR) << "Failed malloc"; free(buffer); @@ -220,7 +217,7 @@ int Devmapper::destroyAll() { return -1; } - struct dm_ioctl *io = (struct dm_ioctl *) buffer; + struct dm_ioctl* io = (struct dm_ioctl*)buffer; ioctlInit(io, (1024 * 64), NULL, 0); if (ioctl(fd, DM_LIST_DEVICES, io)) { @@ -231,7 +228,7 @@ int Devmapper::destroyAll() { return -1; } - struct dm_name_list *n = (struct dm_name_list *) (((char *) buffer) + io->data_start); + struct dm_name_list* n = (struct dm_name_list*)(((char*)buffer) + io->data_start); if (!n->dev) { free(buffer); free(buffer2); @@ -241,13 +238,13 @@ int Devmapper::destroyAll() { unsigned nxt = 0; do { - n = (struct dm_name_list *) (((char *) n) + nxt); + 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; + struct dm_ioctl* io2 = (struct dm_ioctl*)buffer2; ioctlInit(io2, DEVMAPPER_BUFFER_SIZE, n->name, 0); if (ioctl(fd, DM_DEV_REMOVE, io2)) { if (errno != ENXIO) { @@ -266,9 +263,8 @@ int Devmapper::destroyAll() { return 0; } -void *Devmapper::_align(void *ptr, unsigned int a) -{ - unsigned long agn = --a; +void* Devmapper::_align(void* ptr, unsigned int a) { + unsigned long agn = --a; - return (void *) (((unsigned long) ptr + agn) & ~agn); + return (void*)(((unsigned long)ptr + agn) & ~agn); } diff --git a/Devmapper.h b/Devmapper.h index 7bb9786..b1f6dfa 100644 --- a/Devmapper.h +++ b/Devmapper.h @@ -17,20 +17,19 @@ #ifndef _DEVMAPPER_H #define _DEVMAPPER_H -#include #include +#include class Devmapper { -public: - static int create(const char *name, const char *loopFile, const char *key, - unsigned long numSectors, char *buffer, size_t len); - static int destroy(const char *name); + public: + static int create(const char* name, const char* loopFile, const char* key, + 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); + 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 6462dbf..7f0d770 100644 --- a/EncryptInplace.cpp +++ b/EncryptInplace.cpp @@ -16,16 +16,16 @@ #include "EncryptInplace.h" -#include -#include -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include +#include +#include +#include #include @@ -36,13 +36,11 @@ #include "cryptfs.h" // FIXME horrible cut-and-paste code -static inline int unix_read(int fd, void* buff, int len) -{ +static inline int unix_read(int fd, void* buff, int len) { return TEMP_FAILURE_RETRY(read(fd, buff, len)); } -static inline int unix_write(int fd, const void* buff, int len) -{ +static inline int unix_write(int fd, const void* buff, int len) { return TEMP_FAILURE_RETRY(write(fd, buff, len)); } @@ -57,15 +55,14 @@ static inline int unix_write(int fd, const void* buff, int len) #define BLOCKS_AT_A_TIME 1024 #endif -struct encryptGroupsData -{ +struct encryptGroupsData { int realfd; int cryptofd; off64_t numblocks; off64_t one_pct, cur_pct, new_pct; off64_t blocks_already_done, tot_numblocks; off64_t used_blocks_already_done, tot_used_blocks; - char* real_blkdev, * crypto_blkdev; + char *real_blkdev, *crypto_blkdev; int count; off64_t offset; char* buffer; @@ -76,8 +73,7 @@ struct encryptGroupsData bool set_progress_properties; }; -static void update_progress(struct encryptGroupsData* data, int is_used) -{ +static void update_progress(struct encryptGroupsData* data, int is_used) { data->blocks_already_done++; if (is_used) { @@ -104,16 +100,14 @@ static void update_progress(struct encryptGroupsData* data, int is_used) LOG(WARNING) << "Error getting time"; } else { double elapsed_time = difftime(time_now.tv_sec, data->time_started); - off64_t remaining_blocks = data->tot_used_blocks - - data->used_blocks_already_done; - int remaining_time = (int)(elapsed_time * remaining_blocks - / data->used_blocks_already_done); + off64_t remaining_blocks = data->tot_used_blocks - data->used_blocks_already_done; + int remaining_time = + (int)(elapsed_time * remaining_blocks / data->used_blocks_already_done); // Change time only if not yet set, lower, or a lot higher for // best user experience - if (data->remaining_time == -1 - || remaining_time < data->remaining_time - || remaining_time > data->remaining_time + 60) { + if (data->remaining_time == -1 || remaining_time < data->remaining_time || + remaining_time > data->remaining_time + 60) { char buf[8]; snprintf(buf, sizeof(buf), "%d", remaining_time); android::base::SetProperty("vold.encrypt_time_remaining", buf); @@ -123,8 +117,7 @@ static void update_progress(struct encryptGroupsData* data, int is_used) } } -static void log_progress(struct encryptGroupsData const* data, bool completed) -{ +static void log_progress(struct encryptGroupsData const* data, bool completed) { // Precondition - if completed data = 0 else data != 0 // Track progress so we can skip logging blocks @@ -147,8 +140,7 @@ static void log_progress(struct encryptGroupsData const* data, bool completed) } } -static int flush_outstanding_data(struct encryptGroupsData* data) -{ +static int flush_outstanding_data(struct encryptGroupsData* data) { if (data->count == 0) { return 0; } @@ -165,30 +157,29 @@ static int flush_outstanding_data(struct encryptGroupsData* data) << " for inplace encrypt"; return -1; } else { - log_progress(data, false); + log_progress(data, false); } data->count = 0; - data->last_written_sector = (data->offset + data->count) - / info.block_size * CRYPT_SECTOR_SIZE - 1; + data->last_written_sector = + (data->offset + data->count) / info.block_size * CRYPT_SECTOR_SIZE - 1; return 0; } -static int encrypt_groups(struct encryptGroupsData* data) -{ +static int encrypt_groups(struct encryptGroupsData* data) { unsigned int i; - u8 *block_bitmap = 0; + u8* block_bitmap = 0; unsigned int block; off64_t ret; int rc = -1; - data->buffer = (char*) malloc(info.block_size * BLOCKS_AT_A_TIME); + data->buffer = (char*)malloc(info.block_size * BLOCKS_AT_A_TIME); if (!data->buffer) { LOG(ERROR) << "Failed to allocate crypto buffer"; goto errout; } - block_bitmap = (u8*) malloc(info.block_size); + block_bitmap = (u8*)malloc(info.block_size); if (!block_bitmap) { LOG(ERROR) << "failed to allocate block bitmap"; goto errout; @@ -198,11 +189,9 @@ static int encrypt_groups(struct encryptGroupsData* data) LOG(INFO) << "Encrypting group " << i; u32 first_block = aux_info.first_data_block + i * info.blocks_per_group; - u32 block_count = std::min(info.blocks_per_group, - (u32)(aux_info.len_blocks - first_block)); + u32 block_count = std::min(info.blocks_per_group, (u32)(aux_info.len_blocks - first_block)); - off64_t offset = (u64)info.block_size - * aux_info.bg_desc[i].bg_block_bitmap; + off64_t offset = (u64)info.block_size * aux_info.bg_desc[i].bg_block_bitmap; ret = pread64(data->realfd, block_bitmap, info.block_size, offset); if (ret != (int)info.block_size) { @@ -215,8 +204,9 @@ static int encrypt_groups(struct encryptGroupsData* data) data->count = 0; for (block = 0; block < block_count; block++) { - int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ? - 0 : bitmap_get_bit(block_bitmap, block); + int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) + ? 0 + : bitmap_get_bit(block_bitmap, block); update_progress(data, used); if (used) { if (data->count == 0) { @@ -232,8 +222,8 @@ static int encrypt_groups(struct encryptGroupsData* data) offset += info.block_size; /* Write data if we are aligned or buffer size reached */ - if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0 - || data->count == BLOCKS_AT_A_TIME) { + if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0 || + data->count == BLOCKS_AT_A_TIME) { if (flush_outstanding_data(data)) { goto errout; } @@ -260,7 +250,7 @@ static int cryptfs_enable_inplace_ext4(char* crypto_blkdev, char* real_blkdev, o bool set_progress_properties) { u32 i; struct encryptGroupsData data; - int rc; // Can't initialize without causing warning -Wclobbered + int rc; // Can't initialize without causing warning -Wclobbered int retries = RETRY_MOUNT_ATTEMPTS; struct timespec time_started = {0}; @@ -275,7 +265,7 @@ static int cryptfs_enable_inplace_ext4(char* crypto_blkdev, char* real_blkdev, o data.set_progress_properties = set_progress_properties; LOG(DEBUG) << "Opening" << real_blkdev; - if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) { + if ((data.realfd = open(real_blkdev, O_RDWR | O_CLOEXEC)) < 0) { PLOG(ERROR) << "Error opening real_blkdev " << real_blkdev << " for inplace encrypt"; rc = -1; goto errout; @@ -283,7 +273,7 @@ static int cryptfs_enable_inplace_ext4(char* crypto_blkdev, char* real_blkdev, o LOG(DEBUG) << "Opening" << crypto_blkdev; // Wait until the block device appears. Re-use the mount retry values since it is reasonable. - while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) { + while ((data.cryptofd = open(crypto_blkdev, O_WRONLY | O_CLOEXEC)) < 0) { if (--retries) { PLOG(ERROR) << "Error opening crypto_blkdev " << crypto_blkdev << " for ext4 inplace encrypt, retrying"; @@ -296,7 +286,7 @@ static int cryptfs_enable_inplace_ext4(char* crypto_blkdev, char* real_blkdev, o } } - if (setjmp(setjmp_env)) { // NOLINT + if (setjmp(setjmp_env)) { // NOLINT LOG(ERROR) << "Reading ext4 extent caused an exception"; rc = -1; goto errout; @@ -316,7 +306,7 @@ static int cryptfs_enable_inplace_ext4(char* crypto_blkdev, char* real_blkdev, o data.tot_used_blocks = data.numblocks; for (i = 0; i < aux_info.groups; ++i) { - data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count; + data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count; } data.one_pct = data.tot_used_blocks / 100; @@ -345,8 +335,7 @@ errout: return rc; } -static void log_progress_f2fs(u64 block, bool completed) -{ +static void log_progress_f2fs(u64 block, bool completed) { // Precondition - if completed data = 0 else data != 0 // Track progress so we can skip logging blocks @@ -369,9 +358,8 @@ static void log_progress_f2fs(u64 block, bool completed) } } -static int encrypt_one_block_f2fs(u64 pos, void *data) -{ - struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data; +static int encrypt_one_block_f2fs(u64 pos, void* data) { + struct encryptGroupsData* priv_dat = (struct encryptGroupsData*)data; priv_dat->blocks_already_done = pos - 1; update_progress(priv_dat, 1); @@ -400,7 +388,7 @@ static int cryptfs_enable_inplace_f2fs(char* crypto_blkdev, char* real_blkdev, o off64_t previously_encrypted_upto, bool set_progress_properties) { struct encryptGroupsData data; - struct f2fs_info *f2fs_info = NULL; + struct f2fs_info* f2fs_info = NULL; int rc = ENABLE_INPLACE_ERR_OTHER; if (previously_encrypted_upto > *size_already_done) { LOG(DEBUG) << "Not fast encrypting since resuming part way through"; @@ -412,11 +400,11 @@ static int cryptfs_enable_inplace_f2fs(char* crypto_blkdev, char* real_blkdev, o data.set_progress_properties = set_progress_properties; data.realfd = -1; data.cryptofd = -1; - if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) { + if ((data.realfd = open64(real_blkdev, O_RDWR | O_CLOEXEC)) < 0) { PLOG(ERROR) << "Error opening real_blkdev " << real_blkdev << " for f2fs inplace encrypt"; goto errout; } - if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) { + if ((data.cryptofd = open64(crypto_blkdev, O_WRONLY | O_CLOEXEC)) < 0) { PLOG(ERROR) << "Error opening crypto_blkdev " << crypto_blkdev << " for f2fs inplace encrypt"; rc = ENABLE_INPLACE_ERR_DEV; @@ -424,8 +412,7 @@ static int cryptfs_enable_inplace_f2fs(char* crypto_blkdev, char* real_blkdev, o } f2fs_info = generate_f2fs_info(data.realfd); - if (!f2fs_info) - goto errout; + if (!f2fs_info) goto errout; data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE; data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE; @@ -438,7 +425,7 @@ static int cryptfs_enable_inplace_f2fs(char* crypto_blkdev, char* real_blkdev, o data.time_started = time(NULL); data.remaining_time = -1; - data.buffer = (char*) malloc(f2fs_info->block_size); + data.buffer = (char*)malloc(f2fs_info->block_size); if (!data.buffer) { LOG(ERROR) << "Failed to allocate crypto buffer"; goto errout; @@ -475,18 +462,18 @@ static int cryptfs_enable_inplace_full(char* crypto_blkdev, char* real_blkdev, o off64_t previously_encrypted_upto, bool set_progress_properties) { int realfd, cryptofd; - char *buf[CRYPT_INPLACE_BUFSIZE]; + char* buf[CRYPT_INPLACE_BUFSIZE]; int rc = ENABLE_INPLACE_ERR_OTHER; off64_t numblocks, i, remainder; off64_t one_pct, cur_pct, new_pct; off64_t blocks_already_done, tot_numblocks; - if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) { + if ((realfd = open(real_blkdev, O_RDONLY | O_CLOEXEC)) < 0) { PLOG(ERROR) << "Error opening real_blkdev " << real_blkdev << " for inplace encrypt"; return ENABLE_INPLACE_ERR_OTHER; } - if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) { + if ((cryptofd = open(crypto_blkdev, O_WRONLY | O_CLOEXEC)) < 0) { PLOG(ERROR) << "Error opening crypto_blkdev " << crypto_blkdev << " for inplace encrypt"; close(realfd); return ENABLE_INPLACE_ERR_DEV; @@ -516,7 +503,7 @@ static int cryptfs_enable_inplace_full(char* crypto_blkdev, char* real_blkdev, o goto errout; } - for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) { + for (; i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) { if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) { PLOG(ERROR) << "Error reading initial sectors from real_blkdev " << real_blkdev << " for inplace encrypt"; @@ -534,7 +521,7 @@ static int cryptfs_enable_inplace_full(char* crypto_blkdev, char* real_blkdev, o one_pct = tot_numblocks / 100; cur_pct = 0; /* process the majority of the filesystem in blocks */ - for (i/=CRYPT_SECTORS_PER_BUFSIZE; i cur_pct) { char buf[8]; @@ -557,7 +544,7 @@ static int cryptfs_enable_inplace_full(char* crypto_blkdev, char* real_blkdev, o } /* Do any remaining sectors */ - for (i=0; i #include #include -#include #include #include #include #include #include +#include #include @@ -93,7 +93,7 @@ std::map s_ce_key_raw_refs; // TODO abolish this map, per b/26948053 std::map s_ce_keys; -} +} // namespace static bool e4crypt_is_emulated() { return property_get_bool("persist.sys.emulate_fbe", false); @@ -145,8 +145,7 @@ static std::string get_ce_key_current_path(const std::string& directory_path) { } static bool get_ce_key_new_path(const std::string& directory_path, - const std::vector& paths, - std::string *ce_key_path) { + const std::vector& paths, std::string* ce_key_path) { if (paths.empty()) { *ce_key_path = get_ce_key_current_path(directory_path); return true; @@ -163,9 +162,9 @@ static bool get_ce_key_new_path(const std::string& directory_path, // Discard all keys but the named one; rename it to canonical name. // No point in acting on errors in this; ignore them. -static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix, +static void fixate_user_ce_key(const std::string& directory_path, const std::string& to_fix, const std::vector& paths) { - for (auto const other_path: paths) { + for (auto const other_path : paths) { if (other_path != to_fix) { android::vold::destroyKey(other_path); } @@ -181,10 +180,10 @@ static void fixate_user_ce_key(const std::string& directory_path, const std::str static bool read_and_fixate_user_ce_key(userid_t user_id, const android::vold::KeyAuthentication& auth, - KeyBuffer *ce_key) { + KeyBuffer* ce_key) { auto const directory_path = get_ce_key_directory_path(user_id); auto const paths = get_ce_key_paths(directory_path); - for (auto const ce_key_path: paths) { + for (auto const ce_key_path : paths) { LOG(DEBUG) << "Trying user CE key " << ce_key_path; if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) { LOG(DEBUG) << "Successfully retrieved key"; @@ -242,12 +241,14 @@ static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral 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, - kEmptyAuthentication, ce_key)) return false; + if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication, + ce_key)) + return false; fixate_user_ce_key(directory_path, ce_key_path, paths); // Write DE key second; once this is written, all is good. if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp, - kEmptyAuthentication, de_key)) return false; + kEmptyAuthentication, de_key)) + return false; } std::string de_raw_ref; if (!android::vold::installKey(de_key, &de_raw_ref)) return false; @@ -440,14 +441,14 @@ bool e4crypt_destroy_user_key(userid_t user_id) { 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); + success &= + lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && android::vold::evictKey(raw_ref); s_de_key_raw_refs.erase(user_id); auto it = s_ephemeral_users.find(user_id); if (it != s_ephemeral_users.end()) { s_ephemeral_users.erase(it); } else { - for (auto const path: get_ce_key_paths(get_ce_key_directory_path(user_id))) { + for (auto const path : get_ce_key_paths(get_ce_key_directory_path(user_id))) { success &= android::vold::destroyKey(path); } auto de_key_path = get_de_key_path(user_id); @@ -556,14 +557,14 @@ bool e4crypt_add_user_key_auth(userid_t user_id, int serial, const std::string& 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 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; + 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; @@ -670,7 +671,8 @@ bool e4crypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_ if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false; #if MANAGE_MISC_DIRS if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM), - multiuser_get_uid(user_id, AID_EVERYBODY))) return false; + multiuser_get_uid(user_id, AID_EVERYBODY))) + return false; #endif if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false; diff --git a/FileDeviceUtils.cpp b/FileDeviceUtils.cpp index bc9f4bd..ce938a9 100644 --- a/FileDeviceUtils.cpp +++ b/FileDeviceUtils.cpp @@ -16,15 +16,15 @@ #include "FileDeviceUtils.h" +#include +#include +#include +#include +#include #include #include -#include -#include #include -#include -#include -#include -#include +#include #include #include @@ -40,38 +40,33 @@ namespace android { namespace vold { // Given a file path, look for the corresponding block device in /proc/mount -std::string BlockDeviceForPath(const std::string &path) -{ - std::unique_ptr mnts(setmntent("/proc/mounts", "re"), endmntent); +std::string BlockDeviceForPath(const std::string& path) { + std::unique_ptr mnts(setmntent("/proc/mounts", "re"), endmntent); if (!mnts) { PLOG(ERROR) << "Unable to open /proc/mounts"; return ""; } std::string result; size_t best_length = 0; - struct mntent *mnt; // getmntent returns a thread local, so it's safe. + struct mntent* mnt; // getmntent returns a thread local, so it's safe. while ((mnt = getmntent(mnts.get())) != nullptr) { auto l = strlen(mnt->mnt_dir); - if (l > best_length && - path.size() > l && - path[l] == '/' && + if (l > best_length && path.size() > l && path[l] == '/' && path.compare(0, l, mnt->mnt_dir) == 0) { - result = mnt->mnt_fsname; - best_length = l; + result = mnt->mnt_fsname; + best_length = l; } } if (result.empty()) { - LOG(ERROR) <<"Didn't find a mountpoint to match path " << path; + LOG(ERROR) << "Didn't find a mountpoint to match path " << path; return ""; } LOG(DEBUG) << "For path " << path << " block device is " << result; return result; } -std::unique_ptr PathFiemap(const std::string &path, uint32_t extent_count) -{ - android::base::unique_fd fd(TEMP_FAILURE_RETRY(open( - path.c_str(), O_RDONLY | O_CLOEXEC, 0))); +std::unique_ptr PathFiemap(const std::string& path, uint32_t extent_count) { + android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC, 0))); if (fd == -1) { if (errno == ENOENT) { PLOG(DEBUG) << "Unable to open " << path; @@ -88,7 +83,7 @@ std::unique_ptr PathFiemap(const std::string &path, uint32_t exte auto mapped = fiemap->fm_mapped_extents; if (mapped < 1 || mapped > extent_count) { LOG(ERROR) << "Extent count not in bounds 1 <= " << mapped << " <= " << extent_count - << " in " << path; + << " in " << path; return nullptr; } return fiemap; @@ -99,10 +94,9 @@ std::unique_ptr PathFiemap(const std::string &path, uint32_t exte namespace { -std::unique_ptr alloc_fiemap(uint32_t extent_count) -{ +std::unique_ptr alloc_fiemap(uint32_t extent_count) { size_t allocsize = offsetof(struct fiemap, fm_extents[extent_count]); - std::unique_ptr res(new (::operator new (allocsize)) struct fiemap); + std::unique_ptr res(new (::operator new(allocsize)) struct fiemap); memset(res.get(), 0, allocsize); res->fm_start = 0; res->fm_length = UINT64_MAX; @@ -112,4 +106,4 @@ std::unique_ptr alloc_fiemap(uint32_t extent_count) return res; } -} +} // namespace diff --git a/FileDeviceUtils.h b/FileDeviceUtils.h index 4c1d49a..4428cef 100644 --- a/FileDeviceUtils.h +++ b/FileDeviceUtils.h @@ -17,17 +17,17 @@ #ifndef ANDROID_VOLD_FILEDEVICEUTILS_H #define ANDROID_VOLD_FILEDEVICEUTILS_H -#include #include +#include namespace android { namespace vold { // Given a file path, look for the corresponding block device in /proc/mount -std::string BlockDeviceForPath(const std::string &path); +std::string BlockDeviceForPath(const std::string& path); // Read the file's FIEMAP -std::unique_ptr PathFiemap(const std::string &path, uint32_t extent_count); +std::unique_ptr PathFiemap(const std::string& path, uint32_t extent_count); } // namespace vold } // namespace android diff --git a/IdleMaint.cpp b/IdleMaint.cpp index 459b3b8..ff2ebc5 100644 --- a/IdleMaint.cpp +++ b/IdleMaint.cpp @@ -33,11 +33,11 @@ #include #include +#include #include #include #include #include -#include using android::base::Basename; using android::base::ReadFileToString; @@ -80,8 +80,7 @@ static IdleMaintStats idle_maint_stat(IdleMaintStats::kStopped); static std::condition_variable cv_abort, cv_stop; static std::mutex cv_m; -static void addFromVolumeManager(std::list* paths, - PathTypes path_type) { +static void addFromVolumeManager(std::list* paths, PathTypes path_type) { VolumeManager* vm = VolumeManager::Instance(); std::list privateIds; vm->listVolumes(VolumeBase::Type::kPrivate, privateIds); @@ -95,11 +94,9 @@ static void addFromVolumeManager(std::list* paths, const std::string& fs_type = vol->getFsType(); if (fs_type == "f2fs" && (Realpath(vol->getRawDmDevPath(), &gc_path) || Realpath(vol->getRawDevPath(), &gc_path))) { - paths->push_back(std::string("/sys/fs/") + fs_type + - "/" + Basename(gc_path)); + paths->push_back(std::string("/sys/fs/") + fs_type + "/" + Basename(gc_path)); } } - } } } @@ -107,7 +104,7 @@ static void addFromVolumeManager(std::list* paths, static void addFromFstab(std::list* paths, PathTypes path_type) { std::unique_ptr fstab(fs_mgr_read_fstab_default(), fs_mgr_free_fstab); - struct fstab_rec *prev_rec = NULL; + struct fstab_rec* prev_rec = NULL; for (int i = 0; i < fstab->num_entries; i++) { auto fs_type = std::string(fstab->recs[i].fs_type); @@ -138,10 +135,11 @@ static void addFromFstab(std::list* paths, PathTypes path_type) { } else if (path_type == PathTypes::kBlkDevice) { std::string gc_path; if (std::string(fstab->recs[i].fs_type) == "f2fs" && - Realpath(android::vold::BlockDeviceForPath( - std::string(fstab->recs[i].mount_point) + "/"), &gc_path)) { - paths->push_back(std::string("/sys/fs/") + fstab->recs[i].fs_type + - "/" + Basename(gc_path)); + Realpath( + android::vold::BlockDeviceForPath(std::string(fstab->recs[i].mount_point) + "/"), + &gc_path)) { + paths->push_back(std::string("/sys/fs/") + fstab->recs[i].fs_type + "/" + + Basename(gc_path)); } } @@ -184,8 +182,8 @@ void Trim(const android::sp& listener) { } } else { nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start; - LOG(INFO) << "Trimmed " << range.len << " bytes on " << path - << " in " << nanoseconds_to_milliseconds(time) << "ms"; + LOG(INFO) << "Trimmed " << range.len << " bytes on " << path << " in " + << nanoseconds_to_milliseconds(time) << "ms"; extras.putLong(String16("bytes"), range.len); extras.putLong(String16("time"), time); if (listener) { @@ -230,8 +228,8 @@ static bool waitForGc(const std::list& paths) { } lk.lock(); - aborted = cv_abort.wait_for(lk, 10s, []{ - return idle_maint_stat == IdleMaintStats::kAbort;}); + aborted = + cv_abort.wait_for(lk, 10s, [] { return idle_maint_stat == IdleMaintStats::kAbort; }); lk.unlock(); } @@ -267,7 +265,7 @@ static int stopGc(const std::list& paths) { static void runDevGcFstab(void) { std::unique_ptr fstab(fs_mgr_read_fstab_default(), fs_mgr_free_fstab); - struct fstab_rec *rec = NULL; + struct fstab_rec* rec = NULL; for (int i = 0; i < fstab->num_entries; i++) { if (fs_mgr_has_sysfs_path(&fstab->recs[i])) { @@ -427,8 +425,7 @@ int AbortIdleMaint(const android::sp& listener) cv_abort.notify_one(); lk.lock(); LOG(DEBUG) << "aborting idle maintenance"; - cv_stop.wait(lk, []{ - return idle_maint_stat == IdleMaintStats::kStopped;}); + cv_stop.wait(lk, [] { return idle_maint_stat == IdleMaintStats::kStopped; }); } lk.unlock(); diff --git a/KeyBuffer.cpp b/KeyBuffer.cpp index e7aede5..5633bf8 100644 --- a/KeyBuffer.cpp +++ b/KeyBuffer.cpp @@ -34,4 +34,3 @@ KeyBuffer operator+(KeyBuffer&& lhs, const char* rhs) { } // namespace vold } // namespace android - diff --git a/KeyBuffer.h b/KeyBuffer.h index 2087187..a68311f 100644 --- a/KeyBuffer.h +++ b/KeyBuffer.h @@ -33,17 +33,15 @@ namespace vold { #define OPTNONE __attribute__((optimize("O0"))) #endif // not __clang__ inline OPTNONE void* memset_s(void* s, int c, size_t n) { - if (!s) - return s; + if (!s) return s; return memset(s, c, n); } #undef OPTNONE // Allocator that delegates useful work to standard one but zeroes data before deallocating. class ZeroingAllocator : public std::allocator { - public: - void deallocate(pointer p, size_type n) - { + public: + void deallocate(pointer p, size_type n) { memset_s(p, 0, n); std::allocator::deallocate(p, n); } @@ -60,4 +58,3 @@ KeyBuffer operator+(KeyBuffer&& lhs, const char* rhs); } // namespace android #endif - diff --git a/KeyStorage.cpp b/KeyStorage.cpp index 0518930..035c7b7 100644 --- a/KeyStorage.cpp +++ b/KeyStorage.cpp @@ -568,7 +568,10 @@ bool destroyKey(const std::string& dir) { success &= deleteKey(dir); } auto secdiscard_cmd = std::vector{ - kSecdiscardPath, "--", dir + "/" + kFn_encrypted_key, dir + "/" + kFn_secdiscardable, + kSecdiscardPath, + "--", + dir + "/" + kFn_encrypted_key, + dir + "/" + kFn_secdiscardable, }; if (uses_km) { secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob); diff --git a/KeyUtil.cpp b/KeyUtil.cpp index 9885440..29ba699 100644 --- a/KeyUtil.cpp +++ b/KeyUtil.cpp @@ -88,12 +88,7 @@ static bool fillKey(const KeyBuffer& key, ext4_encryption_key* ext4_key) { return true; } -static char const* const NAME_PREFIXES[] = { - "ext4", - "f2fs", - "fscrypt", - nullptr -}; +static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr}; static std::string keyname(const std::string& prefix, const std::string& raw_ref) { std::ostringstream o; @@ -119,7 +114,7 @@ static bool e4cryptKeyring(key_serial_t* device_keyring) { bool installKey(const KeyBuffer& key, std::string* raw_ref) { // Place ext4_encryption_key into automatically zeroing buffer. KeyBuffer ext4KeyBuffer(sizeof(ext4_encryption_key)); - ext4_encryption_key &ext4_key = *reinterpret_cast(ext4KeyBuffer.data()); + ext4_encryption_key& ext4_key = *reinterpret_cast(ext4KeyBuffer.data()); if (!fillKey(key, &ext4_key)) return false; *raw_ref = generateKeyRef(ext4_key.raw, ext4_key.size); @@ -170,8 +165,8 @@ bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_a 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(ERROR) << "No key found in " << key_path; + return false; } LOG(INFO) << "Creating new key in " << key_path; if (!randomKey(&key)) return false; @@ -185,20 +180,19 @@ bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_a return true; } -bool retrieveKey(bool create_if_absent, const std::string& key_path, - const std::string& tmp_path, KeyBuffer* key) { +bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path, + KeyBuffer* key) { if (pathExists(key_path)) { LOG(DEBUG) << "Key exists, using: " << key_path; if (!retrieveKey(key_path, kEmptyAuthentication, key)) return false; } else { if (!create_if_absent) { - LOG(ERROR) << "No key found in " << key_path; - return false; + LOG(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 (!storeKeyAtomically(key_path, tmp_path, kEmptyAuthentication, *key)) return false; } return true; } diff --git a/KeyUtil.h b/KeyUtil.h index a85eca1..b4115f4 100644 --- a/KeyUtil.h +++ b/KeyUtil.h @@ -20,8 +20,8 @@ #include "KeyBuffer.h" #include "KeyStorage.h" -#include #include +#include namespace android { namespace vold { @@ -32,8 +32,8 @@ 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 retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path, + KeyBuffer* key); } // namespace vold } // namespace android diff --git a/Loop.cpp b/Loop.cpp index 335ca13..92f1e97 100644 --- a/Loop.cpp +++ b/Loop.cpp @@ -16,24 +16,24 @@ #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER +#include +#include +#include #include #include -#include -#include -#include -#include #include +#include -#include -#include -#include #include +#include +#include +#include #include #include -#include #include +#include #include #include @@ -79,7 +79,7 @@ int Loop::create(const std::string& target, std::string& out_device) { struct loop_info64 li; memset(&li, 0, sizeof(li)); - strlcpy((char*) li.lo_crypt_name, kVoldPrefix, LO_NAME_SIZE); + strlcpy((char*)li.lo_crypt_name, kVoldPrefix, LO_NAME_SIZE); if (ioctl(device_fd.get(), LOOP_SET_STATUS64, &li) == -1) { PLOG(ERROR) << "Failed to LOOP_SET_STATUS64"; return -errno; @@ -88,7 +88,7 @@ int Loop::create(const std::string& target, std::string& out_device) { return 0; } -int Loop::destroyByDevice(const char *loopDevice) { +int Loop::destroyByDevice(const char* loopDevice) { int device_fd; device_fd = open(loopDevice, O_RDONLY | O_CLOEXEC); @@ -138,7 +138,7 @@ int Loop::destroyAll() { continue; } - auto id = std::string((char*) li.lo_crypt_name); + auto id = std::string((char*)li.lo_crypt_name); if (android::base::StartsWith(id, kVoldPrefix)) { LOG(DEBUG) << "Tearing down stale loop device at " << path << " named " << id; @@ -153,7 +153,7 @@ int Loop::destroyAll() { return 0; } -int Loop::createImageFile(const char *file, unsigned long numSectors) { +int Loop::createImageFile(const char* file, unsigned long numSectors) { unique_fd fd(open(file, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0600)); if (fd.get() == -1) { PLOG(ERROR) << "Failed to create image " << file; @@ -169,7 +169,7 @@ int Loop::createImageFile(const char *file, unsigned long numSectors) { return 0; } -int Loop::resizeImageFile(const char *file, unsigned long numSectors) { +int Loop::resizeImageFile(const char* file, unsigned long numSectors) { int fd; if ((fd = open(file, O_RDWR | O_CLOEXEC)) < 0) { diff --git a/Loop.h b/Loop.h index 130c5b6..4e5f9c1 100644 --- a/Loop.h +++ b/Loop.h @@ -17,19 +17,20 @@ #ifndef _LOOP_H #define _LOOP_H -#include -#include #include +#include +#include class Loop { -public: + public: static const int LOOP_MAX = 4096; -public: + + public: static int create(const std::string& file, std::string& out_device); - static int destroyByDevice(const char *loopDevice); + static int destroyByDevice(const char* loopDevice); static int destroyAll(); - static int createImageFile(const char *file, unsigned long numSectors); - static int resizeImageFile(const char *file, unsigned long numSectors); + static int createImageFile(const char* file, unsigned long numSectors); + static int resizeImageFile(const char* file, unsigned long numSectors); }; #endif diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp index c14b9a2..842b19b 100644 --- a/MetadataCrypt.cpp +++ b/MetadataCrypt.cpp @@ -14,13 +14,13 @@ * limitations under the License. */ -#include "KeyBuffer.h" #include "MetadataCrypt.h" +#include "KeyBuffer.h" +#include #include #include #include -#include #include #include @@ -39,9 +39,9 @@ #include "EncryptInplace.h" #include "KeyStorage.h" #include "KeyUtil.h" -#include "secontext.h" #include "Utils.h" #include "VoldUtil.h" +#include "secontext.h" #define DM_CRYPT_BUF_SIZE 4096 #define TABLE_LOAD_RETRIES 10 @@ -99,9 +99,9 @@ static KeyBuffer default_key_params(const std::string& real_blkdev, const KeyBuf return res; } -static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t *nr_sec) { - android::base::unique_fd dev_fd(TEMP_FAILURE_RETRY(open( - real_blkdev.c_str(), O_RDONLY | O_CLOEXEC, 0))); +static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) { + android::base::unique_fd dev_fd( + TEMP_FAILURE_RETRY(open(real_blkdev.c_str(), O_RDONLY | O_CLOEXEC, 0))); if (dev_fd == -1) { PLOG(ERROR) << "Unable to open " << real_blkdev << " to measure size"; return false; @@ -117,15 +117,14 @@ static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t *nr_s return true; } -static struct dm_ioctl* dm_ioctl_init(char *buffer, size_t buffer_size, - const std::string& dm_name) { +static struct dm_ioctl* dm_ioctl_init(char* buffer, size_t buffer_size, const std::string& dm_name) { if (buffer_size < sizeof(dm_ioctl)) { LOG(ERROR) << "dm_ioctl buffer too small"; return nullptr; } memset(buffer, 0, buffer_size); - struct dm_ioctl* io = (struct dm_ioctl*) buffer; + struct dm_ioctl* io = (struct dm_ioctl*)buffer; io->data_size = buffer_size; io->data_start = sizeof(struct dm_ioctl); io->version[0] = 4; @@ -139,8 +138,8 @@ static struct dm_ioctl* dm_ioctl_init(char *buffer, size_t buffer_size, 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))); + 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"; return false; @@ -158,13 +157,13 @@ static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec, 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)); + *crypto_blkdev = std::string() + "/dev/block/dm-" + + std::to_string((io->dev & 0xff) | ((io->dev >> 12) & 0xfff00)); io = dm_ioctl_init(buffer, sizeof(buffer), dm_name); 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 + size_t endix = (nullix + 1 + 7) & 8; // Add room for \0 and align to 8 byte boundary if (endix > sizeof(buffer)) { LOG(ERROR) << "crypt_params too big for DM_CRYPT_BUF_SIZE"; @@ -172,21 +171,21 @@ static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec, } io->target_count = 1; - auto tgt = (struct dm_target_spec *) (buffer + io->data_start); + 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)); + std::min(crypt_params.size(), sizeof(buffer) - paramix)); buffer[nullix] = '\0'; tgt->next = endix; - for (int i = 0; ; i++) { + for (int i = 0;; i++) { if (ioctl(dm_fd.get(), DM_TABLE_LOAD, io) == 0) { break; } - if (i+1 >= TABLE_LOAD_RETRIES) { + if (i + 1 >= TABLE_LOAD_RETRIES) { PLOG(ERROR) << "DM_TABLE_LOAD ioctl failed"; return false; } diff --git a/MoveStorage.cpp b/MoveStorage.cpp index 4624026..4653e01 100644 --- a/MoveStorage.cpp +++ b/MoveStorage.cpp @@ -29,7 +29,8 @@ #include #include -#define CONSTRAIN(amount, low, high) ((amount) < (low) ? (low) : ((amount) > (high) ? (high) : (amount))) +#define CONSTRAIN(amount, low, high) \ + ((amount) < (low) ? (low) : ((amount) > (high) ? (high) : (amount))) static const char* kPropBlockingExec = "persist.sys.blocking_exec"; @@ -48,7 +49,7 @@ static const char* kRmPath = "/system/bin/rm"; static const char* kWakeLock = "MoveTask"; static void notifyProgress(int progress, - const android::sp& listener) { + const android::sp& listener) { if (listener) { android::os::PersistableBundle extras; listener->onStatus(progress, extras); @@ -56,7 +57,7 @@ static void notifyProgress(int progress, } static status_t pushBackContents(const std::string& path, std::vector& cmd, - bool addWildcard) { + bool addWildcard) { DIR* dir = opendir(path.c_str()); if (dir == NULL) { return -1; @@ -79,7 +80,7 @@ static status_t pushBackContents(const std::string& path, std::vector& listener) { + const android::sp& listener) { notifyProgress(startProgress, listener); uint64_t expectedBytes = GetTreeBytes(path); @@ -114,14 +115,17 @@ static status_t execRm(const std::string& path, int startProgress, int stepProgr sleep(1); uint64_t deltaFreeBytes = GetFreeBytes(path) - startFreeBytes; - notifyProgress(startProgress + CONSTRAIN((int) - ((deltaFreeBytes * stepProgress) / expectedBytes), 0, stepProgress), listener); + notifyProgress( + startProgress + + CONSTRAIN((int)((deltaFreeBytes * stepProgress) / expectedBytes), 0, stepProgress), + listener); } return -1; } static status_t execCp(const std::string& fromPath, const std::string& toPath, int startProgress, - int stepProgress, const android::sp& listener) { + int stepProgress, + const android::sp& listener) { notifyProgress(startProgress, listener); uint64_t expectedBytes = GetTreeBytes(fromPath); @@ -129,7 +133,7 @@ static status_t execCp(const std::string& fromPath, const std::string& toPath, i if (expectedBytes > startFreeBytes) { LOG(ERROR) << "Data size " << expectedBytes << " is too large to fit in free space " - << startFreeBytes; + << startFreeBytes; return -1; } @@ -165,8 +169,10 @@ static status_t execCp(const std::string& fromPath, const std::string& toPath, i sleep(1); uint64_t deltaFreeBytes = startFreeBytes - GetFreeBytes(toPath); - notifyProgress(startProgress + CONSTRAIN((int) - ((deltaFreeBytes * stepProgress) / expectedBytes), 0, stepProgress), listener); + notifyProgress( + startProgress + + CONSTRAIN((int)((deltaFreeBytes * stepProgress) / expectedBytes), 0, stepProgress), + listener); } return -1; } @@ -186,8 +192,8 @@ static void bringOnline(const std::shared_ptr& vol) { } static status_t moveStorageInternal(const std::shared_ptr& from, - const std::shared_ptr& to, - const android::sp& listener) { + const std::shared_ptr& to, + const android::sp& listener) { std::string fromPath; std::string toPath; @@ -239,17 +245,19 @@ copy_fail: // useful anyway. execRm(toPath, 80, 1, listener); fail: + // clang-format off { std::lock_guard lock(VolumeManager::Instance()->getLock()); bringOnline(from); bringOnline(to); } + // clang-format on notifyProgress(kMoveFailedInternalError, listener); return -1; } void MoveStorage(const std::shared_ptr& from, const std::shared_ptr& to, - const android::sp& listener) { + const android::sp& listener) { acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock); android::os::PersistableBundle extras; diff --git a/MoveStorage.h b/MoveStorage.h index d271704..46f745f 100644 --- a/MoveStorage.h +++ b/MoveStorage.h @@ -24,7 +24,7 @@ namespace android { namespace vold { void MoveStorage(const std::shared_ptr& from, const std::shared_ptr& to, - const android::sp& listener); + const android::sp& listener); } // namespace vold } // namespace android diff --git a/NetlinkHandler.cpp b/NetlinkHandler.cpp index 92131e9..d180a95 100644 --- a/NetlinkHandler.cpp +++ b/NetlinkHandler.cpp @@ -14,9 +14,9 @@ * limitations under the License. */ +#include #include #include -#include #include #include @@ -25,12 +25,9 @@ #include "NetlinkHandler.h" #include "VolumeManager.h" -NetlinkHandler::NetlinkHandler(int listenerSocket) : - NetlinkListener(listenerSocket) { -} +NetlinkHandler::NetlinkHandler(int listenerSocket) : NetlinkListener(listenerSocket) {} -NetlinkHandler::~NetlinkHandler() { -} +NetlinkHandler::~NetlinkHandler() {} int NetlinkHandler::start() { return this->startListener(); @@ -40,9 +37,9 @@ int NetlinkHandler::stop() { return this->stopListener(); } -void NetlinkHandler::onEvent(NetlinkEvent *evt) { - VolumeManager *vm = VolumeManager::Instance(); - const char *subsys = evt->getSubsystem(); +void NetlinkHandler::onEvent(NetlinkEvent* evt) { + VolumeManager* vm = VolumeManager::Instance(); + const char* subsys = evt->getSubsystem(); if (!subsys) { LOG(WARNING) << "No subsystem found in netlink event"; diff --git a/NetlinkHandler.h b/NetlinkHandler.h index 56eb23c..8af7575 100644 --- a/NetlinkHandler.h +++ b/NetlinkHandler.h @@ -19,16 +19,15 @@ #include -class NetlinkHandler: public NetlinkListener { - -public: +class NetlinkHandler : public NetlinkListener { + public: explicit NetlinkHandler(int listenerSocket); virtual ~NetlinkHandler(); int start(void); int stop(void); -protected: - virtual void onEvent(NetlinkEvent *evt); + protected: + virtual void onEvent(NetlinkEvent* evt); }; #endif diff --git a/NetlinkManager.cpp b/NetlinkManager.cpp index 409cdc8..aacf4b9 100644 --- a/NetlinkManager.cpp +++ b/NetlinkManager.cpp @@ -14,12 +14,12 @@ * limitations under the License. */ -#include #include +#include #include -#include #include +#include #include #include #include @@ -28,14 +28,13 @@ #include -#include "NetlinkManager.h" #include "NetlinkHandler.h" +#include "NetlinkManager.h" -NetlinkManager *NetlinkManager::sInstance = NULL; +NetlinkManager* NetlinkManager::sInstance = NULL; -NetlinkManager *NetlinkManager::Instance() { - if (!sInstance) - sInstance = new NetlinkManager(); +NetlinkManager* NetlinkManager::Instance() { + if (!sInstance) sInstance = new NetlinkManager(); return sInstance; } @@ -43,8 +42,7 @@ NetlinkManager::NetlinkManager() { mBroadcaster = NULL; } -NetlinkManager::~NetlinkManager() { -} +NetlinkManager::~NetlinkManager() {} int NetlinkManager::start() { struct sockaddr_nl nladdr; @@ -56,8 +54,7 @@ int NetlinkManager::start() { nladdr.nl_pid = getpid(); nladdr.nl_groups = 0xffffffff; - if ((mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, - NETLINK_KOBJECT_UEVENT)) < 0) { + if ((mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT)) < 0) { PLOG(ERROR) << "Unable to create uevent socket"; return -1; } @@ -76,7 +73,7 @@ int NetlinkManager::start() { goto out; } - if (bind(mSock, (struct sockaddr *) &nladdr, sizeof(nladdr)) < 0) { + if (bind(mSock, (struct sockaddr*)&nladdr, sizeof(nladdr)) < 0) { PLOG(ERROR) << "Unable to bind uevent socket"; goto out; } diff --git a/NetlinkManager.h b/NetlinkManager.h index 9c7ba11..e31fc2e 100644 --- a/NetlinkManager.h +++ b/NetlinkManager.h @@ -17,32 +17,32 @@ #ifndef _NETLINKMANAGER_H #define _NETLINKMANAGER_H -#include #include +#include class NetlinkHandler; class NetlinkManager { -private: - static NetlinkManager *sInstance; + private: + static NetlinkManager* sInstance; -private: - SocketListener *mBroadcaster; - NetlinkHandler *mHandler; - int mSock; + private: + SocketListener* mBroadcaster; + NetlinkHandler* mHandler; + int mSock; -public: + public: virtual ~NetlinkManager(); int start(); int stop(); - void setBroadcaster(SocketListener *sl) { mBroadcaster = sl; } - SocketListener *getBroadcaster() { return mBroadcaster; } + void setBroadcaster(SocketListener* sl) { mBroadcaster = sl; } + SocketListener* getBroadcaster() { return mBroadcaster; } - static NetlinkManager *Instance(); + static NetlinkManager* Instance(); -private: + private: NetlinkManager(); }; #endif diff --git a/Process.cpp b/Process.cpp index 9038af2..a5028f2 100644 --- a/Process.cpp +++ b/Process.cpp @@ -14,28 +14,28 @@ * limitations under the License. */ -#include -#include +#include +#include #include -#include #include #include -#include -#include -#include -#include #include -#include +#include #include +#include +#include +#include +#include +#include #include #include #include -#include -#include -#include #include +#include +#include +#include #include "Process.h" diff --git a/ScryptParameters.cpp b/ScryptParameters.cpp index c0e2030..f5a964f 100644 --- a/ScryptParameters.cpp +++ b/ScryptParameters.cpp @@ -19,20 +19,19 @@ #include #include -bool parse_scrypt_parameters(const char* paramstr, int *Nf, int *rf, int *pf) { +bool parse_scrypt_parameters(const char* paramstr, int* Nf, int* rf, int* pf) { int params[3] = {}; - char *token; - char *saveptr; + char* token; + char* saveptr; int i; /* * The token we're looking for should be three integers separated by * colons (e.g., "12:8:1"). Scan the property to make sure it matches. */ - for (i = 0, token = strtok_r(const_cast(paramstr), ":", &saveptr); - token != nullptr && i < 3; - i++, token = strtok_r(nullptr, ":", &saveptr)) { - char *endptr; + for (i = 0, token = strtok_r(const_cast(paramstr), ":", &saveptr); + token != nullptr && i < 3; i++, token = strtok_r(nullptr, ":", &saveptr)) { + char* endptr; params[i] = strtol(token, &endptr, 10); /* @@ -45,6 +44,8 @@ bool parse_scrypt_parameters(const char* paramstr, int *Nf, int *rf, int *pf) { if (token != nullptr) { return false; } - *Nf = params[0]; *rf = params[1]; *pf = params[2]; + *Nf = params[0]; + *rf = params[1]; + *pf = params[2]; return true; } diff --git a/ScryptParameters.h b/ScryptParameters.h index 190842b..edb80cc 100644 --- a/ScryptParameters.h +++ b/ScryptParameters.h @@ -23,6 +23,6 @@ #define SCRYPT_PROP "ro.crypto.scrypt_params" #define SCRYPT_DEFAULTS "15:3:1" -bool parse_scrypt_parameters(const char* paramstr, int *Nf, int *rf, int *pf); +bool parse_scrypt_parameters(const char* paramstr, int* Nf, int* rf, int* pf); #endif diff --git a/Utils.cpp b/Utils.cpp index 002af03..f085c22 100644 --- a/Utils.cpp +++ b/Utils.cpp @@ -22,26 +22,26 @@ #include #include #include -#include #include +#include #include #include #include -#include #include #include #include #include #include -#include #include -#include -#include #include +#include +#include +#include +#include #ifndef UMOUNT_NOFOLLOW -#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */ +#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */ #endif using android::base::ReadFileToString; @@ -81,8 +81,8 @@ status_t CreateDeviceNode(const std::string& path, dev_t dev) { mode_t mode = 0660 | S_IFBLK; if (mknod(cpath, mode, dev) < 0) { if (errno != EEXIST) { - PLOG(ERROR) << "Failed to create device node for " << major(dev) - << ":" << minor(dev) << " at " << path; + PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev) + << " at " << path; res = -errno; } } @@ -209,8 +209,8 @@ bool FindValue(const std::string& raw, const std::string& key, std::string* valu return true; } -static status_t readMetadata(const std::string& path, std::string* fsType, - std::string* fsUuid, std::string* fsLabel, bool untrusted) { +static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid, + std::string* fsLabel, bool untrusted) { fsType->clear(); fsUuid->clear(); fsLabel->clear(); @@ -244,13 +244,13 @@ static status_t readMetadata(const std::string& path, std::string* fsType, return OK; } -status_t ReadMetadata(const std::string& path, std::string* fsType, - std::string* fsUuid, std::string* fsLabel) { +status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid, + std::string* fsLabel) { return readMetadata(path, fsType, fsUuid, fsLabel, false); } -status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, - std::string* fsUuid, std::string* fsLabel) { +status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid, + std::string* fsLabel) { return readMetadata(path, fsType, fsUuid, fsLabel, true); } @@ -261,9 +261,9 @@ status_t ForkExecvp(const std::vector& args) { status_t ForkExecvp(const std::vector& args, security_context_t context) { std::lock_guard lock(kSecurityLock); size_t argc = args.size(); - char** argv = (char**) calloc(argc, sizeof(char*)); + char** argv = (char**)calloc(argc, sizeof(char*)); for (size_t i = 0; i < argc; i++) { - argv[i] = (char*) args[i].c_str(); + argv[i] = (char*)args[i].c_str(); if (i == 0) { LOG(VERBOSE) << args[i]; } else { @@ -289,13 +289,12 @@ status_t ForkExecvp(const std::vector& args, security_context_t con return res; } -status_t ForkExecvp(const std::vector& args, - std::vector& output) { +status_t ForkExecvp(const std::vector& args, std::vector& output) { return ForkExecvp(args, output, nullptr); } -status_t ForkExecvp(const std::vector& args, - std::vector& output, security_context_t context) { +status_t ForkExecvp(const std::vector& args, std::vector& output, + security_context_t context) { std::lock_guard lock(kSecurityLock); std::string cmd; for (size_t i = 0; i < args.size(); i++) { @@ -314,7 +313,7 @@ status_t ForkExecvp(const std::vector& args, abort(); } } - FILE* fp = popen(cmd.c_str(), "r"); // NOLINT + FILE* fp = popen(cmd.c_str(), "r"); // NOLINT if (context) { if (setexeccon(nullptr)) { LOG(ERROR) << "Failed to setexeccon"; @@ -341,9 +340,9 @@ status_t ForkExecvp(const std::vector& args, pid_t ForkExecvpAsync(const std::vector& args) { size_t argc = args.size(); - char** argv = (char**) calloc(argc + 1, sizeof(char*)); + char** argv = (char**)calloc(argc + 1, sizeof(char*)); for (size_t i = 0; i < argc; i++) { - argv[i] = (char*) args[i].c_str(); + argv[i] = (char*)args[i].c_str(); if (i == 0) { LOG(VERBOSE) << args[i]; } else { @@ -400,10 +399,10 @@ status_t ReadRandomBytes(size_t bytes, char* buf) { status_t GenerateRandomUuid(std::string& out) { status_t res = ReadRandomBytes(16, out); if (res == OK) { - out[6] &= 0x0f; /* clear version */ - out[6] |= 0x40; /* set to version 4 */ - out[8] &= 0x3f; /* clear variant */ - out[8] |= 0x80; /* set to IETF variant */ + out[6] &= 0x0f; /* clear version */ + out[6] |= 0x40; /* set to version 4 */ + out[8] &= 0x3f; /* clear variant */ + out[8] |= 0x80; /* set to IETF variant */ } return res; } @@ -415,24 +414,26 @@ status_t HexToStr(const std::string& hex, std::string& str) { for (size_t i = 0; i < hex.size(); i++) { int val = 0; switch (hex[i]) { - case ' ': case '-': case ':': continue; - case 'f': case 'F': val = 15; break; - case 'e': case 'E': val = 14; break; - case 'd': case 'D': val = 13; break; - case 'c': case 'C': val = 12; break; - case 'b': case 'B': val = 11; break; - case 'a': case 'A': val = 10; break; - case '9': val = 9; break; - case '8': val = 8; break; - case '7': val = 7; break; - case '6': val = 6; break; - case '5': val = 5; break; - case '4': val = 4; break; - case '3': val = 3; break; - case '2': val = 2; break; - case '1': val = 1; break; - case '0': val = 0; break; - default: return -EINVAL; + // clang-format off + case ' ': case '-': case ':': continue; + case 'f': case 'F': val = 15; break; + case 'e': case 'E': val = 14; break; + case 'd': case 'D': val = 13; break; + case 'c': case 'C': val = 12; break; + case 'b': case 'B': val = 11; break; + case 'a': case 'A': val = 10; break; + case '9': val = 9; break; + case '8': val = 8; break; + case '7': val = 7; break; + case '6': val = 6; break; + case '5': val = 5; break; + case '4': val = 4; break; + case '3': val = 3; break; + case '2': val = 2; break; + case '1': val = 1; break; + case '0': val = 0; break; + default: return -EINVAL; + // clang-format on } if (even) { @@ -478,7 +479,7 @@ status_t NormalizeHex(const std::string& in, std::string& out) { uint64_t GetFreeBytes(const std::string& path) { struct statvfs sb; if (statvfs(path.c_str(), &sb) == 0) { - return (uint64_t) sb.f_bavail * sb.f_frsize; + return (uint64_t)sb.f_bavail * sb.f_frsize; } else { return -1; } @@ -486,7 +487,7 @@ uint64_t GetFreeBytes(const std::string& path) { // TODO: borrowed from frameworks/native/libs/diskusage/ which should // eventually be migrated into system/ -static int64_t stat_size(struct stat *s) { +static int64_t stat_size(struct stat* s) { int64_t blksize = s->st_blksize; // count actual blocks used instead of nominal file size int64_t size = s->st_blocks * 512; @@ -504,8 +505,8 @@ static int64_t stat_size(struct stat *s) { int64_t calculate_dir_size(int dfd) { int64_t size = 0; struct stat s; - DIR *d; - struct dirent *de; + DIR* d; + struct dirent* de; d = fdopendir(dfd); if (d == NULL) { @@ -514,7 +515,7 @@ int64_t calculate_dir_size(int dfd) { } while ((de = readdir(d))) { - const char *name = de->d_name; + const char* name = de->d_name; if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) { size += stat_size(&s); } @@ -523,10 +524,8 @@ int64_t calculate_dir_size(int dfd) { /* always skip "." and ".." */ if (name[0] == '.') { - if (name[1] == 0) - continue; - if ((name[1] == '.') && (name[2] == 0)) - continue; + if (name[1] == 0) continue; + if ((name[1] == '.') && (name[2] == 0)) continue; } subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC); @@ -576,7 +575,7 @@ status_t WipeBlockDevice(const std::string& path) { } range[0] = 0; - range[1] = (unsigned long long) nr_sec * 512; + range[1] = (unsigned long long)nr_sec * 512; LOG(INFO) << "About to discard " << range[1] << " on " << path; if (ioctl(fd, BLKDISCARD, &range) == 0) { @@ -592,8 +591,7 @@ done: } static bool isValidFilename(const std::string& name) { - if (name.empty() || (name == ".") || (name == "..") - || (name.find('/') != std::string::npos)) { + if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) { return false; } else { return true; @@ -713,8 +711,7 @@ bool Readlinkat(int dirfd, const std::string& path, std::string* result) { while (true) { ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size()); // Unrecoverable error? - if (size == -1) - return false; + if (size == -1) return false; // It fit! (If size == buf.size(), it may have been truncated.) if (static_cast(size) < buf.size()) { result->assign(&buf[0], size); diff --git a/Utils.h b/Utils.h index 5caa4e9..09ce8fa 100644 --- a/Utils.h +++ b/Utils.h @@ -20,12 +20,12 @@ #include "KeyBuffer.h" #include -#include #include #include +#include -#include #include +#include struct DIR; @@ -59,21 +59,20 @@ status_t BindMount(const std::string& source, const std::string& target); bool FindValue(const std::string& raw, const std::string& key, std::string* value); /* Reads filesystem metadata from device at path */ -status_t ReadMetadata(const std::string& path, std::string* fsType, - std::string* fsUuid, std::string* fsLabel); +status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid, + std::string* fsLabel); /* Reads filesystem metadata from untrusted device at path */ -status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, - std::string* fsUuid, std::string* fsLabel); +status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid, + std::string* fsLabel); /* Returns either WEXITSTATUS() status, or a negative errno */ status_t ForkExecvp(const std::vector& args); status_t ForkExecvp(const std::vector& args, security_context_t context); -status_t ForkExecvp(const std::vector& args, - std::vector& output); -status_t ForkExecvp(const std::vector& args, - std::vector& output, security_context_t context); +status_t ForkExecvp(const std::vector& args, std::vector& output); +status_t ForkExecvp(const std::vector& args, std::vector& output, + security_context_t context); pid_t ForkExecvpAsync(const std::vector& args); diff --git a/VoldUtil.cpp b/VoldUtil.cpp index afe8b53..26c817c 100644 --- a/VoldUtil.cpp +++ b/VoldUtil.cpp @@ -14,13 +14,13 @@ * limitations under the License. */ -#include #include +#include -struct fstab *fstab_default; +struct fstab* fstab_default; void get_blkdev_size(int fd, unsigned long* nr_sec) { - if ((ioctl(fd, BLKGETSIZE, nr_sec)) == -1) { - *nr_sec = 0; - } + if ((ioctl(fd, BLKGETSIZE, nr_sec)) == -1) { + *nr_sec = 0; + } } diff --git a/VoldUtil.h b/VoldUtil.h index fd66672..4311586 100644 --- a/VoldUtil.h +++ b/VoldUtil.h @@ -20,7 +20,7 @@ #include #include -extern struct fstab *fstab_default; +extern struct fstab* fstab_default; #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) diff --git a/cryptfs.cpp b/cryptfs.cpp index c4274ed..00e5519 100644 --- a/cryptfs.cpp +++ b/cryptfs.cpp @@ -80,14 +80,12 @@ extern "C" { constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16; constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16; -constexpr size_t INTERMEDIATE_BUF_SIZE = - (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES); +constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES); // SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key. -static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, - "Mismatch of intermediate key sizes"); +static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes"); -#define KEY_IN_FOOTER "footer" +#define KEY_IN_FOOTER "footer" #define DEFAULT_PASSWORD "default_password" @@ -113,27 +111,25 @@ static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr); static unsigned char saved_master_key[MAX_KEY_LEN]; -static char *saved_mount_point; -static int master_key_saved = 0; -static struct crypt_persist_data *persist_data = NULL; +static char* saved_mount_point; +static int master_key_saved = 0; +static struct crypt_persist_data* persist_data = NULL; /* Should we use keymaster? */ -static int keymaster_check_compatibility() -{ +static int keymaster_check_compatibility() { return keymaster_compatibility_cryptfs_scrypt(); } /* Create a new keymaster key and store it in this footer */ -static int keymaster_create_key(struct crypt_mnt_ftr *ftr) -{ +static int keymaster_create_key(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); + 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 too large"); @@ -146,12 +142,9 @@ static int keymaster_create_key(struct crypt_mnt_ftr *ftr) } /* This signs the given object using the keymaster key. */ -static int keymaster_sign_object(struct crypt_mnt_ftr *ftr, - const unsigned char *object, - const size_t object_size, - unsigned char **signature, - size_t *signature_size) -{ +static int keymaster_sign_object(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); @@ -230,21 +223,20 @@ static char* password = 0; static int password_expiry_time = 0; static const int password_max_age_seconds = 60; -enum class RebootType {reboot, recovery, shutdown}; -static void cryptfs_reboot(RebootType rt) -{ - switch (rt) { - case RebootType::reboot: - property_set(ANDROID_RB_PROPERTY, "reboot"); - break; +enum class RebootType { reboot, recovery, shutdown }; +static void cryptfs_reboot(RebootType rt) { + switch (rt) { + case RebootType::reboot: + property_set(ANDROID_RB_PROPERTY, "reboot"); + break; - case RebootType::recovery: - property_set(ANDROID_RB_PROPERTY, "reboot,recovery"); - break; + case RebootType::recovery: + property_set(ANDROID_RB_PROPERTY, "reboot,recovery"); + break; - case RebootType::shutdown: - property_set(ANDROID_RB_PROPERTY, "shutdown"); - break; + case RebootType::shutdown: + property_set(ANDROID_RB_PROPERTY, "shutdown"); + break; } sleep(20); @@ -253,8 +245,7 @@ static void cryptfs_reboot(RebootType rt) return; } -static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags) -{ +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); @@ -272,7 +263,7 @@ namespace { struct CryptoType; // Use to get the CryptoType in use on this device. -const CryptoType &get_crypto_type(); +const CryptoType& get_crypto_type(); struct CryptoType { // We should only be constructing CryptoTypes as part of @@ -284,60 +275,60 @@ struct CryptoType { 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 { + 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 { + 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 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; + private: + const char* property_name; + const char* crypto_name; uint32_t keysize; - constexpr CryptoType(const char *property, const char *crypto, - uint32_t ksize) + 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(); + 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() { +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); + .set_property_name("AES-128-CBC") + .set_crypto_name("aes-cbc-essiv:sha256") + .set_keysize(16); constexpr CryptoType supported_crypto_types[] = { default_crypto_type, // 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 -constexpr size_t array_length(T (&)[N]) { return 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) { +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)); @@ -348,8 +339,8 @@ constexpr bool isValidCryptoType(const CryptoType &crypto_type) { // 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)); + (isValidCryptoType(supported_crypto_types[index]) && + validateSupportedCryptoTypes(index + 1)); } static_assert(validateSupportedCryptoTypes(0), @@ -357,34 +348,30 @@ static_assert(validateSupportedCryptoTypes(0), "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() { +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) { + 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()); + 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 * given device. */ -static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) { +static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) { char paramstr[PROPERTY_VALUE_MAX]; int Nf, rf, pf; @@ -402,17 +389,16 @@ uint32_t cryptfs_get_keysize() { return get_crypto_type().get_keysize(); } -const char *cryptfs_get_crypto_name() { +const char* cryptfs_get_crypto_name() { return get_crypto_type().get_crypto_name(); } -static unsigned int get_fs_size(char *dev) -{ +static unsigned int get_fs_size(char* dev) { int fd, block_size; struct ext4_super_block sb; off64_t len; - if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) { + if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) { SLOGE("Cannot open device to get filesystem size "); return 0; } @@ -435,68 +421,66 @@ static unsigned int get_fs_size(char *dev) } block_size = 1024 << sb.s_log_block_size; /* compute length in bytes */ - len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size; + len = (((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size; /* return length in sectors */ - return (unsigned int) (len / 512); + return (unsigned int)(len / 512); } -static int get_crypt_ftr_info(char **metadata_fname, off64_t *off) -{ - static int cached_data = 0; - static off64_t cached_off = 0; - static char cached_metadata_fname[PROPERTY_VALUE_MAX] = ""; - int fd; - char key_loc[PROPERTY_VALUE_MAX]; - char real_blkdev[PROPERTY_VALUE_MAX]; - int rc = -1; +static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) { + static int cached_data = 0; + static off64_t cached_off = 0; + static char cached_metadata_fname[PROPERTY_VALUE_MAX] = ""; + int fd; + char key_loc[PROPERTY_VALUE_MAX]; + char real_blkdev[PROPERTY_VALUE_MAX]; + int rc = -1; - if (!cached_data) { - fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc)); + if (!cached_data) { + fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc)); - if (!strcmp(key_loc, KEY_IN_FOOTER)) { - if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) { - SLOGE("Cannot open real block device %s\n", real_blkdev); - return -1; - } + if (!strcmp(key_loc, KEY_IN_FOOTER)) { + if ((fd = open(real_blkdev, O_RDWR | O_CLOEXEC)) < 0) { + SLOGE("Cannot open real block device %s\n", real_blkdev); + return -1; + } - unsigned long nr_sec = 0; - get_blkdev_size(fd, &nr_sec); - if (nr_sec != 0) { - /* If it's an encrypted Android partition, the last 16 Kbytes contain the - * encryption info footer and key, and plenty of bytes to spare for future - * growth. - */ - strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname)); - cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET; - cached_data = 1; - } else { - SLOGE("Cannot get size of block device %s\n", real_blkdev); - } - close(fd); - } else { - strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname)); - cached_off = 0; - cached_data = 1; + unsigned long nr_sec = 0; + get_blkdev_size(fd, &nr_sec); + if (nr_sec != 0) { + /* If it's an encrypted Android partition, the last 16 Kbytes contain the + * encryption info footer and key, and plenty of bytes to spare for future + * growth. + */ + strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname)); + cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET; + cached_data = 1; + } else { + SLOGE("Cannot get size of block device %s\n", real_blkdev); + } + close(fd); + } else { + strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname)); + cached_off = 0; + cached_data = 1; + } } - } - if (cached_data) { - if (metadata_fname) { - *metadata_fname = cached_metadata_fname; + if (cached_data) { + if (metadata_fname) { + *metadata_fname = cached_metadata_fname; + } + if (off) { + *off = cached_off; + } + rc = 0; } - if (off) { - *off = cached_off; - } - rc = 0; - } - return rc; + return rc; } /* Set sha256 checksum in structure */ -static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr) -{ +static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) { SHA256_CTX c; SHA256_Init(&c); memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256)); @@ -507,82 +491,76 @@ static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr) /* key or salt can be NULL, in which case just skip writing that value. Useful to * update the failed mount count but not change the key. */ -static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr) -{ - int fd; - unsigned int cnt; - /* starting_off is set to the SEEK_SET offset - * where the crypto structure starts - */ - off64_t starting_off; - int rc = -1; - char *fname = NULL; - struct stat statbuf; +static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) { + int fd; + unsigned int cnt; + /* starting_off is set to the SEEK_SET offset + * where the crypto structure starts + */ + off64_t starting_off; + int rc = -1; + char* fname = NULL; + struct stat statbuf; - set_ftr_sha(crypt_ftr); + set_ftr_sha(crypt_ftr); - if (get_crypt_ftr_info(&fname, &starting_off)) { - SLOGE("Unable to get crypt_ftr_info\n"); - return -1; - } - if (fname[0] != '/') { - SLOGE("Unexpected value for crypto key location\n"); - return -1; - } - if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) { - SLOGE("Cannot open footer file %s for put\n", fname); - return -1; - } - - /* Seek to the start of the crypt footer */ - if (lseek64(fd, starting_off, SEEK_SET) == -1) { - SLOGE("Cannot seek to real block device footer\n"); - goto errout; - } - - if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) { - SLOGE("Cannot write real block device footer\n"); - goto errout; - } - - fstat(fd, &statbuf); - /* If the keys are kept on a raw block device, do not try to truncate it. */ - if (S_ISREG(statbuf.st_mode)) { - if (ftruncate(fd, 0x4000)) { - SLOGE("Cannot set footer file size\n"); - goto errout; + if (get_crypt_ftr_info(&fname, &starting_off)) { + SLOGE("Unable to get crypt_ftr_info\n"); + return -1; + } + if (fname[0] != '/') { + SLOGE("Unexpected value for crypto key location\n"); + return -1; + } + if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) { + SLOGE("Cannot open footer file %s for put\n", fname); + return -1; } - } - /* Success! */ - rc = 0; + /* Seek to the start of the crypt footer */ + if (lseek64(fd, starting_off, SEEK_SET) == -1) { + SLOGE("Cannot seek to real block device footer\n"); + goto errout; + } + + if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) { + SLOGE("Cannot write real block device footer\n"); + goto errout; + } + + fstat(fd, &statbuf); + /* If the keys are kept on a raw block device, do not try to truncate it. */ + if (S_ISREG(statbuf.st_mode)) { + if (ftruncate(fd, 0x4000)) { + SLOGE("Cannot set footer file size\n"); + goto errout; + } + } + + /* Success! */ + rc = 0; errout: - close(fd); - return rc; - + close(fd); + return rc; } -static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr) -{ +static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) { struct crypt_mnt_ftr copy; memcpy(©, crypt_ftr, sizeof(copy)); set_ftr_sha(©); return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0; } -static inline int unix_read(int fd, void* buff, int len) -{ +static inline int unix_read(int fd, void* buff, int len) { return TEMP_FAILURE_RETRY(read(fd, buff, len)); } -static inline int unix_write(int fd, const void* buff, int len) -{ +static inline int unix_write(int fd, const void* buff, int len) { return TEMP_FAILURE_RETRY(write(fd, buff, len)); } -static void init_empty_persist_data(struct crypt_persist_data *pdata, int len) -{ +static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) { memset(pdata, 0, len); pdata->persist_magic = PERSIST_DATA_MAGIC; pdata->persist_valid_entries = 0; @@ -593,18 +571,17 @@ static void init_empty_persist_data(struct crypt_persist_data *pdata, int len) * data, crypt_ftr is a pointer to the struct to be updated, and offset is the * absolute offset to the start of the crypt_mnt_ftr on the passed in fd. */ -static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset) -{ +static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) { int orig_major = crypt_ftr->major_version; int orig_minor = crypt_ftr->minor_version; if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) { - struct crypt_persist_data *pdata; + struct crypt_persist_data* pdata; off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET; SLOGW("upgrading crypto footer to 1.1"); - pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE); + pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE); if (pdata == NULL) { SLOGE("Cannot allocate persisent data\n"); return; @@ -657,91 +634,89 @@ static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t o } } +static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) { + int fd; + unsigned int cnt; + off64_t starting_off; + int rc = -1; + char* fname = NULL; + struct stat statbuf; -static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr) -{ - int fd; - unsigned int cnt; - off64_t starting_off; - int rc = -1; - char *fname = NULL; - struct stat statbuf; + if (get_crypt_ftr_info(&fname, &starting_off)) { + SLOGE("Unable to get crypt_ftr_info\n"); + return -1; + } + if (fname[0] != '/') { + SLOGE("Unexpected value for crypto key location\n"); + return -1; + } + if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) { + SLOGE("Cannot open footer file %s for get\n", fname); + return -1; + } - if (get_crypt_ftr_info(&fname, &starting_off)) { - SLOGE("Unable to get crypt_ftr_info\n"); - return -1; - } - if (fname[0] != '/') { - SLOGE("Unexpected value for crypto key location\n"); - return -1; - } - if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) { - SLOGE("Cannot open footer file %s for get\n", fname); - return -1; - } + /* Make sure it's 16 Kbytes in length */ + fstat(fd, &statbuf); + if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) { + SLOGE("footer file %s is not the expected size!\n", fname); + goto errout; + } - /* Make sure it's 16 Kbytes in length */ - fstat(fd, &statbuf); - if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) { - SLOGE("footer file %s is not the expected size!\n", fname); - goto errout; - } + /* Seek to the start of the crypt footer */ + if (lseek64(fd, starting_off, SEEK_SET) == -1) { + SLOGE("Cannot seek to real block device footer\n"); + goto errout; + } - /* Seek to the start of the crypt footer */ - if (lseek64(fd, starting_off, SEEK_SET) == -1) { - SLOGE("Cannot seek to real block device footer\n"); - goto errout; - } + if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) { + SLOGE("Cannot read real block device footer\n"); + goto errout; + } - if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) { - SLOGE("Cannot read real block device footer\n"); - goto errout; - } + if (crypt_ftr->magic != CRYPT_MNT_MAGIC) { + SLOGE("Bad magic for real block device %s\n", fname); + goto errout; + } - if (crypt_ftr->magic != CRYPT_MNT_MAGIC) { - SLOGE("Bad magic for real block device %s\n", fname); - goto errout; - } + if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) { + SLOGE("Cannot understand major version %d real block device footer; expected %d\n", + crypt_ftr->major_version, CURRENT_MAJOR_VERSION); + goto errout; + } - if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) { - SLOGE("Cannot understand major version %d real block device footer; expected %d\n", - crypt_ftr->major_version, CURRENT_MAJOR_VERSION); - goto errout; - } + // We risk buffer overflows with oversized keys, so we just reject them. + // 0-sized keys are problematic (essentially by-passing encryption), and + // AES-CBC key wrapping only works for multiples of 16 bytes. + if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) || + (crypt_ftr->keysize > MAX_KEY_LEN)) { + SLOGE( + "Invalid keysize (%u) for block device %s; Must be non-zero, " + "divisible by 16, and <= %d\n", + crypt_ftr->keysize, fname, MAX_KEY_LEN); + goto errout; + } - // We risk buffer overflows with oversized keys, so we just reject them. - // 0-sized keys are problematic (essentially by-passing encryption), and - // AES-CBC key wrapping only works for multiples of 16 bytes. - if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) || - (crypt_ftr->keysize > MAX_KEY_LEN)) { - SLOGE("Invalid keysize (%u) for block device %s; Must be non-zero, " - "divisible by 16, and <= %d\n", crypt_ftr->keysize, fname, - MAX_KEY_LEN); - goto errout; - } + if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) { + SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n", + crypt_ftr->minor_version, CURRENT_MINOR_VERSION); + } - if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) { - SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n", - crypt_ftr->minor_version, CURRENT_MINOR_VERSION); - } + /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the + * copy on disk before returning. + */ + if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) { + upgrade_crypt_ftr(fd, crypt_ftr, starting_off); + } - /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the - * copy on disk before returning. - */ - if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) { - upgrade_crypt_ftr(fd, crypt_ftr, starting_off); - } - - /* Success! */ - rc = 0; + /* Success! */ + rc = 0; errout: - close(fd); - return rc; + close(fd); + return rc; } -static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr) -{ +static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) { if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size > crypt_ftr->persist_data_offset[1]) { SLOGE("Crypt_ftr persist data regions overlap"); @@ -754,7 +729,7 @@ static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr) } if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) - - (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) > + (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) > CRYPT_FOOTER_OFFSET) { SLOGE("Persistent data extends past crypto footer"); return -1; @@ -763,12 +738,11 @@ static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr) return 0; } -static int load_persistent_data(void) -{ +static int load_persistent_data(void) { struct crypt_mnt_ftr crypt_ftr; - struct crypt_persist_data *pdata = NULL; + struct crypt_persist_data* pdata = NULL; char encrypted_state[PROPERTY_VALUE_MAX]; - char *fname; + char* fname; int found = 0; int fd; int ret; @@ -779,10 +753,9 @@ static int load_persistent_data(void) return 0; } - /* If not encrypted, just allocate an empty table and initialize it */ property_get("ro.crypto.state", encrypted_state, ""); - if (strcmp(encrypted_state, "encrypted") ) { + if (strcmp(encrypted_state, "encrypted")) { pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE); if (pdata) { init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE); @@ -792,12 +765,12 @@ static int load_persistent_data(void) return -1; } - if(get_crypt_ftr_and_key(&crypt_ftr)) { + if (get_crypt_ftr_and_key(&crypt_ftr)) { return -1; } - if ((crypt_ftr.major_version < 1) - || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) { + if ((crypt_ftr.major_version < 1) || + (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) { SLOGE("Crypt_ftr version doesn't support persistent data"); return -1; } @@ -811,7 +784,7 @@ static int load_persistent_data(void) return -1; } - fd = open(fname, O_RDONLY|O_CLOEXEC); + fd = open(fname, O_RDONLY | O_CLOEXEC); if (fd < 0) { SLOGE("Cannot open %s metadata file", fname); return -1; @@ -828,7 +801,7 @@ static int load_persistent_data(void) SLOGE("Cannot seek to read persistent data on %s", fname); goto err2; } - if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){ + if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) { SLOGE("Error reading persistent data on iteration %d", i); goto err2; } @@ -856,11 +829,10 @@ err: return -1; } -static int save_persistent_data(void) -{ +static int save_persistent_data(void) { struct crypt_mnt_ftr crypt_ftr; - struct crypt_persist_data *pdata; - char *fname; + struct crypt_persist_data* pdata; + char* fname; off64_t write_offset; off64_t erase_offset; int fd; @@ -871,12 +843,12 @@ static int save_persistent_data(void) return -1; } - if(get_crypt_ftr_and_key(&crypt_ftr)) { + if (get_crypt_ftr_and_key(&crypt_ftr)) { return -1; } - if ((crypt_ftr.major_version < 1) - || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) { + if ((crypt_ftr.major_version < 1) || + (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) { SLOGE("Crypt_ftr version doesn't support persistent data"); return -1; } @@ -890,7 +862,7 @@ static int save_persistent_data(void) return -1; } - fd = open(fname, O_RDWR|O_CLOEXEC); + fd = open(fname, O_RDWR | O_CLOEXEC); if (fd < 0) { SLOGE("Cannot open %s metadata file", fname); return -1; @@ -908,20 +880,20 @@ static int save_persistent_data(void) } if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) { - SLOGE("Error reading persistent data before save"); - goto err2; + SLOGE("Error reading persistent data before save"); + goto err2; } if (pdata->persist_magic == PERSIST_DATA_MAGIC) { /* The first copy is the curent valid copy, so write to * the second copy and erase this one */ - write_offset = crypt_ftr.persist_data_offset[1]; - erase_offset = crypt_ftr.persist_data_offset[0]; + write_offset = crypt_ftr.persist_data_offset[1]; + erase_offset = crypt_ftr.persist_data_offset[0]; } else { /* The second copy must be the valid copy, so write to * the first copy, and erase the second */ - write_offset = crypt_ftr.persist_data_offset[0]; - erase_offset = crypt_ftr.persist_data_offset[1]; + write_offset = crypt_ftr.persist_data_offset[0]; + erase_offset = crypt_ftr.persist_data_offset[1]; } /* Write the new copy first, if successful, then erase the old copy */ @@ -930,15 +902,14 @@ static int save_persistent_data(void) goto err2; } if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) == - (int) crypt_ftr.persist_data_size) { + (int)crypt_ftr.persist_data_size) { if (lseek64(fd, erase_offset, SEEK_SET) < 0) { SLOGE("Cannot seek to erase previous persistent data"); goto err2; } fsync(fd); memset(pdata, 0, crypt_ftr.persist_data_size); - if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != - (int) crypt_ftr.persist_data_size) { + if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) { SLOGE("Cannot write to erase previous persistent data"); goto err2; } @@ -963,85 +934,82 @@ err: /* Convert a binary key of specified length into an ascii hex string equivalent, * without the leading 0x and with null termination */ -static void convert_key_to_hex_ascii(const unsigned char *master_key, - unsigned int keysize, char *master_key_ascii) { +static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize, + char* master_key_ascii) { unsigned int i, a; unsigned char nibble; - for (i=0, a=0; i> 4) & 0xf; master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30); nibble = master_key[i] & 0xf; - master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30); + master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30); } /* Add the null termination */ 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; +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; + io = (struct dm_ioctl*)buffer; - /* Load the mapping table for this device */ - tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)]; + /* 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); + 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); + 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("Extra parameters for dm_crypt: %s\n", 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; + buff_offset = crypt_params - buffer; + SLOGI("Extra parameters for dm_crypt: %s\n", 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; + for (i = 0; i < TABLE_LOAD_RETRIES; i++) { + if (!ioctl(fd, DM_TABLE_LOAD, io)) { + break; + } + usleep(500000); } - usleep(500000); - } - if (i == TABLE_LOAD_RETRIES) { - /* We failed to load the table, return an error */ - return -1; - } else { - return i + 1; - } + 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) -{ +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; + struct dm_ioctl* io; + struct dm_target_versions* v; - io = (struct dm_ioctl *) buffer; + io = (struct dm_ioctl*)buffer; ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0); @@ -1052,16 +1020,16 @@ static int get_dm_crypt_version(int fd, const char *name, int *version) /* 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)]; + v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)]; while (v->next) { - if (! strcmp(v->name, "crypt")) { + 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); + v = (struct dm_target_versions*)(((char*)v) + v->next); } return -1; @@ -1143,87 +1111,78 @@ static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned retval = 0; errout: - close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */ + close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */ - return retval; + return retval; } -static int delete_crypto_blk_dev(const char *name) -{ - int fd; - char buffer[DM_CRYPT_BUF_SIZE]; - struct dm_ioctl *io; - int retval = -1; +static int delete_crypto_blk_dev(const char* name) { + int fd; + char buffer[DM_CRYPT_BUF_SIZE]; + struct dm_ioctl* io; + int retval = -1; - if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) { - SLOGE("Cannot open device-mapper\n"); - goto errout; - } + if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) { + SLOGE("Cannot open device-mapper\n"); + goto errout; + } - io = (struct dm_ioctl *) buffer; + io = (struct dm_ioctl*)buffer; - ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0); - if (ioctl(fd, DM_DEV_REMOVE, io)) { - SLOGE("Cannot remove dm-crypt device\n"); - goto errout; - } + ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0); + if (ioctl(fd, DM_DEV_REMOVE, io)) { + SLOGE("Cannot remove dm-crypt device\n"); + goto errout; + } - /* We made it here with no errors. Woot! */ - retval = 0; + /* 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; + close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */ + return retval; } -static int pbkdf2(const char *passwd, const unsigned char *salt, - unsigned char *ikey, void *params UNUSED) -{ +static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey, + void* params UNUSED) { SLOGI("Using pbkdf2 for cryptfs KDF"); /* Turn the password into a key and IV that can decrypt the master key */ - return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, - HASH_COUNT, INTERMEDIATE_BUF_SIZE, - ikey) != 1; + return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT, + INTERMEDIATE_BUF_SIZE, ikey) != 1; } -static int scrypt(const char *passwd, const unsigned char *salt, - unsigned char *ikey, void *params) -{ +static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) { SLOGI("Using scrypt for cryptfs KDF"); - struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params; + struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params; int N = 1 << ftr->N_factor; int r = 1 << ftr->r_factor; int p = 1 << ftr->p_factor; /* Turn the password into a key and IV that can decrypt the master key */ - crypto_scrypt((const uint8_t*)passwd, strlen(passwd), - salt, SALT_LEN, N, r, p, ikey, + crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey, INTERMEDIATE_BUF_SIZE); - return 0; + return 0; } -static int scrypt_keymaster(const char *passwd, const unsigned char *salt, - unsigned char *ikey, void *params) -{ +static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey, + void* params) { SLOGI("Using scrypt with keymaster for cryptfs KDF"); int rc; size_t signature_size; unsigned char* signature; - struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params; + struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params; int N = 1 << ftr->N_factor; int r = 1 << ftr->r_factor; int p = 1 << ftr->p_factor; - rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), - salt, SALT_LEN, N, r, p, ikey, + rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey, INTERMEDIATE_BUF_SIZE); if (rc) { @@ -1231,14 +1190,13 @@ static int scrypt_keymaster(const char *passwd, const unsigned char *salt, return -1; } - if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, - &signature, &signature_size)) { + if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) { SLOGE("Signing failed"); return -1; } - rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, - N, r, p, ikey, INTERMEDIATE_BUF_SIZE); + rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey, + INTERMEDIATE_BUF_SIZE); free(signature); if (rc) { @@ -1249,12 +1207,10 @@ static int scrypt_keymaster(const char *passwd, const unsigned char *salt, return 0; } -static int encrypt_master_key(const char *passwd, const unsigned char *salt, - const unsigned char *decrypted_master_key, - unsigned char *encrypted_master_key, - struct crypt_mnt_ftr *crypt_ftr) -{ - unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 }; +static int encrypt_master_key(const char* passwd, const unsigned char* salt, + const unsigned char* decrypted_master_key, + unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) { + unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0}; EVP_CIPHER_CTX e_ctx; int encrypted_len, final_len; int rc = 0; @@ -1263,46 +1219,46 @@ static int encrypt_master_key(const char *passwd, const unsigned char *salt, get_device_scrypt_params(crypt_ftr); switch (crypt_ftr->kdf_type) { - case KDF_SCRYPT_KEYMASTER: - if (keymaster_create_key(crypt_ftr)) { - SLOGE("keymaster_create_key failed"); - return -1; - } + case KDF_SCRYPT_KEYMASTER: + if (keymaster_create_key(crypt_ftr)) { + SLOGE("keymaster_create_key failed"); + return -1; + } - if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) { - SLOGE("scrypt failed"); - return -1; - } - break; + if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) { + SLOGE("scrypt failed"); + return -1; + } + break; - case KDF_SCRYPT: - if (scrypt(passwd, salt, ikey, crypt_ftr)) { - SLOGE("scrypt failed"); - return -1; - } - break; + case KDF_SCRYPT: + if (scrypt(passwd, salt, ikey, crypt_ftr)) { + SLOGE("scrypt failed"); + return -1; + } + break; - default: - SLOGE("Invalid kdf_type"); - return -1; + default: + SLOGE("Invalid kdf_type"); + return -1; } /* Initialize the decryption engine */ EVP_CIPHER_CTX_init(&e_ctx); - if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, - ikey+INTERMEDIATE_KEY_LEN_BYTES)) { + if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey, + ikey + INTERMEDIATE_KEY_LEN_BYTES)) { SLOGE("EVP_EncryptInit failed\n"); return -1; } EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */ /* Encrypt the master key */ - if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, - decrypted_master_key, crypt_ftr->keysize)) { + if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key, + crypt_ftr->keysize)) { SLOGE("EVP_EncryptUpdate failed\n"); return -1; } - if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) { + if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) { SLOGE("EVP_EncryptFinal failed\n"); return -1; } @@ -1321,13 +1277,12 @@ static int encrypt_master_key(const char *passwd, const unsigned char *salt, int r = 1 << crypt_ftr->r_factor; int p = 1 << crypt_ftr->p_factor; - rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, - crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p, - crypt_ftr->scrypted_intermediate_key, + rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt), + N, r, p, crypt_ftr->scrypted_intermediate_key, sizeof(crypt_ftr->scrypted_intermediate_key)); if (rc) { - SLOGE("encrypt_master_key: crypto_scrypt failed"); + SLOGE("encrypt_master_key: crypto_scrypt failed"); } EVP_CIPHER_CTX_cleanup(&e_ctx); @@ -1335,60 +1290,57 @@ static int encrypt_master_key(const char *passwd, const unsigned char *salt, return 0; } -static int decrypt_master_key_aux(const char *passwd, unsigned char *salt, - const unsigned char *encrypted_master_key, - size_t keysize, - unsigned char *decrypted_master_key, - kdf_func kdf, void *kdf_params, - unsigned char** intermediate_key, - size_t* intermediate_key_size) -{ - unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 }; - EVP_CIPHER_CTX d_ctx; - int decrypted_len, final_len; +static int decrypt_master_key_aux(const char* passwd, unsigned char* salt, + const unsigned char* encrypted_master_key, size_t keysize, + unsigned char* decrypted_master_key, kdf_func kdf, + void* kdf_params, unsigned char** intermediate_key, + size_t* intermediate_key_size) { + unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0}; + EVP_CIPHER_CTX d_ctx; + int decrypted_len, final_len; - /* Turn the password into an intermediate key and IV that can decrypt the - master key */ - if (kdf(passwd, salt, ikey, kdf_params)) { - SLOGE("kdf failed"); - return -1; - } - - /* Initialize the decryption engine */ - EVP_CIPHER_CTX_init(&d_ctx); - if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) { - return -1; - } - EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */ - /* Decrypt the master key */ - if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, - encrypted_master_key, keysize)) { - return -1; - } - if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) { - return -1; - } - - if (decrypted_len + final_len != static_cast(keysize)) { - return -1; - } - - /* Copy intermediate key if needed by params */ - if (intermediate_key && intermediate_key_size) { - *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES); - if (*intermediate_key) { - memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES); - *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES; + /* Turn the password into an intermediate key and IV that can decrypt the + master key */ + if (kdf(passwd, salt, ikey, kdf_params)) { + SLOGE("kdf failed"); + return -1; } - } - EVP_CIPHER_CTX_cleanup(&d_ctx); + /* Initialize the decryption engine */ + EVP_CIPHER_CTX_init(&d_ctx); + if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, + ikey + INTERMEDIATE_KEY_LEN_BYTES)) { + return -1; + } + EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */ + /* Decrypt the master key */ + if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key, + keysize)) { + return -1; + } + if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) { + return -1; + } - return 0; + if (decrypted_len + final_len != static_cast(keysize)) { + return -1; + } + + /* Copy intermediate key if needed by params */ + if (intermediate_key && intermediate_key_size) { + *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES); + if (*intermediate_key) { + memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES); + *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES; + } + } + + EVP_CIPHER_CTX_cleanup(&d_ctx); + + return 0; } -static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params) -{ +static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) { if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) { *kdf = scrypt_keymaster; *kdf_params = ftr; @@ -1401,20 +1353,17 @@ static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_pa } } -static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key, - struct crypt_mnt_ftr *crypt_ftr, - unsigned char** intermediate_key, - size_t* intermediate_key_size) -{ +static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key, + struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key, + size_t* intermediate_key_size) { kdf_func kdf; - void *kdf_params; + void* kdf_params; int ret; get_kdf_func(crypt_ftr, &kdf, &kdf_params); - ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, - crypt_ftr->keysize, - decrypted_master_key, kdf, kdf_params, - intermediate_key, intermediate_key_size); + ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize, + decrypted_master_key, kdf, kdf_params, intermediate_key, + intermediate_key_size); if (ret != 0) { SLOGW("failure decrypting master key"); } @@ -1422,13 +1371,13 @@ static int decrypt_master_key(const char *passwd, unsigned char *decrypted_maste return ret; } -static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt, - struct crypt_mnt_ftr *crypt_ftr) { +static int create_encrypted_random_key(const char* passwd, unsigned char* master_key, + unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) { int fd; unsigned char key_buf[MAX_KEY_LEN]; /* Get some random bits for a key */ - fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC); + fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); read(fd, key_buf, sizeof(key_buf)); read(fd, salt, SALT_LEN); close(fd); @@ -1437,13 +1386,12 @@ static int create_encrypted_random_key(const char *passwd, unsigned char *master return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr); } -int wait_and_unmount(const char *mountpoint, bool kill) -{ +int wait_and_unmount(const char* mountpoint, bool kill) { int i, err, rc; #define WAIT_UNMOUNT_COUNT 20 /* Now umount the tmpfs filesystem */ - for (i=0; i RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */ - SLOGI("Failed to mount %s because it is busy - waiting", - crypto_blkdev); + SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev); if (--retries) { sleep(RETRY_MOUNT_DELAY_SECONDS); } else { @@ -1671,8 +1610,7 @@ static int cryptfs_restart_internal(int restart_main) return rc; } -int cryptfs_restart(void) -{ +int cryptfs_restart(void) { SLOGI("cryptfs_restart"); if (e4crypt_is_native()) { SLOGE("cryptfs_restart not valid for file encryption:"); @@ -1683,193 +1621,189 @@ int cryptfs_restart(void) return cryptfs_restart_internal(1); } -static int do_crypto_complete(const char *mount_point) -{ - struct crypt_mnt_ftr crypt_ftr; - char encrypted_state[PROPERTY_VALUE_MAX]; - char key_loc[PROPERTY_VALUE_MAX]; +static int do_crypto_complete(const char* mount_point) { + struct crypt_mnt_ftr crypt_ftr; + char encrypted_state[PROPERTY_VALUE_MAX]; + char key_loc[PROPERTY_VALUE_MAX]; - property_get("ro.crypto.state", encrypted_state, ""); - if (strcmp(encrypted_state, "encrypted") ) { - SLOGE("not running with encryption, aborting"); - return CRYPTO_COMPLETE_NOT_ENCRYPTED; - } - - // crypto_complete is full disk encrypted status - if (e4crypt_is_native()) { - return CRYPTO_COMPLETE_NOT_ENCRYPTED; - } - - if (get_crypt_ftr_and_key(&crypt_ftr)) { - fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc)); - - /* - * Only report this error if key_loc is a file and it exists. - * If the device was never encrypted, and /data is not mountable for - * some reason, returning 1 should prevent the UI from presenting the - * a "enter password" screen, or worse, a "press button to wipe the - * device" screen. - */ - if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) { - SLOGE("master key file does not exist, aborting"); - return CRYPTO_COMPLETE_NOT_ENCRYPTED; - } else { - SLOGE("Error getting crypt footer and key\n"); - return CRYPTO_COMPLETE_BAD_METADATA; + property_get("ro.crypto.state", encrypted_state, ""); + if (strcmp(encrypted_state, "encrypted")) { + SLOGE("not running with encryption, aborting"); + return CRYPTO_COMPLETE_NOT_ENCRYPTED; } - } - // Test for possible error flags - if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){ - SLOGE("Encryption process is partway completed\n"); - return CRYPTO_COMPLETE_PARTIAL; - } + // crypto_complete is full disk encrypted status + if (e4crypt_is_native()) { + return CRYPTO_COMPLETE_NOT_ENCRYPTED; + } - if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){ - SLOGE("Encryption process was interrupted but cannot continue\n"); - return CRYPTO_COMPLETE_INCONSISTENT; - } + if (get_crypt_ftr_and_key(&crypt_ftr)) { + fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc)); - if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){ - SLOGE("Encryption is successful but data is corrupt\n"); - return CRYPTO_COMPLETE_CORRUPT; - } + /* + * Only report this error if key_loc is a file and it exists. + * If the device was never encrypted, and /data is not mountable for + * some reason, returning 1 should prevent the UI from presenting the + * a "enter password" screen, or worse, a "press button to wipe the + * device" screen. + */ + if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) { + SLOGE("master key file does not exist, aborting"); + return CRYPTO_COMPLETE_NOT_ENCRYPTED; + } else { + SLOGE("Error getting crypt footer and key\n"); + return CRYPTO_COMPLETE_BAD_METADATA; + } + } - /* We passed the test! We shall diminish, and return to the west */ - return CRYPTO_COMPLETE_ENCRYPTED; + // Test for possible error flags + if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) { + SLOGE("Encryption process is partway completed\n"); + return CRYPTO_COMPLETE_PARTIAL; + } + + if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) { + SLOGE("Encryption process was interrupted but cannot continue\n"); + return CRYPTO_COMPLETE_INCONSISTENT; + } + + if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) { + SLOGE("Encryption is successful but data is corrupt\n"); + return CRYPTO_COMPLETE_CORRUPT; + } + + /* We passed the test! We shall diminish, and return to the west */ + return CRYPTO_COMPLETE_ENCRYPTED; } -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]; - char real_blkdev[MAXPATHLEN]; - char tmp_mount_point[64]; - unsigned int orig_failed_decrypt_count; - int rc; - int use_keymaster = 0; - int upgrade = 0; - unsigned char* intermediate_key = 0; - size_t intermediate_key_size = 0; - int N = 1 << crypt_ftr->N_factor; - int r = 1 << crypt_ftr->r_factor; - int p = 1 << crypt_ftr->p_factor; +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]; + char real_blkdev[MAXPATHLEN]; + char tmp_mount_point[64]; + unsigned int orig_failed_decrypt_count; + int rc; + int use_keymaster = 0; + int upgrade = 0; + unsigned char* intermediate_key = 0; + size_t intermediate_key_size = 0; + int N = 1 << crypt_ftr->N_factor; + int r = 1 << crypt_ftr->r_factor; + int p = 1 << crypt_ftr->p_factor; - SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size); - orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count; + SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size); + orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count; - if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) { - if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, - &intermediate_key, &intermediate_key_size)) { - SLOGE("Failed to decrypt master key\n"); - rc = -1; - goto errout; + if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) { + if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key, + &intermediate_key_size)) { + SLOGE("Failed to decrypt master key\n"); + rc = -1; + goto errout; + } } - } - fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev)); + fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev)); - // Create crypto block device - all (non fatal) code paths - // need it - if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) { - SLOGE("Error creating decrypted block device\n"); - rc = -1; - goto errout; - } + // Create crypto block device - all (non fatal) code paths + // need it + if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, + 0)) { + SLOGE("Error creating decrypted block device\n"); + rc = -1; + goto errout; + } - /* Work out if the problem is the password or the data */ - unsigned char scrypted_intermediate_key[sizeof(crypt_ftr-> - scrypted_intermediate_key)]; + /* Work out if the problem is the password or the data */ + unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)]; - rc = crypto_scrypt(intermediate_key, intermediate_key_size, - crypt_ftr->salt, sizeof(crypt_ftr->salt), - N, r, p, scrypted_intermediate_key, - sizeof(scrypted_intermediate_key)); + rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt, + sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key, + sizeof(scrypted_intermediate_key)); - // Does the key match the crypto footer? - if (rc == 0 && memcmp(scrypted_intermediate_key, - crypt_ftr->scrypted_intermediate_key, - sizeof(scrypted_intermediate_key)) == 0) { - SLOGI("Password matches"); - rc = 0; - } else { - /* Try mounting the file system anyway, just in case the problem's with - * 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)) { - SLOGE("Error temp mounting decrypted block device\n"); - delete_crypto_blk_dev(label); - - rc = ++crypt_ftr->failed_decrypt_count; - put_crypt_ftr_and_key(crypt_ftr); + // Does the key match the crypto footer? + if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key, + sizeof(scrypted_intermediate_key)) == 0) { + SLOGI("Password matches"); + rc = 0; } else { - /* Success! */ - SLOGI("Password did not match but decrypted drive mounted - continue"); - umount(tmp_mount_point); - rc = 0; - } - } + /* Try mounting the file system anyway, just in case the problem's with + * 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)) { + SLOGE("Error temp mounting decrypted block device\n"); + delete_crypto_blk_dev(label); - if (rc == 0) { - crypt_ftr->failed_decrypt_count = 0; - if (orig_failed_decrypt_count != 0) { - put_crypt_ftr_and_key(crypt_ftr); - } - - /* 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); - - /* Also save a the master key so we can reencrypted the key - * the key when we want to change the password on it. */ - memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize); - saved_mount_point = strdup(mount_point); - master_key_saved = 1; - SLOGD("%s(): Master key saved\n", __FUNCTION__); - rc = 0; - - // Upgrade if we're not using the latest KDF. - use_keymaster = keymaster_check_compatibility(); - if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) { - // Don't allow downgrade - } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) { - crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER; - upgrade = 1; - } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) { - crypt_ftr->kdf_type = KDF_SCRYPT; - upgrade = 1; - } - - if (upgrade) { - rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key, - crypt_ftr->master_key, crypt_ftr); - if (!rc) { - rc = put_crypt_ftr_and_key(crypt_ftr); - } - SLOGD("Key Derivation Function upgrade: rc=%d\n", rc); - - // Do not fail even if upgrade failed - machine is bootable - // Note that if this code is ever hit, there is a *serious* problem - // since KDFs should never fail. You *must* fix the kdf before - // proceeding! - if (rc) { - SLOGW("Upgrade failed with error %d," - " but continuing with previous state", - rc); - rc = 0; + rc = ++crypt_ftr->failed_decrypt_count; + put_crypt_ftr_and_key(crypt_ftr); + } else { + /* Success! */ + SLOGI("Password did not match but decrypted drive mounted - continue"); + umount(tmp_mount_point); + rc = 0; } } - } - errout: - if (intermediate_key) { - memset(intermediate_key, 0, intermediate_key_size); - free(intermediate_key); - } - return rc; + if (rc == 0) { + crypt_ftr->failed_decrypt_count = 0; + if (orig_failed_decrypt_count != 0) { + put_crypt_ftr_and_key(crypt_ftr); + } + + /* 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); + + /* Also save a the master key so we can reencrypted the key + * the key when we want to change the password on it. */ + memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize); + saved_mount_point = strdup(mount_point); + master_key_saved = 1; + SLOGD("%s(): Master key saved\n", __FUNCTION__); + rc = 0; + + // Upgrade if we're not using the latest KDF. + use_keymaster = keymaster_check_compatibility(); + if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) { + // Don't allow downgrade + } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) { + crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER; + upgrade = 1; + } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) { + crypt_ftr->kdf_type = KDF_SCRYPT; + upgrade = 1; + } + + if (upgrade) { + rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key, + crypt_ftr->master_key, crypt_ftr); + if (!rc) { + rc = put_crypt_ftr_and_key(crypt_ftr); + } + SLOGD("Key Derivation Function upgrade: rc=%d\n", rc); + + // Do not fail even if upgrade failed - machine is bootable + // Note that if this code is ever hit, there is a *serious* problem + // since KDFs should never fail. You *must* fix the kdf before + // proceeding! + if (rc) { + SLOGW( + "Upgrade failed with error %d," + " but continuing with previous state", + rc); + rc = 0; + } + } + } + +errout: + if (intermediate_key) { + memset(intermediate_key, 0, intermediate_key_size); + free(intermediate_key); + } + return rc; } /* @@ -1880,9 +1814,9 @@ static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, * * 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 fd = open(real_blkdev, O_RDONLY|O_CLOEXEC); +int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key, + char* out_crypto_blkdev) { + int fd = open(real_blkdev, O_RDONLY | O_CLOEXEC); if (fd == -1) { SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno)); return -1; @@ -1901,7 +1835,7 @@ int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, 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(), + strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(), MAX_CRYPTO_TYPE_NAME_LEN); uint32_t flags = 0; if (e4crypt_is_native() && @@ -1916,21 +1850,20 @@ int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, * storage volume. */ int cryptfs_revert_ext_volume(const char* label) { - return delete_crypto_blk_dev((char*) label); + return delete_crypto_blk_dev((char*)label); } -int cryptfs_crypto_complete(void) -{ - return do_crypto_complete("/data"); +int cryptfs_crypto_complete(void) { + return do_crypto_complete("/data"); } -int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) -{ +int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) { char encrypted_state[PROPERTY_VALUE_MAX]; property_get("ro.crypto.state", encrypted_state, ""); - if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) { - SLOGE("encrypted fs already validated or not running with encryption," - " aborting"); + if (master_key_saved || strcmp(encrypted_state, "encrypted")) { + SLOGE( + "encrypted fs already validated or not running with encryption," + " aborting"); return -1; } @@ -1942,8 +1875,7 @@ int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) return 0; } -int cryptfs_check_passwd(const char *passwd) -{ +int cryptfs_check_passwd(const char* passwd) { SLOGI("cryptfs_check_passwd"); if (e4crypt_is_native()) { SLOGE("cryptfs_check_passwd not valid for file encryption"); @@ -1959,8 +1891,7 @@ int cryptfs_check_passwd(const char *passwd) return rc; } - rc = test_mount_encrypted_fs(&crypt_ftr, passwd, - DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE); + rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE); if (rc) { SLOGE("Password did not match"); return rc; @@ -1972,8 +1903,8 @@ int cryptfs_check_passwd(const char *passwd) // First, we must delete the crypto block device that // test_mount_encrypted_fs leaves behind as a side effect delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE); - rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, - DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE); + rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT, + CRYPTO_BLOCK_DEVICE); if (rc) { SLOGE("Default password did not match on reboot encryption"); return rc; @@ -1999,15 +1930,14 @@ int cryptfs_check_passwd(const char *passwd) return rc; } -int cryptfs_verify_passwd(const char *passwd) -{ +int cryptfs_verify_passwd(const char* passwd) { struct crypt_mnt_ftr crypt_ftr; unsigned char decrypted_master_key[MAX_KEY_LEN]; char encrypted_state[PROPERTY_VALUE_MAX]; int rc; property_get("ro.crypto.state", encrypted_state, ""); - if (strcmp(encrypted_state, "encrypted") ) { + if (strcmp(encrypted_state, "encrypted")) { SLOGE("device not encrypted, aborting"); return -2; } @@ -2050,8 +1980,7 @@ int cryptfs_verify_passwd(const char *passwd) * Presumably, at a minimum, the caller will update the * filesystem size and crypto_type_name after calling this function. */ -static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr) -{ +static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) { off64_t off; memset(ftr, 0, sizeof(struct crypt_mnt_ftr)); @@ -2062,17 +1991,17 @@ static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr) ftr->keysize = cryptfs_get_keysize(); switch (keymaster_check_compatibility()) { - case 1: - ftr->kdf_type = KDF_SCRYPT_KEYMASTER; - break; + case 1: + ftr->kdf_type = KDF_SCRYPT_KEYMASTER; + break; - case 0: - ftr->kdf_type = KDF_SCRYPT; - break; + case 0: + ftr->kdf_type = KDF_SCRYPT; + break; - default: - SLOGE("keymaster_check_compatibility failed"); - return -1; + default: + SLOGE("keymaster_check_compatibility failed"); + return -1; } get_device_scrypt_params(ftr); @@ -2080,8 +2009,7 @@ static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr) ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE; if (get_crypt_ftr_info(NULL, &off) == 0) { ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET; - ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + - ftr->persist_data_size; + ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size; } return 0; @@ -2089,9 +2017,8 @@ static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr) #define FRAMEWORK_BOOT_WAIT 60 -static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) -{ - int fd = open(filename, O_RDONLY|O_CLOEXEC); +static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) { + int fd = open(filename, O_RDONLY | O_CLOEXEC); if (fd == -1) { SLOGE("Error opening file %s", filename); return -1; @@ -2117,7 +2044,7 @@ static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev, char* real_blkdev, int previously_encrypted_upto) { - off64_t cur_encryption_done=0, tot_encryption_size=0; + off64_t cur_encryption_done = 0, tot_encryption_size = 0; int rc = -1; /* The size of the userdata partition, and add in the vold volumes below */ @@ -2153,11 +2080,11 @@ static int vold_unmountAll(void) { int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN]; unsigned char decrypted_master_key[MAX_KEY_LEN]; - int rc=-1, i; + int rc = -1, i; struct crypt_mnt_ftr crypt_ftr; - struct crypt_persist_data *pdata; + struct crypt_persist_data* pdata; char encrypted_state[PROPERTY_VALUE_MAX]; - char lockid[32] = { 0 }; + char lockid[32] = {0}; char key_loc[PROPERTY_VALUE_MAX]; int num_vols; off64_t previously_encrypted_upto = 0; @@ -2207,7 +2134,7 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev)); /* Get the size of the real block device */ - fd = open(real_blkdev, O_RDONLY|O_CLOEXEC); + fd = open(real_blkdev, O_RDONLY | O_CLOEXEC); if (fd == -1) { SLOGE("Cannot open block device %s\n", real_blkdev); goto error_unencrypted; @@ -2224,8 +2151,7 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { if (!strcmp(key_loc, KEY_IN_FOOTER)) { unsigned int fs_size_sec, max_fs_size_sec; fs_size_sec = get_fs_size(real_blkdev); - if (fs_size_sec == 0) - fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev); + if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev); max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE); @@ -2239,7 +2165,7 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { * device to sleep on us. We'll grab a partial wakelock, and if the UI * wants to keep the screen on, it can grab a full wakelock. */ - snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid()); + snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid()); acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid); /* The init files are setup to stop the class main and late start when @@ -2299,8 +2225,7 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { } if (!strcmp(key_loc, KEY_IN_FOOTER)) { - crypt_ftr.fs_size = nr_sec - - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE); + crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE); } else { crypt_ftr.fs_size = nr_sec; } @@ -2314,7 +2239,8 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE; } crypt_ftr.crypt_type = crypt_type; - strlcpy((char *)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(), MAX_CRYPTO_TYPE_NAME_LEN); + strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(), + MAX_CRYPTO_TYPE_NAME_LEN); /* Make an encrypted master key */ if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd, @@ -2328,8 +2254,8 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { unsigned char fake_master_key[MAX_KEY_LEN]; unsigned char encrypted_fake_master_key[MAX_KEY_LEN]; memset(fake_master_key, 0, sizeof(fake_master_key)); - encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, - encrypted_fake_master_key, &crypt_ftr); + encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key, + &crypt_ftr); } /* Write the key to the end of the partition */ @@ -2339,11 +2265,11 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { * If none, create a valid empty table and save that. */ if (!persist_data) { - pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE); - if (pdata) { - init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE); - persist_data = pdata; - } + pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE); + if (pdata) { + init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE); + persist_data = pdata; + } } if (persist_data) { save_persistent_data(); @@ -2377,8 +2303,8 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { __le8 hash_first_block[SHA256_DIGEST_LENGTH]; rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block); - if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block, - sizeof(hash_first_block)) != 0) { + if (!rc && + memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) { SLOGE("Checksums do not match - trigger wipe"); rc = -1; } @@ -2391,8 +2317,7 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { /* 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, crypt_ftr.hash_first_block); if (rc) { SLOGE("Error calculating checksum for continuing encryption"); rc = -1; @@ -2402,7 +2327,7 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { /* Undo the dm-crypt mapping whether we succeed or not */ delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE); - if (! rc) { + if (!rc) { /* Success */ crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE; @@ -2450,8 +2375,7 @@ int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) { SLOGE("encryption failed - rebooting into recovery to wipe data\n"); std::string err; const std::vector options = { - "--wipe_data\n--reason=cryptfs_enable_internal\n" - }; + "--wipe_data\n--reason=cryptfs_enable_internal\n"}; if (!write_bootloader_message(options, &err)) { SLOGE("could not write bootloader message: %s", err.c_str()); } @@ -2484,7 +2408,9 @@ error_shutting_down: * but the framework is stopped and not restarted to show the error, so it's up to * vold to restart the system. */ - SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system"); + SLOGE( + "Error enabling encryption after framework is shutdown, no data changed, restarting " + "system"); cryptfs_reboot(RebootType::reboot); /* shouldn't get here */ @@ -2503,8 +2429,7 @@ int cryptfs_enable_default(int no_ui) { return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui); } -int cryptfs_changepw(int crypt_type, const char *newpw) -{ +int cryptfs_changepw(int crypt_type, const char* newpw) { if (e4crypt_is_native()) { SLOGE("cryptfs_changepw not valid for file encryption"); return -1; @@ -2532,12 +2457,8 @@ int cryptfs_changepw(int crypt_type, const char *newpw) crypt_ftr.crypt_type = crypt_type; - rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD - : newpw, - crypt_ftr.salt, - saved_master_key, - crypt_ftr.master_key, - &crypt_ftr); + rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw, + crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr); if (rc) { SLOGE("Encrypt master key failed: %d", rc); return -1; @@ -2565,14 +2486,13 @@ static unsigned int persist_get_max_entries(int encrypted) { dsize = CRYPT_PERSIST_DATA_SIZE; } - max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) / - sizeof(struct crypt_persist_entry); + max_persistent_entries = + (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry); return max_persistent_entries; } -static int persist_get_key(const char *fieldname, char *value) -{ +static int persist_get_key(const char* fieldname, char* value) { unsigned int i; if (persist_data == NULL) { @@ -2589,8 +2509,7 @@ static int persist_get_key(const char *fieldname, char *value) return -1; } -static int persist_set_key(const char *fieldname, const char *value, int encrypted) -{ +static int persist_set_key(const char* fieldname, const char* value, int encrypted) { unsigned int i; unsigned int num; unsigned int max_persistent_entries; @@ -2628,7 +2547,7 @@ static int persist_set_key(const char *fieldname, const char *value, int encrypt * Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the * sequence and its index is greater than or equal to index. Return 0 otherwise. */ -int match_multi_entry(const char *key, const char *field, unsigned index) { +int match_multi_entry(const char* key, const char* field, unsigned index) { std::string key_ = key; std::string field_ = field; @@ -2655,8 +2574,7 @@ int match_multi_entry(const char *key, const char *field, unsigned index) { * and PERSIST_DEL_KEY_ERROR_OTHER if error occurs. * */ -static int persist_del_keys(const char *fieldname, unsigned index) -{ +static int persist_del_keys(const char* fieldname, unsigned index) { unsigned int i; unsigned int j; unsigned int num; @@ -2667,7 +2585,7 @@ static int persist_del_keys(const char *fieldname, unsigned index) num = persist_data->persist_valid_entries; - j = 0; // points to the end of non-deleted entries. + j = 0; // points to the end of non-deleted entries. // Filter out to-be-deleted entries in place. for (i = 0; i < num; i++) { if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) { @@ -2687,8 +2605,7 @@ static int persist_del_keys(const char *fieldname, unsigned index) } } -static int persist_count_keys(const char *fieldname) -{ +static int persist_count_keys(const char* fieldname) { unsigned int i; unsigned int count; @@ -2707,8 +2624,7 @@ static int persist_count_keys(const char *fieldname) } /* Return the value of the specified field. */ -int cryptfs_getfield(const char *fieldname, char *value, int len) -{ +int cryptfs_getfield(const char* fieldname, char* value, int len) { if (e4crypt_is_native()) { SLOGE("Cannot get field when file encrypted"); return -1; @@ -2736,7 +2652,7 @@ int cryptfs_getfield(const char *fieldname, char *value, int len) // stitch them back together. if (!persist_get_key(fieldname, temp_value)) { // We found it, copy it to the caller's buffer and keep going until all entries are read. - if (strlcpy(value, temp_value, len) >= (unsigned) len) { + if (strlcpy(value, temp_value, len) >= (unsigned)len) { // value too small rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL; goto out; @@ -2745,7 +2661,7 @@ int cryptfs_getfield(const char *fieldname, char *value, int len) for (i = 1; /* break explicitly */; i++) { if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >= - (int) sizeof(temp_field)) { + (int)sizeof(temp_field)) { // If the fieldname is very long, we stop as soon as it begins to overflow the // maximum field length. At this point we have in fact fully read out the original // value because cryptfs_setfield would not allow fields with longer names to be @@ -2753,11 +2669,11 @@ int cryptfs_getfield(const char *fieldname, char *value, int len) break; } if (!persist_get_key(temp_field, temp_value)) { - if (strlcat(value, temp_value, len) >= (unsigned)len) { - // value too small. - rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL; - goto out; - } + if (strlcat(value, temp_value, len) >= (unsigned)len) { + // value too small. + rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL; + goto out; + } } else { // Exhaust all entries. break; @@ -2773,8 +2689,7 @@ out: } /* Set the value of the specified field. */ -int cryptfs_setfield(const char *fieldname, const char *value) -{ +int cryptfs_setfield(const char* fieldname, const char* value) { if (e4crypt_is_native()) { SLOGE("Cannot set field when file encrypted"); return -1; @@ -2798,7 +2713,7 @@ int cryptfs_setfield(const char *fieldname, const char *value) } property_get("ro.crypto.state", encrypted_state, ""); - if (!strcmp(encrypted_state, "encrypted") ) { + if (!strcmp(encrypted_state, "encrypted")) { encrypted = 1; } @@ -2867,14 +2782,14 @@ out: * On success trigger next init phase and return 0. * Currently do not handle failure - see TODO below. */ -int cryptfs_mount_default_encrypted(void) -{ +int cryptfs_mount_default_encrypted(void) { int crypt_type = cryptfs_get_password_type(); if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) { SLOGE("Bad crypt type - error"); } else if (crypt_type != CRYPT_TYPE_DEFAULT) { - SLOGD("Password is not default - " - "starting min framework to prompt"); + SLOGD( + "Password is not default - " + "starting min framework to prompt"); property_set("vold.decrypt", "trigger_restart_min_framework"); return 0; } else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) { @@ -2894,8 +2809,7 @@ int cryptfs_mount_default_encrypted(void) /* Returns type of the password, default, pattern, pin or password. */ -int cryptfs_get_password_type(void) -{ +int cryptfs_get_password_type(void) { if (e4crypt_is_native()) { SLOGE("cryptfs_get_password_type not valid for file encryption"); return -1; @@ -2915,8 +2829,7 @@ int cryptfs_get_password_type(void) return crypt_ftr.crypt_type; } -const char* cryptfs_get_password() -{ +const char* cryptfs_get_password() { if (e4crypt_is_native()) { SLOGE("cryptfs_get_password not valid for file encryption"); return 0; @@ -2932,8 +2845,7 @@ const char* cryptfs_get_password() } } -void cryptfs_clear_password() -{ +void cryptfs_clear_password() { if (password) { size_t len = strlen(password); memset(password, 0, len); @@ -2943,8 +2855,7 @@ void cryptfs_clear_password() } } -int cryptfs_isConvertibleToFBE() -{ +int cryptfs_isConvertibleToFBE() { struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT); return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0; } diff --git a/cryptfs.h b/cryptfs.h index dc7a8c3..692d7ee 100644 --- a/cryptfs.h +++ b/cryptfs.h @@ -51,32 +51,39 @@ /* 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. */ +#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_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 @@ -92,78 +99,78 @@ #define KEYMASTER_BLOB_SIZE 2048 /* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */ -#define __le8 unsigned char +#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 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*/ + __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. */ + __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*/ + /* 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; + /* 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. + /* 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 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]; + 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]; + /* 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. @@ -180,49 +187,49 @@ struct crypt_mnt_ftr { * and higher crypt_mnt_ftr structures. */ struct crypt_persist_entry { - char key[PROPERTY_KEY_MAX]; - char val[PROPERTY_VALUE_MAX]; + 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]; + __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 -#define CRYPTO_COMPLETE_ENCRYPTED 0 -#define CRYPTO_COMPLETE_BAD_METADATA (-1) -#define CRYPTO_COMPLETE_PARTIAL (-2) -#define CRYPTO_COMPLETE_INCONSISTENT (-3) -#define CRYPTO_COMPLETE_CORRUPT (-4) +#define CRYPTO_COMPLETE_NOT_ENCRYPTED 1 +#define CRYPTO_COMPLETE_ENCRYPTED 0 +#define CRYPTO_COMPLETE_BAD_METADATA (-1) +#define CRYPTO_COMPLETE_PARTIAL (-2) +#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 */ +#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) -#define CRYPTO_GETFIELD_ERROR_OTHER (-2) +#define CRYPTO_GETFIELD_OK 0 +#define CRYPTO_GETFIELD_ERROR_NO_FIELD (-1) +#define CRYPTO_GETFIELD_ERROR_OTHER (-2) #define CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL (-3) /* Return values for cryptfs_setfield */ -#define CRYPTO_SETFIELD_OK 0 -#define CRYPTO_SETFIELD_ERROR_OTHER (-1) +#define CRYPTO_SETFIELD_OK 0 +#define CRYPTO_SETFIELD_ERROR_OTHER (-1) #define CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG (-2) #define CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG (-3) /* Return values for persist_del_key */ -#define PERSIST_DEL_KEY_OK 0 -#define PERSIST_DEL_KEY_ERROR_OTHER (-1) -#define PERSIST_DEL_KEY_ERROR_NO_FIELD (-2) +#define PERSIST_DEL_KEY_OK 0 +#define PERSIST_DEL_KEY_ERROR_OTHER (-1) +#define PERSIST_DEL_KEY_ERROR_NO_FIELD (-2) int match_multi_entry(const char* key, const char* field, unsigned index); int wait_and_unmount(const char* mountpoint, bool kill); diff --git a/fs/Ext4.cpp b/fs/Ext4.cpp index 717c8b7..7ac4853 100644 --- a/fs/Ext4.cpp +++ b/fs/Ext4.cpp @@ -14,23 +14,20 @@ * limitations under the License. */ -#include -#include -#include -#include -#include -#include #include #include #include -#include +#include +#include +#include +#include #include +#include -#include -#include -#include #include #include +#include +#include #include #include @@ -59,9 +56,8 @@ static const char* kMkfsPath = "/system/bin/mke2fs"; static const char* kFsckPath = "/system/bin/e2fsck"; bool IsSupported() { - return access(kMkfsPath, X_OK) == 0 - && access(kFsckPath, X_OK) == 0 - && IsFilesystemSupported("ext4"); + return access(kMkfsPath, X_OK) == 0 && access(kFsckPath, X_OK) == 0 && + IsFilesystemSupported("ext4"); } status_t Check(const std::string& source, const std::string& target) { @@ -74,7 +70,7 @@ status_t Check(const std::string& source, const std::string& target) { int status; int ret; long tmpmnt_flags = MS_NOATIME | MS_NOEXEC | MS_NOSUID; - char *tmpmnt_opts = (char*) "nomblk_io_submit,errors=remount-ro"; + char* tmpmnt_opts = (char*)"nomblk_io_submit,errors=remount-ro"; /* * First try to mount and unmount the filesystem. We do this because @@ -127,8 +123,8 @@ status_t Check(const std::string& source, const std::string& target) { return 0; } -status_t Mount(const std::string& source, const std::string& target, bool ro, - bool remount, bool executable) { +status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount, + bool executable) { int rc; unsigned long flags; @@ -162,8 +158,7 @@ status_t Resize(const std::string& source, unsigned long numSectors) { return ForkExecvp(cmd); } -status_t Format(const std::string& source, unsigned long numSectors, - const std::string& target) { +status_t Format(const std::string& source, unsigned long numSectors, const std::string& target) { std::vector cmd; cmd.push_back(kMkfsPath); diff --git a/fs/Ext4.h b/fs/Ext4.h index f78dc95..329f302 100644 --- a/fs/Ext4.h +++ b/fs/Ext4.h @@ -28,10 +28,9 @@ namespace ext4 { bool IsSupported(); status_t Check(const std::string& source, const std::string& target); -status_t Mount(const std::string& source, const std::string& target, bool ro, - bool remount, bool executable); -status_t Format(const std::string& source, unsigned long numSectors, - const std::string& target); +status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount, + bool executable); +status_t Format(const std::string& source, unsigned long numSectors, const std::string& target); status_t Resize(const std::string& source, unsigned long numSectors); } // namespace ext4 diff --git a/fs/F2fs.cpp b/fs/F2fs.cpp index f24fd91..9d72963 100644 --- a/fs/F2fs.cpp +++ b/fs/F2fs.cpp @@ -22,8 +22,8 @@ #include #include -#include #include +#include #include @@ -37,9 +37,8 @@ static const char* kMkfsPath = "/system/bin/make_f2fs"; static const char* kFsckPath = "/system/bin/fsck.f2fs"; bool IsSupported() { - return access(kMkfsPath, X_OK) == 0 - && access(kFsckPath, X_OK) == 0 - && IsFilesystemSupported("f2fs"); + return access(kMkfsPath, X_OK) == 0 && access(kFsckPath, X_OK) == 0 && + IsFilesystemSupported("f2fs"); } status_t Check(const std::string& source) { diff --git a/fs/Vfat.cpp b/fs/Vfat.cpp index 9873fd4..7b833d1 100644 --- a/fs/Vfat.cpp +++ b/fs/Vfat.cpp @@ -14,24 +14,21 @@ * limitations under the License. */ -#include -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include -#include -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include #include @@ -41,8 +38,8 @@ #include -#include "Vfat.h" #include "Utils.h" +#include "Vfat.h" #include "VoldUtil.h" using android::base::StringPrintf; @@ -55,9 +52,8 @@ static const char* kMkfsPath = "/system/bin/newfs_msdos"; static const char* kFsckPath = "/system/bin/fsck_msdos"; bool IsSupported() { - return access(kMkfsPath, X_OK) == 0 - && access(kFsckPath, X_OK) == 0 - && IsFilesystemSupported("vfat"); + return access(kMkfsPath, X_OK) == 0 && access(kFsckPath, X_OK) == 0 && + IsFilesystemSupported("vfat"); } status_t Check(const std::string& source) { @@ -79,43 +75,42 @@ status_t Check(const std::string& source) { return -1; } - switch(rc) { - case 0: - LOG(INFO) << "Filesystem check completed OK"; - return 0; + switch (rc) { + case 0: + LOG(INFO) << "Filesystem check completed OK"; + return 0; - case 2: - LOG(ERROR) << "Filesystem check failed (not a FAT filesystem)"; - errno = ENODATA; - return -1; + case 2: + LOG(ERROR) << "Filesystem check failed (not a FAT filesystem)"; + errno = ENODATA; + return -1; - case 4: - if (pass++ <= 3) { - LOG(WARNING) << "Filesystem modified - rechecking (pass " << pass << ")"; - continue; - } - LOG(ERROR) << "Failing check after too many rechecks"; - errno = EIO; - return -1; + case 4: + if (pass++ <= 3) { + LOG(WARNING) << "Filesystem modified - rechecking (pass " << pass << ")"; + continue; + } + LOG(ERROR) << "Failing check after too many rechecks"; + errno = EIO; + return -1; - case 8: - LOG(ERROR) << "Filesystem check failed (no filesystem)"; - errno = ENODATA; - return -1; + case 8: + LOG(ERROR) << "Filesystem check failed (no filesystem)"; + errno = ENODATA; + return -1; - default: - LOG(ERROR) << "Filesystem check failed (unknown exit code " << rc << ")"; - errno = EIO; - return -1; + default: + LOG(ERROR) << "Filesystem check failed (unknown exit code " << rc << ")"; + errno = EIO; + return -1; } } while (0); return 0; } -status_t Mount(const std::string& source, const std::string& target, bool ro, - bool remount, bool executable, int ownerUid, int ownerGid, int permMask, - bool createLost) { +status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount, + bool executable, int ownerUid, int ownerGid, int permMask, bool createLost) { int rc; unsigned long flags; @@ -128,9 +123,9 @@ status_t Mount(const std::string& source, const std::string& target, bool ro, flags |= (ro ? MS_RDONLY : 0); flags |= (remount ? MS_REMOUNT : 0); - auto mountData = android::base::StringPrintf( - "utf8,uid=%d,gid=%d,fmask=%o,dmask=%o,shortname=mixed", - ownerUid, ownerGid, permMask, permMask); + auto mountData = + android::base::StringPrintf("utf8,uid=%d,gid=%d,fmask=%o,dmask=%o,shortname=mixed", + ownerUid, ownerGid, permMask, permMask); rc = mount(c_source, c_target, "vfat", flags, mountData.c_str()); diff --git a/fs/Vfat.h b/fs/Vfat.h index 40be5f6..2030067 100644 --- a/fs/Vfat.h +++ b/fs/Vfat.h @@ -28,9 +28,8 @@ namespace vfat { bool IsSupported(); status_t Check(const std::string& source); -status_t Mount(const std::string& source, const std::string& target, bool ro, - bool remount, bool executable, int ownerUid, int ownerGid, int permMask, - bool createLost); +status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount, + bool executable, int ownerUid, int ownerGid, int permMask, bool createLost); status_t Format(const std::string& source, unsigned long numSectors); } // namespace vfat diff --git a/hash.h b/hash.h index 3b483f1..cd81805 100644 --- a/hash.h +++ b/hash.h @@ -1,18 +1,18 @@ /* * Copyright (c) 1999 Kungliga Tekniska Högskolan - * (Royal Institute of Technology, Stockholm, Sweden). - * All rights reserved. + * (Royal Institute of Technology, Stockholm, Sweden). + * All rights reserved. * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KTH nor the names of its contributors may be * used to endorse or promote products derived from this software without @@ -42,7 +42,7 @@ #include #ifndef min -#define min(a,b) (((a)>(b))?(b):(a)) +#define min(a, b) (((a) > (b)) ? (b) : (a)) #endif /* Vector Crays doesn't have a good 32-bit type, or more precisely, @@ -53,14 +53,12 @@ */ #ifdef _CRAY -#define CRAYFIX(X) ((X) & 0xffffffff) +#define CRAYFIX(X) ((X)&0xffffffff) #else #define CRAYFIX(X) (X) #endif -static inline u_int32_t -cshift (u_int32_t x, unsigned int n) -{ +static inline u_int32_t cshift(u_int32_t x, unsigned int n) { x = CRAYFIX(x); return CRAYFIX((x << n) | (x >> (32 - n))); } diff --git a/main.cpp b/main.cpp index c4071d1..52abf20 100644 --- a/main.cpp +++ b/main.cpp @@ -16,12 +16,12 @@ #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER -#include "model/Disk.h" -#include "VolumeManager.h" #include "NetlinkManager.h" #include "VoldNativeService.h" #include "VoldUtil.h" +#include "VolumeManager.h" #include "cryptfs.h" +#include "model/Disk.h" #include "sehandle.h" #include @@ -31,23 +31,23 @@ #include #include +#include +#include +#include +#include +#include #include #include -#include #include #include #include -#include -#include -#include -#include static int process_config(VolumeManager* vm, bool* has_adoptable, bool* has_quota, bool* has_reserved); -static void coldboot(const char *path); +static void coldboot(const char* path); static void parse_args(int argc, char** argv); -struct selabel_handle *sehandle; +struct selabel_handle* sehandle; using android::base::StringPrintf; @@ -60,14 +60,13 @@ int main(int argc, char** argv) { ATRACE_BEGIN("main"); - LOG(VERBOSE) << "Detected support for:" - << (android::vold::IsFilesystemSupported("ext4") ? " ext4" : "") - << (android::vold::IsFilesystemSupported("f2fs") ? " f2fs" : "") - << (android::vold::IsFilesystemSupported("vfat") ? " vfat" : ""); + << (android::vold::IsFilesystemSupported("ext4") ? " ext4" : "") + << (android::vold::IsFilesystemSupported("f2fs") ? " f2fs" : "") + << (android::vold::IsFilesystemSupported("vfat") ? " vfat" : ""); - VolumeManager *vm; - NetlinkManager *nm; + VolumeManager* vm; + NetlinkManager* nm; parse_args(argc, argv); @@ -148,19 +147,21 @@ int main(int argc, char** argv) { static void parse_args(int argc, char** argv) { static struct option opts[] = { - {"blkid_context", required_argument, 0, 'b' }, - {"blkid_untrusted_context", required_argument, 0, 'B' }, - {"fsck_context", required_argument, 0, 'f' }, - {"fsck_untrusted_context", required_argument, 0, 'F' }, + {"blkid_context", required_argument, 0, 'b'}, + {"blkid_untrusted_context", required_argument, 0, 'B'}, + {"fsck_context", required_argument, 0, 'f'}, + {"fsck_untrusted_context", required_argument, 0, 'F'}, }; int c; while ((c = getopt_long(argc, argv, "", opts, nullptr)) != -1) { switch (c) { + // clang-format off case 'b': android::vold::sBlkidContext = optarg; break; case 'B': android::vold::sBlkidUntrustedContext = optarg; break; case 'f': android::vold::sFsckContext = optarg; break; case 'F': android::vold::sFsckUntrustedContext = optarg; break; + // clang-format on } } @@ -170,33 +171,30 @@ static void parse_args(int argc, char** argv) { CHECK(android::vold::sFsckUntrustedContext != nullptr); } -static void do_coldboot(DIR *d, int lvl) { - struct dirent *de; +static void do_coldboot(DIR* d, int lvl) { + struct dirent* de; int dfd, fd; dfd = dirfd(d); fd = openat(dfd, "uevent", O_WRONLY | O_CLOEXEC); - if(fd >= 0) { + if (fd >= 0) { write(fd, "add\n", 4); close(fd); } - while((de = readdir(d))) { - DIR *d2; + while ((de = readdir(d))) { + DIR* d2; - if (de->d_name[0] == '.') - continue; + if (de->d_name[0] == '.') continue; - if (de->d_type != DT_DIR && lvl > 0) - continue; + if (de->d_type != DT_DIR && lvl > 0) continue; fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if(fd < 0) - continue; + if (fd < 0) continue; d2 = fdopendir(fd); - if(d2 == 0) + if (d2 == 0) close(fd); else { do_coldboot(d2, lvl + 1); @@ -205,10 +203,10 @@ static void do_coldboot(DIR *d, int lvl) { } } -static void coldboot(const char *path) { +static void coldboot(const char* path) { ATRACE_NAME("coldboot"); - DIR *d = opendir(path); - if(d) { + DIR* d = opendir(path); + if (d) { do_coldboot(d, 0); closedir(d); } @@ -251,13 +249,13 @@ static int process_config(VolumeManager* vm, bool* has_adoptable, bool* has_quot flags |= android::vold::Disk::Flags::kAdoptable; *has_adoptable = true; } - if (fs_mgr_is_noemulatedsd(rec) - || android::base::GetBoolProperty("vold.debug.default_primary", false)) { + if (fs_mgr_is_noemulatedsd(rec) || + android::base::GetBoolProperty("vold.debug.default_primary", false)) { flags |= android::vold::Disk::Flags::kDefaultPrimary; } vm->addDiskSource(std::shared_ptr( - new VolumeManager::DiskSource(sysPattern, nickname, flags))); + new VolumeManager::DiskSource(sysPattern, nickname, flags))); } } return 0; diff --git a/model/Disk.cpp b/model/Disk.cpp index 781d3e9..13cb1c7 100644 --- a/model/Disk.cpp +++ b/model/Disk.cpp @@ -15,36 +15,36 @@ */ #include "Disk.h" -#include "PublicVolume.h" +#include "Ext4Crypt.h" #include "PrivateVolume.h" +#include "PublicVolume.h" #include "Utils.h" #include "VolumeBase.h" #include "VolumeManager.h" -#include "Ext4Crypt.h" #include #include +#include #include #include #include -#include #include #include "cryptfs.h" -#include #include #include #include #include -#include +#include #include #include -#include +#include +#include using android::base::ReadFileToString; -using android::base::WriteStringToFile; using android::base::StringPrintf; +using android::base::WriteStringToFile; namespace android { namespace vold { @@ -112,20 +112,22 @@ static bool isVirtioBlkDevice(unsigned int major) { * "ranchu", the device's sysfs path should end with "/block/vd[d-z]", etc. * But just having a) and b) is enough for now. */ - return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin - && major <= kMajorBlockExperimentalMax; + return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin && + major <= kMajorBlockExperimentalMax; } static bool isNvmeBlkDevice(unsigned int major, const std::string& sysPath) { - return sysPath.find("nvme") != std::string::npos - && major >= kMajorBlockDynamicMin - && major <= kMajorBlockDynamicMax; + return sysPath.find("nvme") != std::string::npos && major >= kMajorBlockDynamicMin && + major <= kMajorBlockDynamicMax; } -Disk::Disk(const std::string& eventPath, dev_t device, - const std::string& nickname, int flags) : - mDevice(device), mSize(-1), mNickname(nickname), mFlags(flags), mCreated( - false), mJustPartitioned(false) { +Disk::Disk(const std::string& eventPath, dev_t device, const std::string& nickname, int flags) + : mDevice(device), + mSize(-1), + mNickname(nickname), + mFlags(flags), + mCreated(false), + mJustPartitioned(false) { mId = StringPrintf("disk:%u,%u", major(device), minor(device)); mEventPath = eventPath; mSysPath = StringPrintf("/sys/%s", eventPath.c_str()); @@ -251,73 +253,78 @@ status_t Disk::readMetadata() { unsigned int majorId = major(mDevice); switch (majorId) { - case kMajorBlockLoop: { - mLabel = "Virtual"; - break; - } - case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD: - case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH: - case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL: - case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: { - std::string path(mSysPath + "/device/vendor"); - std::string tmp; - if (!ReadFileToString(path, &tmp)) { - PLOG(WARNING) << "Failed to read vendor from " << path; - return -errno; - } - tmp = android::base::Trim(tmp); - mLabel = tmp; - break; - } - case kMajorBlockMmc: { - std::string path(mSysPath + "/device/manfid"); - std::string tmp; - if (!ReadFileToString(path, &tmp)) { - PLOG(WARNING) << "Failed to read manufacturer from " << path; - return -errno; - } - tmp = android::base::Trim(tmp); - int64_t manfid; - if (!android::base::ParseInt(tmp, &manfid)) { - PLOG(WARNING) << "Failed to parse manufacturer " << tmp; - return -EINVAL; - } - // Our goal here is to give the user a meaningful label, ideally - // matching whatever is silk-screened on the card. To reduce - // user confusion, this list doesn't contain white-label manfid. - switch (manfid) { - case 0x000003: mLabel = "SanDisk"; break; - case 0x00001b: mLabel = "Samsung"; break; - case 0x000028: mLabel = "Lexar"; break; - case 0x000074: mLabel = "Transcend"; break; - } - break; - } - default: { - if (isVirtioBlkDevice(majorId)) { - LOG(DEBUG) << "Recognized experimental block major ID " << majorId - << " as virtio-blk (emulator's virtual SD card device)"; + case kMajorBlockLoop: { mLabel = "Virtual"; break; } - if (isNvmeBlkDevice(majorId, mSysPath)) { - std::string path(mSysPath + "/device/model"); + // clang-format off + case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: + case kMajorBlockScsiD: case kMajorBlockScsiE: case kMajorBlockScsiF: + case kMajorBlockScsiG: case kMajorBlockScsiH: case kMajorBlockScsiI: + case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL: + case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: + case kMajorBlockScsiP: { + // clang-format on + std::string path(mSysPath + "/device/vendor"); std::string tmp; if (!ReadFileToString(path, &tmp)) { PLOG(WARNING) << "Failed to read vendor from " << path; return -errno; } + tmp = android::base::Trim(tmp); mLabel = tmp; break; } - LOG(WARNING) << "Unsupported block major type " << majorId; - return -ENOTSUP; - } + case kMajorBlockMmc: { + std::string path(mSysPath + "/device/manfid"); + std::string tmp; + if (!ReadFileToString(path, &tmp)) { + PLOG(WARNING) << "Failed to read manufacturer from " << path; + return -errno; + } + tmp = android::base::Trim(tmp); + int64_t manfid; + if (!android::base::ParseInt(tmp, &manfid)) { + PLOG(WARNING) << "Failed to parse manufacturer " << tmp; + return -EINVAL; + } + // Our goal here is to give the user a meaningful label, ideally + // matching whatever is silk-screened on the card. To reduce + // user confusion, this list doesn't contain white-label manfid. + switch (manfid) { + // clang-format off + case 0x000003: mLabel = "SanDisk"; break; + case 0x00001b: mLabel = "Samsung"; break; + case 0x000028: mLabel = "Lexar"; break; + case 0x000074: mLabel = "Transcend"; break; + // clang-format on + } + break; + } + default: { + if (isVirtioBlkDevice(majorId)) { + LOG(DEBUG) << "Recognized experimental block major ID " << majorId + << " as virtio-blk (emulator's virtual SD card device)"; + mLabel = "Virtual"; + break; + } + if (isNvmeBlkDevice(majorId, mSysPath)) { + std::string path(mSysPath + "/device/model"); + std::string tmp; + if (!ReadFileToString(path, &tmp)) { + PLOG(WARNING) << "Failed to read vendor from " << path; + return -errno; + } + mLabel = tmp; + break; + } + LOG(WARNING) << "Unsupported block major type " << majorId; + return -ENOTSUP; + } } auto listener = VolumeManager::Instance()->getListener(); - if (listener) listener->onDiskMetadataChanged(getId(), - mSize, mLabel, mSysPath); + if (listener) listener->onDiskMetadataChanged(getId(), mSize, mLabel, mSysPath); return OK; } @@ -563,45 +570,49 @@ int Disk::getMaxMinors() { // Figure out maximum partition devices supported unsigned int majorId = major(mDevice); switch (majorId) { - case kMajorBlockLoop: { - std::string tmp; - if (!ReadFileToString(kSysfsLoopMaxMinors, &tmp)) { - LOG(ERROR) << "Failed to read max minors"; - return -errno; + case kMajorBlockLoop: { + std::string tmp; + if (!ReadFileToString(kSysfsLoopMaxMinors, &tmp)) { + LOG(ERROR) << "Failed to read max minors"; + return -errno; + } + return std::stoi(tmp); } - return std::stoi(tmp); - } - case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD: - case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH: - case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL: - case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: { - // Per Documentation/devices.txt this is static - return 15; - } - case kMajorBlockMmc: { - // Per Documentation/devices.txt this is dynamic - std::string tmp; - if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp) && - !ReadFileToString(kSysfsMmcMaxMinorsDeprecated, &tmp)) { - LOG(ERROR) << "Failed to read max minors"; - return -errno; - } - return std::stoi(tmp); - } - default: { - if (isVirtioBlkDevice(majorId)) { - // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is - // 2^4 - 1 = 15 + // clang-format off + case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: + case kMajorBlockScsiD: case kMajorBlockScsiE: case kMajorBlockScsiF: + case kMajorBlockScsiG: case kMajorBlockScsiH: case kMajorBlockScsiI: + case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL: + case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: + case kMajorBlockScsiP: { + // clang-format on + // Per Documentation/devices.txt this is static return 15; } - if (isNvmeBlkDevice(majorId, mSysPath)) { - // despite kernel nvme driver supports up to 1M minors, - // #define NVME_MINORS (1U << MINORBITS) - // sgdisk can not support more than 127 partitions, due to - // #define MAX_MBR_PARTS 128 - return 127; + case kMajorBlockMmc: { + // Per Documentation/devices.txt this is dynamic + std::string tmp; + if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp) && + !ReadFileToString(kSysfsMmcMaxMinorsDeprecated, &tmp)) { + LOG(ERROR) << "Failed to read max minors"; + return -errno; + } + return std::stoi(tmp); + } + default: { + if (isVirtioBlkDevice(majorId)) { + // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is + // 2^4 - 1 = 15 + return 15; + } + if (isNvmeBlkDevice(majorId, mSysPath)) { + // despite kernel nvme driver supports up to 1M minors, + // #define NVME_MINORS (1U << MINORBITS) + // sgdisk can not support more than 127 partitions, due to + // #define MAX_MBR_PARTS 128 + return 127; + } } - } } LOG(ERROR) << "Unsupported block major type " << majorId; diff --git a/model/Disk.h b/model/Disk.h index 63acf6a..3140144 100644 --- a/model/Disk.h +++ b/model/Disk.h @@ -36,7 +36,7 @@ class VolumeBase; * how to repartition itself. */ class Disk { -public: + public: Disk(const std::string& eventPath, dev_t device, const std::string& nickname, int flags); virtual ~Disk(); @@ -79,7 +79,7 @@ public: status_t partitionPrivate(); status_t partitionMixed(int8_t ratio); -private: + private: /* ID that uniquely references this disk */ std::string mId; /* Original event path */ diff --git a/model/EmulatedVolume.h b/model/EmulatedVolume.h index 9b0c049..f618c55 100644 --- a/model/EmulatedVolume.h +++ b/model/EmulatedVolume.h @@ -36,16 +36,16 @@ namespace vold { * store data local to their app. */ class EmulatedVolume : public VolumeBase { -public: + public: explicit EmulatedVolume(const std::string& rawPath); EmulatedVolume(const std::string& rawPath, dev_t device, const std::string& fsUuid); virtual ~EmulatedVolume(); -protected: + protected: status_t doMount() override; status_t doUnmount() override; -private: + private: std::string mRawPath; std::string mLabel; diff --git a/model/ObbVolume.cpp b/model/ObbVolume.cpp index 709c7a3..ec3d267 100644 --- a/model/ObbVolume.cpp +++ b/model/ObbVolume.cpp @@ -14,12 +14,12 @@ * limitations under the License. */ -#include "fs/Vfat.h" +#include "ObbVolume.h" #include "Devmapper.h" #include "Loop.h" -#include "ObbVolume.h" #include "Utils.h" #include "VoldUtil.h" +#include "fs/Vfat.h" #include #include @@ -31,8 +31,8 @@ #include #include #include -#include #include +#include #include using android::base::StringPrintf; @@ -42,15 +42,15 @@ namespace android { namespace vold { ObbVolume::ObbVolume(int id, const std::string& sourcePath, const std::string& sourceKey, - gid_t ownerGid) : VolumeBase(Type::kObb) { + gid_t ownerGid) + : VolumeBase(Type::kObb) { setId(StringPrintf("obb:%d", id)); mSourcePath = sourcePath; mSourceKey = sourceKey; mOwnerGid = ownerGid; } -ObbVolume::~ObbVolume() { -} +ObbVolume::~ObbVolume() {} status_t ObbVolume::doCreate() { if (Loop::create(mSourcePath, mLoopPath)) { @@ -75,8 +75,8 @@ status_t ObbVolume::doCreate() { } char tmp[PATH_MAX]; - if (Devmapper::create(getId().c_str(), mLoopPath.c_str(), mSourceKey.c_str(), nr_sec, - tmp, PATH_MAX)) { + if (Devmapper::create(getId().c_str(), mLoopPath.c_str(), mSourceKey.c_str(), nr_sec, tmp, + PATH_MAX)) { PLOG(ERROR) << getId() << " failed to create dm"; return -1; } @@ -108,8 +108,10 @@ status_t ObbVolume::doMount() { PLOG(ERROR) << getId() << " failed to create mount point"; return -1; } - if (android::vold::vfat::Mount(mMountPath, path, - true, false, true, 0, mOwnerGid, 0227, false)) { + // clang-format off + if (android::vold::vfat::Mount(mMountPath, path, true, false, true, + 0, mOwnerGid, 0227, false)) { + // clang-format on PLOG(ERROR) << getId() << " failed to mount"; return -1; } diff --git a/model/ObbVolume.h b/model/ObbVolume.h index 5ec0cde..8f7ee94 100644 --- a/model/ObbVolume.h +++ b/model/ObbVolume.h @@ -28,18 +28,17 @@ namespace vold { * OBB container. */ class ObbVolume : public VolumeBase { -public: - ObbVolume(int id, const std::string& sourcePath, const std::string& sourceKey, - gid_t ownerGid); + public: + ObbVolume(int id, const std::string& sourcePath, const std::string& sourceKey, gid_t ownerGid); virtual ~ObbVolume(); -protected: + protected: status_t doCreate() override; status_t doDestroy() override; status_t doMount() override; status_t doUnmount() override; -private: + private: std::string mSourcePath; std::string mSourceKey; gid_t mOwnerGid; diff --git a/model/PrivateVolume.cpp b/model/PrivateVolume.cpp index cf21577..de2a09f 100644 --- a/model/PrivateVolume.cpp +++ b/model/PrivateVolume.cpp @@ -14,27 +14,27 @@ * limitations under the License. */ -#include "fs/Ext4.h" -#include "fs/F2fs.h" #include "PrivateVolume.h" #include "EmulatedVolume.h" #include "Utils.h" #include "VolumeManager.h" #include "cryptfs.h" +#include "fs/Ext4.h" +#include "fs/F2fs.h" -#include #include +#include #include #include #include #include #include -#include -#include -#include -#include #include +#include +#include +#include +#include using android::base::StringPrintf; @@ -43,14 +43,13 @@ namespace vold { static const unsigned int kMajorBlockMmc = 179; -PrivateVolume::PrivateVolume(dev_t device, const std::string& keyRaw) : - VolumeBase(Type::kPrivate), mRawDevice(device), mKeyRaw(keyRaw) { +PrivateVolume::PrivateVolume(dev_t device, const std::string& 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()); } -PrivateVolume::~PrivateVolume() { -} +PrivateVolume::~PrivateVolume() {} status_t PrivateVolume::readMetadata() { status_t res = ReadMetadata(mDmDevPath, &mFsType, &mFsUuid, &mFsLabel); @@ -66,9 +65,9 @@ status_t PrivateVolume::doCreate() { return -EIO; } if (mKeyRaw.size() != cryptfs_get_keysize()) { - PLOG(ERROR) << getId() << " Raw keysize " << mKeyRaw.size() << - " does not match crypt keysize " << cryptfs_get_keysize(); - return -EIO; + PLOG(ERROR) << getId() << " Raw keysize " << mKeyRaw.size() + << " does not match crypt keysize " << cryptfs_get_keysize(); + return -EIO; } // Recover from stale vold by tearing down any old mappings @@ -76,10 +75,9 @@ status_t PrivateVolume::doCreate() { // TODO: figure out better SELinux labels for private volumes - unsigned char* key = (unsigned char*) mKeyRaw.data(); + 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); + 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"; @@ -147,12 +145,12 @@ status_t PrivateVolume::doMount() { // Verify that common directories are ready to roll if (PrepareDir(mPath + "/app", 0771, AID_SYSTEM, AID_SYSTEM) || - PrepareDir(mPath + "/user", 0711, AID_SYSTEM, AID_SYSTEM) || - PrepareDir(mPath + "/user_de", 0711, AID_SYSTEM, AID_SYSTEM) || - PrepareDir(mPath + "/media", 0770, AID_MEDIA_RW, AID_MEDIA_RW) || - PrepareDir(mPath + "/media/0", 0770, AID_MEDIA_RW, AID_MEDIA_RW) || - PrepareDir(mPath + "/local", 0751, AID_ROOT, AID_ROOT) || - PrepareDir(mPath + "/local/tmp", 0771, AID_SHELL, AID_SHELL)) { + PrepareDir(mPath + "/user", 0711, AID_SYSTEM, AID_SYSTEM) || + PrepareDir(mPath + "/user_de", 0711, AID_SYSTEM, AID_SYSTEM) || + PrepareDir(mPath + "/media", 0770, AID_MEDIA_RW, AID_MEDIA_RW) || + PrepareDir(mPath + "/media/0", 0770, AID_MEDIA_RW, AID_MEDIA_RW) || + PrepareDir(mPath + "/local", 0751, AID_ROOT, AID_ROOT) || + PrepareDir(mPath + "/local/tmp", 0771, AID_SHELL, AID_SHELL)) { PLOG(ERROR) << getId() << " failed to prepare"; return -EIO; } @@ -160,8 +158,7 @@ status_t PrivateVolume::doMount() { // Create a new emulated volume stacked above us, it will automatically // be destroyed during unmount std::string mediaPath(mPath + "/media"); - auto vol = std::shared_ptr( - new EmulatedVolume(mediaPath, mRawDevice, mFsUuid)); + auto vol = std::shared_ptr(new EmulatedVolume(mediaPath, mRawDevice, mFsUuid)); addVolume(vol); vol->create(); diff --git a/model/PrivateVolume.h b/model/PrivateVolume.h index 9a61f8d..85aa4dc 100644 --- a/model/PrivateVolume.h +++ b/model/PrivateVolume.h @@ -36,14 +36,14 @@ namespace vold { * keys are tightly tied to this device. */ class PrivateVolume : public VolumeBase { -public: + public: PrivateVolume(dev_t device, const std::string& keyRaw); virtual ~PrivateVolume(); const std::string& getFsType() { return mFsType; }; const std::string& getRawDevPath() { return mRawDevPath; }; const std::string& getRawDmDevPath() { return mDmDevPath; }; -protected: + protected: status_t doCreate() override; status_t doDestroy() override; status_t doMount() override; @@ -52,7 +52,7 @@ protected: status_t readMetadata(); -private: + private: /* Kernel device of raw, encrypted partition */ dev_t mRawDevice; /* Path to raw, encrypted block device */ diff --git a/model/PublicVolume.h b/model/PublicVolume.h index 3aa7a73..c918f52 100644 --- a/model/PublicVolume.h +++ b/model/PublicVolume.h @@ -38,11 +38,11 @@ namespace vold { * away the Android directory for secondary users. */ class PublicVolume : public VolumeBase { -public: + public: explicit PublicVolume(dev_t device); virtual ~PublicVolume(); -protected: + protected: status_t doCreate() override; status_t doDestroy() override; status_t doMount() override; @@ -52,7 +52,7 @@ protected: status_t readMetadata(); status_t initAsecStage(); -private: + private: /* Kernel device representing partition */ dev_t mDevice; /* Block device path */ diff --git a/secdiscard.cpp b/secdiscard.cpp index 25a0826..2d9dc35 100644 --- a/secdiscard.cpp +++ b/secdiscard.cpp @@ -18,15 +18,15 @@ #include #include +#include +#include +#include +#include +#include #include #include -#include -#include #include -#include -#include -#include -#include +#include #include #include @@ -42,23 +42,23 @@ struct Options { constexpr uint32_t max_extents = 32; -bool read_command_line(int argc, const char * const argv[], Options &options); -void usage(const char *progname); -bool secdiscard_path(const std::string &path); -bool check_fiemap(const struct fiemap &fiemap, const std::string &path); +bool read_command_line(int argc, const char* const argv[], Options& options); +void usage(const char* progname); +bool secdiscard_path(const std::string& path); +bool check_fiemap(const struct fiemap& fiemap, const std::string& path); bool overwrite_with_zeros(int fd, off64_t start, off64_t length); -} +} // namespace -int main(int argc, const char * const argv[]) { - android::base::InitLogging(const_cast(argv)); +int main(int argc, const char* const argv[]) { + android::base::InitLogging(const_cast(argv)); Options options; if (!read_command_line(argc, argv, options)) { usage(argv[0]); return -1; } - for (auto const &target: options.targets) { + for (auto const& target : options.targets) { // F2FS-specific ioctl // It requires the below kernel commit merged in v4.16-rc1. // 1ad71a27124c ("f2fs: add an ioctl to disable GC for specific file") @@ -70,13 +70,12 @@ int main(int argc, const char * const argv[]) { // ce767d9a55bc ("f2fs: updates on v4.16-rc1") #ifndef F2FS_IOC_SET_PIN_FILE #ifndef F2FS_IOCTL_MAGIC -#define F2FS_IOCTL_MAGIC 0xf5 +#define F2FS_IOCTL_MAGIC 0xf5 #endif -#define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32) -#define F2FS_IOC_GET_PIN_FILE _IOR(F2FS_IOCTL_MAGIC, 14, __u32) +#define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32) +#define F2FS_IOC_GET_PIN_FILE _IOR(F2FS_IOCTL_MAGIC, 14, __u32) #endif - android::base::unique_fd fd(TEMP_FAILURE_RETRY(open( - target.c_str(), O_WRONLY, 0))); + android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(target.c_str(), O_WRONLY, 0))); if (fd == -1) { LOG(ERROR) << "Secure discard open failed for: " << target; return 0; @@ -102,29 +101,29 @@ int main(int argc, const char * const argv[]) { namespace { -bool read_command_line(int argc, const char * const argv[], Options &options) { +bool read_command_line(int argc, const char* const argv[], Options& options) { for (int i = 1; i < argc; i++) { if (!strcmp("--no-unlink", argv[i])) { options.unlink = false; } else if (!strcmp("--", argv[i])) { - for (int j = i+1; j < argc; j++) { - if (argv[j][0] != '/') return false; // Must be absolute path + for (int j = i + 1; j < argc; j++) { + if (argv[j][0] != '/') return false; // Must be absolute path options.targets.emplace_back(argv[j]); } return options.targets.size() > 0; } else { - return false; // Unknown option + return false; // Unknown option } } - return false; // "--" not found + return false; // "--" not found } -void usage(const char *progname) { +void usage(const char* progname) { fprintf(stderr, "Usage: %s [--no-unlink] -- ...\n", progname); } // BLKSECDISCARD all content in "path", if it's small enough. -bool secdiscard_path(const std::string &path) { +bool secdiscard_path(const std::string& path) { auto fiemap = android::vold::PathFiemap(path, max_extents); if (!fiemap || !check_fiemap(*fiemap, path)) { return false; @@ -133,8 +132,8 @@ bool secdiscard_path(const std::string &path) { if (block_device.empty()) { return false; } - android::base::unique_fd fs_fd(TEMP_FAILURE_RETRY(open( - block_device.c_str(), O_RDWR | O_LARGEFILE | O_CLOEXEC, 0))); + android::base::unique_fd fs_fd( + TEMP_FAILURE_RETRY(open(block_device.c_str(), O_RDWR | O_LARGEFILE | O_CLOEXEC, 0))); if (fs_fd == -1) { PLOG(ERROR) << "Failed to open device " << block_device; return false; @@ -153,10 +152,10 @@ bool secdiscard_path(const std::string &path) { } // Ensure that the FIEMAP covers the file and is OK to discard -bool check_fiemap(const struct fiemap &fiemap, const std::string &path) { +bool check_fiemap(const struct fiemap& fiemap, const std::string& path) { auto mapped = fiemap.fm_mapped_extents; if (!(fiemap.fm_extents[mapped - 1].fe_flags & FIEMAP_EXTENT_LAST)) { - LOG(ERROR) << "Extent " << mapped -1 << " was not the last in " << path; + LOG(ERROR) << "Extent " << mapped - 1 << " was not the last in " << path; return false; } for (uint32_t i = 0; i < mapped; i++) { @@ -188,4 +187,4 @@ bool overwrite_with_zeros(int fd, off64_t start, off64_t length) { return true; } -} +} // namespace diff --git a/secontext.cpp b/secontext.cpp index 0529a30..bc21fc2 100644 --- a/secontext.cpp +++ b/secontext.cpp @@ -13,10 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include #include "secontext.h" +#include -security_context_t secontextFsck() -{ +security_context_t secontextFsck() { return android::vold::sFsckContext; } diff --git a/sehandle.h b/sehandle.h index f59d7eb..8921db5 100644 --- a/sehandle.h +++ b/sehandle.h @@ -19,6 +19,6 @@ #include -extern struct selabel_handle *sehandle; +extern struct selabel_handle* sehandle; #endif diff --git a/tests/CryptfsScryptHidlizationEquivalence_test.cpp b/tests/CryptfsScryptHidlizationEquivalence_test.cpp index 2905af2..72170e3 100644 --- a/tests/CryptfsScryptHidlizationEquivalence_test.cpp +++ b/tests/CryptfsScryptHidlizationEquivalence_test.cpp @@ -18,13 +18,13 @@ #define LOG_TAG "scrypt_test" #include +#include #include #include #include -#include -#include "../cryptfs.h" #include "../Keymaster.h" +#include "../cryptfs.h" #ifdef CONFIG_HW_DISK_ENCRYPTION #include "cryptfs_hw.h" @@ -50,9 +50,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) -{ +static int keymaster_init(keymaster0_device_t** keymaster0_dev, + keymaster1_device_t** keymaster1_dev) { int rc; const hw_module_t* mod; @@ -76,8 +75,8 @@ static int keymaster_init(keymaster0_device_t **keymaster0_dev, } if (rc) { - ALOGE("could not open keymaster device in %s (%s)", - KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc)); + ALOGE("could not open keymaster device in %s (%s)", KEYSTORE_HARDWARE_MODULE_ID, + strerror(-rc)); goto err; } @@ -90,10 +89,9 @@ err: } /* Should we use keymaster? */ -static int keymaster_check_compatibility_old() -{ - keymaster0_device_t *keymaster0_dev = 0; - keymaster1_device_t *keymaster1_dev = 0; +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)) { @@ -114,8 +112,7 @@ static int keymaster_check_compatibility_old() // 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) { + if (keymaster0_dev->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_3) { rc = 0; goto out; } @@ -136,11 +133,10 @@ out: } /* Create a new keymaster key and store it in this footer */ -static int keymaster_create_key_old(struct crypt_mnt_ftr *ftr) -{ +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; + keymaster0_device_t* keymaster0_dev = 0; + keymaster1_device_t* keymaster1_dev = 0; if (ftr->keymaster_blob_size) { SLOGI("Already have key"); @@ -177,11 +173,10 @@ static int keymaster_create_key_old(struct crypt_mnt_ftr *ftr) /* 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_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 */); + 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; @@ -190,15 +185,13 @@ static int keymaster_create_key_old(struct crypt_mnt_ftr *ftr) key = (uint8_t*)key_blob.key_material; key_size = key_blob.key_material_size; - } - else if (keymaster0_dev) { + } 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)) { + if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, ¶ms, &key, &key_size)) { SLOGE("Failed to generate keypair"); rc = -1; goto out; @@ -219,24 +212,19 @@ static int keymaster_create_key_old(struct crypt_mnt_ftr *ftr) ftr->keymaster_blob_size = key_size; out: - if (keymaster0_dev) - keymaster0_close(keymaster0_dev); - if (keymaster1_dev) - keymaster1_close(keymaster1_dev); + 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) -{ +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; + 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); @@ -284,32 +272,25 @@ static int keymaster_sign_object_old(struct crypt_mnt_ftr *ftr, 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); + 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_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_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); + 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); + 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); @@ -317,11 +298,10 @@ static int keymaster_sign_object_old(struct crypt_mnt_ftr *ftr, goto out; } - keymaster_blob_t input = { to_sign, to_sign_size }; + 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 */); + 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; @@ -337,8 +317,7 @@ static int keymaster_sign_object_old(struct crypt_mnt_ftr *ftr, keymaster_blob_t tmp_sig; error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */, - NULL /* verify signature */, NULL /* out_params */, - &tmp_sig); + NULL /* verify signature */, NULL /* out_params */, &tmp_sig); if (error != KM_ERROR_OK) { SLOGE("Error finishing keymaster signature transaction: %d", error); rc = -1; @@ -353,19 +332,15 @@ static int keymaster_sign_object_old(struct crypt_mnt_ftr *ftr, goto out; } - out: - if (keymaster1_dev) - keymaster1_close(keymaster1_dev); - if (keymaster0_dev) - keymaster0_close(keymaster0_dev); +out: + if (keymaster1_dev) keymaster1_close(keymaster1_dev); + if (keymaster0_dev) keymaster0_close(keymaster0_dev); - return rc; + return rc; } - /* Should we use keymaster? */ -static int keymaster_check_compatibility_new() -{ +static int keymaster_check_compatibility_new() { return keymaster_compatibility_cryptfs_scrypt(); } @@ -394,12 +369,9 @@ static int keymaster_create_key_new(struct crypt_mnt_ftr *ftr) #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) -{ +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); @@ -443,12 +415,10 @@ static int keymaster_sign_object_new(struct crypt_mnt_ftr *ftr, namespace android { class CryptFsTest : public testing::Test { -protected: - virtual void SetUp() { - } + protected: + virtual void SetUp() {} - virtual void TearDown() { - } + virtual void TearDown() {} }; TEST_F(CryptFsTest, ScryptHidlizationEquivalenceTest) { @@ -458,8 +428,8 @@ TEST_F(CryptFsTest, ScryptHidlizationEquivalenceTest) { ASSERT_EQ(0, keymaster_create_key_old(&ftr)); - uint8_t *sig1 = nullptr; - uint8_t *sig2 = nullptr; + uint8_t* sig1 = nullptr; + uint8_t* sig2 = nullptr; size_t sig_size1 = 123456789; size_t sig_size2 = 123456789; uint8_t object[] = "the object"; @@ -477,4 +447,4 @@ TEST_F(CryptFsTest, ScryptHidlizationEquivalenceTest) { free(sig2); } -} +} // namespace android diff --git a/tests/Utils_test.cpp b/tests/Utils_test.cpp index ab9809e..e16cbac 100644 --- a/tests/Utils_test.cpp +++ b/tests/Utils_test.cpp @@ -21,8 +21,7 @@ namespace android { namespace vold { -class UtilsTest : public testing::Test { -}; +class UtilsTest : public testing::Test {}; TEST_F(UtilsTest, FindValueTest) { std::string tmp; @@ -40,5 +39,5 @@ TEST_F(UtilsTest, FindValueTest) { ASSERT_EQ("BAZ", tmp); } -} -} +} // namespace vold +} // namespace android diff --git a/tests/cryptfs_test.cpp b/tests/cryptfs_test.cpp index 6875c0f..2093768 100644 --- a/tests/cryptfs_test.cpp +++ b/tests/cryptfs_test.cpp @@ -21,12 +21,10 @@ namespace android { class CryptfsTest : public testing::Test { -protected: - virtual void SetUp() { - } + protected: + virtual void SetUp() {} - virtual void TearDown() { - } + virtual void TearDown() {} }; TEST_F(CryptfsTest, MatchMultiEntryTest) { @@ -51,4 +49,4 @@ TEST_F(CryptfsTest, MatchMultiEntryTest) { ASSERT_EQ(0, match_multi_entry("foo_2", "bar", 0)); } -} +} // namespace android diff --git a/vdc.cpp b/vdc.cpp index 3c449ae..f49d6b8 100644 --- a/vdc.cpp +++ b/vdc.cpp @@ -14,15 +14,14 @@ * limitations under the License. */ -#include -#include -#include -#include -#include #include #include -#include #include +#include +#include +#include +#include +#include #include #include @@ -38,7 +37,7 @@ #include -static void usage(char *progname); +static void usage(char* progname); static android::sp getServiceAggressive() { android::sp res; @@ -50,7 +49,7 @@ static android::sp getServiceAggressive() { LOG(VERBOSE) << "Waited " << (i * 10) << "ms for vold"; break; } - usleep(10000); // 10ms + usleep(10000); // 10ms } return res; } @@ -112,6 +111,6 @@ int main(int argc, char** argv) { return 0; } -static void usage(char *progname) { +static void usage(char* progname) { LOG(INFO) << "Usage: " << progname << " [--wait] [args...]"; }