blob: 1e62ce2687689ede63473dc4097129bf9adf7872 [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;
Noah Jacobson81d638d2019-04-28 00:10:07 -0400562 // Can be stored in user 0, so check for both.
563 if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid, handle_str) &&
564 !Find_Keystore_Alias_SubID_And_Prep_Files(0, keystore_alias_subid, handle_str))
565 {
bigbiff7ba75002020-04-11 20:47:09 -0400566 printf("failed to scan keystore alias subid and prep keystore files\n");
567 return disk_decryption_secret_key;
568 }
569
570 // First get the keystore service
571 android::sp<IBinder> binder = getKeystoreBinderRetry();
572 android::sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
573
574 if (service == NULL) {
575 printf("error: could not connect to keystore service\n");
576 return disk_decryption_secret_key;
577 }
578
579 if (auth_token_len > 0) {
580 printf("Starting keystore_auth service...\n");
581 property_set("ctl.start", "keystore_auth");
582 }
583
584 // 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
585 std::string spblob_file = spblob_path + handle_str + ".spblob";
586 std::string spblob_data;
587 if (!android::base::ReadFileToString(spblob_file, &spblob_data)) {
588 printf("Failed to read '%s'\n", spblob_file.c_str());
589 return disk_decryption_secret_key;
590 }
591 unsigned char* byteptr = (unsigned char*)spblob_data.data();
592 if (*byteptr != SYNTHETIC_PASSWORD_VERSION_V2 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V1
593 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V3) {
594 printf("Unsupported synthetic password version %i\n", *byteptr);
595 return disk_decryption_secret_key;
596 }
597 const unsigned char* synthetic_password_version = byteptr;
598 byteptr++;
599 if (*byteptr != SYNTHETIC_PASSWORD_PASSWORD_BASED) {
600 printf("spblob data is not SYNTHETIC_PASSWORD_PASSWORD_BASED\n");
601 return disk_decryption_secret_key;
602 }
603 byteptr++; // Now we're pointing to the blob data itself
604 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V2
605 || *synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
606 printf("spblob v2 / v3\n");
607 /* 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
608 * as seen in https://android.googlesource.com/platform/frameworks/base/+/5025791ac6d1538224e19189397de8d71dcb1a12
609 */
610 /* First decrypt call found in
611 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#135
612 * We will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
613 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
614 * First we set some algorithm parameters as seen in two places:
615 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
616 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
617 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
618 if (auth_token_len > 0) {
619 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
620 if (!auth_result.isOk()) {
621 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
622 printf("keystore error adding auth token\n");
623 return disk_decryption_secret_key;
624 }*/
625 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
626 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
627 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
628 // the /auth_token file never gets deleted.
629 int auth_wait_count = 20;
630 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
631 usleep(5000);
632 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
633 printf("error during keymaster_auth service\n");
634 /* 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 -0400635 * service keystore_auth /system/bin/keystore_auth
bigbiff7ba75002020-04-11 20:47:09 -0400636 * disabled
637 * oneshot
638 * user system
639 * group root
640 * seclabel u:r:recovery:s0
641 *
642 * And check dmesg for error codes regarding this service if needed. */
643 return disk_decryption_secret_key;
644 }
645 }
646 int32_t ret;
647 size_t maclen = 128;
648 unsigned char* iv = (unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
649 ::keystore::hidl_vec<uint8_t> iv_hidlvec;
650 iv_hidlvec.setToExternal((unsigned char*)byteptr, 12);
651 // printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
652 std::string keystore_alias = mKey_Prefix;
653 keystore_alias += keystore_alias_subid;
654 String16 keystore_alias16(keystore_alias.data(), keystore_alias.size());
655 int32_t error_code;
656 unsigned char* cipher_text = (unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
657 std::string cipher_text_str(byteptr, byteptr + spblob_data.size() - 14);
658
659 ::keystore::hidl_vec<uint8_t> cipher_text_hidlvec;
660 ::keystore::AuthorizationSetBuilder begin_params;
661
662 cipher_text_hidlvec.setToExternal(cipher_text, spblob_data.size() - 14 /* 1 each for version and SYNTHETIC_PASSWORD_PASSWORD_BASED and 12 for the iv */);
663 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
664 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
665 begin_params.Padding(::keystore::PaddingMode::NONE);
666 begin_params.Authorization(::keystore::TAG_NONCE, iv_hidlvec);
667 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
668
669 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
670 entropy.resize(0);
671 android::security::keymaster::KeymasterArguments empty_params;
672 android::hardware::keymaster::V4_0::KeyPurpose decryptPurpose = android::hardware::keymaster::V4_0::KeyPurpose::DECRYPT;
673 android::sp<android::IBinder> decryptAuthToken(new android::BBinder);
674
675 android::sp<OperationResultPromise> promise = new OperationResultPromise;
676 auto future = promise->get_future();
677 auto binder_result = service->begin(promise, decryptAuthToken, keystore_alias16, (int32_t)decryptPurpose, true,
678 android::security::keymaster::KeymasterArguments(begin_params.hidl_data()),
679 entropy, -1, &error_code);
680 if (!binder_result.isOk()) {
681 printf("communication error while calling keystore\n");
682 return disk_decryption_secret_key;
683 }
684 ::keystore::KeyStoreNativeReturnCode rc(error_code);
685 if (!rc.isOk()) {
686 printf("Keystore begin returned: %u\n", error_code);
687 return disk_decryption_secret_key;
688 }
689 OperationResult result = future.get();
690 auto handle = std::move(result.token);
691
692 // 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
693 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
694 future = {};
695 promise = new OperationResultPromise();
696 future = promise->get_future();
697 binder_result = service->update(promise, handle, empty_params, cipher_text_hidlvec, &error_code);
698 rc = ::keystore::KeyStoreNativeReturnCode(error_code);
699 if (!rc.isOk()) {
700 printf("Keystore update returned: %d\n", error_code);
701 return disk_decryption_secret_key;
702 }
703 result = future.get();
704 if (!result.resultCode.isOk()) {
705 printf("update failed: %d\n", error_code);
706 return disk_decryption_secret_key;
707 }
708
709 size_t keystore_result_size = result.data.size();
710 unsigned char* keystore_result = (unsigned char*)malloc(keystore_result_size);
711 if (!keystore_result) {
712 printf("malloc on keystore_result\n");
713 return disk_decryption_secret_key;
714 }
715 memcpy(keystore_result, &result.data[0], result.data.size());
716 future = {};
717 promise = new OperationResultPromise();
718 future = promise->get_future();
719 ::keystore::hidl_vec<uint8_t> signature;
720 binder_result = service->finish(promise, handle, empty_params, signature, entropy, &error_code);
721 if (!binder_result.isOk()) {
722 printf("communication error while calling keystore\n");
723 free(keystore_result);
724 return disk_decryption_secret_key;
725 }
726 rc = ::keystore::KeyStoreNativeReturnCode(error_code);
727 if (!rc.isOk()) {
728 printf("Keystore finish returned: %d\n", error_code);
729 return disk_decryption_secret_key;
730 }
731 result = future.get();
732 if (!result.resultCode.isOk()) {
733 printf("finish failed: %d\n", error_code);
734 return disk_decryption_secret_key;
735 }
736 stop_keystore();
737 /* Now we do the second decrypt call as seen in:
738 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#136
739 */
740 const unsigned char* intermediate_iv = keystore_result;
741 // printf("intermediate_iv: "); output_hex((const unsigned char*)intermediate_iv, 12); printf("\n");
742 const unsigned char* intermediate_cipher_text = (const unsigned char*)keystore_result + 12; // The cipher text comes immediately after the IV
743 int cipher_size = keystore_result_size - 12;
744 // 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
745 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
746 if (!personalized_application_id) {
747 return disk_decryption_secret_key;
748 }
749 // printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
750 // Now we'll decrypt using openssl AES/GCM/NoPadding
751 OpenSSL_add_all_ciphers();
752 int actual_size=0, final_size=0;
753 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
754 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
755 // printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
756 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, intermediate_iv);
757 unsigned char* secret_key = (unsigned char*)malloc(cipher_size);
758 if (!secret_key) {
759 printf("malloc failure on secret key\n");
760 return disk_decryption_secret_key;
761 }
762 EVP_DecryptUpdate(d_ctx, secret_key, &actual_size, intermediate_cipher_text, cipher_size);
763 unsigned char tag[AES_BLOCK_SIZE];
764 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
765 EVP_DecryptFinal_ex(d_ctx, secret_key + actual_size, &final_size);
766 EVP_CIPHER_CTX_free(d_ctx);
767 free(personalized_application_id);
768 free(keystore_result);
769 int secret_key_real_size = actual_size - 16;
770 // printf("secret key: "); output_hex((const unsigned char*)secret_key, secret_key_real_size); printf("\n");
771 // 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
772 // We now have the disk decryption key!
773 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
774 // V3 uses SP800 instead of SHA512
775 disk_decryption_secret_key = PersonalizedHashSP800(PERSONALIZATION_FBE_KEY, PERSONALISATION_CONTEXT, (const char*)secret_key, secret_key_real_size);
776 } else {
777 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)secret_key, secret_key_real_size);
778 }
779 // printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
780 free(secret_key);
781 return disk_decryption_secret_key;
782 }
783 return disk_decryption_secret_key;
784}
785
786}}
787
788#define PASSWORD_TOKEN_SIZE 32
789
790/* C++ replacement for
791 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#992
792 * called here
793 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#813 */
794bool Get_Secdis(const std::string& spblob_path, const std::string& handle_str, std::string& secdis_data) {
795 std::string secdis_file = spblob_path + handle_str + ".secdis";
796 if (!android::base::ReadFileToString(secdis_file, &secdis_data)) {
797 printf("Failed to read '%s'\n", secdis_file.c_str());
798 return false;
799 }
800 // output_hex(secdis_data.data(), secdis_data.size());printf("\n");
801 return true;
802}
803
804// 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
805userid_t fakeUid(const userid_t uid) {
806 return 100000 + uid;
807}
808
809bool Is_Weaver(const std::string& spblob_path, const std::string& handle_str) {
810 std::string weaver_file = spblob_path + handle_str + ".weaver";
811 struct stat st;
812 if (stat(weaver_file.c_str(), &st) == 0)
813 return true;
814 return false;
815}
816
817bool Free_Return(bool retval, void* weaver_key, password_data_struct* pwd) {
818 if (weaver_key)
819 free(weaver_key);
820 if (pwd->salt)
821 free(pwd->salt);
822 if (pwd->password_handle)
823 free(pwd->password_handle);
824 return retval;
825}
826
827/* Decrypt_User_Synth_Pass is the TWRP C++ equivalent to spBasedDoVerifyCredential
828 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#1998 */
829bool Decrypt_User_Synth_Pass(const userid_t user_id, const std::string& Password) {
830 bool retval = false;
831 void* weaver_key = NULL;
832 password_data_struct pwd;
833 pwd.salt = NULL;
834 pwd.salt_len = 0;
835 pwd.password_handle = NULL;
836 pwd.handle_len = 0;
837 char application_id[PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH];
838
839 uint32_t auth_token_len = 0;
840
841 std::string secret; // this will be the disk decryption key that is sent to vold
842 std::string token = "!"; // there is no token used for this kind of decrypt, key escrow is handled by weaver
843 int flags = FLAG_STORAGE_DE;
844 if (user_id == 0)
845 flags = FLAG_STORAGE_DE;
846 else
847 flags = FLAG_STORAGE_CE;
848 char spblob_path_char[PATH_MAX];
849 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
850 std::string spblob_path = spblob_path_char;
851 long handle = 0;
852 std::string handle_str;
853 // 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
854 if (!Find_Handle(spblob_path, handle_str)) {
855 printf("Error getting handle\n");
856 return Free_Return(retval, weaver_key, &pwd);
857 }
858 // printf("Handle is '%s'\n", handle_str.c_str());
859 // 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
860 // First we read the password data which contains scrypt parameters
861 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
862 printf("Failed to Get_Password_Data\n");
863 return Free_Return(retval, weaver_key, &pwd);
864 }
865 // 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");
866 unsigned char password_token[PASSWORD_TOKEN_SIZE];
867 // printf("Password: '%s'\n", Password.c_str());
868 // The password token is the password scrypted with the parameters from the password data file
869 if (!Get_Password_Token(&pwd, Password, &password_token[0])) {
870 printf("Failed to Get_Password_Token\n");
871 return Free_Return(retval, weaver_key, &pwd);
872 }
873 // output_hex(&password_token[0], PASSWORD_TOKEN_SIZE);printf("\n");
874 if (Is_Weaver(spblob_path, handle_str)) {
875 printf("using weaver\n");
876 // BEGIN PIXEL 2 WEAVER
877 // Get the weaver data from the .weaver file which tells us which slot to use when we ask weaver for the escrowed key
878 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768
879 weaver_data_struct wd;
880 if (!Get_Weaver_Data(spblob_path, handle_str, &wd)) {
881 printf("Failed to get weaver data\n");
882 return Free_Return(retval, weaver_key, &pwd);
883 }
884 // The weaver key is the the password token prefixed with "weaver-key" padded to 128 with nulls with the password token appended then SHA512
885 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1059
886 weaver_key = PersonalizedHashBinary(PERSONALISATION_WEAVER_KEY, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
887 if (!weaver_key) {
888 printf("malloc error getting weaver_key\n");
889 return Free_Return(retval, weaver_key, &pwd);
890 }
891 // 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
892 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#776
893 android::vold::Weaver weaver;
894 if (!weaver) {
895 printf("Failed to get weaver service\n");
896 return Free_Return(retval, weaver_key, &pwd);
897 }
898 // Get the key size from weaver service
899 uint32_t weaver_key_size = 0;
900 if (!weaver.GetKeySize(&weaver_key_size)) {
901 printf("Failed to get weaver key size\n");
902 return Free_Return(retval, weaver_key, &pwd);
903 } else {
904 printf("weaver key size is %u\n", weaver_key_size);
905 }
906 // printf("weaver key: "); output_hex((unsigned char*)weaver_key, weaver_key_size); printf("\n");
907 // Send the slot from the .weaver file, the computed weaver key, and get the escrowed key data
908 std::vector<uint8_t> weaver_payload;
909 // TODO: we should return more information about the status including time delays before the next retry
910 if (!weaver.WeaverVerify(wd.slot, weaver_key, &weaver_payload)) {
911 printf("failed to weaver verify\n");
912 return Free_Return(retval, weaver_key, &pwd);
913 }
914 // printf("weaver payload: "); output_hex(&weaver_payload); printf("\n");
915 // Done with weaverVerify
916 // Now we will compute the application ID
917 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#964
918 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#780
919 // The escrowed weaver key data is prefixed with "weaver-pwd" padded to 128 with nulls with the weaver payload appended then SHA512
920 void* weaver_secret = PersonalizedHashBinary(PERSONALISATION_WEAVER_PASSWORD, (const char*)weaver_payload.data(), weaver_payload.size());
921 // printf("weaver secret: "); output_hex((unsigned char*)weaver_secret, SHA512_DIGEST_LENGTH); printf("\n");
922 // The application ID is the password token and weaver secret appended to each other
923 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
924 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], weaver_secret, SHA512_DIGEST_LENGTH);
925 // printf("application ID: "); output_hex((unsigned char*)application_id, PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH); printf("\n");
926 // END PIXEL 2 WEAVER
927 } else {
928 printf("using secdis\n");
929 std::string secdis_data;
930 if (!Get_Secdis(spblob_path, handle_str, secdis_data)) {
931 printf("Failed to get secdis data\n");
932 return Free_Return(retval, weaver_key, &pwd);
933 }
934 void* secdiscardable = PersonalizedHashBinary(PERSONALISATION_SECDISCARDABLE, (char*)secdis_data.data(), secdis_data.size());
935 if (!secdiscardable) {
936 printf("malloc error getting secdiscardable\n");
937 return Free_Return(retval, weaver_key, &pwd);
938 }
939 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
940 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], secdiscardable, SHA512_DIGEST_LENGTH);
941
942 int ret = -1;
943 bool request_reenroll = false;
944 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
945 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
946 if (gk_device == nullptr) {
947 printf("failed to get gatekeeper service\n");
948 return Free_Return(retval, weaver_key, &pwd);
949 }
950 if (pwd.handle_len <= 0) {
951 printf("no password handle supplied\n");
952 return Free_Return(retval, weaver_key, &pwd);
953 }
954 android::hardware::hidl_vec<uint8_t> pwd_handle_hidl;
955 pwd_handle_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)pwd.password_handle), pwd.handle_len);
956 void* gk_pwd_token = PersonalizedHashBinary(PERSONALIZATION_USER_GK_AUTH, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
957 if (!gk_pwd_token) {
958 printf("malloc error getting gatekeeper_key\n");
959 return Free_Return(retval, weaver_key, &pwd);
960 }
961 android::hardware::hidl_vec<uint8_t> gk_pwd_token_hidl;
962 gk_pwd_token_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)gk_pwd_token), SHA512_DIGEST_LENGTH);
963 android::hardware::Return<void> hwRet =
964 gk_device->verify(fakeUid(user_id), 0 /* challange */,
965 pwd_handle_hidl,
966 gk_pwd_token_hidl,
967 [&ret, &request_reenroll, &auth_token_len]
968 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
969 ret = static_cast<int>(rsp.code); // propagate errors
970 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
971 auth_token_len = rsp.data.size();
972 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
973 ret = 0; // all success states are reported as 0
974 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file here and later
975 // run a separate service that runs as the system user to add the auth token. We wait for the auth token file to be
976 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after a while seconds if
977 // the /auth_token file never gets deleted.
978 unlink("/auth_token");
979 FILE* auth_file = fopen("/auth_token","wb");
980 if (auth_file != NULL) {
981 fwrite(rsp.data.data(), sizeof(uint8_t), rsp.data.size(), auth_file);
982 fclose(auth_file);
983 } else {
984 printf("failed to open /auth_token for writing\n");
985 ret = -2;
986 }
987 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
988 ret = rsp.timeout;
989 }
990 }
991 );
992 free(gk_pwd_token);
993 if (!hwRet.isOk() || ret != 0) {
994 printf("gatekeeper verification failed\n");
995 return Free_Return(retval, weaver_key, &pwd);
996 }
997 }
998 // 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
999 // Plus we will include the last bit that computes the disk decrypt key found in:
1000 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#153
1001 secret = android::keystore::unwrapSyntheticPasswordBlob(spblob_path, handle_str, user_id, (const void*)&application_id[0],
1002 PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH, auth_token_len);
1003 if (!secret.size()) {
1004 printf("failed to unwrapSyntheticPasswordBlob\n");
1005 return Free_Return(retval, weaver_key, &pwd);
1006 }
1007
1008 if (!fscrypt_unlock_user_key(user_id, 0, token.c_str(), secret.c_str())) {
1009 printf("fscrypt_unlock_user_key returned fail\n");
1010 return Free_Return(retval, weaver_key, &pwd);
1011 }
1012
1013 if (!fscrypt_prepare_user_storage("", user_id, 0, flags)) {
1014 printf("failed to fscrypt_prepare_user_storage\n");
1015 return Free_Return(retval, weaver_key, &pwd);
1016 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001017 printf("User %i Decrypted Successfully!\n", user_id);
bigbiff7ba75002020-04-11 20:47:09 -04001018 retval = true;
1019 return Free_Return(retval, weaver_key, &pwd);
1020}
1021
1022int Get_Password_Type(const userid_t user_id, std::string& filename) {
1023 struct stat st;
1024 char spblob_path_char[PATH_MAX];
1025 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
1026 if (stat(spblob_path_char, &st) == 0) {
1027 printf("Using synthetic password method\n");
1028 std::string spblob_path = spblob_path_char;
1029 std::string handle_str;
1030 if (!Find_Handle(spblob_path, handle_str)) {
1031 printf("Error getting handle\n");
1032 return 0;
1033 }
1034 printf("Handle is '%s'\n", handle_str.c_str());
1035 password_data_struct pwd;
1036 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
1037 printf("Failed to Get_Password_Data\n");
1038 return 0;
1039 }
1040 if (pwd.password_type == 1) { // In Android this means pattern
1041 printf("password type: pattern\n");
1042 return 2; // In TWRP this means pattern
1043 }
1044 else if (pwd.password_type == 2) { // In Android this means PIN or password
1045 printf("password type: pin\n");
1046 return 1; // In TWRP this means PIN or password
1047 }
1048 printf("using default password\n");
1049 return 0; // We'll try the default password
1050 }
1051 std::string path;
1052 if (user_id == 0) {
1053 path = "/data/system/";
1054 } else {
1055 char user_id_str[5];
1056 sprintf(user_id_str, "%i", user_id);
1057 path = "/data/system/users/";
1058 path += user_id_str;
1059 path += "/";
1060 }
1061 filename = path + "gatekeeper.password.key";
1062 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1063 return 1;
1064 filename = path + "gatekeeper.pattern.key";
1065 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1066 return 2;
1067 printf("Unable to locate gatekeeper password file '%s'\n", filename.c_str());
1068 filename = "";
1069 return 0;
1070}
1071
1072bool Decrypt_User(const userid_t user_id, const std::string& Password) {
1073 uint8_t *auth_token;
1074 uint32_t auth_token_len;
1075 int ret;
1076
1077 struct stat st;
1078 if (user_id > 9999) {
1079 printf("user_id is too big\n");
1080 return false;
1081 }
1082 std::string filename;
1083 bool Default_Password = (Password == "!");
1084 if (Get_Password_Type(user_id, filename) == 0 && !Default_Password) {
1085 printf("Unknown password type\n");
1086 return false;
1087 }
1088 int flags = FLAG_STORAGE_DE;
1089 if (user_id == 0)
1090 flags = FLAG_STORAGE_DE;
1091 else
1092 flags = FLAG_STORAGE_CE;
1093
1094 if (Default_Password) {
1095 if (!fscrypt_unlock_user_key(user_id, 0, "!", "!")) {
1096 printf("unlock_user_key returned fail\n");
1097 return false;
1098 }
1099 if (!fscrypt_prepare_user_storage("", user_id, 0, flags)) {
1100 printf("failed to fscrypt_prepare_user_storage\n");
1101 return false;
1102 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001103 printf("User %i Decrypted Successfully!\n", user_id);
bigbiff7ba75002020-04-11 20:47:09 -04001104 return true;
1105 }
1106 if (stat("/data/system_de/0/spblob", &st) == 0) {
1107 printf("Using synthetic password method\n");
1108 return Decrypt_User_Synth_Pass(user_id, Password);
1109 }
1110 // printf("password filename is '%s'\n", filename.c_str());
1111 if (stat(filename.c_str(), &st) != 0) {
1112 printf("error stat'ing key file: %s\n", strerror(errno));
1113 return false;
1114 }
1115 std::string handle;
1116 if (!android::base::ReadFileToString(filename, &handle)) {
1117 printf("Failed to read '%s'\n", filename.c_str());
1118 return false;
1119 }
1120 bool should_reenroll;
1121 bool request_reenroll = false;
1122 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1123 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1124 if (gk_device == nullptr)
1125 return false;
1126 android::hardware::hidl_vec<uint8_t> curPwdHandle;
1127 curPwdHandle.setToExternal(const_cast<uint8_t *>((const uint8_t *)handle.c_str()), st.st_size);
1128 android::hardware::hidl_vec<uint8_t> enteredPwd;
1129 enteredPwd.setToExternal(const_cast<uint8_t *>((const uint8_t *)Password.c_str()), Password.size());
1130
1131 android::hardware::Return<void> hwRet =
1132 gk_device->verify(user_id, 0 /* challange */,
1133 curPwdHandle,
1134 enteredPwd,
1135 [&ret, &request_reenroll, &auth_token, &auth_token_len]
1136 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1137 ret = static_cast<int>(rsp.code); // propagate errors
1138 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1139 auth_token = new uint8_t[rsp.data.size()];
1140 auth_token_len = rsp.data.size();
1141 memcpy(auth_token, rsp.data.data(), auth_token_len);
1142 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1143 ret = 0; // all success states are reported as 0
1144 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1145 ret = rsp.timeout;
1146 }
1147 }
1148 );
1149 if (!hwRet.isOk()) {
1150 return false;
1151 }
1152
1153 char token_hex[(auth_token_len*2)+1];
1154 token_hex[(auth_token_len*2)] = 0;
1155 uint32_t i;
1156 for (i=0;i<auth_token_len;i++) {
1157 sprintf(&token_hex[2*i], "%02X", auth_token[i]);
1158 }
1159 // 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
1160 std::string secret = HashPassword(Password);
1161 if (!fscrypt_unlock_user_key(user_id, 0, token_hex, secret.c_str())) {
1162 printf("fscrypt_unlock_user_key returned fail\n");
1163 return false;
1164 }
1165
1166 if (!fscrypt_prepare_user_storage("", user_id, 0, flags)) {
1167 printf("failed to fscrypt_prepare_user_storage\n");
1168 return false;
1169 }
Noah Jacobson81d638d2019-04-28 00:10:07 -04001170 printf("User %i Decrypted Successfully!\n", user_id);
bigbiff7ba75002020-04-11 20:47:09 -04001171 return true;
1172}