blob.h 11 KB

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