blob: 9360b1a2e16d86b70a7fa3603d42f6ee7dd27281 [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>
Noah Jacobson5a79f672019-04-28 00:10:07 -040066#include <cutils/properties.h>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060067
68#include <android-base/file.h>
69//#include <android-base/logging.h>
70#include <android-base/stringprintf.h>
71
72#define LOG(x) std::cout
73#define PLOG(x) std::cout
74#define DATA_MNT_POINT "/data"
75
76using android::base::StringPrintf;
77using android::vold::kEmptyAuthentication;
78
79// NOTE: keep in sync with StorageManager
80//static constexpr int FLAG_STORAGE_DE = 1 << 0; // moved to Decrypt.h
81//static constexpr int FLAG_STORAGE_CE = 1 << 1;
82
Ethan Yonker79f88bd2016-12-09 14:52:12 -060083// Store main DE raw ref / policy
84std::string de_raw_ref;
85// Map user ids to key references
86std::map<userid_t, std::string> s_de_key_raw_refs;
87std::map<userid_t, std::string> s_ce_key_raw_refs;
88
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060089namespace {
90const std::string device_key_dir = std::string() + DATA_MNT_POINT + e4crypt_unencrypted_folder;
91const std::string device_key_path = device_key_dir + "/key";
92const std::string device_key_temp = device_key_dir + "/temp";
93
94const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
95const std::string user_key_temp = user_key_dir + "/temp";
96
97bool s_global_de_initialized = false;
98
99// Some users are ephemeral, don't try to wipe their keys from disk
100std::set<userid_t> s_ephemeral_users;
101
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600102// TODO abolish this map. Keys should not be long-lived in user memory, only kernel memory.
103// See b/26948053
104std::map<userid_t, std::string> s_ce_keys;
105
106// ext4enc:TODO get this const from somewhere good
107const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
108
109// ext4enc:TODO Include structure from somewhere sensible
110// MUST be in sync with ext4_crypto.c in kernel
111constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
112constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
113constexpr int EXT4_MAX_KEY_SIZE = 64;
114struct ext4_encryption_key {
115 uint32_t mode;
116 char raw[EXT4_MAX_KEY_SIZE];
117 uint32_t size;
118};
119}
120
121static bool e4crypt_is_emulated() {
122 return false; //property_get_bool("persist.sys.emulate_fbe", false);
123}
124
125static const char* escape_null(const char* value) {
126 return (value == nullptr) ? "null" : value;
127}
128
129// Get raw keyref - used to make keyname and to pass to ioctl
130static std::string generate_key_ref(const char* key, int length) {
131 SHA512_CTX c;
132
133 SHA512_Init(&c);
134 SHA512_Update(&c, key, length);
135 unsigned char key_ref1[SHA512_DIGEST_LENGTH];
136 SHA512_Final(key_ref1, &c);
137
138 SHA512_Init(&c);
139 SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
140 unsigned char key_ref2[SHA512_DIGEST_LENGTH];
141 SHA512_Final(key_ref2, &c);
142
143 static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
144 "Hash too short for descriptor");
145 return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
146}
147
148static bool fill_key(const std::string& key, ext4_encryption_key* ext4_key) {
149 if (key.size() != EXT4_AES_256_XTS_KEY_SIZE) {
150 LOG(ERROR) << "Wrong size key " << key.size();
151 return false;
152 }
153 static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key->raw), "Key too long!");
154 ext4_key->mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
155 ext4_key->size = key.size();
156 memset(ext4_key->raw, 0, sizeof(ext4_key->raw));
157 memcpy(ext4_key->raw, key.data(), key.size());
158 return true;
159}
160
161static std::string keyname(const std::string& raw_ref) {
162 std::ostringstream o;
163 o << "ext4:";
164 for (auto i : raw_ref) {
165 o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
166 }
167 LOG(INFO) << "keyname is " << o.str() << "\n";
168 return o.str();
169}
170
171// Get the keyring we store all keys in
172static bool e4crypt_keyring(key_serial_t* device_keyring) {
173 *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
174 if (*device_keyring == -1) {
175 PLOG(ERROR) << "Unable to find device keyring\n";
176 return false;
177 }
178 return true;
179}
180
181// Install password into global keyring
182// Return raw key reference for use in policy
183static bool install_key(const std::string& key, std::string* raw_ref) {
184 ext4_encryption_key ext4_key;
185 if (!fill_key(key, &ext4_key)) return false;
186 *raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
187 auto ref = keyname(*raw_ref);
188 key_serial_t device_keyring;
189 if (!e4crypt_keyring(&device_keyring)) return false;
190 key_serial_t key_id =
191 add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
192 if (key_id == -1) {
193 PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring << "\n";
194 return false;
195 }
196 LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
197 << " in process " << getpid() << "\n";
198 return true;
199}
200
201static std::string get_de_key_path(userid_t user_id) {
202LOG(INFO) << "get_de_key_path " << user_id << " " << StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id) << "\n";
203 return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
204}
205
206static std::string get_ce_key_directory_path(userid_t user_id) {
207LOG(INFO) << "get_ce_key_directory_path " << user_id << ": " << StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id) << "\n";
208 return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
209}
210
211// Returns the keys newest first
212static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
213 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
214 if (!dirp) {
215 PLOG(ERROR) << "Unable to open ce key directory: " + directory_path;
216 return std::vector<std::string>();
217 }
218 std::vector<std::string> result;
219 for (;;) {
220 errno = 0;
221 auto const entry = readdir(dirp.get());
222 if (!entry) {
223 if (errno) {
224 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path;
225 return std::vector<std::string>();
226 }
227 break;
228 }
229 if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
230 LOG(DEBUG) << "Skipping non-key " << entry->d_name;
231 continue;
232 }
233 result.emplace_back(directory_path + "/" + entry->d_name);
234 LOG(INFO) << "get_ce_key_paths adding: " << directory_path + "/" + entry->d_name << "\n";
235 }
236 std::sort(result.begin(), result.end());
237 std::reverse(result.begin(), result.end());
238 return result;
239}
240
241static std::string get_ce_key_current_path(const std::string& directory_path) {
242LOG(INFO) << "get_ce_key_current_path: " << directory_path + "/current\n";
243 return directory_path + "/current";
244}
245
246// Discard all keys but the named one; rename it to canonical name.
247// No point in acting on errors in this; ignore them.
248static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix,
249 const std::vector<std::string>& paths) {
250 for (auto const other_path: paths) {
251 if (other_path != to_fix) {
252 android::vold::destroyKey(other_path);
253 }
254 }
255 auto const current_path = get_ce_key_current_path(directory_path);
256 if (to_fix != current_path) {
257 LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
258 if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
259 PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
260 }
261 }
262}
263
264static bool read_and_fixate_user_ce_key(userid_t user_id,
265 const android::vold::KeyAuthentication& auth,
266 std::string *ce_key) {
267 auto const directory_path = get_ce_key_directory_path(user_id);
268 auto const paths = get_ce_key_paths(directory_path);
269 for (auto const ce_key_path: paths) {
270 LOG(DEBUG) << "Trying user CE key " << ce_key_path;
271 if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
272 LOG(DEBUG) << "Successfully retrieved key";
273 fixate_user_ce_key(directory_path, ce_key_path, paths);
274 return true;
275 }
276 }
277 LOG(ERROR) << "Failed to find working ce key for user " << user_id;
278 return false;
279}
280
281static bool read_and_install_user_ce_key(userid_t user_id,
282 const android::vold::KeyAuthentication& auth) {
283 if (s_ce_key_raw_refs.count(user_id) != 0) return true;
284 std::string ce_key;
285 if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
286 std::string ce_raw_ref;
287 if (!install_key(ce_key, &ce_raw_ref)) return false;
288 s_ce_keys[user_id] = ce_key;
289 s_ce_key_raw_refs[user_id] = ce_raw_ref;
290 LOG(DEBUG) << "Installed ce key for user " << user_id;
291 return true;
292}
293
294static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
295 LOG(DEBUG) << "Preparing: " << dir << "\n";
296 return true;
297 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
298 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
299 PLOG(ERROR) << "Failed to prepare " << dir;
300 return false;
301 }
302 return true;
303}
304
305static bool path_exists(const std::string& path) {
306 return access(path.c_str(), F_OK) == 0;
307}
308
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600309bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600310 std::string* raw_ref) {
311 auto refi = key_map.find(user_id);
312 if (refi == key_map.end()) {
313 LOG(ERROR) << "Cannot find key for " << user_id;
314 return false;
315 }
316 *raw_ref = refi->second;
317 return true;
318}
319
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600320static bool is_numeric(const char* name) {
321 for (const char* p = name; *p != '\0'; p++) {
322 if (!isdigit(*p)) return false;
323 }
324 return true;
325}
326
327static bool load_all_de_keys() {
328 auto de_dir = user_key_dir + "/de";
329 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
330 if (!dirp) {
331 PLOG(ERROR) << "Unable to read de key directory";
332 return false;
333 }
334 for (;;) {
335 errno = 0;
336 auto entry = readdir(dirp.get());
337 if (!entry) {
338 if (errno) {
339 PLOG(ERROR) << "Unable to read de key directory";
340 return false;
341 }
342 break;
343 }
344 if (entry->d_type != DT_DIR || !is_numeric(entry->d_name)) {
345 LOG(DEBUG) << "Skipping non-de-key " << entry->d_name;
346 continue;
347 }
348 userid_t user_id = atoi(entry->d_name);
349 if (s_de_key_raw_refs.count(user_id) == 0) {
350 auto key_path = de_dir + "/" + entry->d_name;
351 std::string key;
352 if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
353 std::string raw_ref;
354 if (!install_key(key, &raw_ref)) return false;
355 s_de_key_raw_refs[user_id] = raw_ref;
356 LOG(DEBUG) << "Installed de key for user " << user_id;
Noah Jacobson5a79f672019-04-28 00:10:07 -0400357
358 std::string user_prop = "twrp.user." + std::to_string(user_id) + ".decrypt";
359 property_set(user_prop.c_str(), "0");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600360 }
361 }
362 // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
363 // correct policy set on them, and that no rogue ones exist.
364 return true;
365}
366
367bool e4crypt_initialize_global_de() {
368
369 if (s_global_de_initialized) {
370 LOG(INFO) << "Already initialized\n";
371 return true;
372 }
373
374 std::string device_key;
375 if (path_exists(device_key_path)) {
376 if (!android::vold::retrieveKey(device_key_path,
377 kEmptyAuthentication, &device_key)) return false;
378 } else {
379 LOG(INFO) << "NOT Creating new key\n";
380 return false;
381 }
382
383 std::string device_key_ref;
384 if (!install_key(device_key, &device_key_ref)) {
385 LOG(ERROR) << "Failed to install device key\n";
386 return false;
387 }
388
389 s_global_de_initialized = true;
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600390 de_raw_ref = device_key_ref;
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600391 return true;
392}
393
394bool e4crypt_init_user0() {
395 if (e4crypt_is_native()) {
396 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
397 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
398 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
399 if (!path_exists(get_de_key_path(0))) {
400 //if (!create_and_install_user_keys(0, false)) return false;
401 printf("de key path not found\n");
402 return false;
403 }
404 // TODO: switch to loading only DE_0 here once framework makes
405 // explicit calls to install DE keys for secondary users
406 if (!load_all_de_keys()) return false;
407 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600408
409 // If this is a non-FBE device that recently left an emulated mode,
410 // restore user data directories to known-good state.
411 if (!e4crypt_is_native() && !e4crypt_is_emulated()) {
412 e4crypt_unlock_user_key(0, 0, "!", "!");
413 }
414
415 return true;
416}
417
418static bool parse_hex(const char* hex, std::string* result) {
419 if (strcmp("!", hex) == 0) {
420 *result = "";
421 return true;
422 }
423 if (android::vold::HexToStr(hex, *result) != 0) {
424 LOG(ERROR) << "Invalid FBE hex string"; // Don't log the string for security reasons
425 return false;
426 }
427 return true;
428}
429
430// TODO: rename to 'install' for consistency, and take flags to know which keys to install
Ethan Yonker58f21322018-08-24 11:17:36 -0500431bool e4crypt_unlock_user_key(userid_t user_id, int serial __unused, const char* token_hex,
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600432 const char* secret_hex) {
433 if (e4crypt_is_native()) {
434 if (s_ce_key_raw_refs.count(user_id) != 0) {
435 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
436 return true;
437 }
438 std::string token, secret;
439 if (!parse_hex(token_hex, &token)) return false;
440 if (!parse_hex(secret_hex, &secret)) return false;
441 android::vold::KeyAuthentication auth(token, secret);
442 if (!read_and_install_user_ce_key(user_id, auth)) {
443 LOG(ERROR) << "Couldn't read key for " << user_id;
444 return false;
445 }
446 } else {
447 printf("Emulation mode not supported in TWRP\n");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600448 }
449 return true;
450}