2 * Copyright (C) 2015 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "Ext4Crypt.h"
29 #include <sys/mount.h>
30 #include <sys/types.h>
33 #include <cutils/properties.h>
34 #include <openssl/sha.h>
36 #include <private/android_filesystem_config.h>
38 #include "unencrypted_properties.h"
39 #include "key_control.h"
41 #include "ext4_crypt_init_extensions.h"
43 #define LOG_TAG "Ext4Crypt"
45 #include <cutils/fs.h>
46 #include <cutils/log.h>
47 #include <cutils/klog.h>
49 #include <base/file.h>
50 #include <base/logging.h>
51 #include <base/stringprintf.h>
53 using android::base::StringPrintf;
55 static const char* kPropEmulateFbe = "persist.sys.emulate_fbe";
59 const int key_length = 128;
60 static_assert(key_length % 8 == 0,
61 "Key length must be multiple of 8 bits");
63 // How long do we store passwords for?
64 const int password_max_age_seconds = 60;
66 // How is device encrypted
68 std::string master_key;
72 std::map<std::string, keys> s_key_store;
74 // ext4enc:TODO get these consts from somewhere good
75 const int SHA512_LENGTH = 64;
76 const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
78 // ext4enc:TODO Include structure from somewhere sensible
79 // MUST be in sync with ext4_crypto.c in kernel
80 const int EXT4_MAX_KEY_SIZE = 64;
81 const int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
82 struct ext4_encryption_key {
84 char raw[EXT4_MAX_KEY_SIZE];
89 const char* magic = "magic";
90 const char* major_version = "major_version";
91 const char* minor_version = "minor_version";
92 const char* flags = "flags";
93 const char* crypt_type = "crypt_type";
94 const char* failed_decrypt_count = "failed_decrypt_count";
95 const char* crypto_type_name = "crypto_type_name";
96 const char* master_key = "master_key";
97 const char* salt = "salt";
98 const char* kdf_type = "kdf_type";
99 const char* N_factor = "N_factor";
100 const char* r_factor = "r_factor";
101 const char* p_factor = "p_factor";
102 const char* keymaster_blob = "keymaster_blob";
103 const char* scrypted_intermediate_key = "scrypted_intermediate_key";
107 static std::string e4crypt_install_key(const std::string &key);
109 static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
110 UnencryptedProperties& props)
112 SLOGI("Putting crypt footer");
114 bool success = props.Set<int>(tag::magic, crypt_ftr.magic)
115 && props.Set<int>(tag::major_version, crypt_ftr.major_version)
116 && props.Set<int>(tag::minor_version, crypt_ftr.minor_version)
117 && props.Set<int>(tag::flags, crypt_ftr.flags)
118 && props.Set<int>(tag::crypt_type, crypt_ftr.crypt_type)
119 && props.Set<int>(tag::failed_decrypt_count,
120 crypt_ftr.failed_decrypt_count)
121 && props.Set<std::string>(tag::crypto_type_name,
122 std::string(reinterpret_cast<const char*>(crypt_ftr.crypto_type_name)))
123 && props.Set<std::string>(tag::master_key,
124 std::string((const char*) crypt_ftr.master_key,
126 && props.Set<std::string>(tag::salt,
127 std::string((const char*) crypt_ftr.salt,
129 && props.Set<int>(tag::kdf_type, crypt_ftr.kdf_type)
130 && props.Set<int>(tag::N_factor, crypt_ftr.N_factor)
131 && props.Set<int>(tag::r_factor, crypt_ftr.r_factor)
132 && props.Set<int>(tag::p_factor, crypt_ftr.p_factor)
133 && props.Set<std::string>(tag::keymaster_blob,
134 std::string((const char*) crypt_ftr.keymaster_blob,
135 crypt_ftr.keymaster_blob_size))
136 && props.Set<std::string>(tag::scrypted_intermediate_key,
137 std::string((const char*) crypt_ftr.scrypted_intermediate_key,
139 return success ? 0 : -1;
142 static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
143 const UnencryptedProperties& props)
145 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
146 crypt_ftr.magic = props.Get<int>(tag::magic);
147 crypt_ftr.major_version = props.Get<int>(tag::major_version);
148 crypt_ftr.minor_version = props.Get<int>(tag::minor_version);
149 crypt_ftr.ftr_size = sizeof(crypt_ftr);
150 crypt_ftr.flags = props.Get<int>(tag::flags);
151 crypt_ftr.crypt_type = props.Get<int>(tag::crypt_type);
152 crypt_ftr.failed_decrypt_count = props.Get<int>(tag::failed_decrypt_count);
153 std::string crypto_type_name = props.Get<std::string>(tag::crypto_type_name);
154 strlcpy(reinterpret_cast<char*>(crypt_ftr.crypto_type_name),
155 crypto_type_name.c_str(),
156 sizeof(crypt_ftr.crypto_type_name));
157 std::string master_key = props.Get<std::string>(tag::master_key);
158 crypt_ftr.keysize = master_key.size();
159 if (crypt_ftr.keysize > sizeof(crypt_ftr.master_key)) {
160 SLOGE("Master key size too long");
163 memcpy(crypt_ftr.master_key, &master_key[0], crypt_ftr.keysize);
164 std::string salt = props.Get<std::string>(tag::salt);
165 if (salt.size() != SALT_LEN) {
166 SLOGE("Salt wrong length");
169 memcpy(crypt_ftr.salt, &salt[0], SALT_LEN);
170 crypt_ftr.kdf_type = props.Get<int>(tag::kdf_type);
171 crypt_ftr.N_factor = props.Get<int>(tag::N_factor);
172 crypt_ftr.r_factor = props.Get<int>(tag::r_factor);
173 crypt_ftr.p_factor = props.Get<int>(tag::p_factor);
174 std::string keymaster_blob = props.Get<std::string>(tag::keymaster_blob);
175 crypt_ftr.keymaster_blob_size = keymaster_blob.size();
176 if (crypt_ftr.keymaster_blob_size > sizeof(crypt_ftr.keymaster_blob)) {
177 SLOGE("Keymaster blob too long");
180 memcpy(crypt_ftr.keymaster_blob, &keymaster_blob[0],
181 crypt_ftr.keymaster_blob_size);
182 std::string scrypted_intermediate_key = props.Get<std::string>(tag::scrypted_intermediate_key);
183 if (scrypted_intermediate_key.size() != SCRYPT_LEN) {
184 SLOGE("scrypted intermediate key wrong length");
187 memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
193 static UnencryptedProperties GetProps(const char* path)
195 return UnencryptedProperties(path);
198 static UnencryptedProperties GetAltProps(const char* path)
200 return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
203 static UnencryptedProperties GetPropsOrAltProps(const char* path)
205 UnencryptedProperties props = GetProps(path);
209 return GetAltProps(path);
212 int e4crypt_enable(const char* path)
215 if (s_key_store.find(path) != s_key_store.end()) {
219 // Not an encryptable device?
220 UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
221 if (!key_props.OK()) {
225 if (key_props.Get<std::string>(tag::master_key).empty()) {
227 if (cryptfs_create_default_ftr(&ftr, key_length)) {
228 SLOGE("Failed to create crypto footer");
232 // Scrub fields not used by ext4enc
233 ftr.persist_data_offset[0] = 0;
234 ftr.persist_data_offset[1] = 0;
235 ftr.persist_data_size = 0;
237 if (put_crypt_ftr_and_key(ftr, key_props)) {
238 SLOGE("Failed to write crypto footer");
243 if (get_crypt_ftr_and_key(ftr2, key_props)) {
244 SLOGE("Failed to read crypto footer back");
248 if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
249 SLOGE("Crypto footer not correctly written");
254 if (!UnencryptedProperties(path).Remove(properties::ref)) {
255 SLOGE("Failed to remove key ref");
259 return e4crypt_check_passwd(path, "");
262 int e4crypt_change_password(const char* path, int crypt_type,
263 const char* password)
265 SLOGI("e4crypt_change_password");
266 auto key_props = GetProps(path).GetChild(properties::key);
269 if (get_crypt_ftr_and_key(ftr, key_props)) {
270 SLOGE("Failed to read crypto footer back");
274 auto mki = s_key_store.find(path);
275 if (mki == s_key_store.end()) {
276 SLOGE("No stored master key - can't change password");
280 const unsigned char* master_key_bytes
281 = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
283 if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
284 SLOGE("Failed to set password");
288 ftr.crypt_type = crypt_type;
290 if (put_crypt_ftr_and_key(ftr, key_props)) {
291 SLOGE("Failed to write crypto footer");
295 if (!UnencryptedProperties(path).Set(properties::is_default,
296 crypt_type == CRYPT_TYPE_DEFAULT)) {
297 SLOGE("Failed to update default flag");
304 int e4crypt_crypto_complete(const char* path)
306 SLOGI("ext4 crypto complete called on %s", path);
307 auto key_props = GetPropsOrAltProps(path).GetChild(properties::key);
308 if (key_props.Get<std::string>(tag::master_key).empty()) {
309 SLOGI("No master key, so not ext4enc");
316 // Get raw keyref - used to make keyname and to pass to ioctl
317 static std::string generate_key_ref(const char* key, int length)
322 SHA512_Update(&c, key, length);
323 unsigned char key_ref1[SHA512_LENGTH];
324 SHA512_Final(key_ref1, &c);
327 SHA512_Update(&c, key_ref1, SHA512_LENGTH);
328 unsigned char key_ref2[SHA512_LENGTH];
329 SHA512_Final(key_ref2, &c);
331 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
334 int e4crypt_check_passwd(const char* path, const char* password)
336 SLOGI("e4crypt_check_password");
337 auto props = GetPropsOrAltProps(path);
338 auto key_props = props.GetChild(properties::key);
341 if (get_crypt_ftr_and_key(ftr, key_props)) {
342 SLOGE("Failed to read crypto footer back");
346 unsigned char master_key_bytes[key_length / 8];
347 if (cryptfs_get_master_key (&ftr, password, master_key_bytes)){
348 SLOGI("Incorrect password");
349 ftr.failed_decrypt_count++;
350 if (put_crypt_ftr_and_key(ftr, key_props)) {
351 SLOGW("Failed to update failed_decrypt_count");
353 return ftr.failed_decrypt_count;
356 if (ftr.failed_decrypt_count) {
357 ftr.failed_decrypt_count = 0;
358 if (put_crypt_ftr_and_key(ftr, key_props)) {
359 SLOGW("Failed to reset failed_decrypt_count");
362 std::string master_key(reinterpret_cast<char*>(master_key_bytes),
363 sizeof(master_key_bytes));
366 clock_gettime(CLOCK_BOOTTIME, &now);
367 s_key_store[path] = keys{master_key, password,
368 now.tv_sec + password_max_age_seconds};
369 auto raw_ref = e4crypt_install_key(master_key);
370 if (raw_ref.empty()) {
374 // Save reference to key so we can set policy later
375 if (!props.Set(properties::ref, raw_ref)) {
376 SLOGE("Cannot save key reference");
383 static ext4_encryption_key fill_key(const std::string &key)
385 // ext4enc:TODO Currently raw key is required to be of length
386 // sizeof(ext4_key.raw) == EXT4_MAX_KEY_SIZE, so zero pad to
387 // this length. Change when kernel bug is fixed.
388 ext4_encryption_key ext4_key = {EXT4_ENCRYPTION_MODE_AES_256_XTS,
390 sizeof(ext4_key.raw)};
391 memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
392 static_assert(key_length / 8 <= sizeof(ext4_key.raw),
394 memcpy(ext4_key.raw, &key[0], key.size());
398 static std::string keyname(const std::string &raw_ref)
400 std::ostringstream o;
402 for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
403 o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
408 // Get the keyring we store all keys in
409 static key_serial_t e4crypt_keyring()
411 return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
414 static int e4crypt_install_key(const ext4_encryption_key &ext4_key, const std::string &ref)
416 key_serial_t device_keyring = e4crypt_keyring();
417 SLOGI("Found device_keyring - id is %d", device_keyring);
418 key_serial_t key_id = add_key("logon", ref.c_str(),
419 (void*)&ext4_key, sizeof(ext4_key),
422 SLOGE("Failed to insert key into keyring with error %s",
426 SLOGI("Added key %d (%s) to keyring %d in process %d",
427 key_id, ref.c_str(), device_keyring, getpid());
431 // Install password into global keyring
432 // Return raw key reference for use in policy
433 static std::string e4crypt_install_key(const std::string &key)
435 auto ext4_key = fill_key(key);
436 auto raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
437 auto ref = keyname(raw_ref);
438 if (e4crypt_install_key(ext4_key, ref) == -1) {
444 int e4crypt_restart(const char* path)
446 SLOGI("e4crypt_restart");
450 SLOGI("ext4 restart called on %s", path);
451 property_set("vold.decrypt", "trigger_reset_main");
452 SLOGI("Just asked init to shut down class main");
455 std::string tmp_path = std::string() + path + "/tmp_mnt";
457 rc = wait_and_unmount(tmp_path.c_str(), true);
459 SLOGE("umount %s failed with rc %d, msg %s",
460 tmp_path.c_str(), rc, strerror(errno));
464 rc = wait_and_unmount(path, true);
466 SLOGE("umount %s failed with rc %d, msg %s",
467 path, rc, strerror(errno));
474 int e4crypt_get_password_type(const char* path)
476 SLOGI("e4crypt_get_password_type");
477 return GetPropsOrAltProps(path).GetChild(properties::key)
478 .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
481 const char* e4crypt_get_password(const char* path)
483 SLOGI("e4crypt_get_password");
485 auto i = s_key_store.find(path);
486 if (i == s_key_store.end()) {
491 clock_gettime(CLOCK_BOOTTIME, &now);
492 if (i->second.expiry_time < now.tv_sec) {
493 e4crypt_clear_password(path);
497 return i->second.password.c_str();
500 void e4crypt_clear_password(const char* path)
502 SLOGI("e4crypt_clear_password");
504 auto i = s_key_store.find(path);
505 if (i == s_key_store.end()) {
509 memset(&i->second.password[0], 0, i->second.password.size());
510 i->second.password = std::string();
513 int e4crypt_get_field(const char* path, const char* fieldname,
514 char* value, size_t len)
516 auto v = GetPropsOrAltProps(path).GetChild(properties::props)
517 .Get<std::string>(fieldname);
520 return CRYPTO_GETFIELD_ERROR_NO_FIELD;
523 if (v.length() >= len) {
524 return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
527 strlcpy(value, v.c_str(), len);
531 int e4crypt_set_field(const char* path, const char* fieldname,
534 return GetPropsOrAltProps(path).GetChild(properties::props)
535 .Set(fieldname, std::string(value)) ? 0 : -1;
538 static std::string get_key_path(const char *mount_path, userid_t user_id) {
539 // ext4enc:TODO get the path properly
540 auto key_dir = StringPrintf("%s/misc/vold/user_keys", mount_path);
541 if (fs_prepare_dir(key_dir.c_str(), 0700, AID_ROOT, AID_ROOT)) {
542 PLOG(ERROR) << "Failed to prepare " << key_dir;
545 return StringPrintf("%s/%d", key_dir.c_str(), user_id);
548 // ext4enc:TODO this can't be the only place keys are read from /dev/urandom
549 // we should unite those places.
550 static std::string e4crypt_get_key(
551 const std::string &key_path,
552 bool create_if_absent)
555 if (android::base::ReadFileToString(key_path, &content)) {
556 if (content.size() != key_length/8) {
557 SLOGE("Wrong size key %zu in %s", content.size(), key_path.c_str());
562 if (!create_if_absent) {
563 SLOGE("No key found in %s", key_path.c_str());
566 std::ifstream urandom("/dev/urandom");
568 SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
571 char key_bytes[key_length / 8];
573 urandom.read(key_bytes, sizeof(key_bytes));
575 SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
578 std::string key(key_bytes, sizeof(key_bytes));
579 if (!android::base::WriteStringToFile(key, key_path)) {
580 SLOGE("Unable to write key to %s (%s)",
581 key_path.c_str(), strerror(errno));
587 static int e4crypt_set_user_policy(const char *mount_path, userid_t user_id,
588 const char *path, bool create_if_absent) {
589 SLOGD("e4crypt_set_user_policy for %d", user_id);
590 auto user_key = e4crypt_get_key(get_key_path(mount_path, user_id),
592 if (user_key.empty()) {
595 auto raw_ref = e4crypt_install_key(user_key);
596 if (raw_ref.empty()) {
599 return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
602 static bool is_numeric(const char *name) {
603 for (const char *p = name; *p != '\0'; p++) {
610 int e4crypt_set_user_crypto_policies(const char *dir)
612 if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
615 SLOGD("e4crypt_set_user_crypto_policies");
616 std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
618 SLOGE("Unable to read directory %s, error %s\n",
619 dir, strerror(errno));
623 struct dirent *result = readdir(dirp.get());
625 // ext4enc:TODO check errno
628 if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
629 continue; // skips user 0, which is a symlink
631 auto user_id = atoi(result->d_name);
632 auto user_dir = std::string() + dir + "/" + result->d_name;
633 // ext4enc:TODO don't hardcode /data
634 if (e4crypt_set_user_policy("/data", user_id, user_dir.c_str(), false)) {
635 // ext4enc:TODO If this function fails, stop the boot: we must
636 // deliver on promised encryption.
637 SLOGE("Unable to set policy on %s\n", user_dir.c_str());
643 int e4crypt_create_user_key(userid_t user_id) {
644 SLOGD("e4crypt_create_user_key(%d)", user_id);
645 // TODO: create second key for user_de data
646 if (e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), true).empty()) {
653 int e4crypt_destroy_user_key(userid_t user_id) {
654 SLOGD("e4crypt_destroy_user_key(%d)", user_id);
655 // TODO: destroy second key for user_de data
656 auto key_path = get_key_path(DATA_MNT_POINT, user_id);
657 auto key = e4crypt_get_key(key_path, false);
658 auto ext4_key = fill_key(key);
659 auto ref = keyname(generate_key_ref(ext4_key.raw, ext4_key.size));
660 auto key_serial = keyctl_search(e4crypt_keyring(), "logon", ref.c_str(), 0);
661 if (keyctl_revoke(key_serial) == 0) {
662 SLOGD("Revoked key with serial %ld ref %s\n", key_serial, ref.c_str());
664 SLOGE("Failed to revoke key with serial %ld ref %s: %s\n",
665 key_serial, ref.c_str(), strerror(errno));
669 SLOGE("Unable to fork: %s", strerror(errno));
673 SLOGD("Forked for secdiscard");
674 execl("/system/bin/secdiscard",
675 "/system/bin/secdiscard",
679 SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
683 // ext4enc:TODO reap the zombie
687 int e4crypt_unlock_user_key(userid_t user_id, const char* token) {
688 if (property_get_bool(kPropEmulateFbe, false)) {
689 // When in emulation mode, we just use chmod
690 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0771) ||
691 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0771)) {
692 PLOG(ERROR) << "Failed to unlock user " << user_id;
696 auto user_key = e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), false);
697 if (user_key.empty()) {
700 auto raw_ref = e4crypt_install_key(user_key);
701 if (raw_ref.empty()) {
708 int e4crypt_lock_user_key(userid_t user_id) {
709 if (property_get_bool(kPropEmulateFbe, false)) {
710 // When in emulation mode, we just use chmod
711 if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0000) ||
712 chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0000)) {
713 PLOG(ERROR) << "Failed to lock user " << user_id;
717 // TODO: remove from kernel keyring
722 int e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id) {
723 std::string system_ce_path(android::vold::BuildDataSystemCePath(user_id));
724 std::string user_ce_path(android::vold::BuildDataUserPath(volume_uuid, user_id));
725 std::string user_de_path(android::vold::BuildDataUserDePath(volume_uuid, user_id));
727 if (fs_prepare_dir(system_ce_path.c_str(), 0700, AID_SYSTEM, AID_SYSTEM)) {
728 PLOG(ERROR) << "Failed to prepare " << system_ce_path;
731 if (fs_prepare_dir(user_ce_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
732 PLOG(ERROR) << "Failed to prepare " << user_ce_path;
735 if (fs_prepare_dir(user_de_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
736 PLOG(ERROR) << "Failed to prepare " << user_de_path;
740 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
741 if (e4crypt_set_user_policy(DATA_MNT_POINT, user_id, system_ce_path.c_str(), true)
742 || e4crypt_set_user_policy(DATA_MNT_POINT, user_id, user_ce_path.c_str(), true)) {