11 #include <sys/mount.h>
12 #include <sys/types.h>
15 #include <cutils/properties.h>
16 #include <openssl/sha.h>
18 #include <private/android_filesystem_config.h>
20 #include "unencrypted_properties.h"
21 #include "key_control.h"
23 #include "ext4_crypt_init_extensions.h"
25 #define LOG_TAG "Ext4Crypt"
26 #include "cutils/log.h"
27 #include <cutils/klog.h>
28 #include <base/file.h>
29 #include <base/stringprintf.h>
33 const int key_length = 128;
34 static_assert(key_length % 8 == 0,
35 "Key length must be multiple of 8 bits");
37 // How long do we store passwords for?
38 const int password_max_age_seconds = 60;
40 // How is device encrypted
42 std::string master_key;
46 std::map<std::string, keys> s_key_store;
48 // ext4enc:TODO get these consts from somewhere good
49 const int SHA512_LENGTH = 64;
50 const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
52 // ext4enc:TODO Include structure from somewhere sensible
53 // MUST be in sync with ext4_crypto.c in kernel
54 const int EXT4_MAX_KEY_SIZE = 64;
55 const int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
56 struct ext4_encryption_key {
58 char raw[EXT4_MAX_KEY_SIZE];
63 const char* magic = "magic";
64 const char* major_version = "major_version";
65 const char* minor_version = "minor_version";
66 const char* flags = "flags";
67 const char* crypt_type = "crypt_type";
68 const char* failed_decrypt_count = "failed_decrypt_count";
69 const char* crypto_type_name = "crypto_type_name";
70 const char* master_key = "master_key";
71 const char* salt = "salt";
72 const char* kdf_type = "kdf_type";
73 const char* N_factor = "N_factor";
74 const char* r_factor = "r_factor";
75 const char* p_factor = "p_factor";
76 const char* keymaster_blob = "keymaster_blob";
77 const char* scrypted_intermediate_key = "scrypted_intermediate_key";
81 static std::string e4crypt_install_key(const std::string &key);
83 static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
84 UnencryptedProperties& props)
86 SLOGI("Putting crypt footer");
88 bool success = props.Set<int>(tag::magic, crypt_ftr.magic)
89 && props.Set<int>(tag::major_version, crypt_ftr.major_version)
90 && props.Set<int>(tag::minor_version, crypt_ftr.minor_version)
91 && props.Set<int>(tag::flags, crypt_ftr.flags)
92 && props.Set<int>(tag::crypt_type, crypt_ftr.crypt_type)
93 && props.Set<int>(tag::failed_decrypt_count,
94 crypt_ftr.failed_decrypt_count)
95 && props.Set<std::string>(tag::crypto_type_name,
96 std::string(reinterpret_cast<const char*>(crypt_ftr.crypto_type_name)))
97 && props.Set<std::string>(tag::master_key,
98 std::string((const char*) crypt_ftr.master_key,
100 && props.Set<std::string>(tag::salt,
101 std::string((const char*) crypt_ftr.salt,
103 && props.Set<int>(tag::kdf_type, crypt_ftr.kdf_type)
104 && props.Set<int>(tag::N_factor, crypt_ftr.N_factor)
105 && props.Set<int>(tag::r_factor, crypt_ftr.r_factor)
106 && props.Set<int>(tag::p_factor, crypt_ftr.p_factor)
107 && props.Set<std::string>(tag::keymaster_blob,
108 std::string((const char*) crypt_ftr.keymaster_blob,
109 crypt_ftr.keymaster_blob_size))
110 && props.Set<std::string>(tag::scrypted_intermediate_key,
111 std::string((const char*) crypt_ftr.scrypted_intermediate_key,
113 return success ? 0 : -1;
116 static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
117 const UnencryptedProperties& props)
119 memset(&crypt_ftr, 0, sizeof(crypt_ftr));
120 crypt_ftr.magic = props.Get<int>(tag::magic);
121 crypt_ftr.major_version = props.Get<int>(tag::major_version);
122 crypt_ftr.minor_version = props.Get<int>(tag::minor_version);
123 crypt_ftr.ftr_size = sizeof(crypt_ftr);
124 crypt_ftr.flags = props.Get<int>(tag::flags);
125 crypt_ftr.crypt_type = props.Get<int>(tag::crypt_type);
126 crypt_ftr.failed_decrypt_count = props.Get<int>(tag::failed_decrypt_count);
127 std::string crypto_type_name = props.Get<std::string>(tag::crypto_type_name);
128 strlcpy(reinterpret_cast<char*>(crypt_ftr.crypto_type_name),
129 crypto_type_name.c_str(),
130 sizeof(crypt_ftr.crypto_type_name));
131 std::string master_key = props.Get<std::string>(tag::master_key);
132 crypt_ftr.keysize = master_key.size();
133 if (crypt_ftr.keysize > sizeof(crypt_ftr.master_key)) {
134 SLOGE("Master key size too long");
137 memcpy(crypt_ftr.master_key, &master_key[0], crypt_ftr.keysize);
138 std::string salt = props.Get<std::string>(tag::salt);
139 if (salt.size() != SALT_LEN) {
140 SLOGE("Salt wrong length");
143 memcpy(crypt_ftr.salt, &salt[0], SALT_LEN);
144 crypt_ftr.kdf_type = props.Get<int>(tag::kdf_type);
145 crypt_ftr.N_factor = props.Get<int>(tag::N_factor);
146 crypt_ftr.r_factor = props.Get<int>(tag::r_factor);
147 crypt_ftr.p_factor = props.Get<int>(tag::p_factor);
148 std::string keymaster_blob = props.Get<std::string>(tag::keymaster_blob);
149 crypt_ftr.keymaster_blob_size = keymaster_blob.size();
150 if (crypt_ftr.keymaster_blob_size > sizeof(crypt_ftr.keymaster_blob)) {
151 SLOGE("Keymaster blob too long");
154 memcpy(crypt_ftr.keymaster_blob, &keymaster_blob[0],
155 crypt_ftr.keymaster_blob_size);
156 std::string scrypted_intermediate_key = props.Get<std::string>(tag::scrypted_intermediate_key);
157 if (scrypted_intermediate_key.size() != SCRYPT_LEN) {
158 SLOGE("scrypted intermediate key wrong length");
161 memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
167 static UnencryptedProperties GetProps(const char* path)
169 return UnencryptedProperties(path);
172 static UnencryptedProperties GetAltProps(const char* path)
174 return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
177 static UnencryptedProperties GetPropsOrAltProps(const char* path)
179 UnencryptedProperties props = GetProps(path);
183 return GetAltProps(path);
186 int e4crypt_enable(const char* path)
189 if (s_key_store.find(path) != s_key_store.end()) {
193 // Not an encryptable device?
194 UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
195 if (!key_props.OK()) {
199 if (key_props.Get<std::string>(tag::master_key).empty()) {
201 if (cryptfs_create_default_ftr(&ftr, key_length)) {
202 SLOGE("Failed to create crypto footer");
206 // Scrub fields not used by ext4enc
207 ftr.persist_data_offset[0] = 0;
208 ftr.persist_data_offset[1] = 0;
209 ftr.persist_data_size = 0;
211 if (put_crypt_ftr_and_key(ftr, key_props)) {
212 SLOGE("Failed to write crypto footer");
217 if (get_crypt_ftr_and_key(ftr2, key_props)) {
218 SLOGE("Failed to read crypto footer back");
222 if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
223 SLOGE("Crypto footer not correctly written");
228 if (!UnencryptedProperties(path).Remove(properties::ref)) {
229 SLOGE("Failed to remove key ref");
233 return e4crypt_check_passwd(path, "");
236 int e4crypt_change_password(const char* path, int crypt_type,
237 const char* password)
239 SLOGI("e4crypt_change_password");
240 auto key_props = GetProps(path).GetChild(properties::key);
243 if (get_crypt_ftr_and_key(ftr, key_props)) {
244 SLOGE("Failed to read crypto footer back");
248 auto mki = s_key_store.find(path);
249 if (mki == s_key_store.end()) {
250 SLOGE("No stored master key - can't change password");
254 const unsigned char* master_key_bytes
255 = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
257 if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
258 SLOGE("Failed to set password");
262 ftr.crypt_type = crypt_type;
264 if (put_crypt_ftr_and_key(ftr, key_props)) {
265 SLOGE("Failed to write crypto footer");
269 if (!UnencryptedProperties(path).Set(properties::is_default,
270 crypt_type == CRYPT_TYPE_DEFAULT)) {
271 SLOGE("Failed to update default flag");
278 int e4crypt_crypto_complete(const char* path)
280 SLOGI("ext4 crypto complete called on %s", path);
281 auto key_props = GetPropsOrAltProps(path).GetChild(properties::key);
282 if (key_props.Get<std::string>(tag::master_key).empty()) {
283 SLOGI("No master key, so not ext4enc");
290 // Get raw keyref - used to make keyname and to pass to ioctl
291 static std::string generate_key_ref(const char* key, int length)
296 SHA512_Update(&c, key, length);
297 unsigned char key_ref1[SHA512_LENGTH];
298 SHA512_Final(key_ref1, &c);
301 SHA512_Update(&c, key_ref1, SHA512_LENGTH);
302 unsigned char key_ref2[SHA512_LENGTH];
303 SHA512_Final(key_ref2, &c);
305 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
308 int e4crypt_check_passwd(const char* path, const char* password)
310 SLOGI("e4crypt_check_password");
311 auto props = GetPropsOrAltProps(path);
312 auto key_props = props.GetChild(properties::key);
315 if (get_crypt_ftr_and_key(ftr, key_props)) {
316 SLOGE("Failed to read crypto footer back");
320 unsigned char master_key_bytes[key_length / 8];
321 if (cryptfs_get_master_key (&ftr, password, master_key_bytes)){
322 SLOGI("Incorrect password");
323 ftr.failed_decrypt_count++;
324 if (put_crypt_ftr_and_key(ftr, key_props)) {
325 SLOGW("Failed to update failed_decrypt_count");
327 return ftr.failed_decrypt_count;
330 if (ftr.failed_decrypt_count) {
331 ftr.failed_decrypt_count = 0;
332 if (put_crypt_ftr_and_key(ftr, key_props)) {
333 SLOGW("Failed to reset failed_decrypt_count");
336 std::string master_key(reinterpret_cast<char*>(master_key_bytes),
337 sizeof(master_key_bytes));
340 clock_gettime(CLOCK_BOOTTIME, &now);
341 s_key_store[path] = keys{master_key, password,
342 now.tv_sec + password_max_age_seconds};
343 auto raw_ref = e4crypt_install_key(master_key);
344 if (raw_ref.empty()) {
348 // Save reference to key so we can set policy later
349 if (!props.Set(properties::ref, raw_ref)) {
350 SLOGE("Cannot save key reference");
357 static ext4_encryption_key fill_key(const std::string &key)
359 // ext4enc:TODO Currently raw key is required to be of length
360 // sizeof(ext4_key.raw) == EXT4_MAX_KEY_SIZE, so zero pad to
361 // this length. Change when kernel bug is fixed.
362 ext4_encryption_key ext4_key = {EXT4_ENCRYPTION_MODE_AES_256_XTS,
364 sizeof(ext4_key.raw)};
365 memset(ext4_key.raw, 0, sizeof(ext4_key.raw));
366 static_assert(key_length / 8 <= sizeof(ext4_key.raw),
368 memcpy(ext4_key.raw, &key[0], key.size());
372 static std::string keyname(const std::string &raw_ref)
374 std::ostringstream o;
376 for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
377 o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
382 // Get the keyring we store all keys in
383 static key_serial_t e4crypt_keyring()
385 return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
388 static int e4crypt_install_key(const ext4_encryption_key &ext4_key, const std::string &ref)
390 key_serial_t device_keyring = e4crypt_keyring();
391 SLOGI("Found device_keyring - id is %d", device_keyring);
392 key_serial_t key_id = add_key("logon", ref.c_str(),
393 (void*)&ext4_key, sizeof(ext4_key),
396 SLOGE("Failed to insert key into keyring with error %s",
400 SLOGI("Added key %d (%s) to keyring %d in process %d",
401 key_id, ref.c_str(), device_keyring, getpid());
405 // Install password into global keyring
406 // Return raw key reference for use in policy
407 static std::string e4crypt_install_key(const std::string &key)
409 auto ext4_key = fill_key(key);
410 auto raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
411 auto ref = keyname(raw_ref);
412 if (e4crypt_install_key(ext4_key, ref) == -1) {
418 int e4crypt_restart(const char* path)
420 SLOGI("e4crypt_restart");
424 SLOGI("ext4 restart called on %s", path);
425 property_set("vold.decrypt", "trigger_reset_main");
426 SLOGI("Just asked init to shut down class main");
429 std::string tmp_path = std::string() + path + "/tmp_mnt";
431 rc = wait_and_unmount(tmp_path.c_str(), true);
433 SLOGE("umount %s failed with rc %d, msg %s",
434 tmp_path.c_str(), rc, strerror(errno));
438 rc = wait_and_unmount(path, true);
440 SLOGE("umount %s failed with rc %d, msg %s",
441 path, rc, strerror(errno));
448 int e4crypt_get_password_type(const char* path)
450 SLOGI("e4crypt_get_password_type");
451 return GetPropsOrAltProps(path).GetChild(properties::key)
452 .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
455 const char* e4crypt_get_password(const char* path)
457 SLOGI("e4crypt_get_password");
459 auto i = s_key_store.find(path);
460 if (i == s_key_store.end()) {
465 clock_gettime(CLOCK_BOOTTIME, &now);
466 if (i->second.expiry_time < now.tv_sec) {
467 e4crypt_clear_password(path);
471 return i->second.password.c_str();
474 void e4crypt_clear_password(const char* path)
476 SLOGI("e4crypt_clear_password");
478 auto i = s_key_store.find(path);
479 if (i == s_key_store.end()) {
483 memset(&i->second.password[0], 0, i->second.password.size());
484 i->second.password = std::string();
487 int e4crypt_get_field(const char* path, const char* fieldname,
488 char* value, size_t len)
490 auto v = GetPropsOrAltProps(path).GetChild(properties::props)
491 .Get<std::string>(fieldname);
494 return CRYPTO_GETFIELD_ERROR_NO_FIELD;
497 if (v.length() >= len) {
498 return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
501 strlcpy(value, v.c_str(), len);
505 int e4crypt_set_field(const char* path, const char* fieldname,
508 return GetPropsOrAltProps(path).GetChild(properties::props)
509 .Set(fieldname, std::string(value)) ? 0 : -1;
512 static std::string get_key_path(
513 const char *mount_path,
514 const char *user_handle)
516 // ext4enc:TODO get the path properly
517 auto key_dir = android::base::StringPrintf("%s/misc/vold/user_keys",
519 if (mkdir(key_dir.c_str(), 0700) < 0 && errno != EEXIST) {
520 SLOGE("Unable to create %s (%s)", key_dir.c_str(), strerror(errno));
523 return key_dir + "/" + user_handle;
526 // ext4enc:TODO this can't be the only place keys are read from /dev/urandom
527 // we should unite those places.
528 static std::string e4crypt_get_key(
529 const std::string &key_path,
530 bool create_if_absent)
533 if (android::base::ReadFileToString(key_path, &content)) {
534 if (content.size() != key_length/8) {
535 SLOGE("Wrong size key %zu in %s", content.size(), key_path.c_str());
540 if (!create_if_absent) {
541 SLOGE("No key found in %s", key_path.c_str());
544 std::ifstream urandom("/dev/urandom");
546 SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
549 char key_bytes[key_length / 8];
551 urandom.read(key_bytes, sizeof(key_bytes));
553 SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
556 std::string key(key_bytes, sizeof(key_bytes));
557 if (!android::base::WriteStringToFile(key, key_path)) {
558 SLOGE("Unable to write key to %s (%s)",
559 key_path.c_str(), strerror(errno));
565 static int e4crypt_set_user_policy(const char *mount_path, const char *user_handle,
566 const char *path, bool create_if_absent)
568 SLOGD("e4crypt_set_user_policy for %s", user_handle);
569 auto user_key = e4crypt_get_key(
570 get_key_path(mount_path, user_handle),
572 if (user_key.empty()) {
575 auto raw_ref = e4crypt_install_key(user_key);
576 if (raw_ref.empty()) {
579 return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
582 int e4crypt_create_new_user_dir(const char *user_handle, const char *path) {
583 SLOGD("e4crypt_create_new_user_dir(\"%s\", \"%s\")", user_handle, path);
584 if (mkdir(path, S_IRWXU | S_IRWXG | S_IXOTH) < 0) {
587 if (chmod(path, S_IRWXU | S_IRWXG | S_IXOTH) < 0) {
590 if (chown(path, AID_SYSTEM, AID_SYSTEM) < 0) {
593 if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
594 // ext4enc:TODO handle errors from this.
595 e4crypt_set_user_policy(DATA_MNT_POINT, user_handle, path, true);
600 static bool is_numeric(const char *name) {
601 for (const char *p = name; *p != '\0'; p++) {
608 int e4crypt_set_user_crypto_policies(const char *dir)
610 if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
613 SLOGD("e4crypt_set_user_crypto_policies");
614 std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
616 SLOGE("Unable to read directory %s, error %s\n",
617 dir, strerror(errno));
621 struct dirent *result = readdir(dirp.get());
623 // ext4enc:TODO check errno
626 if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
627 continue; // skips user 0, which is a symlink
629 auto user_dir = std::string() + dir + "/" + result->d_name;
630 // ext4enc:TODO don't hardcode /data
631 if (e4crypt_set_user_policy("/data", result->d_name,
632 user_dir.c_str(), false)) {
633 // ext4enc:TODO If this function fails, stop the boot: we must
634 // deliver on promised encryption.
635 SLOGE("Unable to set policy on %s\n", user_dir.c_str());
641 int e4crypt_delete_user_key(const char *user_handle) {
642 SLOGD("e4crypt_delete_user_key(\"%s\")", user_handle);
643 auto key_path = get_key_path(DATA_MNT_POINT, user_handle);
644 auto key = e4crypt_get_key(key_path, false);
645 auto ext4_key = fill_key(key);
646 auto ref = keyname(generate_key_ref(ext4_key.raw, ext4_key.size));
647 auto key_serial = keyctl_search(e4crypt_keyring(), "logon", ref.c_str(), 0);
648 if (keyctl_revoke(key_serial) == 0) {
649 SLOGD("Revoked key with serial %ld ref %s\n", key_serial, ref.c_str());
651 SLOGE("Failed to revoke key with serial %ld ref %s: %s\n",
652 key_serial, ref.c_str(), strerror(errno));
656 SLOGE("Unable to fork: %s", strerror(errno));
660 SLOGD("Forked for secdiscard");
661 execl("/system/bin/secdiscard",
662 "/system/bin/secdiscard",
665 SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
669 // ext4enc:TODO reap the zombie