OSDN Git Service

Merge "vold: fix 64 bit ioctl error" am: 3e6c59dc16 am: bf6acf44a9
[android-x86/system-vold.git] / Ext4Crypt.cpp
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "Ext4Crypt.h"
18
19 #include "Utils.h"
20
21 #include <iomanip>
22 #include <map>
23 #include <fstream>
24 #include <string>
25 #include <sstream>
26
27 #include <errno.h>
28 #include <dirent.h>
29 #include <sys/mount.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <cutils/properties.h>
34 #include <openssl/sha.h>
35
36 #include <private/android_filesystem_config.h>
37
38 #include "unencrypted_properties.h"
39 #include "key_control.h"
40 #include "cryptfs.h"
41 #include "ext4_crypt_init_extensions.h"
42
43 #define LOG_TAG "Ext4Crypt"
44
45 #include <cutils/fs.h>
46 #include <cutils/log.h>
47 #include <cutils/klog.h>
48
49 #include <base/file.h>
50 #include <base/logging.h>
51 #include <base/stringprintf.h>
52
53 using android::base::StringPrintf;
54
55 static const char* kPropEmulateFbe = "persist.sys.emulate_fbe";
56
57 namespace {
58     // Key length in bits
59     const int key_length = 128;
60     static_assert(key_length % 8 == 0,
61                   "Key length must be multiple of 8 bits");
62
63     // How long do we store passwords for?
64     const int password_max_age_seconds = 60;
65
66     // How is device encrypted
67     struct keys {
68         std::string master_key;
69         std::string password;
70         time_t expiry_time;
71     };
72     std::map<std::string, keys> s_key_store;
73
74     // ext4enc:TODO get these consts from somewhere good
75     const int SHA512_LENGTH = 64;
76     const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
77
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 {
83         uint32_t mode;
84         char raw[EXT4_MAX_KEY_SIZE];
85         uint32_t size;
86     };
87
88     namespace tag {
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";
104     }
105 }
106
107 static std::string e4crypt_install_key(const std::string &key);
108
109 static int put_crypt_ftr_and_key(const crypt_mnt_ftr& crypt_ftr,
110                                  UnencryptedProperties& props)
111 {
112     SLOGI("Putting crypt footer");
113
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,
125                                             crypt_ftr.keysize))
126       && props.Set<std::string>(tag::salt,
127                                 std::string((const char*) crypt_ftr.salt,
128                                             SALT_LEN))
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,
138                                             SCRYPT_LEN));
139     return success ? 0 : -1;
140 }
141
142 static int get_crypt_ftr_and_key(crypt_mnt_ftr& crypt_ftr,
143                                  const UnencryptedProperties& props)
144 {
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");
161         return -1;
162     }
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");
167         return -1;
168     }
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");
178         return -1;
179     }
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");
185         return -1;
186     }
187     memcpy(crypt_ftr.scrypted_intermediate_key, &scrypted_intermediate_key[0],
188            SCRYPT_LEN);
189
190     return 0;
191 }
192
193 static UnencryptedProperties GetProps(const char* path)
194 {
195     return UnencryptedProperties(path);
196 }
197
198 static UnencryptedProperties GetAltProps(const char* path)
199 {
200     return UnencryptedProperties((std::string() + path + "/tmp_mnt").c_str());
201 }
202
203 static UnencryptedProperties GetPropsOrAltProps(const char* path)
204 {
205     UnencryptedProperties props = GetProps(path);
206     if (props.OK()) {
207         return props;
208     }
209     return GetAltProps(path);
210 }
211
212 int e4crypt_enable(const char* path)
213 {
214     // Already enabled?
215     if (s_key_store.find(path) != s_key_store.end()) {
216         return 0;
217     }
218
219     // Not an encryptable device?
220     UnencryptedProperties key_props = GetProps(path).GetChild(properties::key);
221     if (!key_props.OK()) {
222         return 0;
223     }
224
225     if (key_props.Get<std::string>(tag::master_key).empty()) {
226         crypt_mnt_ftr ftr;
227         if (cryptfs_create_default_ftr(&ftr, key_length)) {
228             SLOGE("Failed to create crypto footer");
229             return -1;
230         }
231
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;
236
237         if (put_crypt_ftr_and_key(ftr, key_props)) {
238             SLOGE("Failed to write crypto footer");
239             return -1;
240         }
241
242         crypt_mnt_ftr ftr2;
243         if (get_crypt_ftr_and_key(ftr2, key_props)) {
244             SLOGE("Failed to read crypto footer back");
245             return -1;
246         }
247
248         if (memcmp(&ftr, &ftr2, sizeof(ftr)) != 0) {
249             SLOGE("Crypto footer not correctly written");
250             return -1;
251         }
252     }
253
254     if (!UnencryptedProperties(path).Remove(properties::ref)) {
255         SLOGE("Failed to remove key ref");
256         return -1;
257     }
258
259     return e4crypt_check_passwd(path, "");
260 }
261
262 int e4crypt_change_password(const char* path, int crypt_type,
263                             const char* password)
264 {
265     SLOGI("e4crypt_change_password");
266     auto key_props = GetProps(path).GetChild(properties::key);
267
268     crypt_mnt_ftr ftr;
269     if (get_crypt_ftr_and_key(ftr, key_props)) {
270         SLOGE("Failed to read crypto footer back");
271         return -1;
272     }
273
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");
277         return -1;
278     }
279
280     const unsigned char* master_key_bytes
281         = reinterpret_cast<const unsigned char*>(&mki->second.master_key[0]);
282
283     if (cryptfs_set_password(&ftr, password, master_key_bytes)) {
284         SLOGE("Failed to set password");
285         return -1;
286     }
287
288     ftr.crypt_type = crypt_type;
289
290     if (put_crypt_ftr_and_key(ftr, key_props)) {
291         SLOGE("Failed to write crypto footer");
292         return -1;
293     }
294
295     if (!UnencryptedProperties(path).Set(properties::is_default,
296                             crypt_type == CRYPT_TYPE_DEFAULT)) {
297         SLOGE("Failed to update default flag");
298         return -1;
299     }
300
301     return 0;
302 }
303
304 int e4crypt_crypto_complete(const char* path)
305 {
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");
310         return -1;
311     }
312
313     return 0;
314 }
315
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)
318 {
319     SHA512_CTX c;
320
321     SHA512_Init(&c);
322     SHA512_Update(&c, key, length);
323     unsigned char key_ref1[SHA512_LENGTH];
324     SHA512_Final(key_ref1, &c);
325
326     SHA512_Init(&c);
327     SHA512_Update(&c, key_ref1, SHA512_LENGTH);
328     unsigned char key_ref2[SHA512_LENGTH];
329     SHA512_Final(key_ref2, &c);
330
331     return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
332 }
333
334 int e4crypt_check_passwd(const char* path, const char* password)
335 {
336     SLOGI("e4crypt_check_password");
337     auto props = GetPropsOrAltProps(path);
338     auto key_props = props.GetChild(properties::key);
339
340     crypt_mnt_ftr ftr;
341     if (get_crypt_ftr_and_key(ftr, key_props)) {
342         SLOGE("Failed to read crypto footer back");
343         return -1;
344     }
345
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");
352         }
353         return ftr.failed_decrypt_count;
354     }
355
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");
360         }
361     }
362     std::string master_key(reinterpret_cast<char*>(master_key_bytes),
363                            sizeof(master_key_bytes));
364
365     struct timespec now;
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()) {
371         return -1;
372     }
373
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");
377         return -1;
378     }
379
380     return 0;
381 }
382
383 static ext4_encryption_key fill_key(const std::string &key)
384 {
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,
389                                     {0},
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),
393                   "Key too long!");
394     memcpy(ext4_key.raw, &key[0], key.size());
395     return ext4_key;
396 }
397
398 static std::string keyname(const std::string &raw_ref)
399 {
400     std::ostringstream o;
401     o << "ext4:";
402     for (auto i = raw_ref.begin(); i != raw_ref.end(); ++i) {
403         o << std::hex << std::setw(2) << std::setfill('0') << (int)*i;
404     }
405     return o.str();
406 }
407
408 // Get the keyring we store all keys in
409 static key_serial_t e4crypt_keyring()
410 {
411     return keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
412 }
413
414 static int e4crypt_install_key(const ext4_encryption_key &ext4_key, const std::string &ref)
415 {
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),
420                                   device_keyring);
421     if (key_id == -1) {
422         SLOGE("Failed to insert key into keyring with error %s",
423               strerror(errno));
424         return -1;
425     }
426     SLOGI("Added key %d (%s) to keyring %d in process %d",
427           key_id, ref.c_str(), device_keyring, getpid());
428     return 0;
429 }
430
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)
434 {
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) {
439         return "";
440     }
441     return raw_ref;
442 }
443
444 int e4crypt_restart(const char* path)
445 {
446     SLOGI("e4crypt_restart");
447
448     int rc = 0;
449
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");
453     sleep(2);
454
455     std::string tmp_path = std::string() + path + "/tmp_mnt";
456
457     rc = wait_and_unmount(tmp_path.c_str(), true);
458     if (rc) {
459         SLOGE("umount %s failed with rc %d, msg %s",
460               tmp_path.c_str(), rc, strerror(errno));
461         return rc;
462     }
463
464     rc = wait_and_unmount(path, true);
465     if (rc) {
466         SLOGE("umount %s failed with rc %d, msg %s",
467               path, rc, strerror(errno));
468         return rc;
469     }
470
471     return 0;
472 }
473
474 int e4crypt_get_password_type(const char* path)
475 {
476     SLOGI("e4crypt_get_password_type");
477     return GetPropsOrAltProps(path).GetChild(properties::key)
478       .Get<int>(tag::crypt_type, CRYPT_TYPE_DEFAULT);
479 }
480
481 const char* e4crypt_get_password(const char* path)
482 {
483     SLOGI("e4crypt_get_password");
484
485     auto i = s_key_store.find(path);
486     if (i == s_key_store.end()) {
487         return 0;
488     }
489
490     struct timespec now;
491     clock_gettime(CLOCK_BOOTTIME, &now);
492     if (i->second.expiry_time < now.tv_sec) {
493         e4crypt_clear_password(path);
494         return 0;
495     }
496
497     return i->second.password.c_str();
498 }
499
500 void e4crypt_clear_password(const char* path)
501 {
502     SLOGI("e4crypt_clear_password");
503
504     auto i = s_key_store.find(path);
505     if (i == s_key_store.end()) {
506         return;
507     }
508
509     memset(&i->second.password[0], 0, i->second.password.size());
510     i->second.password = std::string();
511 }
512
513 int e4crypt_get_field(const char* path, const char* fieldname,
514                       char* value, size_t len)
515 {
516     auto v = GetPropsOrAltProps(path).GetChild(properties::props)
517       .Get<std::string>(fieldname);
518
519     if (v == "") {
520         return CRYPTO_GETFIELD_ERROR_NO_FIELD;
521     }
522
523     if (v.length() >= len) {
524         return CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
525     }
526
527     strlcpy(value, v.c_str(), len);
528     return 0;
529 }
530
531 int e4crypt_set_field(const char* path, const char* fieldname,
532                       const char* value)
533 {
534     return GetPropsOrAltProps(path).GetChild(properties::props)
535         .Set(fieldname, std::string(value)) ? 0 : -1;
536 }
537
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;
543         return "";
544     }
545     return StringPrintf("%s/%d", key_dir.c_str(), user_id);
546 }
547
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)
553 {
554     std::string content;
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());
558             return "";
559         }
560         return content;
561     }
562     if (!create_if_absent) {
563         SLOGE("No key found in %s", key_path.c_str());
564         return "";
565     }
566     std::ifstream urandom("/dev/urandom");
567     if (!urandom) {
568         SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
569         return "";
570     }
571     char key_bytes[key_length / 8];
572     errno = 0;
573     urandom.read(key_bytes, sizeof(key_bytes));
574     if (!urandom) {
575         SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
576         return "";
577     }
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));
582         return "";
583     }
584     return key;
585 }
586
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),
591             create_if_absent);
592     if (user_key.empty()) {
593         return -1;
594     }
595     auto raw_ref = e4crypt_install_key(user_key);
596     if (raw_ref.empty()) {
597         return -1;
598     }
599     return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
600 }
601
602 static bool is_numeric(const char *name) {
603     for (const char *p = name; *p != '\0'; p++) {
604         if (!isdigit(*p))
605             return false;
606     }
607     return true;
608 }
609
610 int e4crypt_set_user_crypto_policies(const char *dir)
611 {
612     if (e4crypt_crypto_complete(DATA_MNT_POINT) != 0) {
613         return 0;
614     }
615     SLOGD("e4crypt_set_user_crypto_policies");
616     std::unique_ptr<DIR, int(*)(DIR*)> dirp(opendir(dir), closedir);
617     if (!dirp) {
618         SLOGE("Unable to read directory %s, error %s\n",
619             dir, strerror(errno));
620         return -1;
621     }
622     for (;;) {
623         struct dirent *result = readdir(dirp.get());
624         if (!result) {
625             // ext4enc:TODO check errno
626             break;
627         }
628         if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
629             continue; // skips user 0, which is a symlink
630         }
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());
638         }
639     }
640     return 0;
641 }
642
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()) {
647         return -1;
648     } else {
649         return 0;
650     }
651 }
652
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());
663     } else {
664         SLOGE("Failed to revoke key with serial %ld ref %s: %s\n",
665             key_serial, ref.c_str(), strerror(errno));
666     }
667     int pid = fork();
668     if (pid < 0) {
669         SLOGE("Unable to fork: %s", strerror(errno));
670         return -1;
671     }
672     if (pid == 0) {
673         SLOGD("Forked for secdiscard");
674         execl("/system/bin/secdiscard",
675             "/system/bin/secdiscard",
676             "--",
677             key_path.c_str(),
678             NULL);
679         SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
680             strerror(errno));
681         exit(-1);
682     }
683     // ext4enc:TODO reap the zombie
684     return 0;
685 }
686
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;
693             return -1;
694         }
695     } else {
696         auto user_key = e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), false);
697         if (user_key.empty()) {
698             return -1;
699         }
700         auto raw_ref = e4crypt_install_key(user_key);
701         if (raw_ref.empty()) {
702             return -1;
703         }
704     }
705     return 0;
706 }
707
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;
714             return -1;
715         }
716     } else {
717         // TODO: remove from kernel keyring
718     }
719     return 0;
720 }
721
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));
726
727     if (fs_prepare_dir(system_ce_path.c_str(), 0700, AID_SYSTEM, AID_SYSTEM)) {
728         PLOG(ERROR) << "Failed to prepare " << system_ce_path;
729         return -1;
730     }
731     if (fs_prepare_dir(user_ce_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
732         PLOG(ERROR) << "Failed to prepare " << user_ce_path;
733         return -1;
734     }
735     if (fs_prepare_dir(user_de_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
736         PLOG(ERROR) << "Failed to prepare " << user_de_path;
737         return -1;
738     }
739
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)) {
743             return -1;
744         }
745     }
746
747     return 0;
748 }