blob: 1c8bb87fc4734ac38d1f2e151e5bad0986a803e8 [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 Rosenberg8cc57162019-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 Rosenberg8cc57162019-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 Crowley63c18d32016-02-10 14:02:47 +000048extern "C" {
49
50#include "crypto_scrypt.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000051}
52
Paul Crowley1ef25582016-01-21 20:26:12 +000053namespace android {
54namespace vold {
55
Satya Tangiralae1361712021-03-15 15:33:08 -070056const KeyAuthentication kEmptyAuthentication{""};
Paul Crowley05720802016-02-08 15:55:41 +000057
Paul Crowley1ef25582016-01-21 20:26:12 +000058static constexpr size_t AES_KEY_BYTES = 32;
59static constexpr size_t GCM_NONCE_BYTES = 12;
60static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080061static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
Shivaprasad Hongal92292622018-07-05 14:49:12 -070062constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
Paul Crowleyb3de3372016-04-27 12:58:41 -070063
Paul Crowley05720802016-02-08 15:55:41 +000064static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000065static const char* kRmPath = "/system/bin/rm";
66static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000067static const char* kStretch_none = "none";
68static const char* kStretch_nopassword = "nopassword";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080069static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
70static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000071static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000072static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070073static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley1ef25582016-01-21 20:26:12 +000074static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000075static const char* kFn_stretching = "stretching";
76static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000077
Phanindra Babu Pabba1fe8ce52021-06-02 14:50:38 +053078static const int32_t KM_TAG_FBE_ICE = static_cast<int32_t>(7 << 28) | 16201;
79
Seth Moore5a43d612021-01-19 17:51:51 +000080namespace {
81
82// Storage binding info for ensuring key encryption keys include a
83// platform-provided seed in their derivation.
84struct StorageBindingInfo {
85 enum class State {
86 UNINITIALIZED,
87 IN_USE, // key storage keys are bound to seed
88 NOT_USED, // key storage keys are NOT bound to seed
89 };
90
91 // Binding seed mixed into all key storage keys.
92 std::vector<uint8_t> seed;
93
94 // State tracker for the key storage key binding.
95 State state = State::UNINITIALIZED;
96
97 std::mutex guard;
98};
99
100// Never freed as the dtor is non-trivial.
101StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
102
103} // namespace
104
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000105static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000106 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800107 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
108 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +0000109 return false;
110 }
111 return true;
112}
113
Paul Crowley26a53882017-10-26 11:16:39 -0700114static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000115 SHA512_CTX c;
116
117 SHA512_Init(&c);
118 // Personalise the hashing by introducing a fixed prefix.
119 // Hashing applications should use personalization except when there is a
120 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800121 std::string hashingPrefix = prefix;
122 hashingPrefix.resize(SHA512_CBLOCK);
123 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
124 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700125 res->assign(SHA512_DIGEST_LENGTH, '\0');
126 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000127}
128
Eric Biggersb2024e02021-03-15 12:44:36 -0700129// Generates a keymaster key, using rollback resistance if supported.
130static bool generateKeymasterKey(Keymaster& keymaster,
131 const km::AuthorizationSetBuilder& paramBuilder,
132 std::string* key) {
133 auto paramsWithRollback = paramBuilder;
134 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
135
136 if (!keymaster.generateKey(paramsWithRollback, key)) {
137 LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keymaster "
138 "doesn't support rollback resistance. Falling back to "
139 "non-rollback-resistant key.";
140 if (!keymaster.generateKey(paramBuilder, key)) return false;
141 }
142 return true;
143}
144
Satya Tangiralae1361712021-03-15 15:33:08 -0700145static bool generateKeyStorageKey(Keymaster& keymaster, const std::string& appId,
146 std::string* key) {
Daniel Normanbe0137a2021-04-28 12:37:42 -0700147 auto paramBuilder = km::AuthorizationSetBuilder()
148 .AesEncryptionKey(AES_KEY_BYTES * 8)
149 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
150 .Authorization(km::TAG_APPLICATION_ID, appId)
151 .Authorization(km::TAG_NO_AUTH_REQUIRED);
Satya Tangirala6b98fb62021-05-11 19:48:47 -0700152 LOG(DEBUG) << "Generating \"key storage\" key";
Eric Biggersb2024e02021-03-15 12:44:36 -0700153 return generateKeymasterKey(keymaster, paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800154}
155
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800156bool generateWrappedStorageKey(KeyBuffer* key) {
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700157 Keymaster keymaster;
158 if (!keymaster) return false;
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700159 std::string key_temp;
Daniel Norman6ce83882021-04-28 14:53:30 -0700160 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8)
161 .Authorization(km::TAG_STORAGE_KEY);
Phanindra Babu Pabba1fe8ce52021-06-02 14:50:38 +0530162
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700163 km::KeyParameter param1;
Phanindra Babu Pabba1fe8ce52021-06-02 14:50:38 +0530164 param1.tag = (km::Tag) (KM_TAG_FBE_ICE);
165 param1.value = km::KeyParameterValue::make<km::KeyParameterValue::boolValue>(true);
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700166 paramBuilder.push_back(param1);
Phanindra Babu Pabba1fe8ce52021-06-02 14:50:38 +0530167
Eric Biggersb2024e02021-03-15 12:44:36 -0700168 if (!generateKeymasterKey(keymaster, paramBuilder, &key_temp)) return false;
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700169 *key = KeyBuffer(key_temp.size());
170 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
171 return true;
172}
173
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800174bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700175 Keymaster keymaster;
176 if (!keymaster) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800177 std::string key_temp;
Smita Ghosh85c46ea2019-01-11 10:38:09 -0800178
Neeraj Soni256fc9c2020-02-26 15:59:27 +0530179 auto ret = keymaster.exportKey(kmKey, &key_temp);
180 if (ret != km::ErrorCode::OK) {
181 if (ret == km::ErrorCode::KEY_REQUIRES_UPGRADE) {
Daniel Norman036b0ba2021-04-29 09:27:54 -0700182 // TODO(b/187304488): Re-land the below logic. (keymaster.upgradeKey() was removed)
Daniel Norman6ce83882021-04-28 14:53:30 -0700183 return false;
184 /*
Neeraj Soni256fc9c2020-02-26 15:59:27 +0530185 std::string kmKeyStr(reinterpret_cast<const char*>(kmKey.data()), kmKey.size());
186 std::string Keystr;
187 if (!keymaster.upgradeKey(kmKeyStr, km::AuthorizationSet(), &Keystr)) return false;
188 KeyBuffer upgradedKey = KeyBuffer(Keystr.size());
189 memcpy(reinterpret_cast<void*>(upgradedKey.data()), Keystr.c_str(), upgradedKey.size());
190 ret = keymaster.exportKey(upgradedKey, &key_temp);
191 if (ret != km::ErrorCode::OK) return false;
Daniel Norman6ce83882021-04-28 14:53:30 -0700192 */
Neeraj Soni256fc9c2020-02-26 15:59:27 +0530193 } else {
194 return false;
195 }
196 }
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800197 *key = KeyBuffer(key_temp.size());
198 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
199 return true;
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700200}
201
Satya Tangiralae1361712021-03-15 15:33:08 -0700202static km::AuthorizationSet beginParams(const std::string& appId) {
203 return km::AuthorizationSetBuilder()
204 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Daniel Normanbe0137a2021-04-28 12:37:42 -0700205 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000206}
207
Paul Crowleydf528a72016-03-09 09:31:37 -0800208static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800209 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800210 PLOG(ERROR) << "Failed to read from " << filename;
211 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000212 }
213 return true;
214}
215
Paul Crowley26a53882017-10-26 11:16:39 -0700216static bool readRandomBytesOrLog(size_t count, std::string* out) {
217 auto status = ReadRandomBytes(count, *out);
218 if (status != OK) {
219 LOG(ERROR) << "Random read failed with status: " << status;
220 return false;
221 }
222 return true;
223}
224
225bool createSecdiscardable(const std::string& filename, std::string* hash) {
226 std::string secdiscardable;
227 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
228 if (!writeStringToFile(secdiscardable, filename)) return false;
229 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
230 return true;
231}
232
233bool readSecdiscardable(const std::string& filename, std::string* hash) {
234 std::string secdiscardable;
235 if (!readFileToString(filename, &secdiscardable)) return false;
236 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
237 return true;
238}
239
Eric Biggersf74373b2020-11-05 19:58:26 -0800240static std::mutex key_upgrade_lock;
241
242// List of key directories that have had their Keymaster key upgraded during
243// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
244// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
245static std::vector<std::string> key_dirs_to_commit;
246
247// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
248// deletes the old key from Keymaster.
249static bool CommitUpgradedKey(Keymaster& keymaster, const std::string& dir) {
250 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
251 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
252
253 std::string blob;
254 if (!readFileToString(blob_file, &blob)) return false;
255
256 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
257 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
258 return false;
Daniel Rosenberg8cc57162019-06-06 20:38:38 -0700259 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800260 // Ensure that the rename is persisted before deleting the Keymaster key.
261 if (!FsyncDirectory(dir)) return false;
262
263 if (!keymaster || !keymaster.deleteKey(blob)) {
264 LOG(WARNING) << "Failed to delete old key " << blob_file
265 << " from Keymaster; continuing anyway";
266 // Continue on, but the space in Keymaster used by the old key won't be freed.
267 }
268 return true;
269}
270
271static void DeferredCommitKeys() {
272 android::base::WaitForProperty("vold.checkpoint_committed", "1");
273 LOG(INFO) << "Committing upgraded keys";
Daniel Rosenberg8cc57162019-06-06 20:38:38 -0700274 Keymaster keymaster;
Eric Biggersf74373b2020-11-05 19:58:26 -0800275 if (!keymaster) {
276 LOG(ERROR) << "Failed to open Keymaster; old keys won't be deleted from Keymaster";
277 // Continue on, but the space in Keymaster used by the old keys won't be freed.
278 }
279 std::lock_guard<std::mutex> lock(key_upgrade_lock);
280 for (auto& dir : key_dirs_to_commit) {
281 LOG(INFO) << "Committing upgraded key " << dir;
282 CommitUpgradedKey(keymaster, dir);
283 }
284 key_dirs_to_commit.clear();
285}
286
287// Returns true if the Keymaster key in |dir| has already been upgraded and is
288// pending being committed. Assumes that key_upgrade_lock is held.
289static bool IsKeyCommitPending(const std::string& dir) {
290 for (const auto& dir_to_commit : key_dirs_to_commit) {
291 if (IsSameFile(dir, dir_to_commit)) return true;
292 }
293 return false;
294}
295
296// Schedules the upgraded Keymaster key in |dir| to be committed later.
297// Assumes that key_upgrade_lock is held.
298static void ScheduleKeyCommit(const std::string& dir) {
299 if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
300 key_dirs_to_commit.push_back(dir);
301}
302
303static void CancelPendingKeyCommit(const std::string& dir) {
304 std::lock_guard<std::mutex> lock(key_upgrade_lock);
305 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
306 if (IsSameFile(*it, dir)) {
307 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
308 << " because it is being destroyed";
309 key_dirs_to_commit.erase(it);
310 break;
311 }
Daniel Rosenberg8cc57162019-06-06 20:38:38 -0700312 }
313}
314
Satya Tangirala9475b112021-05-13 00:43:03 -0700315// Renames a key directory. Also updates the deferred commit vector
316// (key_dirs_to_commit) appropriately.
317//
318// However, @old_name must be the path to the directory that was used to put that
319// directory into the deferred commit list in the first place (since this function
320// directly compares paths instead of using IsSameFile()).
321static bool RenameKeyDir(const std::string& old_name, const std::string& new_name) {
322 std::lock_guard<std::mutex> lock(key_upgrade_lock);
323
324 if (rename(old_name.c_str(), new_name.c_str()) != 0) return false;
325
326 // IsSameFile() doesn't work here since we just renamed @old_name.
327 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
328 if (*it == old_name) *it = new_name;
329 }
330 return true;
331}
332
Eric Biggersf74373b2020-11-05 19:58:26 -0800333// Deletes a leftover upgraded key, if present. An upgraded key can be left
334// over if an update failed, or if we rebooted before committing the key in a
335// freak accident. Either way, we can re-upgrade the key if we need to.
336static void DeleteUpgradedKey(Keymaster& keymaster, const std::string& path) {
337 if (pathExists(path)) {
338 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
339 std::string blob;
340 if (!android::base::ReadFileToString(path, &blob)) {
341 LOG(WARNING) << "Failed to read leftover upgraded key " << path
342 << "; continuing anyway";
343 } else if (!keymaster.deleteKey(blob)) {
344 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
345 << " from Keymaster; continuing anyway";
346 }
347 if (unlink(path.c_str()) != 0) {
348 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
349 << "; continuing anyway";
350 }
Daniel Rosenberg8cc57162019-06-06 20:38:38 -0700351 }
352}
353
Eric Biggersf74373b2020-11-05 19:58:26 -0800354// Begins a Keymaster operation using the key stored in |dir|.
355static KeymasterOperation BeginKeymasterOp(Keymaster& keymaster, const std::string& dir,
Eric Biggersf74373b2020-11-05 19:58:26 -0800356 const km::AuthorizationSet& keyParams,
357 const km::AuthorizationSet& opParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800358 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700359 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100360 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800361
362 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
363 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
364
365 std::lock_guard<std::mutex> lock(key_upgrade_lock);
366
367 std::string blob;
368 bool already_upgraded = IsKeyCommitPending(dir);
369 if (already_upgraded) {
370 LOG(DEBUG)
371 << blob_file
372 << " was already upgraded and is waiting to be committed; using the upgraded blob";
373 if (!readFileToString(upgraded_blob_file, &blob)) return KeymasterOperation();
374 } else {
375 DeleteUpgradedKey(keymaster, upgraded_blob_file);
376 if (!readFileToString(blob_file, &blob)) return KeymasterOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700377 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800378
Daniel Normanbe0137a2021-04-28 12:37:42 -0700379 auto opHandle = keymaster.begin(blob, inParams, outParams);
380 if (!opHandle) return opHandle;
381
382 // If key blob wasn't upgraded, nothing left to do.
383 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800384
385 if (already_upgraded) {
386 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
387 << " still requires upgrade";
388 return KeymasterOperation();
389 }
390 LOG(INFO) << "Upgrading key: " << blob_file;
Daniel Normanbe0137a2021-04-28 12:37:42 -0700391 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
392 return KeymasterOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800393 if (cp_needsCheckpoint()) {
394 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
395 << "; delaying commit due to checkpoint";
396 ScheduleKeyCommit(dir);
397 } else {
398 if (!CommitUpgradedKey(keymaster, dir)) return KeymasterOperation();
399 LOG(INFO) << "Key upgraded: " << blob_file;
400 }
Daniel Normanbe0137a2021-04-28 12:37:42 -0700401 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700402}
403
404static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700405 const km::AuthorizationSet& keyParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800406 const KeyBuffer& message, std::string* ciphertext) {
Daniel Normanbe0137a2021-04-28 12:37:42 -0700407 km::AuthorizationSet opParams =
Haiping Yangc0a46c82021-08-23 01:24:25 +0000408 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700409 km::AuthorizationSet outParams;
Daniel Normanbe0137a2021-04-28 12:37:42 -0700410 auto opHandle = BeginKeymasterOp(keymaster, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700411 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700412 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Daniel Normanbe0137a2021-04-28 12:37:42 -0700413 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700414 LOG(ERROR) << "GCM encryption but no nonce generated";
415 return false;
416 }
417 // nonceBlob here is just a pointer into existing data, must not be freed
Daniel Normanbe0137a2021-04-28 12:37:42 -0700418 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700419 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
420 std::string body;
421 if (!opHandle.updateCompletely(message, &body)) return false;
422
423 std::string mac;
424 if (!opHandle.finish(&mac)) return false;
425 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
426 *ciphertext = nonce + body + mac;
427 return true;
428}
429
430static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700431 const km::AuthorizationSet& keyParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800432 const std::string& ciphertext, KeyBuffer* message) {
Daniel Normanbe0137a2021-04-28 12:37:42 -0700433 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700434 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Daniel Normanbe0137a2021-04-28 12:37:42 -0700435 auto opParams = km::AuthorizationSetBuilder()
436 .Authorization(km::TAG_NONCE, nonce)
437 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
438 auto opHandle = BeginKeymasterOp(keymaster, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700439 if (!opHandle) return false;
440 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
441 if (!opHandle.finish(nullptr)) return false;
442 return true;
443}
444
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800445static std::string getStretching(const KeyAuthentication& auth) {
Satya Tangiralae1361712021-03-15 15:33:08 -0700446 if (auth.usesKeymaster()) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800447 return kStretch_nopassword;
448 } else {
Satya Tangiralae1361712021-03-15 15:33:08 -0700449 return kStretch_none;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800450 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000451}
452
Paul Crowleydf528a72016-03-09 09:31:37 -0800453static bool stretchSecret(const std::string& stretching, const std::string& secret,
Satya Tangirala478cea92021-04-07 14:30:25 -0700454 std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000455 if (stretching == kStretch_nopassword) {
456 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800457 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000458 // Continue anyway
459 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800460 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000461 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800462 *stretched = secret;
Paul Crowley63c18d32016-02-10 14:02:47 +0000463 } else {
464 LOG(ERROR) << "Unknown stretching type: " << stretching;
465 return false;
466 }
467 return true;
468}
469
Paul Crowleydf528a72016-03-09 09:31:37 -0800470static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Satya Tangirala478cea92021-04-07 14:30:25 -0700471 const std::string& secdiscardable_hash, std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000472 std::string stretched;
Satya Tangirala478cea92021-04-07 14:30:25 -0700473 if (!stretchSecret(stretching, auth.secret, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700474 *appId = secdiscardable_hash + stretched;
Seth Moore5a43d612021-01-19 17:51:51 +0000475
476 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
477 switch (storage_binding_info.state) {
478 case StorageBindingInfo::State::UNINITIALIZED:
479 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
480 break;
481 case StorageBindingInfo::State::IN_USE:
482 appId->append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
483 break;
484 case StorageBindingInfo::State::NOT_USED:
485 // noop
486 break;
487 }
488
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800489 return true;
490}
491
492static void logOpensslError() {
493 LOG(ERROR) << "Openssl error: " << ERR_get_error();
494}
495
Shawn Willden785365b2018-01-20 09:37:36 -0700496static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
497 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700498 std::string key;
499 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800500 key.resize(AES_KEY_BYTES);
501 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
502 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
503 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
504 if (!ctx) {
505 logOpensslError();
506 return false;
507 }
508 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700509 reinterpret_cast<const uint8_t*>(key.data()),
510 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800511 logOpensslError();
512 return false;
513 }
514 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
515 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700516 if (1 != EVP_EncryptUpdate(
517 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
518 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800519 logOpensslError();
520 return false;
521 }
522 if (outlen != static_cast<int>(plaintext.size())) {
523 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
524 return false;
525 }
Shawn Willden785365b2018-01-20 09:37:36 -0700526 if (1 != EVP_EncryptFinal_ex(
527 ctx.get(),
528 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
529 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800530 logOpensslError();
531 return false;
532 }
533 if (outlen != 0) {
534 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
535 return false;
536 }
537 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700538 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
539 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800540 logOpensslError();
541 return false;
542 }
543 return true;
544}
545
Shawn Willden785365b2018-01-20 09:37:36 -0700546static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
547 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800548 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
549 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
550 return false;
551 }
Paul Crowley26a53882017-10-26 11:16:39 -0700552 std::string key;
553 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800554 key.resize(AES_KEY_BYTES);
555 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
556 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
557 if (!ctx) {
558 logOpensslError();
559 return false;
560 }
561 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700562 reinterpret_cast<const uint8_t*>(key.data()),
563 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800564 logOpensslError();
565 return false;
566 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100567 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800568 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700569 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
570 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
571 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800572 logOpensslError();
573 return false;
574 }
575 if (outlen != static_cast<int>(plaintext->size())) {
576 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
577 return false;
578 }
579 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700580 const_cast<void*>(reinterpret_cast<const void*>(
581 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800582 logOpensslError();
583 return false;
584 }
585 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700586 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
587 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800588 logOpensslError();
589 return false;
590 }
591 if (outlen != 0) {
592 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
593 return false;
594 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000595 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000596}
597
Pavel Grafove2e2d302017-08-01 17:15:53 +0100598bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000599 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
600 PLOG(ERROR) << "key mkdir " << dir;
601 return false;
602 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800603 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700604 std::string secdiscardable_hash;
605 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800606 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800607 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800608 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700609 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800610 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800611 if (auth.usesKeymaster()) {
612 Keymaster keymaster;
613 if (!keymaster) return false;
614 std::string kmKey;
Satya Tangiralae1361712021-03-15 15:33:08 -0700615 if (!generateKeyStorageKey(keymaster, appId, &kmKey)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800616 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700617 km::AuthorizationSet keyParams = beginParams(appId);
618 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, key, &encryptedKey)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800619 } else {
620 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
621 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000622 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800623 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000624 return true;
625}
626
Paul Crowleyf71ace32016-06-02 11:01:19 -0700627bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100628 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700629 if (pathExists(key_path)) {
630 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
631 return false;
632 }
633 if (pathExists(tmp_path)) {
634 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
635 destroyKey(tmp_path); // May be partially created so ignore errors
636 }
637 if (!storeKey(tmp_path, auth, key)) return false;
Satya Tangirala9475b112021-05-13 00:43:03 -0700638
639 if (!RenameKeyDir(tmp_path, key_path)) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700640 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
641 return false;
642 }
Eric Biggers3345a2a2021-02-16 15:59:17 -0800643 if (!FsyncParentDirectory(key_path)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700644 LOG(DEBUG) << "Created key: " << key_path;
645 return true;
646}
647
Eric Biggersf74373b2020-11-05 19:58:26 -0800648bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000649 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800650 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000651 if (version != kCurrentVersion) {
652 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
653 return false;
654 }
Paul Crowley26a53882017-10-26 11:16:39 -0700655 std::string secdiscardable_hash;
656 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000657 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800658 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800659 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700660 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000661 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800662 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800663 if (auth.usesKeymaster()) {
664 Keymaster keymaster;
665 if (!keymaster) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700666 km::AuthorizationSet keyParams = beginParams(appId);
667 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, encryptedMessage, key))
Shawn Willden785365b2018-01-20 09:37:36 -0700668 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800669 } else {
670 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
671 }
672 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000673}
674
Eric Biggersf74373b2020-11-05 19:58:26 -0800675static bool DeleteKeymasterKey(const std::string& blob_file) {
676 std::string blob;
677 if (!readFileToString(blob_file, &blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000678 Keymaster keymaster;
679 if (!keymaster) return false;
Eric Biggersf74373b2020-11-05 19:58:26 -0800680 LOG(DEBUG) << "Deleting key " << blob_file << " from Keymaster";
681 if (!keymaster.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000682 return true;
683}
684
Rubin Xu2436e272017-04-27 20:43:10 +0100685bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700686 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100687 LOG(ERROR) << "secdiscard failed";
688 return false;
689 }
690 return true;
691}
692
Paul Crowleydf528a72016-03-09 09:31:37 -0800693static bool recursiveDeleteKey(const std::string& dir) {
694 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000695 LOG(ERROR) << "recursive delete failed";
696 return false;
697 }
698 return true;
699}
700
Paul Crowleydf528a72016-03-09 09:31:37 -0800701bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000702 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800703
704 CancelPendingKeyCommit(dir);
705
Paul Crowleyff19b052017-10-26 11:28:55 -0700706 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700707 kSecdiscardPath,
708 "--",
709 dir + "/" + kFn_encrypted_key,
710 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700711 };
Eric Biggersf74373b2020-11-05 19:58:26 -0800712 // Try each thing, even if previous things failed.
713
714 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
715 auto blob_file = dir + "/" + fn;
716 if (pathExists(blob_file)) {
717 success &= DeleteKeymasterKey(blob_file);
718 secdiscard_cmd.push_back(blob_file);
719 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700720 }
721 if (ForkExecvp(secdiscard_cmd) != 0) {
722 LOG(ERROR) << "secdiscard failed";
723 success = false;
724 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000725 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000726 return success;
727}
728
Seth Moore5a43d612021-01-19 17:51:51 +0000729bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
730 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
731 switch (storage_binding_info.state) {
732 case StorageBindingInfo::State::UNINITIALIZED:
733 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
734 storage_binding_info.seed = seed;
735 return true;
736 case StorageBindingInfo::State::IN_USE:
737 LOG(ERROR) << "key storage binding seed already set";
738 return false;
739 case StorageBindingInfo::State::NOT_USED:
740 LOG(ERROR) << "key storage already in use without binding";
741 return false;
742 }
743 return false;
744}
745
Paul Crowley1ef25582016-01-21 20:26:12 +0000746} // namespace vold
747} // namespace android