blob: e1a0e2c0b1a3c07e15309ec4d187c1d30b62e68e [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
Seth Moore8f810b12022-12-12 16:51:01 -080021#include <aidl/android/hardware/security/keymint/BnRemotelyProvisionedComponent.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>
Tri Voec50ee12023-02-14 16:29:53 -080026#include <cppbor.h>
Shawn Willden274bb552020-09-30 22:39:22 -060027#include <cppbor_parse.h>
Shawn Willden274bb552020-09-30 22:39:22 -060028#include <gmock/gmock.h>
Max Bires9704ff62021-04-07 11:12:01 -070029#include <keymaster/cppcose/cppcose.h>
Shawn Willden274bb552020-09-30 22:39:22 -060030#include <keymaster/keymaster_configuration.h>
David Drysdalef0d516d2021-03-22 07:51:43 +000031#include <keymint_support/authorization_set.h>
32#include <openssl/ec.h>
33#include <openssl/ec_key.h>
34#include <openssl/x509.h>
Shawn Willden274bb552020-09-30 22:39:22 -060035#include <remote_prov/remote_prov_utils.h>
Max Bires757ed422022-09-07 16:20:31 -070036#include <optional>
Seth Moorefc86bf42021-12-09 14:07:04 -080037#include <set>
Seth Moore42c11332021-07-02 15:38:17 -070038#include <vector>
Shawn Willden274bb552020-09-30 22:39:22 -060039
David Drysdalef0d516d2021-03-22 07:51:43 +000040#include "KeyMintAidlTestBase.h"
41
Shawn Willden274bb552020-09-30 22:39:22 -060042namespace aidl::android::hardware::security::keymint::test {
43
44using ::std::string;
45using ::std::vector;
46
47namespace {
48
Seth Moorefc86bf42021-12-09 14:07:04 -080049constexpr int32_t VERSION_WITH_UNIQUE_ID_SUPPORT = 2;
Tri Vo0d6204e2022-09-29 16:15:34 -070050constexpr int32_t VERSION_WITHOUT_TEST_MODE = 3;
Seth Moorefc86bf42021-12-09 14:07:04 -080051
Tommy Chiufde3ad12023-03-17 05:58:28 +000052constexpr uint8_t MIN_CHALLENGE_SIZE = 0;
53constexpr uint8_t MAX_CHALLENGE_SIZE = 64;
54
Shawn Willden274bb552020-09-30 22:39:22 -060055#define INSTANTIATE_REM_PROV_AIDL_TEST(name) \
Seth Moore6305e232021-07-27 14:20:17 -070056 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name); \
Shawn Willden274bb552020-09-30 22:39:22 -060057 INSTANTIATE_TEST_SUITE_P( \
58 PerInstance, name, \
59 testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
60 ::android::PrintInstanceNameToString)
61
Seth Moorefc86bf42021-12-09 14:07:04 -080062using ::android::sp;
Shawn Willden274bb552020-09-30 22:39:22 -060063using bytevec = std::vector<uint8_t>;
64using testing::MatchesRegex;
65using namespace remote_prov;
66using namespace keymaster;
67
68bytevec string_to_bytevec(const char* s) {
69 const uint8_t* p = reinterpret_cast<const uint8_t*>(s);
70 return bytevec(p, p + strlen(s));
71}
72
David Drysdalee99ed862021-03-15 16:43:06 +000073ErrMsgOr<MacedPublicKey> corrupt_maced_key(const MacedPublicKey& macedPubKey) {
74 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
75 if (!coseMac0 || coseMac0->asArray()->size() != kCoseMac0EntryCount) {
76 return "COSE Mac0 parse failed";
77 }
78 auto protParams = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
79 auto unprotParams = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
80 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
81 auto tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
82 if (!protParams || !unprotParams || !payload || !tag) {
83 return "Invalid COSE_Sign1: missing content";
84 }
85 auto corruptMac0 = cppbor::Array();
86 corruptMac0.add(protParams->clone());
87 corruptMac0.add(unprotParams->clone());
88 corruptMac0.add(payload->clone());
89 vector<uint8_t> tagData = tag->value();
90 tagData[0] ^= 0x08;
91 tagData[tagData.size() - 1] ^= 0x80;
92 corruptMac0.add(cppbor::Bstr(tagData));
93
94 return MacedPublicKey{corruptMac0.encode()};
95}
96
David Drysdalecceca9f2021-03-12 15:49:47 +000097ErrMsgOr<cppbor::Array> corrupt_sig(const cppbor::Array* coseSign1) {
98 if (coseSign1->size() != kCoseSign1EntryCount) {
99 return "Invalid COSE_Sign1, wrong entry count";
100 }
101 const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
102 const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
103 const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
104 const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
105 if (!protectedParams || !unprotectedParams || !payload || !signature) {
106 return "Invalid COSE_Sign1: missing content";
107 }
108
109 auto corruptSig = cppbor::Array();
110 corruptSig.add(protectedParams->clone());
111 corruptSig.add(unprotectedParams->clone());
112 corruptSig.add(payload->clone());
113 vector<uint8_t> sigData = signature->value();
114 sigData[0] ^= 0x08;
115 corruptSig.add(cppbor::Bstr(sigData));
116
117 return std::move(corruptSig);
118}
119
Seth Moore19acbe92021-06-23 15:15:52 -0700120ErrMsgOr<bytevec> corrupt_sig_chain(const bytevec& encodedEekChain, int which) {
121 auto [chain, _, parseErr] = cppbor::parse(encodedEekChain);
David Drysdalecceca9f2021-03-12 15:49:47 +0000122 if (!chain || !chain->asArray()) {
123 return "EekChain parse failed";
124 }
125
126 cppbor::Array* eekChain = chain->asArray();
127 if (which >= eekChain->size()) {
128 return "selected sig out of range";
129 }
130 auto corruptChain = cppbor::Array();
131
132 for (int ii = 0; ii < eekChain->size(); ++ii) {
133 if (ii == which) {
134 auto sig = corrupt_sig(eekChain->get(which)->asArray());
135 if (!sig) {
136 return "Failed to build corrupted signature" + sig.moveMessage();
137 }
138 corruptChain.add(sig.moveValue());
139 } else {
140 corruptChain.add(eekChain->get(ii)->clone());
141 }
142 }
Seth Moore19acbe92021-06-23 15:15:52 -0700143 return corruptChain.encode();
David Drysdalecceca9f2021-03-12 15:49:47 +0000144}
145
David Drysdale4d3c2982021-03-31 18:21:40 +0100146string device_suffix(const string& name) {
147 size_t pos = name.find('/');
148 if (pos == string::npos) {
149 return name;
150 }
151 return name.substr(pos + 1);
152}
153
154bool matching_keymint_device(const string& rp_name, std::shared_ptr<IKeyMintDevice>* keyMint) {
155 string rp_suffix = device_suffix(rp_name);
156
157 vector<string> km_names = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
158 for (const string& km_name : km_names) {
159 // If the suffix of the KeyMint instance equals the suffix of the
160 // RemotelyProvisionedComponent instance, assume they match.
161 if (device_suffix(km_name) == rp_suffix && AServiceManager_isDeclared(km_name.c_str())) {
162 ::ndk::SpAIBinder binder(AServiceManager_waitForService(km_name.c_str()));
163 *keyMint = IKeyMintDevice::fromBinder(binder);
164 return true;
165 }
166 }
167 return false;
168}
169
Shawn Willden274bb552020-09-30 22:39:22 -0600170} // namespace
171
172class VtsRemotelyProvisionedComponentTests : public testing::TestWithParam<std::string> {
173 public:
174 virtual void SetUp() override {
175 if (AServiceManager_isDeclared(GetParam().c_str())) {
176 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
177 provisionable_ = IRemotelyProvisionedComponent::fromBinder(binder);
178 }
179 ASSERT_NE(provisionable_, nullptr);
subrahmanyamanfb213d62022-02-02 23:10:55 +0000180 ASSERT_TRUE(provisionable_->getHardwareInfo(&rpcHardwareInfo).isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600181 }
182
183 static vector<string> build_params() {
184 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
185 return params;
186 }
187
188 protected:
189 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000190 RpcHardwareInfo rpcHardwareInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600191};
192
Seth Moorefc86bf42021-12-09 14:07:04 -0800193/**
194 * Verify that every implementation reports a different unique id.
195 */
196TEST(NonParameterizedTests, eachRpcHasAUniqueId) {
197 std::set<std::string> uniqueIds;
198 for (auto hal : ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor)) {
199 ASSERT_TRUE(AServiceManager_isDeclared(hal.c_str()));
200 ::ndk::SpAIBinder binder(AServiceManager_waitForService(hal.c_str()));
201 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
202 IRemotelyProvisionedComponent::fromBinder(binder);
203 ASSERT_NE(rpc, nullptr);
204
205 RpcHardwareInfo hwInfo;
206 ASSERT_TRUE(rpc->getHardwareInfo(&hwInfo).isOk());
207
Tri Vodd12c482022-10-12 22:41:28 +0000208 if (hwInfo.versionNumber >= VERSION_WITH_UNIQUE_ID_SUPPORT) {
Seth Moorefc86bf42021-12-09 14:07:04 -0800209 ASSERT_TRUE(hwInfo.uniqueId);
210 auto [_, wasInserted] = uniqueIds.insert(*hwInfo.uniqueId);
211 EXPECT_TRUE(wasInserted);
212 } else {
213 ASSERT_FALSE(hwInfo.uniqueId);
214 }
215 }
216}
217
218using GetHardwareInfoTests = VtsRemotelyProvisionedComponentTests;
219
220INSTANTIATE_REM_PROV_AIDL_TEST(GetHardwareInfoTests);
221
222/**
223 * Verify that a valid curve is reported by the implementation.
224 */
225TEST_P(GetHardwareInfoTests, supportsValidCurve) {
226 RpcHardwareInfo hwInfo;
227 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
228
229 const std::set<int> validCurves = {RpcHardwareInfo::CURVE_P256, RpcHardwareInfo::CURVE_25519};
Hasini Gunasinghe666b2712023-01-05 21:35:51 +0000230 // First check for the implementations that supports only IRPC V3+.
231 if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_TEST_MODE) {
232 bytevec keysToSignMac;
233 DeviceInfo deviceInfo;
234 ProtectedData protectedData;
235 auto status = provisionable_->generateCertificateRequest(false, {}, {}, {}, &deviceInfo,
236 &protectedData, &keysToSignMac);
237 if (!status.isOk() &&
238 (status.getServiceSpecificError() == BnRemotelyProvisionedComponent::STATUS_REMOVED)) {
239 ASSERT_EQ(hwInfo.supportedEekCurve, RpcHardwareInfo::CURVE_NONE)
240 << "Invalid curve: " << hwInfo.supportedEekCurve;
241 return;
242 }
243 }
Seth Moorefc86bf42021-12-09 14:07:04 -0800244 ASSERT_EQ(validCurves.count(hwInfo.supportedEekCurve), 1)
245 << "Invalid curve: " << hwInfo.supportedEekCurve;
246}
247
248/**
249 * Verify that the unique id is within the length limits as described in RpcHardwareInfo.aidl.
250 */
251TEST_P(GetHardwareInfoTests, uniqueId) {
Tri Vodd12c482022-10-12 22:41:28 +0000252 if (rpcHardwareInfo.versionNumber < VERSION_WITH_UNIQUE_ID_SUPPORT) {
Seth Moorefc86bf42021-12-09 14:07:04 -0800253 return;
254 }
255
256 RpcHardwareInfo hwInfo;
257 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
258 ASSERT_TRUE(hwInfo.uniqueId);
259 EXPECT_GE(hwInfo.uniqueId->size(), 1);
260 EXPECT_LE(hwInfo.uniqueId->size(), 32);
261}
262
Tri Vo9cab73c2022-10-28 13:40:24 -0700263/**
264 * Verify implementation supports at least MIN_SUPPORTED_NUM_KEYS_IN_CSR keys in a CSR.
265 */
266TEST_P(GetHardwareInfoTests, supportedNumKeysInCsr) {
267 if (rpcHardwareInfo.versionNumber < VERSION_WITHOUT_TEST_MODE) {
268 return;
269 }
270
271 RpcHardwareInfo hwInfo;
272 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
273 ASSERT_GE(hwInfo.supportedNumKeysInCsr, RpcHardwareInfo::MIN_SUPPORTED_NUM_KEYS_IN_CSR);
274}
275
Shawn Willden274bb552020-09-30 22:39:22 -0600276using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
277
278INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
279
280/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000281 * Generate and validate a production-mode key. MAC tag can't be verified, but
282 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600283 */
Max Bires126869a2021-02-21 18:32:59 -0800284TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600285 MacedPublicKey macedPubKey;
286 bytevec privateKeyBlob;
287 bool testMode = false;
288 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
289 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000290 vector<uint8_t> coseKeyData;
Tri Vob0b8acc2022-11-30 16:22:23 -0800291 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100292}
293
294/**
295 * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
296 */
297TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
298 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
299 std::shared_ptr<IKeyMintDevice> keyMint;
300 if (!matching_keymint_device(GetParam(), &keyMint)) {
301 // No matching IKeyMintDevice.
302 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
303 return;
304 }
305 KeyMintHardwareInfo info;
306 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
307
308 MacedPublicKey macedPubKey;
309 bytevec privateKeyBlob;
310 bool testMode = false;
311 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
312 ASSERT_TRUE(status.isOk());
313 vector<uint8_t> coseKeyData;
Tri Vob0b8acc2022-11-30 16:22:23 -0800314 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100315
David Drysdalef0d516d2021-03-22 07:51:43 +0000316 AttestationKey attestKey;
317 attestKey.keyBlob = std::move(privateKeyBlob);
318 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600319
David Drysdalef0d516d2021-03-22 07:51:43 +0000320 // Generate an ECDSA key that is attested by the generated P256 keypair.
321 AuthorizationSet keyDesc = AuthorizationSetBuilder()
322 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale915ce252021-10-14 15:17:36 +0100323 .EcdsaSigningKey(EcCurve::P_256)
David Drysdalef0d516d2021-03-22 07:51:43 +0000324 .AttestationChallenge("foo")
325 .AttestationApplicationId("bar")
326 .Digest(Digest::NONE)
327 .SetDefaultValidity();
328 KeyCreationResult creationResult;
329 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
330 ASSERT_TRUE(result.isOk());
331 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
332 vector<KeyCharacteristics> attested_key_characteristics =
333 std::move(creationResult.keyCharacteristics);
334 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
335 EXPECT_EQ(attested_key_cert_chain.size(), 1);
336
David Drysdale7dff4fc2021-12-10 10:10:52 +0000337 int32_t aidl_version = 0;
338 ASSERT_TRUE(keyMint->getInterfaceVersion(&aidl_version).isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000339 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
340 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +0000341 EXPECT_TRUE(verify_attestation_record(aidl_version, "foo", "bar", sw_enforced, hw_enforced,
David Drysdalef0d516d2021-03-22 07:51:43 +0000342 info.securityLevel,
343 attested_key_cert_chain[0].encodedCertificate));
344
345 // Attestation by itself is not valid (last entry is not self-signed).
346 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
347
348 // The signature over the attested key should correspond to the P256 public key.
349 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
350 ASSERT_TRUE(key_cert.get());
351 EVP_PKEY_Ptr signing_pubkey;
352 p256_pub_key(coseKeyData, &signing_pubkey);
353 ASSERT_TRUE(signing_pubkey.get());
354
355 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
356 << "Verification of attested certificate failed "
357 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600358}
359
360/**
361 * Generate and validate a test-mode key.
362 */
Max Bires126869a2021-02-21 18:32:59 -0800363TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600364 MacedPublicKey macedPubKey;
365 bytevec privateKeyBlob;
366 bool testMode = true;
367 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
368 ASSERT_TRUE(status.isOk());
Tri Vob0b8acc2022-11-30 16:22:23 -0800369 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600370}
371
Tri Vo0d6204e2022-09-29 16:15:34 -0700372class CertificateRequestTestBase : public VtsRemotelyProvisionedComponentTests {
Shawn Willden274bb552020-09-30 22:39:22 -0600373 protected:
Tri Vo0d6204e2022-09-29 16:15:34 -0700374 CertificateRequestTestBase()
375 : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(64)) {}
David Drysdalecceca9f2021-03-12 15:49:47 +0000376
Seth Moore19acbe92021-06-23 15:15:52 -0700377 void generateTestEekChain(size_t eekLength) {
subrahmanyamanfb213d62022-02-02 23:10:55 +0000378 auto chain = generateEekChain(rpcHardwareInfo.supportedEekCurve, eekLength, eekId_);
David Drysdale08696a72022-03-10 10:43:25 +0000379 ASSERT_TRUE(chain) << chain.message();
Seth Moore19acbe92021-06-23 15:15:52 -0700380 if (chain) testEekChain_ = chain.moveValue();
381 testEekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600382 }
383
384 void generateKeys(bool testMode, size_t numKeys) {
385 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
386 cborKeysToSign_ = cppbor::Array();
387
388 for (auto& key : keysToSign_) {
389 bytevec privateKeyBlob;
390 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
391 ASSERT_TRUE(status.isOk()) << status.getMessage();
392
David Drysdalec8400772021-03-11 12:35:11 +0000393 vector<uint8_t> payload_value;
Tri Vob0b8acc2022-11-30 16:22:23 -0800394 check_maced_pubkey(key, testMode, &payload_value);
David Drysdalec8400772021-03-11 12:35:11 +0000395 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600396 }
397 }
398
399 bytevec eekId_;
Seth Moore19acbe92021-06-23 15:15:52 -0700400 size_t testEekLength_;
401 EekChain testEekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000402 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600403 std::vector<MacedPublicKey> keysToSign_;
404 cppbor::Array cborKeysToSign_;
405};
406
Tri Vo0d6204e2022-09-29 16:15:34 -0700407class CertificateRequestTest : public CertificateRequestTestBase {
408 protected:
409 void SetUp() override {
410 CertificateRequestTestBase::SetUp();
Andrew Scull1bcb6022022-12-27 10:43:27 +0000411 ASSERT_FALSE(HasFatalFailure());
Tri Vo0d6204e2022-09-29 16:15:34 -0700412
413 if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_TEST_MODE) {
Tri Vob0b8acc2022-11-30 16:22:23 -0800414 bytevec keysToSignMac;
415 DeviceInfo deviceInfo;
416 ProtectedData protectedData;
417 auto status = provisionable_->generateCertificateRequest(
418 false, {}, {}, {}, &deviceInfo, &protectedData, &keysToSignMac);
419 if (!status.isOk() && (status.getServiceSpecificError() ==
420 BnRemotelyProvisionedComponent::STATUS_REMOVED)) {
421 GTEST_SKIP() << "This test case applies to RKP v3+ only if "
422 << "generateCertificateRequest() is implemented.";
423 }
Tri Vo0d6204e2022-09-29 16:15:34 -0700424 }
425 }
426};
427
Shawn Willden274bb552020-09-30 22:39:22 -0600428/**
429 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
430 * content.
431 */
Max Bires126869a2021-02-21 18:32:59 -0800432TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600433 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000434 for (size_t eekLength : {2, 3, 7}) {
435 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700436 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600437
David Drysdalecceca9f2021-03-12 15:49:47 +0000438 bytevec keysToSignMac;
439 DeviceInfo deviceInfo;
440 ProtectedData protectedData;
441 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700442 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalecceca9f2021-03-12 15:49:47 +0000443 &protectedData, &keysToSignMac);
444 ASSERT_TRUE(status.isOk()) << status.getMessage();
445
Seth Moore2fc6f832022-09-13 16:10:11 -0700446 auto result = verifyProductionProtectedData(
447 deviceInfo, cppbor::Array(), keysToSignMac, protectedData, testEekChain_, eekId_,
448 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
449 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000450 }
Shawn Willden274bb552020-09-30 22:39:22 -0600451}
452
453/**
Seth Moore42c11332021-07-02 15:38:17 -0700454 * Ensure that test mode outputs a unique BCC root key every time we request a
455 * certificate request. Else, it's possible that the test mode API could be used
456 * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
457 * device public key multiple times.
458 */
459TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
460 constexpr bool testMode = true;
Seth Moore42c11332021-07-02 15:38:17 -0700461
462 bytevec keysToSignMac;
463 DeviceInfo deviceInfo;
464 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000465 generateTestEekChain(3);
Seth Moore42c11332021-07-02 15:38:17 -0700466 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700467 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
468 &protectedData, &keysToSignMac);
Seth Moore42c11332021-07-02 15:38:17 -0700469 ASSERT_TRUE(status.isOk()) << status.getMessage();
470
Seth Moore2fc6f832022-09-13 16:10:11 -0700471 auto firstBcc = verifyProductionProtectedData(
472 deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
473 eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
474 ASSERT_TRUE(firstBcc) << firstBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700475
Seth Moore19acbe92021-06-23 15:15:52 -0700476 status = provisionable_->generateCertificateRequest(
477 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
478 &protectedData, &keysToSignMac);
Seth Moore42c11332021-07-02 15:38:17 -0700479 ASSERT_TRUE(status.isOk()) << status.getMessage();
480
Seth Moore2fc6f832022-09-13 16:10:11 -0700481 auto secondBcc = verifyProductionProtectedData(
482 deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
483 eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
484 ASSERT_TRUE(secondBcc) << secondBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700485
486 // Verify that none of the keys in the first BCC are repeated in the second one.
Seth Moore2fc6f832022-09-13 16:10:11 -0700487 for (const auto& i : *firstBcc) {
488 for (auto& j : *secondBcc) {
Seth Moore42c11332021-07-02 15:38:17 -0700489 ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
490 << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
491 }
492 }
493}
494
495/**
Seth Moore19acbe92021-06-23 15:15:52 -0700496 * Generate an empty certificate request in prod mode. This test must be run explicitly, and
497 * is not run by default. Not all devices are GMS devices, and therefore they do not all
498 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600499 */
Seth Moore19acbe92021-06-23 15:15:52 -0700500TEST_P(CertificateRequestTest, DISABLED_EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600501 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000502
Seth Moore19acbe92021-06-23 15:15:52 -0700503 bytevec keysToSignMac;
504 DeviceInfo deviceInfo;
505 ProtectedData protectedData;
506 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000507 testMode, {} /* keysToSign */, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
508 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700509 EXPECT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600510}
511
512/**
513 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
514 */
Max Bires126869a2021-02-21 18:32:59 -0800515TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600516 bool testMode = true;
517 generateKeys(testMode, 4 /* numKeys */);
518
David Drysdalecceca9f2021-03-12 15:49:47 +0000519 for (size_t eekLength : {2, 3, 7}) {
520 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700521 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600522
David Drysdalecceca9f2021-03-12 15:49:47 +0000523 bytevec keysToSignMac;
524 DeviceInfo deviceInfo;
525 ProtectedData protectedData;
526 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700527 testMode, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo, &protectedData,
David Drysdalecceca9f2021-03-12 15:49:47 +0000528 &keysToSignMac);
529 ASSERT_TRUE(status.isOk()) << status.getMessage();
530
Seth Moore2fc6f832022-09-13 16:10:11 -0700531 auto result = verifyProductionProtectedData(
532 deviceInfo, cborKeysToSign_, keysToSignMac, protectedData, testEekChain_, eekId_,
533 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
534 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000535 }
Shawn Willden274bb552020-09-30 22:39:22 -0600536}
537
538/**
Seth Moore19acbe92021-06-23 15:15:52 -0700539 * Generate a non-empty certificate request in prod mode. This test must be run explicitly, and
540 * is not run by default. Not all devices are GMS devices, and therefore they do not all
541 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600542 */
Seth Moore19acbe92021-06-23 15:15:52 -0700543TEST_P(CertificateRequestTest, DISABLED_NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600544 bool testMode = false;
545 generateKeys(testMode, 4 /* numKeys */);
546
Seth Moore19acbe92021-06-23 15:15:52 -0700547 bytevec keysToSignMac;
548 DeviceInfo deviceInfo;
549 ProtectedData protectedData;
550 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000551 testMode, keysToSign_, getProdEekChain(rpcHardwareInfo.supportedEekCurve), challenge_,
552 &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700553 EXPECT_TRUE(status.isOk());
David Drysdalecceca9f2021-03-12 15:49:47 +0000554}
555
556/**
David Drysdalee99ed862021-03-15 16:43:06 +0000557 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
558 */
559TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
560 bool testMode = true;
561 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000562 auto result = corrupt_maced_key(keysToSign_[0]);
563 ASSERT_TRUE(result) << result.moveMessage();
564 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000565
566 bytevec keysToSignMac;
567 DeviceInfo deviceInfo;
568 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000569 generateTestEekChain(3);
David Drysdalee99ed862021-03-15 16:43:06 +0000570 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700571 testMode, {keyWithCorruptMac}, testEekChain_.chain, challenge_, &deviceInfo,
572 &protectedData, &keysToSignMac);
David Drysdalee99ed862021-03-15 16:43:06 +0000573 ASSERT_FALSE(status.isOk()) << status.getMessage();
574 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
575}
576
577/**
578 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
579 */
580TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
Seth Moore19acbe92021-06-23 15:15:52 -0700581 bool testMode = false;
David Drysdalee99ed862021-03-15 16:43:06 +0000582 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000583 auto result = corrupt_maced_key(keysToSign_[0]);
584 ASSERT_TRUE(result) << result.moveMessage();
585 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000586
587 bytevec keysToSignMac;
588 DeviceInfo deviceInfo;
589 ProtectedData protectedData;
590 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000591 testMode, {keyWithCorruptMac}, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
592 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
David Drysdalee99ed862021-03-15 16:43:06 +0000593 ASSERT_FALSE(status.isOk()) << status.getMessage();
Seth Moore19acbe92021-06-23 15:15:52 -0700594 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
David Drysdalee99ed862021-03-15 16:43:06 +0000595}
596
597/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000598 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
599 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000600 */
601TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
602 bool testMode = false;
603 generateKeys(testMode, 4 /* numKeys */);
604
subrahmanyamanfb213d62022-02-02 23:10:55 +0000605 auto prodEekChain = getProdEekChain(rpcHardwareInfo.supportedEekCurve);
Seth Moore19acbe92021-06-23 15:15:52 -0700606 auto [parsedChain, _, parseErr] = cppbor::parse(prodEekChain);
607 ASSERT_NE(parsedChain, nullptr) << parseErr;
608 ASSERT_NE(parsedChain->asArray(), nullptr);
609
610 for (int ii = 0; ii < parsedChain->asArray()->size(); ++ii) {
611 auto chain = corrupt_sig_chain(prodEekChain, ii);
David Drysdalecceca9f2021-03-12 15:49:47 +0000612 ASSERT_TRUE(chain) << chain.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000613
614 bytevec keysToSignMac;
615 DeviceInfo deviceInfo;
616 ProtectedData protectedData;
Seth Moore19acbe92021-06-23 15:15:52 -0700617 auto status = provisionable_->generateCertificateRequest(testMode, keysToSign_, *chain,
618 challenge_, &deviceInfo,
619 &protectedData, &keysToSignMac);
David Drysdalecceca9f2021-03-12 15:49:47 +0000620 ASSERT_FALSE(status.isOk());
621 ASSERT_EQ(status.getServiceSpecificError(),
622 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
623 }
624}
625
626/**
627 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
628 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000629 */
630TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
631 bool testMode = false;
632 generateKeys(testMode, 4 /* numKeys */);
633
634 // Build an EEK chain that omits the first self-signed cert.
635 auto truncatedChain = cppbor::Array();
subrahmanyamanfb213d62022-02-02 23:10:55 +0000636 auto [chain, _, parseErr] = cppbor::parse(getProdEekChain(rpcHardwareInfo.supportedEekCurve));
David Drysdalecceca9f2021-03-12 15:49:47 +0000637 ASSERT_TRUE(chain);
638 auto eekChain = chain->asArray();
639 ASSERT_NE(eekChain, nullptr);
640 for (size_t ii = 1; ii < eekChain->size(); ii++) {
641 truncatedChain.add(eekChain->get(ii)->clone());
642 }
643
Shawn Willden274bb552020-09-30 22:39:22 -0600644 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700645 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600646 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000647 auto status = provisionable_->generateCertificateRequest(
648 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
649 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600650 ASSERT_FALSE(status.isOk());
651 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
652}
653
654/**
655 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
656 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
657 */
Max Bires126869a2021-02-21 18:32:59 -0800658TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600659 generateKeys(false /* testMode */, 2 /* numKeys */);
660
661 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700662 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600663 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000664 generateTestEekChain(3);
Max Biresfdbb9042021-03-23 12:43:38 -0700665 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700666 true /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700667 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600668 ASSERT_FALSE(status.isOk());
669 ASSERT_EQ(status.getServiceSpecificError(),
670 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
671}
672
673/**
674 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
675 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
676 */
Max Bires126869a2021-02-21 18:32:59 -0800677TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600678 generateKeys(true /* testMode */, 2 /* numKeys */);
679
680 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700681 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600682 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000683 generateTestEekChain(3);
Shawn Willden274bb552020-09-30 22:39:22 -0600684 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700685 false /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalec8400772021-03-11 12:35:11 +0000686 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600687 ASSERT_FALSE(status.isOk());
688 ASSERT_EQ(status.getServiceSpecificError(),
689 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
690}
691
692INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
693
Tri Vo0d6204e2022-09-29 16:15:34 -0700694class CertificateRequestV2Test : public CertificateRequestTestBase {
695 void SetUp() override {
696 CertificateRequestTestBase::SetUp();
Andrew Scull1bcb6022022-12-27 10:43:27 +0000697 ASSERT_FALSE(HasFatalFailure());
Tri Vo0d6204e2022-09-29 16:15:34 -0700698
699 if (rpcHardwareInfo.versionNumber < VERSION_WITHOUT_TEST_MODE) {
700 GTEST_SKIP() << "This test case only applies to RKP v3 and above. "
701 << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
702 }
703 }
704};
705
706/**
Tommy Chiufde3ad12023-03-17 05:58:28 +0000707 * Generate an empty certificate request with all possible length of challenge, and decrypt and
708 * verify the structure and content.
Tri Vo0d6204e2022-09-29 16:15:34 -0700709 */
710TEST_P(CertificateRequestV2Test, EmptyRequest) {
711 bytevec csr;
712
Tommy Chiufde3ad12023-03-17 05:58:28 +0000713 for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
714 SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
715 auto challenge = randomBytes(size);
716 auto status =
717 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
718 ASSERT_TRUE(status.isOk()) << status.getMessage();
Tri Vo0d6204e2022-09-29 16:15:34 -0700719
Tommy Chiufde3ad12023-03-17 05:58:28 +0000720 auto result = verifyProductionCsr(cppbor::Array(), csr, provisionable_.get(), challenge);
721 ASSERT_TRUE(result) << result.message();
722 }
Tri Vo0d6204e2022-09-29 16:15:34 -0700723}
724
725/**
Tommy Chiufde3ad12023-03-17 05:58:28 +0000726 * Generate a non-empty certificate request with all possible length of challenge. Decrypt, parse
727 * and validate the contents.
Tri Vo0d6204e2022-09-29 16:15:34 -0700728 */
729TEST_P(CertificateRequestV2Test, NonEmptyRequest) {
730 generateKeys(false /* testMode */, 1 /* numKeys */);
731
732 bytevec csr;
733
Tommy Chiufde3ad12023-03-17 05:58:28 +0000734 for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
735 SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
736 auto challenge = randomBytes(size);
737 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge, &csr);
738 ASSERT_TRUE(status.isOk()) << status.getMessage();
Tri Vo0d6204e2022-09-29 16:15:34 -0700739
Tommy Chiufde3ad12023-03-17 05:58:28 +0000740 auto result = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge);
741 ASSERT_TRUE(result) << result.message();
742 }
743}
744
745/**
746 * Generate an empty certificate request with invalid size of challenge
747 */
748TEST_P(CertificateRequestV2Test, EmptyRequestWithInvalidChallengeFail) {
749 bytevec csr;
750
751 auto status = provisionable_->generateCertificateRequestV2(
752 /* keysToSign */ {}, randomBytes(MAX_CHALLENGE_SIZE + 1), &csr);
753 EXPECT_FALSE(status.isOk()) << status.getMessage();
754 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_FAILED);
Tri Vo0d6204e2022-09-29 16:15:34 -0700755}
756
757/**
Andrew Scullfb49ad22022-11-09 21:02:48 +0000758 * Generate a non-empty certificate request. Make sure contents are reproducible but allow for the
759 * signature to be different since algorithms including ECDSA P-256 can include a random value.
Tri Vo0d6204e2022-09-29 16:15:34 -0700760 */
761TEST_P(CertificateRequestV2Test, NonEmptyRequestReproducible) {
762 generateKeys(false /* testMode */, 1 /* numKeys */);
763
764 bytevec csr;
765
766 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
767 ASSERT_TRUE(status.isOk()) << status.getMessage();
768
Andrew Scullfb49ad22022-11-09 21:02:48 +0000769 auto firstCsr = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
770 ASSERT_TRUE(firstCsr) << firstCsr.message();
Tri Vo0d6204e2022-09-29 16:15:34 -0700771
772 status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
773 ASSERT_TRUE(status.isOk()) << status.getMessage();
774
Andrew Scullfb49ad22022-11-09 21:02:48 +0000775 auto secondCsr = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
776 ASSERT_TRUE(secondCsr) << secondCsr.message();
Tri Vo0d6204e2022-09-29 16:15:34 -0700777
Andrew Scullfb49ad22022-11-09 21:02:48 +0000778 ASSERT_EQ(**firstCsr, **secondCsr);
Tri Vo0d6204e2022-09-29 16:15:34 -0700779}
780
781/**
782 * Generate a non-empty certificate request with multiple keys.
783 */
784TEST_P(CertificateRequestV2Test, NonEmptyRequestMultipleKeys) {
Tri Vo9cab73c2022-10-28 13:40:24 -0700785 generateKeys(false /* testMode */, rpcHardwareInfo.supportedNumKeysInCsr /* numKeys */);
Tri Vo0d6204e2022-09-29 16:15:34 -0700786
787 bytevec csr;
788
789 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
790 ASSERT_TRUE(status.isOk()) << status.getMessage();
791
792 auto result = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
793 ASSERT_TRUE(result) << result.message();
794}
795
796/**
797 * Generate a non-empty certificate request, but with the MAC corrupted on the keypair.
798 */
799TEST_P(CertificateRequestV2Test, NonEmptyRequestCorruptMac) {
800 generateKeys(false /* testMode */, 1 /* numKeys */);
801 auto result = corrupt_maced_key(keysToSign_[0]);
802 ASSERT_TRUE(result) << result.moveMessage();
803 MacedPublicKey keyWithCorruptMac = result.moveValue();
804
805 bytevec csr;
806 auto status =
807 provisionable_->generateCertificateRequestV2({keyWithCorruptMac}, challenge_, &csr);
808 ASSERT_FALSE(status.isOk()) << status.getMessage();
809 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
810}
811
812/**
Tri Vob0b8acc2022-11-30 16:22:23 -0800813 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
814 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
Tri Vo0d6204e2022-09-29 16:15:34 -0700815 */
816TEST_P(CertificateRequestV2Test, NonEmptyRequest_testKeyInProdCert) {
817 generateKeys(true /* testMode */, 1 /* numKeys */);
818
819 bytevec csr;
820 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Tri Vo0d6204e2022-09-29 16:15:34 -0700821 ASSERT_FALSE(status.isOk()) << status.getMessage();
Tri Vob0b8acc2022-11-30 16:22:23 -0800822 ASSERT_EQ(status.getServiceSpecificError(),
823 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
Tri Vo0d6204e2022-09-29 16:15:34 -0700824}
825
Tri Voec50ee12023-02-14 16:29:53 -0800826void parse_root_of_trust(const vector<uint8_t>& attestation_cert,
827 vector<uint8_t>* verified_boot_key, VerifiedBoot* verified_boot_state,
828 bool* device_locked, vector<uint8_t>* verified_boot_hash) {
829 X509_Ptr cert(parse_cert_blob(attestation_cert));
830 ASSERT_TRUE(cert.get());
831
832 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
833 ASSERT_TRUE(attest_rec);
834
835 auto error = parse_root_of_trust(attest_rec->data, attest_rec->length, verified_boot_key,
836 verified_boot_state, device_locked, verified_boot_hash);
837 ASSERT_EQ(error, ErrorCode::OK);
838}
839
840/**
841 * Generate a CSR and verify DeviceInfo against IDs attested by KeyMint.
842 */
843TEST_P(CertificateRequestV2Test, DeviceInfo) {
844 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
845 std::shared_ptr<IKeyMintDevice> keyMint;
846 if (!matching_keymint_device(GetParam(), &keyMint)) {
847 // No matching IKeyMintDevice.
848 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
849 return;
850 }
851 KeyMintHardwareInfo info;
852 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
853
854 // Get IDs attested by KeyMint.
855 MacedPublicKey macedPubKey;
856 bytevec privateKeyBlob;
857 auto irpcStatus =
858 provisionable_->generateEcdsaP256KeyPair(false, &macedPubKey, &privateKeyBlob);
859 ASSERT_TRUE(irpcStatus.isOk());
860
861 AttestationKey attestKey;
862 attestKey.keyBlob = std::move(privateKeyBlob);
863 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
864
865 // Generate an ECDSA key that is attested by the generated P256 keypair.
866 AuthorizationSet keyDesc = AuthorizationSetBuilder()
867 .Authorization(TAG_NO_AUTH_REQUIRED)
868 .EcdsaSigningKey(EcCurve::P_256)
869 .AttestationChallenge("foo")
870 .AttestationApplicationId("bar")
871 .Digest(Digest::NONE)
872 .SetDefaultValidity();
873 KeyCreationResult creationResult;
874 auto kmStatus = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
875 ASSERT_TRUE(kmStatus.isOk());
876
877 vector<KeyCharacteristics> key_characteristics = std::move(creationResult.keyCharacteristics);
878 vector<Certificate> key_cert_chain = std::move(creationResult.certificateChain);
879 // We didn't provision the attestation key.
880 ASSERT_EQ(key_cert_chain.size(), 1);
881
882 // Parse attested patch levels.
883 auto auths = HwEnforcedAuthorizations(key_characteristics);
884
885 auto attestedSystemPatchLevel = auths.GetTagValue(TAG_OS_PATCHLEVEL);
886 auto attestedVendorPatchLevel = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
887 auto attestedBootPatchLevel = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
888
889 ASSERT_TRUE(attestedSystemPatchLevel.has_value());
890 ASSERT_TRUE(attestedVendorPatchLevel.has_value());
891 ASSERT_TRUE(attestedBootPatchLevel.has_value());
892
893 // Parse attested AVB values.
894 vector<uint8_t> key;
895 VerifiedBoot attestedVbState;
896 bool attestedBootloaderState;
897 vector<uint8_t> attestedVbmetaDigest;
898 parse_root_of_trust(key_cert_chain[0].encodedCertificate, &key, &attestedVbState,
899 &attestedBootloaderState, &attestedVbmetaDigest);
900
901 // Get IDs from DeviceInfo.
902 bytevec csr;
903 irpcStatus =
904 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge_, &csr);
905 ASSERT_TRUE(irpcStatus.isOk()) << irpcStatus.getMessage();
906
907 auto result = verifyProductionCsr(cppbor::Array(), csr, provisionable_.get(), challenge_);
908 ASSERT_TRUE(result) << result.message();
909
910 std::unique_ptr<cppbor::Array> csrPayload = std::move(*result);
911 ASSERT_TRUE(csrPayload);
912
913 auto deviceInfo = csrPayload->get(2)->asMap();
914 ASSERT_TRUE(deviceInfo);
915
916 auto vbState = deviceInfo->get("vb_state")->asTstr();
917 auto bootloaderState = deviceInfo->get("bootloader_state")->asTstr();
918 auto vbmetaDigest = deviceInfo->get("vbmeta_digest")->asBstr();
919 auto systemPatchLevel = deviceInfo->get("system_patch_level")->asUint();
920 auto vendorPatchLevel = deviceInfo->get("vendor_patch_level")->asUint();
921 auto bootPatchLevel = deviceInfo->get("boot_patch_level")->asUint();
922 auto securityLevel = deviceInfo->get("security_level")->asTstr();
923
924 ASSERT_TRUE(vbState);
925 ASSERT_TRUE(bootloaderState);
926 ASSERT_TRUE(vbmetaDigest);
927 ASSERT_TRUE(systemPatchLevel);
928 ASSERT_TRUE(vendorPatchLevel);
929 ASSERT_TRUE(bootPatchLevel);
930 ASSERT_TRUE(securityLevel);
931
932 auto kmDeviceName = device_suffix(GetParam());
933
934 // Compare DeviceInfo against IDs attested by KeyMint.
935 ASSERT_TRUE((securityLevel->value() == "tee" && kmDeviceName == "default") ||
936 (securityLevel->value() == "strongbox" && kmDeviceName == "strongbox"));
937 ASSERT_TRUE((vbState->value() == "green" && attestedVbState == VerifiedBoot::VERIFIED) ||
938 (vbState->value() == "yellow" && attestedVbState == VerifiedBoot::SELF_SIGNED) ||
939 (vbState->value() == "orange" && attestedVbState == VerifiedBoot::UNVERIFIED));
940 ASSERT_TRUE((bootloaderState->value() == "locked" && attestedBootloaderState) ||
941 (bootloaderState->value() == "unlocked" && !attestedBootloaderState));
942 ASSERT_EQ(vbmetaDigest->value(), attestedVbmetaDigest);
943 ASSERT_EQ(systemPatchLevel->value(), attestedSystemPatchLevel.value());
944 ASSERT_EQ(vendorPatchLevel->value(), attestedVendorPatchLevel.value());
945 ASSERT_EQ(bootPatchLevel->value(), attestedBootPatchLevel.value());
946}
947
Tri Vo0d6204e2022-09-29 16:15:34 -0700948INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestV2Test);
949
Max Biresa9b3bb92022-11-21 23:02:09 -0800950using VsrRequirementTest = VtsRemotelyProvisionedComponentTests;
951
952INSTANTIATE_REM_PROV_AIDL_TEST(VsrRequirementTest);
953
954TEST_P(VsrRequirementTest, VsrEnforcementTest) {
955 RpcHardwareInfo hwInfo;
956 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
957 int vsr_api_level = get_vsr_api_level();
958 if (vsr_api_level < 34) {
959 GTEST_SKIP() << "Applies only to VSR API level 34 or newer, this device is: "
960 << vsr_api_level;
961 }
962 EXPECT_GE(hwInfo.versionNumber, 3)
963 << "VSR 14+ requires IRemotelyProvisionedComponent v3 or newer.";
964}
965
Shawn Willden274bb552020-09-30 22:39:22 -0600966} // namespace aidl::android::hardware::security::keymint::test