1 //
2 // Copyright (C) 2020 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 #include "tpm_key_blob_maker.h"
17 
18 #include <vector>
19 
20 #include <android-base/logging.h>
21 #include <tss2/tss2_mu.h>
22 #include <tss2/tss2_rc.h>
23 
24 #include "host/commands/secure_env/composite_serialization.h"
25 #include "host/commands/secure_env/encrypted_serializable.h"
26 #include "host/commands/secure_env/hmac_serializable.h"
27 #include "host/commands/secure_env/primary_key_builder.h"
28 
29 namespace cuttlefish {
30 
31 using keymaster::AuthorizationSet;
32 using keymaster::KeymasterKeyBlob;
33 using keymaster::Serializable;
34 
35 static constexpr char kUniqueKey[] = "TpmKeyBlobMaker";
36 
37 /**
38  * Distinguish what properties the secure_env implementation handles. If
39  * secure_env handles it, the property is put in `hw_enforced`. Otherwise, the
40  * property is put in `sw_enforced`, and the Keystore process inside Android
41  * will try to enforce the property.
42  */
SplitEnforcedProperties(const keymaster::AuthorizationSet & key_description,keymaster::AuthorizationSet * hw_enforced,keymaster::AuthorizationSet * sw_enforced,keymaster::AuthorizationSet * hidden)43 static keymaster_error_t SplitEnforcedProperties(
44     const keymaster::AuthorizationSet& key_description,
45     keymaster::AuthorizationSet* hw_enforced,
46     keymaster::AuthorizationSet* sw_enforced,
47     keymaster::AuthorizationSet* hidden) {
48   for (auto& entry : key_description) {
49     switch (entry.tag) {
50       // These cannot be specified by the client.
51       case KM_TAG_BOOT_PATCHLEVEL:
52       case KM_TAG_ORIGIN:
53       case KM_TAG_OS_PATCHLEVEL:
54       case KM_TAG_OS_VERSION:
55       case KM_TAG_ROOT_OF_TRUST:
56       case KM_TAG_VENDOR_PATCHLEVEL:
57         LOG(DEBUG) << "Root of trust and origin tags may not be specified";
58         return KM_ERROR_INVALID_TAG;
59 
60       // These are hidden
61       case KM_TAG_APPLICATION_DATA:
62       case KM_TAG_APPLICATION_ID:
63         hidden->push_back(entry);
64         break;
65 
66       // These should not be in key descriptions because they're for operation
67       // parameters.
68       case KM_TAG_ASSOCIATED_DATA:
69       case KM_TAG_AUTH_TOKEN:
70       case KM_TAG_CONFIRMATION_TOKEN:
71       case KM_TAG_INVALID:
72       case KM_TAG_MAC_LENGTH:
73       case KM_TAG_NONCE:
74         LOG(DEBUG) << "Tag " << entry.tag
75                    << " not allowed in key generation/import";
76         break;
77 
78       // These are provided to support attestation key generation, but should
79       // not be included in the key characteristics.
80       case KM_TAG_ATTESTATION_APPLICATION_ID:
81       case KM_TAG_ATTESTATION_CHALLENGE:
82       case KM_TAG_ATTESTATION_ID_BRAND:
83       case KM_TAG_ATTESTATION_ID_DEVICE:
84       case KM_TAG_ATTESTATION_ID_IMEI:
85       case KM_TAG_ATTESTATION_ID_SECOND_IMEI:
86       case KM_TAG_ATTESTATION_ID_MANUFACTURER:
87       case KM_TAG_ATTESTATION_ID_MEID:
88       case KM_TAG_ATTESTATION_ID_MODEL:
89       case KM_TAG_ATTESTATION_ID_PRODUCT:
90       case KM_TAG_ATTESTATION_ID_SERIAL:
91       case KM_TAG_CERTIFICATE_SERIAL:
92       case KM_TAG_CERTIFICATE_SUBJECT:
93       case KM_TAG_CERTIFICATE_NOT_BEFORE:
94       case KM_TAG_CERTIFICATE_NOT_AFTER:
95       case KM_TAG_RESET_SINCE_ID_ROTATION:
96         break;
97 
98       // strongbox-only tags
99       case KM_TAG_DEVICE_UNIQUE_ATTESTATION:
100         LOG(DEBUG) << "Strongbox-only tag: " << entry.tag;
101         return KM_ERROR_UNSUPPORTED_TAG;
102 
103       case KM_TAG_ROLLBACK_RESISTANT:
104         return KM_ERROR_UNSUPPORTED_TAG;
105 
106       case KM_TAG_ROLLBACK_RESISTANCE:
107         LOG(DEBUG) << "Rollback resistance is not implemented.";
108         return KM_ERROR_ROLLBACK_RESISTANCE_UNAVAILABLE;
109 
110       // These are nominally HW tags, but we don't actually support HW key
111       // attestation yet.
112       case KM_TAG_ALLOW_WHILE_ON_BODY:
113       case KM_TAG_EXPORTABLE:
114       case KM_TAG_IDENTITY_CREDENTIAL_KEY:
115       case KM_TAG_STORAGE_KEY:
116 
117       case KM_TAG_PURPOSE:
118       case KM_TAG_ALGORITHM:
119       case KM_TAG_KEY_SIZE:
120       case KM_TAG_RSA_PUBLIC_EXPONENT:
121       case KM_TAG_BLOB_USAGE_REQUIREMENTS:
122       case KM_TAG_DIGEST:
123       case KM_TAG_RSA_OAEP_MGF_DIGEST:
124       case KM_TAG_PADDING:
125       case KM_TAG_BLOCK_MODE:
126       case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
127       case KM_TAG_MAX_USES_PER_BOOT:
128       case KM_TAG_USER_SECURE_ID:
129       case KM_TAG_NO_AUTH_REQUIRED:
130       case KM_TAG_AUTH_TIMEOUT:
131       case KM_TAG_CALLER_NONCE:
132       case KM_TAG_MIN_MAC_LENGTH:
133       case KM_TAG_KDF:
134       case KM_TAG_EC_CURVE:
135       case KM_TAG_ECIES_SINGLE_HASH_MODE:
136       case KM_TAG_USER_AUTH_TYPE:
137       case KM_TAG_EARLY_BOOT_ONLY:
138       case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
139         hw_enforced->push_back(entry);
140         break;
141 
142       // The remaining tags are all software.
143       case KM_TAG_ACTIVE_DATETIME:
144       case KM_TAG_ALL_APPLICATIONS:
145       case KM_TAG_ALL_USERS:
146       case KM_TAG_BOOTLOADER_ONLY:
147       case KM_TAG_CREATION_DATETIME:
148       case KM_TAG_INCLUDE_UNIQUE_ID:
149       case KM_TAG_MAX_BOOT_LEVEL:
150       case KM_TAG_ORIGINATION_EXPIRE_DATETIME:
151       case KM_TAG_TRUSTED_CONFIRMATION_REQUIRED:
152       case KM_TAG_TRUSTED_USER_PRESENCE_REQUIRED:
153       case KM_TAG_UNIQUE_ID:
154       case KM_TAG_USAGE_COUNT_LIMIT:
155       case KM_TAG_USAGE_EXPIRE_DATETIME:
156       case KM_TAG_USER_ID:
157         sw_enforced->push_back(entry);
158         break;
159     }
160   }
161 
162   return KM_ERROR_OK;
163 }
164 
SerializableToKeyBlob(const Serializable & serializable)165 static KeymasterKeyBlob SerializableToKeyBlob(
166     const Serializable& serializable) {
167   std::vector<uint8_t> data(serializable.SerializedSize() + 1);
168   uint8_t* buf = data.data();
169   uint8_t* buf_end = buf + data.size();
170   buf = serializable.Serialize(buf, buf_end);
171   if (buf != (buf_end - 1)) {
172     LOG(ERROR) << "Serialized size did not match up with actual usage.";
173     return {};
174   }
175   return KeymasterKeyBlob(data.data(), buf - data.data());
176 }
177 
178 
TpmKeyBlobMaker(TpmResourceManager & resource_manager)179 TpmKeyBlobMaker::TpmKeyBlobMaker(TpmResourceManager& resource_manager)
180     : resource_manager_(resource_manager) {
181 }
182 
CreateKeyBlob(const AuthorizationSet & key_description,keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const183 keymaster_error_t TpmKeyBlobMaker::CreateKeyBlob(
184     const AuthorizationSet& key_description,
185     keymaster_key_origin_t origin,
186     const KeymasterKeyBlob& key_material,
187     KeymasterKeyBlob* blob,
188     AuthorizationSet* hw_enforced,
189     AuthorizationSet* sw_enforced) const {
190   AuthorizationSet hidden;
191   auto rc = SplitEnforcedProperties(key_description, hw_enforced, sw_enforced,
192                                     &hidden);
193   if (rc != KM_ERROR_OK) {
194     return rc;
195   }
196   hw_enforced->push_back(keymaster::TAG_ORIGIN, origin);
197 
198   // TODO(schuffelen): Set the os level and patch level properly.
199   hw_enforced->push_back(keymaster::TAG_OS_VERSION, os_version_);
200   hw_enforced->push_back(keymaster::TAG_OS_PATCHLEVEL, os_patchlevel_);
201 
202   if (vendor_patchlevel_) {
203     hw_enforced->push_back(keymaster::TAG_VENDOR_PATCHLEVEL,
204                            *vendor_patchlevel_);
205   }
206   if (boot_patchlevel_) {
207     hw_enforced->push_back(keymaster::TAG_BOOT_PATCHLEVEL, *boot_patchlevel_);
208   }
209 
210   return UnvalidatedCreateKeyBlob(key_material, *hw_enforced, *sw_enforced,
211                                   hidden, blob);
212 }
213 
UnvalidatedCreateKeyBlob(const KeymasterKeyBlob & key_material,const AuthorizationSet & hw_enforced,const AuthorizationSet & sw_enforced,const AuthorizationSet & hidden,KeymasterKeyBlob * blob) const214 keymaster_error_t TpmKeyBlobMaker::UnvalidatedCreateKeyBlob(
215     const KeymasterKeyBlob& key_material, const AuthorizationSet& hw_enforced,
216     const AuthorizationSet& sw_enforced, const AuthorizationSet& hidden,
217     KeymasterKeyBlob* blob) const {
218   keymaster::Buffer key_material_buffer(
219       key_material.key_material, key_material.key_material_size);
220   AuthorizationSet hw_enforced_mutable = hw_enforced;
221   AuthorizationSet sw_enforced_mutable = sw_enforced;
222   CompositeSerializable sensitive_material(
223       {&key_material_buffer, &hw_enforced_mutable, &sw_enforced_mutable});
224   auto parent_key_fn = ParentKeyCreator(kUniqueKey);
225   EncryptedSerializable encryption(
226       resource_manager_, parent_key_fn, sensitive_material);
227   auto signing_key_fn = SigningKeyCreator(kUniqueKey);
228   // TODO(b/154956668) The "hidden" tags should also be mixed into the TPM ACL
229   // so that the TPM requires them to be presented to unwrap the key. This is
230   // necessary to meet the requirement that full breach of KeyMint means an
231   // attacker cannot unwrap keys w/o the application id/data.
232   HmacSerializable sign_check(resource_manager_, signing_key_fn,
233                               TPM2_SHA256_DIGEST_SIZE, &encryption, &hidden);
234   auto generated_blob = SerializableToKeyBlob(sign_check);
235   LOG(VERBOSE) << "Keymaster key size: " << generated_blob.key_material_size;
236   if (generated_blob.key_material_size != 0) {
237     *blob = generated_blob;
238     return KM_ERROR_OK;
239   }
240   LOG(ERROR) << "Failed to serialize key.";
241   return KM_ERROR_UNKNOWN_ERROR;
242 }
243 
UnwrapKeyBlob(const keymaster_key_blob_t & blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced,const AuthorizationSet & hidden,KeymasterKeyBlob * key_material) const244 keymaster_error_t TpmKeyBlobMaker::UnwrapKeyBlob(
245     const keymaster_key_blob_t& blob, AuthorizationSet* hw_enforced,
246     AuthorizationSet* sw_enforced, const AuthorizationSet& hidden,
247     KeymasterKeyBlob* key_material) const {
248   keymaster::Buffer key_material_buffer(blob.key_material_size);
249   CompositeSerializable sensitive_material(
250       {&key_material_buffer, hw_enforced, sw_enforced});
251   auto parent_key_fn = ParentKeyCreator(kUniqueKey);
252   EncryptedSerializable encryption(
253       resource_manager_, parent_key_fn, sensitive_material);
254   auto signing_key_fn = SigningKeyCreator(kUniqueKey);
255   HmacSerializable sign_check(resource_manager_, signing_key_fn,
256                               TPM2_SHA256_DIGEST_SIZE, &encryption, &hidden);
257   auto buf = blob.key_material;
258   auto buf_end = buf + blob.key_material_size;
259   if (!sign_check.Deserialize(&buf, buf_end)) {
260     LOG(ERROR) << "Failed to deserialize key.";
261     return KM_ERROR_INVALID_KEY_BLOB;
262   }
263   if (key_material_buffer.available_read() == 0) {
264     LOG(ERROR) << "Key material was corrupted and the size was too large";
265     return KM_ERROR_INVALID_KEY_BLOB;
266   }
267   *key_material = KeymasterKeyBlob(
268       key_material_buffer.peek_read(), key_material_buffer.available_read());
269   return KM_ERROR_OK;
270 }
271 
SetSystemVersion(uint32_t os_version,uint32_t os_patchlevel)272 keymaster_error_t TpmKeyBlobMaker::SetSystemVersion(
273     uint32_t os_version, uint32_t os_patchlevel) {
274   // TODO(b/201561154): Only accept new values of these from the bootloader
275   os_version_ = os_version;
276   os_patchlevel_ = os_patchlevel;
277   return KM_ERROR_OK;
278 }
279 
SetVendorPatchlevel(uint32_t patchlevel)280 keymaster_error_t TpmKeyBlobMaker::SetVendorPatchlevel(uint32_t patchlevel) {
281   // TODO(b/201561154): Only accept new values of these from the bootloader
282   vendor_patchlevel_ = patchlevel;
283   return KM_ERROR_OK;
284 }
285 
SetBootPatchlevel(uint32_t boot_patchlevel)286 keymaster_error_t TpmKeyBlobMaker::SetBootPatchlevel(uint32_t boot_patchlevel) {
287   // TODO(b/201561154): Only accept new values of these from the bootloader
288   boot_patchlevel_ = boot_patchlevel;
289   return KM_ERROR_OK;
290 }
291 
292 }  // namespace cuttlefish
293