blob: 48b4ec963e7a95838c7d3c4b3d24d3f5a0af3535 [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
Peter Cai90edd2e2019-05-23 16:32:22 +080019#include "Keymaster4.h"
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050020#include "KeyStorage4.h"
21#include "KeyUtil.h"
22#include "Utils.h"
23#include "Decrypt.h"
24//#include "VoldUtil.h"
25
26#include <algorithm>
27#include <map>
28#include <set>
29#include <sstream>
30#include <string>
31#include <vector>
32
33#include <dirent.h>
34#include <errno.h>
35#include <fcntl.h>
36#include <unistd.h>
37#include <limits.h>
38#include <selinux/android.h>
39#include <sys/mount.h>
40#include <sys/stat.h>
41#include <sys/types.h>
42
43#include <private/android_filesystem_config.h>
44
45//#include "android/os/IVold.h"
46
47//#include "cryptfs.h"
48
49#define EMULATED_USES_SELINUX 0
50#define MANAGE_MISC_DIRS 0
51
52#include <cutils/fs.h>
53#include <cutils/properties.h>
54
55#include <ext4_utils/ext4_crypt.h>
56#include <keyutils.h>
57
58#include <android-base/file.h>
59//#include <android-base/logging.h>
60#include <android-base/properties.h>
61#include <android-base/stringprintf.h>
62
63#include <iostream>
64#define LOG(x) std::cout
65#define PLOG(x) std::cout
66#define DATA_MNT_POINT "/data"
67
68using android::base::StringPrintf;
69using android::base::WriteStringToFile;
70using android::vold::kEmptyAuthentication;
71using android::vold::KeyBuffer;
Peter Cai90edd2e2019-05-23 16:32:22 +080072using android::vold::Keymaster;
73using android::hardware::keymaster::V4_0::KeyFormat;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050074
75// Store main DE raw ref / policy
76std::string de_raw_ref;
77// Map user ids to key references
78std::map<userid_t, std::string> s_de_key_raw_refs;
79std::map<userid_t, std::string> s_ce_key_raw_refs;
80// TODO abolish this map, per b/26948053
81std::map<userid_t, KeyBuffer> s_ce_keys;
82
83namespace {
84
85struct PolicyKeyRef {
86 std::string contents_mode;
87 std::string filenames_mode;
88 std::string key_raw_ref;
89};
90
91const std::string device_key_dir = std::string() + DATA_MNT_POINT + e4crypt_unencrypted_folder;
92const std::string device_key_path = device_key_dir + "/key";
93const std::string device_key_temp = device_key_dir + "/temp";
94
95const std::string user_key_dir = std::string() + DATA_MNT_POINT + "/misc/vold/user_keys";
96const std::string user_key_temp = user_key_dir + "/temp";
97const std::string prepare_subdirs_path = "/system/bin/vold_prepare_subdirs";
98
99const std::string systemwide_volume_key_dir =
100 std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
101
102bool s_global_de_initialized = false;
103
104// Some users are ephemeral, don't try to wipe their keys from disk
105std::set<userid_t> s_ephemeral_users;
106
107}
108
109static bool e4crypt_is_emulated() {
110 return property_get_bool("persist.sys.emulate_fbe", false);
111}
112
Noah Jacobson81d638d2019-04-28 00:10:07 -0400113/*static const char* escape_empty(const std::string& value) {
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500114 return value.empty() ? "null" : value.c_str();
Noah Jacobson81d638d2019-04-28 00:10:07 -0400115}*/
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500116
117static std::string get_de_key_path(userid_t user_id) {
118 return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
119}
120
121static std::string get_ce_key_directory_path(userid_t user_id) {
122 return StringPrintf("%s/ce/%d", user_key_dir.c_str(), user_id);
123}
124
125// Returns the keys newest first
126static std::vector<std::string> get_ce_key_paths(const std::string& directory_path) {
127 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
128 if (!dirp) {
129 PLOG(ERROR) << "Unable to open ce key directory: " + directory_path << std::endl;
130 return std::vector<std::string>();
131 }
132 std::vector<std::string> result;
133 for (;;) {
134 errno = 0;
135 auto const entry = readdir(dirp.get());
136 if (!entry) {
137 if (errno) {
138 PLOG(ERROR) << "Unable to read ce key directory: " + directory_path << std::endl;
139 return std::vector<std::string>();
140 }
141 break;
142 }
143 if (entry->d_type != DT_DIR || entry->d_name[0] != 'c') {
144 LOG(DEBUG) << "Skipping non-key " << entry->d_name << std::endl;
145 continue;
146 }
147 result.emplace_back(directory_path + "/" + entry->d_name);
148 }
149 std::sort(result.begin(), result.end());
150 std::reverse(result.begin(), result.end());
151 return result;
152}
153
154static std::string get_ce_key_current_path(const std::string& directory_path) {
155 return directory_path + "/current";
156}
157
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500158// Discard all keys but the named one; rename it to canonical name.
159// No point in acting on errors in this; ignore them.
160static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix,
161 const std::vector<std::string>& paths) {
162 for (auto const other_path: paths) {
163 if (other_path != to_fix) {
164 android::vold::destroyKey(other_path);
165 }
166 }
167 auto const current_path = get_ce_key_current_path(directory_path);
168 if (to_fix != current_path) {
169 LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path << std::endl;
170 if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
171 PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path << std::endl;
172 }
173 }
174}
175
176static bool read_and_fixate_user_ce_key(userid_t user_id,
177 const android::vold::KeyAuthentication& auth,
178 KeyBuffer *ce_key) {
179 auto const directory_path = get_ce_key_directory_path(user_id);
180 auto const paths = get_ce_key_paths(directory_path);
181 for (auto const ce_key_path: paths) {
182 LOG(DEBUG) << "Trying user CE key " << ce_key_path << std::endl;
183 if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
184 LOG(DEBUG) << "Successfully retrieved key" << std::endl;
185 fixate_user_ce_key(directory_path, ce_key_path, paths);
186 return true;
187 }
188 }
189 LOG(ERROR) << "Failed to find working ce key for user " << user_id << std::endl;
190 return false;
191}
192
Peter Cai90edd2e2019-05-23 16:32:22 +0800193static bool is_wrapped_key_supported_common(const std::string& mount_point) {
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400194 LOG(DEBUG) << "Determining wrapped-key support for " << mount_point << std::endl;
Peter Cai90edd2e2019-05-23 16:32:22 +0800195 std::string wrapped_key_supported = android::base::GetProperty("fbe.data.wrappedkey", "false");
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400196 LOG(DEBUG) << "fbe.data.wrappedkey = " << wrapped_key_supported << std::endl;
Peter Cai90edd2e2019-05-23 16:32:22 +0800197 if (mount_point == DATA_MNT_POINT && wrapped_key_supported == "true") {
bigbiff bigbiff0be03b32019-08-27 20:50:31 -0400198 LOG(DEBUG) << "Wrapped key supported on " << mount_point << std::endl;
Peter Cai90edd2e2019-05-23 16:32:22 +0800199 return true;
200 } else {
201 return false;
202 }
203}
204
205bool is_wrapped_key_supported() {
206 return is_wrapped_key_supported_common(DATA_MNT_POINT);
207}
208
209bool is_wrapped_key_supported_external() {
210 return false;
211}
212
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500213static bool read_and_install_user_ce_key(userid_t user_id,
214 const android::vold::KeyAuthentication& auth) {
215 if (s_ce_key_raw_refs.count(user_id) != 0) return true;
216 KeyBuffer ce_key;
217 if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
218 std::string ce_raw_ref;
Peter Cai90edd2e2019-05-23 16:32:22 +0800219
220 if (is_wrapped_key_supported()) {
221 KeyBuffer ephemeral_wrapped_key;
222 if (!getEphemeralWrappedKey(KeyFormat::RAW, ce_key, &ephemeral_wrapped_key)) {
223 LOG(ERROR) << "Failed to export ce key";
224 return false;
225 }
226
227 ce_key = std::move(ephemeral_wrapped_key);
228 }
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500229 if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
230 s_ce_keys[user_id] = std::move(ce_key);
231 s_ce_key_raw_refs[user_id] = ce_raw_ref;
232 LOG(DEBUG) << "Installed ce key for user " << user_id << std::endl;
233 return true;
234}
235
236static bool prepare_dir(const std::string& dir, mode_t mode, uid_t uid, gid_t gid) {
237 LOG(DEBUG) << "Preparing: " << dir << std::endl;
238 if (fs_prepare_dir(dir.c_str(), mode, uid, gid) != 0) {
239 PLOG(ERROR) << "Failed to prepare " << dir << std::endl;
240 return false;
241 }
242 return true;
243}
244
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500245// NB this assumes that there is only one thread listening for crypt commands, because
246// it creates keys in a fixed location.
247static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
248 /*KeyBuffer de_key, ce_key;
249 if (!android::vold::randomKey(&de_key)) return false;
250 if (!android::vold::randomKey(&ce_key)) return false;
251 if (create_ephemeral) {
252 // If the key should be created as ephemeral, don't store it.
253 s_ephemeral_users.insert(user_id);
254 } else {
255 auto const directory_path = get_ce_key_directory_path(user_id);
256 if (!prepare_dir(directory_path, 0700, AID_ROOT, AID_ROOT)) return false;
257 auto const paths = get_ce_key_paths(directory_path);
258 std::string ce_key_path;
259 if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
260 if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp,
261 kEmptyAuthentication, ce_key)) return false;
262 fixate_user_ce_key(directory_path, ce_key_path, paths);
263 // Write DE key second; once this is written, all is good.
264 if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
265 kEmptyAuthentication, de_key)) return false;
266 }
267 std::string de_raw_ref;
268 if (!android::vold::installKey(de_key, &de_raw_ref)) return false;
269 s_de_key_raw_refs[user_id] = de_raw_ref;
270 std::string ce_raw_ref;
271 if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
272 s_ce_keys[user_id] = ce_key;
273 s_ce_key_raw_refs[user_id] = ce_raw_ref;
274 LOG(DEBUG) << "Created keys for user " << user_id;*/
275 LOG(DEBUG) << "TWRP not doing create_and_install_user_keys\n";
276 return true;
277}
278
279bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
280 std::string* raw_ref) {
281 auto refi = key_map.find(user_id);
282 if (refi == key_map.end()) {
283 LOG(ERROR) << "Cannot find key for " << user_id << std::endl;
284 return false;
285 }
286 *raw_ref = refi->second;
287 return true;
288}
289
290static void get_data_file_encryption_modes(PolicyKeyRef* key_ref) {
291 /*struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
292 char const* contents_mode = strdup("ice");
293 char const* filenames_mode = strdup("aes-256-heh");
294 fs_mgr_get_file_encryption_modes(rec, &contents_mode, &filenames_mode);
295 key_ref->contents_mode = contents_mode;
296 key_ref->filenames_mode = filenames_mode;*/
297 LOG(INFO) << "contents mode '" << android::base::GetProperty("fbe.contents", "aes-256-xts") << "' filenames '" << android::base::GetProperty("fbe.filenames", "aes-256-heh") << "'\n";
298 key_ref->contents_mode =
299 android::base::GetProperty("fbe.contents", "aes-256-xts");
300 key_ref->filenames_mode =
301 android::base::GetProperty("fbe.filenames", "aes-256-heh");
302}
303
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500304static 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;
Peter Cai90edd2e2019-05-23 16:32:22 +0800338 if (is_wrapped_key_supported()) {
339 KeyBuffer ephemeral_wrapped_key;
340 if (!getEphemeralWrappedKey(KeyFormat::RAW, key, &ephemeral_wrapped_key)) {
341 LOG(ERROR) << "Failed to export de_key in create_and_install_user_keys";
342 return false;
343 }
344 key = std::move(ephemeral_wrapped_key);
345 }
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500346 if (!android::vold::installKey(key, &raw_ref)) return false;
347 s_de_key_raw_refs[user_id] = raw_ref;
348 LOG(DEBUG) << "Installed de key for user " << user_id << std::endl;
Noah Jacobson81d638d2019-04-28 00:10:07 -0400349
350 std::string user_prop = "twrp.user." + std::to_string(user_id) + ".decrypt";
351 property_set(user_prop.c_str(), "0");
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500352 }
353 }
354 // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
355 // correct policy set on them, and that no rogue ones exist.
356 return true;
357}
358
359bool e4crypt_initialize_global_de() {
360 LOG(INFO) << "e4crypt_initialize_global_de" << std::endl;
Peter Cai90edd2e2019-05-23 16:32:22 +0800361 bool wrapped_key_supported = false;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500362
363 if (s_global_de_initialized) {
364 LOG(INFO) << "Already initialized" << std::endl;
365 return true;
366 }
367
368 PolicyKeyRef device_ref;
Peter Cai90edd2e2019-05-23 16:32:22 +0800369 wrapped_key_supported = is_wrapped_key_supported();
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500370 LOG(INFO) << "calling retrieveAndInstallKey\n";
371 if (!android::vold::retrieveAndInstallKey(true, kEmptyAuthentication, device_key_path,
Peter Cai90edd2e2019-05-23 16:32:22 +0800372 device_key_temp, &device_ref.key_raw_ref, wrapped_key_supported))
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500373 return false;
374 get_data_file_encryption_modes(&device_ref);
375
376 std::string modestring = device_ref.contents_mode + ":" + device_ref.filenames_mode;
377 std::string mode_filename = std::string("/data") + e4crypt_key_mode;
378 if (!android::base::WriteStringToFile(modestring, mode_filename)) {
379 PLOG(ERROR) << "Cannot save type" << std::endl;
380 return false;
381 }
382
383 std::string ref_filename = std::string("/data") + e4crypt_key_ref;
384 if (!android::base::WriteStringToFile(device_ref.key_raw_ref, ref_filename)) {
385 PLOG(ERROR) << "Cannot save key reference to:" << ref_filename << std::endl;
386 return false;
387 }
388 LOG(INFO) << "Wrote system DE key reference to:" << ref_filename << std::endl;
389
390 s_global_de_initialized = true;
391 de_raw_ref = device_ref.key_raw_ref;
392 return true;
393}
394
395bool e4crypt_init_user0() {
396 LOG(DEBUG) << "e4crypt_init_user0\n";
397 if (e4crypt_is_native()) {
398 if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
399 if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
400 if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
401 if (!android::vold::pathExists(get_de_key_path(0))) {
402 if (!create_and_install_user_keys(0, false)) 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 Yonkere9afc3d2018-08-30 15:16:27 -0500408
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
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500418static bool emulated_unlock(const std::string& path, mode_t mode) {
419 if (chmod(path.c_str(), mode) != 0) {
420 PLOG(ERROR) << "Failed to chmod " << path << std::endl;
421 // FIXME temporary workaround for b/26713622
422 if (e4crypt_is_emulated()) return false;
423 }
424#if EMULATED_USES_SELINUX
425 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
426 PLOG(WARNING) << "Failed to restorecon " << path << std::endl;
427 // FIXME temporary workaround for b/26713622
428 if (e4crypt_is_emulated()) return false;
429 }
430#endif
431 return true;
432}
433
434static bool parse_hex(const std::string& hex, std::string* result) {
435 if (hex == "!") {
436 *result = "";
437 return true;
438 }
439 if (android::vold::HexToStr(hex, *result) != 0) {
440 LOG(ERROR) << "Invalid FBE hex string" << std::endl; // Don't log the string for security reasons
441 return false;
442 }
443 return true;
444}
445
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500446// TODO: rename to 'install' for consistency, and take flags to know which keys to install
447bool e4crypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
448 const std::string& secret_hex) {
449 LOG(DEBUG) << "e4crypt_unlock_user_key " << user_id << " serial=" << serial
450 << " token_present=" << (token_hex != "!") << std::endl;
451 if (e4crypt_is_native()) {
452 if (s_ce_key_raw_refs.count(user_id) != 0) {
453 LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id << std::endl;
454 return true;
455 }
456 std::string token, secret;
457 if (!parse_hex(token_hex, &token)) return false;
458 if (!parse_hex(secret_hex, &secret)) return false;
459 android::vold::KeyAuthentication auth(token, secret);
460 if (!read_and_install_user_ce_key(user_id, auth)) {
461 LOG(ERROR) << "Couldn't read key for " << user_id << std::endl;
462 return false;
463 }
464 } else {
465 // When in emulation mode, we just use chmod. However, we also
466 // unlock directories when not in emulation mode, to bring devices
467 // back into a known-good state.
468 if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
469 !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
470 !emulated_unlock(android::vold::BuildDataMediaCePath("", user_id), 0770) ||
471 !emulated_unlock(android::vold::BuildDataUserCePath("", user_id), 0771)) {
472 LOG(ERROR) << "Failed to unlock user " << user_id << std::endl;
473 return false;
474 }
475 }
476 return true;
477}