blob: cab88a19daf4188ab29028298a05e44cfd5701d7 [file] [log] [blame]
Ethan Yonkere9afc3d2018-08-30 15:16:27 -05001/*
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 "KeyStorage4.h"
18
19#include "Keymaster4.h"
20#include "ScryptParameters.h"
21#include "Utils.h"
22
23#include <vector>
24
25#include <errno.h>
26#include <stdio.h>
27#include <sys/stat.h>
28#include <sys/types.h>
29#include <sys/wait.h>
30#include <unistd.h>
31
32#include <openssl/err.h>
33#include <openssl/evp.h>
34#include <openssl/sha.h>
35
36#include <android-base/file.h>
37//#include <android-base/logging.h>
38#include <android-base/unique_fd.h>
39
40#include <cutils/properties.h>
41
42#include <hardware/hw_auth_token.h>
43#include <keymasterV4_0/authorization_set.h>
44#include <keymasterV4_0/keymaster_utils.h>
45
46#include <iostream>
47#define ERROR 1
48#define LOG(x) std::cout
49#define PLOG(x) std::cout
50
51extern "C" {
52
53#include "crypto_scrypt.h"
54}
55
56namespace android {
57namespace vold {
58
59const KeyAuthentication kEmptyAuthentication{"", ""};
60
61static constexpr size_t AES_KEY_BYTES = 32;
62static constexpr size_t GCM_NONCE_BYTES = 12;
63static constexpr size_t GCM_MAC_BYTES = 16;
64static constexpr size_t SALT_BYTES = 1 << 4;
65static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
66static constexpr size_t STRETCHED_BYTES = 1 << 6;
67
68static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
Peter Cai90edd2e2019-05-23 16:32:22 +080069constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
Ethan Yonkere9afc3d2018-08-30 15:16:27 -050070
71static const char* kCurrentVersion = "1";
72static const char* kRmPath = "/system/bin/rm";
73static const char* kSecdiscardPath = "/system/bin/secdiscard";
74static const char* kStretch_none = "none";
75static const char* kStretch_nopassword = "nopassword";
76static const std::string kStretchPrefix_scrypt = "scrypt ";
77static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
78static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
79static const char* kFn_encrypted_key = "encrypted_key";
80static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
81static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
82static const char* kFn_salt = "salt";
83static const char* kFn_secdiscardable = "secdiscardable";
84static const char* kFn_stretching = "stretching";
85static const char* kFn_version = "version";
86
87static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
88 if (actual != expected) {
89 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
90 << actual << std::endl;
91 return false;
92 }
93 return true;
94}
95
96static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
97 SHA512_CTX c;
98
99 SHA512_Init(&c);
100 // Personalise the hashing by introducing a fixed prefix.
101 // Hashing applications should use personalization except when there is a
102 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
103 std::string hashingPrefix = prefix;
104 hashingPrefix.resize(SHA512_CBLOCK);
105 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
106 SHA512_Update(&c, tohash.data(), tohash.size());
107 res->assign(SHA512_DIGEST_LENGTH, '\0');
108 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
109}
110
111static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
112 const std::string& appId, std::string* key) {
113 auto paramBuilder = km::AuthorizationSetBuilder()
114 .AesEncryptionKey(AES_KEY_BYTES * 8)
115 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
116 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
117 if (auth.token.empty()) {
118 LOG(DEBUG) << "Creating key that doesn't need auth token" << std::endl;
119 paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
120 } else {
121 LOG(DEBUG) << "Auth token required for key" << std::endl;
122 if (auth.token.size() != sizeof(hw_auth_token_t)) {
123 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
124 << auth.token.size() << " bytes" << std::endl;
125 return false;
126 }
127 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
128 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id);
129 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
130 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
131 }
132 return keymaster.generateKey(paramBuilder, key);
133}
134
Peter Cai90edd2e2019-05-23 16:32:22 +0800135bool generateWrappedKey(userid_t user_id, KeyType key_type,
136 KeyBuffer* key) {
137 Keymaster keymaster;
138 if (!keymaster) return false;
139 *key = KeyBuffer(EXT4_AES_256_XTS_KEY_SIZE);
140 std::string key_temp;
141 auto paramBuilder = km::AuthorizationSetBuilder()
142 .AesEncryptionKey(AES_KEY_BYTES * 8)
143 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
144 .Authorization(km::TAG_USER_ID, user_id);
145 km::KeyParameter param1;
146 param1.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_FBE_ICE);
147 param1.f.boolValue = true;
148 paramBuilder.push_back(param1);
149 km::KeyParameter param2;
150 if ((key_type == KeyType::DE_USER) || (key_type == KeyType::DE_SYS)) {
151 param2.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_KEY_TYPE);
152 param2.f.integer = 0;
153 } else if (key_type == KeyType::CE_USER) {
154 param2.tag = (km::Tag) (android::hardware::keymaster::V4_0::KM_TAG_KEY_TYPE);
155 param2.f.integer = 1;
156 }
157 paramBuilder.push_back(param2);
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;
168 if (!keymaster.exportKey(format, kmKey, "!", "!", &key_temp)) return false;
169 *key = KeyBuffer(key_temp.size());
170 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
171 return true;
172}
173
Ethan Yonkere9afc3d2018-08-30 15:16:27 -0500174static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
175 const KeyAuthentication& auth, const std::string& appId) {
176 auto paramBuilder = km::AuthorizationSetBuilder()
177 .GcmModeMacLen(GCM_MAC_BYTES * 8)
178 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
179 km::HardwareAuthToken authToken;
180 if (!auth.token.empty()) {
181 LOG(DEBUG) << "Supplying auth token to Keymaster" << std::endl;
182 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
183 }
184 return {paramBuilder, authToken};
185}
186
187static bool readFileToString(const std::string& filename, std::string* result) {
188 if (!android::base::ReadFileToString(filename, result)) {
189 PLOG(ERROR) << "Failed to read from " << filename << std::endl;
190 return false;
191 }
192 return true;
193}
194
195static bool writeStringToFile(const std::string& payload, const std::string& filename) {
196 PLOG(ERROR) << __FUNCTION__ << " called for " << filename << " and being skipped\n";
197 return true;
198 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
199 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
200 if (fd == -1) {
201 PLOG(ERROR) << "Failed to open " << filename;
202 return false;
203 }
204 if (!android::base::WriteStringToFd(payload, fd)) {
205 PLOG(ERROR) << "Failed to write to " << filename;
206 unlink(filename.c_str());
207 return false;
208 }
209 // fsync as close won't guarantee flush data
210 // see close(2), fsync(2) and b/68901441
211 if (fsync(fd) == -1) {
212 if (errno == EROFS || errno == EINVAL) {
213 PLOG(WARNING) << "Skip fsync " << filename
214 << " on a file system does not support synchronization";
215 } else {
216 PLOG(ERROR) << "Failed to fsync " << filename;
217 unlink(filename.c_str());
218 return false;
219 }
220 }
221 return true;
222}
223
224static bool readRandomBytesOrLog(size_t count, std::string* out) {
225 auto status = ReadRandomBytes(count, *out);
226 if (status != OK) {
227 LOG(ERROR) << "Random read failed with status: " << status << std::endl;
228 return false;
229 }
230 return true;
231}
232
233bool createSecdiscardable(const std::string& filename, std::string* hash) {
234 std::string secdiscardable;
235 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
236 if (!writeStringToFile(secdiscardable, filename)) return false;
237 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
238 return true;
239}
240
241bool readSecdiscardable(const std::string& filename, std::string* hash) {
242 std::string secdiscardable;
243 if (!readFileToString(filename, &secdiscardable)) return false;
244 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
245 return true;
246}
247
248static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
249 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
250 const km::AuthorizationSet& opParams,
251 const km::HardwareAuthToken& authToken,
252 km::AuthorizationSet* outParams) {
253 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
254 std::string kmKey;
255 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
256 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 in memory only: " << dir << std::endl;
265 std::string newKey;
266 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
267 /*auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
268 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
269 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
270 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
271 return KeymasterOperation();
272 }
273 if (!keymaster.deleteKey(kmKey)) {
274 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
275 }*/
276 kmKey = newKey;
277 LOG(INFO) << "Key upgraded in memory but not updated in folder: " << dir << std::endl;
278 }
279}
280
281static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
282 const km::AuthorizationSet& keyParams,
283 const km::HardwareAuthToken& authToken,
284 const KeyBuffer& message, std::string* ciphertext) {
285 km::AuthorizationSet opParams;
286 km::AuthorizationSet outParams;
287 auto opHandle =
288 begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken, &outParams);
289 if (!opHandle) return false;
290 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
291 if (!nonceBlob.isOk()) {
292 LOG(ERROR) << "GCM encryption but no nonce generated" << std::endl;
293 return false;
294 }
295 // nonceBlob here is just a pointer into existing data, must not be freed
296 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
297 nonceBlob.value().size());
298 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
299 std::string body;
300 if (!opHandle.updateCompletely(message, &body)) return false;
301
302 std::string mac;
303 if (!opHandle.finish(&mac)) return false;
304 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
305 *ciphertext = nonce + body + mac;
306 return true;
307}
308
309static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
310 const km::AuthorizationSet& keyParams,
311 const km::HardwareAuthToken& authToken,
312 const std::string& ciphertext, KeyBuffer* message) {
313 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
314 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
315 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
316 km::support::blob2hidlVec(nonce));
317 auto opHandle =
318 begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken, nullptr);
319 if (!opHandle) return false;
320 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
321 if (!opHandle.finish(nullptr)) return false;
322 return true;
323}
324
325static std::string getStretching(const KeyAuthentication& auth) {
326 if (!auth.usesKeymaster()) {
327 return kStretch_none;
328 } else if (auth.secret.empty()) {
329 return kStretch_nopassword;
330 } else {
331 char paramstr[PROPERTY_VALUE_MAX];
332
333 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
334 return std::string() + kStretchPrefix_scrypt + paramstr;
335 }
336}
337
338static bool stretchingNeedsSalt(const std::string& stretching) {
339 return stretching != kStretch_nopassword && stretching != kStretch_none;
340}
341
342static bool stretchSecret(const std::string& stretching, const std::string& secret,
343 const std::string& salt, std::string* stretched) {
344 if (stretching == kStretch_nopassword) {
345 if (!secret.empty()) {
346 LOG(WARNING) << "Password present but stretching is nopassword" << std::endl;
347 // Continue anyway
348 }
349 stretched->clear();
350 } else if (stretching == kStretch_none) {
351 *stretched = secret;
352 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
353 stretching.begin())) {
354 int Nf, rf, pf;
355 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
356 &rf, &pf)) {
357 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching << std::endl;
358 return false;
359 }
360 stretched->assign(STRETCHED_BYTES, '\0');
361 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
362 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
363 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
364 stretched->size()) != 0) {
365 LOG(ERROR) << "scrypt failed with params: " << stretching << std::endl;
366 return false;
367 }
368 } else {
369 LOG(ERROR) << "Unknown stretching type: " << stretching << std::endl;
370 return false;
371 }
372 return true;
373}
374
375static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
376 const std::string& salt, const std::string& secdiscardable_hash,
377 std::string* appId) {
378 std::string stretched;
379 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
380 *appId = secdiscardable_hash + stretched;
381 return true;
382}
383
384static void logOpensslError() {
385 LOG(ERROR) << "Openssl error: " << ERR_get_error() << std::endl;
386}
387
388static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
389 std::string* ciphertext) {
390 std::string key;
391 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
392 key.resize(AES_KEY_BYTES);
393 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
394 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
395 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
396 if (!ctx) {
397 logOpensslError();
398 return false;
399 }
400 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
401 reinterpret_cast<const uint8_t*>(key.data()),
402 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
403 logOpensslError();
404 return false;
405 }
406 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
407 int outlen;
408 if (1 != EVP_EncryptUpdate(
409 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
410 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
411 logOpensslError();
412 return false;
413 }
414 if (outlen != static_cast<int>(plaintext.size())) {
415 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen << std::endl;
416 return false;
417 }
418 if (1 != EVP_EncryptFinal_ex(
419 ctx.get(),
420 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
421 &outlen)) {
422 logOpensslError();
423 return false;
424 }
425 if (outlen != 0) {
426 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen << std::endl;
427 return false;
428 }
429 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
430 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
431 plaintext.size()))) {
432 logOpensslError();
433 return false;
434 }
435 return true;
436}
437
438static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
439 KeyBuffer* plaintext) {
440 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
441 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size() << std::endl;
442 return false;
443 }
444 std::string key;
445 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
446 key.resize(AES_KEY_BYTES);
447 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
448 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
449 if (!ctx) {
450 logOpensslError();
451 return false;
452 }
453 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
454 reinterpret_cast<const uint8_t*>(key.data()),
455 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
456 logOpensslError();
457 return false;
458 }
459 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
460 int outlen;
461 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
462 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
463 plaintext->size())) {
464 logOpensslError();
465 return false;
466 }
467 if (outlen != static_cast<int>(plaintext->size())) {
468 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen << std::endl;
469 return false;
470 }
471 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
472 const_cast<void*>(reinterpret_cast<const void*>(
473 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
474 logOpensslError();
475 return false;
476 }
477 if (1 != EVP_DecryptFinal_ex(ctx.get(),
478 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
479 &outlen)) {
480 logOpensslError();
481 return false;
482 }
483 if (outlen != 0) {
484 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen << std::endl;
485 return false;
486 }
487 return true;
488}
489
490bool pathExists(const std::string& path) {
491 return access(path.c_str(), F_OK) == 0;
492}
493
494bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
495 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
496 PLOG(ERROR) << "key mkdir " << dir << std::endl;
497 return false;
498 }
499 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
500 std::string secdiscardable_hash;
501 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
502 std::string stretching = getStretching(auth);
503 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
504 std::string salt;
505 if (stretchingNeedsSalt(stretching)) {
506 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
507 LOG(ERROR) << "Random read failed" << std::endl;
508 return false;
509 }
510 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
511 }
512 std::string appId;
513 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
514 std::string encryptedKey;
515 if (auth.usesKeymaster()) {
516 Keymaster keymaster;
517 if (!keymaster) return false;
518 std::string kmKey;
519 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
520 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
521 km::AuthorizationSet keyParams;
522 km::HardwareAuthToken authToken;
523 std::tie(keyParams, authToken) = beginParams(auth, appId);
524 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey))
525 return false;
526 } else {
527 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
528 }
529 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) 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 << std::endl;
537 return false;
538 }
539 if (pathExists(tmp_path)) {
540 LOG(DEBUG) << "Already exists, destroying: " << tmp_path << std::endl;
541 destroyKey(tmp_path); // May be partially created so ignore errors
542 }
543 if (!storeKey(tmp_path, auth, key)) return false;
544 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
545 PLOG(ERROR) << "Unable to move new key to location: " << key_path << std::endl;
546 return false;
547 }
548 LOG(DEBUG) << "Created key: " << key_path << std::endl;
549 return true;
550}
551
552bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
553 std::string version;
554 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
555 if (version != kCurrentVersion) {
556 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version << std::endl;
557 return false;
558 }
559 std::string secdiscardable_hash;
560 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
561 std::string stretching;
562 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
563 std::string salt;
564 if (stretchingNeedsSalt(stretching)) {
565 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
566 }
567 std::string appId;
568 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
569 std::string encryptedMessage;
570 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
571 if (auth.usesKeymaster()) {
572 Keymaster keymaster;
573 if (!keymaster) return false;
574 km::AuthorizationSet keyParams;
575 km::HardwareAuthToken authToken;
576 std::tie(keyParams, authToken) = beginParams(auth, appId);
577 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key))
578 return false;
579 } else {
580 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
581 }
582 return true;
583}
584
585static bool deleteKey(const std::string& dir) {
586 LOG(DEBUG) << "not deleting key in " << __FILE__ << std::endl;
587 return true;
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" << std::endl;
599 return false;
600 }
601 return true;
602}
603
604static bool recursiveDeleteKey(const std::string& dir) {
605 LOG(DEBUG) << "not recursively deleting key in " << __FILE__ << std::endl;
606 return true;
607 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
608 LOG(ERROR) << "recursive delete failed" << std::endl;
609 return false;
610 }
611 return true;
612}
613
614bool destroyKey(const std::string& dir) {
615 LOG(DEBUG) << "not destroying key in " << __FILE__ << std::endl;
616 return true;
617 bool success = true;
618 // Try each thing, even if previous things failed.
619 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
620 if (uses_km) {
621 success &= deleteKey(dir);
622 }
623 auto secdiscard_cmd = std::vector<std::string>{
624 kSecdiscardPath, "--", dir + "/" + kFn_encrypted_key, dir + "/" + kFn_secdiscardable,
625 };
626 if (uses_km) {
627 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
628 }
629 if (ForkExecvp(secdiscard_cmd) != 0) {
630 LOG(ERROR) << "secdiscard failed" << std::endl;
631 success = false;
632 }
633 success &= recursiveDeleteKey(dir);
634 return success;
635}
636
637} // namespace vold
638} // namespace android