1 /*
2 * Copyright 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 #include <keymaster/soft_keymaster_context.h>
18
19 #include <memory>
20 #include <time.h>
21
22 #include <openssl/aes.h>
23 #include <openssl/rand.h>
24 #include <openssl/sha.h>
25
26 #include <keymaster/android_keymaster_utils.h>
27 #include <keymaster/logger.h>
28
29 #include "aes_key.h"
30 #include "auth_encrypted_key_blob.h"
31 #include "ec_keymaster0_key.h"
32 #include "hmac_key.h"
33 #include "integrity_assured_key_blob.h"
34 #include "keymaster0_engine.h"
35 #include "ocb_utils.h"
36 #include "openssl_err.h"
37 #include "rsa_keymaster0_key.h"
38
39 using std::unique_ptr;
40
41 namespace keymaster {
42
43 namespace {
44 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};
45 const int NONCE_LENGTH = 12;
46 const int TAG_LENGTH = 16;
47 const KeymasterKeyBlob MASTER_KEY(master_key_bytes, array_length(master_key_bytes));
48 } // anonymous namespace
49
SoftKeymasterContext(keymaster0_device_t * keymaster0_device)50 SoftKeymasterContext::SoftKeymasterContext(keymaster0_device_t* keymaster0_device) {
51 if (keymaster0_device && (keymaster0_device->flags & KEYMASTER_SOFTWARE_ONLY) == 0)
52 engine_.reset(new Keymaster0Engine(keymaster0_device));
53 rsa_factory_.reset(new RsaKeymaster0KeyFactory(this, engine_.get()));
54 ec_factory_.reset(new EcdsaKeymaster0KeyFactory(this, engine_.get()));
55 aes_factory_.reset(new AesKeyFactory(this));
56 hmac_factory_.reset(new HmacKeyFactory(this));
57 }
58
GetKeyFactory(keymaster_algorithm_t algorithm) const59 KeyFactory* SoftKeymasterContext::GetKeyFactory(keymaster_algorithm_t algorithm) const {
60 switch (algorithm) {
61 case KM_ALGORITHM_RSA:
62 return rsa_factory_.get();
63 case KM_ALGORITHM_EC:
64 return ec_factory_.get();
65 case KM_ALGORITHM_AES:
66 return aes_factory_.get();
67 case KM_ALGORITHM_HMAC:
68 return hmac_factory_.get();
69 default:
70 return nullptr;
71 }
72 }
73
74 static keymaster_algorithm_t supported_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC,
75 KM_ALGORITHM_AES, KM_ALGORITHM_HMAC};
76
77 keymaster_algorithm_t*
GetSupportedAlgorithms(size_t * algorithms_count) const78 SoftKeymasterContext::GetSupportedAlgorithms(size_t* algorithms_count) const {
79 *algorithms_count = array_length(supported_algorithms);
80 return supported_algorithms;
81 }
82
GetOperationFactory(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose) const83 OperationFactory* SoftKeymasterContext::GetOperationFactory(keymaster_algorithm_t algorithm,
84 keymaster_purpose_t purpose) const {
85 KeyFactory* key_factory = GetKeyFactory(algorithm);
86 if (!key_factory)
87 return nullptr;
88 return key_factory->GetOperationFactory(purpose);
89 }
90
TranslateAuthorizationSetError(AuthorizationSet::Error err)91 static keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
92 switch (err) {
93 case AuthorizationSet::OK:
94 return KM_ERROR_OK;
95 case AuthorizationSet::ALLOCATION_FAILURE:
96 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
97 case AuthorizationSet::MALFORMED_DATA:
98 return KM_ERROR_UNKNOWN_ERROR;
99 }
100 return KM_ERROR_OK;
101 }
102
BuildHiddenAuthorizations(const AuthorizationSet & input_set,AuthorizationSet * hidden)103 static keymaster_error_t BuildHiddenAuthorizations(const AuthorizationSet& input_set,
104 AuthorizationSet* hidden) {
105 keymaster_blob_t entry;
106 if (input_set.GetTagValue(TAG_APPLICATION_ID, &entry))
107 hidden->push_back(TAG_APPLICATION_ID, entry.data, entry.data_length);
108 if (input_set.GetTagValue(TAG_APPLICATION_DATA, &entry))
109 hidden->push_back(TAG_APPLICATION_DATA, entry.data, entry.data_length);
110
111 keymaster_key_param_t root_of_trust;
112 root_of_trust.tag = KM_TAG_ROOT_OF_TRUST;
113 root_of_trust.blob.data = reinterpret_cast<const uint8_t*>("SW");
114 root_of_trust.blob.data_length = 2;
115 hidden->push_back(root_of_trust);
116
117 return TranslateAuthorizationSetError(hidden->is_valid());
118 }
119
SetAuthorizations(const AuthorizationSet & key_description,keymaster_key_origin_t origin,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)120 static keymaster_error_t SetAuthorizations(const AuthorizationSet& key_description,
121 keymaster_key_origin_t origin,
122 AuthorizationSet* hw_enforced,
123 AuthorizationSet* sw_enforced) {
124 sw_enforced->Clear();
125
126 for (auto& entry : key_description) {
127 switch (entry.tag) {
128 // These cannot be specified by the client.
129 case KM_TAG_ROOT_OF_TRUST:
130 case KM_TAG_ORIGIN:
131 LOG_E("Root of trust and origin tags may not be specified", 0);
132 return KM_ERROR_INVALID_TAG;
133
134 // These don't work.
135 case KM_TAG_ROLLBACK_RESISTANT:
136 LOG_E("KM_TAG_ROLLBACK_RESISTANT not supported", 0);
137 return KM_ERROR_UNSUPPORTED_TAG;
138
139 // These are hidden.
140 case KM_TAG_APPLICATION_ID:
141 case KM_TAG_APPLICATION_DATA:
142 break;
143
144 // Everything else we just copy into sw_enforced, unless the KeyFactory has placed it in
145 // hw_enforced, in which case we defer to its decision.
146 default:
147 if (hw_enforced->GetTagCount(entry.tag) == 0)
148 sw_enforced->push_back(entry);
149 break;
150 }
151 }
152
153 sw_enforced->push_back(TAG_CREATION_DATETIME, java_time(time(NULL)));
154 sw_enforced->push_back(TAG_ORIGIN, origin);
155 return TranslateAuthorizationSetError(sw_enforced->is_valid());
156 }
157
CreateKeyBlob(const AuthorizationSet & key_description,const keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const158 keymaster_error_t SoftKeymasterContext::CreateKeyBlob(const AuthorizationSet& key_description,
159 const keymaster_key_origin_t origin,
160 const KeymasterKeyBlob& key_material,
161 KeymasterKeyBlob* blob,
162 AuthorizationSet* hw_enforced,
163 AuthorizationSet* sw_enforced) const {
164 keymaster_error_t error = SetAuthorizations(key_description, origin, hw_enforced, sw_enforced);
165 if (error != KM_ERROR_OK)
166 return error;
167
168 AuthorizationSet hidden;
169 error = BuildHiddenAuthorizations(key_description, &hidden);
170 if (error != KM_ERROR_OK)
171 return error;
172
173 return SerializeIntegrityAssuredBlob(key_material, hidden, *hw_enforced, *sw_enforced, blob);
174 }
175
ParseOcbAuthEncryptedBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & hidden,KeymasterKeyBlob * key_material,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced)176 static keymaster_error_t ParseOcbAuthEncryptedBlob(const KeymasterKeyBlob& blob,
177 const AuthorizationSet& hidden,
178 KeymasterKeyBlob* key_material,
179 AuthorizationSet* hw_enforced,
180 AuthorizationSet* sw_enforced) {
181 Buffer nonce, tag;
182 KeymasterKeyBlob encrypted_key_material;
183 keymaster_error_t error = DeserializeAuthEncryptedBlob(blob, &encrypted_key_material,
184 hw_enforced, sw_enforced, &nonce, &tag);
185 if (error != KM_ERROR_OK)
186 return error;
187
188 if (nonce.available_read() != OCB_NONCE_LENGTH || tag.available_read() != OCB_TAG_LENGTH)
189 return KM_ERROR_INVALID_KEY_BLOB;
190
191 return OcbDecryptKey(*hw_enforced, *sw_enforced, hidden, MASTER_KEY, encrypted_key_material,
192 nonce, tag, key_material);
193 }
194
195 // Note: This parsing code in below is from system/security/softkeymaster/keymaster_openssl.cpp's
196 // unwrap_key function, modified for the preferred function signature and formatting. It does some
197 // odd things, but they have been left unchanged to avoid breaking compatibility.
198 static const uint8_t SOFT_KEY_MAGIC[] = {'P', 'K', '#', '8'};
199 const uint64_t HUNDRED_YEARS = 1000LL * 60 * 60 * 24 * 365 * 100;
ParseOldSoftkeymasterBlob(const KeymasterKeyBlob & blob,KeymasterKeyBlob * key_material,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const200 keymaster_error_t SoftKeymasterContext::ParseOldSoftkeymasterBlob(
201 const KeymasterKeyBlob& blob, KeymasterKeyBlob* key_material, AuthorizationSet* hw_enforced,
202 AuthorizationSet* sw_enforced) const {
203 long publicLen = 0;
204 long privateLen = 0;
205 const uint8_t* p = blob.key_material;
206 const uint8_t* end = blob.key_material + blob.key_material_size;
207
208 int type = 0;
209 ptrdiff_t min_size =
210 sizeof(SOFT_KEY_MAGIC) + sizeof(type) + sizeof(publicLen) + 1 + sizeof(privateLen) + 1;
211 if (end - p < min_size) {
212 LOG_W("key blob appears to be truncated (if an old SW key)", 0);
213 return KM_ERROR_INVALID_KEY_BLOB;
214 }
215
216 if (memcmp(p, SOFT_KEY_MAGIC, sizeof(SOFT_KEY_MAGIC)) != 0)
217 return KM_ERROR_INVALID_KEY_BLOB;
218 p += sizeof(SOFT_KEY_MAGIC);
219
220 for (size_t i = 0; i < sizeof(type); i++)
221 type = (type << 8) | *p++;
222
223 for (size_t i = 0; i < sizeof(type); i++)
224 publicLen = (publicLen << 8) | *p++;
225
226 if (p + publicLen > end) {
227 LOG_W("public key length encoding error: size=%ld, end=%td", publicLen, end - p);
228 return KM_ERROR_INVALID_KEY_BLOB;
229 }
230 p += publicLen;
231
232 if (end - p < 2) {
233 LOG_W("key blob appears to be truncated (if an old SW key)", 0);
234 return KM_ERROR_INVALID_KEY_BLOB;
235 }
236
237 for (size_t i = 0; i < sizeof(type); i++)
238 privateLen = (privateLen << 8) | *p++;
239
240 if (p + privateLen > end) {
241 LOG_W("private key length encoding error: size=%ld, end=%td", privateLen, end - p);
242 return KM_ERROR_INVALID_KEY_BLOB;
243 }
244
245 // Just to be sure, make sure that the ASN.1 structure parses correctly. We don't actually use
246 // the EVP_PKEY here.
247 unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKEY_new());
248 if (pkey.get() == nullptr)
249 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
250
251 EVP_PKEY* tmp = pkey.get();
252 const uint8_t* key_start = p;
253 if (d2i_PrivateKey(type, &tmp, &p, privateLen) == NULL) {
254 LOG_W("Failed to parse PKCS#8 key material (if old SW key)", 0);
255 return KM_ERROR_INVALID_KEY_BLOB;
256 }
257
258 // All auths go into sw_enforced, including those that would be HW-enforced if we were faking
259 // auths for a HW-backed key.
260 hw_enforced->Clear();
261 keymaster_error_t error = FakeKeyAuthorizations(pkey.get(), sw_enforced, sw_enforced);
262 if (error != KM_ERROR_OK)
263 return error;
264
265 if (!key_material->Reset(privateLen))
266 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
267 memcpy(key_material->writable_data(), key_start, privateLen);
268
269 return KM_ERROR_OK;
270 }
271
ParseKeyBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,KeymasterKeyBlob * key_material,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const272 keymaster_error_t SoftKeymasterContext::ParseKeyBlob(const KeymasterKeyBlob& blob,
273 const AuthorizationSet& additional_params,
274 KeymasterKeyBlob* key_material,
275 AuthorizationSet* hw_enforced,
276 AuthorizationSet* sw_enforced) const {
277 // This is a little bit complicated.
278 //
279 // The SoftKeymasterContext has to handle a lot of different kinds of key blobs.
280 //
281 // 1. New keymaster1 software key blobs. These are integrity-assured but not encrypted. The
282 // raw key material and auth sets should be extracted and returned. This is the kind
283 // produced by this context when the KeyFactory doesn't use keymaster0 to back the keys.
284 //
285 // 2. Old keymaster1 software key blobs. These are OCB-encrypted with an all-zero master key.
286 // They should be decrypted and the key material and auth sets extracted and returned.
287 //
288 // 3. Old keymaster0 software key blobs. These are raw key material with a small header tacked
289 // on the front. They don't have auth sets, so reasonable defaults are generated and
290 // returned along with the raw key material.
291 //
292 // 4. New keymaster0 hardware key blobs. These are integrity-assured but not encrypted (though
293 // they're protected by the keymaster0 hardware implementation). The keymaster0 key blob
294 // and auth sets should be extracted and returned.
295 //
296 // 5. Old keymaster0 hardware key blobs. These are raw hardware key blobs. They don't have
297 // auth sets so reasonable defaults are generated and returned along with the key blob.
298 //
299 // Determining what kind of blob has arrived is somewhat tricky. What helps is that
300 // integrity-assured and OCB-encrypted blobs are self-consistent and effectively impossible to
301 // parse as anything else. Old keymaster0 software key blobs have a header. It's reasonably
302 // unlikely that hardware keys would have the same header. So anything that is neither
303 // integrity-assured nor OCB-encrypted and lacks the old software key header is assumed to be
304 // keymaster0 hardware.
305
306 AuthorizationSet hidden;
307 keymaster_error_t error = BuildHiddenAuthorizations(additional_params, &hidden);
308 if (error != KM_ERROR_OK)
309 return error;
310
311 // Assume it's an integrity-assured blob (new software-only blob, or new keymaster0-backed
312 // blob).
313 error = DeserializeIntegrityAssuredBlob(blob, hidden, key_material, hw_enforced, sw_enforced);
314 if (error != KM_ERROR_INVALID_KEY_BLOB)
315 return error;
316
317 // Wasn't an integrity-assured blob. Maybe it's an OCB-encrypted blob.
318 error = ParseOcbAuthEncryptedBlob(blob, hidden, key_material, hw_enforced, sw_enforced);
319 if (error == KM_ERROR_OK)
320 LOG_D("Parsed an old keymaster1 software key", 0);
321 if (error != KM_ERROR_INVALID_KEY_BLOB)
322 return error;
323
324 // Wasn't an OCB-encrypted blob. Maybe it's an old softkeymaster blob.
325 error = ParseOldSoftkeymasterBlob(blob, key_material, hw_enforced, sw_enforced);
326 if (error == KM_ERROR_OK)
327 LOG_D("Parsed an old sofkeymaster key", 0);
328 if (error != KM_ERROR_INVALID_KEY_BLOB)
329 return error;
330
331 // Not an old softkeymaster blob, either. The only remaining option is old HW keymaster0.
332 if (!engine_)
333 return KM_ERROR_INVALID_KEY_BLOB;
334
335 // See if the HW thinks it's valid.
336 unique_ptr<EVP_PKEY, EVP_PKEY_Delete> tmp_key(engine_->GetKeymaster0PublicKey(blob));
337 if (!tmp_key)
338 return KM_ERROR_INVALID_KEY_BLOB;
339 else
340 error = FakeKeyAuthorizations(tmp_key.get(), hw_enforced, sw_enforced);
341
342 if (error == KM_ERROR_OK)
343 *key_material = blob;
344
345 return error;
346 }
347
FakeKeyAuthorizations(EVP_PKEY * pubkey,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const348 keymaster_error_t SoftKeymasterContext::FakeKeyAuthorizations(EVP_PKEY* pubkey,
349 AuthorizationSet* hw_enforced,
350 AuthorizationSet* sw_enforced) const {
351 hw_enforced->Clear();
352 sw_enforced->Clear();
353
354 switch (EVP_PKEY_type(pubkey->type)) {
355 case EVP_PKEY_RSA: {
356 hw_enforced->push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
357 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_NONE);
358 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_MD5);
359 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA1);
360 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_224);
361 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
362 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
363 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_512);
364 hw_enforced->push_back(TAG_PADDING, KM_PAD_NONE);
365 hw_enforced->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
366 hw_enforced->push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
367 hw_enforced->push_back(TAG_PADDING, KM_PAD_RSA_PSS);
368 hw_enforced->push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
369
370 sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
371 sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
372 sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_ENCRYPT);
373 sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_DECRYPT);
374
375 unique_ptr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(pubkey));
376 if (!rsa)
377 return TranslateLastOpenSslError();
378 hw_enforced->push_back(TAG_KEY_SIZE, RSA_size(rsa.get()) * 8);
379 uint64_t public_exponent = BN_get_word(rsa->e);
380 if (public_exponent == 0xffffffffL)
381 return KM_ERROR_INVALID_KEY_BLOB;
382 hw_enforced->push_back(TAG_RSA_PUBLIC_EXPONENT, public_exponent);
383 break;
384 }
385
386 case EVP_PKEY_EC: {
387 hw_enforced->push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
388 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_NONE);
389 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_MD5);
390 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA1);
391 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_224);
392 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
393 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
394 hw_enforced->push_back(TAG_DIGEST, KM_DIGEST_SHA_2_512);
395
396 sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
397 sw_enforced->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
398
399 UniquePtr<EC_KEY, EC_Delete> ec_key(EVP_PKEY_get1_EC_KEY(pubkey));
400 if (!ec_key.get())
401 return TranslateLastOpenSslError();
402 size_t key_size_bits;
403 keymaster_error_t error =
404 EcKeyFactory::get_group_size(*EC_KEY_get0_group(ec_key.get()), &key_size_bits);
405 if (error != KM_ERROR_OK)
406 return error;
407 hw_enforced->push_back(TAG_KEY_SIZE, key_size_bits);
408 break;
409 }
410
411 default:
412 return KM_ERROR_UNSUPPORTED_ALGORITHM;
413 }
414
415 sw_enforced->push_back(TAG_ALL_USERS);
416 sw_enforced->push_back(TAG_NO_AUTH_REQUIRED);
417
418 return KM_ERROR_OK;
419 }
420
AddRngEntropy(const uint8_t * buf,size_t length) const421 keymaster_error_t SoftKeymasterContext::AddRngEntropy(const uint8_t* buf, size_t length) const {
422 RAND_add(buf, length, 0 /* Don't assume any entropy is added to the pool. */);
423 return KM_ERROR_OK;
424 }
425
GenerateRandom(uint8_t * buf,size_t length) const426 keymaster_error_t SoftKeymasterContext::GenerateRandom(uint8_t* buf, size_t length) const {
427 if (RAND_bytes(buf, length) != 1)
428 return KM_ERROR_UNKNOWN_ERROR;
429 return KM_ERROR_OK;
430 }
431
432 } // namespace keymaster
433