blob: 068c0693ec6e013ad41594e2daf3663f6f90378b [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
19#include "Keymaster.h"
20#include "ScryptParameters.h"
21#include "Utils.h"
22#include "Checkpoint.h"
23
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>
40#include <android-base/unique_fd.h>
41#include <android-base/properties.h>
42
43#include <cutils/properties.h>
44
45#include <hardware/hw_auth_token.h>
46#include <keymasterV4_0/authorization_set.h>
47#include <keymasterV4_0/keymaster_utils.h>
48
49extern "C" {
50
51#include "crypto_scrypt.h"
52}
53
54namespace android {
55namespace vold {
56
57const KeyAuthentication kEmptyAuthentication{"", ""};
58
59static constexpr size_t AES_KEY_BYTES = 32;
60static constexpr size_t GCM_NONCE_BYTES = 12;
61static constexpr size_t GCM_MAC_BYTES = 16;
62static constexpr size_t SALT_BYTES = 1 << 4;
63static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
64static constexpr size_t STRETCHED_BYTES = 1 << 6;
65
66static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
mauronofrio matarrese79820322020-05-25 19:48:56 +020067constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
bigbiff7ba75002020-04-11 20:47:09 -040068
69static const char* kCurrentVersion = "1";
70static const char* kRmPath = "/system/bin/rm";
71static const char* kSecdiscardPath = "/system/bin/secdiscard";
72static const char* kStretch_none = "none";
73static const char* kStretch_nopassword = "nopassword";
74static const std::string kStretchPrefix_scrypt = "scrypt ";
75static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
76static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
77static const char* kFn_encrypted_key = "encrypted_key";
78static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
79static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
80static const char* kFn_salt = "salt";
81static const char* kFn_secdiscardable = "secdiscardable";
82static const char* kFn_stretching = "stretching";
83static const char* kFn_version = "version";
84
85static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
86 if (actual != expected) {
87 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
88 << actual;
89 return false;
90 }
91 return true;
92}
93
94static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
95 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
101 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());
105 res->assign(SHA512_DIGEST_LENGTH, '\0');
106 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
107}
108
109static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
110 const std::string& appId, std::string* key) {
111 auto paramBuilder = km::AuthorizationSetBuilder()
112 .AesEncryptionKey(AES_KEY_BYTES * 8)
113 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
114 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
115 if (auth.token.empty()) {
116 LOG(DEBUG) << "Creating key that doesn't need auth token";
117 paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
118 } 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 "
122 << auth.token.size() << " bytes";
123 return false;
124 }
125 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
126 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id);
127 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
128 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
129 }
130 return keymaster.generateKey(paramBuilder, key);
131}
132
mauronofrio matarrese79820322020-05-25 19:48:56 +0200133bool generateWrappedKey(userid_t user_id, KeyType key_type,
134 KeyBuffer* key) {
135 Keymaster keymaster;
136 if (!keymaster) return false;
137 *key = KeyBuffer(EXT4_AES_256_XTS_KEY_SIZE);
138 std::string key_temp;
139 auto paramBuilder = km::AuthorizationSetBuilder()
140 .AesEncryptionKey(AES_KEY_BYTES * 8)
141 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
142 .Authorization(km::TAG_USER_ID, user_id);
143 km::KeyParameter param1;
144 param1.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_FBE_ICE);
145 param1.f.boolValue = true;
146 paramBuilder.push_back(param1);
147
148 km::KeyParameter param2;
mauronofrio matarresef1079ed2020-05-25 20:52:57 +0200149 if ((key_type == KeyType::DE_USER) || (key_type == KeyType::DE_SYS || (key_type == KeyType::ME))) {
mauronofrio matarrese79820322020-05-25 19:48:56 +0200150 param2.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_KEY_TYPE);
151 param2.f.integer = 0;
152 } else if (key_type == KeyType::CE_USER) {
153 param2.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_KEY_TYPE);
154 param2.f.integer = 1;
155 }
156 paramBuilder.push_back(param2);
157
158 if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
159 *key = KeyBuffer(key_temp.size());
160 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
161 return true;
162}
163
164bool getEphemeralWrappedKey(km::KeyFormat format, KeyBuffer& kmKey, KeyBuffer* key) {
165 std::string key_temp;
166 Keymaster keymaster;
167 if (!keymaster) return false;
mauronofrio matarresebd79db42020-05-25 20:18:52 +0200168
169 //Export once, if upgrade needed, upgrade and export again
170 bool export_again = true;
171 while (export_again) {
172 export_again = false;
173 auto ret = keymaster.exportKey(format, kmKey, "!", "!", &key_temp);
174 if (ret == km::ErrorCode::OK) {
175 *key = KeyBuffer(key_temp.size());
176 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
177 return true;
178 }
179 if (ret != km::ErrorCode::KEY_REQUIRES_UPGRADE) return false;
180 LOG(DEBUG) << "Upgrading key";
181 std::string kmKeyStr(reinterpret_cast<const char*>(kmKey.data()), kmKey.size());
182 std::string newKey;
183 if (!keymaster.upgradeKey(kmKeyStr, km::AuthorizationSet(), &newKey)) return false;
184 memcpy(reinterpret_cast<void*>(kmKey.data()), newKey.c_str(), kmKey.size());
185 LOG(INFO) << "Key upgraded";
186 export_again = true;
187 }
188 //Should never come here
189 return false;
mauronofrio matarrese79820322020-05-25 19:48:56 +0200190}
191
bigbiff7ba75002020-04-11 20:47:09 -0400192static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
193 const KeyAuthentication& auth, const std::string& appId) {
194 auto paramBuilder = km::AuthorizationSetBuilder()
195 .GcmModeMacLen(GCM_MAC_BYTES * 8)
196 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
197 km::HardwareAuthToken authToken;
198 if (!auth.token.empty()) {
199 LOG(DEBUG) << "Supplying auth token to Keymaster";
200 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
201 }
202 return {paramBuilder, authToken};
203}
204
205static bool readFileToString(const std::string& filename, std::string* result) {
206 if (!android::base::ReadFileToString(filename, result)) {
207 PLOG(ERROR) << "Failed to read from " << filename;
208 return false;
209 }
210 return true;
211}
212
213static bool readRandomBytesOrLog(size_t count, std::string* out) {
214 auto status = ReadRandomBytes(count, *out);
215 if (status != OK) {
216 LOG(ERROR) << "Random read failed with status: " << status;
217 return false;
218 }
219 return true;
220}
221
222bool createSecdiscardable(const std::string& filename, std::string* hash) {
223 std::string secdiscardable;
224 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
225 if (!writeStringToFile(secdiscardable, filename)) return false;
226 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
227 return true;
228}
229
230bool readSecdiscardable(const std::string& filename, std::string* hash) {
231 std::string secdiscardable;
232 if (!readFileToString(filename, &secdiscardable)) return false;
233 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
234 return true;
235}
236
237// static void deferedKmDeleteKey(const std::string& kmkey) {
238// while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
239// LOG(ERROR) << "Wait for boot timed out";
240// }
241// Keymaster keymaster;
242// if (!keymaster || !keymaster.deleteKey(kmkey)) {
243// LOG(ERROR) << "Defered Key deletion failed during upgrade";
244// }
245// }
246
247bool kmDeleteKey(Keymaster& keymaster, const std::string& kmKey) {
248 return true;
249 // bool needs_cp = cp_needsCheckpoint();
250
251 // if (needs_cp) {
252 // std::thread(deferedKmDeleteKey, kmKey).detach();
253 // LOG(INFO) << "Deferring Key deletion during upgrade";
254 // return true;
255 // } else {
256 // return keymaster.deleteKey(kmKey);
257 // }
258}
259
260static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
261 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
262 const km::AuthorizationSet& opParams,
263 const km::HardwareAuthToken& authToken,
264 km::AuthorizationSet* outParams, bool keepOld) {
265 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
266 std::string kmKey;
267 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
268 km::AuthorizationSet inParams(keyParams);
269 inParams.append(opParams.begin(), opParams.end());
270 for (;;) {
271 auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
272 if (opHandle) {
273 return opHandle;
274 }
275 if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
276 LOG(DEBUG) << "Upgrading key: " << dir;
277 std::string newKey;
278 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
279 // auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
280 // if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
281 // if (!keepOld) {
282 // if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
283 // PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
284 // return KeymasterOperation();
285 // }
286 // if (!android::vold::FsyncDirectory(dir)) {
287 // LOG(ERROR) << "Key dir sync failed: " << dir;
288 // return KeymasterOperation();
289 // }
290 // if (!kmDeleteKey(keymaster, kmKey)) {
291 // LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
292 // }
293 // }
294 kmKey = newKey;
295 LOG(INFO) << "Key upgraded in memory: " << dir;
296 }
297}
298
299static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
300 const km::AuthorizationSet& keyParams,
301 const km::HardwareAuthToken& authToken, const KeyBuffer& message,
302 std::string* ciphertext, bool keepOld) {
303 km::AuthorizationSet opParams;
304 km::AuthorizationSet outParams;
305 auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
306 &outParams, keepOld);
307 if (!opHandle) return false;
308 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
309 if (!nonceBlob.isOk()) {
310 LOG(ERROR) << "GCM encryption but no nonce generated";
311 return false;
312 }
313 // nonceBlob here is just a pointer into existing data, must not be freed
314 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
315 nonceBlob.value().size());
316 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
317 std::string body;
318 if (!opHandle.updateCompletely(message, &body)) return false;
319
320 std::string mac;
321 if (!opHandle.finish(&mac)) return false;
322 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
323 *ciphertext = nonce + body + mac;
324 return true;
325}
326
327static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
328 const km::AuthorizationSet& keyParams,
329 const km::HardwareAuthToken& authToken,
330 const std::string& ciphertext, KeyBuffer* message,
331 bool keepOld) {
332 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
333 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
334 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
335 km::support::blob2hidlVec(nonce));
336 auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
337 nullptr, keepOld);
338 if (!opHandle) return false;
339 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
340 if (!opHandle.finish(nullptr)) return false;
341 return true;
342}
343
344static std::string getStretching(const KeyAuthentication& auth) {
345 if (!auth.usesKeymaster()) {
346 return kStretch_none;
347 } else if (auth.secret.empty()) {
348 return kStretch_nopassword;
349 } else {
350 char paramstr[PROPERTY_VALUE_MAX];
351
352 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
353 return std::string() + kStretchPrefix_scrypt + paramstr;
354 }
355}
356
357static bool stretchingNeedsSalt(const std::string& stretching) {
358 return stretching != kStretch_nopassword && stretching != kStretch_none;
359}
360
361static bool stretchSecret(const std::string& stretching, const std::string& secret,
362 const std::string& salt, std::string* stretched) {
363 if (stretching == kStretch_nopassword) {
364 if (!secret.empty()) {
365 LOG(WARNING) << "Password present but stretching is nopassword";
366 // Continue anyway
367 }
368 stretched->clear();
369 } else if (stretching == kStretch_none) {
370 *stretched = secret;
371 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
372 stretching.begin())) {
373 int Nf, rf, pf;
374 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
375 &rf, &pf)) {
376 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
377 return false;
378 }
379 stretched->assign(STRETCHED_BYTES, '\0');
380 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
381 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
382 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
383 stretched->size()) != 0) {
384 LOG(ERROR) << "scrypt failed with params: " << stretching;
385 return false;
386 }
387 } else {
388 LOG(ERROR) << "Unknown stretching type: " << stretching;
389 return false;
390 }
391 return true;
392}
393
394static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
395 const std::string& salt, const std::string& secdiscardable_hash,
396 std::string* appId) {
397 std::string stretched;
398 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
399 *appId = secdiscardable_hash + stretched;
400 return true;
401}
402
403static void logOpensslError() {
404 LOG(ERROR) << "Openssl error: " << ERR_get_error();
405}
406
407static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
408 std::string* ciphertext) {
409 std::string key;
410 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
411 key.resize(AES_KEY_BYTES);
412 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
413 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
414 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
415 if (!ctx) {
416 logOpensslError();
417 return false;
418 }
419 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
420 reinterpret_cast<const uint8_t*>(key.data()),
421 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
422 logOpensslError();
423 return false;
424 }
425 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
426 int outlen;
427 if (1 != EVP_EncryptUpdate(
428 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
429 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
430 logOpensslError();
431 return false;
432 }
433 if (outlen != static_cast<int>(plaintext.size())) {
434 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
435 return false;
436 }
437 if (1 != EVP_EncryptFinal_ex(
438 ctx.get(),
439 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
440 &outlen)) {
441 logOpensslError();
442 return false;
443 }
444 if (outlen != 0) {
445 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
446 return false;
447 }
448 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
449 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
450 plaintext.size()))) {
451 logOpensslError();
452 return false;
453 }
454 return true;
455}
456
457static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
458 KeyBuffer* plaintext) {
459 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
460 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
461 return false;
462 }
463 std::string key;
464 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
465 key.resize(AES_KEY_BYTES);
466 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
467 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
468 if (!ctx) {
469 logOpensslError();
470 return false;
471 }
472 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
473 reinterpret_cast<const uint8_t*>(key.data()),
474 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
475 logOpensslError();
476 return false;
477 }
478 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
479 int outlen;
480 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
481 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
482 plaintext->size())) {
483 logOpensslError();
484 return false;
485 }
486 if (outlen != static_cast<int>(plaintext->size())) {
487 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
488 return false;
489 }
490 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
491 const_cast<void*>(reinterpret_cast<const void*>(
492 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
493 logOpensslError();
494 return false;
495 }
496 if (1 != EVP_DecryptFinal_ex(ctx.get(),
497 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
498 &outlen)) {
499 logOpensslError();
500 return false;
501 }
502 if (outlen != 0) {
503 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
504 return false;
505 }
506 return true;
507}
508
509bool pathExists(const std::string& path) {
510 return access(path.c_str(), F_OK) == 0;
511}
512
513bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
514 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
515 PLOG(ERROR) << "key mkdir " << dir;
516 return false;
517 }
518 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
519 std::string secdiscardable_hash;
520 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
521 std::string stretching = getStretching(auth);
522 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
523 std::string salt;
524 if (stretchingNeedsSalt(stretching)) {
525 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
526 LOG(ERROR) << "Random read failed";
527 return false;
528 }
529 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
530 }
531 std::string appId;
532 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
533 std::string encryptedKey;
534 if (auth.usesKeymaster()) {
535 Keymaster keymaster;
536 if (!keymaster) return false;
537 std::string kmKey;
538 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
539 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
540 km::AuthorizationSet keyParams;
541 km::HardwareAuthToken authToken;
542 std::tie(keyParams, authToken) = beginParams(auth, appId);
543 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
544 false))
545 return false;
546 } else {
547 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
548 }
549 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
550 if (!FsyncDirectory(dir)) return false;
551 return true;
552}
553
554bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
555 const KeyAuthentication& auth, const KeyBuffer& key) {
556 if (pathExists(key_path)) {
557 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
558 return false;
559 }
560 if (pathExists(tmp_path)) {
561 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
562 destroyKey(tmp_path); // May be partially created so ignore errors
563 }
564 if (!storeKey(tmp_path, auth, key)) return false;
565 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
566 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
567 return false;
568 }
569 LOG(DEBUG) << "Created key: " << key_path;
570 return true;
571}
572
573bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
574 bool keepOld) {
575 std::string version;
576 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
577 if (version != kCurrentVersion) {
578 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
579 return false;
580 }
581 std::string secdiscardable_hash;
582 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
583 std::string stretching;
584 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
585 std::string salt;
586 if (stretchingNeedsSalt(stretching)) {
587 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
588 }
589 std::string appId;
590 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
591 std::string encryptedMessage;
592 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
593 if (auth.usesKeymaster()) {
594 Keymaster keymaster;
595 if (!keymaster) return false;
596 km::AuthorizationSet keyParams;
597 km::HardwareAuthToken authToken;
598 std::tie(keyParams, authToken) = beginParams(auth, appId);
599 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
600 keepOld))
601 return false;
602 } else {
603 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
604 }
605 return true;
606}
607
608static bool deleteKey(const std::string& dir) {
609 std::string kmKey;
610 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
611 Keymaster keymaster;
612 if (!keymaster) return false;
613 if (!keymaster.deleteKey(kmKey)) return false;
614 return true;
615}
616
617bool runSecdiscardSingle(const std::string& file) {
618 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
619 LOG(ERROR) << "secdiscard failed";
620 return false;
621 }
622 return true;
623}
624
625static bool recursiveDeleteKey(const std::string& dir) {
626 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
627 LOG(ERROR) << "recursive delete failed";
628 return false;
629 }
630 return true;
631}
632
633bool destroyKey(const std::string& dir) {
634 bool success = true;
635 // Try each thing, even if previous things failed.
636 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
637 if (uses_km) {
638 success &= deleteKey(dir);
639 }
640 auto secdiscard_cmd = std::vector<std::string>{
641 kSecdiscardPath,
642 "--",
643 dir + "/" + kFn_encrypted_key,
644 dir + "/" + kFn_secdiscardable,
645 };
646 if (uses_km) {
647 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
648 }
649 if (ForkExecvp(secdiscard_cmd) != 0) {
650 LOG(ERROR) << "secdiscard failed";
651 success = false;
652 }
653 success &= recursiveDeleteKey(dir);
654 return success;
655}
656
657} // namespace vold
658} // namespace android