1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <memory>
18 #include <string>
19 #define LOG_TAG "VtsRemotelyProvisionableComponentTests"
20 
21 #include <aidl/android/hardware/security/keymint/BnRemotelyProvisionedComponent.h>
22 #include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
23 #include <aidl/android/hardware/security/keymint/SecurityLevel.h>
24 #include <android/binder_manager.h>
25 #include <binder/IServiceManager.h>
26 #include <cppbor.h>
27 #include <cppbor_parse.h>
28 #include <gmock/gmock.h>
29 #include <keymaster/cppcose/cppcose.h>
30 #include <keymaster/keymaster_configuration.h>
31 #include <keymint_support/authorization_set.h>
32 #include <openssl/ec.h>
33 #include <openssl/ec_key.h>
34 #include <openssl/x509.h>
35 #include <remote_prov/remote_prov_utils.h>
36 #include <optional>
37 #include <set>
38 #include <vector>
39 
40 #include "KeyMintAidlTestBase.h"
41 
42 namespace aidl::android::hardware::security::keymint::test {
43 
44 using ::std::string;
45 using ::std::vector;
46 
47 namespace {
48 
49 constexpr int32_t VERSION_WITH_UNIQUE_ID_SUPPORT = 2;
50 
51 constexpr int32_t VERSION_WITHOUT_EEK = 3;
52 constexpr int32_t VERSION_WITHOUT_TEST_MODE = 3;
53 constexpr int32_t VERSION_WITH_CERTIFICATE_REQUEST_V2 = 3;
54 constexpr int32_t VERSION_WITH_SUPPORTED_NUM_KEYS_IN_CSR = 3;
55 
56 constexpr uint8_t MIN_CHALLENGE_SIZE = 0;
57 constexpr uint8_t MAX_CHALLENGE_SIZE = 64;
58 const string DEFAULT_INSTANCE_NAME =
59         "android.hardware.security.keymint.IRemotelyProvisionedComponent/default";
60 const string RKP_VM_INSTANCE_NAME =
61         "android.hardware.security.keymint.IRemotelyProvisionedComponent/avf";
62 const string KEYMINT_STRONGBOX_INSTANCE_NAME =
63         "android.hardware.security.keymint.IKeyMintDevice/strongbox";
64 
65 #define INSTANTIATE_REM_PROV_AIDL_TEST(name)                                         \
66     GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name);                             \
67     INSTANTIATE_TEST_SUITE_P(                                                        \
68             PerInstance, name,                                                       \
69             testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
70             ::android::PrintInstanceNameToString)
71 
72 using ::android::sp;
73 using bytevec = std::vector<uint8_t>;
74 using testing::MatchesRegex;
75 using namespace remote_prov;
76 using namespace keymaster;
77 
string_to_bytevec(const char * s)78 bytevec string_to_bytevec(const char* s) {
79     const uint8_t* p = reinterpret_cast<const uint8_t*>(s);
80     return bytevec(p, p + strlen(s));
81 }
82 
corrupt_maced_key(const MacedPublicKey & macedPubKey)83 ErrMsgOr<MacedPublicKey> corrupt_maced_key(const MacedPublicKey& macedPubKey) {
84     auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
85     if (!coseMac0 || coseMac0->asArray()->size() != kCoseMac0EntryCount) {
86         return "COSE Mac0 parse failed";
87     }
88     auto protParams = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
89     auto unprotParams = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
90     auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
91     auto tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
92     if (!protParams || !unprotParams || !payload || !tag) {
93         return "Invalid COSE_Sign1: missing content";
94     }
95     auto corruptMac0 = cppbor::Array();
96     corruptMac0.add(protParams->clone());
97     corruptMac0.add(unprotParams->clone());
98     corruptMac0.add(payload->clone());
99     vector<uint8_t> tagData = tag->value();
100     tagData[0] ^= 0x08;
101     tagData[tagData.size() - 1] ^= 0x80;
102     corruptMac0.add(cppbor::Bstr(tagData));
103 
104     return MacedPublicKey{corruptMac0.encode()};
105 }
106 
corrupt_sig(const cppbor::Array * coseSign1)107 ErrMsgOr<cppbor::Array> corrupt_sig(const cppbor::Array* coseSign1) {
108     if (coseSign1->size() != kCoseSign1EntryCount) {
109         return "Invalid COSE_Sign1, wrong entry count";
110     }
111     const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
112     const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
113     const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
114     const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
115     if (!protectedParams || !unprotectedParams || !payload || !signature) {
116         return "Invalid COSE_Sign1: missing content";
117     }
118 
119     auto corruptSig = cppbor::Array();
120     corruptSig.add(protectedParams->clone());
121     corruptSig.add(unprotectedParams->clone());
122     corruptSig.add(payload->clone());
123     vector<uint8_t> sigData = signature->value();
124     sigData[0] ^= 0x08;
125     corruptSig.add(cppbor::Bstr(sigData));
126 
127     return std::move(corruptSig);
128 }
129 
corrupt_sig_chain(const bytevec & encodedEekChain,int which)130 ErrMsgOr<bytevec> corrupt_sig_chain(const bytevec& encodedEekChain, int which) {
131     auto [chain, _, parseErr] = cppbor::parse(encodedEekChain);
132     if (!chain || !chain->asArray()) {
133         return "EekChain parse failed";
134     }
135 
136     cppbor::Array* eekChain = chain->asArray();
137     if (which >= eekChain->size()) {
138         return "selected sig out of range";
139     }
140     auto corruptChain = cppbor::Array();
141 
142     for (int ii = 0; ii < eekChain->size(); ++ii) {
143         if (ii == which) {
144             auto sig = corrupt_sig(eekChain->get(which)->asArray());
145             if (!sig) {
146                 return "Failed to build corrupted signature" + sig.moveMessage();
147             }
148             corruptChain.add(sig.moveValue());
149         } else {
150             corruptChain.add(eekChain->get(ii)->clone());
151         }
152     }
153     return corruptChain.encode();
154 }
155 
device_suffix(const string & name)156 string device_suffix(const string& name) {
157     size_t pos = name.find('/');
158     if (pos == string::npos) {
159         return name;
160     }
161     return name.substr(pos + 1);
162 }
163 
matching_keymint_device(const string & rp_name,std::shared_ptr<IKeyMintDevice> * keyMint)164 bool matching_keymint_device(const string& rp_name, std::shared_ptr<IKeyMintDevice>* keyMint) {
165     string rp_suffix = device_suffix(rp_name);
166 
167     vector<string> km_names = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
168     for (const string& km_name : km_names) {
169         // If the suffix of the KeyMint instance equals the suffix of the
170         // RemotelyProvisionedComponent instance, assume they match.
171         if (device_suffix(km_name) == rp_suffix && AServiceManager_isDeclared(km_name.c_str())) {
172             ::ndk::SpAIBinder binder(AServiceManager_waitForService(km_name.c_str()));
173             *keyMint = IKeyMintDevice::fromBinder(binder);
174             return true;
175         }
176     }
177     return false;
178 }
179 
180 }  // namespace
181 
182 class VtsRemotelyProvisionedComponentTests : public testing::TestWithParam<std::string> {
183   public:
SetUp()184     virtual void SetUp() override {
185         if (AServiceManager_isDeclared(GetParam().c_str())) {
186             ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
187             provisionable_ = IRemotelyProvisionedComponent::fromBinder(binder);
188         }
189         ASSERT_NE(provisionable_, nullptr);
190         auto status = provisionable_->getHardwareInfo(&rpcHardwareInfo);
191         if (GetParam() == RKP_VM_INSTANCE_NAME) {
192             if (status.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
193                 GTEST_SKIP() << "The RKP VM is not supported on this system.";
194             }
195             int apiLevel = get_vsr_api_level();
196             if (apiLevel < __ANDROID_API_V__) {
197                 GTEST_SKIP() << "The RKP VM is supported only on V+ devices. Vendor API level: "
198                              << apiLevel;
199             }
200         }
201         ASSERT_TRUE(status.isOk());
202     }
203 
build_params()204     static vector<string> build_params() {
205         auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
206         return params;
207     }
208 
209   protected:
210     std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
211     RpcHardwareInfo rpcHardwareInfo;
212 };
213 
214 /**
215  * Verify that every implementation reports a different unique id.
216  */
TEST(NonParameterizedTests,eachRpcHasAUniqueId)217 TEST(NonParameterizedTests, eachRpcHasAUniqueId) {
218     std::set<std::string> uniqueIds;
219     for (auto hal : ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor)) {
220         ASSERT_TRUE(AServiceManager_isDeclared(hal.c_str()));
221         ::ndk::SpAIBinder binder(AServiceManager_waitForService(hal.c_str()));
222         std::shared_ptr<IRemotelyProvisionedComponent> rpc =
223                 IRemotelyProvisionedComponent::fromBinder(binder);
224         ASSERT_NE(rpc, nullptr);
225 
226         RpcHardwareInfo hwInfo;
227         auto status = rpc->getHardwareInfo(&hwInfo);
228         if (hal == RKP_VM_INSTANCE_NAME && status.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
229             GTEST_SKIP() << "The RKP VM is not supported on this system.";
230         }
231         ASSERT_TRUE(status.isOk());
232 
233         if (hwInfo.versionNumber >= VERSION_WITH_UNIQUE_ID_SUPPORT) {
234             ASSERT_TRUE(hwInfo.uniqueId);
235             auto [_, wasInserted] = uniqueIds.insert(*hwInfo.uniqueId);
236             EXPECT_TRUE(wasInserted);
237         } else {
238             ASSERT_FALSE(hwInfo.uniqueId);
239         }
240     }
241 }
242 
243 /**
244  * Verify that the default implementation supports DICE if there is a StrongBox KeyMint instance
245  * on the device.
246  */
247 // @VsrTest = 3.10-015
TEST(NonParameterizedTests,requireDiceOnDefaultInstanceIfStrongboxPresent)248 TEST(NonParameterizedTests, requireDiceOnDefaultInstanceIfStrongboxPresent) {
249     int vsr_api_level = get_vsr_api_level();
250     if (vsr_api_level < 35) {
251         GTEST_SKIP() << "Applies only to VSR API level 35 or newer, this device is: "
252                      << vsr_api_level;
253     }
254 
255     if (!AServiceManager_isDeclared(KEYMINT_STRONGBOX_INSTANCE_NAME.c_str())) {
256         GTEST_SKIP() << "Strongbox is not present on this device.";
257     }
258 
259     ::ndk::SpAIBinder binder(AServiceManager_waitForService(DEFAULT_INSTANCE_NAME.c_str()));
260     std::shared_ptr<IRemotelyProvisionedComponent> rpc =
261             IRemotelyProvisionedComponent::fromBinder(binder);
262     ASSERT_NE(rpc, nullptr);
263 
264     bytevec challenge = randomBytes(64);
265     bytevec csr;
266     auto status = rpc->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
267     EXPECT_TRUE(status.isOk()) << status.getDescription();
268 
269     auto result = isCsrWithProperDiceChain(csr);
270     ASSERT_TRUE(result) << result.message();
271     ASSERT_TRUE(*result);
272 }
273 
274 using GetHardwareInfoTests = VtsRemotelyProvisionedComponentTests;
275 
276 INSTANTIATE_REM_PROV_AIDL_TEST(GetHardwareInfoTests);
277 
278 /**
279  * Verify that a valid curve is reported by the implementation.
280  */
TEST_P(GetHardwareInfoTests,supportsValidCurve)281 TEST_P(GetHardwareInfoTests, supportsValidCurve) {
282     RpcHardwareInfo hwInfo;
283     ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
284 
285     if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_EEK) {
286         ASSERT_EQ(hwInfo.supportedEekCurve, RpcHardwareInfo::CURVE_NONE)
287                 << "Invalid curve: " << hwInfo.supportedEekCurve;
288         return;
289     }
290 
291     const std::set<int> validCurves = {RpcHardwareInfo::CURVE_P256, RpcHardwareInfo::CURVE_25519};
292     ASSERT_EQ(validCurves.count(hwInfo.supportedEekCurve), 1)
293             << "Invalid curve: " << hwInfo.supportedEekCurve;
294 }
295 
296 /**
297  * Verify that the unique id is within the length limits as described in RpcHardwareInfo.aidl.
298  */
TEST_P(GetHardwareInfoTests,uniqueId)299 TEST_P(GetHardwareInfoTests, uniqueId) {
300     if (rpcHardwareInfo.versionNumber < VERSION_WITH_UNIQUE_ID_SUPPORT) {
301         return;
302     }
303 
304     RpcHardwareInfo hwInfo;
305     ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
306     ASSERT_TRUE(hwInfo.uniqueId);
307     EXPECT_GE(hwInfo.uniqueId->size(), 1);
308     EXPECT_LE(hwInfo.uniqueId->size(), 32);
309 }
310 
311 /**
312  * Verify implementation supports at least MIN_SUPPORTED_NUM_KEYS_IN_CSR keys in a CSR.
313  */
TEST_P(GetHardwareInfoTests,supportedNumKeysInCsr)314 TEST_P(GetHardwareInfoTests, supportedNumKeysInCsr) {
315     if (rpcHardwareInfo.versionNumber < VERSION_WITH_SUPPORTED_NUM_KEYS_IN_CSR) {
316         return;
317     }
318 
319     RpcHardwareInfo hwInfo;
320     ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
321     ASSERT_GE(hwInfo.supportedNumKeysInCsr, RpcHardwareInfo::MIN_SUPPORTED_NUM_KEYS_IN_CSR);
322 }
323 
324 using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
325 
326 INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
327 
328 /**
329  * Generate and validate a production-mode key.  MAC tag can't be verified, but
330  * the private key blob should be usable in KeyMint operations.
331  */
TEST_P(GenerateKeyTests,generateEcdsaP256Key_prodMode)332 TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
333     MacedPublicKey macedPubKey;
334     bytevec privateKeyBlob;
335     bool testMode = false;
336     auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
337     ASSERT_TRUE(status.isOk());
338     vector<uint8_t> coseKeyData;
339     check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
340 }
341 
342 /**
343  * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
344  */
TEST_P(GenerateKeyTests,generateAndUseEcdsaP256Key_prodMode)345 TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
346     // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
347     std::shared_ptr<IKeyMintDevice> keyMint;
348     if (!matching_keymint_device(GetParam(), &keyMint)) {
349         // No matching IKeyMintDevice.
350         GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
351         return;
352     }
353     KeyMintHardwareInfo info;
354     ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
355 
356     MacedPublicKey macedPubKey;
357     bytevec privateKeyBlob;
358     bool testMode = false;
359     auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
360     ASSERT_TRUE(status.isOk());
361     vector<uint8_t> coseKeyData;
362     check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
363 
364     AttestationKey attestKey;
365     attestKey.keyBlob = std::move(privateKeyBlob);
366     attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
367 
368     // Generate an ECDSA key that is attested by the generated P256 keypair.
369     AuthorizationSet keyDesc = AuthorizationSetBuilder()
370                                        .Authorization(TAG_NO_AUTH_REQUIRED)
371                                        .EcdsaSigningKey(EcCurve::P_256)
372                                        .AttestationChallenge("foo")
373                                        .AttestationApplicationId("bar")
374                                        .Digest(Digest::NONE)
375                                        .SetDefaultValidity();
376     KeyCreationResult creationResult;
377     auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
378     ASSERT_TRUE(result.isOk());
379     vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
380     vector<KeyCharacteristics> attested_key_characteristics =
381             std::move(creationResult.keyCharacteristics);
382     vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
383     EXPECT_EQ(attested_key_cert_chain.size(), 1);
384 
385     int32_t aidl_version = 0;
386     ASSERT_TRUE(keyMint->getInterfaceVersion(&aidl_version).isOk());
387     AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
388     AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
389     EXPECT_TRUE(verify_attestation_record(aidl_version, "foo", "bar", sw_enforced, hw_enforced,
390                                           info.securityLevel,
391                                           attested_key_cert_chain[0].encodedCertificate));
392 
393     // Attestation by itself is not valid (last entry is not self-signed).
394     EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
395 
396     // The signature over the attested key should correspond to the P256 public key.
397     X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
398     ASSERT_TRUE(key_cert.get());
399     EVP_PKEY_Ptr signing_pubkey;
400     p256_pub_key(coseKeyData, &signing_pubkey);
401     ASSERT_TRUE(signing_pubkey.get());
402 
403     ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
404             << "Verification of attested certificate failed "
405             << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
406 }
407 
408 /**
409  * Generate and validate a test-mode key.
410  */
TEST_P(GenerateKeyTests,generateEcdsaP256Key_testMode)411 TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
412     MacedPublicKey macedPubKey;
413     bytevec privateKeyBlob;
414     bool testMode = true;
415     auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
416 
417     if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_TEST_MODE) {
418         ASSERT_FALSE(status.isOk());
419         EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
420         return;
421     }
422 
423     ASSERT_TRUE(status.isOk());
424     check_maced_pubkey(macedPubKey, testMode, nullptr);
425 }
426 
427 class CertificateRequestTestBase : public VtsRemotelyProvisionedComponentTests {
428   protected:
CertificateRequestTestBase()429     CertificateRequestTestBase()
430         : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(64)) {}
431 
generateTestEekChain(size_t eekLength)432     void generateTestEekChain(size_t eekLength) {
433         auto chain = generateEekChain(rpcHardwareInfo.supportedEekCurve, eekLength, eekId_);
434         ASSERT_TRUE(chain) << chain.message();
435         if (chain) testEekChain_ = chain.moveValue();
436         testEekLength_ = eekLength;
437     }
438 
generateKeys(bool testMode,size_t numKeys)439     void generateKeys(bool testMode, size_t numKeys) {
440         keysToSign_ = std::vector<MacedPublicKey>(numKeys);
441         cborKeysToSign_ = cppbor::Array();
442 
443         for (auto& key : keysToSign_) {
444             bytevec privateKeyBlob;
445             auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
446             ASSERT_TRUE(status.isOk()) << status.getDescription();
447 
448             vector<uint8_t> payload_value;
449             check_maced_pubkey(key, testMode, &payload_value);
450             cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
451         }
452     }
453 
454     bytevec eekId_;
455     size_t testEekLength_;
456     EekChain testEekChain_;
457     bytevec challenge_;
458     std::vector<MacedPublicKey> keysToSign_;
459     cppbor::Array cborKeysToSign_;
460 };
461 
462 class CertificateRequestTest : public CertificateRequestTestBase {
463   protected:
SetUp()464     void SetUp() override {
465         CertificateRequestTestBase::SetUp();
466         ASSERT_FALSE(HasFatalFailure());
467 
468         if (rpcHardwareInfo.versionNumber >= VERSION_WITH_CERTIFICATE_REQUEST_V2) {
469             GTEST_SKIP() << "This test case only applies to RKP v1 and v2. "
470                          << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
471         }
472     }
473 };
474 
475 /**
476  * Generate an empty certificate request in test mode, and decrypt and verify the structure and
477  * content.
478  */
TEST_P(CertificateRequestTest,EmptyRequest_testMode)479 TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
480     bool testMode = true;
481     for (size_t eekLength : {2, 3, 7}) {
482         SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
483         generateTestEekChain(eekLength);
484 
485         bytevec keysToSignMac;
486         DeviceInfo deviceInfo;
487         ProtectedData protectedData;
488         auto status = provisionable_->generateCertificateRequest(
489                 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
490                 &protectedData, &keysToSignMac);
491         ASSERT_TRUE(status.isOk()) << status.getDescription();
492 
493         auto result = verifyProductionProtectedData(
494                 deviceInfo, cppbor::Array(), keysToSignMac, protectedData, testEekChain_, eekId_,
495                 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
496         ASSERT_TRUE(result) << result.message();
497     }
498 }
499 
500 /**
501  * Ensure that test mode outputs a unique BCC root key every time we request a
502  * certificate request. Else, it's possible that the test mode API could be used
503  * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
504  * device public key multiple times.
505  */
TEST_P(CertificateRequestTest,NewKeyPerCallInTestMode)506 TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
507     constexpr bool testMode = true;
508 
509     bytevec keysToSignMac;
510     DeviceInfo deviceInfo;
511     ProtectedData protectedData;
512     generateTestEekChain(3);
513     auto status = provisionable_->generateCertificateRequest(
514             testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
515             &protectedData, &keysToSignMac);
516     ASSERT_TRUE(status.isOk()) << status.getDescription();
517 
518     auto firstBcc = verifyProductionProtectedData(
519             deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
520             eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
521     ASSERT_TRUE(firstBcc) << firstBcc.message();
522 
523     status = provisionable_->generateCertificateRequest(
524             testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
525             &protectedData, &keysToSignMac);
526     ASSERT_TRUE(status.isOk()) << status.getDescription();
527 
528     auto secondBcc = verifyProductionProtectedData(
529             deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
530             eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
531     ASSERT_TRUE(secondBcc) << secondBcc.message();
532 
533     // Verify that none of the keys in the first BCC are repeated in the second one.
534     for (const auto& i : *firstBcc) {
535         for (auto& j : *secondBcc) {
536             ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
537                     << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
538         }
539     }
540 }
541 
542 /**
543  * Generate an empty certificate request in prod mode. This test must be run explicitly, and
544  * is not run by default. Not all devices are GMS devices, and therefore they do not all
545  * trust the Google EEK root.
546  */
TEST_P(CertificateRequestTest,DISABLED_EmptyRequest_prodMode)547 TEST_P(CertificateRequestTest, DISABLED_EmptyRequest_prodMode) {
548     bool testMode = false;
549 
550     bytevec keysToSignMac;
551     DeviceInfo deviceInfo;
552     ProtectedData protectedData;
553     auto status = provisionable_->generateCertificateRequest(
554             testMode, {} /* keysToSign */, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
555             challenge_, &deviceInfo, &protectedData, &keysToSignMac);
556     EXPECT_TRUE(status.isOk());
557 }
558 
559 /**
560  * Generate a non-empty certificate request in test mode.  Decrypt, parse and validate the contents.
561  */
TEST_P(CertificateRequestTest,NonEmptyRequest_testMode)562 TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
563     bool testMode = true;
564     generateKeys(testMode, 4 /* numKeys */);
565 
566     for (size_t eekLength : {2, 3, 7}) {
567         SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
568         generateTestEekChain(eekLength);
569 
570         bytevec keysToSignMac;
571         DeviceInfo deviceInfo;
572         ProtectedData protectedData;
573         auto status = provisionable_->generateCertificateRequest(
574                 testMode, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo, &protectedData,
575                 &keysToSignMac);
576         ASSERT_TRUE(status.isOk()) << status.getDescription();
577 
578         auto result = verifyProductionProtectedData(
579                 deviceInfo, cborKeysToSign_, keysToSignMac, protectedData, testEekChain_, eekId_,
580                 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
581         ASSERT_TRUE(result) << result.message();
582     }
583 }
584 
585 /**
586  * Generate a non-empty certificate request in prod mode. This test must be run explicitly, and
587  * is not run by default. Not all devices are GMS devices, and therefore they do not all
588  * trust the Google EEK root.
589  */
TEST_P(CertificateRequestTest,DISABLED_NonEmptyRequest_prodMode)590 TEST_P(CertificateRequestTest, DISABLED_NonEmptyRequest_prodMode) {
591     bool testMode = false;
592     generateKeys(testMode, 4 /* numKeys */);
593 
594     bytevec keysToSignMac;
595     DeviceInfo deviceInfo;
596     ProtectedData protectedData;
597     auto status = provisionable_->generateCertificateRequest(
598             testMode, keysToSign_, getProdEekChain(rpcHardwareInfo.supportedEekCurve), challenge_,
599             &deviceInfo, &protectedData, &keysToSignMac);
600     EXPECT_TRUE(status.isOk());
601 }
602 
603 /**
604  * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
605  */
TEST_P(CertificateRequestTest,NonEmptyRequestCorruptMac_testMode)606 TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
607     bool testMode = true;
608     generateKeys(testMode, 1 /* numKeys */);
609     auto result = corrupt_maced_key(keysToSign_[0]);
610     ASSERT_TRUE(result) << result.moveMessage();
611     MacedPublicKey keyWithCorruptMac = result.moveValue();
612 
613     bytevec keysToSignMac;
614     DeviceInfo deviceInfo;
615     ProtectedData protectedData;
616     generateTestEekChain(3);
617     auto status = provisionable_->generateCertificateRequest(
618             testMode, {keyWithCorruptMac}, testEekChain_.chain, challenge_, &deviceInfo,
619             &protectedData, &keysToSignMac);
620     ASSERT_FALSE(status.isOk()) << status.getDescription();
621     EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
622 }
623 
624 /**
625  * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
626  */
TEST_P(CertificateRequestTest,NonEmptyRequestCorruptMac_prodMode)627 TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
628     bool testMode = false;
629     generateKeys(testMode, 1 /* numKeys */);
630     auto result = corrupt_maced_key(keysToSign_[0]);
631     ASSERT_TRUE(result) << result.moveMessage();
632     MacedPublicKey keyWithCorruptMac = result.moveValue();
633 
634     bytevec keysToSignMac;
635     DeviceInfo deviceInfo;
636     ProtectedData protectedData;
637     auto status = provisionable_->generateCertificateRequest(
638             testMode, {keyWithCorruptMac}, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
639             challenge_, &deviceInfo, &protectedData, &keysToSignMac);
640     ASSERT_FALSE(status.isOk()) << status.getDescription();
641     EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
642 }
643 
644 /**
645  * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
646  * Confirm that the request is rejected.
647  */
TEST_P(CertificateRequestTest,NonEmptyCorruptEekRequest_prodMode)648 TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
649     bool testMode = false;
650     generateKeys(testMode, 4 /* numKeys */);
651 
652     auto prodEekChain = getProdEekChain(rpcHardwareInfo.supportedEekCurve);
653     auto [parsedChain, _, parseErr] = cppbor::parse(prodEekChain);
654     ASSERT_NE(parsedChain, nullptr) << parseErr;
655     ASSERT_NE(parsedChain->asArray(), nullptr);
656 
657     for (int ii = 0; ii < parsedChain->asArray()->size(); ++ii) {
658         auto chain = corrupt_sig_chain(prodEekChain, ii);
659         ASSERT_TRUE(chain) << chain.message();
660 
661         bytevec keysToSignMac;
662         DeviceInfo deviceInfo;
663         ProtectedData protectedData;
664         auto status = provisionable_->generateCertificateRequest(testMode, keysToSign_, *chain,
665                                                                  challenge_, &deviceInfo,
666                                                                  &protectedData, &keysToSignMac);
667         ASSERT_FALSE(status.isOk());
668         ASSERT_EQ(status.getServiceSpecificError(),
669                   BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
670     }
671 }
672 
673 /**
674  * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
675  * Confirm that the request is rejected.
676  */
TEST_P(CertificateRequestTest,NonEmptyIncompleteEekRequest_prodMode)677 TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
678     bool testMode = false;
679     generateKeys(testMode, 4 /* numKeys */);
680 
681     // Build an EEK chain that omits the first self-signed cert.
682     auto truncatedChain = cppbor::Array();
683     auto [chain, _, parseErr] = cppbor::parse(getProdEekChain(rpcHardwareInfo.supportedEekCurve));
684     ASSERT_TRUE(chain);
685     auto eekChain = chain->asArray();
686     ASSERT_NE(eekChain, nullptr);
687     for (size_t ii = 1; ii < eekChain->size(); ii++) {
688         truncatedChain.add(eekChain->get(ii)->clone());
689     }
690 
691     bytevec keysToSignMac;
692     DeviceInfo deviceInfo;
693     ProtectedData protectedData;
694     auto status = provisionable_->generateCertificateRequest(
695             testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
696             &keysToSignMac);
697     ASSERT_FALSE(status.isOk());
698     ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
699 }
700 
701 /**
702  * Generate a non-empty certificate request in test mode, with prod keys.  Must fail with
703  * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
704  */
TEST_P(CertificateRequestTest,NonEmptyRequest_prodKeyInTestCert)705 TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
706     generateKeys(false /* testMode */, 2 /* numKeys */);
707 
708     bytevec keysToSignMac;
709     DeviceInfo deviceInfo;
710     ProtectedData protectedData;
711     generateTestEekChain(3);
712     auto status = provisionable_->generateCertificateRequest(
713             true /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
714             &protectedData, &keysToSignMac);
715     ASSERT_FALSE(status.isOk());
716     ASSERT_EQ(status.getServiceSpecificError(),
717               BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
718 }
719 
720 /**
721  * Generate a non-empty certificate request in prod mode, with test keys.  Must fail with
722  * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
723  */
TEST_P(CertificateRequestTest,NonEmptyRequest_testKeyInProdCert)724 TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
725     generateKeys(true /* testMode */, 2 /* numKeys */);
726 
727     bytevec keysToSignMac;
728     DeviceInfo deviceInfo;
729     ProtectedData protectedData;
730     generateTestEekChain(3);
731     auto status = provisionable_->generateCertificateRequest(
732             false /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
733             &protectedData, &keysToSignMac);
734     ASSERT_FALSE(status.isOk());
735     ASSERT_EQ(status.getServiceSpecificError(),
736               BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
737 }
738 
739 INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
740 
741 class CertificateRequestV2Test : public CertificateRequestTestBase {
SetUp()742     void SetUp() override {
743         CertificateRequestTestBase::SetUp();
744         ASSERT_FALSE(HasFatalFailure());
745 
746         if (rpcHardwareInfo.versionNumber < VERSION_WITH_CERTIFICATE_REQUEST_V2) {
747             GTEST_SKIP() << "This test case only applies to RKP v3 and above. "
748                          << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
749         }
750     }
751 };
752 
753 /**
754  * Generate an empty certificate request with all possible length of challenge, and decrypt and
755  * verify the structure and content.
756  */
757 // @VsrTest = 3.10-015
TEST_P(CertificateRequestV2Test,EmptyRequest)758 TEST_P(CertificateRequestV2Test, EmptyRequest) {
759     bytevec csr;
760 
761     for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
762         SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
763         auto challenge = randomBytes(size);
764         auto status =
765                 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
766         ASSERT_TRUE(status.isOk()) << status.getDescription();
767 
768         auto result = verifyProductionCsr(cppbor::Array(), csr, provisionable_.get(), challenge);
769         ASSERT_TRUE(result) << result.message();
770     }
771 }
772 
773 /**
774  * Generate a non-empty certificate request with all possible length of challenge.  Decrypt, parse
775  * and validate the contents.
776  */
777 // @VsrTest = 3.10-015
TEST_P(CertificateRequestV2Test,NonEmptyRequest)778 TEST_P(CertificateRequestV2Test, NonEmptyRequest) {
779     generateKeys(false /* testMode */, 1 /* numKeys */);
780 
781     bytevec csr;
782 
783     for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
784         SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
785         auto challenge = randomBytes(size);
786         auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge, &csr);
787         ASSERT_TRUE(status.isOk()) << status.getDescription();
788 
789         auto result = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge);
790         ASSERT_TRUE(result) << result.message();
791     }
792 }
793 
794 /**
795  * Generate an empty certificate request with invalid size of challenge
796  */
TEST_P(CertificateRequestV2Test,EmptyRequestWithInvalidChallengeFail)797 TEST_P(CertificateRequestV2Test, EmptyRequestWithInvalidChallengeFail) {
798     bytevec csr;
799 
800     auto status = provisionable_->generateCertificateRequestV2(
801             /* keysToSign */ {}, randomBytes(MAX_CHALLENGE_SIZE + 1), &csr);
802     EXPECT_FALSE(status.isOk()) << status.getDescription();
803     EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_FAILED);
804 }
805 
806 /**
807  * Generate a non-empty certificate request.  Make sure contents are reproducible but allow for the
808  * signature to be different since algorithms including ECDSA P-256 can include a random value.
809  */
810 // @VsrTest = 3.10-015
TEST_P(CertificateRequestV2Test,NonEmptyRequestReproducible)811 TEST_P(CertificateRequestV2Test, NonEmptyRequestReproducible) {
812     generateKeys(false /* testMode */, 1 /* numKeys */);
813 
814     bytevec csr;
815 
816     auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
817     ASSERT_TRUE(status.isOk()) << status.getDescription();
818 
819     auto firstCsr = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
820     ASSERT_TRUE(firstCsr) << firstCsr.message();
821 
822     status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
823     ASSERT_TRUE(status.isOk()) << status.getDescription();
824 
825     auto secondCsr = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
826     ASSERT_TRUE(secondCsr) << secondCsr.message();
827 
828     ASSERT_EQ(**firstCsr, **secondCsr);
829 }
830 
831 /**
832  * Generate a non-empty certificate request with multiple keys.
833  */
834 // @VsrTest = 3.10-015
TEST_P(CertificateRequestV2Test,NonEmptyRequestMultipleKeys)835 TEST_P(CertificateRequestV2Test, NonEmptyRequestMultipleKeys) {
836     generateKeys(false /* testMode */, rpcHardwareInfo.supportedNumKeysInCsr /* numKeys */);
837 
838     bytevec csr;
839 
840     auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
841     ASSERT_TRUE(status.isOk()) << status.getDescription();
842 
843     auto result = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
844     ASSERT_TRUE(result) << result.message();
845 }
846 
847 /**
848  * Generate a non-empty certificate request, but with the MAC corrupted on the keypair.
849  */
TEST_P(CertificateRequestV2Test,NonEmptyRequestCorruptMac)850 TEST_P(CertificateRequestV2Test, NonEmptyRequestCorruptMac) {
851     generateKeys(false /* testMode */, 1 /* numKeys */);
852     auto result = corrupt_maced_key(keysToSign_[0]);
853     ASSERT_TRUE(result) << result.moveMessage();
854     MacedPublicKey keyWithCorruptMac = result.moveValue();
855 
856     bytevec csr;
857     auto status =
858             provisionable_->generateCertificateRequestV2({keyWithCorruptMac}, challenge_, &csr);
859     ASSERT_FALSE(status.isOk()) << status.getDescription();
860     EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
861 }
862 
863 /**
864  * Call generateCertificateRequest(). Make sure it's removed.
865  */
TEST_P(CertificateRequestV2Test,CertificateRequestV1Removed_prodMode)866 TEST_P(CertificateRequestV2Test, CertificateRequestV1Removed_prodMode) {
867     bytevec keysToSignMac;
868     DeviceInfo deviceInfo;
869     ProtectedData protectedData;
870     auto status = provisionable_->generateCertificateRequest(
871             false /* testMode */, {} /* keysToSign */, {} /* EEK chain */, challenge_, &deviceInfo,
872             &protectedData, &keysToSignMac);
873     ASSERT_FALSE(status.isOk()) << status.getDescription();
874     EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
875 }
876 
877 /**
878  * Call generateCertificateRequest() in test mode. Make sure it's removed.
879  */
TEST_P(CertificateRequestV2Test,CertificateRequestV1Removed_testMode)880 TEST_P(CertificateRequestV2Test, CertificateRequestV1Removed_testMode) {
881     bytevec keysToSignMac;
882     DeviceInfo deviceInfo;
883     ProtectedData protectedData;
884     auto status = provisionable_->generateCertificateRequest(
885             true /* testMode */, {} /* keysToSign */, {} /* EEK chain */, challenge_, &deviceInfo,
886             &protectedData, &keysToSignMac);
887     ASSERT_FALSE(status.isOk()) << status.getDescription();
888     EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
889 }
890 
parse_root_of_trust(const vector<uint8_t> & attestation_cert,vector<uint8_t> * verified_boot_key,VerifiedBoot * verified_boot_state,bool * device_locked,vector<uint8_t> * verified_boot_hash)891 void parse_root_of_trust(const vector<uint8_t>& attestation_cert,
892                          vector<uint8_t>* verified_boot_key, VerifiedBoot* verified_boot_state,
893                          bool* device_locked, vector<uint8_t>* verified_boot_hash) {
894     X509_Ptr cert(parse_cert_blob(attestation_cert));
895     ASSERT_TRUE(cert.get());
896 
897     ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
898     ASSERT_TRUE(attest_rec);
899 
900     auto error = parse_root_of_trust(attest_rec->data, attest_rec->length, verified_boot_key,
901                                      verified_boot_state, device_locked, verified_boot_hash);
902     ASSERT_EQ(error, ErrorCode::OK);
903 }
904 
905 /**
906  * Generate a CSR and verify DeviceInfo against IDs attested by KeyMint.
907  */
908 // @VsrTest = 3.10-015
TEST_P(CertificateRequestV2Test,DeviceInfo)909 TEST_P(CertificateRequestV2Test, DeviceInfo) {
910     // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
911     std::shared_ptr<IKeyMintDevice> keyMint;
912     if (!matching_keymint_device(GetParam(), &keyMint)) {
913         // No matching IKeyMintDevice.
914         GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
915         return;
916     }
917     KeyMintHardwareInfo info;
918     ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
919 
920     // Get IDs attested by KeyMint.
921     MacedPublicKey macedPubKey;
922     bytevec privateKeyBlob;
923     auto irpcStatus =
924             provisionable_->generateEcdsaP256KeyPair(false, &macedPubKey, &privateKeyBlob);
925     ASSERT_TRUE(irpcStatus.isOk());
926 
927     AttestationKey attestKey;
928     attestKey.keyBlob = std::move(privateKeyBlob);
929     attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
930 
931     // Generate an ECDSA key that is attested by the generated P256 keypair.
932     AuthorizationSet keyDesc = AuthorizationSetBuilder()
933                                        .Authorization(TAG_NO_AUTH_REQUIRED)
934                                        .EcdsaSigningKey(EcCurve::P_256)
935                                        .AttestationChallenge("foo")
936                                        .AttestationApplicationId("bar")
937                                        .Digest(Digest::NONE)
938                                        .SetDefaultValidity();
939     KeyCreationResult creationResult;
940     auto kmStatus = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
941     ASSERT_TRUE(kmStatus.isOk());
942 
943     vector<KeyCharacteristics> key_characteristics = std::move(creationResult.keyCharacteristics);
944     vector<Certificate> key_cert_chain = std::move(creationResult.certificateChain);
945     // We didn't provision the attestation key.
946     ASSERT_EQ(key_cert_chain.size(), 1);
947 
948     // Parse attested patch levels.
949     auto auths = HwEnforcedAuthorizations(key_characteristics);
950 
951     auto attestedSystemPatchLevel = auths.GetTagValue(TAG_OS_PATCHLEVEL);
952     auto attestedVendorPatchLevel = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
953     auto attestedBootPatchLevel = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
954 
955     ASSERT_TRUE(attestedSystemPatchLevel.has_value());
956     ASSERT_TRUE(attestedVendorPatchLevel.has_value());
957     ASSERT_TRUE(attestedBootPatchLevel.has_value());
958 
959     // Parse attested AVB values.
960     vector<uint8_t> key;
961     VerifiedBoot attestedVbState;
962     bool attestedBootloaderState;
963     vector<uint8_t> attestedVbmetaDigest;
964     parse_root_of_trust(key_cert_chain[0].encodedCertificate, &key, &attestedVbState,
965                         &attestedBootloaderState, &attestedVbmetaDigest);
966 
967     // Get IDs from DeviceInfo.
968     bytevec csr;
969     irpcStatus =
970             provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge_, &csr);
971     ASSERT_TRUE(irpcStatus.isOk()) << irpcStatus.getDescription();
972 
973     auto result = verifyProductionCsr(cppbor::Array(), csr, provisionable_.get(), challenge_);
974     ASSERT_TRUE(result) << result.message();
975 
976     std::unique_ptr<cppbor::Array> csrPayload = std::move(*result);
977     ASSERT_TRUE(csrPayload);
978 
979     auto deviceInfo = csrPayload->get(2)->asMap();
980     ASSERT_TRUE(deviceInfo);
981 
982     auto vbState = deviceInfo->get("vb_state")->asTstr();
983     auto bootloaderState = deviceInfo->get("bootloader_state")->asTstr();
984     auto vbmetaDigest = deviceInfo->get("vbmeta_digest")->asBstr();
985     auto systemPatchLevel = deviceInfo->get("system_patch_level")->asUint();
986     auto vendorPatchLevel = deviceInfo->get("vendor_patch_level")->asUint();
987     auto bootPatchLevel = deviceInfo->get("boot_patch_level")->asUint();
988     auto securityLevel = deviceInfo->get("security_level")->asTstr();
989 
990     ASSERT_TRUE(vbState);
991     ASSERT_TRUE(bootloaderState);
992     ASSERT_TRUE(vbmetaDigest);
993     ASSERT_TRUE(systemPatchLevel);
994     ASSERT_TRUE(vendorPatchLevel);
995     ASSERT_TRUE(bootPatchLevel);
996     ASSERT_TRUE(securityLevel);
997 
998     auto kmDeviceName = device_suffix(GetParam());
999 
1000     // Compare DeviceInfo against IDs attested by KeyMint.
1001     ASSERT_TRUE((securityLevel->value() == "tee" && kmDeviceName == "default") ||
1002                 (securityLevel->value() == "strongbox" && kmDeviceName == "strongbox"));
1003     ASSERT_TRUE((vbState->value() == "green" && attestedVbState == VerifiedBoot::VERIFIED) ||
1004                 (vbState->value() == "yellow" && attestedVbState == VerifiedBoot::SELF_SIGNED) ||
1005                 (vbState->value() == "orange" && attestedVbState == VerifiedBoot::UNVERIFIED));
1006     ASSERT_TRUE((bootloaderState->value() == "locked" && attestedBootloaderState) ||
1007                 (bootloaderState->value() == "unlocked" && !attestedBootloaderState));
1008     ASSERT_EQ(vbmetaDigest->value(), attestedVbmetaDigest);
1009     ASSERT_EQ(systemPatchLevel->value(), attestedSystemPatchLevel.value());
1010     ASSERT_EQ(vendorPatchLevel->value(), attestedVendorPatchLevel.value());
1011     ASSERT_EQ(bootPatchLevel->value(), attestedBootPatchLevel.value());
1012 }
1013 
1014 INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestV2Test);
1015 
1016 using VsrRequirementTest = VtsRemotelyProvisionedComponentTests;
1017 
1018 INSTANTIATE_REM_PROV_AIDL_TEST(VsrRequirementTest);
1019 
TEST_P(VsrRequirementTest,VsrEnforcementTest)1020 TEST_P(VsrRequirementTest, VsrEnforcementTest) {
1021     RpcHardwareInfo hwInfo;
1022     ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
1023     int vsr_api_level = get_vsr_api_level();
1024     if (vsr_api_level < 34) {
1025         GTEST_SKIP() << "Applies only to VSR API level 34 or newer, this device is: "
1026                      << vsr_api_level;
1027     }
1028     EXPECT_GE(hwInfo.versionNumber, 3)
1029             << "VSR 14+ requires IRemotelyProvisionedComponent v3 or newer.";
1030 }
1031 
1032 }  // namespace aidl::android::hardware::security::keymint::test
1033