blob: 83800ce57d90aa6333082508b9b1787e505ca9d9 [file] [log] [blame]
bigbiff7ba75002020-04-11 20:47:09 -04001/*
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
bigbiffa957f072021-03-07 18:20:29 -050019#include "Checkpoint.h"
bigbiff7ba75002020-04-11 20:47:09 -040020#include "Keymaster.h"
21#include "ScryptParameters.h"
22#include "Utils.h"
bigbiff7ba75002020-04-11 20:47:09 -040023
24#include <thread>
25#include <vector>
26
27#include <errno.h>
28#include <stdio.h>
29#include <sys/stat.h>
30#include <sys/types.h>
31#include <sys/wait.h>
32#include <unistd.h>
33
34#include <openssl/err.h>
35#include <openssl/evp.h>
36#include <openssl/sha.h>
37
38#include <android-base/file.h>
39#include <android-base/logging.h>
bigbiff7ba75002020-04-11 20:47:09 -040040#include <android-base/properties.h>
bigbiffa957f072021-03-07 18:20:29 -050041#include <android-base/unique_fd.h>
bigbiff7ba75002020-04-11 20:47:09 -040042
43#include <cutils/properties.h>
44
45#include <hardware/hw_auth_token.h>
bigbiffa957f072021-03-07 18:20:29 -050046#include <keymasterV4_1/authorization_set.h>
47#include <keymasterV4_1/keymaster_utils.h>
bigbiff7ba75002020-04-11 20:47:09 -040048
49extern "C" {
50
51#include "crypto_scrypt.h"
52}
53
bigbiff7ba75002020-04-11 20:47:09 -040054const KeyAuthentication kEmptyAuthentication{"", ""};
55
56static constexpr size_t AES_KEY_BYTES = 32;
57static constexpr size_t GCM_NONCE_BYTES = 12;
58static constexpr size_t GCM_MAC_BYTES = 16;
59static constexpr size_t SALT_BYTES = 1 << 4;
60static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
61static constexpr size_t STRETCHED_BYTES = 1 << 6;
62
63static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
64
65static const char* kCurrentVersion = "1";
66static const char* kRmPath = "/system/bin/rm";
67static const char* kSecdiscardPath = "/system/bin/secdiscard";
68static const char* kStretch_none = "none";
69static const char* kStretch_nopassword = "nopassword";
70static const std::string kStretchPrefix_scrypt = "scrypt ";
71static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
72static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
73static const char* kFn_encrypted_key = "encrypted_key";
74static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
75static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
76static const char* kFn_salt = "salt";
77static const char* kFn_secdiscardable = "secdiscardable";
78static const char* kFn_stretching = "stretching";
79static const char* kFn_version = "version";
80
81static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
82 if (actual != expected) {
83 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
84 << actual;
85 return false;
86 }
87 return true;
88}
89
90static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
91 SHA512_CTX c;
92
93 SHA512_Init(&c);
94 // Personalise the hashing by introducing a fixed prefix.
95 // Hashing applications should use personalization except when there is a
96 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
97 std::string hashingPrefix = prefix;
98 hashingPrefix.resize(SHA512_CBLOCK);
99 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
100 SHA512_Update(&c, tohash.data(), tohash.size());
101 res->assign(SHA512_DIGEST_LENGTH, '\0');
102 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
103}
104
105static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
106 const std::string& appId, std::string* key) {
107 auto paramBuilder = km::AuthorizationSetBuilder()
108 .AesEncryptionKey(AES_KEY_BYTES * 8)
109 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
110 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
111 if (auth.token.empty()) {
112 LOG(DEBUG) << "Creating key that doesn't need auth token";
113 paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
114 } else {
115 LOG(DEBUG) << "Auth token required for key";
116 if (auth.token.size() != sizeof(hw_auth_token_t)) {
117 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
118 << auth.token.size() << " bytes";
119 return false;
120 }
121 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
bigbiffa957f072021-03-07 18:20:29 -0500122 auto user_id = at->user_id; // Make a copy because at->user_id is unaligned.
123 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400124 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
125 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
126 }
bigbiffa957f072021-03-07 18:20:29 -0500127
128 auto paramsWithRollback = paramBuilder;
129 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
130
131 // Generate rollback-resistant key if possible.
132 return keymaster.generateKey(paramsWithRollback, key) ||
133 keymaster.generateKey(paramBuilder, key);
bigbiff7ba75002020-04-11 20:47:09 -0400134}
135
bigbiffa957f072021-03-07 18:20:29 -0500136bool generateWrappedStorageKey(KeyBuffer* key) {
mauronofrio matarrese79820322020-05-25 19:48:56 +0200137 Keymaster keymaster;
138 if (!keymaster) return false;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200139 std::string key_temp;
bigbiffa957f072021-03-07 18:20:29 -0500140 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
141 paramBuilder.Authorization(km::TAG_ROLLBACK_RESISTANCE);
142 paramBuilder.Authorization(km::TAG_STORAGE_KEY);
mauronofrio matarrese79820322020-05-25 19:48:56 +0200143 if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
144 *key = KeyBuffer(key_temp.size());
145 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
146 return true;
147}
148
bigbiffa957f072021-03-07 18:20:29 -0500149bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
mauronofrio matarrese79820322020-05-25 19:48:56 +0200150 Keymaster keymaster;
151 if (!keymaster) return false;
bigbiffa957f072021-03-07 18:20:29 -0500152 std::string key_temp;
mauronofrio matarresebd79db42020-05-25 20:18:52 +0200153
bigbiffbbbfe172021-05-30 15:52:41 -0400154 auto ret = keymaster.exportKey(kmKey, &key_temp);
155 if (ret != km::ErrorCode::OK) {
156 if (ret == km::ErrorCode::KEY_REQUIRES_UPGRADE) {
157 std::string kmKeyStr(reinterpret_cast<const char*>(kmKey.data()), kmKey.size());
158 std::string Keystr;
159 if (!keymaster.upgradeKey(kmKeyStr, km::AuthorizationSet(), &Keystr)) return false;
160 KeyBuffer upgradedKey = KeyBuffer(Keystr.size());
161 memcpy(reinterpret_cast<void*>(upgradedKey.data()), Keystr.c_str(), upgradedKey.size());
162 ret = keymaster.exportKey(upgradedKey, &key_temp);
163 if (ret != km::ErrorCode::OK) return false;
164 } else {
165 return false;
166 }
167 } *key = KeyBuffer(key_temp.size());
bigbiffa957f072021-03-07 18:20:29 -0500168 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
169 return true;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200170}
171
bigbiff7ba75002020-04-11 20:47:09 -0400172static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
173 const KeyAuthentication& auth, const std::string& appId) {
174 auto paramBuilder = km::AuthorizationSetBuilder()
175 .GcmModeMacLen(GCM_MAC_BYTES * 8)
176 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
177 km::HardwareAuthToken authToken;
178 if (!auth.token.empty()) {
bigbiffbbbfe172021-05-30 15:52:41 -0400179 LOG(INFO) << "Supplying auth token to Keymaster";
bigbiff7ba75002020-04-11 20:47:09 -0400180 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
181 }
182 return {paramBuilder, authToken};
183}
184
185static bool readFileToString(const std::string& filename, std::string* result) {
186 if (!android::base::ReadFileToString(filename, result)) {
187 PLOG(ERROR) << "Failed to read from " << filename;
188 return false;
189 }
190 return true;
191}
192
193static bool readRandomBytesOrLog(size_t count, std::string* out) {
194 auto status = ReadRandomBytes(count, *out);
bigbiffa957f072021-03-07 18:20:29 -0500195 if (status != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400196 LOG(ERROR) << "Random read failed with status: " << status;
197 return false;
198 }
199 return true;
200}
201
202bool createSecdiscardable(const std::string& filename, std::string* hash) {
203 std::string secdiscardable;
204 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
205 if (!writeStringToFile(secdiscardable, filename)) return false;
206 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
207 return true;
208}
209
210bool readSecdiscardable(const std::string& filename, std::string* hash) {
211 std::string secdiscardable;
212 if (!readFileToString(filename, &secdiscardable)) return false;
213 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
214 return true;
215}
216
bigbiffa957f072021-03-07 18:20:29 -0500217static void deferedKmDeleteKey(const std::string& kmkey) {
218 while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
219 LOG(ERROR) << "Wait for boot timed out";
220 }
221 Keymaster keymaster;
222 if (!keymaster || !keymaster.deleteKey(kmkey)) {
223 LOG(ERROR) << "Defered Key deletion failed during upgrade";
224 }
225}
bigbiff7ba75002020-04-11 20:47:09 -0400226
227bool kmDeleteKey(Keymaster& keymaster, const std::string& kmKey) {
bigbiffa957f072021-03-07 18:20:29 -0500228 bool needs_cp = cp_needsCheckpoint();
bigbiff7ba75002020-04-11 20:47:09 -0400229
bigbiffa957f072021-03-07 18:20:29 -0500230 if (needs_cp) {
231 std::thread(deferedKmDeleteKey, kmKey).detach();
232 LOG(INFO) << "Deferring Key deletion during upgrade";
233 return true;
234 } else {
235 return keymaster.deleteKey(kmKey);
236 }
bigbiff7ba75002020-04-11 20:47:09 -0400237}
238
239static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
240 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
241 const km::AuthorizationSet& opParams,
242 const km::HardwareAuthToken& authToken,
243 km::AuthorizationSet* outParams, bool keepOld) {
244 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
245 std::string kmKey;
246 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
247 km::AuthorizationSet inParams(keyParams);
248 inParams.append(opParams.begin(), opParams.end());
249 for (;;) {
250 auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
251 if (opHandle) {
252 return opHandle;
253 }
254 if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
255 LOG(DEBUG) << "Upgrading key: " << dir;
256 std::string newKey;
257 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
bigbiffbbbfe172021-05-30 15:52:41 -0400258 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
259 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
260 if (!keepOld) {
261 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
262 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
263 return KeymasterOperation();
264 }
265 if (!::FsyncDirectory(dir)) {
266 LOG(ERROR) << "Key dir sync failed: " << dir;
267 return KeymasterOperation();
268 }
269 if (!kmDeleteKey(keymaster, kmKey)) {
270 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
271 }
272 }
bigbiff7ba75002020-04-11 20:47:09 -0400273 kmKey = newKey;
bigbiffa957f072021-03-07 18:20:29 -0500274 LOG(INFO) << "Key upgraded: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400275 }
276}
277
278static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
279 const km::AuthorizationSet& keyParams,
280 const km::HardwareAuthToken& authToken, const KeyBuffer& message,
281 std::string* ciphertext, bool keepOld) {
282 km::AuthorizationSet opParams;
283 km::AuthorizationSet outParams;
284 auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
285 &outParams, keepOld);
286 if (!opHandle) return false;
287 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
288 if (!nonceBlob.isOk()) {
289 LOG(ERROR) << "GCM encryption but no nonce generated";
290 return false;
291 }
292 // nonceBlob here is just a pointer into existing data, must not be freed
293 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
294 nonceBlob.value().size());
295 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
296 std::string body;
297 if (!opHandle.updateCompletely(message, &body)) return false;
298
299 std::string mac;
300 if (!opHandle.finish(&mac)) return false;
301 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
302 *ciphertext = nonce + body + mac;
303 return true;
304}
305
306static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
307 const km::AuthorizationSet& keyParams,
308 const km::HardwareAuthToken& authToken,
309 const std::string& ciphertext, KeyBuffer* message,
310 bool keepOld) {
311 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
312 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
313 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
314 km::support::blob2hidlVec(nonce));
315 auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
316 nullptr, keepOld);
317 if (!opHandle) return false;
318 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
319 if (!opHandle.finish(nullptr)) return false;
320 return true;
321}
322
323static std::string getStretching(const KeyAuthentication& auth) {
324 if (!auth.usesKeymaster()) {
325 return kStretch_none;
326 } else if (auth.secret.empty()) {
327 return kStretch_nopassword;
328 } else {
329 char paramstr[PROPERTY_VALUE_MAX];
330
331 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
332 return std::string() + kStretchPrefix_scrypt + paramstr;
333 }
334}
335
336static bool stretchingNeedsSalt(const std::string& stretching) {
337 return stretching != kStretch_nopassword && stretching != kStretch_none;
338}
339
340static bool stretchSecret(const std::string& stretching, const std::string& secret,
341 const std::string& salt, std::string* stretched) {
342 if (stretching == kStretch_nopassword) {
343 if (!secret.empty()) {
344 LOG(WARNING) << "Password present but stretching is nopassword";
345 // Continue anyway
346 }
347 stretched->clear();
348 } else if (stretching == kStretch_none) {
349 *stretched = secret;
350 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
351 stretching.begin())) {
352 int Nf, rf, pf;
353 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
354 &rf, &pf)) {
355 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
356 return false;
357 }
358 stretched->assign(STRETCHED_BYTES, '\0');
359 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
360 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
361 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
362 stretched->size()) != 0) {
363 LOG(ERROR) << "scrypt failed with params: " << stretching;
364 return false;
365 }
366 } else {
367 LOG(ERROR) << "Unknown stretching type: " << stretching;
368 return false;
369 }
370 return true;
371}
372
373static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
374 const std::string& salt, const std::string& secdiscardable_hash,
375 std::string* appId) {
376 std::string stretched;
377 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
378 *appId = secdiscardable_hash + stretched;
379 return true;
380}
381
382static void logOpensslError() {
383 LOG(ERROR) << "Openssl error: " << ERR_get_error();
384}
385
386static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
387 std::string* ciphertext) {
388 std::string key;
389 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
390 key.resize(AES_KEY_BYTES);
391 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
392 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
393 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
394 if (!ctx) {
395 logOpensslError();
396 return false;
397 }
398 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
399 reinterpret_cast<const uint8_t*>(key.data()),
400 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
401 logOpensslError();
402 return false;
403 }
404 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
405 int outlen;
406 if (1 != EVP_EncryptUpdate(
407 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
408 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
409 logOpensslError();
410 return false;
411 }
412 if (outlen != static_cast<int>(plaintext.size())) {
413 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
414 return false;
415 }
416 if (1 != EVP_EncryptFinal_ex(
417 ctx.get(),
418 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
419 &outlen)) {
420 logOpensslError();
421 return false;
422 }
423 if (outlen != 0) {
424 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
425 return false;
426 }
427 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
428 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
429 plaintext.size()))) {
430 logOpensslError();
431 return false;
432 }
433 return true;
434}
435
436static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
437 KeyBuffer* plaintext) {
438 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
439 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
440 return false;
441 }
442 std::string key;
443 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
444 key.resize(AES_KEY_BYTES);
445 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
446 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
447 if (!ctx) {
448 logOpensslError();
449 return false;
450 }
451 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
452 reinterpret_cast<const uint8_t*>(key.data()),
453 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
454 logOpensslError();
455 return false;
456 }
457 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
458 int outlen;
459 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
460 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
461 plaintext->size())) {
462 logOpensslError();
463 return false;
464 }
465 if (outlen != static_cast<int>(plaintext->size())) {
466 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
467 return false;
468 }
469 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
470 const_cast<void*>(reinterpret_cast<const void*>(
471 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
472 logOpensslError();
473 return false;
474 }
475 if (1 != EVP_DecryptFinal_ex(ctx.get(),
476 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
477 &outlen)) {
478 logOpensslError();
479 return false;
480 }
481 if (outlen != 0) {
482 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
483 return false;
484 }
485 return true;
486}
487
488bool pathExists(const std::string& path) {
489 return access(path.c_str(), F_OK) == 0;
490}
491
492bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
493 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
494 PLOG(ERROR) << "key mkdir " << dir;
495 return false;
496 }
497 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
498 std::string secdiscardable_hash;
499 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
500 std::string stretching = getStretching(auth);
501 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
502 std::string salt;
503 if (stretchingNeedsSalt(stretching)) {
bigbiffa957f072021-03-07 18:20:29 -0500504 if (ReadRandomBytes(SALT_BYTES, salt) != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400505 LOG(ERROR) << "Random read failed";
506 return false;
507 }
508 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
509 }
510 std::string appId;
511 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
512 std::string encryptedKey;
513 if (auth.usesKeymaster()) {
514 Keymaster keymaster;
515 if (!keymaster) return false;
516 std::string kmKey;
517 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
518 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
519 km::AuthorizationSet keyParams;
520 km::HardwareAuthToken authToken;
521 std::tie(keyParams, authToken) = beginParams(auth, appId);
522 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
523 false))
524 return false;
525 } else {
526 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
527 }
528 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
529 if (!FsyncDirectory(dir)) return false;
530 return true;
531}
532
533bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
534 const KeyAuthentication& auth, const KeyBuffer& key) {
535 if (pathExists(key_path)) {
536 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
537 return false;
538 }
539 if (pathExists(tmp_path)) {
540 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
541 destroyKey(tmp_path); // May be partially created so ignore errors
542 }
bigbiffa957f072021-03-07 18:20:29 -0500543 if (!::storeKey(tmp_path, auth, key)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400544 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
545 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
546 return false;
547 }
548 LOG(DEBUG) << "Created key: " << key_path;
549 return true;
550}
551
552bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
553 bool keepOld) {
554 std::string version;
555 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
556 if (version != kCurrentVersion) {
557 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
558 return false;
559 }
560 std::string secdiscardable_hash;
561 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
562 std::string stretching;
563 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
564 std::string salt;
565 if (stretchingNeedsSalt(stretching)) {
566 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
567 }
568 std::string appId;
569 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
570 std::string encryptedMessage;
571 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
572 if (auth.usesKeymaster()) {
573 Keymaster keymaster;
574 if (!keymaster) return false;
575 km::AuthorizationSet keyParams;
576 km::HardwareAuthToken authToken;
577 std::tie(keyParams, authToken) = beginParams(auth, appId);
578 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
579 keepOld))
580 return false;
581 } else {
582 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
583 }
584 return true;
585}
586
587static bool deleteKey(const std::string& dir) {
588 std::string kmKey;
589 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
590 Keymaster keymaster;
591 if (!keymaster) return false;
592 if (!keymaster.deleteKey(kmKey)) return false;
593 return true;
594}
595
596bool runSecdiscardSingle(const std::string& file) {
597 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
598 LOG(ERROR) << "secdiscard failed";
599 return false;
600 }
601 return true;
602}
603
604static bool recursiveDeleteKey(const std::string& dir) {
605 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
606 LOG(ERROR) << "recursive delete failed";
607 return false;
608 }
609 return true;
610}
611
612bool destroyKey(const std::string& dir) {
613 bool success = true;
614 // Try each thing, even if previous things failed.
615 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
616 if (uses_km) {
617 success &= deleteKey(dir);
618 }
619 auto secdiscard_cmd = std::vector<std::string>{
620 kSecdiscardPath,
621 "--",
622 dir + "/" + kFn_encrypted_key,
623 dir + "/" + kFn_secdiscardable,
624 };
625 if (uses_km) {
626 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
627 }
628 if (ForkExecvp(secdiscard_cmd) != 0) {
629 LOG(ERROR) << "secdiscard failed";
630 success = false;
631 }
632 success &= recursiveDeleteKey(dir);
633 return success;
634}