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 #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 
25 #include <condition_variable>
26 #include <functional>
27 #include <keystore/keymaster_types.h>
28 #include <keystore/keystore.h>
29 #include <list>
30 #include <mutex>
31 #include <set>
32 #include <sstream>
33 #include <vector>
34 
35 constexpr size_t kValueSize = 32768;
36 constexpr size_t kAesKeySize = 128 / 8;
37 constexpr size_t kGcmTagLength = 128 / 8;
38 constexpr size_t kGcmIvLength = 96 / 8;
39 constexpr size_t kAes128KeySizeBytes = 128 / 8;
40 constexpr size_t kAes256KeySizeBytes = 256 / 8;
41 
42 /* Here is the file format. There are two parts in blob.value, the secret and
43  * the description. The secret is stored in ciphertext, and its original size
44  * can be found in blob.length. The description is stored after the secret in
45  * plaintext, and its size is specified in blob.info. The total size of the two
46  * parts must be no more than kValueSize bytes. The first field is the version,
47  * the second is the blob's type, and the third byte is flags. Fields other
48  * than blob.info, blob.length, and blob.value are modified by encryptBlob()
49  * and decryptBlob(). Thus they should not be accessed from outside. */
50 
51 struct __attribute__((packed)) blobv3 {
52     uint8_t version;
53     uint8_t type;
54     uint8_t flags;
55     uint8_t info;
56     uint8_t initialization_vector[AES_BLOCK_SIZE];  // Only 96 bits is used, rest is zeroed.
57     uint8_t aead_tag[kGcmTagLength];
58     int32_t length;  // in network byte order, only for backward compatibility
59     uint8_t value[kValueSize + AES_BLOCK_SIZE];
60 };
61 
62 struct __attribute__((packed)) blobv2 {
63     uint8_t version;
64     uint8_t type;
65     uint8_t flags;
66     uint8_t info;
67     uint8_t vector[AES_BLOCK_SIZE];
68     uint8_t encrypted[0];  // Marks offset to encrypted data.
69     uint8_t digest[MD5_DIGEST_LENGTH];
70     uint8_t digested[0];  // Marks offset to digested data.
71     int32_t length;       // in network byte order
72     uint8_t value[kValueSize + AES_BLOCK_SIZE];
73 };
74 
75 static_assert(sizeof(blobv3) == sizeof(blobv2) &&
76                   offsetof(blobv3, initialization_vector) == offsetof(blobv2, vector) &&
77                   offsetof(blobv3, aead_tag) == offsetof(blobv2, digest) &&
78                   offsetof(blobv3, aead_tag) == offsetof(blobv2, encrypted) &&
79                   offsetof(blobv3, length) == offsetof(blobv2, length) &&
80                   offsetof(blobv3, value) == offsetof(blobv2, value),
81               "Oops.  Blob layout changed.");
82 
83 static const uint8_t CURRENT_BLOB_VERSION = 3;
84 
85 typedef enum {
86     TYPE_ANY = 0,  // meta type that matches anything
87     TYPE_GENERIC = 1,
88     TYPE_MASTER_KEY = 2,
89     TYPE_KEY_PAIR = 3,
90     TYPE_KEYMASTER_10 = 4,
91     TYPE_KEY_CHARACTERISTICS = 5,
92     TYPE_KEY_CHARACTERISTICS_CACHE = 6,
93     TYPE_MASTER_KEY_AES256 = 7,
94 } BlobType;
95 
96 class LockedKeyBlobEntry;
97 
98 /**
99  * The Blob represents the content of a KeyBlobEntry.
100  *
101  * BEWARE: It is only save to call any member function of a Blob b if bool(b) yields true.
102  *         Exceptions are putKeyCharacteristics(), the assignment operators and operator bool.
103  */
104 class Blob {
105     friend LockedKeyBlobEntry;
106 
107   public:
108     Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
109          BlobType type);
110     explicit Blob(blobv3 b);
111     Blob();
112     Blob(const Blob& rhs);
113     Blob(Blob&& rhs);
114 
~Blob()115     ~Blob() {
116         if (mBlob) *mBlob = {};
117     }
118 
119     Blob& operator=(const Blob& rhs);
120     Blob& operator=(Blob&& rhs);
121     explicit operator bool() const { return bool(mBlob); }
122 
getValue()123     const uint8_t* getValue() const { return mBlob->value; }
124 
getLength()125     int32_t getLength() const { return mBlob->length; }
126 
getInfo()127     const uint8_t* getInfo() const { return mBlob->value + mBlob->length; }
getInfoLength()128     uint8_t getInfoLength() const { return mBlob->info; }
129 
getVersion()130     uint8_t getVersion() const { return mBlob->version; }
131 
132     bool isEncrypted() const;
133     void setEncrypted(bool encrypted);
134 
135     bool isSuperEncrypted() const;
136     void setSuperEncrypted(bool superEncrypted);
137 
138     bool isCriticalToDeviceEncryption() const;
139     void setCriticalToDeviceEncryption(bool critical);
140 
isFallback()141     bool isFallback() const { return mBlob->flags & KEYSTORE_FLAG_FALLBACK; }
142     void setFallback(bool fallback);
143 
setVersion(uint8_t version)144     void setVersion(uint8_t version) { mBlob->version = version; }
getType()145     BlobType getType() const { return BlobType(mBlob->type); }
setType(BlobType type)146     void setType(BlobType type) { mBlob->type = uint8_t(type); }
147 
148     keystore::SecurityLevel getSecurityLevel() const;
149     void setSecurityLevel(keystore::SecurityLevel);
150 
151     std::tuple<bool, keystore::AuthorizationSet, keystore::AuthorizationSet>
152     getKeyCharacteristics() const;
153 
154     bool putKeyCharacteristics(const keystore::AuthorizationSet& hwEnforced,
155                                const keystore::AuthorizationSet& swEnforced);
156 
157   private:
158     std::unique_ptr<blobv3> mBlob;
159 
160     ResponseCode readBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
161                           State state);
162 };
163 
164 /**
165  * A KeyBlobEntry represents a full qualified key blob as known by Keystore. The key blob
166  * is given by the uid of the owning app and the alias used by the app to refer to this key.
167  * The user_dir_ is technically implied by the uid, but computation of the user directory is
168  * done in the user state database. Which is why we also cache it here.
169  *
170  * The KeyBlobEntry knows the location of the key blob files (which may include a characteristics
171  * cache file) but does not allow read or write access to the content. It also does not imply
172  * the existence of the files.
173  *
174  * KeyBlobEntry abstracts, to some extent, from the the file system based storage of key blobs.
175  * An evolution of KeyBlobEntry may be used for key blob storage based on a back end other than
176  * file system, e.g., SQL database or other.
177  *
178  * For access to the key blob content the programmer has to acquire a LockedKeyBlobEntry (see
179  * below).
180  */
181 class KeyBlobEntry {
182   private:
183     std::string alias_;
184     std::string user_dir_;
185     uid_t uid_;
186     bool masterkey_;
187 
188   public:
189     KeyBlobEntry(std::string alias, std::string user_dir, uid_t uid, bool masterkey = false)
alias_(std::move (alias))190         : alias_(std::move(alias)), user_dir_(std::move(user_dir)), uid_(uid),
191           masterkey_(masterkey) {}
192 
193     std::string getKeyBlobBaseName() const;
194     std::string getKeyBlobPath() const;
195 
196     std::string getCharacteristicsBlobBaseName() const;
197     std::string getCharacteristicsBlobPath() const;
198 
199     bool hasKeyBlob() const;
200     bool hasCharacteristicsBlob() const;
201 
202     bool operator<(const KeyBlobEntry& rhs) const {
203         return std::tie(uid_, alias_, user_dir_) < std::tie(rhs.uid_, rhs.alias_, rhs.user_dir_);
204     }
205     bool operator==(const KeyBlobEntry& rhs) const {
206         return std::tie(uid_, alias_, user_dir_) == std::tie(rhs.uid_, rhs.alias_, rhs.user_dir_);
207     }
208     bool operator!=(const KeyBlobEntry& rhs) const { return !(*this == rhs); }
209 
alias()210     inline const std::string& alias() const { return alias_; }
user_dir()211     inline const std::string& user_dir() const { return user_dir_; }
uid()212     inline uid_t uid() const { return uid_; }
213 };
214 
215 /**
216  * The LockedKeyBlobEntry is a proxy object to KeyBlobEntry that expresses exclusive ownership
217  * of a KeyBlobEntry. LockedKeyBlobEntries can be acquired by calling
218  * LockedKeyBlobEntry::get() or LockedKeyBlobEntry::list().
219  *
220  * LockedKeyBlobEntries are movable but not copyable. By convention they can only
221  * be taken by the dispatcher thread of keystore, but not by any keymaster worker thread.
222  * The dispatcher thread may transfer ownership of a locked entry to a keymaster worker thread.
223  *
224  * Locked entries are tracked on the stack or as members of movable functor objects passed to the
225  * keymaster worker request queues. Locks are relinquished as the locked entry gets destroyed, e.g.,
226  * when it goes out of scope or when the owning request functor gets destroyed.
227  *
228  * LockedKeyBlobEntry::list(), which must only be called by the dispatcher, blocks until all
229  * LockedKeyBlobEntries have been destroyed. Thereby list acts as a fence to make sure it gets a
230  * consistent view of the key blob database. Under the assumption that keymaster worker requests
231  * cannot run or block indefinitely and cannot grab new locked entries, progress is guaranteed.
232  * It then grabs locked entries in accordance with the given filter rule.
233  *
234  * LockedKeyBlobEntry allow access to the proxied KeyBlobEntry interface through the operator->.
235  * They add additional functionality to access and modify the key blob's content on disk.
236  * LockedKeyBlobEntry ensures atomic operations on the persistently stored key blobs on a per
237  * entry granularity.
238  */
239 class LockedKeyBlobEntry {
240   private:
241     static std::set<KeyBlobEntry> locked_blobs_;
242     static std::mutex locked_blobs_mutex_;
243     static std::condition_variable locked_blobs_mutex_cond_var_;
244 
245     const KeyBlobEntry* entry_;
246     // NOLINTNEXTLINE(google-explicit-constructor)
LockedKeyBlobEntry(const KeyBlobEntry & entry)247     LockedKeyBlobEntry(const KeyBlobEntry& entry) : entry_(&entry) {}
248 
249     static void put(const KeyBlobEntry& entry);
250     LockedKeyBlobEntry(const LockedKeyBlobEntry&) = delete;
251     LockedKeyBlobEntry& operator=(const LockedKeyBlobEntry&) = delete;
252 
253   public:
LockedKeyBlobEntry()254     LockedKeyBlobEntry() : entry_(nullptr){};
255     ~LockedKeyBlobEntry();
LockedKeyBlobEntry(LockedKeyBlobEntry && rhs)256     LockedKeyBlobEntry(LockedKeyBlobEntry&& rhs) : entry_(rhs.entry_) { rhs.entry_ = nullptr; }
257     LockedKeyBlobEntry& operator=(LockedKeyBlobEntry&& rhs) {
258         // as dummy goes out of scope it relinquishes the lock on this
259         LockedKeyBlobEntry dummy(std::move(*this));
260         entry_ = rhs.entry_;
261         rhs.entry_ = nullptr;
262         return *this;
263     }
264     static LockedKeyBlobEntry get(KeyBlobEntry entry);
265     static std::tuple<ResponseCode, std::list<LockedKeyBlobEntry>>
266     list(const std::string& user_dir,
267          std::function<bool(uid_t, const std::string&)> filter =
268              [](uid_t, const std::string&) -> bool { return true; });
269 
270     ResponseCode writeBlobs(Blob keyBlob, Blob characteristicsBlob,
271                             const std::vector<uint8_t>& aes_key, State state) const;
272     std::tuple<ResponseCode, Blob, Blob> readBlobs(const std::vector<uint8_t>& aes_key,
273                                                    State state) const;
274     ResponseCode deleteBlobs() const;
275 
276     inline explicit operator bool() const { return entry_ != nullptr; }
277     inline const KeyBlobEntry& operator*() const { return *entry_; }
278     inline const KeyBlobEntry* operator->() const { return entry_; }
279 };
280 
281 // Visible for testing
282 std::string encodeKeyName(const std::string& keyName);
283 std::string decodeKeyName(const std::string& encodedName);
284 
285 #endif  // KEYSTORE_BLOB_H_
286