blob: 15d7d8f32d966f76e014eb098c562c6801265fa5 [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
Ethan Yonker58f21322018-08-24 11:17:36 -0500319static bool ensure_policy(const std::string& raw_ref __unused, const std::string& path) {
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600320 LOG(INFO) << "ensure_policy '" << path << "'\n";
321 return true;
322 return access(path.c_str(), F_OK) == 0; // ensure policy will set a policy if one is not set on an empty folder - we don't want to do this in recovery
323 /*if (e4crypt_policy_ensure(path.c_str(), raw_ref.data(), raw_ref.size()) != 0) {
324 LOG(ERROR) << "Failed to set policy on: " << path << "\n";
325 return false;
326 }
327 return true;*/
328}
329
330static bool is_numeric(const char* name) {
331 for (const char* p = name; *p != '\0'; p++) {
332 if (!isdigit(*p)) return false;
333 }
334 return true;
335}
336
337static bool load_all_de_keys() {
338 auto de_dir = user_key_dir + "/de";
339 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
340 if (!dirp) {
341 PLOG(ERROR) << "Unable to read de key directory";
342 return false;
343 }
344 for (;;) {
345 errno = 0;
346 auto entry = readdir(dirp.get());
347 if (!entry) {
348 if (errno) {
349 PLOG(ERROR) << "Unable to read de key directory";
350 return false;
351 }
352 break;
353 }
354 if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
355 LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
356 continue;
357 }
358 userid_t user_id = atoi(entry->d_name);
359 if (s_de_key_raw_refs.count(user_id) == 0) {
360 auto key_path = de_dir + "/" + entry->d_name;
361 std::string key;
362 if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
363 std::string raw_ref;
364 if (!install_key(key, &raw_ref)) return false;
365 s_de_key_raw_refs[user_id] = raw_ref;
366 LOG(DEBUG) << "Installed de key for user " << user_id;
367 }
368 }
369 // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
370 // correct policy set on them, and that no rogue ones exist.
371 return true;
372}
373
374bool e4crypt_initialize_global_de() {
375
376 if (s_global_de_initialized) {
377 LOG(INFO) << "Already initialized\n";
378 return true;
379 }
380
381 std::string device_key;
382 if (path_exists(device_key_path)) {
383 if (!android::vold::retrieveKey(device_key_path,
384 kEmptyAuthentication, &device_key)) return false;
385 } else {
386 LOG(INFO) << "NOT Creating new key\n";
387 return false;
388 }
389
390 std::string device_key_ref;
391 if (!install_key(device_key, &device_key_ref)) {
392 LOG(ERROR) << "Failed to install device key\n";
393 return false;
394 }
395
396 s_global_de_initialized = true;
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600397 de_raw_ref = device_key_ref;
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600398 return true;
399}
400
401bool e4crypt_init_user0() {
402 if (e4crypt_is_native()) {
403 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
404 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
405 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
406 if (!path_exists(get_de_key_path(0))) {
407 //if (!create_and_install_user_keys(0, false)) return false;
408 printf("de key path not found\n");
409 return false;
410 }
411 // TODO: switch to loading only DE_0 here once framework makes
412 // explicit calls to install DE keys for secondary users
413 if (!load_all_de_keys()) return false;
414 }
415 // We can only safely prepare DE storage here, since CE keys are probably
416 // entangled with user credentials. The framework will always prepare CE
417 // storage once CE keys are installed.
418 if (!e4crypt_prepare_user_storage(nullptr, 0, 0, FLAG_STORAGE_DE)) {
419 LOG(ERROR) << "Failed to prepare user 0 storage";
420 return false;
421 }
422
423 // If this is a non-FBE device that recently left an emulated mode,
424 // restore user data directories to known-good state.
425 if (!e4crypt_is_native() && !e4crypt_is_emulated()) {
426 e4crypt_unlock_user_key(0, 0, "!", "!");
427 }
428
429 return true;
430}
431
432static bool parse_hex(const char* hex, std::string* result) {
433 if (strcmp("!", hex) == 0) {
434 *result = "";
435 return true;
436 }
437 if (android::vold::HexToStr(hex, *result) != 0) {
438 LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
439 return false;
440 }
441 return true;
442}
443
444// TODO: rename to 'install' for consistency, and take flags to know which keys to install
Ethan Yonker58f21322018-08-24 11:17:36 -0500445bool e4crypt_unlock_user_key(userid_t user_id, int serial __unused, const char* token_hex,
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600446 const char* secret_hex) {
447 if (e4crypt_is_native()) {
448 if (s_ce_key_raw_refs.count(user_id) != 0) {
449 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
450 return true;
451 }
452 std::string token, secret;
453 if (!parse_hex(token_hex, &token)) return false;
454 if (!parse_hex(secret_hex, &secret)) return false;
455 android::vold::KeyAuthentication auth(token, secret);
456 if (!read_and_install_user_ce_key(user_id, auth)) {
457 LOG(ERROR) << "Couldn't read key for " << user_id;
458 return false;
459 }
460 } else {
461 printf("Emulation mode not supported in TWRP\n");
462 // When in emulation mode, we just use chmod. However, we also
463 // unlock directories when not in emulation mode, to bring devices
464 // back into a known-good state.
465 /*if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
466 !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
467 !emulated_unlock(android::vold::BuildDataMediaCePath(nullptr, user_id), 0770) ||
468 !emulated_unlock(android::vold::BuildDataUserCePath(nullptr, user_id), 0771)) {
469 LOG(ERROR) << "Failed to unlock user " << user_id;
470 return false;
471 }*/
472 }
473 return true;
474}
475
Ethan Yonker58f21322018-08-24 11:17:36 -0500476bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial __unused,
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600477 int flags) {
478
479 if (flags & FLAG_STORAGE_DE) {
480 // DE_sys key
481 auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
482 auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
483 auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
484 auto foreign_de_path = android::vold::BuildDataProfilesForeignDexDePath(user_id);
485
486 // DE_n key
487 auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
488 auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
489 auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
490
491 if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
492#if MANAGE_MISC_DIRS
493 if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
494 multiuser_get_uid(user_id, AID_EVERYBODY))) return false;
495#endif
496 if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
497 if (!prepare_dir(foreign_de_path, 0773, AID_SYSTEM, AID_SYSTEM)) return false;
498
499 if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
500 if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
501 if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
502
503 // For now, FBE is only supported on internal storage
504 if (e4crypt_is_native() && volume_uuid == nullptr) {
505 std::string de_raw_ref;
506 if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_raw_ref)) return false;
507 if (!ensure_policy(de_raw_ref, system_de_path)) return false;
508 if (!ensure_policy(de_raw_ref, misc_de_path)) return false;
509 if (!ensure_policy(de_raw_ref, user_de_path)) return false;
510 }
511 }
512
513 if (flags & FLAG_STORAGE_CE) {
514 // CE_n key
515 auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
516 auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
517 auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
518 auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
519
520 if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
521 if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
522 if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
523 if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
524
525 // For now, FBE is only supported on internal storage
526 if (e4crypt_is_native() && volume_uuid == nullptr) {
527 std::string ce_raw_ref;
528 if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_raw_ref)) return false;
529 if (!ensure_policy(ce_raw_ref, system_ce_path)) return false;
530 if (!ensure_policy(ce_raw_ref, misc_ce_path)) return false;
531 if (!ensure_policy(ce_raw_ref, media_ce_path)) return false;
532 if (!ensure_policy(ce_raw_ref, user_ce_path)) return false;
533 }
534 }
535
536 return true;
537}