blob: d6ea53156ba720b024dba822f4d952d3e5614a7d [file] [log] [blame]
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001/*
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 "Ext4CryptPie.h"
18
19#include "KeyStorage4.h"
20#include "KeyUtil.h"
21#include "Utils.h"
22#include "Decrypt.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 <unistd.h>
36#include <limits.h>
37#include <selinux/android.h>
38#include <sys/mount.h>
39#include <sys/stat.h>
40#include <sys/types.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 <ext4_utils/ext4_crypt.h>
55#include <keyutils.h>
56
57#include <android-base/file.h>
58//#include <android-base/logging.h>
59#include <android-base/properties.h>
60#include <android-base/stringprintf.h>
61
62#include <iostream>
63#define LOG(x) std::cout
64#define PLOG(x) std::cout
65#define DATA_MNT_POINT "/data"
66
67using android::base::StringPrintf;
68using android::base::WriteStringToFile;
69using android::vold::kEmptyAuthentication;
70using android::vold::KeyBuffer;
71
72// Store main DE raw ref / policy
73std::string de_raw_ref;
74// Map user ids to key references
75std::map<userid_t, std::string> s_de_key_raw_refs;
76std::map<userid_t, std::string> s_ce_key_raw_refs;
77// TODO abolish this map, per b/26948053
78std::map<userid_t, KeyBuffer> s_ce_keys;
79
80namespace {
81
82struct PolicyKeyRef {
83 std::string contents_mode;
84 std::string filenames_mode;
85 std::string key_raw_ref;
86};
87
88const std::string device_key_dir = std::string() + DATA_MNT_POINT + e4crypt_unencrypted_folder;
89const std::string device_key_path = device_key_dir + "/key";
90const std::string device_key_temp = device_key_dir + "/temp";
91
92const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
93const std::string user_key_temp = user_key_dir + "/temp";
94const std::string prepare_subdirs_path = "/system/bin/vold_prepare_subdirs";
95
96const std::string systemwide_volume_key_dir =
97 std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
98
99bool s_global_de_initialized = false;
100
101// Some users are ephemeral, don't try to wipe their keys from disk
102std::set<userid_t> s_ephemeral_users;
103
104}
105
106static bool e4crypt_is_emulated() {
107 return property_get_bool("persist.sys.emulate_fbe", false);
108}
109
110static const char* escape_empty(const std::string& value) {
111 return value.empty() ? "null" : value.c_str();
112}
113
114static std::string get_de_key_path(userid_t user_id) {
115 return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
116}
117
118static std::string get_ce_key_directory_path(userid_t user_id) {
119 return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
120}
121
122// Returns the keys newest first
123static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
124 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
125 if (!dirp) {
126 PLOG(ERROR) << "Unable to open ce key directory: " + directory_path << std::endl;
127 return std::vector<std::string>();
128 }
129 std::vector<std::string> result;
130 for (;;) {
131 errno = 0;
132 auto const entry = readdir(dirp.get());
133 if (!entry) {
134 if (errno) {
135 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path << std::endl;
136 return std::vector<std::string>();
137 }
138 break;
139 }
140 if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
141 LOG(DEBUG) << "Skipping non-key " << entry->d_name << std::endl;
142 continue;
143 }
144 result.emplace_back(directory_path + "/" + entry->d_name);
145 }
146 std::sort(result.begin(), result.end());
147 std::reverse(result.begin(), result.end());
148 return result;
149}
150
151static std::string get_ce_key_current_path(const std::string& directory_path) {
152 return directory_path + "/current";
153}
154
155/*static bool get_ce_key_new_path(const std::string& directory_path,
156 const std::vector<std::string>& paths,
157 std::string *ce_key_path) {
158 if (paths.empty()) {
159 *ce_key_path = get_ce_key_current_path(directory_path);
160 return true;
161 }
162 for (unsigned int i = 0; i < UINT_MAX; i++) {
163 auto const candidate = StringPrintf("%s/cx%010u", directory_path.c_str(), i);
164 if (paths[0] < candidate) {
165 *ce_key_path = candidate;
166 return true;
167 }
168 }
169 return false;
170}*/
171
172// Discard all keys but the named one; rename it to canonical name.
173// No point in acting on errors in this; ignore them.
174static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix,
175 const std::vector<std::string>& paths) {
176 for (auto const other_path: paths) {
177 if (other_path != to_fix) {
178 android::vold::destroyKey(other_path);
179 }
180 }
181 auto const current_path = get_ce_key_current_path(directory_path);
182 if (to_fix != current_path) {
183 LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path << std::endl;
184 if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
185 PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path << std::endl;
186 }
187 }
188}
189
190static bool read_and_fixate_user_ce_key(userid_t user_id,
191 const android::vold::KeyAuthentication& auth,
192 KeyBuffer *ce_key) {
193 auto const directory_path = get_ce_key_directory_path(user_id);
194 auto const paths = get_ce_key_paths(directory_path);
195 for (auto const ce_key_path: paths) {
196 LOG(DEBUG) << "Trying user CE key " << ce_key_path << std::endl;
197 if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
198 LOG(DEBUG) << "Successfully retrieved key" << std::endl;
199 fixate_user_ce_key(directory_path, ce_key_path, paths);
200 return true;
201 }
202 }
203 LOG(ERROR) << "Failed to find working ce key for user " << user_id << std::endl;
204 return false;
205}
206
207static bool read_and_install_user_ce_key(userid_t user_id,
208 const android::vold::KeyAuthentication& auth) {
209 if (s_ce_key_raw_refs.count(user_id) != 0) return true;
210 KeyBuffer ce_key;
211 if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
212 std::string ce_raw_ref;
213 if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
214 s_ce_keys[user_id] = std::move(ce_key);
215 s_ce_key_raw_refs[user_id] = ce_raw_ref;
216 LOG(DEBUG) << "Installed ce key for user " << user_id << std::endl;
217 return true;
218}
219
220static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
221 LOG(DEBUG) << "Preparing: " << dir << std::endl;
222 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
223 PLOG(ERROR) << "Failed to prepare " << dir << std::endl;
224 return false;
225 }
226 return true;
227}
228
229/*static bool destroy_dir(const std::string& dir) {
230 LOG(DEBUG) << "Destroying: " << dir;
231 if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
232 PLOG(ERROR) << "Failed to destroy " << dir;
233 return false;
234 }
235 return true;
236}*/
237
238// NB this assumes that there is only one thread listening for crypt commands, because
239// it creates keys in a fixed location.
240static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
241 /*KeyBuffer de_key, ce_key;
242 if (!android::vold::randomKey(&de_key)) return false;
243 if (!android::vold::randomKey(&ce_key)) return false;
244 if (create_ephemeral) {
245 // If the key should be created as ephemeral, don't store it.
246 s_ephemeral_users.insert(user_id);
247 } else {
248 auto const directory_path = get_ce_key_directory_path(user_id);
249 if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
250 auto const paths = get_ce_key_paths(directory_path);
251 std::string ce_key_path;
252 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
253 if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp,
254 kEmptyAuthentication, ce_key)) return false;
255 fixate_user_ce_key(directory_path, ce_key_path, paths);
256 // Write DE key second; once this is written, all is good.
257 if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
258 kEmptyAuthentication, de_key)) return false;
259 }
260 std::string de_raw_ref;
261 if (!android::vold::installKey(de_key, &de_raw_ref)) return false;
262 s_de_key_raw_refs[user_id] = de_raw_ref;
263 std::string ce_raw_ref;
264 if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
265 s_ce_keys[user_id] = ce_key;
266 s_ce_key_raw_refs[user_id] = ce_raw_ref;
267 LOG(DEBUG) << "Created keys for user " << user_id;*/
268 LOG(DEBUG) << "TWRP not doing create_and_install_user_keys\n";
269 return true;
270}
271
272bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
273 std::string* raw_ref) {
274 auto refi = key_map.find(user_id);
275 if (refi == key_map.end()) {
276 LOG(ERROR) << "Cannot find key for " << user_id << std::endl;
277 return false;
278 }
279 *raw_ref = refi->second;
280 return true;
281}
282
283static void get_data_file_encryption_modes(PolicyKeyRef* key_ref) {
284 /*struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
285 char const* contents_mode = strdup("ice");
286 char const* filenames_mode = strdup("aes-256-heh");
287 fs_mgr_get_file_encryption_modes(rec, &contents_mode, &filenames_mode);
288 key_ref->contents_mode = contents_mode;
289 key_ref->filenames_mode = filenames_mode;*/
290 LOG(INFO) << "contents mode '" << android::base::GetProperty("fbe.contents", "aes-256-xts") << "' filenames '" << android::base::GetProperty("fbe.filenames", "aes-256-heh") << "'\n";
291 key_ref->contents_mode =
292 android::base::GetProperty("fbe.contents", "aes-256-xts");
293 key_ref->filenames_mode =
294 android::base::GetProperty("fbe.filenames", "aes-256-heh");
295}
296
297static bool ensure_policy(const PolicyKeyRef& key_ref, const std::string& path) {
Ethan Yonker93382822018-11-01 15:25:31 -0500298 return true;
299 /*return e4crypt_policy_ensure(path.c_str(), key_ref.key_raw_ref.data(),
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500300 key_ref.key_raw_ref.size(), key_ref.contents_mode.c_str(),
Ethan Yonker93382822018-11-01 15:25:31 -0500301 key_ref.filenames_mode.c_str()) == 0;*/
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500302}
303
304static bool is_numeric(const char* name) {
305 for (const char* p = name; *p != '\0'; p++) {
306 if (!isdigit(*p)) return false;
307 }
308 return true;
309}
310
311static bool load_all_de_keys() {
312 auto de_dir = user_key_dir + "/de";
313 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
314 if (!dirp) {
315 PLOG(ERROR) << "Unable to read de key directory" << std::endl;
316 return false;
317 }
318 for (;;) {
319 errno = 0;
320 auto entry = readdir(dirp.get());
321 if (!entry) {
322 if (errno) {
323 PLOG(ERROR) << "Unable to read de key directory" << std::endl;
324 return false;
325 }
326 break;
327 }
328 if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
329 LOG(DEBUG) << "Skipping non-de-key " << entry->d_name << std::endl;
330 continue;
331 }
332 userid_t user_id = std::stoi(entry->d_name);
333 if (s_de_key_raw_refs.count(user_id) == 0) {
334 auto key_path = de_dir + "/" + entry->d_name;
335 KeyBuffer key;
336 if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
337 std::string raw_ref;
338 if (!android::vold::installKey(key, &raw_ref)) return false;
339 s_de_key_raw_refs[user_id] = raw_ref;
340 LOG(DEBUG) << "Installed de key for user " << user_id << std::endl;
341 }
342 }
343 // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
344 // correct policy set on them, and that no rogue ones exist.
345 return true;
346}
347
348bool e4crypt_initialize_global_de() {
349 LOG(INFO) << "e4crypt_initialize_global_de" << std::endl;
350
351 if (s_global_de_initialized) {
352 LOG(INFO) << "Already initialized" << std::endl;
353 return true;
354 }
355
356 PolicyKeyRef device_ref;
357 LOG(INFO) << "calling retrieveAndInstallKey\n";
358 if (!android::vold::retrieveAndInstallKey(true, kEmptyAuthentication, device_key_path,
359 device_key_temp, &device_ref.key_raw_ref))
360 return false;
361 get_data_file_encryption_modes(&device_ref);
362
363 std::string modestring = device_ref.contents_mode + ":" + device_ref.filenames_mode;
364 std::string mode_filename = std::string("/data") + e4crypt_key_mode;
365 if (!android::base::WriteStringToFile(modestring, mode_filename)) {
366 PLOG(ERROR) << "Cannot save type" << std::endl;
367 return false;
368 }
369
370 std::string ref_filename = std::string("/data") + e4crypt_key_ref;
371 if (!android::base::WriteStringToFile(device_ref.key_raw_ref, ref_filename)) {
372 PLOG(ERROR) << "Cannot save key reference to:" << ref_filename << std::endl;
373 return false;
374 }
375 LOG(INFO) << "Wrote system DE key reference to:" << ref_filename << std::endl;
376
377 s_global_de_initialized = true;
378 de_raw_ref = device_ref.key_raw_ref;
379 return true;
380}
381
382bool e4crypt_init_user0() {
383 LOG(DEBUG) << "e4crypt_init_user0\n";
384 if (e4crypt_is_native()) {
385 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
386 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
387 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
388 if (!android::vold::pathExists(get_de_key_path(0))) {
389 if (!create_and_install_user_keys(0, false)) return false;
390 }
391 // TODO: switch to loading only DE_0 here once framework makes
392 // explicit calls to install DE keys for secondary users
393 if (!load_all_de_keys()) return false;
394 }
395 // We can only safely prepare DE storage here, since CE keys are probably
396 // entangled with user credentials. The framework will always prepare CE
397 // storage once CE keys are installed.
398 if (!e4crypt_prepare_user_storage("", 0, 0, /*android::os::IVold::*/STORAGE_FLAG_DE)) {
399 LOG(ERROR) << "Failed to prepare user 0 storage" << std::endl;
400 return false;
401 }
402
403 // If this is a non-FBE device that recently left an emulated mode,
404 // restore user data directories to known-good state.
405 if (!e4crypt_is_native() && !e4crypt_is_emulated()) {
406 e4crypt_unlock_user_key(0, 0, "!", "!");
407 }
408
409 return true;
410}
411
412/*bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
413 LOG(DEBUG) << "TWRP NOT e4crypt_vold_create_user_key for " << user_id << " serial " << serial;
414 return true;
415 if (!e4crypt_is_native()) {
416 return true;
417 }
418 // FIXME test for existence of key that is not loaded yet
419 if (s_ce_key_raw_refs.count(user_id) != 0) {
420 LOG(ERROR) << "Already exists, can't e4crypt_vold_create_user_key for " << user_id
421 << " serial " << serial;
422 // FIXME should we fail the command?
423 return true;
424 }
425 if (!create_and_install_user_keys(user_id, ephemeral)) {
426 return false;
427 }
428 return true;
429}
430
431static void drop_caches() {
432 // Clean any dirty pages (otherwise they won't be dropped).
433 sync();
434 // Drop inode and page caches.
435 if (!WriteStringToFile("3", "/proc/sys/vm/drop_caches")) {
436 PLOG(ERROR) << "Failed to drop caches during key eviction";
437 }
438}
439
440static bool evict_ce_key(userid_t user_id) {
441 LOG(ERROR) << "TWRP NOT evict_ce_key\n";
442 return true;
443 s_ce_keys.erase(user_id);
444 bool success = true;
445 std::string raw_ref;
446 // If we haven't loaded the CE key, no need to evict it.
447 if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
448 success &= android::vold::evictKey(raw_ref);
449 drop_caches();
450 }
451 s_ce_key_raw_refs.erase(user_id);
452 return success;
453}
454
455bool e4crypt_destroy_user_key(userid_t user_id) {
456 LOG(DEBUG) << "NOT e4crypt_destroy_user_key(" << user_id << ")";
457 return true;
458 if (!e4crypt_is_native()) {
459 return true;
460 }
461 bool success = true;
462 std::string raw_ref;
463 success &= evict_ce_key(user_id);
464 success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)
465 && android::vold::evictKey(raw_ref);
466 s_de_key_raw_refs.erase(user_id);
467 auto it = s_ephemeral_users.find(user_id);
468 if (it != s_ephemeral_users.end()) {
469 s_ephemeral_users.erase(it);
470 } else {
471 for (auto const path: get_ce_key_paths(get_ce_key_directory_path(user_id))) {
472 success &= android::vold::destroyKey(path);
473 }
474 auto de_key_path = get_de_key_path(user_id);
475 if (android::vold::pathExists(de_key_path)) {
476 success &= android::vold::destroyKey(de_key_path);
477 } else {
478 LOG(INFO) << "Not present so not erasing: " << de_key_path;
479 }
480 }
481 return success;
482}
483
484static bool emulated_lock(const std::string& path) {
485 if (chmod(path.c_str(), 0000) != 0) {
486 PLOG(ERROR) << "Failed to chmod " << path;
487 return false;
488 }
489#if EMULATED_USES_SELINUX
490 if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
491 PLOG(WARNING) << "Failed to setfilecon " << path;
492 return false;
493 }
494#endif
495 return true;
496}*/
497
498static bool emulated_unlock(const std::string& path, mode_t mode) {
499 if (chmod(path.c_str(), mode) != 0) {
500 PLOG(ERROR) << "Failed to chmod " << path << std::endl;
501 // FIXME temporary workaround for b/26713622
502 if (e4crypt_is_emulated()) return false;
503 }
504#if EMULATED_USES_SELINUX
505 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
506 PLOG(WARNING) << "Failed to restorecon " << path << std::endl;
507 // FIXME temporary workaround for b/26713622
508 if (e4crypt_is_emulated()) return false;
509 }
510#endif
511 return true;
512}
513
514static bool parse_hex(const std::string& hex, std::string* result) {
515 if (hex == "!") {
516 *result = "";
517 return true;
518 }
519 if (android::vold::HexToStr(hex, *result) != 0) {
520 LOG(ERROR) << "Invalid FBE hex string" << std::endl; // Don't log the string for security reasons
521 return false;
522 }
523 return true;
524}
525
526static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
527 return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
528}
529
530static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
531 return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
532}
533
534static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
535 PolicyKeyRef* key_ref) {
536 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
537 std::string secdiscardable_hash;
538 if (android::vold::pathExists(secdiscardable_path)) {
539 if (!android::vold::readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
540 return false;
541 } else {
542 if (fs_mkdirs(secdiscardable_path.c_str(), 0700) != 0) {
543 PLOG(ERROR) << "Creating directories for: " << secdiscardable_path << std::endl;
544 return false;
545 }
546 if (!android::vold::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
547 return false;
548 }
549 auto key_path = volkey_path(misc_path, volume_uuid);
550 if (fs_mkdirs(key_path.c_str(), 0700) != 0) {
551 PLOG(ERROR) << "Creating directories for: " << key_path << std::endl;
552 return false;
553 }
554 android::vold::KeyAuthentication auth("", secdiscardable_hash);
555 if (!android::vold::retrieveAndInstallKey(true, auth, key_path, key_path + "_tmp",
556 &key_ref->key_raw_ref))
557 return false;
558 key_ref->contents_mode =
559 android::base::GetProperty("ro.crypto.volume.contents_mode", "aes-256-xts");
560 key_ref->filenames_mode =
561 android::base::GetProperty("ro.crypto.volume.filenames_mode", "aes-256-heh");
562 return true;
563}
564
565/*static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
566 auto path = volkey_path(misc_path, volume_uuid);
567 if (!android::vold::pathExists(path)) return true;
568 return android::vold::destroyKey(path);
569}
570
571bool e4crypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
572 const std::string& secret_hex) {
573 LOG(DEBUG) << "e4crypt_add_user_key_auth " << user_id << " serial=" << serial
574 << " token_present=" << (token_hex != "!");
575 if (!e4crypt_is_native()) return true;
576 if (s_ephemeral_users.count(user_id) != 0) return true;
577 std::string token, secret;
578 if (!parse_hex(token_hex, &token)) return false;
579 if (!parse_hex(secret_hex, &secret)) return false;
580 auto auth = secret.empty() ? kEmptyAuthentication
581 : android::vold::KeyAuthentication(token, secret);
582 auto it = s_ce_keys.find(user_id);
583 if (it == s_ce_keys.end()) {
584 LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
585 return false;
586 }
587 const auto &ce_key = it->second;
588 auto const directory_path = get_ce_key_directory_path(user_id);
589 auto const paths = get_ce_key_paths(directory_path);
590 std::string ce_key_path;
591 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
592 if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
593 return true;
594}
595
596bool e4crypt_fixate_newest_user_key_auth(userid_t user_id) {
597 LOG(DEBUG) << "e4crypt_fixate_newest_user_key_auth " << user_id;
598 if (!e4crypt_is_native()) return true;
599 if (s_ephemeral_users.count(user_id) != 0) return true;
600 auto const directory_path = get_ce_key_directory_path(user_id);
601 auto const paths = get_ce_key_paths(directory_path);
602 if (paths.empty()) {
603 LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
604 return false;
605 }
606 fixate_user_ce_key(directory_path, paths[0], paths);
607 return true;
608}*/
609
610// TODO: rename to 'install' for consistency, and take flags to know which keys to install
611bool e4crypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
612 const std::string& secret_hex) {
613 LOG(DEBUG) << "e4crypt_unlock_user_key " << user_id << " serial=" << serial
614 << " token_present=" << (token_hex != "!") << std::endl;
615 if (e4crypt_is_native()) {
616 if (s_ce_key_raw_refs.count(user_id) != 0) {
617 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id << std::endl;
618 return true;
619 }
620 std::string token, secret;
621 if (!parse_hex(token_hex, &token)) return false;
622 if (!parse_hex(secret_hex, &secret)) return false;
623 android::vold::KeyAuthentication auth(token, secret);
624 if (!read_and_install_user_ce_key(user_id, auth)) {
625 LOG(ERROR) << "Couldn't read key for " << user_id << std::endl;
626 return false;
627 }
628 } else {
629 // When in emulation mode, we just use chmod. However, we also
630 // unlock directories when not in emulation mode, to bring devices
631 // back into a known-good state.
632 if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
633 !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
634 !emulated_unlock(android::vold::BuildDataMediaCePath("", user_id), 0770) ||
635 !emulated_unlock(android::vold::BuildDataUserCePath("", user_id), 0771)) {
636 LOG(ERROR) << "Failed to unlock user " << user_id << std::endl;
637 return false;
638 }
639 }
640 return true;
641}
642
643// TODO: rename to 'evict' for consistency
644/*bool e4crypt_lock_user_key(userid_t user_id) {
645 LOG(DEBUG) << "TWRP NOTe4crypt_lock_user_key " << user_id;
646 return true;
647 if (e4crypt_is_native()) {
648 return evict_ce_key(user_id);
649 } else if (e4crypt_is_emulated()) {
650 // When in emulation mode, we just use chmod
651 if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
652 !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
653 !emulated_lock(android::vold::BuildDataMediaCePath("", user_id)) ||
654 !emulated_lock(android::vold::BuildDataUserCePath("", user_id))) {
655 LOG(ERROR) << "Failed to lock user " << user_id;
656 return false;
657 }
658 }
659
660 return true;
661}*/
662
663static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
664 userid_t user_id, int flags) {
665 LOG(ERROR) << "not actually forking for vold_prepare_subdirs\n";
666 return true;
667 /*if (0 != android::vold::ForkExecvp(
668 std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
669 std::to_string(user_id), std::to_string(flags)})) {
670 LOG(ERROR) << "vold_prepare_subdirs failed";
671 return false;
672 }
673 return true;*/
674}
675
676bool e4crypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
677 int flags) {
678 LOG(DEBUG) << "e4crypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
679 << ", user " << user_id << ", serial " << serial << ", flags " << flags << std::endl;
680
681 if (flags & /*android::os::IVold::*/STORAGE_FLAG_DE) {
682 // DE_sys key
683 auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
684 auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
685 auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
686
687 // DE_n key
688 auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
689 auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
690 auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
691 auto user_de_path = android::vold::BuildDataUserDePath(nullptr, user_id);
692
693 if (volume_uuid.empty()) {
694 if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
695#if MANAGE_MISC_DIRS
696 if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
697 multiuser_get_uid(user_id, AID_EVERYBODY))) return false;
698#endif
699 if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
700 if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
701 if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
702 if (!prepare_dir(vendor_de_path, 0771, AID_ROOT, AID_ROOT)) return false;
703 }
704 if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
705
706 if (e4crypt_is_native()) {
707 PolicyKeyRef de_ref;
708 if (volume_uuid.empty()) {
709 if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_ref.key_raw_ref)) return false;
710 get_data_file_encryption_modes(&de_ref);
711 if (!ensure_policy(de_ref, system_de_path)) return false;
712 if (!ensure_policy(de_ref, misc_de_path)) return false;
713 if (!ensure_policy(de_ref, vendor_de_path)) return false;
714 } else {
715 if (!read_or_create_volkey(misc_de_path, nullptr, &de_ref)) return false;
716 }
717 if (!ensure_policy(de_ref, user_de_path)) return false;
718 }
719 }
720
721 if (flags & /*android::os::IVold::*/STORAGE_FLAG_CE) {
722 // CE_n key
723 auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
724 auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
725 auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
726 auto media_ce_path = android::vold::BuildDataMediaCePath(nullptr, user_id);
727 auto user_ce_path = android::vold::BuildDataUserCePath(nullptr, user_id);
728
729 if (volume_uuid.empty()) {
730 if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
731 if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
732 if (!prepare_dir(vendor_ce_path, 0771, AID_ROOT, AID_ROOT)) return false;
733 }
734 if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
735 if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
736
737 if (e4crypt_is_native()) {
738 PolicyKeyRef ce_ref;
739 if (volume_uuid.empty()) {
740 if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_ref.key_raw_ref)) return false;
741 get_data_file_encryption_modes(&ce_ref);
742 if (!ensure_policy(ce_ref, system_ce_path)) return false;
743 if (!ensure_policy(ce_ref, misc_ce_path)) return false;
744 if (!ensure_policy(ce_ref, vendor_ce_path)) return false;
745 } else {
746 if (!read_or_create_volkey(misc_ce_path, nullptr, &ce_ref)) return false;
747 }
748 if (!ensure_policy(ce_ref, media_ce_path)) return false;
749 if (!ensure_policy(ce_ref, user_ce_path)) return false;
750 }
751
752 if (volume_uuid.empty()) {
753 // Now that credentials have been installed, we can run restorecon
754 // over these paths
755 // NOTE: these paths need to be kept in sync with libselinux
756 //android::vold::RestoreconRecursive(system_ce_path);
757 //android::vold::RestoreconRecursive(misc_ce_path);
758 }
759 }
760 if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
761 return true;
762}
763
764/*bool e4crypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
765 LOG(DEBUG) << "TWRP NOT e4crypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
766 << ", user " << user_id << ", flags " << flags;
767 bool res = true;
768 return res;
769
770 res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
771
772 if (flags & android::os::IVold::STORAGE_FLAG_CE) {
773 // CE_n key
774 auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
775 auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
776 auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
777 auto media_ce_path = android::vold::BuildDataMediaCePath(nullptr, user_id);
778 auto user_ce_path = android::vold::BuildDataUserCePath(nullptr, user_id);
779
780 res &= destroy_dir(media_ce_path);
781 res &= destroy_dir(user_ce_path);
782 if (volume_uuid.empty()) {
783 res &= destroy_dir(system_ce_path);
784 res &= destroy_dir(misc_ce_path);
785 res &= destroy_dir(vendor_ce_path);
786 } else {
787 if (e4crypt_is_native()) {
788 res &= destroy_volkey(misc_ce_path, volume_uuid);
789 }
790 }
791 }
792
793 if (flags & android::os::IVold::STORAGE_FLAG_DE) {
794 // DE_sys key
795 auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
796 auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
797 auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
798
799 // DE_n key
800 auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
801 auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
802 auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
803 auto user_de_path = android::vold::BuildDataUserDePath(nullptr, user_id);
804
805 res &= destroy_dir(user_de_path);
806 if (volume_uuid.empty()) {
807 res &= destroy_dir(system_legacy_path);
808#if MANAGE_MISC_DIRS
809 res &= destroy_dir(misc_legacy_path);
810#endif
811 res &= destroy_dir(profiles_de_path);
812 res &= destroy_dir(system_de_path);
813 res &= destroy_dir(misc_de_path);
814 res &= destroy_dir(vendor_de_path);
815 } else {
816 if (e4crypt_is_native()) {
817 res &= destroy_volkey(misc_de_path, volume_uuid);
818 }
819 }
820 }
821
822 return res;
823}
824
825static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
826 LOG(ERROR) << "TWRP NOT destroy_volume_keys\n";
827 return true;
828 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
829 if (!dirp) {
830 PLOG(ERROR) << "Unable to open directory: " + directory_path;
831 return false;
832 }
833 bool res = true;
834 for (;;) {
835 errno = 0;
836 auto const entry = readdir(dirp.get());
837 if (!entry) {
838 if (errno) {
839 PLOG(ERROR) << "Unable to read directory: " + directory_path;
840 return false;
841 }
842 break;
843 }
844 if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
845 LOG(DEBUG) << "Skipping non-user " << entry->d_name;
846 continue;
847 }
848 res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
849 }
850 return res;
851}
852
853bool e4crypt_destroy_volume_keys(const std::string& volume_uuid) {
854 bool res = true;
855 LOG(DEBUG) << "TWRP NOT e4crypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
856 /*return res;
857 auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
858 res &= android::vold::runSecdiscardSingle(secdiscardable_path);
859 res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
860 res &= destroy_volume_keys("/data/misc_de", volume_uuid);
861 return res;
862}*/