blob: c8a9cbf1be7fa7a9126c4460ae2c7f26a74fc212 [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>
Branden Archere489a032018-12-28 09:10:49 -080022#include <openssl/rand.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070023#include <string.h>
24
25#include <cutils/log.h>
26
27#include "blob.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070028
29#include "keystore_utils.h"
30
Shawn Willdene9830582017-04-18 10:47:57 -060031namespace {
32
33constexpr size_t kGcmIvSizeBytes = 96 / 8;
34
35template <typename T, void (*FreeFunc)(T*)> struct OpenSslObjectDeleter {
36 void operator()(T* p) { FreeFunc(p); }
37};
38
39#define DEFINE_OPENSSL_OBJECT_POINTER(name) \
40 typedef OpenSslObjectDeleter<name, name##_free> name##_Delete; \
41 typedef std::unique_ptr<name, name##_Delete> name##_Ptr;
42
43DEFINE_OPENSSL_OBJECT_POINTER(EVP_CIPHER_CTX);
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
63/*
64 * Encrypt 'len' data at 'in' with AES-GCM, using 128-bit key at 'key', 96-bit IV at 'iv' and write
65 * output to 'out' (which may be the same location as 'in') and 128-bit tag to 'tag'.
66 */
Branden Archera7a29fa2019-01-10 09:24:14 -080067ResponseCode AES_gcm_encrypt(const uint8_t* in, uint8_t* out, size_t len,
68 const std::vector<uint8_t>& key, const uint8_t* iv, uint8_t* tag) {
Shawn Willdene9830582017-04-18 10:47:57 -060069 const EVP_CIPHER* cipher = EVP_aes_128_gcm();
70 EVP_CIPHER_CTX_Ptr ctx(EVP_CIPHER_CTX_new());
71
Branden Archera7a29fa2019-01-10 09:24:14 -080072 EVP_EncryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key.data(), iv);
Shawn Willdene9830582017-04-18 10:47:57 -060073 EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */);
74
75 std::unique_ptr<uint8_t[]> out_tmp(new uint8_t[len]);
76 uint8_t* out_pos = out_tmp.get();
77 int out_len;
78
79 EVP_EncryptUpdate(ctx.get(), out_pos, &out_len, in, len);
80 out_pos += out_len;
81 EVP_EncryptFinal_ex(ctx.get(), out_pos, &out_len);
82 out_pos += out_len;
83 if (out_pos - out_tmp.get() != static_cast<ssize_t>(len)) {
84 ALOGD("Encrypted ciphertext is the wrong size, expected %zu, got %zd", len,
85 out_pos - out_tmp.get());
86 return ResponseCode::SYSTEM_ERROR;
87 }
88
89 std::copy(out_tmp.get(), out_pos, out);
90 EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, kGcmTagLength, tag);
91
92 return ResponseCode::NO_ERROR;
93}
94
95/*
96 * Decrypt 'len' data at 'in' with AES-GCM, using 128-bit key at 'key', 96-bit IV at 'iv', checking
97 * 128-bit tag at 'tag' and writing plaintext to 'out' (which may be the same location as 'in').
98 */
Branden Archera7a29fa2019-01-10 09:24:14 -080099ResponseCode AES_gcm_decrypt(const uint8_t* in, uint8_t* out, size_t len,
100 const std::vector<uint8_t> key, const uint8_t* iv,
101 const uint8_t* tag) {
Shawn Willdene9830582017-04-18 10:47:57 -0600102 const EVP_CIPHER* cipher = EVP_aes_128_gcm();
103 EVP_CIPHER_CTX_Ptr ctx(EVP_CIPHER_CTX_new());
104
Branden Archera7a29fa2019-01-10 09:24:14 -0800105 EVP_DecryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key.data(), iv);
Shawn Willdene9830582017-04-18 10:47:57 -0600106 EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */);
107 EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, kGcmTagLength, const_cast<uint8_t*>(tag));
108
109 std::unique_ptr<uint8_t[]> out_tmp(new uint8_t[len]);
110 ArrayEraser out_eraser(out_tmp.get(), len);
111 uint8_t* out_pos = out_tmp.get();
112 int out_len;
113
114 EVP_DecryptUpdate(ctx.get(), out_pos, &out_len, in, len);
115 out_pos += out_len;
116 if (!EVP_DecryptFinal_ex(ctx.get(), out_pos, &out_len)) {
117 ALOGD("Failed to decrypt blob; ciphertext or tag is likely corrupted");
Pavel Grafovcef39472018-02-12 18:45:02 +0000118 return ResponseCode::VALUE_CORRUPTED;
Shawn Willdene9830582017-04-18 10:47:57 -0600119 }
120 out_pos += out_len;
121 if (out_pos - out_tmp.get() != static_cast<ssize_t>(len)) {
122 ALOGD("Encrypted plaintext is the wrong size, expected %zu, got %zd", len,
123 out_pos - out_tmp.get());
Pavel Grafovcef39472018-02-12 18:45:02 +0000124 return ResponseCode::VALUE_CORRUPTED;
Shawn Willdene9830582017-04-18 10:47:57 -0600125 }
126
127 std::copy(out_tmp.get(), out_pos, out);
128
129 return ResponseCode::NO_ERROR;
130}
131
132} // namespace
133
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700134Blob::Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
135 BlobType type) {
136 memset(&mBlob, 0, sizeof(mBlob));
Shawn Willdene9830582017-04-18 10:47:57 -0600137 if (valueLength > kValueSize) {
138 valueLength = kValueSize;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700139 ALOGW("Provided blob length too large");
140 }
Shawn Willdene9830582017-04-18 10:47:57 -0600141 if (infoLength + valueLength > kValueSize) {
142 infoLength = kValueSize - valueLength;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700143 ALOGW("Provided info length too large");
144 }
145 mBlob.length = valueLength;
146 memcpy(mBlob.value, value, valueLength);
147
148 mBlob.info = infoLength;
149 memcpy(mBlob.value + valueLength, info, infoLength);
150
151 mBlob.version = CURRENT_BLOB_VERSION;
152 mBlob.type = uint8_t(type);
153
154 if (type == TYPE_MASTER_KEY) {
155 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
156 } else {
157 mBlob.flags = KEYSTORE_FLAG_NONE;
158 }
159}
160
Shawn Willdene9830582017-04-18 10:47:57 -0600161Blob::Blob(blobv3 b) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700162 mBlob = b;
163}
164
165Blob::Blob() {
166 memset(&mBlob, 0, sizeof(mBlob));
167}
168
169bool Blob::isEncrypted() const {
170 if (mBlob.version < 2) {
171 return true;
172 }
173
174 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
175}
176
Shawn Willdend5a24e62017-02-28 13:53:24 -0700177bool Blob::isSuperEncrypted() const {
178 return mBlob.flags & KEYSTORE_FLAG_SUPER_ENCRYPTED;
179}
180
Rubin Xu67899de2017-04-21 19:15:13 +0100181bool Blob::isCriticalToDeviceEncryption() const {
182 return mBlob.flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION;
183}
184
Shawn Willdend5a24e62017-02-28 13:53:24 -0700185inline uint8_t setFlag(uint8_t flags, bool set, KeyStoreFlag flag) {
186 return set ? (flags | flag) : (flags & ~flag);
187}
188
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189void Blob::setEncrypted(bool encrypted) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700190 mBlob.flags = setFlag(mBlob.flags, encrypted, KEYSTORE_FLAG_ENCRYPTED);
191}
192
Rubin Xu67899de2017-04-21 19:15:13 +0100193void Blob::setSuperEncrypted(bool superEncrypted) {
194 mBlob.flags = setFlag(mBlob.flags, superEncrypted, KEYSTORE_FLAG_SUPER_ENCRYPTED);
195}
Rubin Xu48477952017-04-19 14:16:57 +0100196
Rubin Xu67899de2017-04-21 19:15:13 +0100197void Blob::setCriticalToDeviceEncryption(bool critical) {
198 mBlob.flags = setFlag(mBlob.flags, critical, KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700199}
200
201void Blob::setFallback(bool fallback) {
202 if (fallback) {
203 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
204 } else {
205 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
206 }
207}
208
Branden Archera7a29fa2019-01-10 09:24:14 -0800209ResponseCode Blob::writeBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
210 State state) {
Shawn Willdene9830582017-04-18 10:47:57 -0600211 ALOGV("writing blob %s", filename.c_str());
212
213 const size_t dataLength = mBlob.length;
214 mBlob.length = htonl(mBlob.length);
215
Shawn Willdend5a24e62017-02-28 13:53:24 -0700216 if (isEncrypted() || isSuperEncrypted()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700217 if (state != STATE_NO_ERROR) {
218 ALOGD("couldn't insert encrypted blob while not unlocked");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100219 return ResponseCode::LOCKED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700220 }
221
Shawn Willdene9830582017-04-18 10:47:57 -0600222 memset(mBlob.initialization_vector, 0, AES_BLOCK_SIZE);
Branden Archere489a032018-12-28 09:10:49 -0800223 if (!RAND_bytes(mBlob.initialization_vector, kGcmIvSizeBytes)) {
Shawn Willdene9830582017-04-18 10:47:57 -0600224 ALOGW("Could not read random data for: %s", filename.c_str());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100225 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700226 }
Shawn Willdene9830582017-04-18 10:47:57 -0600227
228 auto rc = AES_gcm_encrypt(mBlob.value /* in */, mBlob.value /* out */, dataLength, aes_key,
229 mBlob.initialization_vector, mBlob.aead_tag);
230 if (rc != ResponseCode::NO_ERROR) return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231 }
232
Shawn Willdene9830582017-04-18 10:47:57 -0600233 size_t fileLength = offsetof(blobv3, value) + dataLength + mBlob.info;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234
235 const char* tmpFileName = ".tmp";
236 int out =
237 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
238 if (out < 0) {
239 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100240 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700241 }
Shawn Willdene9830582017-04-18 10:47:57 -0600242
243 const size_t writtenBytes = writeFully(out, (uint8_t*)&mBlob, fileLength);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244 if (close(out) != 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100245 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700246 }
247 if (writtenBytes != fileLength) {
248 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
249 unlink(tmpFileName);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100250 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700251 }
Shawn Willdene9830582017-04-18 10:47:57 -0600252 if (rename(tmpFileName, filename.c_str()) == -1) {
253 ALOGW("could not rename blob to %s: %s", filename.c_str(), strerror(errno));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100254 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700255 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100256 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700257}
258
Branden Archera7a29fa2019-01-10 09:24:14 -0800259ResponseCode Blob::readBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
260 State state) {
Shawn Willdene9830582017-04-18 10:47:57 -0600261 ALOGV("reading blob %s", filename.c_str());
262 const int in = TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700263 if (in < 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100264 return (errno == ENOENT) ? ResponseCode::KEY_NOT_FOUND : ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700265 }
Shawn Willdene9830582017-04-18 10:47:57 -0600266
267 // fileLength may be less than sizeof(mBlob)
268 const size_t fileLength = readFully(in, (uint8_t*)&mBlob, sizeof(mBlob));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700269 if (close(in) != 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100270 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 }
272
273 if (fileLength == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100274 return ResponseCode::VALUE_CORRUPTED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700275 }
276
Janis Danisevskis36316d62017-09-01 14:31:36 -0700277 if ((isEncrypted() || isSuperEncrypted())) {
278 if (state == STATE_LOCKED) return ResponseCode::LOCKED;
279 if (state == STATE_UNINITIALIZED) return ResponseCode::UNINITIALIZED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700280 }
281
Shawn Willdene9830582017-04-18 10:47:57 -0600282 if (fileLength < offsetof(blobv3, value)) return ResponseCode::VALUE_CORRUPTED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700283
Shawn Willdene9830582017-04-18 10:47:57 -0600284 if (mBlob.version == 3) {
285 const ssize_t encryptedLength = ntohl(mBlob.length);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700286
Shawn Willdene9830582017-04-18 10:47:57 -0600287 if (isEncrypted() || isSuperEncrypted()) {
288 auto rc = AES_gcm_decrypt(mBlob.value /* in */, mBlob.value /* out */, encryptedLength,
289 aes_key, mBlob.initialization_vector, mBlob.aead_tag);
290 if (rc != ResponseCode::NO_ERROR) return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700291 }
Shawn Willdene9830582017-04-18 10:47:57 -0600292 } else if (mBlob.version < 3) {
293 blobv2& blob = reinterpret_cast<blobv2&>(mBlob);
294 const size_t headerLength = offsetof(blobv2, encrypted);
295 const ssize_t encryptedLength = fileLength - headerLength - blob.info;
296 if (encryptedLength < 0) return ResponseCode::VALUE_CORRUPTED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700297
Shawn Willdene9830582017-04-18 10:47:57 -0600298 if (isEncrypted() || isSuperEncrypted()) {
299 if (encryptedLength % AES_BLOCK_SIZE != 0) {
300 return ResponseCode::VALUE_CORRUPTED;
301 }
302
303 AES_KEY key;
Branden Archera7a29fa2019-01-10 09:24:14 -0800304 AES_set_decrypt_key(aes_key.data(), kAesKeySize * 8, &key);
Shawn Willdene9830582017-04-18 10:47:57 -0600305 AES_cbc_encrypt(blob.encrypted, blob.encrypted, encryptedLength, &key, blob.vector,
306 AES_DECRYPT);
307 key = {}; // clear key
308
309 uint8_t computedDigest[MD5_DIGEST_LENGTH];
310 ssize_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
311 MD5(blob.digested, digestedLength, computedDigest);
312 if (memcmp(blob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
313 return ResponseCode::VALUE_CORRUPTED;
314 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700315 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700316 }
317
Shawn Willdene9830582017-04-18 10:47:57 -0600318 const ssize_t maxValueLength = fileLength - offsetof(blobv3, value) - mBlob.info;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700319 mBlob.length = ntohl(mBlob.length);
Shawn Willdene9830582017-04-18 10:47:57 -0600320 if (mBlob.length < 0 || mBlob.length > maxValueLength ||
321 mBlob.length + mBlob.info + AES_BLOCK_SIZE > static_cast<ssize_t>(sizeof(mBlob.value))) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100322 return ResponseCode::VALUE_CORRUPTED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700323 }
Shawn Willdene9830582017-04-18 10:47:57 -0600324
325 if (mBlob.info != 0 && mBlob.version < 3) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700326 // move info from after padding to after data
Shawn Willdene9830582017-04-18 10:47:57 -0600327 memmove(mBlob.value + mBlob.length, mBlob.value + maxValueLength, mBlob.info);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700328 }
Shawn Willdene9830582017-04-18 10:47:57 -0600329
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100330 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700331}
Janis Danisevskisc1460142017-12-18 16:48:46 -0800332
333keystore::SecurityLevel Blob::getSecurityLevel() const {
334 return keystore::flagsToSecurityLevel(mBlob.flags);
335}
336
337void Blob::setSecurityLevel(keystore::SecurityLevel secLevel) {
338 mBlob.flags &= ~(KEYSTORE_FLAG_FALLBACK | KEYSTORE_FLAG_STRONGBOX);
339 mBlob.flags |= keystore::securityLevelToFlags(secLevel);
340}