blob: 954ba7fd37a865bf328357a33f845f2796487485 [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 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;
Paul Crowleyb3de3372016-04-27 12:58:41 -070062
Paul Crowley05720802016-02-08 15:55:41 +000063static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000064static const char* kRmPath = "/system/bin/rm";
65static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000066static const char* kStretch_none = "none";
67static const char* kStretch_nopassword = "nopassword";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080068static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
69static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000070static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000071static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070072static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley1ef25582016-01-21 20:26:12 +000073static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000074static const char* kFn_stretching = "stretching";
75static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000076
Seth Moore5a43d612021-01-19 17:51:51 +000077namespace {
78
79// Storage binding info for ensuring key encryption keys include a
80// platform-provided seed in their derivation.
81struct StorageBindingInfo {
82 enum class State {
83 UNINITIALIZED,
84 IN_USE, // key storage keys are bound to seed
85 NOT_USED, // key storage keys are NOT bound to seed
86 };
87
88 // Binding seed mixed into all key storage keys.
89 std::vector<uint8_t> seed;
90
91 // State tracker for the key storage key binding.
92 State state = State::UNINITIALIZED;
93
94 std::mutex guard;
95};
96
97// Never freed as the dtor is non-trivial.
98StorageBindingInfo& storage_binding_info = *new StorageBindingInfo;
99
100} // namespace
101
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000102static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000103 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800104 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
105 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +0000106 return false;
107 }
108 return true;
109}
110
Paul Crowley26a53882017-10-26 11:16:39 -0700111static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000112 SHA512_CTX c;
113
114 SHA512_Init(&c);
115 // Personalise the hashing by introducing a fixed prefix.
116 // Hashing applications should use personalization except when there is a
117 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800118 std::string hashingPrefix = prefix;
119 hashingPrefix.resize(SHA512_CBLOCK);
120 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
121 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700122 res->assign(SHA512_DIGEST_LENGTH, '\0');
123 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000124}
125
Eric Biggersb2024e02021-03-15 12:44:36 -0700126// Generates a keymaster key, using rollback resistance if supported.
127static bool generateKeymasterKey(Keymaster& keymaster,
128 const km::AuthorizationSetBuilder& paramBuilder,
129 std::string* key) {
130 auto paramsWithRollback = paramBuilder;
131 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
132
133 if (!keymaster.generateKey(paramsWithRollback, key)) {
134 LOG(WARNING) << "Failed to generate rollback-resistant key. This is expected if keymaster "
135 "doesn't support rollback resistance. Falling back to "
136 "non-rollback-resistant key.";
137 if (!keymaster.generateKey(paramBuilder, key)) return false;
138 }
139 return true;
140}
141
Satya Tangiralae1361712021-03-15 15:33:08 -0700142static bool generateKeyStorageKey(Keymaster& keymaster, const std::string& appId,
143 std::string* key) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800144 auto paramBuilder = km::AuthorizationSetBuilder()
145 .AesEncryptionKey(AES_KEY_BYTES * 8)
146 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
147 .Authorization(km::TAG_APPLICATION_ID, appId)
148 .Authorization(km::TAG_NO_AUTH_REQUIRED);
Satya Tangirala6b98fb62021-05-11 19:48:47 -0700149 LOG(DEBUG) << "Generating \"key storage\" key";
Eric Biggersb2024e02021-03-15 12:44:36 -0700150 return generateKeymasterKey(keymaster, paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800151}
152
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800153bool generateWrappedStorageKey(KeyBuffer* key) {
154 Keymaster keymaster;
155 if (!keymaster) return false;
156 std::string key_temp;
157 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800158 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Eric Biggersb2024e02021-03-15 12:44:36 -0700159 if (!generateKeymasterKey(keymaster, paramBuilder, &key_temp)) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800160 *key = KeyBuffer(key_temp.size());
161 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
162 return true;
163}
164
165bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
166 Keymaster keymaster;
167 if (!keymaster) return false;
168 std::string key_temp;
169
170 if (!keymaster.exportKey(kmKey, &key_temp)) return false;
171 *key = KeyBuffer(key_temp.size());
172 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
173 return true;
174}
175
Satya Tangiralae1361712021-03-15 15:33:08 -0700176static km::AuthorizationSet beginParams(const std::string& appId) {
177 return km::AuthorizationSetBuilder()
178 .GcmModeMacLen(GCM_MAC_BYTES * 8)
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800179 .Authorization(km::TAG_APPLICATION_ID, appId);
Paul Crowley1ef25582016-01-21 20:26:12 +0000180}
181
Paul Crowleydf528a72016-03-09 09:31:37 -0800182static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800183 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800184 PLOG(ERROR) << "Failed to read from " << filename;
185 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000186 }
187 return true;
188}
189
Paul Crowley26a53882017-10-26 11:16:39 -0700190static bool readRandomBytesOrLog(size_t count, std::string* out) {
191 auto status = ReadRandomBytes(count, *out);
192 if (status != OK) {
193 LOG(ERROR) << "Random read failed with status: " << status;
194 return false;
195 }
196 return true;
197}
198
199bool createSecdiscardable(const std::string& filename, std::string* hash) {
200 std::string secdiscardable;
201 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
202 if (!writeStringToFile(secdiscardable, filename)) return false;
203 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
204 return true;
205}
206
207bool readSecdiscardable(const std::string& filename, std::string* hash) {
208 std::string secdiscardable;
209 if (!readFileToString(filename, &secdiscardable)) return false;
210 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
211 return true;
212}
213
Eric Biggersf74373b2020-11-05 19:58:26 -0800214static std::mutex key_upgrade_lock;
215
216// List of key directories that have had their Keymaster key upgraded during
217// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
218// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
219static std::vector<std::string> key_dirs_to_commit;
220
221// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
222// deletes the old key from Keymaster.
223static bool CommitUpgradedKey(Keymaster& keymaster, const std::string& dir) {
224 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
225 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
226
227 std::string blob;
228 if (!readFileToString(blob_file, &blob)) return false;
229
230 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
231 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
232 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700233 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800234 // Ensure that the rename is persisted before deleting the Keymaster key.
235 if (!FsyncDirectory(dir)) return false;
236
237 if (!keymaster || !keymaster.deleteKey(blob)) {
238 LOG(WARNING) << "Failed to delete old key " << blob_file
239 << " from Keymaster; continuing anyway";
240 // Continue on, but the space in Keymaster used by the old key won't be freed.
241 }
242 return true;
243}
244
245static void DeferredCommitKeys() {
246 android::base::WaitForProperty("vold.checkpoint_committed", "1");
247 LOG(INFO) << "Committing upgraded keys";
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700248 Keymaster keymaster;
Eric Biggersf74373b2020-11-05 19:58:26 -0800249 if (!keymaster) {
250 LOG(ERROR) << "Failed to open Keymaster; old keys won't be deleted from Keymaster";
251 // Continue on, but the space in Keymaster used by the old keys won't be freed.
252 }
253 std::lock_guard<std::mutex> lock(key_upgrade_lock);
254 for (auto& dir : key_dirs_to_commit) {
255 LOG(INFO) << "Committing upgraded key " << dir;
256 CommitUpgradedKey(keymaster, dir);
257 }
258 key_dirs_to_commit.clear();
259}
260
261// Returns true if the Keymaster key in |dir| has already been upgraded and is
262// pending being committed. Assumes that key_upgrade_lock is held.
263static bool IsKeyCommitPending(const std::string& dir) {
264 for (const auto& dir_to_commit : key_dirs_to_commit) {
265 if (IsSameFile(dir, dir_to_commit)) return true;
266 }
267 return false;
268}
269
270// Schedules the upgraded Keymaster key in |dir| to be committed later.
271// Assumes that key_upgrade_lock is held.
272static void ScheduleKeyCommit(const std::string& dir) {
273 if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
274 key_dirs_to_commit.push_back(dir);
275}
276
277static void CancelPendingKeyCommit(const std::string& dir) {
278 std::lock_guard<std::mutex> lock(key_upgrade_lock);
279 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
280 if (IsSameFile(*it, dir)) {
281 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
282 << " because it is being destroyed";
283 key_dirs_to_commit.erase(it);
284 break;
285 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700286 }
287}
288
Eric Biggersf74373b2020-11-05 19:58:26 -0800289// Deletes a leftover upgraded key, if present. An upgraded key can be left
290// over if an update failed, or if we rebooted before committing the key in a
291// freak accident. Either way, we can re-upgrade the key if we need to.
292static void DeleteUpgradedKey(Keymaster& keymaster, const std::string& path) {
293 if (pathExists(path)) {
294 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
295 std::string blob;
296 if (!android::base::ReadFileToString(path, &blob)) {
297 LOG(WARNING) << "Failed to read leftover upgraded key " << path
298 << "; continuing anyway";
299 } else if (!keymaster.deleteKey(blob)) {
300 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
301 << " from Keymaster; continuing anyway";
302 }
303 if (unlink(path.c_str()) != 0) {
304 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
305 << "; continuing anyway";
306 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700307 }
308}
309
Eric Biggersf74373b2020-11-05 19:58:26 -0800310// Begins a Keymaster operation using the key stored in |dir|.
311static KeymasterOperation BeginKeymasterOp(Keymaster& keymaster, const std::string& dir,
Eric Biggersf74373b2020-11-05 19:58:26 -0800312 const km::AuthorizationSet& keyParams,
313 const km::AuthorizationSet& opParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800314 km::AuthorizationSet* outParams) {
Shawn Willden35351812018-01-22 09:08:32 -0700315 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100316 inParams.append(opParams.begin(), opParams.end());
Eric Biggersf74373b2020-11-05 19:58:26 -0800317
318 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
319 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
320
321 std::lock_guard<std::mutex> lock(key_upgrade_lock);
322
323 std::string blob;
324 bool already_upgraded = IsKeyCommitPending(dir);
325 if (already_upgraded) {
326 LOG(DEBUG)
327 << blob_file
328 << " was already upgraded and is waiting to be committed; using the upgraded blob";
329 if (!readFileToString(upgraded_blob_file, &blob)) return KeymasterOperation();
330 } else {
331 DeleteUpgradedKey(keymaster, upgraded_blob_file);
332 if (!readFileToString(blob_file, &blob)) return KeymasterOperation();
Paul Crowleydff8c722016-05-16 08:14:56 -0700333 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800334
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800335 auto opHandle = keymaster.begin(blob, inParams, outParams);
336 if (!opHandle) return opHandle;
337
338 // If key blob wasn't upgraded, nothing left to do.
339 if (!opHandle.getUpgradedBlob()) return opHandle;
Eric Biggersf74373b2020-11-05 19:58:26 -0800340
341 if (already_upgraded) {
342 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
343 << " still requires upgrade";
344 return KeymasterOperation();
345 }
346 LOG(INFO) << "Upgrading key: " << blob_file;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800347 if (!writeStringToFile(*opHandle.getUpgradedBlob(), upgraded_blob_file))
348 return KeymasterOperation();
Eric Biggersf74373b2020-11-05 19:58:26 -0800349 if (cp_needsCheckpoint()) {
350 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
351 << "; delaying commit due to checkpoint";
352 ScheduleKeyCommit(dir);
353 } else {
354 if (!CommitUpgradedKey(keymaster, dir)) return KeymasterOperation();
355 LOG(INFO) << "Key upgraded: " << blob_file;
356 }
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800357 return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700358}
359
360static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700361 const km::AuthorizationSet& keyParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800362 const KeyBuffer& message, std::string* ciphertext) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800363 km::AuthorizationSet opParams =
364 km::AuthorizationSetBuilder().Authorization(km::TAG_PURPOSE, km::KeyPurpose::ENCRYPT);
Shawn Willden35351812018-01-22 09:08:32 -0700365 km::AuthorizationSet outParams;
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800366 auto opHandle = BeginKeymasterOp(keymaster, dir, keyParams, opParams, &outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700367 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700368 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800369 if (!nonceBlob) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700370 LOG(ERROR) << "GCM encryption but no nonce generated";
371 return false;
372 }
373 // nonceBlob here is just a pointer into existing data, must not be freed
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800374 std::string nonce(nonceBlob.value().get().begin(), nonceBlob.value().get().end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700375 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
376 std::string body;
377 if (!opHandle.updateCompletely(message, &body)) return false;
378
379 std::string mac;
380 if (!opHandle.finish(&mac)) return false;
381 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
382 *ciphertext = nonce + body + mac;
383 return true;
384}
385
386static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700387 const km::AuthorizationSet& keyParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800388 const std::string& ciphertext, KeyBuffer* message) {
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800389 const std::string nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
Paul Crowleydff8c722016-05-16 08:14:56 -0700390 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Satya Tangiralae8de4ff2021-02-28 22:32:07 -0800391 auto opParams = km::AuthorizationSetBuilder()
392 .Authorization(km::TAG_NONCE, nonce)
393 .Authorization(km::TAG_PURPOSE, km::KeyPurpose::DECRYPT);
394 auto opHandle = BeginKeymasterOp(keymaster, dir, keyParams, opParams, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700395 if (!opHandle) return false;
396 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
397 if (!opHandle.finish(nullptr)) return false;
398 return true;
399}
400
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800401static std::string getStretching(const KeyAuthentication& auth) {
Satya Tangiralae1361712021-03-15 15:33:08 -0700402 if (auth.usesKeymaster()) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800403 return kStretch_nopassword;
404 } else {
Satya Tangiralae1361712021-03-15 15:33:08 -0700405 return kStretch_none;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800406 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000407}
408
Paul Crowleydf528a72016-03-09 09:31:37 -0800409static bool stretchSecret(const std::string& stretching, const std::string& secret,
Satya Tangirala478cea92021-04-07 14:30:25 -0700410 std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000411 if (stretching == kStretch_nopassword) {
412 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800413 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000414 // Continue anyway
415 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800416 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000417 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800418 *stretched = secret;
Paul Crowley63c18d32016-02-10 14:02:47 +0000419 } else {
420 LOG(ERROR) << "Unknown stretching type: " << stretching;
421 return false;
422 }
423 return true;
424}
425
Paul Crowleydf528a72016-03-09 09:31:37 -0800426static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Satya Tangirala478cea92021-04-07 14:30:25 -0700427 const std::string& secdiscardable_hash, std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000428 std::string stretched;
Satya Tangirala478cea92021-04-07 14:30:25 -0700429 if (!stretchSecret(stretching, auth.secret, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700430 *appId = secdiscardable_hash + stretched;
Seth Moore5a43d612021-01-19 17:51:51 +0000431
432 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
433 switch (storage_binding_info.state) {
434 case StorageBindingInfo::State::UNINITIALIZED:
435 storage_binding_info.state = StorageBindingInfo::State::NOT_USED;
436 break;
437 case StorageBindingInfo::State::IN_USE:
438 appId->append(storage_binding_info.seed.begin(), storage_binding_info.seed.end());
439 break;
440 case StorageBindingInfo::State::NOT_USED:
441 // noop
442 break;
443 }
444
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800445 return true;
446}
447
448static void logOpensslError() {
449 LOG(ERROR) << "Openssl error: " << ERR_get_error();
450}
451
Shawn Willden785365b2018-01-20 09:37:36 -0700452static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
453 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700454 std::string key;
455 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800456 key.resize(AES_KEY_BYTES);
457 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
458 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
459 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
460 if (!ctx) {
461 logOpensslError();
462 return false;
463 }
464 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700465 reinterpret_cast<const uint8_t*>(key.data()),
466 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800467 logOpensslError();
468 return false;
469 }
470 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
471 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700472 if (1 != EVP_EncryptUpdate(
473 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
474 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800475 logOpensslError();
476 return false;
477 }
478 if (outlen != static_cast<int>(plaintext.size())) {
479 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
480 return false;
481 }
Shawn Willden785365b2018-01-20 09:37:36 -0700482 if (1 != EVP_EncryptFinal_ex(
483 ctx.get(),
484 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
485 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800486 logOpensslError();
487 return false;
488 }
489 if (outlen != 0) {
490 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
491 return false;
492 }
493 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700494 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
495 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800496 logOpensslError();
497 return false;
498 }
499 return true;
500}
501
Shawn Willden785365b2018-01-20 09:37:36 -0700502static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
503 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800504 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
505 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
506 return false;
507 }
Paul Crowley26a53882017-10-26 11:16:39 -0700508 std::string key;
509 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800510 key.resize(AES_KEY_BYTES);
511 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
512 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
513 if (!ctx) {
514 logOpensslError();
515 return false;
516 }
517 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700518 reinterpret_cast<const uint8_t*>(key.data()),
519 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800520 logOpensslError();
521 return false;
522 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100523 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800524 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700525 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
526 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
527 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800528 logOpensslError();
529 return false;
530 }
531 if (outlen != static_cast<int>(plaintext->size())) {
532 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
533 return false;
534 }
535 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700536 const_cast<void*>(reinterpret_cast<const void*>(
537 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800538 logOpensslError();
539 return false;
540 }
541 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700542 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
543 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800544 logOpensslError();
545 return false;
546 }
547 if (outlen != 0) {
548 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
549 return false;
550 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000551 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000552}
553
Pavel Grafove2e2d302017-08-01 17:15:53 +0100554bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000555 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
556 PLOG(ERROR) << "key mkdir " << dir;
557 return false;
558 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800559 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700560 std::string secdiscardable_hash;
561 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800562 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800563 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800564 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700565 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800566 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800567 if (auth.usesKeymaster()) {
568 Keymaster keymaster;
569 if (!keymaster) return false;
570 std::string kmKey;
Satya Tangiralae1361712021-03-15 15:33:08 -0700571 if (!generateKeyStorageKey(keymaster, appId, &kmKey)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800572 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700573 km::AuthorizationSet keyParams = beginParams(appId);
574 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, key, &encryptedKey)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800575 } else {
576 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
577 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000578 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800579 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000580 return true;
581}
582
Paul Crowleyf71ace32016-06-02 11:01:19 -0700583bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100584 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700585 if (pathExists(key_path)) {
586 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
587 return false;
588 }
589 if (pathExists(tmp_path)) {
590 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
591 destroyKey(tmp_path); // May be partially created so ignore errors
592 }
593 if (!storeKey(tmp_path, auth, key)) return false;
594 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
595 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
596 return false;
597 }
Eric Biggers3345a2a2021-02-16 15:59:17 -0800598 if (!FsyncParentDirectory(key_path)) return false;
Paul Crowleyf71ace32016-06-02 11:01:19 -0700599 LOG(DEBUG) << "Created key: " << key_path;
600 return true;
601}
602
Eric Biggersf74373b2020-11-05 19:58:26 -0800603bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000604 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800605 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000606 if (version != kCurrentVersion) {
607 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
608 return false;
609 }
Paul Crowley26a53882017-10-26 11:16:39 -0700610 std::string secdiscardable_hash;
611 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000612 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800613 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800614 std::string appId;
Satya Tangirala478cea92021-04-07 14:30:25 -0700615 if (!generateAppId(auth, stretching, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000616 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800617 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800618 if (auth.usesKeymaster()) {
619 Keymaster keymaster;
620 if (!keymaster) return false;
Satya Tangiralae1361712021-03-15 15:33:08 -0700621 km::AuthorizationSet keyParams = beginParams(appId);
622 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, encryptedMessage, key))
Shawn Willden785365b2018-01-20 09:37:36 -0700623 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800624 } else {
625 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
626 }
627 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000628}
629
Eric Biggersf74373b2020-11-05 19:58:26 -0800630static bool DeleteKeymasterKey(const std::string& blob_file) {
631 std::string blob;
632 if (!readFileToString(blob_file, &blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000633 Keymaster keymaster;
634 if (!keymaster) return false;
Eric Biggersf74373b2020-11-05 19:58:26 -0800635 LOG(DEBUG) << "Deleting key " << blob_file << " from Keymaster";
636 if (!keymaster.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000637 return true;
638}
639
Rubin Xu2436e272017-04-27 20:43:10 +0100640bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700641 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100642 LOG(ERROR) << "secdiscard failed";
643 return false;
644 }
645 return true;
646}
647
Paul Crowleydf528a72016-03-09 09:31:37 -0800648static bool recursiveDeleteKey(const std::string& dir) {
649 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000650 LOG(ERROR) << "recursive delete failed";
651 return false;
652 }
653 return true;
654}
655
Paul Crowleydf528a72016-03-09 09:31:37 -0800656bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000657 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800658
659 CancelPendingKeyCommit(dir);
660
Paul Crowleyff19b052017-10-26 11:28:55 -0700661 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700662 kSecdiscardPath,
663 "--",
664 dir + "/" + kFn_encrypted_key,
665 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700666 };
Eric Biggersf74373b2020-11-05 19:58:26 -0800667 // Try each thing, even if previous things failed.
668
669 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
670 auto blob_file = dir + "/" + fn;
671 if (pathExists(blob_file)) {
672 success &= DeleteKeymasterKey(blob_file);
673 secdiscard_cmd.push_back(blob_file);
674 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700675 }
676 if (ForkExecvp(secdiscard_cmd) != 0) {
677 LOG(ERROR) << "secdiscard failed";
678 success = false;
679 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000680 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000681 return success;
682}
683
Seth Moore5a43d612021-01-19 17:51:51 +0000684bool setKeyStorageBindingSeed(const std::vector<uint8_t>& seed) {
685 const std::lock_guard<std::mutex> scope_lock(storage_binding_info.guard);
686 switch (storage_binding_info.state) {
687 case StorageBindingInfo::State::UNINITIALIZED:
688 storage_binding_info.state = StorageBindingInfo::State::IN_USE;
689 storage_binding_info.seed = seed;
690 return true;
691 case StorageBindingInfo::State::IN_USE:
692 LOG(ERROR) << "key storage binding seed already set";
693 return false;
694 case StorageBindingInfo::State::NOT_USED:
695 LOG(ERROR) << "key storage already in use without binding";
696 return false;
697 }
698 return false;
699}
700
Paul Crowley1ef25582016-01-21 20:26:12 +0000701} // namespace vold
702} // namespace android