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