2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "KeyStorage.h"
19 #include "Keymaster.h"
20 #include "ScryptParameters.h"
28 #include <sys/types.h>
32 #include <openssl/err.h>
33 #include <openssl/evp.h>
34 #include <openssl/sha.h>
36 #include <android-base/file.h>
37 #include <android-base/logging.h>
38 #include <android-base/unique_fd.h>
40 #include <cutils/properties.h>
42 #include <hardware/hw_auth_token.h>
43 #include <keymasterV4_0/authorization_set.h>
44 #include <keymasterV4_0/keymaster_utils.h>
48 #include "crypto_scrypt.h"
54 const KeyAuthentication kEmptyAuthentication{"", ""};
56 static constexpr size_t AES_KEY_BYTES = 32;
57 static constexpr size_t GCM_NONCE_BYTES = 12;
58 static constexpr size_t GCM_MAC_BYTES = 16;
59 static constexpr size_t SALT_BYTES = 1 << 4;
60 static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
61 static constexpr size_t STRETCHED_BYTES = 1 << 6;
63 static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
65 static const char* kCurrentVersion = "1";
66 static const char* kRmPath = "/system/bin/rm";
67 static const char* kSecdiscardPath = "/system/bin/secdiscard";
68 static const char* kStretch_none = "none";
69 static const char* kStretch_nopassword = "nopassword";
70 static const std::string kStretchPrefix_scrypt = "scrypt ";
71 static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
72 static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
73 static const char* kFn_encrypted_key = "encrypted_key";
74 static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
75 static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
76 static const char* kFn_salt = "salt";
77 static const char* kFn_secdiscardable = "secdiscardable";
78 static const char* kFn_stretching = "stretching";
79 static const char* kFn_version = "version";
81 static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
82 if (actual != expected) {
83 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
90 static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
94 // Personalise the hashing by introducing a fixed prefix.
95 // Hashing applications should use personalization except when there is a
96 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
97 std::string hashingPrefix = prefix;
98 hashingPrefix.resize(SHA512_CBLOCK);
99 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
100 SHA512_Update(&c, tohash.data(), tohash.size());
101 res->assign(SHA512_DIGEST_LENGTH, '\0');
102 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
105 static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
106 const std::string& appId, std::string* key) {
107 auto paramBuilder = km::AuthorizationSetBuilder()
108 .AesEncryptionKey(AES_KEY_BYTES * 8)
109 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
110 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
111 if (auth.token.empty()) {
112 LOG(DEBUG) << "Creating key that doesn't need auth token";
113 paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
115 LOG(DEBUG) << "Auth token required for key";
116 if (auth.token.size() != sizeof(hw_auth_token_t)) {
117 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
118 << auth.token.size() << " bytes";
121 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
122 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id);
123 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
124 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
126 return keymaster.generateKey(paramBuilder, key);
129 static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
130 const KeyAuthentication& auth, const std::string& appId) {
131 auto paramBuilder = km::AuthorizationSetBuilder()
132 .GcmModeMacLen(GCM_MAC_BYTES * 8)
133 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
134 km::HardwareAuthToken authToken;
135 if (!auth.token.empty()) {
136 LOG(DEBUG) << "Supplying auth token to Keymaster";
137 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
139 return {paramBuilder, authToken};
142 static bool readFileToString(const std::string& filename, std::string* result) {
143 if (!android::base::ReadFileToString(filename, result)) {
144 PLOG(ERROR) << "Failed to read from " << filename;
150 static bool readRandomBytesOrLog(size_t count, std::string* out) {
151 auto status = ReadRandomBytes(count, *out);
153 LOG(ERROR) << "Random read failed with status: " << status;
159 bool createSecdiscardable(const std::string& filename, std::string* hash) {
160 std::string secdiscardable;
161 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
162 if (!writeStringToFile(secdiscardable, filename)) return false;
163 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
167 bool readSecdiscardable(const std::string& filename, std::string* hash) {
168 std::string secdiscardable;
169 if (!readFileToString(filename, &secdiscardable)) return false;
170 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
174 static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
175 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
176 const km::AuthorizationSet& opParams,
177 const km::HardwareAuthToken& authToken,
178 km::AuthorizationSet* outParams, bool keepOld) {
179 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
181 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
182 km::AuthorizationSet inParams(keyParams);
183 inParams.append(opParams.begin(), opParams.end());
185 auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
189 if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
190 LOG(DEBUG) << "Upgrading key: " << dir;
192 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
193 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
194 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
196 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
197 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
198 return KeymasterOperation();
200 if (!android::vold::FsyncDirectory(dir)) {
201 LOG(ERROR) << "Key dir sync failed: " << dir;
202 return KeymasterOperation();
204 if (!keymaster.deleteKey(kmKey)) {
205 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
209 LOG(INFO) << "Key upgraded: " << dir;
213 static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
214 const km::AuthorizationSet& keyParams,
215 const km::HardwareAuthToken& authToken, const KeyBuffer& message,
216 std::string* ciphertext, bool keepOld) {
217 km::AuthorizationSet opParams;
218 km::AuthorizationSet outParams;
219 auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
220 &outParams, keepOld);
221 if (!opHandle) return false;
222 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
223 if (!nonceBlob.isOk()) {
224 LOG(ERROR) << "GCM encryption but no nonce generated";
227 // nonceBlob here is just a pointer into existing data, must not be freed
228 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
229 nonceBlob.value().size());
230 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
232 if (!opHandle.updateCompletely(message, &body)) return false;
235 if (!opHandle.finish(&mac)) return false;
236 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
237 *ciphertext = nonce + body + mac;
241 static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
242 const km::AuthorizationSet& keyParams,
243 const km::HardwareAuthToken& authToken,
244 const std::string& ciphertext, KeyBuffer* message,
246 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
247 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
248 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
249 km::support::blob2hidlVec(nonce));
250 auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
252 if (!opHandle) return false;
253 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
254 if (!opHandle.finish(nullptr)) return false;
258 static std::string getStretching(const KeyAuthentication& auth) {
259 if (!auth.usesKeymaster()) {
260 return kStretch_none;
261 } else if (auth.secret.empty()) {
262 return kStretch_nopassword;
264 char paramstr[PROPERTY_VALUE_MAX];
266 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
267 return std::string() + kStretchPrefix_scrypt + paramstr;
271 static bool stretchingNeedsSalt(const std::string& stretching) {
272 return stretching != kStretch_nopassword && stretching != kStretch_none;
275 static bool stretchSecret(const std::string& stretching, const std::string& secret,
276 const std::string& salt, std::string* stretched) {
277 if (stretching == kStretch_nopassword) {
278 if (!secret.empty()) {
279 LOG(WARNING) << "Password present but stretching is nopassword";
283 } else if (stretching == kStretch_none) {
285 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
286 stretching.begin())) {
288 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
290 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
293 stretched->assign(STRETCHED_BYTES, '\0');
294 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
295 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
296 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
297 stretched->size()) != 0) {
298 LOG(ERROR) << "scrypt failed with params: " << stretching;
302 LOG(ERROR) << "Unknown stretching type: " << stretching;
308 static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
309 const std::string& salt, const std::string& secdiscardable_hash,
310 std::string* appId) {
311 std::string stretched;
312 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
313 *appId = secdiscardable_hash + stretched;
317 static void logOpensslError() {
318 LOG(ERROR) << "Openssl error: " << ERR_get_error();
321 static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
322 std::string* ciphertext) {
324 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
325 key.resize(AES_KEY_BYTES);
326 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
327 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
328 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
333 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
334 reinterpret_cast<const uint8_t*>(key.data()),
335 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
339 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
341 if (1 != EVP_EncryptUpdate(
342 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
343 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
347 if (outlen != static_cast<int>(plaintext.size())) {
348 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
351 if (1 != EVP_EncryptFinal_ex(
353 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
359 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
362 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
363 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
364 plaintext.size()))) {
371 static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
372 KeyBuffer* plaintext) {
373 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
374 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
378 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
379 key.resize(AES_KEY_BYTES);
380 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
381 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
386 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
387 reinterpret_cast<const uint8_t*>(key.data()),
388 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
392 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
394 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
395 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
396 plaintext->size())) {
400 if (outlen != static_cast<int>(plaintext->size())) {
401 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
404 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
405 const_cast<void*>(reinterpret_cast<const void*>(
406 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
410 if (1 != EVP_DecryptFinal_ex(ctx.get(),
411 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
417 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
423 bool pathExists(const std::string& path) {
424 return access(path.c_str(), F_OK) == 0;
427 bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
428 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
429 PLOG(ERROR) << "key mkdir " << dir;
432 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
433 std::string secdiscardable_hash;
434 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
435 std::string stretching = getStretching(auth);
436 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
438 if (stretchingNeedsSalt(stretching)) {
439 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
440 LOG(ERROR) << "Random read failed";
443 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
446 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
447 std::string encryptedKey;
448 if (auth.usesKeymaster()) {
450 if (!keymaster) return false;
452 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
453 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
454 km::AuthorizationSet keyParams;
455 km::HardwareAuthToken authToken;
456 std::tie(keyParams, authToken) = beginParams(auth, appId);
457 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
461 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
463 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
464 if (!FsyncDirectory(dir)) return false;
468 bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
469 const KeyAuthentication& auth, const KeyBuffer& key) {
470 if (pathExists(key_path)) {
471 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
474 if (pathExists(tmp_path)) {
475 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
476 destroyKey(tmp_path); // May be partially created so ignore errors
478 if (!storeKey(tmp_path, auth, key)) return false;
479 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
480 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
483 LOG(DEBUG) << "Created key: " << key_path;
487 bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
490 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
491 if (version != kCurrentVersion) {
492 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
495 std::string secdiscardable_hash;
496 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
497 std::string stretching;
498 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
500 if (stretchingNeedsSalt(stretching)) {
501 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
504 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
505 std::string encryptedMessage;
506 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
507 if (auth.usesKeymaster()) {
509 if (!keymaster) return false;
510 km::AuthorizationSet keyParams;
511 km::HardwareAuthToken authToken;
512 std::tie(keyParams, authToken) = beginParams(auth, appId);
513 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
517 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
522 static bool deleteKey(const std::string& dir) {
524 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
526 if (!keymaster) return false;
527 if (!keymaster.deleteKey(kmKey)) return false;
531 bool runSecdiscardSingle(const std::string& file) {
532 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
533 LOG(ERROR) << "secdiscard failed";
539 static bool recursiveDeleteKey(const std::string& dir) {
540 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
541 LOG(ERROR) << "recursive delete failed";
547 bool destroyKey(const std::string& dir) {
549 // Try each thing, even if previous things failed.
550 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
552 success &= deleteKey(dir);
554 auto secdiscard_cmd = std::vector<std::string>{
557 dir + "/" + kFn_encrypted_key,
558 dir + "/" + kFn_secdiscardable,
561 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
563 if (ForkExecvp(secdiscard_cmd) != 0) {
564 LOG(ERROR) << "secdiscard failed";
567 success &= recursiveDeleteKey(dir);
572 } // namespace android