blob: 8d993e238506de6a1caf068bb2432edcd478bf0b [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
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#define LOG_TAG "keystore"
18
19#include "user_state.h"
20
21#include <dirent.h>
22#include <fcntl.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <sys/stat.h>
26
Branden Archercefbcbc2018-12-28 12:24:53 -080027#include <openssl/digest.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070028#include <openssl/evp.h>
Branden Archer44d1afa2018-12-28 09:10:49 -080029#include <openssl/rand.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030
Logan Chiencdc813f2018-04-23 13:52:28 +080031#include <log/log.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070032
33#include "blob.h"
34#include "keystore_utils.h"
35
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070036namespace keystore {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010037
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070038UserState::UserState(uid_t userId)
39 : mMasterKeyEntry(".masterkey", "user_" + std::to_string(userId), userId, /* masterkey */ true),
40 mUserId(userId), mState(STATE_UNINITIALIZED), mRetry(MAX_RETRY) {}
41
42bool UserState::operator<(const UserState& rhs) const {
43 return getUserId() < rhs.getUserId();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070044}
45
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070046bool UserState::operator<(uid_t userId) const {
47 return getUserId() < userId;
48}
49
50bool operator<(uid_t userId, const UserState& rhs) {
51 return userId < rhs.getUserId();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070052}
53
54bool UserState::initialize() {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070055 if ((mkdir(mMasterKeyEntry.user_dir().c_str(), S_IRUSR | S_IWUSR | S_IXUSR) < 0) &&
56 (errno != EEXIST)) {
57 ALOGE("Could not create directory '%s'", mMasterKeyEntry.user_dir().c_str());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070058 return false;
59 }
60
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070061 if (mMasterKeyEntry.hasKeyBlob()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070062 setState(STATE_LOCKED);
63 } else {
64 setState(STATE_UNINITIALIZED);
65 }
66
67 return true;
68}
69
70void UserState::setState(State state) {
71 mState = state;
72 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
73 mRetry = MAX_RETRY;
74 }
75}
76
77void UserState::zeroizeMasterKeysInMemory() {
Branden Archerf5953d72019-01-10 09:08:18 -080078 memset(mMasterKey.data(), 0, mMasterKey.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070079 memset(mSalt, 0, sizeof(mSalt));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070080}
81
82bool UserState::deleteMasterKey() {
83 setState(STATE_UNINITIALIZED);
84 zeroizeMasterKeysInMemory();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070085 return unlink(mMasterKeyEntry.getKeyBlobPath().c_str()) == 0 || errno == ENOENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070086}
87
Branden Archer44d1afa2018-12-28 09:10:49 -080088ResponseCode UserState::initialize(const android::String8& pw) {
89 if (!generateMasterKey()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010090 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070091 }
Branden Archer44d1afa2018-12-28 09:10:49 -080092 ResponseCode response = writeMasterKey(pw);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010093 if (response != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070094 return response;
95 }
96 setupMasterKeys();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010097 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070098}
99
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700100ResponseCode UserState::copyMasterKey(LockedUserState<UserState>* src) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700101 if (mState != STATE_UNINITIALIZED) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100102 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700103 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700104 if ((*src)->getState() != STATE_NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100105 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700106 }
Branden Archerf5953d72019-01-10 09:08:18 -0800107 mMasterKey = (*src)->mMasterKey;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700108 setupMasterKeys();
109 return copyMasterKeyFile(src);
110}
111
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700112ResponseCode UserState::copyMasterKeyFile(LockedUserState<UserState>* src) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700113 /* Copy the master key file to the new user. Unfortunately we don't have the src user's
114 * password so we cannot generate a new file with a new salt.
115 */
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700116 int in = TEMP_FAILURE_RETRY(open((*src)->getMasterKeyFileName().c_str(), O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700117 if (in < 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100118 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700119 }
Shawn Willdene9830582017-04-18 10:47:57 -0600120 blobv3 rawBlob;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700121 size_t length = readFully(in, (uint8_t*)&rawBlob, sizeof(rawBlob));
122 if (close(in) != 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100123 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700124 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700125 int out = TEMP_FAILURE_RETRY(open(mMasterKeyEntry.getKeyBlobPath().c_str(),
126 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700127 if (out < 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100128 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700129 }
130 size_t outLength = writeFully(out, (uint8_t*)&rawBlob, length);
131 if (close(out) != 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100132 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700133 }
134 if (outLength != length) {
135 ALOGW("blob not fully written %zu != %zu", outLength, length);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700136 unlink(mMasterKeyEntry.getKeyBlobPath().c_str());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100137 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700138 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100139 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700140}
141
Branden Archer44d1afa2018-12-28 09:10:49 -0800142ResponseCode UserState::writeMasterKey(const android::String8& pw) {
Shawn Willden17b87092019-10-01 17:43:43 -0600143 std::vector<uint8_t> passwordKey(mMasterKey.size());
Branden Archerf5953d72019-01-10 09:08:18 -0800144 generateKeyFromPassword(passwordKey, pw, mSalt);
Shawn Willden17b87092019-10-01 17:43:43 -0600145 auto blobType = TYPE_MASTER_KEY_AES256;
146 if (mMasterKey.size() == kAes128KeySizeBytes) {
147 blobType = TYPE_MASTER_KEY;
148 }
149 Blob masterKeyBlob(mMasterKey.data(), mMasterKey.size(), mSalt, sizeof(mSalt), blobType);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700150 auto lockedEntry = LockedKeyBlobEntry::get(mMasterKeyEntry);
Branden Archer44d1afa2018-12-28 09:10:49 -0800151 return lockedEntry.writeBlobs(masterKeyBlob, {}, passwordKey, STATE_NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152}
153
Branden Archer44d1afa2018-12-28 09:10:49 -0800154ResponseCode UserState::readMasterKey(const android::String8& pw) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700155
156 auto lockedEntry = LockedKeyBlobEntry::get(mMasterKeyEntry);
157
158 int in = TEMP_FAILURE_RETRY(open(mMasterKeyEntry.getKeyBlobPath().c_str(), O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700159 if (in < 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100160 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700161 }
162
163 // We read the raw blob to just to get the salt to generate the AES key, then we create the Blob
164 // to use with decryptBlob
Shawn Willdene9830582017-04-18 10:47:57 -0600165 blobv3 rawBlob;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700166 size_t length = readFully(in, (uint8_t*)&rawBlob, sizeof(rawBlob));
167 if (close(in) != 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100168 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700169 }
170 // find salt at EOF if present, otherwise we have an old file
171 uint8_t* salt;
172 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
173 salt = (uint8_t*)&rawBlob + length - SALT_SIZE;
174 } else {
Yi Kongd2916752018-07-26 17:44:27 -0700175 salt = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700176 }
Branden Archerf5953d72019-01-10 09:08:18 -0800177
Branden Archerd0315732019-01-10 14:56:05 -0800178 size_t masterKeySize = MASTER_KEY_SIZE_BYTES;
179 if (rawBlob.type == TYPE_MASTER_KEY) {
Shawn Willden17b87092019-10-01 17:43:43 -0600180 masterKeySize = kAes128KeySizeBytes;
Branden Archerd0315732019-01-10 14:56:05 -0800181 }
182
183 std::vector<uint8_t> passwordKey(masterKeySize);
Branden Archerf5953d72019-01-10 09:08:18 -0800184 generateKeyFromPassword(passwordKey, pw, salt);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700185 Blob masterKeyBlob, dummyBlob;
186 ResponseCode response;
187 std::tie(response, masterKeyBlob, dummyBlob) =
188 lockedEntry.readBlobs(passwordKey, STATE_NO_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100189 if (response == ResponseCode::SYSTEM_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700190 return response;
191 }
Branden Archerd0315732019-01-10 14:56:05 -0800192
193 size_t masterKeyBlobLength = static_cast<size_t>(masterKeyBlob.getLength());
194
195 if (response == ResponseCode::NO_ERROR && masterKeyBlobLength == masterKeySize) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700196 // If salt was missing, generate one and write a new master key file with the salt.
Yi Kongd2916752018-07-26 17:44:27 -0700197 if (salt == nullptr) {
Branden Archer44d1afa2018-12-28 09:10:49 -0800198 if (!generateSalt()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100199 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700200 }
Branden Archer44d1afa2018-12-28 09:10:49 -0800201 response = writeMasterKey(pw);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700202 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100203 if (response == ResponseCode::NO_ERROR) {
Branden Archerf5953d72019-01-10 09:08:18 -0800204 mMasterKey = std::vector<uint8_t>(masterKeyBlob.getValue(),
205 masterKeyBlob.getValue() + masterKeyBlob.getLength());
206
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 setupMasterKeys();
208 }
209 return response;
210 }
211 if (mRetry <= 0) {
212 reset();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100213 return ResponseCode::UNINITIALIZED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700214 }
215 --mRetry;
216 switch (mRetry) {
217 case 0:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100218 return ResponseCode::WRONG_PASSWORD_0;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700219 case 1:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100220 return ResponseCode::WRONG_PASSWORD_1;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700221 case 2:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100222 return ResponseCode::WRONG_PASSWORD_2;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700223 case 3:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100224 return ResponseCode::WRONG_PASSWORD_3;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700225 default:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100226 return ResponseCode::WRONG_PASSWORD_3;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700227 }
228}
229
230bool UserState::reset() {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700231 DIR* dir = opendir(mMasterKeyEntry.user_dir().c_str());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700232 if (!dir) {
233 // If the directory doesn't exist then nothing to do.
234 if (errno == ENOENT) {
235 return true;
236 }
237 ALOGW("couldn't open user directory: %s", strerror(errno));
238 return false;
239 }
240
241 struct dirent* file;
Yi Kongd2916752018-07-26 17:44:27 -0700242 while ((file = readdir(dir)) != nullptr) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700243 // skip . and ..
244 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
245 continue;
246 }
247
248 unlinkat(dirfd(dir), file->d_name, 0);
249 }
250 closedir(dir);
251 return true;
252}
253
Branden Archerf5953d72019-01-10 09:08:18 -0800254void UserState::generateKeyFromPassword(std::vector<uint8_t>& key, const android::String8& pw,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700255 uint8_t* salt) {
256 size_t saltSize;
Yi Kongd2916752018-07-26 17:44:27 -0700257 if (salt != nullptr) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700258 saltSize = SALT_SIZE;
259 } else {
260 // Pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
261 salt = (uint8_t*)"keystore";
262 // sizeof = 9, not strlen = 8
263 saltSize = sizeof("keystore");
264 }
265
Branden Archercefbcbc2018-12-28 12:24:53 -0800266 const EVP_MD* digest = EVP_sha256();
267
268 // SHA1 was used prior to increasing the key size
Shawn Willden17b87092019-10-01 17:43:43 -0600269 if (key.size() == kAes128KeySizeBytes) {
Branden Archercefbcbc2018-12-28 12:24:53 -0800270 digest = EVP_sha1();
271 }
272
273 PKCS5_PBKDF2_HMAC(reinterpret_cast<const char*>(pw.string()), pw.length(), salt, saltSize, 8192,
Branden Archerf5953d72019-01-10 09:08:18 -0800274 digest, key.size(), key.data());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700275}
276
Branden Archer44d1afa2018-12-28 09:10:49 -0800277bool UserState::generateSalt() {
278 return RAND_bytes(mSalt, sizeof(mSalt));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700279}
280
Branden Archer44d1afa2018-12-28 09:10:49 -0800281bool UserState::generateMasterKey() {
Branden Archerf5953d72019-01-10 09:08:18 -0800282 mMasterKey.resize(MASTER_KEY_SIZE_BYTES);
283 if (!RAND_bytes(mMasterKey.data(), mMasterKey.size())) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700284 return false;
285 }
Branden Archer44d1afa2018-12-28 09:10:49 -0800286 if (!generateSalt()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700287 return false;
288 }
289 return true;
290}
291
292void UserState::setupMasterKeys() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700293 setState(STATE_NO_ERROR);
294}
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700295
296LockedUserState<UserState> UserStateDB::getUserState(uid_t userId) {
297 std::unique_lock<std::mutex> lock(locked_state_mutex_);
298 decltype(mMasterKeys.begin()) it;
299 bool inserted;
300 std::tie(it, inserted) = mMasterKeys.emplace(userId, userId);
301 if (inserted) {
302 if (!it->second.initialize()) {
303 /* There's not much we can do if initialization fails. Trying to
304 * unlock the keystore for that user will fail as well, so any
305 * subsequent request for this user will just return SYSTEM_ERROR.
306 */
307 ALOGE("User initialization failed for %u; subsequent operations will fail", userId);
308 }
309 }
310 return get(std::move(lock), &it->second);
311}
312
313LockedUserState<UserState> UserStateDB::getUserStateByUid(uid_t uid) {
314 return getUserState(get_user_id(uid));
315}
316
317LockedUserState<const UserState> UserStateDB::getUserState(uid_t userId) const {
318 std::unique_lock<std::mutex> lock(locked_state_mutex_);
319 auto it = mMasterKeys.find(userId);
320 if (it == mMasterKeys.end()) return {};
321 return get(std::move(lock), &it->second);
322}
323
324LockedUserState<const UserState> UserStateDB::getUserStateByUid(uid_t uid) const {
325 return getUserState(get_user_id(uid));
326}
327
328} // namespace keystore