1 /*
2 * Copyright 2014 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 <assert.h>
18 #include <string.h>
19
20 #include <cstddef>
21
22 #include <openssl/rand.h>
23 #include <openssl/x509.h>
24
25 #include <UniquePtr.h>
26
27 #include <keymaster/google_keymaster.h>
28 #include <keymaster/google_keymaster_utils.h>
29 #include <keymaster/key_blob.h>
30
31 #include "ae.h"
32 #include "key.h"
33 #include "operation.h"
34
35 namespace keymaster {
36
GoogleKeymaster(size_t operation_table_size,Logger * logger)37 GoogleKeymaster::GoogleKeymaster(size_t operation_table_size, Logger* logger)
38 : operation_table_(new OpTableEntry[operation_table_size]),
39 operation_table_size_(operation_table_size), logger_(logger) {
40 if (operation_table_.get() == NULL)
41 operation_table_size_ = 0;
42 }
~GoogleKeymaster()43 GoogleKeymaster::~GoogleKeymaster() {
44 for (size_t i = 0; i < operation_table_size_; ++i)
45 if (operation_table_[i].operation != NULL)
46 delete operation_table_[i].operation;
47 }
48
49 struct AE_CTX_Delete {
operator ()keymaster::AE_CTX_Delete50 void operator()(ae_ctx* ctx) const { ae_free(ctx); }
51 };
52 typedef UniquePtr<ae_ctx, AE_CTX_Delete> Unique_ae_ctx;
53
54 keymaster_algorithm_t supported_algorithms[] = {
55 KM_ALGORITHM_RSA, KM_ALGORITHM_DSA, KM_ALGORITHM_ECDSA,
56 };
57
58 template <typename T>
check_supported(keymaster_algorithm_t algorithm,SupportedResponse<T> * response)59 bool check_supported(keymaster_algorithm_t algorithm, SupportedResponse<T>* response) {
60 if (!array_contains(supported_algorithms, algorithm)) {
61 response->error = KM_ERROR_UNSUPPORTED_ALGORITHM;
62 return false;
63 }
64 return true;
65 }
66
67 void
SupportedAlgorithms(SupportedResponse<keymaster_algorithm_t> * response) const68 GoogleKeymaster::SupportedAlgorithms(SupportedResponse<keymaster_algorithm_t>* response) const {
69 if (response == NULL)
70 return;
71 response->SetResults(supported_algorithms);
72 }
73
74 void
SupportedBlockModes(keymaster_algorithm_t algorithm,SupportedResponse<keymaster_block_mode_t> * response) const75 GoogleKeymaster::SupportedBlockModes(keymaster_algorithm_t algorithm,
76 SupportedResponse<keymaster_block_mode_t>* response) const {
77 if (response == NULL || !check_supported(algorithm, response))
78 return;
79 response->error = KM_ERROR_OK;
80 }
81
82 keymaster_padding_t supported_padding[] = {KM_PAD_NONE};
83 void
SupportedPaddingModes(keymaster_algorithm_t algorithm,SupportedResponse<keymaster_padding_t> * response) const84 GoogleKeymaster::SupportedPaddingModes(keymaster_algorithm_t algorithm,
85 SupportedResponse<keymaster_padding_t>* response) const {
86 if (response == NULL || !check_supported(algorithm, response))
87 return;
88
89 response->error = KM_ERROR_OK;
90 switch (algorithm) {
91 case KM_ALGORITHM_RSA:
92 case KM_ALGORITHM_DSA:
93 case KM_ALGORITHM_ECDSA:
94 response->SetResults(supported_padding);
95 break;
96 default:
97 response->results_length = 0;
98 break;
99 }
100 }
101
102 keymaster_digest_t supported_digests[] = {KM_DIGEST_NONE};
SupportedDigests(keymaster_algorithm_t algorithm,SupportedResponse<keymaster_digest_t> * response) const103 void GoogleKeymaster::SupportedDigests(keymaster_algorithm_t algorithm,
104 SupportedResponse<keymaster_digest_t>* response) const {
105 if (response == NULL || !check_supported(algorithm, response))
106 return;
107
108 response->error = KM_ERROR_OK;
109 switch (algorithm) {
110 case KM_ALGORITHM_RSA:
111 case KM_ALGORITHM_DSA:
112 case KM_ALGORITHM_ECDSA:
113 response->SetResults(supported_digests);
114 break;
115 default:
116 response->results_length = 0;
117 break;
118 }
119 }
120
121 keymaster_key_format_t supported_import_formats[] = {KM_KEY_FORMAT_PKCS8};
122 void
SupportedImportFormats(keymaster_algorithm_t algorithm,SupportedResponse<keymaster_key_format_t> * response) const123 GoogleKeymaster::SupportedImportFormats(keymaster_algorithm_t algorithm,
124 SupportedResponse<keymaster_key_format_t>* response) const {
125 if (response == NULL || !check_supported(algorithm, response))
126 return;
127
128 response->error = KM_ERROR_OK;
129 switch (algorithm) {
130 case KM_ALGORITHM_RSA:
131 case KM_ALGORITHM_DSA:
132 case KM_ALGORITHM_ECDSA:
133 response->SetResults(supported_import_formats);
134 break;
135 default:
136 response->results_length = 0;
137 break;
138 }
139 }
140
141 keymaster_key_format_t supported_export_formats[] = {KM_KEY_FORMAT_X509};
142 void
SupportedExportFormats(keymaster_algorithm_t algorithm,SupportedResponse<keymaster_key_format_t> * response) const143 GoogleKeymaster::SupportedExportFormats(keymaster_algorithm_t algorithm,
144 SupportedResponse<keymaster_key_format_t>* response) const {
145 if (response == NULL || !check_supported(algorithm, response))
146 return;
147
148 response->error = KM_ERROR_OK;
149 switch (algorithm) {
150 case KM_ALGORITHM_RSA:
151 case KM_ALGORITHM_DSA:
152 case KM_ALGORITHM_ECDSA:
153 response->SetResults(supported_export_formats);
154 break;
155 default:
156 response->results_length = 0;
157 break;
158 }
159 }
160
GenerateKey(const GenerateKeyRequest & request,GenerateKeyResponse * response)161 void GoogleKeymaster::GenerateKey(const GenerateKeyRequest& request,
162 GenerateKeyResponse* response) {
163 if (response == NULL)
164 return;
165
166 UniquePtr<Key> key(Key::GenerateKey(request.key_description, logger(), &response->error));
167 if (response->error != KM_ERROR_OK)
168 return;
169
170 response->error = SerializeKey(key.get(), origin(), &response->key_blob, &response->enforced,
171 &response->unenforced);
172 }
173
GetKeyCharacteristics(const GetKeyCharacteristicsRequest & request,GetKeyCharacteristicsResponse * response)174 void GoogleKeymaster::GetKeyCharacteristics(const GetKeyCharacteristicsRequest& request,
175 GetKeyCharacteristicsResponse* response) {
176 if (response == NULL)
177 return;
178 response->error = KM_ERROR_UNKNOWN_ERROR;
179
180 UniquePtr<KeyBlob> blob(
181 LoadKeyBlob(request.key_blob, request.additional_params, &(response->error)));
182 if (blob.get() == NULL)
183 return;
184
185 response->enforced.Reinitialize(blob->enforced());
186 response->unenforced.Reinitialize(blob->unenforced());
187 response->error = KM_ERROR_OK;
188 }
189
BeginOperation(const BeginOperationRequest & request,BeginOperationResponse * response)190 void GoogleKeymaster::BeginOperation(const BeginOperationRequest& request,
191 BeginOperationResponse* response) {
192 if (response == NULL)
193 return;
194 response->op_handle = 0;
195
196 UniquePtr<Key> key(LoadKey(request.key_blob, request.additional_params, &response->error));
197 if (key.get() == NULL)
198 return;
199
200 UniquePtr<Operation> operation(key->CreateOperation(request.purpose, &response->error));
201 if (operation.get() == NULL)
202 return;
203
204 response->error = operation->Begin();
205 if (response->error != KM_ERROR_OK)
206 return;
207
208 response->error = AddOperation(operation.release(), &response->op_handle);
209 }
210
UpdateOperation(const UpdateOperationRequest & request,UpdateOperationResponse * response)211 void GoogleKeymaster::UpdateOperation(const UpdateOperationRequest& request,
212 UpdateOperationResponse* response) {
213 OpTableEntry* entry = FindOperation(request.op_handle);
214 if (entry == NULL) {
215 response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
216 return;
217 }
218
219 response->error = entry->operation->Update(request.input, &response->output);
220 if (response->error != KM_ERROR_OK) {
221 // Any error invalidates the operation.
222 DeleteOperation(entry);
223 }
224 }
225
FinishOperation(const FinishOperationRequest & request,FinishOperationResponse * response)226 void GoogleKeymaster::FinishOperation(const FinishOperationRequest& request,
227 FinishOperationResponse* response) {
228 OpTableEntry* entry = FindOperation(request.op_handle);
229 if (entry == NULL) {
230 response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
231 return;
232 }
233
234 response->error = entry->operation->Finish(request.signature, &response->output);
235 DeleteOperation(entry);
236 }
237
AbortOperation(const keymaster_operation_handle_t op_handle)238 keymaster_error_t GoogleKeymaster::AbortOperation(const keymaster_operation_handle_t op_handle) {
239 OpTableEntry* entry = FindOperation(op_handle);
240 if (entry == NULL)
241 return KM_ERROR_INVALID_OPERATION_HANDLE;
242 DeleteOperation(entry);
243 return KM_ERROR_OK;
244 }
245
is_supported_export_format(keymaster_key_format_t test_format)246 bool GoogleKeymaster::is_supported_export_format(keymaster_key_format_t test_format) {
247 unsigned int index;
248 for (index = 0; index < array_length(supported_export_formats); index++) {
249 if (test_format == supported_export_formats[index]) {
250 return true;
251 }
252 }
253
254 return false;
255 }
256
is_supported_import_format(keymaster_key_format_t test_format)257 bool GoogleKeymaster::is_supported_import_format(keymaster_key_format_t test_format) {
258 unsigned int index;
259 for (index = 0; index < array_length(supported_import_formats); index++) {
260 if (test_format == supported_import_formats[index]) {
261 return true;
262 }
263 }
264
265 return false;
266 }
267
ExportKey(const ExportKeyRequest & request,ExportKeyResponse * response)268 void GoogleKeymaster::ExportKey(const ExportKeyRequest& request, ExportKeyResponse* response) {
269 if (response == NULL)
270 return;
271
272 UniquePtr<Key> to_export(
273 LoadKey(request.key_blob, request.additional_params, &response->error));
274 if (to_export.get() == NULL)
275 return;
276
277 UniquePtr<uint8_t[]> out_key;
278 size_t size;
279 response->error = to_export->formatted_key_material(request.key_format, &out_key, &size);
280 if (response->error == KM_ERROR_OK) {
281 response->key_data = out_key.release();
282 response->key_data_length = size;
283 }
284 }
285
ImportKey(const ImportKeyRequest & request,ImportKeyResponse * response)286 void GoogleKeymaster::ImportKey(const ImportKeyRequest& request, ImportKeyResponse* response) {
287 if (response == NULL)
288 return;
289
290 UniquePtr<Key> key(Key::ImportKey(request.key_description, request.key_format, request.key_data,
291 request.key_data_length, logger(), &response->error));
292 if (response->error != KM_ERROR_OK)
293 return;
294
295 response->error = SerializeKey(key.get(), KM_ORIGIN_IMPORTED, &response->key_blob,
296 &response->enforced, &response->unenforced);
297 }
298
SerializeKey(const Key * key,keymaster_key_origin_t origin,keymaster_key_blob_t * keymaster_blob,AuthorizationSet * enforced,AuthorizationSet * unenforced)299 keymaster_error_t GoogleKeymaster::SerializeKey(const Key* key, keymaster_key_origin_t origin,
300 keymaster_key_blob_t* keymaster_blob,
301 AuthorizationSet* enforced,
302 AuthorizationSet* unenforced) {
303 keymaster_error_t error;
304
305 error = SetAuthorizations(key->authorizations(), origin, enforced, unenforced);
306 if (error != KM_ERROR_OK)
307 return error;
308
309 AuthorizationSet hidden_auths;
310 error = BuildHiddenAuthorizations(key->authorizations(), &hidden_auths);
311 if (error != KM_ERROR_OK)
312 return error;
313
314 UniquePtr<uint8_t[]> key_material;
315 size_t key_material_size;
316 error = key->key_material(&key_material, &key_material_size);
317 if (error != KM_ERROR_OK)
318 return error;
319
320 uint8_t nonce[KeyBlob::NONCE_LENGTH];
321 GenerateNonce(nonce, array_size(nonce));
322
323 keymaster_key_blob_t key_data = {key_material.get(), key_material_size};
324 UniquePtr<KeyBlob> blob(
325 new KeyBlob(*enforced, *unenforced, hidden_auths, key_data, MasterKey(), nonce));
326 if (blob.get() == NULL)
327 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
328 if (blob->error() != KM_ERROR_OK)
329 return blob->error();
330
331 size_t size = blob->SerializedSize();
332 UniquePtr<uint8_t[]> blob_bytes(new uint8_t[size]);
333 if (blob_bytes.get() == NULL)
334 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
335
336 blob->Serialize(blob_bytes.get(), blob_bytes.get() + size);
337 keymaster_blob->key_material_size = size;
338 keymaster_blob->key_material = blob_bytes.release();
339
340 return KM_ERROR_OK;
341 }
342
LoadKey(const keymaster_key_blob_t & key,const AuthorizationSet & client_params,keymaster_error_t * error)343 Key* GoogleKeymaster::LoadKey(const keymaster_key_blob_t& key,
344 const AuthorizationSet& client_params, keymaster_error_t* error) {
345 UniquePtr<KeyBlob> blob(LoadKeyBlob(key, client_params, error));
346 if (*error != KM_ERROR_OK)
347 return NULL;
348 return Key::CreateKey(*blob, logger(), error);
349 }
350
LoadKeyBlob(const keymaster_key_blob_t & key,const AuthorizationSet & client_params,keymaster_error_t * error)351 KeyBlob* GoogleKeymaster::LoadKeyBlob(const keymaster_key_blob_t& key,
352 const AuthorizationSet& client_params,
353 keymaster_error_t* error) {
354 AuthorizationSet hidden;
355 BuildHiddenAuthorizations(client_params, &hidden);
356 UniquePtr<KeyBlob> blob(new KeyBlob(key, hidden, MasterKey()));
357 if (blob.get() == NULL) {
358 *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
359 return NULL;
360 } else if (blob->error() != KM_ERROR_OK) {
361 *error = blob->error();
362 return NULL;
363 }
364 *error = KM_ERROR_OK;
365 return blob.release();
366 }
367
TranslateAuthorizationSetError(AuthorizationSet::Error err)368 static keymaster_error_t TranslateAuthorizationSetError(AuthorizationSet::Error err) {
369 switch (err) {
370 case AuthorizationSet::OK:
371 return KM_ERROR_OK;
372 case AuthorizationSet::ALLOCATION_FAILURE:
373 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
374 case AuthorizationSet::MALFORMED_DATA:
375 return KM_ERROR_UNKNOWN_ERROR;
376 }
377 return KM_ERROR_OK;
378 }
379
SetAuthorizations(const AuthorizationSet & key_description,keymaster_key_origin_t origin,AuthorizationSet * enforced,AuthorizationSet * unenforced)380 keymaster_error_t GoogleKeymaster::SetAuthorizations(const AuthorizationSet& key_description,
381 keymaster_key_origin_t origin,
382 AuthorizationSet* enforced,
383 AuthorizationSet* unenforced) {
384 for (size_t i = 0; i < key_description.size(); ++i) {
385 switch (key_description[i].tag) {
386 // These cannot be specified by the client.
387 case KM_TAG_ROOT_OF_TRUST:
388 case KM_TAG_ORIGIN:
389 return KM_ERROR_INVALID_TAG;
390
391 // These don't work.
392 case KM_TAG_ROLLBACK_RESISTANT:
393 return KM_ERROR_UNSUPPORTED_TAG;
394
395 // These are hidden.
396 case KM_TAG_APPLICATION_ID:
397 case KM_TAG_APPLICATION_DATA:
398 break;
399
400 // Everything else we just copy into the appropriate set.
401 default:
402 AddAuthorization(key_description[i], enforced, unenforced);
403 break;
404 }
405 }
406
407 AddAuthorization(Authorization(TAG_CREATION_DATETIME, java_time(time(NULL))), enforced,
408 unenforced);
409 AddAuthorization(Authorization(TAG_ORIGIN, origin), enforced, unenforced);
410
411 if (enforced->is_valid() != AuthorizationSet::OK)
412 return TranslateAuthorizationSetError(enforced->is_valid());
413
414 return TranslateAuthorizationSetError(unenforced->is_valid());
415 }
416
BuildHiddenAuthorizations(const AuthorizationSet & input_set,AuthorizationSet * hidden)417 keymaster_error_t GoogleKeymaster::BuildHiddenAuthorizations(const AuthorizationSet& input_set,
418 AuthorizationSet* hidden) {
419 keymaster_blob_t entry;
420 if (input_set.GetTagValue(TAG_APPLICATION_ID, &entry))
421 hidden->push_back(TAG_APPLICATION_ID, entry.data, entry.data_length);
422 if (input_set.GetTagValue(TAG_APPLICATION_DATA, &entry))
423 hidden->push_back(TAG_APPLICATION_DATA, entry.data, entry.data_length);
424 hidden->push_back(RootOfTrustTag());
425
426 return TranslateAuthorizationSetError(hidden->is_valid());
427 }
428
AddAuthorization(const keymaster_key_param_t & auth,AuthorizationSet * enforced,AuthorizationSet * unenforced)429 void GoogleKeymaster::AddAuthorization(const keymaster_key_param_t& auth,
430 AuthorizationSet* enforced, AuthorizationSet* unenforced) {
431 if (is_enforced(auth.tag))
432 enforced->push_back(auth);
433 else
434 unenforced->push_back(auth);
435 }
436
AddOperation(Operation * operation,keymaster_operation_handle_t * op_handle)437 keymaster_error_t GoogleKeymaster::AddOperation(Operation* operation,
438 keymaster_operation_handle_t* op_handle) {
439 UniquePtr<Operation> op(operation);
440 if (RAND_bytes(reinterpret_cast<uint8_t*>(op_handle), sizeof(*op_handle)) == 0)
441 return KM_ERROR_UNKNOWN_ERROR;
442 if (*op_handle == 0) {
443 // Statistically this is vanishingly unlikely, which means if it ever happens in practice,
444 // it indicates a broken RNG.
445 return KM_ERROR_UNKNOWN_ERROR;
446 }
447 for (size_t i = 0; i < operation_table_size_; ++i) {
448 if (operation_table_[i].operation == NULL) {
449 operation_table_[i].operation = op.release();
450 operation_table_[i].handle = *op_handle;
451 return KM_ERROR_OK;
452 }
453 }
454 return KM_ERROR_TOO_MANY_OPERATIONS;
455 }
456
457 GoogleKeymaster::OpTableEntry*
FindOperation(keymaster_operation_handle_t op_handle)458 GoogleKeymaster::FindOperation(keymaster_operation_handle_t op_handle) {
459 if (op_handle == 0)
460 return NULL;
461
462 for (size_t i = 0; i < operation_table_size_; ++i) {
463 if (operation_table_[i].handle == op_handle)
464 return operation_table_.get() + i;
465 }
466 return NULL;
467 }
468
DeleteOperation(OpTableEntry * entry)469 void GoogleKeymaster::DeleteOperation(OpTableEntry* entry) {
470 delete entry->operation;
471 entry->operation = NULL;
472 entry->handle = 0;
473 }
474
475 } // namespace keymaster
476