Merge "Support emulator's virtio-blk based SD card" into nyc-dev
diff --git a/Ext4Crypt.cpp b/Ext4Crypt.cpp
index fdc0197..3a31861 100644
--- a/Ext4Crypt.cpp
+++ b/Ext4Crypt.cpp
@@ -22,25 +22,25 @@
#include <iomanip>
#include <map>
#include <set>
-#include <string>
#include <sstream>
+#include <string>
-#include <stdio.h>
-#include <errno.h>
-#include <dirent.h>
-#include <sys/mount.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
#include <cutils/properties.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
#include <openssl/sha.h>
#include <selinux/android.h>
+#include <stdio.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
#include <private/android_filesystem_config.h>
-#include "key_control.h"
#include "cryptfs.h"
#include "ext4_crypt.h"
+#include "key_control.h"
#define EMULATED_USES_SELINUX 0
@@ -58,38 +58,38 @@
static constexpr int FLAG_STORAGE_CE = 1 << 1;
namespace {
- const std::string device_key_dir = std::string() + DATA_MNT_POINT + "/unencrypted";
- const std::string device_key_path = device_key_dir + "/key";
- const std::string device_key_temp = device_key_dir + "/temp";
+const std::string device_key_dir = std::string() + DATA_MNT_POINT + "/unencrypted";
+const std::string device_key_path = device_key_dir + "/key";
+const std::string device_key_temp = device_key_dir + "/temp";
- const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
- const std::string user_key_temp = user_key_dir + "/temp";
+const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
+const std::string user_key_temp = user_key_dir + "/temp";
- bool s_global_de_initialized = false;
+bool s_global_de_initialized = false;
- // Some users are ephemeral, don't try to wipe their keys from disk
- std::set<userid_t> s_ephemeral_users;
+// Some users are ephemeral, don't try to wipe their keys from disk
+std::set<userid_t> s_ephemeral_users;
- // Map user ids to key references
- std::map<userid_t, std::string> s_de_key_raw_refs;
- std::map<userid_t, std::string> s_ce_key_raw_refs;
- // TODO abolish this map. Keys should not be long-lived in user memory, only kernel memory.
- // See b/26948053
- std::map<userid_t, std::string> s_ce_keys;
+// Map user ids to key references
+std::map<userid_t, std::string> s_de_key_raw_refs;
+std::map<userid_t, std::string> s_ce_key_raw_refs;
+// TODO abolish this map. Keys should not be long-lived in user memory, only kernel memory.
+// See b/26948053
+std::map<userid_t, std::string> s_ce_keys;
- // ext4enc:TODO get this const from somewhere good
- const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
+// ext4enc:TODO get this const from somewhere good
+const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
- // ext4enc:TODO Include structure from somewhere sensible
- // MUST be in sync with ext4_crypto.c in kernel
- constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
- constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
- constexpr int EXT4_MAX_KEY_SIZE = 64;
- struct ext4_encryption_key {
- uint32_t mode;
- char raw[EXT4_MAX_KEY_SIZE];
- uint32_t size;
- };
+// ext4enc:TODO Include structure from somewhere sensible
+// MUST be in sync with ext4_crypto.c in kernel
+constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
+constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
+constexpr int EXT4_MAX_KEY_SIZE = 64;
+struct ext4_encryption_key {
+ uint32_t mode;
+ char raw[EXT4_MAX_KEY_SIZE];
+ uint32_t size;
+};
}
// TODO replace with proper function to test for file encryption
@@ -108,8 +108,7 @@
}
// Get raw keyref - used to make keyname and to pass to ioctl
-static std::string generate_key_ref(const char* key, int length)
-{
+static std::string generate_key_ref(const char* key, int length) {
SHA512_CTX c;
SHA512_Init(&c);
@@ -122,58 +121,60 @@
unsigned char key_ref2[SHA512_DIGEST_LENGTH];
SHA512_Final(key_ref2, &c);
+ static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
+ "Hash too short for descriptor");
return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
}
-static bool fill_key(const std::string& key, ext4_encryption_key& ext4_key)
-{
+static bool fill_key(const std::string& key, ext4_encryption_key* ext4_key) {
if (key.size() != EXT4_AES_256_XTS_KEY_SIZE) {
LOG(ERROR) << "Wrong size key " << key.size();
return false;
}
- static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key.raw),
- "Key too long!");
- ext4_key.mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
- ext4_key.size = key.size();
- memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
- memcpy(ext4_key.raw, key.data(), key.size());
+ static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key->raw), "Key too long!");
+ ext4_key->mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
+ ext4_key->size = key.size();
+ memset(ext4_key->raw, 0, sizeof(ext4_key->raw));
+ memcpy(ext4_key->raw, key.data(), key.size());
return true;
}
-static std::string keyname(const std::string &raw_ref)
-{
+static std::string keyname(const std::string& raw_ref) {
std::ostringstream o;
o << "ext4:";
- for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
- o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
+ for (auto i : raw_ref) {
+ o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
}
return o.str();
}
// Get the keyring we store all keys in
-static key_serial_t e4crypt_keyring()
-{
- return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
+static bool e4crypt_keyring(key_serial_t* device_keyring) {
+ *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
+ if (*device_keyring == -1) {
+ PLOG(ERROR) << "Unable to find device keyring";
+ return false;
+ }
+ return true;
}
// Install password into global keyring
// Return raw key reference for use in policy
-static bool install_key(const std::string &key, std::string &raw_ref)
-{
+static bool install_key(const std::string& key, std::string* raw_ref) {
ext4_encryption_key ext4_key;
- if (!fill_key(key, ext4_key)) return false;
- raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
- auto ref = keyname(raw_ref);
- key_serial_t device_keyring = e4crypt_keyring();
- key_serial_t key_id = add_key("logon", ref.c_str(),
- (void*)&ext4_key, sizeof(ext4_key),
- device_keyring);
+ if (!fill_key(key, &ext4_key)) return false;
+ *raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
+ auto ref = keyname(*raw_ref);
+ key_serial_t device_keyring;
+ if (!e4crypt_keyring(&device_keyring)) return false;
+ key_serial_t key_id =
+ add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
if (key_id == -1) {
PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
return false;
}
- LOG(INFO) << "Added key " << key_id << " (" << ref << ") to keyring "
- << device_keyring << " in process " << getpid();
+ LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
+ << " in process " << getpid();
return true;
}
@@ -185,21 +186,21 @@
return StringPrintf("%s/ce/%d/current", user_key_dir.c_str(), user_id);
}
-static bool read_and_install_user_ce_key(
- userid_t user_id, const android::vold::KeyAuthentication &auth) {
+static bool read_and_install_user_ce_key(userid_t user_id,
+ const android::vold::KeyAuthentication& auth) {
if (s_ce_key_raw_refs.count(user_id) != 0) return true;
const auto ce_key_path = get_ce_key_path(user_id);
std::string ce_key;
- if (!android::vold::retrieveKey(ce_key_path, auth, ce_key)) return false;
+ if (!android::vold::retrieveKey(ce_key_path, auth, &ce_key)) return false;
std::string ce_raw_ref;
- if (!install_key(ce_key, ce_raw_ref)) return false;
+ if (!install_key(ce_key, &ce_raw_ref)) return false;
s_ce_keys[user_id] = ce_key;
s_ce_key_raw_refs[user_id] = ce_raw_ref;
LOG(DEBUG) << "Installed ce key for user " << user_id;
return true;
}
-static bool prepare_dir(const std::string &dir, mode_t mode, uid_t uid, gid_t gid) {
+static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
LOG(DEBUG) << "Preparing: " << dir;
if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
PLOG(ERROR) << "Failed to prepare " << dir;
@@ -208,8 +209,8 @@
return true;
}
-static bool random_key(std::string &key) {
- if (android::vold::ReadRandomBytes(EXT4_AES_256_XTS_KEY_SIZE, key) != 0) {
+static bool random_key(std::string* key) {
+ if (android::vold::ReadRandomBytes(EXT4_AES_256_XTS_KEY_SIZE, *key) != 0) {
// TODO status_t plays badly with PLOG, fix it.
LOG(ERROR) << "Random read failed";
return false;
@@ -217,20 +218,20 @@
return true;
}
-static bool path_exists(const std::string &path) {
+static bool path_exists(const std::string& path) {
return access(path.c_str(), F_OK) == 0;
}
// NB this assumes that there is only one thread listening for crypt commands, because
// it creates keys in a fixed location.
-static bool store_key(const std::string &key_path, const std::string &tmp_path,
- const android::vold::KeyAuthentication &auth, const std::string &key) {
+static bool store_key(const std::string& key_path, const std::string& tmp_path,
+ const android::vold::KeyAuthentication& auth, const std::string& key) {
if (path_exists(key_path)) {
LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
return false;
}
if (path_exists(tmp_path)) {
- android::vold::destroyKey(tmp_path);
+ android::vold::destroyKey(tmp_path); // May be partially created so ignore errors
}
if (!android::vold::storeKey(tmp_path, auth, key)) return false;
if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
@@ -243,8 +244,8 @@
static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
std::string de_key, ce_key;
- if (!random_key(de_key)) return false;
- if (!random_key(ce_key)) return false;
+ if (!random_key(&de_key)) return false;
+ if (!random_key(&ce_key)) return false;
if (create_ephemeral) {
// If the key should be created as ephemeral, don't store it.
s_ephemeral_users.insert(user_id);
@@ -257,28 +258,28 @@
kEmptyAuthentication, ce_key)) return false;
}
std::string de_raw_ref;
- if (!install_key(de_key, de_raw_ref)) return false;
+ if (!install_key(de_key, &de_raw_ref)) return false;
s_de_key_raw_refs[user_id] = de_raw_ref;
std::string ce_raw_ref;
- if (!install_key(ce_key, ce_raw_ref)) return false;
+ if (!install_key(ce_key, &ce_raw_ref)) return false;
s_ce_keys[user_id] = ce_key;
s_ce_key_raw_refs[user_id] = ce_raw_ref;
LOG(DEBUG) << "Created keys for user " << user_id;
return true;
}
-static bool lookup_key_ref(const std::map<userid_t, std::string> &key_map,
- userid_t user_id, std::string &raw_ref) {
+static bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
+ std::string* raw_ref) {
auto refi = key_map.find(user_id);
if (refi == key_map.end()) {
LOG(ERROR) << "Cannot find key for " << user_id;
return false;
}
- raw_ref = refi->second;
+ *raw_ref = refi->second;
return true;
}
-static bool ensure_policy(const std::string &raw_ref, const std::string& path) {
+static bool ensure_policy(const std::string& raw_ref, const std::string& path) {
if (e4crypt_policy_ensure(path.c_str(), raw_ref.data(), raw_ref.size()) != 0) {
LOG(ERROR) << "Failed to set policy on: " << path;
return false;
@@ -286,17 +287,16 @@
return true;
}
-static bool is_numeric(const char *name) {
- for (const char *p = name; *p != '\0'; p++) {
- if (!isdigit(*p))
- return false;
+static bool is_numeric(const char* name) {
+ for (const char* p = name; *p != '\0'; p++) {
+ if (!isdigit(*p)) return false;
}
return true;
}
static bool load_all_de_keys() {
auto de_dir = user_key_dir + "/de";
- auto dirp = std::unique_ptr<DIR, int(*)(DIR*)>(opendir(de_dir.c_str()), closedir);
+ auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
if (!dirp) {
PLOG(ERROR) << "Unable to read de key directory";
return false;
@@ -319,9 +319,9 @@
if (s_de_key_raw_refs.count(user_id) == 0) {
auto key_path = de_dir + "/" + entry->d_name;
std::string key;
- if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, key)) return false;
+ if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
std::string raw_ref;
- if (!install_key(key, raw_ref)) return false;
+ if (!install_key(key, &raw_ref)) return false;
s_de_key_raw_refs[user_id] = raw_ref;
LOG(DEBUG) << "Installed de key for user " << user_id;
}
@@ -331,8 +331,7 @@
return true;
}
-bool e4crypt_initialize_global_de()
-{
+bool e4crypt_initialize_global_de() {
LOG(INFO) << "e4crypt_initialize_global_de";
if (s_global_de_initialized) {
@@ -343,16 +342,16 @@
std::string device_key;
if (path_exists(device_key_path)) {
if (!android::vold::retrieveKey(device_key_path,
- kEmptyAuthentication, device_key)) return false;
+ kEmptyAuthentication, &device_key)) return false;
} else {
LOG(INFO) << "Creating new key";
- if (!random_key(device_key)) return false;
+ if (!random_key(&device_key)) return false;
if (!store_key(device_key_path, device_key_temp,
kEmptyAuthentication, device_key)) return false;
}
std::string device_key_ref;
- if (!install_key(device_key, device_key_ref)) {
+ if (!install_key(device_key, &device_key_ref)) {
LOG(ERROR) << "Failed to install device key";
return false;
}
@@ -377,10 +376,10 @@
auto ce_path = get_ce_key_path(0);
if (!path_exists(de_path) || !path_exists(ce_path)) {
if (path_exists(de_path)) {
- android::vold::destroyKey(de_path); // Ignore failure
+ android::vold::destroyKey(de_path); // May be partially created so ignore errors
}
if (path_exists(ce_path)) {
- android::vold::destroyKey(ce_path); // Ignore failure
+ android::vold::destroyKey(ce_path); // May be partially created so ignore errors
}
if (!create_and_install_user_keys(0, false)) return false;
}
@@ -412,21 +411,22 @@
}
// FIXME test for existence of key that is not loaded yet
if (s_ce_key_raw_refs.count(user_id) != 0) {
- LOG(ERROR) << "Already exists, can't e4crypt_vold_create_user_key for "
- << user_id << " serial " << serial;
+ LOG(ERROR) << "Already exists, can't e4crypt_vold_create_user_key for " << user_id
+ << " serial " << serial;
// FIXME should we fail the command?
return true;
}
if (!create_and_install_user_keys(user_id, ephemeral)) {
return false;
}
- // TODO: create second key for user_de data
return true;
}
-static bool evict_key(const std::string &raw_ref) {
+static bool evict_key(const std::string& raw_ref) {
auto ref = keyname(raw_ref);
- auto key_serial = keyctl_search(e4crypt_keyring(), "logon", ref.c_str(), 0);
+ key_serial_t device_keyring;
+ if (!e4crypt_keyring(&device_keyring)) return false;
+ auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
if (keyctl_revoke(key_serial) != 0) {
PLOG(ERROR) << "Failed to revoke key with serial " << key_serial << " ref " << ref;
return false;
@@ -443,9 +443,9 @@
bool success = true;
s_ce_keys.erase(user_id);
std::string raw_ref;
- success &= lookup_key_ref(s_ce_key_raw_refs, user_id, raw_ref) && evict_key(raw_ref);
+ success &= lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref) && evict_key(raw_ref);
s_ce_key_raw_refs.erase(user_id);
- success &= lookup_key_ref(s_de_key_raw_refs, user_id, raw_ref) && evict_key(raw_ref);
+ success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && evict_key(raw_ref);
s_de_key_raw_refs.erase(user_id);
auto it = s_ephemeral_users.find(user_id);
if (it != s_ephemeral_users.end()) {
@@ -487,34 +487,32 @@
return true;
}
-static bool parse_hex(const char *hex, std::string &result) {
+static bool parse_hex(const char* hex, std::string* result) {
if (strcmp("!", hex) == 0) {
- result = "";
+ *result = "";
return true;
}
- if (android::vold::HexToStr(hex, result) != 0) {
- LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
+ if (android::vold::HexToStr(hex, *result) != 0) {
+ LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
return false;
}
return true;
}
-bool e4crypt_change_user_key(userid_t user_id, int serial,
- const char* token_hex, const char* old_secret_hex, const char* new_secret_hex) {
- LOG(DEBUG) << "e4crypt_change_user_key " << user_id << " serial=" << serial <<
- " token_present=" << (strcmp(token_hex, "!") != 0);
+bool e4crypt_change_user_key(userid_t user_id, int serial, const char* token_hex,
+ const char* old_secret_hex, const char* new_secret_hex) {
+ LOG(DEBUG) << "e4crypt_change_user_key " << user_id << " serial=" << serial
+ << " token_present=" << (strcmp(token_hex, "!") != 0);
if (!e4crypt_is_native()) return true;
if (s_ephemeral_users.count(user_id) != 0) return true;
std::string token, old_secret, new_secret;
- if (!parse_hex(token_hex, token)) return false;
- if (!parse_hex(old_secret_hex, old_secret)) return false;
- if (!parse_hex(new_secret_hex, new_secret)) return false;
- auto old_auth = old_secret.empty()
- ? kEmptyAuthentication
- : android::vold::KeyAuthentication(token, old_secret);
- auto new_auth = new_secret.empty()
- ? kEmptyAuthentication
- : android::vold::KeyAuthentication(token, new_secret);
+ if (!parse_hex(token_hex, &token)) return false;
+ if (!parse_hex(old_secret_hex, &old_secret)) return false;
+ if (!parse_hex(new_secret_hex, &new_secret)) return false;
+ auto old_auth = old_secret.empty() ? kEmptyAuthentication
+ : android::vold::KeyAuthentication(token, old_secret);
+ auto new_auth = new_secret.empty() ? kEmptyAuthentication
+ : android::vold::KeyAuthentication(token, new_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;
@@ -523,7 +521,7 @@
auto ce_key = it->second;
auto ce_key_path = get_ce_key_path(user_id);
std::string trial_key;
- if (!android::vold::retrieveKey(ce_key_path, old_auth, trial_key)) {
+ if (!android::vold::retrieveKey(ce_key_path, old_auth, &trial_key)) {
LOG(WARNING) << "change_user_key wasn't given enough info to reconstruct the key";
} else if (ce_key != trial_key) {
LOG(WARNING) << "Reconstructed key != stored key";
@@ -534,18 +532,18 @@
}
// TODO: rename to 'install' for consistency, and take flags to know which keys to install
-bool e4crypt_unlock_user_key(userid_t user_id, int serial,
- const char* token_hex, const char* secret_hex) {
- LOG(DEBUG) << "e4crypt_unlock_user_key " << user_id << " serial=" << serial <<
- " token_present=" << (strcmp(token_hex, "!") != 0);
+bool e4crypt_unlock_user_key(userid_t user_id, int serial, const char* token_hex,
+ const char* secret_hex) {
+ LOG(DEBUG) << "e4crypt_unlock_user_key " << user_id << " serial=" << serial
+ << " token_present=" << (strcmp(token_hex, "!") != 0);
if (e4crypt_is_native()) {
if (s_ce_key_raw_refs.count(user_id) != 0) {
LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
return true;
}
std::string token, secret;
- if (!parse_hex(token_hex, token)) return false;
- if (!parse_hex(secret_hex, secret)) return false;
+ if (!parse_hex(token_hex, &token)) return false;
+ if (!parse_hex(secret_hex, &secret)) return false;
android::vold::KeyAuthentication auth(token, secret);
if (!read_and_install_user_ce_key(user_id, auth)) {
LOG(ERROR) << "Couldn't read key for " << user_id;
@@ -556,9 +554,9 @@
// unlock directories when not in emulation mode, to bring devices
// back into a known-good state.
if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
- !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
- !emulated_unlock(android::vold::BuildDataMediaPath(nullptr, user_id), 0770) ||
- !emulated_unlock(android::vold::BuildDataUserPath(nullptr, user_id), 0771)) {
+ !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
+ !emulated_unlock(android::vold::BuildDataMediaPath(nullptr, user_id), 0770) ||
+ !emulated_unlock(android::vold::BuildDataUserPath(nullptr, user_id), 0771)) {
LOG(ERROR) << "Failed to unlock user " << user_id;
return false;
}
@@ -573,9 +571,9 @@
} else if (e4crypt_is_emulated()) {
// When in emulation mode, we just use chmod
if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
- !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
- !emulated_lock(android::vold::BuildDataMediaPath(nullptr, user_id)) ||
- !emulated_lock(android::vold::BuildDataUserPath(nullptr, user_id))) {
+ !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
+ !emulated_lock(android::vold::BuildDataMediaPath(nullptr, user_id)) ||
+ !emulated_lock(android::vold::BuildDataUserPath(nullptr, user_id))) {
LOG(ERROR) << "Failed to lock user " << user_id;
return false;
}
@@ -584,10 +582,10 @@
return true;
}
-bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id,
- int serial, int flags) {
+bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial,
+ int flags) {
LOG(DEBUG) << "e4crypt_prepare_user_storage for volume " << escape_null(volume_uuid)
- << ", user " << user_id << ", serial " << serial << ", flags " << flags;
+ << ", user " << user_id << ", serial " << serial << ", flags " << flags;
if (flags & FLAG_STORAGE_DE) {
auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
@@ -603,7 +601,7 @@
// For now, we do not store profiles on the adopted storage.
auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
auto foreign_dex_profiles_de_path =
- android::vold::BuildDataProfilesForeignDexDePath(user_id);
+ android::vold::BuildDataProfilesForeignDexDePath(user_id);
if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
if (!prepare_dir(foreign_dex_profiles_de_path, 0773, AID_SYSTEM, AID_SYSTEM)) {
return false;
@@ -612,7 +610,7 @@
if (e4crypt_is_native()) {
std::string de_raw_ref;
- if (!lookup_key_ref(s_de_key_raw_refs, user_id, de_raw_ref)) return false;
+ if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_raw_ref)) return false;
if (!ensure_policy(de_raw_ref, system_de_path)) return false;
if (!ensure_policy(de_raw_ref, misc_de_path)) return false;
if (!ensure_policy(de_raw_ref, user_de_path)) return false;
@@ -634,7 +632,7 @@
if (e4crypt_is_native()) {
std::string ce_raw_ref;
- if (!lookup_key_ref(s_ce_key_raw_refs, user_id, ce_raw_ref)) return false;
+ if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_raw_ref)) return false;
if (!ensure_policy(ce_raw_ref, system_ce_path)) return false;
if (!ensure_policy(ce_raw_ref, misc_ce_path)) return false;
if (!ensure_policy(ce_raw_ref, media_ce_path)) return false;
diff --git a/Ext4Crypt.h b/Ext4Crypt.h
index f183c58..dff2953 100644
--- a/Ext4Crypt.h
+++ b/Ext4Crypt.h
@@ -28,14 +28,12 @@
bool e4crypt_init_user0();
bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral);
bool e4crypt_destroy_user_key(userid_t user_id);
-bool e4crypt_change_user_key(userid_t user_id, int serial,
- const char* token, const char* old_secret, const char* new_secret);
+bool e4crypt_change_user_key(userid_t user_id, int serial, const char* token,
+ const char* old_secret, const char* new_secret);
-bool e4crypt_unlock_user_key(userid_t user_id, int serial,
- const char* token, const char* secret);
+bool e4crypt_unlock_user_key(userid_t user_id, int serial, const char* token, const char* secret);
bool e4crypt_lock_user_key(userid_t user_id);
-bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id,
- int serial, int flags);
+bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial, int flags);
__END_DECLS
diff --git a/KeyStorage.cpp b/KeyStorage.cpp
index 2338f23..f2b16e3 100644
--- a/KeyStorage.cpp
+++ b/KeyStorage.cpp
@@ -35,25 +35,26 @@
#include <cutils/properties.h>
+#include <hardware/hw_auth_token.h>
+
#include <keymaster/authorization_set.h>
extern "C" {
#include "crypto_scrypt.h"
-
}
namespace android {
namespace vold {
-const KeyAuthentication kEmptyAuthentication { "", "" };
+const KeyAuthentication kEmptyAuthentication{"", ""};
static constexpr size_t AES_KEY_BYTES = 32;
static constexpr size_t GCM_NONCE_BYTES = 12;
static constexpr size_t GCM_MAC_BYTES = 16;
-static constexpr size_t SALT_BYTES = 1<<4;
-static constexpr size_t SECDISCARDABLE_BYTES = 1<<14;
-static constexpr size_t STRETCHED_BYTES = 1<<6;
+static constexpr size_t SALT_BYTES = 1 << 4;
+static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
+static constexpr size_t STRETCHED_BYTES = 1 << 6;
static const char* kCurrentVersion = "1";
static const char* kRmPath = "/system/bin/rm";
@@ -70,14 +71,14 @@
static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
if (actual != expected) {
- LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected
- << " got " << actual;
+ LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
+ << actual;
return false;
}
return true;
}
-static std::string hashSecdiscardable(const std::string &secdiscardable) {
+static std::string hashSecdiscardable(const std::string& secdiscardable) {
SHA512_CTX c;
SHA512_Init(&c);
@@ -89,39 +90,56 @@
SHA512_Update(&c, secdiscardableHashingPrefix.data(), secdiscardableHashingPrefix.size());
SHA512_Update(&c, secdiscardable.data(), secdiscardable.size());
std::string res(SHA512_DIGEST_LENGTH, '\0');
- SHA512_Final(reinterpret_cast<uint8_t *>(&res[0]), &c);
+ SHA512_Final(reinterpret_cast<uint8_t*>(&res[0]), &c);
return res;
}
-static bool generateKeymasterKey(Keymaster &keymaster,
- const keymaster::AuthorizationSet &extraParams,
- std::string &key) {
- auto params = keymaster::AuthorizationSetBuilder()
- .AesEncryptionKey(AES_KEY_BYTES * 8)
- .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
- .Authorization(keymaster::TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
- .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
- .Authorization(keymaster::TAG_NO_AUTH_REQUIRED) // FIXME integrate with gatekeeper
- .build();
- params.push_back(extraParams);
- return keymaster.generateKey(params, key);
+static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
+ const std::string& appId, std::string* key) {
+ auto paramBuilder = keymaster::AuthorizationSetBuilder()
+ .AesEncryptionKey(AES_KEY_BYTES * 8)
+ .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
+ .Authorization(keymaster::TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
+ .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE);
+ addStringParam(¶mBuilder, keymaster::TAG_APPLICATION_ID, appId);
+ if (auth.token.empty()) {
+ LOG(DEBUG) << "Creating key that doesn't need auth token";
+ paramBuilder.Authorization(keymaster::TAG_NO_AUTH_REQUIRED);
+ } else {
+ LOG(DEBUG) << "Auth token required for key";
+ if (auth.token.size() != sizeof(hw_auth_token_t)) {
+ LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
+ << auth.token.size() << " bytes";
+ return false;
+ }
+ const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
+ paramBuilder.Authorization(keymaster::TAG_USER_SECURE_ID, at->user_id);
+ paramBuilder.Authorization(keymaster::TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD);
+ paramBuilder.Authorization(keymaster::TAG_AUTH_TIMEOUT, 5);
+ }
+ return keymaster.generateKey(paramBuilder.build(), key);
}
-static bool encryptWithKeymasterKey(
- Keymaster &keymaster,
- const std::string &key,
- const keymaster::AuthorizationSet &extraParams,
- const std::string &message,
- std::string &ciphertext) {
- // FIXME fix repetition
- auto params = keymaster::AuthorizationSetBuilder()
- .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
- .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
- .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
- .build();
- params.push_back(extraParams);
+static keymaster::AuthorizationSetBuilder beginParams(const KeyAuthentication& auth,
+ const std::string& appId) {
+ auto paramBuilder = keymaster::AuthorizationSetBuilder()
+ .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
+ .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
+ .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE);
+ addStringParam(¶mBuilder, keymaster::TAG_APPLICATION_ID, appId);
+ if (!auth.token.empty()) {
+ LOG(DEBUG) << "Supplying auth token to Keymaster";
+ addStringParam(¶mBuilder, keymaster::TAG_AUTH_TOKEN, auth.token);
+ }
+ return paramBuilder;
+}
+
+static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& key,
+ const KeyAuthentication& auth, const std::string& appId,
+ const std::string& message, std::string* ciphertext) {
+ auto params = beginParams(auth, appId).build();
keymaster::AuthorizationSet outParams;
- auto opHandle = keymaster.begin(KM_PURPOSE_ENCRYPT, key, params, outParams);
+ auto opHandle = keymaster.begin(KM_PURPOSE_ENCRYPT, key, params, &outParams);
if (!opHandle) return false;
keymaster_blob_t nonceBlob;
if (!outParams.GetTagValue(keymaster::TAG_NONCE, &nonceBlob)) {
@@ -129,33 +147,24 @@
return false;
}
// nonceBlob here is just a pointer into existing data, must not be freed
- std::string nonce(reinterpret_cast<const char *>(nonceBlob.data), nonceBlob.data_length);
+ std::string nonce(reinterpret_cast<const char*>(nonceBlob.data), nonceBlob.data_length);
if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
std::string body;
- if (!opHandle.updateCompletely(message, body)) return false;
+ if (!opHandle.updateCompletely(message, &body)) return false;
std::string mac;
- if (!opHandle.finishWithOutput(mac)) return false;
+ if (!opHandle.finishWithOutput(&mac)) return false;
if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
- ciphertext = nonce + body + mac;
+ *ciphertext = nonce + body + mac;
return true;
}
-static bool decryptWithKeymasterKey(
- Keymaster &keymaster, const std::string &key,
- const keymaster::AuthorizationSet &extraParams,
- const std::string &ciphertext,
- std::string &message) {
+static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& key,
+ const KeyAuthentication& auth, const std::string& appId,
+ const std::string& ciphertext, std::string* message) {
auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
- // FIXME fix repetition
- auto params = addStringParam(keymaster::AuthorizationSetBuilder(), keymaster::TAG_NONCE, nonce)
- .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
- .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
- .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
- .build();
- params.push_back(extraParams);
-
+ auto params = addStringParam(beginParams(auth, appId), keymaster::TAG_NONCE, nonce).build();
auto opHandle = keymaster.begin(KM_PURPOSE_DECRYPT, key, params);
if (!opHandle) return false;
if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
@@ -163,18 +172,18 @@
return true;
}
-static bool readFileToString(const std::string &filename, std::string &result) {
- if (!android::base::ReadFileToString(filename, &result)) {
- PLOG(ERROR) << "Failed to read from " << filename;
- return false;
+static bool readFileToString(const std::string& filename, std::string* result) {
+ if (!android::base::ReadFileToString(filename, result)) {
+ PLOG(ERROR) << "Failed to read from " << filename;
+ return false;
}
return true;
}
-static bool writeStringToFile(const std::string &payload, const std::string &filename) {
+static bool writeStringToFile(const std::string& payload, const std::string& filename) {
if (!android::base::WriteStringToFile(payload, filename)) {
- PLOG(ERROR) << "Failed to write to " << filename;
- return false;
+ PLOG(ERROR) << "Failed to write to " << filename;
+ return false;
}
return true;
}
@@ -186,34 +195,33 @@
return std::string() + kStretchPrefix_scrypt + paramstr;
}
-static bool stretchingNeedsSalt(const std::string &stretching) {
+static bool stretchingNeedsSalt(const std::string& stretching) {
return stretching != kStretch_nopassword && stretching != kStretch_none;
}
-static bool stretchSecret(const std::string &stretching, const std::string &secret,
- const std::string &salt, std::string &stretched) {
+static bool stretchSecret(const std::string& stretching, const std::string& secret,
+ const std::string& salt, std::string* stretched) {
if (stretching == kStretch_nopassword) {
if (!secret.empty()) {
- LOG(ERROR) << "Password present but stretching is nopasswd";
+ LOG(WARNING) << "Password present but stretching is nopassword";
// Continue anyway
}
- stretched.clear();
+ stretched->clear();
} else if (stretching == kStretch_none) {
- stretched = secret;
- } else if (std::equal(kStretchPrefix_scrypt.begin(),
- kStretchPrefix_scrypt.end(), stretching.begin())) {
+ *stretched = secret;
+ } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
+ stretching.begin())) {
int Nf, rf, pf;
- if (!parse_scrypt_parameters(
- stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf, &rf, &pf)) {
+ if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
+ &rf, &pf)) {
LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
return false;
}
- stretched.assign(STRETCHED_BYTES, '\0');
- if (crypto_scrypt(
- reinterpret_cast<const uint8_t *>(secret.data()), secret.size(),
- reinterpret_cast<const uint8_t *>(salt.data()), salt.size(),
- 1 << Nf, 1 << rf, 1 << pf,
- reinterpret_cast<uint8_t *>(&stretched[0]), stretched.size()) != 0) {
+ stretched->assign(STRETCHED_BYTES, '\0');
+ if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
+ reinterpret_cast<const uint8_t*>(salt.data()), salt.size(),
+ 1 << Nf, 1 << rf, 1 << pf,
+ reinterpret_cast<uint8_t*>(&(*stretched)[0]), stretched->size()) != 0) {
LOG(ERROR) << "scrypt failed with params: " << stretching;
return false;
}
@@ -224,27 +232,21 @@
return true;
}
-static bool buildParams(const KeyAuthentication &auth, const std::string &stretching,
- const std::string &salt, const std::string &secdiscardable,
- keymaster::AuthorizationSet &result) {
+static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
+ const std::string& salt, const std::string& secdiscardable,
+ std::string* appId) {
std::string stretched;
- if (!stretchSecret(stretching, auth.secret, salt, stretched)) return false;
- auto appId = hashSecdiscardable(secdiscardable) + stretched;
- keymaster::AuthorizationSetBuilder paramBuilder;
- addStringParam(paramBuilder, keymaster::TAG_APPLICATION_ID, appId);
- if (!auth.token.empty()) {
- addStringParam(paramBuilder, keymaster::TAG_AUTH_TOKEN, auth.token);
- }
- result = paramBuilder.build();
+ if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
+ *appId = hashSecdiscardable(secdiscardable) + stretched;
return true;
}
-bool storeKey(const std::string &dir, const KeyAuthentication &auth, const std::string &key) {
+bool storeKey(const std::string& dir, const KeyAuthentication& auth, const std::string& key) {
if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
PLOG(ERROR) << "key mkdir " << dir;
return false;
}
- if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
+ if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
std::string secdiscardable;
if (ReadRandomBytes(SECDISCARDABLE_BYTES, secdiscardable) != OK) {
// TODO status_t plays badly with PLOG, fix it.
@@ -253,82 +255,81 @@
}
if (!writeStringToFile(secdiscardable, dir + "/" + kFn_secdiscardable)) return false;
std::string stretching = auth.secret.empty() ? kStretch_nopassword : getStretching();
- if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
+ if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
std::string salt;
if (stretchingNeedsSalt(stretching)) {
if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
LOG(ERROR) << "Random read failed";
return false;
}
- if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
+ if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
}
- keymaster::AuthorizationSet extraParams;
- if (!buildParams(auth, stretching, salt, secdiscardable, extraParams)) return false;
+ std::string appId;
+ if (!generateAppId(auth, stretching, salt, secdiscardable, &appId)) return false;
Keymaster keymaster;
if (!keymaster) return false;
std::string kmKey;
- if (!generateKeymasterKey(keymaster, extraParams, kmKey)) return false;
- std::string encryptedKey;
- if (!encryptWithKeymasterKey(keymaster, kmKey, extraParams, key, encryptedKey)) return false;
+ if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
+ std::string encryptedKey;
+ if (!encryptWithKeymasterKey(keymaster, kmKey, auth, appId, key, &encryptedKey)) return false;
if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
return true;
}
-bool retrieveKey(const std::string &dir, const KeyAuthentication &auth, std::string &key) {
+bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, std::string* key) {
std::string version;
- if (!readFileToString(dir + "/" + kFn_version, version)) return false;
+ if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
if (version != kCurrentVersion) {
LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
return false;
}
std::string secdiscardable;
- if (!readFileToString(dir + "/" + kFn_secdiscardable, secdiscardable)) return false;
+ if (!readFileToString(dir + "/" + kFn_secdiscardable, &secdiscardable)) return false;
std::string stretching;
- if (!readFileToString(dir + "/" + kFn_stretching, stretching)) return false;
+ if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
std::string salt;
if (stretchingNeedsSalt(stretching)) {
- if (!readFileToString(dir + "/" + kFn_salt, salt)) return false;
+ if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
}
- keymaster::AuthorizationSet extraParams;
- if (!buildParams(auth, stretching, salt, secdiscardable, extraParams)) return false;
+ std::string appId;
+ if (!generateAppId(auth, stretching, salt, secdiscardable, &appId)) return false;
std::string kmKey;
- if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
+ if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
std::string encryptedMessage;
- if (!readFileToString(dir + "/" + kFn_encrypted_key, encryptedMessage)) return false;
+ if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Keymaster keymaster;
if (!keymaster) return false;
- return decryptWithKeymasterKey(keymaster, kmKey, extraParams, encryptedMessage, key);
+ return decryptWithKeymasterKey(keymaster, kmKey, auth, appId, encryptedMessage, key);
}
-static bool deleteKey(const std::string &dir) {
+static bool deleteKey(const std::string& dir) {
std::string kmKey;
- if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
+ if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
Keymaster keymaster;
if (!keymaster) return false;
if (!keymaster.deleteKey(kmKey)) return false;
return true;
}
-static bool secdiscardSecdiscardable(const std::string &dir) {
- if (ForkExecvp(std::vector<std::string> {
- kSecdiscardPath, "--", dir + "/" + kFn_secdiscardable}) != 0) {
+static bool secdiscardSecdiscardable(const std::string& dir) {
+ if (ForkExecvp(
+ std::vector<std::string>{kSecdiscardPath, "--", dir + "/" + kFn_secdiscardable}) != 0) {
LOG(ERROR) << "secdiscard failed";
return false;
}
return true;
}
-static bool recursiveDeleteKey(const std::string &dir) {
- if (ForkExecvp(std::vector<std::string> {
- kRmPath, "-rf", dir}) != 0) {
+static bool recursiveDeleteKey(const std::string& dir) {
+ if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
LOG(ERROR) << "recursive delete failed";
return false;
}
return true;
}
-bool destroyKey(const std::string &dir) {
+bool destroyKey(const std::string& dir) {
bool success = true;
// Try each thing, even if previous things failed.
success &= deleteKey(dir);
diff --git a/KeyStorage.h b/KeyStorage.h
index 54c3b2c..10ed789 100644
--- a/KeyStorage.h
+++ b/KeyStorage.h
@@ -27,8 +27,8 @@
// If "secret" is nonempty, it is appended to the application-specific
// binary needed to unlock.
class KeyAuthentication {
-public:
- KeyAuthentication(std::string t, std::string s): token {t}, secret {s} {};
+ public:
+ KeyAuthentication(std::string t, std::string s) : token{t}, secret{s} {};
const std::string token;
const std::string secret;
};
@@ -39,13 +39,13 @@
// in such a way that it can only be retrieved via Keymaster and
// can be securely deleted.
// It's safe to move/rename the directory after creation.
-bool storeKey(const std::string &dir, const KeyAuthentication &auth, const std::string &key);
+bool storeKey(const std::string& dir, const KeyAuthentication& auth, const std::string& key);
// Retrieve the key from the named directory.
-bool retrieveKey(const std::string &dir, const KeyAuthentication &auth, std::string &key);
+bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, std::string* key);
// Securely destroy the key stored in the named directory and delete the directory.
-bool destroyKey(const std::string &dir);
+bool destroyKey(const std::string& dir);
} // namespace vold
} // namespace android
diff --git a/Keymaster.cpp b/Keymaster.cpp
index 0fde8fa..222b930 100644
--- a/Keymaster.cpp
+++ b/Keymaster.cpp
@@ -21,25 +21,23 @@
namespace android {
namespace vold {
-bool KeymasterOperation::updateCompletely(
- const std::string &input,
- std::string &output) {
- output.clear();
+bool KeymasterOperation::updateCompletely(const std::string& input, std::string* output) {
+ output->clear();
auto it = input.begin();
while (it != input.end()) {
size_t toRead = static_cast<size_t>(input.end() - it);
- keymaster_blob_t inputBlob {reinterpret_cast<const uint8_t *>(&*it), toRead};
+ keymaster_blob_t inputBlob{reinterpret_cast<const uint8_t*>(&*it), toRead};
keymaster_blob_t outputBlob;
size_t inputConsumed;
- auto error = mDevice->update(mDevice, mOpHandle,
- nullptr, &inputBlob, &inputConsumed, nullptr, &outputBlob);
+ auto error = mDevice->update(mDevice, mOpHandle, nullptr, &inputBlob, &inputConsumed,
+ nullptr, &outputBlob);
if (error != KM_ERROR_OK) {
LOG(ERROR) << "update failed, code " << error;
mDevice = nullptr;
return false;
}
- output.append(reinterpret_cast<const char *>(outputBlob.data), outputBlob.data_length);
- free(const_cast<uint8_t *>(outputBlob.data));
+ output->append(reinterpret_cast<const char*>(outputBlob.data), outputBlob.data_length);
+ free(const_cast<uint8_t*>(outputBlob.data));
if (inputConsumed > toRead) {
LOG(ERROR) << "update reported too much input consumed";
mDevice = nullptr;
@@ -51,8 +49,7 @@
}
bool KeymasterOperation::finish() {
- auto error = mDevice->finish(mDevice, mOpHandle,
- nullptr, nullptr, nullptr, nullptr);
+ auto error = mDevice->finish(mDevice, mOpHandle, nullptr, nullptr, nullptr, nullptr);
mDevice = nullptr;
if (error != KM_ERROR_OK) {
LOG(ERROR) << "finish failed, code " << error;
@@ -61,23 +58,22 @@
return true;
}
-bool KeymasterOperation::finishWithOutput(std::string &output) {
+bool KeymasterOperation::finishWithOutput(std::string* output) {
keymaster_blob_t outputBlob;
- auto error = mDevice->finish(mDevice, mOpHandle,
- nullptr, nullptr, nullptr, &outputBlob);
+ auto error = mDevice->finish(mDevice, mOpHandle, nullptr, nullptr, nullptr, &outputBlob);
mDevice = nullptr;
if (error != KM_ERROR_OK) {
LOG(ERROR) << "finish failed, code " << error;
return false;
}
- output.assign(reinterpret_cast<const char *>(outputBlob.data), outputBlob.data_length);
- free(const_cast<uint8_t *>(outputBlob.data));
+ output->assign(reinterpret_cast<const char*>(outputBlob.data), outputBlob.data_length);
+ free(const_cast<uint8_t*>(outputBlob.data));
return true;
}
Keymaster::Keymaster() {
mDevice = nullptr;
- const hw_module_t *module;
+ const hw_module_t* module;
int ret = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &module);
if (ret != 0) {
LOG(ERROR) << "hw_get_module_by_class returned " << ret;
@@ -96,22 +92,21 @@
}
}
-bool Keymaster::generateKey(
- const keymaster::AuthorizationSet &inParams,
- std::string &key) {
+bool Keymaster::generateKey(const keymaster::AuthorizationSet& inParams, std::string* key) {
keymaster_key_blob_t keyBlob;
auto error = mDevice->generate_key(mDevice, &inParams, &keyBlob, nullptr);
if (error != KM_ERROR_OK) {
LOG(ERROR) << "generate_key failed, code " << error;
return false;
}
- key.assign(reinterpret_cast<const char *>(keyBlob.key_material), keyBlob.key_material_size);
+ key->assign(reinterpret_cast<const char*>(keyBlob.key_material), keyBlob.key_material_size);
+ free(const_cast<uint8_t*>(keyBlob.key_material));
return true;
}
-bool Keymaster::deleteKey(const std::string &key) {
+bool Keymaster::deleteKey(const std::string& key) {
if (mDevice->delete_key == nullptr) return true;
- keymaster_key_blob_t keyBlob { reinterpret_cast<const uint8_t *>(key.data()), key.size() };
+ keymaster_key_blob_t keyBlob{reinterpret_cast<const uint8_t*>(key.data()), key.size()};
auto error = mDevice->delete_key(mDevice, &keyBlob);
if (error != KM_ERROR_OK) {
LOG(ERROR) << "delete_key failed, code " << error;
@@ -120,34 +115,28 @@
return true;
}
-KeymasterOperation Keymaster::begin(
- keymaster_purpose_t purpose,
- const std::string &key,
- const keymaster::AuthorizationSet &inParams,
- keymaster::AuthorizationSet &outParams) {
- keymaster_key_blob_t keyBlob { reinterpret_cast<const uint8_t *>(key.data()), key.size() };
+KeymasterOperation Keymaster::begin(keymaster_purpose_t purpose, const std::string& key,
+ const keymaster::AuthorizationSet& inParams,
+ keymaster::AuthorizationSet* outParams) {
+ keymaster_key_blob_t keyBlob{reinterpret_cast<const uint8_t*>(key.data()), key.size()};
keymaster_operation_handle_t mOpHandle;
keymaster_key_param_set_t outParams_set;
- auto error = mDevice->begin(mDevice, purpose,
- &keyBlob, &inParams, &outParams_set, &mOpHandle);
+ auto error = mDevice->begin(mDevice, purpose, &keyBlob, &inParams, &outParams_set, &mOpHandle);
if (error != KM_ERROR_OK) {
LOG(ERROR) << "begin failed, code " << error;
return KeymasterOperation(nullptr, mOpHandle);
}
- outParams.Clear();
- outParams.push_back(outParams_set);
+ outParams->Clear();
+ outParams->push_back(outParams_set);
keymaster_free_param_set(&outParams_set);
return KeymasterOperation(mDevice, mOpHandle);
}
-KeymasterOperation Keymaster::begin(
- keymaster_purpose_t purpose,
- const std::string &key,
- const keymaster::AuthorizationSet &inParams) {
- keymaster_key_blob_t keyBlob { reinterpret_cast<const uint8_t *>(key.data()), key.size() };
+KeymasterOperation Keymaster::begin(keymaster_purpose_t purpose, const std::string& key,
+ const keymaster::AuthorizationSet& inParams) {
+ keymaster_key_blob_t keyBlob{reinterpret_cast<const uint8_t*>(key.data()), key.size()};
keymaster_operation_handle_t mOpHandle;
- auto error = mDevice->begin(mDevice, purpose,
- &keyBlob, &inParams, nullptr, &mOpHandle);
+ auto error = mDevice->begin(mDevice, purpose, &keyBlob, &inParams, nullptr, &mOpHandle);
if (error != KM_ERROR_OK) {
LOG(ERROR) << "begin failed, code " << error;
return KeymasterOperation(nullptr, mOpHandle);
diff --git a/Keymaster.h b/Keymaster.h
index a4deddf..cf692f3 100644
--- a/Keymaster.h
+++ b/Keymaster.h
@@ -38,28 +38,31 @@
// in the destructor if it is unfinished. Methods log failures
// to LOG(ERROR).
class KeymasterOperation {
-public:
- ~KeymasterOperation() { if (mDevice) mDevice->abort(mDevice, mOpHandle); }
+ public:
+ ~KeymasterOperation() {
+ if (mDevice) mDevice->abort(mDevice, mOpHandle);
+ }
// Is this instance valid? This is false if creation fails, and becomes
// false on finish or if an update fails.
- explicit operator bool() {return mDevice != nullptr;}
+ explicit operator bool() { return mDevice != nullptr; }
// Call "update" repeatedly until all of the input is consumed, and
// concatenate the output. Return true on success.
- bool updateCompletely(const std::string &input, std::string &output);
+ bool updateCompletely(const std::string& input, std::string* output);
// Finish; pass nullptr for the "output" param.
bool finish();
// Finish and write the output to this string.
- bool finishWithOutput(std::string &output);
+ bool finishWithOutput(std::string* output);
// Move constructor
KeymasterOperation(KeymasterOperation&& rhs) {
mOpHandle = rhs.mOpHandle;
mDevice = rhs.mDevice;
rhs.mDevice = nullptr;
}
-private:
- KeymasterOperation(keymaster1_device_t *d, keymaster_operation_handle_t h):
- mDevice {d}, mOpHandle {h} {}
- keymaster1_device_t *mDevice;
+
+ private:
+ KeymasterOperation(keymaster1_device_t* d, keymaster_operation_handle_t h)
+ : mDevice{d}, mOpHandle{h} {}
+ keymaster1_device_t* mDevice;
keymaster_operation_handle_t mOpHandle;
DISALLOW_COPY_AND_ASSIGN(KeymasterOperation);
friend class Keymaster;
@@ -68,41 +71,40 @@
// Wrapper for a keymaster1_device_t representing an open connection
// to the keymaster, which is closed in the destructor.
class Keymaster {
-public:
+ public:
Keymaster();
- ~Keymaster() { if (mDevice) keymaster1_close(mDevice); }
+ ~Keymaster() {
+ if (mDevice) keymaster1_close(mDevice);
+ }
// false if we failed to open the keymaster device.
- explicit operator bool() {return mDevice != nullptr;}
+ explicit operator bool() { return mDevice != nullptr; }
// Generate a key in the keymaster from the given params.
- bool generateKey(const AuthorizationSet &inParams, std::string &key);
+ bool generateKey(const AuthorizationSet& inParams, std::string* key);
// If the keymaster supports it, permanently delete a key.
- bool deleteKey(const std::string &key);
+ bool deleteKey(const std::string& key);
// Begin a new cryptographic operation, collecting output parameters.
- KeymasterOperation begin(
- keymaster_purpose_t purpose,
- const std::string &key,
- const AuthorizationSet &inParams,
- AuthorizationSet &outParams);
+ KeymasterOperation begin(keymaster_purpose_t purpose, const std::string& key,
+ const AuthorizationSet& inParams, AuthorizationSet* outParams);
// Begin a new cryptographic operation; don't collect output parameters.
- KeymasterOperation begin(
- keymaster_purpose_t purpose,
- const std::string &key,
- const AuthorizationSet &inParams);
-private:
- keymaster1_device_t *mDevice;
+ KeymasterOperation begin(keymaster_purpose_t purpose, const std::string& key,
+ const AuthorizationSet& inParams);
+
+ private:
+ keymaster1_device_t* mDevice;
DISALLOW_COPY_AND_ASSIGN(Keymaster);
};
template <keymaster_tag_t Tag>
-inline AuthorizationSetBuilder& addStringParam(AuthorizationSetBuilder &¶ms,
- TypedTag<KM_BYTES, Tag> tag, const std::string& val) {
+inline AuthorizationSetBuilder& addStringParam(AuthorizationSetBuilder&& params,
+ TypedTag<KM_BYTES, Tag> tag,
+ const std::string& val) {
return params.Authorization(tag, val.data(), val.size());
}
template <keymaster_tag_t Tag>
-inline void addStringParam(AuthorizationSetBuilder ¶ms,
- TypedTag<KM_BYTES, Tag> tag, const std::string& val) {
- params.Authorization(tag, val.data(), val.size());
+inline void addStringParam(AuthorizationSetBuilder* params, TypedTag<KM_BYTES, Tag> tag,
+ const std::string& val) {
+ params->Authorization(tag, val.data(), val.size());
}
} // namespace vold
diff --git a/cryptfs.c b/cryptfs.c
index b99dd56..fcc9724 100644
--- a/cryptfs.c
+++ b/cryptfs.c
@@ -1154,6 +1154,7 @@
struct dm_ioctl *io;
unsigned int minor;
int fd=0;
+ int err;
int retval = -1;
int version[3];
char *extra_params;
@@ -1167,8 +1168,9 @@
io = (struct dm_ioctl *) buffer;
ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
- if (ioctl(fd, DM_DEV_CREATE, io)) {
- SLOGE("Cannot create dm-crypt device\n");
+ err = ioctl(fd, DM_DEV_CREATE, io);
+ if (err) {
+ SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
goto errout;
}