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/sha.h>
34 #include <android-base/file.h>
35 #include <android-base/logging.h>
37 #include <cutils/properties.h>
39 #include <hardware/hw_auth_token.h>
41 #include <keymaster/authorization_set.h>
45 #include "crypto_scrypt.h"
51 const KeyAuthentication kEmptyAuthentication{"", ""};
53 static constexpr size_t AES_KEY_BYTES = 32;
54 static constexpr size_t GCM_NONCE_BYTES = 12;
55 static constexpr size_t GCM_MAC_BYTES = 16;
56 static constexpr size_t SALT_BYTES = 1 << 4;
57 static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
58 static constexpr size_t STRETCHED_BYTES = 1 << 6;
60 static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
62 static const char* kCurrentVersion = "1";
63 static const char* kRmPath = "/system/bin/rm";
64 static const char* kSecdiscardPath = "/system/bin/secdiscard";
65 static const char* kStretch_none = "none";
66 static const char* kStretch_nopassword = "nopassword";
67 static const std::string kStretchPrefix_scrypt = "scrypt ";
68 static const char* kFn_encrypted_key = "encrypted_key";
69 static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
70 static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
71 static const char* kFn_salt = "salt";
72 static const char* kFn_secdiscardable = "secdiscardable";
73 static const char* kFn_stretching = "stretching";
74 static const char* kFn_version = "version";
76 static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
77 if (actual != expected) {
78 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
85 static std::string hashSecdiscardable(const std::string& secdiscardable) {
89 // Personalise the hashing by introducing a fixed prefix.
90 // Hashing applications should use personalization except when there is a
91 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
92 std::string secdiscardableHashingPrefix = "Android secdiscardable SHA512";
93 secdiscardableHashingPrefix.resize(SHA512_CBLOCK);
94 SHA512_Update(&c, secdiscardableHashingPrefix.data(), secdiscardableHashingPrefix.size());
95 SHA512_Update(&c, secdiscardable.data(), secdiscardable.size());
96 std::string res(SHA512_DIGEST_LENGTH, '\0');
97 SHA512_Final(reinterpret_cast<uint8_t*>(&res[0]), &c);
101 static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
102 const std::string& appId, std::string* key) {
103 auto paramBuilder = keymaster::AuthorizationSetBuilder()
104 .AesEncryptionKey(AES_KEY_BYTES * 8)
105 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
106 .Authorization(keymaster::TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
107 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE);
108 addStringParam(¶mBuilder, keymaster::TAG_APPLICATION_ID, appId);
109 if (auth.token.empty()) {
110 LOG(DEBUG) << "Creating key that doesn't need auth token";
111 paramBuilder.Authorization(keymaster::TAG_NO_AUTH_REQUIRED);
113 LOG(DEBUG) << "Auth token required for key";
114 if (auth.token.size() != sizeof(hw_auth_token_t)) {
115 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
116 << auth.token.size() << " bytes";
119 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
120 paramBuilder.Authorization(keymaster::TAG_USER_SECURE_ID, at->user_id);
121 paramBuilder.Authorization(keymaster::TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD);
122 paramBuilder.Authorization(keymaster::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
124 return keymaster.generateKey(paramBuilder.build(), key);
127 static keymaster::AuthorizationSet beginParams(const KeyAuthentication& auth,
128 const std::string& appId) {
129 auto paramBuilder = keymaster::AuthorizationSetBuilder()
130 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
131 .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
132 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE);
133 addStringParam(¶mBuilder, keymaster::TAG_APPLICATION_ID, appId);
134 if (!auth.token.empty()) {
135 LOG(DEBUG) << "Supplying auth token to Keymaster";
136 addStringParam(¶mBuilder, keymaster::TAG_AUTH_TOKEN, auth.token);
138 return paramBuilder.build();
141 static bool readFileToString(const std::string& filename, std::string* result) {
142 if (!android::base::ReadFileToString(filename, result)) {
143 PLOG(ERROR) << "Failed to read from " << filename;
149 static bool writeStringToFile(const std::string& payload, const std::string& filename) {
150 if (!android::base::WriteStringToFile(payload, filename)) {
151 PLOG(ERROR) << "Failed to write to " << filename;
157 static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
158 keymaster_purpose_t purpose,
159 const keymaster::AuthorizationSet &keyParams,
160 const keymaster::AuthorizationSet &opParams,
161 keymaster::AuthorizationSet* outParams) {
162 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
164 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
165 keymaster::AuthorizationSet inParams;
166 inParams.push_back(keyParams);
167 inParams.push_back(opParams);
169 auto opHandle = keymaster.begin(purpose, kmKey, inParams, outParams);
173 if (opHandle.error() != KM_ERROR_KEY_REQUIRES_UPGRADE) return opHandle;
174 LOG(DEBUG) << "Upgrading key: " << dir;
176 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
177 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
178 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
179 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
180 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
181 return KeymasterOperation();
183 if (!keymaster.deleteKey(kmKey)) {
184 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
187 LOG(INFO) << "Key upgraded: " << dir;
191 static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
192 const keymaster::AuthorizationSet &keyParams,
193 const std::string& message, std::string* ciphertext) {
194 keymaster::AuthorizationSet opParams;
195 keymaster::AuthorizationSet outParams;
196 auto opHandle = begin(keymaster, dir, KM_PURPOSE_ENCRYPT, keyParams, opParams, &outParams);
197 if (!opHandle) return false;
198 keymaster_blob_t nonceBlob;
199 if (!outParams.GetTagValue(keymaster::TAG_NONCE, &nonceBlob)) {
200 LOG(ERROR) << "GCM encryption but no nonce generated";
203 // nonceBlob here is just a pointer into existing data, must not be freed
204 std::string nonce(reinterpret_cast<const char*>(nonceBlob.data), nonceBlob.data_length);
205 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
207 if (!opHandle.updateCompletely(message, &body)) return false;
210 if (!opHandle.finish(&mac)) return false;
211 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
212 *ciphertext = nonce + body + mac;
216 static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
217 const keymaster::AuthorizationSet &keyParams,
218 const std::string& ciphertext, std::string* message) {
219 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
220 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
221 auto opParams = addStringParam(keymaster::AuthorizationSetBuilder(),
222 keymaster::TAG_NONCE, nonce).build();
223 auto opHandle = begin(keymaster, dir, KM_PURPOSE_DECRYPT, keyParams, opParams, nullptr);
224 if (!opHandle) return false;
225 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
226 if (!opHandle.finish(nullptr)) return false;
230 static std::string getStretching() {
231 char paramstr[PROPERTY_VALUE_MAX];
233 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
234 return std::string() + kStretchPrefix_scrypt + paramstr;
237 static bool stretchingNeedsSalt(const std::string& stretching) {
238 return stretching != kStretch_nopassword && stretching != kStretch_none;
241 static bool stretchSecret(const std::string& stretching, const std::string& secret,
242 const std::string& salt, std::string* stretched) {
243 if (stretching == kStretch_nopassword) {
244 if (!secret.empty()) {
245 LOG(WARNING) << "Password present but stretching is nopassword";
249 } else if (stretching == kStretch_none) {
251 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
252 stretching.begin())) {
254 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
256 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
259 stretched->assign(STRETCHED_BYTES, '\0');
260 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
261 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(),
262 1 << Nf, 1 << rf, 1 << pf,
263 reinterpret_cast<uint8_t*>(&(*stretched)[0]), stretched->size()) != 0) {
264 LOG(ERROR) << "scrypt failed with params: " << stretching;
268 LOG(ERROR) << "Unknown stretching type: " << stretching;
274 static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
275 const std::string& salt, const std::string& secdiscardable,
276 std::string* appId) {
277 std::string stretched;
278 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
279 *appId = hashSecdiscardable(secdiscardable) + stretched;
283 bool storeKey(const std::string& dir, const KeyAuthentication& auth, const std::string& key) {
284 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
285 PLOG(ERROR) << "key mkdir " << dir;
288 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
289 std::string secdiscardable;
290 if (ReadRandomBytes(SECDISCARDABLE_BYTES, secdiscardable) != OK) {
291 // TODO status_t plays badly with PLOG, fix it.
292 LOG(ERROR) << "Random read failed";
295 if (!writeStringToFile(secdiscardable, dir + "/" + kFn_secdiscardable)) return false;
296 std::string stretching = auth.secret.empty() ? kStretch_nopassword : getStretching();
297 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
299 if (stretchingNeedsSalt(stretching)) {
300 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
301 LOG(ERROR) << "Random read failed";
304 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
307 if (!generateAppId(auth, stretching, salt, secdiscardable, &appId)) return false;
309 if (!keymaster) return false;
311 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
312 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
313 auto keyParams = beginParams(auth, appId);
314 std::string encryptedKey;
315 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, key, &encryptedKey)) return false;
316 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
320 bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, std::string* key) {
322 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
323 if (version != kCurrentVersion) {
324 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
327 std::string secdiscardable;
328 if (!readFileToString(dir + "/" + kFn_secdiscardable, &secdiscardable)) return false;
329 std::string stretching;
330 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
332 if (stretchingNeedsSalt(stretching)) {
333 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
336 if (!generateAppId(auth, stretching, salt, secdiscardable, &appId)) return false;
337 std::string encryptedMessage;
338 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
340 if (!keymaster) return false;
341 auto keyParams = beginParams(auth, appId);
342 return decryptWithKeymasterKey(keymaster, dir, keyParams, encryptedMessage, key);
345 static bool deleteKey(const std::string& dir) {
347 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
349 if (!keymaster) return false;
350 if (!keymaster.deleteKey(kmKey)) return false;
354 static bool runSecdiscard(const std::string& dir) {
356 std::vector<std::string>{kSecdiscardPath, "--",
357 dir + "/" + kFn_encrypted_key,
358 dir + "/" + kFn_keymaster_key_blob,
359 dir + "/" + kFn_secdiscardable,
361 LOG(ERROR) << "secdiscard failed";
367 static bool recursiveDeleteKey(const std::string& dir) {
368 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
369 LOG(ERROR) << "recursive delete failed";
375 bool destroyKey(const std::string& dir) {
377 // Try each thing, even if previous things failed.
378 success &= deleteKey(dir);
379 success &= runSecdiscard(dir);
380 success &= recursiveDeleteKey(dir);
385 } // namespace android