Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [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 "KeyStorage.h" |
| 18 | |
Daniel Rosenberg | d2906b8 | 2019-06-07 14:18:14 -0700 | [diff] [blame] | 19 | #include "Checkpoint.h" |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 20 | #include "Keymaster.h" |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 21 | #include "ScryptParameters.h" |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 22 | #include "Utils.h" |
| 23 | |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 24 | #include <algorithm> |
Seth Moore | 5a43d61 | 2021-01-19 17:51:51 +0000 | [diff] [blame] | 25 | #include <memory> |
| 26 | #include <mutex> |
Daniel Rosenberg | a48730a | 2019-06-06 20:38:38 -0700 | [diff] [blame] | 27 | #include <thread> |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 28 | #include <vector> |
| 29 | |
| 30 | #include <errno.h> |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 31 | #include <stdio.h> |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 32 | #include <sys/stat.h> |
| 33 | #include <sys/types.h> |
| 34 | #include <sys/wait.h> |
| 35 | #include <unistd.h> |
| 36 | |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 37 | #include <openssl/err.h> |
| 38 | #include <openssl/evp.h> |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 39 | #include <openssl/sha.h> |
| 40 | |
| 41 | #include <android-base/file.h> |
| 42 | #include <android-base/logging.h> |
Daniel Rosenberg | a48730a | 2019-06-06 20:38:38 -0700 | [diff] [blame] | 43 | #include <android-base/properties.h> |
Daniel Rosenberg | d2906b8 | 2019-06-07 14:18:14 -0700 | [diff] [blame] | 44 | #include <android-base/unique_fd.h> |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 45 | |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 46 | #include <cutils/properties.h> |
| 47 | |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 48 | #include <hardware/hw_auth_token.h> |
Shawn Willden | 35f0f22 | 2020-01-16 13:21:42 -0700 | [diff] [blame] | 49 | #include <keymasterV4_1/authorization_set.h> |
| 50 | #include <keymasterV4_1/keymaster_utils.h> |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 51 | |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 52 | extern "C" { |
| 53 | |
| 54 | #include "crypto_scrypt.h" |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 55 | } |
| 56 | |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 57 | namespace android { |
| 58 | namespace vold { |
| 59 | |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 60 | const KeyAuthentication kEmptyAuthentication{"", ""}; |
Paul Crowley | 0572080 | 2016-02-08 15:55:41 +0000 | [diff] [blame] | 61 | |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 62 | static constexpr size_t AES_KEY_BYTES = 32; |
| 63 | static constexpr size_t GCM_NONCE_BYTES = 12; |
| 64 | static constexpr size_t GCM_MAC_BYTES = 16; |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 65 | static constexpr size_t SALT_BYTES = 1 << 4; |
| 66 | static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14; |
| 67 | static constexpr size_t STRETCHED_BYTES = 1 << 6; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 68 | |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 69 | static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds |
Paul Crowley | b3de337 | 2016-04-27 12:58:41 -0700 | [diff] [blame] | 70 | |
Paul Crowley | 0572080 | 2016-02-08 15:55:41 +0000 | [diff] [blame] | 71 | static const char* kCurrentVersion = "1"; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 72 | static const char* kRmPath = "/system/bin/rm"; |
| 73 | static const char* kSecdiscardPath = "/system/bin/secdiscard"; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 74 | static const char* kStretch_none = "none"; |
| 75 | static const char* kStretch_nopassword = "nopassword"; |
| 76 | static const std::string kStretchPrefix_scrypt = "scrypt "; |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 77 | static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512"; |
| 78 | static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512"; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 79 | static const char* kFn_encrypted_key = "encrypted_key"; |
Paul Crowley | 0572080 | 2016-02-08 15:55:41 +0000 | [diff] [blame] | 80 | static const char* kFn_keymaster_key_blob = "keymaster_key_blob"; |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 81 | static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded"; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 82 | static const char* kFn_salt = "salt"; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 83 | static const char* kFn_secdiscardable = "secdiscardable"; |
Paul Crowley | 0572080 | 2016-02-08 15:55:41 +0000 | [diff] [blame] | 84 | static const char* kFn_stretching = "stretching"; |
| 85 | static const char* kFn_version = "version"; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 86 | |
Seth Moore | 5a43d61 | 2021-01-19 17:51:51 +0000 | [diff] [blame] | 87 | namespace { |
| 88 | |
| 89 | // Storage binding info for ensuring key encryption keys include a |
| 90 | // platform-provided seed in their derivation. |
| 91 | struct StorageBindingInfo { |
| 92 | enum class State { |
| 93 | UNINITIALIZED, |
| 94 | IN_USE, // key storage keys are bound to seed |
| 95 | NOT_USED, // key storage keys are NOT bound to seed |
| 96 | }; |
| 97 | |
| 98 | // Binding seed mixed into all key storage keys. |
| 99 | std::vector<uint8_t> seed; |
| 100 | |
| 101 | // State tracker for the key storage key binding. |
| 102 | State state = State::UNINITIALIZED; |
| 103 | |
| 104 | std::mutex guard; |
| 105 | }; |
| 106 | |
| 107 | // Never freed as the dtor is non-trivial. |
| 108 | StorageBindingInfo& storage_binding_info = *new StorageBindingInfo; |
| 109 | |
| 110 | } // namespace |
| 111 | |
Paul Crowley | 13ffd8e | 2016-01-27 14:30:22 +0000 | [diff] [blame] | 112 | static bool checkSize(const std::string& kind, size_t actual, size_t expected) { |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 113 | if (actual != expected) { |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 114 | LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got " |
| 115 | << actual; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 116 | return false; |
| 117 | } |
| 118 | return true; |
| 119 | } |
| 120 | |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 121 | static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) { |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 122 | SHA512_CTX c; |
| 123 | |
| 124 | SHA512_Init(&c); |
| 125 | // Personalise the hashing by introducing a fixed prefix. |
| 126 | // Hashing applications should use personalization except when there is a |
| 127 | // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 128 | std::string hashingPrefix = prefix; |
| 129 | hashingPrefix.resize(SHA512_CBLOCK); |
| 130 | SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size()); |
| 131 | SHA512_Update(&c, tohash.data(), tohash.size()); |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 132 | res->assign(SHA512_DIGEST_LENGTH, '\0'); |
| 133 | SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c); |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 134 | } |
| 135 | |
Eric Biggers | b2024e0 | 2021-03-15 12:44:36 -0700 | [diff] [blame] | 136 | // Generates a keymaster key, using rollback resistance if supported. |
| 137 | static bool generateKeymasterKey(Keymaster& keymaster, |
| 138 | const km::AuthorizationSetBuilder& paramBuilder, |
| 139 | std::string* key) { |
| 140 | auto paramsWithRollback = paramBuilder; |
| 141 | paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE); |
| 142 | |
| 143 | if (!keymaster.generateKey(paramsWithRollback, key)) { |
| 144 | LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keymaster " |
| 145 | "doesn't support rollback resistance. Falling back to " |
| 146 | "non-rollback-resistant key."; |
| 147 | if (!keymaster.generateKey(paramBuilder, key)) return false; |
| 148 | } |
| 149 | return true; |
| 150 | } |
| 151 | |
| 152 | static bool generateKeyStorageKey(Keymaster& keymaster, const KeyAuthentication& auth, |
| 153 | const std::string& appId, std::string* key) { |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 154 | auto paramBuilder = km::AuthorizationSetBuilder() |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 155 | .AesEncryptionKey(AES_KEY_BYTES * 8) |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 156 | .GcmModeMinMacLen(GCM_MAC_BYTES * 8) |
| 157 | .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId)); |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 158 | if (auth.token.empty()) { |
Eric Biggers | b2024e0 | 2021-03-15 12:44:36 -0700 | [diff] [blame] | 159 | LOG(DEBUG) << "Generating \"key storage\" key that doesn't need auth token"; |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 160 | paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED); |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 161 | } else { |
Eric Biggers | b2024e0 | 2021-03-15 12:44:36 -0700 | [diff] [blame] | 162 | LOG(DEBUG) << "Generating \"key storage\" key that needs auth token"; |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 163 | if (auth.token.size() != sizeof(hw_auth_token_t)) { |
| 164 | LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was " |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 165 | << auth.token.size() << " bytes"; |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 166 | return false; |
| 167 | } |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 168 | const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data()); |
Paul Crowley | d281de7 | 2018-08-30 15:25:19 -0700 | [diff] [blame] | 169 | auto user_id = at->user_id; // Make a copy because at->user_id is unaligned. |
| 170 | paramBuilder.Authorization(km::TAG_USER_SECURE_ID, user_id); |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 171 | paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD); |
| 172 | paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT); |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 173 | } |
Eric Biggers | b2024e0 | 2021-03-15 12:44:36 -0700 | [diff] [blame] | 174 | return generateKeymasterKey(keymaster, paramBuilder, key); |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 175 | } |
| 176 | |
Barani Muthukumaran | 3dfb094 | 2020-02-03 13:06:45 -0800 | [diff] [blame] | 177 | bool generateWrappedStorageKey(KeyBuffer* key) { |
| 178 | Keymaster keymaster; |
| 179 | if (!keymaster) return false; |
| 180 | std::string key_temp; |
| 181 | auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8); |
Barani Muthukumaran | 3dfb094 | 2020-02-03 13:06:45 -0800 | [diff] [blame] | 182 | paramBuilder.Authorization(km::TAG_STORAGE_KEY); |
Eric Biggers | b2024e0 | 2021-03-15 12:44:36 -0700 | [diff] [blame] | 183 | if (!generateKeymasterKey(keymaster, paramBuilder, &key_temp)) return false; |
Barani Muthukumaran | 3dfb094 | 2020-02-03 13:06:45 -0800 | [diff] [blame] | 184 | *key = KeyBuffer(key_temp.size()); |
| 185 | memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size()); |
| 186 | return true; |
| 187 | } |
| 188 | |
| 189 | bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) { |
| 190 | Keymaster keymaster; |
| 191 | if (!keymaster) return false; |
| 192 | std::string key_temp; |
| 193 | |
| 194 | if (!keymaster.exportKey(kmKey, &key_temp)) return false; |
| 195 | *key = KeyBuffer(key_temp.size()); |
| 196 | memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size()); |
| 197 | return true; |
| 198 | } |
| 199 | |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 200 | static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams( |
| 201 | const KeyAuthentication& auth, const std::string& appId) { |
| 202 | auto paramBuilder = km::AuthorizationSetBuilder() |
| 203 | .GcmModeMacLen(GCM_MAC_BYTES * 8) |
| 204 | .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId)); |
| 205 | km::HardwareAuthToken authToken; |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 206 | if (!auth.token.empty()) { |
| 207 | LOG(DEBUG) << "Supplying auth token to Keymaster"; |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 208 | authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token)); |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 209 | } |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 210 | return {paramBuilder, authToken}; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 211 | } |
| 212 | |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 213 | static bool readFileToString(const std::string& filename, std::string* result) { |
Paul Crowley | a051eb7 | 2016-03-08 16:08:32 -0800 | [diff] [blame] | 214 | if (!android::base::ReadFileToString(filename, result)) { |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 215 | PLOG(ERROR) << "Failed to read from " << filename; |
| 216 | return false; |
Paul Crowley | 13ffd8e | 2016-01-27 14:30:22 +0000 | [diff] [blame] | 217 | } |
| 218 | return true; |
| 219 | } |
| 220 | |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 221 | static bool readRandomBytesOrLog(size_t count, std::string* out) { |
| 222 | auto status = ReadRandomBytes(count, *out); |
| 223 | if (status != OK) { |
| 224 | LOG(ERROR) << "Random read failed with status: " << status; |
| 225 | return false; |
| 226 | } |
| 227 | return true; |
| 228 | } |
| 229 | |
| 230 | bool createSecdiscardable(const std::string& filename, std::string* hash) { |
| 231 | std::string secdiscardable; |
| 232 | if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false; |
| 233 | if (!writeStringToFile(secdiscardable, filename)) return false; |
| 234 | hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash); |
| 235 | return true; |
| 236 | } |
| 237 | |
| 238 | bool readSecdiscardable(const std::string& filename, std::string* hash) { |
| 239 | std::string secdiscardable; |
| 240 | if (!readFileToString(filename, &secdiscardable)) return false; |
| 241 | hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash); |
| 242 | return true; |
| 243 | } |
| 244 | |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 245 | static std::mutex key_upgrade_lock; |
| 246 | |
| 247 | // List of key directories that have had their Keymaster key upgraded during |
| 248 | // this boot and written to "keymaster_key_blob_upgraded", but replacing the old |
| 249 | // key was delayed due to an active checkpoint. Protected by key_upgrade_lock. |
| 250 | static std::vector<std::string> key_dirs_to_commit; |
| 251 | |
| 252 | // Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and |
| 253 | // deletes the old key from Keymaster. |
| 254 | static bool CommitUpgradedKey(Keymaster& keymaster, const std::string& dir) { |
| 255 | auto blob_file = dir + "/" + kFn_keymaster_key_blob; |
| 256 | auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded; |
| 257 | |
| 258 | std::string blob; |
| 259 | if (!readFileToString(blob_file, &blob)) return false; |
| 260 | |
| 261 | if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) { |
| 262 | PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file; |
| 263 | return false; |
Daniel Rosenberg | a48730a | 2019-06-06 20:38:38 -0700 | [diff] [blame] | 264 | } |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 265 | // Ensure that the rename is persisted before deleting the Keymaster key. |
| 266 | if (!FsyncDirectory(dir)) return false; |
| 267 | |
| 268 | if (!keymaster || !keymaster.deleteKey(blob)) { |
| 269 | LOG(WARNING) << "Failed to delete old key " << blob_file |
| 270 | << " from Keymaster; continuing anyway"; |
| 271 | // Continue on, but the space in Keymaster used by the old key won't be freed. |
| 272 | } |
| 273 | return true; |
| 274 | } |
| 275 | |
| 276 | static void DeferredCommitKeys() { |
| 277 | android::base::WaitForProperty("vold.checkpoint_committed", "1"); |
| 278 | LOG(INFO) << "Committing upgraded keys"; |
Daniel Rosenberg | a48730a | 2019-06-06 20:38:38 -0700 | [diff] [blame] | 279 | Keymaster keymaster; |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 280 | if (!keymaster) { |
| 281 | LOG(ERROR) << "Failed to open Keymaster; old keys won't be deleted from Keymaster"; |
| 282 | // Continue on, but the space in Keymaster used by the old keys won't be freed. |
| 283 | } |
| 284 | std::lock_guard<std::mutex> lock(key_upgrade_lock); |
| 285 | for (auto& dir : key_dirs_to_commit) { |
| 286 | LOG(INFO) << "Committing upgraded key " << dir; |
| 287 | CommitUpgradedKey(keymaster, dir); |
| 288 | } |
| 289 | key_dirs_to_commit.clear(); |
| 290 | } |
| 291 | |
| 292 | // Returns true if the Keymaster key in |dir| has already been upgraded and is |
| 293 | // pending being committed. Assumes that key_upgrade_lock is held. |
| 294 | static bool IsKeyCommitPending(const std::string& dir) { |
| 295 | for (const auto& dir_to_commit : key_dirs_to_commit) { |
| 296 | if (IsSameFile(dir, dir_to_commit)) return true; |
| 297 | } |
| 298 | return false; |
| 299 | } |
| 300 | |
| 301 | // Schedules the upgraded Keymaster key in |dir| to be committed later. |
| 302 | // Assumes that key_upgrade_lock is held. |
| 303 | static void ScheduleKeyCommit(const std::string& dir) { |
| 304 | if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach(); |
| 305 | key_dirs_to_commit.push_back(dir); |
| 306 | } |
| 307 | |
| 308 | static void CancelPendingKeyCommit(const std::string& dir) { |
| 309 | std::lock_guard<std::mutex> lock(key_upgrade_lock); |
| 310 | for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) { |
| 311 | if (IsSameFile(*it, dir)) { |
| 312 | LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir |
| 313 | << " because it is being destroyed"; |
| 314 | key_dirs_to_commit.erase(it); |
| 315 | break; |
| 316 | } |
Daniel Rosenberg | a48730a | 2019-06-06 20:38:38 -0700 | [diff] [blame] | 317 | } |
| 318 | } |
| 319 | |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 320 | // Deletes a leftover upgraded key, if present. An upgraded key can be left |
| 321 | // over if an update failed, or if we rebooted before committing the key in a |
| 322 | // freak accident. Either way, we can re-upgrade the key if we need to. |
| 323 | static void DeleteUpgradedKey(Keymaster& keymaster, const std::string& path) { |
| 324 | if (pathExists(path)) { |
| 325 | LOG(DEBUG) << "Deleting leftover upgraded key " << path; |
| 326 | std::string blob; |
| 327 | if (!android::base::ReadFileToString(path, &blob)) { |
| 328 | LOG(WARNING) << "Failed to read leftover upgraded key " << path |
| 329 | << "; continuing anyway"; |
| 330 | } else if (!keymaster.deleteKey(blob)) { |
| 331 | LOG(WARNING) << "Failed to delete leftover upgraded key " << path |
| 332 | << " from Keymaster; continuing anyway"; |
| 333 | } |
| 334 | if (unlink(path.c_str()) != 0) { |
| 335 | LOG(WARNING) << "Failed to unlink leftover upgraded key " << path |
| 336 | << "; continuing anyway"; |
| 337 | } |
Daniel Rosenberg | a48730a | 2019-06-06 20:38:38 -0700 | [diff] [blame] | 338 | } |
| 339 | } |
| 340 | |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 341 | // Begins a Keymaster operation using the key stored in |dir|. |
| 342 | static KeymasterOperation BeginKeymasterOp(Keymaster& keymaster, const std::string& dir, |
| 343 | km::KeyPurpose purpose, |
| 344 | const km::AuthorizationSet& keyParams, |
| 345 | const km::AuthorizationSet& opParams, |
| 346 | const km::HardwareAuthToken& authToken, |
| 347 | km::AuthorizationSet* outParams) { |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 348 | km::AuthorizationSet inParams(keyParams); |
Janis Danisevskis | 8e537b8 | 2016-10-26 14:27:10 +0100 | [diff] [blame] | 349 | inParams.append(opParams.begin(), opParams.end()); |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 350 | |
| 351 | auto blob_file = dir + "/" + kFn_keymaster_key_blob; |
| 352 | auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded; |
| 353 | |
| 354 | std::lock_guard<std::mutex> lock(key_upgrade_lock); |
| 355 | |
| 356 | std::string blob; |
| 357 | bool already_upgraded = IsKeyCommitPending(dir); |
| 358 | if (already_upgraded) { |
| 359 | LOG(DEBUG) |
| 360 | << blob_file |
| 361 | << " was already upgraded and is waiting to be committed; using the upgraded blob"; |
| 362 | if (!readFileToString(upgraded_blob_file, &blob)) return KeymasterOperation(); |
| 363 | } else { |
| 364 | DeleteUpgradedKey(keymaster, upgraded_blob_file); |
| 365 | if (!readFileToString(blob_file, &blob)) return KeymasterOperation(); |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 366 | } |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 367 | |
| 368 | auto opHandle = keymaster.begin(purpose, blob, inParams, authToken, outParams); |
| 369 | if (opHandle) return opHandle; |
| 370 | if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle; |
| 371 | |
| 372 | if (already_upgraded) { |
| 373 | LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file |
| 374 | << " still requires upgrade"; |
| 375 | return KeymasterOperation(); |
| 376 | } |
| 377 | LOG(INFO) << "Upgrading key: " << blob_file; |
| 378 | if (!keymaster.upgradeKey(blob, keyParams, &blob)) return KeymasterOperation(); |
| 379 | if (!writeStringToFile(blob, upgraded_blob_file)) return KeymasterOperation(); |
| 380 | if (cp_needsCheckpoint()) { |
| 381 | LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file |
| 382 | << "; delaying commit due to checkpoint"; |
| 383 | ScheduleKeyCommit(dir); |
| 384 | } else { |
| 385 | if (!CommitUpgradedKey(keymaster, dir)) return KeymasterOperation(); |
| 386 | LOG(INFO) << "Key upgraded: " << blob_file; |
| 387 | } |
| 388 | |
| 389 | return keymaster.begin(purpose, blob, inParams, authToken, outParams); |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 390 | } |
| 391 | |
| 392 | static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir, |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 393 | const km::AuthorizationSet& keyParams, |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 394 | const km::HardwareAuthToken& authToken, |
| 395 | const KeyBuffer& message, std::string* ciphertext) { |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 396 | km::AuthorizationSet opParams; |
| 397 | km::AuthorizationSet outParams; |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 398 | auto opHandle = BeginKeymasterOp(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, |
| 399 | authToken, &outParams); |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 400 | if (!opHandle) return false; |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 401 | auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE); |
Janis Danisevskis | 8e537b8 | 2016-10-26 14:27:10 +0100 | [diff] [blame] | 402 | if (!nonceBlob.isOk()) { |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 403 | LOG(ERROR) << "GCM encryption but no nonce generated"; |
| 404 | return false; |
| 405 | } |
| 406 | // nonceBlob here is just a pointer into existing data, must not be freed |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 407 | std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]), |
| 408 | nonceBlob.value().size()); |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 409 | if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false; |
| 410 | std::string body; |
| 411 | if (!opHandle.updateCompletely(message, &body)) return false; |
| 412 | |
| 413 | std::string mac; |
| 414 | if (!opHandle.finish(&mac)) return false; |
| 415 | if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false; |
| 416 | *ciphertext = nonce + body + mac; |
| 417 | return true; |
| 418 | } |
| 419 | |
| 420 | static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir, |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 421 | const km::AuthorizationSet& keyParams, |
| 422 | const km::HardwareAuthToken& authToken, |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 423 | const std::string& ciphertext, KeyBuffer* message) { |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 424 | auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES); |
| 425 | auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES); |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 426 | auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE, |
| 427 | km::support::blob2hidlVec(nonce)); |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 428 | auto opHandle = BeginKeymasterOp(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, |
| 429 | authToken, nullptr); |
Paul Crowley | dff8c72 | 2016-05-16 08:14:56 -0700 | [diff] [blame] | 430 | if (!opHandle) return false; |
| 431 | if (!opHandle.updateCompletely(bodyAndMac, message)) return false; |
| 432 | if (!opHandle.finish(nullptr)) return false; |
| 433 | return true; |
| 434 | } |
| 435 | |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 436 | static std::string getStretching(const KeyAuthentication& auth) { |
| 437 | if (!auth.usesKeymaster()) { |
| 438 | return kStretch_none; |
| 439 | } else if (auth.secret.empty()) { |
| 440 | return kStretch_nopassword; |
| 441 | } else { |
| 442 | char paramstr[PROPERTY_VALUE_MAX]; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 443 | |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 444 | property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS); |
| 445 | return std::string() + kStretchPrefix_scrypt + paramstr; |
| 446 | } |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 447 | } |
| 448 | |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 449 | static bool stretchingNeedsSalt(const std::string& stretching) { |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 450 | return stretching != kStretch_nopassword && stretching != kStretch_none; |
| 451 | } |
| 452 | |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 453 | static bool stretchSecret(const std::string& stretching, const std::string& secret, |
| 454 | const std::string& salt, std::string* stretched) { |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 455 | if (stretching == kStretch_nopassword) { |
| 456 | if (!secret.empty()) { |
Paul Crowley | d9b9295 | 2016-03-04 13:45:00 -0800 | [diff] [blame] | 457 | LOG(WARNING) << "Password present but stretching is nopassword"; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 458 | // Continue anyway |
| 459 | } |
Paul Crowley | a051eb7 | 2016-03-08 16:08:32 -0800 | [diff] [blame] | 460 | stretched->clear(); |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 461 | } else if (stretching == kStretch_none) { |
Paul Crowley | a051eb7 | 2016-03-08 16:08:32 -0800 | [diff] [blame] | 462 | *stretched = secret; |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 463 | } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(), |
| 464 | stretching.begin())) { |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 465 | int Nf, rf, pf; |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 466 | if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf, |
| 467 | &rf, &pf)) { |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 468 | LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching; |
| 469 | return false; |
| 470 | } |
Paul Crowley | a051eb7 | 2016-03-08 16:08:32 -0800 | [diff] [blame] | 471 | stretched->assign(STRETCHED_BYTES, '\0'); |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 472 | if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(), |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 473 | reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf, |
| 474 | 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]), |
| 475 | stretched->size()) != 0) { |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 476 | LOG(ERROR) << "scrypt failed with params: " << stretching; |
| 477 | return false; |
| 478 | } |
| 479 | } else { |
| 480 | LOG(ERROR) << "Unknown stretching type: " << stretching; |
| 481 | return false; |
| 482 | } |
| 483 | return true; |
| 484 | } |
| 485 | |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 486 | static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching, |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 487 | const std::string& salt, const std::string& secdiscardable_hash, |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 488 | std::string* appId) { |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 489 | std::string stretched; |
Paul Crowley | a051eb7 | 2016-03-08 16:08:32 -0800 | [diff] [blame] | 490 | if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false; |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 491 | *appId = secdiscardable_hash + stretched; |
Seth Moore | 5a43d61 | 2021-01-19 17:51:51 +0000 | [diff] [blame] | 492 | |
| 493 | const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard); |
| 494 | switch (storage_binding_info.state) { |
| 495 | case StorageBindingInfo::State::UNINITIALIZED: |
| 496 | storage_binding_info.state = StorageBindingInfo::State::NOT_USED; |
| 497 | break; |
| 498 | case StorageBindingInfo::State::IN_USE: |
| 499 | appId->append(storage_binding_info.seed.begin(), storage_binding_info.seed.end()); |
| 500 | break; |
| 501 | case StorageBindingInfo::State::NOT_USED: |
| 502 | // noop |
| 503 | break; |
| 504 | } |
| 505 | |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 506 | return true; |
| 507 | } |
| 508 | |
| 509 | static void logOpensslError() { |
| 510 | LOG(ERROR) << "Openssl error: " << ERR_get_error(); |
| 511 | } |
| 512 | |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 513 | static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext, |
| 514 | std::string* ciphertext) { |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 515 | std::string key; |
| 516 | hashWithPrefix(kHashPrefix_keygen, preKey, &key); |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 517 | key.resize(AES_KEY_BYTES); |
| 518 | if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false; |
| 519 | auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>( |
| 520 | EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free); |
| 521 | if (!ctx) { |
| 522 | logOpensslError(); |
| 523 | return false; |
| 524 | } |
| 525 | if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 526 | reinterpret_cast<const uint8_t*>(key.data()), |
| 527 | reinterpret_cast<const uint8_t*>(ciphertext->data()))) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 528 | logOpensslError(); |
| 529 | return false; |
| 530 | } |
| 531 | ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES); |
| 532 | int outlen; |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 533 | if (1 != EVP_EncryptUpdate( |
| 534 | ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES), |
| 535 | &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 536 | logOpensslError(); |
| 537 | return false; |
| 538 | } |
| 539 | if (outlen != static_cast<int>(plaintext.size())) { |
| 540 | LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen; |
| 541 | return false; |
| 542 | } |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 543 | if (1 != EVP_EncryptFinal_ex( |
| 544 | ctx.get(), |
| 545 | reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()), |
| 546 | &outlen)) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 547 | logOpensslError(); |
| 548 | return false; |
| 549 | } |
| 550 | if (outlen != 0) { |
| 551 | LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen; |
| 552 | return false; |
| 553 | } |
| 554 | if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES, |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 555 | reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + |
| 556 | plaintext.size()))) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 557 | logOpensslError(); |
| 558 | return false; |
| 559 | } |
| 560 | return true; |
| 561 | } |
| 562 | |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 563 | static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext, |
| 564 | KeyBuffer* plaintext) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 565 | if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) { |
| 566 | LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size(); |
| 567 | return false; |
| 568 | } |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 569 | std::string key; |
| 570 | hashWithPrefix(kHashPrefix_keygen, preKey, &key); |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 571 | key.resize(AES_KEY_BYTES); |
| 572 | auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>( |
| 573 | EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free); |
| 574 | if (!ctx) { |
| 575 | logOpensslError(); |
| 576 | return false; |
| 577 | } |
| 578 | if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 579 | reinterpret_cast<const uint8_t*>(key.data()), |
| 580 | reinterpret_cast<const uint8_t*>(ciphertext.data()))) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 581 | logOpensslError(); |
| 582 | return false; |
| 583 | } |
Pavel Grafov | e2e2d30 | 2017-08-01 17:15:53 +0100 | [diff] [blame] | 584 | *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES); |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 585 | int outlen; |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 586 | if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen, |
| 587 | reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES), |
| 588 | plaintext->size())) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 589 | logOpensslError(); |
| 590 | return false; |
| 591 | } |
| 592 | if (outlen != static_cast<int>(plaintext->size())) { |
| 593 | LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen; |
| 594 | return false; |
| 595 | } |
| 596 | if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES, |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 597 | const_cast<void*>(reinterpret_cast<const void*>( |
| 598 | ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 599 | logOpensslError(); |
| 600 | return false; |
| 601 | } |
| 602 | if (1 != EVP_DecryptFinal_ex(ctx.get(), |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 603 | reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()), |
| 604 | &outlen)) { |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 605 | logOpensslError(); |
| 606 | return false; |
| 607 | } |
| 608 | if (outlen != 0) { |
| 609 | LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen; |
| 610 | return false; |
| 611 | } |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 612 | return true; |
Paul Crowley | 0572080 | 2016-02-08 15:55:41 +0000 | [diff] [blame] | 613 | } |
| 614 | |
Pavel Grafov | e2e2d30 | 2017-08-01 17:15:53 +0100 | [diff] [blame] | 615 | bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) { |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 616 | if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) { |
| 617 | PLOG(ERROR) << "key mkdir " << dir; |
| 618 | return false; |
| 619 | } |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 620 | if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false; |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 621 | std::string secdiscardable_hash; |
| 622 | if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false; |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 623 | std::string stretching = getStretching(auth); |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 624 | if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 625 | std::string salt; |
| 626 | if (stretchingNeedsSalt(stretching)) { |
| 627 | if (ReadRandomBytes(SALT_BYTES, salt) != OK) { |
| 628 | LOG(ERROR) << "Random read failed"; |
| 629 | return false; |
| 630 | } |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 631 | if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 632 | } |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 633 | std::string appId; |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 634 | if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false; |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 635 | std::string encryptedKey; |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 636 | if (auth.usesKeymaster()) { |
| 637 | Keymaster keymaster; |
| 638 | if (!keymaster) return false; |
| 639 | std::string kmKey; |
Eric Biggers | b2024e0 | 2021-03-15 12:44:36 -0700 | [diff] [blame] | 640 | if (!generateKeyStorageKey(keymaster, auth, appId, &kmKey)) return false; |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 641 | if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false; |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 642 | km::AuthorizationSet keyParams; |
| 643 | km::HardwareAuthToken authToken; |
| 644 | std::tie(keyParams, authToken) = beginParams(auth, appId); |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 645 | if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey)) |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 646 | return false; |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 647 | } else { |
| 648 | if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false; |
| 649 | } |
Paul Crowley | 13ffd8e | 2016-01-27 14:30:22 +0000 | [diff] [blame] | 650 | if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false; |
Paul Crowley | 621d9b9 | 2018-12-07 15:36:09 -0800 | [diff] [blame] | 651 | if (!FsyncDirectory(dir)) return false; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 652 | return true; |
| 653 | } |
| 654 | |
Paul Crowley | f71ace3 | 2016-06-02 11:01:19 -0700 | [diff] [blame] | 655 | bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path, |
Pavel Grafov | e2e2d30 | 2017-08-01 17:15:53 +0100 | [diff] [blame] | 656 | const KeyAuthentication& auth, const KeyBuffer& key) { |
Paul Crowley | f71ace3 | 2016-06-02 11:01:19 -0700 | [diff] [blame] | 657 | if (pathExists(key_path)) { |
| 658 | LOG(ERROR) << "Already exists, cannot create key at: " << key_path; |
| 659 | return false; |
| 660 | } |
| 661 | if (pathExists(tmp_path)) { |
| 662 | LOG(DEBUG) << "Already exists, destroying: " << tmp_path; |
| 663 | destroyKey(tmp_path); // May be partially created so ignore errors |
| 664 | } |
| 665 | if (!storeKey(tmp_path, auth, key)) return false; |
| 666 | if (rename(tmp_path.c_str(), key_path.c_str()) != 0) { |
| 667 | PLOG(ERROR) << "Unable to move new key to location: " << key_path; |
| 668 | return false; |
| 669 | } |
Eric Biggers | 3345a2a | 2021-02-16 15:59:17 -0800 | [diff] [blame] | 670 | if (!FsyncParentDirectory(key_path)) return false; |
Paul Crowley | f71ace3 | 2016-06-02 11:01:19 -0700 | [diff] [blame] | 671 | LOG(DEBUG) << "Created key: " << key_path; |
| 672 | return true; |
| 673 | } |
| 674 | |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 675 | bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) { |
Paul Crowley | 0572080 | 2016-02-08 15:55:41 +0000 | [diff] [blame] | 676 | std::string version; |
Paul Crowley | a051eb7 | 2016-03-08 16:08:32 -0800 | [diff] [blame] | 677 | if (!readFileToString(dir + "/" + kFn_version, &version)) return false; |
Paul Crowley | 0572080 | 2016-02-08 15:55:41 +0000 | [diff] [blame] | 678 | if (version != kCurrentVersion) { |
| 679 | LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version; |
| 680 | return false; |
| 681 | } |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 682 | std::string secdiscardable_hash; |
| 683 | if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 684 | std::string stretching; |
Paul Crowley | a051eb7 | 2016-03-08 16:08:32 -0800 | [diff] [blame] | 685 | if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 686 | std::string salt; |
| 687 | if (stretchingNeedsSalt(stretching)) { |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 688 | if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false; |
Paul Crowley | 63c18d3 | 2016-02-10 14:02:47 +0000 | [diff] [blame] | 689 | } |
Paul Crowley | 320e5e1 | 2016-03-04 14:07:05 -0800 | [diff] [blame] | 690 | std::string appId; |
Paul Crowley | 26a5388 | 2017-10-26 11:16:39 -0700 | [diff] [blame] | 691 | if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false; |
Paul Crowley | 13ffd8e | 2016-01-27 14:30:22 +0000 | [diff] [blame] | 692 | std::string encryptedMessage; |
Paul Crowley | a051eb7 | 2016-03-08 16:08:32 -0800 | [diff] [blame] | 693 | if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false; |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 694 | if (auth.usesKeymaster()) { |
| 695 | Keymaster keymaster; |
| 696 | if (!keymaster) return false; |
Shawn Willden | 3535181 | 2018-01-22 09:08:32 -0700 | [diff] [blame] | 697 | km::AuthorizationSet keyParams; |
| 698 | km::HardwareAuthToken authToken; |
| 699 | std::tie(keyParams, authToken) = beginParams(auth, appId); |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 700 | if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key)) |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 701 | return false; |
Paul Crowley | 6ab2cab | 2017-01-04 22:32:40 -0800 | [diff] [blame] | 702 | } else { |
| 703 | if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false; |
| 704 | } |
| 705 | return true; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 706 | } |
| 707 | |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 708 | static bool DeleteKeymasterKey(const std::string& blob_file) { |
| 709 | std::string blob; |
| 710 | if (!readFileToString(blob_file, &blob)) return false; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 711 | Keymaster keymaster; |
| 712 | if (!keymaster) return false; |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 713 | LOG(DEBUG) << "Deleting key " << blob_file << " from Keymaster"; |
| 714 | if (!keymaster.deleteKey(blob)) return false; |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 715 | return true; |
| 716 | } |
| 717 | |
Rubin Xu | 2436e27 | 2017-04-27 20:43:10 +0100 | [diff] [blame] | 718 | bool runSecdiscardSingle(const std::string& file) { |
Shawn Willden | 785365b | 2018-01-20 09:37:36 -0700 | [diff] [blame] | 719 | if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) { |
Rubin Xu | 2436e27 | 2017-04-27 20:43:10 +0100 | [diff] [blame] | 720 | LOG(ERROR) << "secdiscard failed"; |
| 721 | return false; |
| 722 | } |
| 723 | return true; |
| 724 | } |
| 725 | |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 726 | static bool recursiveDeleteKey(const std::string& dir) { |
| 727 | if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) { |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 728 | LOG(ERROR) << "recursive delete failed"; |
| 729 | return false; |
| 730 | } |
| 731 | return true; |
| 732 | } |
| 733 | |
Paul Crowley | df528a7 | 2016-03-09 09:31:37 -0800 | [diff] [blame] | 734 | bool destroyKey(const std::string& dir) { |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 735 | bool success = true; |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 736 | |
| 737 | CancelPendingKeyCommit(dir); |
| 738 | |
Paul Crowley | ff19b05 | 2017-10-26 11:28:55 -0700 | [diff] [blame] | 739 | auto secdiscard_cmd = std::vector<std::string>{ |
Paul Crowley | 14c8c07 | 2018-09-18 13:30:21 -0700 | [diff] [blame] | 740 | kSecdiscardPath, |
| 741 | "--", |
| 742 | dir + "/" + kFn_encrypted_key, |
| 743 | dir + "/" + kFn_secdiscardable, |
Paul Crowley | ff19b05 | 2017-10-26 11:28:55 -0700 | [diff] [blame] | 744 | }; |
Eric Biggers | f74373b | 2020-11-05 19:58:26 -0800 | [diff] [blame] | 745 | // Try each thing, even if previous things failed. |
| 746 | |
| 747 | for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) { |
| 748 | auto blob_file = dir + "/" + fn; |
| 749 | if (pathExists(blob_file)) { |
| 750 | success &= DeleteKeymasterKey(blob_file); |
| 751 | secdiscard_cmd.push_back(blob_file); |
| 752 | } |
Paul Crowley | ff19b05 | 2017-10-26 11:28:55 -0700 | [diff] [blame] | 753 | } |
| 754 | if (ForkExecvp(secdiscard_cmd) != 0) { |
| 755 | LOG(ERROR) << "secdiscard failed"; |
| 756 | success = false; |
| 757 | } |
Paul Crowley | 13ffd8e | 2016-01-27 14:30:22 +0000 | [diff] [blame] | 758 | success &= recursiveDeleteKey(dir); |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 759 | return success; |
| 760 | } |
| 761 | |
Seth Moore | 5a43d61 | 2021-01-19 17:51:51 +0000 | [diff] [blame] | 762 | bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) { |
| 763 | const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard); |
| 764 | switch (storage_binding_info.state) { |
| 765 | case StorageBindingInfo::State::UNINITIALIZED: |
| 766 | storage_binding_info.state = StorageBindingInfo::State::IN_USE; |
| 767 | storage_binding_info.seed = seed; |
| 768 | return true; |
| 769 | case StorageBindingInfo::State::IN_USE: |
| 770 | LOG(ERROR) << "key storage binding seed already set"; |
| 771 | return false; |
| 772 | case StorageBindingInfo::State::NOT_USED: |
| 773 | LOG(ERROR) << "key storage already in use without binding"; |
| 774 | return false; |
| 775 | } |
| 776 | return false; |
| 777 | } |
| 778 | |
Paul Crowley | 1ef2558 | 2016-01-21 20:26:12 +0000 | [diff] [blame] | 779 | } // namespace vold |
| 780 | } // namespace android |