blob: 05b7eb3b83dc0b5a7814dd20d016c5008edf0ab3 [file] [log] [blame]
Paul Crowley1ef25582016-01-21 20:26:12 +00001/*
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 Rosenbergd2906b82019-06-07 14:18:14 -070019#include "Checkpoint.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000020#include "Keymaster.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000021#include "ScryptParameters.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000022#include "Utils.h"
23
Eric Biggersf74373b2020-11-05 19:58:26 -080024#include <algorithm>
Seth Moore5a43d612021-01-19 17:51:51 +000025#include <memory>
26#include <mutex>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070027#include <thread>
Paul Crowley1ef25582016-01-21 20:26:12 +000028#include <vector>
29
30#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070031#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000032#include <sys/stat.h>
33#include <sys/types.h>
34#include <sys/wait.h>
35#include <unistd.h>
36
Paul Crowley6ab2cab2017-01-04 22:32:40 -080037#include <openssl/err.h>
38#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000039#include <openssl/sha.h>
40
41#include <android-base/file.h>
42#include <android-base/logging.h>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070043#include <android-base/properties.h>
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070044#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000045
Paul Crowley63c18d32016-02-10 14:02:47 +000046#include <cutils/properties.h>
47
Paul Crowley320e5e12016-03-04 14:07:05 -080048#include <hardware/hw_auth_token.h>
49
Paul Crowley63c18d32016-02-10 14:02:47 +000050extern "C" {
51
52#include "crypto_scrypt.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000053}
54
Paul Crowley1ef25582016-01-21 20:26:12 +000055namespace android {
56namespace vold {
57
Satya Tangiralae1361712021-03-15 15:33:08 -070058const KeyAuthentication kEmptyAuthentication{""};
Paul Crowley05720802016-02-08 15:55:41 +000059
Paul Crowley1ef25582016-01-21 20:26:12 +000060static constexpr size_t AES_KEY_BYTES = 32;
61static constexpr size_t GCM_NONCE_BYTES = 12;
62static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080063static constexpr size_t SALT_BYTES = 1 << 4;
64static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
65static constexpr size_t STRETCHED_BYTES = 1 << 6;
Paul Crowley1ef25582016-01-21 20:26:12 +000066
Shawn Willden785365b2018-01-20 09:37:36 -070067static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
Paul Crowleyb3de3372016-04-27 12:58:41 -070068
Paul Crowley05720802016-02-08 15:55:41 +000069static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000070static const char* kRmPath = "/system/bin/rm";
71static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000072static const char* kStretch_none = "none";
73static const char* kStretch_nopassword = "nopassword";
74static const std::string kStretchPrefix_scrypt = "scrypt ";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080075static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
76static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000077static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000078static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070079static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley63c18d32016-02-10 14:02:47 +000080static const char* kFn_salt = "salt";
Paul Crowley1ef25582016-01-21 20:26:12 +000081static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000082static const char* kFn_stretching = "stretching";
83static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000084
Seth Moore5a43d612021-01-19 17:51:51 +000085namespace {
86
87// Storage binding info for ensuring key encryption keys include a
88// platform-provided seed in their derivation.
89struct StorageBindingInfo {
90 enum class State {
91 UNINITIALIZED,
92 IN_USE, // key storage keys are bound to seed
93 NOT_USED, // key storage keys are NOT bound to seed
94 };
95
96 // Binding seed mixed into all key storage keys.
97 std::vector<uint8_t> seed;
98
99 // State tracker for the key storage key binding.
100 State state = State::UNINITIALIZED;
101
102 std::mutex guard;
103};
104
105// Never freed as the dtor is non-trivial.
106StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
107
108} // namespace
109
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000110static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000111 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800112 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
113 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +0000114 return false;
115 }
116 return true;
117}
118
Paul Crowley26a53882017-10-26 11:16:39 -0700119static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000120 SHA512_CTX c;
121
122 SHA512_Init(&c);
123 // Personalise the hashing by introducing a fixed prefix.
124 // Hashing applications should use personalization except when there is a
125 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800126 std::string hashingPrefix = prefix;
127 hashingPrefix.resize(SHA512_CBLOCK);
128 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
129 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700130 res->assign(SHA512_DIGEST_LENGTH, '\0');
131 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000132}
133
Eric Biggersb2024e02021-03-15 12:44:36 -0700134// Generates a keymaster key, using rollback resistance if supported.
135static bool generateKeymasterKey(Keymaster& keymaster,
136 const km::AuthorizationSetBuilder& paramBuilder,
137 std::string* key) {
138 auto paramsWithRollback = paramBuilder;
139 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
140
141 if (!keymaster.generateKey(paramsWithRollback, key)) {
142 LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keymaster "
143 "doesn't support rollback resistance. Falling back to "
144 "non-rollback-resistant key.";
145 if (!keymaster.generateKey(paramBuilder, key)) return false;
146 }
147 return true;
148}
149
Satya Tangiralae1361712021-03-15 15:33:08 -0700150static bool generateKeyStorageKey(Keymaster& keymaster, const std::string& appId,
151 std::string* key) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800152 auto paramBuilder = km::AuthorizationSetBuilder()
153 .AesEncryptionKey(AES_KEY_BYTES * 8)
154 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
155 .Authorization(km::TAG_APPLICATION_ID, appId)
156 .Authorization(km::TAG_NO_AUTH_REQUIRED);
Satya Tangiralae1361712021-03-15 15:33:08 -0700157 LOG(DEBUG) << "Generating \"key storage\" key that doesn't need auth token";
Eric Biggersb2024e02021-03-15 12:44:36 -0700158 return generateKeymasterKey(keymaster, paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800159}
160
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800161bool generateWrappedStorageKey(KeyBuffer* key) {
162 Keymaster keymaster;
163 if (!keymaster) return false;
164 std::string key_temp;
165 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800166 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Eric Biggersb2024e02021-03-15 12:44:36 -0700167 if (!generateKeymasterKey(keymaster, paramBuilder, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800168 *key = KeyBuffer(key_temp.size());
169 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
170 return true;
171}
172
173bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
174 Keymaster keymaster;
175 if (!keymaster) return false;
176 std::string key_temp;
177
178 if (!keymaster.exportKey(kmKey, &key_temp)) return false;
179 *key = KeyBuffer(key_temp.size());
180 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
181 return true;
182}
183
Satya Tangiralae1361712021-03-15 15:33:08 -0700184static km::AuthorizationSet beginParams(const std::string& appId) {
185 return km::AuthorizationSetBuilder()
186 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800187 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000188}
189
Paul Crowleydf528a72016-03-09 09:31:37 -0800190static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800191 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800192 PLOG(ERROR) << "Failed to read from " << filename;
193 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000194 }
195 return true;
196}
197
Paul Crowley26a53882017-10-26 11:16:39 -0700198static bool readRandomBytesOrLog(size_t count, std::string* out) {
199 auto status = ReadRandomBytes(count, *out);
200 if (status != OK) {
201 LOG(ERROR) << "Random read failed with status: " << status;
202 return false;
203 }
204 return true;
205}
206
207bool createSecdiscardable(const std::string& filename, std::string* hash) {
208 std::string secdiscardable;
209 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
210 if (!writeStringToFile(secdiscardable, filename)) return false;
211 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
212 return true;
213}
214
215bool readSecdiscardable(const std::string& filename, std::string* hash) {
216 std::string secdiscardable;
217 if (!readFileToString(filename, &secdiscardable)) return false;
218 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
219 return true;
220}
221
Eric Biggersf74373b2020-11-05 19:58:26 -0800222static std::mutex key_upgrade_lock;
223
224// List of key directories that have had their Keymaster key upgraded during
225// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
226// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
227static std::vector<std::string> key_dirs_to_commit;
228
229// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
230// deletes the old key from Keymaster.
231static bool CommitUpgradedKey(Keymaster& keymaster, const std::string& dir) {
232 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
233 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
234
235 std::string blob;
236 if (!readFileToString(blob_file, &blob)) return false;
237
238 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
239 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
240 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700241 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800242 // Ensure that the rename is persisted before deleting the Keymaster key.
243 if (!FsyncDirectory(dir)) return false;
244
245 if (!keymaster || !keymaster.deleteKey(blob)) {
246 LOG(WARNING) << "Failed to delete old key " << blob_file
247 << " from Keymaster; continuing anyway";
248 // Continue on, but the space in Keymaster used by the old key won't be freed.
249 }
250 return true;
251}
252
253static void DeferredCommitKeys() {
254 android::base::WaitForProperty("vold.checkpoint_committed", "1");
255 LOG(INFO) << "Committing upgraded keys";
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700256 Keymaster keymaster;
Eric Biggersf74373b2020-11-05 19:58:26 -0800257 if (!keymaster) {
258 LOG(ERROR) << "Failed to open Keymaster; old keys won't be deleted from Keymaster";
259 // Continue on, but the space in Keymaster used by the old keys won't be freed.
260 }
261 std::lock_guard<std::mutex> lock(key_upgrade_lock);
262 for (auto& dir : key_dirs_to_commit) {
263 LOG(INFO) << "Committing upgraded key " << dir;
264 CommitUpgradedKey(keymaster, dir);
265 }
266 key_dirs_to_commit.clear();
267}
268
269// Returns true if the Keymaster key in |dir| has already been upgraded and is
270// pending being committed. Assumes that key_upgrade_lock is held.
271static bool IsKeyCommitPending(const std::string& dir) {
272 for (const auto& dir_to_commit : key_dirs_to_commit) {
273 if (IsSameFile(dir, dir_to_commit)) return true;
274 }
275 return false;
276}
277
278// Schedules the upgraded Keymaster key in |dir| to be committed later.
279// Assumes that key_upgrade_lock is held.
280static void ScheduleKeyCommit(const std::string& dir) {
281 if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
282 key_dirs_to_commit.push_back(dir);
283}
284
285static void CancelPendingKeyCommit(const std::string& dir) {
286 std::lock_guard<std::mutex> lock(key_upgrade_lock);
287 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
288 if (IsSameFile(*it, dir)) {
289 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
290 << " because it is being destroyed";
291 key_dirs_to_commit.erase(it);
292 break;
293 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700294 }
295}
296
Eric Biggersf74373b2020-11-05 19:58:26 -0800297// Deletes a leftover upgraded key, if present. An upgraded key can be left
298// over if an update failed, or if we rebooted before committing the key in a
299// freak accident. Either way, we can re-upgrade the key if we need to.
300static void DeleteUpgradedKey(Keymaster& keymaster, const std::string& path) {
301 if (pathExists(path)) {
302 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
303 std::string blob;
304 if (!android::base::ReadFileToString(path, &blob)) {
305 LOG(WARNING) << "Failed to read leftover upgraded key " << path
306 << "; continuing anyway";
307 } else if (!keymaster.deleteKey(blob)) {
308 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
309 << " from Keymaster; continuing anyway";
310 }
311 if (unlink(path.c_str()) != 0) {
312 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
313 << "; continuing anyway";
314 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700315 }
316}
317
Eric Biggersf74373b2020-11-05 19:58:26 -0800318// Begins a Keymaster operation using the key stored in |dir|.
319static KeymasterOperation BeginKeymasterOp(Keymaster& keymaster, const std::string& dir,
Eric Biggersf74373b2020-11-05 19:58:26 -0800320 const km::AuthorizationSet& keyParams,
321 const km::AuthorizationSet& opParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800322 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700323 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100324 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800325
326 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
327 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
328
329 std::lock_guard<std::mutex> lock(key_upgrade_lock);
330
331 std::string blob;
332 bool already_upgraded = IsKeyCommitPending(dir);
333 if (already_upgraded) {
334 LOG(DEBUG)
335 << blob_file
336 << " was already upgraded and is waiting to be committed; using the upgraded blob";
337 if (!readFileToString(upgraded_blob_file, &blob)) return KeymasterOperation();
338 } else {
339 DeleteUpgradedKey(keymaster, upgraded_blob_file);
340 if (!readFileToString(blob_file, &blob)) return KeymasterOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700341 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800342
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800343 auto opHandle = keymaster.begin(blob, inParams, outParams);
344 if (!opHandle) return opHandle;
345
346 // If key blob wasn't upgraded, nothing left to do.
347 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800348
349 if (already_upgraded) {
350 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
351 << " still requires upgrade";
352 return KeymasterOperation();
353 }
354 LOG(INFO) << "Upgrading key: " << blob_file;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800355 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
356 return KeymasterOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800357 if (cp_needsCheckpoint()) {
358 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
359 << "; delaying commit due to checkpoint";
360 ScheduleKeyCommit(dir);
361 } else {
362 if (!CommitUpgradedKey(keymaster, dir)) return KeymasterOperation();
363 LOG(INFO) << "Key upgraded: " << blob_file;
364 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800365 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700366}
367
368static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700369 const km::AuthorizationSet& keyParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800370 const KeyBuffer& message, std::string* ciphertext) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800371 km::AuthorizationSet opParams =
372 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700373 km::AuthorizationSet outParams;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800374 auto opHandle = BeginKeymasterOp(keymaster, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700375 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700376 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800377 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700378 LOG(ERROR) << "GCM encryption but no nonce generated";
379 return false;
380 }
381 // nonceBlob here is just a pointer into existing data, must not be freed
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800382 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700383 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
384 std::string body;
385 if (!opHandle.updateCompletely(message, &body)) return false;
386
387 std::string mac;
388 if (!opHandle.finish(&mac)) return false;
389 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
390 *ciphertext = nonce + body + mac;
391 return true;
392}
393
394static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700395 const km::AuthorizationSet& keyParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800396 const std::string& ciphertext, KeyBuffer* message) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800397 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700398 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800399 auto opParams = km::AuthorizationSetBuilder()
400 .Authorization(km::TAG_NONCE, nonce)
401 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
402 auto opHandle = BeginKeymasterOp(keymaster, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700403 if (!opHandle) return false;
404 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
405 if (!opHandle.finish(nullptr)) return false;
406 return true;
407}
408
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800409static std::string getStretching(const KeyAuthentication& auth) {
Satya Tangiralae1361712021-03-15 15:33:08 -0700410 if (auth.usesKeymaster()) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800411 return kStretch_nopassword;
412 } else {
Satya Tangiralae1361712021-03-15 15:33:08 -0700413 return kStretch_none;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800414 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000415}
416
Paul Crowleydf528a72016-03-09 09:31:37 -0800417static bool stretchSecret(const std::string& stretching, const std::string& secret,
Satya Tangirala478cea92021-04-07 14:30:25 -0700418 std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000419 if (stretching == kStretch_nopassword) {
420 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800421 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000422 // Continue anyway
423 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800424 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000425 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800426 *stretched = secret;
Paul Crowley63c18d32016-02-10 14:02:47 +0000427 } else {
428 LOG(ERROR) << "Unknown stretching type: " << stretching;
429 return false;
430 }
431 return true;
432}
433
Paul Crowleydf528a72016-03-09 09:31:37 -0800434static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Satya Tangirala478cea92021-04-07 14:30:25 -0700435 const std::string& secdiscardable_hash, std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000436 std::string stretched;
Satya Tangirala478cea92021-04-07 14:30:25 -0700437 if (!stretchSecret(stretching, auth.secret, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700438 *appId = secdiscardable_hash + stretched;
Seth Moore5a43d612021-01-19 17:51:51 +0000439
440 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
441 switch (storage_binding_info.state) {
442 case StorageBindingInfo::State::UNINITIALIZED:
443 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
444 break;
445 case StorageBindingInfo::State::IN_USE:
446 appId->append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
447 break;
448 case StorageBindingInfo::State::NOT_USED:
449 // noop
450 break;
451 }
452
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800453 return true;
454}
455
456static void logOpensslError() {
457 LOG(ERROR) << "Openssl error: " << ERR_get_error();
458}
459
Shawn Willden785365b2018-01-20 09:37:36 -0700460static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
461 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700462 std::string key;
463 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800464 key.resize(AES_KEY_BYTES);
465 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
466 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
467 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
468 if (!ctx) {
469 logOpensslError();
470 return false;
471 }
472 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700473 reinterpret_cast<const uint8_t*>(key.data()),
474 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800475 logOpensslError();
476 return false;
477 }
478 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
479 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700480 if (1 != EVP_EncryptUpdate(
481 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
482 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800483 logOpensslError();
484 return false;
485 }
486 if (outlen != static_cast<int>(plaintext.size())) {
487 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
488 return false;
489 }
Shawn Willden785365b2018-01-20 09:37:36 -0700490 if (1 != EVP_EncryptFinal_ex(
491 ctx.get(),
492 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
493 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800494 logOpensslError();
495 return false;
496 }
497 if (outlen != 0) {
498 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
499 return false;
500 }
501 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700502 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
503 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800504 logOpensslError();
505 return false;
506 }
507 return true;
508}
509
Shawn Willden785365b2018-01-20 09:37:36 -0700510static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
511 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800512 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
513 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
514 return false;
515 }
Paul Crowley26a53882017-10-26 11:16:39 -0700516 std::string key;
517 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800518 key.resize(AES_KEY_BYTES);
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_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700526 reinterpret_cast<const uint8_t*>(key.data()),
527 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800528 logOpensslError();
529 return false;
530 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100531 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800532 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700533 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
534 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
535 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800536 logOpensslError();
537 return false;
538 }
539 if (outlen != static_cast<int>(plaintext->size())) {
540 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
541 return false;
542 }
543 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700544 const_cast<void*>(reinterpret_cast<const void*>(
545 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800546 logOpensslError();
547 return false;
548 }
549 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700550 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
551 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800552 logOpensslError();
553 return false;
554 }
555 if (outlen != 0) {
556 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
557 return false;
558 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000559 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000560}
561
Pavel Grafove2e2d302017-08-01 17:15:53 +0100562bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000563 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
564 PLOG(ERROR) << "key mkdir " << dir;
565 return false;
566 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800567 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700568 std::string secdiscardable_hash;
569 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800570 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800571 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800572 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700573 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800574 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800575 if (auth.usesKeymaster()) {
576 Keymaster keymaster;
577 if (!keymaster) return false;
578 std::string kmKey;
Satya Tangiralae1361712021-03-15 15:33:08 -0700579 if (!generateKeyStorageKey(keymaster, appId, &kmKey)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800580 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700581 km::AuthorizationSet keyParams = beginParams(appId);
582 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, key, &encryptedKey)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800583 } else {
584 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
585 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000586 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800587 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000588 return true;
589}
590
Paul Crowleyf71ace32016-06-02 11:01:19 -0700591bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100592 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700593 if (pathExists(key_path)) {
594 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
595 return false;
596 }
597 if (pathExists(tmp_path)) {
598 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
599 destroyKey(tmp_path); // May be partially created so ignore errors
600 }
601 if (!storeKey(tmp_path, auth, key)) return false;
602 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
603 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
604 return false;
605 }
Eric Biggers3345a2a2021-02-16 15:59:17 -0800606 if (!FsyncParentDirectory(key_path)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700607 LOG(DEBUG) << "Created key: " << key_path;
608 return true;
609}
610
Eric Biggersf74373b2020-11-05 19:58:26 -0800611bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000612 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800613 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000614 if (version != kCurrentVersion) {
615 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
616 return false;
617 }
Paul Crowley26a53882017-10-26 11:16:39 -0700618 std::string secdiscardable_hash;
619 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000620 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800621 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800622 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700623 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000624 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800625 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800626 if (auth.usesKeymaster()) {
627 Keymaster keymaster;
628 if (!keymaster) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700629 km::AuthorizationSet keyParams = beginParams(appId);
630 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, encryptedMessage, key))
Shawn Willden785365b2018-01-20 09:37:36 -0700631 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800632 } else {
633 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
634 }
635 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000636}
637
Eric Biggersf74373b2020-11-05 19:58:26 -0800638static bool DeleteKeymasterKey(const std::string& blob_file) {
639 std::string blob;
640 if (!readFileToString(blob_file, &blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000641 Keymaster keymaster;
642 if (!keymaster) return false;
Eric Biggersf74373b2020-11-05 19:58:26 -0800643 LOG(DEBUG) << "Deleting key " << blob_file << " from Keymaster";
644 if (!keymaster.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000645 return true;
646}
647
Rubin Xu2436e272017-04-27 20:43:10 +0100648bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700649 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100650 LOG(ERROR) << "secdiscard failed";
651 return false;
652 }
653 return true;
654}
655
Paul Crowleydf528a72016-03-09 09:31:37 -0800656static bool recursiveDeleteKey(const std::string& dir) {
657 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000658 LOG(ERROR) << "recursive delete failed";
659 return false;
660 }
661 return true;
662}
663
Paul Crowleydf528a72016-03-09 09:31:37 -0800664bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000665 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800666
667 CancelPendingKeyCommit(dir);
668
Paul Crowleyff19b052017-10-26 11:28:55 -0700669 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700670 kSecdiscardPath,
671 "--",
672 dir + "/" + kFn_encrypted_key,
673 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700674 };
Eric Biggersf74373b2020-11-05 19:58:26 -0800675 // Try each thing, even if previous things failed.
676
677 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
678 auto blob_file = dir + "/" + fn;
679 if (pathExists(blob_file)) {
680 success &= DeleteKeymasterKey(blob_file);
681 secdiscard_cmd.push_back(blob_file);
682 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700683 }
684 if (ForkExecvp(secdiscard_cmd) != 0) {
685 LOG(ERROR) << "secdiscard failed";
686 success = false;
687 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000688 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000689 return success;
690}
691
Seth Moore5a43d612021-01-19 17:51:51 +0000692bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
693 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
694 switch (storage_binding_info.state) {
695 case StorageBindingInfo::State::UNINITIALIZED:
696 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
697 storage_binding_info.seed = seed;
698 return true;
699 case StorageBindingInfo::State::IN_USE:
700 LOG(ERROR) << "key storage binding seed already set";
701 return false;
702 case StorageBindingInfo::State::NOT_USED:
703 LOG(ERROR) << "key storage already in use without binding";
704 return false;
705 }
706 return false;
707}
708
Paul Crowley1ef25582016-01-21 20:26:12 +0000709} // namespace vold
710} // namespace android