Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 1 | /* |
| 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 Yonker | 79f88bd | 2016-12-09 14:52:12 -0600 | [diff] [blame] | 20 | #include <map> |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 21 | #include <string> |
| 22 | |
| 23 | #include <errno.h> |
| 24 | #include <stdio.h> |
Ethan Yonker | 79f88bd | 2016-12-09 14:52:12 -0600 | [diff] [blame] | 25 | #include <stdlib.h> |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 26 | #include <sys/stat.h> |
| 27 | #include <sys/types.h> |
| 28 | |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 29 | #ifndef HAVE_LIBKEYUTILS |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 30 | #include "key_control.h" |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 31 | #else |
| 32 | #include <keyutils.h> |
| 33 | #endif |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 34 | |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 35 | #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> |
| 61 | extern "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 Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 71 | #include <hardware/gatekeeper.h> |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 72 | #endif |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 73 | #include "HashPassword.h" |
| 74 | |
| 75 | #include <android-base/file.h> |
| 76 | |
Ethan Yonker | 79f88bd | 2016-12-09 14:52:12 -0600 | [diff] [blame] | 77 | // Store main DE raw ref / policy |
| 78 | extern std::string de_raw_ref; |
| 79 | extern std::map<userid_t, std::string> s_de_key_raw_refs; |
| 80 | extern std::map<userid_t, std::string> s_ce_key_raw_refs; |
| 81 | |
| 82 | static 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 | |
| 92 | extern "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 | |
| 108 | extern "C" bool lookup_ref_tar(const char* policy_type, char* policy) { |
| 109 | if (strncmp(policy_type, "1", 1) != 0) { |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 110 | printf("Unexpected version %c\n", policy_type[0]); |
Ethan Yonker | 79f88bd | 2016-12-09 14:52:12 -0600 | [diff] [blame] | 111 | 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 Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 137 | #ifndef HAVE_GATEKEEPER1 |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 138 | int 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 Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 154 | #endif //ifndef HAVE_GATEKEEPER1 |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 155 | |
| 156 | bool 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 Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 168 | #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 | |
| 179 | void 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 | |
| 187 | void 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 | |
| 195 | void 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. */ |
| 210 | bool 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 |
| 240 | template <class T> |
| 241 | void 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 */ |
| 248 | struct 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 */ |
| 261 | bool 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 Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 290 | intptr++; |
| 291 | byteptr = (const unsigned char*)intptr; |
| 292 | byteptr += pwd->salt_len; |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 293 | } else { |
| 294 | printf("Get_Password_Data salt_len is 0\n"); |
| 295 | return false; |
| 296 | } |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 297 | 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 Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 311 | 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 */ |
| 318 | bool 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 |
| 339 | struct 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 */ |
| 348 | bool 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 | |
| 366 | namespace 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. |
| 370 | static 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. |
| 407 | static 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 */ |
| 416 | sp<IBinder> getKeystoreBinder() { |
| 417 | sp<IServiceManager> sm = defaultServiceManager(); |
| 418 | return sm->getService(String16("android.security.keystore")); |
| 419 | } |
| 420 | |
| 421 | sp<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 | |
| 434 | namespace keystore { |
| 435 | |
Ethan Yonker | c5dd579 | 2018-03-08 21:26:44 -0600 | [diff] [blame] | 436 | #define SYNTHETIC_PASSWORD_VERSION_V1 1 |
| 437 | #define SYNTHETIC_PASSWORD_VERSION 2 |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 438 | #define SYNTHETIC_PASSWORD_PASSWORD_BASED 0 |
| 439 | #define SYNTHETIC_PASSWORD_KEY_PREFIX "USRSKEY_synthetic_password_" |
| 440 | |
| 441 | /* The keystore alias subid is sometimes the same as the handle, but not always. |
| 442 | * In the case of handle 0c5303fd2010fe29, the alias subid used c5303fd2010fe29 |
| 443 | * without the leading 0. We could try to parse the data from a previous |
| 444 | * keystore request, but I think this is an easier solution because there |
| 445 | * is little to no documentation on the format of data we get back from |
| 446 | * the keystore in this instance. We also want to copy everything to a temp |
| 447 | * folder so that any key upgrades that might take place do not actually |
| 448 | * upgrade the keys on the data partition. We rename all 1000 uid files to 0 |
| 449 | * to pass the keystore permission checks. */ |
| 450 | bool Find_Keystore_Alias_SubID_And_Prep_Files(const userid_t user_id, std::string& keystoreid) { |
| 451 | char path_c[PATH_MAX]; |
| 452 | sprintf(path_c, "/data/misc/keystore/user_%d", user_id); |
| 453 | char user_dir[PATH_MAX]; |
| 454 | sprintf(user_dir, "user_%d", user_id); |
| 455 | std::string source_path = "/data/misc/keystore/"; |
| 456 | source_path += user_dir; |
| 457 | |
| 458 | mkdir("/tmp/misc", 0755); |
| 459 | mkdir("/tmp/misc/keystore", 0755); |
| 460 | std::string destination_path = "/tmp/misc/keystore/"; |
| 461 | destination_path += user_dir; |
| 462 | if (mkdir(destination_path.c_str(), 0755) && errno != EEXIST) { |
| 463 | printf("failed to mkdir '%s' %s\n", destination_path.c_str(), strerror(errno)); |
| 464 | return false; |
| 465 | } |
| 466 | destination_path += "/"; |
| 467 | |
| 468 | DIR* dir = opendir(source_path.c_str()); |
| 469 | if (!dir) { |
| 470 | printf("Error opening '%s'\n", source_path.c_str()); |
| 471 | return false; |
| 472 | } |
| 473 | source_path += "/"; |
| 474 | |
| 475 | struct dirent* de = 0; |
| 476 | size_t prefix_len = strlen(SYNTHETIC_PASSWORD_KEY_PREFIX); |
| 477 | bool found_subid = false; |
| 478 | |
| 479 | while ((de = readdir(dir)) != 0) { |
| 480 | if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) |
| 481 | continue; |
| 482 | if (!found_subid) { |
| 483 | size_t len = strlen(de->d_name); |
| 484 | if (len <= prefix_len) |
| 485 | continue; |
| 486 | if (!strstr(de->d_name, SYNTHETIC_PASSWORD_KEY_PREFIX)) |
| 487 | continue; |
| 488 | std::string file = de->d_name; |
| 489 | std::size_t found = file.find_last_of("_"); |
| 490 | if (found != std::string::npos) { |
| 491 | keystoreid = file.substr(found + 1); |
| 492 | printf("keystoreid: '%s'\n", keystoreid.c_str()); |
| 493 | found_subid = true; |
| 494 | } |
| 495 | } |
| 496 | std::string src = source_path; |
| 497 | src += de->d_name; |
| 498 | std::ifstream srcif(src.c_str(), std::ios::binary); |
| 499 | std::string dst = destination_path; |
| 500 | dst += de->d_name; |
| 501 | std::size_t source_uid = dst.find("1000"); |
| 502 | if (source_uid != std::string::npos) |
| 503 | dst.replace(source_uid, 4, "0"); |
| 504 | std::ofstream dstof(dst.c_str(), std::ios::binary); |
| 505 | printf("copying '%s' to '%s'\n", src.c_str(), dst.c_str()); |
| 506 | dstof << srcif.rdbuf(); |
| 507 | srcif.close(); |
| 508 | dstof.close(); |
| 509 | } |
| 510 | closedir(dir); |
| 511 | return found_subid; |
| 512 | } |
| 513 | |
| 514 | /* C++ replacement for function of the same name |
| 515 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#867 |
| 516 | * returning an empty string indicates an error */ |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 517 | std::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 Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 518 | std::string disk_decryption_secret_key = ""; |
| 519 | |
| 520 | std::string keystore_alias_subid; |
| 521 | if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid)) { |
| 522 | printf("failed to scan keystore alias subid and prep keystore files\n"); |
| 523 | return disk_decryption_secret_key; |
| 524 | } |
| 525 | |
| 526 | // First get the keystore service |
| 527 | sp<IBinder> binder = getKeystoreBinderRetry(); |
| 528 | sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); |
| 529 | if (service == NULL) { |
| 530 | printf("error: could not connect to keystore service\n"); |
| 531 | return disk_decryption_secret_key; |
| 532 | } |
| 533 | |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 534 | if (auth_token_len > 0) { |
| 535 | printf("Starting keystore_auth service...\n"); |
| 536 | property_set("ctl.start", "keystore_auth"); |
| 537 | } |
| 538 | |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 539 | // 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 |
| 540 | std::string spblob_file = spblob_path + handle_str + ".spblob"; |
| 541 | std::string spblob_data; |
| 542 | if (!android::base::ReadFileToString(spblob_file, &spblob_data)) { |
| 543 | printf("Failed to read '%s'\n", spblob_file.c_str()); |
| 544 | return disk_decryption_secret_key; |
| 545 | } |
Ethan Yonker | c5dd579 | 2018-03-08 21:26:44 -0600 | [diff] [blame] | 546 | unsigned char* byteptr = (unsigned char*)spblob_data.data(); |
| 547 | if (*byteptr != SYNTHETIC_PASSWORD_VERSION && *byteptr != SYNTHETIC_PASSWORD_VERSION_V1) { |
| 548 | printf("Unsupported synthetic password version %i\n", *byteptr); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 549 | return disk_decryption_secret_key; |
| 550 | } |
Ethan Yonker | c5dd579 | 2018-03-08 21:26:44 -0600 | [diff] [blame] | 551 | const unsigned char* synthetic_password_version = byteptr; |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 552 | byteptr++; |
| 553 | if (*byteptr != SYNTHETIC_PASSWORD_PASSWORD_BASED) { |
| 554 | printf("spblob data is not SYNTHETIC_PASSWORD_PASSWORD_BASED\n"); |
| 555 | return disk_decryption_secret_key; |
| 556 | } |
| 557 | byteptr++; // Now we're pointing to the blob data itself |
Ethan Yonker | c5dd579 | 2018-03-08 21:26:44 -0600 | [diff] [blame] | 558 | if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION_V1) { |
| 559 | printf("spblob v1\n"); |
| 560 | /* 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 |
| 561 | * Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#879 |
| 562 | * 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. |
| 563 | * The keystore data seems to be the serialized data from an entire class in Java. Specifically I think it represents: |
| 564 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java |
| 565 | * or perhaps |
| 566 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java |
| 567 | * 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} |
| 568 | * 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. |
| 569 | * There are 2 calls to a Java decrypt funcion that is overloaded. These 2 calls go in completely different directions despite the seemingly |
| 570 | * similar use of decrypt() and decrypt parameters. To figure out where things were going, I added logging to: |
| 571 | * https://android.googlesource.com/platform/libcore/+/android-8.0.0_r23/ojluni/src/main/java/javax/crypto/Cipher.java#2575 |
| 572 | * Logger.global.severe("Cipher tryCombinations " + prov.getName() + " - " + prov.getInfo()); |
| 573 | * 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 |
| 574 | * 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 |
| 575 | * 2 different providers in use. The first stage to get the intermediate key used: |
| 576 | * https://android.googlesource.com/platform/external/conscrypt/+/android-8.0.0_r23/common/src/main/java/org/conscrypt/OpenSSLProvider.java |
| 577 | * which is a pretty straight-forward OpenSSL implementation of AES/GCM/NoPadding. */ |
| 578 | // 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 |
| 579 | void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size); |
| 580 | if (!personalized_application_id) { |
| 581 | printf("malloc personalized_application_id\n"); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 582 | return disk_decryption_secret_key; |
| 583 | } |
Ethan Yonker | c5dd579 | 2018-03-08 21:26:44 -0600 | [diff] [blame] | 584 | //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n"); |
| 585 | // Now we'll decrypt using openssl AES/GCM/NoPadding |
| 586 | OpenSSL_add_all_ciphers(); |
| 587 | int actual_size=0, final_size=0; |
| 588 | EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new(); |
| 589 | const unsigned char* iv = (const unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob |
| 590 | //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n"); |
| 591 | const unsigned char* cipher_text = (const unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV |
| 592 | //printf("cipher_text: "); output_hex((const unsigned char*)cipher_text, spblob_data.size() - 2 - 12); printf("\n"); |
| 593 | const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID |
| 594 | //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n"); |
| 595 | EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, iv); |
| 596 | std::vector<unsigned char> intermediate_key; |
| 597 | intermediate_key.resize(spblob_data.size() - 2 - 12, '\0'); |
| 598 | EVP_DecryptUpdate(d_ctx, &intermediate_key[0], &actual_size, cipher_text, spblob_data.size() - 2 - 12); |
| 599 | unsigned char tag[AES_BLOCK_SIZE]; |
| 600 | EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag); |
| 601 | EVP_DecryptFinal_ex(d_ctx, &intermediate_key[actual_size], &final_size); |
| 602 | EVP_CIPHER_CTX_free(d_ctx); |
| 603 | free(personalized_application_id); |
| 604 | //printf("spblob_data size: %lu actual_size %i, final_size: %i\n", spblob_data.size(), actual_size, final_size); |
| 605 | 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 |
| 606 | //printf("intermediate key: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n"); |
| 607 | |
| 608 | // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation |
| 609 | if (auth_token_len > 0) { |
| 610 | /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len); |
| 611 | if (!auth_result.isOk()) { |
| 612 | // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0 |
| 613 | printf("keystore error adding auth token\n"); |
| 614 | return disk_decryption_secret_key; |
| 615 | }*/ |
| 616 | // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and |
| 617 | // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be |
| 618 | // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if |
| 619 | // the /auth_token file never gets deleted. |
| 620 | int auth_wait_count = 20; |
| 621 | while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0) |
| 622 | usleep(5000); |
| 623 | if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) { |
| 624 | printf("error during keymaster_auth service\n"); |
| 625 | /* 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 |
| 626 | * service keystore_auth /sbin/keystore_auth |
| 627 | * disabled |
| 628 | * oneshot |
| 629 | * user system |
| 630 | * group root |
| 631 | * seclabel u:r:recovery:s0 |
| 632 | * |
| 633 | * And check dmesg for error codes regarding this service if needed. */ |
| 634 | return disk_decryption_secret_key; |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | int32_t ret; |
| 639 | |
| 640 | /* 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 |
| 641 | * as the key data will be read again by the begin function later via the keystore. |
| 642 | * The data is in a hidl_vec format which consists of a type and a value. */ |
| 643 | /*::keystore::hidl_vec<uint8_t> data; |
| 644 | std::string keystoreid = SYNTHETIC_PASSWORD_KEY_PREFIX; |
| 645 | keystoreid += handle_str; |
| 646 | |
| 647 | ret = service->get(String16(keystoreid.c_str()), user_id, &data); |
| 648 | if (ret < 0) { |
| 649 | printf("Could not connect to keystore service %i\n", ret); |
| 650 | return disk_decryption_secret_key; |
| 651 | } else if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*//*) { |
| 652 | printf("keystore error: (%d)\n", /*responses[ret],*//* ret); |
| 653 | return disk_decryption_secret_key; |
| 654 | } else { |
| 655 | printf("keystore returned: "); output_hex(&data[0], data.size()); printf("\n"); |
| 656 | }*/ |
| 657 | |
| 658 | // Now we'll break up the intermediate key into the IV (first 12 bytes) and the cipher text (the rest of it). |
| 659 | std::vector<unsigned char> nonce = intermediate_key; |
| 660 | nonce.resize(12); |
| 661 | intermediate_key.erase (intermediate_key.begin(),intermediate_key.begin()+12); |
| 662 | //printf("nonce: "); output_hex((const unsigned char*)nonce.data(), nonce.size()); printf("\n"); |
| 663 | //printf("cipher text: "); output_hex((const unsigned char*)intermediate_key.data(), intermediate_key.size()); printf("\n"); |
| 664 | |
| 665 | /* Now we will begin the second decrypt call found in |
| 666 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#122 |
| 667 | * This time we will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java |
| 668 | * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java |
| 669 | * First we set some algorithm parameters as seen in two places: |
| 670 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297 |
| 671 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */ |
| 672 | size_t maclen = 128; |
| 673 | ::keystore::AuthorizationSetBuilder begin_params; |
| 674 | begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES); |
| 675 | begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM); |
| 676 | begin_params.Padding(::keystore::PaddingMode::NONE); |
| 677 | begin_params.Authorization(::keystore::TAG_NONCE, nonce); |
| 678 | begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen); |
| 679 | //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES); |
| 680 | //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockMode); |
| 681 | //keymasterArgs.addEnum(KeymasterDefs.KM_TAG_PADDING, mKeymasterPadding); |
| 682 | //keymasterArgs.addUnsignedInt(KeymasterDefs.KM_TAG_MAC_LENGTH, mTagLengthBits); |
| 683 | ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt |
| 684 | entropy.resize(0); |
| 685 | std::string keystore_alias = SYNTHETIC_PASSWORD_KEY_PREFIX; |
| 686 | keystore_alias += keystore_alias_subid; |
| 687 | String16 keystore_alias16(keystore_alias.c_str()); |
| 688 | ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT; |
| 689 | OperationResult begin_result; |
| 690 | // 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 |
| 691 | service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result); |
| 692 | ret = begin_result.resultCode; |
| 693 | if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) { |
| 694 | printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret); |
| 695 | return disk_decryption_secret_key; |
| 696 | } else { |
| 697 | //printf("keystore begin operation successful\n"); |
| 698 | } |
| 699 | ::keystore::hidl_vec<::keystore::KeyParameter> empty_params; |
| 700 | empty_params.resize(0); |
| 701 | OperationResult update_result; |
| 702 | // 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 |
| 703 | // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208 |
| 704 | service->update(begin_result.token, empty_params, intermediate_key, &update_result); |
| 705 | ret = update_result.resultCode; |
| 706 | if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) { |
| 707 | printf("keystore update error: (%d)\n", /*responses[ret],*/ ret); |
| 708 | return disk_decryption_secret_key; |
| 709 | } else { |
| 710 | //printf("keystore update operation successful\n"); |
| 711 | //printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password |
| 712 | } |
| 713 | // We must use the data in update_data.data before we call finish below or the data will be gone |
| 714 | // 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 |
| 715 | // We now have the disk decryption key! |
| 716 | disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)&update_result.data[0], update_result.data.size()); |
| 717 | //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str()); |
| 718 | ::keystore::hidl_vec<uint8_t> signature; |
| 719 | OperationResult finish_result; |
| 720 | service->finish(begin_result.token, empty_params, signature, entropy, &finish_result); |
| 721 | ret = finish_result.resultCode; |
| 722 | if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) { |
| 723 | printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret); |
| 724 | return disk_decryption_secret_key; |
| 725 | } else { |
| 726 | //printf("keystore finish operation successful\n"); |
| 727 | } |
| 728 | stop_keystore(); |
| 729 | return disk_decryption_secret_key; |
| 730 | } else if (*synthetic_password_version == SYNTHETIC_PASSWORD_VERSION) { |
| 731 | printf("spblob v2\n"); |
| 732 | /* Version 2 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 |
| 733 | * as seen in https://android.googlesource.com/platform/frameworks/base/+/5025791ac6d1538224e19189397de8d71dcb1a12 |
| 734 | */ |
| 735 | /* First decrypt call found in |
| 736 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#135 |
| 737 | * We will use https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreCipherSpiBase.java |
| 738 | * and https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java |
| 739 | * First we set some algorithm parameters as seen in two places: |
| 740 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#297 |
| 741 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java#216 */ |
| 742 | // When using secdis (aka not weaver) you must supply an auth token to the keystore prior to the begin operation |
| 743 | if (auth_token_len > 0) { |
| 744 | /*::keystore::KeyStoreServiceReturnCode auth_result = service->addAuthToken(auth_token, auth_token_len); |
| 745 | if (!auth_result.isOk()) { |
| 746 | // The keystore checks the uid of the calling process and will return a permission denied on this operation for user 0 |
| 747 | printf("keystore error adding auth token\n"); |
| 748 | return disk_decryption_secret_key; |
| 749 | }*/ |
| 750 | // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file earlier and |
| 751 | // run a separate service that runs user the system user to add the auth token. We wait for the auth token file to be |
| 752 | // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after after a while if |
| 753 | // the /auth_token file never gets deleted. |
| 754 | int auth_wait_count = 20; |
| 755 | while (access("/auth_token", F_OK) == 0 && auth_wait_count-- > 0) |
| 756 | usleep(5000); |
| 757 | if (auth_wait_count == 0 || access("/auth_error", F_OK) == 0) { |
| 758 | printf("error during keymaster_auth service\n"); |
| 759 | /* 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 |
| 760 | * service keystore_auth /sbin/keystore_auth |
| 761 | * disabled |
| 762 | * oneshot |
| 763 | * user system |
| 764 | * group root |
| 765 | * seclabel u:r:recovery:s0 |
| 766 | * |
| 767 | * And check dmesg for error codes regarding this service if needed. */ |
| 768 | return disk_decryption_secret_key; |
| 769 | } |
| 770 | } |
| 771 | int32_t ret; |
| 772 | size_t maclen = 128; |
| 773 | unsigned char* iv = (unsigned char*)byteptr; // The IV is the first 12 bytes of the spblob |
| 774 | ::keystore::hidl_vec<uint8_t> iv_hidlvec; |
| 775 | iv_hidlvec.setToExternal((unsigned char*)byteptr, 12); |
| 776 | //printf("iv: "); output_hex((const unsigned char*)iv, 12); printf("\n"); |
| 777 | unsigned char* cipher_text = (unsigned char*)byteptr + 12; // The cipher text comes immediately after the IV |
| 778 | ::keystore::hidl_vec<uint8_t> cipher_text_hidlvec; |
| 779 | cipher_text_hidlvec.setToExternal(cipher_text, spblob_data.size() - 14 /* 1 each for version and SYNTHETIC_PASSWORD_PASSWORD_BASED and 12 for the iv */); |
| 780 | ::keystore::AuthorizationSetBuilder begin_params; |
| 781 | begin_params.Authorization(::keystore::TAG_ALGORITHM, ::keystore::Algorithm::AES); |
| 782 | begin_params.Authorization(::keystore::TAG_BLOCK_MODE, ::keystore::BlockMode::GCM); |
| 783 | begin_params.Padding(::keystore::PaddingMode::NONE); |
| 784 | begin_params.Authorization(::keystore::TAG_NONCE, iv_hidlvec); |
| 785 | begin_params.Authorization(::keystore::TAG_MAC_LENGTH, maclen); |
| 786 | ::keystore::hidl_vec<uint8_t> entropy; // No entropy is needed for decrypt |
| 787 | entropy.resize(0); |
| 788 | std::string keystore_alias = SYNTHETIC_PASSWORD_KEY_PREFIX; |
| 789 | keystore_alias += keystore_alias_subid; |
| 790 | String16 keystore_alias16(keystore_alias.c_str()); |
| 791 | ::keystore::KeyPurpose purpose = ::keystore::KeyPurpose::DECRYPT; |
| 792 | OperationResult begin_result; |
| 793 | // 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 |
| 794 | service->begin(binder, keystore_alias16, purpose, true, begin_params.hidl_data(), entropy, -1, &begin_result); |
| 795 | ret = begin_result.resultCode; |
| 796 | if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) { |
| 797 | printf("keystore begin error: (%d)\n", /*responses[ret],*/ ret); |
| 798 | return disk_decryption_secret_key; |
| 799 | } /*else { |
| 800 | printf("keystore begin operation successful\n"); |
| 801 | }*/ |
| 802 | ::keystore::hidl_vec<::keystore::KeyParameter> empty_params; |
| 803 | empty_params.resize(0); |
| 804 | OperationResult update_result; |
| 805 | // 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 |
| 806 | // See also https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java#208 |
| 807 | service->update(begin_result.token, empty_params, cipher_text_hidlvec, &update_result); |
| 808 | ret = update_result.resultCode; |
| 809 | if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) { |
| 810 | printf("keystore update error: (%d)\n", /*responses[ret],*/ ret); |
| 811 | return disk_decryption_secret_key; |
| 812 | } /*else { |
| 813 | printf("keystore update operation successful\n"); |
| 814 | printf("keystore update returned: "); output_hex(&update_result.data[0], update_result.data.size()); printf("\n"); // this ends up being the synthetic password |
| 815 | }*/ |
| 816 | //printf("keystore resulting data: "); output_hex((unsigned char*)&update_result.data[0], update_result.data.size()); printf("\n"); |
| 817 | // We must copy the data in update_data.data before we call finish below or the data will be gone |
| 818 | size_t keystore_result_size = update_result.data.size(); |
| 819 | unsigned char* keystore_result = (unsigned char*)malloc(keystore_result_size); |
| 820 | if (!keystore_result) { |
| 821 | printf("malloc on keystore_result\n"); |
| 822 | return disk_decryption_secret_key; |
| 823 | } |
| 824 | memcpy(keystore_result, &update_result.data[0], update_result.data.size()); |
| 825 | //printf("keystore_result data: "); output_hex(keystore_result, keystore_result_size); printf("\n"); |
| 826 | ::keystore::hidl_vec<uint8_t> signature; |
| 827 | OperationResult finish_result; |
| 828 | service->finish(begin_result.token, empty_params, signature, entropy, &finish_result); |
| 829 | ret = finish_result.resultCode; |
| 830 | if (ret != 1 /*android::keystore::ResponseCode::NO_ERROR*/) { |
| 831 | printf("keystore finish error: (%d)\n", /*responses[ret],*/ ret); |
| 832 | free(keystore_result); |
| 833 | return disk_decryption_secret_key; |
| 834 | } /*else { |
| 835 | printf("keystore finish operation successful\n"); |
| 836 | }*/ |
| 837 | stop_keystore(); |
| 838 | |
| 839 | /* Now we do the second decrypt call as seen in: |
| 840 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.1.0_r18/services/core/java/com/android/server/locksettings/SyntheticPasswordCrypto.java#136 |
| 841 | */ |
| 842 | const unsigned char* intermediate_iv = keystore_result; |
| 843 | //printf("intermediate_iv: "); output_hex((const unsigned char*)intermediate_iv, 12); printf("\n"); |
| 844 | const unsigned char* intermediate_cipher_text = (const unsigned char*)keystore_result + 12; // The cipher text comes immediately after the IV |
| 845 | int cipher_size = keystore_result_size - 12; |
| 846 | //printf("intermediate_cipher_text: "); output_hex((const unsigned char*)intermediate_cipher_text, cipher_size); printf("\n"); |
| 847 | // 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 |
| 848 | void* personalized_application_id = PersonalizedHashBinary(PERSONALISATION_APPLICATION_ID, (const char*)application_id, application_id_size); |
| 849 | if (!personalized_application_id) { |
| 850 | printf("malloc personalized_application_id\n"); |
| 851 | free(keystore_result); |
| 852 | return disk_decryption_secret_key; |
| 853 | } |
| 854 | //printf("personalized application id: "); output_hex((unsigned char*)personalized_application_id, SHA512_DIGEST_LENGTH); printf("\n"); |
| 855 | // Now we'll decrypt using openssl AES/GCM/NoPadding |
| 856 | OpenSSL_add_all_ciphers(); |
| 857 | int actual_size=0, final_size=0; |
| 858 | EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new(); |
| 859 | const unsigned char* key = (const unsigned char*)personalized_application_id; // The key is the now personalized copy of the application ID |
| 860 | //printf("key: "); output_hex((const unsigned char*)key, 32); printf("\n"); |
| 861 | EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), key, intermediate_iv); |
| 862 | unsigned char* secret_key = (unsigned char*)malloc(cipher_size); |
| 863 | EVP_DecryptUpdate(d_ctx, secret_key, &actual_size, intermediate_cipher_text, cipher_size); |
| 864 | unsigned char tag[AES_BLOCK_SIZE]; |
| 865 | EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag); |
| 866 | EVP_DecryptFinal_ex(d_ctx, secret_key + actual_size, &final_size); |
| 867 | EVP_CIPHER_CTX_free(d_ctx); |
| 868 | free(personalized_application_id); |
| 869 | free(keystore_result); |
| 870 | int secret_key_real_size = actual_size - 16; |
| 871 | //printf("secret key: "); output_hex((const unsigned char*)secret_key, secret_key_real_size); printf("\n"); |
| 872 | // 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 |
| 873 | // We now have the disk decryption key! |
| 874 | disk_decryption_secret_key = PersonalizedHash(PERSONALIZATION_FBE_KEY, (const char*)secret_key, secret_key_real_size); |
| 875 | //printf("disk_decryption_secret_key: '%s'\n", disk_decryption_secret_key.c_str()); |
| 876 | free(secret_key); |
| 877 | return disk_decryption_secret_key; |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 878 | } |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 879 | return disk_decryption_secret_key; |
| 880 | } |
| 881 | |
| 882 | }} |
| 883 | |
| 884 | #define PASSWORD_TOKEN_SIZE 32 |
| 885 | |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 886 | /* C++ replacement for |
| 887 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#992 |
| 888 | * called here |
| 889 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#813 */ |
| 890 | bool Get_Secdis(const std::string& spblob_path, const std::string& handle_str, std::string& secdis_data) { |
| 891 | std::string secdis_file = spblob_path + handle_str + ".secdis"; |
| 892 | if (!android::base::ReadFileToString(secdis_file, &secdis_data)) { |
| 893 | printf("Failed to read '%s'\n", secdis_file.c_str()); |
| 894 | return false; |
| 895 | } |
| 896 | //output_hex(secdis_data.data(), secdis_data.size());printf("\n"); |
| 897 | return true; |
| 898 | } |
| 899 | |
| 900 | // 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 |
| 901 | userid_t fakeUid(const userid_t uid) { |
| 902 | return 100000 + uid; |
| 903 | } |
| 904 | |
| 905 | bool Is_Weaver(const std::string& spblob_path, const std::string& handle_str) { |
| 906 | std::string weaver_file = spblob_path + handle_str + ".weaver"; |
| 907 | struct stat st; |
| 908 | if (stat(weaver_file.c_str(), &st) == 0) |
| 909 | return true; |
| 910 | return false; |
| 911 | } |
| 912 | |
| 913 | bool Free_Return(bool retval, void* weaver_key, password_data_struct* pwd) { |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 914 | if (weaver_key) |
| 915 | free(weaver_key); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 916 | if (pwd->salt) |
| 917 | free(pwd->salt); |
| 918 | if (pwd->password_handle) |
| 919 | free(pwd->password_handle); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 920 | return retval; |
| 921 | } |
| 922 | |
| 923 | /* Decrypt_User_Synth_Pass is the TWRP C++ equivalent to spBasedDoVerifyCredential |
| 924 | * https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/LockSettingsService.java#1998 */ |
| 925 | bool Decrypt_User_Synth_Pass(const userid_t user_id, const std::string& Password) { |
| 926 | bool retval = false; |
| 927 | void* weaver_key = NULL; |
| 928 | password_data_struct pwd; |
| 929 | pwd.salt = NULL; |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 930 | pwd.salt_len = 0; |
| 931 | pwd.password_handle = NULL; |
| 932 | pwd.handle_len = 0; |
| 933 | char application_id[PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH]; |
| 934 | |
| 935 | uint32_t auth_token_len = 0; |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 936 | |
| 937 | std::string secret; // this will be the disk decryption key that is sent to vold |
| 938 | std::string token = "!"; // there is no token used for this kind of decrypt, key escrow is handled by weaver |
| 939 | int flags = FLAG_STORAGE_DE; |
| 940 | if (user_id == 0) |
| 941 | flags = FLAG_STORAGE_DE; |
| 942 | else |
| 943 | flags = FLAG_STORAGE_CE; |
| 944 | char spblob_path_char[PATH_MAX]; |
| 945 | sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id); |
| 946 | std::string spblob_path = spblob_path_char; |
| 947 | long handle = 0; |
| 948 | std::string handle_str; |
| 949 | // 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 |
| 950 | if (!Find_Handle(spblob_path, handle_str)) { |
| 951 | printf("Error getting handle\n"); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 952 | return Free_Return(retval, weaver_key, &pwd); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 953 | } |
| 954 | printf("Handle is '%s'\n", handle_str.c_str()); |
| 955 | // 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 |
| 956 | // First we read the password data which contains scrypt parameters |
| 957 | if (!Get_Password_Data(spblob_path, handle_str, &pwd)) { |
| 958 | printf("Failed to Get_Password_Data\n"); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 959 | return Free_Return(retval, weaver_key, &pwd); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 960 | } |
| 961 | //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"); |
| 962 | unsigned char password_token[PASSWORD_TOKEN_SIZE]; |
| 963 | //printf("Password: '%s'\n", Password.c_str()); |
| 964 | // The password token is the password scrypted with the parameters from the password data file |
| 965 | if (!Get_Password_Token(&pwd, Password, &password_token[0])) { |
| 966 | printf("Failed to Get_Password_Token\n"); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 967 | return Free_Return(retval, weaver_key, &pwd); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 968 | } |
| 969 | //output_hex(&password_token[0], PASSWORD_TOKEN_SIZE);printf("\n"); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 970 | if (Is_Weaver(spblob_path, handle_str)) { |
| 971 | printf("using weaver\n"); |
| 972 | // BEGIN PIXEL 2 WEAVER |
| 973 | // Get the weaver data from the .weaver file which tells us which slot to use when we ask weaver for the escrowed key |
| 974 | // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#768 |
| 975 | weaver_data_struct wd; |
| 976 | if (!Get_Weaver_Data(spblob_path, handle_str, &wd)) { |
| 977 | printf("Failed to get weaver data\n"); |
| 978 | return Free_Return(retval, weaver_key, &pwd); |
| 979 | } |
| 980 | // The weaver key is the the password token prefixed with "weaver-key" padded to 128 with nulls with the password token appended then SHA512 |
| 981 | // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#1059 |
| 982 | weaver_key = PersonalizedHashBinary(PERSONALISATION_WEAVER_KEY, (char*)&password_token[0], PASSWORD_TOKEN_SIZE); |
| 983 | if (!weaver_key) { |
| 984 | printf("malloc error getting weaver_key\n"); |
| 985 | return Free_Return(retval, weaver_key, &pwd); |
| 986 | } |
| 987 | // 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 |
| 988 | // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#776 |
| 989 | android::vold::Weaver weaver; |
| 990 | if (!weaver) { |
| 991 | printf("Failed to get weaver service\n"); |
| 992 | return Free_Return(retval, weaver_key, &pwd); |
| 993 | } |
| 994 | // Get the key size from weaver service |
| 995 | uint32_t weaver_key_size = 0; |
| 996 | if (!weaver.GetKeySize(&weaver_key_size)) { |
| 997 | printf("Failed to get weaver key size\n"); |
| 998 | return Free_Return(retval, weaver_key, &pwd); |
| 999 | } else { |
| 1000 | //printf("weaver key size is %u\n", weaver_key_size); |
| 1001 | } |
| 1002 | //printf("weaver key: "); output_hex((unsigned char*)weaver_key, weaver_key_size); printf("\n"); |
| 1003 | // Send the slot from the .weaver file, the computed weaver key, and get the escrowed key data |
| 1004 | std::vector<uint8_t> weaver_payload; |
| 1005 | // TODO: we should return more information about the status including time delays before the next retry |
| 1006 | if (!weaver.WeaverVerify(wd.slot, weaver_key, &weaver_payload)) { |
| 1007 | printf("failed to weaver verify\n"); |
| 1008 | return Free_Return(retval, weaver_key, &pwd); |
| 1009 | } |
| 1010 | //printf("weaver payload: "); output_hex(&weaver_payload); printf("\n"); |
| 1011 | // Done with weaverVerify |
| 1012 | // Now we will compute the application ID |
| 1013 | // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#964 |
| 1014 | // Called from https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#780 |
| 1015 | // The escrowed weaver key data is prefixed with "weaver-pwd" padded to 128 with nulls with the weaver payload appended then SHA512 |
| 1016 | void* weaver_secret = PersonalizedHashBinary(PERSONALISATION_WEAVER_PASSWORD, (const char*)weaver_payload.data(), weaver_payload.size()); |
| 1017 | //printf("weaver secret: "); output_hex((unsigned char*)weaver_secret, SHA512_DIGEST_LENGTH); printf("\n"); |
| 1018 | // The application ID is the password token and weaver secret appended to each other |
| 1019 | memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE); |
| 1020 | memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], weaver_secret, SHA512_DIGEST_LENGTH); |
| 1021 | //printf("application ID: "); output_hex((unsigned char*)application_id, PASSWORD_TOKEN_SIZE + SHA512_DIGEST_LENGTH); printf("\n"); |
| 1022 | // END PIXEL 2 WEAVER |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1023 | } else { |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 1024 | printf("using secdis\n"); |
| 1025 | std::string secdis_data; |
| 1026 | if (!Get_Secdis(spblob_path, handle_str, secdis_data)) { |
| 1027 | printf("Failed to get secdis data\n"); |
| 1028 | return Free_Return(retval, weaver_key, &pwd); |
| 1029 | } |
| 1030 | void* secdiscardable = PersonalizedHashBinary(PERSONALISATION_SECDISCARDABLE, (char*)secdis_data.data(), secdis_data.size()); |
| 1031 | if (!secdiscardable) { |
| 1032 | printf("malloc error getting secdiscardable\n"); |
| 1033 | return Free_Return(retval, weaver_key, &pwd); |
| 1034 | } |
| 1035 | memcpy((void*)&application_id[0], (void*)&password_token[0], PASSWORD_TOKEN_SIZE); |
| 1036 | memcpy((void*)&application_id[PASSWORD_TOKEN_SIZE], secdiscardable, SHA512_DIGEST_LENGTH); |
| 1037 | |
| 1038 | int ret = -1; |
| 1039 | bool request_reenroll = false; |
| 1040 | android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device; |
| 1041 | gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService(); |
| 1042 | if (gk_device == nullptr) { |
| 1043 | printf("failed to get gatekeeper service\n"); |
| 1044 | return Free_Return(retval, weaver_key, &pwd); |
| 1045 | } |
| 1046 | if (pwd.handle_len <= 0) { |
| 1047 | printf("no password handle supplied\n"); |
| 1048 | return Free_Return(retval, weaver_key, &pwd); |
| 1049 | } |
| 1050 | android::hardware::hidl_vec<uint8_t> pwd_handle_hidl; |
| 1051 | pwd_handle_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)pwd.password_handle), pwd.handle_len); |
| 1052 | void* gk_pwd_token = PersonalizedHashBinary(PERSONALIZATION_USER_GK_AUTH, (char*)&password_token[0], PASSWORD_TOKEN_SIZE); |
| 1053 | if (!gk_pwd_token) { |
| 1054 | printf("malloc error getting gatekeeper_key\n"); |
| 1055 | return Free_Return(retval, weaver_key, &pwd); |
| 1056 | } |
| 1057 | android::hardware::hidl_vec<uint8_t> gk_pwd_token_hidl; |
| 1058 | gk_pwd_token_hidl.setToExternal(const_cast<uint8_t *>((const uint8_t *)gk_pwd_token), SHA512_DIGEST_LENGTH); |
| 1059 | android::hardware::Return<void> hwRet = |
| 1060 | gk_device->verify(fakeUid(user_id), 0 /* challange */, |
| 1061 | pwd_handle_hidl, |
| 1062 | gk_pwd_token_hidl, |
| 1063 | [&ret, &request_reenroll, &auth_token_len] |
| 1064 | (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) { |
| 1065 | ret = static_cast<int>(rsp.code); // propagate errors |
| 1066 | if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) { |
| 1067 | auth_token_len = rsp.data.size(); |
| 1068 | request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL); |
| 1069 | ret = 0; // all success states are reported as 0 |
| 1070 | // The keystore refuses to allow the root user to supply auth tokens, so we write the auth token to a file here and later |
| 1071 | // run a separate service that runs as the system user to add the auth token. We wait for the auth token file to be |
| 1072 | // deleted by the keymaster_auth service and check for a /auth_error file in case of errors. We quit after a while seconds if |
| 1073 | // the /auth_token file never gets deleted. |
| 1074 | unlink("/auth_token"); |
| 1075 | FILE* auth_file = fopen("/auth_token","wb"); |
| 1076 | if (auth_file != NULL) { |
| 1077 | fwrite(rsp.data.data(), sizeof(uint8_t), rsp.data.size(), auth_file); |
| 1078 | fclose(auth_file); |
| 1079 | } else { |
| 1080 | printf("failed to open /auth_token for writing\n"); |
| 1081 | ret = -2; |
| 1082 | } |
| 1083 | } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) { |
| 1084 | ret = rsp.timeout; |
| 1085 | } |
| 1086 | } |
| 1087 | ); |
| 1088 | free(gk_pwd_token); |
| 1089 | if (!hwRet.isOk() || ret != 0) { |
| 1090 | printf("gatekeeper verification failed\n"); |
| 1091 | return Free_Return(retval, weaver_key, &pwd); |
| 1092 | } |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1093 | } |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1094 | // 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 |
| 1095 | // Plus we will include the last bit that computes the disk decrypt key found in: |
| 1096 | // https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r23/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java#153 |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 1097 | 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 Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1098 | if (!secret.size()) { |
| 1099 | printf("failed to unwrapSyntheticPasswordBlob\n"); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 1100 | return Free_Return(retval, weaver_key, &pwd); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1101 | } |
| 1102 | if (!e4crypt_unlock_user_key(user_id, 0, token.c_str(), secret.c_str())) { |
| 1103 | printf("e4crypt_unlock_user_key returned fail\n"); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 1104 | return Free_Return(retval, weaver_key, &pwd); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1105 | } |
| 1106 | if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) { |
| 1107 | printf("failed to e4crypt_prepare_user_storage\n"); |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 1108 | return Free_Return(retval, weaver_key, &pwd); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1109 | } |
| 1110 | printf("Decrypted Successfully!\n"); |
| 1111 | retval = true; |
Ethan Yonker | e131bec | 2017-12-15 23:48:02 -0600 | [diff] [blame] | 1112 | return Free_Return(retval, weaver_key, &pwd); |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1113 | } |
| 1114 | #endif //HAVE_SYNTH_PWD_SUPPORT |
| 1115 | |
| 1116 | int Get_Password_Type(const userid_t user_id, std::string& filename) { |
| 1117 | struct stat st; |
| 1118 | char spblob_path_char[PATH_MAX]; |
| 1119 | sprintf(spblob_path_char, "/data/system_de/%d/spblob/", user_id); |
| 1120 | if (stat(spblob_path_char, &st) == 0) { |
| 1121 | #ifdef HAVE_SYNTH_PWD_SUPPORT |
| 1122 | printf("Using synthetic password method\n"); |
| 1123 | std::string spblob_path = spblob_path_char; |
| 1124 | std::string handle_str; |
| 1125 | if (!Find_Handle(spblob_path, handle_str)) { |
| 1126 | printf("Error getting handle\n"); |
| 1127 | return 0; |
| 1128 | } |
| 1129 | printf("Handle is '%s'\n", handle_str.c_str()); |
| 1130 | password_data_struct pwd; |
| 1131 | if (!Get_Password_Data(spblob_path, handle_str, &pwd)) { |
| 1132 | printf("Failed to Get_Password_Data\n"); |
| 1133 | return 0; |
| 1134 | } |
| 1135 | if (pwd.password_type == 1) // In Android this means pattern |
| 1136 | return 2; // In TWRP this means pattern |
| 1137 | else if (pwd.password_type == 2) // In Android this means PIN or password |
| 1138 | return 1; // In TWRP this means PIN or password |
| 1139 | return 0; // We'll try the default password |
| 1140 | #else |
| 1141 | printf("Synthetic password support not present in TWRP\n"); |
| 1142 | return -1; |
| 1143 | #endif |
| 1144 | } |
| 1145 | std::string path; |
| 1146 | if (user_id == 0) { |
| 1147 | path = "/data/system/"; |
| 1148 | } else { |
| 1149 | char user_id_str[5]; |
| 1150 | sprintf(user_id_str, "%i", user_id); |
| 1151 | path = "/data/system/users/"; |
| 1152 | path += user_id_str; |
| 1153 | path += "/"; |
| 1154 | } |
| 1155 | filename = path + "gatekeeper.password.key"; |
| 1156 | if (stat(filename.c_str(), &st) == 0 && st.st_size > 0) |
| 1157 | return 1; |
| 1158 | filename = path + "gatekeeper.pattern.key"; |
| 1159 | if (stat(filename.c_str(), &st) == 0 && st.st_size > 0) |
| 1160 | return 2; |
| 1161 | printf("Unable to locate gatekeeper password file '%s'\n", filename.c_str()); |
| 1162 | filename = ""; |
| 1163 | return 0; |
| 1164 | } |
| 1165 | |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 1166 | bool Decrypt_User(const userid_t user_id, const std::string& Password) { |
| 1167 | uint8_t *auth_token; |
| 1168 | uint32_t auth_token_len; |
| 1169 | int ret; |
| 1170 | |
| 1171 | struct stat st; |
| 1172 | if (user_id > 9999) { |
| 1173 | printf("user_id is too big\n"); |
| 1174 | return false; |
| 1175 | } |
| 1176 | std::string filename; |
| 1177 | bool Default_Password = (Password == "!"); |
| 1178 | if (Get_Password_Type(user_id, filename) == 0 && !Default_Password) { |
| 1179 | printf("Unknown password type\n"); |
| 1180 | return false; |
| 1181 | } |
| 1182 | int flags = FLAG_STORAGE_DE; |
| 1183 | if (user_id == 0) |
| 1184 | flags = FLAG_STORAGE_DE; |
| 1185 | else |
| 1186 | flags = FLAG_STORAGE_CE; |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 1187 | if (Default_Password) { |
| 1188 | if (!e4crypt_unlock_user_key(user_id, 0, "!", "!")) { |
| 1189 | printf("e4crypt_unlock_user_key returned fail\n"); |
| 1190 | return false; |
| 1191 | } |
| 1192 | if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) { |
| 1193 | printf("failed to e4crypt_prepare_user_storage\n"); |
| 1194 | return false; |
| 1195 | } |
| 1196 | printf("Decrypted Successfully!\n"); |
| 1197 | return true; |
| 1198 | } |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1199 | if (stat("/data/system_de/0/spblob", &st) == 0) { |
| 1200 | #ifdef HAVE_SYNTH_PWD_SUPPORT |
| 1201 | printf("Using synthetic password method\n"); |
| 1202 | return Decrypt_User_Synth_Pass(user_id, Password); |
| 1203 | #else |
| 1204 | printf("Synthetic password support not present in TWRP\n"); |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 1205 | return false; |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1206 | #endif |
| 1207 | } |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 1208 | printf("password filename is '%s'\n", filename.c_str()); |
| 1209 | if (stat(filename.c_str(), &st) != 0) { |
| 1210 | printf("error stat'ing key file: %s\n", strerror(errno)); |
| 1211 | return false; |
| 1212 | } |
| 1213 | std::string handle; |
| 1214 | if (!android::base::ReadFileToString(filename, &handle)) { |
| 1215 | printf("Failed to read '%s'\n", filename.c_str()); |
| 1216 | return false; |
| 1217 | } |
| 1218 | bool should_reenroll; |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1219 | #ifdef HAVE_GATEKEEPER1 |
| 1220 | bool request_reenroll = false; |
| 1221 | android::sp<android::hardware::gatekeeper::V1_0::IGatekeeper> gk_device; |
| 1222 | gk_device = ::android::hardware::gatekeeper::V1_0::IGatekeeper::getService(); |
| 1223 | if (gk_device == nullptr) |
| 1224 | return false; |
| 1225 | android::hardware::hidl_vec<uint8_t> curPwdHandle; |
| 1226 | curPwdHandle.setToExternal(const_cast<uint8_t *>((const uint8_t *)handle.c_str()), st.st_size); |
| 1227 | android::hardware::hidl_vec<uint8_t> enteredPwd; |
| 1228 | enteredPwd.setToExternal(const_cast<uint8_t *>((const uint8_t *)Password.c_str()), Password.size()); |
| 1229 | |
| 1230 | android::hardware::Return<void> hwRet = |
| 1231 | gk_device->verify(user_id, 0 /* challange */, |
| 1232 | curPwdHandle, |
| 1233 | enteredPwd, |
| 1234 | [&ret, &request_reenroll, &auth_token, &auth_token_len] |
| 1235 | (const android::hardware::gatekeeper::V1_0::GatekeeperResponse &rsp) { |
| 1236 | ret = static_cast<int>(rsp.code); // propagate errors |
| 1237 | if (rsp.code >= android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_OK) { |
| 1238 | auth_token = new uint8_t[rsp.data.size()]; |
| 1239 | auth_token_len = rsp.data.size(); |
| 1240 | memcpy(auth_token, rsp.data.data(), auth_token_len); |
| 1241 | request_reenroll = (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::STATUS_REENROLL); |
| 1242 | ret = 0; // all success states are reported as 0 |
| 1243 | } else if (rsp.code == android::hardware::gatekeeper::V1_0::GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) { |
| 1244 | ret = rsp.timeout; |
| 1245 | } |
| 1246 | } |
| 1247 | ); |
| 1248 | if (!hwRet.isOk()) { |
| 1249 | return false; |
| 1250 | } |
| 1251 | #else |
| 1252 | gatekeeper_device_t *gk_device; |
| 1253 | ret = gatekeeper_device_initialize(&gk_device); |
| 1254 | if (ret!=0) |
| 1255 | return false; |
| 1256 | ret = gk_device->verify(gk_device, user_id, 0, (const uint8_t *)handle.c_str(), st.st_size, |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 1257 | (const uint8_t *)Password.c_str(), (uint32_t)Password.size(), &auth_token, &auth_token_len, |
| 1258 | &should_reenroll); |
| 1259 | if (ret !=0) { |
| 1260 | printf("failed to verify\n"); |
| 1261 | return false; |
| 1262 | } |
Ethan Yonker | fefe591 | 2017-09-30 22:22:13 -0500 | [diff] [blame] | 1263 | #endif |
Ethan Yonker | bd7492d | 2016-12-07 13:55:01 -0600 | [diff] [blame] | 1264 | char token_hex[(auth_token_len*2)+1]; |
| 1265 | token_hex[(auth_token_len*2)] = 0; |
| 1266 | uint32_t i; |
| 1267 | for (i=0;i<auth_token_len;i++) { |
| 1268 | sprintf(&token_hex[2*i], "%02X", auth_token[i]); |
| 1269 | } |
| 1270 | // 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 |
| 1271 | std::string secret = HashPassword(Password); |
| 1272 | if (!e4crypt_unlock_user_key(user_id, 0, token_hex, secret.c_str())) { |
| 1273 | printf("e4crypt_unlock_user_key returned fail\n"); |
| 1274 | return false; |
| 1275 | } |
| 1276 | if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) { |
| 1277 | printf("failed to e4crypt_prepare_user_storage\n"); |
| 1278 | return false; |
| 1279 | } |
| 1280 | printf("Decrypted Successfully!\n"); |
| 1281 | return true; |
| 1282 | } |