blob: 829780d442c79a83ec8f72117d2bee2934549814 [file] [log] [blame]
Shawn Willden274bb552020-09-30 22:39:22 -06001/*
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#define LOG_TAG "VtsRemotelyProvisionableComponentTests"
18
Max Bires261a0492021-04-19 18:55:56 -070019#include <AndroidRemotelyProvisionedComponentDevice.h>
Shawn Willden274bb552020-09-30 22:39:22 -060020#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
21#include <aidl/android/hardware/security/keymint/SecurityLevel.h>
22#include <android/binder_manager.h>
Seth Moorefc86bf42021-12-09 14:07:04 -080023#include <binder/IServiceManager.h>
Shawn Willden274bb552020-09-30 22:39:22 -060024#include <cppbor_parse.h>
Shawn Willden274bb552020-09-30 22:39:22 -060025#include <gmock/gmock.h>
Max Bires9704ff62021-04-07 11:12:01 -070026#include <keymaster/cppcose/cppcose.h>
Shawn Willden274bb552020-09-30 22:39:22 -060027#include <keymaster/keymaster_configuration.h>
David Drysdalef0d516d2021-03-22 07:51:43 +000028#include <keymint_support/authorization_set.h>
29#include <openssl/ec.h>
30#include <openssl/ec_key.h>
31#include <openssl/x509.h>
Shawn Willden274bb552020-09-30 22:39:22 -060032#include <remote_prov/remote_prov_utils.h>
Seth Moorefc86bf42021-12-09 14:07:04 -080033#include <set>
Seth Moore42c11332021-07-02 15:38:17 -070034#include <vector>
Shawn Willden274bb552020-09-30 22:39:22 -060035
David Drysdalef0d516d2021-03-22 07:51:43 +000036#include "KeyMintAidlTestBase.h"
37
Shawn Willden274bb552020-09-30 22:39:22 -060038namespace aidl::android::hardware::security::keymint::test {
39
40using ::std::string;
41using ::std::vector;
42
43namespace {
44
Seth Moorefc86bf42021-12-09 14:07:04 -080045constexpr int32_t VERSION_WITH_UNIQUE_ID_SUPPORT = 2;
46
Shawn Willden274bb552020-09-30 22:39:22 -060047#define INSTANTIATE_REM_PROV_AIDL_TEST(name) \
Seth Moore6305e232021-07-27 14:20:17 -070048 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name); \
Shawn Willden274bb552020-09-30 22:39:22 -060049 INSTANTIATE_TEST_SUITE_P( \
50 PerInstance, name, \
51 testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
52 ::android::PrintInstanceNameToString)
53
Seth Moorefc86bf42021-12-09 14:07:04 -080054using ::android::sp;
Shawn Willden274bb552020-09-30 22:39:22 -060055using bytevec = std::vector<uint8_t>;
56using testing::MatchesRegex;
57using namespace remote_prov;
58using namespace keymaster;
59
60bytevec string_to_bytevec(const char* s) {
61 const uint8_t* p = reinterpret_cast<const uint8_t*>(s);
62 return bytevec(p, p + strlen(s));
63}
64
David Drysdalee99ed862021-03-15 16:43:06 +000065ErrMsgOr<MacedPublicKey> corrupt_maced_key(const MacedPublicKey& macedPubKey) {
66 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
67 if (!coseMac0 || coseMac0->asArray()->size() != kCoseMac0EntryCount) {
68 return "COSE Mac0 parse failed";
69 }
70 auto protParams = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
71 auto unprotParams = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
72 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
73 auto tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
74 if (!protParams || !unprotParams || !payload || !tag) {
75 return "Invalid COSE_Sign1: missing content";
76 }
77 auto corruptMac0 = cppbor::Array();
78 corruptMac0.add(protParams->clone());
79 corruptMac0.add(unprotParams->clone());
80 corruptMac0.add(payload->clone());
81 vector<uint8_t> tagData = tag->value();
82 tagData[0] ^= 0x08;
83 tagData[tagData.size() - 1] ^= 0x80;
84 corruptMac0.add(cppbor::Bstr(tagData));
85
86 return MacedPublicKey{corruptMac0.encode()};
87}
88
David Drysdalecceca9f2021-03-12 15:49:47 +000089ErrMsgOr<cppbor::Array> corrupt_sig(const cppbor::Array* coseSign1) {
90 if (coseSign1->size() != kCoseSign1EntryCount) {
91 return "Invalid COSE_Sign1, wrong entry count";
92 }
93 const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
94 const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
95 const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
96 const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
97 if (!protectedParams || !unprotectedParams || !payload || !signature) {
98 return "Invalid COSE_Sign1: missing content";
99 }
100
101 auto corruptSig = cppbor::Array();
102 corruptSig.add(protectedParams->clone());
103 corruptSig.add(unprotectedParams->clone());
104 corruptSig.add(payload->clone());
105 vector<uint8_t> sigData = signature->value();
106 sigData[0] ^= 0x08;
107 corruptSig.add(cppbor::Bstr(sigData));
108
109 return std::move(corruptSig);
110}
111
Seth Moore19acbe92021-06-23 15:15:52 -0700112ErrMsgOr<bytevec> corrupt_sig_chain(const bytevec& encodedEekChain, int which) {
113 auto [chain, _, parseErr] = cppbor::parse(encodedEekChain);
David Drysdalecceca9f2021-03-12 15:49:47 +0000114 if (!chain || !chain->asArray()) {
115 return "EekChain parse failed";
116 }
117
118 cppbor::Array* eekChain = chain->asArray();
119 if (which >= eekChain->size()) {
120 return "selected sig out of range";
121 }
122 auto corruptChain = cppbor::Array();
123
124 for (int ii = 0; ii < eekChain->size(); ++ii) {
125 if (ii == which) {
126 auto sig = corrupt_sig(eekChain->get(which)->asArray());
127 if (!sig) {
128 return "Failed to build corrupted signature" + sig.moveMessage();
129 }
130 corruptChain.add(sig.moveValue());
131 } else {
132 corruptChain.add(eekChain->get(ii)->clone());
133 }
134 }
Seth Moore19acbe92021-06-23 15:15:52 -0700135 return corruptChain.encode();
David Drysdalecceca9f2021-03-12 15:49:47 +0000136}
137
David Drysdale4d3c2982021-03-31 18:21:40 +0100138string device_suffix(const string& name) {
139 size_t pos = name.find('/');
140 if (pos == string::npos) {
141 return name;
142 }
143 return name.substr(pos + 1);
144}
145
146bool matching_keymint_device(const string& rp_name, std::shared_ptr<IKeyMintDevice>* keyMint) {
147 string rp_suffix = device_suffix(rp_name);
148
149 vector<string> km_names = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
150 for (const string& km_name : km_names) {
151 // If the suffix of the KeyMint instance equals the suffix of the
152 // RemotelyProvisionedComponent instance, assume they match.
153 if (device_suffix(km_name) == rp_suffix && AServiceManager_isDeclared(km_name.c_str())) {
154 ::ndk::SpAIBinder binder(AServiceManager_waitForService(km_name.c_str()));
155 *keyMint = IKeyMintDevice::fromBinder(binder);
156 return true;
157 }
158 }
159 return false;
160}
161
Shawn Willden274bb552020-09-30 22:39:22 -0600162} // namespace
163
164class VtsRemotelyProvisionedComponentTests : public testing::TestWithParam<std::string> {
165 public:
166 virtual void SetUp() override {
167 if (AServiceManager_isDeclared(GetParam().c_str())) {
168 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
169 provisionable_ = IRemotelyProvisionedComponent::fromBinder(binder);
170 }
171 ASSERT_NE(provisionable_, nullptr);
172 }
173
174 static vector<string> build_params() {
175 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
176 return params;
177 }
178
179 protected:
180 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
181};
182
Seth Moorefc86bf42021-12-09 14:07:04 -0800183/**
184 * Verify that every implementation reports a different unique id.
185 */
186TEST(NonParameterizedTests, eachRpcHasAUniqueId) {
187 std::set<std::string> uniqueIds;
188 for (auto hal : ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor)) {
189 ASSERT_TRUE(AServiceManager_isDeclared(hal.c_str()));
190 ::ndk::SpAIBinder binder(AServiceManager_waitForService(hal.c_str()));
191 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
192 IRemotelyProvisionedComponent::fromBinder(binder);
193 ASSERT_NE(rpc, nullptr);
194
195 RpcHardwareInfo hwInfo;
196 ASSERT_TRUE(rpc->getHardwareInfo(&hwInfo).isOk());
197
198 int32_t version;
199 ASSERT_TRUE(rpc->getInterfaceVersion(&version).isOk());
200 if (version >= VERSION_WITH_UNIQUE_ID_SUPPORT) {
201 ASSERT_TRUE(hwInfo.uniqueId);
202 auto [_, wasInserted] = uniqueIds.insert(*hwInfo.uniqueId);
203 EXPECT_TRUE(wasInserted);
204 } else {
205 ASSERT_FALSE(hwInfo.uniqueId);
206 }
207 }
208}
209
210using GetHardwareInfoTests = VtsRemotelyProvisionedComponentTests;
211
212INSTANTIATE_REM_PROV_AIDL_TEST(GetHardwareInfoTests);
213
214/**
215 * Verify that a valid curve is reported by the implementation.
216 */
217TEST_P(GetHardwareInfoTests, supportsValidCurve) {
218 RpcHardwareInfo hwInfo;
219 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
220
221 const std::set<int> validCurves = {RpcHardwareInfo::CURVE_P256, RpcHardwareInfo::CURVE_25519};
222 ASSERT_EQ(validCurves.count(hwInfo.supportedEekCurve), 1)
223 << "Invalid curve: " << hwInfo.supportedEekCurve;
224}
225
226/**
227 * Verify that the unique id is within the length limits as described in RpcHardwareInfo.aidl.
228 */
229TEST_P(GetHardwareInfoTests, uniqueId) {
230 int32_t version;
231 ASSERT_TRUE(provisionable_->getInterfaceVersion(&version).isOk());
232
233 if (version < VERSION_WITH_UNIQUE_ID_SUPPORT) {
234 return;
235 }
236
237 RpcHardwareInfo hwInfo;
238 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
239 ASSERT_TRUE(hwInfo.uniqueId);
240 EXPECT_GE(hwInfo.uniqueId->size(), 1);
241 EXPECT_LE(hwInfo.uniqueId->size(), 32);
242}
243
Shawn Willden274bb552020-09-30 22:39:22 -0600244using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
245
246INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
247
248/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000249 * Generate and validate a production-mode key. MAC tag can't be verified, but
250 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600251 */
Max Bires126869a2021-02-21 18:32:59 -0800252TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600253 MacedPublicKey macedPubKey;
254 bytevec privateKeyBlob;
255 bool testMode = false;
256 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
257 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000258 vector<uint8_t> coseKeyData;
259 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100260}
261
262/**
263 * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
264 */
265TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
266 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
267 std::shared_ptr<IKeyMintDevice> keyMint;
268 if (!matching_keymint_device(GetParam(), &keyMint)) {
269 // No matching IKeyMintDevice.
270 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
271 return;
272 }
273 KeyMintHardwareInfo info;
274 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
275
276 MacedPublicKey macedPubKey;
277 bytevec privateKeyBlob;
278 bool testMode = false;
279 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
280 ASSERT_TRUE(status.isOk());
281 vector<uint8_t> coseKeyData;
282 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
283
David Drysdalef0d516d2021-03-22 07:51:43 +0000284 AttestationKey attestKey;
285 attestKey.keyBlob = std::move(privateKeyBlob);
286 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600287
David Drysdalef0d516d2021-03-22 07:51:43 +0000288 // Generate an ECDSA key that is attested by the generated P256 keypair.
289 AuthorizationSet keyDesc = AuthorizationSetBuilder()
290 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale915ce252021-10-14 15:17:36 +0100291 .EcdsaSigningKey(EcCurve::P_256)
David Drysdalef0d516d2021-03-22 07:51:43 +0000292 .AttestationChallenge("foo")
293 .AttestationApplicationId("bar")
294 .Digest(Digest::NONE)
295 .SetDefaultValidity();
296 KeyCreationResult creationResult;
297 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
298 ASSERT_TRUE(result.isOk());
299 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
300 vector<KeyCharacteristics> attested_key_characteristics =
301 std::move(creationResult.keyCharacteristics);
302 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
303 EXPECT_EQ(attested_key_cert_chain.size(), 1);
304
David Drysdale7dff4fc2021-12-10 10:10:52 +0000305 int32_t aidl_version = 0;
306 ASSERT_TRUE(keyMint->getInterfaceVersion(&aidl_version).isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000307 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
308 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +0000309 EXPECT_TRUE(verify_attestation_record(aidl_version, "foo", "bar", sw_enforced, hw_enforced,
David Drysdalef0d516d2021-03-22 07:51:43 +0000310 info.securityLevel,
311 attested_key_cert_chain[0].encodedCertificate));
312
313 // Attestation by itself is not valid (last entry is not self-signed).
314 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
315
316 // The signature over the attested key should correspond to the P256 public key.
317 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
318 ASSERT_TRUE(key_cert.get());
319 EVP_PKEY_Ptr signing_pubkey;
320 p256_pub_key(coseKeyData, &signing_pubkey);
321 ASSERT_TRUE(signing_pubkey.get());
322
323 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
324 << "Verification of attested certificate failed "
325 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600326}
327
328/**
329 * Generate and validate a test-mode key.
330 */
Max Bires126869a2021-02-21 18:32:59 -0800331TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600332 MacedPublicKey macedPubKey;
333 bytevec privateKeyBlob;
334 bool testMode = true;
335 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
336 ASSERT_TRUE(status.isOk());
337
David Drysdalec8400772021-03-11 12:35:11 +0000338 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600339}
340
341class CertificateRequestTest : public VtsRemotelyProvisionedComponentTests {
342 protected:
David Drysdalec8400772021-03-11 12:35:11 +0000343 CertificateRequestTest() : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(32)) {
Seth Moore19acbe92021-06-23 15:15:52 -0700344 generateTestEekChain(3);
David Drysdalecceca9f2021-03-12 15:49:47 +0000345 }
346
Seth Moore19acbe92021-06-23 15:15:52 -0700347 void generateTestEekChain(size_t eekLength) {
David Drysdalecceca9f2021-03-12 15:49:47 +0000348 auto chain = generateEekChain(eekLength, eekId_);
Shawn Willden274bb552020-09-30 22:39:22 -0600349 EXPECT_TRUE(chain) << chain.message();
Seth Moore19acbe92021-06-23 15:15:52 -0700350 if (chain) testEekChain_ = chain.moveValue();
351 testEekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600352 }
353
354 void generateKeys(bool testMode, size_t numKeys) {
355 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
356 cborKeysToSign_ = cppbor::Array();
357
358 for (auto& key : keysToSign_) {
359 bytevec privateKeyBlob;
360 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
361 ASSERT_TRUE(status.isOk()) << status.getMessage();
362
David Drysdalec8400772021-03-11 12:35:11 +0000363 vector<uint8_t> payload_value;
364 check_maced_pubkey(key, testMode, &payload_value);
365 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600366 }
367 }
368
David Drysdalef6fc5a62021-03-31 16:14:31 +0100369 void checkProtectedData(const DeviceInfo& deviceInfo, const cppbor::Array& keysToSign,
Seth Moore42c11332021-07-02 15:38:17 -0700370 const bytevec& keysToSignMac, const ProtectedData& protectedData,
371 std::vector<BccEntryData>* bccOutput = nullptr) {
David Drysdalec8400772021-03-11 12:35:11 +0000372 auto [parsedProtectedData, _, protDataErrMsg] = cppbor::parse(protectedData.protectedData);
373 ASSERT_TRUE(parsedProtectedData) << protDataErrMsg;
374 ASSERT_TRUE(parsedProtectedData->asArray());
375 ASSERT_EQ(parsedProtectedData->asArray()->size(), kCoseEncryptEntryCount);
376
377 auto senderPubkey = getSenderPubKeyFromCoseEncrypt(parsedProtectedData);
378 ASSERT_TRUE(senderPubkey) << senderPubkey.message();
379 EXPECT_EQ(senderPubkey->second, eekId_);
380
Seth Moore19acbe92021-06-23 15:15:52 -0700381 auto sessionKey =
382 x25519_HKDF_DeriveKey(testEekChain_.last_pubkey, testEekChain_.last_privkey,
383 senderPubkey->first, false /* senderIsA */);
David Drysdalec8400772021-03-11 12:35:11 +0000384 ASSERT_TRUE(sessionKey) << sessionKey.message();
385
386 auto protectedDataPayload =
387 decryptCoseEncrypt(*sessionKey, parsedProtectedData.get(), bytevec{} /* aad */);
388 ASSERT_TRUE(protectedDataPayload) << protectedDataPayload.message();
389
390 auto [parsedPayload, __, payloadErrMsg] = cppbor::parse(*protectedDataPayload);
391 ASSERT_TRUE(parsedPayload) << "Failed to parse payload: " << payloadErrMsg;
392 ASSERT_TRUE(parsedPayload->asArray());
393 EXPECT_EQ(parsedPayload->asArray()->size(), 2U);
394
395 auto& signedMac = parsedPayload->asArray()->get(0);
396 auto& bcc = parsedPayload->asArray()->get(1);
397 ASSERT_TRUE(signedMac && signedMac->asArray());
398 ASSERT_TRUE(bcc && bcc->asArray());
399
400 // BCC is [ pubkey, + BccEntry]
401 auto bccContents = validateBcc(bcc->asArray());
402 ASSERT_TRUE(bccContents) << "\n" << bccContents.message() << "\n" << prettyPrint(bcc.get());
403 ASSERT_GT(bccContents->size(), 0U);
404
David Drysdalef6fc5a62021-03-31 16:14:31 +0100405 auto [deviceInfoMap, __2, deviceInfoErrMsg] = cppbor::parse(deviceInfo.deviceInfo);
406 ASSERT_TRUE(deviceInfoMap) << "Failed to parse deviceInfo: " << deviceInfoErrMsg;
407 ASSERT_TRUE(deviceInfoMap->asMap());
408
David Drysdalec8400772021-03-11 12:35:11 +0000409 auto& signingKey = bccContents->back().pubKey;
Seth Moore798188a2021-06-17 10:58:27 -0700410 auto macKey = verifyAndParseCoseSign1(signedMac->asArray(), signingKey,
David Drysdalef6fc5a62021-03-31 16:14:31 +0100411 cppbor::Array() // SignedMacAad
David Drysdalec8400772021-03-11 12:35:11 +0000412 .add(challenge_)
David Drysdalef6fc5a62021-03-31 16:14:31 +0100413 .add(std::move(deviceInfoMap))
Max Bires8dff0b32021-05-26 13:05:09 -0700414 .add(keysToSignMac)
David Drysdalec8400772021-03-11 12:35:11 +0000415 .encode());
416 ASSERT_TRUE(macKey) << macKey.message();
417
418 auto coseMac0 = cppbor::Array()
419 .add(cppbor::Map() // protected
420 .add(ALGORITHM, HMAC_256)
421 .canonicalize()
422 .encode())
423 .add(cppbor::Map()) // unprotected
424 .add(keysToSign.encode()) // payload (keysToSign)
425 .add(keysToSignMac); // tag
426
427 auto macPayload = verifyAndParseCoseMac0(&coseMac0, *macKey);
428 ASSERT_TRUE(macPayload) << macPayload.message();
Seth Moore42c11332021-07-02 15:38:17 -0700429
430 if (bccOutput) {
431 *bccOutput = std::move(*bccContents);
432 }
David Drysdalec8400772021-03-11 12:35:11 +0000433 }
434
Shawn Willden274bb552020-09-30 22:39:22 -0600435 bytevec eekId_;
Seth Moore19acbe92021-06-23 15:15:52 -0700436 size_t testEekLength_;
437 EekChain testEekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000438 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600439 std::vector<MacedPublicKey> keysToSign_;
440 cppbor::Array cborKeysToSign_;
441};
442
443/**
444 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
445 * content.
446 */
Max Bires126869a2021-02-21 18:32:59 -0800447TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600448 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000449 for (size_t eekLength : {2, 3, 7}) {
450 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700451 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600452
David Drysdalecceca9f2021-03-12 15:49:47 +0000453 bytevec keysToSignMac;
454 DeviceInfo deviceInfo;
455 ProtectedData protectedData;
456 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700457 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalecceca9f2021-03-12 15:49:47 +0000458 &protectedData, &keysToSignMac);
459 ASSERT_TRUE(status.isOk()) << status.getMessage();
460
David Drysdalef6fc5a62021-03-31 16:14:31 +0100461 checkProtectedData(deviceInfo, cppbor::Array(), keysToSignMac, protectedData);
David Drysdalecceca9f2021-03-12 15:49:47 +0000462 }
Shawn Willden274bb552020-09-30 22:39:22 -0600463}
464
465/**
Seth Moore42c11332021-07-02 15:38:17 -0700466 * Ensure that test mode outputs a unique BCC root key every time we request a
467 * certificate request. Else, it's possible that the test mode API could be used
468 * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
469 * device public key multiple times.
470 */
471TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
472 constexpr bool testMode = true;
Seth Moore42c11332021-07-02 15:38:17 -0700473
474 bytevec keysToSignMac;
475 DeviceInfo deviceInfo;
476 ProtectedData protectedData;
477 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700478 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
479 &protectedData, &keysToSignMac);
Seth Moore42c11332021-07-02 15:38:17 -0700480 ASSERT_TRUE(status.isOk()) << status.getMessage();
481
482 std::vector<BccEntryData> firstBcc;
483 checkProtectedData(deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData,
484 &firstBcc);
485
Seth Moore19acbe92021-06-23 15:15:52 -0700486 status = provisionable_->generateCertificateRequest(
487 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
488 &protectedData, &keysToSignMac);
Seth Moore42c11332021-07-02 15:38:17 -0700489 ASSERT_TRUE(status.isOk()) << status.getMessage();
490
491 std::vector<BccEntryData> secondBcc;
492 checkProtectedData(deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData,
493 &secondBcc);
494
495 // Verify that none of the keys in the first BCC are repeated in the second one.
496 for (const auto& i : firstBcc) {
497 for (auto& j : secondBcc) {
498 ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
499 << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
500 }
501 }
502}
503
504/**
Seth Moore19acbe92021-06-23 15:15:52 -0700505 * Generate an empty certificate request in prod mode. This test must be run explicitly, and
506 * is not run by default. Not all devices are GMS devices, and therefore they do not all
507 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600508 */
Seth Moore19acbe92021-06-23 15:15:52 -0700509TEST_P(CertificateRequestTest, DISABLED_EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600510 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000511
Seth Moore19acbe92021-06-23 15:15:52 -0700512 bytevec keysToSignMac;
513 DeviceInfo deviceInfo;
514 ProtectedData protectedData;
515 auto status = provisionable_->generateCertificateRequest(
516 testMode, {} /* keysToSign */, getProdEekChain(), challenge_, &deviceInfo,
517 &protectedData, &keysToSignMac);
518 EXPECT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600519}
520
521/**
522 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
523 */
Max Bires126869a2021-02-21 18:32:59 -0800524TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600525 bool testMode = true;
526 generateKeys(testMode, 4 /* numKeys */);
527
David Drysdalecceca9f2021-03-12 15:49:47 +0000528 for (size_t eekLength : {2, 3, 7}) {
529 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700530 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600531
David Drysdalecceca9f2021-03-12 15:49:47 +0000532 bytevec keysToSignMac;
533 DeviceInfo deviceInfo;
534 ProtectedData protectedData;
535 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700536 testMode, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo, &protectedData,
David Drysdalecceca9f2021-03-12 15:49:47 +0000537 &keysToSignMac);
538 ASSERT_TRUE(status.isOk()) << status.getMessage();
539
David Drysdalef6fc5a62021-03-31 16:14:31 +0100540 checkProtectedData(deviceInfo, cborKeysToSign_, keysToSignMac, protectedData);
David Drysdalecceca9f2021-03-12 15:49:47 +0000541 }
Shawn Willden274bb552020-09-30 22:39:22 -0600542}
543
544/**
Seth Moore19acbe92021-06-23 15:15:52 -0700545 * Generate a non-empty certificate request in prod mode. This test must be run explicitly, and
546 * is not run by default. Not all devices are GMS devices, and therefore they do not all
547 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600548 */
Seth Moore19acbe92021-06-23 15:15:52 -0700549TEST_P(CertificateRequestTest, DISABLED_NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600550 bool testMode = false;
551 generateKeys(testMode, 4 /* numKeys */);
552
Seth Moore19acbe92021-06-23 15:15:52 -0700553 bytevec keysToSignMac;
554 DeviceInfo deviceInfo;
555 ProtectedData protectedData;
556 auto status = provisionable_->generateCertificateRequest(
557 testMode, keysToSign_, getProdEekChain(), challenge_, &deviceInfo, &protectedData,
558 &keysToSignMac);
559 EXPECT_TRUE(status.isOk());
David Drysdalecceca9f2021-03-12 15:49:47 +0000560}
561
562/**
David Drysdalee99ed862021-03-15 16:43:06 +0000563 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
564 */
565TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
566 bool testMode = true;
567 generateKeys(testMode, 1 /* numKeys */);
568 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
569
570 bytevec keysToSignMac;
571 DeviceInfo deviceInfo;
572 ProtectedData protectedData;
573 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700574 testMode, {keyWithCorruptMac}, testEekChain_.chain, challenge_, &deviceInfo,
575 &protectedData, &keysToSignMac);
David Drysdalee99ed862021-03-15 16:43:06 +0000576 ASSERT_FALSE(status.isOk()) << status.getMessage();
577 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
578}
579
580/**
581 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
582 */
583TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
Seth Moore19acbe92021-06-23 15:15:52 -0700584 bool testMode = false;
David Drysdalee99ed862021-03-15 16:43:06 +0000585 generateKeys(testMode, 1 /* numKeys */);
586 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
587
588 bytevec keysToSignMac;
589 DeviceInfo deviceInfo;
590 ProtectedData protectedData;
591 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700592 testMode, {keyWithCorruptMac}, getProdEekChain(), challenge_, &deviceInfo,
593 &protectedData, &keysToSignMac);
David Drysdalee99ed862021-03-15 16:43:06 +0000594 ASSERT_FALSE(status.isOk()) << status.getMessage();
Seth Moore19acbe92021-06-23 15:15:52 -0700595 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
David Drysdalee99ed862021-03-15 16:43:06 +0000596}
597
598/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000599 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
600 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000601 */
602TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
603 bool testMode = false;
604 generateKeys(testMode, 4 /* numKeys */);
605
Seth Moore19acbe92021-06-23 15:15:52 -0700606 auto prodEekChain = getProdEekChain();
607 auto [parsedChain, _, parseErr] = cppbor::parse(prodEekChain);
608 ASSERT_NE(parsedChain, nullptr) << parseErr;
609 ASSERT_NE(parsedChain->asArray(), nullptr);
610
611 for (int ii = 0; ii < parsedChain->asArray()->size(); ++ii) {
612 auto chain = corrupt_sig_chain(prodEekChain, ii);
David Drysdalecceca9f2021-03-12 15:49:47 +0000613 ASSERT_TRUE(chain) << chain.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000614
615 bytevec keysToSignMac;
616 DeviceInfo deviceInfo;
617 ProtectedData protectedData;
Seth Moore19acbe92021-06-23 15:15:52 -0700618 auto status = provisionable_->generateCertificateRequest(testMode, keysToSign_, *chain,
619 challenge_, &deviceInfo,
620 &protectedData, &keysToSignMac);
David Drysdalecceca9f2021-03-12 15:49:47 +0000621 ASSERT_FALSE(status.isOk());
622 ASSERT_EQ(status.getServiceSpecificError(),
623 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
624 }
625}
626
627/**
628 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
629 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000630 */
631TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
632 bool testMode = false;
633 generateKeys(testMode, 4 /* numKeys */);
634
635 // Build an EEK chain that omits the first self-signed cert.
636 auto truncatedChain = cppbor::Array();
Seth Moore19acbe92021-06-23 15:15:52 -0700637 auto [chain, _, parseErr] = cppbor::parse(getProdEekChain());
David Drysdalecceca9f2021-03-12 15:49:47 +0000638 ASSERT_TRUE(chain);
639 auto eekChain = chain->asArray();
640 ASSERT_NE(eekChain, nullptr);
641 for (size_t ii = 1; ii < eekChain->size(); ii++) {
642 truncatedChain.add(eekChain->get(ii)->clone());
643 }
644
Shawn Willden274bb552020-09-30 22:39:22 -0600645 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700646 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600647 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000648 auto status = provisionable_->generateCertificateRequest(
649 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
650 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600651 ASSERT_FALSE(status.isOk());
652 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
653}
654
655/**
656 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
657 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
658 */
Max Bires126869a2021-02-21 18:32:59 -0800659TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600660 generateKeys(false /* testMode */, 2 /* numKeys */);
661
662 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700663 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600664 ProtectedData protectedData;
Max Biresfdbb9042021-03-23 12:43:38 -0700665 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700666 true /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700667 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600668 ASSERT_FALSE(status.isOk());
669 ASSERT_EQ(status.getServiceSpecificError(),
670 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
671}
672
673/**
674 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
675 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
676 */
Max Bires126869a2021-02-21 18:32:59 -0800677TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600678 generateKeys(true /* testMode */, 2 /* numKeys */);
679
680 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700681 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600682 ProtectedData protectedData;
683 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700684 false /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalec8400772021-03-11 12:35:11 +0000685 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600686 ASSERT_FALSE(status.isOk());
687 ASSERT_EQ(status.getServiceSpecificError(),
688 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
689}
690
691INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
692
693} // namespace aidl::android::hardware::security::keymint::test