blob: c9e71fd9bb817c992e7e1ab37a856638ee3eba2c [file] [log] [blame]
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001/*
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 "Ext4Crypt.h"
18#include "Decrypt.h"
19
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050020#ifdef USE_KEYSTORAGE_3
21#include "KeyStorage3.h"
22#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060023#include "KeyStorage.h"
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050024#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060025#include "Utils.h"
26
27#include <algorithm>
28#include <iomanip>
29#include <map>
30#include <set>
31#include <sstream>
32#include <string>
33
34#include <dirent.h>
35#include <errno.h>
36#include <fcntl.h>
37#include <limits.h>
38#include <openssl/sha.h>
39#include <selinux/android.h>
40#include <stdio.h>
41#include <sys/mount.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <iostream>
45
46#include <private/android_filesystem_config.h>
47
Ethan Yonkerfefe5912017-09-30 22:22:13 -050048#ifdef HAVE_SYNTH_PWD_SUPPORT
49#include <ext4_utils/ext4_crypt.h>
50#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060051#include "ext4_crypt.h"
Ethan Yonkerfefe5912017-09-30 22:22:13 -050052#endif
53#ifndef HAVE_LIBKEYUTILS
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060054#include "key_control.h"
Ethan Yonkerfefe5912017-09-30 22:22:13 -050055#else
56#include <keyutils.h>
57#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060058
59#include <hardware/gatekeeper.h>
60#include "HashPassword.h"
61
62#define EMULATED_USES_SELINUX 0
63#define MANAGE_MISC_DIRS 0
64
65#include <cutils/fs.h>
66
67#include <android-base/file.h>
68//#include <android-base/logging.h>
69#include <android-base/stringprintf.h>
70
71#define LOG(x) std::cout
72#define PLOG(x) std::cout
73#define DATA_MNT_POINT "/data"
74
75using android::base::StringPrintf;
76using android::vold::kEmptyAuthentication;
77
78// NOTE: keep in sync with StorageManager
79//static constexpr int FLAG_STORAGE_DE = 1 << 0; // moved to Decrypt.h
80//static constexpr int FLAG_STORAGE_CE = 1 << 1;
81
Ethan Yonker79f88bd2016-12-09 14:52:12 -060082// Store main DE raw ref / policy
83std::string de_raw_ref;
84// Map user ids to key references
85std::map<userid_t, std::string> s_de_key_raw_refs;
86std::map<userid_t, std::string> s_ce_key_raw_refs;
87
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060088namespace {
89const std::string device_key_dir = std::string() + DATA_MNT_POINT + e4crypt_unencrypted_folder;
90const std::string device_key_path = device_key_dir + "/key";
91const std::string device_key_temp = device_key_dir + "/temp";
92
93const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
94const std::string user_key_temp = user_key_dir + "/temp";
95
96bool s_global_de_initialized = false;
97
98// Some users are ephemeral, don't try to wipe their keys from disk
99std::set<userid_t> s_ephemeral_users;
100
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600101// TODO abolish this map. Keys should not be long-lived in user memory, only kernel memory.
102// See b/26948053
103std::map<userid_t, std::string> s_ce_keys;
104
105// ext4enc:TODO get this const from somewhere good
106const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
107
108// ext4enc:TODO Include structure from somewhere sensible
109// MUST be in sync with ext4_crypto.c in kernel
110constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
111constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
112constexpr int EXT4_MAX_KEY_SIZE = 64;
113struct ext4_encryption_key {
114 uint32_t mode;
115 char raw[EXT4_MAX_KEY_SIZE];
116 uint32_t size;
117};
118}
119
120static bool e4crypt_is_emulated() {
121 return false; //property_get_bool("persist.sys.emulate_fbe", false);
122}
123
124static const char* escape_null(const char* value) {
125 return (value == nullptr) ? "null" : value;
126}
127
128// Get raw keyref - used to make keyname and to pass to ioctl
129static std::string generate_key_ref(const char* key, int length) {
130 SHA512_CTX c;
131
132 SHA512_Init(&c);
133 SHA512_Update(&c, key, length);
134 unsigned char key_ref1[SHA512_DIGEST_LENGTH];
135 SHA512_Final(key_ref1, &c);
136
137 SHA512_Init(&c);
138 SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
139 unsigned char key_ref2[SHA512_DIGEST_LENGTH];
140 SHA512_Final(key_ref2, &c);
141
142 static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
143 "Hash too short for descriptor");
144 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
145}
146
147static bool fill_key(const std::string& key, ext4_encryption_key* ext4_key) {
148 if (key.size() != EXT4_AES_256_XTS_KEY_SIZE) {
149 LOG(ERROR) << "Wrong size key " << key.size();
150 return false;
151 }
152 static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key->raw), "Key too long!");
153 ext4_key->mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
154 ext4_key->size = key.size();
155 memset(ext4_key->raw, 0, sizeof(ext4_key->raw));
156 memcpy(ext4_key->raw, key.data(), key.size());
157 return true;
158}
159
160static std::string keyname(const std::string& raw_ref) {
161 std::ostringstream o;
162 o << "ext4:";
163 for (auto i : raw_ref) {
164 o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
165 }
166 LOG(INFO) << "keyname is " << o.str() << "\n";
167 return o.str();
168}
169
170// Get the keyring we store all keys in
171static bool e4crypt_keyring(key_serial_t* device_keyring) {
172 *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
173 if (*device_keyring == -1) {
174 PLOG(ERROR) << "Unable to find device keyring\n";
175 return false;
176 }
177 return true;
178}
179
180// Install password into global keyring
181// Return raw key reference for use in policy
182static bool install_key(const std::string& key, std::string* raw_ref) {
183 ext4_encryption_key ext4_key;
184 if (!fill_key(key, &ext4_key)) return false;
185 *raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
186 auto ref = keyname(*raw_ref);
187 key_serial_t device_keyring;
188 if (!e4crypt_keyring(&device_keyring)) return false;
189 key_serial_t key_id =
190 add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
191 if (key_id == -1) {
192 PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring << "\n";
193 return false;
194 }
195 LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
196 << " in process " << getpid() << "\n";
197 return true;
198}
199
200static std::string get_de_key_path(userid_t user_id) {
201LOG(INFO) << "get_de_key_path " << user_id << " " << StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id) << "\n";
202 return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
203}
204
205static std::string get_ce_key_directory_path(userid_t user_id) {
206LOG(INFO) << "get_ce_key_directory_path " << user_id << ": " << StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id) << "\n";
207 return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
208}
209
210// Returns the keys newest first
211static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
212 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
213 if (!dirp) {
214 PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
215 return std::vector<std::string>();
216 }
217 std::vector<std::string> result;
218 for (;;) {
219 errno = 0;
220 auto const entry = readdir(dirp.get());
221 if (!entry) {
222 if (errno) {
223 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
224 return std::vector<std::string>();
225 }
226 break;
227 }
228 if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
229 LOG(DEBUG) << "Skipping non-key " << entry->d_name;
230 continue;
231 }
232 result.emplace_back(directory_path + "/" + entry->d_name);
233 LOG(INFO) << "get_ce_key_paths adding: " << directory_path + "/" + entry->d_name << "\n";
234 }
235 std::sort(result.begin(), result.end());
236 std::reverse(result.begin(), result.end());
237 return result;
238}
239
240static std::string get_ce_key_current_path(const std::string& directory_path) {
241LOG(INFO) << "get_ce_key_current_path: " << directory_path + "/current\n";
242 return directory_path + "/current";
243}
244
245// Discard all keys but the named one; rename it to canonical name.
246// No point in acting on errors in this; ignore them.
247static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix,
248 const std::vector<std::string>& paths) {
249 for (auto const other_path: paths) {
250 if (other_path != to_fix) {
251 android::vold::destroyKey(other_path);
252 }
253 }
254 auto const current_path = get_ce_key_current_path(directory_path);
255 if (to_fix != current_path) {
256 LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
257 if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
258 PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
259 }
260 }
261}
262
263static bool read_and_fixate_user_ce_key(userid_t user_id,
264 const android::vold::KeyAuthentication& auth,
265 std::string *ce_key) {
266 auto const directory_path = get_ce_key_directory_path(user_id);
267 auto const paths = get_ce_key_paths(directory_path);
268 for (auto const ce_key_path: paths) {
269 LOG(DEBUG) << "Trying user CE key " << ce_key_path;
270 if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
271 LOG(DEBUG) << "Successfully retrieved key";
272 fixate_user_ce_key(directory_path, ce_key_path, paths);
273 return true;
274 }
275 }
276 LOG(ERROR) << "Failed to find working ce key for user " << user_id;
277 return false;
278}
279
280static bool read_and_install_user_ce_key(userid_t user_id,
281 const android::vold::KeyAuthentication& auth) {
282 if (s_ce_key_raw_refs.count(user_id) != 0) return true;
283 std::string ce_key;
284 if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
285 std::string ce_raw_ref;
286 if (!install_key(ce_key, &ce_raw_ref)) return false;
287 s_ce_keys[user_id] = ce_key;
288 s_ce_key_raw_refs[user_id] = ce_raw_ref;
289 LOG(DEBUG) << "Installed ce key for user " << user_id;
290 return true;
291}
292
293static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
294 LOG(DEBUG) << "Preparing: " << dir << "\n";
295 return true;
296 return access(dir.c_str(), F_OK) == 0; // we don't want recovery creating directories or changing permissions at this point, so we will just return true if the path already exists
297 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
298 PLOG(ERROR) << "Failed to prepare " << dir;
299 return false;
300 }
301 return true;
302}
303
304static bool path_exists(const std::string& path) {
305 return access(path.c_str(), F_OK) == 0;
306}
307
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600308bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600309 std::string* raw_ref) {
310 auto refi = key_map.find(user_id);
311 if (refi == key_map.end()) {
312 LOG(ERROR) << "Cannot find key for " << user_id;
313 return false;
314 }
315 *raw_ref = refi->second;
316 return true;
317}
318
bigbiffadc599e2020-05-28 19:36:30 +0000319static bool ensure_policy(const std::string& raw_ref __unused, const std::string& path) {
320 return true;
321 // ensure policy will set a policy if one is not set on an empty folder - we don't want to do this in recovery
322 /*if (e4crypt_policy_ensure(path.c_str(), raw_ref.data(), raw_ref.size()) != 0) {
323 LOG(ERROR) << "Failed to set policy on: " << path << "\n";
324 return false;
325 }
326 return true;*/
327}
328
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600329static bool is_numeric(const char* name) {
330 for (const char* p = name; *p != '\0'; p++) {
331 if (!isdigit(*p)) return false;
332 }
333 return true;
334}
335
336static bool load_all_de_keys() {
337 auto de_dir = user_key_dir + "/de";
338 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
339 if (!dirp) {
340 PLOG(ERROR) << "Unable to read de key directory";
341 return false;
342 }
343 for (;;) {
344 errno = 0;
345 auto entry = readdir(dirp.get());
346 if (!entry) {
347 if (errno) {
348 PLOG(ERROR) << "Unable to read de key directory";
349 return false;
350 }
351 break;
352 }
353 if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
354 LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
355 continue;
356 }
357 userid_t user_id = atoi(entry->d_name);
358 if (s_de_key_raw_refs.count(user_id) == 0) {
359 auto key_path = de_dir + "/" + entry->d_name;
360 std::string key;
361 if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
362 std::string raw_ref;
363 if (!install_key(key, &raw_ref)) return false;
364 s_de_key_raw_refs[user_id] = raw_ref;
365 LOG(DEBUG) << "Installed de key for user " << user_id;
366 }
367 }
368 // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
369 // correct policy set on them, and that no rogue ones exist.
370 return true;
371}
372
373bool e4crypt_initialize_global_de() {
374
375 if (s_global_de_initialized) {
376 LOG(INFO) << "Already initialized\n";
377 return true;
378 }
379
380 std::string device_key;
381 if (path_exists(device_key_path)) {
382 if (!android::vold::retrieveKey(device_key_path,
383 kEmptyAuthentication, &device_key)) return false;
384 } else {
385 LOG(INFO) << "NOT Creating new key\n";
386 return false;
387 }
388
389 std::string device_key_ref;
390 if (!install_key(device_key, &device_key_ref)) {
391 LOG(ERROR) << "Failed to install device key\n";
392 return false;
393 }
394
395 s_global_de_initialized = true;
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600396 de_raw_ref = device_key_ref;
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600397 return true;
398}
399
400bool e4crypt_init_user0() {
401 if (e4crypt_is_native()) {
402 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
403 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
404 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
405 if (!path_exists(get_de_key_path(0))) {
406 //if (!create_and_install_user_keys(0, false)) return false;
407 printf("de key path not found\n");
408 return false;
409 }
410 // TODO: switch to loading only DE_0 here once framework makes
411 // explicit calls to install DE keys for secondary users
412 if (!load_all_de_keys()) return false;
413 }
bigbiffadc599e2020-05-28 19:36:30 +0000414 // We can only safely prepare DE storage here, since CE keys are probably
415 // entangled with user credentials. The framework will always prepare CE
416 // storage once CE keys are installed.
417 if (!e4crypt_prepare_user_storage(nullptr, 0, 0, FLAG_STORAGE_DE)) {
418 LOG(ERROR) << "Failed to prepare user 0 storage";
419 return false;
420 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600421
422 // If this is a non-FBE device that recently left an emulated mode,
423 // restore user data directories to known-good state.
424 if (!e4crypt_is_native() && !e4crypt_is_emulated()) {
425 e4crypt_unlock_user_key(0, 0, "!", "!");
426 }
427
428 return true;
429}
430
431static bool parse_hex(const char* hex, std::string* result) {
432 if (strcmp("!", hex) == 0) {
433 *result = "";
434 return true;
435 }
436 if (android::vold::HexToStr(hex, *result) != 0) {
437 LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
438 return false;
439 }
440 return true;
441}
442
443// TODO: rename to 'install' for consistency, and take flags to know which keys to install
Ethan Yonker58f21322018-08-24 11:17:36 -0500444bool e4crypt_unlock_user_key(userid_t user_id, int serial __unused, const char* token_hex,
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600445 const char* secret_hex) {
446 if (e4crypt_is_native()) {
447 if (s_ce_key_raw_refs.count(user_id) != 0) {
448 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
449 return true;
450 }
451 std::string token, secret;
452 if (!parse_hex(token_hex, &token)) return false;
453 if (!parse_hex(secret_hex, &secret)) return false;
454 android::vold::KeyAuthentication auth(token, secret);
455 if (!read_and_install_user_ce_key(user_id, auth)) {
456 LOG(ERROR) << "Couldn't read key for " << user_id;
457 return false;
458 }
459 } else {
460 printf("Emulation mode not supported in TWRP\n");
bigbiffadc599e2020-05-28 19:36:30 +0000461 // When in emulation mode, we just use chmod. However, we also
462 // unlock directories when not in emulation mode, to bring devices
463 // back into a known-good state.
464 /*if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
465 !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
466 !emulated_unlock(android::vold::BuildDataMediaCePath(nullptr, user_id), 0770) ||
467 !emulated_unlock(android::vold::BuildDataUserCePath(nullptr, user_id), 0771)) {
468 LOG(ERROR) << "Failed to unlock user " << user_id;
469 return false;
470 }*/
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600471 }
472 return true;
473}
bigbiffadc599e2020-05-28 19:36:30 +0000474
475bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial __unused,
476 int flags) {
477
478 if (flags & FLAG_STORAGE_DE) {
479 // DE_sys key
480 auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
481 auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
482 auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
483 auto foreign_de_path = android::vold::BuildDataProfilesForeignDexDePath(user_id);
484
485 // DE_n key
486 auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
487 auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
488 auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
489
490 if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
491#if MANAGE_MISC_DIRS
492 if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
493 multiuser_get_uid(user_id, AID_EVERYBODY))) return false;
494#endif
495 if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
496 if (!prepare_dir(foreign_de_path, 0773, AID_SYSTEM, AID_SYSTEM)) return false;
497
498 if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
499 if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
500 if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
501
502 // For now, FBE is only supported on internal storage
503 if (e4crypt_is_native() && volume_uuid == nullptr) {
504 std::string de_raw_ref;
505 if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_raw_ref)) return false;
506 if (!ensure_policy(de_raw_ref, system_de_path)) return false;
507 if (!ensure_policy(de_raw_ref, misc_de_path)) return false;
508 if (!ensure_policy(de_raw_ref, user_de_path)) return false;
509 }
510 }
511
512 if (flags & FLAG_STORAGE_CE) {
513 // CE_n key
514 auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
515 auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
516 auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
517 auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
518
519 if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
520 if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
521 if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
522 if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
523
524 // For now, FBE is only supported on internal storage
525 if (e4crypt_is_native() && volume_uuid == nullptr) {
526 std::string ce_raw_ref;
527 if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_raw_ref)) return false;
528 if (!ensure_policy(ce_raw_ref, system_ce_path)) return false;
529 if (!ensure_policy(ce_raw_ref, misc_ce_path)) return false;
530 if (!ensure_policy(ce_raw_ref, media_ce_path)) return false;
531 if (!ensure_policy(ce_raw_ref, user_ce_path)) return false;
532 }
533 }
534
535 return true;
536}