blob: 2dab1664616a6cf1b9ae94c1757b7411b2cc324a [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"
18#include "Ext4Crypt.h"
19
Ethan Yonker79f88bd2016-12-09 14:52:12 -060020#include <map>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060021#include <string>
22
23#include <errno.h>
24#include <stdio.h>
Ethan Yonker79f88bd2016-12-09 14:52:12 -060025#include <stdlib.h>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060026#include <sys/stat.h>
27#include <sys/types.h>
28
Ethan Yonkerfefe5912017-09-30 22:22:13 -050029#ifndef HAVE_LIBKEYUTILS
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060030#include "key_control.h"
Ethan Yonkerfefe5912017-09-30 22:22:13 -050031#else
32#include <keyutils.h>
33#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060034
Ethan Yonkerfefe5912017-09-30 22:22:13 -050035#ifdef HAVE_SYNTH_PWD_SUPPORT
36#include "Weaver1.h"
37#include "cutils/properties.h"
38
39#include <openssl/sha.h>
40#include <openssl/aes.h>
41#include <openssl/evp.h>
42#include <openssl/rand.h>
43
44#include <dirent.h>
45#include <stdio.h>
46#include <stdint.h>
47#include <string.h>
48#include <sys/types.h>
49#include <fstream>
50
51#include <ext4_utils/ext4_crypt.h>
52
53#include <keystore/IKeystoreService.h>
54#include <binder/IPCThreadState.h>
55#include <binder/IServiceManager.h>
56
57#include <keystore/keystore.h>
58#include <keystore/authorization_set.h>
59
60#include <algorithm>
61extern "C" {
62#include "crypto_scrypt.h"
63}
64#else
65#include "ext4_crypt.h"
66#endif //ifdef HAVE_SYNTH_PWD_SUPPORT
67
68#ifdef HAVE_GATEKEEPER1
69#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
70#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060071#include <hardware/gatekeeper.h>
Ethan Yonkerfefe5912017-09-30 22:22:13 -050072#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060073#include "HashPassword.h"
74
75#include <android-base/file.h>
76
Ethan Yonker79f88bd2016-12-09 14:52:12 -060077// Store main DE raw ref / policy
78extern std::string de_raw_ref;
79extern std::map<userid_t, std::string> s_de_key_raw_refs;
80extern std::map<userid_t, std::string> s_ce_key_raw_refs;
81
82static bool lookup_ref_key_internal(std::map<userid_t, std::string>& key_map, const char* policy, userid_t* user_id) {
83 for (std::map<userid_t, std::string>::iterator it=key_map.begin(); it!=key_map.end(); ++it) {
84 if (strncmp(it->second.c_str(), policy, it->second.size()) == 0) {
85 *user_id = it->first;
86 return true;
87 }
88 }
89 return false;
90}
91
92extern "C" bool lookup_ref_key(const char* policy, char* policy_type) {
93 userid_t user_id = 0;
94 if (strncmp(de_raw_ref.c_str(), policy, de_raw_ref.size()) == 0) {
95 strcpy(policy_type, "1DK");
96 return true;
97 }
98 if (!lookup_ref_key_internal(s_de_key_raw_refs, policy, &user_id)) {
99 if (!lookup_ref_key_internal(s_ce_key_raw_refs, policy, &user_id)) {
100 return false;
101 } else
102 sprintf(policy_type, "1CE%d", user_id);
103 } else
104 sprintf(policy_type, "1DE%d", user_id);
105 return true;
106}
107
108extern "C" bool lookup_ref_tar(const char* policy_type, char* policy) {
109 if (strncmp(policy_type, "1", 1) != 0) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500110 printf("Unexpected version %c\n", policy_type[0]);
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600111 return false;
112 }
113 const char* ptr = policy_type + 1; // skip past the version number
114 if (strncmp(ptr, "DK", 2) == 0) {
115 strncpy(policy, de_raw_ref.data(), de_raw_ref.size());
116 return true;
117 }
118 userid_t user_id = atoi(ptr + 2);
119 std::string raw_ref;
120 if (*ptr == 'D') {
121 if (lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)) {
122 strncpy(policy, raw_ref.data(), raw_ref.size());
123 } else
124 return false;
125 } else if (*ptr == 'C') {
126 if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
127 strncpy(policy, raw_ref.data(), raw_ref.size());
128 } else
129 return false;
130 } else {
131 printf("unknown policy type '%s'\n", policy_type);
132 return false;
133 }
134 return true;
135}
136
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500137#ifndef HAVE_GATEKEEPER1
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600138int gatekeeper_device_initialize(gatekeeper_device_t **dev) {
139 int ret;
140 const hw_module_t *mod;
141 ret = hw_get_module_by_class(GATEKEEPER_HARDWARE_MODULE_ID, NULL, &mod);
142
143 if (ret!=0) {
144 printf("failed to get hw module\n");
145 return ret;
146 }
147
148 ret = gatekeeper_open(mod, dev);
149
150 if (ret!=0)
151 printf("failed to open gatekeeper\n");
152 return ret;
153}
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500154#endif //ifndef HAVE_GATEKEEPER1
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600155
156bool Decrypt_DE() {
157 if (!e4crypt_initialize_global_de()) { // this deals with the overarching device encryption
158 printf("e4crypt_initialize_global_de returned fail\n");
159 return false;
160 }
161 if (!e4crypt_init_user0()) {
162 printf("e4crypt_init_user0 returned fail\n");
163 return false;
164 }
165 return true;
166}
167
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500168#ifdef HAVE_SYNTH_PWD_SUPPORT
169// Crappy functions for debugging, please ignore unless you need to debug
170/*void output_hex(const std::string& in) {
171 const char *buf = in.data();
172 char hex[in.size() * 2 + 1];
173 unsigned int index;
174 for (index = 0; index < in.size(); index++)
175 sprintf(&hex[2 * index], "%02X", buf[index]);
176 printf("%s", hex);
177}
178
179void output_hex(const char* buf, const int size) {
180 char hex[size * 2 + 1];
181 int index;
182 for (index = 0; index < size; index++)
183 sprintf(&hex[2 * index], "%02X", buf[index]);
184 printf("%s", hex);
185}
186
187void output_hex(const unsigned char* buf, const int size) {
188 char hex[size * 2 + 1];
189 int index;
190 for (index = 0; index < size; index++)
191 sprintf(&hex[2 * index], "%02X", buf[index]);
192 printf("%s", hex);
193}
194
195void output_hex(std::vector<uint8_t>* vec) {
196 char hex[3];
197 unsigned int index;
198 for (index = 0; index < vec->size(); index++) {
199 sprintf(&hex[0], "%02X", vec->at(index));
200 printf("%s", hex);
201 }
202}*/
203
204/* An alternative is to use:
205 * sqlite3 /data/system/locksettings.db "SELECT value FROM locksettings WHERE name='sp-handle' AND user=0;"
206 * but we really don't want to include the 1.1MB libsqlite in TWRP. We scan the spblob folder for the
207 * password data file (*.pwd) and get the handle from the filename instead. This is a replacement for
208 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#2017
209 * We never use this data as an actual long. We always use it as a string. */
210bool Find_Handle(const std::string& spblob_path, std::string& handle_str) {
211 DIR* dir = opendir(spblob_path.c_str());
212 if (!dir) {
213 printf("Error opening '%s'\n", spblob_path.c_str());
214 return false;
215 }
216
217 struct dirent* de = 0;
218
219 while ((de = readdir(dir)) != 0) {
220 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
221 continue;
222 size_t len = strlen(de->d_name);
223 if (len <= 4)
224 continue;
225 char* p = de->d_name;
226 p += len - 4;
227 if (strncmp(p, ".pwd", 4) == 0) {
228 handle_str = de->d_name;
229 handle_str = handle_str.substr(0, len - 4);
230 //*handle = strtoull(handle_str.c_str(), 0 , 16);
231 closedir(dir);
232 return true;
233 }
234 }
235 closedir(dir);
236 return false;
237}
238
239// The password data is stored in big endian and has to be swapped on little endian ARM
240template <class T>
241void endianswap(T *objp) {
242 unsigned char *memp = reinterpret_cast<unsigned char*>(objp);
243 std::reverse(memp, memp + sizeof(T));
244}
245
246/* This is the structure of the data in the password data (*.pwd) file which the structure can be found
247 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#187 */
248struct password_data_struct {
249 int password_type;
250 unsigned char scryptN;
251 unsigned char scryptR;
252 unsigned char scryptP;
253 int salt_len;
254 void* salt;
255 int handle_len;
256 void* password_handle;
257};
258
259/* C++ replacement for
260 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#764 */
261bool Get_Password_Data(const std::string& spblob_path, const std::string& handle_str, password_data_struct *pwd) {
262 std::string pwd_file = spblob_path + handle_str + ".pwd";
263 std::string pwd_data;
264 if (!android::base::ReadFileToString(pwd_file, &pwd_data)) {
265 printf("Failed to read '%s'\n", pwd_file.c_str());
266 return false;
267 }
268 //output_hex(pwd_data.data(), pwd_data.size());printf("\n");
269 const int* intptr = (const int*)pwd_data.data();
270 pwd->password_type = *intptr;
271 endianswap(&pwd->password_type);
272 //printf("password type %i\n", pwd->password_type); // 2 was PIN, 1 for pattern, 2 also for password, -1 for default password
273 const unsigned char* byteptr = (const unsigned char*)pwd_data.data() + sizeof(int);
274 pwd->scryptN = *byteptr;
275 byteptr++;
276 pwd->scryptR = *byteptr;
277 byteptr++;
278 pwd->scryptP = *byteptr;
279 byteptr++;
280 intptr = (const int*)byteptr;
281 pwd->salt_len = *intptr;
282 endianswap(&pwd->salt_len);
283 if (pwd->salt_len != 0) {
284 pwd->salt = malloc(pwd->salt_len);
285 if (!pwd->salt) {
286 printf("Get_Password_Data malloc salt\n");
287 return false;
288 }
289 memcpy(pwd->salt, intptr + 1, pwd->salt_len);
290 } else {
291 printf("Get_Password_Data salt_len is 0\n");
292 return false;
293 }
294 return true;
295}
296
297/* C++ replacement for
298 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#765
299 * called here
300 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1050 */
301bool Get_Password_Token(const password_data_struct *pwd, const std::string& Password, unsigned char* password_token) {
302 if (!password_token) {
303 printf("password_token is null\n");
304 return false;
305 }
306 unsigned int N = 1 << pwd->scryptN;
307 unsigned int r = 1 << pwd->scryptR;
308 unsigned int p = 1 << pwd->scryptP;
309 //printf("N %i r %i p %i\n", N, r, p);
310 int ret = crypto_scrypt(reinterpret_cast<const uint8_t*>(Password.data()), Password.size(),
311 reinterpret_cast<const uint8_t*>(pwd->salt), pwd->salt_len,
312 N, r, p,
313 password_token, 32);
314 if (ret != 0) {
315 printf("scrypt error\n");
316 return false;
317 }
318 return true;
319}
320
321// Data structure for the *.weaver file, see Get_Weaver_Data below
322struct weaver_data_struct {
323 unsigned char version;
324 int slot;
325};
326
327/* C++ replacement for
328 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#501
329 * called here
330 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768 */
331bool Get_Weaver_Data(const std::string& spblob_path, const std::string& handle_str, weaver_data_struct *wd) {
332 std::string weaver_file = spblob_path + handle_str + ".weaver";
333 std::string weaver_data;
334 if (!android::base::ReadFileToString(weaver_file, &weaver_data)) {
335 printf("Failed to read '%s'\n", weaver_file.c_str());
336 return false;
337 }
338 //output_hex(weaver_data.data(), weaver_data.size());printf("\n");
339 const unsigned char* byteptr = (const unsigned char*)weaver_data.data();
340 wd->version = *byteptr;
341 //printf("weaver version %i\n", wd->version);
342 const int* intptr = (const int*)weaver_data.data() + sizeof(unsigned char);
343 wd->slot = *intptr;
344 //endianswap(&wd->slot); not needed
345 //printf("weaver slot %i\n", wd->slot);
346 return true;
347}
348
349namespace android {
350
351// On Android 8.0 for some reason init can't seem to completely stop keystore
352// so we have to kill it too if it doesn't die on its own.
353static void kill_keystore() {
354 DIR* dir = opendir("/proc");
355 if (dir) {
356 struct dirent* de = 0;
357
358 while ((de = readdir(dir)) != 0) {
359 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
360 continue;
361
362 int pid = -1;
363 int ret = sscanf(de->d_name, "%d", &pid);
364
365 if (ret == 1) {
366 char cmdpath[PATH_MAX];
367 sprintf(cmdpath, "/proc/%d/cmdline", pid);
368
369 FILE* file = fopen(cmdpath, "r");
370 size_t task_size = PATH_MAX;
371 char task[PATH_MAX];
372 char* p = task;
373 if (getline(&p, &task_size, file) > 0) {
374 if (strstr(task, "keystore") != 0) {
375 printf("keystore pid %d found, sending kill.\n", pid);
376 kill(pid, SIGINT);
377 usleep(5000);
378 kill(pid, SIGKILL);
379 }
380 }
381 fclose(file);
382 }
383 }
384 closedir(dir);
385 }
386}
387
388// The keystore holds a file open on /data so we have to stop / kill it
389// if we want to be able to unmount /data for things like formatting.
390static void stop_keystore() {
391 printf("Stopping keystore...\n");
392 property_set("ctl.stop", "keystore");
393 usleep(5000);
394 kill_keystore();
395}
396
397/* These next 2 functions try to get the keystore service 50 times because
398 * the keystore is not always ready when TWRP boots */
399sp<IBinder> getKeystoreBinder() {
400 sp<IServiceManager> sm = defaultServiceManager();
401 return sm->getService(String16("android.security.keystore"));
402}
403
404sp<IBinder> getKeystoreBinderRetry() {
405 printf("Starting keystore...\n");
406 property_set("ctl.start", "keystore");
407 int retry_count = 50;
408 sp<IBinder> binder = getKeystoreBinder();
409 while (binder == NULL && retry_count) {
410 printf("Waiting for keystore service... %i\n", retry_count--);
411 sleep(1);
412 binder = getKeystoreBinder();
413 }
414 return binder;
415}
416
417namespace keystore {
418
419#define SYNTHETIC_PASSWORD_VERSION 1
420#define SYNTHETIC_PASSWORD_PASSWORD_BASED 0
421#define SYNTHETIC_PASSWORD_KEY_PREFIX "USRSKEY_synthetic_password_"
422
423/* The keystore alias subid is sometimes the same as the handle, but not always.
424 * In the case of handle 0c5303fd2010fe29, the alias subid used c5303fd2010fe29
425 * without the leading 0. We could try to parse the data from a previous
426 * keystore request, but I think this is an easier solution because there
427 * is little to no documentation on the format of data we get back from
428 * the keystore in this instance. We also want to copy everything to a temp
429 * folder so that any key upgrades that might take place do not actually
430 * upgrade the keys on the data partition. We rename all 1000 uid files to 0
431 * to pass the keystore permission checks. */
432bool Find_Keystore_Alias_SubID_And_Prep_Files(const userid_t user_id, std::string& keystoreid) {
433 char path_c[PATH_MAX];
434 sprintf(path_c, "/data/misc/keystore/user_%d", user_id);
435 char user_dir[PATH_MAX];
436 sprintf(user_dir, "user_%d", user_id);
437 std::string source_path = "/data/misc/keystore/";
438 source_path += user_dir;
439
440 mkdir("/tmp/misc", 0755);
441 mkdir("/tmp/misc/keystore", 0755);
442 std::string destination_path = "/tmp/misc/keystore/";
443 destination_path += user_dir;
444 if (mkdir(destination_path.c_str(), 0755) && errno != EEXIST) {
445 printf("failed to mkdir '%s' %s\n", destination_path.c_str(), strerror(errno));
446 return false;
447 }
448 destination_path += "/";
449
450 DIR* dir = opendir(source_path.c_str());
451 if (!dir) {
452 printf("Error opening '%s'\n", source_path.c_str());
453 return false;
454 }
455 source_path += "/";
456
457 struct dirent* de = 0;
458 size_t prefix_len = strlen(SYNTHETIC_PASSWORD_KEY_PREFIX);
459 bool found_subid = false;
460
461 while ((de = readdir(dir)) != 0) {
462 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
463 continue;
464 if (!found_subid) {
465 size_t len = strlen(de->d_name);
466 if (len <= prefix_len)
467 continue;
468 if (!strstr(de->d_name, SYNTHETIC_PASSWORD_KEY_PREFIX))
469 continue;
470 std::string file = de->d_name;
471 std::size_t found = file.find_last_of("_");
472 if (found != std::string::npos) {
473 keystoreid = file.substr(found + 1);
474 printf("keystoreid: '%s'\n", keystoreid.c_str());
475 found_subid = true;
476 }
477 }
478 std::string src = source_path;
479 src += de->d_name;
480 std::ifstream srcif(src.c_str(), std::ios::binary);
481 std::string dst = destination_path;
482 dst += de->d_name;
483 std::size_t source_uid = dst.find("1000");
484 if (source_uid != std::string::npos)
485 dst.replace(source_uid, 4, "0");
486 std::ofstream dstof(dst.c_str(), std::ios::binary);
487 printf("copying '%s' to '%s'\n", src.c_str(), dst.c_str());
488 dstof << srcif.rdbuf();
489 srcif.close();
490 dstof.close();
491 }
492 closedir(dir);
493 return found_subid;
494}
495
496/* C++ replacement for function of the same name
497 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#867
498 * returning an empty string indicates an error */
499std::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) {
500 std::string disk_decryption_secret_key = "";
501
502 std::string keystore_alias_subid;
503 if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid)) {
504 printf("failed to scan keystore alias subid and prep keystore files\n");
505 return disk_decryption_secret_key;
506 }
507
508 // First get the keystore service
509 sp<IBinder> binder = getKeystoreBinderRetry();
510 sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
511 if (service == NULL) {
512 printf("error: could not connect to keystore service\n");
513 return disk_decryption_secret_key;
514 }
515
516 // 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
517 std::string spblob_file = spblob_path + handle_str + ".spblob";
518 std::string spblob_data;
519 if (!android::base::ReadFileToString(spblob_file, &spblob_data)) {
520 printf("Failed to read '%s'\n", spblob_file.c_str());
521 return disk_decryption_secret_key;
522 }
523 const unsigned char* byteptr = (const unsigned char*)spblob_data.data();
524 if (*byteptr != SYNTHETIC_PASSWORD_VERSION) {
525 printf("SYNTHETIC_PASSWORD_VERSION does not match\n");
526 return disk_decryption_secret_key;
527 }
528 byteptr++;
529 if (*byteptr != SYNTHETIC_PASSWORD_PASSWORD_BASED) {
530 printf("spblob data is not SYNTHETIC_PASSWORD_PASSWORD_BASED\n");
531 return disk_decryption_secret_key;
532 }
533 byteptr++; // Now we're pointing to the blob data itself
534 /* 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
535 * Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#879
536 * 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.
537 * The keystore data seems to be the serialized data from an entire class in Java. Specifically I think it represents:
538 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
539 * or perhaps
540 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
541 * 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}
542 * 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.
543 * There are 2 calls to a Java decrypt funcion that is overloaded. These 2 calls go in completely different directions despite the seemingly
544 * similar use of decrypt() and decrypt parameters. To figure out where things were going, I added logging to:
545 * https://android.googlesource.com/platform/libcore/+/android-8.0.0_r23/ojluni/src/main/java/javax/crypto/Cipher.java#2575
546 * Logger.global.severe("Cipher tryCombinations " + prov.getName() + " - " + prov.getInfo());
547 * 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
548 * 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
549 * 2 different providers in use. The first stage to get the intermediate key used:
550 * https://android.googlesource.com/platform/external/conscrypt/+/android-8.0.0_r23/common/src/main/java/org/conscrypt/OpenSSLProvider.java
551 * which is a pretty straight-forward OpenSSL implementation of AES/GCM/NoPadding. */
552 // 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
553 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
554 if (!personalized_application_id) {
555 printf("malloc personalized_application_id\n");
556 return disk_decryption_secret_key;
557 }
558 //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
559 // Now we'll decrypt using openssl AES/GCM/NoPadding
560 OpenSSL_add_all_ciphers();
561 int actual_size=0, final_size=0;
562 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
563 const unsigned char* iv = (const unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
564 //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
565 const unsigned char* cipher_text = (const unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
566 //printf("cipher_text: "); output_hex((const unsigned char*)cipher_text, spblob_data.size() - 2 - 12); printf("\n");
567 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
568 //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
569 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, iv);
570 std::vector<unsigned char> intermediate_key;
571 intermediate_key.resize(spblob_data.size() - 2 - 12, '\0');
572 EVP_DecryptUpdate(d_ctx, &intermediate_key[0], &actual_size, cipher_text, spblob_data.size() - 2 - 12);
573 unsigned char tag[AES_BLOCK_SIZE];
574 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
575 EVP_DecryptFinal_ex(d_ctx, &intermediate_key[actual_size], &final_size);
576 EVP_CIPHER_CTX_free(d_ctx);
577 free(personalized_application_id);
578 //printf("spblob_data size: %lu actual_size %i, final_size: %i\n", spblob_data.size(), actual_size, final_size);
579 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
580 //printf("intermediate key: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
581
582 int32_t ret;
583
584 /* 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
585 * as the key data will be read again by the begin function later via the keystore.
586 * The data is in a hidl_vec format which consists of a type and a value. */
587 /*::keystore::hidl_vec<uint8_t> data;
588 std::string keystoreid = SYNTHETIC_PASSWORD_KEY_PREFIX;
589 keystoreid += handle_str;
590
591 ret = service->get(String16(keystoreid.c_str()), user_id, &data);
592 if (ret < 0) {
593 printf("Could not connect to keystore service %i\n", ret);
594 return disk_decryption_secret_key;
595 } else if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*//*) {
596 printf("keystore error: (%d)\n", /*responses[ret],*//* ret);
597 return disk_decryption_secret_key;
598 } else {
599 printf("keystore returned: "); output_hex(&data[0], data.size()); printf("\n");
600 }*/
601
602 // Now we'll break up the intermediate key into the IV (first 12 bytes) and the cipher text (the rest of it).
603 std::vector<unsigned char> nonce = intermediate_key;
604 nonce.resize(12);
605 intermediate_key.erase (intermediate_key.begin(),intermediate_key.begin()+12);
606 //printf("nonce: "); output_hex((const unsigned char*)nonce.data(), nonce.size()); printf("\n");
607 //printf("cipher text: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
608
609 /* Now we will begin the second decrypt call found in
610 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#122
611 * This time we will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
612 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
613 * First we set some algorithm parameters as seen in two places:
614 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
615 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
616 size_t maclen = 128;
617 ::keystore::AuthorizationSetBuilder begin_params;
618 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
619 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
620 begin_params.Padding(::keystore::PaddingMode::NONE);
621 begin_params.Authorization(::keystore::TAG_NONCE, nonce);
622 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
623 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES);
624 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockMode);
625 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_PADDING, mKeymasterPadding);
626 //keymasterArgs.addUnsignedInt(KeymasterDefs.KM_TAG_MAC_LENGTH, mTagLengthBits);
627 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
628 entropy.resize(0);
629 std::string keystore_alias = SYNTHETIC_PASSWORD_KEY_PREFIX;
630 keystore_alias += keystore_alias_subid;
631 String16 keystore_alias16(keystore_alias.c_str());
632 ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT;
633 OperationResult begin_result;
634 // 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
635 service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result);
636 ret = begin_result.resultCode;
637 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
638 printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret);
639 return disk_decryption_secret_key;
640 } else {
641 //printf("keystore begin operation successful\n");
642 }
643 ::keystore::hidl_vec<::keystore::KeyParameter> empty_params;
644 empty_params.resize(0);
645 OperationResult update_result;
646 // 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
647 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
648 service->update(begin_result.token, empty_params, intermediate_key, &update_result);
649 ret = update_result.resultCode;
650 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
651 printf("keystore update error: (%d)\n", /*responses[ret],*/ ret);
652 return disk_decryption_secret_key;
653 } else {
654 //printf("keystore update operation successful\n");
655 //printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password
656 }
657 // We must use the data in update_data.data before we call finish below or the data will be gone
658 // 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
659 // We now have the disk decryption key!
660 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)&update_result.data[0], update_result.data.size());
661 //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
662 ::keystore::hidl_vec<uint8_t> signature;
663 OperationResult finish_result;
664 service->finish(begin_result.token, empty_params, signature, entropy, &finish_result);
665 ret = finish_result.resultCode;
666 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
667 printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret);
668 return disk_decryption_secret_key;
669 } else {
670 //printf("keystore finish operation successful\n");
671 }
672 stop_keystore();
673 return disk_decryption_secret_key;
674}
675
676}}
677
678#define PASSWORD_TOKEN_SIZE 32
679
680bool Free_Return(bool retval, void* weaver_key, void* pwd_salt) {
681 if (weaver_key)
682 free(weaver_key);
683 if (pwd_salt)
684 free(pwd_salt);
685 return retval;
686}
687
688/* Decrypt_User_Synth_Pass is the TWRP C++ equivalent to spBasedDoVerifyCredential
689 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#1998 */
690bool Decrypt_User_Synth_Pass(const userid_t user_id, const std::string& Password) {
691 bool retval = false;
692 void* weaver_key = NULL;
693 password_data_struct pwd;
694 pwd.salt = NULL;
695
696 std::string secret; // this will be the disk decryption key that is sent to vold
697 std::string token = "!"; // there is no token used for this kind of decrypt, key escrow is handled by weaver
698 int flags = FLAG_STORAGE_DE;
699 if (user_id == 0)
700 flags = FLAG_STORAGE_DE;
701 else
702 flags = FLAG_STORAGE_CE;
703 char spblob_path_char[PATH_MAX];
704 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
705 std::string spblob_path = spblob_path_char;
706 long handle = 0;
707 std::string handle_str;
708 // 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
709 if (!Find_Handle(spblob_path, handle_str)) {
710 printf("Error getting handle\n");
711 return Free_Return(retval, weaver_key, pwd.salt);
712 }
713 printf("Handle is '%s'\n", handle_str.c_str());
714 // 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
715 // First we read the password data which contains scrypt parameters
716 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
717 printf("Failed to Get_Password_Data\n");
718 return Free_Return(retval, weaver_key, pwd.salt);
719 }
720 //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");
721 unsigned char password_token[PASSWORD_TOKEN_SIZE];
722 //printf("Password: '%s'\n", Password.c_str());
723 // The password token is the password scrypted with the parameters from the password data file
724 if (!Get_Password_Token(&pwd, Password, &password_token[0])) {
725 printf("Failed to Get_Password_Token\n");
726 return Free_Return(retval, weaver_key, pwd.salt);
727 }
728 //output_hex(&password_token[0], PASSWORD_TOKEN_SIZE);printf("\n");
729 // BEGIN PIXEL 2 WEAVER
730 // Get the weaver data from the .weaver file which tells us which slot to use when we ask weaver for the escrowed key
731 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768
732 weaver_data_struct wd;
733 if (!Get_Weaver_Data(spblob_path, handle_str, &wd)) {
734 printf("Failed to get weaver data\n");
735 // Fail over to gatekeeper path for Pixel 1???
736 return Free_Return(retval, weaver_key, pwd.salt);
737 }
738 // The weaver key is the the password token prefixed with "weaver-key" padded to 128 with nulls with the password token appended then SHA512
739 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1059
740 weaver_key = PersonalizedHashBinary(PERSONALISATION_WEAVER_KEY, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
741 if (!weaver_key) {
742 printf("malloc error getting weaver_key\n");
743 return Free_Return(retval, weaver_key, pwd.salt);
744 }
745 // 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
746 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#776
747 android::vold::Weaver weaver;
748 if (!weaver) {
749 printf("Failed to get weaver service\n");
750 return Free_Return(retval, weaver_key, pwd.salt);
751 }
752 // Get the key size from weaver service
753 uint32_t weaver_key_size = 0;
754 if (!weaver.GetKeySize(&weaver_key_size)) {
755 printf("Failed to get weaver key size\n");
756 return Free_Return(retval, weaver_key, pwd.salt);
757 } else {
758 //printf("weaver key size is %u\n", weaver_key_size);
759 }
760 //printf("weaver key: "); output_hex((unsigned char*)weaver_key, weaver_key_size); printf("\n");
761 // Send the slot from the .weaver file, the computed weaver key, and get the escrowed key data
762 std::vector<uint8_t> weaver_payload;
763 // TODO: we should return more information about the status including time delays before the next retry
764 if (!weaver.WeaverVerify(wd.slot, weaver_key, &weaver_payload)) {
765 printf("failed to weaver verify\n");
766 return Free_Return(retval, weaver_key, pwd.salt);
767 }
768 //printf("weaver payload: "); output_hex(&weaver_payload); printf("\n");
769 // Done with weaverVerify
770 // Now we will compute the application ID
771 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#964
772 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#780
773 // The escrowed weaver key data is prefixed with "weaver-pwd" padded to 128 with nulls with the weaver payload appended then SHA512
774 void* weaver_secret = PersonalizedHashBinary(PERSONALISATION_WEAVER_PASSWORD, (const char*)weaver_payload.data(), weaver_payload.size());
775 //printf("weaver secret: "); output_hex((unsigned char*)weaver_secret, SHA512_DIGEST_LENGTH); printf("\n");
776 // The application ID is the password token and weaver secret appended to each other
777 char application_id[PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH];
778 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
779 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], weaver_secret, SHA512_DIGEST_LENGTH);
780 //printf("application ID: "); output_hex((unsigned char*)application_id, PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH); printf("\n");
781 // END PIXEL 2 WEAVER
782 // 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
783 // Plus we will include the last bit that computes the disk decrypt key found in:
784 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#153
785 secret = android::keystore::unwrapSyntheticPasswordBlob(spblob_path, handle_str, user_id, (const void*)&application_id[0], PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH);
786 if (!secret.size()) {
787 printf("failed to unwrapSyntheticPasswordBlob\n");
788 return Free_Return(retval, weaver_key, pwd.salt);
789 }
790 if (!e4crypt_unlock_user_key(user_id, 0, token.c_str(), secret.c_str())) {
791 printf("e4crypt_unlock_user_key returned fail\n");
792 return Free_Return(retval, weaver_key, pwd.salt);
793 }
794 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
795 printf("failed to e4crypt_prepare_user_storage\n");
796 return Free_Return(retval, weaver_key, pwd.salt);
797 }
798 printf("Decrypted Successfully!\n");
799 retval = true;
800 return Free_Return(retval, weaver_key, pwd.salt);
801}
802#endif //HAVE_SYNTH_PWD_SUPPORT
803
804int Get_Password_Type(const userid_t user_id, std::string& filename) {
805 struct stat st;
806 char spblob_path_char[PATH_MAX];
807 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
808 if (stat(spblob_path_char, &st) == 0) {
809#ifdef HAVE_SYNTH_PWD_SUPPORT
810 printf("Using synthetic password method\n");
811 std::string spblob_path = spblob_path_char;
812 std::string handle_str;
813 if (!Find_Handle(spblob_path, handle_str)) {
814 printf("Error getting handle\n");
815 return 0;
816 }
817 printf("Handle is '%s'\n", handle_str.c_str());
818 password_data_struct pwd;
819 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
820 printf("Failed to Get_Password_Data\n");
821 return 0;
822 }
823 if (pwd.password_type == 1) // In Android this means pattern
824 return 2; // In TWRP this means pattern
825 else if (pwd.password_type == 2) // In Android this means PIN or password
826 return 1; // In TWRP this means PIN or password
827 return 0; // We'll try the default password
828#else
829 printf("Synthetic password support not present in TWRP\n");
830 return -1;
831#endif
832 }
833 std::string path;
834 if (user_id == 0) {
835 path = "/data/system/";
836 } else {
837 char user_id_str[5];
838 sprintf(user_id_str, "%i", user_id);
839 path = "/data/system/users/";
840 path += user_id_str;
841 path += "/";
842 }
843 filename = path + "gatekeeper.password.key";
844 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
845 return 1;
846 filename = path + "gatekeeper.pattern.key";
847 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
848 return 2;
849 printf("Unable to locate gatekeeper password file '%s'\n", filename.c_str());
850 filename = "";
851 return 0;
852}
853
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600854bool Decrypt_User(const userid_t user_id, const std::string& Password) {
855 uint8_t *auth_token;
856 uint32_t auth_token_len;
857 int ret;
858
859 struct stat st;
860 if (user_id > 9999) {
861 printf("user_id is too big\n");
862 return false;
863 }
864 std::string filename;
865 bool Default_Password = (Password == "!");
866 if (Get_Password_Type(user_id, filename) == 0 && !Default_Password) {
867 printf("Unknown password type\n");
868 return false;
869 }
870 int flags = FLAG_STORAGE_DE;
871 if (user_id == 0)
872 flags = FLAG_STORAGE_DE;
873 else
874 flags = FLAG_STORAGE_CE;
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600875 if (Default_Password) {
876 if (!e4crypt_unlock_user_key(user_id, 0, "!", "!")) {
877 printf("e4crypt_unlock_user_key returned fail\n");
878 return false;
879 }
880 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
881 printf("failed to e4crypt_prepare_user_storage\n");
882 return false;
883 }
884 printf("Decrypted Successfully!\n");
885 return true;
886 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500887 if (stat("/data/system_de/0/spblob", &st) == 0) {
888#ifdef HAVE_SYNTH_PWD_SUPPORT
889 printf("Using synthetic password method\n");
890 return Decrypt_User_Synth_Pass(user_id, Password);
891#else
892 printf("Synthetic password support not present in TWRP\n");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600893 return false;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500894#endif
895 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600896 printf("password filename is '%s'\n", filename.c_str());
897 if (stat(filename.c_str(), &st) != 0) {
898 printf("error stat'ing key file: %s\n", strerror(errno));
899 return false;
900 }
901 std::string handle;
902 if (!android::base::ReadFileToString(filename, &handle)) {
903 printf("Failed to read '%s'\n", filename.c_str());
904 return false;
905 }
906 bool should_reenroll;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500907#ifdef HAVE_GATEKEEPER1
908 bool request_reenroll = false;
909 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
910 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
911 if (gk_device == nullptr)
912 return false;
913 android::hardware::hidl_vec<uint8_t> curPwdHandle;
914 curPwdHandle.setToExternal(const_cast<uint8_t *>((const uint8_t *)handle.c_str()), st.st_size);
915 android::hardware::hidl_vec<uint8_t> enteredPwd;
916 enteredPwd.setToExternal(const_cast<uint8_t *>((const uint8_t *)Password.c_str()), Password.size());
917
918 android::hardware::Return<void> hwRet =
919 gk_device->verify(user_id, 0 /* challange */,
920 curPwdHandle,
921 enteredPwd,
922 [&ret, &request_reenroll, &auth_token, &auth_token_len]
923 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
924 ret = static_cast<int>(rsp.code); // propagate errors
925 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
926 auth_token = new uint8_t[rsp.data.size()];
927 auth_token_len = rsp.data.size();
928 memcpy(auth_token, rsp.data.data(), auth_token_len);
929 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
930 ret = 0; // all success states are reported as 0
931 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
932 ret = rsp.timeout;
933 }
934 }
935 );
936 if (!hwRet.isOk()) {
937 return false;
938 }
939#else
940 gatekeeper_device_t *gk_device;
941 ret = gatekeeper_device_initialize(&gk_device);
942 if (ret!=0)
943 return false;
944 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 -0600945 (const uint8_t *)Password.c_str(), (uint32_t)Password.size(), &auth_token, &auth_token_len,
946 &should_reenroll);
947 if (ret !=0) {
948 printf("failed to verify\n");
949 return false;
950 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500951#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600952 char token_hex[(auth_token_len*2)+1];
953 token_hex[(auth_token_len*2)] = 0;
954 uint32_t i;
955 for (i=0;i<auth_token_len;i++) {
956 sprintf(&token_hex[2*i], "%02X", auth_token[i]);
957 }
958 // 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
959 std::string secret = HashPassword(Password);
960 if (!e4crypt_unlock_user_key(user_id, 0, token_hex, secret.c_str())) {
961 printf("e4crypt_unlock_user_key returned fail\n");
962 return false;
963 }
964 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
965 printf("failed to e4crypt_prepare_user_storage\n");
966 return false;
967 }
968 printf("Decrypted Successfully!\n");
969 return true;
970}