blob: 418164ed55eac8c0de1f9dbbd297e37afad80381 [file] [log] [blame]
bigbiff7ba75002020-04-11 20:47:09 -04001/*
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"
bigbiffa957f072021-03-07 18:20:29 -050022#include "VoldUtil.h"
bigbiff7ba75002020-04-11 20:47:09 -040023
24#include <algorithm>
25#include <map>
bigbiffa957f072021-03-07 18:20:29 -050026#include <optional>
bigbiff7ba75002020-04-11 20:47:09 -040027#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>
bigbiffa957f072021-03-07 18:20:29 -050043#include <private/android_projectid_config.h>
bigbiff7ba75002020-04-11 20:47:09 -040044
bigbiffa957f072021-03-07 18:20:29 -050045#include "android/os/IVold.h"
bigbiff7ba75002020-04-11 20:47:09 -040046
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>
bigbiff7ba75002020-04-11 20:47:09 -040054#include <keyutils.h>
bigbiffa957f072021-03-07 18:20:29 -050055#include <libdm/dm.h>
bigbiff7ba75002020-04-11 20:47:09 -040056
57#include <android-base/file.h>
58#include <android-base/logging.h>
59#include <android-base/properties.h>
60#include <android-base/stringprintf.h>
bigbiffa957f072021-03-07 18:20:29 -050061#include <android-base/strings.h>
bigbiff7ba75002020-04-11 20:47:09 -040062#include <android-base/unique_fd.h>
63
bigbiffa957f072021-03-07 18:20:29 -050064#include "fscrypt-common.h"
bigbiff7ba75002020-04-11 20:47:09 -040065
bigbiffa957f072021-03-07 18:20:29 -050066using android::base::Basename;
67using android::base::Realpath;
68using android::base::StartsWith;
bigbiff7ba75002020-04-11 20:47:09 -040069using android::base::StringPrintf;
70using android::fs_mgr::GetEntryForMountPoint;
bigbiffa957f072021-03-07 18:20:29 -050071using ::BuildDataPath;
72using ::IsFilesystemSupported;
73using ::kEmptyAuthentication;
74using ::KeyBuffer;
75using ::KeyGeneration;
76using ::retrieveKey;
77using ::retrieveOrGenerateKey;
78using ::SetQuotaInherit;
79using ::SetQuotaProjectId;
80using ::writeStringToFile;
81using namespace android::fscrypt;
82using namespace android::dm;
bigbiff7ba75002020-04-11 20:47:09 -040083
bigbiffa957f072021-03-07 18:20:29 -050084// Map user ids to encryption policies
85std::map<userid_t, EncryptionPolicy> s_de_policies;
86std::map<userid_t, EncryptionPolicy> s_ce_policies;
87std::string de_key_raw_ref;
bigbiff7ba75002020-04-11 20:47:09 -040088
89namespace {
90
bigbiff7ba75002020-04-11 20:47:09 -040091const std::string device_key_dir = std::string() + DATA_MNT_POINT + fscrypt_unencrypted_folder;
92const std::string device_key_path = device_key_dir + "/key";
93const std::string device_key_temp = device_key_dir + "/temp";
94
95const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
96const std::string user_key_temp = user_key_dir + "/temp";
bigbiffad58e1b2020-07-06 20:24:34 -040097const std::string prepare_subdirs_path = "/system/bin/vold_prepare_subdirs";
bigbiff7ba75002020-04-11 20:47:09 -040098
99const std::string systemwide_volume_key_dir =
100 std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
bigbiff7ba75002020-04-11 20:47:09 -0400101
102// Some users are ephemeral, don't try to wipe their keys from disk
103std::set<userid_t> s_ephemeral_users;
104
bigbiff7ba75002020-04-11 20:47:09 -0400105} // namespace
106
bigbiffa957f072021-03-07 18:20:29 -0500107// Returns KeyGeneration suitable for key as described in EncryptionOptions
108static KeyGeneration makeGen(const EncryptionOptions& options) {
109 return KeyGeneration{FSCRYPT_MAX_KEY_SIZE, true, options.use_hw_wrapped_key};
110}
111
bigbiff7ba75002020-04-11 20:47:09 -0400112static bool fscrypt_is_emulated() {
113 return property_get_bool("persist.sys.emulate_fbe", false);
114}
115
116static const char* escape_empty(const std::string& value) {
117 return value.empty() ? "null" : value.c_str();
118}
119
120static std::string get_de_key_path(userid_t user_id) {
121 return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
122}
123
124static std::string get_ce_key_directory_path(userid_t user_id) {
125 return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
126}
127
128// Returns the keys newest first
129static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
130 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
131 if (!dirp) {
132 PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
133 return std::vector<std::string>();
134 }
135 std::vector<std::string> result;
136 for (;;) {
137 errno = 0;
138 auto const entry = readdir(dirp.get());
139 if (!entry) {
140 if (errno) {
141 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
142 return std::vector<std::string>();
143 }
144 break;
145 }
146 if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
bigbiffa957f072021-03-07 18:20:29 -0500147 LOG(INFO) << "Skipping non-key " << entry->d_name;
bigbiff7ba75002020-04-11 20:47:09 -0400148 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
157static std::string get_ce_key_current_path(const std::string& directory_path) {
158 return directory_path + "/current";
159}
160
161static 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.
179static 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) {
bigbiffa957f072021-03-07 18:20:29 -0500183 ::destroyKey(other_path);
bigbiff7ba75002020-04-11 20:47:09 -0400184 }
185 }
186 auto const current_path = get_ce_key_current_path(directory_path);
187 if (to_fix != current_path) {
bigbiffa957f072021-03-07 18:20:29 -0500188 LOG(INFO) << "Renaming " << to_fix << " to " << current_path;
bigbiff7ba75002020-04-11 20:47:09 -0400189 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 }
bigbiffa957f072021-03-07 18:20:29 -0500194 ::FsyncDirectory(directory_path);
bigbiff7ba75002020-04-11 20:47:09 -0400195}
196
197static bool read_and_fixate_user_ce_key(userid_t user_id,
bigbiffa957f072021-03-07 18:20:29 -0500198 const ::KeyAuthentication& auth,
bigbiff7ba75002020-04-11 20:47:09 -0400199 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) {
bigbiffa957f072021-03-07 18:20:29 -0500203 LOG(INFO) << "Trying user CE key " << ce_key_path;
204 if (retrieveKey(ce_key_path, auth, ce_key)) {
205 LOG(INFO) << "Successfully retrieved key";
bigbiff7ba75002020-04-11 20:47:09 -0400206 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
bigbiffa957f072021-03-07 18:20:29 -0500214static 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(INFO) << "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.
235static bool get_data_file_encryption_options(EncryptionOptions* options) {
236 if (!ReadDefaultFstab(&fstab_default)) {
237 PLOG(ERROR) << "Failed to open default fstab";
mauronofrio matarrese79820322020-05-25 19:48:56 +0200238 return false;
239 }
bigbiffa957f072021-03-07 18:20:29 -0500240 auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
241 if (entry == nullptr) {
242 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
mauronofrio matarresef1079ed2020-05-25 20:52:57 +0200243 return false;
244 }
bigbiffa957f072021-03-07 18:20:29 -0500245 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 !IsEmmcStorage(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;
mauronofrio matarresef1079ed2020-05-25 20:52:57 +0200257}
258
bigbiffa957f072021-03-07 18:20:29 -0500259static 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.
273static 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 constexpr uint64_t pre_gki_level = 29;
280 auto filenames_mode =
281 android::base::GetProperty("ro.crypto.volume.filenames_mode",
282 first_api_level > pre_gki_level ? "" : "aes-256-heh");
283 auto options_string = android::base::GetProperty("ro.crypto.volume.options",
284 contents_mode + ":" + filenames_mode);
285 if (!ParseOptionsForApiLevel(first_api_level, options_string, options)) {
286 LOG(ERROR) << "Unable to parse volume encryption options: " << options_string;
287 return false;
288 }
289 if (options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
290 LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage. Remove "
291 "this flag from ro.crypto.volume.options";
292 return false;
293 }
294 return true;
mauronofrio539597d2020-05-25 22:23:48 +0200295}
296
bigbiff7ba75002020-04-11 20:47:09 -0400297static bool read_and_install_user_ce_key(userid_t user_id,
bigbiffa957f072021-03-07 18:20:29 -0500298 const ::KeyAuthentication& auth) {
299 if (s_ce_policies.count(user_id) != 0) return true;
300 EncryptionOptions options;
301 if (!get_data_file_encryption_options(&options)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400302 KeyBuffer ce_key;
303 if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500304 EncryptionPolicy ce_policy;
305 if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
306 s_ce_policies[user_id] = ce_policy;
307 LOG(INFO) << "Installed ce key for user " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400308 return true;
309}
310
311static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
bigbiffa957f072021-03-07 18:20:29 -0500312 LOG(INFO) << "Preparing: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400313 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
314 PLOG(ERROR) << "Failed to prepare " << dir;
315 return false;
316 }
317 return true;
318}
319
320static bool destroy_dir(const std::string& dir) {
bigbiffa957f072021-03-07 18:20:29 -0500321 LOG(INFO) << "Destroying: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400322 if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
323 PLOG(ERROR) << "Failed to destroy " << dir;
324 return false;
325 }
326 return true;
327}
328
329// NB this assumes that there is only one thread listening for crypt commands, because
330// it creates keys in a fixed location.
331static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
bigbiffa957f072021-03-07 18:20:29 -0500332 LOG(INFO) << "fscrypt::create_and_install_user_keys";
333 EncryptionOptions options;
334 if (!get_data_file_encryption_options(&options)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400335 KeyBuffer de_key, ce_key;
bigbiffa957f072021-03-07 18:20:29 -0500336 if (!generateStorageKey(makeGen(options), &de_key)) return false;
337 if (!generateStorageKey(makeGen(options), &ce_key)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400338 if (create_ephemeral) {
339 // If the key should be created as ephemeral, don't store it.
340 s_ephemeral_users.insert(user_id);
341 } else {
342 auto const directory_path = get_ce_key_directory_path(user_id);
343 if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
344 auto const paths = get_ce_key_paths(directory_path);
345 std::string ce_key_path;
346 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500347 if (!::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication,
bigbiff7ba75002020-04-11 20:47:09 -0400348 ce_key))
349 return false;
350 fixate_user_ce_key(directory_path, ce_key_path, paths);
351 // Write DE key second; once this is written, all is good.
bigbiffa957f072021-03-07 18:20:29 -0500352 if (!::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
bigbiff7ba75002020-04-11 20:47:09 -0400353 kEmptyAuthentication, de_key))
354 return false;
355 }
bigbiffa957f072021-03-07 18:20:29 -0500356 EncryptionPolicy de_policy;
357 if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
358 s_de_policies[user_id] = de_policy;
359 LOG(INFO) << "fscrypt::added de_policy";
360 EncryptionPolicy ce_policy;
361 if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
362 s_ce_policies[user_id] = ce_policy;
363 LOG(INFO) << "Created keys for user " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400364 return true;
365}
366
bigbiffa957f072021-03-07 18:20:29 -0500367bool lookup_policy(const std::map<userid_t, EncryptionPolicy>& key_map, userid_t user_id,
368 EncryptionPolicy* policy) {
bigbiff7ba75002020-04-11 20:47:09 -0400369 auto refi = key_map.find(user_id);
370 if (refi == key_map.end()) {
bigbiffa957f072021-03-07 18:20:29 -0500371 LOG(ERROR) << "Cannot find key for " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400372 return false;
373 }
bigbiffa957f072021-03-07 18:20:29 -0500374 *policy = refi->second;
bigbiff7ba75002020-04-11 20:47:09 -0400375 return true;
376}
377
bigbiff7ba75002020-04-11 20:47:09 -0400378static bool is_numeric(const char* name) {
379 for (const char* p = name; *p != '\0'; p++) {
380 if (!isdigit(*p)) return false;
381 }
382 return true;
383}
384
385static bool load_all_de_keys() {
bigbiffa957f072021-03-07 18:20:29 -0500386 LOG(INFO) << "fscrypt::load_all_de_keys";
387 EncryptionOptions options;
388 if (!get_data_file_encryption_options(&options)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400389 auto de_dir = user_key_dir + "/de";
390 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
391 if (!dirp) {
392 PLOG(ERROR) << "Unable to read de key directory";
393 return false;
394 }
395 for (;;) {
396 errno = 0;
397 auto entry = readdir(dirp.get());
398 if (!entry) {
399 if (errno) {
400 PLOG(ERROR) << "Unable to read de key directory";
401 return false;
402 }
403 break;
404 }
405 if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
bigbiffa957f072021-03-07 18:20:29 -0500406 LOG(INFO) << "Skipping non-de-key " << entry->d_name;
bigbiff7ba75002020-04-11 20:47:09 -0400407 continue;
408 }
409 userid_t user_id = std::stoi(entry->d_name);
bigbiffa957f072021-03-07 18:20:29 -0500410 auto key_path = de_dir + "/" + entry->d_name;
411 KeyBuffer de_key;
412 if (!retrieveKey(key_path, kEmptyAuthentication, &de_key)) return false;
413 EncryptionPolicy de_policy;
414 if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
415 auto ret = s_de_policies.insert({user_id, de_policy});
416 LOG(INFO) << "fscrypt::load_all_de_keys::s_de_policies::size::" << s_de_policies.size();
417 if (!ret.second && ret.first->second != de_policy) {
418 LOG(INFO) << "DE policy for user" << user_id << " changed";
419 return false;
bigbiff7ba75002020-04-11 20:47:09 -0400420 }
bigbiffa957f072021-03-07 18:20:29 -0500421 LOG(INFO) << "Installed de key for user " << user_id;
422 std::string user_prop = "twrp.user." + std::to_string(user_id) + ".decrypt";
423 property_set(user_prop.c_str(), "0");
bigbiff7ba75002020-04-11 20:47:09 -0400424 }
425 // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
426 // correct policy set on them, and that no rogue ones exist.
427 return true;
428}
429
bigbiffa957f072021-03-07 18:20:29 -0500430// Attempt to reinstall CE keys for users that we think are unlocked.
431static bool try_reload_ce_keys() {
432 for (const auto& it : s_ce_policies) {
433 if (!::reloadKeyFromSessionKeyring(DATA_MNT_POINT, it.second)) {
434 LOG(ERROR) << "Failed to load CE key from session keyring for user " << it.first;
435 return false;
436 }
437 }
438 return true;
439}
440
bigbiff7ba75002020-04-11 20:47:09 -0400441bool fscrypt_initialize_systemwide_keys() {
442 LOG(INFO) << "fscrypt_initialize_systemwide_keys";
443
bigbiffa957f072021-03-07 18:20:29 -0500444 EncryptionOptions options;
445 if (!get_data_file_encryption_options(&options)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400446
bigbiffa957f072021-03-07 18:20:29 -0500447 KeyBuffer device_key;
448 if (!retrieveOrGenerateKey(device_key_path, device_key_temp, kEmptyAuthentication,
449 makeGen(options), &device_key))
bigbiff7ba75002020-04-11 20:47:09 -0400450 return false;
bigbiff7ba75002020-04-11 20:47:09 -0400451
bigbiffa957f072021-03-07 18:20:29 -0500452 EncryptionPolicy device_policy;
453 if (!install_storage_key(DATA_MNT_POINT, options, device_key, &device_policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400454
bigbiffa957f072021-03-07 18:20:29 -0500455 std::string options_string;
456 if (!OptionsToString(device_policy.options, &options_string)) {
457 LOG(ERROR) << "Unable to serialize options";
458 return false;
459 }
460 std::string options_filename = std::string(DATA_MNT_POINT) + fscrypt_key_mode;
461 if (!::writeStringToFile(options_string, options_filename)) return false;
462
463 std::string ref_filename = std::string(DATA_MNT_POINT) + fscrypt_key_ref;
464 de_key_raw_ref = device_policy.key_raw_ref;
465 if (!::writeStringToFile(device_policy.key_raw_ref, ref_filename)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400466 LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
467
468 KeyBuffer per_boot_key;
bigbiffa957f072021-03-07 18:20:29 -0500469 if (!generateStorageKey(makeGen(options), &per_boot_key)) return false;
470 EncryptionPolicy per_boot_policy;
471 if (!install_storage_key(DATA_MNT_POINT, options, per_boot_key, &per_boot_policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400472 std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
bigbiffa957f072021-03-07 18:20:29 -0500473 if (!::writeStringToFile(per_boot_policy.key_raw_ref, per_boot_ref_filename))
474 return false;
bigbiff7ba75002020-04-11 20:47:09 -0400475 LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
476
bigbiffa957f072021-03-07 18:20:29 -0500477 if (!::FsyncDirectory(device_key_dir)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400478 return true;
479}
480
481bool fscrypt_init_user0() {
bigbiffa957f072021-03-07 18:20:29 -0500482 if (!ReadDefaultFstab(&fstab_default)) {
bigbiff7ba75002020-04-11 20:47:09 -0400483 PLOG(ERROR) << "Failed to open default fstab";
484 return -1;
485 }
bigbiffa957f072021-03-07 18:20:29 -0500486 LOG(INFO) << "fscrypt_init_user0";
bigbiff7ba75002020-04-11 20:47:09 -0400487 if (fscrypt_is_native()) {
488 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
489 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
490 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500491 if (!::pathExists(get_de_key_path(0))) {
bigbiff7ba75002020-04-11 20:47:09 -0400492 if (!create_and_install_user_keys(0, false)) return false;
493 }
494 // TODO: switch to loading only DE_0 here once framework makes
495 // explicit calls to install DE keys for secondary users
496 if (!load_all_de_keys()) return false;
497 }
498 // We can only safely prepare DE storage here, since CE keys are probably
499 // entangled with user credentials. The framework will always prepare CE
500 // storage once CE keys are installed.
bigbiffa957f072021-03-07 18:20:29 -0500501 LOG(INFO) << "attempting fscrypt_prepare_user_storage";
502 if (!fscrypt_prepare_user_storage("", 0, 0, android::os::IVold::STORAGE_FLAG_DE)) {
bigbiff7ba75002020-04-11 20:47:09 -0400503 LOG(ERROR) << "Failed to prepare user 0 storage";
504 return false;
505 }
bigbiffa957f072021-03-07 18:20:29 -0500506
bigbiff7ba75002020-04-11 20:47:09 -0400507 // If this is a non-FBE device that recently left an emulated mode,
508 // restore user data directories to known-good state.
509 if (!fscrypt_is_native() && !fscrypt_is_emulated()) {
bigbiffa957f072021-03-07 18:20:29 -0500510 LOG(INFO) << "unlocking data media";
bigbiff7ba75002020-04-11 20:47:09 -0400511 fscrypt_unlock_user_key(0, 0, "!", "!");
512 }
513
bigbiffa957f072021-03-07 18:20:29 -0500514 // In some scenarios (e.g. userspace reboot) we might unmount userdata
515 // without doing a hard reboot. If CE keys were stored in fs keyring then
516 // they will be lost after unmount. Attempt to re-install them.
517 if (fscrypt_is_native() && ::isFsKeyringSupported()) {
518 LOG(INFO) << "reloading ce keys";
519 if (!try_reload_ce_keys()) return false;
520 }
521
bigbiff7ba75002020-04-11 20:47:09 -0400522 return true;
523}
524
525bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
bigbiffa957f072021-03-07 18:20:29 -0500526 LOG(INFO) << "fscrypt_vold_create_user_key for " << user_id << " serial " << serial;
bigbiff7ba75002020-04-11 20:47:09 -0400527 if (!fscrypt_is_native()) {
bigbiffa957f072021-03-07 18:20:29 -0500528 return true;
bigbiff7ba75002020-04-11 20:47:09 -0400529 }
530 // FIXME test for existence of key that is not loaded yet
bigbiffa957f072021-03-07 18:20:29 -0500531 if (s_ce_policies.count(user_id) != 0) {
bigbiff7ba75002020-04-11 20:47:09 -0400532 LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
533 << " serial " << serial;
534 // FIXME should we fail the command?
535 return true;
536 }
537 if (!create_and_install_user_keys(user_id, ephemeral)) {
538 return false;
539 }
540 return true;
541}
542
bigbiffa957f072021-03-07 18:20:29 -0500543// "Lock" all encrypted directories whose key has been removed. This is needed
544// in the case where the keys are being put in the session keyring (rather in
545// the newer filesystem-level keyrings), because removing a key from the session
546// keyring doesn't affect inodes in the kernel's inode cache whose per-file key
547// was already set up. So to remove the per-file keys and make the files
548// "appear encrypted", these inodes must be evicted.
549//
550// To do this, sync() to clean all dirty inodes, then drop all reclaimable slab
551// objects systemwide. This is overkill, but it's the best available method
552// currently. Don't use drop_caches mode "3" because that also evicts pagecache
553// for in-use files; all files relevant here are already closed and sync'ed.
554static void drop_caches_if_needed() {
555 if (::isFsKeyringSupported()) {
556 return;
557 }
bigbiff7ba75002020-04-11 20:47:09 -0400558 sync();
bigbiffa957f072021-03-07 18:20:29 -0500559 if (!writeStringToFile("2", "/proc/sys/vm/drop_caches")) {
bigbiff7ba75002020-04-11 20:47:09 -0400560 PLOG(ERROR) << "Failed to drop caches during key eviction";
561 }
562}
563
564static bool evict_ce_key(userid_t user_id) {
bigbiff7ba75002020-04-11 20:47:09 -0400565 bool success = true;
bigbiffa957f072021-03-07 18:20:29 -0500566 EncryptionPolicy policy;
bigbiff7ba75002020-04-11 20:47:09 -0400567 // If we haven't loaded the CE key, no need to evict it.
bigbiffa957f072021-03-07 18:20:29 -0500568 if (lookup_policy(s_ce_policies, user_id, &policy)) {
569 success &= ::evictKey(DATA_MNT_POINT, policy);
570 drop_caches_if_needed();
bigbiff7ba75002020-04-11 20:47:09 -0400571 }
bigbiffa957f072021-03-07 18:20:29 -0500572 s_ce_policies.erase(user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400573 return success;
574}
575
576bool fscrypt_destroy_user_key(userid_t user_id) {
bigbiffa957f072021-03-07 18:20:29 -0500577 LOG(INFO) << "fscrypt_destroy_user_key(" << user_id << ")";
bigbiff7ba75002020-04-11 20:47:09 -0400578 if (!fscrypt_is_native()) {
579 return true;
580 }
581 bool success = true;
bigbiff7ba75002020-04-11 20:47:09 -0400582 success &= evict_ce_key(user_id);
bigbiffa957f072021-03-07 18:20:29 -0500583 EncryptionPolicy de_policy;
584 success &= lookup_policy(s_de_policies, user_id, &de_policy) &&
585 ::evictKey(DATA_MNT_POINT, de_policy);
586 s_de_policies.erase(user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400587 auto it = s_ephemeral_users.find(user_id);
588 if (it != s_ephemeral_users.end()) {
589 s_ephemeral_users.erase(it);
590 } else {
591 for (auto const path : get_ce_key_paths(get_ce_key_directory_path(user_id))) {
bigbiffa957f072021-03-07 18:20:29 -0500592 success &= ::destroyKey(path);
bigbiff7ba75002020-04-11 20:47:09 -0400593 }
594 auto de_key_path = get_de_key_path(user_id);
bigbiffa957f072021-03-07 18:20:29 -0500595 if (::pathExists(de_key_path)) {
596 success &= ::destroyKey(de_key_path);
bigbiff7ba75002020-04-11 20:47:09 -0400597 } else {
598 LOG(INFO) << "Not present so not erasing: " << de_key_path;
599 }
600 }
601 return success;
602}
603
604static bool emulated_lock(const std::string& path) {
605 if (chmod(path.c_str(), 0000) != 0) {
606 PLOG(ERROR) << "Failed to chmod " << path;
607 return false;
608 }
609#if EMULATED_USES_SELINUX
610 if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
611 PLOG(WARNING) << "Failed to setfilecon " << path;
612 return false;
613 }
614#endif
615 return true;
616}
617
618static bool emulated_unlock(const std::string& path, mode_t mode) {
619 if (chmod(path.c_str(), mode) != 0) {
620 PLOG(ERROR) << "Failed to chmod " << path;
621 // FIXME temporary workaround for b/26713622
622 if (fscrypt_is_emulated()) return false;
623 }
624#if EMULATED_USES_SELINUX
625 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
626 PLOG(WARNING) << "Failed to restorecon " << path;
627 // FIXME temporary workaround for b/26713622
628 if (fscrypt_is_emulated()) return false;
629 }
630#endif
631 return true;
632}
633
634static bool parse_hex(const std::string& hex, std::string* result) {
635 if (hex == "!") {
636 *result = "";
637 return true;
638 }
bigbiffa957f072021-03-07 18:20:29 -0500639 if (::HexToStr(hex, *result) != 0) {
bigbiff7ba75002020-04-11 20:47:09 -0400640 LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
641 return false;
642 }
643 return true;
644}
645
bigbiffa957f072021-03-07 18:20:29 -0500646static std::optional<::KeyAuthentication> authentication_from_hex(
647 const std::string& token_hex, const std::string& secret_hex) {
648 std::string token, secret;
649 if (!parse_hex(token_hex, &token)) return std::optional<::KeyAuthentication>();
650 if (!parse_hex(secret_hex, &secret)) return std::optional<::KeyAuthentication>();
651 if (secret.empty()) {
652 return kEmptyAuthentication;
653 } else {
654 return ::KeyAuthentication(token, secret);
655 }
656}
657
bigbiff7ba75002020-04-11 20:47:09 -0400658static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
659 return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
660}
661
662static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
663 return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
664}
665
666static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
bigbiffa957f072021-03-07 18:20:29 -0500667 EncryptionPolicy* policy) {
bigbiff7ba75002020-04-11 20:47:09 -0400668 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
669 std::string secdiscardable_hash;
bigbiffa957f072021-03-07 18:20:29 -0500670 if (::pathExists(secdiscardable_path)) {
671 if (!readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
bigbiff7ba75002020-04-11 20:47:09 -0400672 return false;
673 } else {
674 if (fs_mkdirs(secdiscardable_path.c_str(), 0700) != 0) {
675 PLOG(ERROR) << "Creating directories for: " << secdiscardable_path;
676 return false;
677 }
bigbiffa957f072021-03-07 18:20:29 -0500678 if (!::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
bigbiff7ba75002020-04-11 20:47:09 -0400679 return false;
680 }
681 auto key_path = volkey_path(misc_path, volume_uuid);
682 if (fs_mkdirs(key_path.c_str(), 0700) != 0) {
683 PLOG(ERROR) << "Creating directories for: " << key_path;
684 return false;
685 }
bigbiffa957f072021-03-07 18:20:29 -0500686 ::KeyAuthentication auth("", secdiscardable_hash);
mauronofrio matarrese79820322020-05-25 19:48:56 +0200687
bigbiffa957f072021-03-07 18:20:29 -0500688 EncryptionOptions options;
689 if (!get_volume_file_encryption_options(&options)) return false;
690 KeyBuffer key;
691 if (!retrieveOrGenerateKey(key_path, key_path + "_tmp", auth, makeGen(options), &key))
bigbiff7ba75002020-04-11 20:47:09 -0400692 return false;
bigbiffa957f072021-03-07 18:20:29 -0500693 if (!install_storage_key(BuildDataPath(volume_uuid), options, key, policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400694 return true;
695}
696
697static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
698 auto path = volkey_path(misc_path, volume_uuid);
bigbiffa957f072021-03-07 18:20:29 -0500699 if (!::pathExists(path)) return true;
700 return ::destroyKey(path);
701}
702
703static bool fscrypt_rewrap_user_key(userid_t user_id, int serial,
704 const ::KeyAuthentication& retrieve_auth,
705 const ::KeyAuthentication& store_auth) {
706 if (s_ephemeral_users.count(user_id) != 0) return true;
707 auto const directory_path = get_ce_key_directory_path(user_id);
708 KeyBuffer ce_key;
709 std::string ce_key_current_path = get_ce_key_current_path(directory_path);
710 if (retrieveKey(ce_key_current_path, retrieve_auth, &ce_key)) {
711 LOG(INFO) << "Successfully retrieved key";
712 // TODO(147732812): Remove this once Locksettingservice is fixed.
713 // Currently it calls fscrypt_clear_user_key_auth with a secret when lockscreen is
714 // changed from swipe to none or vice-versa
715 } else if (retrieveKey(ce_key_current_path, kEmptyAuthentication, &ce_key)) {
716 LOG(INFO) << "Successfully retrieved key with empty auth";
717 } else {
718 LOG(ERROR) << "Failed to retrieve key for user " << user_id;
719 return false;
720 }
721 auto const paths = get_ce_key_paths(directory_path);
722 std::string ce_key_path;
723 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
724 if (!::storeKeyAtomically(ce_key_path, user_key_temp, store_auth, ce_key))
725 return false;
726 if (!::FsyncDirectory(directory_path)) return false;
727 return true;
bigbiff7ba75002020-04-11 20:47:09 -0400728}
729
730bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
731 const std::string& secret_hex) {
bigbiffa957f072021-03-07 18:20:29 -0500732 LOG(INFO) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial
bigbiff7ba75002020-04-11 20:47:09 -0400733 << " token_present=" << (token_hex != "!");
734 if (!fscrypt_is_native()) return true;
bigbiffa957f072021-03-07 18:20:29 -0500735 auto auth = authentication_from_hex(token_hex, secret_hex);
736 if (!auth) return false;
737 return fscrypt_rewrap_user_key(user_id, serial, kEmptyAuthentication, *auth);
bigbiff7ba75002020-04-11 20:47:09 -0400738}
739
mauronofrio matarrese79820322020-05-25 19:48:56 +0200740bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
741 const std::string& secret_hex) {
bigbiffa957f072021-03-07 18:20:29 -0500742 LOG(INFO) << "fscrypt_clear_user_key_auth " << user_id << " serial=" << serial
mauronofrio matarrese79820322020-05-25 19:48:56 +0200743 << " token_present=" << (token_hex != "!");
744 if (!fscrypt_is_native()) return true;
bigbiffa957f072021-03-07 18:20:29 -0500745 auto auth = authentication_from_hex(token_hex, secret_hex);
746 if (!auth) return false;
747 return fscrypt_rewrap_user_key(user_id, serial, *auth, kEmptyAuthentication);
mauronofrio matarrese79820322020-05-25 19:48:56 +0200748}
749
bigbiff7ba75002020-04-11 20:47:09 -0400750bool fscrypt_fixate_newest_user_key_auth(userid_t user_id) {
bigbiffa957f072021-03-07 18:20:29 -0500751 LOG(INFO) << "fscrypt_fixate_newest_user_key_auth " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400752 if (!fscrypt_is_native()) return true;
753 if (s_ephemeral_users.count(user_id) != 0) return true;
754 auto const directory_path = get_ce_key_directory_path(user_id);
755 auto const paths = get_ce_key_paths(directory_path);
756 if (paths.empty()) {
757 LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
758 return false;
759 }
760 fixate_user_ce_key(directory_path, paths[0], paths);
761 return true;
762}
763
764// TODO: rename to 'install' for consistency, and take flags to know which keys to install
765bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
766 const std::string& secret_hex) {
bigbiffa957f072021-03-07 18:20:29 -0500767 LOG(INFO) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial
bigbiff7ba75002020-04-11 20:47:09 -0400768 << " token_present=" << (token_hex != "!");
769 if (fscrypt_is_native()) {
bigbiffa957f072021-03-07 18:20:29 -0500770 if (s_ce_policies.count(user_id) != 0) {
bigbiff7ba75002020-04-11 20:47:09 -0400771 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
772 return true;
773 }
bigbiffa957f072021-03-07 18:20:29 -0500774 auto auth = authentication_from_hex(token_hex, secret_hex);
775 if (!auth) return false;
776 if (!read_and_install_user_ce_key(user_id, *auth)) {
bigbiff7ba75002020-04-11 20:47:09 -0400777 LOG(ERROR) << "Couldn't read key for " << user_id;
778 return false;
779 }
780 } else {
781 // When in emulation mode, we just use chmod. However, we also
782 // unlock directories when not in emulation mode, to bring devices
783 // back into a known-good state.
bigbiffa957f072021-03-07 18:20:29 -0500784 if (!emulated_unlock(::BuildDataSystemCePath(user_id), 0771) ||
785 !emulated_unlock(::BuildDataMiscCePath(user_id), 01771) ||
786 !emulated_unlock(::BuildDataMediaCePath("", user_id), 0770) ||
787 !emulated_unlock(::BuildDataUserCePath("", user_id), 0771)) {
bigbiff7ba75002020-04-11 20:47:09 -0400788 LOG(ERROR) << "Failed to unlock user " << user_id;
789 return false;
790 }
791 }
792 return true;
793}
794
795// TODO: rename to 'evict' for consistency
796bool fscrypt_lock_user_key(userid_t user_id) {
bigbiffa957f072021-03-07 18:20:29 -0500797 LOG(INFO) << "fscrypt_lock_user_key " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400798 if (fscrypt_is_native()) {
799 return evict_ce_key(user_id);
800 } else if (fscrypt_is_emulated()) {
801 // When in emulation mode, we just use chmod
bigbiffa957f072021-03-07 18:20:29 -0500802 if (!emulated_lock(::BuildDataSystemCePath(user_id)) ||
803 !emulated_lock(::BuildDataMiscCePath(user_id)) ||
804 !emulated_lock(::BuildDataMediaCePath("", user_id)) ||
805 !emulated_lock(::BuildDataUserCePath("", user_id))) {
bigbiff7ba75002020-04-11 20:47:09 -0400806 LOG(ERROR) << "Failed to lock user " << user_id;
807 return false;
808 }
809 }
810
811 return true;
812}
813
814static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
815 userid_t user_id, int flags) {
bigbiffa957f072021-03-07 18:20:29 -0500816 if (0 != ::ForkExecvp(
bigbiff7ba75002020-04-11 20:47:09 -0400817 std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
818 std::to_string(user_id), std::to_string(flags)})) {
819 LOG(ERROR) << "vold_prepare_subdirs failed";
820 return false;
821 }
822 return true;
823}
824
825bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
826 int flags) {
bigbiffa957f072021-03-07 18:20:29 -0500827 LOG(INFO) << "fscrypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
bigbiff7ba75002020-04-11 20:47:09 -0400828 << ", user " << user_id << ", serial " << serial << ", flags " << flags;
829
bigbiffa957f072021-03-07 18:20:29 -0500830 if (flags & android::os::IVold::STORAGE_FLAG_DE) {
bigbiff7ba75002020-04-11 20:47:09 -0400831 // DE_sys key
bigbiffa957f072021-03-07 18:20:29 -0500832 auto system_legacy_path = ::BuildDataSystemLegacyPath(user_id);
833 auto misc_legacy_path = ::BuildDataMiscLegacyPath(user_id);
834 auto profiles_de_path = ::BuildDataProfilesDePath(user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400835
836 // DE_n key
bigbiffa957f072021-03-07 18:20:29 -0500837 auto system_de_path = ::BuildDataSystemDePath(user_id);
838 auto misc_de_path = ::BuildDataMiscDePath(user_id);
839 auto vendor_de_path = ::BuildDataVendorDePath(user_id);
840 auto user_de_path = ::BuildDataUserDePath(volume_uuid, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400841
842 if (volume_uuid.empty()) {
843 if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
844#if MANAGE_MISC_DIRS
845 if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
846 multiuser_get_uid(user_id, AID_EVERYBODY)))
847 return false;
848#endif
849 if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
850
851 if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
852 if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
853 if (!prepare_dir(vendor_de_path, 0771, AID_ROOT, AID_ROOT)) return false;
854 }
855 if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400856 if (fscrypt_is_native()) {
bigbiffa957f072021-03-07 18:20:29 -0500857 EncryptionPolicy de_policy;
bigbiff7ba75002020-04-11 20:47:09 -0400858 if (volume_uuid.empty()) {
bigbiffa957f072021-03-07 18:20:29 -0500859 if (!lookup_policy(s_de_policies, user_id, &de_policy)) return false;
860 if (!EnsurePolicy(de_policy, system_de_path)) return false;
861 if (!EnsurePolicy(de_policy, misc_de_path)) return false;
862 if (!EnsurePolicy(de_policy, vendor_de_path)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400863 } else {
bigbiffa957f072021-03-07 18:20:29 -0500864 if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400865 }
bigbiffa957f072021-03-07 18:20:29 -0500866 if (!EnsurePolicy(de_policy, user_de_path)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400867 }
868 }
bigbiffa957f072021-03-07 18:20:29 -0500869
870 if (flags & android::os::IVold::STORAGE_FLAG_CE) {
bigbiff7ba75002020-04-11 20:47:09 -0400871 // CE_n key
bigbiffa957f072021-03-07 18:20:29 -0500872 auto system_ce_path = ::BuildDataSystemCePath(user_id);
873 auto misc_ce_path = ::BuildDataMiscCePath(user_id);
874 auto vendor_ce_path = ::BuildDataVendorCePath(user_id);
875 auto media_ce_path = ::BuildDataMediaCePath(volume_uuid, user_id);
876 auto user_ce_path = ::BuildDataUserCePath(volume_uuid, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400877
878 if (volume_uuid.empty()) {
879 if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
880 if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
881 if (!prepare_dir(vendor_ce_path, 0771, AID_ROOT, AID_ROOT)) return false;
882 }
883 if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500884
bigbiff7ba75002020-04-11 20:47:09 -0400885 if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
886
887 if (fscrypt_is_native()) {
bigbiffa957f072021-03-07 18:20:29 -0500888 EncryptionPolicy ce_policy;
bigbiff7ba75002020-04-11 20:47:09 -0400889 if (volume_uuid.empty()) {
bigbiffa957f072021-03-07 18:20:29 -0500890 if (!lookup_policy(s_ce_policies, user_id, &ce_policy)) return false;
891 if (!EnsurePolicy(ce_policy, system_ce_path)) return false;
892 if (!EnsurePolicy(ce_policy, misc_ce_path)) return false;
893 if (!EnsurePolicy(ce_policy, vendor_ce_path)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400894 } else {
bigbiffa957f072021-03-07 18:20:29 -0500895 if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400896 }
bigbiffa957f072021-03-07 18:20:29 -0500897 if (!EnsurePolicy(ce_policy, media_ce_path)) return false;
898 if (!EnsurePolicy(ce_policy, user_ce_path)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400899 }
900
901 if (volume_uuid.empty()) {
902 // Now that credentials have been installed, we can run restorecon
903 // over these paths
904 // NOTE: these paths need to be kept in sync with libselinux
bigbiffa957f072021-03-07 18:20:29 -0500905 ::RestoreconRecursive(system_ce_path);
906 ::RestoreconRecursive(vendor_ce_path);
907 ::RestoreconRecursive(misc_ce_path);
bigbiff7ba75002020-04-11 20:47:09 -0400908 }
909 }
910 if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
911
912 return true;
913}
914
915bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
bigbiffa957f072021-03-07 18:20:29 -0500916 LOG(INFO) << "fscrypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
bigbiff7ba75002020-04-11 20:47:09 -0400917 << ", user " << user_id << ", flags " << flags;
918 bool res = true;
919
920 res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
921
bigbiffa957f072021-03-07 18:20:29 -0500922 if (flags & android::os::IVold::STORAGE_FLAG_CE) {
bigbiff7ba75002020-04-11 20:47:09 -0400923 // CE_n key
bigbiffa957f072021-03-07 18:20:29 -0500924 auto system_ce_path = ::BuildDataSystemCePath(user_id);
925 auto misc_ce_path = ::BuildDataMiscCePath(user_id);
926 auto vendor_ce_path = ::BuildDataVendorCePath(user_id);
927 auto media_ce_path = ::BuildDataMediaCePath(volume_uuid, user_id);
928 auto user_ce_path = ::BuildDataUserCePath(volume_uuid, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400929
930 res &= destroy_dir(media_ce_path);
931 res &= destroy_dir(user_ce_path);
932 if (volume_uuid.empty()) {
933 res &= destroy_dir(system_ce_path);
934 res &= destroy_dir(misc_ce_path);
935 res &= destroy_dir(vendor_ce_path);
936 } else {
937 if (fscrypt_is_native()) {
938 res &= destroy_volkey(misc_ce_path, volume_uuid);
939 }
940 }
941 }
942
bigbiffa957f072021-03-07 18:20:29 -0500943 if (flags & android::os::IVold::STORAGE_FLAG_DE) {
bigbiff7ba75002020-04-11 20:47:09 -0400944 // DE_sys key
bigbiffa957f072021-03-07 18:20:29 -0500945 auto system_legacy_path = ::BuildDataSystemLegacyPath(user_id);
946 auto misc_legacy_path = ::BuildDataMiscLegacyPath(user_id);
947 auto profiles_de_path = ::BuildDataProfilesDePath(user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400948
949 // DE_n key
bigbiffa957f072021-03-07 18:20:29 -0500950 auto system_de_path = ::BuildDataSystemDePath(user_id);
951 auto misc_de_path = ::BuildDataMiscDePath(user_id);
952 auto vendor_de_path = ::BuildDataVendorDePath(user_id);
953 auto user_de_path = ::BuildDataUserDePath(volume_uuid, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400954
955 res &= destroy_dir(user_de_path);
956 if (volume_uuid.empty()) {
957 res &= destroy_dir(system_legacy_path);
958#if MANAGE_MISC_DIRS
959 res &= destroy_dir(misc_legacy_path);
960#endif
961 res &= destroy_dir(profiles_de_path);
962 res &= destroy_dir(system_de_path);
963 res &= destroy_dir(misc_de_path);
964 res &= destroy_dir(vendor_de_path);
965 } else {
966 if (fscrypt_is_native()) {
967 res &= destroy_volkey(misc_de_path, volume_uuid);
968 }
969 }
970 }
971
972 return res;
973}
974
975static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
976 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
977 if (!dirp) {
978 PLOG(ERROR) << "Unable to open directory: " + directory_path;
979 return false;
980 }
981 bool res = true;
982 for (;;) {
983 errno = 0;
984 auto const entry = readdir(dirp.get());
985 if (!entry) {
986 if (errno) {
987 PLOG(ERROR) << "Unable to read directory: " + directory_path;
988 return false;
989 }
990 break;
991 }
992 if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
bigbiffa957f072021-03-07 18:20:29 -0500993 LOG(INFO) << "Skipping non-user " << entry->d_name;
bigbiff7ba75002020-04-11 20:47:09 -0400994 continue;
995 }
996 res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
997 }
998 return res;
999}
1000
1001bool fscrypt_destroy_volume_keys(const std::string& volume_uuid) {
1002 bool res = true;
bigbiffa957f072021-03-07 18:20:29 -05001003 LOG(INFO) << "fscrypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
bigbiff7ba75002020-04-11 20:47:09 -04001004 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
bigbiffa957f072021-03-07 18:20:29 -05001005 res &= ::runSecdiscardSingle(secdiscardable_path);
bigbiff7ba75002020-04-11 20:47:09 -04001006 res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
1007 res &= destroy_volume_keys("/data/misc_de", volume_uuid);
1008 return res;
1009}
bigbiffa957f072021-03-07 18:20:29 -05001010
1011bool lookup_key_ref(const std::map<userid_t, android::fscrypt::EncryptionPolicy>& key_map, userid_t user_id,
1012 std::string* raw_ref) {
1013 auto refi = key_map.find(user_id);
1014 if (refi == key_map.end()) {
1015 LOG(ERROR) << "Cannot find key for " << user_id;
1016 return false;
1017 }
1018 *raw_ref = refi->second.key_raw_ref;
1019 return true;
1020}