1 /*
2 * Copyright (C) 2017 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 "KeymasterHidlTest.h"
18
19 #include <chrono>
20 #include <vector>
21
22 #include <android-base/logging.h>
23 #include <android/hidl/manager/1.0/IServiceManager.h>
24
25 #include <keymasterV4_0/key_param_output.h>
26 #include <keymasterV4_0/keymaster_utils.h>
27
28 namespace android {
29 namespace hardware {
30 namespace keymaster {
31 namespace V4_0 {
32
operator <<(::std::ostream & os,const AuthorizationSet & set)33 ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
34 if (set.size() == 0)
35 os << "(Empty)" << ::std::endl;
36 else {
37 os << "\n";
38 for (size_t i = 0; i < set.size(); ++i) os << set[i] << ::std::endl;
39 }
40 return os;
41 }
42
43 namespace test {
44
45 using namespace std::literals::chrono_literals;
46
InitializeKeymaster(sp<IKeymasterDevice> keymaster)47 void KeymasterHidlTest::InitializeKeymaster(sp<IKeymasterDevice> keymaster) {
48 ASSERT_NE(keymaster, nullptr);
49 keymaster_ = keymaster;
50 ASSERT_TRUE(keymaster_
51 ->getHardwareInfo([&](SecurityLevel securityLevel, const hidl_string& name,
52 const hidl_string& author) {
53 securityLevel_ = securityLevel;
54 name_ = name;
55 author_ = author;
56 })
57 .isOk());
58
59 os_version_ = support::getOsVersion();
60 os_patch_level_ = support::getOsPatchlevel();
61 }
62
SetUp()63 void KeymasterHidlTest::SetUp() {
64 InitializeKeymaster(IKeymasterDevice::getService(GetParam()));
65 }
66
GenerateKey(const AuthorizationSet & key_desc,HidlBuf * key_blob,KeyCharacteristics * key_characteristics)67 ErrorCode KeymasterHidlTest::GenerateKey(const AuthorizationSet& key_desc, HidlBuf* key_blob,
68 KeyCharacteristics* key_characteristics) {
69 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
70 EXPECT_EQ(0U, key_blob->size()) << "Key blob not empty before generating key. Test bug.";
71 EXPECT_NE(key_characteristics, nullptr)
72 << "Previous characteristics not deleted before generating key. Test bug.";
73
74 ErrorCode error;
75 EXPECT_TRUE(keymaster_
76 ->generateKey(key_desc.hidl_data(),
77 [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
78 const KeyCharacteristics& hidl_key_characteristics) {
79 error = hidl_error;
80 *key_blob = hidl_key_blob;
81 *key_characteristics = hidl_key_characteristics;
82 })
83 .isOk());
84 // On error, blob & characteristics should be empty.
85 if (error != ErrorCode::OK) {
86 EXPECT_EQ(0U, key_blob->size());
87 EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
88 key_characteristics->hardwareEnforced.size()));
89 }
90 return error;
91 }
92
GenerateKey(const AuthorizationSet & key_desc)93 ErrorCode KeymasterHidlTest::GenerateKey(const AuthorizationSet& key_desc) {
94 return GenerateKey(key_desc, &key_blob_, &key_characteristics_);
95 }
96
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material,HidlBuf * key_blob,KeyCharacteristics * key_characteristics)97 ErrorCode KeymasterHidlTest::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
98 const string& key_material, HidlBuf* key_blob,
99 KeyCharacteristics* key_characteristics) {
100 ErrorCode error;
101 EXPECT_TRUE(keymaster_
102 ->importKey(key_desc.hidl_data(), format, HidlBuf(key_material),
103 [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
104 const KeyCharacteristics& hidl_key_characteristics) {
105 error = hidl_error;
106 *key_blob = hidl_key_blob;
107 *key_characteristics = hidl_key_characteristics;
108 })
109 .isOk());
110 // On error, blob & characteristics should be empty.
111 if (error != ErrorCode::OK) {
112 EXPECT_EQ(0U, key_blob->size());
113 EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
114 key_characteristics->hardwareEnforced.size()));
115 }
116 return error;
117 }
118
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material)119 ErrorCode KeymasterHidlTest::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
120 const string& key_material) {
121 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
122 }
123
ImportWrappedKey(string wrapped_key,string wrapping_key,const AuthorizationSet & wrapping_key_desc,string masking_key,const AuthorizationSet & unwrapping_params)124 ErrorCode KeymasterHidlTest::ImportWrappedKey(string wrapped_key, string wrapping_key,
125 const AuthorizationSet& wrapping_key_desc,
126 string masking_key,
127 const AuthorizationSet& unwrapping_params) {
128 ErrorCode error;
129 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
130 EXPECT_TRUE(keymaster_
131 ->importWrappedKey(HidlBuf(wrapped_key), key_blob_, HidlBuf(masking_key),
132 unwrapping_params.hidl_data(), 0 /* passwordSid */,
133 0 /* biometricSid */,
134 [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
135 const KeyCharacteristics& hidl_key_characteristics) {
136 error = hidl_error;
137 key_blob_ = hidl_key_blob;
138 key_characteristics_ = hidl_key_characteristics;
139 })
140 .isOk());
141 return error;
142 }
143
ExportKey(KeyFormat format,const HidlBuf & key_blob,const HidlBuf & client_id,const HidlBuf & app_data,HidlBuf * key_material)144 ErrorCode KeymasterHidlTest::ExportKey(KeyFormat format, const HidlBuf& key_blob,
145 const HidlBuf& client_id, const HidlBuf& app_data,
146 HidlBuf* key_material) {
147 ErrorCode error;
148 EXPECT_TRUE(keymaster_
149 ->exportKey(format, key_blob, client_id, app_data,
150 [&](ErrorCode hidl_error_code, const HidlBuf& hidl_key_material) {
151 error = hidl_error_code;
152 *key_material = hidl_key_material;
153 })
154 .isOk());
155 // On error, blob should be empty.
156 if (error != ErrorCode::OK) {
157 EXPECT_EQ(0U, key_material->size());
158 }
159 return error;
160 }
161
ExportKey(KeyFormat format,HidlBuf * key_material)162 ErrorCode KeymasterHidlTest::ExportKey(KeyFormat format, HidlBuf* key_material) {
163 HidlBuf client_id, app_data;
164 return ExportKey(format, key_blob_, client_id, app_data, key_material);
165 }
166
DeleteKey(HidlBuf * key_blob,bool keep_key_blob)167 ErrorCode KeymasterHidlTest::DeleteKey(HidlBuf* key_blob, bool keep_key_blob) {
168 auto rc = keymaster_->deleteKey(*key_blob);
169 if (!keep_key_blob) *key_blob = HidlBuf();
170 if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR;
171 return rc;
172 }
173
DeleteKey(bool keep_key_blob)174 ErrorCode KeymasterHidlTest::DeleteKey(bool keep_key_blob) {
175 return DeleteKey(&key_blob_, keep_key_blob);
176 }
177
DeleteAllKeys()178 ErrorCode KeymasterHidlTest::DeleteAllKeys() {
179 ErrorCode error = keymaster_->deleteAllKeys();
180 return error;
181 }
182
CheckedDeleteKey(HidlBuf * key_blob,bool keep_key_blob)183 void KeymasterHidlTest::CheckedDeleteKey(HidlBuf* key_blob, bool keep_key_blob) {
184 auto rc = DeleteKey(key_blob, keep_key_blob);
185 EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
186 }
187
CheckedDeleteKey()188 void KeymasterHidlTest::CheckedDeleteKey() {
189 CheckedDeleteKey(&key_blob_);
190 }
191
CheckGetCharacteristics(const HidlBuf & key_blob,const HidlBuf & client_id,const HidlBuf & app_data,KeyCharacteristics * key_characteristics)192 void KeymasterHidlTest::CheckGetCharacteristics(const HidlBuf& key_blob, const HidlBuf& client_id,
193 const HidlBuf& app_data,
194 KeyCharacteristics* key_characteristics) {
195 HidlBuf empty_buf = {};
196 EXPECT_EQ(ErrorCode::OK,
197 GetCharacteristics(key_blob, client_id, app_data, key_characteristics));
198 if (SecLevel() != SecurityLevel::SOFTWARE) {
199 EXPECT_GT(key_characteristics->hardwareEnforced.size(), 0);
200 }
201 EXPECT_GT(key_characteristics->softwareEnforced.size(), 0);
202
203 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
204 GetCharacteristics(key_blob, empty_buf, app_data, key_characteristics));
205 EXPECT_EQ(key_characteristics->hardwareEnforced.size(), 0);
206 EXPECT_EQ(key_characteristics->softwareEnforced.size(), 0);
207
208 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
209 GetCharacteristics(key_blob, client_id, empty_buf, key_characteristics));
210 EXPECT_EQ(key_characteristics->hardwareEnforced.size(), 0);
211 EXPECT_EQ(key_characteristics->softwareEnforced.size(), 0);
212
213 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
214 GetCharacteristics(key_blob, empty_buf, empty_buf, key_characteristics));
215 EXPECT_EQ(key_characteristics->hardwareEnforced.size(), 0);
216 EXPECT_EQ(key_characteristics->softwareEnforced.size(), 0);
217 }
218
GetCharacteristics(const HidlBuf & key_blob,const HidlBuf & client_id,const HidlBuf & app_data,KeyCharacteristics * key_characteristics)219 ErrorCode KeymasterHidlTest::GetCharacteristics(const HidlBuf& key_blob, const HidlBuf& client_id,
220 const HidlBuf& app_data,
221 KeyCharacteristics* key_characteristics) {
222 ErrorCode error = ErrorCode::UNKNOWN_ERROR;
223 EXPECT_TRUE(
224 keymaster_
225 ->getKeyCharacteristics(
226 key_blob, client_id, app_data,
227 [&](ErrorCode hidl_error, const KeyCharacteristics& hidl_key_characteristics) {
228 error = hidl_error, *key_characteristics = hidl_key_characteristics;
229 })
230 .isOk());
231 return error;
232 }
233
GetCharacteristics(const HidlBuf & key_blob,KeyCharacteristics * key_characteristics)234 ErrorCode KeymasterHidlTest::GetCharacteristics(const HidlBuf& key_blob,
235 KeyCharacteristics* key_characteristics) {
236 HidlBuf client_id, app_data;
237 return GetCharacteristics(key_blob, client_id, app_data, key_characteristics);
238 }
239
GetDebugInfo(DebugInfo * debug_info)240 ErrorCode KeymasterHidlTest::GetDebugInfo(DebugInfo* debug_info) {
241 EXPECT_TRUE(keymaster_->getDebugInfo([&](const DebugInfo& hidl_debug_info) {
242 *debug_info = hidl_debug_info;
243 }).isOk());
244 return ErrorCode::OK;
245 }
246
Begin(KeyPurpose purpose,const HidlBuf & key_blob,const AuthorizationSet & in_params,AuthorizationSet * out_params,OperationHandle * op_handle)247 ErrorCode KeymasterHidlTest::Begin(KeyPurpose purpose, const HidlBuf& key_blob,
248 const AuthorizationSet& in_params, AuthorizationSet* out_params,
249 OperationHandle* op_handle) {
250 SCOPED_TRACE("Begin");
251 ErrorCode error;
252 OperationHandle saved_handle = *op_handle;
253 EXPECT_TRUE(keymaster_
254 ->begin(purpose, key_blob, in_params.hidl_data(), HardwareAuthToken(),
255 [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
256 uint64_t hidl_op_handle) {
257 error = hidl_error;
258 *out_params = hidl_out_params;
259 *op_handle = hidl_op_handle;
260 })
261 .isOk());
262 if (error != ErrorCode::OK) {
263 // Some implementations may modify *op_handle on error.
264 *op_handle = saved_handle;
265 }
266 return error;
267 }
268
Begin(KeyPurpose purpose,const AuthorizationSet & in_params,AuthorizationSet * out_params)269 ErrorCode KeymasterHidlTest::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
270 AuthorizationSet* out_params) {
271 SCOPED_TRACE("Begin");
272 EXPECT_EQ(kOpHandleSentinel, op_handle_);
273 return Begin(purpose, key_blob_, in_params, out_params, &op_handle_);
274 }
275
Begin(KeyPurpose purpose,const AuthorizationSet & in_params)276 ErrorCode KeymasterHidlTest::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
277 SCOPED_TRACE("Begin");
278 AuthorizationSet out_params;
279 ErrorCode error = Begin(purpose, in_params, &out_params);
280 EXPECT_TRUE(out_params.empty());
281 return error;
282 }
283
Update(OperationHandle op_handle,const AuthorizationSet & in_params,const string & input,AuthorizationSet * out_params,string * output,size_t * input_consumed)284 ErrorCode KeymasterHidlTest::Update(OperationHandle op_handle, const AuthorizationSet& in_params,
285 const string& input, AuthorizationSet* out_params,
286 string* output, size_t* input_consumed) {
287 SCOPED_TRACE("Update");
288 ErrorCode error;
289 EXPECT_TRUE(keymaster_
290 ->update(op_handle, in_params.hidl_data(), HidlBuf(input), HardwareAuthToken(),
291 VerificationToken(),
292 [&](ErrorCode hidl_error, uint32_t hidl_input_consumed,
293 const hidl_vec<KeyParameter>& hidl_out_params,
294 const HidlBuf& hidl_output) {
295 error = hidl_error;
296 out_params->push_back(AuthorizationSet(hidl_out_params));
297 output->append(hidl_output.to_string());
298 *input_consumed = hidl_input_consumed;
299 })
300 .isOk());
301 return error;
302 }
303
Update(const string & input,string * out,size_t * input_consumed)304 ErrorCode KeymasterHidlTest::Update(const string& input, string* out, size_t* input_consumed) {
305 SCOPED_TRACE("Update");
306 AuthorizationSet out_params;
307 ErrorCode error = Update(op_handle_, AuthorizationSet() /* in_params */, input, &out_params,
308 out, input_consumed);
309 EXPECT_TRUE(out_params.empty());
310 return error;
311 }
312
Finish(OperationHandle op_handle,const AuthorizationSet & in_params,const string & input,const string & signature,AuthorizationSet * out_params,string * output)313 ErrorCode KeymasterHidlTest::Finish(OperationHandle op_handle, const AuthorizationSet& in_params,
314 const string& input, const string& signature,
315 AuthorizationSet* out_params, string* output) {
316 SCOPED_TRACE("Finish");
317 ErrorCode error;
318 EXPECT_TRUE(
319 keymaster_
320 ->finish(op_handle, in_params.hidl_data(), HidlBuf(input), HidlBuf(signature),
321 HardwareAuthToken(), VerificationToken(),
322 [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
323 const HidlBuf& hidl_output) {
324 error = hidl_error;
325 *out_params = hidl_out_params;
326 output->append(hidl_output.to_string());
327 })
328 .isOk());
329 op_handle_ = kOpHandleSentinel; // So dtor doesn't Abort().
330 return error;
331 }
332
Finish(const string & message,string * output)333 ErrorCode KeymasterHidlTest::Finish(const string& message, string* output) {
334 SCOPED_TRACE("Finish");
335 AuthorizationSet out_params;
336 string finish_output;
337 ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message,
338 "" /* signature */, &out_params, output);
339 if (error != ErrorCode::OK) {
340 return error;
341 }
342 EXPECT_EQ(0U, out_params.size());
343 return error;
344 }
345
Finish(const string & message,const string & signature,string * output)346 ErrorCode KeymasterHidlTest::Finish(const string& message, const string& signature,
347 string* output) {
348 SCOPED_TRACE("Finish");
349 AuthorizationSet out_params;
350 ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message, signature,
351 &out_params, output);
352 op_handle_ = kOpHandleSentinel; // So dtor doesn't Abort().
353 if (error != ErrorCode::OK) {
354 return error;
355 }
356 EXPECT_EQ(0U, out_params.size());
357 return error;
358 }
359
Abort(OperationHandle op_handle)360 ErrorCode KeymasterHidlTest::Abort(OperationHandle op_handle) {
361 SCOPED_TRACE("Abort");
362 auto retval = keymaster_->abort(op_handle);
363 EXPECT_TRUE(retval.isOk());
364 return retval;
365 }
366
AbortIfNeeded()367 void KeymasterHidlTest::AbortIfNeeded() {
368 SCOPED_TRACE("AbortIfNeeded");
369 if (op_handle_ != kOpHandleSentinel) {
370 EXPECT_EQ(ErrorCode::OK, Abort(op_handle_));
371 op_handle_ = kOpHandleSentinel;
372 }
373 }
374
AttestKey(const HidlBuf & key_blob,const AuthorizationSet & attest_params,hidl_vec<hidl_vec<uint8_t>> * cert_chain)375 ErrorCode KeymasterHidlTest::AttestKey(const HidlBuf& key_blob,
376 const AuthorizationSet& attest_params,
377 hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
378 SCOPED_TRACE("AttestKey");
379 ErrorCode error;
380 auto rc = keymaster_->attestKey(
381 key_blob, attest_params.hidl_data(),
382 [&](ErrorCode hidl_error, const hidl_vec<hidl_vec<uint8_t>>& hidl_cert_chain) {
383 error = hidl_error;
384 *cert_chain = hidl_cert_chain;
385 });
386
387 EXPECT_TRUE(rc.isOk()) << rc.description();
388 if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR;
389
390 return error;
391 }
392
AttestKey(const AuthorizationSet & attest_params,hidl_vec<hidl_vec<uint8_t>> * cert_chain)393 ErrorCode KeymasterHidlTest::AttestKey(const AuthorizationSet& attest_params,
394 hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
395 SCOPED_TRACE("AttestKey");
396 return AttestKey(key_blob_, attest_params, cert_chain);
397 }
398
ProcessMessage(const HidlBuf & key_blob,KeyPurpose operation,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)399 string KeymasterHidlTest::ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation,
400 const string& message, const AuthorizationSet& in_params,
401 AuthorizationSet* out_params) {
402 SCOPED_TRACE("ProcessMessage");
403 AuthorizationSet begin_out_params;
404 EXPECT_EQ(ErrorCode::OK, Begin(operation, key_blob, in_params, &begin_out_params, &op_handle_));
405
406 string output;
407 size_t consumed = 0;
408 AuthorizationSet update_params;
409 AuthorizationSet update_out_params;
410 EXPECT_EQ(ErrorCode::OK,
411 Update(op_handle_, update_params, message, &update_out_params, &output, &consumed));
412
413 string unused;
414 AuthorizationSet finish_params;
415 AuthorizationSet finish_out_params;
416 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message.substr(consumed), unused,
417 &finish_out_params, &output));
418 op_handle_ = kOpHandleSentinel;
419
420 out_params->push_back(begin_out_params);
421 out_params->push_back(finish_out_params);
422 return output;
423 }
424
SignMessage(const HidlBuf & key_blob,const string & message,const AuthorizationSet & params)425 string KeymasterHidlTest::SignMessage(const HidlBuf& key_blob, const string& message,
426 const AuthorizationSet& params) {
427 SCOPED_TRACE("SignMessage");
428 AuthorizationSet out_params;
429 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
430 EXPECT_TRUE(out_params.empty());
431 return signature;
432 }
433
SignMessage(const string & message,const AuthorizationSet & params)434 string KeymasterHidlTest::SignMessage(const string& message, const AuthorizationSet& params) {
435 SCOPED_TRACE("SignMessage");
436 return SignMessage(key_blob_, message, params);
437 }
438
MacMessage(const string & message,Digest digest,size_t mac_length)439 string KeymasterHidlTest::MacMessage(const string& message, Digest digest, size_t mac_length) {
440 SCOPED_TRACE("MacMessage");
441 return SignMessage(
442 key_blob_, message,
443 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
444 }
445
CheckAesIncrementalEncryptOperation(BlockMode block_mode,int message_size)446 void KeymasterHidlTest::CheckAesIncrementalEncryptOperation(BlockMode block_mode,
447 int message_size) {
448 auto builder = AuthorizationSetBuilder()
449 .Authorization(TAG_NO_AUTH_REQUIRED)
450 .AesEncryptionKey(128)
451 .BlockMode(block_mode)
452 .Padding(PaddingMode::NONE);
453 if (block_mode == BlockMode::GCM) {
454 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
455 }
456 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
457
458 for (int increment = 1; increment <= message_size; ++increment) {
459 string message(message_size, 'a');
460 auto params = AuthorizationSetBuilder()
461 .BlockMode(block_mode)
462 .Padding(PaddingMode::NONE)
463 .Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
464
465 AuthorizationSet output_params;
466 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
467
468 string ciphertext;
469 size_t input_consumed;
470 string to_send;
471 for (size_t i = 0; i < message.size(); i += increment) {
472 to_send.append(message.substr(i, increment));
473 EXPECT_EQ(ErrorCode::OK, Update(to_send, &ciphertext, &input_consumed));
474 EXPECT_EQ(to_send.length(), input_consumed);
475 to_send = to_send.substr(input_consumed);
476 EXPECT_EQ(0U, to_send.length());
477
478 switch (block_mode) {
479 case BlockMode::ECB:
480 case BlockMode::CBC:
481 // Implementations must take as many blocks as possible, leaving less than
482 // a block.
483 EXPECT_LE(to_send.length(), 16U);
484 break;
485 case BlockMode::GCM:
486 case BlockMode::CTR:
487 // Implementations must always take all the data.
488 EXPECT_EQ(0U, to_send.length());
489 break;
490 }
491 }
492 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) << "Error sending " << to_send;
493
494 switch (block_mode) {
495 case BlockMode::GCM:
496 EXPECT_EQ(message.size() + 16, ciphertext.size());
497 break;
498 case BlockMode::CTR:
499 EXPECT_EQ(message.size(), ciphertext.size());
500 break;
501 case BlockMode::CBC:
502 case BlockMode::ECB:
503 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
504 break;
505 }
506
507 auto iv = output_params.GetTagValue(TAG_NONCE);
508 switch (block_mode) {
509 case BlockMode::CBC:
510 case BlockMode::GCM:
511 case BlockMode::CTR:
512 ASSERT_TRUE(iv.isOk()) << "No IV for block mode " << block_mode;
513 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv.value().size());
514 params.push_back(TAG_NONCE, iv.value());
515 break;
516
517 case BlockMode::ECB:
518 EXPECT_FALSE(iv.isOk()) << "ECB mode should not generate IV";
519 break;
520 }
521
522 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
523 << "Decrypt begin() failed for block mode " << block_mode;
524
525 string plaintext;
526 for (size_t i = 0; i < ciphertext.size(); i += increment) {
527 to_send.append(ciphertext.substr(i, increment));
528 EXPECT_EQ(ErrorCode::OK, Update(to_send, &plaintext, &input_consumed));
529 to_send = to_send.substr(input_consumed);
530 }
531 ErrorCode error = Finish(to_send, &plaintext);
532 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
533 << " and increment " << increment;
534 if (error == ErrorCode::OK) {
535 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode " << block_mode
536 << " and increment " << increment;
537 }
538 }
539 }
540
CheckHmacTestVector(const string & key,const string & message,Digest digest,const string & expected_mac)541 void KeymasterHidlTest::CheckHmacTestVector(const string& key, const string& message, Digest digest,
542 const string& expected_mac) {
543 SCOPED_TRACE("CheckHmacTestVector");
544 ASSERT_EQ(ErrorCode::OK,
545 ImportKey(AuthorizationSetBuilder()
546 .Authorization(TAG_NO_AUTH_REQUIRED)
547 .HmacKey(key.size() * 8)
548 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
549 .Digest(digest),
550 KeyFormat::RAW, key));
551 string signature = MacMessage(message, digest, expected_mac.size() * 8);
552 EXPECT_EQ(expected_mac, signature)
553 << "Test vector didn't match for key of size " << key.size() << " message of size "
554 << message.size() << " and digest " << digest;
555 CheckedDeleteKey();
556 }
557
CheckAesCtrTestVector(const string & key,const string & nonce,const string & message,const string & expected_ciphertext)558 void KeymasterHidlTest::CheckAesCtrTestVector(const string& key, const string& nonce,
559 const string& message,
560 const string& expected_ciphertext) {
561 SCOPED_TRACE("CheckAesCtrTestVector");
562 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
563 .Authorization(TAG_NO_AUTH_REQUIRED)
564 .AesEncryptionKey(key.size() * 8)
565 .BlockMode(BlockMode::CTR)
566 .Authorization(TAG_CALLER_NONCE)
567 .Padding(PaddingMode::NONE),
568 KeyFormat::RAW, key));
569
570 auto params = AuthorizationSetBuilder()
571 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
572 .BlockMode(BlockMode::CTR)
573 .Padding(PaddingMode::NONE);
574 AuthorizationSet out_params;
575 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
576 EXPECT_EQ(expected_ciphertext, ciphertext);
577 }
578
CheckTripleDesTestVector(KeyPurpose purpose,BlockMode block_mode,PaddingMode padding_mode,const string & key,const string & iv,const string & input,const string & expected_output)579 void KeymasterHidlTest::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
580 PaddingMode padding_mode, const string& key,
581 const string& iv, const string& input,
582 const string& expected_output) {
583 auto authset = AuthorizationSetBuilder()
584 .TripleDesEncryptionKey(key.size() * 7)
585 .BlockMode(block_mode)
586 .Authorization(TAG_NO_AUTH_REQUIRED)
587 .Padding(padding_mode);
588 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
589 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
590 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
591 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
592 AuthorizationSet output_params;
593 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
594 EXPECT_EQ(expected_output, output);
595 }
596
VerifyMessage(const HidlBuf & key_blob,const string & message,const string & signature,const AuthorizationSet & params)597 void KeymasterHidlTest::VerifyMessage(const HidlBuf& key_blob, const string& message,
598 const string& signature, const AuthorizationSet& params) {
599 SCOPED_TRACE("VerifyMessage");
600 AuthorizationSet begin_out_params;
601 ASSERT_EQ(ErrorCode::OK,
602 Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params, &op_handle_));
603
604 string output;
605 AuthorizationSet update_params;
606 AuthorizationSet update_out_params;
607 size_t consumed;
608 ASSERT_EQ(ErrorCode::OK,
609 Update(op_handle_, update_params, message, &update_out_params, &output, &consumed));
610 EXPECT_TRUE(output.empty());
611 EXPECT_GT(consumed, 0U);
612
613 string unused;
614 AuthorizationSet finish_params;
615 AuthorizationSet finish_out_params;
616 EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message.substr(consumed), signature,
617 &finish_out_params, &output));
618 op_handle_ = kOpHandleSentinel;
619 EXPECT_TRUE(output.empty());
620 }
621
VerifyMessage(const string & message,const string & signature,const AuthorizationSet & params)622 void KeymasterHidlTest::VerifyMessage(const string& message, const string& signature,
623 const AuthorizationSet& params) {
624 SCOPED_TRACE("VerifyMessage");
625 VerifyMessage(key_blob_, message, signature, params);
626 }
627
EncryptMessage(const HidlBuf & key_blob,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)628 string KeymasterHidlTest::EncryptMessage(const HidlBuf& key_blob, const string& message,
629 const AuthorizationSet& in_params,
630 AuthorizationSet* out_params) {
631 SCOPED_TRACE("EncryptMessage");
632 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
633 }
634
EncryptMessage(const string & message,const AuthorizationSet & params,AuthorizationSet * out_params)635 string KeymasterHidlTest::EncryptMessage(const string& message, const AuthorizationSet& params,
636 AuthorizationSet* out_params) {
637 SCOPED_TRACE("EncryptMessage");
638 return EncryptMessage(key_blob_, message, params, out_params);
639 }
640
EncryptMessage(const string & message,const AuthorizationSet & params)641 string KeymasterHidlTest::EncryptMessage(const string& message, const AuthorizationSet& params) {
642 SCOPED_TRACE("EncryptMessage");
643 AuthorizationSet out_params;
644 string ciphertext = EncryptMessage(message, params, &out_params);
645 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
646 return ciphertext;
647 }
648
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding)649 string KeymasterHidlTest::EncryptMessage(const string& message, BlockMode block_mode,
650 PaddingMode padding) {
651 SCOPED_TRACE("EncryptMessage");
652 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
653 AuthorizationSet out_params;
654 string ciphertext = EncryptMessage(message, params, &out_params);
655 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
656 return ciphertext;
657 }
658
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,HidlBuf * iv_out)659 string KeymasterHidlTest::EncryptMessage(const string& message, BlockMode block_mode,
660 PaddingMode padding, HidlBuf* iv_out) {
661 SCOPED_TRACE("EncryptMessage");
662 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
663 AuthorizationSet out_params;
664 string ciphertext = EncryptMessage(message, params, &out_params);
665 EXPECT_EQ(1U, out_params.size());
666 auto ivVal = out_params.GetTagValue(TAG_NONCE);
667 EXPECT_TRUE(ivVal.isOk());
668 if (ivVal.isOk()) *iv_out = ivVal.value();
669 return ciphertext;
670 }
671
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,const HidlBuf & iv_in)672 string KeymasterHidlTest::EncryptMessage(const string& message, BlockMode block_mode,
673 PaddingMode padding, const HidlBuf& iv_in) {
674 SCOPED_TRACE("EncryptMessage");
675 auto params = AuthorizationSetBuilder()
676 .BlockMode(block_mode)
677 .Padding(padding)
678 .Authorization(TAG_NONCE, iv_in);
679 AuthorizationSet out_params;
680 string ciphertext = EncryptMessage(message, params, &out_params);
681 return ciphertext;
682 }
683
EncryptMessage(const string & message,BlockMode block_mode,PaddingMode padding,uint8_t mac_length_bits,const HidlBuf & iv_in)684 string KeymasterHidlTest::EncryptMessage(const string& message, BlockMode block_mode,
685 PaddingMode padding, uint8_t mac_length_bits,
686 const HidlBuf& iv_in) {
687 SCOPED_TRACE("EncryptMessage");
688 auto params = AuthorizationSetBuilder()
689 .BlockMode(block_mode)
690 .Padding(padding)
691 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
692 .Authorization(TAG_NONCE, iv_in);
693 AuthorizationSet out_params;
694 string ciphertext = EncryptMessage(message, params, &out_params);
695 return ciphertext;
696 }
697
DecryptMessage(const HidlBuf & key_blob,const string & ciphertext,const AuthorizationSet & params)698 string KeymasterHidlTest::DecryptMessage(const HidlBuf& key_blob, const string& ciphertext,
699 const AuthorizationSet& params) {
700 SCOPED_TRACE("DecryptMessage");
701 AuthorizationSet out_params;
702 string plaintext =
703 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
704 EXPECT_TRUE(out_params.empty());
705 return plaintext;
706 }
707
DecryptMessage(const string & ciphertext,const AuthorizationSet & params)708 string KeymasterHidlTest::DecryptMessage(const string& ciphertext, const AuthorizationSet& params) {
709 SCOPED_TRACE("DecryptMessage");
710 return DecryptMessage(key_blob_, ciphertext, params);
711 }
712
DecryptMessage(const string & ciphertext,BlockMode block_mode,PaddingMode padding_mode,const HidlBuf & iv)713 string KeymasterHidlTest::DecryptMessage(const string& ciphertext, BlockMode block_mode,
714 PaddingMode padding_mode, const HidlBuf& iv) {
715 SCOPED_TRACE("DecryptMessage");
716 auto params = AuthorizationSetBuilder()
717 .BlockMode(block_mode)
718 .Padding(padding_mode)
719 .Authorization(TAG_NONCE, iv);
720 return DecryptMessage(key_blob_, ciphertext, params);
721 }
722
UpgradeKey(const HidlBuf & key_blob)723 std::pair<ErrorCode, HidlBuf> KeymasterHidlTest::UpgradeKey(const HidlBuf& key_blob) {
724 std::pair<ErrorCode, HidlBuf> retval;
725 keymaster_->upgradeKey(key_blob, hidl_vec<KeyParameter>(),
726 [&](ErrorCode error, const hidl_vec<uint8_t>& upgraded_blob) {
727 retval = std::tie(error, upgraded_blob);
728 });
729 return retval;
730 }
ValidKeySizes(Algorithm algorithm)731 std::vector<uint32_t> KeymasterHidlTest::ValidKeySizes(Algorithm algorithm) {
732 switch (algorithm) {
733 case Algorithm::RSA:
734 switch (SecLevel()) {
735 case SecurityLevel::SOFTWARE:
736 case SecurityLevel::TRUSTED_ENVIRONMENT:
737 return {2048, 3072, 4096};
738 case SecurityLevel::STRONGBOX:
739 return {2048};
740 default:
741 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
742 break;
743 }
744 break;
745 case Algorithm::EC:
746 switch (SecLevel()) {
747 case SecurityLevel::SOFTWARE:
748 case SecurityLevel::TRUSTED_ENVIRONMENT:
749 return {224, 256, 384, 521};
750 case SecurityLevel::STRONGBOX:
751 return {256};
752 default:
753 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
754 break;
755 }
756 break;
757 case Algorithm::AES:
758 return {128, 256};
759 case Algorithm::TRIPLE_DES:
760 return {168};
761 case Algorithm::HMAC: {
762 std::vector<uint32_t> retval((512 - 64) / 8 + 1);
763 uint32_t size = 64 - 8;
764 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
765 return retval;
766 }
767 default:
768 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
769 return {};
770 }
771 ADD_FAILURE() << "Should be impossible to get here";
772 return {};
773 }
774
InvalidKeySizes(Algorithm algorithm)775 std::vector<uint32_t> KeymasterHidlTest::InvalidKeySizes(Algorithm algorithm) {
776 if (SecLevel() == SecurityLevel::STRONGBOX) {
777 switch (algorithm) {
778 case Algorithm::RSA:
779 return {3072, 4096};
780 case Algorithm::EC:
781 return {224, 384, 521};
782 case Algorithm::AES:
783 return {192};
784 default:
785 return {};
786 }
787 }
788 return {};
789 }
790
ValidCurves()791 std::vector<EcCurve> KeymasterHidlTest::ValidCurves() {
792 if (securityLevel_ == SecurityLevel::STRONGBOX) {
793 return {EcCurve::P_256};
794 } else {
795 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
796 }
797 }
798
InvalidCurves()799 std::vector<EcCurve> KeymasterHidlTest::InvalidCurves() {
800 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
801 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
802 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
803 }
804
ValidDigests(bool withNone,bool withMD5)805 std::vector<Digest> KeymasterHidlTest::ValidDigests(bool withNone, bool withMD5) {
806 switch (SecLevel()) {
807 case SecurityLevel::SOFTWARE:
808 case SecurityLevel::TRUSTED_ENVIRONMENT:
809 if (withNone) {
810 if (withMD5)
811 return {Digest::NONE, Digest::MD5, Digest::SHA1,
812 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
813 Digest::SHA_2_512};
814 else
815 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
816 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
817 } else {
818 if (withMD5)
819 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
820 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
821 else
822 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
823 Digest::SHA_2_512};
824 }
825 break;
826 case SecurityLevel::STRONGBOX:
827 if (withNone)
828 return {Digest::NONE, Digest::SHA_2_256};
829 else
830 return {Digest::SHA_2_256};
831 break;
832 default:
833 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
834 break;
835 }
836 ADD_FAILURE() << "Should be impossible to get here";
837 return {};
838 }
839
InvalidDigests()840 std::vector<Digest> KeymasterHidlTest::InvalidDigests() {
841 return {};
842 }
843
parse_cert_blob(const hidl_vec<uint8_t> & blob)844 X509* parse_cert_blob(const hidl_vec<uint8_t>& blob) {
845 const uint8_t* p = blob.data();
846 return d2i_X509(nullptr, &p, blob.size());
847 }
848
get_attestation_record(X509 * certificate)849 ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
850 ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
851 EXPECT_TRUE(!!oid.get());
852 if (!oid.get()) return nullptr;
853
854 int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
855 EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
856 if (location == -1) return nullptr;
857
858 X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
859 EXPECT_TRUE(!!attest_rec_ext)
860 << "Found attestation extension but couldn't retrieve it? Probably a BoringSSL bug.";
861 if (!attest_rec_ext) return nullptr;
862
863 ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
864 EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
865 return attest_rec;
866 }
867
868 } // namespace test
869 } // namespace V4_0
870 } // namespace keymaster
871 } // namespace hardware
872 } // namespace android
873