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"
27 #include <sys/types.h>
31 #include <openssl/sha.h>
33 #include <android-base/file.h>
34 #include <android-base/logging.h>
36 #include <cutils/properties.h>
38 #include <keymaster/authorization_set.h>
42 #include "crypto_scrypt.h"
49 const KeyAuthentication kEmptyAuthentication { "", "" };
51 static constexpr size_t AES_KEY_BYTES = 32;
52 static constexpr size_t GCM_NONCE_BYTES = 12;
53 static constexpr size_t GCM_MAC_BYTES = 16;
54 static constexpr size_t SALT_BYTES = 1<<4;
55 static constexpr size_t SECDISCARDABLE_BYTES = 1<<14;
56 static constexpr size_t STRETCHED_BYTES = 1<<6;
58 static const char* kCurrentVersion = "1";
59 static const char* kRmPath = "/system/bin/rm";
60 static const char* kSecdiscardPath = "/system/bin/secdiscard";
61 static const char* kStretch_none = "none";
62 static const char* kStretch_nopassword = "nopassword";
63 static const std::string kStretchPrefix_scrypt = "scrypt ";
64 static const char* kFn_encrypted_key = "encrypted_key";
65 static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
66 static const char* kFn_salt = "salt";
67 static const char* kFn_secdiscardable = "secdiscardable";
68 static const char* kFn_stretching = "stretching";
69 static const char* kFn_version = "version";
71 static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
72 if (actual != expected) {
73 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected
80 static std::string hashSecdiscardable(const std::string &secdiscardable) {
84 // Personalise the hashing by introducing a fixed prefix.
85 // Hashing applications should use personalization except when there is a
86 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
87 std::string secdiscardableHashingPrefix = "Android secdiscardable SHA512";
88 secdiscardableHashingPrefix.resize(SHA512_CBLOCK);
89 SHA512_Update(&c, secdiscardableHashingPrefix.data(), secdiscardableHashingPrefix.size());
90 SHA512_Update(&c, secdiscardable.data(), secdiscardable.size());
91 std::string res(SHA512_DIGEST_LENGTH, '\0');
92 SHA512_Final(reinterpret_cast<uint8_t *>(&res[0]), &c);
96 static bool generateKeymasterKey(Keymaster &keymaster,
97 const keymaster::AuthorizationSet &extraParams,
99 auto params = keymaster::AuthorizationSetBuilder()
100 .AesEncryptionKey(AES_KEY_BYTES * 8)
101 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
102 .Authorization(keymaster::TAG_MIN_MAC_LENGTH, GCM_MAC_BYTES * 8)
103 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
104 .Authorization(keymaster::TAG_NO_AUTH_REQUIRED) // FIXME integrate with gatekeeper
106 params.push_back(extraParams);
107 return keymaster.generateKey(params, key);
110 static bool encryptWithKeymasterKey(
111 Keymaster &keymaster,
112 const std::string &key,
113 const keymaster::AuthorizationSet &extraParams,
114 const std::string &message,
115 std::string &ciphertext) {
116 // FIXME fix repetition
117 auto params = keymaster::AuthorizationSetBuilder()
118 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
119 .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
120 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
122 params.push_back(extraParams);
123 keymaster::AuthorizationSet outParams;
124 auto opHandle = keymaster.begin(KM_PURPOSE_ENCRYPT, key, params, outParams);
125 if (!opHandle) return false;
126 keymaster_blob_t nonceBlob;
127 if (!outParams.GetTagValue(keymaster::TAG_NONCE, &nonceBlob)) {
128 LOG(ERROR) << "GCM encryption but no nonce generated";
131 // nonceBlob here is just a pointer into existing data, must not be freed
132 std::string nonce(reinterpret_cast<const char *>(nonceBlob.data), nonceBlob.data_length);
133 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
135 if (!opHandle.updateCompletely(message, body)) return false;
138 if (!opHandle.finishWithOutput(mac)) return false;
139 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
140 ciphertext = nonce + body + mac;
144 static bool decryptWithKeymasterKey(
145 Keymaster &keymaster, const std::string &key,
146 const keymaster::AuthorizationSet &extraParams,
147 const std::string &ciphertext,
148 std::string &message) {
149 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
150 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
151 // FIXME fix repetition
152 auto params = addStringParam(keymaster::AuthorizationSetBuilder(), keymaster::TAG_NONCE, nonce)
153 .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM)
154 .Authorization(keymaster::TAG_MAC_LENGTH, GCM_MAC_BYTES * 8)
155 .Authorization(keymaster::TAG_PADDING, KM_PAD_NONE)
157 params.push_back(extraParams);
159 auto opHandle = keymaster.begin(KM_PURPOSE_DECRYPT, key, params);
160 if (!opHandle) return false;
161 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
162 if (!opHandle.finish()) return false;
166 static bool readFileToString(const std::string &filename, std::string &result) {
167 if (!android::base::ReadFileToString(filename, &result)) {
168 PLOG(ERROR) << "Failed to read from " << filename;
174 static bool writeStringToFile(const std::string &payload, const std::string &filename) {
175 if (!android::base::WriteStringToFile(payload, filename)) {
176 PLOG(ERROR) << "Failed to write to " << filename;
182 static std::string getStretching() {
183 char paramstr[PROPERTY_VALUE_MAX];
185 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
186 return std::string() + kStretchPrefix_scrypt + paramstr;
189 static bool stretchingNeedsSalt(const std::string &stretching) {
190 return stretching != kStretch_nopassword && stretching != kStretch_none;
193 static bool stretchSecret(const std::string &stretching, const std::string &secret,
194 const std::string &salt, std::string &stretched) {
195 if (stretching == kStretch_nopassword) {
196 if (!secret.empty()) {
197 LOG(WARNING) << "Password present but stretching is nopassword";
201 } else if (stretching == kStretch_none) {
203 } else if (std::equal(kStretchPrefix_scrypt.begin(),
204 kStretchPrefix_scrypt.end(), stretching.begin())) {
206 if (!parse_scrypt_parameters(
207 stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf, &rf, &pf)) {
208 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
211 stretched.assign(STRETCHED_BYTES, '\0');
213 reinterpret_cast<const uint8_t *>(secret.data()), secret.size(),
214 reinterpret_cast<const uint8_t *>(salt.data()), salt.size(),
215 1 << Nf, 1 << rf, 1 << pf,
216 reinterpret_cast<uint8_t *>(&stretched[0]), stretched.size()) != 0) {
217 LOG(ERROR) << "scrypt failed with params: " << stretching;
221 LOG(ERROR) << "Unknown stretching type: " << stretching;
227 static bool buildParams(const KeyAuthentication &auth, const std::string &stretching,
228 const std::string &salt, const std::string &secdiscardable,
229 keymaster::AuthorizationSet &result) {
230 std::string stretched;
231 if (!stretchSecret(stretching, auth.secret, salt, stretched)) return false;
232 auto appId = hashSecdiscardable(secdiscardable) + stretched;
233 keymaster::AuthorizationSetBuilder paramBuilder;
234 addStringParam(paramBuilder, keymaster::TAG_APPLICATION_ID, appId);
235 if (!auth.token.empty()) {
236 addStringParam(paramBuilder, keymaster::TAG_AUTH_TOKEN, auth.token);
238 result = paramBuilder.build();
242 bool storeKey(const std::string &dir, const KeyAuthentication &auth, const std::string &key) {
243 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
244 PLOG(ERROR) << "key mkdir " << dir;
247 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
248 std::string secdiscardable;
249 if (ReadRandomBytes(SECDISCARDABLE_BYTES, secdiscardable) != OK) {
250 // TODO status_t plays badly with PLOG, fix it.
251 LOG(ERROR) << "Random read failed";
254 if (!writeStringToFile(secdiscardable, dir + "/" + kFn_secdiscardable)) return false;
255 std::string stretching = auth.secret.empty() ? kStretch_nopassword : getStretching();
256 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
258 if (stretchingNeedsSalt(stretching)) {
259 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
260 LOG(ERROR) << "Random read failed";
263 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
265 keymaster::AuthorizationSet extraParams;
266 if (!buildParams(auth, stretching, salt, secdiscardable, extraParams)) return false;
268 if (!keymaster) return false;
270 if (!generateKeymasterKey(keymaster, extraParams, kmKey)) return false;
271 std::string encryptedKey;
272 if (!encryptWithKeymasterKey(keymaster, kmKey, extraParams, key, encryptedKey)) return false;
273 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
274 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
278 bool retrieveKey(const std::string &dir, const KeyAuthentication &auth, std::string &key) {
280 if (!readFileToString(dir + "/" + kFn_version, version)) return false;
281 if (version != kCurrentVersion) {
282 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
285 std::string secdiscardable;
286 if (!readFileToString(dir + "/" + kFn_secdiscardable, secdiscardable)) return false;
287 std::string stretching;
288 if (!readFileToString(dir + "/" + kFn_stretching, stretching)) return false;
290 if (stretchingNeedsSalt(stretching)) {
291 if (!readFileToString(dir + "/" + kFn_salt, salt)) return false;
293 keymaster::AuthorizationSet extraParams;
294 if (!buildParams(auth, stretching, salt, secdiscardable, extraParams)) return false;
296 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
297 std::string encryptedMessage;
298 if (!readFileToString(dir + "/" + kFn_encrypted_key, encryptedMessage)) return false;
300 if (!keymaster) return false;
301 return decryptWithKeymasterKey(keymaster, kmKey, extraParams, encryptedMessage, key);
304 static bool deleteKey(const std::string &dir) {
306 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, kmKey)) return false;
308 if (!keymaster) return false;
309 if (!keymaster.deleteKey(kmKey)) return false;
313 static bool secdiscardSecdiscardable(const std::string &dir) {
314 if (ForkExecvp(std::vector<std::string> {
315 kSecdiscardPath, "--", dir + "/" + kFn_secdiscardable}) != 0) {
316 LOG(ERROR) << "secdiscard failed";
322 static bool recursiveDeleteKey(const std::string &dir) {
323 if (ForkExecvp(std::vector<std::string> {
324 kRmPath, "-rf", dir}) != 0) {
325 LOG(ERROR) << "recursive delete failed";
331 bool destroyKey(const std::string &dir) {
333 // Try each thing, even if previous things failed.
334 success &= deleteKey(dir);
335 success &= secdiscardSecdiscardable(dir);
336 success &= recursiveDeleteKey(dir);
341 } // namespace android