blob: 3f82aa17af7113da130997e6fe9fe87d47b930ce [file] [log] [blame]
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001/*
2 * Copyright (C) 2016 The Team Win Recovery 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 "Decrypt.h"
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050018#ifdef USE_KEYSTORAGE_4
19#include "Ext4CryptPie.h"
20#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060021#include "Ext4Crypt.h"
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050022#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060023
Ethan Yonker79f88bd2016-12-09 14:52:12 -060024#include <map>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060025#include <string>
26
27#include <errno.h>
28#include <stdio.h>
Ethan Yonker79f88bd2016-12-09 14:52:12 -060029#include <stdlib.h>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060030#include <sys/stat.h>
31#include <sys/types.h>
32
Ethan Yonkerfefe5912017-09-30 22:22:13 -050033#ifndef HAVE_LIBKEYUTILS
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060034#include "key_control.h"
Ethan Yonkerfefe5912017-09-30 22:22:13 -050035#else
36#include <keyutils.h>
37#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060038
Ethan Yonkerfefe5912017-09-30 22:22:13 -050039#ifdef HAVE_SYNTH_PWD_SUPPORT
40#include "Weaver1.h"
41#include "cutils/properties.h"
42
43#include <openssl/sha.h>
44#include <openssl/aes.h>
45#include <openssl/evp.h>
46#include <openssl/rand.h>
47
48#include <dirent.h>
49#include <stdio.h>
50#include <stdint.h>
51#include <string.h>
52#include <sys/types.h>
53#include <fstream>
54
bigbiffd58ba182020-03-23 10:02:29 -040055#include "ext4_crypt.h"
Ethan Yonkerfefe5912017-09-30 22:22:13 -050056
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050057#ifdef USE_KEYSTORAGE_4
bigbiffd58ba182020-03-23 10:02:29 -040058#include <android/hardware/confirmationui/1.0/types.h>
59#include <android/security/BnConfirmationPromptCallback.h>
60#include <android/security/keystore/IKeystoreService.h>
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050061#else
Ethan Yonkerfefe5912017-09-30 22:22:13 -050062#include <keystore/IKeystoreService.h>
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050063#include <keystore/authorization_set.h>
64#endif
Ethan Yonkerfefe5912017-09-30 22:22:13 -050065#include <binder/IPCThreadState.h>
66#include <binder/IServiceManager.h>
67
68#include <keystore/keystore.h>
Ethan Yonkerfefe5912017-09-30 22:22:13 -050069
70#include <algorithm>
71extern "C" {
72#include "crypto_scrypt.h"
73}
74#else
75#include "ext4_crypt.h"
76#endif //ifdef HAVE_SYNTH_PWD_SUPPORT
77
78#ifdef HAVE_GATEKEEPER1
79#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
80#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060081#include <hardware/gatekeeper.h>
Ethan Yonkerfefe5912017-09-30 22:22:13 -050082#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060083#include "HashPassword.h"
84
85#include <android-base/file.h>
86
bigbiffd58ba182020-03-23 10:02:29 -040087#ifdef USE_KEYSTORAGE_4
88using android::security::keystore::IKeystoreService;
89#endif
90
Ethan Yonker79f88bd2016-12-09 14:52:12 -060091// Store main DE raw ref / policy
92extern std::string de_raw_ref;
93extern std::map<userid_t, std::string> s_de_key_raw_refs;
94extern std::map<userid_t, std::string> s_ce_key_raw_refs;
95
96static bool lookup_ref_key_internal(std::map<userid_t, std::string>& key_map, const char* policy, userid_t* user_id) {
97 for (std::map<userid_t, std::string>::iterator it=key_map.begin(); it!=key_map.end(); ++it) {
98 if (strncmp(it->second.c_str(), policy, it->second.size()) == 0) {
99 *user_id = it->first;
100 return true;
101 }
102 }
103 return false;
104}
105
106extern "C" bool lookup_ref_key(const char* policy, char* policy_type) {
107 userid_t user_id = 0;
108 if (strncmp(de_raw_ref.c_str(), policy, de_raw_ref.size()) == 0) {
109 strcpy(policy_type, "1DK");
110 return true;
111 }
112 if (!lookup_ref_key_internal(s_de_key_raw_refs, policy, &user_id)) {
113 if (!lookup_ref_key_internal(s_ce_key_raw_refs, policy, &user_id)) {
114 return false;
115 } else
116 sprintf(policy_type, "1CE%d", user_id);
117 } else
118 sprintf(policy_type, "1DE%d", user_id);
119 return true;
120}
121
122extern "C" bool lookup_ref_tar(const char* policy_type, char* policy) {
123 if (strncmp(policy_type, "1", 1) != 0) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500124 printf("Unexpected version %c\n", policy_type[0]);
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600125 return false;
126 }
127 const char* ptr = policy_type + 1; // skip past the version number
128 if (strncmp(ptr, "DK", 2) == 0) {
129 strncpy(policy, de_raw_ref.data(), de_raw_ref.size());
130 return true;
131 }
132 userid_t user_id = atoi(ptr + 2);
133 std::string raw_ref;
134 if (*ptr == 'D') {
135 if (lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)) {
136 strncpy(policy, raw_ref.data(), raw_ref.size());
137 } else
138 return false;
139 } else if (*ptr == 'C') {
140 if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
141 strncpy(policy, raw_ref.data(), raw_ref.size());
142 } else
143 return false;
144 } else {
145 printf("unknown policy type '%s'\n", policy_type);
146 return false;
147 }
148 return true;
149}
150
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500151#ifndef HAVE_GATEKEEPER1
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600152int gatekeeper_device_initialize(gatekeeper_device_t **dev) {
153 int ret;
154 const hw_module_t *mod;
155 ret = hw_get_module_by_class(GATEKEEPER_HARDWARE_MODULE_ID, NULL, &mod);
156
157 if (ret!=0) {
158 printf("failed to get hw module\n");
159 return ret;
160 }
161
162 ret = gatekeeper_open(mod, dev);
163
164 if (ret!=0)
165 printf("failed to open gatekeeper\n");
166 return ret;
167}
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500168#endif //ifndef HAVE_GATEKEEPER1
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600169
170bool Decrypt_DE() {
171 if (!e4crypt_initialize_global_de()) { // this deals with the overarching device encryption
172 printf("e4crypt_initialize_global_de returned fail\n");
173 return false;
174 }
175 if (!e4crypt_init_user0()) {
176 printf("e4crypt_init_user0 returned fail\n");
177 return false;
178 }
179 return true;
180}
181
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500182#ifdef HAVE_SYNTH_PWD_SUPPORT
183// Crappy functions for debugging, please ignore unless you need to debug
184/*void output_hex(const std::string& in) {
185 const char *buf = in.data();
186 char hex[in.size() * 2 + 1];
187 unsigned int index;
188 for (index = 0; index < in.size(); index++)
189 sprintf(&hex[2 * index], "%02X", buf[index]);
190 printf("%s", hex);
191}
192
193void output_hex(const char* buf, const int size) {
194 char hex[size * 2 + 1];
195 int index;
196 for (index = 0; index < size; index++)
197 sprintf(&hex[2 * index], "%02X", buf[index]);
198 printf("%s", hex);
199}
200
201void output_hex(const unsigned char* buf, const int size) {
202 char hex[size * 2 + 1];
203 int index;
204 for (index = 0; index < size; index++)
205 sprintf(&hex[2 * index], "%02X", buf[index]);
206 printf("%s", hex);
207}
208
209void output_hex(std::vector<uint8_t>* vec) {
210 char hex[3];
211 unsigned int index;
212 for (index = 0; index < vec->size(); index++) {
213 sprintf(&hex[0], "%02X", vec->at(index));
214 printf("%s", hex);
215 }
216}*/
217
218/* An alternative is to use:
219 * sqlite3 /data/system/locksettings.db "SELECT value FROM locksettings WHERE name='sp-handle' AND user=0;"
220 * but we really don't want to include the 1.1MB libsqlite in TWRP. We scan the spblob folder for the
221 * password data file (*.pwd) and get the handle from the filename instead. This is a replacement for
222 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#2017
223 * We never use this data as an actual long. We always use it as a string. */
224bool Find_Handle(const std::string& spblob_path, std::string& handle_str) {
225 DIR* dir = opendir(spblob_path.c_str());
226 if (!dir) {
227 printf("Error opening '%s'\n", spblob_path.c_str());
228 return false;
229 }
230
231 struct dirent* de = 0;
232
233 while ((de = readdir(dir)) != 0) {
234 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
235 continue;
236 size_t len = strlen(de->d_name);
237 if (len <= 4)
238 continue;
239 char* p = de->d_name;
240 p += len - 4;
241 if (strncmp(p, ".pwd", 4) == 0) {
242 handle_str = de->d_name;
243 handle_str = handle_str.substr(0, len - 4);
244 //*handle = strtoull(handle_str.c_str(), 0 , 16);
245 closedir(dir);
246 return true;
247 }
248 }
249 closedir(dir);
250 return false;
251}
252
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500253/* This is the structure of the data in the password data (*.pwd) file which the structure can be found
254 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#187 */
255struct password_data_struct {
256 int password_type;
257 unsigned char scryptN;
258 unsigned char scryptR;
259 unsigned char scryptP;
260 int salt_len;
261 void* salt;
262 int handle_len;
263 void* password_handle;
264};
265
266/* C++ replacement for
267 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#764 */
268bool Get_Password_Data(const std::string& spblob_path, const std::string& handle_str, password_data_struct *pwd) {
269 std::string pwd_file = spblob_path + handle_str + ".pwd";
270 std::string pwd_data;
271 if (!android::base::ReadFileToString(pwd_file, &pwd_data)) {
272 printf("Failed to read '%s'\n", pwd_file.c_str());
273 return false;
274 }
275 //output_hex(pwd_data.data(), pwd_data.size());printf("\n");
276 const int* intptr = (const int*)pwd_data.data();
277 pwd->password_type = *intptr;
278 endianswap(&pwd->password_type);
279 //printf("password type %i\n", pwd->password_type); // 2 was PIN, 1 for pattern, 2 also for password, -1 for default password
280 const unsigned char* byteptr = (const unsigned char*)pwd_data.data() + sizeof(int);
281 pwd->scryptN = *byteptr;
282 byteptr++;
283 pwd->scryptR = *byteptr;
284 byteptr++;
285 pwd->scryptP = *byteptr;
286 byteptr++;
287 intptr = (const int*)byteptr;
288 pwd->salt_len = *intptr;
289 endianswap(&pwd->salt_len);
290 if (pwd->salt_len != 0) {
291 pwd->salt = malloc(pwd->salt_len);
292 if (!pwd->salt) {
293 printf("Get_Password_Data malloc salt\n");
294 return false;
295 }
296 memcpy(pwd->salt, intptr + 1, pwd->salt_len);
Ethan Yonkere131bec2017-12-15 23:48:02 -0600297 intptr++;
298 byteptr = (const unsigned char*)intptr;
299 byteptr += pwd->salt_len;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500300 } else {
301 printf("Get_Password_Data salt_len is 0\n");
302 return false;
303 }
Ethan Yonkere131bec2017-12-15 23:48:02 -0600304 intptr = (const int*)byteptr;
305 pwd->handle_len = *intptr;
306 endianswap(&pwd->handle_len);
307 if (pwd->handle_len != 0) {
308 pwd->password_handle = malloc(pwd->handle_len);
309 if (!pwd->password_handle) {
310 printf("Get_Password_Data malloc password_handle\n");
311 return false;
312 }
313 memcpy(pwd->password_handle, intptr + 1, pwd->handle_len);
314 } else {
315 printf("Get_Password_Data handle_len is 0\n");
316 // Not an error if using weaver
317 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500318 return true;
319}
320
321/* C++ replacement for
322 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#765
323 * called here
324 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1050 */
325bool Get_Password_Token(const password_data_struct *pwd, const std::string& Password, unsigned char* password_token) {
326 if (!password_token) {
327 printf("password_token is null\n");
328 return false;
329 }
330 unsigned int N = 1 << pwd->scryptN;
331 unsigned int r = 1 << pwd->scryptR;
332 unsigned int p = 1 << pwd->scryptP;
333 //printf("N %i r %i p %i\n", N, r, p);
334 int ret = crypto_scrypt(reinterpret_cast<const uint8_t*>(Password.data()), Password.size(),
335 reinterpret_cast<const uint8_t*>(pwd->salt), pwd->salt_len,
336 N, r, p,
337 password_token, 32);
338 if (ret != 0) {
339 printf("scrypt error\n");
340 return false;
341 }
342 return true;
343}
344
345// Data structure for the *.weaver file, see Get_Weaver_Data below
346struct weaver_data_struct {
347 unsigned char version;
348 int slot;
349};
350
351/* C++ replacement for
352 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#501
353 * called here
354 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768 */
355bool Get_Weaver_Data(const std::string& spblob_path, const std::string& handle_str, weaver_data_struct *wd) {
356 std::string weaver_file = spblob_path + handle_str + ".weaver";
357 std::string weaver_data;
358 if (!android::base::ReadFileToString(weaver_file, &weaver_data)) {
359 printf("Failed to read '%s'\n", weaver_file.c_str());
360 return false;
361 }
362 //output_hex(weaver_data.data(), weaver_data.size());printf("\n");
363 const unsigned char* byteptr = (const unsigned char*)weaver_data.data();
364 wd->version = *byteptr;
365 //printf("weaver version %i\n", wd->version);
366 const int* intptr = (const int*)weaver_data.data() + sizeof(unsigned char);
367 wd->slot = *intptr;
368 //endianswap(&wd->slot); not needed
369 //printf("weaver slot %i\n", wd->slot);
370 return true;
371}
372
373namespace android {
374
375// On Android 8.0 for some reason init can't seem to completely stop keystore
376// so we have to kill it too if it doesn't die on its own.
377static void kill_keystore() {
378 DIR* dir = opendir("/proc");
379 if (dir) {
380 struct dirent* de = 0;
381
382 while ((de = readdir(dir)) != 0) {
383 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
384 continue;
385
386 int pid = -1;
387 int ret = sscanf(de->d_name, "%d", &pid);
388
389 if (ret == 1) {
390 char cmdpath[PATH_MAX];
391 sprintf(cmdpath, "/proc/%d/cmdline", pid);
392
393 FILE* file = fopen(cmdpath, "r");
394 size_t task_size = PATH_MAX;
395 char task[PATH_MAX];
396 char* p = task;
397 if (getline(&p, &task_size, file) > 0) {
398 if (strstr(task, "keystore") != 0) {
399 printf("keystore pid %d found, sending kill.\n", pid);
400 kill(pid, SIGINT);
401 usleep(5000);
402 kill(pid, SIGKILL);
403 }
404 }
405 fclose(file);
406 }
407 }
408 closedir(dir);
409 }
410}
411
412// The keystore holds a file open on /data so we have to stop / kill it
413// if we want to be able to unmount /data for things like formatting.
414static void stop_keystore() {
415 printf("Stopping keystore...\n");
416 property_set("ctl.stop", "keystore");
417 usleep(5000);
418 kill_keystore();
419}
420
421/* These next 2 functions try to get the keystore service 50 times because
422 * the keystore is not always ready when TWRP boots */
423sp<IBinder> getKeystoreBinder() {
424 sp<IServiceManager> sm = defaultServiceManager();
425 return sm->getService(String16("android.security.keystore"));
426}
427
428sp<IBinder> getKeystoreBinderRetry() {
429 printf("Starting keystore...\n");
430 property_set("ctl.start", "keystore");
431 int retry_count = 50;
432 sp<IBinder> binder = getKeystoreBinder();
433 while (binder == NULL && retry_count) {
434 printf("Waiting for keystore service... %i\n", retry_count--);
435 sleep(1);
436 binder = getKeystoreBinder();
437 }
438 return binder;
439}
440
441namespace keystore {
442
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600443#define SYNTHETIC_PASSWORD_VERSION_V1 1
Peter Caiea1764c2019-05-23 21:44:35 +0800444#define SYNTHETIC_PASSWORD_VERSION_V2 2
445#define SYNTHETIC_PASSWORD_VERSION_V3 3
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500446#define SYNTHETIC_PASSWORD_PASSWORD_BASED 0
447#define SYNTHETIC_PASSWORD_KEY_PREFIX "USRSKEY_synthetic_password_"
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500448#define USR_PRIVATE_KEY_PREFIX "USRPKEY_synthetic_password_"
449
450static std::string mKey_Prefix;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500451
452/* The keystore alias subid is sometimes the same as the handle, but not always.
453 * In the case of handle 0c5303fd2010fe29, the alias subid used c5303fd2010fe29
454 * without the leading 0. We could try to parse the data from a previous
455 * keystore request, but I think this is an easier solution because there
456 * is little to no documentation on the format of data we get back from
457 * the keystore in this instance. We also want to copy everything to a temp
458 * folder so that any key upgrades that might take place do not actually
459 * upgrade the keys on the data partition. We rename all 1000 uid files to 0
460 * to pass the keystore permission checks. */
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500461bool Find_Keystore_Alias_SubID_And_Prep_Files(const userid_t user_id, std::string& keystoreid, const std::string& handle_str) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500462 char path_c[PATH_MAX];
463 sprintf(path_c, "/data/misc/keystore/user_%d", user_id);
464 char user_dir[PATH_MAX];
465 sprintf(user_dir, "user_%d", user_id);
466 std::string source_path = "/data/misc/keystore/";
467 source_path += user_dir;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500468 std::string handle_sub = handle_str;
469 while (handle_sub.substr(0,1) == "0") {
470 std::string temp = handle_sub.substr(1);
471 handle_sub = temp;
472 }
473 mKey_Prefix = "";
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500474
475 mkdir("/tmp/misc", 0755);
476 mkdir("/tmp/misc/keystore", 0755);
477 std::string destination_path = "/tmp/misc/keystore/";
478 destination_path += user_dir;
479 if (mkdir(destination_path.c_str(), 0755) && errno != EEXIST) {
480 printf("failed to mkdir '%s' %s\n", destination_path.c_str(), strerror(errno));
481 return false;
482 }
483 destination_path += "/";
484
485 DIR* dir = opendir(source_path.c_str());
486 if (!dir) {
487 printf("Error opening '%s'\n", source_path.c_str());
488 return false;
489 }
490 source_path += "/";
491
492 struct dirent* de = 0;
493 size_t prefix_len = strlen(SYNTHETIC_PASSWORD_KEY_PREFIX);
494 bool found_subid = false;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500495 bool has_pkey = false; // PKEY has priority over SKEY
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500496
497 while ((de = readdir(dir)) != 0) {
498 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
499 continue;
500 if (!found_subid) {
501 size_t len = strlen(de->d_name);
502 if (len <= prefix_len)
503 continue;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500504 if (strstr(de->d_name, SYNTHETIC_PASSWORD_KEY_PREFIX) && !has_pkey)
505 mKey_Prefix = SYNTHETIC_PASSWORD_KEY_PREFIX;
506 else if (strstr(de->d_name, USR_PRIVATE_KEY_PREFIX)) {
507 mKey_Prefix = USR_PRIVATE_KEY_PREFIX;
508 has_pkey = true;
509 } else
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500510 continue;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500511 if (strstr(de->d_name, handle_sub.c_str())) {
512 keystoreid = handle_sub;
513 printf("keystoreid matched handle_sub: '%s'\n", keystoreid.c_str());
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500514 found_subid = true;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500515 } else {
516 std::string file = de->d_name;
517 std::size_t found = file.find_last_of("_");
518 if (found != std::string::npos) {
519 keystoreid = file.substr(found + 1);
520 printf("possible keystoreid: '%s'\n", keystoreid.c_str());
521 //found_subid = true; // we'll keep going in hopes that we find a pkey or a match to the handle_sub
522 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500523 }
524 }
525 std::string src = source_path;
526 src += de->d_name;
527 std::ifstream srcif(src.c_str(), std::ios::binary);
528 std::string dst = destination_path;
529 dst += de->d_name;
530 std::size_t source_uid = dst.find("1000");
531 if (source_uid != std::string::npos)
532 dst.replace(source_uid, 4, "0");
533 std::ofstream dstof(dst.c_str(), std::ios::binary);
534 printf("copying '%s' to '%s'\n", src.c_str(), dst.c_str());
535 dstof << srcif.rdbuf();
536 srcif.close();
537 dstof.close();
538 }
539 closedir(dir);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500540 if (!found_subid && !mKey_Prefix.empty() && !keystoreid.empty())
541 found_subid = true;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500542 return found_subid;
543}
544
545/* C++ replacement for function of the same name
546 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#867
547 * returning an empty string indicates an error */
Ethan Yonkere131bec2017-12-15 23:48:02 -0600548std::string unwrapSyntheticPasswordBlob(const std::string& spblob_path, const std::string& handle_str, const userid_t user_id, const void* application_id, const size_t application_id_size, uint32_t auth_token_len) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500549 std::string disk_decryption_secret_key = "";
550
551 std::string keystore_alias_subid;
Noah Jacobson81d638d2019-04-28 00:10:07 -0400552 // Can be stored in user 0, so check for both.
553 if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid, handle_str) &&
554 !Find_Keystore_Alias_SubID_And_Prep_Files(0, keystore_alias_subid, handle_str))
555 {
556 printf("failed to scan keystore alias subid and prep keystore files\n");
557 return disk_decryption_secret_key;
558 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500559
560 // First get the keystore service
Noah Jacobson81d638d2019-04-28 00:10:07 -0400561 sp<IBinder> binder = getKeystoreBinderRetry();
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500562#ifdef USE_KEYSTORAGE_4
bigbiffd58ba182020-03-23 10:02:29 -0400563 sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500564#else
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500565 sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500566#endif
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500567 if (service == NULL) {
568 printf("error: could not connect to keystore service\n");
569 return disk_decryption_secret_key;
570 }
571
Ethan Yonkere131bec2017-12-15 23:48:02 -0600572 if (auth_token_len > 0) {
573 printf("Starting keystore_auth service...\n");
574 property_set("ctl.start", "keystore_auth");
575 }
576
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500577 // Read the data from the .spblob file per: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#869
578 std::string spblob_file = spblob_path + handle_str + ".spblob";
579 std::string spblob_data;
580 if (!android::base::ReadFileToString(spblob_file, &spblob_data)) {
581 printf("Failed to read '%s'\n", spblob_file.c_str());
582 return disk_decryption_secret_key;
583 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600584 unsigned char* byteptr = (unsigned char*)spblob_data.data();
Peter Caiea1764c2019-05-23 21:44:35 +0800585 if (*byteptr != SYNTHETIC_PASSWORD_VERSION_V2 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V1
586 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V3) {
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600587 printf("Unsupported synthetic password version %i\n", *byteptr);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500588 return disk_decryption_secret_key;
589 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600590 const unsigned char* synthetic_password_version = byteptr;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500591 byteptr++;
592 if (*byteptr != SYNTHETIC_PASSWORD_PASSWORD_BASED) {
593 printf("spblob data is not SYNTHETIC_PASSWORD_PASSWORD_BASED\n");
594 return disk_decryption_secret_key;
595 }
596 byteptr++; // Now we're pointing to the blob data itself
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600597 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V1) {
598 printf("spblob v1\n");
599 /* We're now going to handle decryptSPBlob: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#115
600 * Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#879
601 * This small function ends up being quite a headache. The call to get data from the keystore basically is not needed in TWRP at this time.
602 * The keystore data seems to be the serialized data from an entire class in Java. Specifically I think it represents:
603 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
604 * or perhaps
605 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
606 * but the only things we "need" from this keystore are a user ID and the keyAlias which ends up being USRSKEY_synthetic_password_{handle_str}
607 * the latter of which we already have. We may need to figure out how to get the user ID if we ever support decrypting mulitple users.
608 * There are 2 calls to a Java decrypt funcion that is overloaded. These 2 calls go in completely different directions despite the seemingly
609 * similar use of decrypt() and decrypt parameters. To figure out where things were going, I added logging to:
610 * https://android.googlesource.com/platform/libcore/+/android-8.0.0_r23/ojluni/src/main/java/javax/crypto/Cipher.java#2575
611 * Logger.global.severe("Cipher tryCombinations " + prov.getName() + " - " + prov.getInfo());
612 * To make logging work in libcore, import java.util.logging.Logger; and either set a better logging level or modify the framework to log everything
613 * regardless of logging level. This will give you some strings that you can grep for and find the actual crypto provider in use. In our case there were
614 * 2 different providers in use. The first stage to get the intermediate key used:
615 * https://android.googlesource.com/platform/external/conscrypt/+/android-8.0.0_r23/common/src/main/java/org/conscrypt/OpenSSLProvider.java
616 * which is a pretty straight-forward OpenSSL implementation of AES/GCM/NoPadding. */
617 // First we personalize as seen https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#102
618 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
619 if (!personalized_application_id) {
620 printf("malloc personalized_application_id\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600621 return disk_decryption_secret_key;
622 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600623 //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
624 // Now we'll decrypt using openssl AES/GCM/NoPadding
625 OpenSSL_add_all_ciphers();
626 int actual_size=0, final_size=0;
627 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
628 const unsigned char* iv = (const unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
629 //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
630 const unsigned char* cipher_text = (const unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
631 //printf("cipher_text: "); output_hex((const unsigned char*)cipher_text, spblob_data.size() - 2 - 12); printf("\n");
632 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
633 //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
634 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, iv);
635 std::vector<unsigned char> intermediate_key;
636 intermediate_key.resize(spblob_data.size() - 2 - 12, '\0');
637 EVP_DecryptUpdate(d_ctx, &intermediate_key[0], &actual_size, cipher_text, spblob_data.size() - 2 - 12);
638 unsigned char tag[AES_BLOCK_SIZE];
639 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
640 EVP_DecryptFinal_ex(d_ctx, &intermediate_key[actual_size], &final_size);
641 EVP_CIPHER_CTX_free(d_ctx);
642 free(personalized_application_id);
643 //printf("spblob_data size: %lu actual_size %i, final_size: %i\n", spblob_data.size(), actual_size, final_size);
644 intermediate_key.resize(actual_size + final_size - 16, '\0');// not sure why we have to trim the size by 16 as I don't see where this is done in Java side
645 //printf("intermediate key: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
646
647 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
648 if (auth_token_len > 0) {
649 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
650 if (!auth_result.isOk()) {
651 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
652 printf("keystore error adding auth token\n");
653 return disk_decryption_secret_key;
654 }*/
655 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
656 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
657 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
658 // the /auth_token file never gets deleted.
659 int auth_wait_count = 20;
660 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
661 usleep(5000);
662 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
663 printf("error during keymaster_auth service\n");
664 /* If you are getting this error, make sure that you have the keymaster_auth service defined in your init scripts, preferrably in init.recovery.{ro.hardware}.rc
bigbiffad58e1b2020-07-06 20:24:34 -0400665 * service keystore_auth /system/bin/keystore_auth
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600666 * disabled
667 * oneshot
668 * user system
669 * group root
670 * seclabel u:r:recovery:s0
671 *
672 * And check dmesg for error codes regarding this service if needed. */
673 return disk_decryption_secret_key;
674 }
675 }
676
677 int32_t ret;
678
679 /* We only need a keyAlias which is USRSKEY_synthetic_password_b6f71045af7bd042 which we find and a uid which is -1 or 1000, I forget which
680 * as the key data will be read again by the begin function later via the keystore.
681 * The data is in a hidl_vec format which consists of a type and a value. */
682 /*::keystore::hidl_vec<uint8_t> data;
683 std::string keystoreid = SYNTHETIC_PASSWORD_KEY_PREFIX;
684 keystoreid += handle_str;
685
686 ret = service->get(String16(keystoreid.c_str()), user_id, &data);
687 if (ret < 0) {
688 printf("Could not connect to keystore service %i\n", ret);
689 return disk_decryption_secret_key;
690 } else if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*//*) {
691 printf("keystore error: (%d)\n", /*responses[ret],*//* ret);
692 return disk_decryption_secret_key;
693 } else {
694 printf("keystore returned: "); output_hex(&data[0], data.size()); printf("\n");
695 }*/
696
697 // Now we'll break up the intermediate key into the IV (first 12 bytes) and the cipher text (the rest of it).
698 std::vector<unsigned char> nonce = intermediate_key;
699 nonce.resize(12);
700 intermediate_key.erase (intermediate_key.begin(),intermediate_key.begin()+12);
701 //printf("nonce: "); output_hex((const unsigned char*)nonce.data(), nonce.size()); printf("\n");
702 //printf("cipher text: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
703
704 /* Now we will begin the second decrypt call found in
705 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#122
706 * This time we will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
707 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
708 * First we set some algorithm parameters as seen in two places:
709 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
710 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
711 size_t maclen = 128;
712 ::keystore::AuthorizationSetBuilder begin_params;
713 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
714 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
715 begin_params.Padding(::keystore::PaddingMode::NONE);
716 begin_params.Authorization(::keystore::TAG_NONCE, nonce);
717 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
718 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES);
719 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockMode);
720 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_PADDING, mKeymasterPadding);
721 //keymasterArgs.addUnsignedInt(KeymasterDefs.KM_TAG_MAC_LENGTH, mTagLengthBits);
722 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
723 entropy.resize(0);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500724 std::string keystore_alias = mKey_Prefix;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600725 keystore_alias += keystore_alias_subid;
726 String16 keystore_alias16(keystore_alias.c_str());
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500727#ifdef USE_KEYSTORAGE_4
728 android::hardware::keymaster::V4_0::KeyPurpose purpose = android::hardware::keymaster::V4_0::KeyPurpose::DECRYPT;
729 security::keymaster::OperationResult begin_result;
730 security::keymaster::OperationResult update_result;
731 security::keymaster::OperationResult finish_result;
732 ::android::security::keymaster::KeymasterArguments empty_params;
733 // These parameters are mostly driven by the cipher.init call https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#63
734 service->begin(binder, keystore_alias16, (int32_t)purpose, true, android::security::keymaster::KeymasterArguments(begin_params.hidl_data()), entropy, -1, &begin_result);
735#else
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600736 ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT;
737 OperationResult begin_result;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500738 OperationResult update_result;
739 OperationResult finish_result;
740 ::keystore::hidl_vec<::keystore::KeyParameter> empty_params;
741 empty_params.resize(0);
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600742 // These parameters are mostly driven by the cipher.init call https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#63
743 service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500744#endif
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600745 ret = begin_result.resultCode;
746 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
747 printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret);
748 return disk_decryption_secret_key;
749 } else {
750 //printf("keystore begin operation successful\n");
751 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600752 // The cipher.doFinal call triggers an update to the keystore followed by a finish https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#64
753 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
754 service->update(begin_result.token, empty_params, intermediate_key, &update_result);
755 ret = update_result.resultCode;
756 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
757 printf("keystore update error: (%d)\n", /*responses[ret],*/ ret);
758 return disk_decryption_secret_key;
759 } else {
760 //printf("keystore update operation successful\n");
761 //printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password
762 }
763 // We must use the data in update_data.data before we call finish below or the data will be gone
764 // The payload data from the keystore update is further personalized at https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#153
765 // We now have the disk decryption key!
766 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)&update_result.data[0], update_result.data.size());
767 //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
768 ::keystore::hidl_vec<uint8_t> signature;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600769 service->finish(begin_result.token, empty_params, signature, entropy, &finish_result);
770 ret = finish_result.resultCode;
771 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
772 printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret);
773 return disk_decryption_secret_key;
774 } else {
775 //printf("keystore finish operation successful\n");
776 }
777 stop_keystore();
778 return disk_decryption_secret_key;
Peter Caiea1764c2019-05-23 21:44:35 +0800779 } else if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V2
780 || *synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
781 printf("spblob v2 / v3\n");
782 /* Version 2 / 3 of the spblob is basically the same as version 1, but the order of getting the intermediate key and disk decryption key have been flip-flopped
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600783 * as seen in https://android.googlesource.com/platform/frameworks/base/+/5025791ac6d1538224e19189397de8d71dcb1a12
784 */
785 /* First decrypt call found in
786 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#135
787 * We will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
788 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
789 * First we set some algorithm parameters as seen in two places:
790 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
791 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
792 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
793 if (auth_token_len > 0) {
794 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
795 if (!auth_result.isOk()) {
796 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
797 printf("keystore error adding auth token\n");
798 return disk_decryption_secret_key;
799 }*/
800 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
801 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
802 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
803 // the /auth_token file never gets deleted.
804 int auth_wait_count = 20;
805 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
806 usleep(5000);
807 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
808 printf("error during keymaster_auth service\n");
809 /* If you are getting this error, make sure that you have the keymaster_auth service defined in your init scripts, preferrably in init.recovery.{ro.hardware}.rc
bigbiffad58e1b2020-07-06 20:24:34 -0400810 * service keystore_auth /system/bin/keystore_auth
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600811 * disabled
812 * oneshot
813 * user system
814 * group root
815 * seclabel u:r:recovery:s0
816 *
817 * And check dmesg for error codes regarding this service if needed. */
818 return disk_decryption_secret_key;
819 }
820 }
821 int32_t ret;
822 size_t maclen = 128;
823 unsigned char* iv = (unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
824 ::keystore::hidl_vec<uint8_t> iv_hidlvec;
825 iv_hidlvec.setToExternal((unsigned char*)byteptr, 12);
826 //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
827 unsigned char* cipher_text = (unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
828 ::keystore::hidl_vec<uint8_t> cipher_text_hidlvec;
829 cipher_text_hidlvec.setToExternal(cipher_text, spblob_data.size() - 14 /* 1 each for version and SYNTHETIC_PASSWORD_PASSWORD_BASED and 12 for the iv */);
830 ::keystore::AuthorizationSetBuilder begin_params;
831 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
832 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
833 begin_params.Padding(::keystore::PaddingMode::NONE);
834 begin_params.Authorization(::keystore::TAG_NONCE, iv_hidlvec);
835 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
836 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
837 entropy.resize(0);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500838 std::string keystore_alias = mKey_Prefix;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600839 keystore_alias += keystore_alias_subid;
840 String16 keystore_alias16(keystore_alias.c_str());
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500841#ifdef USE_KEYSTORAGE_4
842 android::hardware::keymaster::V4_0::KeyPurpose purpose = android::hardware::keymaster::V4_0::KeyPurpose::DECRYPT;
843 security::keymaster::OperationResult begin_result;
844 security::keymaster::OperationResult update_result;
845 security::keymaster::OperationResult finish_result;
846 ::android::security::keymaster::KeymasterArguments empty_params;
847 // These parameters are mostly driven by the cipher.init call https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#63
848 service->begin(binder, keystore_alias16, (int32_t)purpose, true, android::security::keymaster::KeymasterArguments(begin_params.hidl_data()), entropy, -1, &begin_result);
849#else
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600850 ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT;
851 OperationResult begin_result;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500852 OperationResult update_result;
853 OperationResult finish_result;
854 ::keystore::hidl_vec<::keystore::KeyParameter> empty_params;
855 empty_params.resize(0);
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600856 // These parameters are mostly driven by the cipher.init call https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#63
857 service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500858#endif
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600859 ret = begin_result.resultCode;
860 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
861 printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret);
862 return disk_decryption_secret_key;
863 } /*else {
864 printf("keystore begin operation successful\n");
865 }*/
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600866 // The cipher.doFinal call triggers an update to the keystore followed by a finish https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#64
867 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
868 service->update(begin_result.token, empty_params, cipher_text_hidlvec, &update_result);
869 ret = update_result.resultCode;
870 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
871 printf("keystore update error: (%d)\n", /*responses[ret],*/ ret);
872 return disk_decryption_secret_key;
873 } /*else {
874 printf("keystore update operation successful\n");
875 printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password
876 }*/
877 //printf("keystore resulting data: "); output_hex((unsigned char*)&update_result.data[0], update_result.data.size()); printf("\n");
878 // We must copy the data in update_data.data before we call finish below or the data will be gone
879 size_t keystore_result_size = update_result.data.size();
880 unsigned char* keystore_result = (unsigned char*)malloc(keystore_result_size);
881 if (!keystore_result) {
882 printf("malloc on keystore_result\n");
883 return disk_decryption_secret_key;
884 }
885 memcpy(keystore_result, &update_result.data[0], update_result.data.size());
886 //printf("keystore_result data: "); output_hex(keystore_result, keystore_result_size); printf("\n");
887 ::keystore::hidl_vec<uint8_t> signature;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600888 service->finish(begin_result.token, empty_params, signature, entropy, &finish_result);
889 ret = finish_result.resultCode;
890 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
891 printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret);
892 free(keystore_result);
893 return disk_decryption_secret_key;
894 } /*else {
895 printf("keystore finish operation successful\n");
896 }*/
897 stop_keystore();
898
899 /* Now we do the second decrypt call as seen in:
900 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#136
901 */
902 const unsigned char* intermediate_iv = keystore_result;
903 //printf("intermediate_iv: "); output_hex((const unsigned char*)intermediate_iv, 12); printf("\n");
904 const unsigned char* intermediate_cipher_text = (const unsigned char*)keystore_result + 12; // The cipher text comes immediately after the IV
905 int cipher_size = keystore_result_size - 12;
906 //printf("intermediate_cipher_text: "); output_hex((const unsigned char*)intermediate_cipher_text, cipher_size); printf("\n");
907 // First we personalize as seen https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#102
908 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
909 if (!personalized_application_id) {
910 printf("malloc personalized_application_id\n");
911 free(keystore_result);
912 return disk_decryption_secret_key;
913 }
914 //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
915 // Now we'll decrypt using openssl AES/GCM/NoPadding
916 OpenSSL_add_all_ciphers();
917 int actual_size=0, final_size=0;
918 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
919 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
920 //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
921 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, intermediate_iv);
922 unsigned char* secret_key = (unsigned char*)malloc(cipher_size);
923 EVP_DecryptUpdate(d_ctx, secret_key, &actual_size, intermediate_cipher_text, cipher_size);
924 unsigned char tag[AES_BLOCK_SIZE];
925 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
926 EVP_DecryptFinal_ex(d_ctx, secret_key + actual_size, &final_size);
927 EVP_CIPHER_CTX_free(d_ctx);
928 free(personalized_application_id);
929 free(keystore_result);
930 int secret_key_real_size = actual_size - 16;
931 //printf("secret key: "); output_hex((const unsigned char*)secret_key, secret_key_real_size); printf("\n");
932 // The payload data from the keystore update is further personalized at https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#153
933 // We now have the disk decryption key!
Peter Caiea1764c2019-05-23 21:44:35 +0800934 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
935 // V3 uses SP800 instead of SHA512
936 disk_decryption_secret_key = PersonalizedHashSP800(PERSONALIZATION_FBE_KEY, PERSONALISATION_CONTEXT, (const char*)secret_key, secret_key_real_size);
937 } else {
938 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)secret_key, secret_key_real_size);
939 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600940 //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
941 free(secret_key);
942 return disk_decryption_secret_key;
Ethan Yonkere131bec2017-12-15 23:48:02 -0600943 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500944 return disk_decryption_secret_key;
945}
946
947}}
948
949#define PASSWORD_TOKEN_SIZE 32
950
Ethan Yonkere131bec2017-12-15 23:48:02 -0600951/* C++ replacement for
952 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#992
953 * called here
954 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#813 */
955bool Get_Secdis(const std::string& spblob_path, const std::string& handle_str, std::string& secdis_data) {
956 std::string secdis_file = spblob_path + handle_str + ".secdis";
957 if (!android::base::ReadFileToString(secdis_file, &secdis_data)) {
958 printf("Failed to read '%s'\n", secdis_file.c_str());
959 return false;
960 }
961 //output_hex(secdis_data.data(), secdis_data.size());printf("\n");
962 return true;
963}
964
965// C++ replacement for https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1033
966userid_t fakeUid(const userid_t uid) {
967 return 100000 + uid;
968}
969
970bool Is_Weaver(const std::string& spblob_path, const std::string& handle_str) {
971 std::string weaver_file = spblob_path + handle_str + ".weaver";
972 struct stat st;
973 if (stat(weaver_file.c_str(), &st) == 0)
974 return true;
975 return false;
976}
977
978bool Free_Return(bool retval, void* weaver_key, password_data_struct* pwd) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500979 if (weaver_key)
980 free(weaver_key);
Ethan Yonkere131bec2017-12-15 23:48:02 -0600981 if (pwd->salt)
982 free(pwd->salt);
983 if (pwd->password_handle)
984 free(pwd->password_handle);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500985 return retval;
986}
987
988/* Decrypt_User_Synth_Pass is the TWRP C++ equivalent to spBasedDoVerifyCredential
989 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#1998 */
990bool Decrypt_User_Synth_Pass(const userid_t user_id, const std::string& Password) {
991 bool retval = false;
992 void* weaver_key = NULL;
993 password_data_struct pwd;
994 pwd.salt = NULL;
Ethan Yonkere131bec2017-12-15 23:48:02 -0600995 pwd.salt_len = 0;
996 pwd.password_handle = NULL;
997 pwd.handle_len = 0;
998 char application_id[PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH];
999
1000 uint32_t auth_token_len = 0;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001001
1002 std::string secret; // this will be the disk decryption key that is sent to vold
1003 std::string token = "!"; // there is no token used for this kind of decrypt, key escrow is handled by weaver
1004 int flags = FLAG_STORAGE_DE;
1005 if (user_id == 0)
1006 flags = FLAG_STORAGE_DE;
1007 else
1008 flags = FLAG_STORAGE_CE;
1009 char spblob_path_char[PATH_MAX];
1010 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
1011 std::string spblob_path = spblob_path_char;
1012 long handle = 0;
1013 std::string handle_str;
1014 // Get the handle: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#2017
1015 if (!Find_Handle(spblob_path, handle_str)) {
1016 printf("Error getting handle\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001017 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001018 }
1019 printf("Handle is '%s'\n", handle_str.c_str());
1020 // Now we begin driving unwrapPasswordBasedSyntheticPassword from: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#758
1021 // First we read the password data which contains scrypt parameters
1022 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
1023 printf("Failed to Get_Password_Data\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001024 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001025 }
1026 //printf("pwd N %i R %i P %i salt ", pwd.scryptN, pwd.scryptR, pwd.scryptP); output_hex((char*)pwd.salt, pwd.salt_len); printf("\n");
1027 unsigned char password_token[PASSWORD_TOKEN_SIZE];
1028 //printf("Password: '%s'\n", Password.c_str());
1029 // The password token is the password scrypted with the parameters from the password data file
1030 if (!Get_Password_Token(&pwd, Password, &password_token[0])) {
1031 printf("Failed to Get_Password_Token\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001032 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001033 }
1034 //output_hex(&password_token[0], PASSWORD_TOKEN_SIZE);printf("\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001035 if (Is_Weaver(spblob_path, handle_str)) {
1036 printf("using weaver\n");
1037 // BEGIN PIXEL 2 WEAVER
1038 // Get the weaver data from the .weaver file which tells us which slot to use when we ask weaver for the escrowed key
1039 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768
1040 weaver_data_struct wd;
1041 if (!Get_Weaver_Data(spblob_path, handle_str, &wd)) {
1042 printf("Failed to get weaver data\n");
1043 return Free_Return(retval, weaver_key, &pwd);
1044 }
1045 // The weaver key is the the password token prefixed with "weaver-key" padded to 128 with nulls with the password token appended then SHA512
1046 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1059
1047 weaver_key = PersonalizedHashBinary(PERSONALISATION_WEAVER_KEY, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
1048 if (!weaver_key) {
1049 printf("malloc error getting weaver_key\n");
1050 return Free_Return(retval, weaver_key, &pwd);
1051 }
1052 // Now we start driving weaverVerify: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#343
1053 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#776
1054 android::vold::Weaver weaver;
1055 if (!weaver) {
1056 printf("Failed to get weaver service\n");
1057 return Free_Return(retval, weaver_key, &pwd);
1058 }
1059 // Get the key size from weaver service
1060 uint32_t weaver_key_size = 0;
1061 if (!weaver.GetKeySize(&weaver_key_size)) {
1062 printf("Failed to get weaver key size\n");
1063 return Free_Return(retval, weaver_key, &pwd);
1064 } else {
1065 //printf("weaver key size is %u\n", weaver_key_size);
1066 }
1067 //printf("weaver key: "); output_hex((unsigned char*)weaver_key, weaver_key_size); printf("\n");
1068 // Send the slot from the .weaver file, the computed weaver key, and get the escrowed key data
1069 std::vector<uint8_t> weaver_payload;
1070 // TODO: we should return more information about the status including time delays before the next retry
1071 if (!weaver.WeaverVerify(wd.slot, weaver_key, &weaver_payload)) {
1072 printf("failed to weaver verify\n");
1073 return Free_Return(retval, weaver_key, &pwd);
1074 }
1075 //printf("weaver payload: "); output_hex(&weaver_payload); printf("\n");
1076 // Done with weaverVerify
1077 // Now we will compute the application ID
1078 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#964
1079 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#780
1080 // The escrowed weaver key data is prefixed with "weaver-pwd" padded to 128 with nulls with the weaver payload appended then SHA512
1081 void* weaver_secret = PersonalizedHashBinary(PERSONALISATION_WEAVER_PASSWORD, (const char*)weaver_payload.data(), weaver_payload.size());
1082 //printf("weaver secret: "); output_hex((unsigned char*)weaver_secret, SHA512_DIGEST_LENGTH); printf("\n");
1083 // The application ID is the password token and weaver secret appended to each other
1084 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
1085 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], weaver_secret, SHA512_DIGEST_LENGTH);
1086 //printf("application ID: "); output_hex((unsigned char*)application_id, PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH); printf("\n");
1087 // END PIXEL 2 WEAVER
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001088 } else {
Ethan Yonkere131bec2017-12-15 23:48:02 -06001089 printf("using secdis\n");
1090 std::string secdis_data;
1091 if (!Get_Secdis(spblob_path, handle_str, secdis_data)) {
1092 printf("Failed to get secdis data\n");
1093 return Free_Return(retval, weaver_key, &pwd);
1094 }
1095 void* secdiscardable = PersonalizedHashBinary(PERSONALISATION_SECDISCARDABLE, (char*)secdis_data.data(), secdis_data.size());
1096 if (!secdiscardable) {
1097 printf("malloc error getting secdiscardable\n");
1098 return Free_Return(retval, weaver_key, &pwd);
1099 }
1100 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
1101 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], secdiscardable, SHA512_DIGEST_LENGTH);
1102
1103 int ret = -1;
1104 bool request_reenroll = false;
1105 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1106 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1107 if (gk_device == nullptr) {
1108 printf("failed to get gatekeeper service\n");
1109 return Free_Return(retval, weaver_key, &pwd);
1110 }
1111 if (pwd.handle_len <= 0) {
1112 printf("no password handle supplied\n");
1113 return Free_Return(retval, weaver_key, &pwd);
1114 }
1115 android::hardware::hidl_vec<uint8_t> pwd_handle_hidl;
1116 pwd_handle_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)pwd.password_handle), pwd.handle_len);
1117 void* gk_pwd_token = PersonalizedHashBinary(PERSONALIZATION_USER_GK_AUTH, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
1118 if (!gk_pwd_token) {
1119 printf("malloc error getting gatekeeper_key\n");
1120 return Free_Return(retval, weaver_key, &pwd);
1121 }
1122 android::hardware::hidl_vec<uint8_t> gk_pwd_token_hidl;
1123 gk_pwd_token_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)gk_pwd_token), SHA512_DIGEST_LENGTH);
1124 android::hardware::Return<void> hwRet =
1125 gk_device->verify(fakeUid(user_id), 0 /* challange */,
1126 pwd_handle_hidl,
1127 gk_pwd_token_hidl,
1128 [&ret, &request_reenroll, &auth_token_len]
1129 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1130 ret = static_cast<int>(rsp.code); // propagate errors
1131 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1132 auth_token_len = rsp.data.size();
1133 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1134 ret = 0; // all success states are reported as 0
1135 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file here and later
1136 // run a separate service that runs as the system user to add the auth token. We wait for the auth token file to be
1137 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after a while seconds if
1138 // the /auth_token file never gets deleted.
1139 unlink("/auth_token");
1140 FILE* auth_file = fopen("/auth_token","wb");
1141 if (auth_file != NULL) {
1142 fwrite(rsp.data.data(), sizeof(uint8_t), rsp.data.size(), auth_file);
1143 fclose(auth_file);
1144 } else {
1145 printf("failed to open /auth_token for writing\n");
1146 ret = -2;
1147 }
1148 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1149 ret = rsp.timeout;
1150 }
1151 }
1152 );
1153 free(gk_pwd_token);
1154 if (!hwRet.isOk() || ret != 0) {
1155 printf("gatekeeper verification failed\n");
1156 return Free_Return(retval, weaver_key, &pwd);
1157 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001158 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001159 // Now we will handle https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#816
1160 // Plus we will include the last bit that computes the disk decrypt key found in:
1161 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#153
Ethan Yonkere131bec2017-12-15 23:48:02 -06001162 secret = android::keystore::unwrapSyntheticPasswordBlob(spblob_path, handle_str, user_id, (const void*)&application_id[0], PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH, auth_token_len);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001163 if (!secret.size()) {
1164 printf("failed to unwrapSyntheticPasswordBlob\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001165 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001166 }
1167 if (!e4crypt_unlock_user_key(user_id, 0, token.c_str(), secret.c_str())) {
1168 printf("e4crypt_unlock_user_key returned fail\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001169 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001170 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001171/*#ifdef USE_KEYSTORAGE_4
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001172 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1173#else
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001174 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001175#endif
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001176 printf("failed to e4crypt_prepare_user_storage\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001177 return Free_Return(retval, weaver_key, &pwd);
Noah Jacobson81d638d2019-04-28 00:10:07 -04001178 }*/
1179 printf("User %i Decrypted Successfully!\n", user_id);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001180 retval = true;
Ethan Yonkere131bec2017-12-15 23:48:02 -06001181 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001182}
1183#endif //HAVE_SYNTH_PWD_SUPPORT
1184
1185int Get_Password_Type(const userid_t user_id, std::string& filename) {
1186 struct stat st;
1187 char spblob_path_char[PATH_MAX];
1188 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
1189 if (stat(spblob_path_char, &st) == 0) {
1190#ifdef HAVE_SYNTH_PWD_SUPPORT
1191 printf("Using synthetic password method\n");
1192 std::string spblob_path = spblob_path_char;
1193 std::string handle_str;
1194 if (!Find_Handle(spblob_path, handle_str)) {
1195 printf("Error getting handle\n");
1196 return 0;
1197 }
1198 printf("Handle is '%s'\n", handle_str.c_str());
1199 password_data_struct pwd;
1200 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
1201 printf("Failed to Get_Password_Data\n");
1202 return 0;
1203 }
1204 if (pwd.password_type == 1) // In Android this means pattern
1205 return 2; // In TWRP this means pattern
Alexander Sulfrian8dfcf2a2020-12-15 01:58:55 +01001206 // In Android <11 type 2 is PIN or password
1207 // In Android 11 type 3 is PIN and type 4 is password
1208 else if (pwd.password_type > 1)
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001209 return 1; // In TWRP this means PIN or password
1210 return 0; // We'll try the default password
1211#else
1212 printf("Synthetic password support not present in TWRP\n");
1213 return -1;
1214#endif
1215 }
1216 std::string path;
1217 if (user_id == 0) {
1218 path = "/data/system/";
1219 } else {
1220 char user_id_str[5];
1221 sprintf(user_id_str, "%i", user_id);
1222 path = "/data/system/users/";
1223 path += user_id_str;
1224 path += "/";
1225 }
1226 filename = path + "gatekeeper.password.key";
1227 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1228 return 1;
1229 filename = path + "gatekeeper.pattern.key";
1230 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1231 return 2;
1232 printf("Unable to locate gatekeeper password file '%s'\n", filename.c_str());
1233 filename = "";
1234 return 0;
1235}
1236
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001237bool Decrypt_User(const userid_t user_id, const std::string& Password) {
1238 uint8_t *auth_token;
1239 uint32_t auth_token_len;
1240 int ret;
1241
1242 struct stat st;
1243 if (user_id > 9999) {
1244 printf("user_id is too big\n");
1245 return false;
1246 }
1247 std::string filename;
1248 bool Default_Password = (Password == "!");
1249 if (Get_Password_Type(user_id, filename) == 0 && !Default_Password) {
1250 printf("Unknown password type\n");
1251 return false;
1252 }
1253 int flags = FLAG_STORAGE_DE;
1254 if (user_id == 0)
1255 flags = FLAG_STORAGE_DE;
1256 else
1257 flags = FLAG_STORAGE_CE;
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001258 if (Default_Password) {
1259 if (!e4crypt_unlock_user_key(user_id, 0, "!", "!")) {
1260 printf("e4crypt_unlock_user_key returned fail\n");
1261 return false;
1262 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001263/*#ifdef USE_KEYSTORAGE_4
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001264 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1265#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001266 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001267#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001268 printf("failed to e4crypt_prepare_user_storage\n");
1269 return false;
Noah Jacobson81d638d2019-04-28 00:10:07 -04001270 }*/
1271 printf("User %i Decrypted Successfully!\n", user_id);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001272 return true;
1273 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001274 if (stat("/data/system_de/0/spblob", &st) == 0) {
1275#ifdef HAVE_SYNTH_PWD_SUPPORT
1276 printf("Using synthetic password method\n");
1277 return Decrypt_User_Synth_Pass(user_id, Password);
1278#else
1279 printf("Synthetic password support not present in TWRP\n");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001280 return false;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001281#endif
1282 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001283 printf("password filename is '%s'\n", filename.c_str());
1284 if (stat(filename.c_str(), &st) != 0) {
1285 printf("error stat'ing key file: %s\n", strerror(errno));
1286 return false;
1287 }
1288 std::string handle;
1289 if (!android::base::ReadFileToString(filename, &handle)) {
1290 printf("Failed to read '%s'\n", filename.c_str());
1291 return false;
1292 }
1293 bool should_reenroll;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001294#ifdef HAVE_GATEKEEPER1
1295 bool request_reenroll = false;
1296 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1297 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1298 if (gk_device == nullptr)
1299 return false;
1300 android::hardware::hidl_vec<uint8_t> curPwdHandle;
1301 curPwdHandle.setToExternal(const_cast<uint8_t *>((const uint8_t *)handle.c_str()), st.st_size);
1302 android::hardware::hidl_vec<uint8_t> enteredPwd;
1303 enteredPwd.setToExternal(const_cast<uint8_t *>((const uint8_t *)Password.c_str()), Password.size());
1304
1305 android::hardware::Return<void> hwRet =
1306 gk_device->verify(user_id, 0 /* challange */,
1307 curPwdHandle,
1308 enteredPwd,
1309 [&ret, &request_reenroll, &auth_token, &auth_token_len]
1310 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1311 ret = static_cast<int>(rsp.code); // propagate errors
1312 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1313 auth_token = new uint8_t[rsp.data.size()];
1314 auth_token_len = rsp.data.size();
1315 memcpy(auth_token, rsp.data.data(), auth_token_len);
1316 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1317 ret = 0; // all success states are reported as 0
1318 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1319 ret = rsp.timeout;
1320 }
1321 }
1322 );
1323 if (!hwRet.isOk()) {
1324 return false;
1325 }
1326#else
1327 gatekeeper_device_t *gk_device;
1328 ret = gatekeeper_device_initialize(&gk_device);
1329 if (ret!=0)
1330 return false;
1331 ret = gk_device->verify(gk_device, user_id, 0, (const uint8_t *)handle.c_str(), st.st_size,
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001332 (const uint8_t *)Password.c_str(), (uint32_t)Password.size(), &auth_token, &auth_token_len,
1333 &should_reenroll);
1334 if (ret !=0) {
1335 printf("failed to verify\n");
1336 return false;
1337 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001338#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001339 char token_hex[(auth_token_len*2)+1];
1340 token_hex[(auth_token_len*2)] = 0;
1341 uint32_t i;
1342 for (i=0;i<auth_token_len;i++) {
1343 sprintf(&token_hex[2*i], "%02X", auth_token[i]);
1344 }
1345 // The secret is "Android FBE credential hash" plus appended 0x00 to reach 128 bytes then append the user's password then feed that to sha512sum
1346 std::string secret = HashPassword(Password);
1347 if (!e4crypt_unlock_user_key(user_id, 0, token_hex, secret.c_str())) {
1348 printf("e4crypt_unlock_user_key returned fail\n");
1349 return false;
1350 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001351/*#ifdef USE_KEYSTORAGE_4
codeworkx22e3aa92019-04-23 12:02:26 +02001352 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1353#else
1354 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
1355#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001356 printf("failed to e4crypt_prepare_user_storage\n");
1357 return false;
Noah Jacobson81d638d2019-04-28 00:10:07 -04001358 }*/
1359 printf("User %i Decrypted Successfully!\n", user_id);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001360 return true;
1361}