Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 1 | /* |
| 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 Chien | cdc813f | 2018-04-23 13:52:28 +0800 | [diff] [blame] | 24 | #include <log/log.h> |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 25 | |
| 26 | #include "blob.h" |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 27 | |
| 28 | #include "keystore_utils.h" |
| 29 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 30 | #include <openssl/evp.h> |
Branden Archer | 44d1afa | 2018-12-28 09:10:49 -0800 | [diff] [blame] | 31 | #include <openssl/rand.h> |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 32 | |
| 33 | #include <istream> |
| 34 | #include <ostream> |
| 35 | #include <streambuf> |
| 36 | #include <string> |
| 37 | |
| 38 | #include <android-base/logging.h> |
| 39 | |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 40 | namespace { |
| 41 | |
| 42 | constexpr size_t kGcmIvSizeBytes = 96 / 8; |
| 43 | |
| 44 | template <typename T, void (*FreeFunc)(T*)> struct OpenSslObjectDeleter { |
| 45 | void operator()(T* p) { FreeFunc(p); } |
| 46 | }; |
| 47 | |
| 48 | #define DEFINE_OPENSSL_OBJECT_POINTER(name) \ |
| 49 | typedef OpenSslObjectDeleter<name, name##_free> name##_Delete; \ |
| 50 | typedef std::unique_ptr<name, name##_Delete> name##_Ptr; |
| 51 | |
| 52 | DEFINE_OPENSSL_OBJECT_POINTER(EVP_CIPHER_CTX); |
| 53 | |
Shawn Willden | 0ed642c | 2017-05-26 10:13:28 -0600 | [diff] [blame] | 54 | #if defined(__clang__) |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 55 | #define OPTNONE __attribute__((optnone)) |
Shawn Willden | 0ed642c | 2017-05-26 10:13:28 -0600 | [diff] [blame] | 56 | #elif defined(__GNUC__) |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 57 | #define OPTNONE __attribute__((optimize("O0"))) |
Shawn Willden | 0ed642c | 2017-05-26 10:13:28 -0600 | [diff] [blame] | 58 | #else |
| 59 | #error Need a definition for OPTNONE |
| 60 | #endif |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 61 | |
| 62 | class ArrayEraser { |
| 63 | public: |
| 64 | ArrayEraser(uint8_t* arr, size_t size) : mArr(arr), mSize(size) {} |
| 65 | OPTNONE ~ArrayEraser() { std::fill(mArr, mArr + mSize, 0); } |
| 66 | |
| 67 | private: |
Shawn Willden | 0ed642c | 2017-05-26 10:13:28 -0600 | [diff] [blame] | 68 | volatile uint8_t* mArr; |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 69 | size_t mSize; |
| 70 | }; |
| 71 | |
| 72 | /* |
| 73 | * Encrypt 'len' data at 'in' with AES-GCM, using 128-bit key at 'key', 96-bit IV at 'iv' and write |
| 74 | * output to 'out' (which may be the same location as 'in') and 128-bit tag to 'tag'. |
| 75 | */ |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 76 | ResponseCode AES_gcm_encrypt(const uint8_t* in, uint8_t* out, size_t len, |
| 77 | const std::vector<uint8_t>& key, const uint8_t* iv, uint8_t* tag) { |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 78 | const EVP_CIPHER* cipher = EVP_aes_128_gcm(); |
| 79 | EVP_CIPHER_CTX_Ptr ctx(EVP_CIPHER_CTX_new()); |
| 80 | |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 81 | EVP_EncryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key.data(), iv); |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 82 | EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */); |
| 83 | |
| 84 | std::unique_ptr<uint8_t[]> out_tmp(new uint8_t[len]); |
| 85 | uint8_t* out_pos = out_tmp.get(); |
| 86 | int out_len; |
| 87 | |
| 88 | EVP_EncryptUpdate(ctx.get(), out_pos, &out_len, in, len); |
| 89 | out_pos += out_len; |
| 90 | EVP_EncryptFinal_ex(ctx.get(), out_pos, &out_len); |
| 91 | out_pos += out_len; |
| 92 | if (out_pos - out_tmp.get() != static_cast<ssize_t>(len)) { |
| 93 | ALOGD("Encrypted ciphertext is the wrong size, expected %zu, got %zd", len, |
| 94 | out_pos - out_tmp.get()); |
| 95 | return ResponseCode::SYSTEM_ERROR; |
| 96 | } |
| 97 | |
| 98 | std::copy(out_tmp.get(), out_pos, out); |
| 99 | EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, kGcmTagLength, tag); |
| 100 | |
| 101 | return ResponseCode::NO_ERROR; |
| 102 | } |
| 103 | |
| 104 | /* |
| 105 | * Decrypt 'len' data at 'in' with AES-GCM, using 128-bit key at 'key', 96-bit IV at 'iv', checking |
| 106 | * 128-bit tag at 'tag' and writing plaintext to 'out' (which may be the same location as 'in'). |
| 107 | */ |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 108 | ResponseCode AES_gcm_decrypt(const uint8_t* in, uint8_t* out, size_t len, |
| 109 | const std::vector<uint8_t> key, const uint8_t* iv, |
| 110 | const uint8_t* tag) { |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 111 | const EVP_CIPHER* cipher = EVP_aes_128_gcm(); |
| 112 | EVP_CIPHER_CTX_Ptr ctx(EVP_CIPHER_CTX_new()); |
| 113 | |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 114 | EVP_DecryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key.data(), iv); |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 115 | EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */); |
| 116 | EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, kGcmTagLength, const_cast<uint8_t*>(tag)); |
| 117 | |
| 118 | std::unique_ptr<uint8_t[]> out_tmp(new uint8_t[len]); |
| 119 | ArrayEraser out_eraser(out_tmp.get(), len); |
| 120 | uint8_t* out_pos = out_tmp.get(); |
| 121 | int out_len; |
| 122 | |
| 123 | EVP_DecryptUpdate(ctx.get(), out_pos, &out_len, in, len); |
| 124 | out_pos += out_len; |
| 125 | if (!EVP_DecryptFinal_ex(ctx.get(), out_pos, &out_len)) { |
| 126 | ALOGD("Failed to decrypt blob; ciphertext or tag is likely corrupted"); |
Pavel Grafov | cef3947 | 2018-02-12 18:45:02 +0000 | [diff] [blame] | 127 | return ResponseCode::VALUE_CORRUPTED; |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 128 | } |
| 129 | out_pos += out_len; |
| 130 | if (out_pos - out_tmp.get() != static_cast<ssize_t>(len)) { |
| 131 | ALOGD("Encrypted plaintext is the wrong size, expected %zu, got %zd", len, |
| 132 | out_pos - out_tmp.get()); |
Pavel Grafov | cef3947 | 2018-02-12 18:45:02 +0000 | [diff] [blame] | 133 | return ResponseCode::VALUE_CORRUPTED; |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 134 | } |
| 135 | |
| 136 | std::copy(out_tmp.get(), out_pos, out); |
| 137 | |
| 138 | return ResponseCode::NO_ERROR; |
| 139 | } |
| 140 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 141 | class ArrayStreamBuffer : public std::streambuf { |
| 142 | public: |
| 143 | template <typename T, size_t size> ArrayStreamBuffer(const T (&data)[size]) { |
| 144 | static_assert(sizeof(T) == 1, "Array element size too large"); |
| 145 | std::streambuf::char_type* d = const_cast<std::streambuf::char_type*>( |
| 146 | reinterpret_cast<const std::streambuf::char_type*>(&data[0])); |
| 147 | setg(d, d, d + size); |
| 148 | setp(d, d + size); |
| 149 | } |
| 150 | |
| 151 | protected: |
| 152 | pos_type seekoff(off_type off, std::ios_base::seekdir dir, |
| 153 | std::ios_base::openmode which = std::ios_base::in | |
| 154 | std::ios_base::out) override { |
| 155 | bool in = which & std::ios_base::in; |
| 156 | bool out = which & std::ios_base::out; |
| 157 | if ((!in && !out) || (in && out && dir == std::ios_base::cur)) return -1; |
| 158 | std::streambuf::char_type* newPosPtr; |
| 159 | switch (dir) { |
| 160 | case std::ios_base::beg: |
| 161 | newPosPtr = pbase(); |
| 162 | break; |
| 163 | case std::ios_base::cur: |
| 164 | // if dir == cur then in xor out due to |
| 165 | // if ((!in && !out) || (in && out && dir == std::ios_base::cur)) return -1; above |
| 166 | if (in) |
| 167 | newPosPtr = gptr(); |
| 168 | else |
| 169 | newPosPtr = pptr(); |
| 170 | break; |
| 171 | case std::ios_base::end: |
| 172 | // in and out bounds are the same and cannot change, so we can take either range |
| 173 | // regardless of the value of "which" |
| 174 | newPosPtr = epptr(); |
| 175 | break; |
| 176 | } |
| 177 | newPosPtr += off; |
| 178 | if (newPosPtr < pbase() || newPosPtr > epptr()) return -1; |
| 179 | if (in) { |
| 180 | gbump(newPosPtr - gptr()); |
| 181 | } |
| 182 | if (out) { |
| 183 | pbump(newPosPtr - pptr()); |
| 184 | } |
| 185 | return newPosPtr - pbase(); |
| 186 | } |
| 187 | }; |
| 188 | |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 189 | } // namespace |
| 190 | |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 191 | Blob::Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength, |
| 192 | BlobType type) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 193 | mBlob = std::make_unique<blobv3>(); |
| 194 | memset(mBlob.get(), 0, sizeof(blobv3)); |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 195 | if (valueLength > kValueSize) { |
| 196 | valueLength = kValueSize; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 197 | ALOGW("Provided blob length too large"); |
| 198 | } |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 199 | if (infoLength + valueLength > kValueSize) { |
| 200 | infoLength = kValueSize - valueLength; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 201 | ALOGW("Provided info length too large"); |
| 202 | } |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 203 | mBlob->length = valueLength; |
| 204 | memcpy(mBlob->value, value, valueLength); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 205 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 206 | mBlob->info = infoLength; |
| 207 | memcpy(mBlob->value + valueLength, info, infoLength); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 208 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 209 | mBlob->version = CURRENT_BLOB_VERSION; |
| 210 | mBlob->type = uint8_t(type); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 211 | |
| 212 | if (type == TYPE_MASTER_KEY) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 213 | mBlob->flags = KEYSTORE_FLAG_ENCRYPTED; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 214 | } else { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 215 | mBlob->flags = KEYSTORE_FLAG_NONE; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 216 | } |
| 217 | } |
| 218 | |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 219 | Blob::Blob(blobv3 b) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 220 | mBlob = std::make_unique<blobv3>(b); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 221 | } |
| 222 | |
| 223 | Blob::Blob() { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 224 | if (mBlob) *mBlob = {}; |
| 225 | } |
| 226 | |
| 227 | Blob::Blob(const Blob& rhs) { |
| 228 | if (rhs.mBlob) { |
| 229 | mBlob = std::make_unique<blobv3>(*rhs.mBlob); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | Blob::Blob(Blob&& rhs) : mBlob(std::move(rhs.mBlob)) {} |
| 234 | |
| 235 | Blob& Blob::operator=(const Blob& rhs) { |
| 236 | if (&rhs != this) { |
| 237 | if (mBlob) *mBlob = {}; |
| 238 | if (rhs) { |
| 239 | mBlob = std::make_unique<blobv3>(*rhs.mBlob); |
| 240 | } else { |
| 241 | mBlob = {}; |
| 242 | } |
| 243 | } |
| 244 | return *this; |
| 245 | } |
| 246 | |
| 247 | Blob& Blob::operator=(Blob&& rhs) { |
| 248 | if (mBlob) *mBlob = {}; |
| 249 | mBlob = std::move(rhs.mBlob); |
| 250 | return *this; |
| 251 | } |
| 252 | |
| 253 | template <typename BlobType> static bool rawBlobIsEncrypted(const BlobType& blob) { |
| 254 | if (blob.version < 2) return true; |
| 255 | |
| 256 | return blob.flags & (KEYSTORE_FLAG_ENCRYPTED | KEYSTORE_FLAG_SUPER_ENCRYPTED); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 257 | } |
| 258 | |
| 259 | bool Blob::isEncrypted() const { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 260 | if (mBlob->version < 2) { |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 261 | return true; |
| 262 | } |
| 263 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 264 | return mBlob->flags & KEYSTORE_FLAG_ENCRYPTED; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 265 | } |
| 266 | |
Shawn Willden | d5a24e6 | 2017-02-28 13:53:24 -0700 | [diff] [blame] | 267 | bool Blob::isSuperEncrypted() const { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 268 | return mBlob->flags & KEYSTORE_FLAG_SUPER_ENCRYPTED; |
Shawn Willden | d5a24e6 | 2017-02-28 13:53:24 -0700 | [diff] [blame] | 269 | } |
| 270 | |
Rubin Xu | 67899de | 2017-04-21 19:15:13 +0100 | [diff] [blame] | 271 | bool Blob::isCriticalToDeviceEncryption() const { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 272 | return mBlob->flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION; |
Rubin Xu | 67899de | 2017-04-21 19:15:13 +0100 | [diff] [blame] | 273 | } |
| 274 | |
Shawn Willden | d5a24e6 | 2017-02-28 13:53:24 -0700 | [diff] [blame] | 275 | inline uint8_t setFlag(uint8_t flags, bool set, KeyStoreFlag flag) { |
| 276 | return set ? (flags | flag) : (flags & ~flag); |
| 277 | } |
| 278 | |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 279 | void Blob::setEncrypted(bool encrypted) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 280 | mBlob->flags = setFlag(mBlob->flags, encrypted, KEYSTORE_FLAG_ENCRYPTED); |
Shawn Willden | d5a24e6 | 2017-02-28 13:53:24 -0700 | [diff] [blame] | 281 | } |
| 282 | |
Rubin Xu | 67899de | 2017-04-21 19:15:13 +0100 | [diff] [blame] | 283 | void Blob::setSuperEncrypted(bool superEncrypted) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 284 | mBlob->flags = setFlag(mBlob->flags, superEncrypted, KEYSTORE_FLAG_SUPER_ENCRYPTED); |
Rubin Xu | 67899de | 2017-04-21 19:15:13 +0100 | [diff] [blame] | 285 | } |
Rubin Xu | 4847795 | 2017-04-19 14:16:57 +0100 | [diff] [blame] | 286 | |
Rubin Xu | 67899de | 2017-04-21 19:15:13 +0100 | [diff] [blame] | 287 | void Blob::setCriticalToDeviceEncryption(bool critical) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 288 | mBlob->flags = setFlag(mBlob->flags, critical, KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 289 | } |
| 290 | |
| 291 | void Blob::setFallback(bool fallback) { |
| 292 | if (fallback) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 293 | mBlob->flags |= KEYSTORE_FLAG_FALLBACK; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 294 | } else { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 295 | mBlob->flags &= ~KEYSTORE_FLAG_FALLBACK; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 296 | } |
| 297 | } |
| 298 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 299 | static ResponseCode writeBlob(const std::string& filename, Blob blob, blobv3* rawBlob, |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 300 | const std::vector<uint8_t>& aes_key, State state) { |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 301 | ALOGV("writing blob %s", filename.c_str()); |
| 302 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 303 | const size_t dataLength = rawBlob->length; |
| 304 | rawBlob->length = htonl(rawBlob->length); |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 305 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 306 | if (blob.isEncrypted() || blob.isSuperEncrypted()) { |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 307 | if (state != STATE_NO_ERROR) { |
| 308 | ALOGD("couldn't insert encrypted blob while not unlocked"); |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 309 | return ResponseCode::LOCKED; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 310 | } |
| 311 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 312 | memset(rawBlob->initialization_vector, 0, AES_BLOCK_SIZE); |
Branden Archer | 44d1afa | 2018-12-28 09:10:49 -0800 | [diff] [blame] | 313 | if (!RAND_bytes(rawBlob->initialization_vector, kGcmIvSizeBytes)) { |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 314 | ALOGW("Could not read random data for: %s", filename.c_str()); |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 315 | return ResponseCode::SYSTEM_ERROR; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 316 | } |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 317 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 318 | auto rc = AES_gcm_encrypt(rawBlob->value /* in */, rawBlob->value /* out */, dataLength, |
| 319 | aes_key, rawBlob->initialization_vector, rawBlob->aead_tag); |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 320 | if (rc != ResponseCode::NO_ERROR) return rc; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 321 | } |
| 322 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 323 | size_t fileLength = offsetof(blobv3, value) + dataLength + rawBlob->info; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 324 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 325 | int out = |
| 326 | TEMP_FAILURE_RETRY(open(filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR)); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 327 | if (out < 0) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 328 | ALOGW("could not open file: %s: %s", filename.c_str(), strerror(errno)); |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 329 | return ResponseCode::SYSTEM_ERROR; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 330 | } |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 331 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 332 | const size_t writtenBytes = writeFully(out, reinterpret_cast<uint8_t*>(rawBlob), fileLength); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 333 | if (close(out) != 0) { |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 334 | return ResponseCode::SYSTEM_ERROR; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 335 | } |
| 336 | if (writtenBytes != fileLength) { |
| 337 | ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength); |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 338 | unlink(filename.c_str()); |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 339 | return ResponseCode::SYSTEM_ERROR; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 340 | } |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 341 | return ResponseCode::NO_ERROR; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 342 | } |
| 343 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 344 | ResponseCode LockedKeyBlobEntry::writeBlobs(Blob keyBlob, Blob characteristicsBlob, |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 345 | const std::vector<uint8_t>& aes_key, |
| 346 | State state) const { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 347 | if (entry_ == nullptr) { |
| 348 | return ResponseCode::SYSTEM_ERROR; |
| 349 | } |
| 350 | ResponseCode rc; |
| 351 | if (keyBlob) { |
| 352 | blobv3* rawBlob = keyBlob.mBlob.get(); |
Branden Archer | 44d1afa | 2018-12-28 09:10:49 -0800 | [diff] [blame] | 353 | rc = writeBlob(entry_->getKeyBlobPath(), std::move(keyBlob), rawBlob, aes_key, state); |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 354 | if (rc != ResponseCode::NO_ERROR) { |
| 355 | return rc; |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | if (characteristicsBlob) { |
| 360 | blobv3* rawBlob = characteristicsBlob.mBlob.get(); |
| 361 | rc = writeBlob(entry_->getCharacteristicsBlobPath(), std::move(characteristicsBlob), |
Branden Archer | 44d1afa | 2018-12-28 09:10:49 -0800 | [diff] [blame] | 362 | rawBlob, aes_key, state); |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 363 | } |
| 364 | return rc; |
| 365 | } |
| 366 | |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 367 | ResponseCode Blob::readBlob(const std::string& filename, const std::vector<uint8_t>& aes_key, |
| 368 | State state) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 369 | ResponseCode rc; |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 370 | ALOGV("reading blob %s", filename.c_str()); |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 371 | std::unique_ptr<blobv3> rawBlob = std::make_unique<blobv3>(); |
| 372 | |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 373 | const int in = TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY)); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 374 | if (in < 0) { |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 375 | return (errno == ENOENT) ? ResponseCode::KEY_NOT_FOUND : ResponseCode::SYSTEM_ERROR; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 376 | } |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 377 | |
| 378 | // fileLength may be less than sizeof(mBlob) |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 379 | const size_t fileLength = readFully(in, (uint8_t*)rawBlob.get(), sizeof(blobv3)); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 380 | if (close(in) != 0) { |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 381 | return ResponseCode::SYSTEM_ERROR; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 382 | } |
| 383 | |
| 384 | if (fileLength == 0) { |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 385 | return ResponseCode::VALUE_CORRUPTED; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 386 | } |
| 387 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 388 | if (rawBlobIsEncrypted(*rawBlob)) { |
| 389 | if (state == STATE_LOCKED) { |
| 390 | mBlob = std::move(rawBlob); |
| 391 | return ResponseCode::LOCKED; |
| 392 | } |
Janis Danisevskis | 36316d6 | 2017-09-01 14:31:36 -0700 | [diff] [blame] | 393 | if (state == STATE_UNINITIALIZED) return ResponseCode::UNINITIALIZED; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 394 | } |
| 395 | |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 396 | if (fileLength < offsetof(blobv3, value)) return ResponseCode::VALUE_CORRUPTED; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 397 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 398 | if (rawBlob->version == 3) { |
| 399 | const ssize_t encryptedLength = ntohl(rawBlob->length); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 400 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 401 | if (rawBlobIsEncrypted(*rawBlob)) { |
| 402 | rc = AES_gcm_decrypt(rawBlob->value /* in */, rawBlob->value /* out */, encryptedLength, |
| 403 | aes_key, rawBlob->initialization_vector, rawBlob->aead_tag); |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 404 | if (rc != ResponseCode::NO_ERROR) return rc; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 405 | } |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 406 | } else if (rawBlob->version < 3) { |
| 407 | blobv2& v2blob = reinterpret_cast<blobv2&>(*rawBlob); |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 408 | const size_t headerLength = offsetof(blobv2, encrypted); |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 409 | const ssize_t encryptedLength = fileLength - headerLength - v2blob.info; |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 410 | if (encryptedLength < 0) return ResponseCode::VALUE_CORRUPTED; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 411 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 412 | if (rawBlobIsEncrypted(*rawBlob)) { |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 413 | if (encryptedLength % AES_BLOCK_SIZE != 0) { |
| 414 | return ResponseCode::VALUE_CORRUPTED; |
| 415 | } |
| 416 | |
| 417 | AES_KEY key; |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 418 | AES_set_decrypt_key(aes_key.data(), kAesKeySize * 8, &key); |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 419 | AES_cbc_encrypt(v2blob.encrypted, v2blob.encrypted, encryptedLength, &key, |
| 420 | v2blob.vector, AES_DECRYPT); |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 421 | key = {}; // clear key |
| 422 | |
| 423 | uint8_t computedDigest[MD5_DIGEST_LENGTH]; |
| 424 | ssize_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH; |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 425 | MD5(v2blob.digested, digestedLength, computedDigest); |
| 426 | if (memcmp(v2blob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) { |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 427 | return ResponseCode::VALUE_CORRUPTED; |
| 428 | } |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 429 | } |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 430 | } |
| 431 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 432 | const ssize_t maxValueLength = fileLength - offsetof(blobv3, value) - rawBlob->info; |
| 433 | rawBlob->length = ntohl(rawBlob->length); |
| 434 | if (rawBlob->length < 0 || rawBlob->length > maxValueLength || |
| 435 | rawBlob->length + rawBlob->info + AES_BLOCK_SIZE > |
| 436 | static_cast<ssize_t>(sizeof(rawBlob->value))) { |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 437 | return ResponseCode::VALUE_CORRUPTED; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 438 | } |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 439 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 440 | if (rawBlob->info != 0 && rawBlob->version < 3) { |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 441 | // move info from after padding to after data |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 442 | memmove(rawBlob->value + rawBlob->length, rawBlob->value + maxValueLength, rawBlob->info); |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 443 | } |
Shawn Willden | e983058 | 2017-04-18 10:47:57 -0600 | [diff] [blame] | 444 | |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 445 | mBlob = std::move(rawBlob); |
Janis Danisevskis | c7a9fa2 | 2016-10-13 18:43:45 +0100 | [diff] [blame] | 446 | return ResponseCode::NO_ERROR; |
Shawn Willden | c1d1fee | 2016-01-26 22:44:56 -0700 | [diff] [blame] | 447 | } |
Janis Danisevskis | c146014 | 2017-12-18 16:48:46 -0800 | [diff] [blame] | 448 | |
Branden Archer | f5953d7 | 2019-01-10 09:08:18 -0800 | [diff] [blame^] | 449 | std::tuple<ResponseCode, Blob, Blob> |
| 450 | LockedKeyBlobEntry::readBlobs(const std::vector<uint8_t>& aes_key, State state) const { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 451 | std::tuple<ResponseCode, Blob, Blob> result; |
| 452 | auto& [rc, keyBlob, characteristicsBlob] = result; |
| 453 | if (entry_ == nullptr) return rc = ResponseCode::SYSTEM_ERROR, result; |
| 454 | |
| 455 | rc = keyBlob.readBlob(entry_->getKeyBlobPath(), aes_key, state); |
| 456 | if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::UNINITIALIZED) { |
| 457 | return result; |
| 458 | } |
| 459 | |
| 460 | if (entry_->hasCharacteristicsBlob()) { |
| 461 | characteristicsBlob.readBlob(entry_->getCharacteristicsBlobPath(), aes_key, state); |
| 462 | } |
| 463 | return result; |
| 464 | } |
| 465 | |
| 466 | ResponseCode LockedKeyBlobEntry::deleteBlobs() const { |
| 467 | if (entry_ == nullptr) return ResponseCode::NO_ERROR; |
| 468 | |
| 469 | // always try to delete both |
| 470 | ResponseCode rc1 = (unlink(entry_->getKeyBlobPath().c_str()) && errno != ENOENT) |
| 471 | ? ResponseCode::SYSTEM_ERROR |
| 472 | : ResponseCode::NO_ERROR; |
| 473 | if (rc1 != ResponseCode::NO_ERROR) { |
| 474 | ALOGW("Failed to delete key blob file \"%s\"", entry_->getKeyBlobPath().c_str()); |
| 475 | } |
| 476 | ResponseCode rc2 = (unlink(entry_->getCharacteristicsBlobPath().c_str()) && errno != ENOENT) |
| 477 | ? ResponseCode::SYSTEM_ERROR |
| 478 | : ResponseCode::NO_ERROR; |
| 479 | if (rc2 != ResponseCode::NO_ERROR) { |
| 480 | ALOGW("Failed to delete key characteristics file \"%s\"", |
| 481 | entry_->getCharacteristicsBlobPath().c_str()); |
| 482 | } |
| 483 | // then report the first error that occured |
| 484 | if (rc1 != ResponseCode::NO_ERROR) return rc1; |
| 485 | return rc2; |
| 486 | } |
| 487 | |
Janis Danisevskis | c146014 | 2017-12-18 16:48:46 -0800 | [diff] [blame] | 488 | keystore::SecurityLevel Blob::getSecurityLevel() const { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 489 | return keystore::flagsToSecurityLevel(mBlob->flags); |
Janis Danisevskis | c146014 | 2017-12-18 16:48:46 -0800 | [diff] [blame] | 490 | } |
| 491 | |
| 492 | void Blob::setSecurityLevel(keystore::SecurityLevel secLevel) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 493 | mBlob->flags &= ~(KEYSTORE_FLAG_FALLBACK | KEYSTORE_FLAG_STRONGBOX); |
| 494 | mBlob->flags |= keystore::securityLevelToFlags(secLevel); |
| 495 | } |
| 496 | |
| 497 | std::tuple<bool, keystore::AuthorizationSet, keystore::AuthorizationSet> |
| 498 | Blob::getKeyCharacteristics() const { |
| 499 | std::tuple<bool, keystore::AuthorizationSet, keystore::AuthorizationSet> result; |
| 500 | auto& [success, hwEnforced, swEnforced] = result; |
| 501 | success = false; |
| 502 | ArrayStreamBuffer buf(mBlob->value); |
| 503 | std::istream in(&buf); |
| 504 | |
| 505 | // only the characteristics cache has both sets |
| 506 | if (getType() == TYPE_KEY_CHARACTERISTICS_CACHE) { |
| 507 | hwEnforced.Deserialize(&in); |
| 508 | } else if (getType() != TYPE_KEY_CHARACTERISTICS) { |
| 509 | // if its not the cache and not the legacy characteristics file we have no business |
| 510 | // here |
| 511 | return result; |
| 512 | } |
| 513 | swEnforced.Deserialize(&in); |
| 514 | success = !in.bad(); |
| 515 | |
| 516 | return result; |
| 517 | } |
| 518 | bool Blob::putKeyCharacteristics(const keystore::AuthorizationSet& hwEnforced, |
| 519 | const keystore::AuthorizationSet& swEnforced) { |
| 520 | if (!mBlob) mBlob = std::make_unique<blobv3>(); |
| 521 | mBlob->version = CURRENT_BLOB_VERSION; |
| 522 | ArrayStreamBuffer buf(mBlob->value); |
| 523 | std::ostream out(&buf); |
| 524 | hwEnforced.Serialize(&out); |
| 525 | swEnforced.Serialize(&out); |
| 526 | if (out.bad()) return false; |
| 527 | setType(TYPE_KEY_CHARACTERISTICS_CACHE); |
| 528 | mBlob->length = out.tellp(); |
| 529 | return true; |
| 530 | } |
| 531 | |
| 532 | void LockedKeyBlobEntry::put(const KeyBlobEntry& entry) { |
| 533 | std::unique_lock<std::mutex> lock(locked_blobs_mutex_); |
| 534 | locked_blobs_.erase(entry); |
| 535 | lock.unlock(); |
| 536 | locked_blobs_mutex_cond_var_.notify_all(); |
| 537 | } |
| 538 | |
| 539 | LockedKeyBlobEntry::~LockedKeyBlobEntry() { |
| 540 | if (entry_ != nullptr) put(*entry_); |
| 541 | } |
| 542 | |
| 543 | LockedKeyBlobEntry LockedKeyBlobEntry::get(KeyBlobEntry entry) { |
| 544 | std::unique_lock<std::mutex> lock(locked_blobs_mutex_); |
| 545 | locked_blobs_mutex_cond_var_.wait( |
| 546 | lock, [&] { return locked_blobs_.find(entry) == locked_blobs_.end(); }); |
| 547 | auto [iterator, success] = locked_blobs_.insert(std::move(entry)); |
| 548 | if (!success) return {}; |
| 549 | return LockedKeyBlobEntry(*iterator); |
| 550 | } |
| 551 | |
| 552 | std::set<KeyBlobEntry> LockedKeyBlobEntry::locked_blobs_; |
| 553 | std::mutex LockedKeyBlobEntry::locked_blobs_mutex_; |
| 554 | std::condition_variable LockedKeyBlobEntry::locked_blobs_mutex_cond_var_; |
| 555 | |
| 556 | /* Here is the encoding of key names. This is necessary in order to allow arbitrary |
| 557 | * characters in key names. Characters in [0-~] are not encoded. Others are encoded |
| 558 | * into two bytes. The first byte is one of [+-.] which represents the first |
| 559 | * two bits of the character. The second byte encodes the rest of the bits into |
| 560 | * [0-o]. Therefore in the worst case the length of a key gets doubled. Note |
| 561 | * that Base64 cannot be used here due to the need of prefix match on keys. */ |
| 562 | |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 563 | std::string encodeKeyName(const std::string& keyName) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 564 | std::string encodedName; |
| 565 | encodedName.reserve(keyName.size() * 2); |
| 566 | auto in = keyName.begin(); |
| 567 | while (in != keyName.end()) { |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 568 | // Input character needs to be encoded. |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 569 | if (*in < '0' || *in > '~') { |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 570 | // Encode the two most-significant bits of the input char in the first |
| 571 | // output character, by counting up from 43 ('+'). |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 572 | encodedName.append(1, '+' + (uint8_t(*in) >> 6)); |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 573 | // Encode the six least-significant bits of the input char in the second |
| 574 | // output character, by counting up from 48 ('0'). |
| 575 | // This is safe because the maximum value is 112, which is the |
| 576 | // character 'p'. |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 577 | encodedName.append(1, '0' + (*in & 0x3F)); |
| 578 | } else { |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 579 | // No need to encode input char - append as-is. |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 580 | encodedName.append(1, *in); |
| 581 | } |
| 582 | ++in; |
| 583 | } |
| 584 | return encodedName; |
| 585 | } |
| 586 | |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 587 | std::string decodeKeyName(const std::string& encodedName) { |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 588 | std::string decodedName; |
| 589 | decodedName.reserve(encodedName.size()); |
| 590 | auto in = encodedName.begin(); |
| 591 | bool multichar = false; |
| 592 | char c; |
| 593 | while (in != encodedName.end()) { |
| 594 | if (multichar) { |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 595 | // Second part of a multi-character encoding. Turn off the multichar |
| 596 | // flag and set the six least-significant bits of c to the value originally |
| 597 | // encoded by counting up from '0'. |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 598 | multichar = false; |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 599 | decodedName.append(1, c | (uint8_t(*in) - '0')); |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 600 | } else if (*in >= '+' && *in <= '.') { |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 601 | // First part of a multi-character encoding. Set the multichar flag |
| 602 | // and set the two most-significant bits of c to be the two bits originally |
| 603 | // encoded by counting up from '+'. |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 604 | multichar = true; |
| 605 | c = (*in - '+') << 6; |
| 606 | } else { |
Eran Messeri | 2ba77c3 | 2018-12-04 12:22:16 +0000 | [diff] [blame] | 607 | // Regular character, append as-is. |
Janis Danisevskis | ff3d7f4 | 2018-10-08 07:15:09 -0700 | [diff] [blame] | 608 | decodedName.append(1, *in); |
| 609 | } |
| 610 | ++in; |
| 611 | } |
| 612 | // mulitchars at the end get truncated |
| 613 | return decodedName; |
| 614 | } |
| 615 | |
| 616 | std::string KeyBlobEntry::getKeyBlobBaseName() const { |
| 617 | std::stringstream s; |
| 618 | if (masterkey_) { |
| 619 | s << alias_; |
| 620 | } else { |
| 621 | s << uid_ << "_" << encodeKeyName(alias_); |
| 622 | } |
| 623 | return s.str(); |
| 624 | } |
| 625 | |
| 626 | std::string KeyBlobEntry::getKeyBlobPath() const { |
| 627 | std::stringstream s; |
| 628 | if (masterkey_) { |
| 629 | s << user_dir_ << "/" << alias_; |
| 630 | } else { |
| 631 | s << user_dir_ << "/" << uid_ << "_" << encodeKeyName(alias_); |
| 632 | } |
| 633 | return s.str(); |
| 634 | } |
| 635 | |
| 636 | std::string KeyBlobEntry::getCharacteristicsBlobBaseName() const { |
| 637 | std::stringstream s; |
| 638 | if (!masterkey_) s << "." << uid_ << "_chr_" << encodeKeyName(alias_); |
| 639 | return s.str(); |
| 640 | } |
| 641 | |
| 642 | std::string KeyBlobEntry::getCharacteristicsBlobPath() const { |
| 643 | std::stringstream s; |
| 644 | if (!masterkey_) |
| 645 | s << user_dir_ << "/" |
| 646 | << "." << uid_ << "_chr_" << encodeKeyName(alias_); |
| 647 | return s.str(); |
| 648 | } |
| 649 | |
| 650 | bool KeyBlobEntry::hasKeyBlob() const { |
| 651 | return !access(getKeyBlobPath().c_str(), R_OK | W_OK); |
| 652 | } |
| 653 | bool KeyBlobEntry::hasCharacteristicsBlob() const { |
| 654 | return !access(getCharacteristicsBlobPath().c_str(), R_OK | W_OK); |
| 655 | } |
| 656 | |
| 657 | static std::tuple<bool, uid_t, std::string> filename2UidAlias(const std::string& filepath) { |
| 658 | std::tuple<bool, uid_t, std::string> result; |
| 659 | |
| 660 | auto& [success, uid, alias] = result; |
| 661 | |
| 662 | success = false; |
| 663 | |
| 664 | auto filenamebase = filepath.find_last_of('/'); |
| 665 | std::string filename = |
| 666 | filenamebase == std::string::npos ? filepath : filepath.substr(filenamebase + 1); |
| 667 | |
| 668 | if (filename[0] == '.') return result; |
| 669 | |
| 670 | auto sep = filename.find('_'); |
| 671 | if (sep == std::string::npos) return result; |
| 672 | |
| 673 | std::stringstream s(filename.substr(0, sep)); |
| 674 | s >> uid; |
| 675 | if (!s) return result; |
| 676 | |
| 677 | alias = decodeKeyName(filename.substr(sep + 1)); |
| 678 | success = true; |
| 679 | return result; |
| 680 | } |
| 681 | |
| 682 | std::tuple<ResponseCode, std::list<LockedKeyBlobEntry>> |
| 683 | LockedKeyBlobEntry::list(const std::string& user_dir, |
| 684 | std::function<bool(uid_t, const std::string&)> filter) { |
| 685 | std::list<LockedKeyBlobEntry> matches; |
| 686 | |
| 687 | // This is a fence against any concurrent database accesses during database iteration. |
| 688 | // Only the keystore thread can lock entries. So it cannot be starved |
| 689 | // by workers grabbing new individual locks. We just wait here until all |
| 690 | // workers have relinquished their locked files. |
| 691 | std::unique_lock<std::mutex> lock(locked_blobs_mutex_); |
| 692 | locked_blobs_mutex_cond_var_.wait(lock, [&] { return locked_blobs_.empty(); }); |
| 693 | |
| 694 | DIR* dir = opendir(user_dir.c_str()); |
| 695 | if (!dir) { |
| 696 | ALOGW("can't open directory for user: %s", strerror(errno)); |
| 697 | return std::tuple<ResponseCode, std::list<LockedKeyBlobEntry>&&>{ResponseCode::SYSTEM_ERROR, |
| 698 | std::move(matches)}; |
| 699 | } |
| 700 | |
| 701 | struct dirent* file; |
| 702 | while ((file = readdir(dir)) != nullptr) { |
| 703 | // We only care about files. |
| 704 | if (file->d_type != DT_REG) { |
| 705 | continue; |
| 706 | } |
| 707 | |
| 708 | // Skip anything that starts with a "." |
| 709 | if (file->d_name[0] == '.') { |
| 710 | continue; |
| 711 | } |
| 712 | |
| 713 | auto [success, uid, alias] = filename2UidAlias(file->d_name); |
| 714 | |
| 715 | if (!success) { |
| 716 | ALOGW("could not parse key filename \"%s\"", file->d_name); |
| 717 | continue; |
| 718 | } |
| 719 | |
| 720 | if (!filter(uid, alias)) continue; |
| 721 | |
| 722 | auto [iterator, dummy] = locked_blobs_.emplace(alias, user_dir, uid); |
| 723 | matches.push_back(*iterator); |
| 724 | } |
| 725 | closedir(dir); |
| 726 | return std::tuple<ResponseCode, std::list<LockedKeyBlobEntry>&&>{ResponseCode::NO_ERROR, |
| 727 | std::move(matches)}; |
Janis Danisevskis | c146014 | 2017-12-18 16:48:46 -0800 | [diff] [blame] | 728 | } |