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