Home | History | Annotate | Download | only in vold
      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 "KeyStorage.h"
     20 #include "Utils.h"
     21 
     22 #include <algorithm>
     23 #include <iomanip>
     24 #include <map>
     25 #include <set>
     26 #include <sstream>
     27 #include <string>
     28 
     29 #include <dirent.h>
     30 #include <errno.h>
     31 #include <fcntl.h>
     32 #include <limits.h>
     33 #include <openssl/sha.h>
     34 #include <selinux/android.h>
     35 #include <stdio.h>
     36 #include <sys/mount.h>
     37 #include <sys/stat.h>
     38 #include <sys/types.h>
     39 
     40 #include <private/android_filesystem_config.h>
     41 
     42 #include "cryptfs.h"
     43 
     44 #define EMULATED_USES_SELINUX 0
     45 #define MANAGE_MISC_DIRS 0
     46 
     47 #include <cutils/fs.h>
     48 #include <ext4_utils/ext4_crypt.h>
     49 #include <ext4_utils/key_control.h>
     50 
     51 #include <android-base/file.h>
     52 #include <android-base/logging.h>
     53 #include <android-base/stringprintf.h>
     54 
     55 using android::base::StringPrintf;
     56 using android::vold::kEmptyAuthentication;
     57 
     58 // NOTE: keep in sync with StorageManager
     59 static constexpr int FLAG_STORAGE_DE = 1 << 0;
     60 static constexpr int FLAG_STORAGE_CE = 1 << 1;
     61 
     62 namespace {
     63 
     64 const std::string device_key_dir = std::string() + DATA_MNT_POINT + e4crypt_unencrypted_folder;
     65 const std::string device_key_path = device_key_dir + "/key";
     66 const std::string device_key_temp = device_key_dir + "/temp";
     67 
     68 const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
     69 const std::string user_key_temp = user_key_dir + "/temp";
     70 
     71 bool s_global_de_initialized = false;
     72 
     73 // Some users are ephemeral, don't try to wipe their keys from disk
     74 std::set<userid_t> s_ephemeral_users;
     75 
     76 // Map user ids to key references
     77 std::map<userid_t, std::string> s_de_key_raw_refs;
     78 std::map<userid_t, std::string> s_ce_key_raw_refs;
     79 // TODO abolish this map, per b/26948053
     80 std::map<userid_t, std::string> s_ce_keys;
     81 
     82 // ext4enc:TODO get this const from somewhere good
     83 const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
     84 
     85 // ext4enc:TODO Include structure from somewhere sensible
     86 // MUST be in sync with ext4_crypto.c in kernel
     87 constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
     88 constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
     89 constexpr int EXT4_MAX_KEY_SIZE = 64;
     90 struct ext4_encryption_key {
     91     uint32_t mode;
     92     char raw[EXT4_MAX_KEY_SIZE];
     93     uint32_t size;
     94 };
     95 }
     96 
     97 static bool e4crypt_is_emulated() {
     98     return property_get_bool("persist.sys.emulate_fbe", false);
     99 }
    100 
    101 static const char* escape_null(const char* value) {
    102     return (value == nullptr) ? "null" : value;
    103 }
    104 
    105 // Get raw keyref - used to make keyname and to pass to ioctl
    106 static std::string generate_key_ref(const char* key, int length) {
    107     SHA512_CTX c;
    108 
    109     SHA512_Init(&c);
    110     SHA512_Update(&c, key, length);
    111     unsigned char key_ref1[SHA512_DIGEST_LENGTH];
    112     SHA512_Final(key_ref1, &c);
    113 
    114     SHA512_Init(&c);
    115     SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
    116     unsigned char key_ref2[SHA512_DIGEST_LENGTH];
    117     SHA512_Final(key_ref2, &c);
    118 
    119     static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
    120                   "Hash too short for descriptor");
    121     return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
    122 }
    123 
    124 static bool fill_key(const std::string& key, ext4_encryption_key* ext4_key) {
    125     if (key.size() != EXT4_AES_256_XTS_KEY_SIZE) {
    126         LOG(ERROR) << "Wrong size key " << key.size();
    127         return false;
    128     }
    129     static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key->raw), "Key too long!");
    130     ext4_key->mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
    131     ext4_key->size = key.size();
    132     memset(ext4_key->raw, 0, sizeof(ext4_key->raw));
    133     memcpy(ext4_key->raw, key.data(), key.size());
    134     return true;
    135 }
    136 
    137 static std::string keyname(const std::string& raw_ref) {
    138     std::ostringstream o;
    139     o << "ext4:";
    140     for (unsigned char i : raw_ref) {
    141         o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
    142     }
    143     return o.str();
    144 }
    145 
    146 // Get the keyring we store all keys in
    147 static bool e4crypt_keyring(key_serial_t* device_keyring) {
    148     *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
    149     if (*device_keyring == -1) {
    150         PLOG(ERROR) << "Unable to find device keyring";
    151         return false;
    152     }
    153     return true;
    154 }
    155 
    156 // Install password into global keyring
    157 // Return raw key reference for use in policy
    158 static bool install_key(const std::string& key, std::string* raw_ref) {
    159     ext4_encryption_key ext4_key;
    160     if (!fill_key(key, &ext4_key)) return false;
    161     *raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
    162     auto ref = keyname(*raw_ref);
    163     key_serial_t device_keyring;
    164     if (!e4crypt_keyring(&device_keyring)) return false;
    165     key_serial_t key_id =
    166         add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
    167     if (key_id == -1) {
    168         PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
    169         return false;
    170     }
    171     LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
    172                << " in process " << getpid();
    173 
    174     return true;
    175 }
    176 
    177 static std::string get_de_key_path(userid_t user_id) {
    178     return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
    179 }
    180 
    181 static std::string get_ce_key_directory_path(userid_t user_id) {
    182     return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
    183 }
    184 
    185 // Returns the keys newest first
    186 static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
    187     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
    188     if (!dirp) {
    189         PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
    190         return std::vector<std::string>();
    191     }
    192     std::vector<std::string> result;
    193     for (;;) {
    194         errno = 0;
    195         auto const entry = readdir(dirp.get());
    196         if (!entry) {
    197             if (errno) {
    198                 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
    199                 return std::vector<std::string>();
    200             }
    201             break;
    202         }
    203         if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
    204             LOG(DEBUG) << "Skipping non-key " << entry->d_name;
    205             continue;
    206         }
    207         result.emplace_back(directory_path + "/" + entry->d_name);
    208     }
    209     std::sort(result.begin(), result.end());
    210     std::reverse(result.begin(), result.end());
    211     return result;
    212 }
    213 
    214 static std::string get_ce_key_current_path(const std::string& directory_path) {
    215     return directory_path + "/current";
    216 }
    217 
    218 static bool get_ce_key_new_path(const std::string& directory_path,
    219                                 const std::vector<std::string>& paths,
    220                                 std::string *ce_key_path) {
    221     if (paths.empty()) {
    222         *ce_key_path = get_ce_key_current_path(directory_path);
    223         return true;
    224     }
    225     for (unsigned int i = 0; i < UINT_MAX; i++) {
    226         auto const candidate = StringPrintf("%s/cx%010u", directory_path.c_str(), i);
    227         if (paths[0] < candidate) {
    228             *ce_key_path = candidate;
    229             return true;
    230         }
    231     }
    232     return false;
    233 }
    234 
    235 // Discard all keys but the named one; rename it to canonical name.
    236 // No point in acting on errors in this; ignore them.
    237 static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix,
    238                                const std::vector<std::string>& paths) {
    239     for (auto const other_path: paths) {
    240         if (other_path != to_fix) {
    241             android::vold::destroyKey(other_path);
    242         }
    243     }
    244     auto const current_path = get_ce_key_current_path(directory_path);
    245     if (to_fix != current_path) {
    246         LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
    247         if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
    248             PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
    249         }
    250     }
    251 }
    252 
    253 static bool read_and_fixate_user_ce_key(userid_t user_id,
    254                                         const android::vold::KeyAuthentication& auth,
    255                                         std::string *ce_key) {
    256     auto const directory_path = get_ce_key_directory_path(user_id);
    257     auto const paths = get_ce_key_paths(directory_path);
    258     for (auto const ce_key_path: paths) {
    259         LOG(DEBUG) << "Trying user CE key " << ce_key_path;
    260         if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
    261             LOG(DEBUG) << "Successfully retrieved key";
    262             fixate_user_ce_key(directory_path, ce_key_path, paths);
    263             return true;
    264         }
    265     }
    266     LOG(ERROR) << "Failed to find working ce key for user " << user_id;
    267     return false;
    268 }
    269 
    270 static bool read_and_install_user_ce_key(userid_t user_id,
    271                                          const android::vold::KeyAuthentication& auth) {
    272     if (s_ce_key_raw_refs.count(user_id) != 0) return true;
    273     std::string ce_key;
    274     if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
    275     std::string ce_raw_ref;
    276     if (!install_key(ce_key, &ce_raw_ref)) return false;
    277     s_ce_keys[user_id] = ce_key;
    278     s_ce_key_raw_refs[user_id] = ce_raw_ref;
    279     LOG(DEBUG) << "Installed ce key for user " << user_id;
    280     return true;
    281 }
    282 
    283 static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
    284     LOG(DEBUG) << "Preparing: " << dir;
    285     if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
    286         PLOG(ERROR) << "Failed to prepare " << dir;
    287         return false;
    288     }
    289     return true;
    290 }
    291 
    292 static bool destroy_dir(const std::string& dir) {
    293     LOG(DEBUG) << "Destroying: " << dir;
    294     if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
    295         PLOG(ERROR) << "Failed to destroy " << dir;
    296         return false;
    297     }
    298     return true;
    299 }
    300 
    301 static bool random_key(std::string* key) {
    302     if (android::vold::ReadRandomBytes(EXT4_AES_256_XTS_KEY_SIZE, *key) != 0) {
    303         // TODO status_t plays badly with PLOG, fix it.
    304         LOG(ERROR) << "Random read failed";
    305         return false;
    306     }
    307     return true;
    308 }
    309 
    310 static bool path_exists(const std::string& path) {
    311     return access(path.c_str(), F_OK) == 0;
    312 }
    313 
    314 // NB this assumes that there is only one thread listening for crypt commands, because
    315 // it creates keys in a fixed location.
    316 static bool store_key(const std::string& key_path, const std::string& tmp_path,
    317                       const android::vold::KeyAuthentication& auth, const std::string& key) {
    318     if (path_exists(key_path)) {
    319         LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
    320         return false;
    321     }
    322     if (path_exists(tmp_path)) {
    323         android::vold::destroyKey(tmp_path);  // May be partially created so ignore errors
    324     }
    325     if (!android::vold::storeKey(tmp_path, auth, key)) return false;
    326     if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
    327         PLOG(ERROR) << "Unable to move new key to location: " << key_path;
    328         return false;
    329     }
    330     LOG(DEBUG) << "Created key " << key_path;
    331     return true;
    332 }
    333 
    334 static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
    335     std::string de_key, ce_key;
    336     if (!random_key(&de_key)) return false;
    337     if (!random_key(&ce_key)) return false;
    338     if (create_ephemeral) {
    339         // If the key should be created as ephemeral, don't store it.
    340         s_ephemeral_users.insert(user_id);
    341     } else {
    342         auto const directory_path = get_ce_key_directory_path(user_id);
    343         if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
    344         auto const paths = get_ce_key_paths(directory_path);
    345         std::string ce_key_path;
    346         if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
    347         if (!store_key(ce_key_path, user_key_temp,
    348                 kEmptyAuthentication, ce_key)) return false;
    349         fixate_user_ce_key(directory_path, ce_key_path, paths);
    350         // Write DE key second; once this is written, all is good.
    351         if (!store_key(get_de_key_path(user_id), user_key_temp,
    352                 kEmptyAuthentication, de_key)) return false;
    353     }
    354     std::string de_raw_ref;
    355     if (!install_key(de_key, &de_raw_ref)) return false;
    356     s_de_key_raw_refs[user_id] = de_raw_ref;
    357     std::string ce_raw_ref;
    358     if (!install_key(ce_key, &ce_raw_ref)) return false;
    359     s_ce_keys[user_id] = ce_key;
    360     s_ce_key_raw_refs[user_id] = ce_raw_ref;
    361     LOG(DEBUG) << "Created keys for user " << user_id;
    362     return true;
    363 }
    364 
    365 static bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
    366                            std::string* raw_ref) {
    367     auto refi = key_map.find(user_id);
    368     if (refi == key_map.end()) {
    369         LOG(ERROR) << "Cannot find key for " << user_id;
    370         return false;
    371     }
    372     *raw_ref = refi->second;
    373     return true;
    374 }
    375 
    376 static bool ensure_policy(const std::string& raw_ref, const std::string& path) {
    377     const char *contents_mode;
    378     const char *filenames_mode;
    379 
    380     cryptfs_get_file_encryption_modes(&contents_mode, &filenames_mode);
    381 
    382     if (e4crypt_policy_ensure(path.c_str(),
    383                               raw_ref.data(), raw_ref.size(),
    384                               contents_mode, filenames_mode) != 0) {
    385         LOG(ERROR) << "Failed to set policy on: " << path;
    386         return false;
    387     }
    388     return true;
    389 }
    390 
    391 static bool is_numeric(const char* name) {
    392     for (const char* p = name; *p != '\0'; p++) {
    393         if (!isdigit(*p)) return false;
    394     }
    395     return true;
    396 }
    397 
    398 static bool load_all_de_keys() {
    399     auto de_dir = user_key_dir + "/de";
    400     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
    401     if (!dirp) {
    402         PLOG(ERROR) << "Unable to read de key directory";
    403         return false;
    404     }
    405     for (;;) {
    406         errno = 0;
    407         auto entry = readdir(dirp.get());
    408         if (!entry) {
    409             if (errno) {
    410                 PLOG(ERROR) << "Unable to read de key directory";
    411                 return false;
    412             }
    413             break;
    414         }
    415         if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
    416             LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
    417             continue;
    418         }
    419         userid_t user_id = atoi(entry->d_name);
    420         if (s_de_key_raw_refs.count(user_id) == 0) {
    421             auto key_path = de_dir + "/" + entry->d_name;
    422             std::string key;
    423             if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
    424             std::string raw_ref;
    425             if (!install_key(key, &raw_ref)) return false;
    426             s_de_key_raw_refs[user_id] = raw_ref;
    427             LOG(DEBUG) << "Installed de key for user " << user_id;
    428         }
    429     }
    430     // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
    431     // correct policy set on them, and that no rogue ones exist.
    432     return true;
    433 }
    434 
    435 bool e4crypt_initialize_global_de() {
    436     LOG(INFO) << "e4crypt_initialize_global_de";
    437 
    438     if (s_global_de_initialized) {
    439         LOG(INFO) << "Already initialized";
    440         return true;
    441     }
    442 
    443     const char *contents_mode;
    444     const char *filenames_mode;
    445     cryptfs_get_file_encryption_modes(&contents_mode, &filenames_mode);
    446     std::string modestring = std::string(contents_mode) + ":" + filenames_mode;
    447 
    448     std::string mode_filename = std::string("/data") + e4crypt_key_mode;
    449     if (!android::base::WriteStringToFile(modestring, mode_filename)) {
    450         PLOG(ERROR) << "Cannot save type";
    451         return false;
    452     }
    453 
    454     std::string device_key;
    455     if (path_exists(device_key_path)) {
    456         if (!android::vold::retrieveKey(device_key_path,
    457                 kEmptyAuthentication, &device_key)) return false;
    458     } else {
    459         LOG(INFO) << "Creating new key";
    460         if (!random_key(&device_key)) return false;
    461         if (!store_key(device_key_path, device_key_temp,
    462                 kEmptyAuthentication, device_key)) return false;
    463     }
    464 
    465     std::string device_key_ref;
    466     if (!install_key(device_key, &device_key_ref)) {
    467         LOG(ERROR) << "Failed to install device key";
    468         return false;
    469     }
    470 
    471     std::string ref_filename = std::string("/data") + e4crypt_key_ref;
    472     if (!android::base::WriteStringToFile(device_key_ref, ref_filename)) {
    473         PLOG(ERROR) << "Cannot save key reference";
    474         return false;
    475     }
    476 
    477     s_global_de_initialized = true;
    478     return true;
    479 }
    480 
    481 bool e4crypt_init_user0() {
    482     LOG(DEBUG) << "e4crypt_init_user0";
    483     if (e4crypt_is_native()) {
    484         if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
    485         if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
    486         if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
    487         if (!path_exists(get_de_key_path(0))) {
    488             if (!create_and_install_user_keys(0, false)) return false;
    489         }
    490         // TODO: switch to loading only DE_0 here once framework makes
    491         // explicit calls to install DE keys for secondary users
    492         if (!load_all_de_keys()) return false;
    493     }
    494     // We can only safely prepare DE storage here, since CE keys are probably
    495     // entangled with user credentials.  The framework will always prepare CE
    496     // storage once CE keys are installed.
    497     if (!e4crypt_prepare_user_storage(nullptr, 0, 0, FLAG_STORAGE_DE)) {
    498         LOG(ERROR) << "Failed to prepare user 0 storage";
    499         return false;
    500     }
    501 
    502     // If this is a non-FBE device that recently left an emulated mode,
    503     // restore user data directories to known-good state.
    504     if (!e4crypt_is_native() && !e4crypt_is_emulated()) {
    505         e4crypt_unlock_user_key(0, 0, "!", "!");
    506     }
    507 
    508     return true;
    509 }
    510 
    511 bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
    512     LOG(DEBUG) << "e4crypt_vold_create_user_key for " << user_id << " serial " << serial;
    513     if (!e4crypt_is_native()) {
    514         return true;
    515     }
    516     // FIXME test for existence of key that is not loaded yet
    517     if (s_ce_key_raw_refs.count(user_id) != 0) {
    518         LOG(ERROR) << "Already exists, can't e4crypt_vold_create_user_key for " << user_id
    519                    << " serial " << serial;
    520         // FIXME should we fail the command?
    521         return true;
    522     }
    523     if (!create_and_install_user_keys(user_id, ephemeral)) {
    524         return false;
    525     }
    526     return true;
    527 }
    528 
    529 static bool evict_key(const std::string &raw_ref) {
    530     auto ref = keyname(raw_ref);
    531     key_serial_t device_keyring;
    532     if (!e4crypt_keyring(&device_keyring)) return false;
    533     auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
    534 
    535     // Unlink the key from the keyring.  Prefer unlinking to revoking or
    536     // invalidating, since unlinking is actually no less secure currently, and
    537     // it avoids bugs in certain kernel versions where the keyring key is
    538     // referenced from places it shouldn't be.
    539     if (keyctl_unlink(key_serial, device_keyring) != 0) {
    540         PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
    541         return false;
    542     }
    543     LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
    544     return true;
    545 }
    546 
    547 static bool evict_ce_key(userid_t user_id) {
    548     s_ce_keys.erase(user_id);
    549     bool success = true;
    550     std::string raw_ref;
    551     // If we haven't loaded the CE key, no need to evict it.
    552     if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
    553         success &= evict_key(raw_ref);
    554     }
    555     s_ce_key_raw_refs.erase(user_id);
    556     return success;
    557 }
    558 
    559 bool e4crypt_destroy_user_key(userid_t user_id) {
    560     LOG(DEBUG) << "e4crypt_destroy_user_key(" << user_id << ")";
    561     if (!e4crypt_is_native()) {
    562         return true;
    563     }
    564     bool success = true;
    565     std::string raw_ref;
    566     success &= evict_ce_key(user_id);
    567     success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && evict_key(raw_ref);
    568     s_de_key_raw_refs.erase(user_id);
    569     auto it = s_ephemeral_users.find(user_id);
    570     if (it != s_ephemeral_users.end()) {
    571         s_ephemeral_users.erase(it);
    572     } else {
    573         for (auto const path: get_ce_key_paths(get_ce_key_directory_path(user_id))) {
    574             success &= android::vold::destroyKey(path);
    575         }
    576         auto de_key_path = get_de_key_path(user_id);
    577         if (path_exists(de_key_path)) {
    578             success &= android::vold::destroyKey(de_key_path);
    579         } else {
    580             LOG(INFO) << "Not present so not erasing: " << de_key_path;
    581         }
    582     }
    583     return success;
    584 }
    585 
    586 static bool emulated_lock(const std::string& path) {
    587     if (chmod(path.c_str(), 0000) != 0) {
    588         PLOG(ERROR) << "Failed to chmod " << path;
    589         return false;
    590     }
    591 #if EMULATED_USES_SELINUX
    592     if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
    593         PLOG(WARNING) << "Failed to setfilecon " << path;
    594         return false;
    595     }
    596 #endif
    597     return true;
    598 }
    599 
    600 static bool emulated_unlock(const std::string& path, mode_t mode) {
    601     if (chmod(path.c_str(), mode) != 0) {
    602         PLOG(ERROR) << "Failed to chmod " << path;
    603         // FIXME temporary workaround for b/26713622
    604         if (e4crypt_is_emulated()) return false;
    605     }
    606 #if EMULATED_USES_SELINUX
    607     if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
    608         PLOG(WARNING) << "Failed to restorecon " << path;
    609         // FIXME temporary workaround for b/26713622
    610         if (e4crypt_is_emulated()) return false;
    611     }
    612 #endif
    613     return true;
    614 }
    615 
    616 static bool parse_hex(const char* hex, std::string* result) {
    617     if (strcmp("!", hex) == 0) {
    618         *result = "";
    619         return true;
    620     }
    621     if (android::vold::HexToStr(hex, *result) != 0) {
    622         LOG(ERROR) << "Invalid FBE hex string";  // Don't log the string for security reasons
    623         return false;
    624     }
    625     return true;
    626 }
    627 
    628 bool e4crypt_add_user_key_auth(userid_t user_id, int serial, const char* token_hex,
    629                           const char* secret_hex) {
    630     LOG(DEBUG) << "e4crypt_add_user_key_auth " << user_id << " serial=" << serial
    631                << " token_present=" << (strcmp(token_hex, "!") != 0);
    632     if (!e4crypt_is_native()) return true;
    633     if (s_ephemeral_users.count(user_id) != 0) return true;
    634     std::string token, secret;
    635     if (!parse_hex(token_hex, &token)) return false;
    636     if (!parse_hex(secret_hex, &secret)) return false;
    637     auto auth = secret.empty() ? kEmptyAuthentication
    638                                    : android::vold::KeyAuthentication(token, secret);
    639     auto it = s_ce_keys.find(user_id);
    640     if (it == s_ce_keys.end()) {
    641         LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
    642         return false;
    643     }
    644     auto ce_key = it->second;
    645     auto const directory_path = get_ce_key_directory_path(user_id);
    646     auto const paths = get_ce_key_paths(directory_path);
    647     std::string ce_key_path;
    648     if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
    649     if (!store_key(ce_key_path, user_key_temp, auth, ce_key)) return false;
    650     return true;
    651 }
    652 
    653 bool e4crypt_fixate_newest_user_key_auth(userid_t user_id) {
    654     LOG(DEBUG) << "e4crypt_fixate_newest_user_key_auth " << user_id;
    655     if (!e4crypt_is_native()) return true;
    656     if (s_ephemeral_users.count(user_id) != 0) return true;
    657     auto const directory_path = get_ce_key_directory_path(user_id);
    658     auto const paths = get_ce_key_paths(directory_path);
    659     if (paths.empty()) {
    660         LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
    661         return false;
    662     }
    663     fixate_user_ce_key(directory_path, paths[0], paths);
    664     return true;
    665 }
    666 
    667 // TODO: rename to 'install' for consistency, and take flags to know which keys to install
    668 bool e4crypt_unlock_user_key(userid_t user_id, int serial, const char* token_hex,
    669                              const char* secret_hex) {
    670     LOG(DEBUG) << "e4crypt_unlock_user_key " << user_id << " serial=" << serial
    671                << " token_present=" << (strcmp(token_hex, "!") != 0);
    672     if (e4crypt_is_native()) {
    673         if (s_ce_key_raw_refs.count(user_id) != 0) {
    674             LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
    675             return true;
    676         }
    677         std::string token, secret;
    678         if (!parse_hex(token_hex, &token)) return false;
    679         if (!parse_hex(secret_hex, &secret)) return false;
    680         android::vold::KeyAuthentication auth(token, secret);
    681         if (!read_and_install_user_ce_key(user_id, auth)) {
    682             LOG(ERROR) << "Couldn't read key for " << user_id;
    683             return false;
    684         }
    685     } else {
    686         // When in emulation mode, we just use chmod. However, we also
    687         // unlock directories when not in emulation mode, to bring devices
    688         // back into a known-good state.
    689         if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
    690             !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
    691             !emulated_unlock(android::vold::BuildDataMediaCePath(nullptr, user_id), 0770) ||
    692             !emulated_unlock(android::vold::BuildDataUserCePath(nullptr, user_id), 0771)) {
    693             LOG(ERROR) << "Failed to unlock user " << user_id;
    694             return false;
    695         }
    696     }
    697     return true;
    698 }
    699 
    700 // TODO: rename to 'evict' for consistency
    701 bool e4crypt_lock_user_key(userid_t user_id) {
    702     LOG(DEBUG) << "e4crypt_lock_user_key " << user_id;
    703     if (e4crypt_is_native()) {
    704         return evict_ce_key(user_id);
    705     } else if (e4crypt_is_emulated()) {
    706         // When in emulation mode, we just use chmod
    707         if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
    708             !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
    709             !emulated_lock(android::vold::BuildDataMediaCePath(nullptr, user_id)) ||
    710             !emulated_lock(android::vold::BuildDataUserCePath(nullptr, user_id))) {
    711             LOG(ERROR) << "Failed to lock user " << user_id;
    712             return false;
    713         }
    714     }
    715 
    716     return true;
    717 }
    718 
    719 bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial,
    720         int flags) {
    721     LOG(DEBUG) << "e4crypt_prepare_user_storage for volume " << escape_null(volume_uuid)
    722                << ", user " << user_id << ", serial " << serial << ", flags " << flags;
    723 
    724     if (flags & FLAG_STORAGE_DE) {
    725         // DE_sys key
    726         auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
    727         auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
    728         auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
    729 
    730         // DE_n key
    731         auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
    732         auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
    733         auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
    734 
    735         if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
    736 #if MANAGE_MISC_DIRS
    737         if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
    738                 multiuser_get_uid(user_id, AID_EVERYBODY))) return false;
    739 #endif
    740         if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
    741 
    742         if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
    743         if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
    744         if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
    745 
    746         // For now, FBE is only supported on internal storage
    747         if (e4crypt_is_native() && volume_uuid == nullptr) {
    748             std::string de_raw_ref;
    749             if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_raw_ref)) return false;
    750             if (!ensure_policy(de_raw_ref, system_de_path)) return false;
    751             if (!ensure_policy(de_raw_ref, misc_de_path)) return false;
    752             if (!ensure_policy(de_raw_ref, user_de_path)) return false;
    753         }
    754     }
    755 
    756     if (flags & FLAG_STORAGE_CE) {
    757         // CE_n key
    758         auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
    759         auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
    760         auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
    761         auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
    762 
    763         if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
    764         if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
    765         if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
    766         if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
    767 
    768         // For now, FBE is only supported on internal storage
    769         if (e4crypt_is_native() && volume_uuid == nullptr) {
    770             std::string ce_raw_ref;
    771             if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_raw_ref)) return false;
    772             if (!ensure_policy(ce_raw_ref, system_ce_path)) return false;
    773             if (!ensure_policy(ce_raw_ref, misc_ce_path)) return false;
    774             if (!ensure_policy(ce_raw_ref, media_ce_path)) return false;
    775             if (!ensure_policy(ce_raw_ref, user_ce_path)) return false;
    776 
    777             // Now that credentials have been installed, we can run restorecon
    778             // over these paths
    779             // NOTE: these paths need to be kept in sync with libselinux
    780             android::vold::RestoreconRecursive(system_ce_path);
    781             android::vold::RestoreconRecursive(misc_ce_path);
    782         }
    783     }
    784 
    785     return true;
    786 }
    787 
    788 bool e4crypt_destroy_user_storage(const char* volume_uuid, userid_t user_id, int flags) {
    789     LOG(DEBUG) << "e4crypt_destroy_user_storage for volume " << escape_null(volume_uuid)
    790                << ", user " << user_id << ", flags " << flags;
    791     bool res = true;
    792 
    793     if (flags & FLAG_STORAGE_DE) {
    794         // DE_sys key
    795         auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
    796         auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
    797         auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
    798 
    799         // DE_n key
    800         auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
    801         auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
    802         auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
    803 
    804         if (volume_uuid == nullptr) {
    805             res &= destroy_dir(system_legacy_path);
    806 #if MANAGE_MISC_DIRS
    807             res &= destroy_dir(misc_legacy_path);
    808 #endif
    809             res &= destroy_dir(profiles_de_path);
    810             res &= destroy_dir(system_de_path);
    811             res &= destroy_dir(misc_de_path);
    812         }
    813         res &= destroy_dir(user_de_path);
    814     }
    815 
    816     if (flags & FLAG_STORAGE_CE) {
    817         // CE_n key
    818         auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
    819         auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
    820         auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
    821         auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
    822 
    823         if (volume_uuid == nullptr) {
    824             res &= destroy_dir(system_ce_path);
    825             res &= destroy_dir(misc_ce_path);
    826         }
    827         res &= destroy_dir(media_ce_path);
    828         res &= destroy_dir(user_ce_path);
    829     }
    830 
    831     return res;
    832 }
    833 
    834 bool e4crypt_secdiscard(const char* path) {
    835     return android::vold::runSecdiscardSingle(std::string(path));
    836 }
    837