blob: 86f367f58deea97cd3cdc12063532d005b2d7a77 [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#ifndef KEYSTORE_BLOB_H_
18#define KEYSTORE_BLOB_H_
19
20#include <stdint.h>
21
22#include <openssl/aes.h>
23#include <openssl/md5.h>
24
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070025#include <condition_variable>
26#include <functional>
Janis Danisevskisc1460142017-12-18 16:48:46 -080027#include <keystore/keymaster_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070028#include <keystore/keystore.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070029#include <list>
30#include <mutex>
31#include <set>
32#include <sstream>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070033
Shawn Willdene9830582017-04-18 10:47:57 -060034constexpr size_t kValueSize = 32768;
35constexpr size_t kAesKeySize = 128 / 8;
36constexpr size_t kGcmTagLength = 128 / 8;
37constexpr size_t kGcmIvLength = 96 / 8;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038
39/* Here is the file format. There are two parts in blob.value, the secret and
40 * the description. The secret is stored in ciphertext, and its original size
41 * can be found in blob.length. The description is stored after the secret in
42 * plaintext, and its size is specified in blob.info. The total size of the two
Shawn Willdene9830582017-04-18 10:47:57 -060043 * parts must be no more than kValueSize bytes. The first field is the version,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070044 * the second is the blob's type, and the third byte is flags. Fields other
45 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
46 * and decryptBlob(). Thus they should not be accessed from outside. */
47
Shawn Willdene9830582017-04-18 10:47:57 -060048struct __attribute__((packed)) blobv3 {
49 uint8_t version;
50 uint8_t type;
51 uint8_t flags;
52 uint8_t info;
53 uint8_t initialization_vector[AES_BLOCK_SIZE]; // Only 96 bits is used, rest is zeroed.
54 uint8_t aead_tag[kGcmTagLength];
55 int32_t length; // in network byte order, only for backward compatibility
56 uint8_t value[kValueSize + AES_BLOCK_SIZE];
57};
58
59struct __attribute__((packed)) blobv2 {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070060 uint8_t version;
61 uint8_t type;
62 uint8_t flags;
63 uint8_t info;
64 uint8_t vector[AES_BLOCK_SIZE];
65 uint8_t encrypted[0]; // Marks offset to encrypted data.
66 uint8_t digest[MD5_DIGEST_LENGTH];
67 uint8_t digested[0]; // Marks offset to digested data.
Shawn Willdene9830582017-04-18 10:47:57 -060068 int32_t length; // in network byte order
69 uint8_t value[kValueSize + AES_BLOCK_SIZE];
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070070};
71
Shawn Willdene9830582017-04-18 10:47:57 -060072static_assert(sizeof(blobv3) == sizeof(blobv2) &&
73 offsetof(blobv3, initialization_vector) == offsetof(blobv2, vector) &&
74 offsetof(blobv3, aead_tag) == offsetof(blobv2, digest) &&
75 offsetof(blobv3, aead_tag) == offsetof(blobv2, encrypted) &&
76 offsetof(blobv3, length) == offsetof(blobv2, length) &&
77 offsetof(blobv3, value) == offsetof(blobv2, value),
78 "Oops. Blob layout changed.");
79
80static const uint8_t CURRENT_BLOB_VERSION = 3;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070081
82typedef enum {
83 TYPE_ANY = 0, // meta type that matches anything
84 TYPE_GENERIC = 1,
85 TYPE_MASTER_KEY = 2,
86 TYPE_KEY_PAIR = 3,
87 TYPE_KEYMASTER_10 = 4,
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -040088 TYPE_KEY_CHARACTERISTICS = 5,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070089 TYPE_KEY_CHARACTERISTICS_CACHE = 6,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070090} BlobType;
91
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070092class LockedKeyBlobEntry;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070093
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070094/**
95 * The Blob represents the content of a KeyBlobEntry.
96 *
97 * BEWARE: It is only save to call any member function of a Blob b if bool(b) yields true.
98 * Exceptions are putKeyCharacteristics(), the assignment operators and operator bool.
99 */
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700100class Blob {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700101 friend LockedKeyBlobEntry;
102
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700103 public:
104 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
105 BlobType type);
Shawn Willdene9830582017-04-18 10:47:57 -0600106 explicit Blob(blobv3 b);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700107 Blob();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700108 Blob(const Blob& rhs);
109 Blob(Blob&& rhs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700110
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700111 ~Blob() {
112 if (mBlob) *mBlob = {};
113 }
Shawn Willdene9830582017-04-18 10:47:57 -0600114
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700115 Blob& operator=(const Blob& rhs);
116 Blob& operator=(Blob&& rhs);
117 operator bool() const { return bool(mBlob); }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700118
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700119 const uint8_t* getValue() const { return mBlob->value; }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700120
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700121 int32_t getLength() const { return mBlob->length; }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700122
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700123 const uint8_t* getInfo() const { return mBlob->value + mBlob->length; }
124 uint8_t getInfoLength() const { return mBlob->info; }
125
126 uint8_t getVersion() const { return mBlob->version; }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700127
128 bool isEncrypted() const;
129 void setEncrypted(bool encrypted);
130
Shawn Willdend5a24e62017-02-28 13:53:24 -0700131 bool isSuperEncrypted() const;
132 void setSuperEncrypted(bool superEncrypted);
133
Rubin Xu67899de2017-04-21 19:15:13 +0100134 bool isCriticalToDeviceEncryption() const;
135 void setCriticalToDeviceEncryption(bool critical);
136
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700137 bool isFallback() const { return mBlob->flags & KEYSTORE_FLAG_FALLBACK; }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700138 void setFallback(bool fallback);
139
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700140 void setVersion(uint8_t version) { mBlob->version = version; }
141 BlobType getType() const { return BlobType(mBlob->type); }
142 void setType(BlobType type) { mBlob->type = uint8_t(type); }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700143
Janis Danisevskisc1460142017-12-18 16:48:46 -0800144 keystore::SecurityLevel getSecurityLevel() const;
145 void setSecurityLevel(keystore::SecurityLevel);
146
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700147 std::tuple<bool, keystore::AuthorizationSet, keystore::AuthorizationSet>
148 getKeyCharacteristics() const;
149
150 bool putKeyCharacteristics(const keystore::AuthorizationSet& hwEnforced,
151 const keystore::AuthorizationSet& swEnforced);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152
153 private:
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700154 std::unique_ptr<blobv3> mBlob;
155
156 ResponseCode readBlob(const std::string& filename, const uint8_t* aes_key, State state);
157};
158
159/**
160 * A KeyBlobEntry represents a full qualified key blob as known by Keystore. The key blob
161 * is given by the uid of the owning app and the alias used by the app to refer to this key.
162 * The user_dir_ is technically implied by the uid, but computation of the user directory is
163 * done in the user state database. Which is why we also cache it here.
164 *
165 * The KeyBlobEntry knows the location of the key blob files (which may include a characteristics
166 * cache file) but does not allow read or write access to the content. It also does not imply
167 * the existence of the files.
168 *
169 * KeyBlobEntry abstracts, to some extent, from the the file system based storage of key blobs.
170 * An evolution of KeyBlobEntry may be used for key blob storage based on a back end other than
171 * file system, e.g., SQL database or other.
172 *
173 * For access to the key blob content the programmer has to acquire a LockedKeyBlobEntry (see
174 * below).
175 */
176class KeyBlobEntry {
177 private:
178 std::string alias_;
179 std::string user_dir_;
180 uid_t uid_;
181 bool masterkey_;
182
183 public:
184 KeyBlobEntry(std::string alias, std::string user_dir, uid_t uid, bool masterkey = false)
185 : alias_(std::move(alias)), user_dir_(std::move(user_dir)), uid_(uid),
186 masterkey_(masterkey) {}
187
188 std::string getKeyBlobBaseName() const;
189 std::string getKeyBlobPath() const;
190
191 std::string getCharacteristicsBlobBaseName() const;
192 std::string getCharacteristicsBlobPath() const;
193
194 bool hasKeyBlob() const;
195 bool hasCharacteristicsBlob() const;
196
197 bool operator<(const KeyBlobEntry& rhs) const {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800198 return std::tie(uid_, alias_, user_dir_) < std::tie(rhs.uid_, rhs.alias_, rhs.user_dir_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700199 }
200 bool operator==(const KeyBlobEntry& rhs) const {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800201 return std::tie(uid_, alias_, user_dir_) == std::tie(rhs.uid_, rhs.alias_, rhs.user_dir_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700202 }
203 bool operator!=(const KeyBlobEntry& rhs) const { return !(*this == rhs); }
204
205 inline const std::string& alias() const { return alias_; }
206 inline const std::string& user_dir() const { return user_dir_; }
207 inline uid_t uid() const { return uid_; }
208};
209
210/**
211 * The LockedKeyBlobEntry is a proxy object to KeyBlobEntry that expresses exclusive ownership
212 * of a KeyBlobEntry. LockedKeyBlobEntries can be acquired by calling
213 * LockedKeyBlobEntry::get() or LockedKeyBlobEntry::list().
214 *
215 * LockedKeyBlobEntries are movable but not copyable. By convention they can only
216 * be taken by the dispatcher thread of keystore, but not by any keymaster worker thread.
217 * The dispatcher thread may transfer ownership of a locked entry to a keymaster worker thread.
218 *
219 * Locked entries are tracked on the stack or as members of movable functor objects passed to the
220 * keymaster worker request queues. Locks are relinquished as the locked entry gets destroyed, e.g.,
221 * when it goes out of scope or when the owning request functor gets destroyed.
222 *
223 * LockedKeyBlobEntry::list(), which must only be called by the dispatcher, blocks until all
224 * LockedKeyBlobEntries have been destroyed. Thereby list acts as a fence to make sure it gets a
225 * consistent view of the key blob database. Under the assumption that keymaster worker requests
226 * cannot run or block indefinitely and cannot grab new locked entries, progress is guaranteed.
227 * It then grabs locked entries in accordance with the given filter rule.
228 *
229 * LockedKeyBlobEntry allow access to the proxied KeyBlobEntry interface through the operator->.
230 * They add additional functionality to access and modify the key blob's content on disk.
231 * LockedKeyBlobEntry ensures atomic operations on the persistently stored key blobs on a per
232 * entry granularity.
233 */
234class LockedKeyBlobEntry {
235 private:
236 static std::set<KeyBlobEntry> locked_blobs_;
237 static std::mutex locked_blobs_mutex_;
238 static std::condition_variable locked_blobs_mutex_cond_var_;
239
240 const KeyBlobEntry* entry_;
241 LockedKeyBlobEntry(const KeyBlobEntry& entry) : entry_(&entry) {}
242
243 static void put(const KeyBlobEntry& entry);
244 LockedKeyBlobEntry(const LockedKeyBlobEntry&) = delete;
245 LockedKeyBlobEntry& operator=(const LockedKeyBlobEntry&) = delete;
246
247 public:
248 LockedKeyBlobEntry() : entry_(nullptr){};
249 ~LockedKeyBlobEntry();
250 LockedKeyBlobEntry(LockedKeyBlobEntry&& rhs) : entry_(rhs.entry_) { rhs.entry_ = nullptr; }
251 LockedKeyBlobEntry& operator=(LockedKeyBlobEntry&& rhs) {
252 // as dummy goes out of scope it relinquishes the lock on this
253 LockedKeyBlobEntry dummy(std::move(*this));
254 entry_ = rhs.entry_;
255 rhs.entry_ = nullptr;
256 return *this;
257 }
258 static LockedKeyBlobEntry get(KeyBlobEntry entry);
259 static std::tuple<ResponseCode, std::list<LockedKeyBlobEntry>>
260 list(const std::string& user_dir,
261 std::function<bool(uid_t, const std::string&)> filter =
262 [](uid_t, const std::string&) -> bool { return true; });
263
264 ResponseCode writeBlobs(Blob keyBlob, Blob characteristicsBlob, const uint8_t* aes_key,
Branden Archer44d1afa2018-12-28 09:10:49 -0800265 State state) const;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700266 std::tuple<ResponseCode, Blob, Blob> readBlobs(const uint8_t* aes_key, State state) const;
267 ResponseCode deleteBlobs() const;
268
269 inline operator bool() const { return entry_ != nullptr; }
270 inline const KeyBlobEntry& operator*() const { return *entry_; }
271 inline const KeyBlobEntry* operator->() const { return entry_; }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700272};
273
Eran Messeri2ba77c32018-12-04 12:22:16 +0000274// Visible for testing
275std::string encodeKeyName(const std::string& keyName);
276std::string decodeKeyName(const std::string& encodedName);
277
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700278#endif // KEYSTORE_BLOB_H_