blob: fb162404d03ce1a2103202a3293627ccc5fa8973 [file] [log] [blame]
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001/*
2 * Copyright (C) 2016 The Team Win Recovery Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "Decrypt.h"
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050018#ifdef USE_KEYSTORAGE_4
19#include "Ext4CryptPie.h"
20#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060021#include "Ext4Crypt.h"
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050022#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060023
Ethan Yonker79f88bd2016-12-09 14:52:12 -060024#include <map>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060025#include <string>
26
27#include <errno.h>
28#include <stdio.h>
Ethan Yonker79f88bd2016-12-09 14:52:12 -060029#include <stdlib.h>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060030#include <sys/stat.h>
31#include <sys/types.h>
32
Ethan Yonkerfefe5912017-09-30 22:22:13 -050033#ifndef HAVE_LIBKEYUTILS
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060034#include "key_control.h"
Ethan Yonkerfefe5912017-09-30 22:22:13 -050035#else
36#include <keyutils.h>
37#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060038
Ethan Yonkerfefe5912017-09-30 22:22:13 -050039#ifdef HAVE_SYNTH_PWD_SUPPORT
40#include "Weaver1.h"
41#include "cutils/properties.h"
42
43#include <openssl/sha.h>
44#include <openssl/aes.h>
45#include <openssl/evp.h>
46#include <openssl/rand.h>
47
48#include <dirent.h>
49#include <stdio.h>
50#include <stdint.h>
51#include <string.h>
52#include <sys/types.h>
53#include <fstream>
54
55#include <ext4_utils/ext4_crypt.h>
56
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050057#ifdef USE_KEYSTORAGE_4
58#include <android/security/IKeystoreService.h>
59#else
Ethan Yonkerfefe5912017-09-30 22:22:13 -050060#include <keystore/IKeystoreService.h>
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050061#include <keystore/authorization_set.h>
62#endif
Ethan Yonkerfefe5912017-09-30 22:22:13 -050063#include <binder/IPCThreadState.h>
64#include <binder/IServiceManager.h>
65
66#include <keystore/keystore.h>
Ethan Yonkerfefe5912017-09-30 22:22:13 -050067
68#include <algorithm>
69extern "C" {
70#include "crypto_scrypt.h"
71}
72#else
73#include "ext4_crypt.h"
74#endif //ifdef HAVE_SYNTH_PWD_SUPPORT
75
76#ifdef HAVE_GATEKEEPER1
77#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
78#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060079#include <hardware/gatekeeper.h>
Ethan Yonkerfefe5912017-09-30 22:22:13 -050080#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060081#include "HashPassword.h"
82
83#include <android-base/file.h>
84
Ethan Yonker79f88bd2016-12-09 14:52:12 -060085// Store main DE raw ref / policy
86extern std::string de_raw_ref;
87extern std::map<userid_t, std::string> s_de_key_raw_refs;
88extern std::map<userid_t, std::string> s_ce_key_raw_refs;
89
90static bool lookup_ref_key_internal(std::map<userid_t, std::string>& key_map, const char* policy, userid_t* user_id) {
91 for (std::map<userid_t, std::string>::iterator it=key_map.begin(); it!=key_map.end(); ++it) {
92 if (strncmp(it->second.c_str(), policy, it->second.size()) == 0) {
93 *user_id = it->first;
94 return true;
95 }
96 }
97 return false;
98}
99
100extern "C" bool lookup_ref_key(const char* policy, char* policy_type) {
101 userid_t user_id = 0;
102 if (strncmp(de_raw_ref.c_str(), policy, de_raw_ref.size()) == 0) {
103 strcpy(policy_type, "1DK");
104 return true;
105 }
106 if (!lookup_ref_key_internal(s_de_key_raw_refs, policy, &user_id)) {
107 if (!lookup_ref_key_internal(s_ce_key_raw_refs, policy, &user_id)) {
108 return false;
109 } else
110 sprintf(policy_type, "1CE%d", user_id);
111 } else
112 sprintf(policy_type, "1DE%d", user_id);
113 return true;
114}
115
116extern "C" bool lookup_ref_tar(const char* policy_type, char* policy) {
117 if (strncmp(policy_type, "1", 1) != 0) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500118 printf("Unexpected version %c\n", policy_type[0]);
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600119 return false;
120 }
121 const char* ptr = policy_type + 1; // skip past the version number
122 if (strncmp(ptr, "DK", 2) == 0) {
123 strncpy(policy, de_raw_ref.data(), de_raw_ref.size());
124 return true;
125 }
126 userid_t user_id = atoi(ptr + 2);
127 std::string raw_ref;
128 if (*ptr == 'D') {
129 if (lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)) {
130 strncpy(policy, raw_ref.data(), raw_ref.size());
131 } else
132 return false;
133 } else if (*ptr == 'C') {
134 if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
135 strncpy(policy, raw_ref.data(), raw_ref.size());
136 } else
137 return false;
138 } else {
139 printf("unknown policy type '%s'\n", policy_type);
140 return false;
141 }
142 return true;
143}
144
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500145#ifndef HAVE_GATEKEEPER1
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600146int gatekeeper_device_initialize(gatekeeper_device_t **dev) {
147 int ret;
148 const hw_module_t *mod;
149 ret = hw_get_module_by_class(GATEKEEPER_HARDWARE_MODULE_ID, NULL, &mod);
150
151 if (ret!=0) {
152 printf("failed to get hw module\n");
153 return ret;
154 }
155
156 ret = gatekeeper_open(mod, dev);
157
158 if (ret!=0)
159 printf("failed to open gatekeeper\n");
160 return ret;
161}
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500162#endif //ifndef HAVE_GATEKEEPER1
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600163
164bool Decrypt_DE() {
165 if (!e4crypt_initialize_global_de()) { // this deals with the overarching device encryption
166 printf("e4crypt_initialize_global_de returned fail\n");
167 return false;
168 }
169 if (!e4crypt_init_user0()) {
170 printf("e4crypt_init_user0 returned fail\n");
171 return false;
172 }
173 return true;
174}
175
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500176#ifdef HAVE_SYNTH_PWD_SUPPORT
177// Crappy functions for debugging, please ignore unless you need to debug
178/*void output_hex(const std::string& in) {
179 const char *buf = in.data();
180 char hex[in.size() * 2 + 1];
181 unsigned int index;
182 for (index = 0; index < in.size(); index++)
183 sprintf(&hex[2 * index], "%02X", buf[index]);
184 printf("%s", hex);
185}
186
187void output_hex(const char* buf, const int size) {
188 char hex[size * 2 + 1];
189 int index;
190 for (index = 0; index < size; index++)
191 sprintf(&hex[2 * index], "%02X", buf[index]);
192 printf("%s", hex);
193}
194
195void output_hex(const unsigned char* buf, const int size) {
196 char hex[size * 2 + 1];
197 int index;
198 for (index = 0; index < size; index++)
199 sprintf(&hex[2 * index], "%02X", buf[index]);
200 printf("%s", hex);
201}
202
203void output_hex(std::vector<uint8_t>* vec) {
204 char hex[3];
205 unsigned int index;
206 for (index = 0; index < vec->size(); index++) {
207 sprintf(&hex[0], "%02X", vec->at(index));
208 printf("%s", hex);
209 }
210}*/
211
212/* An alternative is to use:
213 * sqlite3 /data/system/locksettings.db "SELECT value FROM locksettings WHERE name='sp-handle' AND user=0;"
214 * but we really don't want to include the 1.1MB libsqlite in TWRP. We scan the spblob folder for the
215 * password data file (*.pwd) and get the handle from the filename instead. This is a replacement for
216 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#2017
217 * We never use this data as an actual long. We always use it as a string. */
218bool Find_Handle(const std::string& spblob_path, std::string& handle_str) {
219 DIR* dir = opendir(spblob_path.c_str());
220 if (!dir) {
221 printf("Error opening '%s'\n", spblob_path.c_str());
222 return false;
223 }
224
225 struct dirent* de = 0;
226
227 while ((de = readdir(dir)) != 0) {
228 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
229 continue;
230 size_t len = strlen(de->d_name);
231 if (len <= 4)
232 continue;
233 char* p = de->d_name;
234 p += len - 4;
235 if (strncmp(p, ".pwd", 4) == 0) {
236 handle_str = de->d_name;
237 handle_str = handle_str.substr(0, len - 4);
238 //*handle = strtoull(handle_str.c_str(), 0 , 16);
239 closedir(dir);
240 return true;
241 }
242 }
243 closedir(dir);
244 return false;
245}
246
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500247/* This is the structure of the data in the password data (*.pwd) file which the structure can be found
248 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#187 */
249struct password_data_struct {
250 int password_type;
251 unsigned char scryptN;
252 unsigned char scryptR;
253 unsigned char scryptP;
254 int salt_len;
255 void* salt;
256 int handle_len;
257 void* password_handle;
258};
259
260/* C++ replacement for
261 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#764 */
262bool Get_Password_Data(const std::string& spblob_path, const std::string& handle_str, password_data_struct *pwd) {
263 std::string pwd_file = spblob_path + handle_str + ".pwd";
264 std::string pwd_data;
265 if (!android::base::ReadFileToString(pwd_file, &pwd_data)) {
266 printf("Failed to read '%s'\n", pwd_file.c_str());
267 return false;
268 }
269 //output_hex(pwd_data.data(), pwd_data.size());printf("\n");
270 const int* intptr = (const int*)pwd_data.data();
271 pwd->password_type = *intptr;
272 endianswap(&pwd->password_type);
273 //printf("password type %i\n", pwd->password_type); // 2 was PIN, 1 for pattern, 2 also for password, -1 for default password
274 const unsigned char* byteptr = (const unsigned char*)pwd_data.data() + sizeof(int);
275 pwd->scryptN = *byteptr;
276 byteptr++;
277 pwd->scryptR = *byteptr;
278 byteptr++;
279 pwd->scryptP = *byteptr;
280 byteptr++;
281 intptr = (const int*)byteptr;
282 pwd->salt_len = *intptr;
283 endianswap(&pwd->salt_len);
284 if (pwd->salt_len != 0) {
285 pwd->salt = malloc(pwd->salt_len);
286 if (!pwd->salt) {
287 printf("Get_Password_Data malloc salt\n");
288 return false;
289 }
290 memcpy(pwd->salt, intptr + 1, pwd->salt_len);
Ethan Yonkere131bec2017-12-15 23:48:02 -0600291 intptr++;
292 byteptr = (const unsigned char*)intptr;
293 byteptr += pwd->salt_len;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500294 } else {
295 printf("Get_Password_Data salt_len is 0\n");
296 return false;
297 }
Ethan Yonkere131bec2017-12-15 23:48:02 -0600298 intptr = (const int*)byteptr;
299 pwd->handle_len = *intptr;
300 endianswap(&pwd->handle_len);
301 if (pwd->handle_len != 0) {
302 pwd->password_handle = malloc(pwd->handle_len);
303 if (!pwd->password_handle) {
304 printf("Get_Password_Data malloc password_handle\n");
305 return false;
306 }
307 memcpy(pwd->password_handle, intptr + 1, pwd->handle_len);
308 } else {
309 printf("Get_Password_Data handle_len is 0\n");
310 // Not an error if using weaver
311 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500312 return true;
313}
314
315/* C++ replacement for
316 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#765
317 * called here
318 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1050 */
319bool Get_Password_Token(const password_data_struct *pwd, const std::string& Password, unsigned char* password_token) {
320 if (!password_token) {
321 printf("password_token is null\n");
322 return false;
323 }
324 unsigned int N = 1 << pwd->scryptN;
325 unsigned int r = 1 << pwd->scryptR;
326 unsigned int p = 1 << pwd->scryptP;
327 //printf("N %i r %i p %i\n", N, r, p);
328 int ret = crypto_scrypt(reinterpret_cast<const uint8_t*>(Password.data()), Password.size(),
329 reinterpret_cast<const uint8_t*>(pwd->salt), pwd->salt_len,
330 N, r, p,
331 password_token, 32);
332 if (ret != 0) {
333 printf("scrypt error\n");
334 return false;
335 }
336 return true;
337}
338
339// Data structure for the *.weaver file, see Get_Weaver_Data below
340struct weaver_data_struct {
341 unsigned char version;
342 int slot;
343};
344
345/* C++ replacement for
346 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#501
347 * called here
348 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768 */
349bool Get_Weaver_Data(const std::string& spblob_path, const std::string& handle_str, weaver_data_struct *wd) {
350 std::string weaver_file = spblob_path + handle_str + ".weaver";
351 std::string weaver_data;
352 if (!android::base::ReadFileToString(weaver_file, &weaver_data)) {
353 printf("Failed to read '%s'\n", weaver_file.c_str());
354 return false;
355 }
356 //output_hex(weaver_data.data(), weaver_data.size());printf("\n");
357 const unsigned char* byteptr = (const unsigned char*)weaver_data.data();
358 wd->version = *byteptr;
359 //printf("weaver version %i\n", wd->version);
360 const int* intptr = (const int*)weaver_data.data() + sizeof(unsigned char);
361 wd->slot = *intptr;
362 //endianswap(&wd->slot); not needed
363 //printf("weaver slot %i\n", wd->slot);
364 return true;
365}
366
367namespace android {
368
369// On Android 8.0 for some reason init can't seem to completely stop keystore
370// so we have to kill it too if it doesn't die on its own.
371static void kill_keystore() {
372 DIR* dir = opendir("/proc");
373 if (dir) {
374 struct dirent* de = 0;
375
376 while ((de = readdir(dir)) != 0) {
377 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
378 continue;
379
380 int pid = -1;
381 int ret = sscanf(de->d_name, "%d", &pid);
382
383 if (ret == 1) {
384 char cmdpath[PATH_MAX];
385 sprintf(cmdpath, "/proc/%d/cmdline", pid);
386
387 FILE* file = fopen(cmdpath, "r");
388 size_t task_size = PATH_MAX;
389 char task[PATH_MAX];
390 char* p = task;
391 if (getline(&p, &task_size, file) > 0) {
392 if (strstr(task, "keystore") != 0) {
393 printf("keystore pid %d found, sending kill.\n", pid);
394 kill(pid, SIGINT);
395 usleep(5000);
396 kill(pid, SIGKILL);
397 }
398 }
399 fclose(file);
400 }
401 }
402 closedir(dir);
403 }
404}
405
406// The keystore holds a file open on /data so we have to stop / kill it
407// if we want to be able to unmount /data for things like formatting.
408static void stop_keystore() {
409 printf("Stopping keystore...\n");
410 property_set("ctl.stop", "keystore");
411 usleep(5000);
412 kill_keystore();
413}
414
415/* These next 2 functions try to get the keystore service 50 times because
416 * the keystore is not always ready when TWRP boots */
417sp<IBinder> getKeystoreBinder() {
418 sp<IServiceManager> sm = defaultServiceManager();
419 return sm->getService(String16("android.security.keystore"));
420}
421
422sp<IBinder> getKeystoreBinderRetry() {
423 printf("Starting keystore...\n");
424 property_set("ctl.start", "keystore");
425 int retry_count = 50;
426 sp<IBinder> binder = getKeystoreBinder();
427 while (binder == NULL && retry_count) {
428 printf("Waiting for keystore service... %i\n", retry_count--);
429 sleep(1);
430 binder = getKeystoreBinder();
431 }
432 return binder;
433}
434
435namespace keystore {
436
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600437#define SYNTHETIC_PASSWORD_VERSION_V1 1
Peter Caiea1764c2019-05-23 21:44:35 +0800438#define SYNTHETIC_PASSWORD_VERSION_V2 2
439#define SYNTHETIC_PASSWORD_VERSION_V3 3
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500440#define SYNTHETIC_PASSWORD_PASSWORD_BASED 0
441#define SYNTHETIC_PASSWORD_KEY_PREFIX "USRSKEY_synthetic_password_"
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500442#define USR_PRIVATE_KEY_PREFIX "USRPKEY_synthetic_password_"
443
444static std::string mKey_Prefix;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500445
446/* The keystore alias subid is sometimes the same as the handle, but not always.
447 * In the case of handle 0c5303fd2010fe29, the alias subid used c5303fd2010fe29
448 * without the leading 0. We could try to parse the data from a previous
449 * keystore request, but I think this is an easier solution because there
450 * is little to no documentation on the format of data we get back from
451 * the keystore in this instance. We also want to copy everything to a temp
452 * folder so that any key upgrades that might take place do not actually
453 * upgrade the keys on the data partition. We rename all 1000 uid files to 0
454 * to pass the keystore permission checks. */
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500455bool Find_Keystore_Alias_SubID_And_Prep_Files(const userid_t user_id, std::string& keystoreid, const std::string& handle_str) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500456 char path_c[PATH_MAX];
457 sprintf(path_c, "/data/misc/keystore/user_%d", user_id);
458 char user_dir[PATH_MAX];
459 sprintf(user_dir, "user_%d", user_id);
460 std::string source_path = "/data/misc/keystore/";
461 source_path += user_dir;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500462 std::string handle_sub = handle_str;
463 while (handle_sub.substr(0,1) == "0") {
464 std::string temp = handle_sub.substr(1);
465 handle_sub = temp;
466 }
467 mKey_Prefix = "";
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500468
469 mkdir("/tmp/misc", 0755);
470 mkdir("/tmp/misc/keystore", 0755);
471 std::string destination_path = "/tmp/misc/keystore/";
472 destination_path += user_dir;
473 if (mkdir(destination_path.c_str(), 0755) && errno != EEXIST) {
474 printf("failed to mkdir '%s' %s\n", destination_path.c_str(), strerror(errno));
475 return false;
476 }
477 destination_path += "/";
478
479 DIR* dir = opendir(source_path.c_str());
480 if (!dir) {
481 printf("Error opening '%s'\n", source_path.c_str());
482 return false;
483 }
484 source_path += "/";
485
486 struct dirent* de = 0;
487 size_t prefix_len = strlen(SYNTHETIC_PASSWORD_KEY_PREFIX);
488 bool found_subid = false;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500489 bool has_pkey = false; // PKEY has priority over SKEY
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500490
491 while ((de = readdir(dir)) != 0) {
492 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
493 continue;
494 if (!found_subid) {
495 size_t len = strlen(de->d_name);
496 if (len <= prefix_len)
497 continue;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500498 if (strstr(de->d_name, SYNTHETIC_PASSWORD_KEY_PREFIX) && !has_pkey)
499 mKey_Prefix = SYNTHETIC_PASSWORD_KEY_PREFIX;
500 else if (strstr(de->d_name, USR_PRIVATE_KEY_PREFIX)) {
501 mKey_Prefix = USR_PRIVATE_KEY_PREFIX;
502 has_pkey = true;
503 } else
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500504 continue;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500505 if (strstr(de->d_name, handle_sub.c_str())) {
506 keystoreid = handle_sub;
507 printf("keystoreid matched handle_sub: '%s'\n", keystoreid.c_str());
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500508 found_subid = true;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500509 } else {
510 std::string file = de->d_name;
511 std::size_t found = file.find_last_of("_");
512 if (found != std::string::npos) {
513 keystoreid = file.substr(found + 1);
514 printf("possible keystoreid: '%s'\n", keystoreid.c_str());
515 //found_subid = true; // we'll keep going in hopes that we find a pkey or a match to the handle_sub
516 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500517 }
518 }
519 std::string src = source_path;
520 src += de->d_name;
521 std::ifstream srcif(src.c_str(), std::ios::binary);
522 std::string dst = destination_path;
523 dst += de->d_name;
524 std::size_t source_uid = dst.find("1000");
525 if (source_uid != std::string::npos)
526 dst.replace(source_uid, 4, "0");
527 std::ofstream dstof(dst.c_str(), std::ios::binary);
528 printf("copying '%s' to '%s'\n", src.c_str(), dst.c_str());
529 dstof << srcif.rdbuf();
530 srcif.close();
531 dstof.close();
532 }
533 closedir(dir);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500534 if (!found_subid && !mKey_Prefix.empty() && !keystoreid.empty())
535 found_subid = true;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500536 return found_subid;
537}
538
539/* C++ replacement for function of the same name
540 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#867
541 * returning an empty string indicates an error */
Ethan Yonkere131bec2017-12-15 23:48:02 -0600542std::string unwrapSyntheticPasswordBlob(const std::string& spblob_path, const std::string& handle_str, const userid_t user_id, const void* application_id, const size_t application_id_size, uint32_t auth_token_len) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500543 std::string disk_decryption_secret_key = "";
544
545 std::string keystore_alias_subid;
Noah Jacobson5a79f672019-04-28 00:10:07 -0400546 // Can be stored in user 0, so check for both.
547 if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid, handle_str) &&
548 !Find_Keystore_Alias_SubID_And_Prep_Files(0, keystore_alias_subid, handle_str))
549 {
550 printf("failed to scan keystore alias subid and prep keystore files\n");
551 return disk_decryption_secret_key;
552 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500553
554 // First get the keystore service
Noah Jacobson5a79f672019-04-28 00:10:07 -0400555 sp<IBinder> binder = getKeystoreBinderRetry();
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500556#ifdef USE_KEYSTORAGE_4
557 sp<security::IKeystoreService> service = interface_cast<security::IKeystoreService>(binder);
558#else
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500559 sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500560#endif
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500561 if (service == NULL) {
562 printf("error: could not connect to keystore service\n");
563 return disk_decryption_secret_key;
564 }
565
Ethan Yonkere131bec2017-12-15 23:48:02 -0600566 if (auth_token_len > 0) {
567 printf("Starting keystore_auth service...\n");
568 property_set("ctl.start", "keystore_auth");
569 }
570
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500571 // 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
572 std::string spblob_file = spblob_path + handle_str + ".spblob";
573 std::string spblob_data;
574 if (!android::base::ReadFileToString(spblob_file, &spblob_data)) {
575 printf("Failed to read '%s'\n", spblob_file.c_str());
576 return disk_decryption_secret_key;
577 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600578 unsigned char* byteptr = (unsigned char*)spblob_data.data();
Peter Caiea1764c2019-05-23 21:44:35 +0800579 if (*byteptr != SYNTHETIC_PASSWORD_VERSION_V2 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V1
580 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V3) {
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600581 printf("Unsupported synthetic password version %i\n", *byteptr);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500582 return disk_decryption_secret_key;
583 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600584 const unsigned char* synthetic_password_version = byteptr;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500585 byteptr++;
586 if (*byteptr != SYNTHETIC_PASSWORD_PASSWORD_BASED) {
587 printf("spblob data is not SYNTHETIC_PASSWORD_PASSWORD_BASED\n");
588 return disk_decryption_secret_key;
589 }
590 byteptr++; // Now we're pointing to the blob data itself
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600591 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V1) {
592 printf("spblob v1\n");
593 /* We're now going to handle decryptSPBlob: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#115
594 * Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#879
595 * This small function ends up being quite a headache. The call to get data from the keystore basically is not needed in TWRP at this time.
596 * The keystore data seems to be the serialized data from an entire class in Java. Specifically I think it represents:
597 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
598 * or perhaps
599 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
600 * but the only things we "need" from this keystore are a user ID and the keyAlias which ends up being USRSKEY_synthetic_password_{handle_str}
601 * the latter of which we already have. We may need to figure out how to get the user ID if we ever support decrypting mulitple users.
602 * There are 2 calls to a Java decrypt funcion that is overloaded. These 2 calls go in completely different directions despite the seemingly
603 * similar use of decrypt() and decrypt parameters. To figure out where things were going, I added logging to:
604 * https://android.googlesource.com/platform/libcore/+/android-8.0.0_r23/ojluni/src/main/java/javax/crypto/Cipher.java#2575
605 * Logger.global.severe("Cipher tryCombinations " + prov.getName() + " - " + prov.getInfo());
606 * To make logging work in libcore, import java.util.logging.Logger; and either set a better logging level or modify the framework to log everything
607 * regardless of logging level. This will give you some strings that you can grep for and find the actual crypto provider in use. In our case there were
608 * 2 different providers in use. The first stage to get the intermediate key used:
609 * https://android.googlesource.com/platform/external/conscrypt/+/android-8.0.0_r23/common/src/main/java/org/conscrypt/OpenSSLProvider.java
610 * which is a pretty straight-forward OpenSSL implementation of AES/GCM/NoPadding. */
611 // 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
612 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
613 if (!personalized_application_id) {
614 printf("malloc personalized_application_id\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600615 return disk_decryption_secret_key;
616 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600617 //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
618 // Now we'll decrypt using openssl AES/GCM/NoPadding
619 OpenSSL_add_all_ciphers();
620 int actual_size=0, final_size=0;
621 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
622 const unsigned char* iv = (const unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
623 //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
624 const unsigned char* cipher_text = (const unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
625 //printf("cipher_text: "); output_hex((const unsigned char*)cipher_text, spblob_data.size() - 2 - 12); printf("\n");
626 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
627 //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
628 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, iv);
629 std::vector<unsigned char> intermediate_key;
630 intermediate_key.resize(spblob_data.size() - 2 - 12, '\0');
631 EVP_DecryptUpdate(d_ctx, &intermediate_key[0], &actual_size, cipher_text, spblob_data.size() - 2 - 12);
632 unsigned char tag[AES_BLOCK_SIZE];
633 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
634 EVP_DecryptFinal_ex(d_ctx, &intermediate_key[actual_size], &final_size);
635 EVP_CIPHER_CTX_free(d_ctx);
636 free(personalized_application_id);
637 //printf("spblob_data size: %lu actual_size %i, final_size: %i\n", spblob_data.size(), actual_size, final_size);
638 intermediate_key.resize(actual_size + final_size - 16, '\0');// not sure why we have to trim the size by 16 as I don't see where this is done in Java side
639 //printf("intermediate key: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
640
641 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
642 if (auth_token_len > 0) {
643 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
644 if (!auth_result.isOk()) {
645 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
646 printf("keystore error adding auth token\n");
647 return disk_decryption_secret_key;
648 }*/
649 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
650 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
651 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
652 // the /auth_token file never gets deleted.
653 int auth_wait_count = 20;
654 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
655 usleep(5000);
656 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
657 printf("error during keymaster_auth service\n");
658 /* 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
659 * service keystore_auth /sbin/keystore_auth
660 * disabled
661 * oneshot
662 * user system
663 * group root
664 * seclabel u:r:recovery:s0
665 *
666 * And check dmesg for error codes regarding this service if needed. */
667 return disk_decryption_secret_key;
668 }
669 }
670
671 int32_t ret;
672
673 /* We only need a keyAlias which is USRSKEY_synthetic_password_b6f71045af7bd042 which we find and a uid which is -1 or 1000, I forget which
674 * as the key data will be read again by the begin function later via the keystore.
675 * The data is in a hidl_vec format which consists of a type and a value. */
676 /*::keystore::hidl_vec<uint8_t> data;
677 std::string keystoreid = SYNTHETIC_PASSWORD_KEY_PREFIX;
678 keystoreid += handle_str;
679
680 ret = service->get(String16(keystoreid.c_str()), user_id, &data);
681 if (ret < 0) {
682 printf("Could not connect to keystore service %i\n", ret);
683 return disk_decryption_secret_key;
684 } else if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*//*) {
685 printf("keystore error: (%d)\n", /*responses[ret],*//* ret);
686 return disk_decryption_secret_key;
687 } else {
688 printf("keystore returned: "); output_hex(&data[0], data.size()); printf("\n");
689 }*/
690
691 // Now we'll break up the intermediate key into the IV (first 12 bytes) and the cipher text (the rest of it).
692 std::vector<unsigned char> nonce = intermediate_key;
693 nonce.resize(12);
694 intermediate_key.erase (intermediate_key.begin(),intermediate_key.begin()+12);
695 //printf("nonce: "); output_hex((const unsigned char*)nonce.data(), nonce.size()); printf("\n");
696 //printf("cipher text: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
697
698 /* Now we will begin the second decrypt call found in
699 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#122
700 * This time we will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
701 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
702 * First we set some algorithm parameters as seen in two places:
703 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
704 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
705 size_t maclen = 128;
706 ::keystore::AuthorizationSetBuilder begin_params;
707 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
708 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
709 begin_params.Padding(::keystore::PaddingMode::NONE);
710 begin_params.Authorization(::keystore::TAG_NONCE, nonce);
711 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
712 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES);
713 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockMode);
714 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_PADDING, mKeymasterPadding);
715 //keymasterArgs.addUnsignedInt(KeymasterDefs.KM_TAG_MAC_LENGTH, mTagLengthBits);
716 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
717 entropy.resize(0);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500718 std::string keystore_alias = mKey_Prefix;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600719 keystore_alias += keystore_alias_subid;
720 String16 keystore_alias16(keystore_alias.c_str());
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500721#ifdef USE_KEYSTORAGE_4
722 android::hardware::keymaster::V4_0::KeyPurpose purpose = android::hardware::keymaster::V4_0::KeyPurpose::DECRYPT;
723 security::keymaster::OperationResult begin_result;
724 security::keymaster::OperationResult update_result;
725 security::keymaster::OperationResult finish_result;
726 ::android::security::keymaster::KeymasterArguments empty_params;
727 // These parameters are mostly driven by the cipher.init call https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#63
728 service->begin(binder, keystore_alias16, (int32_t)purpose, true, android::security::keymaster::KeymasterArguments(begin_params.hidl_data()), entropy, -1, &begin_result);
729#else
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600730 ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT;
731 OperationResult begin_result;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500732 OperationResult update_result;
733 OperationResult finish_result;
734 ::keystore::hidl_vec<::keystore::KeyParameter> empty_params;
735 empty_params.resize(0);
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600736 // These parameters are mostly driven by the cipher.init call https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#63
737 service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500738#endif
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600739 ret = begin_result.resultCode;
740 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
741 printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret);
742 return disk_decryption_secret_key;
743 } else {
744 //printf("keystore begin operation successful\n");
745 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600746 // 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
747 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
748 service->update(begin_result.token, empty_params, intermediate_key, &update_result);
749 ret = update_result.resultCode;
750 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
751 printf("keystore update error: (%d)\n", /*responses[ret],*/ ret);
752 return disk_decryption_secret_key;
753 } else {
754 //printf("keystore update operation successful\n");
755 //printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password
756 }
757 // We must use the data in update_data.data before we call finish below or the data will be gone
758 // 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
759 // We now have the disk decryption key!
760 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)&update_result.data[0], update_result.data.size());
761 //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
762 ::keystore::hidl_vec<uint8_t> signature;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600763 service->finish(begin_result.token, empty_params, signature, entropy, &finish_result);
764 ret = finish_result.resultCode;
765 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
766 printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret);
767 return disk_decryption_secret_key;
768 } else {
769 //printf("keystore finish operation successful\n");
770 }
771 stop_keystore();
772 return disk_decryption_secret_key;
Peter Caiea1764c2019-05-23 21:44:35 +0800773 } else if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V2
774 || *synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
775 printf("spblob v2 / v3\n");
776 /* 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
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600777 * as seen in https://android.googlesource.com/platform/frameworks/base/+/5025791ac6d1538224e19189397de8d71dcb1a12
778 */
779 /* First decrypt call found in
780 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#135
781 * We will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
782 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
783 * First we set some algorithm parameters as seen in two places:
784 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
785 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
786 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
787 if (auth_token_len > 0) {
788 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
789 if (!auth_result.isOk()) {
790 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
791 printf("keystore error adding auth token\n");
792 return disk_decryption_secret_key;
793 }*/
794 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
795 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
796 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
797 // the /auth_token file never gets deleted.
798 int auth_wait_count = 20;
799 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
800 usleep(5000);
801 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
802 printf("error during keymaster_auth service\n");
803 /* 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
804 * service keystore_auth /sbin/keystore_auth
805 * disabled
806 * oneshot
807 * user system
808 * group root
809 * seclabel u:r:recovery:s0
810 *
811 * And check dmesg for error codes regarding this service if needed. */
812 return disk_decryption_secret_key;
813 }
814 }
815 int32_t ret;
816 size_t maclen = 128;
817 unsigned char* iv = (unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
818 ::keystore::hidl_vec<uint8_t> iv_hidlvec;
819 iv_hidlvec.setToExternal((unsigned char*)byteptr, 12);
820 //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
821 unsigned char* cipher_text = (unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
822 ::keystore::hidl_vec<uint8_t> cipher_text_hidlvec;
823 cipher_text_hidlvec.setToExternal(cipher_text, spblob_data.size() - 14 /* 1 each for version and SYNTHETIC_PASSWORD_PASSWORD_BASED and 12 for the iv */);
824 ::keystore::AuthorizationSetBuilder begin_params;
825 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
826 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
827 begin_params.Padding(::keystore::PaddingMode::NONE);
828 begin_params.Authorization(::keystore::TAG_NONCE, iv_hidlvec);
829 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
830 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
831 entropy.resize(0);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500832 std::string keystore_alias = mKey_Prefix;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600833 keystore_alias += keystore_alias_subid;
834 String16 keystore_alias16(keystore_alias.c_str());
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500835#ifdef USE_KEYSTORAGE_4
836 android::hardware::keymaster::V4_0::KeyPurpose purpose = android::hardware::keymaster::V4_0::KeyPurpose::DECRYPT;
837 security::keymaster::OperationResult begin_result;
838 security::keymaster::OperationResult update_result;
839 security::keymaster::OperationResult finish_result;
840 ::android::security::keymaster::KeymasterArguments empty_params;
841 // These parameters are mostly driven by the cipher.init call https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#63
842 service->begin(binder, keystore_alias16, (int32_t)purpose, true, android::security::keymaster::KeymasterArguments(begin_params.hidl_data()), entropy, -1, &begin_result);
843#else
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600844 ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT;
845 OperationResult begin_result;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500846 OperationResult update_result;
847 OperationResult finish_result;
848 ::keystore::hidl_vec<::keystore::KeyParameter> empty_params;
849 empty_params.resize(0);
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600850 // These parameters are mostly driven by the cipher.init call https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#63
851 service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500852#endif
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600853 ret = begin_result.resultCode;
854 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
855 printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret);
856 return disk_decryption_secret_key;
857 } /*else {
858 printf("keystore begin operation successful\n");
859 }*/
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600860 // 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
861 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
862 service->update(begin_result.token, empty_params, cipher_text_hidlvec, &update_result);
863 ret = update_result.resultCode;
864 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
865 printf("keystore update error: (%d)\n", /*responses[ret],*/ ret);
866 return disk_decryption_secret_key;
867 } /*else {
868 printf("keystore update operation successful\n");
869 printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password
870 }*/
871 //printf("keystore resulting data: "); output_hex((unsigned char*)&update_result.data[0], update_result.data.size()); printf("\n");
872 // We must copy the data in update_data.data before we call finish below or the data will be gone
873 size_t keystore_result_size = update_result.data.size();
874 unsigned char* keystore_result = (unsigned char*)malloc(keystore_result_size);
875 if (!keystore_result) {
876 printf("malloc on keystore_result\n");
877 return disk_decryption_secret_key;
878 }
879 memcpy(keystore_result, &update_result.data[0], update_result.data.size());
880 //printf("keystore_result data: "); output_hex(keystore_result, keystore_result_size); printf("\n");
881 ::keystore::hidl_vec<uint8_t> signature;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600882 service->finish(begin_result.token, empty_params, signature, entropy, &finish_result);
883 ret = finish_result.resultCode;
884 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
885 printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret);
886 free(keystore_result);
887 return disk_decryption_secret_key;
888 } /*else {
889 printf("keystore finish operation successful\n");
890 }*/
891 stop_keystore();
892
893 /* Now we do the second decrypt call as seen in:
894 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#136
895 */
896 const unsigned char* intermediate_iv = keystore_result;
897 //printf("intermediate_iv: "); output_hex((const unsigned char*)intermediate_iv, 12); printf("\n");
898 const unsigned char* intermediate_cipher_text = (const unsigned char*)keystore_result + 12; // The cipher text comes immediately after the IV
899 int cipher_size = keystore_result_size - 12;
900 //printf("intermediate_cipher_text: "); output_hex((const unsigned char*)intermediate_cipher_text, cipher_size); printf("\n");
901 // 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
902 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
903 if (!personalized_application_id) {
904 printf("malloc personalized_application_id\n");
905 free(keystore_result);
906 return disk_decryption_secret_key;
907 }
908 //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
909 // Now we'll decrypt using openssl AES/GCM/NoPadding
910 OpenSSL_add_all_ciphers();
911 int actual_size=0, final_size=0;
912 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
913 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
914 //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
915 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, intermediate_iv);
916 unsigned char* secret_key = (unsigned char*)malloc(cipher_size);
917 EVP_DecryptUpdate(d_ctx, secret_key, &actual_size, intermediate_cipher_text, cipher_size);
918 unsigned char tag[AES_BLOCK_SIZE];
919 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
920 EVP_DecryptFinal_ex(d_ctx, secret_key + actual_size, &final_size);
921 EVP_CIPHER_CTX_free(d_ctx);
922 free(personalized_application_id);
923 free(keystore_result);
924 int secret_key_real_size = actual_size - 16;
925 //printf("secret key: "); output_hex((const unsigned char*)secret_key, secret_key_real_size); printf("\n");
926 // 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
927 // We now have the disk decryption key!
Peter Caiea1764c2019-05-23 21:44:35 +0800928 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
929 // V3 uses SP800 instead of SHA512
930 disk_decryption_secret_key = PersonalizedHashSP800(PERSONALIZATION_FBE_KEY, PERSONALISATION_CONTEXT, (const char*)secret_key, secret_key_real_size);
931 } else {
932 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)secret_key, secret_key_real_size);
933 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600934 //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
935 free(secret_key);
936 return disk_decryption_secret_key;
Ethan Yonkere131bec2017-12-15 23:48:02 -0600937 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500938 return disk_decryption_secret_key;
939}
940
941}}
942
943#define PASSWORD_TOKEN_SIZE 32
944
Ethan Yonkere131bec2017-12-15 23:48:02 -0600945/* C++ replacement for
946 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#992
947 * called here
948 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#813 */
949bool Get_Secdis(const std::string& spblob_path, const std::string& handle_str, std::string& secdis_data) {
950 std::string secdis_file = spblob_path + handle_str + ".secdis";
951 if (!android::base::ReadFileToString(secdis_file, &secdis_data)) {
952 printf("Failed to read '%s'\n", secdis_file.c_str());
953 return false;
954 }
955 //output_hex(secdis_data.data(), secdis_data.size());printf("\n");
956 return true;
957}
958
959// 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
960userid_t fakeUid(const userid_t uid) {
961 return 100000 + uid;
962}
963
964bool Is_Weaver(const std::string& spblob_path, const std::string& handle_str) {
965 std::string weaver_file = spblob_path + handle_str + ".weaver";
966 struct stat st;
967 if (stat(weaver_file.c_str(), &st) == 0)
968 return true;
969 return false;
970}
971
972bool Free_Return(bool retval, void* weaver_key, password_data_struct* pwd) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500973 if (weaver_key)
974 free(weaver_key);
Ethan Yonkere131bec2017-12-15 23:48:02 -0600975 if (pwd->salt)
976 free(pwd->salt);
977 if (pwd->password_handle)
978 free(pwd->password_handle);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500979 return retval;
980}
981
982/* Decrypt_User_Synth_Pass is the TWRP C++ equivalent to spBasedDoVerifyCredential
983 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#1998 */
984bool Decrypt_User_Synth_Pass(const userid_t user_id, const std::string& Password) {
985 bool retval = false;
986 void* weaver_key = NULL;
987 password_data_struct pwd;
988 pwd.salt = NULL;
Ethan Yonkere131bec2017-12-15 23:48:02 -0600989 pwd.salt_len = 0;
990 pwd.password_handle = NULL;
991 pwd.handle_len = 0;
992 char application_id[PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH];
993
994 uint32_t auth_token_len = 0;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500995
996 std::string secret; // this will be the disk decryption key that is sent to vold
997 std::string token = "!"; // there is no token used for this kind of decrypt, key escrow is handled by weaver
998 int flags = FLAG_STORAGE_DE;
999 if (user_id == 0)
1000 flags = FLAG_STORAGE_DE;
1001 else
1002 flags = FLAG_STORAGE_CE;
1003 char spblob_path_char[PATH_MAX];
1004 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
1005 std::string spblob_path = spblob_path_char;
1006 long handle = 0;
1007 std::string handle_str;
1008 // 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
1009 if (!Find_Handle(spblob_path, handle_str)) {
1010 printf("Error getting handle\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001011 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001012 }
1013 printf("Handle is '%s'\n", handle_str.c_str());
1014 // 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
1015 // First we read the password data which contains scrypt parameters
1016 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
1017 printf("Failed to Get_Password_Data\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001018 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001019 }
1020 //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");
1021 unsigned char password_token[PASSWORD_TOKEN_SIZE];
1022 //printf("Password: '%s'\n", Password.c_str());
1023 // The password token is the password scrypted with the parameters from the password data file
1024 if (!Get_Password_Token(&pwd, Password, &password_token[0])) {
1025 printf("Failed to Get_Password_Token\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001026 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001027 }
1028 //output_hex(&password_token[0], PASSWORD_TOKEN_SIZE);printf("\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001029 if (Is_Weaver(spblob_path, handle_str)) {
1030 printf("using weaver\n");
1031 // BEGIN PIXEL 2 WEAVER
1032 // Get the weaver data from the .weaver file which tells us which slot to use when we ask weaver for the escrowed key
1033 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768
1034 weaver_data_struct wd;
1035 if (!Get_Weaver_Data(spblob_path, handle_str, &wd)) {
1036 printf("Failed to get weaver data\n");
1037 return Free_Return(retval, weaver_key, &pwd);
1038 }
1039 // The weaver key is the the password token prefixed with "weaver-key" padded to 128 with nulls with the password token appended then SHA512
1040 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1059
1041 weaver_key = PersonalizedHashBinary(PERSONALISATION_WEAVER_KEY, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
1042 if (!weaver_key) {
1043 printf("malloc error getting weaver_key\n");
1044 return Free_Return(retval, weaver_key, &pwd);
1045 }
1046 // 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
1047 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#776
1048 android::vold::Weaver weaver;
1049 if (!weaver) {
1050 printf("Failed to get weaver service\n");
1051 return Free_Return(retval, weaver_key, &pwd);
1052 }
1053 // Get the key size from weaver service
1054 uint32_t weaver_key_size = 0;
1055 if (!weaver.GetKeySize(&weaver_key_size)) {
1056 printf("Failed to get weaver key size\n");
1057 return Free_Return(retval, weaver_key, &pwd);
1058 } else {
1059 //printf("weaver key size is %u\n", weaver_key_size);
1060 }
1061 //printf("weaver key: "); output_hex((unsigned char*)weaver_key, weaver_key_size); printf("\n");
1062 // Send the slot from the .weaver file, the computed weaver key, and get the escrowed key data
1063 std::vector<uint8_t> weaver_payload;
1064 // TODO: we should return more information about the status including time delays before the next retry
1065 if (!weaver.WeaverVerify(wd.slot, weaver_key, &weaver_payload)) {
1066 printf("failed to weaver verify\n");
1067 return Free_Return(retval, weaver_key, &pwd);
1068 }
1069 //printf("weaver payload: "); output_hex(&weaver_payload); printf("\n");
1070 // Done with weaverVerify
1071 // Now we will compute the application ID
1072 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#964
1073 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#780
1074 // The escrowed weaver key data is prefixed with "weaver-pwd" padded to 128 with nulls with the weaver payload appended then SHA512
1075 void* weaver_secret = PersonalizedHashBinary(PERSONALISATION_WEAVER_PASSWORD, (const char*)weaver_payload.data(), weaver_payload.size());
1076 //printf("weaver secret: "); output_hex((unsigned char*)weaver_secret, SHA512_DIGEST_LENGTH); printf("\n");
1077 // The application ID is the password token and weaver secret appended to each other
1078 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
1079 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], weaver_secret, SHA512_DIGEST_LENGTH);
1080 //printf("application ID: "); output_hex((unsigned char*)application_id, PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH); printf("\n");
1081 // END PIXEL 2 WEAVER
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001082 } else {
Ethan Yonkere131bec2017-12-15 23:48:02 -06001083 printf("using secdis\n");
1084 std::string secdis_data;
1085 if (!Get_Secdis(spblob_path, handle_str, secdis_data)) {
1086 printf("Failed to get secdis data\n");
1087 return Free_Return(retval, weaver_key, &pwd);
1088 }
1089 void* secdiscardable = PersonalizedHashBinary(PERSONALISATION_SECDISCARDABLE, (char*)secdis_data.data(), secdis_data.size());
1090 if (!secdiscardable) {
1091 printf("malloc error getting secdiscardable\n");
1092 return Free_Return(retval, weaver_key, &pwd);
1093 }
1094 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
1095 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], secdiscardable, SHA512_DIGEST_LENGTH);
1096
1097 int ret = -1;
1098 bool request_reenroll = false;
1099 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1100 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1101 if (gk_device == nullptr) {
1102 printf("failed to get gatekeeper service\n");
1103 return Free_Return(retval, weaver_key, &pwd);
1104 }
1105 if (pwd.handle_len <= 0) {
1106 printf("no password handle supplied\n");
1107 return Free_Return(retval, weaver_key, &pwd);
1108 }
1109 android::hardware::hidl_vec<uint8_t> pwd_handle_hidl;
1110 pwd_handle_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)pwd.password_handle), pwd.handle_len);
1111 void* gk_pwd_token = PersonalizedHashBinary(PERSONALIZATION_USER_GK_AUTH, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
1112 if (!gk_pwd_token) {
1113 printf("malloc error getting gatekeeper_key\n");
1114 return Free_Return(retval, weaver_key, &pwd);
1115 }
1116 android::hardware::hidl_vec<uint8_t> gk_pwd_token_hidl;
1117 gk_pwd_token_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)gk_pwd_token), SHA512_DIGEST_LENGTH);
1118 android::hardware::Return<void> hwRet =
1119 gk_device->verify(fakeUid(user_id), 0 /* challange */,
1120 pwd_handle_hidl,
1121 gk_pwd_token_hidl,
1122 [&ret, &request_reenroll, &auth_token_len]
1123 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1124 ret = static_cast<int>(rsp.code); // propagate errors
1125 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1126 auth_token_len = rsp.data.size();
1127 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1128 ret = 0; // all success states are reported as 0
1129 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file here and later
1130 // run a separate service that runs as the system user to add the auth token. We wait for the auth token file to be
1131 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after a while seconds if
1132 // the /auth_token file never gets deleted.
1133 unlink("/auth_token");
1134 FILE* auth_file = fopen("/auth_token","wb");
1135 if (auth_file != NULL) {
1136 fwrite(rsp.data.data(), sizeof(uint8_t), rsp.data.size(), auth_file);
1137 fclose(auth_file);
1138 } else {
1139 printf("failed to open /auth_token for writing\n");
1140 ret = -2;
1141 }
1142 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1143 ret = rsp.timeout;
1144 }
1145 }
1146 );
1147 free(gk_pwd_token);
1148 if (!hwRet.isOk() || ret != 0) {
1149 printf("gatekeeper verification failed\n");
1150 return Free_Return(retval, weaver_key, &pwd);
1151 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001152 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001153 // 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
1154 // Plus we will include the last bit that computes the disk decrypt key found in:
1155 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#153
Ethan Yonkere131bec2017-12-15 23:48:02 -06001156 secret = android::keystore::unwrapSyntheticPasswordBlob(spblob_path, handle_str, user_id, (const void*)&application_id[0], PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH, auth_token_len);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001157 if (!secret.size()) {
1158 printf("failed to unwrapSyntheticPasswordBlob\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001159 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001160 }
1161 if (!e4crypt_unlock_user_key(user_id, 0, token.c_str(), secret.c_str())) {
1162 printf("e4crypt_unlock_user_key returned fail\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001163 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001164 }
Noah Jacobson5a79f672019-04-28 00:10:07 -04001165/*#ifdef USE_KEYSTORAGE_4
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001166 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1167#else
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001168 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001169#endif
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001170 printf("failed to e4crypt_prepare_user_storage\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001171 return Free_Return(retval, weaver_key, &pwd);
Noah Jacobson5a79f672019-04-28 00:10:07 -04001172 }*/
1173 printf("User %i Decrypted Successfully!\n", user_id);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001174 retval = true;
Ethan Yonkere131bec2017-12-15 23:48:02 -06001175 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001176}
1177#endif //HAVE_SYNTH_PWD_SUPPORT
1178
1179int Get_Password_Type(const userid_t user_id, std::string& filename) {
1180 struct stat st;
1181 char spblob_path_char[PATH_MAX];
1182 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
1183 if (stat(spblob_path_char, &st) == 0) {
1184#ifdef HAVE_SYNTH_PWD_SUPPORT
1185 printf("Using synthetic password method\n");
1186 std::string spblob_path = spblob_path_char;
1187 std::string handle_str;
1188 if (!Find_Handle(spblob_path, handle_str)) {
1189 printf("Error getting handle\n");
1190 return 0;
1191 }
1192 printf("Handle is '%s'\n", handle_str.c_str());
1193 password_data_struct pwd;
1194 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
1195 printf("Failed to Get_Password_Data\n");
1196 return 0;
1197 }
1198 if (pwd.password_type == 1) // In Android this means pattern
1199 return 2; // In TWRP this means pattern
Alexander Sulfrian81acef12020-12-15 01:58:55 +01001200 // In Android <11 type 2 is PIN or password
1201 // In Android 11 type 3 is PIN and type 4 is password
1202 else if (pwd.password_type > 1)
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001203 return 1; // In TWRP this means PIN or password
1204 return 0; // We'll try the default password
1205#else
1206 printf("Synthetic password support not present in TWRP\n");
1207 return -1;
1208#endif
1209 }
1210 std::string path;
1211 if (user_id == 0) {
1212 path = "/data/system/";
1213 } else {
1214 char user_id_str[5];
1215 sprintf(user_id_str, "%i", user_id);
1216 path = "/data/system/users/";
1217 path += user_id_str;
1218 path += "/";
1219 }
1220 filename = path + "gatekeeper.password.key";
1221 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1222 return 1;
1223 filename = path + "gatekeeper.pattern.key";
1224 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1225 return 2;
1226 printf("Unable to locate gatekeeper password file '%s'\n", filename.c_str());
1227 filename = "";
1228 return 0;
1229}
1230
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001231bool Decrypt_User(const userid_t user_id, const std::string& Password) {
1232 uint8_t *auth_token;
1233 uint32_t auth_token_len;
1234 int ret;
1235
1236 struct stat st;
1237 if (user_id > 9999) {
1238 printf("user_id is too big\n");
1239 return false;
1240 }
1241 std::string filename;
1242 bool Default_Password = (Password == "!");
1243 if (Get_Password_Type(user_id, filename) == 0 && !Default_Password) {
1244 printf("Unknown password type\n");
1245 return false;
1246 }
1247 int flags = FLAG_STORAGE_DE;
1248 if (user_id == 0)
1249 flags = FLAG_STORAGE_DE;
1250 else
1251 flags = FLAG_STORAGE_CE;
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001252 if (Default_Password) {
1253 if (!e4crypt_unlock_user_key(user_id, 0, "!", "!")) {
1254 printf("e4crypt_unlock_user_key returned fail\n");
1255 return false;
1256 }
Noah Jacobson5a79f672019-04-28 00:10:07 -04001257/*#ifdef USE_KEYSTORAGE_4
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001258 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1259#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001260 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001261#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001262 printf("failed to e4crypt_prepare_user_storage\n");
1263 return false;
Noah Jacobson5a79f672019-04-28 00:10:07 -04001264 }*/
1265 printf("User %i Decrypted Successfully!\n", user_id);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001266 return true;
1267 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001268 if (stat("/data/system_de/0/spblob", &st) == 0) {
1269#ifdef HAVE_SYNTH_PWD_SUPPORT
1270 printf("Using synthetic password method\n");
1271 return Decrypt_User_Synth_Pass(user_id, Password);
1272#else
1273 printf("Synthetic password support not present in TWRP\n");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001274 return false;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001275#endif
1276 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001277 printf("password filename is '%s'\n", filename.c_str());
1278 if (stat(filename.c_str(), &st) != 0) {
1279 printf("error stat'ing key file: %s\n", strerror(errno));
1280 return false;
1281 }
1282 std::string handle;
1283 if (!android::base::ReadFileToString(filename, &handle)) {
1284 printf("Failed to read '%s'\n", filename.c_str());
1285 return false;
1286 }
1287 bool should_reenroll;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001288#ifdef HAVE_GATEKEEPER1
1289 bool request_reenroll = false;
1290 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1291 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1292 if (gk_device == nullptr)
1293 return false;
1294 android::hardware::hidl_vec<uint8_t> curPwdHandle;
1295 curPwdHandle.setToExternal(const_cast<uint8_t *>((const uint8_t *)handle.c_str()), st.st_size);
1296 android::hardware::hidl_vec<uint8_t> enteredPwd;
1297 enteredPwd.setToExternal(const_cast<uint8_t *>((const uint8_t *)Password.c_str()), Password.size());
1298
1299 android::hardware::Return<void> hwRet =
1300 gk_device->verify(user_id, 0 /* challange */,
1301 curPwdHandle,
1302 enteredPwd,
1303 [&ret, &request_reenroll, &auth_token, &auth_token_len]
1304 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1305 ret = static_cast<int>(rsp.code); // propagate errors
1306 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1307 auth_token = new uint8_t[rsp.data.size()];
1308 auth_token_len = rsp.data.size();
1309 memcpy(auth_token, rsp.data.data(), auth_token_len);
1310 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1311 ret = 0; // all success states are reported as 0
1312 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1313 ret = rsp.timeout;
1314 }
1315 }
1316 );
1317 if (!hwRet.isOk()) {
1318 return false;
1319 }
1320#else
1321 gatekeeper_device_t *gk_device;
1322 ret = gatekeeper_device_initialize(&gk_device);
1323 if (ret!=0)
1324 return false;
1325 ret = gk_device->verify(gk_device, user_id, 0, (const uint8_t *)handle.c_str(), st.st_size,
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001326 (const uint8_t *)Password.c_str(), (uint32_t)Password.size(), &auth_token, &auth_token_len,
1327 &should_reenroll);
1328 if (ret !=0) {
1329 printf("failed to verify\n");
1330 return false;
1331 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001332#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001333 char token_hex[(auth_token_len*2)+1];
1334 token_hex[(auth_token_len*2)] = 0;
1335 uint32_t i;
1336 for (i=0;i<auth_token_len;i++) {
1337 sprintf(&token_hex[2*i], "%02X", auth_token[i]);
1338 }
1339 // 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
1340 std::string secret = HashPassword(Password);
1341 if (!e4crypt_unlock_user_key(user_id, 0, token_hex, secret.c_str())) {
1342 printf("e4crypt_unlock_user_key returned fail\n");
1343 return false;
1344 }
Noah Jacobson5a79f672019-04-28 00:10:07 -04001345/*#ifdef USE_KEYSTORAGE_4
codeworkx22e3aa92019-04-23 12:02:26 +02001346 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1347#else
1348 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
1349#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001350 printf("failed to e4crypt_prepare_user_storage\n");
1351 return false;
Noah Jacobson5a79f672019-04-28 00:10:07 -04001352 }*/
1353 printf("User %i Decrypted Successfully!\n", user_id);
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001354 return true;
1355}