blob: 766c02dea923a6b0d184dde5cff9d40c12a780ce [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 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 "KeyMintAidlTestBase.h"
18
19#include <chrono>
Shawn Willden7f424372021-01-10 18:06:50 -070020#include <unordered_set>
Selene Huang31ab4042020-04-29 04:22:39 -070021#include <vector>
22
23#include <android-base/logging.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080024#include <android/binder_manager.h>
Selene Huang31ab4042020-04-29 04:22:39 -070025
Shawn Willden08a7e432020-12-11 13:05:27 +000026#include <keymint_support/key_param_output.h>
27#include <keymint_support/keymint_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070028
Janis Danisevskis24c04702020-12-16 18:28:39 -080029namespace aidl::android::hardware::security::keymint {
Selene Huang31ab4042020-04-29 04:22:39 -070030
31using namespace std::literals::chrono_literals;
32using std::endl;
33using std::optional;
34
35::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
36 if (set.size() == 0)
37 os << "(Empty)" << ::std::endl;
38 else {
39 os << "\n";
Shawn Willden0e80b5d2020-12-17 09:07:27 -070040 for (auto& entry : set) os << entry << ::std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -070041 }
42 return os;
43}
44
45namespace test {
46
Shawn Willden7f424372021-01-10 18:06:50 -070047namespace {
48
49// Predicate for testing basic characteristics validity in generation or import.
50bool KeyCharacteristicsBasicallyValid(SecurityLevel secLevel,
51 const vector<KeyCharacteristics>& key_characteristics) {
52 if (key_characteristics.empty()) return false;
53
54 std::unordered_set<SecurityLevel> levels_seen;
55 for (auto& entry : key_characteristics) {
56 if (entry.authorizations.empty()) return false;
57
58 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
59 levels_seen.insert(entry.securityLevel);
60
61 // Generally, we should only have one entry, at the same security level as the KM
62 // instance. There is an exception: StrongBox KM can have some authorizations that are
63 // enforced by the TEE.
64 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
65 (secLevel == SecurityLevel::STRONGBOX &&
66 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
67
68 if (!isExpectedSecurityLevel) return false;
69 }
70 return true;
71}
72
73} // namespace
74
Janis Danisevskis24c04702020-12-16 18:28:39 -080075ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -070076 if (result.isOk()) return ErrorCode::OK;
77
Janis Danisevskis24c04702020-12-16 18:28:39 -080078 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
79 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -070080 }
81
82 return ErrorCode::UNKNOWN_ERROR;
83}
84
Janis Danisevskis24c04702020-12-16 18:28:39 -080085void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -070086 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -080087 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -070088
89 KeyMintHardwareInfo info;
90 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
91
92 securityLevel_ = info.securityLevel;
93 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
94 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
95
96 os_version_ = getOsVersion();
97 os_patch_level_ = getOsPatchlevel();
98}
99
100void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800101 if (AServiceManager_isDeclared(GetParam().c_str())) {
102 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
103 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
104 } else {
105 InitializeKeyMint(nullptr);
106 }
Selene Huang31ab4042020-04-29 04:22:39 -0700107}
108
109ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7f424372021-01-10 18:06:50 -0700110 vector<uint8_t>* key_blob,
111 vector<KeyCharacteristics>* key_characteristics) {
112 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
113 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700114 << "Previous characteristics not deleted before generating key. Test bug.";
115
116 // Aidl does not clear these output parameters if the function returns
117 // error. This is different from hal where output parameter is always
118 // cleared due to hal returning void. So now we need to do our own clearing
119 // of the output variables prior to calling keyMint aidl libraries.
Shawn Willden7f424372021-01-10 18:06:50 -0700120 key_blob->clear();
121 key_characteristics->clear();
122 cert_chain_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700123
Shawn Willden7f424372021-01-10 18:06:50 -0700124 KeyCreationResult creationResult;
125 Status result = keymint_->generateKey(key_desc.vector_data(), &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700126
Selene Huang31ab4042020-04-29 04:22:39 -0700127 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700128 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
129 creationResult.keyCharacteristics);
130 EXPECT_GT(creationResult.keyBlob.size(), 0);
131 *key_blob = std::move(creationResult.keyBlob);
132 *key_characteristics = std::move(creationResult.keyCharacteristics);
133 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700134
135 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
136 EXPECT_TRUE(algorithm);
137 if (algorithm &&
138 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
139 EXPECT_GE(cert_chain_.size(), 1);
140 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
141 } else {
142 // For symmetric keys there should be no certificates.
143 EXPECT_EQ(cert_chain_.size(), 0);
144 }
Selene Huang31ab4042020-04-29 04:22:39 -0700145 }
146
147 return GetReturnErrorCode(result);
148}
149
150ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc) {
151 return GenerateKey(key_desc, &key_blob_, &key_characteristics_);
152}
153
154ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
155 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700156 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700157 Status result;
158
Shawn Willden7f424372021-01-10 18:06:50 -0700159 cert_chain_.clear();
160 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700161 key_blob->clear();
162
Shawn Willden7f424372021-01-10 18:06:50 -0700163 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700164 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700165 vector<uint8_t>(key_material.begin(), key_material.end()),
166 &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700167
168 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700169 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
170 creationResult.keyCharacteristics);
171 EXPECT_GT(creationResult.keyBlob.size(), 0);
172
173 *key_blob = std::move(creationResult.keyBlob);
174 *key_characteristics = std::move(creationResult.keyCharacteristics);
175 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700176
177 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
178 EXPECT_TRUE(algorithm);
179 if (algorithm &&
180 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
181 EXPECT_GE(cert_chain_.size(), 1);
182 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
183 } else {
184 // For symmetric keys there should be no certificates.
185 EXPECT_EQ(cert_chain_.size(), 0);
186 }
Selene Huang31ab4042020-04-29 04:22:39 -0700187 }
188
189 return GetReturnErrorCode(result);
190}
191
192ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
193 const string& key_material) {
194 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
195}
196
197ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
198 const AuthorizationSet& wrapping_key_desc,
199 string masking_key,
200 const AuthorizationSet& unwrapping_params) {
Selene Huang31ab4042020-04-29 04:22:39 -0700201 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
202
Shawn Willden7f424372021-01-10 18:06:50 -0700203 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700204
Shawn Willden7f424372021-01-10 18:06:50 -0700205 KeyCreationResult creationResult;
206 Status result = keymint_->importWrappedKey(
207 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
208 vector<uint8_t>(masking_key.begin(), masking_key.end()),
209 unwrapping_params.vector_data(), 0 /* passwordSid */, 0 /* biometricSid */,
210 &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700211
212 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700213 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
214 creationResult.keyCharacteristics);
215 EXPECT_GT(creationResult.keyBlob.size(), 0);
216
217 key_blob_ = std::move(creationResult.keyBlob);
218 key_characteristics_ = std::move(creationResult.keyCharacteristics);
219 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700220
221 AuthorizationSet allAuths;
222 for (auto& entry : key_characteristics_) {
223 allAuths.push_back(AuthorizationSet(entry.authorizations));
224 }
225 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
226 EXPECT_TRUE(algorithm);
227 if (algorithm &&
228 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
229 EXPECT_GE(cert_chain_.size(), 1);
230 } else {
231 // For symmetric keys there should be no certificates.
232 EXPECT_EQ(cert_chain_.size(), 0);
233 }
Selene Huang31ab4042020-04-29 04:22:39 -0700234 }
235
236 return GetReturnErrorCode(result);
237}
238
239ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
240 Status result = keymint_->deleteKey(*key_blob);
241 if (!keep_key_blob) {
242 *key_blob = vector<uint8_t>();
243 }
244
Janis Danisevskis24c04702020-12-16 18:28:39 -0800245 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700246 return GetReturnErrorCode(result);
247}
248
249ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
250 return DeleteKey(&key_blob_, keep_key_blob);
251}
252
253ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
254 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800255 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700256 return GetReturnErrorCode(result);
257}
258
259void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
260 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
261 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
262}
263
264void KeyMintAidlTestBase::CheckedDeleteKey() {
265 CheckedDeleteKey(&key_blob_);
266}
267
268ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
269 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800270 AuthorizationSet* out_params,
271 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700272 SCOPED_TRACE("Begin");
273 Status result;
274 BeginResult out;
275 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
276
277 if (result.isOk()) {
278 *out_params = out.params;
279 challenge_ = out.challenge;
280 op = out.operation;
281 }
282
283 return GetReturnErrorCode(result);
284}
285
286ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
287 const AuthorizationSet& in_params,
288 AuthorizationSet* out_params) {
289 SCOPED_TRACE("Begin");
290 Status result;
291 BeginResult out;
292
293 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
294
295 if (result.isOk()) {
296 *out_params = out.params;
297 challenge_ = out.challenge;
298 op_ = out.operation;
299 }
300
301 return GetReturnErrorCode(result);
302}
303
304ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
305 AuthorizationSet* out_params) {
306 SCOPED_TRACE("Begin");
307 EXPECT_EQ(nullptr, op_);
308 return Begin(purpose, key_blob_, in_params, out_params);
309}
310
311ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
312 SCOPED_TRACE("Begin");
313 AuthorizationSet out_params;
314 ErrorCode result = Begin(purpose, in_params, &out_params);
315 EXPECT_TRUE(out_params.empty());
316 return result;
317}
318
319ErrorCode KeyMintAidlTestBase::Update(const AuthorizationSet& in_params, const string& input,
320 AuthorizationSet* out_params, string* output,
321 int32_t* input_consumed) {
322 SCOPED_TRACE("Update");
323
324 Status result;
325 EXPECT_NE(op_, nullptr);
326 if (!op_) {
327 return ErrorCode::UNEXPECTED_NULL_POINTER;
328 }
329
330 KeyParameterArray key_params;
331 key_params.params = in_params.vector_data();
332
333 KeyParameterArray in_keyParams;
334 in_keyParams.params = in_params.vector_data();
335
336 optional<KeyParameterArray> out_keyParams;
337 optional<ByteArray> o_put;
338 result = op_->update(in_keyParams, vector<uint8_t>(input.begin(), input.end()), {}, {},
339 &out_keyParams, &o_put, input_consumed);
340
341 if (result.isOk()) {
342 if (o_put) {
343 output->append(o_put->data.begin(), o_put->data.end());
344 }
345
346 if (out_keyParams) {
347 out_params->push_back(AuthorizationSet(out_keyParams->params));
348 }
349 }
350
351 return GetReturnErrorCode(result);
352}
353
354ErrorCode KeyMintAidlTestBase::Update(const string& input, string* out, int32_t* input_consumed) {
355 SCOPED_TRACE("Update");
356 AuthorizationSet out_params;
357 ErrorCode result =
358 Update(AuthorizationSet() /* in_params */, input, &out_params, out, input_consumed);
359 EXPECT_TRUE(out_params.empty());
360 return result;
361}
362
363ErrorCode KeyMintAidlTestBase::Finish(const AuthorizationSet& in_params, const string& input,
364 const string& signature, AuthorizationSet* out_params,
365 string* output) {
366 SCOPED_TRACE("Finish");
367 Status result;
368
369 EXPECT_NE(op_, nullptr);
370 if (!op_) {
371 return ErrorCode::UNEXPECTED_NULL_POINTER;
372 }
373
374 KeyParameterArray key_params;
375 key_params.params = in_params.vector_data();
376
377 KeyParameterArray in_keyParams;
378 in_keyParams.params = in_params.vector_data();
379
380 optional<KeyParameterArray> out_keyParams;
381 optional<vector<uint8_t>> o_put;
382
383 vector<uint8_t> oPut;
384 result = op_->finish(in_keyParams, vector<uint8_t>(input.begin(), input.end()),
385 vector<uint8_t>(signature.begin(), signature.end()), {}, {},
386 &out_keyParams, &oPut);
387
388 if (result.isOk()) {
389 if (out_keyParams) {
390 out_params->push_back(AuthorizationSet(out_keyParams->params));
391 }
392
393 output->append(oPut.begin(), oPut.end());
394 }
395
Janis Danisevskis24c04702020-12-16 18:28:39 -0800396 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700397 return GetReturnErrorCode(result);
398}
399
400ErrorCode KeyMintAidlTestBase::Finish(const string& message, string* output) {
401 SCOPED_TRACE("Finish");
402 AuthorizationSet out_params;
403 string finish_output;
404 ErrorCode result = Finish(AuthorizationSet() /* in_params */, message, "" /* signature */,
405 &out_params, output);
406 if (result != ErrorCode::OK) {
407 return result;
408 }
409 EXPECT_EQ(0U, out_params.size());
410 return result;
411}
412
413ErrorCode KeyMintAidlTestBase::Finish(const string& message, const string& signature,
414 string* output) {
415 SCOPED_TRACE("Finish");
416 AuthorizationSet out_params;
417 ErrorCode result =
418 Finish(AuthorizationSet() /* in_params */, message, signature, &out_params, output);
419
420 if (result != ErrorCode::OK) {
421 return result;
422 }
423
424 EXPECT_EQ(0U, out_params.size());
425 return result;
426}
427
Janis Danisevskis24c04702020-12-16 18:28:39 -0800428ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700429 SCOPED_TRACE("Abort");
430
431 EXPECT_NE(op, nullptr);
432 if (!op) {
433 return ErrorCode::UNEXPECTED_NULL_POINTER;
434 }
435
436 Status retval = op->abort();
437 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800438 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700439}
440
441ErrorCode KeyMintAidlTestBase::Abort() {
442 SCOPED_TRACE("Abort");
443
444 EXPECT_NE(op_, nullptr);
445 if (!op_) {
446 return ErrorCode::UNEXPECTED_NULL_POINTER;
447 }
448
449 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800450 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700451}
452
453void KeyMintAidlTestBase::AbortIfNeeded() {
454 SCOPED_TRACE("AbortIfNeeded");
455 if (op_) {
456 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800457 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700458 }
459}
460
461string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
462 const string& message, const AuthorizationSet& in_params,
463 AuthorizationSet* out_params) {
464 SCOPED_TRACE("ProcessMessage");
465 AuthorizationSet begin_out_params;
466 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
467 EXPECT_EQ(ErrorCode::OK, result);
468 if (result != ErrorCode::OK) {
469 return "";
470 }
471
472 string output;
473 int32_t consumed = 0;
474 AuthorizationSet update_params;
475 AuthorizationSet update_out_params;
476 result = Update(update_params, message, &update_out_params, &output, &consumed);
477 EXPECT_EQ(ErrorCode::OK, result);
478 if (result != ErrorCode::OK) {
479 return "";
480 }
481
482 string unused;
483 AuthorizationSet finish_params;
484 AuthorizationSet finish_out_params;
485 EXPECT_EQ(ErrorCode::OK,
486 Finish(finish_params, message.substr(consumed), unused, &finish_out_params, &output));
487
488 out_params->push_back(begin_out_params);
489 out_params->push_back(finish_out_params);
490 return output;
491}
492
493string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
494 const AuthorizationSet& params) {
495 SCOPED_TRACE("SignMessage");
496 AuthorizationSet out_params;
497 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
498 EXPECT_TRUE(out_params.empty());
499 return signature;
500}
501
502string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
503 SCOPED_TRACE("SignMessage");
504 return SignMessage(key_blob_, message, params);
505}
506
507string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
508 SCOPED_TRACE("MacMessage");
509 return SignMessage(
510 key_blob_, message,
511 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
512}
513
514void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
515 Digest digest, const string& expected_mac) {
516 SCOPED_TRACE("CheckHmacTestVector");
517 ASSERT_EQ(ErrorCode::OK,
518 ImportKey(AuthorizationSetBuilder()
519 .Authorization(TAG_NO_AUTH_REQUIRED)
520 .HmacKey(key.size() * 8)
521 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
522 .Digest(digest),
523 KeyFormat::RAW, key));
524 string signature = MacMessage(message, digest, expected_mac.size() * 8);
525 EXPECT_EQ(expected_mac, signature)
526 << "Test vector didn't match for key of size " << key.size() << " message of size "
527 << message.size() << " and digest " << digest;
528 CheckedDeleteKey();
529}
530
531void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
532 const string& message,
533 const string& expected_ciphertext) {
534 SCOPED_TRACE("CheckAesCtrTestVector");
535 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
536 .Authorization(TAG_NO_AUTH_REQUIRED)
537 .AesEncryptionKey(key.size() * 8)
538 .BlockMode(BlockMode::CTR)
539 .Authorization(TAG_CALLER_NONCE)
540 .Padding(PaddingMode::NONE),
541 KeyFormat::RAW, key));
542
543 auto params = AuthorizationSetBuilder()
544 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
545 .BlockMode(BlockMode::CTR)
546 .Padding(PaddingMode::NONE);
547 AuthorizationSet out_params;
548 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
549 EXPECT_EQ(expected_ciphertext, ciphertext);
550}
551
552void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
553 PaddingMode padding_mode, const string& key,
554 const string& iv, const string& input,
555 const string& expected_output) {
556 auto authset = AuthorizationSetBuilder()
557 .TripleDesEncryptionKey(key.size() * 7)
558 .BlockMode(block_mode)
559 .Authorization(TAG_NO_AUTH_REQUIRED)
560 .Padding(padding_mode);
561 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
562 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
563 ASSERT_GT(key_blob_.size(), 0U);
564
565 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
566 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
567 AuthorizationSet output_params;
568 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
569 EXPECT_EQ(expected_output, output);
570}
571
572void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
573 const string& signature, const AuthorizationSet& params) {
574 SCOPED_TRACE("VerifyMessage");
575 AuthorizationSet begin_out_params;
576 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
577
578 string output;
579 AuthorizationSet update_params;
580 AuthorizationSet update_out_params;
581 int32_t consumed;
582 ASSERT_EQ(ErrorCode::OK,
583 Update(update_params, message, &update_out_params, &output, &consumed));
584 EXPECT_TRUE(output.empty());
585 EXPECT_GT(consumed, 0U);
586
587 string unused;
588 AuthorizationSet finish_params;
589 AuthorizationSet finish_out_params;
590 EXPECT_EQ(ErrorCode::OK, Finish(finish_params, message.substr(consumed), signature,
591 &finish_out_params, &output));
Janis Danisevskis24c04702020-12-16 18:28:39 -0800592 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700593 EXPECT_TRUE(output.empty());
594}
595
596void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
597 const AuthorizationSet& params) {
598 SCOPED_TRACE("VerifyMessage");
599 VerifyMessage(key_blob_, message, signature, params);
600}
601
602string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
603 const AuthorizationSet& in_params,
604 AuthorizationSet* out_params) {
605 SCOPED_TRACE("EncryptMessage");
606 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
607}
608
609string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
610 AuthorizationSet* out_params) {
611 SCOPED_TRACE("EncryptMessage");
612 return EncryptMessage(key_blob_, message, params, out_params);
613}
614
615string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
616 SCOPED_TRACE("EncryptMessage");
617 AuthorizationSet out_params;
618 string ciphertext = EncryptMessage(message, params, &out_params);
619 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
620 return ciphertext;
621}
622
623string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
624 PaddingMode padding) {
625 SCOPED_TRACE("EncryptMessage");
626 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
627 AuthorizationSet out_params;
628 string ciphertext = EncryptMessage(message, params, &out_params);
629 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
630 return ciphertext;
631}
632
633string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
634 PaddingMode padding, vector<uint8_t>* iv_out) {
635 SCOPED_TRACE("EncryptMessage");
636 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
637 AuthorizationSet out_params;
638 string ciphertext = EncryptMessage(message, params, &out_params);
639 EXPECT_EQ(1U, out_params.size());
640 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800641 EXPECT_TRUE(ivVal);
642 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700643 return ciphertext;
644}
645
646string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
647 PaddingMode padding, const vector<uint8_t>& iv_in) {
648 SCOPED_TRACE("EncryptMessage");
649 auto params = AuthorizationSetBuilder()
650 .BlockMode(block_mode)
651 .Padding(padding)
652 .Authorization(TAG_NONCE, iv_in);
653 AuthorizationSet out_params;
654 string ciphertext = EncryptMessage(message, params, &out_params);
655 return ciphertext;
656}
657
658string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
659 PaddingMode padding, uint8_t mac_length_bits,
660 const vector<uint8_t>& iv_in) {
661 SCOPED_TRACE("EncryptMessage");
662 auto params = AuthorizationSetBuilder()
663 .BlockMode(block_mode)
664 .Padding(padding)
665 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
666 .Authorization(TAG_NONCE, iv_in);
667 AuthorizationSet out_params;
668 string ciphertext = EncryptMessage(message, params, &out_params);
669 return ciphertext;
670}
671
672string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
673 const string& ciphertext,
674 const AuthorizationSet& params) {
675 SCOPED_TRACE("DecryptMessage");
676 AuthorizationSet out_params;
677 string plaintext =
678 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
679 EXPECT_TRUE(out_params.empty());
680 return plaintext;
681}
682
683string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
684 const AuthorizationSet& params) {
685 SCOPED_TRACE("DecryptMessage");
686 return DecryptMessage(key_blob_, ciphertext, params);
687}
688
689string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
690 PaddingMode padding_mode, const vector<uint8_t>& iv) {
691 SCOPED_TRACE("DecryptMessage");
692 auto params = AuthorizationSetBuilder()
693 .BlockMode(block_mode)
694 .Padding(padding_mode)
695 .Authorization(TAG_NONCE, iv);
696 return DecryptMessage(key_blob_, ciphertext, params);
697}
698
699std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
700 const vector<uint8_t>& key_blob) {
701 std::pair<ErrorCode, vector<uint8_t>> retval;
702 vector<uint8_t> outKeyBlob;
703 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
704 ErrorCode errorcode = GetReturnErrorCode(result);
705 retval = std::tie(errorcode, outKeyBlob);
706
707 return retval;
708}
709vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
710 switch (algorithm) {
711 case Algorithm::RSA:
712 switch (SecLevel()) {
713 case SecurityLevel::SOFTWARE:
714 case SecurityLevel::TRUSTED_ENVIRONMENT:
715 return {2048, 3072, 4096};
716 case SecurityLevel::STRONGBOX:
717 return {2048};
718 default:
719 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
720 break;
721 }
722 break;
723 case Algorithm::EC:
724 switch (SecLevel()) {
725 case SecurityLevel::SOFTWARE:
726 case SecurityLevel::TRUSTED_ENVIRONMENT:
727 return {224, 256, 384, 521};
728 case SecurityLevel::STRONGBOX:
729 return {256};
730 default:
731 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
732 break;
733 }
734 break;
735 case Algorithm::AES:
736 return {128, 256};
737 case Algorithm::TRIPLE_DES:
738 return {168};
739 case Algorithm::HMAC: {
740 vector<uint32_t> retval((512 - 64) / 8 + 1);
741 uint32_t size = 64 - 8;
742 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
743 return retval;
744 }
745 default:
746 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
747 return {};
748 }
749 ADD_FAILURE() << "Should be impossible to get here";
750 return {};
751}
752
753vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
754 if (SecLevel() == SecurityLevel::STRONGBOX) {
755 switch (algorithm) {
756 case Algorithm::RSA:
757 return {3072, 4096};
758 case Algorithm::EC:
759 return {224, 384, 521};
760 case Algorithm::AES:
761 return {192};
762 default:
763 return {};
764 }
765 }
766 return {};
767}
768
769vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
770 if (securityLevel_ == SecurityLevel::STRONGBOX) {
771 return {EcCurve::P_256};
772 } else {
773 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
774 }
775}
776
777vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
778 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
779 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
780 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
781}
782
783vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
784 switch (SecLevel()) {
785 case SecurityLevel::SOFTWARE:
786 case SecurityLevel::TRUSTED_ENVIRONMENT:
787 if (withNone) {
788 if (withMD5)
789 return {Digest::NONE, Digest::MD5, Digest::SHA1,
790 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
791 Digest::SHA_2_512};
792 else
793 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
794 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
795 } else {
796 if (withMD5)
797 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
798 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
799 else
800 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
801 Digest::SHA_2_512};
802 }
803 break;
804 case SecurityLevel::STRONGBOX:
805 if (withNone)
806 return {Digest::NONE, Digest::SHA_2_256};
807 else
808 return {Digest::SHA_2_256};
809 break;
810 default:
811 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
812 break;
813 }
814 ADD_FAILURE() << "Should be impossible to get here";
815 return {};
816}
817
Shawn Willden7f424372021-01-10 18:06:50 -0700818static const vector<KeyParameter> kEmptyAuthList{};
819
820const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
821 const vector<KeyCharacteristics>& key_characteristics) {
822 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
823 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
824 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
825}
826
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700827const vector<KeyParameter>& KeyMintAidlTestBase::HwEnforcedAuthorizations(
828 const vector<KeyCharacteristics>& key_characteristics) {
829 auto found =
830 std::find_if(key_characteristics.begin(), key_characteristics.end(), [](auto& entry) {
831 return entry.securityLevel == SecurityLevel::STRONGBOX ||
832 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT;
833 });
834 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
835}
836
837const vector<KeyParameter>& KeyMintAidlTestBase::SwEnforcedAuthorizations(
838 const vector<KeyCharacteristics>& key_characteristics) {
839 auto found = std::find_if(
840 key_characteristics.begin(), key_characteristics.end(),
841 [](auto& entry) { return entry.securityLevel == SecurityLevel::SOFTWARE; });
842 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
843}
844
Selene Huang31ab4042020-04-29 04:22:39 -0700845} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +0000846
Janis Danisevskis24c04702020-12-16 18:28:39 -0800847} // namespace aidl::android::hardware::security::keymint