blob: bd3d0679cfbb63c6d77d61f5db00bf7b3247c4e9 [file] [log] [blame]
bigbiff7ba75002020-04-11 20:47:09 -04001/*
2 * Copyright (C) 2016 - 2020 The TeamWin 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 "FsCrypt.h"
19
20#include <map>
21#include <string>
22
23#include <errno.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28
29#ifndef HAVE_LIBKEYUTILS
30#include "key_control.h"
31#else
32#include <keyutils.h>
33#endif
34#include "keystore_client.pb.h"
35#include "Weaver1.h"
36#include "cutils/properties.h"
37
38#include <openssl/sha.h>
39#include <openssl/aes.h>
40#include <openssl/evp.h>
41#include <openssl/rand.h>
42
43#include <dirent.h>
44#include <stdio.h>
45#include <stdint.h>
46#include <string.h>
47#include <sys/types.h>
48#include <fstream>
49#include <future>
50#include <algorithm>
51
52#include <android-base/file.h>
53#include <base/threading/platform_thread.h>
54#include <android/hardware/confirmationui/1.0/types.h>
55#include <android/security/BnConfirmationPromptCallback.h>
56#include <android/security/keystore/IKeystoreService.h>
57#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
58
59#include <binder/IServiceManager.h>
60#include <binder/IPCThreadState.h>
61#include <hardware/hw_auth_token.h>
62
63#include <keystore/keystore.h>
64#include <keystore/keystore_client.h>
65#include <keystore/keystore_client_impl.h>
66#include <keystore/KeystoreResponse.h>
67#include <keystore/keystore_hidl_support.h>
68#include <keystore/keystore_promises.h>
69#include <keystore/keystore_return_types.h>
70#include <keystore/keymaster_types.h>
71#include <keymasterV4_0/Keymaster.h>
72#include <keystore/OperationResult.h>
73#include "keystore_client.pb.h"
74
75#include <keymasterV4_0/authorization_set.h>
76#include <keymasterV4_0/keymaster_utils.h>
77
78extern "C" {
79#include "crypto_scrypt.h"
80}
81
82#include "fscrypt_policy.h"
83#include "HashPassword.h"
84#include "KeyStorage.h"
85
86using android::security::keystore::IKeystoreService;
87using keystore::KeystoreResponsePromise;
88using keystore::OperationResultPromise;
89using android::security::keymaster::OperationResult;
90
91// 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
96inline std::string hidlVec2String(const ::keystore::hidl_vec<uint8_t>& value) {
97 return std::string(reinterpret_cast<const std::string::value_type*>(&value[0]), value.size());
98}
99
100static bool lookup_ref_key_internal(std::map<userid_t, std::string>& key_map, const uint8_t* policy, userid_t* user_id) {
101 char policy_string_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
102 char key_map_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
103 policy_to_hex(policy, policy_string_hex);
104
105 for (std::map<userid_t, std::string>::iterator it=key_map.begin(); it!=key_map.end(); ++it) {
106 policy_to_hex(reinterpret_cast<const uint8_t*>(&it->second[0]), key_map_hex);
107 std::string key_map_hex_string = std::string(key_map_hex);
108 if (key_map_hex_string == policy_string_hex) {
109 *user_id = it->first;
110 return true;
111 }
112 }
113 return false;
114}
115
116extern "C" bool lookup_ref_key(const uint8_t* policy, uint8_t* policy_type) {
117 userid_t user_id = 0;
118 char policy_string_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
119 char de_raw_ref_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
120 policy_to_hex(policy, policy_string_hex);
121 policy_to_hex(reinterpret_cast<const uint8_t*>(&de_raw_ref[0]), de_raw_ref_hex);
122 std::string de_raw_ref_hex_string = std::string(de_raw_ref_hex);
123
124 std::string policy_type_string;
125 if (policy_string_hex == de_raw_ref_hex_string) {
126 policy_type_string = "0DK";
127 memcpy(policy_type, policy_type_string.data(), policy_type_string.size());
128 return true;
129 }
130
131 if (!lookup_ref_key_internal(s_de_key_raw_refs, policy, &user_id)) {
132 if (!lookup_ref_key_internal(s_ce_key_raw_refs, policy, &user_id)) {
133 return false;
134 } else
135 policy_type_string = "0CE" + std::to_string(user_id);
136 } else
137 policy_type_string = "0DE" + std::to_string(user_id);
138 memcpy(policy_type, policy_type_string.data(), policy_type_string.size());
139 return true;
140}
141
142extern "C" bool lookup_ref_tar(const uint8_t* policy_type, uint8_t* policy) {
143 std::string policy_type_string = std::string((char *) policy_type);
144 char policy_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
145 policy_to_hex(policy_type, policy_hex);
146
147 // Current encryption fscrypt policy is v1 (which is stored as version 0e)
148 if (policy_type_string.substr(0,1) != "0") {
149 printf("Unexpected version %c\n", policy_type[0]);
150 return false;
151 }
152
153 if (policy_type_string.substr(1, 2) == "DK") {
154 memcpy(policy, de_raw_ref.data(), de_raw_ref.size());
155 return true;
156 }
157
158 userid_t user_id = atoi(policy_type_string.substr(3, 4).c_str());
159 std::string raw_ref;
160
161 if (policy_type_string.substr(1, 1) == "D") {
162 if (lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)) {
163 memcpy(policy, raw_ref.data(), raw_ref.size());
164 } else
165 return false;
166 } else if (policy_type_string.substr(1, 1) == "C") {
167 if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
168 memcpy(policy, raw_ref.data(), raw_ref.size());
169 } else
170 return false;
171 } else {
172 printf("unknown policy type '%s'\n", policy_type);
173 return false;
174 }
175 return true;
176}
177
178bool Decrypt_DE() {
179 if (!fscrypt_initialize_systemwide_keys()) { // this deals with the overarching device encryption
180 printf("fscrypt_initialize_systemwide_keys returned fail\n");
181 return false;
182 }
183 if (!fscrypt_init_user0()) {
184 printf("fscrypt_init_user0 returned fail\n");
185 return false;
186 }
187 return true;
188}
189
190// Crappy functions for debugging, please ignore unless you need to debug
191// void output_hex(const std::string& in) {
192// const char *buf = in.data();
193// char hex[in.size() * 2 + 1];
194// unsigned int index;
195// for (index = 0; index < in.size(); index++)
196// sprintf(&hex[2 * index], "%02X", buf[index]);
197// printf("%s", hex);
198// }
199
200// void output_hex(const char* buf, const int size) {
201// char hex[size * 2 + 1];
202// int index;
203// for (index = 0; index < size; index++)
204// sprintf(&hex[2 * index], "%02X", buf[index]);
205// printf("%s", hex);
206// }
207
208// void output_hex(const unsigned char* buf, const int size) {
209// char hex[size * 2 + 1];
210// int index;
211// for (index = 0; index < size; index++)
212// sprintf(&hex[2 * index], "%02X", buf[index]);
213// printf("%s", hex);
214// }
215
216// void output_hex(std::vector<uint8_t>* vec) {
217// char hex[3];
218// unsigned int index;
219// for (index = 0; index < vec->size(); index++) {
220// sprintf(&hex[0], "%02X", vec->at(index));
221// printf("%s", hex);
222// }
223// }
224
225/* An alternative is to use:
226 * sqlite3 /data/system/locksettings.db "SELECT value FROM locksettings WHERE name='sp-handle' AND user=0;"
227 * but we really don't want to include the 1.1MB libsqlite in TWRP. We scan the spblob folder for the
228 * password data file (*.pwd) and get the handle from the filename instead. This is a replacement for
229 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#2017
230 * We never use this data as an actual long. We always use it as a string. */
231bool Find_Handle(const std::string& spblob_path, std::string& handle_str) {
232 DIR* dir = opendir(spblob_path.c_str());
233 if (!dir) {
234 printf("Error opening '%s'\n", spblob_path.c_str());
235 return false;
236 }
237
238 struct dirent* de = 0;
239
240 while ((de = readdir(dir)) != 0) {
241 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
242 continue;
243 size_t len = strlen(de->d_name);
244 if (len <= 4)
245 continue;
246 char* p = de->d_name;
247 p += len - 4;
248 if (strncmp(p, ".pwd", 4) == 0) {
249 handle_str = de->d_name;
250 handle_str = handle_str.substr(0, len - 4);
251 //*handle = strtoull(handle_str.c_str(), 0 , 16);
252 closedir(dir);
253 return true;
254 }
255 }
256 closedir(dir);
257 return false;
258}
259
260/* This is the structure of the data in the password data (*.pwd) file which the structure can be found
261 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#187 */
262struct password_data_struct {
263 int password_type;
264 unsigned char scryptN;
265 unsigned char scryptR;
266 unsigned char scryptP;
267 int salt_len;
268 void* salt;
269 int handle_len;
270 void* password_handle;
271};
272
273/* C++ replacement for
274 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#764 */
275bool Get_Password_Data(const std::string& spblob_path, const std::string& handle_str, password_data_struct *pwd) {
276 std::string pwd_file = spblob_path + handle_str + ".pwd";
277 std::string pwd_data;
278 if (!android::base::ReadFileToString(pwd_file, &pwd_data)) {
279 printf("Failed to read '%s'\n", pwd_file.c_str());
280 return false;
281 }
282 // output_hex(pwd_data.data(), pwd_data.size());printf("\n");
283 const int* intptr = (const int*)pwd_data.data();
284 pwd->password_type = *intptr;
285 endianswap(&pwd->password_type);
286 //printf("password type %i\n", pwd->password_type); // 2 was PIN, 1 for pattern, 2 also for password, -1 for default password
287 const unsigned char* byteptr = (const unsigned char*)pwd_data.data() + sizeof(int);
288 pwd->scryptN = *byteptr;
289 byteptr++;
290 pwd->scryptR = *byteptr;
291 byteptr++;
292 pwd->scryptP = *byteptr;
293 byteptr++;
294 intptr = (const int*)byteptr;
295 pwd->salt_len = *intptr;
296 endianswap(&pwd->salt_len);
297 if (pwd->salt_len != 0) {
298 pwd->salt = malloc(pwd->salt_len);
299 if (!pwd->salt) {
300 printf("Get_Password_Data malloc salt\n");
301 return false;
302 }
303 memcpy(pwd->salt, intptr + 1, pwd->salt_len);
304 intptr++;
305 byteptr = (const unsigned char*)intptr;
306 byteptr += pwd->salt_len;
307 } else {
308 printf("Get_Password_Data salt_len is 0\n");
309 return false;
310 }
311 intptr = (const int*)byteptr;
312 pwd->handle_len = *intptr;
313 endianswap(&pwd->handle_len);
314 if (pwd->handle_len != 0) {
315 pwd->password_handle = malloc(pwd->handle_len);
316 if (!pwd->password_handle) {
317 printf("Get_Password_Data malloc password_handle\n");
318 return false;
319 }
320 memcpy(pwd->password_handle, intptr + 1, pwd->handle_len);
321 } else {
322 printf("Get_Password_Data handle_len is 0\n");
323 // Not an error if using weaver
324 }
325 return true;
326}
327
328/* C++ replacement for
329 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#765
330 * called here
331 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1050 */
332bool Get_Password_Token(const password_data_struct *pwd, const std::string& Password, unsigned char* password_token) {
333 if (!password_token) {
334 printf("password_token is null\n");
335 return false;
336 }
337 unsigned int N = 1 << pwd->scryptN;
338 unsigned int r = 1 << pwd->scryptR;
339 unsigned int p = 1 << pwd->scryptP;
340 //printf("N %i r %i p %i\n", N, r, p);
341 int ret = crypto_scrypt(reinterpret_cast<const uint8_t*>(Password.data()), Password.size(),
342 reinterpret_cast<const uint8_t*>(pwd->salt), pwd->salt_len,
343 N, r, p,
344 password_token, 32);
345 if (ret != 0) {
346 printf("scrypt error\n");
347 return false;
348 }
349 return true;
350}
351
352// Data structure for the *.weaver file, see Get_Weaver_Data below
353struct weaver_data_struct {
354 unsigned char version;
355 int slot;
356};
357
358/* C++ replacement for
359 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#501
360 * called here
361 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768 */
362bool Get_Weaver_Data(const std::string& spblob_path, const std::string& handle_str, weaver_data_struct *wd) {
363 std::string weaver_file = spblob_path + handle_str + ".weaver";
364 std::string weaver_data;
365 if (!android::base::ReadFileToString(weaver_file, &weaver_data)) {
366 printf("Failed to read '%s'\n", weaver_file.c_str());
367 return false;
368 }
369 // output_hex(weaver_data.data(), weaver_data.size());printf("\n");
370 const unsigned char* byteptr = (const unsigned char*)weaver_data.data();
371 wd->version = *byteptr;
372 // printf("weaver version %i\n", wd->version);
373 const int* intptr = (const int*)weaver_data.data() + sizeof(unsigned char);
374 wd->slot = *intptr;
375 //endianswap(&wd->slot); not needed
376 // printf("weaver slot %i\n", wd->slot);
377 return true;
378}
379
380namespace android {
381
382// On Android 8.0 for some reason init can't seem to completely stop keystore
383// so we have to kill it too if it doesn't die on its own.
384static void kill_keystore() {
385 DIR* dir = opendir("/proc");
386 if (dir) {
387 struct dirent* de = 0;
388
389 while ((de = readdir(dir)) != 0) {
390 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
391 continue;
392
393 int pid = -1;
394 int ret = sscanf(de->d_name, "%d", &pid);
395
396 if (ret == 1) {
397 char cmdpath[PATH_MAX];
398 sprintf(cmdpath, "/proc/%d/cmdline", pid);
399
400 FILE* file = fopen(cmdpath, "r");
401 size_t task_size = PATH_MAX;
402 char task[PATH_MAX];
403 char* p = task;
404 if (getline(&p, &task_size, file) > 0) {
405 if (strstr(task, "keystore") != 0) {
406 printf("keystore pid %d found, sending kill.\n", pid);
407 kill(pid, SIGINT);
408 usleep(5000);
409 kill(pid, SIGKILL);
410 }
411 }
412 fclose(file);
413 }
414 }
415 closedir(dir);
416 }
417}
418
419// The keystore holds a file open on /data so we have to stop / kill it
420// if we want to be able to unmount /data for things like formatting.
421static void stop_keystore() {
422 printf("Stopping keystore...\n");
423 property_set("ctl.stop", "keystore");
424 usleep(5000);
425 kill_keystore();
426}
427
428/* These next 2 functions try to get the keystore service 50 times because
429 * the keystore is not always ready when TWRP boots */
430android::sp<IBinder> getKeystoreBinder() {
431 android::sp<IServiceManager> sm = android::defaultServiceManager();
432 return sm->getService(String16("android.security.keystore"));
433}
434
435android::sp<IBinder> getKeystoreBinderRetry() {
436 printf("Starting keystore...\n");
437 property_set("ctl.start", "keystore");
438 int retry_count = 50;
439 android::sp<IBinder> binder = getKeystoreBinder();
440 while (binder == NULL && retry_count) {
441 printf("Waiting for keystore service... %i\n", retry_count--);
442 sleep(1);
443 binder = getKeystoreBinder();
444 }
445 return binder;
446}
447
448namespace keystore {
449
450#define SYNTHETIC_PASSWORD_VERSION_V1 1
451#define SYNTHETIC_PASSWORD_VERSION_V2 2
452#define SYNTHETIC_PASSWORD_VERSION_V3 3
453#define SYNTHETIC_PASSWORD_PASSWORD_BASED 0
454#define SYNTHETIC_PASSWORD_KEY_PREFIX "USRSKEY_synthetic_password_"
455#define USR_PRIVATE_KEY_PREFIX "USRPKEY_synthetic_password_"
456
457static std::string mKey_Prefix;
458
459/* The keystore alias subid is sometimes the same as the handle, but not always.
460 * In the case of handle 0c5303fd2010fe29, the alias subid used c5303fd2010fe29
461 * without the leading 0. We could try to parse the data from a previous
462 * keystore request, but I think this is an easier solution because there
463 * is little to no documentation on the format of data we get back from
464 * the keystore in this instance. We also want to copy everything to a temp
465 * folder so that any key upgrades that might take place do not actually
466 * upgrade the keys on the data partition. We rename all 1000 uid files to 0
467 * to pass the keystore permission checks. */
468bool Find_Keystore_Alias_SubID_And_Prep_Files(const userid_t user_id, std::string& keystoreid, const std::string& handle_str) {
469 char path_c[PATH_MAX];
470 sprintf(path_c, "/data/misc/keystore/user_%d", user_id);
471 char user_dir[PATH_MAX];
472 sprintf(user_dir, "user_%d", user_id);
473 std::string source_path = "/data/misc/keystore/";
474 source_path += user_dir;
475 std::string handle_sub = handle_str;
476 while (handle_sub.substr(0,1) == "0") {
477 std::string temp = handle_sub.substr(1);
478 handle_sub = temp;
479 }
480 mKey_Prefix = "";
481
482 mkdir("/tmp/misc", 0755);
483 mkdir("/tmp/misc/keystore", 0755);
484 std::string destination_path = "/tmp/misc/keystore/";
485 destination_path += user_dir;
486 if (mkdir(destination_path.c_str(), 0755) && errno != EEXIST) {
487 printf("failed to mkdir '%s' %s\n", destination_path.c_str(), strerror(errno));
488 return false;
489 }
490 destination_path += "/";
491
492 DIR* dir = opendir(source_path.c_str());
493 if (!dir) {
494 printf("Error opening '%s'\n", source_path.c_str());
495 return false;
496 }
497 source_path += "/";
498
499 struct dirent* de = 0;
500 size_t prefix_len = strlen(SYNTHETIC_PASSWORD_KEY_PREFIX);
501 bool found_subid = false;
502 bool has_pkey = false; // PKEY has priority over SKEY
503
504 while ((de = readdir(dir)) != 0) {
505 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
506 continue;
507 if (!found_subid) {
508 size_t len = strlen(de->d_name);
509 if (len <= prefix_len)
510 continue;
511 if (strstr(de->d_name, SYNTHETIC_PASSWORD_KEY_PREFIX) && !has_pkey)
512 mKey_Prefix = SYNTHETIC_PASSWORD_KEY_PREFIX;
513 else if (strstr(de->d_name, USR_PRIVATE_KEY_PREFIX)) {
514 mKey_Prefix = USR_PRIVATE_KEY_PREFIX;
515 has_pkey = true;
516 } else
517 continue;
518 if (strstr(de->d_name, handle_sub.c_str())) {
519 keystoreid = handle_sub;
520 printf("keystoreid matched handle_sub: '%s'\n", keystoreid.c_str());
521 found_subid = true;
522 } else {
523 std::string file = de->d_name;
524 std::size_t found = file.find_last_of("_");
525 if (found != std::string::npos) {
526 keystoreid = file.substr(found + 1);
527 // printf("possible keystoreid: '%s'\n", keystoreid.c_str());
528 //found_subid = true; // we'll keep going in hopes that we find a pkey or a match to the handle_sub
529 }
530 }
531 }
532 std::string src = source_path;
533 src += de->d_name;
534 std::ifstream srcif(src.c_str(), std::ios::binary);
535 std::string dst = destination_path;
536 dst += de->d_name;
537 std::size_t source_uid = dst.find("1000");
538 if (source_uid != std::string::npos)
539 dst.replace(source_uid, 4, "0");
540 std::ofstream dstof(dst.c_str(), std::ios::binary);
541 printf("copying '%s' to '%s'\n", src.c_str(), dst.c_str());
542 dstof << srcif.rdbuf();
543 srcif.close();
544 dstof.close();
545 }
546 closedir(dir);
547 if (!found_subid && !mKey_Prefix.empty() && !keystoreid.empty())
548 found_subid = true;
549 return found_subid;
550}
551
552/* C++ replacement for function of the same name
553 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#867
554 * returning an empty string indicates an error */
555std::string unwrapSyntheticPasswordBlob(const std::string& spblob_path, const std::string& handle_str, const userid_t user_id,
556 const void* application_id, const size_t application_id_size, uint32_t auth_token_len) {
557 std::string disk_decryption_secret_key = "";
558
559 android::ProcessState::self()->startThreadPool();
560
561 std::string keystore_alias_subid;
562 if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid, handle_str)) {
563 printf("failed to scan keystore alias subid and prep keystore files\n");
564 return disk_decryption_secret_key;
565 }
566
567 // First get the keystore service
568 android::sp<IBinder> binder = getKeystoreBinderRetry();
569 android::sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
570
571 if (service == NULL) {
572 printf("error: could not connect to keystore service\n");
573 return disk_decryption_secret_key;
574 }
575
576 if (auth_token_len > 0) {
577 printf("Starting keystore_auth service...\n");
578 property_set("ctl.start", "keystore_auth");
579 }
580
581 // 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
582 std::string spblob_file = spblob_path + handle_str + ".spblob";
583 std::string spblob_data;
584 if (!android::base::ReadFileToString(spblob_file, &spblob_data)) {
585 printf("Failed to read '%s'\n", spblob_file.c_str());
586 return disk_decryption_secret_key;
587 }
588 unsigned char* byteptr = (unsigned char*)spblob_data.data();
589 if (*byteptr != SYNTHETIC_PASSWORD_VERSION_V2 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V1
590 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V3) {
591 printf("Unsupported synthetic password version %i\n", *byteptr);
592 return disk_decryption_secret_key;
593 }
594 const unsigned char* synthetic_password_version = byteptr;
595 byteptr++;
596 if (*byteptr != SYNTHETIC_PASSWORD_PASSWORD_BASED) {
597 printf("spblob data is not SYNTHETIC_PASSWORD_PASSWORD_BASED\n");
598 return disk_decryption_secret_key;
599 }
600 byteptr++; // Now we're pointing to the blob data itself
601 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V2
602 || *synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
603 printf("spblob v2 / v3\n");
604 /* 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
605 * as seen in https://android.googlesource.com/platform/frameworks/base/+/5025791ac6d1538224e19189397de8d71dcb1a12
606 */
607 /* First decrypt call found in
608 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#135
609 * We will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
610 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
611 * First we set some algorithm parameters as seen in two places:
612 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
613 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
614 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
615 if (auth_token_len > 0) {
616 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
617 if (!auth_result.isOk()) {
618 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
619 printf("keystore error adding auth token\n");
620 return disk_decryption_secret_key;
621 }*/
622 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
623 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
624 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
625 // the /auth_token file never gets deleted.
626 int auth_wait_count = 20;
627 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
628 usleep(5000);
629 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
630 printf("error during keymaster_auth service\n");
631 /* 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 -0400632 * service keystore_auth /system/bin/keystore_auth
bigbiff7ba75002020-04-11 20:47:09 -0400633 * disabled
634 * oneshot
635 * user system
636 * group root
637 * seclabel u:r:recovery:s0
638 *
639 * And check dmesg for error codes regarding this service if needed. */
640 return disk_decryption_secret_key;
641 }
642 }
643 int32_t ret;
644 size_t maclen = 128;
645 unsigned char* iv = (unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
646 ::keystore::hidl_vec<uint8_t> iv_hidlvec;
647 iv_hidlvec.setToExternal((unsigned char*)byteptr, 12);
648 // printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
649 std::string keystore_alias = mKey_Prefix;
650 keystore_alias += keystore_alias_subid;
651 String16 keystore_alias16(keystore_alias.data(), keystore_alias.size());
652 int32_t error_code;
653 unsigned char* cipher_text = (unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
654 std::string cipher_text_str(byteptr, byteptr + spblob_data.size() - 14);
655
656 ::keystore::hidl_vec<uint8_t> cipher_text_hidlvec;
657 ::keystore::AuthorizationSetBuilder begin_params;
658
659 cipher_text_hidlvec.setToExternal(cipher_text, spblob_data.size() - 14 /* 1 each for version and SYNTHETIC_PASSWORD_PASSWORD_BASED and 12 for the iv */);
660 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
661 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
662 begin_params.Padding(::keystore::PaddingMode::NONE);
663 begin_params.Authorization(::keystore::TAG_NONCE, iv_hidlvec);
664 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
665
666 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
667 entropy.resize(0);
668 android::security::keymaster::KeymasterArguments empty_params;
669 android::hardware::keymaster::V4_0::KeyPurpose decryptPurpose = android::hardware::keymaster::V4_0::KeyPurpose::DECRYPT;
670 android::sp<android::IBinder> decryptAuthToken(new android::BBinder);
671
672 android::sp<OperationResultPromise> promise = new OperationResultPromise;
673 auto future = promise->get_future();
674 auto binder_result = service->begin(promise, decryptAuthToken, keystore_alias16, (int32_t)decryptPurpose, true,
675 android::security::keymaster::KeymasterArguments(begin_params.hidl_data()),
676 entropy, -1, &error_code);
677 if (!binder_result.isOk()) {
678 printf("communication error while calling keystore\n");
679 return disk_decryption_secret_key;
680 }
681 ::keystore::KeyStoreNativeReturnCode rc(error_code);
682 if (!rc.isOk()) {
683 printf("Keystore begin returned: %u\n", error_code);
684 return disk_decryption_secret_key;
685 }
686 OperationResult result = future.get();
687 auto handle = std::move(result.token);
688
689 // 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
690 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
691 future = {};
692 promise = new OperationResultPromise();
693 future = promise->get_future();
694 binder_result = service->update(promise, handle, empty_params, cipher_text_hidlvec, &error_code);
695 rc = ::keystore::KeyStoreNativeReturnCode(error_code);
696 if (!rc.isOk()) {
697 printf("Keystore update returned: %d\n", error_code);
698 return disk_decryption_secret_key;
699 }
700 result = future.get();
701 if (!result.resultCode.isOk()) {
702 printf("update failed: %d\n", error_code);
703 return disk_decryption_secret_key;
704 }
705
706 size_t keystore_result_size = result.data.size();
707 unsigned char* keystore_result = (unsigned char*)malloc(keystore_result_size);
708 if (!keystore_result) {
709 printf("malloc on keystore_result\n");
710 return disk_decryption_secret_key;
711 }
712 memcpy(keystore_result, &result.data[0], result.data.size());
713 future = {};
714 promise = new OperationResultPromise();
715 future = promise->get_future();
716 ::keystore::hidl_vec<uint8_t> signature;
717 binder_result = service->finish(promise, handle, empty_params, signature, entropy, &error_code);
718 if (!binder_result.isOk()) {
719 printf("communication error while calling keystore\n");
720 free(keystore_result);
721 return disk_decryption_secret_key;
722 }
723 rc = ::keystore::KeyStoreNativeReturnCode(error_code);
724 if (!rc.isOk()) {
725 printf("Keystore finish returned: %d\n", error_code);
726 return disk_decryption_secret_key;
727 }
728 result = future.get();
729 if (!result.resultCode.isOk()) {
730 printf("finish failed: %d\n", error_code);
731 return disk_decryption_secret_key;
732 }
733 stop_keystore();
734 /* Now we do the second decrypt call as seen in:
735 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#136
736 */
737 const unsigned char* intermediate_iv = keystore_result;
738 // printf("intermediate_iv: "); output_hex((const unsigned char*)intermediate_iv, 12); printf("\n");
739 const unsigned char* intermediate_cipher_text = (const unsigned char*)keystore_result + 12; // The cipher text comes immediately after the IV
740 int cipher_size = keystore_result_size - 12;
741 // 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
742 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
743 if (!personalized_application_id) {
744 return disk_decryption_secret_key;
745 }
746 // printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
747 // Now we'll decrypt using openssl AES/GCM/NoPadding
748 OpenSSL_add_all_ciphers();
749 int actual_size=0, final_size=0;
750 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
751 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
752 // printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
753 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, intermediate_iv);
754 unsigned char* secret_key = (unsigned char*)malloc(cipher_size);
755 if (!secret_key) {
756 printf("malloc failure on secret key\n");
757 return disk_decryption_secret_key;
758 }
759 EVP_DecryptUpdate(d_ctx, secret_key, &actual_size, intermediate_cipher_text, cipher_size);
760 unsigned char tag[AES_BLOCK_SIZE];
761 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
762 EVP_DecryptFinal_ex(d_ctx, secret_key + actual_size, &final_size);
763 EVP_CIPHER_CTX_free(d_ctx);
764 free(personalized_application_id);
765 free(keystore_result);
766 int secret_key_real_size = actual_size - 16;
767 // printf("secret key: "); output_hex((const unsigned char*)secret_key, secret_key_real_size); printf("\n");
768 // 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
769 // We now have the disk decryption key!
770 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
771 // V3 uses SP800 instead of SHA512
772 disk_decryption_secret_key = PersonalizedHashSP800(PERSONALIZATION_FBE_KEY, PERSONALISATION_CONTEXT, (const char*)secret_key, secret_key_real_size);
773 } else {
774 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)secret_key, secret_key_real_size);
775 }
776 // printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
777 free(secret_key);
778 return disk_decryption_secret_key;
779 }
780 return disk_decryption_secret_key;
781}
782
783}}
784
785#define PASSWORD_TOKEN_SIZE 32
786
787/* C++ replacement for
788 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#992
789 * called here
790 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#813 */
791bool Get_Secdis(const std::string& spblob_path, const std::string& handle_str, std::string& secdis_data) {
792 std::string secdis_file = spblob_path + handle_str + ".secdis";
793 if (!android::base::ReadFileToString(secdis_file, &secdis_data)) {
794 printf("Failed to read '%s'\n", secdis_file.c_str());
795 return false;
796 }
797 // output_hex(secdis_data.data(), secdis_data.size());printf("\n");
798 return true;
799}
800
801// 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
802userid_t fakeUid(const userid_t uid) {
803 return 100000 + uid;
804}
805
806bool Is_Weaver(const std::string& spblob_path, const std::string& handle_str) {
807 std::string weaver_file = spblob_path + handle_str + ".weaver";
808 struct stat st;
809 if (stat(weaver_file.c_str(), &st) == 0)
810 return true;
811 return false;
812}
813
814bool Free_Return(bool retval, void* weaver_key, password_data_struct* pwd) {
815 if (weaver_key)
816 free(weaver_key);
817 if (pwd->salt)
818 free(pwd->salt);
819 if (pwd->password_handle)
820 free(pwd->password_handle);
821 return retval;
822}
823
824/* Decrypt_User_Synth_Pass is the TWRP C++ equivalent to spBasedDoVerifyCredential
825 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#1998 */
826bool Decrypt_User_Synth_Pass(const userid_t user_id, const std::string& Password) {
827 bool retval = false;
828 void* weaver_key = NULL;
829 password_data_struct pwd;
830 pwd.salt = NULL;
831 pwd.salt_len = 0;
832 pwd.password_handle = NULL;
833 pwd.handle_len = 0;
834 char application_id[PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH];
835
836 uint32_t auth_token_len = 0;
837
838 std::string secret; // this will be the disk decryption key that is sent to vold
839 std::string token = "!"; // there is no token used for this kind of decrypt, key escrow is handled by weaver
840 int flags = FLAG_STORAGE_DE;
841 if (user_id == 0)
842 flags = FLAG_STORAGE_DE;
843 else
844 flags = FLAG_STORAGE_CE;
845 char spblob_path_char[PATH_MAX];
846 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
847 std::string spblob_path = spblob_path_char;
848 long handle = 0;
849 std::string handle_str;
850 // 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
851 if (!Find_Handle(spblob_path, handle_str)) {
852 printf("Error getting handle\n");
853 return Free_Return(retval, weaver_key, &pwd);
854 }
855 // printf("Handle is '%s'\n", handle_str.c_str());
856 // 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
857 // First we read the password data which contains scrypt parameters
858 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
859 printf("Failed to Get_Password_Data\n");
860 return Free_Return(retval, weaver_key, &pwd);
861 }
862 // 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");
863 unsigned char password_token[PASSWORD_TOKEN_SIZE];
864 // printf("Password: '%s'\n", Password.c_str());
865 // The password token is the password scrypted with the parameters from the password data file
866 if (!Get_Password_Token(&pwd, Password, &password_token[0])) {
867 printf("Failed to Get_Password_Token\n");
868 return Free_Return(retval, weaver_key, &pwd);
869 }
870 // output_hex(&password_token[0], PASSWORD_TOKEN_SIZE);printf("\n");
871 if (Is_Weaver(spblob_path, handle_str)) {
872 printf("using weaver\n");
873 // BEGIN PIXEL 2 WEAVER
874 // Get the weaver data from the .weaver file which tells us which slot to use when we ask weaver for the escrowed key
875 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768
876 weaver_data_struct wd;
877 if (!Get_Weaver_Data(spblob_path, handle_str, &wd)) {
878 printf("Failed to get weaver data\n");
879 return Free_Return(retval, weaver_key, &pwd);
880 }
881 // The weaver key is the the password token prefixed with "weaver-key" padded to 128 with nulls with the password token appended then SHA512
882 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1059
883 weaver_key = PersonalizedHashBinary(PERSONALISATION_WEAVER_KEY, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
884 if (!weaver_key) {
885 printf("malloc error getting weaver_key\n");
886 return Free_Return(retval, weaver_key, &pwd);
887 }
888 // 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
889 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#776
890 android::vold::Weaver weaver;
891 if (!weaver) {
892 printf("Failed to get weaver service\n");
893 return Free_Return(retval, weaver_key, &pwd);
894 }
895 // Get the key size from weaver service
896 uint32_t weaver_key_size = 0;
897 if (!weaver.GetKeySize(&weaver_key_size)) {
898 printf("Failed to get weaver key size\n");
899 return Free_Return(retval, weaver_key, &pwd);
900 } else {
901 printf("weaver key size is %u\n", weaver_key_size);
902 }
903 // printf("weaver key: "); output_hex((unsigned char*)weaver_key, weaver_key_size); printf("\n");
904 // Send the slot from the .weaver file, the computed weaver key, and get the escrowed key data
905 std::vector<uint8_t> weaver_payload;
906 // TODO: we should return more information about the status including time delays before the next retry
907 if (!weaver.WeaverVerify(wd.slot, weaver_key, &weaver_payload)) {
908 printf("failed to weaver verify\n");
909 return Free_Return(retval, weaver_key, &pwd);
910 }
911 // printf("weaver payload: "); output_hex(&weaver_payload); printf("\n");
912 // Done with weaverVerify
913 // Now we will compute the application ID
914 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#964
915 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#780
916 // The escrowed weaver key data is prefixed with "weaver-pwd" padded to 128 with nulls with the weaver payload appended then SHA512
917 void* weaver_secret = PersonalizedHashBinary(PERSONALISATION_WEAVER_PASSWORD, (const char*)weaver_payload.data(), weaver_payload.size());
918 // printf("weaver secret: "); output_hex((unsigned char*)weaver_secret, SHA512_DIGEST_LENGTH); printf("\n");
919 // The application ID is the password token and weaver secret appended to each other
920 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
921 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], weaver_secret, SHA512_DIGEST_LENGTH);
922 // printf("application ID: "); output_hex((unsigned char*)application_id, PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH); printf("\n");
923 // END PIXEL 2 WEAVER
924 } else {
925 printf("using secdis\n");
926 std::string secdis_data;
927 if (!Get_Secdis(spblob_path, handle_str, secdis_data)) {
928 printf("Failed to get secdis data\n");
929 return Free_Return(retval, weaver_key, &pwd);
930 }
931 void* secdiscardable = PersonalizedHashBinary(PERSONALISATION_SECDISCARDABLE, (char*)secdis_data.data(), secdis_data.size());
932 if (!secdiscardable) {
933 printf("malloc error getting secdiscardable\n");
934 return Free_Return(retval, weaver_key, &pwd);
935 }
936 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
937 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], secdiscardable, SHA512_DIGEST_LENGTH);
938
939 int ret = -1;
940 bool request_reenroll = false;
941 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
942 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
943 if (gk_device == nullptr) {
944 printf("failed to get gatekeeper service\n");
945 return Free_Return(retval, weaver_key, &pwd);
946 }
947 if (pwd.handle_len <= 0) {
948 printf("no password handle supplied\n");
949 return Free_Return(retval, weaver_key, &pwd);
950 }
951 android::hardware::hidl_vec<uint8_t> pwd_handle_hidl;
952 pwd_handle_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)pwd.password_handle), pwd.handle_len);
953 void* gk_pwd_token = PersonalizedHashBinary(PERSONALIZATION_USER_GK_AUTH, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
954 if (!gk_pwd_token) {
955 printf("malloc error getting gatekeeper_key\n");
956 return Free_Return(retval, weaver_key, &pwd);
957 }
958 android::hardware::hidl_vec<uint8_t> gk_pwd_token_hidl;
959 gk_pwd_token_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)gk_pwd_token), SHA512_DIGEST_LENGTH);
960 android::hardware::Return<void> hwRet =
961 gk_device->verify(fakeUid(user_id), 0 /* challange */,
962 pwd_handle_hidl,
963 gk_pwd_token_hidl,
964 [&ret, &request_reenroll, &auth_token_len]
965 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
966 ret = static_cast<int>(rsp.code); // propagate errors
967 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
968 auth_token_len = rsp.data.size();
969 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
970 ret = 0; // all success states are reported as 0
971 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file here and later
972 // run a separate service that runs as the system user to add the auth token. We wait for the auth token file to be
973 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after a while seconds if
974 // the /auth_token file never gets deleted.
975 unlink("/auth_token");
976 FILE* auth_file = fopen("/auth_token","wb");
977 if (auth_file != NULL) {
978 fwrite(rsp.data.data(), sizeof(uint8_t), rsp.data.size(), auth_file);
979 fclose(auth_file);
980 } else {
981 printf("failed to open /auth_token for writing\n");
982 ret = -2;
983 }
984 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
985 ret = rsp.timeout;
986 }
987 }
988 );
989 free(gk_pwd_token);
990 if (!hwRet.isOk() || ret != 0) {
991 printf("gatekeeper verification failed\n");
992 return Free_Return(retval, weaver_key, &pwd);
993 }
994 }
995 // 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
996 // Plus we will include the last bit that computes the disk decrypt key found in:
997 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#153
998 secret = android::keystore::unwrapSyntheticPasswordBlob(spblob_path, handle_str, user_id, (const void*)&application_id[0],
999 PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH, auth_token_len);
1000 if (!secret.size()) {
1001 printf("failed to unwrapSyntheticPasswordBlob\n");
1002 return Free_Return(retval, weaver_key, &pwd);
1003 }
1004
1005 if (!fscrypt_unlock_user_key(user_id, 0, token.c_str(), secret.c_str())) {
1006 printf("fscrypt_unlock_user_key returned fail\n");
1007 return Free_Return(retval, weaver_key, &pwd);
1008 }
1009
1010 if (!fscrypt_prepare_user_storage("", user_id, 0, flags)) {
1011 printf("failed to fscrypt_prepare_user_storage\n");
1012 return Free_Return(retval, weaver_key, &pwd);
1013 }
1014 printf("Decrypted Successfully!\n");
1015 retval = true;
1016 return Free_Return(retval, weaver_key, &pwd);
1017}
1018
1019int Get_Password_Type(const userid_t user_id, std::string& filename) {
1020 struct stat st;
1021 char spblob_path_char[PATH_MAX];
1022 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
1023 if (stat(spblob_path_char, &st) == 0) {
1024 printf("Using synthetic password method\n");
1025 std::string spblob_path = spblob_path_char;
1026 std::string handle_str;
1027 if (!Find_Handle(spblob_path, handle_str)) {
1028 printf("Error getting handle\n");
1029 return 0;
1030 }
1031 printf("Handle is '%s'\n", handle_str.c_str());
1032 password_data_struct pwd;
1033 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
1034 printf("Failed to Get_Password_Data\n");
1035 return 0;
1036 }
1037 if (pwd.password_type == 1) { // In Android this means pattern
1038 printf("password type: pattern\n");
1039 return 2; // In TWRP this means pattern
1040 }
1041 else if (pwd.password_type == 2) { // In Android this means PIN or password
1042 printf("password type: pin\n");
1043 return 1; // In TWRP this means PIN or password
1044 }
1045 printf("using default password\n");
1046 return 0; // We'll try the default password
1047 }
1048 std::string path;
1049 if (user_id == 0) {
1050 path = "/data/system/";
1051 } else {
1052 char user_id_str[5];
1053 sprintf(user_id_str, "%i", user_id);
1054 path = "/data/system/users/";
1055 path += user_id_str;
1056 path += "/";
1057 }
1058 filename = path + "gatekeeper.password.key";
1059 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1060 return 1;
1061 filename = path + "gatekeeper.pattern.key";
1062 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1063 return 2;
1064 printf("Unable to locate gatekeeper password file '%s'\n", filename.c_str());
1065 filename = "";
1066 return 0;
1067}
1068
1069bool Decrypt_User(const userid_t user_id, const std::string& Password) {
1070 uint8_t *auth_token;
1071 uint32_t auth_token_len;
1072 int ret;
1073
1074 struct stat st;
1075 if (user_id > 9999) {
1076 printf("user_id is too big\n");
1077 return false;
1078 }
1079 std::string filename;
1080 bool Default_Password = (Password == "!");
1081 if (Get_Password_Type(user_id, filename) == 0 && !Default_Password) {
1082 printf("Unknown password type\n");
1083 return false;
1084 }
1085 int flags = FLAG_STORAGE_DE;
1086 if (user_id == 0)
1087 flags = FLAG_STORAGE_DE;
1088 else
1089 flags = FLAG_STORAGE_CE;
1090
1091 if (Default_Password) {
1092 if (!fscrypt_unlock_user_key(user_id, 0, "!", "!")) {
1093 printf("unlock_user_key returned fail\n");
1094 return false;
1095 }
1096 if (!fscrypt_prepare_user_storage("", user_id, 0, flags)) {
1097 printf("failed to fscrypt_prepare_user_storage\n");
1098 return false;
1099 }
1100 printf("Decrypted Successfully!\n");
1101 return true;
1102 }
1103 if (stat("/data/system_de/0/spblob", &st) == 0) {
1104 printf("Using synthetic password method\n");
1105 return Decrypt_User_Synth_Pass(user_id, Password);
1106 }
1107 // printf("password filename is '%s'\n", filename.c_str());
1108 if (stat(filename.c_str(), &st) != 0) {
1109 printf("error stat'ing key file: %s\n", strerror(errno));
1110 return false;
1111 }
1112 std::string handle;
1113 if (!android::base::ReadFileToString(filename, &handle)) {
1114 printf("Failed to read '%s'\n", filename.c_str());
1115 return false;
1116 }
1117 bool should_reenroll;
1118 bool request_reenroll = false;
1119 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1120 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1121 if (gk_device == nullptr)
1122 return false;
1123 android::hardware::hidl_vec<uint8_t> curPwdHandle;
1124 curPwdHandle.setToExternal(const_cast<uint8_t *>((const uint8_t *)handle.c_str()), st.st_size);
1125 android::hardware::hidl_vec<uint8_t> enteredPwd;
1126 enteredPwd.setToExternal(const_cast<uint8_t *>((const uint8_t *)Password.c_str()), Password.size());
1127
1128 android::hardware::Return<void> hwRet =
1129 gk_device->verify(user_id, 0 /* challange */,
1130 curPwdHandle,
1131 enteredPwd,
1132 [&ret, &request_reenroll, &auth_token, &auth_token_len]
1133 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1134 ret = static_cast<int>(rsp.code); // propagate errors
1135 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1136 auth_token = new uint8_t[rsp.data.size()];
1137 auth_token_len = rsp.data.size();
1138 memcpy(auth_token, rsp.data.data(), auth_token_len);
1139 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1140 ret = 0; // all success states are reported as 0
1141 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1142 ret = rsp.timeout;
1143 }
1144 }
1145 );
1146 if (!hwRet.isOk()) {
1147 return false;
1148 }
1149
1150 char token_hex[(auth_token_len*2)+1];
1151 token_hex[(auth_token_len*2)] = 0;
1152 uint32_t i;
1153 for (i=0;i<auth_token_len;i++) {
1154 sprintf(&token_hex[2*i], "%02X", auth_token[i]);
1155 }
1156 // 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
1157 std::string secret = HashPassword(Password);
1158 if (!fscrypt_unlock_user_key(user_id, 0, token_hex, secret.c_str())) {
1159 printf("fscrypt_unlock_user_key returned fail\n");
1160 return false;
1161 }
1162
1163 if (!fscrypt_prepare_user_storage("", user_id, 0, flags)) {
1164 printf("failed to fscrypt_prepare_user_storage\n");
1165 return false;
1166 }
1167 printf("Decrypted Successfully!\n");
1168 return true;
1169}