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 (!android::vold::RenameKeyDir(to_fix, current_path)) return;
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)) {
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
MightBeEmmcStorage(const std::string & blk_device)211 static bool MightBeEmmcStorage(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) << "MightBeEmmcStorage(): blk_device = " << blk_device
228 << ", real_path=" << real_path;
229 std::string name = Basename(real_path);
230 return StartsWith(name, "mmcblk") ||
231 // virtio devices may provide inline encryption support that is
232 // backed by eMMC inline encryption on the host, thus inheriting the
233 // DUN size limitation. So virtio devices must be allowed here too.
234 // TODO(b/207390665): check the maximum DUN size directly instead.
235 StartsWith(name, "vd");
236 }
237
238 // Retrieve the options to use for encryption policies on the /data filesystem.
get_data_file_encryption_options(EncryptionOptions * options)239 static bool get_data_file_encryption_options(EncryptionOptions* options) {
240 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
241 if (entry == nullptr) {
242 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
243 return false;
244 }
245 if (!ParseOptions(entry->encryption_options, options)) {
246 LOG(ERROR) << "Unable to parse encryption options for " << DATA_MNT_POINT ": "
247 << entry->encryption_options;
248 return false;
249 }
250 if ((options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
251 !MightBeEmmcStorage(entry->blk_device)) {
252 LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage. Remove "
253 "this flag from the device's fstab";
254 return false;
255 }
256 return true;
257 }
258
install_storage_key(const std::string & mountpoint,const EncryptionOptions & options,const KeyBuffer & key,EncryptionPolicy * policy)259 static bool install_storage_key(const std::string& mountpoint, const EncryptionOptions& options,
260 const KeyBuffer& key, EncryptionPolicy* policy) {
261 KeyBuffer ephemeral_wrapped_key;
262 if (options.use_hw_wrapped_key) {
263 if (!exportWrappedStorageKey(key, &ephemeral_wrapped_key)) {
264 LOG(ERROR) << "Failed to get ephemeral wrapped key";
265 return false;
266 }
267 }
268 return installKey(mountpoint, options, options.use_hw_wrapped_key ? ephemeral_wrapped_key : key,
269 policy);
270 }
271
272 // Retrieve the options to use for encryption policies on adoptable storage.
get_volume_file_encryption_options(EncryptionOptions * options)273 static bool get_volume_file_encryption_options(EncryptionOptions* options) {
274 // If we give the empty string, libfscrypt will use the default (currently XTS)
275 auto contents_mode = android::base::GetProperty("ro.crypto.volume.contents_mode", "");
276 // HEH as default was always a mistake. Use the libfscrypt default (CTS)
277 // for devices launching on versions above Android 10.
278 auto first_api_level = GetFirstApiLevel();
279 auto filenames_mode =
280 android::base::GetProperty("ro.crypto.volume.filenames_mode",
281 first_api_level > __ANDROID_API_Q__ ? "" : "aes-256-heh");
282 auto options_string = android::base::GetProperty("ro.crypto.volume.options",
283 contents_mode + ":" + filenames_mode);
284 if (!ParseOptionsForApiLevel(first_api_level, options_string, options)) {
285 LOG(ERROR) << "Unable to parse volume encryption options: " << options_string;
286 return false;
287 }
288 if (options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
289 LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage. Remove "
290 "this flag from ro.crypto.volume.options";
291 return false;
292 }
293 return true;
294 }
295
read_and_install_user_ce_key(userid_t user_id,const android::vold::KeyAuthentication & auth)296 static bool read_and_install_user_ce_key(userid_t user_id,
297 const android::vold::KeyAuthentication& auth) {
298 if (s_ce_policies.count(user_id) != 0) return true;
299 EncryptionOptions options;
300 if (!get_data_file_encryption_options(&options)) return false;
301 KeyBuffer ce_key;
302 if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
303 EncryptionPolicy ce_policy;
304 if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
305 s_ce_policies[user_id] = ce_policy;
306 LOG(DEBUG) << "Installed ce key for user " << user_id;
307 return true;
308 }
309
prepare_dir(const std::string & dir,mode_t mode,uid_t uid,gid_t gid)310 static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
311 LOG(DEBUG) << "Preparing: " << dir;
312 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
313 PLOG(ERROR) << "Failed to prepare " << dir;
314 return false;
315 }
316 return true;
317 }
318
destroy_dir(const std::string & dir)319 static bool destroy_dir(const std::string& dir) {
320 LOG(DEBUG) << "Destroying: " << dir;
321 if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
322 PLOG(ERROR) << "Failed to destroy " << dir;
323 return false;
324 }
325 return true;
326 }
327
328 // NB this assumes that there is only one thread listening for crypt commands, because
329 // it creates keys in a fixed location.
create_and_install_user_keys(userid_t user_id,bool create_ephemeral)330 static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
331 EncryptionOptions options;
332 if (!get_data_file_encryption_options(&options)) return false;
333 KeyBuffer de_key, ce_key;
334 if (!generateStorageKey(makeGen(options), &de_key)) return false;
335 if (!generateStorageKey(makeGen(options), &ce_key)) return false;
336 if (create_ephemeral) {
337 // If the key should be created as ephemeral, don't store it.
338 s_ephemeral_users.insert(user_id);
339 } else {
340 auto const directory_path = get_ce_key_directory_path(user_id);
341 if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
342 auto const paths = get_ce_key_paths(directory_path);
343 std::string ce_key_path;
344 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
345 if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication,
346 ce_key))
347 return false;
348 fixate_user_ce_key(directory_path, ce_key_path, paths);
349 // Write DE key second; once this is written, all is good.
350 if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
351 kEmptyAuthentication, de_key))
352 return false;
353 }
354 EncryptionPolicy de_policy;
355 if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
356 s_de_policies[user_id] = de_policy;
357 EncryptionPolicy ce_policy;
358 if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
359 s_ce_policies[user_id] = ce_policy;
360 LOG(DEBUG) << "Created keys for user " << user_id;
361 return true;
362 }
363
lookup_policy(const std::map<userid_t,EncryptionPolicy> & key_map,userid_t user_id,EncryptionPolicy * policy)364 static bool lookup_policy(const std::map<userid_t, EncryptionPolicy>& key_map, userid_t user_id,
365 EncryptionPolicy* policy) {
366 auto refi = key_map.find(user_id);
367 if (refi == key_map.end()) {
368 LOG(DEBUG) << "Cannot find key for " << user_id;
369 return false;
370 }
371 *policy = refi->second;
372 return true;
373 }
374
is_numeric(const char * name)375 static bool is_numeric(const char* name) {
376 for (const char* p = name; *p != '\0'; p++) {
377 if (!isdigit(*p)) return false;
378 }
379 return true;
380 }
381
load_all_de_keys()382 static bool load_all_de_keys() {
383 EncryptionOptions options;
384 if (!get_data_file_encryption_options(&options)) return false;
385 auto de_dir = user_key_dir + "/de";
386 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
387 if (!dirp) {
388 PLOG(ERROR) << "Unable to read de key directory";
389 return false;
390 }
391 for (;;) {
392 errno = 0;
393 auto entry = readdir(dirp.get());
394 if (!entry) {
395 if (errno) {
396 PLOG(ERROR) << "Unable to read de key directory";
397 return false;
398 }
399 break;
400 }
401 if (IsDotOrDotDot(*entry)) continue;
402 if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
403 LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
404 continue;
405 }
406 userid_t user_id = std::stoi(entry->d_name);
407 auto key_path = de_dir + "/" + entry->d_name;
408 KeyBuffer de_key;
409 if (!retrieveKey(key_path, kEmptyAuthentication, &de_key)) return false;
410 EncryptionPolicy de_policy;
411 if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
412 auto ret = s_de_policies.insert({user_id, de_policy});
413 if (!ret.second && ret.first->second != de_policy) {
414 LOG(ERROR) << "DE policy for user" << user_id << " changed";
415 return false;
416 }
417 LOG(DEBUG) << "Installed de key for user " << user_id;
418 }
419 // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
420 // correct policy set on them, and that no rogue ones exist.
421 return true;
422 }
423
424 // Attempt to reinstall CE keys for users that we think are unlocked.
try_reload_ce_keys()425 static bool try_reload_ce_keys() {
426 for (const auto& it : s_ce_policies) {
427 if (!android::vold::reloadKeyFromSessionKeyring(DATA_MNT_POINT, it.second)) {
428 LOG(ERROR) << "Failed to load CE key from session keyring for user " << it.first;
429 return false;
430 }
431 }
432 return true;
433 }
434
fscrypt_initialize_systemwide_keys()435 bool fscrypt_initialize_systemwide_keys() {
436 LOG(INFO) << "fscrypt_initialize_systemwide_keys";
437
438 EncryptionOptions options;
439 if (!get_data_file_encryption_options(&options)) return false;
440
441 KeyBuffer device_key;
442 if (!retrieveOrGenerateKey(device_key_path, device_key_temp, kEmptyAuthentication,
443 makeGen(options), &device_key))
444 return false;
445
446 EncryptionPolicy device_policy;
447 if (!install_storage_key(DATA_MNT_POINT, options, device_key, &device_policy)) return false;
448
449 std::string options_string;
450 if (!OptionsToString(device_policy.options, &options_string)) {
451 LOG(ERROR) << "Unable to serialize options";
452 return false;
453 }
454 std::string options_filename = std::string(DATA_MNT_POINT) + fscrypt_key_mode;
455 if (!android::vold::writeStringToFile(options_string, options_filename)) return false;
456
457 std::string ref_filename = std::string(DATA_MNT_POINT) + fscrypt_key_ref;
458 if (!android::vold::writeStringToFile(device_policy.key_raw_ref, ref_filename)) return false;
459 LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
460
461 KeyBuffer per_boot_key;
462 if (!generateStorageKey(makeGen(options), &per_boot_key)) return false;
463 EncryptionPolicy per_boot_policy;
464 if (!install_storage_key(DATA_MNT_POINT, options, per_boot_key, &per_boot_policy)) return false;
465 std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
466 if (!android::vold::writeStringToFile(per_boot_policy.key_raw_ref, per_boot_ref_filename))
467 return false;
468 LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
469
470 return true;
471 }
472
473 bool fscrypt_init_user0_done;
474
fscrypt_init_user0()475 bool fscrypt_init_user0() {
476 LOG(DEBUG) << "fscrypt_init_user0";
477 if (fscrypt_is_native()) {
478 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
479 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
480 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
481 if (!android::vold::pathExists(get_de_key_path(0))) {
482 if (!create_and_install_user_keys(0, false)) return false;
483 }
484 // TODO: switch to loading only DE_0 here once framework makes
485 // explicit calls to install DE keys for secondary users
486 if (!load_all_de_keys()) return false;
487 }
488 // We can only safely prepare DE storage here, since CE keys are probably
489 // entangled with user credentials. The framework will always prepare CE
490 // storage once CE keys are installed.
491 if (!fscrypt_prepare_user_storage("", 0, 0, android::os::IVold::STORAGE_FLAG_DE)) {
492 LOG(ERROR) << "Failed to prepare user 0 storage";
493 return false;
494 }
495
496 // If this is a non-FBE device that recently left an emulated mode,
497 // restore user data directories to known-good state.
498 if (!fscrypt_is_native() && !fscrypt_is_emulated()) {
499 fscrypt_unlock_user_key(0, 0, "!");
500 }
501
502 // In some scenarios (e.g. userspace reboot) we might unmount userdata
503 // without doing a hard reboot. If CE keys were stored in fs keyring then
504 // they will be lost after unmount. Attempt to re-install them.
505 if (fscrypt_is_native() && android::vold::isFsKeyringSupported()) {
506 if (!try_reload_ce_keys()) return false;
507 }
508
509 fscrypt_init_user0_done = true;
510 return true;
511 }
512
fscrypt_vold_create_user_key(userid_t user_id,int serial,bool ephemeral)513 bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
514 LOG(DEBUG) << "fscrypt_vold_create_user_key for " << user_id << " serial " << serial;
515 if (!fscrypt_is_native()) {
516 return true;
517 }
518 // FIXME test for existence of key that is not loaded yet
519 if (s_ce_policies.count(user_id) != 0) {
520 LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
521 << " serial " << serial;
522 // FIXME should we fail the command?
523 return true;
524 }
525 if (!create_and_install_user_keys(user_id, ephemeral)) {
526 return false;
527 }
528 return true;
529 }
530
531 // "Lock" all encrypted directories whose key has been removed. This is needed
532 // in the case where the keys are being put in the session keyring (rather in
533 // the newer filesystem-level keyrings), because removing a key from the session
534 // keyring doesn't affect inodes in the kernel's inode cache whose per-file key
535 // was already set up. So to remove the per-file keys and make the files
536 // "appear encrypted", these inodes must be evicted.
537 //
538 // To do this, sync() to clean all dirty inodes, then drop all reclaimable slab
539 // objects systemwide. This is overkill, but it's the best available method
540 // currently. Don't use drop_caches mode "3" because that also evicts pagecache
541 // for in-use files; all files relevant here are already closed and sync'ed.
drop_caches_if_needed()542 static void drop_caches_if_needed() {
543 if (android::vold::isFsKeyringSupported()) {
544 return;
545 }
546 sync();
547 if (!writeStringToFile("2", "/proc/sys/vm/drop_caches")) {
548 PLOG(ERROR) << "Failed to drop caches during key eviction";
549 }
550 }
551
evict_ce_key(userid_t user_id)552 static bool evict_ce_key(userid_t user_id) {
553 bool success = true;
554 EncryptionPolicy policy;
555 // If we haven't loaded the CE key, no need to evict it.
556 if (lookup_policy(s_ce_policies, user_id, &policy)) {
557 success &= android::vold::evictKey(DATA_MNT_POINT, policy);
558 drop_caches_if_needed();
559 }
560 s_ce_policies.erase(user_id);
561 return success;
562 }
563
fscrypt_destroy_user_key(userid_t user_id)564 bool fscrypt_destroy_user_key(userid_t user_id) {
565 LOG(DEBUG) << "fscrypt_destroy_user_key(" << user_id << ")";
566 if (!fscrypt_is_native()) {
567 return true;
568 }
569 bool success = true;
570 success &= evict_ce_key(user_id);
571 EncryptionPolicy de_policy;
572 success &= lookup_policy(s_de_policies, user_id, &de_policy) &&
573 android::vold::evictKey(DATA_MNT_POINT, de_policy);
574 s_de_policies.erase(user_id);
575 auto it = s_ephemeral_users.find(user_id);
576 if (it != s_ephemeral_users.end()) {
577 s_ephemeral_users.erase(it);
578 } else {
579 auto ce_path = get_ce_key_directory_path(user_id);
580 for (auto const path : get_ce_key_paths(ce_path)) {
581 success &= android::vold::destroyKey(path);
582 }
583 success &= destroy_dir(ce_path);
584
585 auto de_key_path = get_de_key_path(user_id);
586 if (android::vold::pathExists(de_key_path)) {
587 success &= android::vold::destroyKey(de_key_path);
588 } else {
589 LOG(INFO) << "Not present so not erasing: " << de_key_path;
590 }
591 }
592 return success;
593 }
594
emulated_lock(const std::string & path)595 static bool emulated_lock(const std::string& path) {
596 if (chmod(path.c_str(), 0000) != 0) {
597 PLOG(ERROR) << "Failed to chmod " << path;
598 return false;
599 }
600 #if EMULATED_USES_SELINUX
601 if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
602 PLOG(WARNING) << "Failed to setfilecon " << path;
603 return false;
604 }
605 #endif
606 return true;
607 }
608
emulated_unlock(const std::string & path,mode_t mode)609 static bool emulated_unlock(const std::string& path, mode_t mode) {
610 if (chmod(path.c_str(), mode) != 0) {
611 PLOG(ERROR) << "Failed to chmod " << path;
612 // FIXME temporary workaround for b/26713622
613 if (fscrypt_is_emulated()) return false;
614 }
615 #if EMULATED_USES_SELINUX
616 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
617 PLOG(WARNING) << "Failed to restorecon " << path;
618 // FIXME temporary workaround for b/26713622
619 if (fscrypt_is_emulated()) return false;
620 }
621 #endif
622 return true;
623 }
624
parse_hex(const std::string & hex,std::string * result)625 static bool parse_hex(const std::string& hex, std::string* result) {
626 if (hex == "!") {
627 *result = "";
628 return true;
629 }
630 if (android::vold::HexToStr(hex, *result) != 0) {
631 LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
632 return false;
633 }
634 return true;
635 }
636
authentication_from_hex(const std::string & secret_hex)637 static std::optional<android::vold::KeyAuthentication> authentication_from_hex(
638 const std::string& secret_hex) {
639 std::string secret;
640 if (!parse_hex(secret_hex, &secret)) return std::optional<android::vold::KeyAuthentication>();
641 if (secret.empty()) {
642 return kEmptyAuthentication;
643 } else {
644 return android::vold::KeyAuthentication(secret);
645 }
646 }
647
volkey_path(const std::string & misc_path,const std::string & volume_uuid)648 static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
649 return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
650 }
651
volume_secdiscardable_path(const std::string & volume_uuid)652 static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
653 return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
654 }
655
read_or_create_volkey(const std::string & misc_path,const std::string & volume_uuid,EncryptionPolicy * policy)656 static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
657 EncryptionPolicy* policy) {
658 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
659 std::string secdiscardable_hash;
660 if (android::vold::pathExists(secdiscardable_path)) {
661 if (!android::vold::readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
662 return false;
663 } else {
664 if (!android::vold::MkdirsSync(secdiscardable_path, 0700)) return false;
665 if (!android::vold::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
666 return false;
667 }
668 auto key_path = volkey_path(misc_path, volume_uuid);
669 if (!android::vold::MkdirsSync(key_path, 0700)) return false;
670 android::vold::KeyAuthentication auth(secdiscardable_hash);
671
672 EncryptionOptions options;
673 if (!get_volume_file_encryption_options(&options)) return false;
674 KeyBuffer key;
675 if (!retrieveOrGenerateKey(key_path, key_path + "_tmp", auth, makeGen(options), &key))
676 return false;
677 if (!install_storage_key(BuildDataPath(volume_uuid), options, key, policy)) return false;
678 return true;
679 }
680
destroy_volkey(const std::string & misc_path,const std::string & volume_uuid)681 static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
682 auto path = volkey_path(misc_path, volume_uuid);
683 if (!android::vold::pathExists(path)) return true;
684 return android::vold::destroyKey(path);
685 }
686
fscrypt_rewrap_user_key(userid_t user_id,int serial,const android::vold::KeyAuthentication & retrieve_auth,const android::vold::KeyAuthentication & store_auth)687 static bool fscrypt_rewrap_user_key(userid_t user_id, int serial,
688 const android::vold::KeyAuthentication& retrieve_auth,
689 const android::vold::KeyAuthentication& store_auth) {
690 if (s_ephemeral_users.count(user_id) != 0) return true;
691 auto const directory_path = get_ce_key_directory_path(user_id);
692 KeyBuffer ce_key;
693 std::string ce_key_current_path = get_ce_key_current_path(directory_path);
694 if (retrieveKey(ce_key_current_path, retrieve_auth, &ce_key)) {
695 LOG(DEBUG) << "Successfully retrieved key";
696 // TODO(147732812): Remove this once Locksettingservice is fixed.
697 // Currently it calls fscrypt_clear_user_key_auth with a secret when lockscreen is
698 // changed from swipe to none or vice-versa
699 } else if (retrieveKey(ce_key_current_path, kEmptyAuthentication, &ce_key)) {
700 LOG(DEBUG) << "Successfully retrieved key with empty auth";
701 } else {
702 LOG(ERROR) << "Failed to retrieve key for user " << user_id;
703 return false;
704 }
705 auto const paths = get_ce_key_paths(directory_path);
706 std::string ce_key_path;
707 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
708 if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, store_auth, ce_key))
709 return false;
710 return true;
711 }
712
fscrypt_add_user_key_auth(userid_t user_id,int serial,const std::string & secret_hex)713 bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& secret_hex) {
714 LOG(DEBUG) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial;
715 if (!fscrypt_is_native()) return true;
716 auto auth = authentication_from_hex(secret_hex);
717 if (!auth) return false;
718 return fscrypt_rewrap_user_key(user_id, serial, kEmptyAuthentication, *auth);
719 }
720
fscrypt_clear_user_key_auth(userid_t user_id,int serial,const std::string & secret_hex)721 bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& secret_hex) {
722 LOG(DEBUG) << "fscrypt_clear_user_key_auth " << user_id << " serial=" << serial;
723 if (!fscrypt_is_native()) return true;
724 auto auth = authentication_from_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
fscrypt_get_unlocked_users()743 std::vector<int> fscrypt_get_unlocked_users() {
744 std::vector<int> user_ids;
745 for (const auto& it : s_ce_policies) {
746 user_ids.push_back(it.first);
747 }
748 return user_ids;
749 }
750
751 // 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)752 bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& secret_hex) {
753 LOG(DEBUG) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial;
754 if (fscrypt_is_native()) {
755 if (s_ce_policies.count(user_id) != 0) {
756 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
757 return true;
758 }
759 auto auth = authentication_from_hex(secret_hex);
760 if (!auth) return false;
761 if (!read_and_install_user_ce_key(user_id, *auth)) {
762 LOG(ERROR) << "Couldn't read key for " << user_id;
763 return false;
764 }
765 } else {
766 // When in emulation mode, we just use chmod. However, we also
767 // unlock directories when not in emulation mode, to bring devices
768 // back into a known-good state.
769 if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
770 !emulated_unlock(android::vold::BuildDataMiscCePath("", user_id), 01771) ||
771 !emulated_unlock(android::vold::BuildDataMediaCePath("", user_id), 0770) ||
772 !emulated_unlock(android::vold::BuildDataUserCePath("", user_id), 0771)) {
773 LOG(ERROR) << "Failed to unlock user " << user_id;
774 return false;
775 }
776 }
777 return true;
778 }
779
780 // TODO: rename to 'evict' for consistency
fscrypt_lock_user_key(userid_t user_id)781 bool fscrypt_lock_user_key(userid_t user_id) {
782 LOG(DEBUG) << "fscrypt_lock_user_key " << user_id;
783 if (fscrypt_is_native()) {
784 return evict_ce_key(user_id);
785 } else if (fscrypt_is_emulated()) {
786 // When in emulation mode, we just use chmod
787 if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
788 !emulated_lock(android::vold::BuildDataMiscCePath("", user_id)) ||
789 !emulated_lock(android::vold::BuildDataMediaCePath("", user_id)) ||
790 !emulated_lock(android::vold::BuildDataUserCePath("", user_id))) {
791 LOG(ERROR) << "Failed to lock user " << user_id;
792 return false;
793 }
794 }
795
796 return true;
797 }
798
prepare_subdirs(const std::string & action,const std::string & volume_uuid,userid_t user_id,int flags)799 static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
800 userid_t user_id, int flags) {
801 if (0 != android::vold::ForkExecvp(
802 std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
803 std::to_string(user_id), std::to_string(flags)})) {
804 LOG(ERROR) << "vold_prepare_subdirs failed";
805 return false;
806 }
807 return true;
808 }
809
fscrypt_prepare_user_storage(const std::string & volume_uuid,userid_t user_id,int serial,int flags)810 bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
811 int flags) {
812 LOG(DEBUG) << "fscrypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
813 << ", user " << user_id << ", serial " << serial << ", flags " << flags;
814
815 // Internal storage must be prepared before adoptable storage, since the
816 // user's volume keys are stored in their internal storage.
817 if (!volume_uuid.empty()) {
818 if ((flags & android::os::IVold::STORAGE_FLAG_DE) &&
819 !android::vold::pathExists(android::vold::BuildDataMiscDePath("", user_id))) {
820 LOG(ERROR) << "Cannot prepare DE storage for user " << user_id << " on volume "
821 << volume_uuid << " before internal storage";
822 return false;
823 }
824 if ((flags & android::os::IVold::STORAGE_FLAG_CE) &&
825 !android::vold::pathExists(android::vold::BuildDataMiscCePath("", user_id))) {
826 LOG(ERROR) << "Cannot prepare CE storage for user " << user_id << " on volume "
827 << volume_uuid << " before internal storage";
828 return false;
829 }
830 }
831
832 if (flags & android::os::IVold::STORAGE_FLAG_DE) {
833 // DE_sys key
834 auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
835 auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
836 auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
837
838 // DE_n key
839 auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
840 auto misc_de_path = android::vold::BuildDataMiscDePath(volume_uuid, user_id);
841 auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
842 auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
843
844 if (volume_uuid.empty()) {
845 if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
846 #if MANAGE_MISC_DIRS
847 if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
848 multiuser_get_uid(user_id, AID_EVERYBODY)))
849 return false;
850 #endif
851 if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
852
853 if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
854 if (!prepare_dir(vendor_de_path, 0771, AID_ROOT, AID_ROOT)) return false;
855 }
856
857 if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
858 if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
859
860 if (fscrypt_is_native()) {
861 EncryptionPolicy de_policy;
862 if (volume_uuid.empty()) {
863 if (!lookup_policy(s_de_policies, user_id, &de_policy)) return false;
864 if (!EnsurePolicy(de_policy, system_de_path)) return false;
865 if (!EnsurePolicy(de_policy, vendor_de_path)) return false;
866 } else {
867 auto misc_de_empty_volume_path = android::vold::BuildDataMiscDePath("", user_id);
868 if (!read_or_create_volkey(misc_de_empty_volume_path, volume_uuid, &de_policy)) {
869 return false;
870 }
871 }
872 if (!EnsurePolicy(de_policy, misc_de_path)) return false;
873 if (!EnsurePolicy(de_policy, user_de_path)) return false;
874 }
875 }
876
877 if (flags & android::os::IVold::STORAGE_FLAG_CE) {
878 // CE_n key
879 auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
880 auto misc_ce_path = android::vold::BuildDataMiscCePath(volume_uuid, user_id);
881 auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
882 auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
883 auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
884
885 if (volume_uuid.empty()) {
886 if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
887 if (!prepare_dir(vendor_ce_path, 0771, AID_ROOT, AID_ROOT)) return false;
888 }
889 if (!prepare_dir(media_ce_path, 02770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
890 // On devices without sdcardfs (kernel 5.4+), the path permissions aren't fixed
891 // up automatically; therefore, use a default ACL, to ensure apps with MEDIA_RW
892 // can keep reading external storage; in particular, this allows app cloning
893 // scenarios to work correctly on such devices.
894 int ret = SetDefaultAcl(media_ce_path, 02770, AID_MEDIA_RW, AID_MEDIA_RW, {AID_MEDIA_RW});
895 if (ret != android::OK) {
896 return false;
897 }
898
899 if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
900 if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
901
902 if (fscrypt_is_native()) {
903 EncryptionPolicy ce_policy;
904 if (volume_uuid.empty()) {
905 if (!lookup_policy(s_ce_policies, user_id, &ce_policy)) return false;
906 if (!EnsurePolicy(ce_policy, system_ce_path)) return false;
907 if (!EnsurePolicy(ce_policy, vendor_ce_path)) return false;
908 } else {
909 auto misc_ce_empty_volume_path = android::vold::BuildDataMiscCePath("", user_id);
910 if (!read_or_create_volkey(misc_ce_empty_volume_path, volume_uuid, &ce_policy)) {
911 return false;
912 }
913 }
914 if (!EnsurePolicy(ce_policy, media_ce_path)) return false;
915 if (!EnsurePolicy(ce_policy, misc_ce_path)) return false;
916 if (!EnsurePolicy(ce_policy, user_ce_path)) return false;
917 }
918
919 if (volume_uuid.empty()) {
920 // Now that credentials have been installed, we can run restorecon
921 // over these paths
922 // NOTE: these paths need to be kept in sync with libselinux
923 android::vold::RestoreconRecursive(system_ce_path);
924 android::vold::RestoreconRecursive(vendor_ce_path);
925 android::vold::RestoreconRecursive(misc_ce_path);
926 }
927 }
928 if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
929
930 return true;
931 }
932
fscrypt_destroy_user_storage(const std::string & volume_uuid,userid_t user_id,int flags)933 bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
934 LOG(DEBUG) << "fscrypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
935 << ", user " << user_id << ", flags " << flags;
936 bool res = true;
937
938 res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
939
940 if (flags & android::os::IVold::STORAGE_FLAG_CE) {
941 // CE_n key
942 auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
943 auto misc_ce_path = android::vold::BuildDataMiscCePath(volume_uuid, user_id);
944 auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
945 auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
946 auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
947
948 res &= destroy_dir(media_ce_path);
949 res &= destroy_dir(misc_ce_path);
950 res &= destroy_dir(user_ce_path);
951 if (volume_uuid.empty()) {
952 res &= destroy_dir(system_ce_path);
953 res &= destroy_dir(vendor_ce_path);
954 } else {
955 if (fscrypt_is_native()) {
956 auto misc_ce_empty_volume_path = android::vold::BuildDataMiscCePath("", user_id);
957 res &= destroy_volkey(misc_ce_empty_volume_path, volume_uuid);
958 }
959 }
960 }
961
962 if (flags & android::os::IVold::STORAGE_FLAG_DE) {
963 // DE_sys key
964 auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
965 auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
966 auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
967
968 // DE_n key
969 auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
970 auto misc_de_path = android::vold::BuildDataMiscDePath(volume_uuid, user_id);
971 auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
972 auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
973
974 res &= destroy_dir(user_de_path);
975 res &= destroy_dir(misc_de_path);
976 if (volume_uuid.empty()) {
977 res &= destroy_dir(system_legacy_path);
978 #if MANAGE_MISC_DIRS
979 res &= destroy_dir(misc_legacy_path);
980 #endif
981 res &= destroy_dir(profiles_de_path);
982 res &= destroy_dir(system_de_path);
983 res &= destroy_dir(vendor_de_path);
984 } else {
985 if (fscrypt_is_native()) {
986 auto misc_de_empty_volume_path = android::vold::BuildDataMiscDePath("", user_id);
987 res &= destroy_volkey(misc_de_empty_volume_path, volume_uuid);
988 }
989 }
990 }
991
992 return res;
993 }
994
destroy_volume_keys(const std::string & directory_path,const std::string & volume_uuid)995 static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
996 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
997 if (!dirp) {
998 PLOG(ERROR) << "Unable to open directory: " + directory_path;
999 return false;
1000 }
1001 bool res = true;
1002 for (;;) {
1003 errno = 0;
1004 auto const entry = readdir(dirp.get());
1005 if (!entry) {
1006 if (errno) {
1007 PLOG(ERROR) << "Unable to read directory: " + directory_path;
1008 return false;
1009 }
1010 break;
1011 }
1012 if (IsDotOrDotDot(*entry)) continue;
1013 if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
1014 LOG(DEBUG) << "Skipping non-user " << entry->d_name;
1015 continue;
1016 }
1017 res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
1018 }
1019 return res;
1020 }
1021
fscrypt_destroy_volume_keys(const std::string & volume_uuid)1022 bool fscrypt_destroy_volume_keys(const std::string& volume_uuid) {
1023 bool res = true;
1024 LOG(DEBUG) << "fscrypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
1025 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
1026 res &= android::vold::runSecdiscardSingle(secdiscardable_path);
1027 res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
1028 res &= destroy_volume_keys("/data/misc_de", volume_uuid);
1029 return res;
1030 }
1031