Run clang-format over ext4crypt related code am: df528a7011

am: 1d348d29a3

* commit '1d348d29a30e24b15ea5c32774b92bc13e8041a7':
  Run clang-format over ext4crypt related code
gugelfrei
Paul Crowley 8 years ago committed by android-build-merger
commit c1a3ca29ed

@ -22,25 +22,25 @@
#include <iomanip>
#include <map>
#include <set>
#include <string>
#include <sstream>
#include <string>
#include <stdio.h>
#include <errno.h>
#include <cutils/properties.h>
#include <dirent.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <cutils/properties.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_DE = 1 << 0;
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 @@ static const char* escape_null(const char* value) {
}
// 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);
@ -123,18 +122,16 @@ static std::string generate_key_ref(const char* key, int length)
SHA512_Final(key_ref2, &c);
static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
"Hash too short for descriptor");
"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!");
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));
@ -142,19 +139,17 @@ static bool fill_key(const std::string& key, ext4_encryption_key* ext4_key)
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) {
for (auto i : raw_ref) {
o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
}
return o.str();
}
// Get the keyring we store all keys in
static bool e4crypt_keyring(key_serial_t* device_keyring)
{
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";
@ -165,23 +160,21 @@ static bool e4crypt_keyring(key_serial_t* device_keyring)
// 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;
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);
key_serial_t key_id =
add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
if (key_id == -1) {
PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
return false;
}
LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring "
<< device_keyring << " in process " << getpid();
LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
<< " in process " << getpid();
return true;
}
@ -193,8 +186,8 @@ static std::string get_ce_key_path(userid_t user_id) {
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;
@ -207,7 +200,7 @@ static bool read_and_install_user_ce_key(
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;
@ -216,7 +209,7 @@ static bool prepare_dir(const std::string &dir, mode_t mode, uid_t uid, gid_t gi
return true;
}
static bool random_key(std::string *key) {
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";
@ -225,20 +218,20 @@ static bool random_key(std::string *key) {
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); // May be partially created so ignore errors
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) {
@ -275,8 +268,8 @@ static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral
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;
@ -286,7 +279,7 @@ static bool lookup_key_ref(const std::map<userid_t, std::string> &key_map,
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;
@ -294,17 +287,16 @@ static bool ensure_policy(const std::string &raw_ref, const std::string& path) {
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;
@ -339,8 +331,7 @@ static bool load_all_de_keys() {
return true;
}
bool e4crypt_initialize_global_de()
{
bool e4crypt_initialize_global_de() {
LOG(INFO) << "e4crypt_initialize_global_de";
if (s_global_de_initialized) {
@ -385,10 +376,10 @@ bool e4crypt_init_user0() {
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); // May be partially created so ignore errors
android::vold::destroyKey(de_path); // May be partially created so ignore errors
}
if (path_exists(ce_path)) {
android::vold::destroyKey(ce_path); // May be partially created so ignore errors
android::vold::destroyKey(ce_path); // May be partially created so ignore errors
}
if (!create_and_install_user_keys(0, false)) return false;
}
@ -420,8 +411,8 @@ bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral)
}
// 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;
}
@ -431,7 +422,7 @@ bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral)
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);
key_serial_t device_keyring;
if (!e4crypt_keyring(&device_keyring)) return false;
@ -496,34 +487,32 @@ static bool emulated_unlock(const std::string& path, mode_t mode) {
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 = "";
return true;
}
if (android::vold::HexToStr(hex, *result) != 0) {
LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
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);
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;
@ -543,10 +532,10 @@ bool e4crypt_change_user_key(userid_t user_id, int serial,
}
// 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;
@ -565,9 +554,9 @@ bool e4crypt_unlock_user_key(userid_t user_id, int serial,
// 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;
}
@ -582,9 +571,9 @@ bool e4crypt_lock_user_key(userid_t user_id) {
} 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;
}
@ -593,10 +582,10 @@ bool e4crypt_lock_user_key(userid_t user_id) {
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);
@ -612,7 +601,7 @@ bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id,
// 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;

@ -28,14 +28,12 @@ bool e4crypt_initialize_global_de();
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

@ -42,20 +42,19 @@
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";
@ -72,14 +71,14 @@ static const char* kFn_version = "version";
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);
@ -91,18 +90,17 @@ static std::string hashSecdiscardable(const std::string &secdiscardable) {
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 KeyAuthentication &auth, const std::string &appId,
std::string *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);
.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(&paramBuilder, keymaster::TAG_APPLICATION_ID, appId);
if (auth.token.empty()) {
LOG(DEBUG) << "Creating key that doesn't need auth token";
@ -111,10 +109,10 @@ static bool generateKeymasterKey(Keymaster &keymaster,
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";
<< auth.token.size() << " bytes";
return false;
}
const hw_auth_token_t *at = reinterpret_cast<const hw_auth_token_t *>(auth.token.data());
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);
@ -122,12 +120,12 @@ static bool generateKeymasterKey(Keymaster &keymaster,
return keymaster.generateKey(paramBuilder.build(), key);
}
static keymaster::AuthorizationSetBuilder beginParams(
const KeyAuthentication &auth, const std::string &appId) {
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);
.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(&paramBuilder, keymaster::TAG_APPLICATION_ID, appId);
if (!auth.token.empty()) {
LOG(DEBUG) << "Supplying auth token to Keymaster";
@ -136,13 +134,9 @@ static keymaster::AuthorizationSetBuilder beginParams(
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) {
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);
@ -153,7 +147,7 @@ static bool encryptWithKeymasterKey(
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;
@ -165,13 +159,9 @@ static bool encryptWithKeymasterKey(
return true;
}
static bool decryptWithKeymasterKey(
Keymaster &keymaster,
const std::string &key,
const KeyAuthentication &auth,
const std::string &appId,
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);
auto params = addStringParam(beginParams(auth, appId), keymaster::TAG_NONCE, nonce).build();
@ -182,18 +172,18 @@ static bool decryptWithKeymasterKey(
return true;
}
static bool readFileToString(const std::string &filename, std::string *result) {
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;
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;
}
@ -205,12 +195,12 @@ static std::string getStretching() {
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(WARNING) << "Password present but stretching is nopassword";
@ -219,20 +209,19 @@ static bool stretchSecret(const std::string &stretching, const std::string &secr
stretched->clear();
} else if (stretching == kStretch_none) {
*stretched = secret;
} else if (std::equal(kStretchPrefix_scrypt.begin(),
kStretchPrefix_scrypt.end(), stretching.begin())) {
} 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) {
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;
}
@ -243,21 +232,21 @@ static bool stretchSecret(const std::string &stretching, const std::string &secr
return true;
}
static bool generateAppId(const KeyAuthentication &auth, const std::string &stretching,
const std::string &salt, const std::string &secdiscardable,
std::string* appId) {
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;
*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.
@ -266,14 +255,14 @@ bool storeKey(const std::string &dir, const KeyAuthentication &auth, const std::
}
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;
}
std::string appId;
if (!generateAppId(auth, stretching, salt, secdiscardable, &appId)) return false;
@ -288,7 +277,7 @@ bool storeKey(const std::string &dir, const KeyAuthentication &auth, const std::
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 (version != kCurrentVersion) {
@ -301,7 +290,7 @@ bool retrieveKey(const std::string &dir, const KeyAuthentication &auth, std::str
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;
}
std::string appId;
if (!generateAppId(auth, stretching, salt, secdiscardable, &appId)) return false;
@ -314,7 +303,7 @@ bool retrieveKey(const std::string &dir, const KeyAuthentication &auth, std::str
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;
Keymaster keymaster;
@ -323,25 +312,24 @@ static bool deleteKey(const std::string &dir) {
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);

@ -27,8 +27,8 @@ namespace vold {
// 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 @@ extern const KeyAuthentication kEmptyAuthentication;
// 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

@ -21,25 +21,23 @@
namespace android {
namespace vold {
bool KeymasterOperation::updateCompletely(
const std::string &input,
std::string *output) {
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::updateCompletely(
}
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 @@ bool KeymasterOperation::finish() {
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,23 +92,21 @@ Keymaster::Keymaster() {
}
}
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);
free(const_cast<uint8_t *>(keyBlob.key_material));
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;
@ -121,16 +115,13 @@ bool Keymaster::deleteKey(const std::string &key) {
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);
@ -141,14 +132,11 @@ KeymasterOperation Keymaster::begin(
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);

@ -38,28 +38,31 @@ using namespace keymaster;
// 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,40 +71,39 @@ private:
// 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 &&params,
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 *params,
TypedTag<KM_BYTES, Tag> tag, const std::string& val) {
inline void addStringParam(AuthorizationSetBuilder* params, TypedTag<KM_BYTES, Tag> tag,
const std::string& val) {
params->Authorization(tag, val.data(), val.size());
}

Loading…
Cancel
Save