blob: eb66aca58a7a45386fe95157b425514c8b3ef246 [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 {
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000048typedef KeyMintAidlTestBase::KeyData KeyData;
Shawn Willden7f424372021-01-10 18:06:50 -070049// 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
Qi Wubeefae42021-01-28 23:16:37 +080058 // Just ignore the SecurityLevel::KEYSTORE as the KM won't do any enforcement on this.
59 if (entry.securityLevel == SecurityLevel::KEYSTORE) continue;
60
Shawn Willden7f424372021-01-10 18:06:50 -070061 if (levels_seen.find(entry.securityLevel) != levels_seen.end()) return false;
62 levels_seen.insert(entry.securityLevel);
63
64 // Generally, we should only have one entry, at the same security level as the KM
65 // instance. There is an exception: StrongBox KM can have some authorizations that are
66 // enforced by the TEE.
67 bool isExpectedSecurityLevel = secLevel == entry.securityLevel ||
68 (secLevel == SecurityLevel::STRONGBOX &&
69 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT);
70
71 if (!isExpectedSecurityLevel) return false;
72 }
73 return true;
74}
75
76} // namespace
77
Janis Danisevskis24c04702020-12-16 18:28:39 -080078ErrorCode KeyMintAidlTestBase::GetReturnErrorCode(const Status& result) {
Selene Huang31ab4042020-04-29 04:22:39 -070079 if (result.isOk()) return ErrorCode::OK;
80
Janis Danisevskis24c04702020-12-16 18:28:39 -080081 if (result.getExceptionCode() == EX_SERVICE_SPECIFIC) {
82 return static_cast<ErrorCode>(result.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -070083 }
84
85 return ErrorCode::UNKNOWN_ERROR;
86}
87
Janis Danisevskis24c04702020-12-16 18:28:39 -080088void KeyMintAidlTestBase::InitializeKeyMint(std::shared_ptr<IKeyMintDevice> keyMint) {
Selene Huang31ab4042020-04-29 04:22:39 -070089 ASSERT_NE(keyMint, nullptr);
Janis Danisevskis24c04702020-12-16 18:28:39 -080090 keymint_ = std::move(keyMint);
Selene Huang31ab4042020-04-29 04:22:39 -070091
92 KeyMintHardwareInfo info;
93 ASSERT_TRUE(keymint_->getHardwareInfo(&info).isOk());
94
95 securityLevel_ = info.securityLevel;
96 name_.assign(info.keyMintName.begin(), info.keyMintName.end());
97 author_.assign(info.keyMintAuthorName.begin(), info.keyMintAuthorName.end());
98
99 os_version_ = getOsVersion();
100 os_patch_level_ = getOsPatchlevel();
101}
102
103void KeyMintAidlTestBase::SetUp() {
Janis Danisevskis24c04702020-12-16 18:28:39 -0800104 if (AServiceManager_isDeclared(GetParam().c_str())) {
105 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
106 InitializeKeyMint(IKeyMintDevice::fromBinder(binder));
107 } else {
108 InitializeKeyMint(nullptr);
109 }
Selene Huang31ab4042020-04-29 04:22:39 -0700110}
111
112ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc,
Shawn Willden7f424372021-01-10 18:06:50 -0700113 vector<uint8_t>* key_blob,
114 vector<KeyCharacteristics>* key_characteristics) {
115 EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null. Test bug";
116 EXPECT_NE(key_characteristics, nullptr)
Selene Huang31ab4042020-04-29 04:22:39 -0700117 << "Previous characteristics not deleted before generating key. Test bug.";
118
119 // Aidl does not clear these output parameters if the function returns
120 // error. This is different from hal where output parameter is always
121 // cleared due to hal returning void. So now we need to do our own clearing
122 // of the output variables prior to calling keyMint aidl libraries.
Shawn Willden7f424372021-01-10 18:06:50 -0700123 key_blob->clear();
124 key_characteristics->clear();
125 cert_chain_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700126
Shawn Willden7f424372021-01-10 18:06:50 -0700127 KeyCreationResult creationResult;
128 Status result = keymint_->generateKey(key_desc.vector_data(), &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700129
Selene Huang31ab4042020-04-29 04:22:39 -0700130 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700131 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
132 creationResult.keyCharacteristics);
133 EXPECT_GT(creationResult.keyBlob.size(), 0);
134 *key_blob = std::move(creationResult.keyBlob);
135 *key_characteristics = std::move(creationResult.keyCharacteristics);
136 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700137
138 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
139 EXPECT_TRUE(algorithm);
140 if (algorithm &&
141 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
142 EXPECT_GE(cert_chain_.size(), 1);
143 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
144 } else {
145 // For symmetric keys there should be no certificates.
146 EXPECT_EQ(cert_chain_.size(), 0);
147 }
Selene Huang31ab4042020-04-29 04:22:39 -0700148 }
149
150 return GetReturnErrorCode(result);
151}
152
153ErrorCode KeyMintAidlTestBase::GenerateKey(const AuthorizationSet& key_desc) {
154 return GenerateKey(key_desc, &key_blob_, &key_characteristics_);
155}
156
157ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
158 const string& key_material, vector<uint8_t>* key_blob,
Shawn Willden7f424372021-01-10 18:06:50 -0700159 vector<KeyCharacteristics>* key_characteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700160 Status result;
161
Shawn Willden7f424372021-01-10 18:06:50 -0700162 cert_chain_.clear();
163 key_characteristics->clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700164 key_blob->clear();
165
Shawn Willden7f424372021-01-10 18:06:50 -0700166 KeyCreationResult creationResult;
Selene Huang31ab4042020-04-29 04:22:39 -0700167 result = keymint_->importKey(key_desc.vector_data(), format,
Shawn Willden7f424372021-01-10 18:06:50 -0700168 vector<uint8_t>(key_material.begin(), key_material.end()),
169 &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700170
171 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700172 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
173 creationResult.keyCharacteristics);
174 EXPECT_GT(creationResult.keyBlob.size(), 0);
175
176 *key_blob = std::move(creationResult.keyBlob);
177 *key_characteristics = std::move(creationResult.keyCharacteristics);
178 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700179
180 auto algorithm = key_desc.GetTagValue(TAG_ALGORITHM);
181 EXPECT_TRUE(algorithm);
182 if (algorithm &&
183 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
184 EXPECT_GE(cert_chain_.size(), 1);
185 if (key_desc.Contains(TAG_ATTESTATION_CHALLENGE)) EXPECT_GT(cert_chain_.size(), 1);
186 } else {
187 // For symmetric keys there should be no certificates.
188 EXPECT_EQ(cert_chain_.size(), 0);
189 }
Selene Huang31ab4042020-04-29 04:22:39 -0700190 }
191
192 return GetReturnErrorCode(result);
193}
194
195ErrorCode KeyMintAidlTestBase::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
196 const string& key_material) {
197 return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
198}
199
200ErrorCode KeyMintAidlTestBase::ImportWrappedKey(string wrapped_key, string wrapping_key,
201 const AuthorizationSet& wrapping_key_desc,
202 string masking_key,
203 const AuthorizationSet& unwrapping_params) {
Selene Huang31ab4042020-04-29 04:22:39 -0700204 EXPECT_EQ(ErrorCode::OK, ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key));
205
Shawn Willden7f424372021-01-10 18:06:50 -0700206 key_characteristics_.clear();
Selene Huang31ab4042020-04-29 04:22:39 -0700207
Shawn Willden7f424372021-01-10 18:06:50 -0700208 KeyCreationResult creationResult;
209 Status result = keymint_->importWrappedKey(
210 vector<uint8_t>(wrapped_key.begin(), wrapped_key.end()), key_blob_,
211 vector<uint8_t>(masking_key.begin(), masking_key.end()),
212 unwrapping_params.vector_data(), 0 /* passwordSid */, 0 /* biometricSid */,
213 &creationResult);
Selene Huang31ab4042020-04-29 04:22:39 -0700214
215 if (result.isOk()) {
Shawn Willden7f424372021-01-10 18:06:50 -0700216 EXPECT_PRED2(KeyCharacteristicsBasicallyValid, SecLevel(),
217 creationResult.keyCharacteristics);
218 EXPECT_GT(creationResult.keyBlob.size(), 0);
219
220 key_blob_ = std::move(creationResult.keyBlob);
221 key_characteristics_ = std::move(creationResult.keyCharacteristics);
222 cert_chain_ = std::move(creationResult.certificateChain);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700223
224 AuthorizationSet allAuths;
225 for (auto& entry : key_characteristics_) {
226 allAuths.push_back(AuthorizationSet(entry.authorizations));
227 }
228 auto algorithm = allAuths.GetTagValue(TAG_ALGORITHM);
229 EXPECT_TRUE(algorithm);
230 if (algorithm &&
231 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC)) {
232 EXPECT_GE(cert_chain_.size(), 1);
233 } else {
234 // For symmetric keys there should be no certificates.
235 EXPECT_EQ(cert_chain_.size(), 0);
236 }
Selene Huang31ab4042020-04-29 04:22:39 -0700237 }
238
239 return GetReturnErrorCode(result);
240}
241
242ErrorCode KeyMintAidlTestBase::DeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
243 Status result = keymint_->deleteKey(*key_blob);
244 if (!keep_key_blob) {
245 *key_blob = vector<uint8_t>();
246 }
247
Janis Danisevskis24c04702020-12-16 18:28:39 -0800248 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700249 return GetReturnErrorCode(result);
250}
251
252ErrorCode KeyMintAidlTestBase::DeleteKey(bool keep_key_blob) {
253 return DeleteKey(&key_blob_, keep_key_blob);
254}
255
256ErrorCode KeyMintAidlTestBase::DeleteAllKeys() {
257 Status result = keymint_->deleteAllKeys();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800258 EXPECT_TRUE(result.isOk()) << result.getServiceSpecificError() << endl;
Selene Huang31ab4042020-04-29 04:22:39 -0700259 return GetReturnErrorCode(result);
260}
261
262void KeyMintAidlTestBase::CheckedDeleteKey(vector<uint8_t>* key_blob, bool keep_key_blob) {
263 ErrorCode result = DeleteKey(key_blob, keep_key_blob);
264 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED) << result << endl;
265}
266
267void KeyMintAidlTestBase::CheckedDeleteKey() {
268 CheckedDeleteKey(&key_blob_);
269}
270
271ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
272 const AuthorizationSet& in_params,
Janis Danisevskis24c04702020-12-16 18:28:39 -0800273 AuthorizationSet* out_params,
274 std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700275 SCOPED_TRACE("Begin");
276 Status result;
277 BeginResult out;
278 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
279
280 if (result.isOk()) {
281 *out_params = out.params;
282 challenge_ = out.challenge;
283 op = out.operation;
284 }
285
286 return GetReturnErrorCode(result);
287}
288
289ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const vector<uint8_t>& key_blob,
290 const AuthorizationSet& in_params,
291 AuthorizationSet* out_params) {
292 SCOPED_TRACE("Begin");
293 Status result;
294 BeginResult out;
295
296 result = keymint_->begin(purpose, key_blob, in_params.vector_data(), HardwareAuthToken(), &out);
297
298 if (result.isOk()) {
299 *out_params = out.params;
300 challenge_ = out.challenge;
301 op_ = out.operation;
302 }
303
304 return GetReturnErrorCode(result);
305}
306
307ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
308 AuthorizationSet* out_params) {
309 SCOPED_TRACE("Begin");
310 EXPECT_EQ(nullptr, op_);
311 return Begin(purpose, key_blob_, in_params, out_params);
312}
313
314ErrorCode KeyMintAidlTestBase::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
315 SCOPED_TRACE("Begin");
316 AuthorizationSet out_params;
317 ErrorCode result = Begin(purpose, in_params, &out_params);
318 EXPECT_TRUE(out_params.empty());
319 return result;
320}
321
322ErrorCode KeyMintAidlTestBase::Update(const AuthorizationSet& in_params, const string& input,
323 AuthorizationSet* out_params, string* output,
324 int32_t* input_consumed) {
325 SCOPED_TRACE("Update");
326
327 Status result;
328 EXPECT_NE(op_, nullptr);
329 if (!op_) {
330 return ErrorCode::UNEXPECTED_NULL_POINTER;
331 }
332
333 KeyParameterArray key_params;
334 key_params.params = in_params.vector_data();
335
336 KeyParameterArray in_keyParams;
337 in_keyParams.params = in_params.vector_data();
338
339 optional<KeyParameterArray> out_keyParams;
340 optional<ByteArray> o_put;
341 result = op_->update(in_keyParams, vector<uint8_t>(input.begin(), input.end()), {}, {},
342 &out_keyParams, &o_put, input_consumed);
343
344 if (result.isOk()) {
345 if (o_put) {
346 output->append(o_put->data.begin(), o_put->data.end());
347 }
348
349 if (out_keyParams) {
350 out_params->push_back(AuthorizationSet(out_keyParams->params));
351 }
352 }
353
354 return GetReturnErrorCode(result);
355}
356
357ErrorCode KeyMintAidlTestBase::Update(const string& input, string* out, int32_t* input_consumed) {
358 SCOPED_TRACE("Update");
359 AuthorizationSet out_params;
360 ErrorCode result =
361 Update(AuthorizationSet() /* in_params */, input, &out_params, out, input_consumed);
362 EXPECT_TRUE(out_params.empty());
363 return result;
364}
365
366ErrorCode KeyMintAidlTestBase::Finish(const AuthorizationSet& in_params, const string& input,
367 const string& signature, AuthorizationSet* out_params,
368 string* output) {
369 SCOPED_TRACE("Finish");
370 Status result;
371
372 EXPECT_NE(op_, nullptr);
373 if (!op_) {
374 return ErrorCode::UNEXPECTED_NULL_POINTER;
375 }
376
377 KeyParameterArray key_params;
378 key_params.params = in_params.vector_data();
379
380 KeyParameterArray in_keyParams;
381 in_keyParams.params = in_params.vector_data();
382
383 optional<KeyParameterArray> out_keyParams;
384 optional<vector<uint8_t>> o_put;
385
386 vector<uint8_t> oPut;
387 result = op_->finish(in_keyParams, vector<uint8_t>(input.begin(), input.end()),
388 vector<uint8_t>(signature.begin(), signature.end()), {}, {},
389 &out_keyParams, &oPut);
390
391 if (result.isOk()) {
392 if (out_keyParams) {
393 out_params->push_back(AuthorizationSet(out_keyParams->params));
394 }
395
396 output->append(oPut.begin(), oPut.end());
397 }
398
Janis Danisevskis24c04702020-12-16 18:28:39 -0800399 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700400 return GetReturnErrorCode(result);
401}
402
403ErrorCode KeyMintAidlTestBase::Finish(const string& message, string* output) {
404 SCOPED_TRACE("Finish");
405 AuthorizationSet out_params;
406 string finish_output;
407 ErrorCode result = Finish(AuthorizationSet() /* in_params */, message, "" /* signature */,
408 &out_params, output);
409 if (result != ErrorCode::OK) {
410 return result;
411 }
412 EXPECT_EQ(0U, out_params.size());
413 return result;
414}
415
416ErrorCode KeyMintAidlTestBase::Finish(const string& message, const string& signature,
417 string* output) {
418 SCOPED_TRACE("Finish");
419 AuthorizationSet out_params;
420 ErrorCode result =
421 Finish(AuthorizationSet() /* in_params */, message, signature, &out_params, output);
422
423 if (result != ErrorCode::OK) {
424 return result;
425 }
426
427 EXPECT_EQ(0U, out_params.size());
428 return result;
429}
430
Janis Danisevskis24c04702020-12-16 18:28:39 -0800431ErrorCode KeyMintAidlTestBase::Abort(const std::shared_ptr<IKeyMintOperation>& op) {
Selene Huang31ab4042020-04-29 04:22:39 -0700432 SCOPED_TRACE("Abort");
433
434 EXPECT_NE(op, nullptr);
435 if (!op) {
436 return ErrorCode::UNEXPECTED_NULL_POINTER;
437 }
438
439 Status retval = op->abort();
440 EXPECT_TRUE(retval.isOk());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800441 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700442}
443
444ErrorCode KeyMintAidlTestBase::Abort() {
445 SCOPED_TRACE("Abort");
446
447 EXPECT_NE(op_, nullptr);
448 if (!op_) {
449 return ErrorCode::UNEXPECTED_NULL_POINTER;
450 }
451
452 Status retval = op_->abort();
Janis Danisevskis24c04702020-12-16 18:28:39 -0800453 return static_cast<ErrorCode>(retval.getServiceSpecificError());
Selene Huang31ab4042020-04-29 04:22:39 -0700454}
455
456void KeyMintAidlTestBase::AbortIfNeeded() {
457 SCOPED_TRACE("AbortIfNeeded");
458 if (op_) {
459 EXPECT_EQ(ErrorCode::OK, Abort());
Janis Danisevskis24c04702020-12-16 18:28:39 -0800460 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700461 }
462}
463
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000464auto KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
465 const string& message, const AuthorizationSet& in_params)
466 -> std::tuple<ErrorCode, string, AuthorizationSet /* out_params */> {
467 AuthorizationSet begin_out_params;
468 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
469 AuthorizationSet out_params(std::move(begin_out_params));
470 if (result != ErrorCode::OK) {
471 return {result, {}, out_params};
472 }
473
474 string output;
475 int32_t consumed = 0;
476 AuthorizationSet update_params;
477 AuthorizationSet update_out_params;
478 result = Update(update_params, message, &update_out_params, &output, &consumed);
479 out_params.push_back(update_out_params);
480 if (result != ErrorCode::OK) {
481 return {result, output, out_params};
482 }
483
484 string unused;
485 AuthorizationSet finish_params;
486 AuthorizationSet finish_out_params;
487 result = Finish(finish_params, message.substr(consumed), unused, &finish_out_params, &output);
488 out_params.push_back(finish_out_params);
489 return {result, output, out_params};
490}
491
Selene Huang31ab4042020-04-29 04:22:39 -0700492string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
493 const string& message, const AuthorizationSet& in_params,
494 AuthorizationSet* out_params) {
495 SCOPED_TRACE("ProcessMessage");
496 AuthorizationSet begin_out_params;
497 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
498 EXPECT_EQ(ErrorCode::OK, result);
499 if (result != ErrorCode::OK) {
500 return "";
501 }
502
503 string output;
504 int32_t consumed = 0;
505 AuthorizationSet update_params;
506 AuthorizationSet update_out_params;
507 result = Update(update_params, message, &update_out_params, &output, &consumed);
508 EXPECT_EQ(ErrorCode::OK, result);
509 if (result != ErrorCode::OK) {
510 return "";
511 }
512
513 string unused;
514 AuthorizationSet finish_params;
515 AuthorizationSet finish_out_params;
516 EXPECT_EQ(ErrorCode::OK,
517 Finish(finish_params, message.substr(consumed), unused, &finish_out_params, &output));
518
519 out_params->push_back(begin_out_params);
520 out_params->push_back(finish_out_params);
521 return output;
522}
523
524string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
525 const AuthorizationSet& params) {
526 SCOPED_TRACE("SignMessage");
527 AuthorizationSet out_params;
528 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
529 EXPECT_TRUE(out_params.empty());
530 return signature;
531}
532
533string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
534 SCOPED_TRACE("SignMessage");
535 return SignMessage(key_blob_, message, params);
536}
537
538string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
539 SCOPED_TRACE("MacMessage");
540 return SignMessage(
541 key_blob_, message,
542 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
543}
544
545void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
546 Digest digest, const string& expected_mac) {
547 SCOPED_TRACE("CheckHmacTestVector");
548 ASSERT_EQ(ErrorCode::OK,
549 ImportKey(AuthorizationSetBuilder()
550 .Authorization(TAG_NO_AUTH_REQUIRED)
551 .HmacKey(key.size() * 8)
552 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
553 .Digest(digest),
554 KeyFormat::RAW, key));
555 string signature = MacMessage(message, digest, expected_mac.size() * 8);
556 EXPECT_EQ(expected_mac, signature)
557 << "Test vector didn't match for key of size " << key.size() << " message of size "
558 << message.size() << " and digest " << digest;
559 CheckedDeleteKey();
560}
561
562void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
563 const string& message,
564 const string& expected_ciphertext) {
565 SCOPED_TRACE("CheckAesCtrTestVector");
566 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
567 .Authorization(TAG_NO_AUTH_REQUIRED)
568 .AesEncryptionKey(key.size() * 8)
569 .BlockMode(BlockMode::CTR)
570 .Authorization(TAG_CALLER_NONCE)
571 .Padding(PaddingMode::NONE),
572 KeyFormat::RAW, key));
573
574 auto params = AuthorizationSetBuilder()
575 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
576 .BlockMode(BlockMode::CTR)
577 .Padding(PaddingMode::NONE);
578 AuthorizationSet out_params;
579 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
580 EXPECT_EQ(expected_ciphertext, ciphertext);
581}
582
583void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
584 PaddingMode padding_mode, const string& key,
585 const string& iv, const string& input,
586 const string& expected_output) {
587 auto authset = AuthorizationSetBuilder()
588 .TripleDesEncryptionKey(key.size() * 7)
589 .BlockMode(block_mode)
590 .Authorization(TAG_NO_AUTH_REQUIRED)
591 .Padding(padding_mode);
592 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
593 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
594 ASSERT_GT(key_blob_.size(), 0U);
595
596 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
597 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
598 AuthorizationSet output_params;
599 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
600 EXPECT_EQ(expected_output, output);
601}
602
603void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
604 const string& signature, const AuthorizationSet& params) {
605 SCOPED_TRACE("VerifyMessage");
606 AuthorizationSet begin_out_params;
607 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
608
609 string output;
610 AuthorizationSet update_params;
611 AuthorizationSet update_out_params;
612 int32_t consumed;
613 ASSERT_EQ(ErrorCode::OK,
614 Update(update_params, message, &update_out_params, &output, &consumed));
615 EXPECT_TRUE(output.empty());
616 EXPECT_GT(consumed, 0U);
617
618 string unused;
619 AuthorizationSet finish_params;
620 AuthorizationSet finish_out_params;
621 EXPECT_EQ(ErrorCode::OK, Finish(finish_params, message.substr(consumed), signature,
622 &finish_out_params, &output));
Janis Danisevskis24c04702020-12-16 18:28:39 -0800623 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700624 EXPECT_TRUE(output.empty());
625}
626
627void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
628 const AuthorizationSet& params) {
629 SCOPED_TRACE("VerifyMessage");
630 VerifyMessage(key_blob_, message, signature, params);
631}
632
633string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
634 const AuthorizationSet& in_params,
635 AuthorizationSet* out_params) {
636 SCOPED_TRACE("EncryptMessage");
637 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
638}
639
640string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
641 AuthorizationSet* out_params) {
642 SCOPED_TRACE("EncryptMessage");
643 return EncryptMessage(key_blob_, message, params, out_params);
644}
645
646string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
647 SCOPED_TRACE("EncryptMessage");
648 AuthorizationSet out_params;
649 string ciphertext = EncryptMessage(message, params, &out_params);
650 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
651 return ciphertext;
652}
653
654string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
655 PaddingMode padding) {
656 SCOPED_TRACE("EncryptMessage");
657 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
658 AuthorizationSet out_params;
659 string ciphertext = EncryptMessage(message, params, &out_params);
660 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
661 return ciphertext;
662}
663
664string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
665 PaddingMode padding, vector<uint8_t>* iv_out) {
666 SCOPED_TRACE("EncryptMessage");
667 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
668 AuthorizationSet out_params;
669 string ciphertext = EncryptMessage(message, params, &out_params);
670 EXPECT_EQ(1U, out_params.size());
671 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800672 EXPECT_TRUE(ivVal);
673 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700674 return ciphertext;
675}
676
677string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
678 PaddingMode padding, const vector<uint8_t>& iv_in) {
679 SCOPED_TRACE("EncryptMessage");
680 auto params = AuthorizationSetBuilder()
681 .BlockMode(block_mode)
682 .Padding(padding)
683 .Authorization(TAG_NONCE, iv_in);
684 AuthorizationSet out_params;
685 string ciphertext = EncryptMessage(message, params, &out_params);
686 return ciphertext;
687}
688
689string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
690 PaddingMode padding, uint8_t mac_length_bits,
691 const vector<uint8_t>& iv_in) {
692 SCOPED_TRACE("EncryptMessage");
693 auto params = AuthorizationSetBuilder()
694 .BlockMode(block_mode)
695 .Padding(padding)
696 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
697 .Authorization(TAG_NONCE, iv_in);
698 AuthorizationSet out_params;
699 string ciphertext = EncryptMessage(message, params, &out_params);
700 return ciphertext;
701}
702
703string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
704 const string& ciphertext,
705 const AuthorizationSet& params) {
706 SCOPED_TRACE("DecryptMessage");
707 AuthorizationSet out_params;
708 string plaintext =
709 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
710 EXPECT_TRUE(out_params.empty());
711 return plaintext;
712}
713
714string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
715 const AuthorizationSet& params) {
716 SCOPED_TRACE("DecryptMessage");
717 return DecryptMessage(key_blob_, ciphertext, params);
718}
719
720string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
721 PaddingMode padding_mode, const vector<uint8_t>& iv) {
722 SCOPED_TRACE("DecryptMessage");
723 auto params = AuthorizationSetBuilder()
724 .BlockMode(block_mode)
725 .Padding(padding_mode)
726 .Authorization(TAG_NONCE, iv);
727 return DecryptMessage(key_blob_, ciphertext, params);
728}
729
730std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
731 const vector<uint8_t>& key_blob) {
732 std::pair<ErrorCode, vector<uint8_t>> retval;
733 vector<uint8_t> outKeyBlob;
734 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
735 ErrorCode errorcode = GetReturnErrorCode(result);
736 retval = std::tie(errorcode, outKeyBlob);
737
738 return retval;
739}
740vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
741 switch (algorithm) {
742 case Algorithm::RSA:
743 switch (SecLevel()) {
744 case SecurityLevel::SOFTWARE:
745 case SecurityLevel::TRUSTED_ENVIRONMENT:
746 return {2048, 3072, 4096};
747 case SecurityLevel::STRONGBOX:
748 return {2048};
749 default:
750 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
751 break;
752 }
753 break;
754 case Algorithm::EC:
755 switch (SecLevel()) {
756 case SecurityLevel::SOFTWARE:
757 case SecurityLevel::TRUSTED_ENVIRONMENT:
758 return {224, 256, 384, 521};
759 case SecurityLevel::STRONGBOX:
760 return {256};
761 default:
762 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
763 break;
764 }
765 break;
766 case Algorithm::AES:
767 return {128, 256};
768 case Algorithm::TRIPLE_DES:
769 return {168};
770 case Algorithm::HMAC: {
771 vector<uint32_t> retval((512 - 64) / 8 + 1);
772 uint32_t size = 64 - 8;
773 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
774 return retval;
775 }
776 default:
777 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
778 return {};
779 }
780 ADD_FAILURE() << "Should be impossible to get here";
781 return {};
782}
783
784vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
785 if (SecLevel() == SecurityLevel::STRONGBOX) {
786 switch (algorithm) {
787 case Algorithm::RSA:
788 return {3072, 4096};
789 case Algorithm::EC:
790 return {224, 384, 521};
791 case Algorithm::AES:
792 return {192};
793 default:
794 return {};
795 }
796 }
797 return {};
798}
799
800vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
801 if (securityLevel_ == SecurityLevel::STRONGBOX) {
802 return {EcCurve::P_256};
803 } else {
804 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
805 }
806}
807
808vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
809 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
810 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
811 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
812}
813
814vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
815 switch (SecLevel()) {
816 case SecurityLevel::SOFTWARE:
817 case SecurityLevel::TRUSTED_ENVIRONMENT:
818 if (withNone) {
819 if (withMD5)
820 return {Digest::NONE, Digest::MD5, Digest::SHA1,
821 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
822 Digest::SHA_2_512};
823 else
824 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
825 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
826 } else {
827 if (withMD5)
828 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
829 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
830 else
831 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
832 Digest::SHA_2_512};
833 }
834 break;
835 case SecurityLevel::STRONGBOX:
836 if (withNone)
837 return {Digest::NONE, Digest::SHA_2_256};
838 else
839 return {Digest::SHA_2_256};
840 break;
841 default:
842 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
843 break;
844 }
845 ADD_FAILURE() << "Should be impossible to get here";
846 return {};
847}
848
Shawn Willden7f424372021-01-10 18:06:50 -0700849static const vector<KeyParameter> kEmptyAuthList{};
850
851const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
852 const vector<KeyCharacteristics>& key_characteristics) {
853 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
854 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
855 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
856}
857
Qi Wubeefae42021-01-28 23:16:37 +0800858const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
859 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
860 auto found = std::find_if(
861 key_characteristics.begin(), key_characteristics.end(),
862 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700863 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
864}
865
Qi Wubeefae42021-01-28 23:16:37 +0800866AuthorizationSet KeyMintAidlTestBase::HwEnforcedAuthorizations(
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700867 const vector<KeyCharacteristics>& key_characteristics) {
Qi Wubeefae42021-01-28 23:16:37 +0800868 AuthorizationSet authList;
869 for (auto& entry : key_characteristics) {
870 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
871 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
872 authList.push_back(AuthorizationSet(entry.authorizations));
873 }
874 }
875 return authList;
876}
877
878AuthorizationSet KeyMintAidlTestBase::SwEnforcedAuthorizations(
879 const vector<KeyCharacteristics>& key_characteristics) {
880 AuthorizationSet authList;
881 for (auto& entry : key_characteristics) {
882 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
883 entry.securityLevel == SecurityLevel::KEYSTORE) {
884 authList.push_back(AuthorizationSet(entry.authorizations));
885 }
886 }
887 return authList;
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700888}
889
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000890ErrorCode KeyMintAidlTestBase::UseAesKey(const vector<uint8_t>& aesKeyBlob) {
891 auto [result, ciphertext, out_params] = ProcessMessage(
892 aesKeyBlob, KeyPurpose::ENCRYPT, "1234567890123456",
893 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE));
894 return result;
895}
896
897ErrorCode KeyMintAidlTestBase::UseHmacKey(const vector<uint8_t>& hmacKeyBlob) {
898 auto [result, mac, out_params] = ProcessMessage(
899 hmacKeyBlob, KeyPurpose::SIGN, "1234567890123456",
900 AuthorizationSetBuilder().Authorization(TAG_MAC_LENGTH, 128).Digest(Digest::SHA_2_256));
901 return result;
902}
903
904ErrorCode KeyMintAidlTestBase::UseRsaKey(const vector<uint8_t>& rsaKeyBlob) {
905 std::string message(2048 / 8, 'a');
906 auto [result, signature, out_params] = ProcessMessage(
907 rsaKeyBlob, KeyPurpose::SIGN, message,
908 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
909 return result;
910}
911
912ErrorCode KeyMintAidlTestBase::UseEcdsaKey(const vector<uint8_t>& ecdsaKeyBlob) {
913 auto [result, signature, out_params] =
914 ProcessMessage(ecdsaKeyBlob, KeyPurpose::SIGN, "a",
915 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
916 return result;
917}
918
Selene Huang31ab4042020-04-29 04:22:39 -0700919} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +0000920
Janis Danisevskis24c04702020-12-16 18:28:39 -0800921} // namespace aidl::android::hardware::security::keymint