blob: 8afc57929c99962eec76d55e2219dae186dbec37 [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
zhenyolkae46d6962021-11-08 19:09:16 +030065static const std::string kPkmBlob("pKMblob\x00", 8);
66
bigbiff7ba75002020-04-11 20:47:09 -040067static const char* kCurrentVersion = "1";
68static const char* kRmPath = "/system/bin/rm";
69static const char* kSecdiscardPath = "/system/bin/secdiscard";
70static const char* kStretch_none = "none";
71static const char* kStretch_nopassword = "nopassword";
72static const std::string kStretchPrefix_scrypt = "scrypt ";
73static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
74static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
75static const char* kFn_encrypted_key = "encrypted_key";
76static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
77static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
78static const char* kFn_salt = "salt";
79static const char* kFn_secdiscardable = "secdiscardable";
80static const char* kFn_stretching = "stretching";
81static const char* kFn_version = "version";
82
83static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
84 if (actual != expected) {
85 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
86 << actual;
87 return false;
88 }
89 return true;
90}
91
92static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
93 SHA512_CTX c;
94
95 SHA512_Init(&c);
96 // Personalise the hashing by introducing a fixed prefix.
97 // Hashing applications should use personalization except when there is a
98 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
99 std::string hashingPrefix = prefix;
100 hashingPrefix.resize(SHA512_CBLOCK);
101 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
102 SHA512_Update(&c, tohash.data(), tohash.size());
103 res->assign(SHA512_DIGEST_LENGTH, '\0');
104 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
105}
106
107static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
108 const std::string& appId, std::string* key) {
109 auto paramBuilder = km::AuthorizationSetBuilder()
110 .AesEncryptionKey(AES_KEY_BYTES * 8)
111 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
112 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
113 if (auth.token.empty()) {
114 LOG(DEBUG) << "Creating key that doesn't need auth token";
115 paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
116 } else {
117 LOG(DEBUG) << "Auth token required for key";
118 if (auth.token.size() != sizeof(hw_auth_token_t)) {
119 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
120 << auth.token.size() << " bytes";
121 return false;
122 }
123 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
bigbiffa957f072021-03-07 18:20:29 -0500124 auto user_id = at->user_id; // Make a copy because at->user_id is unaligned.
125 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, user_id);
bigbiff7ba75002020-04-11 20:47:09 -0400126 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
127 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
128 }
bigbiffa957f072021-03-07 18:20:29 -0500129
130 auto paramsWithRollback = paramBuilder;
131 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
132
133 // Generate rollback-resistant key if possible.
134 return keymaster.generateKey(paramsWithRollback, key) ||
135 keymaster.generateKey(paramBuilder, key);
bigbiff7ba75002020-04-11 20:47:09 -0400136}
137
bigbiffa957f072021-03-07 18:20:29 -0500138bool generateWrappedStorageKey(KeyBuffer* key) {
mauronofrio matarrese79820322020-05-25 19:48:56 +0200139 Keymaster keymaster;
140 if (!keymaster) return false;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200141 std::string key_temp;
bigbiffa957f072021-03-07 18:20:29 -0500142 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
bigbiffbcd23d32021-09-22 18:22:13 -0400143 km::KeyParameter param1;
144 param1.tag = static_cast<::android::hardware::keymaster::V4_0::Tag>(
145 android::hardware::keymaster::V4_0::KM_TAG_FBE_ICE);
146 param1.f.boolValue = true;
147 paramBuilder.push_back(param1);
mauronofrio matarrese79820322020-05-25 19:48:56 +0200148 if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
149 *key = KeyBuffer(key_temp.size());
150 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
151 return true;
152}
153
bigbiffa957f072021-03-07 18:20:29 -0500154bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
mauronofrio matarrese79820322020-05-25 19:48:56 +0200155 Keymaster keymaster;
156 if (!keymaster) return false;
bigbiffa957f072021-03-07 18:20:29 -0500157 std::string key_temp;
mauronofrio matarresebd79db42020-05-25 20:18:52 +0200158
bigbiffbbbfe172021-05-30 15:52:41 -0400159 auto ret = keymaster.exportKey(kmKey, &key_temp);
160 if (ret != km::ErrorCode::OK) {
161 if (ret == km::ErrorCode::KEY_REQUIRES_UPGRADE) {
162 std::string kmKeyStr(reinterpret_cast<const char*>(kmKey.data()), kmKey.size());
163 std::string Keystr;
164 if (!keymaster.upgradeKey(kmKeyStr, km::AuthorizationSet(), &Keystr)) return false;
165 KeyBuffer upgradedKey = KeyBuffer(Keystr.size());
166 memcpy(reinterpret_cast<void*>(upgradedKey.data()), Keystr.c_str(), upgradedKey.size());
167 ret = keymaster.exportKey(upgradedKey, &key_temp);
168 if (ret != km::ErrorCode::OK) return false;
169 } else {
170 return false;
171 }
172 } *key = KeyBuffer(key_temp.size());
bigbiffa957f072021-03-07 18:20:29 -0500173 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
174 return true;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200175}
176
bigbiff7ba75002020-04-11 20:47:09 -0400177static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
178 const KeyAuthentication& auth, const std::string& appId) {
179 auto paramBuilder = km::AuthorizationSetBuilder()
180 .GcmModeMacLen(GCM_MAC_BYTES * 8)
181 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
182 km::HardwareAuthToken authToken;
183 if (!auth.token.empty()) {
bigbiffbbbfe172021-05-30 15:52:41 -0400184 LOG(INFO) << "Supplying auth token to Keymaster";
bigbiff7ba75002020-04-11 20:47:09 -0400185 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
186 }
187 return {paramBuilder, authToken};
188}
189
190static bool readFileToString(const std::string& filename, std::string* result) {
191 if (!android::base::ReadFileToString(filename, result)) {
192 PLOG(ERROR) << "Failed to read from " << filename;
193 return false;
194 }
195 return true;
196}
197
198static bool readRandomBytesOrLog(size_t count, std::string* out) {
199 auto status = ReadRandomBytes(count, *out);
bigbiffa957f072021-03-07 18:20:29 -0500200 if (status != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400201 LOG(ERROR) << "Random read failed with status: " << status;
202 return false;
203 }
204 return true;
205}
206
207bool createSecdiscardable(const std::string& filename, std::string* hash) {
208 std::string secdiscardable;
209 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
210 if (!writeStringToFile(secdiscardable, filename)) return false;
211 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
212 return true;
213}
214
215bool readSecdiscardable(const std::string& filename, std::string* hash) {
216 std::string secdiscardable;
217 if (!readFileToString(filename, &secdiscardable)) return false;
218 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
219 return true;
220}
221
bigbiffa957f072021-03-07 18:20:29 -0500222static void deferedKmDeleteKey(const std::string& kmkey) {
223 while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
224 LOG(ERROR) << "Wait for boot timed out";
225 }
226 Keymaster keymaster;
227 if (!keymaster || !keymaster.deleteKey(kmkey)) {
228 LOG(ERROR) << "Defered Key deletion failed during upgrade";
229 }
230}
bigbiff7ba75002020-04-11 20:47:09 -0400231
232bool kmDeleteKey(Keymaster& keymaster, const std::string& kmKey) {
bigbiffa957f072021-03-07 18:20:29 -0500233 bool needs_cp = cp_needsCheckpoint();
bigbiff7ba75002020-04-11 20:47:09 -0400234
bigbiffa957f072021-03-07 18:20:29 -0500235 if (needs_cp) {
236 std::thread(deferedKmDeleteKey, kmKey).detach();
237 LOG(INFO) << "Deferring Key deletion during upgrade";
238 return true;
239 } else {
240 return keymaster.deleteKey(kmKey);
241 }
bigbiff7ba75002020-04-11 20:47:09 -0400242}
243
244static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
245 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
246 const km::AuthorizationSet& opParams,
247 const km::HardwareAuthToken& authToken,
248 km::AuthorizationSet* outParams, bool keepOld) {
249 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
250 std::string kmKey;
251 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
zhenyolkae46d6962021-11-08 19:09:16 +0300252 // In A12 keymaster_key_blob format changed:
253 // it have useless for us bytes in beginning, so remove them to correctly handle key
254 if (!kmKey.compare(0, kPkmBlob.size(), kPkmBlob))
255 kmKey.erase(0, kPkmBlob.size());
bigbiff7ba75002020-04-11 20:47:09 -0400256 km::AuthorizationSet inParams(keyParams);
257 inParams.append(opParams.begin(), opParams.end());
258 for (;;) {
259 auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
260 if (opHandle) {
261 return opHandle;
262 }
263 if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
264 LOG(DEBUG) << "Upgrading key: " << dir;
265 std::string newKey;
266 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
bigbiffbbbfe172021-05-30 15:52:41 -0400267 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
268 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
269 if (!keepOld) {
270 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
271 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
272 return KeymasterOperation();
273 }
274 if (!::FsyncDirectory(dir)) {
275 LOG(ERROR) << "Key dir sync failed: " << dir;
276 return KeymasterOperation();
277 }
278 if (!kmDeleteKey(keymaster, kmKey)) {
279 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
280 }
281 }
bigbiff7ba75002020-04-11 20:47:09 -0400282 kmKey = newKey;
bigbiffa957f072021-03-07 18:20:29 -0500283 LOG(INFO) << "Key upgraded: " << dir;
bigbiff7ba75002020-04-11 20:47:09 -0400284 }
285}
286
287static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
288 const km::AuthorizationSet& keyParams,
289 const km::HardwareAuthToken& authToken, const KeyBuffer& message,
290 std::string* ciphertext, bool keepOld) {
291 km::AuthorizationSet opParams;
292 km::AuthorizationSet outParams;
293 auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
294 &outParams, keepOld);
295 if (!opHandle) return false;
296 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
297 if (!nonceBlob.isOk()) {
298 LOG(ERROR) << "GCM encryption but no nonce generated";
299 return false;
300 }
301 // nonceBlob here is just a pointer into existing data, must not be freed
302 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
303 nonceBlob.value().size());
304 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
305 std::string body;
306 if (!opHandle.updateCompletely(message, &body)) return false;
307
308 std::string mac;
309 if (!opHandle.finish(&mac)) return false;
310 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
311 *ciphertext = nonce + body + mac;
312 return true;
313}
314
315static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
316 const km::AuthorizationSet& keyParams,
317 const km::HardwareAuthToken& authToken,
318 const std::string& ciphertext, KeyBuffer* message,
319 bool keepOld) {
320 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
321 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
322 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
323 km::support::blob2hidlVec(nonce));
324 auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
325 nullptr, keepOld);
326 if (!opHandle) return false;
327 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
328 if (!opHandle.finish(nullptr)) return false;
329 return true;
330}
331
332static std::string getStretching(const KeyAuthentication& auth) {
333 if (!auth.usesKeymaster()) {
334 return kStretch_none;
335 } else if (auth.secret.empty()) {
336 return kStretch_nopassword;
337 } else {
338 char paramstr[PROPERTY_VALUE_MAX];
339
340 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
341 return std::string() + kStretchPrefix_scrypt + paramstr;
342 }
343}
344
345static bool stretchingNeedsSalt(const std::string& stretching) {
346 return stretching != kStretch_nopassword && stretching != kStretch_none;
347}
348
349static bool stretchSecret(const std::string& stretching, const std::string& secret,
350 const std::string& salt, std::string* stretched) {
351 if (stretching == kStretch_nopassword) {
352 if (!secret.empty()) {
353 LOG(WARNING) << "Password present but stretching is nopassword";
354 // Continue anyway
355 }
356 stretched->clear();
357 } else if (stretching == kStretch_none) {
358 *stretched = secret;
359 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
360 stretching.begin())) {
361 int Nf, rf, pf;
362 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
363 &rf, &pf)) {
364 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
365 return false;
366 }
367 stretched->assign(STRETCHED_BYTES, '\0');
368 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
369 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
370 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
371 stretched->size()) != 0) {
372 LOG(ERROR) << "scrypt failed with params: " << stretching;
373 return false;
374 }
375 } else {
376 LOG(ERROR) << "Unknown stretching type: " << stretching;
377 return false;
378 }
379 return true;
380}
381
382static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
383 const std::string& salt, const std::string& secdiscardable_hash,
384 std::string* appId) {
385 std::string stretched;
386 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
387 *appId = secdiscardable_hash + stretched;
388 return true;
389}
390
391static void logOpensslError() {
392 LOG(ERROR) << "Openssl error: " << ERR_get_error();
393}
394
395static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
396 std::string* ciphertext) {
397 std::string key;
398 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
399 key.resize(AES_KEY_BYTES);
400 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
401 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
402 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
403 if (!ctx) {
404 logOpensslError();
405 return false;
406 }
407 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
408 reinterpret_cast<const uint8_t*>(key.data()),
409 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
410 logOpensslError();
411 return false;
412 }
413 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
414 int outlen;
415 if (1 != EVP_EncryptUpdate(
416 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
417 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
418 logOpensslError();
419 return false;
420 }
421 if (outlen != static_cast<int>(plaintext.size())) {
422 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
423 return false;
424 }
425 if (1 != EVP_EncryptFinal_ex(
426 ctx.get(),
427 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
428 &outlen)) {
429 logOpensslError();
430 return false;
431 }
432 if (outlen != 0) {
433 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
434 return false;
435 }
436 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
437 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
438 plaintext.size()))) {
439 logOpensslError();
440 return false;
441 }
442 return true;
443}
444
445static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
446 KeyBuffer* plaintext) {
447 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
448 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
449 return false;
450 }
451 std::string key;
452 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
453 key.resize(AES_KEY_BYTES);
454 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
455 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
456 if (!ctx) {
457 logOpensslError();
458 return false;
459 }
460 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
461 reinterpret_cast<const uint8_t*>(key.data()),
462 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
463 logOpensslError();
464 return false;
465 }
466 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
467 int outlen;
468 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
469 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
470 plaintext->size())) {
471 logOpensslError();
472 return false;
473 }
474 if (outlen != static_cast<int>(plaintext->size())) {
475 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
476 return false;
477 }
478 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
479 const_cast<void*>(reinterpret_cast<const void*>(
480 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
481 logOpensslError();
482 return false;
483 }
484 if (1 != EVP_DecryptFinal_ex(ctx.get(),
485 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
486 &outlen)) {
487 logOpensslError();
488 return false;
489 }
490 if (outlen != 0) {
491 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
492 return false;
493 }
494 return true;
495}
496
497bool pathExists(const std::string& path) {
498 return access(path.c_str(), F_OK) == 0;
499}
500
501bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
502 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
503 PLOG(ERROR) << "key mkdir " << dir;
504 return false;
505 }
506 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
507 std::string secdiscardable_hash;
508 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
509 std::string stretching = getStretching(auth);
510 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
511 std::string salt;
512 if (stretchingNeedsSalt(stretching)) {
bigbiffa957f072021-03-07 18:20:29 -0500513 if (ReadRandomBytes(SALT_BYTES, salt) != android::OK) {
bigbiff7ba75002020-04-11 20:47:09 -0400514 LOG(ERROR) << "Random read failed";
515 return false;
516 }
517 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
518 }
519 std::string appId;
520 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
521 std::string encryptedKey;
522 if (auth.usesKeymaster()) {
523 Keymaster keymaster;
524 if (!keymaster) return false;
525 std::string kmKey;
526 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
527 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
528 km::AuthorizationSet keyParams;
529 km::HardwareAuthToken authToken;
530 std::tie(keyParams, authToken) = beginParams(auth, appId);
531 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
532 false))
533 return false;
534 } else {
535 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
536 }
537 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
538 if (!FsyncDirectory(dir)) return false;
539 return true;
540}
541
542bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
543 const KeyAuthentication& auth, const KeyBuffer& key) {
544 if (pathExists(key_path)) {
545 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
546 return false;
547 }
548 if (pathExists(tmp_path)) {
549 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
550 destroyKey(tmp_path); // May be partially created so ignore errors
551 }
bigbiffa957f072021-03-07 18:20:29 -0500552 if (!::storeKey(tmp_path, auth, key)) return false;
bigbiff7ba75002020-04-11 20:47:09 -0400553 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
554 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
555 return false;
556 }
557 LOG(DEBUG) << "Created key: " << key_path;
558 return true;
559}
560
561bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
562 bool keepOld) {
563 std::string version;
564 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
565 if (version != kCurrentVersion) {
566 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
567 return false;
568 }
569 std::string secdiscardable_hash;
570 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
571 std::string stretching;
572 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
573 std::string salt;
574 if (stretchingNeedsSalt(stretching)) {
575 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
576 }
577 std::string appId;
578 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
579 std::string encryptedMessage;
580 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
581 if (auth.usesKeymaster()) {
582 Keymaster keymaster;
583 if (!keymaster) return false;
584 km::AuthorizationSet keyParams;
585 km::HardwareAuthToken authToken;
586 std::tie(keyParams, authToken) = beginParams(auth, appId);
587 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
588 keepOld))
589 return false;
590 } else {
591 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
592 }
593 return true;
594}
595
596static bool deleteKey(const std::string& dir) {
597 std::string kmKey;
598 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
zhenyolkae46d6962021-11-08 19:09:16 +0300599 // In A12 keymaster_key_blob format changed:
600 // it have useless for us bytes in beginning, so remove them to correctly handle key
601 if (!kmKey.compare(0, kPkmBlob.size(), kPkmBlob))
602 kmKey.erase(0, kPkmBlob.size());
bigbiff7ba75002020-04-11 20:47:09 -0400603 Keymaster keymaster;
604 if (!keymaster) return false;
605 if (!keymaster.deleteKey(kmKey)) return false;
606 return true;
607}
608
609bool runSecdiscardSingle(const std::string& file) {
610 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
611 LOG(ERROR) << "secdiscard failed";
612 return false;
613 }
614 return true;
615}
616
617static bool recursiveDeleteKey(const std::string& dir) {
618 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
619 LOG(ERROR) << "recursive delete failed";
620 return false;
621 }
622 return true;
623}
624
625bool destroyKey(const std::string& dir) {
626 bool success = true;
627 // Try each thing, even if previous things failed.
628 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
629 if (uses_km) {
630 success &= deleteKey(dir);
631 }
632 auto secdiscard_cmd = std::vector<std::string>{
633 kSecdiscardPath,
634 "--",
635 dir + "/" + kFn_encrypted_key,
636 dir + "/" + kFn_secdiscardable,
637 };
638 if (uses_km) {
639 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
640 }
641 if (ForkExecvp(secdiscard_cmd) != 0) {
642 LOG(ERROR) << "secdiscard failed";
643 success = false;
644 }
645 success &= recursiveDeleteKey(dir);
646 return success;
647}