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