1 /*
2 **
3 ** Copyright 2017, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 #include <keymaster/key_blob_utils/software_keyblobs.h>
19 
20 #include <stdint.h>
21 
22 #include <hardware/keymaster_defs.h>
23 
24 #include <keymaster/android_keymaster_utils.h>
25 #include <keymaster/authorization_set.h>
26 #include <keymaster/key.h>
27 #include <keymaster/key_blob_utils/auth_encrypted_key_blob.h>
28 #include <keymaster/key_blob_utils/integrity_assured_key_blob.h>
29 #include <keymaster/key_blob_utils/ocb_utils.h>
30 #include <keymaster/km_openssl/openssl_utils.h>
31 #include <keymaster/km_openssl/openssl_err.h>
32 #include <keymaster/logger.h>
33 #include <keymaster/UniquePtr.h>
34 
35 #include <openssl/aes.h>
36 
37 namespace keymaster {
38 
39 static uint8_t SWROT[2] = {'S', 'W'};
40 KeymasterBlob softwareRootOfTrust(SWROT);
41 
42 namespace {
43 
UpgradeIntegerTag(keymaster_tag_t tag,uint32_t value,AuthorizationSet * set,bool * set_changed)44 bool UpgradeIntegerTag(keymaster_tag_t tag, uint32_t value, AuthorizationSet* set,
45                               bool* set_changed) {
46     int index = set->find(tag);
47     if (index == -1) {
48         keymaster_key_param_t param;
49         param.tag = tag;
50         param.integer = value;
51         set->push_back(param);
52         *set_changed = true;
53         return true;
54     }
55 
56     if (set->params[index].integer > value)
57         return false;
58 
59     if (set->params[index].integer != value) {
60         set->params[index].integer = value;
61         *set_changed = true;
62     }
63     return true;
64 }
65 
TranslateAuthorizationSetError(AuthorizationSet::Error err)66 keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
67     switch (err) {
68     case AuthorizationSet::OK:
69         return KM_ERROR_OK;
70     case AuthorizationSet::ALLOCATION_FAILURE:
71         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
72     case AuthorizationSet::MALFORMED_DATA:
73         return KM_ERROR_UNKNOWN_ERROR;
74     }
75     return KM_ERROR_OK;
76 }
77 
78 } // anonymous namespace
79 
BuildHiddenAuthorizations(const AuthorizationSet & input_set,AuthorizationSet * hidden,const KeymasterBlob & root_of_trust)80 keymaster_error_t BuildHiddenAuthorizations(const AuthorizationSet& input_set,
81                                             AuthorizationSet* hidden,
82                                             const KeymasterBlob& root_of_trust) {
83     keymaster_blob_t entry;
84     if (input_set.GetTagValue(TAG_APPLICATION_ID, &entry))
85         hidden->push_back(TAG_APPLICATION_ID, entry.data, entry.data_length);
86     if (input_set.GetTagValue(TAG_APPLICATION_DATA, &entry))
87         hidden->push_back(TAG_APPLICATION_DATA, entry.data, entry.data_length);
88 
89     hidden->push_back(TAG_ROOT_OF_TRUST, root_of_trust);
90 
91     return TranslateAuthorizationSetError(hidden->is_valid());
92 }
93 
FakeKeyAuthorizations(EVP_PKEY * pubkey,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)94 keymaster_error_t FakeKeyAuthorizations(EVP_PKEY* pubkey,
95                                         AuthorizationSet* hw_enforced,
96                                         AuthorizationSet* sw_enforced) {
97     hw_enforced->Clear();
98     sw_enforced->Clear();
99 
100     switch (EVP_PKEY_type(pubkey->type)) {
101     case EVP_PKEY_RSA: {
102         hw_enforced->push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
103         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_NONE);
104         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_MD5);
105         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA1);
106         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_224);
107         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
108         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
109         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_512);
110         hw_enforced->push_back(TAG_PADDING, KM_PAD_NONE);
111         hw_enforced->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
112         hw_enforced->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
113         hw_enforced->push_back(TAG_PADDING, KM_PAD_RSA_PSS);
114         hw_enforced->push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
115 
116         sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
117         sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
118         sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_ENCRYPT);
119         sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_DECRYPT);
120 
121         RSA_Ptr rsa(EVP_PKEY_get1_RSA(pubkey));
122         if (!rsa)
123             return TranslateLastOpenSslError();
124         hw_enforced->push_back(TAG_KEY_SIZE, RSA_size(rsa.get()) * 8);
125         uint64_t public_exponent = BN_get_word(rsa->e);
126         if (public_exponent == 0xffffffffL)
127             return KM_ERROR_INVALID_KEY_BLOB;
128         hw_enforced->push_back(TAG_RSA_PUBLIC_EXPONENT, public_exponent);
129         break;
130     }
131 
132     case EVP_PKEY_EC: {
133         hw_enforced->push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
134         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_NONE);
135         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_MD5);
136         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA1);
137         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_224);
138         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
139         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
140         hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_512);
141 
142         sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
143         sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
144 
145         UniquePtr<EC_KEY, EC_KEY_Delete> ec_key(EVP_PKEY_get1_EC_KEY(pubkey));
146         if (!ec_key.get())
147             return TranslateLastOpenSslError();
148         size_t key_size_bits;
149         keymaster_error_t error =
150             ec_get_group_size(EC_KEY_get0_group(ec_key.get()), &key_size_bits);
151         if (error != KM_ERROR_OK)
152             return error;
153         hw_enforced->push_back(TAG_KEY_SIZE, key_size_bits);
154         break;
155     }
156 
157     default:
158         return KM_ERROR_UNSUPPORTED_ALGORITHM;
159     }
160 
161     sw_enforced->push_back(TAG_ALL_USERS);
162     sw_enforced->push_back(TAG_NO_AUTH_REQUIRED);
163 
164     return KM_ERROR_OK;
165 }
166 
167 
168 // Note: This parsing code in below is from system/security/softkeymaster/keymaster_openssl.cpp's
169 // unwrap_key function, modified for the preferred function signature and formatting.  It does some
170 // odd things, but they have been left unchanged to avoid breaking compatibility.
171 static const uint8_t SOFT_KEY_MAGIC[] = {'P', 'K', '#', '8'};
ParseOldSoftkeymasterBlob(const KeymasterKeyBlob & blob,KeymasterKeyBlob * key_material,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)172 keymaster_error_t ParseOldSoftkeymasterBlob(
173     const KeymasterKeyBlob& blob, KeymasterKeyBlob* key_material, AuthorizationSet* hw_enforced,
174     AuthorizationSet* sw_enforced) {
175     long publicLen = 0;
176     long privateLen = 0;
177     const uint8_t* p = blob.key_material;
178     const uint8_t* end = blob.key_material + blob.key_material_size;
179 
180     int type = 0;
181     ptrdiff_t min_size =
182         sizeof(SOFT_KEY_MAGIC) + sizeof(type) + sizeof(publicLen) + 1 + sizeof(privateLen) + 1;
183     if (end - p < min_size) {
184         LOG_W("key blob appears to be truncated (if an old SW key)", 0);
185         return KM_ERROR_INVALID_KEY_BLOB;
186     }
187 
188     if (memcmp(p, SOFT_KEY_MAGIC, sizeof(SOFT_KEY_MAGIC)) != 0)
189         return KM_ERROR_INVALID_KEY_BLOB;
190     p += sizeof(SOFT_KEY_MAGIC);
191 
192     for (size_t i = 0; i < sizeof(type); i++)
193         type = (type << 8) | *p++;
194 
195     for (size_t i = 0; i < sizeof(type); i++)
196         publicLen = (publicLen << 8) | *p++;
197 
198     if (p + publicLen > end) {
199         LOG_W("public key length encoding error: size=%ld, end=%td", publicLen, end - p);
200         return KM_ERROR_INVALID_KEY_BLOB;
201     }
202     p += publicLen;
203 
204     if (end - p < 2) {
205         LOG_W("key blob appears to be truncated (if an old SW key)", 0);
206         return KM_ERROR_INVALID_KEY_BLOB;
207     }
208 
209     for (size_t i = 0; i < sizeof(type); i++)
210         privateLen = (privateLen << 8) | *p++;
211 
212     if (p + privateLen > end) {
213         LOG_W("private key length encoding error: size=%ld, end=%td", privateLen, end - p);
214         return KM_ERROR_INVALID_KEY_BLOB;
215     }
216 
217     // Just to be sure, make sure that the ASN.1 structure parses correctly.  We don't actually use
218     // the EVP_PKEY here.
219     const uint8_t* key_start = p;
220     EVP_PKEY_Ptr pkey(d2i_PrivateKey(type, nullptr, &p, privateLen));
221     if (pkey.get() == nullptr) {
222         LOG_W("Failed to parse PKCS#8 key material (if old SW key)", 0);
223         return KM_ERROR_INVALID_KEY_BLOB;
224     }
225 
226     // All auths go into sw_enforced, including those that would be HW-enforced if we were faking
227     // auths for a HW-backed key.
228     hw_enforced->Clear();
229     keymaster_error_t error = FakeKeyAuthorizations(pkey.get(), sw_enforced, sw_enforced);
230     if (error != KM_ERROR_OK)
231         return error;
232 
233     if (!key_material->Reset(privateLen))
234         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
235     memcpy(key_material->writable_data(), key_start, privateLen);
236 
237     return KM_ERROR_OK;
238 }
239 
240 static uint8_t master_key_bytes[AES_BLOCK_SIZE] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
241 const KeymasterKeyBlob MASTER_KEY(master_key_bytes, array_length(master_key_bytes));
242 
ParseOcbAuthEncryptedBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & hidden,KeymasterKeyBlob * key_material,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)243 keymaster_error_t ParseOcbAuthEncryptedBlob(const KeymasterKeyBlob& blob,
244                                             const AuthorizationSet& hidden,
245                                             KeymasterKeyBlob* key_material,
246                                             AuthorizationSet* hw_enforced,
247                                             AuthorizationSet* sw_enforced) {
248     Buffer nonce, tag;
249     KeymasterKeyBlob encrypted_key_material;
250     keymaster_error_t error = DeserializeAuthEncryptedBlob(blob, &encrypted_key_material,
251                                                            hw_enforced, sw_enforced, &nonce, &tag);
252     if (error != KM_ERROR_OK)
253         return error;
254 
255     if (nonce.available_read() != OCB_NONCE_LENGTH || tag.available_read() != OCB_TAG_LENGTH)
256         return KM_ERROR_INVALID_KEY_BLOB;
257 
258     return OcbDecryptKey(*hw_enforced, *sw_enforced, hidden, MASTER_KEY, encrypted_key_material,
259                          nonce, tag, key_material);
260 }
261 
SetKeyBlobAuthorizations(const AuthorizationSet & key_description,keymaster_key_origin_t origin,uint32_t os_version,uint32_t os_patchlevel,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)262 keymaster_error_t SetKeyBlobAuthorizations(const AuthorizationSet& key_description,
263                                            keymaster_key_origin_t origin, uint32_t os_version,
264                                            uint32_t os_patchlevel, AuthorizationSet* hw_enforced,
265                                            AuthorizationSet* sw_enforced) {
266     sw_enforced->Clear();
267 
268     for (auto& entry : key_description) {
269         switch (entry.tag) {
270         // These cannot be specified by the client.
271         case KM_TAG_ROOT_OF_TRUST:
272         case KM_TAG_ORIGIN:
273             LOG_E("Root of trust and origin tags may not be specified", 0);
274             return KM_ERROR_INVALID_TAG;
275 
276         // These don't work.
277         case KM_TAG_ROLLBACK_RESISTANT:
278             LOG_E("KM_TAG_ROLLBACK_RESISTANT not supported", 0);
279             return KM_ERROR_UNSUPPORTED_TAG;
280 
281         // These are hidden.
282         case KM_TAG_APPLICATION_ID:
283         case KM_TAG_APPLICATION_DATA:
284             break;
285 
286         // Everything else we just copy into sw_enforced, unless the KeyFactory has placed it in
287         // hw_enforced, in which case we defer to its decision.
288         default:
289             if (hw_enforced->GetTagCount(entry.tag) == 0)
290                 sw_enforced->push_back(entry);
291             break;
292         }
293     }
294 
295     // If hw_enforced is non-empty, we're pretending to be some sort of secure hardware.
296     AuthorizationSet* pseudo_hw_enforced = (hw_enforced->empty()) ? sw_enforced : hw_enforced;
297     pseudo_hw_enforced->push_back(TAG_ORIGIN, origin);
298     pseudo_hw_enforced->push_back(TAG_OS_VERSION, os_version);
299     pseudo_hw_enforced->push_back(TAG_OS_PATCHLEVEL, os_patchlevel);
300 
301     // Honor caller creation, if provided.
302     if (!sw_enforced->Contains(TAG_CREATION_DATETIME)) {
303         sw_enforced->push_back(TAG_CREATION_DATETIME, java_time(time(nullptr)));
304     }
305 
306     return TranslateAuthorizationSetError(sw_enforced->is_valid());
307 }
308 
309 
UpgradeSoftKeyBlob(const UniquePtr<Key> & key,const uint32_t os_version,const uint32_t os_patchlevel,const AuthorizationSet & upgrade_params,KeymasterKeyBlob * upgraded_key)310 keymaster_error_t UpgradeSoftKeyBlob(const UniquePtr<Key>& key,
311                                  const uint32_t os_version, const uint32_t os_patchlevel,
312                                  const AuthorizationSet& upgrade_params,
313                                  KeymasterKeyBlob* upgraded_key) {
314     bool set_changed = false;
315 
316     if (os_version == 0) {
317         // We need to allow "upgrading" OS version to zero, to support upgrading from proper
318         // numbered releases to unnumbered development and preview releases.
319 
320         int key_os_version_pos = key->sw_enforced().find(TAG_OS_VERSION);
321         if (key_os_version_pos != -1) {
322             uint32_t key_os_version = key->sw_enforced()[key_os_version_pos].integer;
323             if (key_os_version != 0) {
324                 key->sw_enforced()[key_os_version_pos].integer = os_version;
325                 set_changed = true;
326             }
327         }
328     }
329 
330     if (!UpgradeIntegerTag(TAG_OS_VERSION, os_version, &key->sw_enforced(), &set_changed) ||
331         !UpgradeIntegerTag(TAG_OS_PATCHLEVEL, os_patchlevel, &key->sw_enforced(), &set_changed))
332         // One of the version fields would have been a downgrade. Not allowed.
333         return KM_ERROR_INVALID_ARGUMENT;
334 
335     if (!set_changed)
336         // Dont' need an upgrade.
337         return KM_ERROR_OK;
338 
339     AuthorizationSet hidden;
340     auto error = BuildHiddenAuthorizations(upgrade_params, &hidden, softwareRootOfTrust);
341     if (error != KM_ERROR_OK)
342         return error;
343     return SerializeIntegrityAssuredBlob(key->key_material(), hidden, key->hw_enforced(),
344                                          key->sw_enforced(), upgraded_key);
345 }
346 
347 } // namespace keymaster
348