blob: e1f65fec780d3e9333fd22e729f3f80699fe7371 [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
Seth Mooref1f62152022-09-13 12:00:30 -070017#include <memory>
Seth Moore2fc6f832022-09-13 16:10:11 -070018#include <string>
Shawn Willden274bb552020-09-30 22:39:22 -060019#define LOG_TAG "VtsRemotelyProvisionableComponentTests"
20
Max Bires261a0492021-04-19 18:55:56 -070021#include <AndroidRemotelyProvisionedComponentDevice.h>
Shawn Willden274bb552020-09-30 22:39:22 -060022#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
23#include <aidl/android/hardware/security/keymint/SecurityLevel.h>
24#include <android/binder_manager.h>
Seth Moorefc86bf42021-12-09 14:07:04 -080025#include <binder/IServiceManager.h>
Shawn Willden274bb552020-09-30 22:39:22 -060026#include <cppbor_parse.h>
Shawn Willden274bb552020-09-30 22:39:22 -060027#include <gmock/gmock.h>
Max Bires9704ff62021-04-07 11:12:01 -070028#include <keymaster/cppcose/cppcose.h>
Shawn Willden274bb552020-09-30 22:39:22 -060029#include <keymaster/keymaster_configuration.h>
David Drysdalef0d516d2021-03-22 07:51:43 +000030#include <keymint_support/authorization_set.h>
31#include <openssl/ec.h>
32#include <openssl/ec_key.h>
33#include <openssl/x509.h>
Shawn Willden274bb552020-09-30 22:39:22 -060034#include <remote_prov/remote_prov_utils.h>
Max Bires757ed422022-09-07 16:20:31 -070035#include <optional>
Seth Moorefc86bf42021-12-09 14:07:04 -080036#include <set>
Seth Moore42c11332021-07-02 15:38:17 -070037#include <vector>
Shawn Willden274bb552020-09-30 22:39:22 -060038
David Drysdalef0d516d2021-03-22 07:51:43 +000039#include "KeyMintAidlTestBase.h"
40
Shawn Willden274bb552020-09-30 22:39:22 -060041namespace aidl::android::hardware::security::keymint::test {
42
43using ::std::string;
44using ::std::vector;
45
46namespace {
47
Seth Moorefc86bf42021-12-09 14:07:04 -080048constexpr int32_t VERSION_WITH_UNIQUE_ID_SUPPORT = 2;
49
Shawn Willden274bb552020-09-30 22:39:22 -060050#define INSTANTIATE_REM_PROV_AIDL_TEST(name) \
Seth Moore6305e232021-07-27 14:20:17 -070051 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name); \
Shawn Willden274bb552020-09-30 22:39:22 -060052 INSTANTIATE_TEST_SUITE_P( \
53 PerInstance, name, \
54 testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
55 ::android::PrintInstanceNameToString)
56
Seth Moorefc86bf42021-12-09 14:07:04 -080057using ::android::sp;
Shawn Willden274bb552020-09-30 22:39:22 -060058using bytevec = std::vector<uint8_t>;
59using testing::MatchesRegex;
60using namespace remote_prov;
61using namespace keymaster;
62
63bytevec string_to_bytevec(const char* s) {
64 const uint8_t* p = reinterpret_cast<const uint8_t*>(s);
65 return bytevec(p, p + strlen(s));
66}
67
David Drysdalee99ed862021-03-15 16:43:06 +000068ErrMsgOr<MacedPublicKey> corrupt_maced_key(const MacedPublicKey& macedPubKey) {
69 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
70 if (!coseMac0 || coseMac0->asArray()->size() != kCoseMac0EntryCount) {
71 return "COSE Mac0 parse failed";
72 }
73 auto protParams = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
74 auto unprotParams = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
75 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
76 auto tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
77 if (!protParams || !unprotParams || !payload || !tag) {
78 return "Invalid COSE_Sign1: missing content";
79 }
80 auto corruptMac0 = cppbor::Array();
81 corruptMac0.add(protParams->clone());
82 corruptMac0.add(unprotParams->clone());
83 corruptMac0.add(payload->clone());
84 vector<uint8_t> tagData = tag->value();
85 tagData[0] ^= 0x08;
86 tagData[tagData.size() - 1] ^= 0x80;
87 corruptMac0.add(cppbor::Bstr(tagData));
88
89 return MacedPublicKey{corruptMac0.encode()};
90}
91
David Drysdalecceca9f2021-03-12 15:49:47 +000092ErrMsgOr<cppbor::Array> corrupt_sig(const cppbor::Array* coseSign1) {
93 if (coseSign1->size() != kCoseSign1EntryCount) {
94 return "Invalid COSE_Sign1, wrong entry count";
95 }
96 const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
97 const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
98 const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
99 const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
100 if (!protectedParams || !unprotectedParams || !payload || !signature) {
101 return "Invalid COSE_Sign1: missing content";
102 }
103
104 auto corruptSig = cppbor::Array();
105 corruptSig.add(protectedParams->clone());
106 corruptSig.add(unprotectedParams->clone());
107 corruptSig.add(payload->clone());
108 vector<uint8_t> sigData = signature->value();
109 sigData[0] ^= 0x08;
110 corruptSig.add(cppbor::Bstr(sigData));
111
112 return std::move(corruptSig);
113}
114
Seth Moore19acbe92021-06-23 15:15:52 -0700115ErrMsgOr<bytevec> corrupt_sig_chain(const bytevec& encodedEekChain, int which) {
116 auto [chain, _, parseErr] = cppbor::parse(encodedEekChain);
David Drysdalecceca9f2021-03-12 15:49:47 +0000117 if (!chain || !chain->asArray()) {
118 return "EekChain parse failed";
119 }
120
121 cppbor::Array* eekChain = chain->asArray();
122 if (which >= eekChain->size()) {
123 return "selected sig out of range";
124 }
125 auto corruptChain = cppbor::Array();
126
127 for (int ii = 0; ii < eekChain->size(); ++ii) {
128 if (ii == which) {
129 auto sig = corrupt_sig(eekChain->get(which)->asArray());
130 if (!sig) {
131 return "Failed to build corrupted signature" + sig.moveMessage();
132 }
133 corruptChain.add(sig.moveValue());
134 } else {
135 corruptChain.add(eekChain->get(ii)->clone());
136 }
137 }
Seth Moore19acbe92021-06-23 15:15:52 -0700138 return corruptChain.encode();
David Drysdalecceca9f2021-03-12 15:49:47 +0000139}
140
David Drysdale4d3c2982021-03-31 18:21:40 +0100141string device_suffix(const string& name) {
142 size_t pos = name.find('/');
143 if (pos == string::npos) {
144 return name;
145 }
146 return name.substr(pos + 1);
147}
148
149bool matching_keymint_device(const string& rp_name, std::shared_ptr<IKeyMintDevice>* keyMint) {
150 string rp_suffix = device_suffix(rp_name);
151
152 vector<string> km_names = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
153 for (const string& km_name : km_names) {
154 // If the suffix of the KeyMint instance equals the suffix of the
155 // RemotelyProvisionedComponent instance, assume they match.
156 if (device_suffix(km_name) == rp_suffix && AServiceManager_isDeclared(km_name.c_str())) {
157 ::ndk::SpAIBinder binder(AServiceManager_waitForService(km_name.c_str()));
158 *keyMint = IKeyMintDevice::fromBinder(binder);
159 return true;
160 }
161 }
162 return false;
163}
164
Shawn Willden274bb552020-09-30 22:39:22 -0600165} // namespace
166
167class VtsRemotelyProvisionedComponentTests : public testing::TestWithParam<std::string> {
168 public:
169 virtual void SetUp() override {
170 if (AServiceManager_isDeclared(GetParam().c_str())) {
171 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
172 provisionable_ = IRemotelyProvisionedComponent::fromBinder(binder);
173 }
174 ASSERT_NE(provisionable_, nullptr);
subrahmanyamanfb213d62022-02-02 23:10:55 +0000175 ASSERT_TRUE(provisionable_->getHardwareInfo(&rpcHardwareInfo).isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600176 }
177
178 static vector<string> build_params() {
179 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
180 return params;
181 }
182
183 protected:
184 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000185 RpcHardwareInfo rpcHardwareInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600186};
187
Seth Moorefc86bf42021-12-09 14:07:04 -0800188/**
189 * Verify that every implementation reports a different unique id.
190 */
191TEST(NonParameterizedTests, eachRpcHasAUniqueId) {
192 std::set<std::string> uniqueIds;
193 for (auto hal : ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor)) {
194 ASSERT_TRUE(AServiceManager_isDeclared(hal.c_str()));
195 ::ndk::SpAIBinder binder(AServiceManager_waitForService(hal.c_str()));
196 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
197 IRemotelyProvisionedComponent::fromBinder(binder);
198 ASSERT_NE(rpc, nullptr);
199
200 RpcHardwareInfo hwInfo;
201 ASSERT_TRUE(rpc->getHardwareInfo(&hwInfo).isOk());
202
203 int32_t version;
204 ASSERT_TRUE(rpc->getInterfaceVersion(&version).isOk());
205 if (version >= VERSION_WITH_UNIQUE_ID_SUPPORT) {
206 ASSERT_TRUE(hwInfo.uniqueId);
207 auto [_, wasInserted] = uniqueIds.insert(*hwInfo.uniqueId);
208 EXPECT_TRUE(wasInserted);
209 } else {
210 ASSERT_FALSE(hwInfo.uniqueId);
211 }
212 }
213}
214
215using GetHardwareInfoTests = VtsRemotelyProvisionedComponentTests;
216
217INSTANTIATE_REM_PROV_AIDL_TEST(GetHardwareInfoTests);
218
219/**
220 * Verify that a valid curve is reported by the implementation.
221 */
222TEST_P(GetHardwareInfoTests, supportsValidCurve) {
223 RpcHardwareInfo hwInfo;
224 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
225
226 const std::set<int> validCurves = {RpcHardwareInfo::CURVE_P256, RpcHardwareInfo::CURVE_25519};
227 ASSERT_EQ(validCurves.count(hwInfo.supportedEekCurve), 1)
228 << "Invalid curve: " << hwInfo.supportedEekCurve;
229}
230
231/**
232 * Verify that the unique id is within the length limits as described in RpcHardwareInfo.aidl.
233 */
234TEST_P(GetHardwareInfoTests, uniqueId) {
235 int32_t version;
236 ASSERT_TRUE(provisionable_->getInterfaceVersion(&version).isOk());
237
238 if (version < VERSION_WITH_UNIQUE_ID_SUPPORT) {
239 return;
240 }
241
242 RpcHardwareInfo hwInfo;
243 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
244 ASSERT_TRUE(hwInfo.uniqueId);
245 EXPECT_GE(hwInfo.uniqueId->size(), 1);
246 EXPECT_LE(hwInfo.uniqueId->size(), 32);
247}
248
Shawn Willden274bb552020-09-30 22:39:22 -0600249using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
250
251INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
252
253/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000254 * Generate and validate a production-mode key. MAC tag can't be verified, but
255 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600256 */
Max Bires126869a2021-02-21 18:32:59 -0800257TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600258 MacedPublicKey macedPubKey;
259 bytevec privateKeyBlob;
260 bool testMode = false;
261 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
262 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000263 vector<uint8_t> coseKeyData;
264 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100265}
266
267/**
268 * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
269 */
270TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
271 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
272 std::shared_ptr<IKeyMintDevice> keyMint;
273 if (!matching_keymint_device(GetParam(), &keyMint)) {
274 // No matching IKeyMintDevice.
275 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
276 return;
277 }
278 KeyMintHardwareInfo info;
279 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
280
281 MacedPublicKey macedPubKey;
282 bytevec privateKeyBlob;
283 bool testMode = false;
284 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
285 ASSERT_TRUE(status.isOk());
286 vector<uint8_t> coseKeyData;
287 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
288
David Drysdalef0d516d2021-03-22 07:51:43 +0000289 AttestationKey attestKey;
290 attestKey.keyBlob = std::move(privateKeyBlob);
291 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600292
David Drysdalef0d516d2021-03-22 07:51:43 +0000293 // Generate an ECDSA key that is attested by the generated P256 keypair.
294 AuthorizationSet keyDesc = AuthorizationSetBuilder()
295 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale915ce252021-10-14 15:17:36 +0100296 .EcdsaSigningKey(EcCurve::P_256)
David Drysdalef0d516d2021-03-22 07:51:43 +0000297 .AttestationChallenge("foo")
298 .AttestationApplicationId("bar")
299 .Digest(Digest::NONE)
300 .SetDefaultValidity();
301 KeyCreationResult creationResult;
302 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
303 ASSERT_TRUE(result.isOk());
304 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
305 vector<KeyCharacteristics> attested_key_characteristics =
306 std::move(creationResult.keyCharacteristics);
307 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
308 EXPECT_EQ(attested_key_cert_chain.size(), 1);
309
David Drysdale7dff4fc2021-12-10 10:10:52 +0000310 int32_t aidl_version = 0;
311 ASSERT_TRUE(keyMint->getInterfaceVersion(&aidl_version).isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000312 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
313 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +0000314 EXPECT_TRUE(verify_attestation_record(aidl_version, "foo", "bar", sw_enforced, hw_enforced,
David Drysdalef0d516d2021-03-22 07:51:43 +0000315 info.securityLevel,
316 attested_key_cert_chain[0].encodedCertificate));
317
318 // Attestation by itself is not valid (last entry is not self-signed).
319 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
320
321 // The signature over the attested key should correspond to the P256 public key.
322 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
323 ASSERT_TRUE(key_cert.get());
324 EVP_PKEY_Ptr signing_pubkey;
325 p256_pub_key(coseKeyData, &signing_pubkey);
326 ASSERT_TRUE(signing_pubkey.get());
327
328 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
329 << "Verification of attested certificate failed "
330 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600331}
332
333/**
334 * Generate and validate a test-mode key.
335 */
Max Bires126869a2021-02-21 18:32:59 -0800336TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600337 MacedPublicKey macedPubKey;
338 bytevec privateKeyBlob;
339 bool testMode = true;
340 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
341 ASSERT_TRUE(status.isOk());
342
David Drysdalec8400772021-03-11 12:35:11 +0000343 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600344}
345
346class CertificateRequestTest : public VtsRemotelyProvisionedComponentTests {
347 protected:
Max Bires89c74882022-03-27 21:06:11 -0700348 CertificateRequestTest() : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(64)) {}
David Drysdalecceca9f2021-03-12 15:49:47 +0000349
Seth Moore19acbe92021-06-23 15:15:52 -0700350 void generateTestEekChain(size_t eekLength) {
subrahmanyamanfb213d62022-02-02 23:10:55 +0000351 auto chain = generateEekChain(rpcHardwareInfo.supportedEekCurve, eekLength, eekId_);
David Drysdale08696a72022-03-10 10:43:25 +0000352 ASSERT_TRUE(chain) << chain.message();
Seth Moore19acbe92021-06-23 15:15:52 -0700353 if (chain) testEekChain_ = chain.moveValue();
354 testEekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600355 }
356
357 void generateKeys(bool testMode, size_t numKeys) {
358 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
359 cborKeysToSign_ = cppbor::Array();
360
361 for (auto& key : keysToSign_) {
362 bytevec privateKeyBlob;
363 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
364 ASSERT_TRUE(status.isOk()) << status.getMessage();
365
David Drysdalec8400772021-03-11 12:35:11 +0000366 vector<uint8_t> payload_value;
367 check_maced_pubkey(key, testMode, &payload_value);
368 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600369 }
370 }
371
372 bytevec eekId_;
Seth Moore19acbe92021-06-23 15:15:52 -0700373 size_t testEekLength_;
374 EekChain testEekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000375 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600376 std::vector<MacedPublicKey> keysToSign_;
377 cppbor::Array cborKeysToSign_;
378};
379
380/**
381 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
382 * content.
383 */
Max Bires126869a2021-02-21 18:32:59 -0800384TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600385 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000386 for (size_t eekLength : {2, 3, 7}) {
387 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700388 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600389
David Drysdalecceca9f2021-03-12 15:49:47 +0000390 bytevec keysToSignMac;
391 DeviceInfo deviceInfo;
392 ProtectedData protectedData;
393 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700394 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalecceca9f2021-03-12 15:49:47 +0000395 &protectedData, &keysToSignMac);
396 ASSERT_TRUE(status.isOk()) << status.getMessage();
397
Seth Moore2fc6f832022-09-13 16:10:11 -0700398 auto result = verifyProductionProtectedData(
399 deviceInfo, cppbor::Array(), keysToSignMac, protectedData, testEekChain_, eekId_,
400 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
401 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000402 }
Shawn Willden274bb552020-09-30 22:39:22 -0600403}
404
405/**
Seth Moore42c11332021-07-02 15:38:17 -0700406 * Ensure that test mode outputs a unique BCC root key every time we request a
407 * certificate request. Else, it's possible that the test mode API could be used
408 * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
409 * device public key multiple times.
410 */
411TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
412 constexpr bool testMode = true;
Seth Moore42c11332021-07-02 15:38:17 -0700413
414 bytevec keysToSignMac;
415 DeviceInfo deviceInfo;
416 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000417 generateTestEekChain(3);
Seth Moore42c11332021-07-02 15:38:17 -0700418 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700419 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
420 &protectedData, &keysToSignMac);
Seth Moore42c11332021-07-02 15:38:17 -0700421 ASSERT_TRUE(status.isOk()) << status.getMessage();
422
Seth Moore2fc6f832022-09-13 16:10:11 -0700423 auto firstBcc = verifyProductionProtectedData(
424 deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
425 eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
426 ASSERT_TRUE(firstBcc) << firstBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700427
Seth Moore19acbe92021-06-23 15:15:52 -0700428 status = provisionable_->generateCertificateRequest(
429 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
430 &protectedData, &keysToSignMac);
Seth Moore42c11332021-07-02 15:38:17 -0700431 ASSERT_TRUE(status.isOk()) << status.getMessage();
432
Seth Moore2fc6f832022-09-13 16:10:11 -0700433 auto secondBcc = verifyProductionProtectedData(
434 deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
435 eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
436 ASSERT_TRUE(secondBcc) << secondBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700437
438 // Verify that none of the keys in the first BCC are repeated in the second one.
Seth Moore2fc6f832022-09-13 16:10:11 -0700439 for (const auto& i : *firstBcc) {
440 for (auto& j : *secondBcc) {
Seth Moore42c11332021-07-02 15:38:17 -0700441 ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
442 << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
443 }
444 }
445}
446
447/**
Seth Moore19acbe92021-06-23 15:15:52 -0700448 * Generate an empty certificate request in prod mode. This test must be run explicitly, and
449 * is not run by default. Not all devices are GMS devices, and therefore they do not all
450 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600451 */
Seth Moore19acbe92021-06-23 15:15:52 -0700452TEST_P(CertificateRequestTest, DISABLED_EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600453 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000454
Seth Moore19acbe92021-06-23 15:15:52 -0700455 bytevec keysToSignMac;
456 DeviceInfo deviceInfo;
457 ProtectedData protectedData;
458 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000459 testMode, {} /* keysToSign */, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
460 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700461 EXPECT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600462}
463
464/**
465 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
466 */
Max Bires126869a2021-02-21 18:32:59 -0800467TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600468 bool testMode = true;
469 generateKeys(testMode, 4 /* numKeys */);
470
David Drysdalecceca9f2021-03-12 15:49:47 +0000471 for (size_t eekLength : {2, 3, 7}) {
472 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700473 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600474
David Drysdalecceca9f2021-03-12 15:49:47 +0000475 bytevec keysToSignMac;
476 DeviceInfo deviceInfo;
477 ProtectedData protectedData;
478 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700479 testMode, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo, &protectedData,
David Drysdalecceca9f2021-03-12 15:49:47 +0000480 &keysToSignMac);
481 ASSERT_TRUE(status.isOk()) << status.getMessage();
482
Seth Moore2fc6f832022-09-13 16:10:11 -0700483 auto result = verifyProductionProtectedData(
484 deviceInfo, cborKeysToSign_, keysToSignMac, protectedData, testEekChain_, eekId_,
485 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
486 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000487 }
Shawn Willden274bb552020-09-30 22:39:22 -0600488}
489
490/**
Seth Moore19acbe92021-06-23 15:15:52 -0700491 * Generate a non-empty certificate request in prod mode. This test must be run explicitly, and
492 * is not run by default. Not all devices are GMS devices, and therefore they do not all
493 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600494 */
Seth Moore19acbe92021-06-23 15:15:52 -0700495TEST_P(CertificateRequestTest, DISABLED_NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600496 bool testMode = false;
497 generateKeys(testMode, 4 /* numKeys */);
498
Seth Moore19acbe92021-06-23 15:15:52 -0700499 bytevec keysToSignMac;
500 DeviceInfo deviceInfo;
501 ProtectedData protectedData;
502 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000503 testMode, keysToSign_, getProdEekChain(rpcHardwareInfo.supportedEekCurve), challenge_,
504 &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700505 EXPECT_TRUE(status.isOk());
David Drysdalecceca9f2021-03-12 15:49:47 +0000506}
507
508/**
David Drysdalee99ed862021-03-15 16:43:06 +0000509 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
510 */
511TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
512 bool testMode = true;
513 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000514 auto result = corrupt_maced_key(keysToSign_[0]);
515 ASSERT_TRUE(result) << result.moveMessage();
516 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000517
518 bytevec keysToSignMac;
519 DeviceInfo deviceInfo;
520 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000521 generateTestEekChain(3);
David Drysdalee99ed862021-03-15 16:43:06 +0000522 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700523 testMode, {keyWithCorruptMac}, testEekChain_.chain, challenge_, &deviceInfo,
524 &protectedData, &keysToSignMac);
David Drysdalee99ed862021-03-15 16:43:06 +0000525 ASSERT_FALSE(status.isOk()) << status.getMessage();
526 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
527}
528
529/**
530 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
531 */
532TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
Seth Moore19acbe92021-06-23 15:15:52 -0700533 bool testMode = false;
David Drysdalee99ed862021-03-15 16:43:06 +0000534 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000535 auto result = corrupt_maced_key(keysToSign_[0]);
536 ASSERT_TRUE(result) << result.moveMessage();
537 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000538
539 bytevec keysToSignMac;
540 DeviceInfo deviceInfo;
541 ProtectedData protectedData;
542 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000543 testMode, {keyWithCorruptMac}, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
544 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
David Drysdalee99ed862021-03-15 16:43:06 +0000545 ASSERT_FALSE(status.isOk()) << status.getMessage();
Seth Moore19acbe92021-06-23 15:15:52 -0700546 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
David Drysdalee99ed862021-03-15 16:43:06 +0000547}
548
549/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000550 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
551 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000552 */
553TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
554 bool testMode = false;
555 generateKeys(testMode, 4 /* numKeys */);
556
subrahmanyamanfb213d62022-02-02 23:10:55 +0000557 auto prodEekChain = getProdEekChain(rpcHardwareInfo.supportedEekCurve);
Seth Moore19acbe92021-06-23 15:15:52 -0700558 auto [parsedChain, _, parseErr] = cppbor::parse(prodEekChain);
559 ASSERT_NE(parsedChain, nullptr) << parseErr;
560 ASSERT_NE(parsedChain->asArray(), nullptr);
561
562 for (int ii = 0; ii < parsedChain->asArray()->size(); ++ii) {
563 auto chain = corrupt_sig_chain(prodEekChain, ii);
David Drysdalecceca9f2021-03-12 15:49:47 +0000564 ASSERT_TRUE(chain) << chain.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000565
566 bytevec keysToSignMac;
567 DeviceInfo deviceInfo;
568 ProtectedData protectedData;
Seth Moore19acbe92021-06-23 15:15:52 -0700569 auto status = provisionable_->generateCertificateRequest(testMode, keysToSign_, *chain,
570 challenge_, &deviceInfo,
571 &protectedData, &keysToSignMac);
David Drysdalecceca9f2021-03-12 15:49:47 +0000572 ASSERT_FALSE(status.isOk());
573 ASSERT_EQ(status.getServiceSpecificError(),
574 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
575 }
576}
577
578/**
579 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
580 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000581 */
582TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
583 bool testMode = false;
584 generateKeys(testMode, 4 /* numKeys */);
585
586 // Build an EEK chain that omits the first self-signed cert.
587 auto truncatedChain = cppbor::Array();
subrahmanyamanfb213d62022-02-02 23:10:55 +0000588 auto [chain, _, parseErr] = cppbor::parse(getProdEekChain(rpcHardwareInfo.supportedEekCurve));
David Drysdalecceca9f2021-03-12 15:49:47 +0000589 ASSERT_TRUE(chain);
590 auto eekChain = chain->asArray();
591 ASSERT_NE(eekChain, nullptr);
592 for (size_t ii = 1; ii < eekChain->size(); ii++) {
593 truncatedChain.add(eekChain->get(ii)->clone());
594 }
595
Shawn Willden274bb552020-09-30 22:39:22 -0600596 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700597 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600598 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000599 auto status = provisionable_->generateCertificateRequest(
600 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
601 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600602 ASSERT_FALSE(status.isOk());
603 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
604}
605
606/**
607 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
608 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
609 */
Max Bires126869a2021-02-21 18:32:59 -0800610TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600611 generateKeys(false /* testMode */, 2 /* numKeys */);
612
613 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700614 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600615 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000616 generateTestEekChain(3);
Max Biresfdbb9042021-03-23 12:43:38 -0700617 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700618 true /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700619 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600620 ASSERT_FALSE(status.isOk());
621 ASSERT_EQ(status.getServiceSpecificError(),
622 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
623}
624
625/**
626 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
627 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
628 */
Max Bires126869a2021-02-21 18:32:59 -0800629TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600630 generateKeys(true /* testMode */, 2 /* numKeys */);
631
632 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700633 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600634 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000635 generateTestEekChain(3);
Shawn Willden274bb552020-09-30 22:39:22 -0600636 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700637 false /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalec8400772021-03-11 12:35:11 +0000638 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600639 ASSERT_FALSE(status.isOk());
640 ASSERT_EQ(status.getServiceSpecificError(),
641 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
642}
643
644INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
645
646} // namespace aidl::android::hardware::security::keymint::test