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