blob: d8542dca7251239f887980f24afe711812c017f8 [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;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500546 if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid, handle_str)) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500547 printf("failed to scan keystore alias subid and prep keystore files\n");
548 return disk_decryption_secret_key;
549 }
550
551 // First get the keystore service
552 sp<IBinder> binder = getKeystoreBinderRetry();
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500553#ifdef USE_KEYSTORAGE_4
554 sp<security::IKeystoreService> service = interface_cast<security::IKeystoreService>(binder);
555#else
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500556 sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500557#endif
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500558 if (service == NULL) {
559 printf("error: could not connect to keystore service\n");
560 return disk_decryption_secret_key;
561 }
562
Ethan Yonkere131bec2017-12-15 23:48:02 -0600563 if (auth_token_len > 0) {
564 printf("Starting keystore_auth service...\n");
565 property_set("ctl.start", "keystore_auth");
566 }
567
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500568 // 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
569 std::string spblob_file = spblob_path + handle_str + ".spblob";
570 std::string spblob_data;
571 if (!android::base::ReadFileToString(spblob_file, &spblob_data)) {
572 printf("Failed to read '%s'\n", spblob_file.c_str());
573 return disk_decryption_secret_key;
574 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600575 unsigned char* byteptr = (unsigned char*)spblob_data.data();
Peter Caiea1764c2019-05-23 21:44:35 +0800576 if (*byteptr != SYNTHETIC_PASSWORD_VERSION_V2 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V1
577 && *byteptr != SYNTHETIC_PASSWORD_VERSION_V3) {
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600578 printf("Unsupported synthetic password version %i\n", *byteptr);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500579 return disk_decryption_secret_key;
580 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600581 const unsigned char* synthetic_password_version = byteptr;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500582 byteptr++;
583 if (*byteptr != SYNTHETIC_PASSWORD_PASSWORD_BASED) {
584 printf("spblob data is not SYNTHETIC_PASSWORD_PASSWORD_BASED\n");
585 return disk_decryption_secret_key;
586 }
587 byteptr++; // Now we're pointing to the blob data itself
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600588 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V1) {
589 printf("spblob v1\n");
590 /* 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
591 * Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#879
592 * 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.
593 * The keystore data seems to be the serialized data from an entire class in Java. Specifically I think it represents:
594 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
595 * or perhaps
596 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
597 * 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}
598 * 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.
599 * There are 2 calls to a Java decrypt funcion that is overloaded. These 2 calls go in completely different directions despite the seemingly
600 * similar use of decrypt() and decrypt parameters. To figure out where things were going, I added logging to:
601 * https://android.googlesource.com/platform/libcore/+/android-8.0.0_r23/ojluni/src/main/java/javax/crypto/Cipher.java#2575
602 * Logger.global.severe("Cipher tryCombinations " + prov.getName() + " - " + prov.getInfo());
603 * 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
604 * 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
605 * 2 different providers in use. The first stage to get the intermediate key used:
606 * https://android.googlesource.com/platform/external/conscrypt/+/android-8.0.0_r23/common/src/main/java/org/conscrypt/OpenSSLProvider.java
607 * which is a pretty straight-forward OpenSSL implementation of AES/GCM/NoPadding. */
608 // 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
609 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
610 if (!personalized_application_id) {
611 printf("malloc personalized_application_id\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600612 return disk_decryption_secret_key;
613 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600614 //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
615 // Now we'll decrypt using openssl AES/GCM/NoPadding
616 OpenSSL_add_all_ciphers();
617 int actual_size=0, final_size=0;
618 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
619 const unsigned char* iv = (const unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
620 //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
621 const unsigned char* cipher_text = (const unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
622 //printf("cipher_text: "); output_hex((const unsigned char*)cipher_text, spblob_data.size() - 2 - 12); printf("\n");
623 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
624 //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
625 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, iv);
626 std::vector<unsigned char> intermediate_key;
627 intermediate_key.resize(spblob_data.size() - 2 - 12, '\0');
628 EVP_DecryptUpdate(d_ctx, &intermediate_key[0], &actual_size, cipher_text, spblob_data.size() - 2 - 12);
629 unsigned char tag[AES_BLOCK_SIZE];
630 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
631 EVP_DecryptFinal_ex(d_ctx, &intermediate_key[actual_size], &final_size);
632 EVP_CIPHER_CTX_free(d_ctx);
633 free(personalized_application_id);
634 //printf("spblob_data size: %lu actual_size %i, final_size: %i\n", spblob_data.size(), actual_size, final_size);
635 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
636 //printf("intermediate key: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
637
638 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
639 if (auth_token_len > 0) {
640 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
641 if (!auth_result.isOk()) {
642 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
643 printf("keystore error adding auth token\n");
644 return disk_decryption_secret_key;
645 }*/
646 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
647 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
648 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
649 // the /auth_token file never gets deleted.
650 int auth_wait_count = 20;
651 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
652 usleep(5000);
653 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
654 printf("error during keymaster_auth service\n");
655 /* 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
656 * service keystore_auth /sbin/keystore_auth
657 * disabled
658 * oneshot
659 * user system
660 * group root
661 * seclabel u:r:recovery:s0
662 *
663 * And check dmesg for error codes regarding this service if needed. */
664 return disk_decryption_secret_key;
665 }
666 }
667
668 int32_t ret;
669
670 /* 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
671 * as the key data will be read again by the begin function later via the keystore.
672 * The data is in a hidl_vec format which consists of a type and a value. */
673 /*::keystore::hidl_vec<uint8_t> data;
674 std::string keystoreid = SYNTHETIC_PASSWORD_KEY_PREFIX;
675 keystoreid += handle_str;
676
677 ret = service->get(String16(keystoreid.c_str()), user_id, &data);
678 if (ret < 0) {
679 printf("Could not connect to keystore service %i\n", ret);
680 return disk_decryption_secret_key;
681 } else if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*//*) {
682 printf("keystore error: (%d)\n", /*responses[ret],*//* ret);
683 return disk_decryption_secret_key;
684 } else {
685 printf("keystore returned: "); output_hex(&data[0], data.size()); printf("\n");
686 }*/
687
688 // Now we'll break up the intermediate key into the IV (first 12 bytes) and the cipher text (the rest of it).
689 std::vector<unsigned char> nonce = intermediate_key;
690 nonce.resize(12);
691 intermediate_key.erase (intermediate_key.begin(),intermediate_key.begin()+12);
692 //printf("nonce: "); output_hex((const unsigned char*)nonce.data(), nonce.size()); printf("\n");
693 //printf("cipher text: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
694
695 /* Now we will begin the second decrypt call found in
696 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#122
697 * This time we will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
698 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
699 * First we set some algorithm parameters as seen in two places:
700 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
701 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
702 size_t maclen = 128;
703 ::keystore::AuthorizationSetBuilder begin_params;
704 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
705 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
706 begin_params.Padding(::keystore::PaddingMode::NONE);
707 begin_params.Authorization(::keystore::TAG_NONCE, nonce);
708 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
709 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES);
710 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockMode);
711 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_PADDING, mKeymasterPadding);
712 //keymasterArgs.addUnsignedInt(KeymasterDefs.KM_TAG_MAC_LENGTH, mTagLengthBits);
713 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
714 entropy.resize(0);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500715 std::string keystore_alias = mKey_Prefix;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600716 keystore_alias += keystore_alias_subid;
717 String16 keystore_alias16(keystore_alias.c_str());
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500718#ifdef USE_KEYSTORAGE_4
719 android::hardware::keymaster::V4_0::KeyPurpose purpose = android::hardware::keymaster::V4_0::KeyPurpose::DECRYPT;
720 security::keymaster::OperationResult begin_result;
721 security::keymaster::OperationResult update_result;
722 security::keymaster::OperationResult finish_result;
723 ::android::security::keymaster::KeymasterArguments empty_params;
724 // 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
725 service->begin(binder, keystore_alias16, (int32_t)purpose, true, android::security::keymaster::KeymasterArguments(begin_params.hidl_data()), entropy, -1, &begin_result);
726#else
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600727 ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT;
728 OperationResult begin_result;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500729 OperationResult update_result;
730 OperationResult finish_result;
731 ::keystore::hidl_vec<::keystore::KeyParameter> empty_params;
732 empty_params.resize(0);
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600733 // 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
734 service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500735#endif
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600736 ret = begin_result.resultCode;
737 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
738 printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret);
739 return disk_decryption_secret_key;
740 } else {
741 //printf("keystore begin operation successful\n");
742 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600743 // 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
744 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
745 service->update(begin_result.token, empty_params, intermediate_key, &update_result);
746 ret = update_result.resultCode;
747 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
748 printf("keystore update error: (%d)\n", /*responses[ret],*/ ret);
749 return disk_decryption_secret_key;
750 } else {
751 //printf("keystore update operation successful\n");
752 //printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password
753 }
754 // We must use the data in update_data.data before we call finish below or the data will be gone
755 // 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
756 // We now have the disk decryption key!
757 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)&update_result.data[0], update_result.data.size());
758 //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
759 ::keystore::hidl_vec<uint8_t> signature;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600760 service->finish(begin_result.token, empty_params, signature, entropy, &finish_result);
761 ret = finish_result.resultCode;
762 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
763 printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret);
764 return disk_decryption_secret_key;
765 } else {
766 //printf("keystore finish operation successful\n");
767 }
768 stop_keystore();
769 return disk_decryption_secret_key;
Peter Caiea1764c2019-05-23 21:44:35 +0800770 } else if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V2
771 || *synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
772 printf("spblob v2 / v3\n");
773 /* 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 -0600774 * as seen in https://android.googlesource.com/platform/frameworks/base/+/5025791ac6d1538224e19189397de8d71dcb1a12
775 */
776 /* First decrypt call found in
777 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#135
778 * We will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
779 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
780 * First we set some algorithm parameters as seen in two places:
781 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
782 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
783 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
784 if (auth_token_len > 0) {
785 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
786 if (!auth_result.isOk()) {
787 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
788 printf("keystore error adding auth token\n");
789 return disk_decryption_secret_key;
790 }*/
791 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
792 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
793 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
794 // the /auth_token file never gets deleted.
795 int auth_wait_count = 20;
796 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
797 usleep(5000);
798 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
799 printf("error during keymaster_auth service\n");
800 /* 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
801 * service keystore_auth /sbin/keystore_auth
802 * disabled
803 * oneshot
804 * user system
805 * group root
806 * seclabel u:r:recovery:s0
807 *
808 * And check dmesg for error codes regarding this service if needed. */
809 return disk_decryption_secret_key;
810 }
811 }
812 int32_t ret;
813 size_t maclen = 128;
814 unsigned char* iv = (unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
815 ::keystore::hidl_vec<uint8_t> iv_hidlvec;
816 iv_hidlvec.setToExternal((unsigned char*)byteptr, 12);
817 //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
818 unsigned char* cipher_text = (unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
819 ::keystore::hidl_vec<uint8_t> cipher_text_hidlvec;
820 cipher_text_hidlvec.setToExternal(cipher_text, spblob_data.size() - 14 /* 1 each for version and SYNTHETIC_PASSWORD_PASSWORD_BASED and 12 for the iv */);
821 ::keystore::AuthorizationSetBuilder begin_params;
822 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
823 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
824 begin_params.Padding(::keystore::PaddingMode::NONE);
825 begin_params.Authorization(::keystore::TAG_NONCE, iv_hidlvec);
826 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
827 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
828 entropy.resize(0);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500829 std::string keystore_alias = mKey_Prefix;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600830 keystore_alias += keystore_alias_subid;
831 String16 keystore_alias16(keystore_alias.c_str());
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500832#ifdef USE_KEYSTORAGE_4
833 android::hardware::keymaster::V4_0::KeyPurpose purpose = android::hardware::keymaster::V4_0::KeyPurpose::DECRYPT;
834 security::keymaster::OperationResult begin_result;
835 security::keymaster::OperationResult update_result;
836 security::keymaster::OperationResult finish_result;
837 ::android::security::keymaster::KeymasterArguments empty_params;
838 // 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
839 service->begin(binder, keystore_alias16, (int32_t)purpose, true, android::security::keymaster::KeymasterArguments(begin_params.hidl_data()), entropy, -1, &begin_result);
840#else
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600841 ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT;
842 OperationResult begin_result;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500843 OperationResult update_result;
844 OperationResult finish_result;
845 ::keystore::hidl_vec<::keystore::KeyParameter> empty_params;
846 empty_params.resize(0);
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600847 // 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
848 service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result);
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500849#endif
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600850 ret = begin_result.resultCode;
851 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
852 printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret);
853 return disk_decryption_secret_key;
854 } /*else {
855 printf("keystore begin operation successful\n");
856 }*/
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600857 // 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
858 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
859 service->update(begin_result.token, empty_params, cipher_text_hidlvec, &update_result);
860 ret = update_result.resultCode;
861 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
862 printf("keystore update error: (%d)\n", /*responses[ret],*/ ret);
863 return disk_decryption_secret_key;
864 } /*else {
865 printf("keystore update operation successful\n");
866 printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password
867 }*/
868 //printf("keystore resulting data: "); output_hex((unsigned char*)&update_result.data[0], update_result.data.size()); printf("\n");
869 // We must copy the data in update_data.data before we call finish below or the data will be gone
870 size_t keystore_result_size = update_result.data.size();
871 unsigned char* keystore_result = (unsigned char*)malloc(keystore_result_size);
872 if (!keystore_result) {
873 printf("malloc on keystore_result\n");
874 return disk_decryption_secret_key;
875 }
876 memcpy(keystore_result, &update_result.data[0], update_result.data.size());
877 //printf("keystore_result data: "); output_hex(keystore_result, keystore_result_size); printf("\n");
878 ::keystore::hidl_vec<uint8_t> signature;
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600879 service->finish(begin_result.token, empty_params, signature, entropy, &finish_result);
880 ret = finish_result.resultCode;
881 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
882 printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret);
883 free(keystore_result);
884 return disk_decryption_secret_key;
885 } /*else {
886 printf("keystore finish operation successful\n");
887 }*/
888 stop_keystore();
889
890 /* Now we do the second decrypt call as seen in:
891 * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#136
892 */
893 const unsigned char* intermediate_iv = keystore_result;
894 //printf("intermediate_iv: "); output_hex((const unsigned char*)intermediate_iv, 12); printf("\n");
895 const unsigned char* intermediate_cipher_text = (const unsigned char*)keystore_result + 12; // The cipher text comes immediately after the IV
896 int cipher_size = keystore_result_size - 12;
897 //printf("intermediate_cipher_text: "); output_hex((const unsigned char*)intermediate_cipher_text, cipher_size); printf("\n");
898 // 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
899 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
900 if (!personalized_application_id) {
901 printf("malloc personalized_application_id\n");
902 free(keystore_result);
903 return disk_decryption_secret_key;
904 }
905 //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
906 // Now we'll decrypt using openssl AES/GCM/NoPadding
907 OpenSSL_add_all_ciphers();
908 int actual_size=0, final_size=0;
909 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
910 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
911 //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
912 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, intermediate_iv);
913 unsigned char* secret_key = (unsigned char*)malloc(cipher_size);
914 EVP_DecryptUpdate(d_ctx, secret_key, &actual_size, intermediate_cipher_text, cipher_size);
915 unsigned char tag[AES_BLOCK_SIZE];
916 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
917 EVP_DecryptFinal_ex(d_ctx, secret_key + actual_size, &final_size);
918 EVP_CIPHER_CTX_free(d_ctx);
919 free(personalized_application_id);
920 free(keystore_result);
921 int secret_key_real_size = actual_size - 16;
922 //printf("secret key: "); output_hex((const unsigned char*)secret_key, secret_key_real_size); printf("\n");
923 // 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
924 // We now have the disk decryption key!
Peter Caiea1764c2019-05-23 21:44:35 +0800925 if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V3) {
926 // V3 uses SP800 instead of SHA512
927 disk_decryption_secret_key = PersonalizedHashSP800(PERSONALIZATION_FBE_KEY, PERSONALISATION_CONTEXT, (const char*)secret_key, secret_key_real_size);
928 } else {
929 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)secret_key, secret_key_real_size);
930 }
Ethan Yonkerc5dd5792018-03-08 21:26:44 -0600931 //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
932 free(secret_key);
933 return disk_decryption_secret_key;
Ethan Yonkere131bec2017-12-15 23:48:02 -0600934 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500935 return disk_decryption_secret_key;
936}
937
938}}
939
940#define PASSWORD_TOKEN_SIZE 32
941
Ethan Yonkere131bec2017-12-15 23:48:02 -0600942/* C++ replacement for
943 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#992
944 * called here
945 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#813 */
946bool Get_Secdis(const std::string& spblob_path, const std::string& handle_str, std::string& secdis_data) {
947 std::string secdis_file = spblob_path + handle_str + ".secdis";
948 if (!android::base::ReadFileToString(secdis_file, &secdis_data)) {
949 printf("Failed to read '%s'\n", secdis_file.c_str());
950 return false;
951 }
952 //output_hex(secdis_data.data(), secdis_data.size());printf("\n");
953 return true;
954}
955
956// 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
957userid_t fakeUid(const userid_t uid) {
958 return 100000 + uid;
959}
960
961bool Is_Weaver(const std::string& spblob_path, const std::string& handle_str) {
962 std::string weaver_file = spblob_path + handle_str + ".weaver";
963 struct stat st;
964 if (stat(weaver_file.c_str(), &st) == 0)
965 return true;
966 return false;
967}
968
969bool Free_Return(bool retval, void* weaver_key, password_data_struct* pwd) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500970 if (weaver_key)
971 free(weaver_key);
Ethan Yonkere131bec2017-12-15 23:48:02 -0600972 if (pwd->salt)
973 free(pwd->salt);
974 if (pwd->password_handle)
975 free(pwd->password_handle);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500976 return retval;
977}
978
979/* Decrypt_User_Synth_Pass is the TWRP C++ equivalent to spBasedDoVerifyCredential
980 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#1998 */
981bool Decrypt_User_Synth_Pass(const userid_t user_id, const std::string& Password) {
982 bool retval = false;
983 void* weaver_key = NULL;
984 password_data_struct pwd;
985 pwd.salt = NULL;
Ethan Yonkere131bec2017-12-15 23:48:02 -0600986 pwd.salt_len = 0;
987 pwd.password_handle = NULL;
988 pwd.handle_len = 0;
989 char application_id[PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH];
990
991 uint32_t auth_token_len = 0;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500992
993 std::string secret; // this will be the disk decryption key that is sent to vold
994 std::string token = "!"; // there is no token used for this kind of decrypt, key escrow is handled by weaver
995 int flags = FLAG_STORAGE_DE;
996 if (user_id == 0)
997 flags = FLAG_STORAGE_DE;
998 else
999 flags = FLAG_STORAGE_CE;
1000 char spblob_path_char[PATH_MAX];
1001 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
1002 std::string spblob_path = spblob_path_char;
1003 long handle = 0;
1004 std::string handle_str;
1005 // 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
1006 if (!Find_Handle(spblob_path, handle_str)) {
1007 printf("Error getting handle\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001008 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001009 }
1010 printf("Handle is '%s'\n", handle_str.c_str());
1011 // 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
1012 // First we read the password data which contains scrypt parameters
1013 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
1014 printf("Failed to Get_Password_Data\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001015 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001016 }
1017 //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");
1018 unsigned char password_token[PASSWORD_TOKEN_SIZE];
1019 //printf("Password: '%s'\n", Password.c_str());
1020 // The password token is the password scrypted with the parameters from the password data file
1021 if (!Get_Password_Token(&pwd, Password, &password_token[0])) {
1022 printf("Failed to Get_Password_Token\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001023 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001024 }
1025 //output_hex(&password_token[0], PASSWORD_TOKEN_SIZE);printf("\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001026 if (Is_Weaver(spblob_path, handle_str)) {
1027 printf("using weaver\n");
1028 // BEGIN PIXEL 2 WEAVER
1029 // Get the weaver data from the .weaver file which tells us which slot to use when we ask weaver for the escrowed key
1030 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768
1031 weaver_data_struct wd;
1032 if (!Get_Weaver_Data(spblob_path, handle_str, &wd)) {
1033 printf("Failed to get weaver data\n");
1034 return Free_Return(retval, weaver_key, &pwd);
1035 }
1036 // The weaver key is the the password token prefixed with "weaver-key" padded to 128 with nulls with the password token appended then SHA512
1037 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1059
1038 weaver_key = PersonalizedHashBinary(PERSONALISATION_WEAVER_KEY, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
1039 if (!weaver_key) {
1040 printf("malloc error getting weaver_key\n");
1041 return Free_Return(retval, weaver_key, &pwd);
1042 }
1043 // 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
1044 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#776
1045 android::vold::Weaver weaver;
1046 if (!weaver) {
1047 printf("Failed to get weaver service\n");
1048 return Free_Return(retval, weaver_key, &pwd);
1049 }
1050 // Get the key size from weaver service
1051 uint32_t weaver_key_size = 0;
1052 if (!weaver.GetKeySize(&weaver_key_size)) {
1053 printf("Failed to get weaver key size\n");
1054 return Free_Return(retval, weaver_key, &pwd);
1055 } else {
1056 //printf("weaver key size is %u\n", weaver_key_size);
1057 }
1058 //printf("weaver key: "); output_hex((unsigned char*)weaver_key, weaver_key_size); printf("\n");
1059 // Send the slot from the .weaver file, the computed weaver key, and get the escrowed key data
1060 std::vector<uint8_t> weaver_payload;
1061 // TODO: we should return more information about the status including time delays before the next retry
1062 if (!weaver.WeaverVerify(wd.slot, weaver_key, &weaver_payload)) {
1063 printf("failed to weaver verify\n");
1064 return Free_Return(retval, weaver_key, &pwd);
1065 }
1066 //printf("weaver payload: "); output_hex(&weaver_payload); printf("\n");
1067 // Done with weaverVerify
1068 // Now we will compute the application ID
1069 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#964
1070 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#780
1071 // The escrowed weaver key data is prefixed with "weaver-pwd" padded to 128 with nulls with the weaver payload appended then SHA512
1072 void* weaver_secret = PersonalizedHashBinary(PERSONALISATION_WEAVER_PASSWORD, (const char*)weaver_payload.data(), weaver_payload.size());
1073 //printf("weaver secret: "); output_hex((unsigned char*)weaver_secret, SHA512_DIGEST_LENGTH); printf("\n");
1074 // The application ID is the password token and weaver secret appended to each other
1075 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
1076 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], weaver_secret, SHA512_DIGEST_LENGTH);
1077 //printf("application ID: "); output_hex((unsigned char*)application_id, PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH); printf("\n");
1078 // END PIXEL 2 WEAVER
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001079 } else {
Ethan Yonkere131bec2017-12-15 23:48:02 -06001080 printf("using secdis\n");
1081 std::string secdis_data;
1082 if (!Get_Secdis(spblob_path, handle_str, secdis_data)) {
1083 printf("Failed to get secdis data\n");
1084 return Free_Return(retval, weaver_key, &pwd);
1085 }
1086 void* secdiscardable = PersonalizedHashBinary(PERSONALISATION_SECDISCARDABLE, (char*)secdis_data.data(), secdis_data.size());
1087 if (!secdiscardable) {
1088 printf("malloc error getting secdiscardable\n");
1089 return Free_Return(retval, weaver_key, &pwd);
1090 }
1091 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
1092 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], secdiscardable, SHA512_DIGEST_LENGTH);
1093
1094 int ret = -1;
1095 bool request_reenroll = false;
1096 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1097 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1098 if (gk_device == nullptr) {
1099 printf("failed to get gatekeeper service\n");
1100 return Free_Return(retval, weaver_key, &pwd);
1101 }
1102 if (pwd.handle_len <= 0) {
1103 printf("no password handle supplied\n");
1104 return Free_Return(retval, weaver_key, &pwd);
1105 }
1106 android::hardware::hidl_vec<uint8_t> pwd_handle_hidl;
1107 pwd_handle_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)pwd.password_handle), pwd.handle_len);
1108 void* gk_pwd_token = PersonalizedHashBinary(PERSONALIZATION_USER_GK_AUTH, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
1109 if (!gk_pwd_token) {
1110 printf("malloc error getting gatekeeper_key\n");
1111 return Free_Return(retval, weaver_key, &pwd);
1112 }
1113 android::hardware::hidl_vec<uint8_t> gk_pwd_token_hidl;
1114 gk_pwd_token_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)gk_pwd_token), SHA512_DIGEST_LENGTH);
1115 android::hardware::Return<void> hwRet =
1116 gk_device->verify(fakeUid(user_id), 0 /* challange */,
1117 pwd_handle_hidl,
1118 gk_pwd_token_hidl,
1119 [&ret, &request_reenroll, &auth_token_len]
1120 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1121 ret = static_cast<int>(rsp.code); // propagate errors
1122 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1123 auth_token_len = rsp.data.size();
1124 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1125 ret = 0; // all success states are reported as 0
1126 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file here and later
1127 // run a separate service that runs as the system user to add the auth token. We wait for the auth token file to be
1128 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after a while seconds if
1129 // the /auth_token file never gets deleted.
1130 unlink("/auth_token");
1131 FILE* auth_file = fopen("/auth_token","wb");
1132 if (auth_file != NULL) {
1133 fwrite(rsp.data.data(), sizeof(uint8_t), rsp.data.size(), auth_file);
1134 fclose(auth_file);
1135 } else {
1136 printf("failed to open /auth_token for writing\n");
1137 ret = -2;
1138 }
1139 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1140 ret = rsp.timeout;
1141 }
1142 }
1143 );
1144 free(gk_pwd_token);
1145 if (!hwRet.isOk() || ret != 0) {
1146 printf("gatekeeper verification failed\n");
1147 return Free_Return(retval, weaver_key, &pwd);
1148 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001149 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001150 // 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
1151 // Plus we will include the last bit that computes the disk decrypt key found in:
1152 // 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 -06001153 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 -05001154 if (!secret.size()) {
1155 printf("failed to unwrapSyntheticPasswordBlob\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001156 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001157 }
1158 if (!e4crypt_unlock_user_key(user_id, 0, token.c_str(), secret.c_str())) {
1159 printf("e4crypt_unlock_user_key returned fail\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001160 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001161 }
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001162#ifdef USE_KEYSTORAGE_4
1163 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1164#else
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001165 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001166#endif
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001167 printf("failed to e4crypt_prepare_user_storage\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -06001168 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001169 }
1170 printf("Decrypted Successfully!\n");
1171 retval = true;
Ethan Yonkere131bec2017-12-15 23:48:02 -06001172 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001173}
1174#endif //HAVE_SYNTH_PWD_SUPPORT
1175
1176int Get_Password_Type(const userid_t user_id, std::string& filename) {
1177 struct stat st;
1178 char spblob_path_char[PATH_MAX];
1179 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
1180 if (stat(spblob_path_char, &st) == 0) {
1181#ifdef HAVE_SYNTH_PWD_SUPPORT
1182 printf("Using synthetic password method\n");
1183 std::string spblob_path = spblob_path_char;
1184 std::string handle_str;
1185 if (!Find_Handle(spblob_path, handle_str)) {
1186 printf("Error getting handle\n");
1187 return 0;
1188 }
1189 printf("Handle is '%s'\n", handle_str.c_str());
1190 password_data_struct pwd;
1191 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
1192 printf("Failed to Get_Password_Data\n");
1193 return 0;
1194 }
1195 if (pwd.password_type == 1) // In Android this means pattern
1196 return 2; // In TWRP this means pattern
1197 else if (pwd.password_type == 2) // In Android this means PIN or password
1198 return 1; // In TWRP this means PIN or password
1199 return 0; // We'll try the default password
1200#else
1201 printf("Synthetic password support not present in TWRP\n");
1202 return -1;
1203#endif
1204 }
1205 std::string path;
1206 if (user_id == 0) {
1207 path = "/data/system/";
1208 } else {
1209 char user_id_str[5];
1210 sprintf(user_id_str, "%i", user_id);
1211 path = "/data/system/users/";
1212 path += user_id_str;
1213 path += "/";
1214 }
1215 filename = path + "gatekeeper.password.key";
1216 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1217 return 1;
1218 filename = path + "gatekeeper.pattern.key";
1219 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1220 return 2;
1221 printf("Unable to locate gatekeeper password file '%s'\n", filename.c_str());
1222 filename = "";
1223 return 0;
1224}
1225
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001226bool Decrypt_User(const userid_t user_id, const std::string& Password) {
1227 uint8_t *auth_token;
1228 uint32_t auth_token_len;
1229 int ret;
1230
1231 struct stat st;
1232 if (user_id > 9999) {
1233 printf("user_id is too big\n");
1234 return false;
1235 }
1236 std::string filename;
1237 bool Default_Password = (Password == "!");
1238 if (Get_Password_Type(user_id, filename) == 0 && !Default_Password) {
1239 printf("Unknown password type\n");
1240 return false;
1241 }
1242 int flags = FLAG_STORAGE_DE;
1243 if (user_id == 0)
1244 flags = FLAG_STORAGE_DE;
1245 else
1246 flags = FLAG_STORAGE_CE;
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001247 if (Default_Password) {
1248 if (!e4crypt_unlock_user_key(user_id, 0, "!", "!")) {
1249 printf("e4crypt_unlock_user_key returned fail\n");
1250 return false;
1251 }
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001252#ifdef USE_KEYSTORAGE_4
1253 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1254#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001255 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001256#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001257 printf("failed to e4crypt_prepare_user_storage\n");
1258 return false;
1259 }
1260 printf("Decrypted Successfully!\n");
1261 return true;
1262 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001263 if (stat("/data/system_de/0/spblob", &st) == 0) {
1264#ifdef HAVE_SYNTH_PWD_SUPPORT
1265 printf("Using synthetic password method\n");
1266 return Decrypt_User_Synth_Pass(user_id, Password);
1267#else
1268 printf("Synthetic password support not present in TWRP\n");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001269 return false;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001270#endif
1271 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001272 printf("password filename is '%s'\n", filename.c_str());
1273 if (stat(filename.c_str(), &st) != 0) {
1274 printf("error stat'ing key file: %s\n", strerror(errno));
1275 return false;
1276 }
1277 std::string handle;
1278 if (!android::base::ReadFileToString(filename, &handle)) {
1279 printf("Failed to read '%s'\n", filename.c_str());
1280 return false;
1281 }
1282 bool should_reenroll;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001283#ifdef HAVE_GATEKEEPER1
1284 bool request_reenroll = false;
1285 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1286 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1287 if (gk_device == nullptr)
1288 return false;
1289 android::hardware::hidl_vec<uint8_t> curPwdHandle;
1290 curPwdHandle.setToExternal(const_cast<uint8_t *>((const uint8_t *)handle.c_str()), st.st_size);
1291 android::hardware::hidl_vec<uint8_t> enteredPwd;
1292 enteredPwd.setToExternal(const_cast<uint8_t *>((const uint8_t *)Password.c_str()), Password.size());
1293
1294 android::hardware::Return<void> hwRet =
1295 gk_device->verify(user_id, 0 /* challange */,
1296 curPwdHandle,
1297 enteredPwd,
1298 [&ret, &request_reenroll, &auth_token, &auth_token_len]
1299 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1300 ret = static_cast<int>(rsp.code); // propagate errors
1301 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1302 auth_token = new uint8_t[rsp.data.size()];
1303 auth_token_len = rsp.data.size();
1304 memcpy(auth_token, rsp.data.data(), auth_token_len);
1305 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1306 ret = 0; // all success states are reported as 0
1307 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1308 ret = rsp.timeout;
1309 }
1310 }
1311 );
1312 if (!hwRet.isOk()) {
1313 return false;
1314 }
1315#else
1316 gatekeeper_device_t *gk_device;
1317 ret = gatekeeper_device_initialize(&gk_device);
1318 if (ret!=0)
1319 return false;
1320 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 -06001321 (const uint8_t *)Password.c_str(), (uint32_t)Password.size(), &auth_token, &auth_token_len,
1322 &should_reenroll);
1323 if (ret !=0) {
1324 printf("failed to verify\n");
1325 return false;
1326 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001327#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001328 char token_hex[(auth_token_len*2)+1];
1329 token_hex[(auth_token_len*2)] = 0;
1330 uint32_t i;
1331 for (i=0;i<auth_token_len;i++) {
1332 sprintf(&token_hex[2*i], "%02X", auth_token[i]);
1333 }
1334 // 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
1335 std::string secret = HashPassword(Password);
1336 if (!e4crypt_unlock_user_key(user_id, 0, token_hex, secret.c_str())) {
1337 printf("e4crypt_unlock_user_key returned fail\n");
1338 return false;
1339 }
codeworkx22e3aa92019-04-23 12:02:26 +02001340#ifdef USE_KEYSTORAGE_4
1341 if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
1342#else
1343 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
1344#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001345 printf("failed to e4crypt_prepare_user_storage\n");
1346 return false;
1347 }
1348 printf("Decrypted Successfully!\n");
1349 return true;
1350}