Ethan Yonker | e9afc3d | 2018-08-30 15:16:27 -0500 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2016 The Android Open Source 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 "KeyStorage4.h" |
| 18 | |
| 19 | #include "Keymaster4.h" |
| 20 | #include "ScryptParameters.h" |
| 21 | #include "Utils.h" |
| 22 | |
| 23 | #include <vector> |
| 24 | |
| 25 | #include <errno.h> |
| 26 | #include <stdio.h> |
| 27 | #include <sys/stat.h> |
| 28 | #include <sys/types.h> |
| 29 | #include <sys/wait.h> |
| 30 | #include <unistd.h> |
| 31 | |
| 32 | #include <openssl/err.h> |
| 33 | #include <openssl/evp.h> |
| 34 | #include <openssl/sha.h> |
| 35 | |
| 36 | #include <android-base/file.h> |
| 37 | //#include <android-base/logging.h> |
| 38 | #include <android-base/unique_fd.h> |
| 39 | |
| 40 | #include <cutils/properties.h> |
| 41 | |
| 42 | #include <hardware/hw_auth_token.h> |
| 43 | #include <keymasterV4_0/authorization_set.h> |
| 44 | #include <keymasterV4_0/keymaster_utils.h> |
| 45 | |
| 46 | #include <iostream> |
| 47 | #define ERROR 1 |
| 48 | #define LOG(x) std::cout |
| 49 | #define PLOG(x) std::cout |
| 50 | |
| 51 | extern "C" { |
| 52 | |
| 53 | #include "crypto_scrypt.h" |
| 54 | } |
| 55 | |
| 56 | namespace android { |
| 57 | namespace vold { |
| 58 | |
| 59 | const KeyAuthentication kEmptyAuthentication{"", ""}; |
| 60 | |
| 61 | static constexpr size_t AES_KEY_BYTES = 32; |
| 62 | static constexpr size_t GCM_NONCE_BYTES = 12; |
| 63 | static constexpr size_t GCM_MAC_BYTES = 16; |
| 64 | static constexpr size_t SALT_BYTES = 1 << 4; |
| 65 | static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14; |
| 66 | static constexpr size_t STRETCHED_BYTES = 1 << 6; |
| 67 | |
| 68 | static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds |
Peter Cai | 90edd2e | 2019-05-23 16:32:22 +0800 | [diff] [blame] | 69 | constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64; |
Ethan Yonker | e9afc3d | 2018-08-30 15:16:27 -0500 | [diff] [blame] | 70 | |
| 71 | static const char* kCurrentVersion = "1"; |
| 72 | static const char* kRmPath = "/system/bin/rm"; |
| 73 | static const char* kSecdiscardPath = "/system/bin/secdiscard"; |
| 74 | static const char* kStretch_none = "none"; |
| 75 | static const char* kStretch_nopassword = "nopassword"; |
| 76 | static const std::string kStretchPrefix_scrypt = "scrypt "; |
| 77 | static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512"; |
| 78 | static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512"; |
| 79 | static const char* kFn_encrypted_key = "encrypted_key"; |
| 80 | static const char* kFn_keymaster_key_blob = "keymaster_key_blob"; |
| 81 | static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded"; |
| 82 | static const char* kFn_salt = "salt"; |
| 83 | static const char* kFn_secdiscardable = "secdiscardable"; |
| 84 | static const char* kFn_stretching = "stretching"; |
| 85 | static const char* kFn_version = "version"; |
| 86 | |
| 87 | static bool checkSize(const std::string& kind, size_t actual, size_t expected) { |
| 88 | if (actual != expected) { |
| 89 | LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got " |
| 90 | << actual << std::endl; |
| 91 | return false; |
| 92 | } |
| 93 | return true; |
| 94 | } |
| 95 | |
| 96 | static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) { |
| 97 | SHA512_CTX c; |
| 98 | |
| 99 | SHA512_Init(&c); |
| 100 | // Personalise the hashing by introducing a fixed prefix. |
| 101 | // Hashing applications should use personalization except when there is a |
| 102 | // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf |
| 103 | std::string hashingPrefix = prefix; |
| 104 | hashingPrefix.resize(SHA512_CBLOCK); |
| 105 | SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size()); |
| 106 | SHA512_Update(&c, tohash.data(), tohash.size()); |
| 107 | res->assign(SHA512_DIGEST_LENGTH, '\0'); |
| 108 | SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c); |
| 109 | } |
| 110 | |
| 111 | static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth, |
| 112 | const std::string& appId, std::string* key) { |
| 113 | auto paramBuilder = km::AuthorizationSetBuilder() |
| 114 | .AesEncryptionKey(AES_KEY_BYTES * 8) |
| 115 | .GcmModeMinMacLen(GCM_MAC_BYTES * 8) |
| 116 | .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId)); |
| 117 | if (auth.token.empty()) { |
| 118 | LOG(DEBUG) << "Creating key that doesn't need auth token" << std::endl; |
| 119 | paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED); |
| 120 | } else { |
| 121 | LOG(DEBUG) << "Auth token required for key" << std::endl; |
| 122 | if (auth.token.size() != sizeof(hw_auth_token_t)) { |
| 123 | LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was " |
| 124 | << auth.token.size() << " bytes" << std::endl; |
| 125 | return false; |
| 126 | } |
| 127 | const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data()); |
| 128 | paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id); |
| 129 | paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD); |
| 130 | paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT); |
| 131 | } |
| 132 | return keymaster.generateKey(paramBuilder, key); |
| 133 | } |
| 134 | |
Peter Cai | 90edd2e | 2019-05-23 16:32:22 +0800 | [diff] [blame] | 135 | bool generateWrappedKey(userid_t user_id, KeyType key_type, |
| 136 | KeyBuffer* key) { |
| 137 | Keymaster keymaster; |
| 138 | if (!keymaster) return false; |
| 139 | *key = KeyBuffer(EXT4_AES_256_XTS_KEY_SIZE); |
| 140 | std::string key_temp; |
| 141 | auto paramBuilder = km::AuthorizationSetBuilder() |
| 142 | .AesEncryptionKey(AES_KEY_BYTES * 8) |
| 143 | .GcmModeMinMacLen(GCM_MAC_BYTES * 8) |
| 144 | .Authorization(km::TAG_USER_ID, user_id); |
| 145 | km::KeyParameter param1; |
| 146 | param1.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_FBE_ICE); |
| 147 | param1.f.boolValue = true; |
| 148 | paramBuilder.push_back(param1); |
| 149 | km::KeyParameter param2; |
| 150 | if ((key_type == KeyType::DE_USER) || (key_type == KeyType::DE_SYS)) { |
| 151 | param2.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_KEY_TYPE); |
| 152 | param2.f.integer = 0; |
| 153 | } else if (key_type == KeyType::CE_USER) { |
| 154 | param2.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_KEY_TYPE); |
| 155 | param2.f.integer = 1; |
| 156 | } |
| 157 | paramBuilder.push_back(param2); |
| 158 | if (!keymaster.generateKey(paramBuilder, &key_temp)) return false; |
| 159 | *key = KeyBuffer(key_temp.size()); |
| 160 | memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size()); |
| 161 | return true; |
| 162 | } |
| 163 | |
| 164 | bool getEphemeralWrappedKey(km::KeyFormat format, KeyBuffer& kmKey, KeyBuffer* key) { |
| 165 | std::string key_temp; |
| 166 | Keymaster keymaster; |
| 167 | if (!keymaster) return false; |
Peter Cai | 05cd3f8 | 2019-05-25 21:12:29 +0800 | [diff] [blame] | 168 | |
| 169 | //Export once, if upgrade needed, upgrade and export again |
| 170 | bool export_again = true; |
| 171 | while (export_again) { |
| 172 | export_again = false; |
| 173 | auto ret = keymaster.exportKey(format, kmKey, "!", "!", &key_temp); |
| 174 | if (ret == km::ErrorCode::OK) { |
| 175 | *key = KeyBuffer(key_temp.size()); |
| 176 | memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size()); |
| 177 | return true; |
| 178 | } |
| 179 | if (ret != km::ErrorCode::KEY_REQUIRES_UPGRADE) return false; |
bigbiff bigbiff | 0be03b3 | 2019-08-27 20:50:31 -0400 | [diff] [blame] | 180 | LOG(DEBUG) << "Upgrading key" << std::endl; |
Peter Cai | 05cd3f8 | 2019-05-25 21:12:29 +0800 | [diff] [blame] | 181 | std::string kmKeyStr(reinterpret_cast<const char*>(kmKey.data()), kmKey.size()); |
| 182 | std::string newKey; |
| 183 | if (!keymaster.upgradeKey(kmKeyStr, km::AuthorizationSet(), &newKey)) return false; |
| 184 | memcpy(reinterpret_cast<void*>(kmKey.data()), newKey.c_str(), kmKey.size()); |
bigbiff bigbiff | 0be03b3 | 2019-08-27 20:50:31 -0400 | [diff] [blame] | 185 | LOG(INFO) << "Key upgraded" << std::endl; |
Peter Cai | 05cd3f8 | 2019-05-25 21:12:29 +0800 | [diff] [blame] | 186 | export_again = true; |
| 187 | } |
| 188 | //Should never come here |
| 189 | return false; |
Peter Cai | 90edd2e | 2019-05-23 16:32:22 +0800 | [diff] [blame] | 190 | } |
| 191 | |
Ethan Yonker | e9afc3d | 2018-08-30 15:16:27 -0500 | [diff] [blame] | 192 | static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams( |
| 193 | const KeyAuthentication& auth, const std::string& appId) { |
| 194 | auto paramBuilder = km::AuthorizationSetBuilder() |
| 195 | .GcmModeMacLen(GCM_MAC_BYTES * 8) |
| 196 | .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId)); |
| 197 | km::HardwareAuthToken authToken; |
| 198 | if (!auth.token.empty()) { |
| 199 | LOG(DEBUG) << "Supplying auth token to Keymaster" << std::endl; |
| 200 | authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token)); |
| 201 | } |
| 202 | return {paramBuilder, authToken}; |
| 203 | } |
| 204 | |
| 205 | static bool readFileToString(const std::string& filename, std::string* result) { |
| 206 | if (!android::base::ReadFileToString(filename, result)) { |
| 207 | PLOG(ERROR) << "Failed to read from " << filename << std::endl; |
| 208 | return false; |
| 209 | } |
| 210 | return true; |
| 211 | } |
| 212 | |
| 213 | static bool writeStringToFile(const std::string& payload, const std::string& filename) { |
| 214 | PLOG(ERROR) << __FUNCTION__ << " called for " << filename << " and being skipped\n"; |
| 215 | return true; |
| 216 | android::base::unique_fd fd(TEMP_FAILURE_RETRY( |
| 217 | open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666))); |
| 218 | if (fd == -1) { |
| 219 | PLOG(ERROR) << "Failed to open " << filename; |
| 220 | return false; |
| 221 | } |
| 222 | if (!android::base::WriteStringToFd(payload, fd)) { |
| 223 | PLOG(ERROR) << "Failed to write to " << filename; |
| 224 | unlink(filename.c_str()); |
| 225 | return false; |
| 226 | } |
| 227 | // fsync as close won't guarantee flush data |
| 228 | // see close(2), fsync(2) and b/68901441 |
| 229 | if (fsync(fd) == -1) { |
| 230 | if (errno == EROFS || errno == EINVAL) { |
| 231 | PLOG(WARNING) << "Skip fsync " << filename |
| 232 | << " on a file system does not support synchronization"; |
| 233 | } else { |
| 234 | PLOG(ERROR) << "Failed to fsync " << filename; |
| 235 | unlink(filename.c_str()); |
| 236 | return false; |
| 237 | } |
| 238 | } |
| 239 | return true; |
| 240 | } |
| 241 | |
| 242 | static bool readRandomBytesOrLog(size_t count, std::string* out) { |
| 243 | auto status = ReadRandomBytes(count, *out); |
| 244 | if (status != OK) { |
| 245 | LOG(ERROR) << "Random read failed with status: " << status << std::endl; |
| 246 | return false; |
| 247 | } |
| 248 | return true; |
| 249 | } |
| 250 | |
| 251 | bool createSecdiscardable(const std::string& filename, std::string* hash) { |
| 252 | std::string secdiscardable; |
| 253 | if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false; |
| 254 | if (!writeStringToFile(secdiscardable, filename)) return false; |
| 255 | hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash); |
| 256 | return true; |
| 257 | } |
| 258 | |
| 259 | bool readSecdiscardable(const std::string& filename, std::string* hash) { |
| 260 | std::string secdiscardable; |
| 261 | if (!readFileToString(filename, &secdiscardable)) return false; |
| 262 | hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash); |
| 263 | return true; |
| 264 | } |
| 265 | |
| 266 | static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir, |
| 267 | km::KeyPurpose purpose, const km::AuthorizationSet& keyParams, |
| 268 | const km::AuthorizationSet& opParams, |
| 269 | const km::HardwareAuthToken& authToken, |
| 270 | km::AuthorizationSet* outParams) { |
| 271 | auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob; |
| 272 | std::string kmKey; |
| 273 | if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation(); |
| 274 | km::AuthorizationSet inParams(keyParams); |
| 275 | inParams.append(opParams.begin(), opParams.end()); |
| 276 | for (;;) { |
| 277 | auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams); |
| 278 | if (opHandle) { |
| 279 | return opHandle; |
| 280 | } |
| 281 | if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle; |
| 282 | LOG(DEBUG) << "Upgrading key in memory only: " << dir << std::endl; |
| 283 | std::string newKey; |
| 284 | if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation(); |
| 285 | /*auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded; |
| 286 | if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation(); |
| 287 | if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) { |
| 288 | PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath; |
| 289 | return KeymasterOperation(); |
| 290 | } |
| 291 | if (!keymaster.deleteKey(kmKey)) { |
| 292 | LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir; |
| 293 | }*/ |
| 294 | kmKey = newKey; |
| 295 | LOG(INFO) << "Key upgraded in memory but not updated in folder: " << dir << std::endl; |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir, |
| 300 | const km::AuthorizationSet& keyParams, |
| 301 | const km::HardwareAuthToken& authToken, |
| 302 | const KeyBuffer& message, std::string* ciphertext) { |
| 303 | km::AuthorizationSet opParams; |
| 304 | km::AuthorizationSet outParams; |
| 305 | auto opHandle = |
| 306 | begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken, &outParams); |
| 307 | if (!opHandle) return false; |
| 308 | auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE); |
| 309 | if (!nonceBlob.isOk()) { |
| 310 | LOG(ERROR) << "GCM encryption but no nonce generated" << std::endl; |
| 311 | return false; |
| 312 | } |
| 313 | // nonceBlob here is just a pointer into existing data, must not be freed |
| 314 | std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]), |
| 315 | nonceBlob.value().size()); |
| 316 | if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false; |
| 317 | std::string body; |
| 318 | if (!opHandle.updateCompletely(message, &body)) return false; |
| 319 | |
| 320 | std::string mac; |
| 321 | if (!opHandle.finish(&mac)) return false; |
| 322 | if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false; |
| 323 | *ciphertext = nonce + body + mac; |
| 324 | return true; |
| 325 | } |
| 326 | |
| 327 | static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir, |
| 328 | const km::AuthorizationSet& keyParams, |
| 329 | const km::HardwareAuthToken& authToken, |
| 330 | const std::string& ciphertext, KeyBuffer* message) { |
| 331 | auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES); |
| 332 | auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES); |
| 333 | auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE, |
| 334 | km::support::blob2hidlVec(nonce)); |
| 335 | auto opHandle = |
| 336 | begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken, nullptr); |
| 337 | if (!opHandle) return false; |
| 338 | if (!opHandle.updateCompletely(bodyAndMac, message)) return false; |
| 339 | if (!opHandle.finish(nullptr)) return false; |
| 340 | return true; |
| 341 | } |
| 342 | |
| 343 | static std::string getStretching(const KeyAuthentication& auth) { |
| 344 | if (!auth.usesKeymaster()) { |
| 345 | return kStretch_none; |
| 346 | } else if (auth.secret.empty()) { |
| 347 | return kStretch_nopassword; |
| 348 | } else { |
| 349 | char paramstr[PROPERTY_VALUE_MAX]; |
| 350 | |
| 351 | property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS); |
| 352 | return std::string() + kStretchPrefix_scrypt + paramstr; |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | static bool stretchingNeedsSalt(const std::string& stretching) { |
| 357 | return stretching != kStretch_nopassword && stretching != kStretch_none; |
| 358 | } |
| 359 | |
| 360 | static bool stretchSecret(const std::string& stretching, const std::string& secret, |
| 361 | const std::string& salt, std::string* stretched) { |
| 362 | if (stretching == kStretch_nopassword) { |
| 363 | if (!secret.empty()) { |
| 364 | LOG(WARNING) << "Password present but stretching is nopassword" << std::endl; |
| 365 | // Continue anyway |
| 366 | } |
| 367 | stretched->clear(); |
| 368 | } else if (stretching == kStretch_none) { |
| 369 | *stretched = secret; |
| 370 | } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(), |
| 371 | stretching.begin())) { |
| 372 | int Nf, rf, pf; |
| 373 | if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf, |
| 374 | &rf, &pf)) { |
| 375 | LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching << std::endl; |
| 376 | return false; |
| 377 | } |
| 378 | stretched->assign(STRETCHED_BYTES, '\0'); |
| 379 | if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(), |
| 380 | reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf, |
| 381 | 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]), |
| 382 | stretched->size()) != 0) { |
| 383 | LOG(ERROR) << "scrypt failed with params: " << stretching << std::endl; |
| 384 | return false; |
| 385 | } |
| 386 | } else { |
| 387 | LOG(ERROR) << "Unknown stretching type: " << stretching << std::endl; |
| 388 | return false; |
| 389 | } |
| 390 | return true; |
| 391 | } |
| 392 | |
| 393 | static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching, |
| 394 | const std::string& salt, const std::string& secdiscardable_hash, |
| 395 | std::string* appId) { |
| 396 | std::string stretched; |
| 397 | if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false; |
| 398 | *appId = secdiscardable_hash + stretched; |
| 399 | return true; |
| 400 | } |
| 401 | |
| 402 | static void logOpensslError() { |
| 403 | LOG(ERROR) << "Openssl error: " << ERR_get_error() << std::endl; |
| 404 | } |
| 405 | |
| 406 | static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext, |
| 407 | std::string* ciphertext) { |
| 408 | std::string key; |
| 409 | hashWithPrefix(kHashPrefix_keygen, preKey, &key); |
| 410 | key.resize(AES_KEY_BYTES); |
| 411 | if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false; |
| 412 | auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>( |
| 413 | EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free); |
| 414 | if (!ctx) { |
| 415 | logOpensslError(); |
| 416 | return false; |
| 417 | } |
| 418 | if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, |
| 419 | reinterpret_cast<const uint8_t*>(key.data()), |
| 420 | reinterpret_cast<const uint8_t*>(ciphertext->data()))) { |
| 421 | logOpensslError(); |
| 422 | return false; |
| 423 | } |
| 424 | ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES); |
| 425 | int outlen; |
| 426 | if (1 != EVP_EncryptUpdate( |
| 427 | ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES), |
| 428 | &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) { |
| 429 | logOpensslError(); |
| 430 | return false; |
| 431 | } |
| 432 | if (outlen != static_cast<int>(plaintext.size())) { |
| 433 | LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen << std::endl; |
| 434 | return false; |
| 435 | } |
| 436 | if (1 != EVP_EncryptFinal_ex( |
| 437 | ctx.get(), |
| 438 | reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()), |
| 439 | &outlen)) { |
| 440 | logOpensslError(); |
| 441 | return false; |
| 442 | } |
| 443 | if (outlen != 0) { |
| 444 | LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen << std::endl; |
| 445 | return false; |
| 446 | } |
| 447 | if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES, |
| 448 | reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + |
| 449 | plaintext.size()))) { |
| 450 | logOpensslError(); |
| 451 | return false; |
| 452 | } |
| 453 | return true; |
| 454 | } |
| 455 | |
| 456 | static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext, |
| 457 | KeyBuffer* plaintext) { |
| 458 | if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) { |
| 459 | LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size() << std::endl; |
| 460 | return false; |
| 461 | } |
| 462 | std::string key; |
| 463 | hashWithPrefix(kHashPrefix_keygen, preKey, &key); |
| 464 | key.resize(AES_KEY_BYTES); |
| 465 | auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>( |
| 466 | EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free); |
| 467 | if (!ctx) { |
| 468 | logOpensslError(); |
| 469 | return false; |
| 470 | } |
| 471 | if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, |
| 472 | reinterpret_cast<const uint8_t*>(key.data()), |
| 473 | reinterpret_cast<const uint8_t*>(ciphertext.data()))) { |
| 474 | logOpensslError(); |
| 475 | return false; |
| 476 | } |
| 477 | *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES); |
| 478 | int outlen; |
| 479 | if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen, |
| 480 | reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES), |
| 481 | plaintext->size())) { |
| 482 | logOpensslError(); |
| 483 | return false; |
| 484 | } |
| 485 | if (outlen != static_cast<int>(plaintext->size())) { |
| 486 | LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen << std::endl; |
| 487 | return false; |
| 488 | } |
| 489 | if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES, |
| 490 | const_cast<void*>(reinterpret_cast<const void*>( |
| 491 | ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) { |
| 492 | logOpensslError(); |
| 493 | return false; |
| 494 | } |
| 495 | if (1 != EVP_DecryptFinal_ex(ctx.get(), |
| 496 | reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()), |
| 497 | &outlen)) { |
| 498 | logOpensslError(); |
| 499 | return false; |
| 500 | } |
| 501 | if (outlen != 0) { |
| 502 | LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen << std::endl; |
| 503 | return false; |
| 504 | } |
| 505 | return true; |
| 506 | } |
| 507 | |
| 508 | bool pathExists(const std::string& path) { |
| 509 | return access(path.c_str(), F_OK) == 0; |
| 510 | } |
| 511 | |
| 512 | bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) { |
| 513 | if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) { |
| 514 | PLOG(ERROR) << "key mkdir " << dir << std::endl; |
| 515 | return false; |
| 516 | } |
| 517 | if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false; |
| 518 | std::string secdiscardable_hash; |
| 519 | if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false; |
| 520 | std::string stretching = getStretching(auth); |
| 521 | if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false; |
| 522 | std::string salt; |
| 523 | if (stretchingNeedsSalt(stretching)) { |
| 524 | if (ReadRandomBytes(SALT_BYTES, salt) != OK) { |
| 525 | LOG(ERROR) << "Random read failed" << std::endl; |
| 526 | return false; |
| 527 | } |
| 528 | if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false; |
| 529 | } |
| 530 | std::string appId; |
| 531 | if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false; |
| 532 | std::string encryptedKey; |
| 533 | if (auth.usesKeymaster()) { |
| 534 | Keymaster keymaster; |
| 535 | if (!keymaster) return false; |
| 536 | std::string kmKey; |
| 537 | if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false; |
| 538 | if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false; |
| 539 | km::AuthorizationSet keyParams; |
| 540 | km::HardwareAuthToken authToken; |
| 541 | std::tie(keyParams, authToken) = beginParams(auth, appId); |
| 542 | if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey)) |
| 543 | return false; |
| 544 | } else { |
| 545 | if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false; |
| 546 | } |
| 547 | if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false; |
| 548 | return true; |
| 549 | } |
| 550 | |
| 551 | bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path, |
| 552 | const KeyAuthentication& auth, const KeyBuffer& key) { |
| 553 | if (pathExists(key_path)) { |
| 554 | LOG(ERROR) << "Already exists, cannot create key at: " << key_path << std::endl; |
| 555 | return false; |
| 556 | } |
| 557 | if (pathExists(tmp_path)) { |
| 558 | LOG(DEBUG) << "Already exists, destroying: " << tmp_path << std::endl; |
| 559 | destroyKey(tmp_path); // May be partially created so ignore errors |
| 560 | } |
| 561 | if (!storeKey(tmp_path, auth, key)) return false; |
| 562 | if (rename(tmp_path.c_str(), key_path.c_str()) != 0) { |
| 563 | PLOG(ERROR) << "Unable to move new key to location: " << key_path << std::endl; |
| 564 | return false; |
| 565 | } |
| 566 | LOG(DEBUG) << "Created key: " << key_path << std::endl; |
| 567 | return true; |
| 568 | } |
| 569 | |
| 570 | bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) { |
| 571 | std::string version; |
| 572 | if (!readFileToString(dir + "/" + kFn_version, &version)) return false; |
| 573 | if (version != kCurrentVersion) { |
| 574 | LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version << std::endl; |
| 575 | return false; |
| 576 | } |
| 577 | std::string secdiscardable_hash; |
| 578 | if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false; |
| 579 | std::string stretching; |
| 580 | if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false; |
| 581 | std::string salt; |
| 582 | if (stretchingNeedsSalt(stretching)) { |
| 583 | if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false; |
| 584 | } |
| 585 | std::string appId; |
| 586 | if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false; |
| 587 | std::string encryptedMessage; |
| 588 | if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false; |
| 589 | if (auth.usesKeymaster()) { |
| 590 | Keymaster keymaster; |
| 591 | if (!keymaster) return false; |
| 592 | km::AuthorizationSet keyParams; |
| 593 | km::HardwareAuthToken authToken; |
| 594 | std::tie(keyParams, authToken) = beginParams(auth, appId); |
| 595 | if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key)) |
| 596 | return false; |
| 597 | } else { |
| 598 | if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false; |
| 599 | } |
| 600 | return true; |
| 601 | } |
| 602 | |
| 603 | static bool deleteKey(const std::string& dir) { |
| 604 | LOG(DEBUG) << "not deleting key in " << __FILE__ << std::endl; |
| 605 | return true; |
| 606 | std::string kmKey; |
| 607 | if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false; |
| 608 | Keymaster keymaster; |
| 609 | if (!keymaster) return false; |
| 610 | if (!keymaster.deleteKey(kmKey)) return false; |
| 611 | return true; |
| 612 | } |
| 613 | |
| 614 | bool runSecdiscardSingle(const std::string& file) { |
| 615 | if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) { |
| 616 | LOG(ERROR) << "secdiscard failed" << std::endl; |
| 617 | return false; |
| 618 | } |
| 619 | return true; |
| 620 | } |
| 621 | |
| 622 | static bool recursiveDeleteKey(const std::string& dir) { |
| 623 | LOG(DEBUG) << "not recursively deleting key in " << __FILE__ << std::endl; |
| 624 | return true; |
| 625 | if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) { |
| 626 | LOG(ERROR) << "recursive delete failed" << std::endl; |
| 627 | return false; |
| 628 | } |
| 629 | return true; |
| 630 | } |
| 631 | |
| 632 | bool destroyKey(const std::string& dir) { |
| 633 | LOG(DEBUG) << "not destroying key in " << __FILE__ << std::endl; |
| 634 | return true; |
| 635 | bool success = true; |
| 636 | // Try each thing, even if previous things failed. |
| 637 | bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob); |
| 638 | if (uses_km) { |
| 639 | success &= deleteKey(dir); |
| 640 | } |
| 641 | auto secdiscard_cmd = std::vector<std::string>{ |
| 642 | kSecdiscardPath, "--", dir + "/" + kFn_encrypted_key, dir + "/" + kFn_secdiscardable, |
| 643 | }; |
| 644 | if (uses_km) { |
| 645 | secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob); |
| 646 | } |
| 647 | if (ForkExecvp(secdiscard_cmd) != 0) { |
| 648 | LOG(ERROR) << "secdiscard failed" << std::endl; |
| 649 | success = false; |
| 650 | } |
| 651 | success &= recursiveDeleteKey(dir); |
| 652 | return success; |
| 653 | } |
| 654 | |
| 655 | } // namespace vold |
| 656 | } // namespace android |