blob: 46df2b673aec96feebd709245f659aff9cd608a4 [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
mauronofrio matarrese79820322020-05-25 19:48:56 +020019#include "Keymaster.h"
bigbiff7ba75002020-04-11 20:47:09 -040020#include "KeyStorage.h"
21#include "KeyUtil.h"
22#include "Utils.h"
23// #include "VoldUtil.h"
24
25#include <algorithm>
26#include <map>
27#include <set>
28#include <sstream>
29#include <string>
30#include <vector>
31
32#include <dirent.h>
33#include <errno.h>
34#include <fcntl.h>
35#include <limits.h>
36#include <selinux/android.h>
37#include <sys/mount.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <unistd.h>
41
42#include <private/android_filesystem_config.h>
43
44// #include "android/os/IVold.h"
45
46#include "cryptfs.h"
47
48#define EMULATED_USES_SELINUX 0
49#define MANAGE_MISC_DIRS 0
50
51#include <cutils/fs.h>
52#include <cutils/properties.h>
53
54#include <fscrypt/fscrypt.h>
55#include <fs_mgr.h>
56#include <keyutils.h>
57
58#include <android-base/file.h>
59#include <android-base/logging.h>
60#include <android-base/properties.h>
61#include <android-base/stringprintf.h>
62#include <android-base/unique_fd.h>
63
64
65using android::base::StringPrintf;
66using android::fs_mgr::GetEntryForMountPoint;
67using android::vold::kEmptyAuthentication;
68using android::vold::KeyBuffer;
mauronofrio matarrese79820322020-05-25 19:48:56 +020069using android::vold::Keymaster;
70using android::hardware::keymaster::V4_0::KeyFormat;
bigbiff7ba75002020-04-11 20:47:09 -040071// using android::vold::writeStringToFile;
72
73// Store main DE raw ref / policy
74std::string de_raw_ref;
75std::map<userid_t, std::string> s_de_key_raw_refs;
76std::map<userid_t, std::string> s_ce_key_raw_refs;
77
78namespace {
79
80struct PolicyKeyRef {
81 std::string contents_mode;
82 std::string filenames_mode;
83 std::string key_raw_ref;
84};
85
86const std::string device_key_dir = std::string() + DATA_MNT_POINT + fscrypt_unencrypted_folder;
87const std::string device_key_path = device_key_dir + "/key";
88const std::string device_key_temp = device_key_dir + "/temp";
89
90const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
91const std::string user_key_temp = user_key_dir + "/temp";
92const std::string prepare_subdirs_path = "/sbin/vold_prepare_subdirs";
93
94const std::string systemwide_volume_key_dir =
95 std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
96const int STORAGE_FLAG_DE = 1;
97const int STORAGE_FLAG_CE = 2;
98
99bool s_systemwide_keys_initialized = false;
100
101android::fs_mgr::Fstab fstab_default;
102
103// Some users are ephemeral, don't try to wipe their keys from disk
104std::set<userid_t> s_ephemeral_users;
105
106// TODO abolish this map, per b/26948053
107std::map<userid_t, KeyBuffer> s_ce_keys;
108
109} // namespace
110
111static bool fscrypt_is_emulated() {
112 return property_get_bool("persist.sys.emulate_fbe", false);
113}
114
115static const char* escape_empty(const std::string& value) {
116 return value.empty() ? "null" : value.c_str();
117}
118
119static std::string get_de_key_path(userid_t user_id) {
120 return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
121}
122
123static std::string get_ce_key_directory_path(userid_t user_id) {
124 return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
125}
126
127// Returns the keys newest first
128static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
129 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
130 if (!dirp) {
131 PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
132 return std::vector<std::string>();
133 }
134 std::vector<std::string> result;
135 for (;;) {
136 errno = 0;
137 auto const entry = readdir(dirp.get());
138 if (!entry) {
139 if (errno) {
140 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
141 return std::vector<std::string>();
142 }
143 break;
144 }
145 if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
146 LOG(DEBUG) << "Skipping non-key " << entry->d_name;
147 continue;
148 }
149 result.emplace_back(directory_path + "/" + entry->d_name);
150 }
151 std::sort(result.begin(), result.end());
152 std::reverse(result.begin(), result.end());
153 return result;
154}
155
156static std::string get_ce_key_current_path(const std::string& directory_path) {
157 return directory_path + "/current";
158}
159
160static bool get_ce_key_new_path(const std::string& directory_path,
161 const std::vector<std::string>& paths, std::string* ce_key_path) {
162 if (paths.empty()) {
163 *ce_key_path = get_ce_key_current_path(directory_path);
164 return true;
165 }
166 for (unsigned int i = 0; i < UINT_MAX; i++) {
167 auto const candidate = StringPrintf("%s/cx%010u", directory_path.c_str(), i);
168 if (paths[0] < candidate) {
169 *ce_key_path = candidate;
170 return true;
171 }
172 }
173 return false;
174}
175
176// Discard all keys but the named one; rename it to canonical name.
177// No point in acting on errors in this; ignore them.
178static void fixate_user_ce_key(const std::string& directory_path, const std::string& to_fix,
179 const std::vector<std::string>& paths) {
180 for (auto const other_path : paths) {
181 if (other_path != to_fix) {
182 android::vold::destroyKey(other_path);
183 }
184 }
185 auto const current_path = get_ce_key_current_path(directory_path);
186 if (to_fix != current_path) {
187 LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
188 if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
189 PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
190 return;
191 }
192 }
193 android::vold::FsyncDirectory(directory_path);
194}
195
196static bool read_and_fixate_user_ce_key(userid_t user_id,
197 const android::vold::KeyAuthentication& auth,
198 KeyBuffer* ce_key) {
199 auto const directory_path = get_ce_key_directory_path(user_id);
200 auto const paths = get_ce_key_paths(directory_path);
201 for (auto const ce_key_path : paths) {
202 LOG(DEBUG) << "Trying user CE key " << ce_key_path;
203 if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
204 LOG(DEBUG) << "Successfully retrieved key";
205 fixate_user_ce_key(directory_path, ce_key_path, paths);
206 return true;
207 }
208 }
209 LOG(ERROR) << "Failed to find working ce key for user " << user_id;
210 return false;
211}
212
mauronofrio matarrese79820322020-05-25 19:48:56 +0200213static bool is_wrapped_key_supported_common(const std::string& mount_point) {
mauronofrio matarrese17fb1212020-05-25 19:59:17 +0200214 LOG(DEBUG) << "Determining wrapped-key support for " << mount_point;
215 std::string wrapped_key_supported = android::base::GetProperty("fbe.data.wrappedkey", "false");
216 LOG(DEBUG) << "fbe.data.wrappedkey = " << wrapped_key_supported;
217 if (mount_point == DATA_MNT_POINT && wrapped_key_supported == "true") {
218 LOG(DEBUG) << "Wrapped key supported on " << mount_point;
219 return true;
220 } else {
mauronofrio matarrese79820322020-05-25 19:48:56 +0200221 return false;
222 }
mauronofrio matarrese79820322020-05-25 19:48:56 +0200223}
224
225bool is_wrapped_key_supported() {
226 return is_wrapped_key_supported_common(DATA_MNT_POINT);
227}
228
229bool is_wrapped_key_supported_external() {
230 return false;
231}
232
bigbiff7ba75002020-04-11 20:47:09 -0400233static bool read_and_install_user_ce_key(userid_t user_id,
234 const android::vold::KeyAuthentication& auth) {
235 if (s_ce_key_raw_refs.count(user_id) != 0) return true;
236 KeyBuffer ce_key;
237 if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
238 std::string ce_raw_ref;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200239 if (is_wrapped_key_supported()) {
240 KeyBuffer ephemeral_wrapped_key;
241 if (!getEphemeralWrappedKey(KeyFormat::RAW, ce_key, &ephemeral_wrapped_key)) {
242 LOG(ERROR) << "Failed to export ce key";
243 return false;
244 }
245 ce_key = std::move(ephemeral_wrapped_key);
246 }
bigbiff7ba75002020-04-11 20:47:09 -0400247 if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
248 s_ce_keys[user_id] = std::move(ce_key);
249 s_ce_key_raw_refs[user_id] = ce_raw_ref;
250 LOG(DEBUG) << "Installed ce key for user " << user_id;
251 return true;
252}
253
254static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
255 LOG(DEBUG) << "Preparing: " << dir;
256 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
257 PLOG(ERROR) << "Failed to prepare " << dir;
258 return false;
259 }
260 return true;
261}
262
263static bool destroy_dir(const std::string& dir) {
264 LOG(DEBUG) << "Destroying: " << dir;
265 if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
266 PLOG(ERROR) << "Failed to destroy " << dir;
267 return false;
268 }
269 return true;
270}
271
272// NB this assumes that there is only one thread listening for crypt commands, because
273// it creates keys in a fixed location.
274static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
275 KeyBuffer de_key, ce_key;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200276
277 if(is_wrapped_key_supported()) {
278 if (!generateWrappedKey(user_id, android::vold::KeyType::DE_USER, &de_key)) return false;
279 if (!generateWrappedKey(user_id, android::vold::KeyType::CE_USER, &ce_key)) return false;
280 } else {
281 if (!android::vold::randomKey(&de_key)) return false;
282 if (!android::vold::randomKey(&ce_key)) return false;
283 }
284
bigbiff7ba75002020-04-11 20:47:09 -0400285 if (create_ephemeral) {
286 // If the key should be created as ephemeral, don't store it.
287 s_ephemeral_users.insert(user_id);
288 } else {
289 auto const directory_path = get_ce_key_directory_path(user_id);
290 if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
291 auto const paths = get_ce_key_paths(directory_path);
292 std::string ce_key_path;
293 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
294 if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication,
295 ce_key))
296 return false;
297 fixate_user_ce_key(directory_path, ce_key_path, paths);
298 // Write DE key second; once this is written, all is good.
299 if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
300 kEmptyAuthentication, de_key))
301 return false;
302 }
mauronofrio matarrese79820322020-05-25 19:48:56 +0200303
bigbiff7ba75002020-04-11 20:47:09 -0400304 std::string ce_raw_ref;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200305 if (is_wrapped_key_supported()) {
306 KeyBuffer ephemeral_wrapped_de_key;
307 KeyBuffer ephemeral_wrapped_ce_key;
308
309 /* Export and install the DE keys */
310 if (!getEphemeralWrappedKey(KeyFormat::RAW, de_key, &ephemeral_wrapped_de_key)) {
311 LOG(ERROR) << "Failed to export de_key";
312 return false;
313 }
314 /* Export and install the CE keys */
315 if (!getEphemeralWrappedKey(KeyFormat::RAW, ce_key, &ephemeral_wrapped_ce_key)) {
316 LOG(ERROR) << "Failed to export de_key";
317 return false;
318 }
319
320 de_key = std::move(ephemeral_wrapped_de_key);
321 ce_key = std::move(ephemeral_wrapped_ce_key);
322 }
323 if (!android::vold::installKey(de_key, &de_raw_ref)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400324 if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200325 s_ce_keys[user_id] = std::move(ce_key);
326
327 s_de_key_raw_refs[user_id] = de_raw_ref;
bigbiff7ba75002020-04-11 20:47:09 -0400328 s_ce_key_raw_refs[user_id] = ce_raw_ref;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200329
bigbiff7ba75002020-04-11 20:47:09 -0400330 LOG(DEBUG) << "Created keys for user " << user_id;
331 return true;
332}
333
334bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
335 std::string* raw_ref) {
336 auto refi = key_map.find(user_id);
337 if (refi == key_map.end()) {
338 LOG(DEBUG) << "Cannot find key for " << user_id;
339 return false;
340 }
341 *raw_ref = refi->second;
342 return true;
343}
344
345static void get_data_file_encryption_modes(PolicyKeyRef* key_ref) {
346 if (!ReadDefaultFstab(&fstab_default)) {
347 PLOG(ERROR) << "Failed to open default fstab";
348 return;
349 }
350 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
351 if (entry == nullptr) {
352 LOG(ERROR) << "get_data_file_encryption_modes::failed\n";
353 return;
354 }
355 key_ref->contents_mode = entry->file_contents_mode;
356 key_ref->filenames_mode = entry->file_names_mode;
357}
358
359static bool ensure_policy(const PolicyKeyRef& key_ref, const std::string& path) {
360 return fscrypt_policy_ensure(path.c_str(), key_ref.key_raw_ref.data(),
361 key_ref.key_raw_ref.size(), key_ref.contents_mode.c_str(),
362 key_ref.filenames_mode.c_str()) == 0;
363}
364
365static bool is_numeric(const char* name) {
366 for (const char* p = name; *p != '\0'; p++) {
367 if (!isdigit(*p)) return false;
368 }
369 return true;
370}
371
372static bool load_all_de_keys() {
373 auto de_dir = user_key_dir + "/de";
374 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
375 if (!dirp) {
376 PLOG(ERROR) << "Unable to read de key directory";
377 return false;
378 }
379 for (;;) {
380 errno = 0;
381 auto entry = readdir(dirp.get());
382 if (!entry) {
383 if (errno) {
384 PLOG(ERROR) << "Unable to read de key directory";
385 return false;
386 }
387 break;
388 }
389 if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
390 LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
391 continue;
392 }
393 userid_t user_id = std::stoi(entry->d_name);
394 if (s_de_key_raw_refs.count(user_id) == 0) {
395 auto key_path = de_dir + "/" + entry->d_name;
396 KeyBuffer key;
397 if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
398 std::string raw_ref;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200399 if (is_wrapped_key_supported()) {
400 KeyBuffer ephemeral_wrapped_key;
401 if (!getEphemeralWrappedKey(KeyFormat::RAW, key, &ephemeral_wrapped_key)) {
402 LOG(ERROR) << "Failed to export de_key in create_and_install_user_keys";
403 return false;
404 }
405 key = std::move(ephemeral_wrapped_key);
406 }
bigbiff7ba75002020-04-11 20:47:09 -0400407 if (!android::vold::installKey(key, &raw_ref)) return false;
408 s_de_key_raw_refs[user_id] = raw_ref;
409 LOG(DEBUG) << "Installed de key for user " << user_id;
410 }
411 }
412 // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
413 // correct policy set on them, and that no rogue ones exist.
414 return true;
415}
416
417bool fscrypt_initialize_systemwide_keys() {
418 LOG(INFO) << "fscrypt_initialize_systemwide_keys";
mauronofrio matarrese79820322020-05-25 19:48:56 +0200419 bool wrapped_key_supported = false;
bigbiff7ba75002020-04-11 20:47:09 -0400420
421 if (s_systemwide_keys_initialized) {
422 LOG(INFO) << "Already initialized";
423 return true;
424 }
425
426 PolicyKeyRef device_ref;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200427 wrapped_key_supported = is_wrapped_key_supported();
428
429 if (!android::vold::retrieveAndInstallKey(true, kEmptyAuthentication,
430 device_key_path, device_key_temp,
431 &device_ref.key_raw_ref, wrapped_key_supported))
bigbiff7ba75002020-04-11 20:47:09 -0400432 return false;
433 get_data_file_encryption_modes(&device_ref);
434
435 std::string modestring = device_ref.contents_mode + ":" + device_ref.filenames_mode;
436 std::string mode_filename = std::string("/data") + fscrypt_key_mode;
437 if (!android::vold::writeStringToFile(modestring, mode_filename)) return false;
438
439 std::string ref_filename = std::string("/data") + fscrypt_key_ref;
440 if (!android::vold::writeStringToFile(device_ref.key_raw_ref, ref_filename)) return false;
441 LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
442
443 KeyBuffer per_boot_key;
444 if (!android::vold::randomKey(&per_boot_key)) return false;
445 std::string per_boot_raw_ref;
446 if (!android::vold::installKey(per_boot_key, &per_boot_raw_ref)) return false;
447 std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
448 if (!android::vold::writeStringToFile(per_boot_raw_ref, per_boot_ref_filename)) return false;
449 LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
450
451 if (!android::vold::FsyncDirectory(device_key_dir)) return false;
452 s_systemwide_keys_initialized = true;
453 de_raw_ref = device_ref.key_raw_ref;
454 return true;
455}
456
457bool fscrypt_init_user0() {
458 if (!ReadDefaultFstab(&fstab_default)) {
459 PLOG(ERROR) << "Failed to open default fstab";
460 return -1;
461 }
462 if (fscrypt_is_native()) {
463 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
464 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
465 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
466 if (!android::vold::pathExists(get_de_key_path(0))) {
467 if (!create_and_install_user_keys(0, false)) return false;
468 }
469 // TODO: switch to loading only DE_0 here once framework makes
470 // explicit calls to install DE keys for secondary users
471 if (!load_all_de_keys()) return false;
472 }
473 // We can only safely prepare DE storage here, since CE keys are probably
474 // entangled with user credentials. The framework will always prepare CE
475 // storage once CE keys are installed.
476 if (!fscrypt_prepare_user_storage("", 0, 0, STORAGE_FLAG_DE)) {
477 LOG(ERROR) << "Failed to prepare user 0 storage";
478 return false;
479 }
480 // If this is a non-FBE device that recently left an emulated mode,
481 // restore user data directories to known-good state.
482 if (!fscrypt_is_native() && !fscrypt_is_emulated()) {
483 fscrypt_unlock_user_key(0, 0, "!", "!");
484 }
485
486 return true;
487}
488
489bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
490 LOG(DEBUG) << "fscrypt_vold_create_user_key for " << user_id << " serial " << serial;
491 if (!fscrypt_is_native()) {
492 return true;
493 }
494 // FIXME test for existence of key that is not loaded yet
495 if (s_ce_key_raw_refs.count(user_id) != 0) {
496 LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
497 << " serial " << serial;
498 // FIXME should we fail the command?
499 return true;
500 }
501 if (!create_and_install_user_keys(user_id, ephemeral)) {
502 return false;
503 }
504 return true;
505}
506
507static void drop_caches() {
508 // Clean any dirty pages (otherwise they won't be dropped).
509 sync();
510 // Drop inode and page caches.
511 if (!android::vold::writeStringToFile("3", "/proc/sys/vm/drop_caches")) {
512 PLOG(ERROR) << "Failed to drop caches during key eviction";
513 }
514}
515
516static bool evict_ce_key(userid_t user_id) {
517 s_ce_keys.erase(user_id);
518 bool success = true;
519 std::string raw_ref;
520 // If we haven't loaded the CE key, no need to evict it.
521 if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
522 success &= android::vold::evictKey(raw_ref);
523 drop_caches();
524 }
525 s_ce_key_raw_refs.erase(user_id);
526 return success;
527}
528
529bool fscrypt_destroy_user_key(userid_t user_id) {
530 LOG(DEBUG) << "fscrypt_destroy_user_key(" << user_id << ")";
531 if (!fscrypt_is_native()) {
532 return true;
533 }
534 bool success = true;
535 std::string raw_ref;
536 success &= evict_ce_key(user_id);
537 success &=
538 lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && android::vold::evictKey(raw_ref);
539 s_de_key_raw_refs.erase(user_id);
540 auto it = s_ephemeral_users.find(user_id);
541 if (it != s_ephemeral_users.end()) {
542 s_ephemeral_users.erase(it);
543 } else {
544 for (auto const path : get_ce_key_paths(get_ce_key_directory_path(user_id))) {
545 success &= android::vold::destroyKey(path);
546 }
547 auto de_key_path = get_de_key_path(user_id);
548 if (android::vold::pathExists(de_key_path)) {
549 success &= android::vold::destroyKey(de_key_path);
550 } else {
551 LOG(INFO) << "Not present so not erasing: " << de_key_path;
552 }
553 }
554 return success;
555}
556
557static bool emulated_lock(const std::string& path) {
558 if (chmod(path.c_str(), 0000) != 0) {
559 PLOG(ERROR) << "Failed to chmod " << path;
560 return false;
561 }
562#if EMULATED_USES_SELINUX
563 if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
564 PLOG(WARNING) << "Failed to setfilecon " << path;
565 return false;
566 }
567#endif
568 return true;
569}
570
571static bool emulated_unlock(const std::string& path, mode_t mode) {
572 if (chmod(path.c_str(), mode) != 0) {
573 PLOG(ERROR) << "Failed to chmod " << path;
574 // FIXME temporary workaround for b/26713622
575 if (fscrypt_is_emulated()) return false;
576 }
577#if EMULATED_USES_SELINUX
578 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
579 PLOG(WARNING) << "Failed to restorecon " << path;
580 // FIXME temporary workaround for b/26713622
581 if (fscrypt_is_emulated()) return false;
582 }
583#endif
584 return true;
585}
586
587static bool parse_hex(const std::string& hex, std::string* result) {
588 if (hex == "!") {
589 *result = "";
590 return true;
591 }
592 if (android::vold::HexToStr(hex, *result) != 0) {
593 LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
594 return false;
595 }
596 return true;
597}
598
599static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
600 return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
601}
602
603static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
604 return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
605}
606
607static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
608 PolicyKeyRef* key_ref) {
609 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
610 std::string secdiscardable_hash;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200611 bool wrapped_key_supported = false;
bigbiff7ba75002020-04-11 20:47:09 -0400612 if (android::vold::pathExists(secdiscardable_path)) {
613 if (!android::vold::readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
614 return false;
615 } else {
616 if (fs_mkdirs(secdiscardable_path.c_str(), 0700) != 0) {
617 PLOG(ERROR) << "Creating directories for: " << secdiscardable_path;
618 return false;
619 }
620 if (!android::vold::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
621 return false;
622 }
623 auto key_path = volkey_path(misc_path, volume_uuid);
624 if (fs_mkdirs(key_path.c_str(), 0700) != 0) {
625 PLOG(ERROR) << "Creating directories for: " << key_path;
626 return false;
627 }
628 android::vold::KeyAuthentication auth("", secdiscardable_hash);
mauronofrio matarrese79820322020-05-25 19:48:56 +0200629 wrapped_key_supported = is_wrapped_key_supported_external();
630
bigbiff7ba75002020-04-11 20:47:09 -0400631 if (!android::vold::retrieveAndInstallKey(true, auth, key_path, key_path + "_tmp",
mauronofrio matarrese79820322020-05-25 19:48:56 +0200632 &key_ref->key_raw_ref, wrapped_key_supported))
bigbiff7ba75002020-04-11 20:47:09 -0400633 return false;
634 key_ref->contents_mode =
635 android::base::GetProperty("ro.crypto.volume.contents_mode", "aes-256-xts");
636 key_ref->filenames_mode =
637 android::base::GetProperty("ro.crypto.volume.filenames_mode", "aes-256-heh");
638 return true;
639}
640
641static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
642 auto path = volkey_path(misc_path, volume_uuid);
643 if (!android::vold::pathExists(path)) return true;
644 return android::vold::destroyKey(path);
645}
646
647bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
648 const std::string& secret_hex) {
649 LOG(DEBUG) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial
650 << " token_present=" << (token_hex != "!");
651 if (!fscrypt_is_native()) return true;
652 if (s_ephemeral_users.count(user_id) != 0) return true;
653 std::string token, secret;
654 if (!parse_hex(token_hex, &token)) return false;
655 if (!parse_hex(secret_hex, &secret)) return false;
656 auto auth =
657 secret.empty() ? kEmptyAuthentication : android::vold::KeyAuthentication(token, secret);
bigbiff7ba75002020-04-11 20:47:09 -0400658 auto const directory_path = get_ce_key_directory_path(user_id);
659 auto const paths = get_ce_key_paths(directory_path);
mauronofrio matarrese79820322020-05-25 19:48:56 +0200660
661 KeyBuffer ce_key;
662 if(is_wrapped_key_supported()) {
663 std::string ce_key_current_path = get_ce_key_current_path(directory_path);
664 if (android::vold::retrieveKey(ce_key_current_path, kEmptyAuthentication, &ce_key)) {
665 LOG(DEBUG) << "Successfully retrieved key";
666 } else {
667 if (android::vold::retrieveKey(ce_key_current_path, auth, &ce_key)) {
668 LOG(DEBUG) << "Successfully retrieved key";
669 }
670 }
671 } else {
672 auto it = s_ce_keys.find(user_id);
673 if (it == s_ce_keys.end()) {
674 LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
675 return false;
676 }
677 ce_key = it->second;
678 }
679
bigbiff7ba75002020-04-11 20:47:09 -0400680 std::string ce_key_path;
681 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
682 if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
683 if (!android::vold::FsyncDirectory(directory_path)) return false;
684 return true;
685}
686
mauronofrio matarrese79820322020-05-25 19:48:56 +0200687bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
688 const std::string& secret_hex) {
689 LOG(DEBUG) << "fscrypt_clear_user_key_auth " << user_id << " serial=" << serial
690 << " token_present=" << (token_hex != "!");
691 if (!fscrypt_is_native()) return true;
692 if (s_ephemeral_users.count(user_id) != 0) return true;
693 std::string token, secret;
694
695 if (!parse_hex(token_hex, &token)) return false;
696 if (!parse_hex(secret_hex, &secret)) return false;
697
698 if (is_wrapped_key_supported()) {
699 auto const directory_path = get_ce_key_directory_path(user_id);
700 auto const paths = get_ce_key_paths(directory_path);
701
702 KeyBuffer ce_key;
703 std::string ce_key_current_path = get_ce_key_current_path(directory_path);
704
705 auto auth = android::vold::KeyAuthentication(token, secret);
706 /* Retrieve key while removing a pin. A secret is needed */
707 if (android::vold::retrieveKey(ce_key_current_path, auth, &ce_key)) {
708 LOG(DEBUG) << "Successfully retrieved key";
709 } else {
710 /* Retrieve key when going None to swipe and vice versa when a
711 synthetic password is present */
712 if (android::vold::retrieveKey(ce_key_current_path, kEmptyAuthentication, &ce_key)) {
713 LOG(DEBUG) << "Successfully retrieved key";
714 }
715 }
716
717 std::string ce_key_path;
718 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
719 if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication, ce_key))
720 return false;
721 } else {
722 if(!fscrypt_add_user_key_auth(user_id, serial, "!", "!")) return false;
723 }
724 return true;
725}
726
bigbiff7ba75002020-04-11 20:47:09 -0400727bool fscrypt_fixate_newest_user_key_auth(userid_t user_id) {
728 LOG(DEBUG) << "fscrypt_fixate_newest_user_key_auth " << user_id;
729 if (!fscrypt_is_native()) return true;
730 if (s_ephemeral_users.count(user_id) != 0) return true;
731 auto const directory_path = get_ce_key_directory_path(user_id);
732 auto const paths = get_ce_key_paths(directory_path);
733 if (paths.empty()) {
734 LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
735 return false;
736 }
737 fixate_user_ce_key(directory_path, paths[0], paths);
738 return true;
739}
740
741// TODO: rename to 'install' for consistency, and take flags to know which keys to install
742bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
743 const std::string& secret_hex) {
744 LOG(DEBUG) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial
745 << " token_present=" << (token_hex != "!");
746 if (fscrypt_is_native()) {
747 if (s_ce_key_raw_refs.count(user_id) != 0) {
748 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
749 return true;
750 }
751 std::string token, secret;
752 if (!parse_hex(token_hex, &token)) return false;
753 if (!parse_hex(secret_hex, &secret)) return false;
754 android::vold::KeyAuthentication auth(token, secret);
755 if (!read_and_install_user_ce_key(user_id, auth)) {
756 LOG(ERROR) << "Couldn't read key for " << user_id;
757 return false;
758 }
759 } else {
760 // When in emulation mode, we just use chmod. However, we also
761 // unlock directories when not in emulation mode, to bring devices
762 // back into a known-good state.
763 if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
764 !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
765 !emulated_unlock(android::vold::BuildDataMediaCePath("", user_id), 0770) ||
766 !emulated_unlock(android::vold::BuildDataUserCePath("", user_id), 0771)) {
767 LOG(ERROR) << "Failed to unlock user " << user_id;
768 return false;
769 }
770 }
771 return true;
772}
773
774// TODO: rename to 'evict' for consistency
775bool fscrypt_lock_user_key(userid_t user_id) {
776 LOG(DEBUG) << "fscrypt_lock_user_key " << user_id;
777 if (fscrypt_is_native()) {
778 return evict_ce_key(user_id);
779 } else if (fscrypt_is_emulated()) {
780 // When in emulation mode, we just use chmod
781 if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
782 !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
783 !emulated_lock(android::vold::BuildDataMediaCePath("", user_id)) ||
784 !emulated_lock(android::vold::BuildDataUserCePath("", user_id))) {
785 LOG(ERROR) << "Failed to lock user " << user_id;
786 return false;
787 }
788 }
789
790 return true;
791}
792
793static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
794 userid_t user_id, int flags) {
795 if (0 != android::vold::ForkExecvp(
796 std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
797 std::to_string(user_id), std::to_string(flags)})) {
798 LOG(ERROR) << "vold_prepare_subdirs failed";
799 return false;
800 }
801 return true;
802}
803
804bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
805 int flags) {
806 LOG(DEBUG) << "fscrypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
807 << ", user " << user_id << ", serial " << serial << ", flags " << flags;
808
809 if (flags & STORAGE_FLAG_DE) {
810 // DE_sys key
811 auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
812 auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
813 auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
814
815 // DE_n key
816 auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
817 auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
818 auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
819 auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
820
821 if (volume_uuid.empty()) {
822 if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
823#if MANAGE_MISC_DIRS
824 if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
825 multiuser_get_uid(user_id, AID_EVERYBODY)))
826 return false;
827#endif
828 if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
829
830 if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
831 if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
832 if (!prepare_dir(vendor_de_path, 0771, AID_ROOT, AID_ROOT)) return false;
833 }
834 if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
835
836 if (fscrypt_is_native()) {
837 PolicyKeyRef de_ref;
838 if (volume_uuid.empty()) {
839 if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_ref.key_raw_ref)) return false;
840 get_data_file_encryption_modes(&de_ref);
841 if (!ensure_policy(de_ref, system_de_path)) return false;
842 if (!ensure_policy(de_ref, misc_de_path)) return false;
843 if (!ensure_policy(de_ref, vendor_de_path)) return false;
844 } else {
845 if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_ref)) return false;
846 }
847 if (!ensure_policy(de_ref, user_de_path)) return false;
848 }
849 }
850 if (flags & STORAGE_FLAG_CE) {
851 // CE_n key
852 auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
853 auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
854 auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
855 auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
856 auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
857
858 if (volume_uuid.empty()) {
859 if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
860 if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
861 if (!prepare_dir(vendor_ce_path, 0771, AID_ROOT, AID_ROOT)) return false;
862 }
863 if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
864 if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
865
866 if (fscrypt_is_native()) {
867 PolicyKeyRef ce_ref;
868 if (volume_uuid.empty()) {
869 if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_ref.key_raw_ref)) return false;
870 get_data_file_encryption_modes(&ce_ref);
871 if (!ensure_policy(ce_ref, system_ce_path)) return false;
872 if (!ensure_policy(ce_ref, misc_ce_path)) return false;
873 if (!ensure_policy(ce_ref, vendor_ce_path)) return false;
874
875 } else {
876 if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_ref)) return false;
877 }
878 if (!ensure_policy(ce_ref, media_ce_path)) return false;
879 if (!ensure_policy(ce_ref, user_ce_path)) return false;
880 }
881
882 if (volume_uuid.empty()) {
883 // Now that credentials have been installed, we can run restorecon
884 // over these paths
885 // NOTE: these paths need to be kept in sync with libselinux
886 android::vold::RestoreconRecursive(system_ce_path);
887 android::vold::RestoreconRecursive(vendor_ce_path);
888 android::vold::RestoreconRecursive(misc_ce_path);
889 }
890 }
891 if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
892
893 return true;
894}
895
896bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
897 LOG(DEBUG) << "fscrypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
898 << ", user " << user_id << ", flags " << flags;
899 bool res = true;
900
901 res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
902
903 if (flags & STORAGE_FLAG_CE) {
904 // CE_n key
905 auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
906 auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
907 auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
908 auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
909 auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
910
911 res &= destroy_dir(media_ce_path);
912 res &= destroy_dir(user_ce_path);
913 if (volume_uuid.empty()) {
914 res &= destroy_dir(system_ce_path);
915 res &= destroy_dir(misc_ce_path);
916 res &= destroy_dir(vendor_ce_path);
917 } else {
918 if (fscrypt_is_native()) {
919 res &= destroy_volkey(misc_ce_path, volume_uuid);
920 }
921 }
922 }
923
924 if (flags & STORAGE_FLAG_DE) {
925 // DE_sys key
926 auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
927 auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
928 auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
929
930 // DE_n key
931 auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
932 auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
933 auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
934 auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
935
936 res &= destroy_dir(user_de_path);
937 if (volume_uuid.empty()) {
938 res &= destroy_dir(system_legacy_path);
939#if MANAGE_MISC_DIRS
940 res &= destroy_dir(misc_legacy_path);
941#endif
942 res &= destroy_dir(profiles_de_path);
943 res &= destroy_dir(system_de_path);
944 res &= destroy_dir(misc_de_path);
945 res &= destroy_dir(vendor_de_path);
946 } else {
947 if (fscrypt_is_native()) {
948 res &= destroy_volkey(misc_de_path, volume_uuid);
949 }
950 }
951 }
952
953 return res;
954}
955
956static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
957 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
958 if (!dirp) {
959 PLOG(ERROR) << "Unable to open directory: " + directory_path;
960 return false;
961 }
962 bool res = true;
963 for (;;) {
964 errno = 0;
965 auto const entry = readdir(dirp.get());
966 if (!entry) {
967 if (errno) {
968 PLOG(ERROR) << "Unable to read directory: " + directory_path;
969 return false;
970 }
971 break;
972 }
973 if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
974 LOG(DEBUG) << "Skipping non-user " << entry->d_name;
975 continue;
976 }
977 res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
978 }
979 return res;
980}
981
982bool fscrypt_destroy_volume_keys(const std::string& volume_uuid) {
983 bool res = true;
984 LOG(DEBUG) << "fscrypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
985 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
986 res &= android::vold::runSecdiscardSingle(secdiscardable_path);
987 res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
988 res &= destroy_volume_keys("/data/misc_de", volume_uuid);
989 return res;
990}