blob: 81478277ed39e2b48c1e73d6f3facf5c2953cae4 [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>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070025#include <thread>
Paul Crowley1ef25582016-01-21 20:26:12 +000026#include <vector>
27
28#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070029#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000030#include <sys/stat.h>
31#include <sys/types.h>
32#include <sys/wait.h>
33#include <unistd.h>
34
Paul Crowley6ab2cab2017-01-04 22:32:40 -080035#include <openssl/err.h>
36#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000037#include <openssl/sha.h>
38
39#include <android-base/file.h>
40#include <android-base/logging.h>
Daniel Rosenberga48730a2019-06-06 20:38:38 -070041#include <android-base/properties.h>
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070042#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000043
Paul Crowley63c18d32016-02-10 14:02:47 +000044#include <cutils/properties.h>
45
Paul Crowley320e5e12016-03-04 14:07:05 -080046#include <hardware/hw_auth_token.h>
Shawn Willden35f0f222020-01-16 13:21:42 -070047#include <keymasterV4_1/authorization_set.h>
48#include <keymasterV4_1/keymaster_utils.h>
Paul Crowley320e5e12016-03-04 14:07:05 -080049
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
Paul Crowleydf528a72016-03-09 09:31:37 -080058const 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
Paul Crowley13ffd8e2016-01-27 14:30:22 +000085static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000086 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080087 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
88 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000089 return false;
90 }
91 return true;
92}
93
Paul Crowley26a53882017-10-26 11:16:39 -070094static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +000095 SHA512_CTX c;
96
97 SHA512_Init(&c);
98 // Personalise the hashing by introducing a fixed prefix.
99 // Hashing applications should use personalization except when there is a
100 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800101 std::string hashingPrefix = prefix;
102 hashingPrefix.resize(SHA512_CBLOCK);
103 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
104 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700105 res->assign(SHA512_DIGEST_LENGTH, '\0');
106 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000107}
108
Paul Crowleydf528a72016-03-09 09:31:37 -0800109static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
110 const std::string& appId, std::string* key) {
Shawn Willden35351812018-01-22 09:08:32 -0700111 auto paramBuilder = km::AuthorizationSetBuilder()
Paul Crowleydf528a72016-03-09 09:31:37 -0800112 .AesEncryptionKey(AES_KEY_BYTES * 8)
Shawn Willden35351812018-01-22 09:08:32 -0700113 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
114 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800115 if (auth.token.empty()) {
116 LOG(DEBUG) << "Creating key that doesn't need auth token";
Shawn Willden35351812018-01-22 09:08:32 -0700117 paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
Paul Crowley320e5e12016-03-04 14:07:05 -0800118 } else {
119 LOG(DEBUG) << "Auth token required for key";
120 if (auth.token.size() != sizeof(hw_auth_token_t)) {
121 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
Paul Crowleydf528a72016-03-09 09:31:37 -0800122 << auth.token.size() << " bytes";
Paul Crowley320e5e12016-03-04 14:07:05 -0800123 return false;
124 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800125 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
Paul Crowleyd281de72018-08-30 15:25:19 -0700126 auto user_id = at->user_id; // Make a copy because at->user_id is unaligned.
127 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, user_id);
Shawn Willden35351812018-01-22 09:08:32 -0700128 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
129 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
Paul Crowley320e5e12016-03-04 14:07:05 -0800130 }
Shawn Willden8431fe22018-12-06 07:45:02 -0700131
132 auto paramsWithRollback = paramBuilder;
133 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
134
135 // Generate rollback-resistant key if possible.
136 return keymaster.generateKey(paramsWithRollback, key) ||
137 keymaster.generateKey(paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800138}
139
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800140bool generateWrappedStorageKey(KeyBuffer* key) {
141 Keymaster keymaster;
142 if (!keymaster) return false;
143 std::string key_temp;
144 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800145 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Gaurav Kashyap75736a82020-09-11 15:24:01 -0700146 auto paramsWithRollback = paramBuilder;
147 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
148 if (!keymaster.generateKey(paramsWithRollback, &key_temp)) {
149 if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
150 }
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800151 *key = KeyBuffer(key_temp.size());
152 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
153 return true;
154}
155
156bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
157 Keymaster keymaster;
158 if (!keymaster) return false;
159 std::string key_temp;
160
161 if (!keymaster.exportKey(kmKey, &key_temp)) return false;
162 *key = KeyBuffer(key_temp.size());
163 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
164 return true;
165}
166
Shawn Willden35351812018-01-22 09:08:32 -0700167static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
168 const KeyAuthentication& auth, const std::string& appId) {
169 auto paramBuilder = km::AuthorizationSetBuilder()
170 .GcmModeMacLen(GCM_MAC_BYTES * 8)
171 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
172 km::HardwareAuthToken authToken;
Paul Crowley320e5e12016-03-04 14:07:05 -0800173 if (!auth.token.empty()) {
174 LOG(DEBUG) << "Supplying auth token to Keymaster";
Shawn Willden35351812018-01-22 09:08:32 -0700175 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
Paul Crowley320e5e12016-03-04 14:07:05 -0800176 }
Shawn Willden35351812018-01-22 09:08:32 -0700177 return {paramBuilder, authToken};
Paul Crowley1ef25582016-01-21 20:26:12 +0000178}
179
Paul Crowleydf528a72016-03-09 09:31:37 -0800180static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800181 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800182 PLOG(ERROR) << "Failed to read from " << filename;
183 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000184 }
185 return true;
186}
187
Paul Crowley26a53882017-10-26 11:16:39 -0700188static bool readRandomBytesOrLog(size_t count, std::string* out) {
189 auto status = ReadRandomBytes(count, *out);
190 if (status != OK) {
191 LOG(ERROR) << "Random read failed with status: " << status;
192 return false;
193 }
194 return true;
195}
196
197bool createSecdiscardable(const std::string& filename, std::string* hash) {
198 std::string secdiscardable;
199 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
200 if (!writeStringToFile(secdiscardable, filename)) return false;
201 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
202 return true;
203}
204
205bool readSecdiscardable(const std::string& filename, std::string* hash) {
206 std::string secdiscardable;
207 if (!readFileToString(filename, &secdiscardable)) return false;
208 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
209 return true;
210}
211
Eric Biggersf74373b2020-11-05 19:58:26 -0800212static std::mutex key_upgrade_lock;
213
214// List of key directories that have had their Keymaster key upgraded during
215// this boot and written to "keymaster_key_blob_upgraded", but replacing the old
216// key was delayed due to an active checkpoint. Protected by key_upgrade_lock.
217static std::vector<std::string> key_dirs_to_commit;
218
219// Replaces |dir|/keymaster_key_blob with |dir|/keymaster_key_blob_upgraded and
220// deletes the old key from Keymaster.
221static bool CommitUpgradedKey(Keymaster& keymaster, const std::string& dir) {
222 auto blob_file = dir + "/" + kFn_keymaster_key_blob;
223 auto upgraded_blob_file = dir + "/" + kFn_keymaster_key_blob_upgraded;
224
225 std::string blob;
226 if (!readFileToString(blob_file, &blob)) return false;
227
228 if (rename(upgraded_blob_file.c_str(), blob_file.c_str()) != 0) {
229 PLOG(ERROR) << "Failed to rename " << upgraded_blob_file << " to " << blob_file;
230 return false;
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700231 }
Eric Biggersf74373b2020-11-05 19:58:26 -0800232 // Ensure that the rename is persisted before deleting the Keymaster key.
233 if (!FsyncDirectory(dir)) return false;
234
235 if (!keymaster || !keymaster.deleteKey(blob)) {
236 LOG(WARNING) << "Failed to delete old key " << blob_file
237 << " from Keymaster; continuing anyway";
238 // Continue on, but the space in Keymaster used by the old key won't be freed.
239 }
240 return true;
241}
242
243static void DeferredCommitKeys() {
244 android::base::WaitForProperty("vold.checkpoint_committed", "1");
245 LOG(INFO) << "Committing upgraded keys";
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700246 Keymaster keymaster;
Eric Biggersf74373b2020-11-05 19:58:26 -0800247 if (!keymaster) {
248 LOG(ERROR) << "Failed to open Keymaster; old keys won't be deleted from Keymaster";
249 // Continue on, but the space in Keymaster used by the old keys won't be freed.
250 }
251 std::lock_guard<std::mutex> lock(key_upgrade_lock);
252 for (auto& dir : key_dirs_to_commit) {
253 LOG(INFO) << "Committing upgraded key " << dir;
254 CommitUpgradedKey(keymaster, dir);
255 }
256 key_dirs_to_commit.clear();
257}
258
259// Returns true if the Keymaster key in |dir| has already been upgraded and is
260// pending being committed. Assumes that key_upgrade_lock is held.
261static bool IsKeyCommitPending(const std::string& dir) {
262 for (const auto& dir_to_commit : key_dirs_to_commit) {
263 if (IsSameFile(dir, dir_to_commit)) return true;
264 }
265 return false;
266}
267
268// Schedules the upgraded Keymaster key in |dir| to be committed later.
269// Assumes that key_upgrade_lock is held.
270static void ScheduleKeyCommit(const std::string& dir) {
271 if (key_dirs_to_commit.empty()) std::thread(DeferredCommitKeys).detach();
272 key_dirs_to_commit.push_back(dir);
273}
274
275static void CancelPendingKeyCommit(const std::string& dir) {
276 std::lock_guard<std::mutex> lock(key_upgrade_lock);
277 for (auto it = key_dirs_to_commit.begin(); it != key_dirs_to_commit.end(); it++) {
278 if (IsSameFile(*it, dir)) {
279 LOG(DEBUG) << "Cancelling pending commit of upgraded key " << dir
280 << " because it is being destroyed";
281 key_dirs_to_commit.erase(it);
282 break;
283 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700284 }
285}
286
Eric Biggersf74373b2020-11-05 19:58:26 -0800287// Deletes a leftover upgraded key, if present. An upgraded key can be left
288// over if an update failed, or if we rebooted before committing the key in a
289// freak accident. Either way, we can re-upgrade the key if we need to.
290static void DeleteUpgradedKey(Keymaster& keymaster, const std::string& path) {
291 if (pathExists(path)) {
292 LOG(DEBUG) << "Deleting leftover upgraded key " << path;
293 std::string blob;
294 if (!android::base::ReadFileToString(path, &blob)) {
295 LOG(WARNING) << "Failed to read leftover upgraded key " << path
296 << "; continuing anyway";
297 } else if (!keymaster.deleteKey(blob)) {
298 LOG(WARNING) << "Failed to delete leftover upgraded key " << path
299 << " from Keymaster; continuing anyway";
300 }
301 if (unlink(path.c_str()) != 0) {
302 LOG(WARNING) << "Failed to unlink leftover upgraded key " << path
303 << "; continuing anyway";
304 }
Daniel Rosenberga48730a2019-06-06 20:38:38 -0700305 }
306}
307
Eric Biggersf74373b2020-11-05 19:58:26 -0800308// Begins a Keymaster operation using the key stored in |dir|.
309static KeymasterOperation BeginKeymasterOp(Keymaster& keymaster, const std::string& dir,
310 km::KeyPurpose purpose,
311 const km::AuthorizationSet& keyParams,
312 const km::AuthorizationSet& opParams,
313 const km::HardwareAuthToken& authToken,
314 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
335 auto opHandle = keymaster.begin(purpose, blob, inParams, authToken, outParams);
336 if (opHandle) return opHandle;
337 if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
338
339 if (already_upgraded) {
340 LOG(ERROR) << "Unexpected case; already-upgraded key " << upgraded_blob_file
341 << " still requires upgrade";
342 return KeymasterOperation();
343 }
344 LOG(INFO) << "Upgrading key: " << blob_file;
345 if (!keymaster.upgradeKey(blob, keyParams, &blob)) return KeymasterOperation();
346 if (!writeStringToFile(blob, upgraded_blob_file)) return KeymasterOperation();
347 if (cp_needsCheckpoint()) {
348 LOG(INFO) << "Wrote upgraded key to " << upgraded_blob_file
349 << "; delaying commit due to checkpoint";
350 ScheduleKeyCommit(dir);
351 } else {
352 if (!CommitUpgradedKey(keymaster, dir)) return KeymasterOperation();
353 LOG(INFO) << "Key upgraded: " << blob_file;
354 }
355
356 return keymaster.begin(purpose, blob, inParams, authToken, outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700357}
358
359static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700360 const km::AuthorizationSet& keyParams,
Eric Biggersf74373b2020-11-05 19:58:26 -0800361 const km::HardwareAuthToken& authToken,
362 const KeyBuffer& message, std::string* ciphertext) {
Shawn Willden35351812018-01-22 09:08:32 -0700363 km::AuthorizationSet opParams;
364 km::AuthorizationSet outParams;
Eric Biggersf74373b2020-11-05 19:58:26 -0800365 auto opHandle = BeginKeymasterOp(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams,
366 authToken, &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);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100369 if (!nonceBlob.isOk()) {
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
Shawn Willden785365b2018-01-20 09:37:36 -0700374 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
375 nonceBlob.value().size());
Paul Crowleydff8c722016-05-16 08:14:56 -0700376 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
377 std::string body;
378 if (!opHandle.updateCompletely(message, &body)) return false;
379
380 std::string mac;
381 if (!opHandle.finish(&mac)) return false;
382 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
383 *ciphertext = nonce + body + mac;
384 return true;
385}
386
387static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700388 const km::AuthorizationSet& keyParams,
389 const km::HardwareAuthToken& authToken,
Eric Biggersf74373b2020-11-05 19:58:26 -0800390 const std::string& ciphertext, KeyBuffer* message) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700391 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
392 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Shawn Willden35351812018-01-22 09:08:32 -0700393 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
394 km::support::blob2hidlVec(nonce));
Eric Biggersf74373b2020-11-05 19:58:26 -0800395 auto opHandle = BeginKeymasterOp(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams,
396 authToken, nullptr);
Paul Crowleydff8c722016-05-16 08:14:56 -0700397 if (!opHandle) return false;
398 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
399 if (!opHandle.finish(nullptr)) return false;
400 return true;
401}
402
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800403static std::string getStretching(const KeyAuthentication& auth) {
404 if (!auth.usesKeymaster()) {
405 return kStretch_none;
406 } else if (auth.secret.empty()) {
407 return kStretch_nopassword;
408 } else {
409 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000410
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800411 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
412 return std::string() + kStretchPrefix_scrypt + paramstr;
413 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000414}
415
Paul Crowleydf528a72016-03-09 09:31:37 -0800416static bool stretchingNeedsSalt(const std::string& stretching) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000417 return stretching != kStretch_nopassword && stretching != kStretch_none;
418}
419
Paul Crowleydf528a72016-03-09 09:31:37 -0800420static bool stretchSecret(const std::string& stretching, const std::string& secret,
421 const std::string& salt, std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000422 if (stretching == kStretch_nopassword) {
423 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800424 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000425 // Continue anyway
426 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800427 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000428 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800429 *stretched = secret;
Paul Crowleydf528a72016-03-09 09:31:37 -0800430 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
431 stretching.begin())) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000432 int Nf, rf, pf;
Paul Crowleydf528a72016-03-09 09:31:37 -0800433 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
434 &rf, &pf)) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000435 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
436 return false;
437 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800438 stretched->assign(STRETCHED_BYTES, '\0');
Paul Crowleydf528a72016-03-09 09:31:37 -0800439 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
Shawn Willden785365b2018-01-20 09:37:36 -0700440 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
441 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
442 stretched->size()) != 0) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000443 LOG(ERROR) << "scrypt failed with params: " << stretching;
444 return false;
445 }
446 } else {
447 LOG(ERROR) << "Unknown stretching type: " << stretching;
448 return false;
449 }
450 return true;
451}
452
Paul Crowleydf528a72016-03-09 09:31:37 -0800453static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Paul Crowley26a53882017-10-26 11:16:39 -0700454 const std::string& salt, const std::string& secdiscardable_hash,
Paul Crowleydf528a72016-03-09 09:31:37 -0800455 std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000456 std::string stretched;
Paul Crowleya051eb72016-03-08 16:08:32 -0800457 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700458 *appId = secdiscardable_hash + stretched;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800459 return true;
460}
461
462static void logOpensslError() {
463 LOG(ERROR) << "Openssl error: " << ERR_get_error();
464}
465
Shawn Willden785365b2018-01-20 09:37:36 -0700466static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
467 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700468 std::string key;
469 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800470 key.resize(AES_KEY_BYTES);
471 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
472 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
473 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
474 if (!ctx) {
475 logOpensslError();
476 return false;
477 }
478 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700479 reinterpret_cast<const uint8_t*>(key.data()),
480 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800481 logOpensslError();
482 return false;
483 }
484 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
485 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700486 if (1 != EVP_EncryptUpdate(
487 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
488 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800489 logOpensslError();
490 return false;
491 }
492 if (outlen != static_cast<int>(plaintext.size())) {
493 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
494 return false;
495 }
Shawn Willden785365b2018-01-20 09:37:36 -0700496 if (1 != EVP_EncryptFinal_ex(
497 ctx.get(),
498 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
499 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800500 logOpensslError();
501 return false;
502 }
503 if (outlen != 0) {
504 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
505 return false;
506 }
507 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700508 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
509 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800510 logOpensslError();
511 return false;
512 }
513 return true;
514}
515
Shawn Willden785365b2018-01-20 09:37:36 -0700516static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
517 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800518 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
519 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
520 return false;
521 }
Paul Crowley26a53882017-10-26 11:16:39 -0700522 std::string key;
523 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800524 key.resize(AES_KEY_BYTES);
525 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
526 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
527 if (!ctx) {
528 logOpensslError();
529 return false;
530 }
531 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700532 reinterpret_cast<const uint8_t*>(key.data()),
533 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800534 logOpensslError();
535 return false;
536 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100537 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800538 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700539 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
540 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
541 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800542 logOpensslError();
543 return false;
544 }
545 if (outlen != static_cast<int>(plaintext->size())) {
546 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
547 return false;
548 }
549 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700550 const_cast<void*>(reinterpret_cast<const void*>(
551 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800552 logOpensslError();
553 return false;
554 }
555 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700556 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
557 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800558 logOpensslError();
559 return false;
560 }
561 if (outlen != 0) {
562 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
563 return false;
564 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000565 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000566}
567
Paul Crowleyf71ace32016-06-02 11:01:19 -0700568bool pathExists(const std::string& path) {
569 return access(path.c_str(), F_OK) == 0;
570}
571
Pavel Grafove2e2d302017-08-01 17:15:53 +0100572bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000573 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
574 PLOG(ERROR) << "key mkdir " << dir;
575 return false;
576 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800577 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700578 std::string secdiscardable_hash;
579 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800580 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800581 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000582 std::string salt;
583 if (stretchingNeedsSalt(stretching)) {
584 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
585 LOG(ERROR) << "Random read failed";
586 return false;
587 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800588 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000589 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800590 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700591 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800592 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800593 if (auth.usesKeymaster()) {
594 Keymaster keymaster;
595 if (!keymaster) return false;
596 std::string kmKey;
597 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
598 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700599 km::AuthorizationSet keyParams;
600 km::HardwareAuthToken authToken;
601 std::tie(keyParams, authToken) = beginParams(auth, appId);
Eric Biggersf74373b2020-11-05 19:58:26 -0800602 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey))
Shawn Willden35351812018-01-22 09:08:32 -0700603 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800604 } else {
605 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
606 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000607 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800608 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000609 return true;
610}
611
Paul Crowleyf71ace32016-06-02 11:01:19 -0700612bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100613 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700614 if (pathExists(key_path)) {
615 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
616 return false;
617 }
618 if (pathExists(tmp_path)) {
619 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
620 destroyKey(tmp_path); // May be partially created so ignore errors
621 }
622 if (!storeKey(tmp_path, auth, key)) return false;
623 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
624 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
625 return false;
626 }
627 LOG(DEBUG) << "Created key: " << key_path;
628 return true;
629}
630
Eric Biggersf74373b2020-11-05 19:58:26 -0800631bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
Paul Crowley05720802016-02-08 15:55:41 +0000632 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800633 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000634 if (version != kCurrentVersion) {
635 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
636 return false;
637 }
Paul Crowley26a53882017-10-26 11:16:39 -0700638 std::string secdiscardable_hash;
639 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000640 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800641 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000642 std::string salt;
643 if (stretchingNeedsSalt(stretching)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800644 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000645 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800646 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700647 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000648 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800649 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800650 if (auth.usesKeymaster()) {
651 Keymaster keymaster;
652 if (!keymaster) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700653 km::AuthorizationSet keyParams;
654 km::HardwareAuthToken authToken;
655 std::tie(keyParams, authToken) = beginParams(auth, appId);
Eric Biggersf74373b2020-11-05 19:58:26 -0800656 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key))
Shawn Willden785365b2018-01-20 09:37:36 -0700657 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800658 } else {
659 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
660 }
661 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000662}
663
Eric Biggersf74373b2020-11-05 19:58:26 -0800664static bool DeleteKeymasterKey(const std::string& blob_file) {
665 std::string blob;
666 if (!readFileToString(blob_file, &blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000667 Keymaster keymaster;
668 if (!keymaster) return false;
Eric Biggersf74373b2020-11-05 19:58:26 -0800669 LOG(DEBUG) << "Deleting key " << blob_file << " from Keymaster";
670 if (!keymaster.deleteKey(blob)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000671 return true;
672}
673
Rubin Xu2436e272017-04-27 20:43:10 +0100674bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700675 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100676 LOG(ERROR) << "secdiscard failed";
677 return false;
678 }
679 return true;
680}
681
Paul Crowleydf528a72016-03-09 09:31:37 -0800682static bool recursiveDeleteKey(const std::string& dir) {
683 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000684 LOG(ERROR) << "recursive delete failed";
685 return false;
686 }
687 return true;
688}
689
Paul Crowleydf528a72016-03-09 09:31:37 -0800690bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000691 bool success = true;
Eric Biggersf74373b2020-11-05 19:58:26 -0800692
693 CancelPendingKeyCommit(dir);
694
Paul Crowleyff19b052017-10-26 11:28:55 -0700695 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700696 kSecdiscardPath,
697 "--",
698 dir + "/" + kFn_encrypted_key,
699 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700700 };
Eric Biggersf74373b2020-11-05 19:58:26 -0800701 // Try each thing, even if previous things failed.
702
703 for (auto& fn : {kFn_keymaster_key_blob, kFn_keymaster_key_blob_upgraded}) {
704 auto blob_file = dir + "/" + fn;
705 if (pathExists(blob_file)) {
706 success &= DeleteKeymasterKey(blob_file);
707 secdiscard_cmd.push_back(blob_file);
708 }
Paul Crowleyff19b052017-10-26 11:28:55 -0700709 }
710 if (ForkExecvp(secdiscard_cmd) != 0) {
711 LOG(ERROR) << "secdiscard failed";
712 success = false;
713 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000714 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000715 return success;
716}
717
718} // namespace vold
719} // namespace android