blob: 86262816b225829394dfe783e95e033c92f2ad24 [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2015 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 <arpa/inet.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <string.h>
23
Logan Chiencdc813f2018-04-23 13:52:28 +080024#include <log/log.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070025
26#include "blob.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070027
28#include "keystore_utils.h"
29
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070030#include <openssl/evp.h>
Branden Archer44d1afa2018-12-28 09:10:49 -080031#include <openssl/rand.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070032
33#include <istream>
34#include <ostream>
35#include <streambuf>
36#include <string>
37
38#include <android-base/logging.h>
Janis Danisevskis6a0d9982019-04-30 15:43:59 -070039#include <android-base/unique_fd.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070040
Shawn Willdene9830582017-04-18 10:47:57 -060041namespace {
42
43constexpr size_t kGcmIvSizeBytes = 96 / 8;
44
Shawn Willden0ed642c2017-05-26 10:13:28 -060045#if defined(__clang__)
Shawn Willdene9830582017-04-18 10:47:57 -060046#define OPTNONE __attribute__((optnone))
Shawn Willden0ed642c2017-05-26 10:13:28 -060047#elif defined(__GNUC__)
Shawn Willdene9830582017-04-18 10:47:57 -060048#define OPTNONE __attribute__((optimize("O0")))
Shawn Willden0ed642c2017-05-26 10:13:28 -060049#else
50#error Need a definition for OPTNONE
51#endif
Shawn Willdene9830582017-04-18 10:47:57 -060052
53class ArrayEraser {
54 public:
55 ArrayEraser(uint8_t* arr, size_t size) : mArr(arr), mSize(size) {}
56 OPTNONE ~ArrayEraser() { std::fill(mArr, mArr + mSize, 0); }
57
58 private:
Shawn Willden0ed642c2017-05-26 10:13:28 -060059 volatile uint8_t* mArr;
Shawn Willdene9830582017-04-18 10:47:57 -060060 size_t mSize;
61};
62
Branden Archerd0315732019-01-10 14:56:05 -080063/**
64 * Returns a EVP_CIPHER appropriate for the given key, based on the key's size.
65 */
66const EVP_CIPHER* getAesCipherForKey(const std::vector<uint8_t>& key) {
67 const EVP_CIPHER* cipher = EVP_aes_256_gcm();
68 if (key.size() == kAes128KeySizeBytes) {
69 cipher = EVP_aes_128_gcm();
70 }
71 return cipher;
72}
73
Shawn Willdene9830582017-04-18 10:47:57 -060074/*
Branden Archerd0315732019-01-10 14:56:05 -080075 * Encrypt 'len' data at 'in' with AES-GCM, using 128-bit or 256-bit key at 'key', 96-bit IV at
76 * 'iv' and write output to 'out' (which may be the same location as 'in') and 128-bit tag to
77 * 'tag'.
Shawn Willdene9830582017-04-18 10:47:57 -060078 */
Branden Archerf5953d72019-01-10 09:08:18 -080079ResponseCode AES_gcm_encrypt(const uint8_t* in, uint8_t* out, size_t len,
80 const std::vector<uint8_t>& key, const uint8_t* iv, uint8_t* tag) {
Branden Archerd0315732019-01-10 14:56:05 -080081
82 // There can be 128-bit and 256-bit keys
83 const EVP_CIPHER* cipher = getAesCipherForKey(key);
84
David Benjamindc4d1422019-08-08 12:50:38 -040085 bssl::UniquePtr<EVP_CIPHER_CTX> ctx(EVP_CIPHER_CTX_new());
Shawn Willdene9830582017-04-18 10:47:57 -060086
Branden Archerf5953d72019-01-10 09:08:18 -080087 EVP_EncryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key.data(), iv);
Shawn Willdene9830582017-04-18 10:47:57 -060088 EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */);
89
90 std::unique_ptr<uint8_t[]> out_tmp(new uint8_t[len]);
91 uint8_t* out_pos = out_tmp.get();
92 int out_len;
93
94 EVP_EncryptUpdate(ctx.get(), out_pos, &out_len, in, len);
95 out_pos += out_len;
96 EVP_EncryptFinal_ex(ctx.get(), out_pos, &out_len);
97 out_pos += out_len;
98 if (out_pos - out_tmp.get() != static_cast<ssize_t>(len)) {
99 ALOGD("Encrypted ciphertext is the wrong size, expected %zu, got %zd", len,
100 out_pos - out_tmp.get());
101 return ResponseCode::SYSTEM_ERROR;
102 }
103
104 std::copy(out_tmp.get(), out_pos, out);
105 EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, kGcmTagLength, tag);
106
107 return ResponseCode::NO_ERROR;
108}
109
110/*
Branden Archerd0315732019-01-10 14:56:05 -0800111 * Decrypt 'len' data at 'in' with AES-GCM, using 128-bit or 256-bit key at 'key', 96-bit IV at
112 * 'iv', checking 128-bit tag at 'tag' and writing plaintext to 'out'(which may be the same
113 * location as 'in').
Shawn Willdene9830582017-04-18 10:47:57 -0600114 */
Branden Archerf5953d72019-01-10 09:08:18 -0800115ResponseCode AES_gcm_decrypt(const uint8_t* in, uint8_t* out, size_t len,
116 const std::vector<uint8_t> key, const uint8_t* iv,
117 const uint8_t* tag) {
Branden Archerd0315732019-01-10 14:56:05 -0800118
119 // There can be 128-bit and 256-bit keys
120 const EVP_CIPHER* cipher = getAesCipherForKey(key);
121
David Benjamindc4d1422019-08-08 12:50:38 -0400122 bssl::UniquePtr<EVP_CIPHER_CTX> ctx(EVP_CIPHER_CTX_new());
Shawn Willdene9830582017-04-18 10:47:57 -0600123
Branden Archerf5953d72019-01-10 09:08:18 -0800124 EVP_DecryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key.data(), iv);
Shawn Willdene9830582017-04-18 10:47:57 -0600125 EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */);
126 EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, kGcmTagLength, const_cast<uint8_t*>(tag));
127
128 std::unique_ptr<uint8_t[]> out_tmp(new uint8_t[len]);
129 ArrayEraser out_eraser(out_tmp.get(), len);
130 uint8_t* out_pos = out_tmp.get();
131 int out_len;
132
133 EVP_DecryptUpdate(ctx.get(), out_pos, &out_len, in, len);
134 out_pos += out_len;
135 if (!EVP_DecryptFinal_ex(ctx.get(), out_pos, &out_len)) {
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700136 ALOGE("Failed to decrypt blob; ciphertext or tag is likely corrupted");
Pavel Grafovcef39472018-02-12 18:45:02 +0000137 return ResponseCode::VALUE_CORRUPTED;
Shawn Willdene9830582017-04-18 10:47:57 -0600138 }
139 out_pos += out_len;
140 if (out_pos - out_tmp.get() != static_cast<ssize_t>(len)) {
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700141 ALOGE("Encrypted plaintext is the wrong size, expected %zu, got %zd", len,
Shawn Willdene9830582017-04-18 10:47:57 -0600142 out_pos - out_tmp.get());
Pavel Grafovcef39472018-02-12 18:45:02 +0000143 return ResponseCode::VALUE_CORRUPTED;
Shawn Willdene9830582017-04-18 10:47:57 -0600144 }
145
146 std::copy(out_tmp.get(), out_pos, out);
147
148 return ResponseCode::NO_ERROR;
149}
150
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700151class ArrayStreamBuffer : public std::streambuf {
152 public:
Chih-Hung Hsieh4fa39ef2019-01-04 13:34:17 -0800153 template <typename T, size_t size> explicit ArrayStreamBuffer(const T (&data)[size]) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700154 static_assert(sizeof(T) == 1, "Array element size too large");
155 std::streambuf::char_type* d = const_cast<std::streambuf::char_type*>(
156 reinterpret_cast<const std::streambuf::char_type*>(&data[0]));
157 setg(d, d, d + size);
158 setp(d, d + size);
159 }
160
161 protected:
162 pos_type seekoff(off_type off, std::ios_base::seekdir dir,
163 std::ios_base::openmode which = std::ios_base::in |
164 std::ios_base::out) override {
165 bool in = which & std::ios_base::in;
166 bool out = which & std::ios_base::out;
167 if ((!in && !out) || (in && out && dir == std::ios_base::cur)) return -1;
168 std::streambuf::char_type* newPosPtr;
169 switch (dir) {
170 case std::ios_base::beg:
171 newPosPtr = pbase();
172 break;
173 case std::ios_base::cur:
174 // if dir == cur then in xor out due to
175 // if ((!in && !out) || (in && out && dir == std::ios_base::cur)) return -1; above
176 if (in)
177 newPosPtr = gptr();
178 else
179 newPosPtr = pptr();
180 break;
181 case std::ios_base::end:
182 // in and out bounds are the same and cannot change, so we can take either range
183 // regardless of the value of "which"
184 newPosPtr = epptr();
185 break;
186 }
187 newPosPtr += off;
188 if (newPosPtr < pbase() || newPosPtr > epptr()) return -1;
189 if (in) {
190 gbump(newPosPtr - gptr());
191 }
192 if (out) {
193 pbump(newPosPtr - pptr());
194 }
195 return newPosPtr - pbase();
196 }
197};
198
Shawn Willdene9830582017-04-18 10:47:57 -0600199} // namespace
200
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700201Blob::Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
202 BlobType type) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700203 mBlob = std::make_unique<blobv3>();
204 memset(mBlob.get(), 0, sizeof(blobv3));
Shawn Willdene9830582017-04-18 10:47:57 -0600205 if (valueLength > kValueSize) {
206 valueLength = kValueSize;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 ALOGW("Provided blob length too large");
208 }
Shawn Willdene9830582017-04-18 10:47:57 -0600209 if (infoLength + valueLength > kValueSize) {
210 infoLength = kValueSize - valueLength;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700211 ALOGW("Provided info length too large");
212 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700213 mBlob->length = valueLength;
214 memcpy(mBlob->value, value, valueLength);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700215
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700216 mBlob->info = infoLength;
217 memcpy(mBlob->value + valueLength, info, infoLength);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700218
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700219 mBlob->version = CURRENT_BLOB_VERSION;
220 mBlob->type = uint8_t(type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700221
222 if (type == TYPE_MASTER_KEY) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700223 mBlob->flags = KEYSTORE_FLAG_ENCRYPTED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700224 } else {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700225 mBlob->flags = KEYSTORE_FLAG_NONE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700226 }
227}
228
Shawn Willdene9830582017-04-18 10:47:57 -0600229Blob::Blob(blobv3 b) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700230 mBlob = std::make_unique<blobv3>(b);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231}
232
233Blob::Blob() {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700234 if (mBlob) *mBlob = {};
235}
236
237Blob::Blob(const Blob& rhs) {
238 if (rhs.mBlob) {
239 mBlob = std::make_unique<blobv3>(*rhs.mBlob);
240 }
241}
242
243Blob::Blob(Blob&& rhs) : mBlob(std::move(rhs.mBlob)) {}
244
245Blob& Blob::operator=(const Blob& rhs) {
246 if (&rhs != this) {
247 if (mBlob) *mBlob = {};
248 if (rhs) {
249 mBlob = std::make_unique<blobv3>(*rhs.mBlob);
250 } else {
251 mBlob = {};
252 }
253 }
254 return *this;
255}
256
257Blob& Blob::operator=(Blob&& rhs) {
258 if (mBlob) *mBlob = {};
259 mBlob = std::move(rhs.mBlob);
260 return *this;
261}
262
263template <typename BlobType> static bool rawBlobIsEncrypted(const BlobType& blob) {
264 if (blob.version < 2) return true;
265
266 return blob.flags & (KEYSTORE_FLAG_ENCRYPTED | KEYSTORE_FLAG_SUPER_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700267}
268
269bool Blob::isEncrypted() const {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700270 if (mBlob->version < 2) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 return true;
272 }
273
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700274 return mBlob->flags & KEYSTORE_FLAG_ENCRYPTED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700275}
276
Shawn Willdend5a24e62017-02-28 13:53:24 -0700277bool Blob::isSuperEncrypted() const {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700278 return mBlob->flags & KEYSTORE_FLAG_SUPER_ENCRYPTED;
Shawn Willdend5a24e62017-02-28 13:53:24 -0700279}
280
Rubin Xu67899de2017-04-21 19:15:13 +0100281bool Blob::isCriticalToDeviceEncryption() const {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700282 return mBlob->flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION;
Rubin Xu67899de2017-04-21 19:15:13 +0100283}
284
Shawn Willdend5a24e62017-02-28 13:53:24 -0700285inline uint8_t setFlag(uint8_t flags, bool set, KeyStoreFlag flag) {
286 return set ? (flags | flag) : (flags & ~flag);
287}
288
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700289void Blob::setEncrypted(bool encrypted) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700290 mBlob->flags = setFlag(mBlob->flags, encrypted, KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdend5a24e62017-02-28 13:53:24 -0700291}
292
Rubin Xu67899de2017-04-21 19:15:13 +0100293void Blob::setSuperEncrypted(bool superEncrypted) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700294 mBlob->flags = setFlag(mBlob->flags, superEncrypted, KEYSTORE_FLAG_SUPER_ENCRYPTED);
Rubin Xu67899de2017-04-21 19:15:13 +0100295}
Rubin Xu48477952017-04-19 14:16:57 +0100296
Rubin Xu67899de2017-04-21 19:15:13 +0100297void Blob::setCriticalToDeviceEncryption(bool critical) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700298 mBlob->flags = setFlag(mBlob->flags, critical, KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700299}
300
301void Blob::setFallback(bool fallback) {
302 if (fallback) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700303 mBlob->flags |= KEYSTORE_FLAG_FALLBACK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700304 } else {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700305 mBlob->flags &= ~KEYSTORE_FLAG_FALLBACK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700306 }
307}
308
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700309static ResponseCode writeBlob(const std::string& filename, Blob blob, blobv3* rawBlob,
Branden Archerf5953d72019-01-10 09:08:18 -0800310 const std::vector<uint8_t>& aes_key, State state) {
Shawn Willdene9830582017-04-18 10:47:57 -0600311 ALOGV("writing blob %s", filename.c_str());
312
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700313 const size_t dataLength = rawBlob->length;
314 rawBlob->length = htonl(rawBlob->length);
Shawn Willdene9830582017-04-18 10:47:57 -0600315
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700316 if (blob.isEncrypted() || blob.isSuperEncrypted()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700317 if (state != STATE_NO_ERROR) {
318 ALOGD("couldn't insert encrypted blob while not unlocked");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100319 return ResponseCode::LOCKED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700320 }
321
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700322 memset(rawBlob->initialization_vector, 0, AES_BLOCK_SIZE);
Branden Archer44d1afa2018-12-28 09:10:49 -0800323 if (!RAND_bytes(rawBlob->initialization_vector, kGcmIvSizeBytes)) {
Shawn Willdene9830582017-04-18 10:47:57 -0600324 ALOGW("Could not read random data for: %s", filename.c_str());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100325 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700326 }
Shawn Willdene9830582017-04-18 10:47:57 -0600327
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700328 auto rc = AES_gcm_encrypt(rawBlob->value /* in */, rawBlob->value /* out */, dataLength,
329 aes_key, rawBlob->initialization_vector, rawBlob->aead_tag);
Shawn Willdene9830582017-04-18 10:47:57 -0600330 if (rc != ResponseCode::NO_ERROR) return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700331 }
332
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700333 size_t fileLength = offsetof(blobv3, value) + dataLength + rawBlob->info;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700334
Janis Danisevskis6a0d9982019-04-30 15:43:59 -0700335 char tmpFileName[] = ".tmpXXXXXX";
336 {
337 android::base::unique_fd out(TEMP_FAILURE_RETRY(mkstemp(tmpFileName)));
338 if (out < 0) {
339 LOG(ERROR) << "could not open temp file: " << tmpFileName
340 << " for writing blob file: " << filename.c_str()
341 << " because: " << strerror(errno);
342 return ResponseCode::SYSTEM_ERROR;
343 }
344
345 const size_t writtenBytes =
346 writeFully(out, reinterpret_cast<uint8_t*>(rawBlob), fileLength);
347
348 if (writtenBytes != fileLength) {
349 LOG(ERROR) << "blob not fully written " << writtenBytes << " != " << fileLength;
350 unlink(tmpFileName);
351 return ResponseCode::SYSTEM_ERROR;
352 }
353 }
354
355 if (rename(tmpFileName, filename.c_str()) == -1) {
356 LOG(ERROR) << "could not rename blob file to " << filename
357 << " because: " << strerror(errno);
358 unlink(tmpFileName);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100359 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700360 }
Shawn Willdene9830582017-04-18 10:47:57 -0600361
Janis Danisevskis6a0d9982019-04-30 15:43:59 -0700362 fsyncDirectory(getContainingDirectory(filename));
363
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100364 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365}
366
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700367ResponseCode LockedKeyBlobEntry::writeBlobs(Blob keyBlob, Blob characteristicsBlob,
Branden Archerf5953d72019-01-10 09:08:18 -0800368 const std::vector<uint8_t>& aes_key,
369 State state) const {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700370 if (entry_ == nullptr) {
371 return ResponseCode::SYSTEM_ERROR;
372 }
373 ResponseCode rc;
374 if (keyBlob) {
375 blobv3* rawBlob = keyBlob.mBlob.get();
Branden Archer44d1afa2018-12-28 09:10:49 -0800376 rc = writeBlob(entry_->getKeyBlobPath(), std::move(keyBlob), rawBlob, aes_key, state);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700377 if (rc != ResponseCode::NO_ERROR) {
378 return rc;
379 }
380 }
381
382 if (characteristicsBlob) {
383 blobv3* rawBlob = characteristicsBlob.mBlob.get();
384 rc = writeBlob(entry_->getCharacteristicsBlobPath(), std::move(characteristicsBlob),
Branden Archer44d1afa2018-12-28 09:10:49 -0800385 rawBlob, aes_key, state);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700386 }
387 return rc;
388}
389
Branden Archerf5953d72019-01-10 09:08:18 -0800390ResponseCode Blob::readBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
391 State state) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700392 ResponseCode rc;
Shawn Willdene9830582017-04-18 10:47:57 -0600393 ALOGV("reading blob %s", filename.c_str());
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700394 std::unique_ptr<blobv3> rawBlob = std::make_unique<blobv3>();
395
Shawn Willdene9830582017-04-18 10:47:57 -0600396 const int in = TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700397 if (in < 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100398 return (errno == ENOENT) ? ResponseCode::KEY_NOT_FOUND : ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 }
Shawn Willdene9830582017-04-18 10:47:57 -0600400
401 // fileLength may be less than sizeof(mBlob)
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700402 const size_t fileLength = readFully(in, (uint8_t*)rawBlob.get(), sizeof(blobv3));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 if (close(in) != 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100404 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700405 }
406
407 if (fileLength == 0) {
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700408 LOG(ERROR) << __func__ << " VALUE_CORRUPTED file length == 0";
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100409 return ResponseCode::VALUE_CORRUPTED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700410 }
411
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700412 if (rawBlobIsEncrypted(*rawBlob)) {
413 if (state == STATE_LOCKED) {
414 mBlob = std::move(rawBlob);
415 return ResponseCode::LOCKED;
416 }
Janis Danisevskis36316d62017-09-01 14:31:36 -0700417 if (state == STATE_UNINITIALIZED) return ResponseCode::UNINITIALIZED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418 }
419
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700420 if (fileLength < offsetof(blobv3, value)) {
421 LOG(ERROR) << __func__ << " VALUE_CORRUPTED blob file too short: " << fileLength;
422 return ResponseCode::VALUE_CORRUPTED;
423 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700424
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700425 if (rawBlob->version == 3) {
426 const ssize_t encryptedLength = ntohl(rawBlob->length);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700427
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700428 if (rawBlobIsEncrypted(*rawBlob)) {
429 rc = AES_gcm_decrypt(rawBlob->value /* in */, rawBlob->value /* out */, encryptedLength,
430 aes_key, rawBlob->initialization_vector, rawBlob->aead_tag);
Max Bires624cf842018-11-02 10:45:12 -0700431 if (rc != ResponseCode::NO_ERROR) {
432 // If the blob was superencrypted and decryption failed, it is
433 // almost certain that decryption is failing due to a user's
434 // changed master key.
435 if ((rawBlob->flags & KEYSTORE_FLAG_SUPER_ENCRYPTED) &&
436 (rc == ResponseCode::VALUE_CORRUPTED)) {
437 return ResponseCode::KEY_PERMANENTLY_INVALIDATED;
438 }
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700439 LOG(ERROR) << __func__ << " AES_gcm_decrypt returned: " << uint32_t(rc);
440
Max Bires624cf842018-11-02 10:45:12 -0700441 return rc;
442 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700444 } else if (rawBlob->version < 3) {
445 blobv2& v2blob = reinterpret_cast<blobv2&>(*rawBlob);
Shawn Willdene9830582017-04-18 10:47:57 -0600446 const size_t headerLength = offsetof(blobv2, encrypted);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700447 const ssize_t encryptedLength = fileLength - headerLength - v2blob.info;
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700448 if (encryptedLength < 0) {
449 LOG(ERROR) << __func__ << " VALUE_CORRUPTED v2blob file too short";
450 return ResponseCode::VALUE_CORRUPTED;
451 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700453 if (rawBlobIsEncrypted(*rawBlob)) {
Shawn Willdene9830582017-04-18 10:47:57 -0600454 if (encryptedLength % AES_BLOCK_SIZE != 0) {
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700455 LOG(ERROR) << __func__
456 << " VALUE_CORRUPTED encrypted length is not a multiple"
457 " of the AES block size";
Shawn Willdene9830582017-04-18 10:47:57 -0600458 return ResponseCode::VALUE_CORRUPTED;
459 }
460
461 AES_KEY key;
Branden Archerf5953d72019-01-10 09:08:18 -0800462 AES_set_decrypt_key(aes_key.data(), kAesKeySize * 8, &key);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700463 AES_cbc_encrypt(v2blob.encrypted, v2blob.encrypted, encryptedLength, &key,
464 v2blob.vector, AES_DECRYPT);
Shawn Willdene9830582017-04-18 10:47:57 -0600465 key = {}; // clear key
466
467 uint8_t computedDigest[MD5_DIGEST_LENGTH];
468 ssize_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700469 MD5(v2blob.digested, digestedLength, computedDigest);
470 if (memcmp(v2blob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700471 LOG(ERROR) << __func__ << " v2blob MD5 digest mismatch";
Shawn Willdene9830582017-04-18 10:47:57 -0600472 return ResponseCode::VALUE_CORRUPTED;
473 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700474 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700475 }
476
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700477 const ssize_t maxValueLength = fileLength - offsetof(blobv3, value) - rawBlob->info;
478 rawBlob->length = ntohl(rawBlob->length);
479 if (rawBlob->length < 0 || rawBlob->length > maxValueLength ||
480 rawBlob->length + rawBlob->info + AES_BLOCK_SIZE >
481 static_cast<ssize_t>(sizeof(rawBlob->value))) {
Janis Danisevskis56ec4392019-04-11 13:16:48 -0700482 LOG(ERROR) << __func__ << " raw blob length is out of bounds";
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100483 return ResponseCode::VALUE_CORRUPTED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 }
Shawn Willdene9830582017-04-18 10:47:57 -0600485
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700486 if (rawBlob->info != 0 && rawBlob->version < 3) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700487 // move info from after padding to after data
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700488 memmove(rawBlob->value + rawBlob->length, rawBlob->value + maxValueLength, rawBlob->info);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489 }
Shawn Willdene9830582017-04-18 10:47:57 -0600490
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700491 mBlob = std::move(rawBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100492 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700493}
Janis Danisevskisc1460142017-12-18 16:48:46 -0800494
Branden Archerf5953d72019-01-10 09:08:18 -0800495std::tuple<ResponseCode, Blob, Blob>
496LockedKeyBlobEntry::readBlobs(const std::vector<uint8_t>& aes_key, State state) const {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700497 std::tuple<ResponseCode, Blob, Blob> result;
498 auto& [rc, keyBlob, characteristicsBlob] = result;
499 if (entry_ == nullptr) return rc = ResponseCode::SYSTEM_ERROR, result;
500
501 rc = keyBlob.readBlob(entry_->getKeyBlobPath(), aes_key, state);
502 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::UNINITIALIZED) {
503 return result;
504 }
505
506 if (entry_->hasCharacteristicsBlob()) {
507 characteristicsBlob.readBlob(entry_->getCharacteristicsBlobPath(), aes_key, state);
508 }
509 return result;
510}
511
512ResponseCode LockedKeyBlobEntry::deleteBlobs() const {
513 if (entry_ == nullptr) return ResponseCode::NO_ERROR;
514
515 // always try to delete both
516 ResponseCode rc1 = (unlink(entry_->getKeyBlobPath().c_str()) && errno != ENOENT)
517 ? ResponseCode::SYSTEM_ERROR
518 : ResponseCode::NO_ERROR;
519 if (rc1 != ResponseCode::NO_ERROR) {
520 ALOGW("Failed to delete key blob file \"%s\"", entry_->getKeyBlobPath().c_str());
521 }
522 ResponseCode rc2 = (unlink(entry_->getCharacteristicsBlobPath().c_str()) && errno != ENOENT)
523 ? ResponseCode::SYSTEM_ERROR
524 : ResponseCode::NO_ERROR;
525 if (rc2 != ResponseCode::NO_ERROR) {
526 ALOGW("Failed to delete key characteristics file \"%s\"",
527 entry_->getCharacteristicsBlobPath().c_str());
528 }
529 // then report the first error that occured
530 if (rc1 != ResponseCode::NO_ERROR) return rc1;
531 return rc2;
532}
533
Janis Danisevskisc1460142017-12-18 16:48:46 -0800534keystore::SecurityLevel Blob::getSecurityLevel() const {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700535 return keystore::flagsToSecurityLevel(mBlob->flags);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800536}
537
538void Blob::setSecurityLevel(keystore::SecurityLevel secLevel) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700539 mBlob->flags &= ~(KEYSTORE_FLAG_FALLBACK | KEYSTORE_FLAG_STRONGBOX);
540 mBlob->flags |= keystore::securityLevelToFlags(secLevel);
541}
542
543std::tuple<bool, keystore::AuthorizationSet, keystore::AuthorizationSet>
544Blob::getKeyCharacteristics() const {
545 std::tuple<bool, keystore::AuthorizationSet, keystore::AuthorizationSet> result;
546 auto& [success, hwEnforced, swEnforced] = result;
547 success = false;
548 ArrayStreamBuffer buf(mBlob->value);
549 std::istream in(&buf);
550
551 // only the characteristics cache has both sets
552 if (getType() == TYPE_KEY_CHARACTERISTICS_CACHE) {
553 hwEnforced.Deserialize(&in);
554 } else if (getType() != TYPE_KEY_CHARACTERISTICS) {
555 // if its not the cache and not the legacy characteristics file we have no business
556 // here
557 return result;
558 }
559 swEnforced.Deserialize(&in);
560 success = !in.bad();
561
562 return result;
563}
564bool Blob::putKeyCharacteristics(const keystore::AuthorizationSet& hwEnforced,
565 const keystore::AuthorizationSet& swEnforced) {
566 if (!mBlob) mBlob = std::make_unique<blobv3>();
567 mBlob->version = CURRENT_BLOB_VERSION;
568 ArrayStreamBuffer buf(mBlob->value);
569 std::ostream out(&buf);
570 hwEnforced.Serialize(&out);
571 swEnforced.Serialize(&out);
572 if (out.bad()) return false;
573 setType(TYPE_KEY_CHARACTERISTICS_CACHE);
574 mBlob->length = out.tellp();
575 return true;
576}
577
578void LockedKeyBlobEntry::put(const KeyBlobEntry& entry) {
579 std::unique_lock<std::mutex> lock(locked_blobs_mutex_);
580 locked_blobs_.erase(entry);
581 lock.unlock();
582 locked_blobs_mutex_cond_var_.notify_all();
583}
584
585LockedKeyBlobEntry::~LockedKeyBlobEntry() {
586 if (entry_ != nullptr) put(*entry_);
587}
588
589LockedKeyBlobEntry LockedKeyBlobEntry::get(KeyBlobEntry entry) {
590 std::unique_lock<std::mutex> lock(locked_blobs_mutex_);
591 locked_blobs_mutex_cond_var_.wait(
592 lock, [&] { return locked_blobs_.find(entry) == locked_blobs_.end(); });
593 auto [iterator, success] = locked_blobs_.insert(std::move(entry));
594 if (!success) return {};
595 return LockedKeyBlobEntry(*iterator);
596}
597
598std::set<KeyBlobEntry> LockedKeyBlobEntry::locked_blobs_;
599std::mutex LockedKeyBlobEntry::locked_blobs_mutex_;
600std::condition_variable LockedKeyBlobEntry::locked_blobs_mutex_cond_var_;
601
602/* Here is the encoding of key names. This is necessary in order to allow arbitrary
603 * characters in key names. Characters in [0-~] are not encoded. Others are encoded
604 * into two bytes. The first byte is one of [+-.] which represents the first
605 * two bits of the character. The second byte encodes the rest of the bits into
606 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
607 * that Base64 cannot be used here due to the need of prefix match on keys. */
608
Eran Messeri2ba77c32018-12-04 12:22:16 +0000609std::string encodeKeyName(const std::string& keyName) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700610 std::string encodedName;
611 encodedName.reserve(keyName.size() * 2);
612 auto in = keyName.begin();
613 while (in != keyName.end()) {
Eran Messeri2ba77c32018-12-04 12:22:16 +0000614 // Input character needs to be encoded.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700615 if (*in < '0' || *in > '~') {
Eran Messeri2ba77c32018-12-04 12:22:16 +0000616 // Encode the two most-significant bits of the input char in the first
617 // output character, by counting up from 43 ('+').
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700618 encodedName.append(1, '+' + (uint8_t(*in) >> 6));
Eran Messeri2ba77c32018-12-04 12:22:16 +0000619 // Encode the six least-significant bits of the input char in the second
620 // output character, by counting up from 48 ('0').
621 // This is safe because the maximum value is 112, which is the
622 // character 'p'.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700623 encodedName.append(1, '0' + (*in & 0x3F));
624 } else {
Eran Messeri2ba77c32018-12-04 12:22:16 +0000625 // No need to encode input char - append as-is.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700626 encodedName.append(1, *in);
627 }
628 ++in;
629 }
630 return encodedName;
631}
632
Eran Messeri2ba77c32018-12-04 12:22:16 +0000633std::string decodeKeyName(const std::string& encodedName) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700634 std::string decodedName;
635 decodedName.reserve(encodedName.size());
636 auto in = encodedName.begin();
637 bool multichar = false;
638 char c;
639 while (in != encodedName.end()) {
640 if (multichar) {
Eran Messeri2ba77c32018-12-04 12:22:16 +0000641 // Second part of a multi-character encoding. Turn off the multichar
642 // flag and set the six least-significant bits of c to the value originally
643 // encoded by counting up from '0'.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700644 multichar = false;
Eran Messeri2ba77c32018-12-04 12:22:16 +0000645 decodedName.append(1, c | (uint8_t(*in) - '0'));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700646 } else if (*in >= '+' && *in <= '.') {
Eran Messeri2ba77c32018-12-04 12:22:16 +0000647 // First part of a multi-character encoding. Set the multichar flag
648 // and set the two most-significant bits of c to be the two bits originally
649 // encoded by counting up from '+'.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700650 multichar = true;
651 c = (*in - '+') << 6;
652 } else {
Eran Messeri2ba77c32018-12-04 12:22:16 +0000653 // Regular character, append as-is.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700654 decodedName.append(1, *in);
655 }
656 ++in;
657 }
658 // mulitchars at the end get truncated
659 return decodedName;
660}
661
662std::string KeyBlobEntry::getKeyBlobBaseName() const {
663 std::stringstream s;
664 if (masterkey_) {
665 s << alias_;
666 } else {
667 s << uid_ << "_" << encodeKeyName(alias_);
668 }
669 return s.str();
670}
671
672std::string KeyBlobEntry::getKeyBlobPath() const {
673 std::stringstream s;
674 if (masterkey_) {
675 s << user_dir_ << "/" << alias_;
676 } else {
677 s << user_dir_ << "/" << uid_ << "_" << encodeKeyName(alias_);
678 }
679 return s.str();
680}
681
682std::string KeyBlobEntry::getCharacteristicsBlobBaseName() const {
683 std::stringstream s;
684 if (!masterkey_) s << "." << uid_ << "_chr_" << encodeKeyName(alias_);
685 return s.str();
686}
687
688std::string KeyBlobEntry::getCharacteristicsBlobPath() const {
689 std::stringstream s;
690 if (!masterkey_)
691 s << user_dir_ << "/"
692 << "." << uid_ << "_chr_" << encodeKeyName(alias_);
693 return s.str();
694}
695
696bool KeyBlobEntry::hasKeyBlob() const {
Janis Danisevskis8196b8c2019-03-15 14:57:10 -0700697 int trys = 3;
698 while (trys--) {
699 if (!access(getKeyBlobPath().c_str(), R_OK | W_OK)) return true;
700 if (errno == ENOENT) return false;
701 LOG(WARNING) << "access encountered " << strerror(errno) << " (" << errno << ")"
702 << " while checking for key blob";
703 if (errno != EAGAIN) break;
704 }
705 return false;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700706}
Janis Danisevskis8196b8c2019-03-15 14:57:10 -0700707
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700708bool KeyBlobEntry::hasCharacteristicsBlob() const {
Janis Danisevskis8196b8c2019-03-15 14:57:10 -0700709 int trys = 3;
710 while (trys--) {
711 if (!access(getCharacteristicsBlobPath().c_str(), R_OK | W_OK)) return true;
712 if (errno == ENOENT) return false;
713 LOG(WARNING) << "access encountered " << strerror(errno) << " (" << errno << ")"
714 << " while checking for key characteristics blob";
715 if (errno != EAGAIN) break;
716 }
717 return false;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700718}
719
720static std::tuple<bool, uid_t, std::string> filename2UidAlias(const std::string& filepath) {
721 std::tuple<bool, uid_t, std::string> result;
722
723 auto& [success, uid, alias] = result;
724
725 success = false;
726
727 auto filenamebase = filepath.find_last_of('/');
728 std::string filename =
729 filenamebase == std::string::npos ? filepath : filepath.substr(filenamebase + 1);
730
731 if (filename[0] == '.') return result;
732
733 auto sep = filename.find('_');
734 if (sep == std::string::npos) return result;
735
736 std::stringstream s(filename.substr(0, sep));
737 s >> uid;
738 if (!s) return result;
739
740 alias = decodeKeyName(filename.substr(sep + 1));
741 success = true;
742 return result;
743}
744
745std::tuple<ResponseCode, std::list<LockedKeyBlobEntry>>
746LockedKeyBlobEntry::list(const std::string& user_dir,
747 std::function<bool(uid_t, const std::string&)> filter) {
748 std::list<LockedKeyBlobEntry> matches;
749
750 // This is a fence against any concurrent database accesses during database iteration.
751 // Only the keystore thread can lock entries. So it cannot be starved
752 // by workers grabbing new individual locks. We just wait here until all
753 // workers have relinquished their locked files.
754 std::unique_lock<std::mutex> lock(locked_blobs_mutex_);
755 locked_blobs_mutex_cond_var_.wait(lock, [&] { return locked_blobs_.empty(); });
756
757 DIR* dir = opendir(user_dir.c_str());
758 if (!dir) {
759 ALOGW("can't open directory for user: %s", strerror(errno));
760 return std::tuple<ResponseCode, std::list<LockedKeyBlobEntry>&&>{ResponseCode::SYSTEM_ERROR,
761 std::move(matches)};
762 }
763
764 struct dirent* file;
765 while ((file = readdir(dir)) != nullptr) {
766 // We only care about files.
767 if (file->d_type != DT_REG) {
768 continue;
769 }
770
771 // Skip anything that starts with a "."
772 if (file->d_name[0] == '.') {
773 continue;
774 }
775
776 auto [success, uid, alias] = filename2UidAlias(file->d_name);
777
778 if (!success) {
779 ALOGW("could not parse key filename \"%s\"", file->d_name);
780 continue;
781 }
782
783 if (!filter(uid, alias)) continue;
784
785 auto [iterator, dummy] = locked_blobs_.emplace(alias, user_dir, uid);
786 matches.push_back(*iterator);
787 }
788 closedir(dir);
789 return std::tuple<ResponseCode, std::list<LockedKeyBlobEntry>&&>{ResponseCode::NO_ERROR,
790 std::move(matches)};
Janis Danisevskisc1460142017-12-18 16:48:46 -0800791}