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 "FsCrypt.h"
18 
19 #include "Checkpoint.h"
20 #include "KeyStorage.h"
21 #include "KeyUtil.h"
22 #include "Utils.h"
23 #include "VoldUtil.h"
24 
25 #include <algorithm>
26 #include <map>
27 #include <optional>
28 #include <set>
29 #include <sstream>
30 #include <string>
31 #include <vector>
32 
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <limits.h>
37 #include <sys/mount.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <unistd.h>
41 
42 #include <private/android_filesystem_config.h>
43 #include <private/android_projectid_config.h>
44 
45 #include "android/os/IVold.h"
46 
47 #include <cutils/fs.h>
48 #include <cutils/properties.h>
49 
50 #include <fscrypt/fscrypt.h>
51 #include <libdm/dm.h>
52 
53 #include <android-base/file.h>
54 #include <android-base/logging.h>
55 #include <android-base/properties.h>
56 #include <android-base/stringprintf.h>
57 #include <android-base/strings.h>
58 #include <android-base/unique_fd.h>
59 
60 using android::base::Basename;
61 using android::base::Realpath;
62 using android::base::StartsWith;
63 using android::base::StringPrintf;
64 using android::fs_mgr::GetEntryForMountPoint;
65 using android::vold::BuildDataPath;
66 using android::vold::IsDotOrDotDot;
67 using android::vold::IsFilesystemSupported;
68 using android::vold::kEmptyAuthentication;
69 using android::vold::KeyBuffer;
70 using android::vold::KeyGeneration;
71 using android::vold::retrieveKey;
72 using android::vold::retrieveOrGenerateKey;
73 using android::vold::SetDefaultAcl;
74 using android::vold::SetQuotaInherit;
75 using android::vold::SetQuotaProjectId;
76 using namespace android::fscrypt;
77 using namespace android::dm;
78 
79 namespace {
80 
81 const std::string device_key_dir = std::string() + DATA_MNT_POINT + fscrypt_unencrypted_folder;
82 const std::string device_key_path = device_key_dir + "/key";
83 const std::string device_key_temp = device_key_dir + "/temp";
84 
85 const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
86 const std::string user_key_temp = user_key_dir + "/temp";
87 const std::string prepare_subdirs_path = "/system/bin/vold_prepare_subdirs";
88 
89 const std::string systemwide_volume_key_dir =
90     std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
91 
92 const std::string data_data_dir = std::string() + DATA_MNT_POINT + "/data";
93 const std::string data_user_0_dir = std::string() + DATA_MNT_POINT + "/user/0";
94 const std::string media_obb_dir = std::string() + DATA_MNT_POINT + "/media/obb";
95 
96 // The file encryption options to use on the /data filesystem
97 EncryptionOptions s_data_options;
98 
99 // Some users are ephemeral; don't try to store or wipe their keys on disk.
100 std::set<userid_t> s_ephemeral_users;
101 
102 // New CE keys that haven't been committed to disk yet
103 std::map<userid_t, KeyBuffer> s_new_ce_keys;
104 
105 // CE key fixation operations that have been deferred to checkpoint commit
106 std::map<std::string, std::string> s_deferred_fixations;
107 
108 // The system DE encryption policy
109 EncryptionPolicy s_device_policy;
110 
111 // Struct that holds the EncryptionPolicy for each CE or DE key that is currently installed
112 // (added to the kernel) for a particular user
113 struct UserPolicies {
114     // Internal storage policy.  Exists whenever a user's UserPolicies exists at all, and used
115     // instead of a map entry keyed by an empty UUID to make this invariant explicit.
116     EncryptionPolicy internal;
117     // Adoptable storage policies, indexed by (nonempty) volume UUID
118     std::map<std::string, EncryptionPolicy> adoptable;
119 };
120 
121 // The currently installed CE and DE keys for each user.  Protected by VolumeManager::mCryptLock.
122 std::map<userid_t, UserPolicies> s_ce_policies;
123 std::map<userid_t, UserPolicies> s_de_policies;
124 
125 }  // namespace
126 
127 // Returns KeyGeneration suitable for key as described in EncryptionOptions
makeGen(const EncryptionOptions & options)128 static KeyGeneration makeGen(const EncryptionOptions& options) {
129     if (options.version == 0) {
130         LOG(ERROR) << "EncryptionOptions not initialized";
131         return android::vold::neverGen();
132     }
133     return KeyGeneration{FSCRYPT_MAX_KEY_SIZE, true, options.use_hw_wrapped_key};
134 }
135 
escape_empty(const std::string & value)136 static const char* escape_empty(const std::string& value) {
137     return value.empty() ? "null" : value.c_str();
138 }
139 
get_de_key_path(userid_t user_id)140 static std::string get_de_key_path(userid_t user_id) {
141     return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
142 }
143 
get_ce_key_directory_path(userid_t user_id)144 static std::string get_ce_key_directory_path(userid_t user_id) {
145     return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
146 }
147 
148 // Returns the keys newest first
get_ce_key_paths(const std::string & directory_path)149 static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
150     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
151     if (!dirp) {
152         PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
153         return std::vector<std::string>();
154     }
155     std::vector<std::string> result;
156     for (;;) {
157         errno = 0;
158         auto const entry = readdir(dirp.get());
159         if (!entry) {
160             if (errno) {
161                 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
162                 return std::vector<std::string>();
163             }
164             break;
165         }
166         if (IsDotOrDotDot(*entry)) continue;
167         if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
168             LOG(DEBUG) << "Skipping non-key " << entry->d_name;
169             continue;
170         }
171         result.emplace_back(directory_path + "/" + entry->d_name);
172     }
173     std::sort(result.begin(), result.end());
174     std::reverse(result.begin(), result.end());
175     return result;
176 }
177 
get_ce_key_current_path(const std::string & directory_path)178 static std::string get_ce_key_current_path(const std::string& directory_path) {
179     return directory_path + "/current";
180 }
181 
get_ce_key_new_path(const std::string & directory_path,const std::vector<std::string> & paths,std::string * ce_key_path)182 static bool get_ce_key_new_path(const std::string& directory_path,
183                                 const std::vector<std::string>& paths, std::string* ce_key_path) {
184     if (paths.empty()) {
185         *ce_key_path = get_ce_key_current_path(directory_path);
186         return true;
187     }
188     for (unsigned int i = 0; i < UINT_MAX; i++) {
189         auto const candidate = StringPrintf("%s/cx%010u", directory_path.c_str(), i);
190         if (paths[0] < candidate) {
191             *ce_key_path = candidate;
192             return true;
193         }
194     }
195     return false;
196 }
197 
198 // Discard all keys but the named one; rename it to canonical name.
fixate_user_ce_key(const std::string & directory_path,const std::string & to_fix,const std::vector<std::string> & paths)199 static bool fixate_user_ce_key(const std::string& directory_path, const std::string& to_fix,
200                                const std::vector<std::string>& paths) {
201     bool need_sync = false;
202     for (auto const other_path : paths) {
203         if (other_path != to_fix) {
204             android::vold::destroyKey(other_path);
205             need_sync = true;
206         }
207     }
208     auto const current_path = get_ce_key_current_path(directory_path);
209     if (to_fix != current_path) {
210         LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
211         if (!android::vold::RenameKeyDir(to_fix, current_path)) return false;
212         need_sync = true;
213     }
214     if (need_sync && !android::vold::FsyncDirectory(directory_path)) return false;
215     return true;
216 }
217 
read_and_fixate_user_ce_key(userid_t user_id,const android::vold::KeyAuthentication & auth,KeyBuffer * ce_key)218 static bool read_and_fixate_user_ce_key(userid_t user_id,
219                                         const android::vold::KeyAuthentication& auth,
220                                         KeyBuffer* ce_key) {
221     auto const directory_path = get_ce_key_directory_path(user_id);
222     auto const paths = get_ce_key_paths(directory_path);
223     for (auto const ce_key_path : paths) {
224         LOG(DEBUG) << "Trying user CE key " << ce_key_path;
225         if (retrieveKey(ce_key_path, auth, ce_key)) {
226             LOG(DEBUG) << "Successfully retrieved key";
227             s_deferred_fixations.erase(directory_path);
228             fixate_user_ce_key(directory_path, ce_key_path, paths);
229             return true;
230         }
231     }
232     LOG(ERROR) << "Failed to find working ce key for user " << user_id;
233     return false;
234 }
235 
MightBeEmmcStorage(const std::string & blk_device)236 static bool MightBeEmmcStorage(const std::string& blk_device) {
237     // Handle symlinks.
238     std::string real_path;
239     if (!Realpath(blk_device, &real_path)) {
240         real_path = blk_device;
241     }
242 
243     // Handle logical volumes.
244     auto& dm = DeviceMapper::Instance();
245     for (;;) {
246         auto parent = dm.GetParentBlockDeviceByPath(real_path);
247         if (!parent.has_value()) break;
248         real_path = *parent;
249     }
250 
251     // Now we should have the "real" block device.
252     LOG(DEBUG) << "MightBeEmmcStorage(): blk_device = " << blk_device
253                << ", real_path=" << real_path;
254     std::string name = Basename(real_path);
255     return StartsWith(name, "mmcblk") ||
256            // virtio devices may provide inline encryption support that is
257            // backed by eMMC inline encryption on the host, thus inheriting the
258            // DUN size limitation.  So virtio devices must be allowed here too.
259            // TODO(b/207390665): check the maximum DUN size directly instead.
260            StartsWith(name, "vd");
261 }
262 
263 // Sets s_data_options to the file encryption options for the /data filesystem.
init_data_file_encryption_options()264 static bool init_data_file_encryption_options() {
265     auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
266     if (entry == nullptr) {
267         LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
268         return false;
269     }
270     if (!ParseOptions(entry->encryption_options, &s_data_options)) {
271         LOG(ERROR) << "Unable to parse encryption options for " << DATA_MNT_POINT ": "
272                    << entry->encryption_options;
273         return false;
274     }
275     if ((s_data_options.flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
276         !MightBeEmmcStorage(entry->blk_device)) {
277         LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage.  Remove "
278                       "this flag from the device's fstab";
279         return false;
280     }
281     return true;
282 }
283 
install_storage_key(const std::string & mountpoint,const EncryptionOptions & options,const KeyBuffer & key,EncryptionPolicy * policy)284 static bool install_storage_key(const std::string& mountpoint, const EncryptionOptions& options,
285                                 const KeyBuffer& key, EncryptionPolicy* policy) {
286     if (options.version == 0) {
287         LOG(ERROR) << "EncryptionOptions not initialized";
288         return false;
289     }
290     KeyBuffer ephemeral_wrapped_key;
291     if (options.use_hw_wrapped_key) {
292         if (!exportWrappedStorageKey(key, &ephemeral_wrapped_key)) {
293             LOG(ERROR) << "Failed to get ephemeral wrapped key";
294             return false;
295         }
296     }
297     return installKey(mountpoint, options, options.use_hw_wrapped_key ? ephemeral_wrapped_key : key,
298                       policy);
299 }
300 
301 // Retrieve the options to use for encryption policies on adoptable storage.
get_volume_file_encryption_options(EncryptionOptions * options)302 static bool get_volume_file_encryption_options(EncryptionOptions* options) {
303     // If we give the empty string, libfscrypt will use the default (currently XTS)
304     auto contents_mode = android::base::GetProperty("ro.crypto.volume.contents_mode", "");
305     // HEH as default was always a mistake. Use the libfscrypt default (CTS)
306     // for devices launching on versions above Android 10.
307     auto first_api_level = GetFirstApiLevel();
308     auto filenames_mode =
309             android::base::GetProperty("ro.crypto.volume.filenames_mode",
310                                        first_api_level > __ANDROID_API_Q__ ? "" : "aes-256-heh");
311     auto options_string = android::base::GetProperty("ro.crypto.volume.options",
312                                                      contents_mode + ":" + filenames_mode);
313     if (!ParseOptionsForApiLevel(first_api_level, options_string, options)) {
314         LOG(ERROR) << "Unable to parse volume encryption options: " << options_string;
315         return false;
316     }
317     if (options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
318         LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage.  Remove "
319                       "this flag from ro.crypto.volume.options";
320         return false;
321     }
322     return true;
323 }
324 
325 // Prepare a directory without assigning it an encryption policy.  The directory
326 // will inherit the encryption policy of its parent directory, or will be
327 // unencrypted if the parent directory is unencrypted.
prepare_dir(const std::string & dir,mode_t mode,uid_t uid,gid_t gid)328 static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
329     LOG(DEBUG) << "Preparing: " << dir;
330     if (android::vold::PrepareDir(dir, mode, uid, gid, 0) != 0) {
331         PLOG(ERROR) << "Failed to prepare " << dir;
332         return false;
333     }
334     return true;
335 }
336 
337 // Prepare a directory and assign it the given encryption policy.
prepare_dir_with_policy(const std::string & dir,mode_t mode,uid_t uid,gid_t gid,const EncryptionPolicy & policy)338 static bool prepare_dir_with_policy(const std::string& dir, mode_t mode, uid_t uid, gid_t gid,
339                                     const EncryptionPolicy& policy) {
340     if (android::vold::pathExists(dir)) {
341         if (!prepare_dir(dir, mode, uid, gid)) return false;
342         if (IsFbeEnabled() && !EnsurePolicy(policy, dir)) return false;
343     } else {
344         // If the directory does not yet exist, then create it under a temporary name, and only move
345         // it to the final name after it is fully prepared with an encryption policy and the desired
346         // file permissions.  This prevents the directory from being accessed before it is ready.
347         //
348         // Note: this relies on the SELinux file_contexts assigning the same type to the file path
349         // with the ".new" suffix as to the file path without the ".new" suffix.
350 
351         const std::string tmp_dir = dir + ".new";
352         if (android::vold::pathExists(tmp_dir)) {
353             android::vold::DeleteDirContentsAndDir(tmp_dir);
354         }
355         if (!prepare_dir(tmp_dir, mode, uid, gid)) return false;
356         if (IsFbeEnabled() && !EnsurePolicy(policy, tmp_dir)) return false;
357 
358         // On some buggy kernels, renaming a directory that is both encrypted and case-insensitive
359         // fails in some specific circumstances.  Unfortunately, these circumstances happen here
360         // when processing the "media" directory.  This was already fixed by kernel commit
361         // https://git.kernel.org/linus/b5639bb4313b9d45 ('f2fs: don't use casefolded comparison for
362         // "." and ".."').  But to support kernels that lack that fix, we use the below workaround.
363         // It bypasses the bug by making the encryption key of tmp_dir be loaded before the rename.
364         android::vold::pathExists(tmp_dir + "/subdir");
365 
366         if (rename(tmp_dir.c_str(), dir.c_str()) != 0) {
367             PLOG(ERROR) << "Failed to rename " << tmp_dir << " to " << dir;
368             return false;
369         }
370     }
371     return true;
372 }
373 
destroy_dir(const std::string & dir)374 static bool destroy_dir(const std::string& dir) {
375     LOG(DEBUG) << "Destroying: " << dir;
376     if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
377         PLOG(ERROR) << "Failed to destroy " << dir;
378         return false;
379     }
380     return true;
381 }
382 
383 // Checks whether the DE key directory exists for the given user.
de_key_exists(userid_t user_id)384 static bool de_key_exists(userid_t user_id) {
385     return android::vold::pathExists(get_de_key_path(user_id));
386 }
387 
388 // Checks whether at least one CE key subdirectory exists for the given user.
ce_key_exists(userid_t user_id)389 static bool ce_key_exists(userid_t user_id) {
390     auto directory_path = get_ce_key_directory_path(user_id);
391     // The common case is that "$dir/current" exists, so check for that first.
392     if (android::vold::pathExists(get_ce_key_current_path(directory_path))) return true;
393 
394     // Else, there could still be another subdirectory of $dir (if a crash
395     // occurred during fixate_user_ce_key()), so check for one.
396     return android::vold::pathExists(directory_path) && !get_ce_key_paths(directory_path).empty();
397 }
398 
create_de_key(userid_t user_id,bool ephemeral)399 static bool create_de_key(userid_t user_id, bool ephemeral) {
400     KeyBuffer de_key;
401     if (!generateStorageKey(makeGen(s_data_options), &de_key)) return false;
402     if (!ephemeral && !android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
403                                                          kEmptyAuthentication, de_key))
404         return false;
405     EncryptionPolicy de_policy;
406     if (!install_storage_key(DATA_MNT_POINT, s_data_options, de_key, &de_policy)) return false;
407     s_de_policies[user_id].internal = de_policy;
408     LOG(INFO) << "Created DE key for user " << user_id;
409     return true;
410 }
411 
create_ce_key(userid_t user_id,bool ephemeral)412 static bool create_ce_key(userid_t user_id, bool ephemeral) {
413     KeyBuffer ce_key;
414     if (!generateStorageKey(makeGen(s_data_options), &ce_key)) return false;
415     if (!ephemeral) {
416         if (!prepare_dir(get_ce_key_directory_path(user_id), 0700, AID_ROOT, AID_ROOT))
417             return false;
418         // We don't store the CE key on disk here, since here we don't have the
419         // secret needed to do so securely.  Instead, we cache it in memory for
420         // now, and we store it later in fscrypt_set_ce_key_protection().
421         s_new_ce_keys.insert({user_id, ce_key});
422     }
423     EncryptionPolicy ce_policy;
424     if (!install_storage_key(DATA_MNT_POINT, s_data_options, ce_key, &ce_policy)) return false;
425     s_ce_policies[user_id].internal = ce_policy;
426     LOG(INFO) << "Created CE key for user " << user_id;
427     return true;
428 }
429 
is_numeric(const char * name)430 static bool is_numeric(const char* name) {
431     for (const char* p = name; *p != '\0'; p++) {
432         if (!isdigit(*p)) return false;
433     }
434     return true;
435 }
436 
load_all_de_keys()437 static bool load_all_de_keys() {
438     auto de_dir = user_key_dir + "/de";
439     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
440     if (!dirp) {
441         PLOG(ERROR) << "Unable to read de key directory";
442         return false;
443     }
444     for (;;) {
445         errno = 0;
446         auto entry = readdir(dirp.get());
447         if (!entry) {
448             if (errno) {
449                 PLOG(ERROR) << "Unable to read de key directory";
450                 return false;
451             }
452             break;
453         }
454         if (IsDotOrDotDot(*entry)) continue;
455         if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
456             LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
457             continue;
458         }
459         userid_t user_id = std::stoi(entry->d_name);
460         auto key_path = de_dir + "/" + entry->d_name;
461         KeyBuffer de_key;
462         if (!retrieveKey(key_path, kEmptyAuthentication, &de_key)) {
463             // This is probably a partially removed user, so ignore
464             if (user_id != 0) continue;
465             return false;
466         }
467         EncryptionPolicy de_policy;
468         if (!install_storage_key(DATA_MNT_POINT, s_data_options, de_key, &de_policy)) return false;
469         const auto& [existing, is_new] = s_de_policies.insert({user_id, {de_policy, {}}});
470         if (!is_new && existing->second.internal != de_policy) {
471             LOG(ERROR) << "DE policy for user" << user_id << " changed";
472             return false;
473         }
474         LOG(DEBUG) << "Installed de key for user " << user_id;
475     }
476     // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
477     // correct policy set on them, and that no rogue ones exist.
478     return true;
479 }
480 
fscrypt_initialize_systemwide_keys()481 bool fscrypt_initialize_systemwide_keys() {
482     LOG(INFO) << "fscrypt_initialize_systemwide_keys";
483 
484     if (!init_data_file_encryption_options()) return false;
485 
486     KeyBuffer device_key;
487     if (!retrieveOrGenerateKey(device_key_path, device_key_temp, kEmptyAuthentication,
488                                makeGen(s_data_options), &device_key))
489         return false;
490 
491     // This initializes s_device_policy, which is a global variable so that
492     // fscrypt_init_user0() can access it later.
493     if (!install_storage_key(DATA_MNT_POINT, s_data_options, device_key, &s_device_policy))
494         return false;
495 
496     std::string options_string;
497     if (!OptionsToString(s_device_policy.options, &options_string)) {
498         LOG(ERROR) << "Unable to serialize options";
499         return false;
500     }
501     std::string options_filename = std::string(DATA_MNT_POINT) + fscrypt_key_mode;
502     if (!android::vold::writeStringToFile(options_string, options_filename)) return false;
503 
504     std::string ref_filename = std::string(DATA_MNT_POINT) + fscrypt_key_ref;
505     if (!android::vold::writeStringToFile(s_device_policy.key_raw_ref, ref_filename)) return false;
506     LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
507 
508     KeyBuffer per_boot_key;
509     if (!generateStorageKey(makeGen(s_data_options), &per_boot_key)) return false;
510     EncryptionPolicy per_boot_policy;
511     if (!install_storage_key(DATA_MNT_POINT, s_data_options, per_boot_key, &per_boot_policy))
512         return false;
513     std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
514     if (!android::vold::writeStringToFile(per_boot_policy.key_raw_ref, per_boot_ref_filename))
515         return false;
516     LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
517 
518     return true;
519 }
520 
prepare_special_dirs()521 static bool prepare_special_dirs() {
522     // Ensure that /data/data and its "alias" /data/user/0 exist, and create the
523     // bind mount of /data/data onto /data/user/0.  This *should* happen in
524     // fscrypt_prepare_user_storage().  However, it actually must be done early,
525     // before the rest of user 0's CE storage is prepared.  This is because
526     // zygote may need to set up app data isolation before then, which requires
527     // mounting a tmpfs over /data/data to ensure it remains hidden.  This issue
528     // arises due to /data/data being in the top-level directory.
529 
530     // /data/user/0 used to be a symlink to /data/data, so we must first delete
531     // the old symlink if present.
532     if (android::vold::IsSymlink(data_user_0_dir) && android::vold::Unlink(data_user_0_dir) != 0)
533         return false;
534     // On first boot, we'll be creating /data/data for the first time, and user
535     // 0's CE key will be installed already since it was just created.  Take the
536     // opportunity to also set the encryption policy of /data/data right away.
537     if (s_ce_policies.count(0) != 0) {
538         const EncryptionPolicy& ce_policy = s_ce_policies[0].internal;
539         if (!prepare_dir_with_policy(data_data_dir, 0771, AID_SYSTEM, AID_SYSTEM, ce_policy)) {
540             // Preparing /data/data failed, yet we had just generated a new CE
541             // key because one wasn't stored.  Before erroring out, try deleting
542             // the directory and retrying, as it's possible that the directory
543             // exists with different CE policy from an interrupted first boot.
544             if (rmdir(data_data_dir.c_str()) != 0) {
545                 PLOG(ERROR) << "rmdir " << data_data_dir << " failed";
546             }
547             if (!prepare_dir_with_policy(data_data_dir, 0771, AID_SYSTEM, AID_SYSTEM, ce_policy))
548                 return false;
549         }
550     } else {
551         if (!prepare_dir(data_data_dir, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
552         // EnsurePolicy() will have to happen later, in fscrypt_prepare_user_storage().
553     }
554     if (!prepare_dir(data_user_0_dir, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
555     if (android::vold::BindMount(data_data_dir, data_user_0_dir) != 0) return false;
556 
557     // If /data/media/obb doesn't exist, create it and encrypt it with the
558     // device policy.  Normally, device-policy-encrypted directories are created
559     // and encrypted by init; /data/media/obb is special because it is located
560     // in /data/media.  Since /data/media also contains per-user encrypted
561     // directories, by design only vold can write to it.  As a side effect of
562     // that, vold must create /data/media/obb.
563     //
564     // We must tolerate /data/media/obb being unencrypted if it already exists
565     // on-disk, since it used to be unencrypted (b/64566063).
566     if (android::vold::pathExists(media_obb_dir)) {
567         if (!prepare_dir(media_obb_dir, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
568     } else {
569         if (!prepare_dir_with_policy(media_obb_dir, 0770, AID_MEDIA_RW, AID_MEDIA_RW,
570                                      s_device_policy))
571             return false;
572     }
573     return true;
574 }
575 
576 bool fscrypt_init_user0_done;
577 
fscrypt_init_user0()578 bool fscrypt_init_user0() {
579     LOG(DEBUG) << "fscrypt_init_user0";
580 
581     if (IsFbeEnabled()) {
582         if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
583         if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
584         if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
585 
586         // Create user 0's DE and CE keys if they don't already exist.  Check
587         // each key independently, since if the first boot was interrupted it is
588         // possible that the DE key exists but the CE key does not.
589         if (!de_key_exists(0) && !create_de_key(0, false)) return false;
590         if (!ce_key_exists(0) && !create_ce_key(0, false)) return false;
591 
592         // TODO: switch to loading only DE_0 here once framework makes
593         // explicit calls to install DE keys for secondary users
594         if (!load_all_de_keys()) return false;
595     }
596 
597     // Now that user 0's CE key has been created, we can prepare /data/data.
598     if (!prepare_special_dirs()) return false;
599 
600     // With the exception of what is done by prepare_special_dirs() above, we
601     // only prepare DE storage here, since user 0's CE key won't be installed
602     // yet unless it was just created.  The framework will prepare the user's CE
603     // storage later, once their CE key is installed.
604     if (!fscrypt_prepare_user_storage("", 0, android::os::IVold::STORAGE_FLAG_DE)) {
605         LOG(ERROR) << "Failed to prepare user 0 storage";
606         return false;
607     }
608 
609     fscrypt_init_user0_done = true;
610     return true;
611 }
612 
613 // Creates the CE and DE keys for a new user.
fscrypt_create_user_keys(userid_t user_id,bool ephemeral)614 bool fscrypt_create_user_keys(userid_t user_id, bool ephemeral) {
615     LOG(DEBUG) << "fscrypt_create_user_keys for " << user_id;
616     if (!IsFbeEnabled()) {
617         return true;
618     }
619     // FIXME test for existence of key that is not loaded yet
620     if (s_ce_policies.count(user_id) != 0) {
621         LOG(ERROR) << "Already exists, can't create keys for " << user_id;
622         // FIXME should we fail the command?
623         return true;
624     }
625     if (!create_de_key(user_id, ephemeral)) return false;
626     if (!create_ce_key(user_id, ephemeral)) return false;
627     if (ephemeral) s_ephemeral_users.insert(user_id);
628     return true;
629 }
630 
631 // Evicts all the user's keys of one type from all volumes (internal and adoptable).
632 // This evicts either CE keys or DE keys, depending on which map is passed.
evict_user_keys(std::map<userid_t,UserPolicies> & policy_map,userid_t user_id)633 static bool evict_user_keys(std::map<userid_t, UserPolicies>& policy_map, userid_t user_id) {
634     bool success = true;
635     auto it = policy_map.find(user_id);
636     if (it != policy_map.end()) {
637         const UserPolicies& policies = it->second;
638         success &= android::vold::evictKey(BuildDataPath(""), policies.internal);
639         for (const auto& [volume_uuid, policy] : policies.adoptable) {
640             success &= android::vold::evictKey(BuildDataPath(volume_uuid), policy);
641         }
642         policy_map.erase(it);
643     }
644     return success;
645 }
646 
647 // Evicts and destroys all CE and DE keys for a user.  This is called when the user is removed.
fscrypt_destroy_user_keys(userid_t user_id)648 bool fscrypt_destroy_user_keys(userid_t user_id) {
649     LOG(DEBUG) << "fscrypt_destroy_user_keys(" << user_id << ")";
650     if (!IsFbeEnabled()) {
651         return true;
652     }
653     bool success = true;
654 
655     success &= evict_user_keys(s_ce_policies, user_id);
656     success &= evict_user_keys(s_de_policies, user_id);
657 
658     if (!s_ephemeral_users.erase(user_id)) {
659         auto ce_path = get_ce_key_directory_path(user_id);
660         if (!s_new_ce_keys.erase(user_id)) {
661             for (auto const path : get_ce_key_paths(ce_path)) {
662                 success &= android::vold::destroyKey(path);
663             }
664         }
665         s_deferred_fixations.erase(ce_path);
666         success &= destroy_dir(ce_path);
667 
668         auto de_key_path = get_de_key_path(user_id);
669         if (android::vold::pathExists(de_key_path)) {
670             success &= android::vold::destroyKey(de_key_path);
671         } else {
672             LOG(INFO) << "Not present so not erasing: " << de_key_path;
673         }
674     }
675     return success;
676 }
677 
authentication_from_secret(const std::vector<uint8_t> & secret)678 static android::vold::KeyAuthentication authentication_from_secret(
679         const std::vector<uint8_t>& secret) {
680     std::string secret_str(secret.begin(), secret.end());
681     if (secret_str.empty()) {
682         return kEmptyAuthentication;
683     } else {
684         return android::vold::KeyAuthentication(secret_str);
685     }
686 }
687 
volkey_path(const std::string & misc_path,const std::string & volume_uuid)688 static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
689     return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
690 }
691 
volume_secdiscardable_path(const std::string & volume_uuid)692 static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
693     return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
694 }
695 
read_or_create_volkey(const std::string & misc_path,const std::string & volume_uuid,UserPolicies & user_policies,EncryptionPolicy * policy)696 static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
697                                   UserPolicies& user_policies, EncryptionPolicy* policy) {
698     auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
699     std::string secdiscardable_hash;
700     if (android::vold::pathExists(secdiscardable_path)) {
701         if (!android::vold::readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
702             return false;
703     } else {
704         if (!android::vold::MkdirsSync(secdiscardable_path, 0700)) return false;
705         if (!android::vold::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
706             return false;
707     }
708     auto key_path = volkey_path(misc_path, volume_uuid);
709     if (!android::vold::MkdirsSync(key_path, 0700)) return false;
710     android::vold::KeyAuthentication auth(secdiscardable_hash);
711 
712     EncryptionOptions options;
713     if (!get_volume_file_encryption_options(&options)) return false;
714     KeyBuffer key;
715     if (!retrieveOrGenerateKey(key_path, key_path + "_tmp", auth, makeGen(options), &key))
716         return false;
717     if (!install_storage_key(BuildDataPath(volume_uuid), options, key, policy)) return false;
718     user_policies.adoptable[volume_uuid] = *policy;
719     return true;
720 }
721 
destroy_volkey(const std::string & misc_path,const std::string & volume_uuid)722 static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
723     auto path = volkey_path(misc_path, volume_uuid);
724     if (!android::vold::pathExists(path)) return true;
725     return android::vold::destroyKey(path);
726 }
727 
728 // (Re-)encrypts the user's CE key with the given secret.  This function handles
729 // storing the CE key for a new user for the first time.  It also handles
730 // re-encrypting the CE key upon upgrade from an Android version where the CE
731 // key was stored with kEmptyAuthentication when the user didn't have an LSKF.
732 // See the comments below for the different cases handled.
fscrypt_set_ce_key_protection(userid_t user_id,const std::vector<uint8_t> & secret)733 bool fscrypt_set_ce_key_protection(userid_t user_id, const std::vector<uint8_t>& secret) {
734     LOG(DEBUG) << "fscrypt_set_ce_key_protection " << user_id;
735     if (!IsFbeEnabled()) return true;
736     auto auth = authentication_from_secret(secret);
737     if (auth.secret.empty()) {
738         LOG(ERROR) << "fscrypt_set_ce_key_protection: secret must be nonempty";
739         return false;
740     }
741     // We shouldn't store any keys for ephemeral users.
742     if (s_ephemeral_users.count(user_id) != 0) {
743         LOG(DEBUG) << "Not storing key because user is ephemeral";
744         return true;
745     }
746     KeyBuffer ce_key;
747     auto it = s_new_ce_keys.find(user_id);
748     if (it != s_new_ce_keys.end()) {
749         // If the key exists in s_new_ce_keys, then the key is a
750         // not-yet-committed key for a new user, and we are committing it here.
751         // This happens when the user's synthetic password is created.
752         ce_key = it->second;
753     } else if (ce_key_exists(user_id)) {
754         // If the key doesn't exist in s_new_ce_keys but does exist on-disk,
755         // then we are setting the protection on an existing key.  This happens
756         // at upgrade time, when CE keys that were previously protected by
757         // kEmptyAuthentication are encrypted by the user's synthetic password.
758         LOG(DEBUG) << "CE key already exists on-disk; re-protecting it with the given secret";
759         if (!read_and_fixate_user_ce_key(user_id, kEmptyAuthentication, &ce_key)) {
760             LOG(ERROR) << "Failed to retrieve CE key for user " << user_id << " using empty auth";
761             // Before failing, also check whether the key is already protected
762             // with the given secret.  This isn't expected, but in theory it
763             // could happen if an upgrade is requested for a user more than once
764             // due to a power-off or other interruption.
765             if (read_and_fixate_user_ce_key(user_id, auth, &ce_key)) {
766                 LOG(WARNING) << "CE key is already protected by given secret";
767                 return true;
768             }
769             // The key isn't protected by either kEmptyAuthentication or by
770             // |auth|.  This should never happen, and there's nothing we can do
771             // besides return an error.
772             return false;
773         }
774     } else {
775         // If the key doesn't exist in memory or on-disk, then we need to
776         // generate it here, then commit it to disk.  This is needed after the
777         // unusual case where a non-system user was created during early boot,
778         // and then the device was force-rebooted before the boot completed.  In
779         // that case, the Android user record was committed but the CE key was
780         // not.  So the CE key was lost, and we need to regenerate it.  This
781         // should be fine, since the key should not have been used yet.
782         LOG(WARNING) << "CE key not found!  Regenerating it";
783         if (!create_ce_key(user_id, false)) return false;
784         ce_key = s_new_ce_keys.find(user_id)->second;
785     }
786 
787     auto const directory_path = get_ce_key_directory_path(user_id);
788     auto const paths = get_ce_key_paths(directory_path);
789     std::string ce_key_path;
790     if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
791     if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
792 
793     // Fixate the key, i.e. delete all other bindings of it.  (In practice this
794     // just means the kEmptyAuthentication binding, if there is one.)  However,
795     // if a userdata filesystem checkpoint is pending, then we need to delay the
796     // fixation until the checkpoint has been committed, since deleting keys
797     // from Keystore cannot be rolled back.
798     if (android::vold::cp_needsCheckpoint()) {
799         LOG(INFO) << "Deferring fixation of " << directory_path << " until checkpoint is committed";
800         s_deferred_fixations[directory_path] = ce_key_path;
801     } else {
802         s_deferred_fixations.erase(directory_path);
803         if (!fixate_user_ce_key(directory_path, ce_key_path, paths)) return false;
804     }
805 
806     if (s_new_ce_keys.erase(user_id)) {
807         LOG(INFO) << "Stored CE key for new user " << user_id;
808     }
809     return true;
810 }
811 
fscrypt_deferred_fixate_ce_keys()812 void fscrypt_deferred_fixate_ce_keys() {
813     for (const auto& it : s_deferred_fixations) {
814         const auto& directory_path = it.first;
815         const auto& to_fix = it.second;
816         LOG(INFO) << "Doing deferred fixation of " << directory_path;
817         fixate_user_ce_key(directory_path, to_fix, get_ce_key_paths(directory_path));
818         // Continue on error.
819     }
820     s_deferred_fixations.clear();
821 }
822 
fscrypt_get_unlocked_users()823 std::vector<int> fscrypt_get_unlocked_users() {
824     std::vector<int> user_ids;
825     for (const auto& [user_id, user_policies] : s_ce_policies) {
826         user_ids.push_back(user_id);
827     }
828     return user_ids;
829 }
830 
831 // Unlocks internal CE storage for the given user.  This only unlocks internal storage, since
832 // fscrypt_prepare_user_storage() has to be called for each adoptable storage volume anyway (since
833 // the volume might have been absent when the user was created), and that handles the unlocking.
fscrypt_unlock_ce_storage(userid_t user_id,const std::vector<uint8_t> & secret)834 bool fscrypt_unlock_ce_storage(userid_t user_id, const std::vector<uint8_t>& secret) {
835     LOG(DEBUG) << "fscrypt_unlock_ce_storage " << user_id;
836     if (!IsFbeEnabled()) return true;
837     if (s_ce_policies.count(user_id) != 0) {
838         LOG(WARNING) << "CE storage for user " << user_id << " is already unlocked";
839         return true;
840     }
841     auto auth = authentication_from_secret(secret);
842     KeyBuffer ce_key;
843     if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
844     EncryptionPolicy ce_policy;
845     if (!install_storage_key(DATA_MNT_POINT, s_data_options, ce_key, &ce_policy)) return false;
846     s_ce_policies[user_id].internal = ce_policy;
847     LOG(DEBUG) << "Installed CE key for user " << user_id;
848     return true;
849 }
850 
851 // Locks CE storage for the given user.  This locks both internal and adoptable storage.
fscrypt_lock_ce_storage(userid_t user_id)852 bool fscrypt_lock_ce_storage(userid_t user_id) {
853     LOG(DEBUG) << "fscrypt_lock_ce_storage " << user_id;
854     if (!IsFbeEnabled()) return true;
855     return evict_user_keys(s_ce_policies, user_id);
856 }
857 
prepare_subdirs(const std::string & action,const std::string & volume_uuid,userid_t user_id,int flags)858 static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
859                             userid_t user_id, int flags) {
860     if (0 != android::vold::ForkExecvp(
861                  std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
862                                           std::to_string(user_id), std::to_string(flags)})) {
863         LOG(ERROR) << "vold_prepare_subdirs failed";
864         return false;
865     }
866     return true;
867 }
868 
fscrypt_prepare_user_storage(const std::string & volume_uuid,userid_t user_id,int flags)869 bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
870     LOG(DEBUG) << "fscrypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
871                << ", user " << user_id << ", flags " << flags;
872 
873     // Internal storage must be prepared before adoptable storage, since the
874     // user's volume keys are stored in their internal storage.
875     if (!volume_uuid.empty()) {
876         if ((flags & android::os::IVold::STORAGE_FLAG_DE) &&
877             !android::vold::pathExists(android::vold::BuildDataMiscDePath("", user_id))) {
878             LOG(ERROR) << "Cannot prepare DE storage for user " << user_id << " on volume "
879                        << volume_uuid << " before internal storage";
880             return false;
881         }
882         if ((flags & android::os::IVold::STORAGE_FLAG_CE) &&
883             !android::vold::pathExists(android::vold::BuildDataMiscCePath("", user_id))) {
884             LOG(ERROR) << "Cannot prepare CE storage for user " << user_id << " on volume "
885                        << volume_uuid << " before internal storage";
886             return false;
887         }
888     }
889 
890     if (flags & android::os::IVold::STORAGE_FLAG_DE) {
891         // DE_sys key
892         auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
893         auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
894 
895         // DE_n key
896         EncryptionPolicy de_policy;
897         auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
898         auto misc_de_path = android::vold::BuildDataMiscDePath(volume_uuid, user_id);
899         auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
900         auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
901 
902         if (IsFbeEnabled()) {
903             auto it = s_de_policies.find(user_id);
904             if (it == s_de_policies.end()) {
905                 LOG(ERROR) << "Cannot find DE policy for user " << user_id;
906                 return false;
907             }
908             UserPolicies& user_de_policies = it->second;
909             if (volume_uuid.empty()) {
910                 de_policy = user_de_policies.internal;
911             } else {
912                 auto misc_de_empty_volume_path = android::vold::BuildDataMiscDePath("", user_id);
913                 if (!read_or_create_volkey(misc_de_empty_volume_path, volume_uuid, user_de_policies,
914                                            &de_policy)) {
915                     return false;
916                 }
917             }
918         }
919 
920         if (volume_uuid.empty()) {
921             if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
922             if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
923 
924             if (!prepare_dir_with_policy(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM, de_policy))
925                 return false;
926             if (!prepare_dir_with_policy(vendor_de_path, 0771, AID_ROOT, AID_ROOT, de_policy))
927                 return false;
928         }
929 
930         if (!prepare_dir_with_policy(misc_de_path, 01771, AID_SYSTEM, AID_MISC, de_policy))
931             return false;
932         if (!prepare_dir_with_policy(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM, de_policy))
933             return false;
934     }
935 
936     if (flags & android::os::IVold::STORAGE_FLAG_CE) {
937         // CE_n key
938         EncryptionPolicy ce_policy;
939         auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
940         auto misc_ce_path = android::vold::BuildDataMiscCePath(volume_uuid, user_id);
941         auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
942         auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
943         auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
944 
945         if (IsFbeEnabled()) {
946             auto it = s_ce_policies.find(user_id);
947             if (it == s_ce_policies.end()) {
948                 LOG(ERROR) << "Cannot find CE policy for user " << user_id;
949                 return false;
950             }
951             UserPolicies& user_ce_policies = it->second;
952             if (volume_uuid.empty()) {
953                 ce_policy = user_ce_policies.internal;
954             } else {
955                 auto misc_ce_empty_volume_path = android::vold::BuildDataMiscCePath("", user_id);
956                 if (!read_or_create_volkey(misc_ce_empty_volume_path, volume_uuid, user_ce_policies,
957                                            &ce_policy)) {
958                     return false;
959                 }
960             }
961         }
962 
963         if (volume_uuid.empty()) {
964             if (!prepare_dir_with_policy(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM, ce_policy))
965                 return false;
966             if (!prepare_dir_with_policy(vendor_ce_path, 0771, AID_ROOT, AID_ROOT, ce_policy))
967                 return false;
968         }
969         if (!prepare_dir_with_policy(media_ce_path, 02770, AID_MEDIA_RW, AID_MEDIA_RW, ce_policy))
970             return false;
971         // On devices without sdcardfs (kernel 5.4+), the path permissions aren't fixed
972         // up automatically; therefore, use a default ACL, to ensure apps with MEDIA_RW
973         // can keep reading external storage; in particular, this allows app cloning
974         // scenarios to work correctly on such devices.
975         int ret = SetDefaultAcl(media_ce_path, 02770, AID_MEDIA_RW, AID_MEDIA_RW, {AID_MEDIA_RW});
976         if (ret != android::OK) {
977             return false;
978         }
979         if (!prepare_dir_with_policy(misc_ce_path, 01771, AID_SYSTEM, AID_MISC, ce_policy))
980             return false;
981         if (!prepare_dir_with_policy(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM, ce_policy))
982             return false;
983 
984         if (volume_uuid.empty()) {
985             // Now that credentials have been installed, we can run restorecon
986             // over these paths
987             // NOTE: these paths need to be kept in sync with libselinux
988             android::vold::RestoreconRecursive(system_ce_path);
989             android::vold::RestoreconRecursive(vendor_ce_path);
990             android::vold::RestoreconRecursive(misc_ce_path);
991         }
992     }
993     if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
994 
995     return true;
996 }
997 
fscrypt_destroy_user_storage(const std::string & volume_uuid,userid_t user_id,int flags)998 bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
999     LOG(DEBUG) << "fscrypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
1000                << ", user " << user_id << ", flags " << flags;
1001     bool res = true;
1002 
1003     res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
1004 
1005     if (flags & android::os::IVold::STORAGE_FLAG_CE) {
1006         // CE_n key
1007         auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
1008         auto misc_ce_path = android::vold::BuildDataMiscCePath(volume_uuid, user_id);
1009         auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
1010         auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
1011         auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
1012 
1013         res &= destroy_dir(media_ce_path);
1014         res &= destroy_dir(misc_ce_path);
1015         res &= destroy_dir(user_ce_path);
1016         if (volume_uuid.empty()) {
1017             res &= destroy_dir(system_ce_path);
1018             res &= destroy_dir(vendor_ce_path);
1019         } else {
1020             if (IsFbeEnabled()) {
1021                 auto misc_ce_empty_volume_path = android::vold::BuildDataMiscCePath("", user_id);
1022                 res &= destroy_volkey(misc_ce_empty_volume_path, volume_uuid);
1023             }
1024         }
1025     }
1026 
1027     if (flags & android::os::IVold::STORAGE_FLAG_DE) {
1028         // DE_sys key
1029         auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
1030         auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
1031 
1032         // DE_n key
1033         auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
1034         auto misc_de_path = android::vold::BuildDataMiscDePath(volume_uuid, user_id);
1035         auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
1036         auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
1037 
1038         res &= destroy_dir(user_de_path);
1039         res &= destroy_dir(misc_de_path);
1040         if (volume_uuid.empty()) {
1041             res &= destroy_dir(system_legacy_path);
1042             res &= destroy_dir(profiles_de_path);
1043             res &= destroy_dir(system_de_path);
1044             res &= destroy_dir(vendor_de_path);
1045         } else {
1046             if (IsFbeEnabled()) {
1047                 auto misc_de_empty_volume_path = android::vold::BuildDataMiscDePath("", user_id);
1048                 res &= destroy_volkey(misc_de_empty_volume_path, volume_uuid);
1049             }
1050         }
1051     }
1052 
1053     return res;
1054 }
1055 
destroy_volume_keys(const std::string & directory_path,const std::string & volume_uuid)1056 static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
1057     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
1058     if (!dirp) {
1059         PLOG(ERROR) << "Unable to open directory: " + directory_path;
1060         return false;
1061     }
1062     bool res = true;
1063     for (;;) {
1064         errno = 0;
1065         auto const entry = readdir(dirp.get());
1066         if (!entry) {
1067             if (errno) {
1068                 PLOG(ERROR) << "Unable to read directory: " + directory_path;
1069                 return false;
1070             }
1071             break;
1072         }
1073         if (IsDotOrDotDot(*entry)) continue;
1074         if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
1075             LOG(DEBUG) << "Skipping non-user " << entry->d_name;
1076             continue;
1077         }
1078         res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
1079     }
1080     return res;
1081 }
1082 
erase_volume_policies(std::map<userid_t,UserPolicies> & policy_map,const std::string & volume_uuid)1083 static void erase_volume_policies(std::map<userid_t, UserPolicies>& policy_map,
1084                                   const std::string& volume_uuid) {
1085     for (auto& [user_id, user_policies] : policy_map) {
1086         user_policies.adoptable.erase(volume_uuid);
1087     }
1088 }
1089 
1090 // Destroys all CE and DE keys for an adoptable storage volume that is permanently going away.
1091 // Requires VolumeManager::mCryptLock.
fscrypt_destroy_volume_keys(const std::string & volume_uuid)1092 bool fscrypt_destroy_volume_keys(const std::string& volume_uuid) {
1093     if (!IsFbeEnabled()) return true;
1094     bool res = true;
1095     LOG(DEBUG) << "fscrypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
1096     auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
1097     res &= android::vold::runSecdiscardSingle(secdiscardable_path);
1098     res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
1099     res &= destroy_volume_keys("/data/misc_de", volume_uuid);
1100     // Drop the CE and DE policies stored in memory, as they are not needed anymore.  Note that it's
1101     // not necessary to also evict the corresponding keys from the kernel, as that happens
1102     // automatically as a result of the volume being unmounted.
1103     erase_volume_policies(s_ce_policies, volume_uuid);
1104     erase_volume_policies(s_de_policies, volume_uuid);
1105     return res;
1106 }
1107