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