blob: 0b1874c9de8f7ebcf6382847a9626dfc74c71ecf [file] [log] [blame]
Paul Crowley1ef25582016-01-21 20:26:12 +00001/*
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 "KeyStorage.h"
18
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070019#include "Checkpoint.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000020#include "Keymaster.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000021#include "ScryptParameters.h"
Paul Crowley1ef25582016-01-21 20:26:12 +000022#include "Utils.h"
23
Daniel Rosenberg8cc57162019-06-06 20:38:38 -070024#include <thread>
Paul Crowley1ef25582016-01-21 20:26:12 +000025#include <vector>
26
27#include <errno.h>
Paul Crowleydff8c722016-05-16 08:14:56 -070028#include <stdio.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000029#include <sys/stat.h>
30#include <sys/types.h>
31#include <sys/wait.h>
32#include <unistd.h>
33
Paul Crowley6ab2cab2017-01-04 22:32:40 -080034#include <openssl/err.h>
35#include <openssl/evp.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000036#include <openssl/sha.h>
37
38#include <android-base/file.h>
39#include <android-base/logging.h>
Daniel Rosenberg8cc57162019-06-06 20:38:38 -070040#include <android-base/properties.h>
Daniel Rosenbergd2906b82019-06-07 14:18:14 -070041#include <android-base/unique_fd.h>
Paul Crowley1ef25582016-01-21 20:26:12 +000042
Paul Crowley63c18d32016-02-10 14:02:47 +000043#include <cutils/properties.h>
44
Paul Crowley320e5e12016-03-04 14:07:05 -080045#include <hardware/hw_auth_token.h>
Shawn Willdenae8f06f2020-01-16 13:21:42 -070046#include <keymasterV4_1/authorization_set.h>
47#include <keymasterV4_1/keymaster_utils.h>
Paul Crowley320e5e12016-03-04 14:07:05 -080048
Paul Crowley63c18d32016-02-10 14:02:47 +000049extern "C" {
50
51#include "crypto_scrypt.h"
Paul Crowley63c18d32016-02-10 14:02:47 +000052}
53
Paul Crowley1ef25582016-01-21 20:26:12 +000054namespace android {
55namespace vold {
56
Paul Crowleydf528a72016-03-09 09:31:37 -080057const KeyAuthentication kEmptyAuthentication{"", ""};
Paul Crowley05720802016-02-08 15:55:41 +000058
Paul Crowley1ef25582016-01-21 20:26:12 +000059static constexpr size_t AES_KEY_BYTES = 32;
60static constexpr size_t GCM_NONCE_BYTES = 12;
61static constexpr size_t GCM_MAC_BYTES = 16;
Paul Crowleydf528a72016-03-09 09:31:37 -080062static constexpr size_t SALT_BYTES = 1 << 4;
63static constexpr size_t SECDISCARDABLE_BYTES = 1 << 14;
64static constexpr size_t STRETCHED_BYTES = 1 << 6;
Paul Crowley1ef25582016-01-21 20:26:12 +000065
Shawn Willden785365b2018-01-20 09:37:36 -070066static constexpr uint32_t AUTH_TIMEOUT = 30; // Seconds
Shivaprasad Hongal92292622018-07-05 14:49:12 -070067constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
Paul Crowleyb3de3372016-04-27 12:58:41 -070068
Paul Crowley05720802016-02-08 15:55:41 +000069static const char* kCurrentVersion = "1";
Paul Crowley1ef25582016-01-21 20:26:12 +000070static const char* kRmPath = "/system/bin/rm";
71static const char* kSecdiscardPath = "/system/bin/secdiscard";
Paul Crowley63c18d32016-02-10 14:02:47 +000072static const char* kStretch_none = "none";
73static const char* kStretch_nopassword = "nopassword";
74static const std::string kStretchPrefix_scrypt = "scrypt ";
Paul Crowley6ab2cab2017-01-04 22:32:40 -080075static const char* kHashPrefix_secdiscardable = "Android secdiscardable SHA512";
76static const char* kHashPrefix_keygen = "Android key wrapping key generation SHA512";
Paul Crowley1ef25582016-01-21 20:26:12 +000077static const char* kFn_encrypted_key = "encrypted_key";
Paul Crowley05720802016-02-08 15:55:41 +000078static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
Paul Crowleydff8c722016-05-16 08:14:56 -070079static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
Paul Crowley63c18d32016-02-10 14:02:47 +000080static const char* kFn_salt = "salt";
Paul Crowley1ef25582016-01-21 20:26:12 +000081static const char* kFn_secdiscardable = "secdiscardable";
Paul Crowley05720802016-02-08 15:55:41 +000082static const char* kFn_stretching = "stretching";
83static const char* kFn_version = "version";
Paul Crowley1ef25582016-01-21 20:26:12 +000084
Paul Crowley13ffd8e2016-01-27 14:30:22 +000085static bool checkSize(const std::string& kind, size_t actual, size_t expected) {
Paul Crowley1ef25582016-01-21 20:26:12 +000086 if (actual != expected) {
Paul Crowleydf528a72016-03-09 09:31:37 -080087 LOG(ERROR) << "Wrong number of bytes in " << kind << ", expected " << expected << " got "
88 << actual;
Paul Crowley1ef25582016-01-21 20:26:12 +000089 return false;
90 }
91 return true;
92}
93
Paul Crowley26a53882017-10-26 11:16:39 -070094static void hashWithPrefix(char const* prefix, const std::string& tohash, std::string* res) {
Paul Crowley1ef25582016-01-21 20:26:12 +000095 SHA512_CTX c;
96
97 SHA512_Init(&c);
98 // Personalise the hashing by introducing a fixed prefix.
99 // Hashing applications should use personalization except when there is a
100 // specific reason not to; see section 4.11 of https://www.schneier.com/skein1.3.pdf
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800101 std::string hashingPrefix = prefix;
102 hashingPrefix.resize(SHA512_CBLOCK);
103 SHA512_Update(&c, hashingPrefix.data(), hashingPrefix.size());
104 SHA512_Update(&c, tohash.data(), tohash.size());
Paul Crowley26a53882017-10-26 11:16:39 -0700105 res->assign(SHA512_DIGEST_LENGTH, '\0');
106 SHA512_Final(reinterpret_cast<uint8_t*>(&(*res)[0]), &c);
Paul Crowley1ef25582016-01-21 20:26:12 +0000107}
108
Paul Crowleydf528a72016-03-09 09:31:37 -0800109static bool generateKeymasterKey(Keymaster& keymaster, const KeyAuthentication& auth,
110 const std::string& appId, std::string* key) {
Shawn Willden35351812018-01-22 09:08:32 -0700111 auto paramBuilder = km::AuthorizationSetBuilder()
Paul Crowleydf528a72016-03-09 09:31:37 -0800112 .AesEncryptionKey(AES_KEY_BYTES * 8)
Shawn Willden35351812018-01-22 09:08:32 -0700113 .GcmModeMinMacLen(GCM_MAC_BYTES * 8)
114 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
Paul Crowley320e5e12016-03-04 14:07:05 -0800115 if (auth.token.empty()) {
116 LOG(DEBUG) << "Creating key that doesn't need auth token";
Shawn Willden35351812018-01-22 09:08:32 -0700117 paramBuilder.Authorization(km::TAG_NO_AUTH_REQUIRED);
Paul Crowley320e5e12016-03-04 14:07:05 -0800118 } else {
119 LOG(DEBUG) << "Auth token required for key";
120 if (auth.token.size() != sizeof(hw_auth_token_t)) {
121 LOG(ERROR) << "Auth token should be " << sizeof(hw_auth_token_t) << " bytes, was "
Paul Crowleydf528a72016-03-09 09:31:37 -0800122 << auth.token.size() << " bytes";
Paul Crowley320e5e12016-03-04 14:07:05 -0800123 return false;
124 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800125 const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
Paul Crowleyd281de72018-08-30 15:25:19 -0700126 auto user_id = at->user_id; // Make a copy because at->user_id is unaligned.
127 paramBuilder.Authorization(km::TAG_USER_SECURE_ID, user_id);
Shawn Willden35351812018-01-22 09:08:32 -0700128 paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
129 paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
Paul Crowley320e5e12016-03-04 14:07:05 -0800130 }
Shawn Willden8431fe22018-12-06 07:45:02 -0700131
132 auto paramsWithRollback = paramBuilder;
133 paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
134
135 // Generate rollback-resistant key if possible.
136 return keymaster.generateKey(paramsWithRollback, key) ||
137 keymaster.generateKey(paramBuilder, key);
Paul Crowley320e5e12016-03-04 14:07:05 -0800138}
139
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800140bool generateWrappedStorageKey(KeyBuffer* key) {
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700141 Keymaster keymaster;
142 if (!keymaster) return false;
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700143 std::string key_temp;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800144 auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700145 km::KeyParameter param1;
Steven Laver4771d982020-01-23 17:03:42 -0800146 param1.tag = static_cast<::android::hardware::keymaster::V4_0::Tag>(
Steven Laver7fe4cdb2020-02-14 13:18:26 -0800147 android::hardware::keymaster::V4_0::KM_TAG_FBE_ICE);
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700148 param1.f.boolValue = true;
149 paramBuilder.push_back(param1);
Steven Laver7fe4cdb2020-02-14 13:18:26 -0800150 //paramBuilder.Authorization(km::TAG_ROLLBACK_RESISTANCE);
151 //paramBuilder.Authorization(km::TAG_STORAGE_KEY);
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700152 if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
153 *key = KeyBuffer(key_temp.size());
154 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
155 return true;
156}
157
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800158bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700159 Keymaster keymaster;
160 if (!keymaster) return false;
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800161 std::string key_temp;
Smita Ghosh85c46ea2019-01-11 10:38:09 -0800162
Neeraj Soni256fc9c2020-02-26 15:59:27 +0530163 auto ret = keymaster.exportKey(kmKey, &key_temp);
164 if (ret != km::ErrorCode::OK) {
165 if (ret == km::ErrorCode::KEY_REQUIRES_UPGRADE) {
166 std::string kmKeyStr(reinterpret_cast<const char*>(kmKey.data()), kmKey.size());
167 std::string Keystr;
168 if (!keymaster.upgradeKey(kmKeyStr, km::AuthorizationSet(), &Keystr)) return false;
169 KeyBuffer upgradedKey = KeyBuffer(Keystr.size());
170 memcpy(reinterpret_cast<void*>(upgradedKey.data()), Keystr.c_str(), upgradedKey.size());
171 ret = keymaster.exportKey(upgradedKey, &key_temp);
172 if (ret != km::ErrorCode::OK) return false;
173 } else {
174 return false;
175 }
176 }
Barani Muthukumaran3dfb0942020-02-03 13:06:45 -0800177 *key = KeyBuffer(key_temp.size());
178 memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
179 return true;
Shivaprasad Hongal92292622018-07-05 14:49:12 -0700180}
181
Shawn Willden35351812018-01-22 09:08:32 -0700182static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
183 const KeyAuthentication& auth, const std::string& appId) {
184 auto paramBuilder = km::AuthorizationSetBuilder()
185 .GcmModeMacLen(GCM_MAC_BYTES * 8)
186 .Authorization(km::TAG_APPLICATION_ID, km::support::blob2hidlVec(appId));
187 km::HardwareAuthToken authToken;
Paul Crowley320e5e12016-03-04 14:07:05 -0800188 if (!auth.token.empty()) {
189 LOG(DEBUG) << "Supplying auth token to Keymaster";
Shawn Willden35351812018-01-22 09:08:32 -0700190 authToken = km::support::hidlVec2AuthToken(km::support::blob2hidlVec(auth.token));
Paul Crowley320e5e12016-03-04 14:07:05 -0800191 }
Shawn Willden35351812018-01-22 09:08:32 -0700192 return {paramBuilder, authToken};
Paul Crowley1ef25582016-01-21 20:26:12 +0000193}
194
Paul Crowleydf528a72016-03-09 09:31:37 -0800195static bool readFileToString(const std::string& filename, std::string* result) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800196 if (!android::base::ReadFileToString(filename, result)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800197 PLOG(ERROR) << "Failed to read from " << filename;
198 return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000199 }
200 return true;
201}
202
Paul Crowley26a53882017-10-26 11:16:39 -0700203static bool readRandomBytesOrLog(size_t count, std::string* out) {
204 auto status = ReadRandomBytes(count, *out);
205 if (status != OK) {
206 LOG(ERROR) << "Random read failed with status: " << status;
207 return false;
208 }
209 return true;
210}
211
212bool createSecdiscardable(const std::string& filename, std::string* hash) {
213 std::string secdiscardable;
214 if (!readRandomBytesOrLog(SECDISCARDABLE_BYTES, &secdiscardable)) return false;
215 if (!writeStringToFile(secdiscardable, filename)) return false;
216 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
217 return true;
218}
219
220bool readSecdiscardable(const std::string& filename, std::string* hash) {
221 std::string secdiscardable;
222 if (!readFileToString(filename, &secdiscardable)) return false;
223 hashWithPrefix(kHashPrefix_secdiscardable, secdiscardable, hash);
224 return true;
225}
226
Daniel Rosenberg8cc57162019-06-06 20:38:38 -0700227static void deferedKmDeleteKey(const std::string& kmkey) {
228 while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
229 LOG(ERROR) << "Wait for boot timed out";
230 }
231 Keymaster keymaster;
232 if (!keymaster || !keymaster.deleteKey(kmkey)) {
233 LOG(ERROR) << "Defered Key deletion failed during upgrade";
234 }
235}
236
237bool kmDeleteKey(Keymaster& keymaster, const std::string& kmKey) {
238 bool needs_cp = cp_needsCheckpoint();
239
240 if (needs_cp) {
241 std::thread(deferedKmDeleteKey, kmKey).detach();
242 LOG(INFO) << "Deferring Key deletion during upgrade";
243 return true;
244 } else {
245 return keymaster.deleteKey(kmKey);
246 }
247}
248
Shawn Willden35351812018-01-22 09:08:32 -0700249static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
250 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
251 const km::AuthorizationSet& opParams,
252 const km::HardwareAuthToken& authToken,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800253 km::AuthorizationSet* outParams, bool keepOld) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700254 auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
255 std::string kmKey;
256 if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
Shawn Willden35351812018-01-22 09:08:32 -0700257 km::AuthorizationSet inParams(keyParams);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100258 inParams.append(opParams.begin(), opParams.end());
Paul Crowleydff8c722016-05-16 08:14:56 -0700259 for (;;) {
Shawn Willden35351812018-01-22 09:08:32 -0700260 auto opHandle = keymaster.begin(purpose, kmKey, inParams, authToken, outParams);
Paul Crowleydff8c722016-05-16 08:14:56 -0700261 if (opHandle) {
262 return opHandle;
263 }
Shawn Willden35351812018-01-22 09:08:32 -0700264 if (opHandle.errorCode() != km::ErrorCode::KEY_REQUIRES_UPGRADE) return opHandle;
Paul Crowleydff8c722016-05-16 08:14:56 -0700265 LOG(DEBUG) << "Upgrading key: " << dir;
266 std::string newKey;
267 if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
268 auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
269 if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800270 if (!keepOld) {
271 if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
272 PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
273 return KeymasterOperation();
274 }
Woody Lin37c82f52019-03-11 20:58:20 +0800275 if (!android::vold::FsyncDirectory(dir)) {
276 LOG(ERROR) << "Key dir sync failed: " << dir;
277 return KeymasterOperation();
278 }
Daniel Rosenberg8cc57162019-06-06 20:38:38 -0700279 if (!kmDeleteKey(keymaster, kmKey)) {
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800280 LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
281 }
Paul Crowleydff8c722016-05-16 08:14:56 -0700282 }
283 kmKey = newKey;
284 LOG(INFO) << "Key upgraded: " << dir;
285 }
286}
287
288static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700289 const km::AuthorizationSet& keyParams,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800290 const km::HardwareAuthToken& authToken, const KeyBuffer& message,
291 std::string* ciphertext, bool keepOld) {
Shawn Willden35351812018-01-22 09:08:32 -0700292 km::AuthorizationSet opParams;
293 km::AuthorizationSet outParams;
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800294 auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
295 &outParams, keepOld);
Paul Crowleydff8c722016-05-16 08:14:56 -0700296 if (!opHandle) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700297 auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
Janis Danisevskis8e537b82016-10-26 14:27:10 +0100298 if (!nonceBlob.isOk()) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700299 LOG(ERROR) << "GCM encryption but no nonce generated";
300 return false;
301 }
302 // nonceBlob here is just a pointer into existing data, must not be freed
Shawn Willden785365b2018-01-20 09:37:36 -0700303 std::string nonce(reinterpret_cast<const char*>(&nonceBlob.value()[0]),
304 nonceBlob.value().size());
Paul Crowleydff8c722016-05-16 08:14:56 -0700305 if (!checkSize("nonce", nonce.size(), GCM_NONCE_BYTES)) return false;
306 std::string body;
307 if (!opHandle.updateCompletely(message, &body)) return false;
308
309 std::string mac;
310 if (!opHandle.finish(&mac)) return false;
311 if (!checkSize("mac", mac.size(), GCM_MAC_BYTES)) return false;
312 *ciphertext = nonce + body + mac;
313 return true;
314}
315
316static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
Shawn Willden35351812018-01-22 09:08:32 -0700317 const km::AuthorizationSet& keyParams,
318 const km::HardwareAuthToken& authToken,
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800319 const std::string& ciphertext, KeyBuffer* message,
320 bool keepOld) {
Paul Crowleydff8c722016-05-16 08:14:56 -0700321 auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
322 auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
Shawn Willden35351812018-01-22 09:08:32 -0700323 auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
324 km::support::blob2hidlVec(nonce));
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800325 auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
326 nullptr, keepOld);
Paul Crowleydff8c722016-05-16 08:14:56 -0700327 if (!opHandle) return false;
328 if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
329 if (!opHandle.finish(nullptr)) return false;
330 return true;
331}
332
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800333static std::string getStretching(const KeyAuthentication& auth) {
334 if (!auth.usesKeymaster()) {
335 return kStretch_none;
336 } else if (auth.secret.empty()) {
337 return kStretch_nopassword;
338 } else {
339 char paramstr[PROPERTY_VALUE_MAX];
Paul Crowley63c18d32016-02-10 14:02:47 +0000340
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800341 property_get(SCRYPT_PROP, paramstr, SCRYPT_DEFAULTS);
342 return std::string() + kStretchPrefix_scrypt + paramstr;
343 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000344}
345
Paul Crowleydf528a72016-03-09 09:31:37 -0800346static bool stretchingNeedsSalt(const std::string& stretching) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000347 return stretching != kStretch_nopassword && stretching != kStretch_none;
348}
349
Paul Crowleydf528a72016-03-09 09:31:37 -0800350static bool stretchSecret(const std::string& stretching, const std::string& secret,
351 const std::string& salt, std::string* stretched) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000352 if (stretching == kStretch_nopassword) {
353 if (!secret.empty()) {
Paul Crowleyd9b92952016-03-04 13:45:00 -0800354 LOG(WARNING) << "Password present but stretching is nopassword";
Paul Crowley63c18d32016-02-10 14:02:47 +0000355 // Continue anyway
356 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800357 stretched->clear();
Paul Crowley63c18d32016-02-10 14:02:47 +0000358 } else if (stretching == kStretch_none) {
Paul Crowleya051eb72016-03-08 16:08:32 -0800359 *stretched = secret;
Paul Crowleydf528a72016-03-09 09:31:37 -0800360 } else if (std::equal(kStretchPrefix_scrypt.begin(), kStretchPrefix_scrypt.end(),
361 stretching.begin())) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000362 int Nf, rf, pf;
Paul Crowleydf528a72016-03-09 09:31:37 -0800363 if (!parse_scrypt_parameters(stretching.substr(kStretchPrefix_scrypt.size()).c_str(), &Nf,
364 &rf, &pf)) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000365 LOG(ERROR) << "Unable to parse scrypt params in stretching: " << stretching;
366 return false;
367 }
Paul Crowleya051eb72016-03-08 16:08:32 -0800368 stretched->assign(STRETCHED_BYTES, '\0');
Paul Crowleydf528a72016-03-09 09:31:37 -0800369 if (crypto_scrypt(reinterpret_cast<const uint8_t*>(secret.data()), secret.size(),
Shawn Willden785365b2018-01-20 09:37:36 -0700370 reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), 1 << Nf,
371 1 << rf, 1 << pf, reinterpret_cast<uint8_t*>(&(*stretched)[0]),
372 stretched->size()) != 0) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000373 LOG(ERROR) << "scrypt failed with params: " << stretching;
374 return false;
375 }
376 } else {
377 LOG(ERROR) << "Unknown stretching type: " << stretching;
378 return false;
379 }
380 return true;
381}
382
Paul Crowleydf528a72016-03-09 09:31:37 -0800383static bool generateAppId(const KeyAuthentication& auth, const std::string& stretching,
Paul Crowley26a53882017-10-26 11:16:39 -0700384 const std::string& salt, const std::string& secdiscardable_hash,
Paul Crowleydf528a72016-03-09 09:31:37 -0800385 std::string* appId) {
Paul Crowley63c18d32016-02-10 14:02:47 +0000386 std::string stretched;
Paul Crowleya051eb72016-03-08 16:08:32 -0800387 if (!stretchSecret(stretching, auth.secret, salt, &stretched)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700388 *appId = secdiscardable_hash + stretched;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800389 return true;
390}
391
392static void logOpensslError() {
393 LOG(ERROR) << "Openssl error: " << ERR_get_error();
394}
395
Shawn Willden785365b2018-01-20 09:37:36 -0700396static bool encryptWithoutKeymaster(const std::string& preKey, const KeyBuffer& plaintext,
397 std::string* ciphertext) {
Paul Crowley26a53882017-10-26 11:16:39 -0700398 std::string key;
399 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800400 key.resize(AES_KEY_BYTES);
401 if (!readRandomBytesOrLog(GCM_NONCE_BYTES, ciphertext)) return false;
402 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
403 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
404 if (!ctx) {
405 logOpensslError();
406 return false;
407 }
408 if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700409 reinterpret_cast<const uint8_t*>(key.data()),
410 reinterpret_cast<const uint8_t*>(ciphertext->data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800411 logOpensslError();
412 return false;
413 }
414 ciphertext->resize(GCM_NONCE_BYTES + plaintext.size() + GCM_MAC_BYTES);
415 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700416 if (1 != EVP_EncryptUpdate(
417 ctx.get(), reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES),
418 &outlen, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800419 logOpensslError();
420 return false;
421 }
422 if (outlen != static_cast<int>(plaintext.size())) {
423 LOG(ERROR) << "GCM ciphertext length should be " << plaintext.size() << " was " << outlen;
424 return false;
425 }
Shawn Willden785365b2018-01-20 09:37:36 -0700426 if (1 != EVP_EncryptFinal_ex(
427 ctx.get(),
428 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES + plaintext.size()),
429 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800430 logOpensslError();
431 return false;
432 }
433 if (outlen != 0) {
434 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
435 return false;
436 }
437 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700438 reinterpret_cast<uint8_t*>(&(*ciphertext)[0] + GCM_NONCE_BYTES +
439 plaintext.size()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800440 logOpensslError();
441 return false;
442 }
443 return true;
444}
445
Shawn Willden785365b2018-01-20 09:37:36 -0700446static bool decryptWithoutKeymaster(const std::string& preKey, const std::string& ciphertext,
447 KeyBuffer* plaintext) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800448 if (ciphertext.size() < GCM_NONCE_BYTES + GCM_MAC_BYTES) {
449 LOG(ERROR) << "GCM ciphertext too small: " << ciphertext.size();
450 return false;
451 }
Paul Crowley26a53882017-10-26 11:16:39 -0700452 std::string key;
453 hashWithPrefix(kHashPrefix_keygen, preKey, &key);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800454 key.resize(AES_KEY_BYTES);
455 auto ctx = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>(
456 EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
457 if (!ctx) {
458 logOpensslError();
459 return false;
460 }
461 if (1 != EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL,
Shawn Willden785365b2018-01-20 09:37:36 -0700462 reinterpret_cast<const uint8_t*>(key.data()),
463 reinterpret_cast<const uint8_t*>(ciphertext.data()))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800464 logOpensslError();
465 return false;
466 }
Pavel Grafove2e2d302017-08-01 17:15:53 +0100467 *plaintext = KeyBuffer(ciphertext.size() - GCM_NONCE_BYTES - GCM_MAC_BYTES);
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800468 int outlen;
Shawn Willden785365b2018-01-20 09:37:36 -0700469 if (1 != EVP_DecryptUpdate(ctx.get(), reinterpret_cast<uint8_t*>(&(*plaintext)[0]), &outlen,
470 reinterpret_cast<const uint8_t*>(ciphertext.data() + GCM_NONCE_BYTES),
471 plaintext->size())) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800472 logOpensslError();
473 return false;
474 }
475 if (outlen != static_cast<int>(plaintext->size())) {
476 LOG(ERROR) << "GCM plaintext length should be " << plaintext->size() << " was " << outlen;
477 return false;
478 }
479 if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, GCM_MAC_BYTES,
Shawn Willden785365b2018-01-20 09:37:36 -0700480 const_cast<void*>(reinterpret_cast<const void*>(
481 ciphertext.data() + GCM_NONCE_BYTES + plaintext->size())))) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800482 logOpensslError();
483 return false;
484 }
485 if (1 != EVP_DecryptFinal_ex(ctx.get(),
Shawn Willden785365b2018-01-20 09:37:36 -0700486 reinterpret_cast<uint8_t*>(&(*plaintext)[0] + plaintext->size()),
487 &outlen)) {
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800488 logOpensslError();
489 return false;
490 }
491 if (outlen != 0) {
492 LOG(ERROR) << "GCM EncryptFinal should be 0, was " << outlen;
493 return false;
494 }
Paul Crowley63c18d32016-02-10 14:02:47 +0000495 return true;
Paul Crowley05720802016-02-08 15:55:41 +0000496}
497
Paul Crowleyf71ace32016-06-02 11:01:19 -0700498bool pathExists(const std::string& path) {
499 return access(path.c_str(), F_OK) == 0;
500}
501
Pavel Grafove2e2d302017-08-01 17:15:53 +0100502bool storeKey(const std::string& dir, const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000503 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
504 PLOG(ERROR) << "key mkdir " << dir;
505 return false;
506 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800507 if (!writeStringToFile(kCurrentVersion, dir + "/" + kFn_version)) return false;
Paul Crowley26a53882017-10-26 11:16:39 -0700508 std::string secdiscardable_hash;
509 if (!createSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800510 std::string stretching = getStretching(auth);
Paul Crowleydf528a72016-03-09 09:31:37 -0800511 if (!writeStringToFile(stretching, dir + "/" + kFn_stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000512 std::string salt;
513 if (stretchingNeedsSalt(stretching)) {
514 if (ReadRandomBytes(SALT_BYTES, salt) != OK) {
515 LOG(ERROR) << "Random read failed";
516 return false;
517 }
Paul Crowleydf528a72016-03-09 09:31:37 -0800518 if (!writeStringToFile(salt, dir + "/" + kFn_salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000519 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800520 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700521 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley320e5e12016-03-04 14:07:05 -0800522 std::string encryptedKey;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800523 if (auth.usesKeymaster()) {
524 Keymaster keymaster;
525 if (!keymaster) return false;
526 std::string kmKey;
527 if (!generateKeymasterKey(keymaster, auth, appId, &kmKey)) return false;
528 if (!writeStringToFile(kmKey, dir + "/" + kFn_keymaster_key_blob)) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700529 km::AuthorizationSet keyParams;
530 km::HardwareAuthToken authToken;
531 std::tie(keyParams, authToken) = beginParams(auth, appId);
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800532 if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
533 false))
Shawn Willden35351812018-01-22 09:08:32 -0700534 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800535 } else {
536 if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
537 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000538 if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
Paul Crowley621d9b92018-12-07 15:36:09 -0800539 if (!FsyncDirectory(dir)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000540 return true;
541}
542
Paul Crowleyf71ace32016-06-02 11:01:19 -0700543bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
Pavel Grafove2e2d302017-08-01 17:15:53 +0100544 const KeyAuthentication& auth, const KeyBuffer& key) {
Paul Crowleyf71ace32016-06-02 11:01:19 -0700545 if (pathExists(key_path)) {
546 LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
547 return false;
548 }
549 if (pathExists(tmp_path)) {
550 LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
551 destroyKey(tmp_path); // May be partially created so ignore errors
552 }
553 if (!storeKey(tmp_path, auth, key)) return false;
554 if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
555 PLOG(ERROR) << "Unable to move new key to location: " << key_path;
556 return false;
557 }
558 LOG(DEBUG) << "Created key: " << key_path;
559 return true;
560}
561
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800562bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
563 bool keepOld) {
Paul Crowley05720802016-02-08 15:55:41 +0000564 std::string version;
Paul Crowleya051eb72016-03-08 16:08:32 -0800565 if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
Paul Crowley05720802016-02-08 15:55:41 +0000566 if (version != kCurrentVersion) {
567 LOG(ERROR) << "Version mismatch, expected " << kCurrentVersion << " got " << version;
568 return false;
569 }
Paul Crowley26a53882017-10-26 11:16:39 -0700570 std::string secdiscardable_hash;
571 if (!readSecdiscardable(dir + "/" + kFn_secdiscardable, &secdiscardable_hash)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000572 std::string stretching;
Paul Crowleya051eb72016-03-08 16:08:32 -0800573 if (!readFileToString(dir + "/" + kFn_stretching, &stretching)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000574 std::string salt;
575 if (stretchingNeedsSalt(stretching)) {
Paul Crowleydf528a72016-03-09 09:31:37 -0800576 if (!readFileToString(dir + "/" + kFn_salt, &salt)) return false;
Paul Crowley63c18d32016-02-10 14:02:47 +0000577 }
Paul Crowley320e5e12016-03-04 14:07:05 -0800578 std::string appId;
Paul Crowley26a53882017-10-26 11:16:39 -0700579 if (!generateAppId(auth, stretching, salt, secdiscardable_hash, &appId)) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000580 std::string encryptedMessage;
Paul Crowleya051eb72016-03-08 16:08:32 -0800581 if (!readFileToString(dir + "/" + kFn_encrypted_key, &encryptedMessage)) return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800582 if (auth.usesKeymaster()) {
583 Keymaster keymaster;
584 if (!keymaster) return false;
Shawn Willden35351812018-01-22 09:08:32 -0700585 km::AuthorizationSet keyParams;
586 km::HardwareAuthToken authToken;
587 std::tie(keyParams, authToken) = beginParams(auth, appId);
Daniel Rosenberg690d6de2018-12-14 01:08:10 -0800588 if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
589 keepOld))
Shawn Willden785365b2018-01-20 09:37:36 -0700590 return false;
Paul Crowley6ab2cab2017-01-04 22:32:40 -0800591 } else {
592 if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
593 }
594 return true;
Paul Crowley1ef25582016-01-21 20:26:12 +0000595}
596
Paul Crowleydf528a72016-03-09 09:31:37 -0800597static bool deleteKey(const std::string& dir) {
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000598 std::string kmKey;
Paul Crowleya051eb72016-03-08 16:08:32 -0800599 if (!readFileToString(dir + "/" + kFn_keymaster_key_blob, &kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000600 Keymaster keymaster;
601 if (!keymaster) return false;
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000602 if (!keymaster.deleteKey(kmKey)) return false;
Paul Crowley1ef25582016-01-21 20:26:12 +0000603 return true;
604}
605
Rubin Xu2436e272017-04-27 20:43:10 +0100606bool runSecdiscardSingle(const std::string& file) {
Shawn Willden785365b2018-01-20 09:37:36 -0700607 if (ForkExecvp(std::vector<std::string>{kSecdiscardPath, "--", file}) != 0) {
Rubin Xu2436e272017-04-27 20:43:10 +0100608 LOG(ERROR) << "secdiscard failed";
609 return false;
610 }
611 return true;
612}
613
Paul Crowleydf528a72016-03-09 09:31:37 -0800614static bool recursiveDeleteKey(const std::string& dir) {
615 if (ForkExecvp(std::vector<std::string>{kRmPath, "-rf", dir}) != 0) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000616 LOG(ERROR) << "recursive delete failed";
617 return false;
618 }
619 return true;
620}
621
Paul Crowleydf528a72016-03-09 09:31:37 -0800622bool destroyKey(const std::string& dir) {
Paul Crowley1ef25582016-01-21 20:26:12 +0000623 bool success = true;
624 // Try each thing, even if previous things failed.
Paul Crowleyff19b052017-10-26 11:28:55 -0700625 bool uses_km = pathExists(dir + "/" + kFn_keymaster_key_blob);
626 if (uses_km) {
627 success &= deleteKey(dir);
628 }
629 auto secdiscard_cmd = std::vector<std::string>{
Paul Crowley14c8c072018-09-18 13:30:21 -0700630 kSecdiscardPath,
631 "--",
632 dir + "/" + kFn_encrypted_key,
633 dir + "/" + kFn_secdiscardable,
Paul Crowleyff19b052017-10-26 11:28:55 -0700634 };
635 if (uses_km) {
636 secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
637 }
638 if (ForkExecvp(secdiscard_cmd) != 0) {
639 LOG(ERROR) << "secdiscard failed";
640 success = false;
641 }
Paul Crowley13ffd8e2016-01-27 14:30:22 +0000642 success &= recursiveDeleteKey(dir);
Paul Crowley1ef25582016-01-21 20:26:12 +0000643 return success;
644}
645
646} // namespace vold
647} // namespace android