blob: 76fb79b6185f420cad0a543a204b586c32190ff5 [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>
23#include <cppbor_parse.h>
Shawn Willden274bb552020-09-30 22:39:22 -060024#include <gmock/gmock.h>
Max Bires9704ff62021-04-07 11:12:01 -070025#include <keymaster/cppcose/cppcose.h>
Shawn Willden274bb552020-09-30 22:39:22 -060026#include <keymaster/keymaster_configuration.h>
David Drysdalef0d516d2021-03-22 07:51:43 +000027#include <keymint_support/authorization_set.h>
28#include <openssl/ec.h>
29#include <openssl/ec_key.h>
30#include <openssl/x509.h>
Shawn Willden274bb552020-09-30 22:39:22 -060031#include <remote_prov/remote_prov_utils.h>
Seth Moore42c11332021-07-02 15:38:17 -070032#include <vector>
Shawn Willden274bb552020-09-30 22:39:22 -060033
David Drysdalef0d516d2021-03-22 07:51:43 +000034#include "KeyMintAidlTestBase.h"
35
Shawn Willden274bb552020-09-30 22:39:22 -060036namespace aidl::android::hardware::security::keymint::test {
37
38using ::std::string;
39using ::std::vector;
40
41namespace {
42
43#define INSTANTIATE_REM_PROV_AIDL_TEST(name) \
Seth Moore6305e232021-07-27 14:20:17 -070044 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name); \
Shawn Willden274bb552020-09-30 22:39:22 -060045 INSTANTIATE_TEST_SUITE_P( \
46 PerInstance, name, \
47 testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
48 ::android::PrintInstanceNameToString)
49
50using bytevec = std::vector<uint8_t>;
51using testing::MatchesRegex;
52using namespace remote_prov;
53using namespace keymaster;
54
55bytevec string_to_bytevec(const char* s) {
56 const uint8_t* p = reinterpret_cast<const uint8_t*>(s);
57 return bytevec(p, p + strlen(s));
58}
59
David Drysdalee99ed862021-03-15 16:43:06 +000060ErrMsgOr<MacedPublicKey> corrupt_maced_key(const MacedPublicKey& macedPubKey) {
61 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
62 if (!coseMac0 || coseMac0->asArray()->size() != kCoseMac0EntryCount) {
63 return "COSE Mac0 parse failed";
64 }
65 auto protParams = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
66 auto unprotParams = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
67 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
68 auto tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
69 if (!protParams || !unprotParams || !payload || !tag) {
70 return "Invalid COSE_Sign1: missing content";
71 }
72 auto corruptMac0 = cppbor::Array();
73 corruptMac0.add(protParams->clone());
74 corruptMac0.add(unprotParams->clone());
75 corruptMac0.add(payload->clone());
76 vector<uint8_t> tagData = tag->value();
77 tagData[0] ^= 0x08;
78 tagData[tagData.size() - 1] ^= 0x80;
79 corruptMac0.add(cppbor::Bstr(tagData));
80
81 return MacedPublicKey{corruptMac0.encode()};
82}
83
David Drysdalecceca9f2021-03-12 15:49:47 +000084ErrMsgOr<cppbor::Array> corrupt_sig(const cppbor::Array* coseSign1) {
85 if (coseSign1->size() != kCoseSign1EntryCount) {
86 return "Invalid COSE_Sign1, wrong entry count";
87 }
88 const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
89 const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
90 const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
91 const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
92 if (!protectedParams || !unprotectedParams || !payload || !signature) {
93 return "Invalid COSE_Sign1: missing content";
94 }
95
96 auto corruptSig = cppbor::Array();
97 corruptSig.add(protectedParams->clone());
98 corruptSig.add(unprotectedParams->clone());
99 corruptSig.add(payload->clone());
100 vector<uint8_t> sigData = signature->value();
101 sigData[0] ^= 0x08;
102 corruptSig.add(cppbor::Bstr(sigData));
103
104 return std::move(corruptSig);
105}
106
Seth Moore19acbe92021-06-23 15:15:52 -0700107ErrMsgOr<bytevec> corrupt_sig_chain(const bytevec& encodedEekChain, int which) {
108 auto [chain, _, parseErr] = cppbor::parse(encodedEekChain);
David Drysdalecceca9f2021-03-12 15:49:47 +0000109 if (!chain || !chain->asArray()) {
110 return "EekChain parse failed";
111 }
112
113 cppbor::Array* eekChain = chain->asArray();
114 if (which >= eekChain->size()) {
115 return "selected sig out of range";
116 }
117 auto corruptChain = cppbor::Array();
118
119 for (int ii = 0; ii < eekChain->size(); ++ii) {
120 if (ii == which) {
121 auto sig = corrupt_sig(eekChain->get(which)->asArray());
122 if (!sig) {
123 return "Failed to build corrupted signature" + sig.moveMessage();
124 }
125 corruptChain.add(sig.moveValue());
126 } else {
127 corruptChain.add(eekChain->get(ii)->clone());
128 }
129 }
Seth Moore19acbe92021-06-23 15:15:52 -0700130 return corruptChain.encode();
David Drysdalecceca9f2021-03-12 15:49:47 +0000131}
132
David Drysdale4d3c2982021-03-31 18:21:40 +0100133string device_suffix(const string& name) {
134 size_t pos = name.find('/');
135 if (pos == string::npos) {
136 return name;
137 }
138 return name.substr(pos + 1);
139}
140
141bool matching_keymint_device(const string& rp_name, std::shared_ptr<IKeyMintDevice>* keyMint) {
142 string rp_suffix = device_suffix(rp_name);
143
144 vector<string> km_names = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
145 for (const string& km_name : km_names) {
146 // If the suffix of the KeyMint instance equals the suffix of the
147 // RemotelyProvisionedComponent instance, assume they match.
148 if (device_suffix(km_name) == rp_suffix && AServiceManager_isDeclared(km_name.c_str())) {
149 ::ndk::SpAIBinder binder(AServiceManager_waitForService(km_name.c_str()));
150 *keyMint = IKeyMintDevice::fromBinder(binder);
151 return true;
152 }
153 }
154 return false;
155}
156
Shawn Willden274bb552020-09-30 22:39:22 -0600157} // namespace
158
159class VtsRemotelyProvisionedComponentTests : public testing::TestWithParam<std::string> {
160 public:
161 virtual void SetUp() override {
162 if (AServiceManager_isDeclared(GetParam().c_str())) {
163 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
164 provisionable_ = IRemotelyProvisionedComponent::fromBinder(binder);
165 }
166 ASSERT_NE(provisionable_, nullptr);
167 }
168
169 static vector<string> build_params() {
170 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
171 return params;
172 }
173
174 protected:
175 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
176};
177
178using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
179
180INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
181
182/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000183 * Generate and validate a production-mode key. MAC tag can't be verified, but
184 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600185 */
Max Bires126869a2021-02-21 18:32:59 -0800186TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600187 MacedPublicKey macedPubKey;
188 bytevec privateKeyBlob;
189 bool testMode = false;
190 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
191 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000192 vector<uint8_t> coseKeyData;
193 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100194}
195
196/**
197 * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
198 */
199TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
200 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
201 std::shared_ptr<IKeyMintDevice> keyMint;
202 if (!matching_keymint_device(GetParam(), &keyMint)) {
203 // No matching IKeyMintDevice.
204 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
205 return;
206 }
207 KeyMintHardwareInfo info;
208 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
209
210 MacedPublicKey macedPubKey;
211 bytevec privateKeyBlob;
212 bool testMode = false;
213 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
214 ASSERT_TRUE(status.isOk());
215 vector<uint8_t> coseKeyData;
216 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
217
David Drysdalef0d516d2021-03-22 07:51:43 +0000218 AttestationKey attestKey;
219 attestKey.keyBlob = std::move(privateKeyBlob);
220 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600221
David Drysdalef0d516d2021-03-22 07:51:43 +0000222 // Generate an ECDSA key that is attested by the generated P256 keypair.
223 AuthorizationSet keyDesc = AuthorizationSetBuilder()
224 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale915ce252021-10-14 15:17:36 +0100225 .EcdsaSigningKey(EcCurve::P_256)
David Drysdalef0d516d2021-03-22 07:51:43 +0000226 .AttestationChallenge("foo")
227 .AttestationApplicationId("bar")
228 .Digest(Digest::NONE)
229 .SetDefaultValidity();
230 KeyCreationResult creationResult;
231 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
232 ASSERT_TRUE(result.isOk());
233 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
234 vector<KeyCharacteristics> attested_key_characteristics =
235 std::move(creationResult.keyCharacteristics);
236 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
237 EXPECT_EQ(attested_key_cert_chain.size(), 1);
238
239 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
240 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
241 EXPECT_TRUE(verify_attestation_record("foo", "bar", sw_enforced, hw_enforced,
242 info.securityLevel,
243 attested_key_cert_chain[0].encodedCertificate));
244
245 // Attestation by itself is not valid (last entry is not self-signed).
246 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
247
248 // The signature over the attested key should correspond to the P256 public key.
249 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
250 ASSERT_TRUE(key_cert.get());
251 EVP_PKEY_Ptr signing_pubkey;
252 p256_pub_key(coseKeyData, &signing_pubkey);
253 ASSERT_TRUE(signing_pubkey.get());
254
255 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
256 << "Verification of attested certificate failed "
257 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600258}
259
260/**
261 * Generate and validate a test-mode key.
262 */
Max Bires126869a2021-02-21 18:32:59 -0800263TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600264 MacedPublicKey macedPubKey;
265 bytevec privateKeyBlob;
266 bool testMode = true;
267 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
268 ASSERT_TRUE(status.isOk());
269
David Drysdalec8400772021-03-11 12:35:11 +0000270 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600271}
272
273class CertificateRequestTest : public VtsRemotelyProvisionedComponentTests {
274 protected:
David Drysdalec8400772021-03-11 12:35:11 +0000275 CertificateRequestTest() : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(32)) {
Seth Moore19acbe92021-06-23 15:15:52 -0700276 generateTestEekChain(3);
David Drysdalecceca9f2021-03-12 15:49:47 +0000277 }
278
Seth Moore19acbe92021-06-23 15:15:52 -0700279 void generateTestEekChain(size_t eekLength) {
David Drysdalecceca9f2021-03-12 15:49:47 +0000280 auto chain = generateEekChain(eekLength, eekId_);
Shawn Willden274bb552020-09-30 22:39:22 -0600281 EXPECT_TRUE(chain) << chain.message();
Seth Moore19acbe92021-06-23 15:15:52 -0700282 if (chain) testEekChain_ = chain.moveValue();
283 testEekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600284 }
285
286 void generateKeys(bool testMode, size_t numKeys) {
287 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
288 cborKeysToSign_ = cppbor::Array();
289
290 for (auto& key : keysToSign_) {
291 bytevec privateKeyBlob;
292 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
293 ASSERT_TRUE(status.isOk()) << status.getMessage();
294
David Drysdalec8400772021-03-11 12:35:11 +0000295 vector<uint8_t> payload_value;
296 check_maced_pubkey(key, testMode, &payload_value);
297 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600298 }
299 }
300
David Drysdalef6fc5a62021-03-31 16:14:31 +0100301 void checkProtectedData(const DeviceInfo& deviceInfo, const cppbor::Array& keysToSign,
Seth Moore42c11332021-07-02 15:38:17 -0700302 const bytevec& keysToSignMac, const ProtectedData& protectedData,
303 std::vector<BccEntryData>* bccOutput = nullptr) {
David Drysdalec8400772021-03-11 12:35:11 +0000304 auto [parsedProtectedData, _, protDataErrMsg] = cppbor::parse(protectedData.protectedData);
305 ASSERT_TRUE(parsedProtectedData) << protDataErrMsg;
306 ASSERT_TRUE(parsedProtectedData->asArray());
307 ASSERT_EQ(parsedProtectedData->asArray()->size(), kCoseEncryptEntryCount);
308
309 auto senderPubkey = getSenderPubKeyFromCoseEncrypt(parsedProtectedData);
310 ASSERT_TRUE(senderPubkey) << senderPubkey.message();
311 EXPECT_EQ(senderPubkey->second, eekId_);
312
Seth Moore19acbe92021-06-23 15:15:52 -0700313 auto sessionKey =
314 x25519_HKDF_DeriveKey(testEekChain_.last_pubkey, testEekChain_.last_privkey,
315 senderPubkey->first, false /* senderIsA */);
David Drysdalec8400772021-03-11 12:35:11 +0000316 ASSERT_TRUE(sessionKey) << sessionKey.message();
317
318 auto protectedDataPayload =
319 decryptCoseEncrypt(*sessionKey, parsedProtectedData.get(), bytevec{} /* aad */);
320 ASSERT_TRUE(protectedDataPayload) << protectedDataPayload.message();
321
322 auto [parsedPayload, __, payloadErrMsg] = cppbor::parse(*protectedDataPayload);
323 ASSERT_TRUE(parsedPayload) << "Failed to parse payload: " << payloadErrMsg;
324 ASSERT_TRUE(parsedPayload->asArray());
325 EXPECT_EQ(parsedPayload->asArray()->size(), 2U);
326
327 auto& signedMac = parsedPayload->asArray()->get(0);
328 auto& bcc = parsedPayload->asArray()->get(1);
329 ASSERT_TRUE(signedMac && signedMac->asArray());
330 ASSERT_TRUE(bcc && bcc->asArray());
331
332 // BCC is [ pubkey, + BccEntry]
333 auto bccContents = validateBcc(bcc->asArray());
334 ASSERT_TRUE(bccContents) << "\n" << bccContents.message() << "\n" << prettyPrint(bcc.get());
335 ASSERT_GT(bccContents->size(), 0U);
336
David Drysdalef6fc5a62021-03-31 16:14:31 +0100337 auto [deviceInfoMap, __2, deviceInfoErrMsg] = cppbor::parse(deviceInfo.deviceInfo);
338 ASSERT_TRUE(deviceInfoMap) << "Failed to parse deviceInfo: " << deviceInfoErrMsg;
339 ASSERT_TRUE(deviceInfoMap->asMap());
340
David Drysdalec8400772021-03-11 12:35:11 +0000341 auto& signingKey = bccContents->back().pubKey;
Seth Moore798188a2021-06-17 10:58:27 -0700342 auto macKey = verifyAndParseCoseSign1(signedMac->asArray(), signingKey,
David Drysdalef6fc5a62021-03-31 16:14:31 +0100343 cppbor::Array() // SignedMacAad
David Drysdalec8400772021-03-11 12:35:11 +0000344 .add(challenge_)
David Drysdalef6fc5a62021-03-31 16:14:31 +0100345 .add(std::move(deviceInfoMap))
Max Bires8dff0b32021-05-26 13:05:09 -0700346 .add(keysToSignMac)
David Drysdalec8400772021-03-11 12:35:11 +0000347 .encode());
348 ASSERT_TRUE(macKey) << macKey.message();
349
350 auto coseMac0 = cppbor::Array()
351 .add(cppbor::Map() // protected
352 .add(ALGORITHM, HMAC_256)
353 .canonicalize()
354 .encode())
355 .add(cppbor::Map()) // unprotected
356 .add(keysToSign.encode()) // payload (keysToSign)
357 .add(keysToSignMac); // tag
358
359 auto macPayload = verifyAndParseCoseMac0(&coseMac0, *macKey);
360 ASSERT_TRUE(macPayload) << macPayload.message();
Seth Moore42c11332021-07-02 15:38:17 -0700361
362 if (bccOutput) {
363 *bccOutput = std::move(*bccContents);
364 }
David Drysdalec8400772021-03-11 12:35:11 +0000365 }
366
Shawn Willden274bb552020-09-30 22:39:22 -0600367 bytevec eekId_;
Seth Moore19acbe92021-06-23 15:15:52 -0700368 size_t testEekLength_;
369 EekChain testEekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000370 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600371 std::vector<MacedPublicKey> keysToSign_;
372 cppbor::Array cborKeysToSign_;
373};
374
375/**
376 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
377 * content.
378 */
Max Bires126869a2021-02-21 18:32:59 -0800379TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600380 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000381 for (size_t eekLength : {2, 3, 7}) {
382 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700383 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600384
David Drysdalecceca9f2021-03-12 15:49:47 +0000385 bytevec keysToSignMac;
386 DeviceInfo deviceInfo;
387 ProtectedData protectedData;
388 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700389 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalecceca9f2021-03-12 15:49:47 +0000390 &protectedData, &keysToSignMac);
391 ASSERT_TRUE(status.isOk()) << status.getMessage();
392
David Drysdalef6fc5a62021-03-31 16:14:31 +0100393 checkProtectedData(deviceInfo, cppbor::Array(), keysToSignMac, protectedData);
David Drysdalecceca9f2021-03-12 15:49:47 +0000394 }
Shawn Willden274bb552020-09-30 22:39:22 -0600395}
396
397/**
Seth Moore42c11332021-07-02 15:38:17 -0700398 * Ensure that test mode outputs a unique BCC root key every time we request a
399 * certificate request. Else, it's possible that the test mode API could be used
400 * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
401 * device public key multiple times.
402 */
403TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
404 constexpr bool testMode = true;
Seth Moore42c11332021-07-02 15:38:17 -0700405
406 bytevec keysToSignMac;
407 DeviceInfo deviceInfo;
408 ProtectedData protectedData;
409 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700410 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
411 &protectedData, &keysToSignMac);
Seth Moore42c11332021-07-02 15:38:17 -0700412 ASSERT_TRUE(status.isOk()) << status.getMessage();
413
414 std::vector<BccEntryData> firstBcc;
415 checkProtectedData(deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData,
416 &firstBcc);
417
Seth Moore19acbe92021-06-23 15:15:52 -0700418 status = provisionable_->generateCertificateRequest(
419 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
420 &protectedData, &keysToSignMac);
Seth Moore42c11332021-07-02 15:38:17 -0700421 ASSERT_TRUE(status.isOk()) << status.getMessage();
422
423 std::vector<BccEntryData> secondBcc;
424 checkProtectedData(deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData,
425 &secondBcc);
426
427 // Verify that none of the keys in the first BCC are repeated in the second one.
428 for (const auto& i : firstBcc) {
429 for (auto& j : secondBcc) {
430 ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
431 << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
432 }
433 }
434}
435
436/**
Seth Moore19acbe92021-06-23 15:15:52 -0700437 * Generate an empty certificate request in prod mode. This test must be run explicitly, and
438 * is not run by default. Not all devices are GMS devices, and therefore they do not all
439 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600440 */
Seth Moore19acbe92021-06-23 15:15:52 -0700441TEST_P(CertificateRequestTest, DISABLED_EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600442 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000443
Seth Moore19acbe92021-06-23 15:15:52 -0700444 bytevec keysToSignMac;
445 DeviceInfo deviceInfo;
446 ProtectedData protectedData;
447 auto status = provisionable_->generateCertificateRequest(
448 testMode, {} /* keysToSign */, getProdEekChain(), challenge_, &deviceInfo,
449 &protectedData, &keysToSignMac);
450 EXPECT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600451}
452
453/**
454 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
455 */
Max Bires126869a2021-02-21 18:32:59 -0800456TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600457 bool testMode = true;
458 generateKeys(testMode, 4 /* numKeys */);
459
David Drysdalecceca9f2021-03-12 15:49:47 +0000460 for (size_t eekLength : {2, 3, 7}) {
461 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700462 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600463
David Drysdalecceca9f2021-03-12 15:49:47 +0000464 bytevec keysToSignMac;
465 DeviceInfo deviceInfo;
466 ProtectedData protectedData;
467 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700468 testMode, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo, &protectedData,
David Drysdalecceca9f2021-03-12 15:49:47 +0000469 &keysToSignMac);
470 ASSERT_TRUE(status.isOk()) << status.getMessage();
471
David Drysdalef6fc5a62021-03-31 16:14:31 +0100472 checkProtectedData(deviceInfo, cborKeysToSign_, keysToSignMac, protectedData);
David Drysdalecceca9f2021-03-12 15:49:47 +0000473 }
Shawn Willden274bb552020-09-30 22:39:22 -0600474}
475
476/**
Seth Moore19acbe92021-06-23 15:15:52 -0700477 * Generate a non-empty certificate request in prod mode. This test must be run explicitly, and
478 * is not run by default. Not all devices are GMS devices, and therefore they do not all
479 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600480 */
Seth Moore19acbe92021-06-23 15:15:52 -0700481TEST_P(CertificateRequestTest, DISABLED_NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600482 bool testMode = false;
483 generateKeys(testMode, 4 /* numKeys */);
484
Seth Moore19acbe92021-06-23 15:15:52 -0700485 bytevec keysToSignMac;
486 DeviceInfo deviceInfo;
487 ProtectedData protectedData;
488 auto status = provisionable_->generateCertificateRequest(
489 testMode, keysToSign_, getProdEekChain(), challenge_, &deviceInfo, &protectedData,
490 &keysToSignMac);
491 EXPECT_TRUE(status.isOk());
David Drysdalecceca9f2021-03-12 15:49:47 +0000492}
493
494/**
David Drysdalee99ed862021-03-15 16:43:06 +0000495 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
496 */
497TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
498 bool testMode = true;
499 generateKeys(testMode, 1 /* numKeys */);
500 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
501
502 bytevec keysToSignMac;
503 DeviceInfo deviceInfo;
504 ProtectedData protectedData;
505 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700506 testMode, {keyWithCorruptMac}, testEekChain_.chain, challenge_, &deviceInfo,
507 &protectedData, &keysToSignMac);
David Drysdalee99ed862021-03-15 16:43:06 +0000508 ASSERT_FALSE(status.isOk()) << status.getMessage();
509 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
510}
511
512/**
513 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
514 */
515TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
Seth Moore19acbe92021-06-23 15:15:52 -0700516 bool testMode = false;
David Drysdalee99ed862021-03-15 16:43:06 +0000517 generateKeys(testMode, 1 /* numKeys */);
518 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
519
520 bytevec keysToSignMac;
521 DeviceInfo deviceInfo;
522 ProtectedData protectedData;
523 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700524 testMode, {keyWithCorruptMac}, getProdEekChain(), challenge_, &deviceInfo,
525 &protectedData, &keysToSignMac);
David Drysdalee99ed862021-03-15 16:43:06 +0000526 ASSERT_FALSE(status.isOk()) << status.getMessage();
Seth Moore19acbe92021-06-23 15:15:52 -0700527 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
David Drysdalee99ed862021-03-15 16:43:06 +0000528}
529
530/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000531 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
532 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000533 */
534TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
535 bool testMode = false;
536 generateKeys(testMode, 4 /* numKeys */);
537
Seth Moore19acbe92021-06-23 15:15:52 -0700538 auto prodEekChain = getProdEekChain();
539 auto [parsedChain, _, parseErr] = cppbor::parse(prodEekChain);
540 ASSERT_NE(parsedChain, nullptr) << parseErr;
541 ASSERT_NE(parsedChain->asArray(), nullptr);
542
543 for (int ii = 0; ii < parsedChain->asArray()->size(); ++ii) {
544 auto chain = corrupt_sig_chain(prodEekChain, ii);
David Drysdalecceca9f2021-03-12 15:49:47 +0000545 ASSERT_TRUE(chain) << chain.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000546
547 bytevec keysToSignMac;
548 DeviceInfo deviceInfo;
549 ProtectedData protectedData;
Seth Moore19acbe92021-06-23 15:15:52 -0700550 auto status = provisionable_->generateCertificateRequest(testMode, keysToSign_, *chain,
551 challenge_, &deviceInfo,
552 &protectedData, &keysToSignMac);
David Drysdalecceca9f2021-03-12 15:49:47 +0000553 ASSERT_FALSE(status.isOk());
554 ASSERT_EQ(status.getServiceSpecificError(),
555 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
556 }
557}
558
559/**
560 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
561 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000562 */
563TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
564 bool testMode = false;
565 generateKeys(testMode, 4 /* numKeys */);
566
567 // Build an EEK chain that omits the first self-signed cert.
568 auto truncatedChain = cppbor::Array();
Seth Moore19acbe92021-06-23 15:15:52 -0700569 auto [chain, _, parseErr] = cppbor::parse(getProdEekChain());
David Drysdalecceca9f2021-03-12 15:49:47 +0000570 ASSERT_TRUE(chain);
571 auto eekChain = chain->asArray();
572 ASSERT_NE(eekChain, nullptr);
573 for (size_t ii = 1; ii < eekChain->size(); ii++) {
574 truncatedChain.add(eekChain->get(ii)->clone());
575 }
576
Shawn Willden274bb552020-09-30 22:39:22 -0600577 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700578 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600579 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000580 auto status = provisionable_->generateCertificateRequest(
581 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
582 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600583 ASSERT_FALSE(status.isOk());
584 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
585}
586
587/**
588 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
589 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
590 */
Max Bires126869a2021-02-21 18:32:59 -0800591TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600592 generateKeys(false /* testMode */, 2 /* numKeys */);
593
594 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700595 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600596 ProtectedData protectedData;
Max Biresfdbb9042021-03-23 12:43:38 -0700597 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700598 true /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700599 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600600 ASSERT_FALSE(status.isOk());
601 ASSERT_EQ(status.getServiceSpecificError(),
602 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
603}
604
605/**
606 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
607 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
608 */
Max Bires126869a2021-02-21 18:32:59 -0800609TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600610 generateKeys(true /* testMode */, 2 /* numKeys */);
611
612 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700613 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600614 ProtectedData protectedData;
615 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700616 false /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalec8400772021-03-11 12:35:11 +0000617 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600618 ASSERT_FALSE(status.isOk());
619 ASSERT_EQ(status.getServiceSpecificError(),
620 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
621}
622
623INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
624
625} // namespace aidl::android::hardware::security::keymint::test