blob: aa31fe1eba1213d3bf12c2470ef28adc2291cadb [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;
bigbiffbbbfe172021-05-30 15:52:41 -0400204 if (retrieveKey(ce_key_path, auth, ce_key, true)) {
bigbiffa957f072021-03-07 18:20:29 -0500205 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 }
bigbiffbcd23d32021-09-22 18:22:13 -0400250 if (options->version == 1) {
251 options->use_hw_wrapped_key =
252 GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT)->fs_mgr_flags.wrapped_key;
253 }
bigbiffa957f072021-03-07 18:20:29 -0500254 if ((options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
255 !IsEmmcStorage(entry->blk_device)) {
256 LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage. Remove "
257 "this flag from the device's fstab";
258 return false;
259 }
260 return true;
mauronofrio matarresef1079ed2020-05-25 20:52:57 +0200261}
262
bigbiffa957f072021-03-07 18:20:29 -0500263static bool install_storage_key(const std::string& mountpoint, const EncryptionOptions& options,
264 const KeyBuffer& key, EncryptionPolicy* policy) {
265 KeyBuffer ephemeral_wrapped_key;
266 if (options.use_hw_wrapped_key) {
267 if (!exportWrappedStorageKey(key, &ephemeral_wrapped_key)) {
268 LOG(ERROR) << "Failed to get ephemeral wrapped key";
269 return false;
270 }
271 }
272 return installKey(mountpoint, options, options.use_hw_wrapped_key ? ephemeral_wrapped_key : key,
273 policy);
274}
275
276// Retrieve the options to use for encryption policies on adoptable storage.
277static bool get_volume_file_encryption_options(EncryptionOptions* options) {
278 // If we give the empty string, libfscrypt will use the default (currently XTS)
279 auto contents_mode = android::base::GetProperty("ro.crypto.volume.contents_mode", "");
280 // HEH as default was always a mistake. Use the libfscrypt default (CTS)
281 // for devices launching on versions above Android 10.
282 auto first_api_level = GetFirstApiLevel();
283 constexpr uint64_t pre_gki_level = 29;
284 auto filenames_mode =
285 android::base::GetProperty("ro.crypto.volume.filenames_mode",
286 first_api_level > pre_gki_level ? "" : "aes-256-heh");
287 auto options_string = android::base::GetProperty("ro.crypto.volume.options",
288 contents_mode + ":" + filenames_mode);
289 if (!ParseOptionsForApiLevel(first_api_level, options_string, options)) {
290 LOG(ERROR) << "Unable to parse volume encryption options: " << options_string;
291 return false;
292 }
293 if (options->flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
294 LOG(ERROR) << "The emmc_optimized encryption flag is only allowed on eMMC storage. Remove "
295 "this flag from ro.crypto.volume.options";
296 return false;
297 }
298 return true;
mauronofrio539597d2020-05-25 22:23:48 +0200299}
300
bigbiffbcd23d32021-09-22 18:22:13 -0400301bool is_metadata_wrapped_key_supported() {
302 if (!ReadDefaultFstab(&fstab_default)) {
303 PLOG(ERROR) << "Failed to open default fstab";
304 return false;
305 }
306 return GetEntryForMountPoint(&fstab_default, METADATA_MNT_POINT)->fs_mgr_flags.wrapped_key;
307}
308
bigbiff7ba75002020-04-11 20:47:09 -0400309static bool read_and_install_user_ce_key(userid_t user_id,
bigbiffa957f072021-03-07 18:20:29 -0500310 const ::KeyAuthentication& auth) {
311 if (s_ce_policies.count(user_id) != 0) return true;
312 EncryptionOptions options;
313 if (!get_data_file_encryption_options(&options)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400314 KeyBuffer ce_key;
315 if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500316 EncryptionPolicy ce_policy;
317 if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
318 s_ce_policies[user_id] = ce_policy;
319 LOG(INFO) << "Installed ce key for user " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400320 return true;
321}
322
323static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
bigbiffa957f072021-03-07 18:20:29 -0500324 LOG(INFO) << "Preparing: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400325 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
326 PLOG(ERROR) << "Failed to prepare " << dir;
327 return false;
328 }
329 return true;
330}
331
332static bool destroy_dir(const std::string& dir) {
bigbiffa957f072021-03-07 18:20:29 -0500333 LOG(INFO) << "Destroying: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400334 if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
335 PLOG(ERROR) << "Failed to destroy " << dir;
336 return false;
337 }
338 return true;
339}
340
341// NB this assumes that there is only one thread listening for crypt commands, because
342// it creates keys in a fixed location.
343static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
bigbiffa957f072021-03-07 18:20:29 -0500344 LOG(INFO) << "fscrypt::create_and_install_user_keys";
345 EncryptionOptions options;
346 if (!get_data_file_encryption_options(&options)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400347 KeyBuffer de_key, ce_key;
bigbiffa957f072021-03-07 18:20:29 -0500348 if (!generateStorageKey(makeGen(options), &de_key)) return false;
349 if (!generateStorageKey(makeGen(options), &ce_key)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400350 if (create_ephemeral) {
351 // If the key should be created as ephemeral, don't store it.
352 s_ephemeral_users.insert(user_id);
353 } else {
354 auto const directory_path = get_ce_key_directory_path(user_id);
355 if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
356 auto const paths = get_ce_key_paths(directory_path);
357 std::string ce_key_path;
358 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500359 if (!::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication,
bigbiff7ba75002020-04-11 20:47:09 -0400360 ce_key))
361 return false;
362 fixate_user_ce_key(directory_path, ce_key_path, paths);
363 // Write DE key second; once this is written, all is good.
bigbiffa957f072021-03-07 18:20:29 -0500364 if (!::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
bigbiff7ba75002020-04-11 20:47:09 -0400365 kEmptyAuthentication, de_key))
366 return false;
367 }
bigbiffa957f072021-03-07 18:20:29 -0500368 EncryptionPolicy de_policy;
369 if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
370 s_de_policies[user_id] = de_policy;
371 LOG(INFO) << "fscrypt::added de_policy";
372 EncryptionPolicy ce_policy;
373 if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
374 s_ce_policies[user_id] = ce_policy;
375 LOG(INFO) << "Created keys for user " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400376 return true;
377}
378
bigbiffa957f072021-03-07 18:20:29 -0500379bool lookup_policy(const std::map<userid_t, EncryptionPolicy>& key_map, userid_t user_id,
380 EncryptionPolicy* policy) {
bigbiff7ba75002020-04-11 20:47:09 -0400381 auto refi = key_map.find(user_id);
382 if (refi == key_map.end()) {
bigbiffa957f072021-03-07 18:20:29 -0500383 LOG(ERROR) << "Cannot find key for " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400384 return false;
385 }
bigbiffa957f072021-03-07 18:20:29 -0500386 *policy = refi->second;
bigbiff7ba75002020-04-11 20:47:09 -0400387 return true;
388}
389
bigbiff7ba75002020-04-11 20:47:09 -0400390static bool is_numeric(const char* name) {
391 for (const char* p = name; *p != '\0'; p++) {
392 if (!isdigit(*p)) return false;
393 }
394 return true;
395}
396
397static bool load_all_de_keys() {
bigbiffa957f072021-03-07 18:20:29 -0500398 LOG(INFO) << "fscrypt::load_all_de_keys";
399 EncryptionOptions options;
400 if (!get_data_file_encryption_options(&options)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400401 auto de_dir = user_key_dir + "/de";
402 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
403 if (!dirp) {
404 PLOG(ERROR) << "Unable to read de key directory";
405 return false;
406 }
407 for (;;) {
408 errno = 0;
409 auto entry = readdir(dirp.get());
410 if (!entry) {
411 if (errno) {
412 PLOG(ERROR) << "Unable to read de key directory";
413 return false;
414 }
415 break;
416 }
417 if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
bigbiffa957f072021-03-07 18:20:29 -0500418 LOG(INFO) << "Skipping non-de-key " << entry->d_name;
bigbiff7ba75002020-04-11 20:47:09 -0400419 continue;
420 }
421 userid_t user_id = std::stoi(entry->d_name);
bigbiffa957f072021-03-07 18:20:29 -0500422 auto key_path = de_dir + "/" + entry->d_name;
423 KeyBuffer de_key;
bigbiffbbbfe172021-05-30 15:52:41 -0400424 if (!retrieveKey(key_path, kEmptyAuthentication, &de_key, true)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500425 EncryptionPolicy de_policy;
426 if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
427 auto ret = s_de_policies.insert({user_id, de_policy});
428 LOG(INFO) << "fscrypt::load_all_de_keys::s_de_policies::size::" << s_de_policies.size();
429 if (!ret.second && ret.first->second != de_policy) {
430 LOG(INFO) << "DE policy for user" << user_id << " changed";
431 return false;
bigbiff7ba75002020-04-11 20:47:09 -0400432 }
bigbiffa957f072021-03-07 18:20:29 -0500433 LOG(INFO) << "Installed de key for user " << user_id;
434 std::string user_prop = "twrp.user." + std::to_string(user_id) + ".decrypt";
435 property_set(user_prop.c_str(), "0");
bigbiff7ba75002020-04-11 20:47:09 -0400436 }
437 // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
438 // correct policy set on them, and that no rogue ones exist.
439 return true;
440}
441
bigbiffa957f072021-03-07 18:20:29 -0500442// Attempt to reinstall CE keys for users that we think are unlocked.
443static bool try_reload_ce_keys() {
444 for (const auto& it : s_ce_policies) {
445 if (!::reloadKeyFromSessionKeyring(DATA_MNT_POINT, it.second)) {
446 LOG(ERROR) << "Failed to load CE key from session keyring for user " << it.first;
447 return false;
448 }
449 }
450 return true;
451}
452
bigbiff7ba75002020-04-11 20:47:09 -0400453bool fscrypt_initialize_systemwide_keys() {
454 LOG(INFO) << "fscrypt_initialize_systemwide_keys";
455
bigbiffa957f072021-03-07 18:20:29 -0500456 EncryptionOptions options;
457 if (!get_data_file_encryption_options(&options)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400458
bigbiffa957f072021-03-07 18:20:29 -0500459 KeyBuffer device_key;
460 if (!retrieveOrGenerateKey(device_key_path, device_key_temp, kEmptyAuthentication,
461 makeGen(options), &device_key))
bigbiff7ba75002020-04-11 20:47:09 -0400462 return false;
bigbiff7ba75002020-04-11 20:47:09 -0400463
bigbiffa957f072021-03-07 18:20:29 -0500464 EncryptionPolicy device_policy;
465 if (!install_storage_key(DATA_MNT_POINT, options, device_key, &device_policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400466
bigbiffa957f072021-03-07 18:20:29 -0500467 std::string options_string;
468 if (!OptionsToString(device_policy.options, &options_string)) {
469 LOG(ERROR) << "Unable to serialize options";
470 return false;
471 }
472 std::string options_filename = std::string(DATA_MNT_POINT) + fscrypt_key_mode;
473 if (!::writeStringToFile(options_string, options_filename)) return false;
474
475 std::string ref_filename = std::string(DATA_MNT_POINT) + fscrypt_key_ref;
476 de_key_raw_ref = device_policy.key_raw_ref;
477 if (!::writeStringToFile(device_policy.key_raw_ref, ref_filename)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400478 LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
479
480 KeyBuffer per_boot_key;
bigbiffa957f072021-03-07 18:20:29 -0500481 if (!generateStorageKey(makeGen(options), &per_boot_key)) return false;
482 EncryptionPolicy per_boot_policy;
483 if (!install_storage_key(DATA_MNT_POINT, options, per_boot_key, &per_boot_policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400484 std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
bigbiffa957f072021-03-07 18:20:29 -0500485 if (!::writeStringToFile(per_boot_policy.key_raw_ref, per_boot_ref_filename))
486 return false;
bigbiff7ba75002020-04-11 20:47:09 -0400487 LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
488
bigbiffa957f072021-03-07 18:20:29 -0500489 if (!::FsyncDirectory(device_key_dir)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400490 return true;
491}
492
493bool fscrypt_init_user0() {
bigbiffa957f072021-03-07 18:20:29 -0500494 if (!ReadDefaultFstab(&fstab_default)) {
bigbiff7ba75002020-04-11 20:47:09 -0400495 PLOG(ERROR) << "Failed to open default fstab";
496 return -1;
497 }
bigbiffa957f072021-03-07 18:20:29 -0500498 LOG(INFO) << "fscrypt_init_user0";
bigbiff7ba75002020-04-11 20:47:09 -0400499 if (fscrypt_is_native()) {
500 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
501 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
502 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500503 if (!::pathExists(get_de_key_path(0))) {
bigbiff7ba75002020-04-11 20:47:09 -0400504 if (!create_and_install_user_keys(0, false)) return false;
505 }
506 // TODO: switch to loading only DE_0 here once framework makes
507 // explicit calls to install DE keys for secondary users
508 if (!load_all_de_keys()) return false;
509 }
510 // We can only safely prepare DE storage here, since CE keys are probably
511 // entangled with user credentials. The framework will always prepare CE
512 // storage once CE keys are installed.
bigbiffa957f072021-03-07 18:20:29 -0500513 LOG(INFO) << "attempting fscrypt_prepare_user_storage";
514 if (!fscrypt_prepare_user_storage("", 0, 0, android::os::IVold::STORAGE_FLAG_DE)) {
bigbiff7ba75002020-04-11 20:47:09 -0400515 LOG(ERROR) << "Failed to prepare user 0 storage";
516 return false;
517 }
bigbiffa957f072021-03-07 18:20:29 -0500518
bigbiff7ba75002020-04-11 20:47:09 -0400519 // If this is a non-FBE device that recently left an emulated mode,
520 // restore user data directories to known-good state.
521 if (!fscrypt_is_native() && !fscrypt_is_emulated()) {
bigbiffa957f072021-03-07 18:20:29 -0500522 LOG(INFO) << "unlocking data media";
bigbiff7ba75002020-04-11 20:47:09 -0400523 fscrypt_unlock_user_key(0, 0, "!", "!");
524 }
525
bigbiffa957f072021-03-07 18:20:29 -0500526 // In some scenarios (e.g. userspace reboot) we might unmount userdata
527 // without doing a hard reboot. If CE keys were stored in fs keyring then
528 // they will be lost after unmount. Attempt to re-install them.
529 if (fscrypt_is_native() && ::isFsKeyringSupported()) {
530 LOG(INFO) << "reloading ce keys";
531 if (!try_reload_ce_keys()) return false;
532 }
533
bigbiff7ba75002020-04-11 20:47:09 -0400534 return true;
535}
536
537bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
bigbiffa957f072021-03-07 18:20:29 -0500538 LOG(INFO) << "fscrypt_vold_create_user_key for " << user_id << " serial " << serial;
bigbiff7ba75002020-04-11 20:47:09 -0400539 if (!fscrypt_is_native()) {
bigbiffa957f072021-03-07 18:20:29 -0500540 return true;
bigbiff7ba75002020-04-11 20:47:09 -0400541 }
542 // FIXME test for existence of key that is not loaded yet
bigbiffa957f072021-03-07 18:20:29 -0500543 if (s_ce_policies.count(user_id) != 0) {
bigbiff7ba75002020-04-11 20:47:09 -0400544 LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
545 << " serial " << serial;
546 // FIXME should we fail the command?
547 return true;
548 }
549 if (!create_and_install_user_keys(user_id, ephemeral)) {
550 return false;
551 }
552 return true;
553}
554
bigbiffa957f072021-03-07 18:20:29 -0500555// "Lock" all encrypted directories whose key has been removed. This is needed
556// in the case where the keys are being put in the session keyring (rather in
557// the newer filesystem-level keyrings), because removing a key from the session
558// keyring doesn't affect inodes in the kernel's inode cache whose per-file key
559// was already set up. So to remove the per-file keys and make the files
560// "appear encrypted", these inodes must be evicted.
561//
562// To do this, sync() to clean all dirty inodes, then drop all reclaimable slab
563// objects systemwide. This is overkill, but it's the best available method
564// currently. Don't use drop_caches mode "3" because that also evicts pagecache
565// for in-use files; all files relevant here are already closed and sync'ed.
566static void drop_caches_if_needed() {
567 if (::isFsKeyringSupported()) {
568 return;
569 }
bigbiff7ba75002020-04-11 20:47:09 -0400570 sync();
bigbiffa957f072021-03-07 18:20:29 -0500571 if (!writeStringToFile("2", "/proc/sys/vm/drop_caches")) {
bigbiff7ba75002020-04-11 20:47:09 -0400572 PLOG(ERROR) << "Failed to drop caches during key eviction";
573 }
574}
575
576static bool evict_ce_key(userid_t user_id) {
bigbiff7ba75002020-04-11 20:47:09 -0400577 bool success = true;
bigbiffa957f072021-03-07 18:20:29 -0500578 EncryptionPolicy policy;
bigbiff7ba75002020-04-11 20:47:09 -0400579 // If we haven't loaded the CE key, no need to evict it.
bigbiffa957f072021-03-07 18:20:29 -0500580 if (lookup_policy(s_ce_policies, user_id, &policy)) {
581 success &= ::evictKey(DATA_MNT_POINT, policy);
582 drop_caches_if_needed();
bigbiff7ba75002020-04-11 20:47:09 -0400583 }
bigbiffa957f072021-03-07 18:20:29 -0500584 s_ce_policies.erase(user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400585 return success;
586}
587
588bool fscrypt_destroy_user_key(userid_t user_id) {
bigbiffa957f072021-03-07 18:20:29 -0500589 LOG(INFO) << "fscrypt_destroy_user_key(" << user_id << ")";
bigbiff7ba75002020-04-11 20:47:09 -0400590 if (!fscrypt_is_native()) {
591 return true;
592 }
593 bool success = true;
bigbiff7ba75002020-04-11 20:47:09 -0400594 success &= evict_ce_key(user_id);
bigbiffa957f072021-03-07 18:20:29 -0500595 EncryptionPolicy de_policy;
596 success &= lookup_policy(s_de_policies, user_id, &de_policy) &&
597 ::evictKey(DATA_MNT_POINT, de_policy);
598 s_de_policies.erase(user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400599 auto it = s_ephemeral_users.find(user_id);
600 if (it != s_ephemeral_users.end()) {
601 s_ephemeral_users.erase(it);
602 } else {
603 for (auto const path : get_ce_key_paths(get_ce_key_directory_path(user_id))) {
bigbiffa957f072021-03-07 18:20:29 -0500604 success &= ::destroyKey(path);
bigbiff7ba75002020-04-11 20:47:09 -0400605 }
606 auto de_key_path = get_de_key_path(user_id);
bigbiffa957f072021-03-07 18:20:29 -0500607 if (::pathExists(de_key_path)) {
608 success &= ::destroyKey(de_key_path);
bigbiff7ba75002020-04-11 20:47:09 -0400609 } else {
610 LOG(INFO) << "Not present so not erasing: " << de_key_path;
611 }
612 }
613 return success;
614}
615
616static bool emulated_lock(const std::string& path) {
617 if (chmod(path.c_str(), 0000) != 0) {
618 PLOG(ERROR) << "Failed to chmod " << path;
619 return false;
620 }
621#if EMULATED_USES_SELINUX
622 if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
623 PLOG(WARNING) << "Failed to setfilecon " << path;
624 return false;
625 }
626#endif
627 return true;
628}
629
630static bool emulated_unlock(const std::string& path, mode_t mode) {
631 if (chmod(path.c_str(), mode) != 0) {
632 PLOG(ERROR) << "Failed to chmod " << path;
633 // FIXME temporary workaround for b/26713622
634 if (fscrypt_is_emulated()) return false;
635 }
636#if EMULATED_USES_SELINUX
637 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
638 PLOG(WARNING) << "Failed to restorecon " << path;
639 // FIXME temporary workaround for b/26713622
640 if (fscrypt_is_emulated()) return false;
641 }
642#endif
643 return true;
644}
645
646static bool parse_hex(const std::string& hex, std::string* result) {
647 if (hex == "!") {
648 *result = "";
649 return true;
650 }
bigbiffa957f072021-03-07 18:20:29 -0500651 if (::HexToStr(hex, *result) != 0) {
bigbiff7ba75002020-04-11 20:47:09 -0400652 LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
653 return false;
654 }
655 return true;
656}
657
bigbiffa957f072021-03-07 18:20:29 -0500658static std::optional<::KeyAuthentication> authentication_from_hex(
659 const std::string& token_hex, const std::string& secret_hex) {
660 std::string token, secret;
661 if (!parse_hex(token_hex, &token)) return std::optional<::KeyAuthentication>();
662 if (!parse_hex(secret_hex, &secret)) return std::optional<::KeyAuthentication>();
663 if (secret.empty()) {
664 return kEmptyAuthentication;
665 } else {
666 return ::KeyAuthentication(token, secret);
667 }
668}
669
bigbiff7ba75002020-04-11 20:47:09 -0400670static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
671 return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
672}
673
674static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
675 return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
676}
677
678static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
bigbiffa957f072021-03-07 18:20:29 -0500679 EncryptionPolicy* policy) {
bigbiff7ba75002020-04-11 20:47:09 -0400680 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
681 std::string secdiscardable_hash;
bigbiffa957f072021-03-07 18:20:29 -0500682 if (::pathExists(secdiscardable_path)) {
683 if (!readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
bigbiff7ba75002020-04-11 20:47:09 -0400684 return false;
685 } else {
686 if (fs_mkdirs(secdiscardable_path.c_str(), 0700) != 0) {
687 PLOG(ERROR) << "Creating directories for: " << secdiscardable_path;
688 return false;
689 }
bigbiffa957f072021-03-07 18:20:29 -0500690 if (!::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
bigbiff7ba75002020-04-11 20:47:09 -0400691 return false;
692 }
693 auto key_path = volkey_path(misc_path, volume_uuid);
694 if (fs_mkdirs(key_path.c_str(), 0700) != 0) {
695 PLOG(ERROR) << "Creating directories for: " << key_path;
696 return false;
697 }
bigbiffa957f072021-03-07 18:20:29 -0500698 ::KeyAuthentication auth("", secdiscardable_hash);
mauronofrio matarrese79820322020-05-25 19:48:56 +0200699
bigbiffa957f072021-03-07 18:20:29 -0500700 EncryptionOptions options;
701 if (!get_volume_file_encryption_options(&options)) return false;
702 KeyBuffer key;
703 if (!retrieveOrGenerateKey(key_path, key_path + "_tmp", auth, makeGen(options), &key))
bigbiff7ba75002020-04-11 20:47:09 -0400704 return false;
bigbiffa957f072021-03-07 18:20:29 -0500705 if (!install_storage_key(BuildDataPath(volume_uuid), options, key, policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400706 return true;
707}
708
709static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
710 auto path = volkey_path(misc_path, volume_uuid);
bigbiffa957f072021-03-07 18:20:29 -0500711 if (!::pathExists(path)) return true;
712 return ::destroyKey(path);
713}
714
715static bool fscrypt_rewrap_user_key(userid_t user_id, int serial,
716 const ::KeyAuthentication& retrieve_auth,
717 const ::KeyAuthentication& store_auth) {
718 if (s_ephemeral_users.count(user_id) != 0) return true;
719 auto const directory_path = get_ce_key_directory_path(user_id);
720 KeyBuffer ce_key;
721 std::string ce_key_current_path = get_ce_key_current_path(directory_path);
bigbiffbbbfe172021-05-30 15:52:41 -0400722 if (retrieveKey(ce_key_current_path, retrieve_auth, &ce_key, true)) {
bigbiffa957f072021-03-07 18:20:29 -0500723 LOG(INFO) << "Successfully retrieved key";
724 // TODO(147732812): Remove this once Locksettingservice is fixed.
725 // Currently it calls fscrypt_clear_user_key_auth with a secret when lockscreen is
726 // changed from swipe to none or vice-versa
bigbiffbbbfe172021-05-30 15:52:41 -0400727 } else if (retrieveKey(ce_key_current_path, kEmptyAuthentication, &ce_key, true)) {
bigbiffa957f072021-03-07 18:20:29 -0500728 LOG(INFO) << "Successfully retrieved key with empty auth";
729 } else {
730 LOG(ERROR) << "Failed to retrieve key for user " << user_id;
731 return false;
732 }
733 auto const paths = get_ce_key_paths(directory_path);
734 std::string ce_key_path;
735 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
736 if (!::storeKeyAtomically(ce_key_path, user_key_temp, store_auth, ce_key))
737 return false;
738 if (!::FsyncDirectory(directory_path)) return false;
739 return true;
bigbiff7ba75002020-04-11 20:47:09 -0400740}
741
742bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
743 const std::string& secret_hex) {
bigbiffa957f072021-03-07 18:20:29 -0500744 LOG(INFO) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial
bigbiff7ba75002020-04-11 20:47:09 -0400745 << " token_present=" << (token_hex != "!");
746 if (!fscrypt_is_native()) return true;
bigbiffa957f072021-03-07 18:20:29 -0500747 auto auth = authentication_from_hex(token_hex, secret_hex);
748 if (!auth) return false;
749 return fscrypt_rewrap_user_key(user_id, serial, kEmptyAuthentication, *auth);
bigbiff7ba75002020-04-11 20:47:09 -0400750}
751
mauronofrio matarrese79820322020-05-25 19:48:56 +0200752bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
753 const std::string& secret_hex) {
bigbiffa957f072021-03-07 18:20:29 -0500754 LOG(INFO) << "fscrypt_clear_user_key_auth " << user_id << " serial=" << serial
mauronofrio matarrese79820322020-05-25 19:48:56 +0200755 << " token_present=" << (token_hex != "!");
756 if (!fscrypt_is_native()) return true;
bigbiffa957f072021-03-07 18:20:29 -0500757 auto auth = authentication_from_hex(token_hex, secret_hex);
758 if (!auth) return false;
759 return fscrypt_rewrap_user_key(user_id, serial, *auth, kEmptyAuthentication);
mauronofrio matarrese79820322020-05-25 19:48:56 +0200760}
761
bigbiff7ba75002020-04-11 20:47:09 -0400762bool fscrypt_fixate_newest_user_key_auth(userid_t user_id) {
bigbiffa957f072021-03-07 18:20:29 -0500763 LOG(INFO) << "fscrypt_fixate_newest_user_key_auth " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400764 if (!fscrypt_is_native()) return true;
765 if (s_ephemeral_users.count(user_id) != 0) return true;
766 auto const directory_path = get_ce_key_directory_path(user_id);
767 auto const paths = get_ce_key_paths(directory_path);
768 if (paths.empty()) {
769 LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
770 return false;
771 }
772 fixate_user_ce_key(directory_path, paths[0], paths);
773 return true;
774}
775
776// TODO: rename to 'install' for consistency, and take flags to know which keys to install
777bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
778 const std::string& secret_hex) {
bigbiffa957f072021-03-07 18:20:29 -0500779 LOG(INFO) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial
bigbiff7ba75002020-04-11 20:47:09 -0400780 << " token_present=" << (token_hex != "!");
781 if (fscrypt_is_native()) {
bigbiffa957f072021-03-07 18:20:29 -0500782 if (s_ce_policies.count(user_id) != 0) {
bigbiff7ba75002020-04-11 20:47:09 -0400783 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
784 return true;
785 }
bigbiffa957f072021-03-07 18:20:29 -0500786 auto auth = authentication_from_hex(token_hex, secret_hex);
787 if (!auth) return false;
788 if (!read_and_install_user_ce_key(user_id, *auth)) {
bigbiff7ba75002020-04-11 20:47:09 -0400789 LOG(ERROR) << "Couldn't read key for " << user_id;
790 return false;
791 }
792 } else {
793 // When in emulation mode, we just use chmod. However, we also
794 // unlock directories when not in emulation mode, to bring devices
795 // back into a known-good state.
bigbiffa957f072021-03-07 18:20:29 -0500796 if (!emulated_unlock(::BuildDataSystemCePath(user_id), 0771) ||
797 !emulated_unlock(::BuildDataMiscCePath(user_id), 01771) ||
798 !emulated_unlock(::BuildDataMediaCePath("", user_id), 0770) ||
799 !emulated_unlock(::BuildDataUserCePath("", user_id), 0771)) {
bigbiff7ba75002020-04-11 20:47:09 -0400800 LOG(ERROR) << "Failed to unlock user " << user_id;
801 return false;
802 }
803 }
804 return true;
805}
806
807// TODO: rename to 'evict' for consistency
808bool fscrypt_lock_user_key(userid_t user_id) {
bigbiffa957f072021-03-07 18:20:29 -0500809 LOG(INFO) << "fscrypt_lock_user_key " << user_id;
bigbiff7ba75002020-04-11 20:47:09 -0400810 if (fscrypt_is_native()) {
811 return evict_ce_key(user_id);
812 } else if (fscrypt_is_emulated()) {
813 // When in emulation mode, we just use chmod
bigbiffa957f072021-03-07 18:20:29 -0500814 if (!emulated_lock(::BuildDataSystemCePath(user_id)) ||
815 !emulated_lock(::BuildDataMiscCePath(user_id)) ||
816 !emulated_lock(::BuildDataMediaCePath("", user_id)) ||
817 !emulated_lock(::BuildDataUserCePath("", user_id))) {
bigbiff7ba75002020-04-11 20:47:09 -0400818 LOG(ERROR) << "Failed to lock user " << user_id;
819 return false;
820 }
821 }
822
823 return true;
824}
825
826static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
827 userid_t user_id, int flags) {
bigbiffa957f072021-03-07 18:20:29 -0500828 if (0 != ::ForkExecvp(
bigbiff7ba75002020-04-11 20:47:09 -0400829 std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
830 std::to_string(user_id), std::to_string(flags)})) {
831 LOG(ERROR) << "vold_prepare_subdirs failed";
832 return false;
833 }
834 return true;
835}
836
837bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
838 int flags) {
bigbiffa957f072021-03-07 18:20:29 -0500839 LOG(INFO) << "fscrypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
bigbiff7ba75002020-04-11 20:47:09 -0400840 << ", user " << user_id << ", serial " << serial << ", flags " << flags;
841
bigbiffa957f072021-03-07 18:20:29 -0500842 if (flags & android::os::IVold::STORAGE_FLAG_DE) {
bigbiff7ba75002020-04-11 20:47:09 -0400843 // DE_sys key
bigbiffa957f072021-03-07 18:20:29 -0500844 auto system_legacy_path = ::BuildDataSystemLegacyPath(user_id);
845 auto misc_legacy_path = ::BuildDataMiscLegacyPath(user_id);
846 auto profiles_de_path = ::BuildDataProfilesDePath(user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400847
848 // DE_n key
bigbiffa957f072021-03-07 18:20:29 -0500849 auto system_de_path = ::BuildDataSystemDePath(user_id);
850 auto misc_de_path = ::BuildDataMiscDePath(user_id);
851 auto vendor_de_path = ::BuildDataVendorDePath(user_id);
852 auto user_de_path = ::BuildDataUserDePath(volume_uuid, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400853
854 if (volume_uuid.empty()) {
855 if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
856#if MANAGE_MISC_DIRS
857 if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
858 multiuser_get_uid(user_id, AID_EVERYBODY)))
859 return false;
860#endif
861 if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
862
863 if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
864 if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
865 if (!prepare_dir(vendor_de_path, 0771, AID_ROOT, AID_ROOT)) return false;
866 }
867 if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400868 if (fscrypt_is_native()) {
bigbiffa957f072021-03-07 18:20:29 -0500869 EncryptionPolicy de_policy;
bigbiff7ba75002020-04-11 20:47:09 -0400870 if (volume_uuid.empty()) {
bigbiffa957f072021-03-07 18:20:29 -0500871 if (!lookup_policy(s_de_policies, user_id, &de_policy)) return false;
872 if (!EnsurePolicy(de_policy, system_de_path)) return false;
873 if (!EnsurePolicy(de_policy, misc_de_path)) return false;
874 if (!EnsurePolicy(de_policy, vendor_de_path)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400875 } else {
bigbiffa957f072021-03-07 18:20:29 -0500876 if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400877 }
bigbiffa957f072021-03-07 18:20:29 -0500878 if (!EnsurePolicy(de_policy, user_de_path)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400879 }
880 }
bigbiffa957f072021-03-07 18:20:29 -0500881
882 if (flags & android::os::IVold::STORAGE_FLAG_CE) {
bigbiff7ba75002020-04-11 20:47:09 -0400883 // CE_n key
bigbiffa957f072021-03-07 18:20:29 -0500884 auto system_ce_path = ::BuildDataSystemCePath(user_id);
885 auto misc_ce_path = ::BuildDataMiscCePath(user_id);
886 auto vendor_ce_path = ::BuildDataVendorCePath(user_id);
887 auto media_ce_path = ::BuildDataMediaCePath(volume_uuid, user_id);
888 auto user_ce_path = ::BuildDataUserCePath(volume_uuid, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400889
890 if (volume_uuid.empty()) {
891 if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
892 if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
893 if (!prepare_dir(vendor_ce_path, 0771, AID_ROOT, AID_ROOT)) return false;
894 }
895 if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
bigbiffa957f072021-03-07 18:20:29 -0500896
bigbiff7ba75002020-04-11 20:47:09 -0400897 if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
898
899 if (fscrypt_is_native()) {
bigbiffa957f072021-03-07 18:20:29 -0500900 EncryptionPolicy ce_policy;
bigbiff7ba75002020-04-11 20:47:09 -0400901 if (volume_uuid.empty()) {
bigbiffa957f072021-03-07 18:20:29 -0500902 if (!lookup_policy(s_ce_policies, user_id, &ce_policy)) return false;
903 if (!EnsurePolicy(ce_policy, system_ce_path)) return false;
904 if (!EnsurePolicy(ce_policy, misc_ce_path)) return false;
905 if (!EnsurePolicy(ce_policy, vendor_ce_path)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400906 } else {
bigbiffa957f072021-03-07 18:20:29 -0500907 if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_policy)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400908 }
bigbiffa957f072021-03-07 18:20:29 -0500909 if (!EnsurePolicy(ce_policy, media_ce_path)) return false;
910 if (!EnsurePolicy(ce_policy, user_ce_path)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400911 }
912
913 if (volume_uuid.empty()) {
914 // Now that credentials have been installed, we can run restorecon
915 // over these paths
916 // NOTE: these paths need to be kept in sync with libselinux
bigbiffa957f072021-03-07 18:20:29 -0500917 ::RestoreconRecursive(system_ce_path);
918 ::RestoreconRecursive(vendor_ce_path);
919 ::RestoreconRecursive(misc_ce_path);
bigbiff7ba75002020-04-11 20:47:09 -0400920 }
921 }
922 if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
923
924 return true;
925}
926
927bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
bigbiffa957f072021-03-07 18:20:29 -0500928 LOG(INFO) << "fscrypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
bigbiff7ba75002020-04-11 20:47:09 -0400929 << ", user " << user_id << ", flags " << flags;
930 bool res = true;
931
932 res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
933
bigbiffa957f072021-03-07 18:20:29 -0500934 if (flags & android::os::IVold::STORAGE_FLAG_CE) {
bigbiff7ba75002020-04-11 20:47:09 -0400935 // CE_n key
bigbiffa957f072021-03-07 18:20:29 -0500936 auto system_ce_path = ::BuildDataSystemCePath(user_id);
937 auto misc_ce_path = ::BuildDataMiscCePath(user_id);
938 auto vendor_ce_path = ::BuildDataVendorCePath(user_id);
939 auto media_ce_path = ::BuildDataMediaCePath(volume_uuid, user_id);
940 auto user_ce_path = ::BuildDataUserCePath(volume_uuid, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400941
942 res &= destroy_dir(media_ce_path);
943 res &= destroy_dir(user_ce_path);
944 if (volume_uuid.empty()) {
945 res &= destroy_dir(system_ce_path);
946 res &= destroy_dir(misc_ce_path);
947 res &= destroy_dir(vendor_ce_path);
948 } else {
949 if (fscrypt_is_native()) {
950 res &= destroy_volkey(misc_ce_path, volume_uuid);
951 }
952 }
953 }
954
bigbiffa957f072021-03-07 18:20:29 -0500955 if (flags & android::os::IVold::STORAGE_FLAG_DE) {
bigbiff7ba75002020-04-11 20:47:09 -0400956 // DE_sys key
bigbiffa957f072021-03-07 18:20:29 -0500957 auto system_legacy_path = ::BuildDataSystemLegacyPath(user_id);
958 auto misc_legacy_path = ::BuildDataMiscLegacyPath(user_id);
959 auto profiles_de_path = ::BuildDataProfilesDePath(user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400960
961 // DE_n key
bigbiffa957f072021-03-07 18:20:29 -0500962 auto system_de_path = ::BuildDataSystemDePath(user_id);
963 auto misc_de_path = ::BuildDataMiscDePath(user_id);
964 auto vendor_de_path = ::BuildDataVendorDePath(user_id);
965 auto user_de_path = ::BuildDataUserDePath(volume_uuid, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400966
967 res &= destroy_dir(user_de_path);
968 if (volume_uuid.empty()) {
969 res &= destroy_dir(system_legacy_path);
970#if MANAGE_MISC_DIRS
971 res &= destroy_dir(misc_legacy_path);
972#endif
973 res &= destroy_dir(profiles_de_path);
974 res &= destroy_dir(system_de_path);
975 res &= destroy_dir(misc_de_path);
976 res &= destroy_dir(vendor_de_path);
977 } else {
978 if (fscrypt_is_native()) {
979 res &= destroy_volkey(misc_de_path, volume_uuid);
980 }
981 }
982 }
983
984 return res;
985}
986
987static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
988 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
989 if (!dirp) {
990 PLOG(ERROR) << "Unable to open directory: " + directory_path;
991 return false;
992 }
993 bool res = true;
994 for (;;) {
995 errno = 0;
996 auto const entry = readdir(dirp.get());
997 if (!entry) {
998 if (errno) {
999 PLOG(ERROR) << "Unable to read directory: " + directory_path;
1000 return false;
1001 }
1002 break;
1003 }
1004 if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
bigbiffa957f072021-03-07 18:20:29 -05001005 LOG(INFO) << "Skipping non-user " << entry->d_name;
bigbiff7ba75002020-04-11 20:47:09 -04001006 continue;
1007 }
1008 res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
1009 }
1010 return res;
1011}
1012
1013bool fscrypt_destroy_volume_keys(const std::string& volume_uuid) {
1014 bool res = true;
bigbiffa957f072021-03-07 18:20:29 -05001015 LOG(INFO) << "fscrypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
bigbiff7ba75002020-04-11 20:47:09 -04001016 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
bigbiffa957f072021-03-07 18:20:29 -05001017 res &= ::runSecdiscardSingle(secdiscardable_path);
bigbiff7ba75002020-04-11 20:47:09 -04001018 res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
1019 res &= destroy_volume_keys("/data/misc_de", volume_uuid);
1020 return res;
1021}
bigbiffa957f072021-03-07 18:20:29 -05001022
1023bool lookup_key_ref(const std::map<userid_t, android::fscrypt::EncryptionPolicy>& key_map, userid_t user_id,
1024 std::string* raw_ref) {
1025 auto refi = key_map.find(user_id);
1026 if (refi == key_map.end()) {
1027 LOG(ERROR) << "Cannot find key for " << user_id;
1028 return false;
1029 }
1030 *raw_ref = refi->second.key_raw_ref;
1031 return true;
1032}