blob: 6555157e5ca9ac9fafa2995f5b71efb79696d534 [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
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
464string KeyMintAidlTestBase::ProcessMessage(const vector<uint8_t>& key_blob, KeyPurpose operation,
465 const string& message, const AuthorizationSet& in_params,
466 AuthorizationSet* out_params) {
467 SCOPED_TRACE("ProcessMessage");
468 AuthorizationSet begin_out_params;
469 ErrorCode result = Begin(operation, key_blob, in_params, &begin_out_params);
470 EXPECT_EQ(ErrorCode::OK, result);
471 if (result != ErrorCode::OK) {
472 return "";
473 }
474
475 string output;
476 int32_t consumed = 0;
477 AuthorizationSet update_params;
478 AuthorizationSet update_out_params;
479 result = Update(update_params, message, &update_out_params, &output, &consumed);
480 EXPECT_EQ(ErrorCode::OK, result);
481 if (result != ErrorCode::OK) {
482 return "";
483 }
484
485 string unused;
486 AuthorizationSet finish_params;
487 AuthorizationSet finish_out_params;
488 EXPECT_EQ(ErrorCode::OK,
489 Finish(finish_params, message.substr(consumed), unused, &finish_out_params, &output));
490
491 out_params->push_back(begin_out_params);
492 out_params->push_back(finish_out_params);
493 return output;
494}
495
496string KeyMintAidlTestBase::SignMessage(const vector<uint8_t>& key_blob, const string& message,
497 const AuthorizationSet& params) {
498 SCOPED_TRACE("SignMessage");
499 AuthorizationSet out_params;
500 string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
501 EXPECT_TRUE(out_params.empty());
502 return signature;
503}
504
505string KeyMintAidlTestBase::SignMessage(const string& message, const AuthorizationSet& params) {
506 SCOPED_TRACE("SignMessage");
507 return SignMessage(key_blob_, message, params);
508}
509
510string KeyMintAidlTestBase::MacMessage(const string& message, Digest digest, size_t mac_length) {
511 SCOPED_TRACE("MacMessage");
512 return SignMessage(
513 key_blob_, message,
514 AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
515}
516
517void KeyMintAidlTestBase::CheckHmacTestVector(const string& key, const string& message,
518 Digest digest, const string& expected_mac) {
519 SCOPED_TRACE("CheckHmacTestVector");
520 ASSERT_EQ(ErrorCode::OK,
521 ImportKey(AuthorizationSetBuilder()
522 .Authorization(TAG_NO_AUTH_REQUIRED)
523 .HmacKey(key.size() * 8)
524 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
525 .Digest(digest),
526 KeyFormat::RAW, key));
527 string signature = MacMessage(message, digest, expected_mac.size() * 8);
528 EXPECT_EQ(expected_mac, signature)
529 << "Test vector didn't match for key of size " << key.size() << " message of size "
530 << message.size() << " and digest " << digest;
531 CheckedDeleteKey();
532}
533
534void KeyMintAidlTestBase::CheckAesCtrTestVector(const string& key, const string& nonce,
535 const string& message,
536 const string& expected_ciphertext) {
537 SCOPED_TRACE("CheckAesCtrTestVector");
538 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
539 .Authorization(TAG_NO_AUTH_REQUIRED)
540 .AesEncryptionKey(key.size() * 8)
541 .BlockMode(BlockMode::CTR)
542 .Authorization(TAG_CALLER_NONCE)
543 .Padding(PaddingMode::NONE),
544 KeyFormat::RAW, key));
545
546 auto params = AuthorizationSetBuilder()
547 .Authorization(TAG_NONCE, nonce.data(), nonce.size())
548 .BlockMode(BlockMode::CTR)
549 .Padding(PaddingMode::NONE);
550 AuthorizationSet out_params;
551 string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
552 EXPECT_EQ(expected_ciphertext, ciphertext);
553}
554
555void KeyMintAidlTestBase::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
556 PaddingMode padding_mode, const string& key,
557 const string& iv, const string& input,
558 const string& expected_output) {
559 auto authset = AuthorizationSetBuilder()
560 .TripleDesEncryptionKey(key.size() * 7)
561 .BlockMode(block_mode)
562 .Authorization(TAG_NO_AUTH_REQUIRED)
563 .Padding(padding_mode);
564 if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
565 ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
566 ASSERT_GT(key_blob_.size(), 0U);
567
568 auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
569 if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
570 AuthorizationSet output_params;
571 string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
572 EXPECT_EQ(expected_output, output);
573}
574
575void KeyMintAidlTestBase::VerifyMessage(const vector<uint8_t>& key_blob, const string& message,
576 const string& signature, const AuthorizationSet& params) {
577 SCOPED_TRACE("VerifyMessage");
578 AuthorizationSet begin_out_params;
579 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params));
580
581 string output;
582 AuthorizationSet update_params;
583 AuthorizationSet update_out_params;
584 int32_t consumed;
585 ASSERT_EQ(ErrorCode::OK,
586 Update(update_params, message, &update_out_params, &output, &consumed));
587 EXPECT_TRUE(output.empty());
588 EXPECT_GT(consumed, 0U);
589
590 string unused;
591 AuthorizationSet finish_params;
592 AuthorizationSet finish_out_params;
593 EXPECT_EQ(ErrorCode::OK, Finish(finish_params, message.substr(consumed), signature,
594 &finish_out_params, &output));
Janis Danisevskis24c04702020-12-16 18:28:39 -0800595 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -0700596 EXPECT_TRUE(output.empty());
597}
598
599void KeyMintAidlTestBase::VerifyMessage(const string& message, const string& signature,
600 const AuthorizationSet& params) {
601 SCOPED_TRACE("VerifyMessage");
602 VerifyMessage(key_blob_, message, signature, params);
603}
604
605string KeyMintAidlTestBase::EncryptMessage(const vector<uint8_t>& key_blob, const string& message,
606 const AuthorizationSet& in_params,
607 AuthorizationSet* out_params) {
608 SCOPED_TRACE("EncryptMessage");
609 return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
610}
611
612string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params,
613 AuthorizationSet* out_params) {
614 SCOPED_TRACE("EncryptMessage");
615 return EncryptMessage(key_blob_, message, params, out_params);
616}
617
618string KeyMintAidlTestBase::EncryptMessage(const string& message, const AuthorizationSet& params) {
619 SCOPED_TRACE("EncryptMessage");
620 AuthorizationSet out_params;
621 string ciphertext = EncryptMessage(message, params, &out_params);
622 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
623 return ciphertext;
624}
625
626string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
627 PaddingMode padding) {
628 SCOPED_TRACE("EncryptMessage");
629 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
630 AuthorizationSet out_params;
631 string ciphertext = EncryptMessage(message, params, &out_params);
632 EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
633 return ciphertext;
634}
635
636string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
637 PaddingMode padding, vector<uint8_t>* iv_out) {
638 SCOPED_TRACE("EncryptMessage");
639 auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
640 AuthorizationSet out_params;
641 string ciphertext = EncryptMessage(message, params, &out_params);
642 EXPECT_EQ(1U, out_params.size());
643 auto ivVal = out_params.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -0800644 EXPECT_TRUE(ivVal);
645 if (ivVal) *iv_out = *ivVal;
Selene Huang31ab4042020-04-29 04:22:39 -0700646 return ciphertext;
647}
648
649string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
650 PaddingMode padding, const vector<uint8_t>& iv_in) {
651 SCOPED_TRACE("EncryptMessage");
652 auto params = AuthorizationSetBuilder()
653 .BlockMode(block_mode)
654 .Padding(padding)
655 .Authorization(TAG_NONCE, iv_in);
656 AuthorizationSet out_params;
657 string ciphertext = EncryptMessage(message, params, &out_params);
658 return ciphertext;
659}
660
661string KeyMintAidlTestBase::EncryptMessage(const string& message, BlockMode block_mode,
662 PaddingMode padding, uint8_t mac_length_bits,
663 const vector<uint8_t>& iv_in) {
664 SCOPED_TRACE("EncryptMessage");
665 auto params = AuthorizationSetBuilder()
666 .BlockMode(block_mode)
667 .Padding(padding)
668 .Authorization(TAG_MAC_LENGTH, mac_length_bits)
669 .Authorization(TAG_NONCE, iv_in);
670 AuthorizationSet out_params;
671 string ciphertext = EncryptMessage(message, params, &out_params);
672 return ciphertext;
673}
674
675string KeyMintAidlTestBase::DecryptMessage(const vector<uint8_t>& key_blob,
676 const string& ciphertext,
677 const AuthorizationSet& params) {
678 SCOPED_TRACE("DecryptMessage");
679 AuthorizationSet out_params;
680 string plaintext =
681 ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
682 EXPECT_TRUE(out_params.empty());
683 return plaintext;
684}
685
686string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext,
687 const AuthorizationSet& params) {
688 SCOPED_TRACE("DecryptMessage");
689 return DecryptMessage(key_blob_, ciphertext, params);
690}
691
692string KeyMintAidlTestBase::DecryptMessage(const string& ciphertext, BlockMode block_mode,
693 PaddingMode padding_mode, const vector<uint8_t>& iv) {
694 SCOPED_TRACE("DecryptMessage");
695 auto params = AuthorizationSetBuilder()
696 .BlockMode(block_mode)
697 .Padding(padding_mode)
698 .Authorization(TAG_NONCE, iv);
699 return DecryptMessage(key_blob_, ciphertext, params);
700}
701
702std::pair<ErrorCode, vector<uint8_t>> KeyMintAidlTestBase::UpgradeKey(
703 const vector<uint8_t>& key_blob) {
704 std::pair<ErrorCode, vector<uint8_t>> retval;
705 vector<uint8_t> outKeyBlob;
706 Status result = keymint_->upgradeKey(key_blob, vector<KeyParameter>(), &outKeyBlob);
707 ErrorCode errorcode = GetReturnErrorCode(result);
708 retval = std::tie(errorcode, outKeyBlob);
709
710 return retval;
711}
712vector<uint32_t> KeyMintAidlTestBase::ValidKeySizes(Algorithm algorithm) {
713 switch (algorithm) {
714 case Algorithm::RSA:
715 switch (SecLevel()) {
716 case SecurityLevel::SOFTWARE:
717 case SecurityLevel::TRUSTED_ENVIRONMENT:
718 return {2048, 3072, 4096};
719 case SecurityLevel::STRONGBOX:
720 return {2048};
721 default:
722 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
723 break;
724 }
725 break;
726 case Algorithm::EC:
727 switch (SecLevel()) {
728 case SecurityLevel::SOFTWARE:
729 case SecurityLevel::TRUSTED_ENVIRONMENT:
730 return {224, 256, 384, 521};
731 case SecurityLevel::STRONGBOX:
732 return {256};
733 default:
734 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
735 break;
736 }
737 break;
738 case Algorithm::AES:
739 return {128, 256};
740 case Algorithm::TRIPLE_DES:
741 return {168};
742 case Algorithm::HMAC: {
743 vector<uint32_t> retval((512 - 64) / 8 + 1);
744 uint32_t size = 64 - 8;
745 std::generate(retval.begin(), retval.end(), [&]() { return (size += 8); });
746 return retval;
747 }
748 default:
749 ADD_FAILURE() << "Invalid Algorithm: " << algorithm;
750 return {};
751 }
752 ADD_FAILURE() << "Should be impossible to get here";
753 return {};
754}
755
756vector<uint32_t> KeyMintAidlTestBase::InvalidKeySizes(Algorithm algorithm) {
757 if (SecLevel() == SecurityLevel::STRONGBOX) {
758 switch (algorithm) {
759 case Algorithm::RSA:
760 return {3072, 4096};
761 case Algorithm::EC:
762 return {224, 384, 521};
763 case Algorithm::AES:
764 return {192};
765 default:
766 return {};
767 }
768 }
769 return {};
770}
771
772vector<EcCurve> KeyMintAidlTestBase::ValidCurves() {
773 if (securityLevel_ == SecurityLevel::STRONGBOX) {
774 return {EcCurve::P_256};
775 } else {
776 return {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
777 }
778}
779
780vector<EcCurve> KeyMintAidlTestBase::InvalidCurves() {
781 if (SecLevel() == SecurityLevel::TRUSTED_ENVIRONMENT) return {};
782 CHECK(SecLevel() == SecurityLevel::STRONGBOX);
783 return {EcCurve::P_224, EcCurve::P_384, EcCurve::P_521};
784}
785
786vector<Digest> KeyMintAidlTestBase::ValidDigests(bool withNone, bool withMD5) {
787 switch (SecLevel()) {
788 case SecurityLevel::SOFTWARE:
789 case SecurityLevel::TRUSTED_ENVIRONMENT:
790 if (withNone) {
791 if (withMD5)
792 return {Digest::NONE, Digest::MD5, Digest::SHA1,
793 Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
794 Digest::SHA_2_512};
795 else
796 return {Digest::NONE, Digest::SHA1, Digest::SHA_2_224,
797 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
798 } else {
799 if (withMD5)
800 return {Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
801 Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
802 else
803 return {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
804 Digest::SHA_2_512};
805 }
806 break;
807 case SecurityLevel::STRONGBOX:
808 if (withNone)
809 return {Digest::NONE, Digest::SHA_2_256};
810 else
811 return {Digest::SHA_2_256};
812 break;
813 default:
814 ADD_FAILURE() << "Invalid security level " << uint32_t(SecLevel());
815 break;
816 }
817 ADD_FAILURE() << "Should be impossible to get here";
818 return {};
819}
820
Shawn Willden7f424372021-01-10 18:06:50 -0700821static const vector<KeyParameter> kEmptyAuthList{};
822
823const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
824 const vector<KeyCharacteristics>& key_characteristics) {
825 auto found = std::find_if(key_characteristics.begin(), key_characteristics.end(),
826 [this](auto& entry) { return entry.securityLevel == SecLevel(); });
827 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
828}
829
Qi Wubeefae42021-01-28 23:16:37 +0800830const vector<KeyParameter>& KeyMintAidlTestBase::SecLevelAuthorizations(
831 const vector<KeyCharacteristics>& key_characteristics, SecurityLevel securityLevel) {
832 auto found = std::find_if(
833 key_characteristics.begin(), key_characteristics.end(),
834 [securityLevel](auto& entry) { return entry.securityLevel == securityLevel; });
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700835 return (found == key_characteristics.end()) ? kEmptyAuthList : found->authorizations;
836}
837
Qi Wubeefae42021-01-28 23:16:37 +0800838AuthorizationSet KeyMintAidlTestBase::HwEnforcedAuthorizations(
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700839 const vector<KeyCharacteristics>& key_characteristics) {
Qi Wubeefae42021-01-28 23:16:37 +0800840 AuthorizationSet authList;
841 for (auto& entry : key_characteristics) {
842 if (entry.securityLevel == SecurityLevel::STRONGBOX ||
843 entry.securityLevel == SecurityLevel::TRUSTED_ENVIRONMENT) {
844 authList.push_back(AuthorizationSet(entry.authorizations));
845 }
846 }
847 return authList;
848}
849
850AuthorizationSet KeyMintAidlTestBase::SwEnforcedAuthorizations(
851 const vector<KeyCharacteristics>& key_characteristics) {
852 AuthorizationSet authList;
853 for (auto& entry : key_characteristics) {
854 if (entry.securityLevel == SecurityLevel::SOFTWARE ||
855 entry.securityLevel == SecurityLevel::KEYSTORE) {
856 authList.push_back(AuthorizationSet(entry.authorizations));
857 }
858 }
859 return authList;
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700860}
861
Selene Huang31ab4042020-04-29 04:22:39 -0700862} // namespace test
Shawn Willden08a7e432020-12-11 13:05:27 +0000863
Janis Danisevskis24c04702020-12-16 18:28:39 -0800864} // namespace aidl::android::hardware::security::keymint