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