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/contexts/pure_soft_keymaster_context.h>
18
19 #include <memory>
20
21 #include <openssl/aes.h>
22 #include <openssl/evp.h>
23 #include <openssl/hmac.h>
24 #include <openssl/rand.h>
25 #include <openssl/sha.h>
26 #include <openssl/x509v3.h>
27
28 #include <keymaster/android_keymaster_utils.h>
29 #include <keymaster/key_blob_utils/auth_encrypted_key_blob.h>
30 #include <keymaster/key_blob_utils/integrity_assured_key_blob.h>
31 #include <keymaster/key_blob_utils/ocb_utils.h>
32 #include <keymaster/key_blob_utils/software_keyblobs.h>
33 #include <keymaster/km_openssl/aes_key.h>
34 #include <keymaster/km_openssl/asymmetric_key.h>
35 #include <keymaster/km_openssl/attestation_utils.h>
36 #include <keymaster/km_openssl/ec_key_factory.h>
37 #include <keymaster/km_openssl/hmac_key.h>
38 #include <keymaster/km_openssl/openssl_err.h>
39 #include <keymaster/km_openssl/openssl_utils.h>
40 #include <keymaster/km_openssl/rsa_key_factory.h>
41 #include <keymaster/km_openssl/soft_keymaster_enforcement.h>
42 #include <keymaster/km_openssl/triple_des_key.h>
43 #include <keymaster/logger.h>
44 #include <keymaster/operation.h>
45 #include <keymaster/wrapped_key.h>
46
47 #include "soft_attestation_cert.h"
48
49 using std::unique_ptr;
50
51 namespace keymaster {
52
PureSoftKeymasterContext()53 PureSoftKeymasterContext::PureSoftKeymasterContext()
54 : rsa_factory_(new RsaKeyFactory(this)), ec_factory_(new EcKeyFactory(this)),
55 aes_factory_(new AesKeyFactory(this, this)),
56 tdes_factory_(new TripleDesKeyFactory(this, this)),
57 hmac_factory_(new HmacKeyFactory(this, this)), os_version_(0), os_patchlevel_(0),
58 soft_keymaster_enforcement_(64, 64) {}
59
~PureSoftKeymasterContext()60 PureSoftKeymasterContext::~PureSoftKeymasterContext() {}
61
SetSystemVersion(uint32_t os_version,uint32_t os_patchlevel)62 keymaster_error_t PureSoftKeymasterContext::SetSystemVersion(uint32_t os_version,
63 uint32_t os_patchlevel) {
64 os_version_ = os_version;
65 os_patchlevel_ = os_patchlevel;
66 return KM_ERROR_OK;
67 }
68
GetSystemVersion(uint32_t * os_version,uint32_t * os_patchlevel) const69 void PureSoftKeymasterContext::GetSystemVersion(uint32_t* os_version, uint32_t* os_patchlevel) const {
70 *os_version = os_version_;
71 *os_patchlevel = os_patchlevel_;
72 }
73
GetKeyFactory(keymaster_algorithm_t algorithm) const74 KeyFactory* PureSoftKeymasterContext::GetKeyFactory(keymaster_algorithm_t algorithm) const {
75 switch (algorithm) {
76 case KM_ALGORITHM_RSA:
77 return rsa_factory_.get();
78 case KM_ALGORITHM_EC:
79 return ec_factory_.get();
80 case KM_ALGORITHM_AES:
81 return aes_factory_.get();
82 case KM_ALGORITHM_TRIPLE_DES:
83 return tdes_factory_.get();
84 case KM_ALGORITHM_HMAC:
85 return hmac_factory_.get();
86 default:
87 return nullptr;
88 }
89 }
90
91 static keymaster_algorithm_t supported_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC,
92 KM_ALGORITHM_AES, KM_ALGORITHM_HMAC};
93
94 keymaster_algorithm_t*
GetSupportedAlgorithms(size_t * algorithms_count) const95 PureSoftKeymasterContext::GetSupportedAlgorithms(size_t* algorithms_count) const {
96 *algorithms_count = array_length(supported_algorithms);
97 return supported_algorithms;
98 }
99
GetOperationFactory(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose) const100 OperationFactory* PureSoftKeymasterContext::GetOperationFactory(keymaster_algorithm_t algorithm,
101 keymaster_purpose_t purpose) const {
102 KeyFactory* key_factory = GetKeyFactory(algorithm);
103 if (!key_factory)
104 return nullptr;
105 return key_factory->GetOperationFactory(purpose);
106 }
107
CreateKeyBlob(const AuthorizationSet & key_description,const keymaster_key_origin_t origin,const KeymasterKeyBlob & key_material,KeymasterKeyBlob * blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const108 keymaster_error_t PureSoftKeymasterContext::CreateKeyBlob(const AuthorizationSet& key_description,
109 const keymaster_key_origin_t origin,
110 const KeymasterKeyBlob& key_material,
111 KeymasterKeyBlob* blob,
112 AuthorizationSet* hw_enforced,
113 AuthorizationSet* sw_enforced) const {
114 keymaster_error_t error = SetKeyBlobAuthorizations(key_description, origin, os_version_,
115 os_patchlevel_, hw_enforced, sw_enforced);
116 if (error != KM_ERROR_OK)
117 return error;
118
119 AuthorizationSet hidden;
120 error = BuildHiddenAuthorizations(key_description, &hidden, softwareRootOfTrust);
121 if (error != KM_ERROR_OK)
122 return error;
123
124 return SerializeIntegrityAssuredBlob(key_material, hidden, *hw_enforced, *sw_enforced, blob);
125 }
126
UpgradeKeyBlob(const KeymasterKeyBlob & key_to_upgrade,const AuthorizationSet & upgrade_params,KeymasterKeyBlob * upgraded_key) const127 keymaster_error_t PureSoftKeymasterContext::UpgradeKeyBlob(const KeymasterKeyBlob& key_to_upgrade,
128 const AuthorizationSet& upgrade_params,
129 KeymasterKeyBlob* upgraded_key) const {
130 UniquePtr<Key> key;
131 keymaster_error_t error = ParseKeyBlob(key_to_upgrade, upgrade_params, &key);
132 if (error != KM_ERROR_OK)
133 return error;
134
135 return UpgradeSoftKeyBlob(key, os_version_, os_patchlevel_, upgrade_params, upgraded_key);
136 }
137
ParseKeyBlob(const KeymasterKeyBlob & blob,const AuthorizationSet & additional_params,UniquePtr<Key> * key) const138 keymaster_error_t PureSoftKeymasterContext::ParseKeyBlob(const KeymasterKeyBlob& blob,
139 const AuthorizationSet& additional_params,
140 UniquePtr<Key>* key) const {
141 // This is a little bit complicated.
142 //
143 // The SoftKeymasterContext has to handle a lot of different kinds of key blobs.
144 //
145 // 1. New keymaster1 software key blobs. These are integrity-assured but not encrypted. The
146 // raw key material and auth sets should be extracted and returned. This is the kind
147 // produced by this context when the KeyFactory doesn't use keymaster0 to back the keys.
148 //
149 // 2. Old keymaster1 software key blobs. These are OCB-encrypted with an all-zero master key.
150 // They should be decrypted and the key material and auth sets extracted and returned.
151 //
152 // 3. Old keymaster0 software key blobs. These are raw key material with a small header tacked
153 // on the front. They don't have auth sets, so reasonable defaults are generated and
154 // returned along with the raw key material.
155 //
156 // Determining what kind of blob has arrived is somewhat tricky. What helps is that
157 // integrity-assured and OCB-encrypted blobs are self-consistent and effectively impossible to
158 // parse as anything else. Old keymaster0 software key blobs have a header. It's reasonably
159 // unlikely that hardware keys would have the same header. So anything that is neither
160 // integrity-assured nor OCB-encrypted and lacks the old software key header is assumed to be
161 // keymaster0 hardware.
162
163 AuthorizationSet hw_enforced;
164 AuthorizationSet sw_enforced;
165 KeymasterKeyBlob key_material;
166 keymaster_error_t error;
167
168 auto constructKey = [&, this] () mutable -> keymaster_error_t {
169 // GetKeyFactory
170 if (error != KM_ERROR_OK) return error;
171 keymaster_algorithm_t algorithm;
172 if (!hw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm) &&
173 !sw_enforced.GetTagValue(TAG_ALGORITHM, &algorithm)) {
174 return KM_ERROR_INVALID_ARGUMENT;
175 }
176 auto factory = GetKeyFactory(algorithm);
177 return factory->LoadKey(move(key_material), additional_params, move(hw_enforced),
178 move(sw_enforced), key);
179 };
180
181 AuthorizationSet hidden;
182 error = BuildHiddenAuthorizations(additional_params, &hidden, softwareRootOfTrust);
183 if (error != KM_ERROR_OK)
184 return error;
185
186 // Assume it's an integrity-assured blob (new software-only blob, or new keymaster0-backed
187 // blob).
188 error = DeserializeIntegrityAssuredBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
189 if (error != KM_ERROR_INVALID_KEY_BLOB)
190 return constructKey();
191
192 // Wasn't an integrity-assured blob. Maybe it's an OCB-encrypted blob.
193 error = ParseOcbAuthEncryptedBlob(blob, hidden, &key_material, &hw_enforced, &sw_enforced);
194 if (error == KM_ERROR_OK)
195 LOG_D("Parsed an old keymaster1 software key", 0);
196 if (error != KM_ERROR_INVALID_KEY_BLOB)
197 return constructKey();
198
199 // Wasn't an OCB-encrypted blob. Maybe it's an old softkeymaster blob.
200 error = ParseOldSoftkeymasterBlob(blob, &key_material, &hw_enforced, &sw_enforced);
201 if (error == KM_ERROR_OK)
202 LOG_D("Parsed an old sofkeymaster key", 0);
203
204 return constructKey();
205 }
206
DeleteKey(const KeymasterKeyBlob &) const207 keymaster_error_t PureSoftKeymasterContext::DeleteKey(const KeymasterKeyBlob& /* blob */) const {
208 // Nothing to do for software-only contexts.
209 return KM_ERROR_OK;
210 }
211
DeleteAllKeys() const212 keymaster_error_t PureSoftKeymasterContext::DeleteAllKeys() const {
213 return KM_ERROR_OK;
214 }
215
AddRngEntropy(const uint8_t * buf,size_t length) const216 keymaster_error_t PureSoftKeymasterContext::AddRngEntropy(const uint8_t* buf, size_t length) const {
217 // XXX TODO according to boringssl openssl/rand.h RAND_add is deprecated and does
218 // nothing
219 RAND_add(buf, length, 0 /* Don't assume any entropy is added to the pool. */);
220 return KM_ERROR_OK;
221 }
222
GenerateAttestation(const Key & key,const AuthorizationSet & attest_params,CertChainPtr * cert_chain) const223 keymaster_error_t PureSoftKeymasterContext::GenerateAttestation(const Key& key,
224 const AuthorizationSet& attest_params,
225 CertChainPtr* cert_chain) const {
226
227 keymaster_error_t error = KM_ERROR_OK;
228 keymaster_algorithm_t key_algorithm;
229 if (!key.authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) {
230 return KM_ERROR_UNKNOWN_ERROR;
231 }
232
233 if ((key_algorithm != KM_ALGORITHM_RSA && key_algorithm != KM_ALGORITHM_EC))
234 return KM_ERROR_INCOMPATIBLE_ALGORITHM;
235
236 // We have established that the given key has the correct algorithm, and because this is the
237 // SoftKeymasterContext we can assume that the Key is an AsymmetricKey. So we can downcast.
238 const AsymmetricKey& asymmetric_key = static_cast<const AsymmetricKey&>(key);
239
240 auto attestation_chain = getAttestationChain(key_algorithm, &error);
241 if (error != KM_ERROR_OK) return error;
242
243 auto attestation_key = getAttestationKey(key_algorithm, &error);
244 if (error != KM_ERROR_OK) return error;
245
246 return generate_attestation(asymmetric_key, attest_params,
247 *attestation_chain, *attestation_key, *this, cert_chain);
248 }
249
TranslateAuthorizationSetError(AuthorizationSet::Error err)250 static keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
251 switch (err) {
252 case AuthorizationSet::OK:
253 return KM_ERROR_OK;
254 case AuthorizationSet::ALLOCATION_FAILURE:
255 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
256 case AuthorizationSet::MALFORMED_DATA:
257 return KM_ERROR_UNKNOWN_ERROR;
258 }
259 return KM_ERROR_OK;
260 }
261
UnwrapKey(const KeymasterKeyBlob & wrapped_key_blob,const KeymasterKeyBlob & wrapping_key_blob,const AuthorizationSet &,const KeymasterKeyBlob & masking_key,AuthorizationSet * wrapped_key_params,keymaster_key_format_t * wrapped_key_format,KeymasterKeyBlob * wrapped_key_material) const262 keymaster_error_t PureSoftKeymasterContext::UnwrapKey(
263 const KeymasterKeyBlob& wrapped_key_blob, const KeymasterKeyBlob& wrapping_key_blob,
264 const AuthorizationSet& /* wrapping_key_params */, const KeymasterKeyBlob& masking_key,
265 AuthorizationSet* wrapped_key_params, keymaster_key_format_t* wrapped_key_format,
266 KeymasterKeyBlob* wrapped_key_material) const {
267 keymaster_error_t error = KM_ERROR_OK;
268
269 if (!wrapped_key_material) return KM_ERROR_UNEXPECTED_NULL_POINTER;
270
271 // Parse wrapped key data
272 KeymasterBlob iv;
273 KeymasterKeyBlob transit_key;
274 KeymasterKeyBlob secure_key;
275 KeymasterBlob tag;
276 KeymasterBlob wrapped_key_description;
277 error = parse_wrapped_key(wrapped_key_blob, &iv, &transit_key, &secure_key, &tag,
278 wrapped_key_params, wrapped_key_format, &wrapped_key_description);
279 if (error != KM_ERROR_OK) return error;
280
281 UniquePtr<Key> key;
282 auto wrapping_key_params = AuthorizationSetBuilder()
283 .RsaEncryptionKey(2048, 65537)
284 .Digest(KM_DIGEST_SHA1)
285 .Padding(KM_PAD_RSA_OAEP)
286 .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
287 .build();
288 error = ParseKeyBlob(wrapping_key_blob, wrapping_key_params, &key);
289 if (error != KM_ERROR_OK) return error;
290
291 // Ensure the wrapping key has the right purpose
292 if (!key->hw_enforced().Contains(TAG_PURPOSE, KM_PURPOSE_WRAP) &&
293 !key->sw_enforced().Contains(TAG_PURPOSE, KM_PURPOSE_WRAP)) {
294 return KM_ERROR_INCOMPATIBLE_PURPOSE;
295 }
296
297 auto operation_factory = GetOperationFactory(KM_ALGORITHM_RSA, KM_PURPOSE_DECRYPT);
298 if (!operation_factory) return KM_ERROR_UNKNOWN_ERROR;
299
300 AuthorizationSet out_params;
301 OperationPtr operation(
302 operation_factory->CreateOperation(move(*key), wrapping_key_params, &error));
303 if (!operation.get()) return error;
304
305 error = operation->Begin(wrapping_key_params, &out_params);
306 if (error != KM_ERROR_OK) return error;
307
308 Buffer input;
309 Buffer output;
310 if (!input.Reinitialize(transit_key.key_material, transit_key.key_material_size)) {
311 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
312 }
313
314 error = operation->Finish(wrapping_key_params, input, Buffer() /* signature */, &out_params,
315 &output);
316 if (error != KM_ERROR_OK) return error;
317
318 // decrypt the encrypted key material with the transit key
319 KeymasterKeyBlob key_material = {output.peek_read(), output.available_read()};
320
321 // XOR the transit key with the masking key
322 if (key_material.key_material_size != masking_key.key_material_size) {
323 return KM_ERROR_INVALID_ARGUMENT;
324 }
325 for (size_t i = 0; i < key_material.key_material_size; i++) {
326 key_material.writable_data()[i] ^= masking_key.key_material[i];
327 }
328
329 auto transit_key_authorizations = AuthorizationSetBuilder()
330 .AesEncryptionKey(256)
331 .Padding(KM_PAD_NONE)
332 .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
333 .Authorization(TAG_NONCE, iv)
334 .Authorization(TAG_MIN_MAC_LENGTH, 128)
335 .build();
336 if (transit_key_authorizations.is_valid() != AuthorizationSet::Error::OK) {
337 return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
338 }
339 auto gcm_params = AuthorizationSetBuilder()
340 .Padding(KM_PAD_NONE)
341 .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
342 .Authorization(TAG_NONCE, iv)
343 .Authorization(TAG_MAC_LENGTH, 128)
344 .build();
345 if (gcm_params.is_valid() != AuthorizationSet::Error::OK) {
346 return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
347 }
348
349 auto aes_factory = GetKeyFactory(KM_ALGORITHM_AES);
350 if (!aes_factory) return KM_ERROR_UNKNOWN_ERROR;
351
352 UniquePtr<Key> aes_key;
353 error = aes_factory->LoadKey(move(key_material), gcm_params, move(transit_key_authorizations),
354 AuthorizationSet(), &aes_key);
355 if (error != KM_ERROR_OK) return error;
356
357 auto aes_operation_factory = GetOperationFactory(KM_ALGORITHM_AES, KM_PURPOSE_DECRYPT);
358 if (!aes_operation_factory) return KM_ERROR_UNKNOWN_ERROR;
359
360 OperationPtr aes_operation(
361 aes_operation_factory->CreateOperation(move(*aes_key), gcm_params, &error));
362 if (!aes_operation.get()) return error;
363
364 error = aes_operation->Begin(gcm_params, &out_params);
365 if (error != KM_ERROR_OK) return error;
366
367 size_t consumed = 0;
368 Buffer encrypted_key, plaintext;
369 if (!plaintext.Reinitialize(secure_key.key_material_size + tag.data_length)) {
370 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
371 }
372 if (!encrypted_key.Reinitialize(secure_key.key_material_size + tag.data_length)) {
373 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
374 }
375 if (!encrypted_key.write(secure_key.key_material, secure_key.key_material_size)) {
376 return KM_ERROR_UNKNOWN_ERROR;
377 }
378 if (!encrypted_key.write(tag.data, tag.data_length)) {
379 return KM_ERROR_UNKNOWN_ERROR;
380 }
381
382 AuthorizationSet update_outparams;
383 auto update_params = AuthorizationSetBuilder()
384 .Authorization(TAG_ASSOCIATED_DATA, wrapped_key_description.data,
385 wrapped_key_description.data_length)
386 .build();
387 if (update_params.is_valid() != AuthorizationSet::Error::OK) {
388 return TranslateAuthorizationSetError(transit_key_authorizations.is_valid());
389 }
390
391 error = aes_operation->Update(update_params, encrypted_key, &update_outparams, &plaintext,
392 &consumed);
393 if (error != KM_ERROR_OK) return error;
394
395 AuthorizationSet finish_params, finish_out_params;
396 Buffer finish_input;
397 error = aes_operation->Finish(finish_params, finish_input, Buffer() /* signature */,
398 &finish_out_params, &plaintext);
399 if (error != KM_ERROR_OK) return error;
400
401 *wrapped_key_material = {plaintext.peek_read(), plaintext.available_read()};
402 if (!wrapped_key_material->key_material && plaintext.peek_read()) {
403 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
404 }
405
406 return error;
407 }
408
409 } // namespace keymaster
410