blob: 4a8494e5e606d79cd6eb50450c6ded993553f7ce [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"
18#include "Ext4Crypt.h"
19
Ethan Yonker79f88bd2016-12-09 14:52:12 -060020#include <map>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060021#include <string>
22
23#include <errno.h>
24#include <stdio.h>
Ethan Yonker79f88bd2016-12-09 14:52:12 -060025#include <stdlib.h>
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060026#include <sys/stat.h>
27#include <sys/types.h>
28
Ethan Yonkerfefe5912017-09-30 22:22:13 -050029#ifndef HAVE_LIBKEYUTILS
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060030#include "key_control.h"
Ethan Yonkerfefe5912017-09-30 22:22:13 -050031#else
32#include <keyutils.h>
33#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060034
Ethan Yonkerfefe5912017-09-30 22:22:13 -050035#ifdef HAVE_SYNTH_PWD_SUPPORT
36#include "Weaver1.h"
37#include "cutils/properties.h"
38
39#include <openssl/sha.h>
40#include <openssl/aes.h>
41#include <openssl/evp.h>
42#include <openssl/rand.h>
43
44#include <dirent.h>
45#include <stdio.h>
46#include <stdint.h>
47#include <string.h>
48#include <sys/types.h>
49#include <fstream>
50
51#include <ext4_utils/ext4_crypt.h>
52
53#include <keystore/IKeystoreService.h>
54#include <binder/IPCThreadState.h>
55#include <binder/IServiceManager.h>
56
57#include <keystore/keystore.h>
58#include <keystore/authorization_set.h>
59
60#include <algorithm>
61extern "C" {
62#include "crypto_scrypt.h"
63}
64#else
65#include "ext4_crypt.h"
66#endif //ifdef HAVE_SYNTH_PWD_SUPPORT
67
68#ifdef HAVE_GATEKEEPER1
69#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
70#else
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060071#include <hardware/gatekeeper.h>
Ethan Yonkerfefe5912017-09-30 22:22:13 -050072#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -060073#include "HashPassword.h"
74
75#include <android-base/file.h>
76
Ethan Yonker79f88bd2016-12-09 14:52:12 -060077// Store main DE raw ref / policy
78extern std::string de_raw_ref;
79extern std::map<userid_t, std::string> s_de_key_raw_refs;
80extern std::map<userid_t, std::string> s_ce_key_raw_refs;
81
82static bool lookup_ref_key_internal(std::map<userid_t, std::string>& key_map, const char* policy, userid_t* user_id) {
83 for (std::map<userid_t, std::string>::iterator it=key_map.begin(); it!=key_map.end(); ++it) {
84 if (strncmp(it->second.c_str(), policy, it->second.size()) == 0) {
85 *user_id = it->first;
86 return true;
87 }
88 }
89 return false;
90}
91
92extern "C" bool lookup_ref_key(const char* policy, char* policy_type) {
93 userid_t user_id = 0;
94 if (strncmp(de_raw_ref.c_str(), policy, de_raw_ref.size()) == 0) {
95 strcpy(policy_type, "1DK");
96 return true;
97 }
98 if (!lookup_ref_key_internal(s_de_key_raw_refs, policy, &user_id)) {
99 if (!lookup_ref_key_internal(s_ce_key_raw_refs, policy, &user_id)) {
100 return false;
101 } else
102 sprintf(policy_type, "1CE%d", user_id);
103 } else
104 sprintf(policy_type, "1DE%d", user_id);
105 return true;
106}
107
108extern "C" bool lookup_ref_tar(const char* policy_type, char* policy) {
109 if (strncmp(policy_type, "1", 1) != 0) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500110 printf("Unexpected version %c\n", policy_type[0]);
Ethan Yonker79f88bd2016-12-09 14:52:12 -0600111 return false;
112 }
113 const char* ptr = policy_type + 1; // skip past the version number
114 if (strncmp(ptr, "DK", 2) == 0) {
115 strncpy(policy, de_raw_ref.data(), de_raw_ref.size());
116 return true;
117 }
118 userid_t user_id = atoi(ptr + 2);
119 std::string raw_ref;
120 if (*ptr == 'D') {
121 if (lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)) {
122 strncpy(policy, raw_ref.data(), raw_ref.size());
123 } else
124 return false;
125 } else if (*ptr == 'C') {
126 if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
127 strncpy(policy, raw_ref.data(), raw_ref.size());
128 } else
129 return false;
130 } else {
131 printf("unknown policy type '%s'\n", policy_type);
132 return false;
133 }
134 return true;
135}
136
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500137#ifndef HAVE_GATEKEEPER1
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600138int gatekeeper_device_initialize(gatekeeper_device_t **dev) {
139 int ret;
140 const hw_module_t *mod;
141 ret = hw_get_module_by_class(GATEKEEPER_HARDWARE_MODULE_ID, NULL, &mod);
142
143 if (ret!=0) {
144 printf("failed to get hw module\n");
145 return ret;
146 }
147
148 ret = gatekeeper_open(mod, dev);
149
150 if (ret!=0)
151 printf("failed to open gatekeeper\n");
152 return ret;
153}
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500154#endif //ifndef HAVE_GATEKEEPER1
Ethan Yonkerbd7492d2016-12-07 13:55:01 -0600155
156bool Decrypt_DE() {
157 if (!e4crypt_initialize_global_de()) { // this deals with the overarching device encryption
158 printf("e4crypt_initialize_global_de returned fail\n");
159 return false;
160 }
161 if (!e4crypt_init_user0()) {
162 printf("e4crypt_init_user0 returned fail\n");
163 return false;
164 }
165 return true;
166}
167
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500168#ifdef HAVE_SYNTH_PWD_SUPPORT
169// Crappy functions for debugging, please ignore unless you need to debug
170/*void output_hex(const std::string& in) {
171 const char *buf = in.data();
172 char hex[in.size() * 2 + 1];
173 unsigned int index;
174 for (index = 0; index < in.size(); index++)
175 sprintf(&hex[2 * index], "%02X", buf[index]);
176 printf("%s", hex);
177}
178
179void output_hex(const char* buf, const int size) {
180 char hex[size * 2 + 1];
181 int index;
182 for (index = 0; index < size; index++)
183 sprintf(&hex[2 * index], "%02X", buf[index]);
184 printf("%s", hex);
185}
186
187void output_hex(const unsigned 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(std::vector<uint8_t>* vec) {
196 char hex[3];
197 unsigned int index;
198 for (index = 0; index < vec->size(); index++) {
199 sprintf(&hex[0], "%02X", vec->at(index));
200 printf("%s", hex);
201 }
202}*/
203
204/* An alternative is to use:
205 * sqlite3 /data/system/locksettings.db "SELECT value FROM locksettings WHERE name='sp-handle' AND user=0;"
206 * but we really don't want to include the 1.1MB libsqlite in TWRP. We scan the spblob folder for the
207 * password data file (*.pwd) and get the handle from the filename instead. This is a replacement for
208 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#2017
209 * We never use this data as an actual long. We always use it as a string. */
210bool Find_Handle(const std::string& spblob_path, std::string& handle_str) {
211 DIR* dir = opendir(spblob_path.c_str());
212 if (!dir) {
213 printf("Error opening '%s'\n", spblob_path.c_str());
214 return false;
215 }
216
217 struct dirent* de = 0;
218
219 while ((de = readdir(dir)) != 0) {
220 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
221 continue;
222 size_t len = strlen(de->d_name);
223 if (len <= 4)
224 continue;
225 char* p = de->d_name;
226 p += len - 4;
227 if (strncmp(p, ".pwd", 4) == 0) {
228 handle_str = de->d_name;
229 handle_str = handle_str.substr(0, len - 4);
230 //*handle = strtoull(handle_str.c_str(), 0 , 16);
231 closedir(dir);
232 return true;
233 }
234 }
235 closedir(dir);
236 return false;
237}
238
239// The password data is stored in big endian and has to be swapped on little endian ARM
240template <class T>
241void endianswap(T *objp) {
242 unsigned char *memp = reinterpret_cast<unsigned char*>(objp);
243 std::reverse(memp, memp + sizeof(T));
244}
245
246/* This is the structure of the data in the password data (*.pwd) file which the structure can be found
247 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#187 */
248struct password_data_struct {
249 int password_type;
250 unsigned char scryptN;
251 unsigned char scryptR;
252 unsigned char scryptP;
253 int salt_len;
254 void* salt;
255 int handle_len;
256 void* password_handle;
257};
258
259/* C++ replacement for
260 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#764 */
261bool Get_Password_Data(const std::string& spblob_path, const std::string& handle_str, password_data_struct *pwd) {
262 std::string pwd_file = spblob_path + handle_str + ".pwd";
263 std::string pwd_data;
264 if (!android::base::ReadFileToString(pwd_file, &pwd_data)) {
265 printf("Failed to read '%s'\n", pwd_file.c_str());
266 return false;
267 }
268 //output_hex(pwd_data.data(), pwd_data.size());printf("\n");
269 const int* intptr = (const int*)pwd_data.data();
270 pwd->password_type = *intptr;
271 endianswap(&pwd->password_type);
272 //printf("password type %i\n", pwd->password_type); // 2 was PIN, 1 for pattern, 2 also for password, -1 for default password
273 const unsigned char* byteptr = (const unsigned char*)pwd_data.data() + sizeof(int);
274 pwd->scryptN = *byteptr;
275 byteptr++;
276 pwd->scryptR = *byteptr;
277 byteptr++;
278 pwd->scryptP = *byteptr;
279 byteptr++;
280 intptr = (const int*)byteptr;
281 pwd->salt_len = *intptr;
282 endianswap(&pwd->salt_len);
283 if (pwd->salt_len != 0) {
284 pwd->salt = malloc(pwd->salt_len);
285 if (!pwd->salt) {
286 printf("Get_Password_Data malloc salt\n");
287 return false;
288 }
289 memcpy(pwd->salt, intptr + 1, pwd->salt_len);
Ethan Yonkere131bec2017-12-15 23:48:02 -0600290 intptr++;
291 byteptr = (const unsigned char*)intptr;
292 byteptr += pwd->salt_len;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500293 } else {
294 printf("Get_Password_Data salt_len is 0\n");
295 return false;
296 }
Ethan Yonkere131bec2017-12-15 23:48:02 -0600297 intptr = (const int*)byteptr;
298 pwd->handle_len = *intptr;
299 endianswap(&pwd->handle_len);
300 if (pwd->handle_len != 0) {
301 pwd->password_handle = malloc(pwd->handle_len);
302 if (!pwd->password_handle) {
303 printf("Get_Password_Data malloc password_handle\n");
304 return false;
305 }
306 memcpy(pwd->password_handle, intptr + 1, pwd->handle_len);
307 } else {
308 printf("Get_Password_Data handle_len is 0\n");
309 // Not an error if using weaver
310 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500311 return true;
312}
313
314/* C++ replacement for
315 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#765
316 * called here
317 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1050 */
318bool Get_Password_Token(const password_data_struct *pwd, const std::string& Password, unsigned char* password_token) {
319 if (!password_token) {
320 printf("password_token is null\n");
321 return false;
322 }
323 unsigned int N = 1 << pwd->scryptN;
324 unsigned int r = 1 << pwd->scryptR;
325 unsigned int p = 1 << pwd->scryptP;
326 //printf("N %i r %i p %i\n", N, r, p);
327 int ret = crypto_scrypt(reinterpret_cast<const uint8_t*>(Password.data()), Password.size(),
328 reinterpret_cast<const uint8_t*>(pwd->salt), pwd->salt_len,
329 N, r, p,
330 password_token, 32);
331 if (ret != 0) {
332 printf("scrypt error\n");
333 return false;
334 }
335 return true;
336}
337
338// Data structure for the *.weaver file, see Get_Weaver_Data below
339struct weaver_data_struct {
340 unsigned char version;
341 int slot;
342};
343
344/* C++ replacement for
345 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#501
346 * called here
347 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768 */
348bool Get_Weaver_Data(const std::string& spblob_path, const std::string& handle_str, weaver_data_struct *wd) {
349 std::string weaver_file = spblob_path + handle_str + ".weaver";
350 std::string weaver_data;
351 if (!android::base::ReadFileToString(weaver_file, &weaver_data)) {
352 printf("Failed to read '%s'\n", weaver_file.c_str());
353 return false;
354 }
355 //output_hex(weaver_data.data(), weaver_data.size());printf("\n");
356 const unsigned char* byteptr = (const unsigned char*)weaver_data.data();
357 wd->version = *byteptr;
358 //printf("weaver version %i\n", wd->version);
359 const int* intptr = (const int*)weaver_data.data() + sizeof(unsigned char);
360 wd->slot = *intptr;
361 //endianswap(&wd->slot); not needed
362 //printf("weaver slot %i\n", wd->slot);
363 return true;
364}
365
366namespace android {
367
368// On Android 8.0 for some reason init can't seem to completely stop keystore
369// so we have to kill it too if it doesn't die on its own.
370static void kill_keystore() {
371 DIR* dir = opendir("/proc");
372 if (dir) {
373 struct dirent* de = 0;
374
375 while ((de = readdir(dir)) != 0) {
376 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
377 continue;
378
379 int pid = -1;
380 int ret = sscanf(de->d_name, "%d", &pid);
381
382 if (ret == 1) {
383 char cmdpath[PATH_MAX];
384 sprintf(cmdpath, "/proc/%d/cmdline", pid);
385
386 FILE* file = fopen(cmdpath, "r");
387 size_t task_size = PATH_MAX;
388 char task[PATH_MAX];
389 char* p = task;
390 if (getline(&p, &task_size, file) > 0) {
391 if (strstr(task, "keystore") != 0) {
392 printf("keystore pid %d found, sending kill.\n", pid);
393 kill(pid, SIGINT);
394 usleep(5000);
395 kill(pid, SIGKILL);
396 }
397 }
398 fclose(file);
399 }
400 }
401 closedir(dir);
402 }
403}
404
405// The keystore holds a file open on /data so we have to stop / kill it
406// if we want to be able to unmount /data for things like formatting.
407static void stop_keystore() {
408 printf("Stopping keystore...\n");
409 property_set("ctl.stop", "keystore");
410 usleep(5000);
411 kill_keystore();
412}
413
414/* These next 2 functions try to get the keystore service 50 times because
415 * the keystore is not always ready when TWRP boots */
416sp<IBinder> getKeystoreBinder() {
417 sp<IServiceManager> sm = defaultServiceManager();
418 return sm->getService(String16("android.security.keystore"));
419}
420
421sp<IBinder> getKeystoreBinderRetry() {
422 printf("Starting keystore...\n");
423 property_set("ctl.start", "keystore");
424 int retry_count = 50;
425 sp<IBinder> binder = getKeystoreBinder();
426 while (binder == NULL && retry_count) {
427 printf("Waiting for keystore service... %i\n", retry_count--);
428 sleep(1);
429 binder = getKeystoreBinder();
430 }
431 return binder;
432}
433
434namespace keystore {
435
436#define SYNTHETIC_PASSWORD_VERSION 1
437#define SYNTHETIC_PASSWORD_PASSWORD_BASED 0
438#define SYNTHETIC_PASSWORD_KEY_PREFIX "USRSKEY_synthetic_password_"
439
440/* The keystore alias subid is sometimes the same as the handle, but not always.
441 * In the case of handle 0c5303fd2010fe29, the alias subid used c5303fd2010fe29
442 * without the leading 0. We could try to parse the data from a previous
443 * keystore request, but I think this is an easier solution because there
444 * is little to no documentation on the format of data we get back from
445 * the keystore in this instance. We also want to copy everything to a temp
446 * folder so that any key upgrades that might take place do not actually
447 * upgrade the keys on the data partition. We rename all 1000 uid files to 0
448 * to pass the keystore permission checks. */
449bool Find_Keystore_Alias_SubID_And_Prep_Files(const userid_t user_id, std::string& keystoreid) {
450 char path_c[PATH_MAX];
451 sprintf(path_c, "/data/misc/keystore/user_%d", user_id);
452 char user_dir[PATH_MAX];
453 sprintf(user_dir, "user_%d", user_id);
454 std::string source_path = "/data/misc/keystore/";
455 source_path += user_dir;
456
457 mkdir("/tmp/misc", 0755);
458 mkdir("/tmp/misc/keystore", 0755);
459 std::string destination_path = "/tmp/misc/keystore/";
460 destination_path += user_dir;
461 if (mkdir(destination_path.c_str(), 0755) && errno != EEXIST) {
462 printf("failed to mkdir '%s' %s\n", destination_path.c_str(), strerror(errno));
463 return false;
464 }
465 destination_path += "/";
466
467 DIR* dir = opendir(source_path.c_str());
468 if (!dir) {
469 printf("Error opening '%s'\n", source_path.c_str());
470 return false;
471 }
472 source_path += "/";
473
474 struct dirent* de = 0;
475 size_t prefix_len = strlen(SYNTHETIC_PASSWORD_KEY_PREFIX);
476 bool found_subid = false;
477
478 while ((de = readdir(dir)) != 0) {
479 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
480 continue;
481 if (!found_subid) {
482 size_t len = strlen(de->d_name);
483 if (len <= prefix_len)
484 continue;
485 if (!strstr(de->d_name, SYNTHETIC_PASSWORD_KEY_PREFIX))
486 continue;
487 std::string file = de->d_name;
488 std::size_t found = file.find_last_of("_");
489 if (found != std::string::npos) {
490 keystoreid = file.substr(found + 1);
491 printf("keystoreid: '%s'\n", keystoreid.c_str());
492 found_subid = true;
493 }
494 }
495 std::string src = source_path;
496 src += de->d_name;
497 std::ifstream srcif(src.c_str(), std::ios::binary);
498 std::string dst = destination_path;
499 dst += de->d_name;
500 std::size_t source_uid = dst.find("1000");
501 if (source_uid != std::string::npos)
502 dst.replace(source_uid, 4, "0");
503 std::ofstream dstof(dst.c_str(), std::ios::binary);
504 printf("copying '%s' to '%s'\n", src.c_str(), dst.c_str());
505 dstof << srcif.rdbuf();
506 srcif.close();
507 dstof.close();
508 }
509 closedir(dir);
510 return found_subid;
511}
512
513/* C++ replacement for function of the same name
514 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#867
515 * returning an empty string indicates an error */
Ethan Yonkere131bec2017-12-15 23:48:02 -0600516std::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 -0500517 std::string disk_decryption_secret_key = "";
518
519 std::string keystore_alias_subid;
520 if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid)) {
521 printf("failed to scan keystore alias subid and prep keystore files\n");
522 return disk_decryption_secret_key;
523 }
524
525 // First get the keystore service
526 sp<IBinder> binder = getKeystoreBinderRetry();
527 sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
528 if (service == NULL) {
529 printf("error: could not connect to keystore service\n");
530 return disk_decryption_secret_key;
531 }
532
Ethan Yonkere131bec2017-12-15 23:48:02 -0600533 if (auth_token_len > 0) {
534 printf("Starting keystore_auth service...\n");
535 property_set("ctl.start", "keystore_auth");
536 }
537
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500538 // 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
539 std::string spblob_file = spblob_path + handle_str + ".spblob";
540 std::string spblob_data;
541 if (!android::base::ReadFileToString(spblob_file, &spblob_data)) {
542 printf("Failed to read '%s'\n", spblob_file.c_str());
543 return disk_decryption_secret_key;
544 }
545 const unsigned char* byteptr = (const unsigned char*)spblob_data.data();
546 if (*byteptr != SYNTHETIC_PASSWORD_VERSION) {
547 printf("SYNTHETIC_PASSWORD_VERSION does not match\n");
548 return disk_decryption_secret_key;
549 }
550 byteptr++;
551 if (*byteptr != SYNTHETIC_PASSWORD_PASSWORD_BASED) {
552 printf("spblob data is not SYNTHETIC_PASSWORD_PASSWORD_BASED\n");
553 return disk_decryption_secret_key;
554 }
555 byteptr++; // Now we're pointing to the blob data itself
556 /* 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
557 * Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#879
558 * 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.
559 * The keystore data seems to be the serialized data from an entire class in Java. Specifically I think it represents:
560 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
561 * or perhaps
562 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
563 * 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}
564 * 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.
565 * There are 2 calls to a Java decrypt funcion that is overloaded. These 2 calls go in completely different directions despite the seemingly
566 * similar use of decrypt() and decrypt parameters. To figure out where things were going, I added logging to:
567 * https://android.googlesource.com/platform/libcore/+/android-8.0.0_r23/ojluni/src/main/java/javax/crypto/Cipher.java#2575
568 * Logger.global.severe("Cipher tryCombinations " + prov.getName() + " - " + prov.getInfo());
569 * 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
570 * 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
571 * 2 different providers in use. The first stage to get the intermediate key used:
572 * https://android.googlesource.com/platform/external/conscrypt/+/android-8.0.0_r23/common/src/main/java/org/conscrypt/OpenSSLProvider.java
573 * which is a pretty straight-forward OpenSSL implementation of AES/GCM/NoPadding. */
574 // 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
575 void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size);
576 if (!personalized_application_id) {
577 printf("malloc personalized_application_id\n");
578 return disk_decryption_secret_key;
579 }
580 //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n");
581 // Now we'll decrypt using openssl AES/GCM/NoPadding
582 OpenSSL_add_all_ciphers();
583 int actual_size=0, final_size=0;
584 EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new();
585 const unsigned char* iv = (const unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob
586 //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n");
587 const unsigned char* cipher_text = (const unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV
588 //printf("cipher_text: "); output_hex((const unsigned char*)cipher_text, spblob_data.size() - 2 - 12); printf("\n");
589 const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID
590 //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n");
591 EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, iv);
592 std::vector<unsigned char> intermediate_key;
593 intermediate_key.resize(spblob_data.size() - 2 - 12, '\0');
594 EVP_DecryptUpdate(d_ctx, &intermediate_key[0], &actual_size, cipher_text, spblob_data.size() - 2 - 12);
595 unsigned char tag[AES_BLOCK_SIZE];
596 EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
597 EVP_DecryptFinal_ex(d_ctx, &intermediate_key[actual_size], &final_size);
598 EVP_CIPHER_CTX_free(d_ctx);
599 free(personalized_application_id);
600 //printf("spblob_data size: %lu actual_size %i, final_size: %i\n", spblob_data.size(), actual_size, final_size);
601 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
602 //printf("intermediate key: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
603
Ethan Yonkere131bec2017-12-15 23:48:02 -0600604 // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation
605 if (auth_token_len > 0) {
606 /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len);
607 if (!auth_result.isOk()) {
608 // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0
609 printf("keystore error adding auth token\n");
610 return disk_decryption_secret_key;
611 }*/
612 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and
613 // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be
614 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if
615 // the /auth_token file never gets deleted.
616 int auth_wait_count = 20;
617 while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0)
618 usleep(5000);
619 if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) {
620 printf("error during keymaster_auth service\n");
621 /* 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
622 * service keystore_auth /sbin/keystore_auth
623 * disabled
624 * oneshot
625 * user system
626 * group root
627 * seclabel u:r:recovery:s0
628 *
629 * And check dmesg for error codes regarding this service if needed. */
630 return disk_decryption_secret_key;
631 }
632 }
633
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500634 int32_t ret;
635
636 /* 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
637 * as the key data will be read again by the begin function later via the keystore.
638 * The data is in a hidl_vec format which consists of a type and a value. */
639 /*::keystore::hidl_vec<uint8_t> data;
640 std::string keystoreid = SYNTHETIC_PASSWORD_KEY_PREFIX;
641 keystoreid += handle_str;
642
643 ret = service->get(String16(keystoreid.c_str()), user_id, &data);
644 if (ret < 0) {
645 printf("Could not connect to keystore service %i\n", ret);
646 return disk_decryption_secret_key;
647 } else if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*//*) {
648 printf("keystore error: (%d)\n", /*responses[ret],*//* ret);
649 return disk_decryption_secret_key;
650 } else {
651 printf("keystore returned: "); output_hex(&data[0], data.size()); printf("\n");
652 }*/
653
654 // Now we'll break up the intermediate key into the IV (first 12 bytes) and the cipher text (the rest of it).
655 std::vector<unsigned char> nonce = intermediate_key;
656 nonce.resize(12);
657 intermediate_key.erase (intermediate_key.begin(),intermediate_key.begin()+12);
658 //printf("nonce: "); output_hex((const unsigned char*)nonce.data(), nonce.size()); printf("\n");
659 //printf("cipher text: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n");
660
661 /* Now we will begin the second decrypt call found in
662 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#122
663 * This time we will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java
664 * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
665 * First we set some algorithm parameters as seen in two places:
666 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297
667 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */
668 size_t maclen = 128;
669 ::keystore::AuthorizationSetBuilder begin_params;
670 begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES);
671 begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM);
672 begin_params.Padding(::keystore::PaddingMode::NONE);
673 begin_params.Authorization(::keystore::TAG_NONCE, nonce);
674 begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen);
675 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES);
676 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockMode);
677 //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_PADDING, mKeymasterPadding);
678 //keymasterArgs.addUnsignedInt(KeymasterDefs.KM_TAG_MAC_LENGTH, mTagLengthBits);
679 ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt
680 entropy.resize(0);
681 std::string keystore_alias = SYNTHETIC_PASSWORD_KEY_PREFIX;
682 keystore_alias += keystore_alias_subid;
683 String16 keystore_alias16(keystore_alias.c_str());
684 ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT;
685 OperationResult begin_result;
686 // 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
687 service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result);
688 ret = begin_result.resultCode;
689 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
690 printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret);
691 return disk_decryption_secret_key;
692 } else {
693 //printf("keystore begin operation successful\n");
694 }
695 ::keystore::hidl_vec<::keystore::KeyParameter> empty_params;
696 empty_params.resize(0);
697 OperationResult update_result;
698 // 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
699 // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208
700 service->update(begin_result.token, empty_params, intermediate_key, &update_result);
701 ret = update_result.resultCode;
702 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
703 printf("keystore update error: (%d)\n", /*responses[ret],*/ ret);
704 return disk_decryption_secret_key;
705 } else {
706 //printf("keystore update operation successful\n");
707 //printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password
708 }
709 // We must use the data in update_data.data before we call finish below or the data will be gone
710 // 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
711 // We now have the disk decryption key!
712 disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)&update_result.data[0], update_result.data.size());
713 //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str());
714 ::keystore::hidl_vec<uint8_t> signature;
715 OperationResult finish_result;
716 service->finish(begin_result.token, empty_params, signature, entropy, &finish_result);
717 ret = finish_result.resultCode;
718 if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) {
719 printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret);
720 return disk_decryption_secret_key;
721 } else {
722 //printf("keystore finish operation successful\n");
723 }
724 stop_keystore();
725 return disk_decryption_secret_key;
726}
727
728}}
729
730#define PASSWORD_TOKEN_SIZE 32
731
Ethan Yonkere131bec2017-12-15 23:48:02 -0600732/* C++ replacement for
733 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#992
734 * called here
735 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#813 */
736bool Get_Secdis(const std::string& spblob_path, const std::string& handle_str, std::string& secdis_data) {
737 std::string secdis_file = spblob_path + handle_str + ".secdis";
738 if (!android::base::ReadFileToString(secdis_file, &secdis_data)) {
739 printf("Failed to read '%s'\n", secdis_file.c_str());
740 return false;
741 }
742 //output_hex(secdis_data.data(), secdis_data.size());printf("\n");
743 return true;
744}
745
746// 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
747userid_t fakeUid(const userid_t uid) {
748 return 100000 + uid;
749}
750
751bool Is_Weaver(const std::string& spblob_path, const std::string& handle_str) {
752 std::string weaver_file = spblob_path + handle_str + ".weaver";
753 struct stat st;
754 if (stat(weaver_file.c_str(), &st) == 0)
755 return true;
756 return false;
757}
758
759bool Free_Return(bool retval, void* weaver_key, password_data_struct* pwd) {
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500760 if (weaver_key)
761 free(weaver_key);
Ethan Yonkere131bec2017-12-15 23:48:02 -0600762 if (pwd->salt)
763 free(pwd->salt);
764 if (pwd->password_handle)
765 free(pwd->password_handle);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500766 return retval;
767}
768
769/* Decrypt_User_Synth_Pass is the TWRP C++ equivalent to spBasedDoVerifyCredential
770 * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#1998 */
771bool Decrypt_User_Synth_Pass(const userid_t user_id, const std::string& Password) {
772 bool retval = false;
773 void* weaver_key = NULL;
774 password_data_struct pwd;
775 pwd.salt = NULL;
Ethan Yonkere131bec2017-12-15 23:48:02 -0600776 pwd.salt_len = 0;
777 pwd.password_handle = NULL;
778 pwd.handle_len = 0;
779 char application_id[PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH];
780
781 uint32_t auth_token_len = 0;
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500782
783 std::string secret; // this will be the disk decryption key that is sent to vold
784 std::string token = "!"; // there is no token used for this kind of decrypt, key escrow is handled by weaver
785 int flags = FLAG_STORAGE_DE;
786 if (user_id == 0)
787 flags = FLAG_STORAGE_DE;
788 else
789 flags = FLAG_STORAGE_CE;
790 char spblob_path_char[PATH_MAX];
791 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
792 std::string spblob_path = spblob_path_char;
793 long handle = 0;
794 std::string handle_str;
795 // 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
796 if (!Find_Handle(spblob_path, handle_str)) {
797 printf("Error getting handle\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600798 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500799 }
800 printf("Handle is '%s'\n", handle_str.c_str());
801 // 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
802 // First we read the password data which contains scrypt parameters
803 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
804 printf("Failed to Get_Password_Data\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600805 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500806 }
807 //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");
808 unsigned char password_token[PASSWORD_TOKEN_SIZE];
809 //printf("Password: '%s'\n", Password.c_str());
810 // The password token is the password scrypted with the parameters from the password data file
811 if (!Get_Password_Token(&pwd, Password, &password_token[0])) {
812 printf("Failed to Get_Password_Token\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600813 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500814 }
815 //output_hex(&password_token[0], PASSWORD_TOKEN_SIZE);printf("\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600816 if (Is_Weaver(spblob_path, handle_str)) {
817 printf("using weaver\n");
818 // BEGIN PIXEL 2 WEAVER
819 // Get the weaver data from the .weaver file which tells us which slot to use when we ask weaver for the escrowed key
820 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768
821 weaver_data_struct wd;
822 if (!Get_Weaver_Data(spblob_path, handle_str, &wd)) {
823 printf("Failed to get weaver data\n");
824 return Free_Return(retval, weaver_key, &pwd);
825 }
826 // The weaver key is the the password token prefixed with "weaver-key" padded to 128 with nulls with the password token appended then SHA512
827 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1059
828 weaver_key = PersonalizedHashBinary(PERSONALISATION_WEAVER_KEY, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
829 if (!weaver_key) {
830 printf("malloc error getting weaver_key\n");
831 return Free_Return(retval, weaver_key, &pwd);
832 }
833 // 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
834 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#776
835 android::vold::Weaver weaver;
836 if (!weaver) {
837 printf("Failed to get weaver service\n");
838 return Free_Return(retval, weaver_key, &pwd);
839 }
840 // Get the key size from weaver service
841 uint32_t weaver_key_size = 0;
842 if (!weaver.GetKeySize(&weaver_key_size)) {
843 printf("Failed to get weaver key size\n");
844 return Free_Return(retval, weaver_key, &pwd);
845 } else {
846 //printf("weaver key size is %u\n", weaver_key_size);
847 }
848 //printf("weaver key: "); output_hex((unsigned char*)weaver_key, weaver_key_size); printf("\n");
849 // Send the slot from the .weaver file, the computed weaver key, and get the escrowed key data
850 std::vector<uint8_t> weaver_payload;
851 // TODO: we should return more information about the status including time delays before the next retry
852 if (!weaver.WeaverVerify(wd.slot, weaver_key, &weaver_payload)) {
853 printf("failed to weaver verify\n");
854 return Free_Return(retval, weaver_key, &pwd);
855 }
856 //printf("weaver payload: "); output_hex(&weaver_payload); printf("\n");
857 // Done with weaverVerify
858 // Now we will compute the application ID
859 // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#964
860 // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#780
861 // The escrowed weaver key data is prefixed with "weaver-pwd" padded to 128 with nulls with the weaver payload appended then SHA512
862 void* weaver_secret = PersonalizedHashBinary(PERSONALISATION_WEAVER_PASSWORD, (const char*)weaver_payload.data(), weaver_payload.size());
863 //printf("weaver secret: "); output_hex((unsigned char*)weaver_secret, SHA512_DIGEST_LENGTH); printf("\n");
864 // The application ID is the password token and weaver secret appended to each other
865 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
866 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], weaver_secret, SHA512_DIGEST_LENGTH);
867 //printf("application ID: "); output_hex((unsigned char*)application_id, PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH); printf("\n");
868 // END PIXEL 2 WEAVER
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500869 } else {
Ethan Yonkere131bec2017-12-15 23:48:02 -0600870 printf("using secdis\n");
871 std::string secdis_data;
872 if (!Get_Secdis(spblob_path, handle_str, secdis_data)) {
873 printf("Failed to get secdis data\n");
874 return Free_Return(retval, weaver_key, &pwd);
875 }
876 void* secdiscardable = PersonalizedHashBinary(PERSONALISATION_SECDISCARDABLE, (char*)secdis_data.data(), secdis_data.size());
877 if (!secdiscardable) {
878 printf("malloc error getting secdiscardable\n");
879 return Free_Return(retval, weaver_key, &pwd);
880 }
881 memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE);
882 memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], secdiscardable, SHA512_DIGEST_LENGTH);
883
884 int ret = -1;
885 bool request_reenroll = false;
886 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
887 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
888 if (gk_device == nullptr) {
889 printf("failed to get gatekeeper service\n");
890 return Free_Return(retval, weaver_key, &pwd);
891 }
892 if (pwd.handle_len <= 0) {
893 printf("no password handle supplied\n");
894 return Free_Return(retval, weaver_key, &pwd);
895 }
896 android::hardware::hidl_vec<uint8_t> pwd_handle_hidl;
897 pwd_handle_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)pwd.password_handle), pwd.handle_len);
898 void* gk_pwd_token = PersonalizedHashBinary(PERSONALIZATION_USER_GK_AUTH, (char*)&password_token[0], PASSWORD_TOKEN_SIZE);
899 if (!gk_pwd_token) {
900 printf("malloc error getting gatekeeper_key\n");
901 return Free_Return(retval, weaver_key, &pwd);
902 }
903 android::hardware::hidl_vec<uint8_t> gk_pwd_token_hidl;
904 gk_pwd_token_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)gk_pwd_token), SHA512_DIGEST_LENGTH);
905 android::hardware::Return<void> hwRet =
906 gk_device->verify(fakeUid(user_id), 0 /* challange */,
907 pwd_handle_hidl,
908 gk_pwd_token_hidl,
909 [&ret, &request_reenroll, &auth_token_len]
910 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
911 ret = static_cast<int>(rsp.code); // propagate errors
912 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
913 auth_token_len = rsp.data.size();
914 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
915 ret = 0; // all success states are reported as 0
916 // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file here and later
917 // run a separate service that runs as the system user to add the auth token. We wait for the auth token file to be
918 // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after a while seconds if
919 // the /auth_token file never gets deleted.
920 unlink("/auth_token");
921 FILE* auth_file = fopen("/auth_token","wb");
922 if (auth_file != NULL) {
923 fwrite(rsp.data.data(), sizeof(uint8_t), rsp.data.size(), auth_file);
924 fclose(auth_file);
925 } else {
926 printf("failed to open /auth_token for writing\n");
927 ret = -2;
928 }
929 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
930 ret = rsp.timeout;
931 }
932 }
933 );
934 free(gk_pwd_token);
935 if (!hwRet.isOk() || ret != 0) {
936 printf("gatekeeper verification failed\n");
937 return Free_Return(retval, weaver_key, &pwd);
938 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500939 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500940 // 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
941 // Plus we will include the last bit that computes the disk decrypt key found in:
942 // 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 -0600943 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 -0500944 if (!secret.size()) {
945 printf("failed to unwrapSyntheticPasswordBlob\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600946 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500947 }
948 if (!e4crypt_unlock_user_key(user_id, 0, token.c_str(), secret.c_str())) {
949 printf("e4crypt_unlock_user_key returned fail\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600950 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500951 }
952 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
953 printf("failed to e4crypt_prepare_user_storage\n");
Ethan Yonkere131bec2017-12-15 23:48:02 -0600954 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500955 }
956 printf("Decrypted Successfully!\n");
957 retval = true;
Ethan Yonkere131bec2017-12-15 23:48:02 -0600958 return Free_Return(retval, weaver_key, &pwd);
Ethan Yonkerfefe5912017-09-30 22:22:13 -0500959}
960#endif //HAVE_SYNTH_PWD_SUPPORT
961
962int Get_Password_Type(const userid_t user_id, std::string& filename) {
963 struct stat st;
964 char spblob_path_char[PATH_MAX];
965 sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id);
966 if (stat(spblob_path_char, &st) == 0) {
967#ifdef HAVE_SYNTH_PWD_SUPPORT
968 printf("Using synthetic password method\n");
969 std::string spblob_path = spblob_path_char;
970 std::string handle_str;
971 if (!Find_Handle(spblob_path, handle_str)) {
972 printf("Error getting handle\n");
973 return 0;
974 }
975 printf("Handle is '%s'\n", handle_str.c_str());
976 password_data_struct pwd;
977 if (!Get_Password_Data(spblob_path, handle_str, &pwd)) {
978 printf("Failed to Get_Password_Data\n");
979 return 0;
980 }
981 if (pwd.password_type == 1) // In Android this means pattern
982 return 2; // In TWRP this means pattern
983 else if (pwd.password_type == 2) // In Android this means PIN or password
984 return 1; // In TWRP this means PIN or password
985 return 0; // We'll try the default password
986#else
987 printf("Synthetic password support not present in TWRP\n");
988 return -1;
989#endif
990 }
991 std::string path;
992 if (user_id == 0) {
993 path = "/data/system/";
994 } else {
995 char user_id_str[5];
996 sprintf(user_id_str, "%i", user_id);
997 path = "/data/system/users/";
998 path += user_id_str;
999 path += "/";
1000 }
1001 filename = path + "gatekeeper.password.key";
1002 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1003 return 1;
1004 filename = path + "gatekeeper.pattern.key";
1005 if (stat(filename.c_str(), &st) == 0 && st.st_size > 0)
1006 return 2;
1007 printf("Unable to locate gatekeeper password file '%s'\n", filename.c_str());
1008 filename = "";
1009 return 0;
1010}
1011
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001012bool Decrypt_User(const userid_t user_id, const std::string& Password) {
1013 uint8_t *auth_token;
1014 uint32_t auth_token_len;
1015 int ret;
1016
1017 struct stat st;
1018 if (user_id > 9999) {
1019 printf("user_id is too big\n");
1020 return false;
1021 }
1022 std::string filename;
1023 bool Default_Password = (Password == "!");
1024 if (Get_Password_Type(user_id, filename) == 0 && !Default_Password) {
1025 printf("Unknown password type\n");
1026 return false;
1027 }
1028 int flags = FLAG_STORAGE_DE;
1029 if (user_id == 0)
1030 flags = FLAG_STORAGE_DE;
1031 else
1032 flags = FLAG_STORAGE_CE;
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001033 if (Default_Password) {
1034 if (!e4crypt_unlock_user_key(user_id, 0, "!", "!")) {
1035 printf("e4crypt_unlock_user_key returned fail\n");
1036 return false;
1037 }
1038 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
1039 printf("failed to e4crypt_prepare_user_storage\n");
1040 return false;
1041 }
1042 printf("Decrypted Successfully!\n");
1043 return true;
1044 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001045 if (stat("/data/system_de/0/spblob", &st) == 0) {
1046#ifdef HAVE_SYNTH_PWD_SUPPORT
1047 printf("Using synthetic password method\n");
1048 return Decrypt_User_Synth_Pass(user_id, Password);
1049#else
1050 printf("Synthetic password support not present in TWRP\n");
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001051 return false;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001052#endif
1053 }
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001054 printf("password filename is '%s'\n", filename.c_str());
1055 if (stat(filename.c_str(), &st) != 0) {
1056 printf("error stat'ing key file: %s\n", strerror(errno));
1057 return false;
1058 }
1059 std::string handle;
1060 if (!android::base::ReadFileToString(filename, &handle)) {
1061 printf("Failed to read '%s'\n", filename.c_str());
1062 return false;
1063 }
1064 bool should_reenroll;
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001065#ifdef HAVE_GATEKEEPER1
1066 bool request_reenroll = false;
1067 android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device;
1068 gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService();
1069 if (gk_device == nullptr)
1070 return false;
1071 android::hardware::hidl_vec<uint8_t> curPwdHandle;
1072 curPwdHandle.setToExternal(const_cast<uint8_t *>((const uint8_t *)handle.c_str()), st.st_size);
1073 android::hardware::hidl_vec<uint8_t> enteredPwd;
1074 enteredPwd.setToExternal(const_cast<uint8_t *>((const uint8_t *)Password.c_str()), Password.size());
1075
1076 android::hardware::Return<void> hwRet =
1077 gk_device->verify(user_id, 0 /* challange */,
1078 curPwdHandle,
1079 enteredPwd,
1080 [&ret, &request_reenroll, &auth_token, &auth_token_len]
1081 (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) {
1082 ret = static_cast<int>(rsp.code); // propagate errors
1083 if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) {
1084 auth_token = new uint8_t[rsp.data.size()];
1085 auth_token_len = rsp.data.size();
1086 memcpy(auth_token, rsp.data.data(), auth_token_len);
1087 request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL);
1088 ret = 0; // all success states are reported as 0
1089 } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
1090 ret = rsp.timeout;
1091 }
1092 }
1093 );
1094 if (!hwRet.isOk()) {
1095 return false;
1096 }
1097#else
1098 gatekeeper_device_t *gk_device;
1099 ret = gatekeeper_device_initialize(&gk_device);
1100 if (ret!=0)
1101 return false;
1102 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 -06001103 (const uint8_t *)Password.c_str(), (uint32_t)Password.size(), &auth_token, &auth_token_len,
1104 &should_reenroll);
1105 if (ret !=0) {
1106 printf("failed to verify\n");
1107 return false;
1108 }
Ethan Yonkerfefe5912017-09-30 22:22:13 -05001109#endif
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001110 char token_hex[(auth_token_len*2)+1];
1111 token_hex[(auth_token_len*2)] = 0;
1112 uint32_t i;
1113 for (i=0;i<auth_token_len;i++) {
1114 sprintf(&token_hex[2*i], "%02X", auth_token[i]);
1115 }
1116 // 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
1117 std::string secret = HashPassword(Password);
1118 if (!e4crypt_unlock_user_key(user_id, 0, token_hex, secret.c_str())) {
1119 printf("e4crypt_unlock_user_key returned fail\n");
1120 return false;
1121 }
1122 if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
1123 printf("failed to e4crypt_prepare_user_storage\n");
1124 return false;
1125 }
1126 printf("Decrypted Successfully!\n");
1127 return true;
1128}