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 "KeyStorage.h"
20 #include "KeyUtil.h"
21 #include "Utils.h"
22 #include "VoldUtil.h"
23 
24 #include <algorithm>
25 #include <map>
26 #include <optional>
27 #include <set>
28 #include <sstream>
29 #include <string>
30 #include <vector>
31 
32 #include <dirent.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <limits.h>
36 #include <selinux/android.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 #define EMULATED_USES_SELINUX 0
48 #define MANAGE_MISC_DIRS 0
49 
50 #include <cutils/fs.h>
51 #include <cutils/properties.h>
52 
53 #include <fscrypt/fscrypt.h>
54 #include <keyutils.h>
55 #include <libdm/dm.h>
56 
57 #include <android-base/file.h>
58 #include <android-base/logging.h>
59 #include <android-base/properties.h>
60 #include <android-base/stringprintf.h>
61 #include <android-base/strings.h>
62 #include <android-base/unique_fd.h>
63 
64 using android::base::Basename;
65 using android::base::Realpath;
66 using android::base::StartsWith;
67 using android::base::StringPrintf;
68 using android::fs_mgr::GetEntryForMountPoint;
69 using android::vold::BuildDataPath;
70 using android::vold::IsDotOrDotDot;
71 using android::vold::IsFilesystemSupported;
72 using android::vold::kEmptyAuthentication;
73 using android::vold::KeyBuffer;
74 using android::vold::KeyGeneration;
75 using android::vold::retrieveKey;
76 using android::vold::retrieveOrGenerateKey;
77 using android::vold::SetDefaultAcl;
78 using android::vold::SetQuotaInherit;
79 using android::vold::SetQuotaProjectId;
80 using android::vold::writeStringToFile;
81 using namespace android::fscrypt;
82 using namespace android::dm;
83 
84 namespace {
85 
86 const std::string device_key_dir = std::string() + DATA_MNT_POINT + fscrypt_unencrypted_folder;
87 const std::string device_key_path = device_key_dir + "/key";
88 const std::string device_key_temp = device_key_dir + "/temp";
89 
90 const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
91 const std::string user_key_temp = user_key_dir + "/temp";
92 const std::string prepare_subdirs_path = "/system/bin/vold_prepare_subdirs";
93 
94 const std::string systemwide_volume_key_dir =
95     std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
96 
97 // Some users are ephemeral, don't try to wipe their keys from disk
98 std::set<userid_t> s_ephemeral_users;
99 
100 // Map user ids to encryption policies
101 std::map<userid_t, EncryptionPolicy> s_de_policies;
102 std::map<userid_t, EncryptionPolicy> s_ce_policies;
103 
104 }  // namespace
105 
106 // Returns KeyGeneration suitable for key as described in EncryptionOptions
makeGen(const EncryptionOptions & options)107 static KeyGeneration makeGen(const EncryptionOptions& options) {
108     return KeyGeneration{FSCRYPT_MAX_KEY_SIZE, true, options.use_hw_wrapped_key};
109 }
110 
fscrypt_is_emulated()111 static bool fscrypt_is_emulated() {
112     return property_get_bool("persist.sys.emulate_fbe", false);
113 }
114 
escape_empty(const std::string & value)115 static const char* escape_empty(const std::string& value) {
116     return value.empty() ? "null" : value.c_str();
117 }
118 
get_de_key_path(userid_t user_id)119 static std::string get_de_key_path(userid_t user_id) {
120     return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
121 }
122 
get_ce_key_directory_path(userid_t user_id)123 static std::string get_ce_key_directory_path(userid_t user_id) {
124     return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
125 }
126 
127 // Returns the keys newest first
get_ce_key_paths(const std::string & directory_path)128 static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
129     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
130     if (!dirp) {
131         PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
132         return std::vector<std::string>();
133     }
134     std::vector<std::string> result;
135     for (;;) {
136         errno = 0;
137         auto const entry = readdir(dirp.get());
138         if (!entry) {
139             if (errno) {
140                 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
141                 return std::vector<std::string>();
142             }
143             break;
144         }
145         if (IsDotOrDotDot(*entry)) continue;
146         if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
147             LOG(DEBUG) << "Skipping non-key " << entry->d_name;
148             continue;
149         }
150         result.emplace_back(directory_path + "/" + entry->d_name);
151     }
152     std::sort(result.begin(), result.end());
153     std::reverse(result.begin(), result.end());
154     return result;
155 }
156 
get_ce_key_current_path(const std::string & directory_path)157 static std::string get_ce_key_current_path(const std::string& directory_path) {
158     return directory_path + "/current";
159 }
160 
get_ce_key_new_path(const std::string & directory_path,const std::vector<std::string> & paths,std::string * ce_key_path)161 static bool get_ce_key_new_path(const std::string& directory_path,
162                                 const std::vector<std::string>& paths, std::string* ce_key_path) {
163     if (paths.empty()) {
164         *ce_key_path = get_ce_key_current_path(directory_path);
165         return true;
166     }
167     for (unsigned int i = 0; i < UINT_MAX; i++) {
168         auto const candidate = StringPrintf("%s/cx%010u", directory_path.c_str(), i);
169         if (paths[0] < candidate) {
170             *ce_key_path = candidate;
171             return true;
172         }
173     }
174     return false;
175 }
176 
177 // Discard all keys but the named one; rename it to canonical name.
178 // No point in acting on errors in this; ignore them.
fixate_user_ce_key(const std::string & directory_path,const std::string & to_fix,const std::vector<std::string> & paths)179 static void fixate_user_ce_key(const std::string& directory_path, const std::string& to_fix,
180                                const std::vector<std::string>& paths) {
181     for (auto const other_path : paths) {
182         if (other_path != to_fix) {
183             android::vold::destroyKey(other_path);
184         }
185     }
186     auto const current_path = get_ce_key_current_path(directory_path);
187     if (to_fix != current_path) {
188         LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
189         if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
190             PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
191             return;
192         }
193     }
194     android::vold::FsyncDirectory(directory_path);
195 }
196 
read_and_fixate_user_ce_key(userid_t user_id,const android::vold::KeyAuthentication & auth,KeyBuffer * ce_key)197 static bool read_and_fixate_user_ce_key(userid_t user_id,
198                                         const android::vold::KeyAuthentication& auth,
199                                         KeyBuffer* ce_key) {
200     auto const directory_path = get_ce_key_directory_path(user_id);
201     auto const paths = get_ce_key_paths(directory_path);
202     for (auto const ce_key_path : paths) {
203         LOG(DEBUG) << "Trying user CE key " << ce_key_path;
204         if (retrieveKey(ce_key_path, auth, ce_key)) {
205             LOG(DEBUG) << "Successfully retrieved key";
206             fixate_user_ce_key(directory_path, ce_key_path, paths);
207             return true;
208         }
209     }
210     LOG(ERROR) << "Failed to find working ce key for user " << user_id;
211     return false;
212 }
213 
IsEmmcStorage(const std::string & blk_device)214 static bool IsEmmcStorage(const std::string& blk_device) {
215     // Handle symlinks.
216     std::string real_path;
217     if (!Realpath(blk_device, &real_path)) {
218         real_path = blk_device;
219     }
220 
221     // Handle logical volumes.
222     auto& dm = DeviceMapper::Instance();
223     for (;;) {
224         auto parent = dm.GetParentBlockDeviceByPath(real_path);
225         if (!parent.has_value()) break;
226         real_path = *parent;
227     }
228 
229     // Now we should have the "real" block device.
230     LOG(DEBUG) << "IsEmmcStorage(): blk_device = " << blk_device << ", real_path=" << real_path;
231     return StartsWith(Basename(real_path), "mmcblk");
232 }
233 
234 // Retrieve the options to use for encryption policies on the /data filesystem.
get_data_file_encryption_options(EncryptionOptions * options)235 static bool get_data_file_encryption_options(EncryptionOptions* options) {
236     auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
237     if (entry == nullptr) {
238         LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
239         return false;
240     }
241     if (!ParseOptions(entry->encryption_options, options)) {
242         LOG(ERROR) << "Unable to parse encryption options for " << DATA_MNT_POINT ": "
243                    << entry->encryption_options;
244         return false;
245     }
246     if ((options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
247         !IsEmmcStorage(entry->blk_device)) {
248         LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage.  Remove "
249                       "this flag from the device's fstab";
250         return false;
251     }
252     return true;
253 }
254 
install_storage_key(const std::string & mountpoint,const EncryptionOptions & options,const KeyBuffer & key,EncryptionPolicy * policy)255 static bool install_storage_key(const std::string& mountpoint, const EncryptionOptions& options,
256                                 const KeyBuffer& key, EncryptionPolicy* policy) {
257     KeyBuffer ephemeral_wrapped_key;
258     if (options.use_hw_wrapped_key) {
259         if (!exportWrappedStorageKey(key, &ephemeral_wrapped_key)) {
260             LOG(ERROR) << "Failed to get ephemeral wrapped key";
261             return false;
262         }
263     }
264     return installKey(mountpoint, options, options.use_hw_wrapped_key ? ephemeral_wrapped_key : key,
265                       policy);
266 }
267 
268 // Retrieve the options to use for encryption policies on adoptable storage.
get_volume_file_encryption_options(EncryptionOptions * options)269 static bool get_volume_file_encryption_options(EncryptionOptions* options) {
270     // If we give the empty string, libfscrypt will use the default (currently XTS)
271     auto contents_mode = android::base::GetProperty("ro.crypto.volume.contents_mode", "");
272     // HEH as default was always a mistake. Use the libfscrypt default (CTS)
273     // for devices launching on versions above Android 10.
274     auto first_api_level = GetFirstApiLevel();
275     auto filenames_mode =
276             android::base::GetProperty("ro.crypto.volume.filenames_mode",
277                                        first_api_level > __ANDROID_API_Q__ ? "" : "aes-256-heh");
278     auto options_string = android::base::GetProperty("ro.crypto.volume.options",
279                                                      contents_mode + ":" + filenames_mode);
280     if (!ParseOptionsForApiLevel(first_api_level, options_string, options)) {
281         LOG(ERROR) << "Unable to parse volume encryption options: " << options_string;
282         return false;
283     }
284     if (options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
285         LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage.  Remove "
286                       "this flag from ro.crypto.volume.options";
287         return false;
288     }
289     return true;
290 }
291 
read_and_install_user_ce_key(userid_t user_id,const android::vold::KeyAuthentication & auth)292 static bool read_and_install_user_ce_key(userid_t user_id,
293                                          const android::vold::KeyAuthentication& auth) {
294     if (s_ce_policies.count(user_id) != 0) return true;
295     EncryptionOptions options;
296     if (!get_data_file_encryption_options(&options)) return false;
297     KeyBuffer ce_key;
298     if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
299     EncryptionPolicy ce_policy;
300     if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
301     s_ce_policies[user_id] = ce_policy;
302     LOG(DEBUG) << "Installed ce key for user " << user_id;
303     return true;
304 }
305 
prepare_dir(const std::string & dir,mode_t mode,uid_t uid,gid_t gid)306 static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
307     LOG(DEBUG) << "Preparing: " << dir;
308     if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
309         PLOG(ERROR) << "Failed to prepare " << dir;
310         return false;
311     }
312     return true;
313 }
314 
destroy_dir(const std::string & dir)315 static bool destroy_dir(const std::string& dir) {
316     LOG(DEBUG) << "Destroying: " << dir;
317     if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
318         PLOG(ERROR) << "Failed to destroy " << dir;
319         return false;
320     }
321     return true;
322 }
323 
324 // NB this assumes that there is only one thread listening for crypt commands, because
325 // it creates keys in a fixed location.
create_and_install_user_keys(userid_t user_id,bool create_ephemeral)326 static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
327     EncryptionOptions options;
328     if (!get_data_file_encryption_options(&options)) return false;
329     KeyBuffer de_key, ce_key;
330     if (!generateStorageKey(makeGen(options), &de_key)) return false;
331     if (!generateStorageKey(makeGen(options), &ce_key)) return false;
332     if (create_ephemeral) {
333         // If the key should be created as ephemeral, don't store it.
334         s_ephemeral_users.insert(user_id);
335     } else {
336         auto const directory_path = get_ce_key_directory_path(user_id);
337         if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
338         auto const paths = get_ce_key_paths(directory_path);
339         std::string ce_key_path;
340         if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
341         if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication,
342                                                ce_key))
343             return false;
344         fixate_user_ce_key(directory_path, ce_key_path, paths);
345         // Write DE key second; once this is written, all is good.
346         if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
347                                                kEmptyAuthentication, de_key))
348             return false;
349     }
350     EncryptionPolicy de_policy;
351     if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
352     s_de_policies[user_id] = de_policy;
353     EncryptionPolicy ce_policy;
354     if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
355     s_ce_policies[user_id] = ce_policy;
356     LOG(DEBUG) << "Created keys for user " << user_id;
357     return true;
358 }
359 
lookup_policy(const std::map<userid_t,EncryptionPolicy> & key_map,userid_t user_id,EncryptionPolicy * policy)360 static bool lookup_policy(const std::map<userid_t, EncryptionPolicy>& key_map, userid_t user_id,
361                           EncryptionPolicy* policy) {
362     auto refi = key_map.find(user_id);
363     if (refi == key_map.end()) {
364         LOG(DEBUG) << "Cannot find key for " << user_id;
365         return false;
366     }
367     *policy = refi->second;
368     return true;
369 }
370 
is_numeric(const char * name)371 static bool is_numeric(const char* name) {
372     for (const char* p = name; *p != '\0'; p++) {
373         if (!isdigit(*p)) return false;
374     }
375     return true;
376 }
377 
load_all_de_keys()378 static bool load_all_de_keys() {
379     EncryptionOptions options;
380     if (!get_data_file_encryption_options(&options)) return false;
381     auto de_dir = user_key_dir + "/de";
382     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
383     if (!dirp) {
384         PLOG(ERROR) << "Unable to read de key directory";
385         return false;
386     }
387     for (;;) {
388         errno = 0;
389         auto entry = readdir(dirp.get());
390         if (!entry) {
391             if (errno) {
392                 PLOG(ERROR) << "Unable to read de key directory";
393                 return false;
394             }
395             break;
396         }
397         if (IsDotOrDotDot(*entry)) continue;
398         if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
399             LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
400             continue;
401         }
402         userid_t user_id = std::stoi(entry->d_name);
403         auto key_path = de_dir + "/" + entry->d_name;
404         KeyBuffer de_key;
405         if (!retrieveKey(key_path, kEmptyAuthentication, &de_key)) return false;
406         EncryptionPolicy de_policy;
407         if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
408         auto ret = s_de_policies.insert({user_id, de_policy});
409         if (!ret.second && ret.first->second != de_policy) {
410             LOG(ERROR) << "DE policy for user" << user_id << " changed";
411             return false;
412         }
413         LOG(DEBUG) << "Installed de key for user " << user_id;
414     }
415     // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
416     // correct policy set on them, and that no rogue ones exist.
417     return true;
418 }
419 
420 // Attempt to reinstall CE keys for users that we think are unlocked.
try_reload_ce_keys()421 static bool try_reload_ce_keys() {
422     for (const auto& it : s_ce_policies) {
423         if (!android::vold::reloadKeyFromSessionKeyring(DATA_MNT_POINT, it.second)) {
424             LOG(ERROR) << "Failed to load CE key from session keyring for user " << it.first;
425             return false;
426         }
427     }
428     return true;
429 }
430 
fscrypt_initialize_systemwide_keys()431 bool fscrypt_initialize_systemwide_keys() {
432     LOG(INFO) << "fscrypt_initialize_systemwide_keys";
433 
434     EncryptionOptions options;
435     if (!get_data_file_encryption_options(&options)) return false;
436 
437     KeyBuffer device_key;
438     if (!retrieveOrGenerateKey(device_key_path, device_key_temp, kEmptyAuthentication,
439                                makeGen(options), &device_key))
440         return false;
441 
442     EncryptionPolicy device_policy;
443     if (!install_storage_key(DATA_MNT_POINT, options, device_key, &device_policy)) return false;
444 
445     std::string options_string;
446     if (!OptionsToString(device_policy.options, &options_string)) {
447         LOG(ERROR) << "Unable to serialize options";
448         return false;
449     }
450     std::string options_filename = std::string(DATA_MNT_POINT) + fscrypt_key_mode;
451     if (!android::vold::writeStringToFile(options_string, options_filename)) return false;
452 
453     std::string ref_filename = std::string(DATA_MNT_POINT) + fscrypt_key_ref;
454     if (!android::vold::writeStringToFile(device_policy.key_raw_ref, ref_filename)) return false;
455     LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
456 
457     KeyBuffer per_boot_key;
458     if (!generateStorageKey(makeGen(options), &per_boot_key)) return false;
459     EncryptionPolicy per_boot_policy;
460     if (!install_storage_key(DATA_MNT_POINT, options, per_boot_key, &per_boot_policy)) return false;
461     std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
462     if (!android::vold::writeStringToFile(per_boot_policy.key_raw_ref, per_boot_ref_filename))
463         return false;
464     LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
465 
466     return true;
467 }
468 
fscrypt_init_user0()469 bool fscrypt_init_user0() {
470     LOG(DEBUG) << "fscrypt_init_user0";
471     if (fscrypt_is_native()) {
472         if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
473         if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
474         if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
475         if (!android::vold::pathExists(get_de_key_path(0))) {
476             if (!create_and_install_user_keys(0, false)) return false;
477         }
478         // TODO: switch to loading only DE_0 here once framework makes
479         // explicit calls to install DE keys for secondary users
480         if (!load_all_de_keys()) return false;
481     }
482     // We can only safely prepare DE storage here, since CE keys are probably
483     // entangled with user credentials.  The framework will always prepare CE
484     // storage once CE keys are installed.
485     if (!fscrypt_prepare_user_storage("", 0, 0, android::os::IVold::STORAGE_FLAG_DE)) {
486         LOG(ERROR) << "Failed to prepare user 0 storage";
487         return false;
488     }
489 
490     // If this is a non-FBE device that recently left an emulated mode,
491     // restore user data directories to known-good state.
492     if (!fscrypt_is_native() && !fscrypt_is_emulated()) {
493         fscrypt_unlock_user_key(0, 0, "!");
494     }
495 
496     // In some scenarios (e.g. userspace reboot) we might unmount userdata
497     // without doing a hard reboot. If CE keys were stored in fs keyring then
498     // they will be lost after unmount. Attempt to re-install them.
499     if (fscrypt_is_native() && android::vold::isFsKeyringSupported()) {
500         if (!try_reload_ce_keys()) return false;
501     }
502 
503     return true;
504 }
505 
fscrypt_vold_create_user_key(userid_t user_id,int serial,bool ephemeral)506 bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
507     LOG(DEBUG) << "fscrypt_vold_create_user_key for " << user_id << " serial " << serial;
508     if (!fscrypt_is_native()) {
509         return true;
510     }
511     // FIXME test for existence of key that is not loaded yet
512     if (s_ce_policies.count(user_id) != 0) {
513         LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
514                    << " serial " << serial;
515         // FIXME should we fail the command?
516         return true;
517     }
518     if (!create_and_install_user_keys(user_id, ephemeral)) {
519         return false;
520     }
521     return true;
522 }
523 
524 // "Lock" all encrypted directories whose key has been removed.  This is needed
525 // in the case where the keys are being put in the session keyring (rather in
526 // the newer filesystem-level keyrings), because removing a key from the session
527 // keyring doesn't affect inodes in the kernel's inode cache whose per-file key
528 // was already set up.  So to remove the per-file keys and make the files
529 // "appear encrypted", these inodes must be evicted.
530 //
531 // To do this, sync() to clean all dirty inodes, then drop all reclaimable slab
532 // objects systemwide.  This is overkill, but it's the best available method
533 // currently.  Don't use drop_caches mode "3" because that also evicts pagecache
534 // for in-use files; all files relevant here are already closed and sync'ed.
drop_caches_if_needed()535 static void drop_caches_if_needed() {
536     if (android::vold::isFsKeyringSupported()) {
537         return;
538     }
539     sync();
540     if (!writeStringToFile("2", "/proc/sys/vm/drop_caches")) {
541         PLOG(ERROR) << "Failed to drop caches during key eviction";
542     }
543 }
544 
evict_ce_key(userid_t user_id)545 static bool evict_ce_key(userid_t user_id) {
546     bool success = true;
547     EncryptionPolicy policy;
548     // If we haven't loaded the CE key, no need to evict it.
549     if (lookup_policy(s_ce_policies, user_id, &policy)) {
550         success &= android::vold::evictKey(DATA_MNT_POINT, policy);
551         drop_caches_if_needed();
552     }
553     s_ce_policies.erase(user_id);
554     return success;
555 }
556 
fscrypt_destroy_user_key(userid_t user_id)557 bool fscrypt_destroy_user_key(userid_t user_id) {
558     LOG(DEBUG) << "fscrypt_destroy_user_key(" << user_id << ")";
559     if (!fscrypt_is_native()) {
560         return true;
561     }
562     bool success = true;
563     success &= evict_ce_key(user_id);
564     EncryptionPolicy de_policy;
565     success &= lookup_policy(s_de_policies, user_id, &de_policy) &&
566                android::vold::evictKey(DATA_MNT_POINT, de_policy);
567     s_de_policies.erase(user_id);
568     auto it = s_ephemeral_users.find(user_id);
569     if (it != s_ephemeral_users.end()) {
570         s_ephemeral_users.erase(it);
571     } else {
572         for (auto const path : get_ce_key_paths(get_ce_key_directory_path(user_id))) {
573             success &= android::vold::destroyKey(path);
574         }
575         auto de_key_path = get_de_key_path(user_id);
576         if (android::vold::pathExists(de_key_path)) {
577             success &= android::vold::destroyKey(de_key_path);
578         } else {
579             LOG(INFO) << "Not present so not erasing: " << de_key_path;
580         }
581     }
582     return success;
583 }
584 
emulated_lock(const std::string & path)585 static bool emulated_lock(const std::string& path) {
586     if (chmod(path.c_str(), 0000) != 0) {
587         PLOG(ERROR) << "Failed to chmod " << path;
588         return false;
589     }
590 #if EMULATED_USES_SELINUX
591     if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
592         PLOG(WARNING) << "Failed to setfilecon " << path;
593         return false;
594     }
595 #endif
596     return true;
597 }
598 
emulated_unlock(const std::string & path,mode_t mode)599 static bool emulated_unlock(const std::string& path, mode_t mode) {
600     if (chmod(path.c_str(), mode) != 0) {
601         PLOG(ERROR) << "Failed to chmod " << path;
602         // FIXME temporary workaround for b/26713622
603         if (fscrypt_is_emulated()) return false;
604     }
605 #if EMULATED_USES_SELINUX
606     if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
607         PLOG(WARNING) << "Failed to restorecon " << path;
608         // FIXME temporary workaround for b/26713622
609         if (fscrypt_is_emulated()) return false;
610     }
611 #endif
612     return true;
613 }
614 
parse_hex(const std::string & hex,std::string * result)615 static bool parse_hex(const std::string& hex, std::string* result) {
616     if (hex == "!") {
617         *result = "";
618         return true;
619     }
620     if (android::vold::HexToStr(hex, *result) != 0) {
621         LOG(ERROR) << "Invalid FBE hex string";  // Don't log the string for security reasons
622         return false;
623     }
624     return true;
625 }
626 
authentication_from_hex(const std::string & secret_hex)627 static std::optional<android::vold::KeyAuthentication> authentication_from_hex(
628         const std::string& secret_hex) {
629     std::string secret;
630     if (!parse_hex(secret_hex, &secret)) return std::optional<android::vold::KeyAuthentication>();
631     if (secret.empty()) {
632         return kEmptyAuthentication;
633     } else {
634         return android::vold::KeyAuthentication(secret);
635     }
636 }
637 
volkey_path(const std::string & misc_path,const std::string & volume_uuid)638 static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
639     return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
640 }
641 
volume_secdiscardable_path(const std::string & volume_uuid)642 static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
643     return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
644 }
645 
read_or_create_volkey(const std::string & misc_path,const std::string & volume_uuid,EncryptionPolicy * policy)646 static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
647                                   EncryptionPolicy* policy) {
648     auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
649     std::string secdiscardable_hash;
650     if (android::vold::pathExists(secdiscardable_path)) {
651         if (!android::vold::readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
652             return false;
653     } else {
654         if (!android::vold::MkdirsSync(secdiscardable_path, 0700)) return false;
655         if (!android::vold::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
656             return false;
657     }
658     auto key_path = volkey_path(misc_path, volume_uuid);
659     if (!android::vold::MkdirsSync(key_path, 0700)) return false;
660     android::vold::KeyAuthentication auth(secdiscardable_hash);
661 
662     EncryptionOptions options;
663     if (!get_volume_file_encryption_options(&options)) return false;
664     KeyBuffer key;
665     if (!retrieveOrGenerateKey(key_path, key_path + "_tmp", auth, makeGen(options), &key))
666         return false;
667     if (!install_storage_key(BuildDataPath(volume_uuid), options, key, policy)) return false;
668     return true;
669 }
670 
destroy_volkey(const std::string & misc_path,const std::string & volume_uuid)671 static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
672     auto path = volkey_path(misc_path, volume_uuid);
673     if (!android::vold::pathExists(path)) return true;
674     return android::vold::destroyKey(path);
675 }
676 
fscrypt_rewrap_user_key(userid_t user_id,int serial,const android::vold::KeyAuthentication & retrieve_auth,const android::vold::KeyAuthentication & store_auth)677 static bool fscrypt_rewrap_user_key(userid_t user_id, int serial,
678                                     const android::vold::KeyAuthentication& retrieve_auth,
679                                     const android::vold::KeyAuthentication& store_auth) {
680     if (s_ephemeral_users.count(user_id) != 0) return true;
681     auto const directory_path = get_ce_key_directory_path(user_id);
682     KeyBuffer ce_key;
683     std::string ce_key_current_path = get_ce_key_current_path(directory_path);
684     if (retrieveKey(ce_key_current_path, retrieve_auth, &ce_key)) {
685         LOG(DEBUG) << "Successfully retrieved key";
686         // TODO(147732812): Remove this once Locksettingservice is fixed.
687         // Currently it calls fscrypt_clear_user_key_auth with a secret when lockscreen is
688         // changed from swipe to none or vice-versa
689     } else if (retrieveKey(ce_key_current_path, kEmptyAuthentication, &ce_key)) {
690         LOG(DEBUG) << "Successfully retrieved key with empty auth";
691     } else {
692         LOG(ERROR) << "Failed to retrieve key for user " << user_id;
693         return false;
694     }
695     auto const paths = get_ce_key_paths(directory_path);
696     std::string ce_key_path;
697     if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
698     if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, store_auth, ce_key))
699         return false;
700     return true;
701 }
702 
fscrypt_add_user_key_auth(userid_t user_id,int serial,const std::string & secret_hex)703 bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& secret_hex) {
704     LOG(DEBUG) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial;
705     if (!fscrypt_is_native()) return true;
706     auto auth = authentication_from_hex(secret_hex);
707     if (!auth) return false;
708     return fscrypt_rewrap_user_key(user_id, serial, kEmptyAuthentication, *auth);
709 }
710 
fscrypt_clear_user_key_auth(userid_t user_id,int serial,const std::string & secret_hex)711 bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& secret_hex) {
712     LOG(DEBUG) << "fscrypt_clear_user_key_auth " << user_id << " serial=" << serial;
713     if (!fscrypt_is_native()) return true;
714     auto auth = authentication_from_hex(secret_hex);
715     if (!auth) return false;
716     return fscrypt_rewrap_user_key(user_id, serial, *auth, kEmptyAuthentication);
717 }
718 
fscrypt_fixate_newest_user_key_auth(userid_t user_id)719 bool fscrypt_fixate_newest_user_key_auth(userid_t user_id) {
720     LOG(DEBUG) << "fscrypt_fixate_newest_user_key_auth " << user_id;
721     if (!fscrypt_is_native()) return true;
722     if (s_ephemeral_users.count(user_id) != 0) return true;
723     auto const directory_path = get_ce_key_directory_path(user_id);
724     auto const paths = get_ce_key_paths(directory_path);
725     if (paths.empty()) {
726         LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
727         return false;
728     }
729     fixate_user_ce_key(directory_path, paths[0], paths);
730     return true;
731 }
732 
fscrypt_get_unlocked_users()733 std::vector<int> fscrypt_get_unlocked_users() {
734     std::vector<int> user_ids;
735     for (const auto& it : s_ce_policies) {
736         user_ids.push_back(it.first);
737     }
738     return user_ids;
739 }
740 
741 // TODO: rename to 'install' for consistency, and take flags to know which keys to install
fscrypt_unlock_user_key(userid_t user_id,int serial,const std::string & secret_hex)742 bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& secret_hex) {
743     LOG(DEBUG) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial;
744     if (fscrypt_is_native()) {
745         if (s_ce_policies.count(user_id) != 0) {
746             LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
747             return true;
748         }
749         auto auth = authentication_from_hex(secret_hex);
750         if (!auth) return false;
751         if (!read_and_install_user_ce_key(user_id, *auth)) {
752             LOG(ERROR) << "Couldn't read key for " << user_id;
753             return false;
754         }
755     } else {
756         // When in emulation mode, we just use chmod. However, we also
757         // unlock directories when not in emulation mode, to bring devices
758         // back into a known-good state.
759         if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
760             !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
761             !emulated_unlock(android::vold::BuildDataMediaCePath("", user_id), 0770) ||
762             !emulated_unlock(android::vold::BuildDataUserCePath("", user_id), 0771)) {
763             LOG(ERROR) << "Failed to unlock user " << user_id;
764             return false;
765         }
766     }
767     return true;
768 }
769 
770 // TODO: rename to 'evict' for consistency
fscrypt_lock_user_key(userid_t user_id)771 bool fscrypt_lock_user_key(userid_t user_id) {
772     LOG(DEBUG) << "fscrypt_lock_user_key " << user_id;
773     if (fscrypt_is_native()) {
774         return evict_ce_key(user_id);
775     } else if (fscrypt_is_emulated()) {
776         // When in emulation mode, we just use chmod
777         if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
778             !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
779             !emulated_lock(android::vold::BuildDataMediaCePath("", user_id)) ||
780             !emulated_lock(android::vold::BuildDataUserCePath("", user_id))) {
781             LOG(ERROR) << "Failed to lock user " << user_id;
782             return false;
783         }
784     }
785 
786     return true;
787 }
788 
prepare_subdirs(const std::string & action,const std::string & volume_uuid,userid_t user_id,int flags)789 static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
790                             userid_t user_id, int flags) {
791     if (0 != android::vold::ForkExecvp(
792                  std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
793                                           std::to_string(user_id), std::to_string(flags)})) {
794         LOG(ERROR) << "vold_prepare_subdirs failed";
795         return false;
796     }
797     return true;
798 }
799 
fscrypt_prepare_user_storage(const std::string & volume_uuid,userid_t user_id,int serial,int flags)800 bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
801                                   int flags) {
802     LOG(DEBUG) << "fscrypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
803                << ", user " << user_id << ", serial " << serial << ", flags " << flags;
804 
805     if (flags & android::os::IVold::STORAGE_FLAG_DE) {
806         // DE_sys key
807         auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
808         auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
809         auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
810 
811         // DE_n key
812         auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
813         auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
814         auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
815         auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
816 
817         if (volume_uuid.empty()) {
818             if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
819 #if MANAGE_MISC_DIRS
820             if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
821                              multiuser_get_uid(user_id, AID_EVERYBODY)))
822                 return false;
823 #endif
824             if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
825 
826             if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
827             if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
828             if (!prepare_dir(vendor_de_path, 0771, AID_ROOT, AID_ROOT)) return false;
829         }
830         if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
831 
832         if (fscrypt_is_native()) {
833             EncryptionPolicy de_policy;
834             if (volume_uuid.empty()) {
835                 if (!lookup_policy(s_de_policies, user_id, &de_policy)) return false;
836                 if (!EnsurePolicy(de_policy, system_de_path)) return false;
837                 if (!EnsurePolicy(de_policy, misc_de_path)) return false;
838                 if (!EnsurePolicy(de_policy, vendor_de_path)) return false;
839             } else {
840                 if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_policy)) return false;
841             }
842             if (!EnsurePolicy(de_policy, user_de_path)) return false;
843         }
844     }
845 
846     if (flags & android::os::IVold::STORAGE_FLAG_CE) {
847         // CE_n key
848         auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
849         auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
850         auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
851         auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
852         auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
853 
854         if (volume_uuid.empty()) {
855             if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
856             if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
857             if (!prepare_dir(vendor_ce_path, 0771, AID_ROOT, AID_ROOT)) return false;
858         }
859         if (!prepare_dir(media_ce_path, 02770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
860         // On devices without sdcardfs (kernel 5.4+), the path permissions aren't fixed
861         // up automatically; therefore, use a default ACL, to ensure apps with MEDIA_RW
862         // can keep reading external storage; in particular, this allows app cloning
863         // scenarios to work correctly on such devices.
864         int ret = SetDefaultAcl(media_ce_path, 02770, AID_MEDIA_RW, AID_MEDIA_RW, {AID_MEDIA_RW});
865         if (ret != android::OK) {
866             return false;
867         }
868 
869         if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
870 
871         if (fscrypt_is_native()) {
872             EncryptionPolicy ce_policy;
873             if (volume_uuid.empty()) {
874                 if (!lookup_policy(s_ce_policies, user_id, &ce_policy)) return false;
875                 if (!EnsurePolicy(ce_policy, system_ce_path)) return false;
876                 if (!EnsurePolicy(ce_policy, misc_ce_path)) return false;
877                 if (!EnsurePolicy(ce_policy, vendor_ce_path)) return false;
878             } else {
879                 if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_policy)) return false;
880             }
881             if (!EnsurePolicy(ce_policy, media_ce_path)) return false;
882             if (!EnsurePolicy(ce_policy, user_ce_path)) return false;
883         }
884 
885         if (volume_uuid.empty()) {
886             // Now that credentials have been installed, we can run restorecon
887             // over these paths
888             // NOTE: these paths need to be kept in sync with libselinux
889             android::vold::RestoreconRecursive(system_ce_path);
890             android::vold::RestoreconRecursive(vendor_ce_path);
891             android::vold::RestoreconRecursive(misc_ce_path);
892         }
893     }
894     if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
895 
896     return true;
897 }
898 
fscrypt_destroy_user_storage(const std::string & volume_uuid,userid_t user_id,int flags)899 bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
900     LOG(DEBUG) << "fscrypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
901                << ", user " << user_id << ", flags " << flags;
902     bool res = true;
903 
904     res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
905 
906     if (flags & android::os::IVold::STORAGE_FLAG_CE) {
907         // CE_n key
908         auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
909         auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
910         auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
911         auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
912         auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
913 
914         res &= destroy_dir(media_ce_path);
915         res &= destroy_dir(user_ce_path);
916         if (volume_uuid.empty()) {
917             res &= destroy_dir(system_ce_path);
918             res &= destroy_dir(misc_ce_path);
919             res &= destroy_dir(vendor_ce_path);
920         } else {
921             if (fscrypt_is_native()) {
922                 res &= destroy_volkey(misc_ce_path, volume_uuid);
923             }
924         }
925     }
926 
927     if (flags & android::os::IVold::STORAGE_FLAG_DE) {
928         // DE_sys key
929         auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
930         auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
931         auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
932 
933         // DE_n key
934         auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
935         auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
936         auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
937         auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
938 
939         res &= destroy_dir(user_de_path);
940         if (volume_uuid.empty()) {
941             res &= destroy_dir(system_legacy_path);
942 #if MANAGE_MISC_DIRS
943             res &= destroy_dir(misc_legacy_path);
944 #endif
945             res &= destroy_dir(profiles_de_path);
946             res &= destroy_dir(system_de_path);
947             res &= destroy_dir(misc_de_path);
948             res &= destroy_dir(vendor_de_path);
949         } else {
950             if (fscrypt_is_native()) {
951                 res &= destroy_volkey(misc_de_path, volume_uuid);
952             }
953         }
954     }
955 
956     return res;
957 }
958 
destroy_volume_keys(const std::string & directory_path,const std::string & volume_uuid)959 static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
960     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
961     if (!dirp) {
962         PLOG(ERROR) << "Unable to open directory: " + directory_path;
963         return false;
964     }
965     bool res = true;
966     for (;;) {
967         errno = 0;
968         auto const entry = readdir(dirp.get());
969         if (!entry) {
970             if (errno) {
971                 PLOG(ERROR) << "Unable to read directory: " + directory_path;
972                 return false;
973             }
974             break;
975         }
976         if (IsDotOrDotDot(*entry)) continue;
977         if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
978             LOG(DEBUG) << "Skipping non-user " << entry->d_name;
979             continue;
980         }
981         res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
982     }
983     return res;
984 }
985 
fscrypt_destroy_volume_keys(const std::string & volume_uuid)986 bool fscrypt_destroy_volume_keys(const std::string& volume_uuid) {
987     bool res = true;
988     LOG(DEBUG) << "fscrypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
989     auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
990     res &= android::vold::runSecdiscardSingle(secdiscardable_path);
991     res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
992     res &= destroy_volume_keys("/data/misc_de", volume_uuid);
993     return res;
994 }
995