blob: 2a8fd966111ac68bd3e8b94ea442870cfa9393ab [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;
Andrew Scullf2ae1932023-04-24 19:09:09 +000050
51constexpr int32_t VERSION_WITHOUT_EEK = 3;
Tri Vo0d6204e2022-09-29 16:15:34 -070052constexpr int32_t VERSION_WITHOUT_TEST_MODE = 3;
Andrew Scullf2ae1932023-04-24 19:09:09 +000053constexpr int32_t VERSION_WITH_CERTIFICATE_REQUEST_V2 = 3;
54constexpr int32_t VERSION_WITH_SUPPORTED_NUM_KEYS_IN_CSR = 3;
Seth Moorefc86bf42021-12-09 14:07:04 -080055
Tommy Chiufde3ad12023-03-17 05:58:28 +000056constexpr uint8_t MIN_CHALLENGE_SIZE = 0;
57constexpr uint8_t MAX_CHALLENGE_SIZE = 64;
Andrew Scull21461522024-03-25 15:08:08 +000058const string DEFAULT_INSTANCE_NAME =
59 "android.hardware.security.keymint.IRemotelyProvisionedComponent/default";
Alice Wang895f4b32023-11-14 07:38:18 +000060const string RKP_VM_INSTANCE_NAME =
61 "android.hardware.security.keymint.IRemotelyProvisionedComponent/avf";
Andrew Scull21461522024-03-25 15:08:08 +000062const string KEYMINT_STRONGBOX_INSTANCE_NAME =
63 "android.hardware.security.keymint.IKeyMintDevice/strongbox";
Tommy Chiufde3ad12023-03-17 05:58:28 +000064
Shawn Willden274bb552020-09-30 22:39:22 -060065#define INSTANTIATE_REM_PROV_AIDL_TEST(name) \
Seth Moore6305e232021-07-27 14:20:17 -070066 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name); \
Shawn Willden274bb552020-09-30 22:39:22 -060067 INSTANTIATE_TEST_SUITE_P( \
68 PerInstance, name, \
69 testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
70 ::android::PrintInstanceNameToString)
71
Seth Moorefc86bf42021-12-09 14:07:04 -080072using ::android::sp;
Shawn Willden274bb552020-09-30 22:39:22 -060073using bytevec = std::vector<uint8_t>;
74using testing::MatchesRegex;
75using namespace remote_prov;
76using namespace keymaster;
77
78bytevec 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
David Drysdalee99ed862021-03-15 16:43:06 +000083ErrMsgOr<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
David Drysdalecceca9f2021-03-12 15:49:47 +0000107ErrMsgOr<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
Seth Moore19acbe92021-06-23 15:15:52 -0700130ErrMsgOr<bytevec> corrupt_sig_chain(const bytevec& encodedEekChain, int which) {
131 auto [chain, _, parseErr] = cppbor::parse(encodedEekChain);
David Drysdalecceca9f2021-03-12 15:49:47 +0000132 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 }
Seth Moore19acbe92021-06-23 15:15:52 -0700153 return corruptChain.encode();
David Drysdalecceca9f2021-03-12 15:49:47 +0000154}
155
David Drysdale4d3c2982021-03-31 18:21:40 +0100156string 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
164bool 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
Shawn Willden274bb552020-09-30 22:39:22 -0600180} // namespace
181
182class VtsRemotelyProvisionedComponentTests : public testing::TestWithParam<std::string> {
183 public:
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);
Alice Wang895f4b32023-11-14 07:38:18 +0000190 auto status = provisionable_->getHardwareInfo(&rpcHardwareInfo);
191 if (GetParam() == RKP_VM_INSTANCE_NAME &&
192 status.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
193 GTEST_SKIP() << "The RKP VM is not supported on this system.";
194 }
195 ASSERT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600196 }
197
198 static vector<string> build_params() {
199 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
200 return params;
201 }
202
203 protected:
204 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000205 RpcHardwareInfo rpcHardwareInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600206};
207
Seth Moorefc86bf42021-12-09 14:07:04 -0800208/**
209 * Verify that every implementation reports a different unique id.
210 */
211TEST(NonParameterizedTests, eachRpcHasAUniqueId) {
212 std::set<std::string> uniqueIds;
213 for (auto hal : ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor)) {
214 ASSERT_TRUE(AServiceManager_isDeclared(hal.c_str()));
215 ::ndk::SpAIBinder binder(AServiceManager_waitForService(hal.c_str()));
216 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
217 IRemotelyProvisionedComponent::fromBinder(binder);
218 ASSERT_NE(rpc, nullptr);
219
220 RpcHardwareInfo hwInfo;
Alice Wang895f4b32023-11-14 07:38:18 +0000221 auto status = rpc->getHardwareInfo(&hwInfo);
222 if (hal == RKP_VM_INSTANCE_NAME && status.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
223 GTEST_SKIP() << "The RKP VM is not supported on this system.";
224 }
225 ASSERT_TRUE(status.isOk());
Seth Moorefc86bf42021-12-09 14:07:04 -0800226
Tri Vodd12c482022-10-12 22:41:28 +0000227 if (hwInfo.versionNumber >= VERSION_WITH_UNIQUE_ID_SUPPORT) {
Seth Moorefc86bf42021-12-09 14:07:04 -0800228 ASSERT_TRUE(hwInfo.uniqueId);
229 auto [_, wasInserted] = uniqueIds.insert(*hwInfo.uniqueId);
230 EXPECT_TRUE(wasInserted);
231 } else {
232 ASSERT_FALSE(hwInfo.uniqueId);
233 }
234 }
235}
236
Andrew Scull21461522024-03-25 15:08:08 +0000237/**
238 * Verify that the default implementation supports DICE if there is a StrongBox KeyMint instance
239 * on the device.
240 */
241// @VsrTest = 3.10-015
242TEST(NonParameterizedTests, requireDiceOnDefaultInstanceIfStrongboxPresent) {
243 int vsr_api_level = get_vsr_api_level();
244 if (vsr_api_level < 35) {
245 GTEST_SKIP() << "Applies only to VSR API level 35 or newer, this device is: "
246 << vsr_api_level;
247 }
248
249 if (!AServiceManager_isDeclared(KEYMINT_STRONGBOX_INSTANCE_NAME.c_str())) {
250 GTEST_SKIP() << "Strongbox is not present on this device.";
251 }
252
253 ::ndk::SpAIBinder binder(AServiceManager_waitForService(DEFAULT_INSTANCE_NAME.c_str()));
254 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
255 IRemotelyProvisionedComponent::fromBinder(binder);
256 ASSERT_NE(rpc, nullptr);
257
258 bytevec challenge = randomBytes(64);
259 bytevec csr;
260 auto status = rpc->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
261 EXPECT_TRUE(status.isOk()) << status.getDescription();
262
263 auto result = isCsrWithProperDiceChain(csr);
264 ASSERT_TRUE(result) << result.message();
265 ASSERT_TRUE(*result);
266}
267
Seth Moorefc86bf42021-12-09 14:07:04 -0800268using GetHardwareInfoTests = VtsRemotelyProvisionedComponentTests;
269
270INSTANTIATE_REM_PROV_AIDL_TEST(GetHardwareInfoTests);
271
272/**
273 * Verify that a valid curve is reported by the implementation.
274 */
275TEST_P(GetHardwareInfoTests, supportsValidCurve) {
276 RpcHardwareInfo hwInfo;
277 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
278
Andrew Scullf2ae1932023-04-24 19:09:09 +0000279 if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_EEK) {
280 ASSERT_EQ(hwInfo.supportedEekCurve, RpcHardwareInfo::CURVE_NONE)
281 << "Invalid curve: " << hwInfo.supportedEekCurve;
282 return;
Hasini Gunasinghe666b2712023-01-05 21:35:51 +0000283 }
Andrew Scullf2ae1932023-04-24 19:09:09 +0000284
285 const std::set<int> validCurves = {RpcHardwareInfo::CURVE_P256, RpcHardwareInfo::CURVE_25519};
Seth Moorefc86bf42021-12-09 14:07:04 -0800286 ASSERT_EQ(validCurves.count(hwInfo.supportedEekCurve), 1)
287 << "Invalid curve: " << hwInfo.supportedEekCurve;
288}
289
290/**
291 * Verify that the unique id is within the length limits as described in RpcHardwareInfo.aidl.
292 */
293TEST_P(GetHardwareInfoTests, uniqueId) {
Tri Vodd12c482022-10-12 22:41:28 +0000294 if (rpcHardwareInfo.versionNumber < VERSION_WITH_UNIQUE_ID_SUPPORT) {
Seth Moorefc86bf42021-12-09 14:07:04 -0800295 return;
296 }
297
298 RpcHardwareInfo hwInfo;
299 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
300 ASSERT_TRUE(hwInfo.uniqueId);
301 EXPECT_GE(hwInfo.uniqueId->size(), 1);
302 EXPECT_LE(hwInfo.uniqueId->size(), 32);
303}
304
Tri Vo9cab73c2022-10-28 13:40:24 -0700305/**
306 * Verify implementation supports at least MIN_SUPPORTED_NUM_KEYS_IN_CSR keys in a CSR.
307 */
308TEST_P(GetHardwareInfoTests, supportedNumKeysInCsr) {
Andrew Scullf2ae1932023-04-24 19:09:09 +0000309 if (rpcHardwareInfo.versionNumber < VERSION_WITH_SUPPORTED_NUM_KEYS_IN_CSR) {
Tri Vo9cab73c2022-10-28 13:40:24 -0700310 return;
311 }
312
313 RpcHardwareInfo hwInfo;
314 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
315 ASSERT_GE(hwInfo.supportedNumKeysInCsr, RpcHardwareInfo::MIN_SUPPORTED_NUM_KEYS_IN_CSR);
316}
317
Shawn Willden274bb552020-09-30 22:39:22 -0600318using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
319
320INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
321
322/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000323 * Generate and validate a production-mode key. MAC tag can't be verified, but
324 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600325 */
Max Bires126869a2021-02-21 18:32:59 -0800326TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600327 MacedPublicKey macedPubKey;
328 bytevec privateKeyBlob;
329 bool testMode = false;
330 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
331 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000332 vector<uint8_t> coseKeyData;
Tri Vob0b8acc2022-11-30 16:22:23 -0800333 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100334}
335
336/**
337 * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
338 */
339TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
340 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
341 std::shared_ptr<IKeyMintDevice> keyMint;
342 if (!matching_keymint_device(GetParam(), &keyMint)) {
343 // No matching IKeyMintDevice.
344 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
345 return;
346 }
347 KeyMintHardwareInfo info;
348 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
349
350 MacedPublicKey macedPubKey;
351 bytevec privateKeyBlob;
352 bool testMode = false;
353 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
354 ASSERT_TRUE(status.isOk());
355 vector<uint8_t> coseKeyData;
Tri Vob0b8acc2022-11-30 16:22:23 -0800356 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100357
David Drysdalef0d516d2021-03-22 07:51:43 +0000358 AttestationKey attestKey;
359 attestKey.keyBlob = std::move(privateKeyBlob);
360 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600361
David Drysdalef0d516d2021-03-22 07:51:43 +0000362 // Generate an ECDSA key that is attested by the generated P256 keypair.
363 AuthorizationSet keyDesc = AuthorizationSetBuilder()
364 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale915ce252021-10-14 15:17:36 +0100365 .EcdsaSigningKey(EcCurve::P_256)
David Drysdalef0d516d2021-03-22 07:51:43 +0000366 .AttestationChallenge("foo")
367 .AttestationApplicationId("bar")
368 .Digest(Digest::NONE)
369 .SetDefaultValidity();
370 KeyCreationResult creationResult;
371 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
372 ASSERT_TRUE(result.isOk());
373 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
374 vector<KeyCharacteristics> attested_key_characteristics =
375 std::move(creationResult.keyCharacteristics);
376 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
377 EXPECT_EQ(attested_key_cert_chain.size(), 1);
378
David Drysdale7dff4fc2021-12-10 10:10:52 +0000379 int32_t aidl_version = 0;
380 ASSERT_TRUE(keyMint->getInterfaceVersion(&aidl_version).isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000381 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
382 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +0000383 EXPECT_TRUE(verify_attestation_record(aidl_version, "foo", "bar", sw_enforced, hw_enforced,
David Drysdalef0d516d2021-03-22 07:51:43 +0000384 info.securityLevel,
385 attested_key_cert_chain[0].encodedCertificate));
386
387 // Attestation by itself is not valid (last entry is not self-signed).
388 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
389
390 // The signature over the attested key should correspond to the P256 public key.
391 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
392 ASSERT_TRUE(key_cert.get());
393 EVP_PKEY_Ptr signing_pubkey;
394 p256_pub_key(coseKeyData, &signing_pubkey);
395 ASSERT_TRUE(signing_pubkey.get());
396
397 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
398 << "Verification of attested certificate failed "
399 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600400}
401
402/**
403 * Generate and validate a test-mode key.
404 */
Max Bires126869a2021-02-21 18:32:59 -0800405TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600406 MacedPublicKey macedPubKey;
407 bytevec privateKeyBlob;
408 bool testMode = true;
409 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
Andrew Scullf2ae1932023-04-24 19:09:09 +0000410
411 if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_TEST_MODE) {
412 ASSERT_FALSE(status.isOk());
413 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
414 return;
415 }
416
Shawn Willden274bb552020-09-30 22:39:22 -0600417 ASSERT_TRUE(status.isOk());
Tri Vob0b8acc2022-11-30 16:22:23 -0800418 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600419}
420
Tri Vo0d6204e2022-09-29 16:15:34 -0700421class CertificateRequestTestBase : public VtsRemotelyProvisionedComponentTests {
Shawn Willden274bb552020-09-30 22:39:22 -0600422 protected:
Tri Vo0d6204e2022-09-29 16:15:34 -0700423 CertificateRequestTestBase()
424 : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(64)) {}
David Drysdalecceca9f2021-03-12 15:49:47 +0000425
Seth Moore19acbe92021-06-23 15:15:52 -0700426 void generateTestEekChain(size_t eekLength) {
subrahmanyamanfb213d62022-02-02 23:10:55 +0000427 auto chain = generateEekChain(rpcHardwareInfo.supportedEekCurve, eekLength, eekId_);
David Drysdale08696a72022-03-10 10:43:25 +0000428 ASSERT_TRUE(chain) << chain.message();
Seth Moore19acbe92021-06-23 15:15:52 -0700429 if (chain) testEekChain_ = chain.moveValue();
430 testEekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600431 }
432
433 void generateKeys(bool testMode, size_t numKeys) {
434 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
435 cborKeysToSign_ = cppbor::Array();
436
437 for (auto& key : keysToSign_) {
438 bytevec privateKeyBlob;
439 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
Frederick Mayle9891be02023-11-03 14:39:24 -0700440 ASSERT_TRUE(status.isOk()) << status.getDescription();
Shawn Willden274bb552020-09-30 22:39:22 -0600441
David Drysdalec8400772021-03-11 12:35:11 +0000442 vector<uint8_t> payload_value;
Tri Vob0b8acc2022-11-30 16:22:23 -0800443 check_maced_pubkey(key, testMode, &payload_value);
David Drysdalec8400772021-03-11 12:35:11 +0000444 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600445 }
446 }
447
448 bytevec eekId_;
Seth Moore19acbe92021-06-23 15:15:52 -0700449 size_t testEekLength_;
450 EekChain testEekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000451 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600452 std::vector<MacedPublicKey> keysToSign_;
453 cppbor::Array cborKeysToSign_;
454};
455
Tri Vo0d6204e2022-09-29 16:15:34 -0700456class CertificateRequestTest : public CertificateRequestTestBase {
457 protected:
458 void SetUp() override {
459 CertificateRequestTestBase::SetUp();
Andrew Scull1bcb6022022-12-27 10:43:27 +0000460 ASSERT_FALSE(HasFatalFailure());
Tri Vo0d6204e2022-09-29 16:15:34 -0700461
Andrew Scullf2ae1932023-04-24 19:09:09 +0000462 if (rpcHardwareInfo.versionNumber >= VERSION_WITH_CERTIFICATE_REQUEST_V2) {
Andrew Scull95b31312023-03-27 19:16:07 +0000463 GTEST_SKIP() << "This test case only applies to RKP v1 and v2. "
464 << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
Tri Vo0d6204e2022-09-29 16:15:34 -0700465 }
466 }
467};
468
Shawn Willden274bb552020-09-30 22:39:22 -0600469/**
470 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
471 * content.
472 */
Max Bires126869a2021-02-21 18:32:59 -0800473TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600474 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000475 for (size_t eekLength : {2, 3, 7}) {
476 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700477 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600478
David Drysdalecceca9f2021-03-12 15:49:47 +0000479 bytevec keysToSignMac;
480 DeviceInfo deviceInfo;
481 ProtectedData protectedData;
482 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700483 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalecceca9f2021-03-12 15:49:47 +0000484 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700485 ASSERT_TRUE(status.isOk()) << status.getDescription();
David Drysdalecceca9f2021-03-12 15:49:47 +0000486
Seth Moore2fc6f832022-09-13 16:10:11 -0700487 auto result = verifyProductionProtectedData(
488 deviceInfo, cppbor::Array(), keysToSignMac, protectedData, testEekChain_, eekId_,
489 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
490 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000491 }
Shawn Willden274bb552020-09-30 22:39:22 -0600492}
493
494/**
Seth Moore42c11332021-07-02 15:38:17 -0700495 * Ensure that test mode outputs a unique BCC root key every time we request a
496 * certificate request. Else, it's possible that the test mode API could be used
497 * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
498 * device public key multiple times.
499 */
500TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
501 constexpr bool testMode = true;
Seth Moore42c11332021-07-02 15:38:17 -0700502
503 bytevec keysToSignMac;
504 DeviceInfo deviceInfo;
505 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000506 generateTestEekChain(3);
Seth Moore42c11332021-07-02 15:38:17 -0700507 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700508 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
509 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700510 ASSERT_TRUE(status.isOk()) << status.getDescription();
Seth Moore42c11332021-07-02 15:38:17 -0700511
Seth Moore2fc6f832022-09-13 16:10:11 -0700512 auto firstBcc = verifyProductionProtectedData(
513 deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
514 eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
515 ASSERT_TRUE(firstBcc) << firstBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700516
Seth Moore19acbe92021-06-23 15:15:52 -0700517 status = provisionable_->generateCertificateRequest(
518 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
519 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700520 ASSERT_TRUE(status.isOk()) << status.getDescription();
Seth Moore42c11332021-07-02 15:38:17 -0700521
Seth Moore2fc6f832022-09-13 16:10:11 -0700522 auto secondBcc = verifyProductionProtectedData(
523 deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
524 eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
525 ASSERT_TRUE(secondBcc) << secondBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700526
527 // Verify that none of the keys in the first BCC are repeated in the second one.
Seth Moore2fc6f832022-09-13 16:10:11 -0700528 for (const auto& i : *firstBcc) {
529 for (auto& j : *secondBcc) {
Seth Moore42c11332021-07-02 15:38:17 -0700530 ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
531 << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
532 }
533 }
534}
535
536/**
Seth Moore19acbe92021-06-23 15:15:52 -0700537 * Generate an empty certificate request in prod mode. This test must be run explicitly, and
538 * is not run by default. Not all devices are GMS devices, and therefore they do not all
539 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600540 */
Seth Moore19acbe92021-06-23 15:15:52 -0700541TEST_P(CertificateRequestTest, DISABLED_EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600542 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000543
Seth Moore19acbe92021-06-23 15:15:52 -0700544 bytevec keysToSignMac;
545 DeviceInfo deviceInfo;
546 ProtectedData protectedData;
547 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000548 testMode, {} /* keysToSign */, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
549 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700550 EXPECT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600551}
552
553/**
554 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
555 */
Max Bires126869a2021-02-21 18:32:59 -0800556TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600557 bool testMode = true;
558 generateKeys(testMode, 4 /* numKeys */);
559
David Drysdalecceca9f2021-03-12 15:49:47 +0000560 for (size_t eekLength : {2, 3, 7}) {
561 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700562 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600563
David Drysdalecceca9f2021-03-12 15:49:47 +0000564 bytevec keysToSignMac;
565 DeviceInfo deviceInfo;
566 ProtectedData protectedData;
567 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700568 testMode, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo, &protectedData,
David Drysdalecceca9f2021-03-12 15:49:47 +0000569 &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700570 ASSERT_TRUE(status.isOk()) << status.getDescription();
David Drysdalecceca9f2021-03-12 15:49:47 +0000571
Seth Moore2fc6f832022-09-13 16:10:11 -0700572 auto result = verifyProductionProtectedData(
573 deviceInfo, cborKeysToSign_, keysToSignMac, protectedData, testEekChain_, eekId_,
574 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
575 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000576 }
Shawn Willden274bb552020-09-30 22:39:22 -0600577}
578
579/**
Seth Moore19acbe92021-06-23 15:15:52 -0700580 * Generate a non-empty certificate request in prod mode. This test must be run explicitly, and
581 * is not run by default. Not all devices are GMS devices, and therefore they do not all
582 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600583 */
Seth Moore19acbe92021-06-23 15:15:52 -0700584TEST_P(CertificateRequestTest, DISABLED_NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600585 bool testMode = false;
586 generateKeys(testMode, 4 /* numKeys */);
587
Seth Moore19acbe92021-06-23 15:15:52 -0700588 bytevec keysToSignMac;
589 DeviceInfo deviceInfo;
590 ProtectedData protectedData;
591 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000592 testMode, keysToSign_, getProdEekChain(rpcHardwareInfo.supportedEekCurve), challenge_,
593 &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700594 EXPECT_TRUE(status.isOk());
David Drysdalecceca9f2021-03-12 15:49:47 +0000595}
596
597/**
David Drysdalee99ed862021-03-15 16:43:06 +0000598 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
599 */
600TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
601 bool testMode = true;
602 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000603 auto result = corrupt_maced_key(keysToSign_[0]);
604 ASSERT_TRUE(result) << result.moveMessage();
605 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000606
607 bytevec keysToSignMac;
608 DeviceInfo deviceInfo;
609 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000610 generateTestEekChain(3);
David Drysdalee99ed862021-03-15 16:43:06 +0000611 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700612 testMode, {keyWithCorruptMac}, testEekChain_.chain, challenge_, &deviceInfo,
613 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700614 ASSERT_FALSE(status.isOk()) << status.getDescription();
David Drysdalee99ed862021-03-15 16:43:06 +0000615 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
616}
617
618/**
619 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
620 */
621TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
Seth Moore19acbe92021-06-23 15:15:52 -0700622 bool testMode = false;
David Drysdalee99ed862021-03-15 16:43:06 +0000623 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000624 auto result = corrupt_maced_key(keysToSign_[0]);
625 ASSERT_TRUE(result) << result.moveMessage();
626 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000627
628 bytevec keysToSignMac;
629 DeviceInfo deviceInfo;
630 ProtectedData protectedData;
631 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000632 testMode, {keyWithCorruptMac}, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
633 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700634 ASSERT_FALSE(status.isOk()) << status.getDescription();
Seth Moore19acbe92021-06-23 15:15:52 -0700635 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
David Drysdalee99ed862021-03-15 16:43:06 +0000636}
637
638/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000639 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
640 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000641 */
642TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
643 bool testMode = false;
644 generateKeys(testMode, 4 /* numKeys */);
645
subrahmanyamanfb213d62022-02-02 23:10:55 +0000646 auto prodEekChain = getProdEekChain(rpcHardwareInfo.supportedEekCurve);
Seth Moore19acbe92021-06-23 15:15:52 -0700647 auto [parsedChain, _, parseErr] = cppbor::parse(prodEekChain);
648 ASSERT_NE(parsedChain, nullptr) << parseErr;
649 ASSERT_NE(parsedChain->asArray(), nullptr);
650
651 for (int ii = 0; ii < parsedChain->asArray()->size(); ++ii) {
652 auto chain = corrupt_sig_chain(prodEekChain, ii);
David Drysdalecceca9f2021-03-12 15:49:47 +0000653 ASSERT_TRUE(chain) << chain.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000654
655 bytevec keysToSignMac;
656 DeviceInfo deviceInfo;
657 ProtectedData protectedData;
Seth Moore19acbe92021-06-23 15:15:52 -0700658 auto status = provisionable_->generateCertificateRequest(testMode, keysToSign_, *chain,
659 challenge_, &deviceInfo,
660 &protectedData, &keysToSignMac);
David Drysdalecceca9f2021-03-12 15:49:47 +0000661 ASSERT_FALSE(status.isOk());
662 ASSERT_EQ(status.getServiceSpecificError(),
663 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
664 }
665}
666
667/**
668 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
669 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000670 */
671TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
672 bool testMode = false;
673 generateKeys(testMode, 4 /* numKeys */);
674
675 // Build an EEK chain that omits the first self-signed cert.
676 auto truncatedChain = cppbor::Array();
subrahmanyamanfb213d62022-02-02 23:10:55 +0000677 auto [chain, _, parseErr] = cppbor::parse(getProdEekChain(rpcHardwareInfo.supportedEekCurve));
David Drysdalecceca9f2021-03-12 15:49:47 +0000678 ASSERT_TRUE(chain);
679 auto eekChain = chain->asArray();
680 ASSERT_NE(eekChain, nullptr);
681 for (size_t ii = 1; ii < eekChain->size(); ii++) {
682 truncatedChain.add(eekChain->get(ii)->clone());
683 }
684
Shawn Willden274bb552020-09-30 22:39:22 -0600685 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700686 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600687 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000688 auto status = provisionable_->generateCertificateRequest(
689 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
690 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600691 ASSERT_FALSE(status.isOk());
692 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
693}
694
695/**
696 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
697 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
698 */
Max Bires126869a2021-02-21 18:32:59 -0800699TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600700 generateKeys(false /* testMode */, 2 /* numKeys */);
701
702 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700703 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600704 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000705 generateTestEekChain(3);
Max Biresfdbb9042021-03-23 12:43:38 -0700706 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700707 true /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700708 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600709 ASSERT_FALSE(status.isOk());
710 ASSERT_EQ(status.getServiceSpecificError(),
711 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
712}
713
714/**
715 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
716 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
717 */
Max Bires126869a2021-02-21 18:32:59 -0800718TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600719 generateKeys(true /* testMode */, 2 /* numKeys */);
720
721 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700722 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600723 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000724 generateTestEekChain(3);
Shawn Willden274bb552020-09-30 22:39:22 -0600725 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700726 false /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalec8400772021-03-11 12:35:11 +0000727 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600728 ASSERT_FALSE(status.isOk());
729 ASSERT_EQ(status.getServiceSpecificError(),
730 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
731}
732
733INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
734
Tri Vo0d6204e2022-09-29 16:15:34 -0700735class CertificateRequestV2Test : public CertificateRequestTestBase {
736 void SetUp() override {
737 CertificateRequestTestBase::SetUp();
Andrew Scull1bcb6022022-12-27 10:43:27 +0000738 ASSERT_FALSE(HasFatalFailure());
Tri Vo0d6204e2022-09-29 16:15:34 -0700739
Andrew Scullf2ae1932023-04-24 19:09:09 +0000740 if (rpcHardwareInfo.versionNumber < VERSION_WITH_CERTIFICATE_REQUEST_V2) {
Tri Vo0d6204e2022-09-29 16:15:34 -0700741 GTEST_SKIP() << "This test case only applies to RKP v3 and above. "
742 << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
743 }
744 }
745};
746
747/**
Tommy Chiufde3ad12023-03-17 05:58:28 +0000748 * Generate an empty certificate request with all possible length of challenge, and decrypt and
749 * verify the structure and content.
Tri Vo0d6204e2022-09-29 16:15:34 -0700750 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700751// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700752TEST_P(CertificateRequestV2Test, EmptyRequest) {
753 bytevec csr;
754
Tommy Chiufde3ad12023-03-17 05:58:28 +0000755 for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
756 SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
757 auto challenge = randomBytes(size);
758 auto status =
759 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700760 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700761
Tommy Chiufde3ad12023-03-17 05:58:28 +0000762 auto result = verifyProductionCsr(cppbor::Array(), csr, provisionable_.get(), challenge);
763 ASSERT_TRUE(result) << result.message();
764 }
Tri Vo0d6204e2022-09-29 16:15:34 -0700765}
766
767/**
Tommy Chiufde3ad12023-03-17 05:58:28 +0000768 * Generate a non-empty certificate request with all possible length of challenge. Decrypt, parse
769 * and validate the contents.
Tri Vo0d6204e2022-09-29 16:15:34 -0700770 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700771// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700772TEST_P(CertificateRequestV2Test, NonEmptyRequest) {
773 generateKeys(false /* testMode */, 1 /* numKeys */);
774
775 bytevec csr;
776
Tommy Chiufde3ad12023-03-17 05:58:28 +0000777 for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
778 SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
779 auto challenge = randomBytes(size);
780 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700781 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700782
Tommy Chiufde3ad12023-03-17 05:58:28 +0000783 auto result = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge);
784 ASSERT_TRUE(result) << result.message();
785 }
786}
787
788/**
789 * Generate an empty certificate request with invalid size of challenge
790 */
791TEST_P(CertificateRequestV2Test, EmptyRequestWithInvalidChallengeFail) {
792 bytevec csr;
793
794 auto status = provisionable_->generateCertificateRequestV2(
795 /* keysToSign */ {}, randomBytes(MAX_CHALLENGE_SIZE + 1), &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700796 EXPECT_FALSE(status.isOk()) << status.getDescription();
Tommy Chiufde3ad12023-03-17 05:58:28 +0000797 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_FAILED);
Tri Vo0d6204e2022-09-29 16:15:34 -0700798}
799
800/**
Andrew Scullfb49ad22022-11-09 21:02:48 +0000801 * Generate a non-empty certificate request. Make sure contents are reproducible but allow for the
802 * signature to be different since algorithms including ECDSA P-256 can include a random value.
Tri Vo0d6204e2022-09-29 16:15:34 -0700803 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700804// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700805TEST_P(CertificateRequestV2Test, NonEmptyRequestReproducible) {
806 generateKeys(false /* testMode */, 1 /* numKeys */);
807
808 bytevec csr;
809
810 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700811 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700812
Andrew Scullfb49ad22022-11-09 21:02:48 +0000813 auto firstCsr = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
814 ASSERT_TRUE(firstCsr) << firstCsr.message();
Tri Vo0d6204e2022-09-29 16:15:34 -0700815
816 status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700817 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700818
Andrew Scullfb49ad22022-11-09 21:02:48 +0000819 auto secondCsr = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
820 ASSERT_TRUE(secondCsr) << secondCsr.message();
Tri Vo0d6204e2022-09-29 16:15:34 -0700821
Andrew Scullfb49ad22022-11-09 21:02:48 +0000822 ASSERT_EQ(**firstCsr, **secondCsr);
Tri Vo0d6204e2022-09-29 16:15:34 -0700823}
824
825/**
826 * Generate a non-empty certificate request with multiple keys.
827 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700828// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700829TEST_P(CertificateRequestV2Test, NonEmptyRequestMultipleKeys) {
Tri Vo9cab73c2022-10-28 13:40:24 -0700830 generateKeys(false /* testMode */, rpcHardwareInfo.supportedNumKeysInCsr /* numKeys */);
Tri Vo0d6204e2022-09-29 16:15:34 -0700831
832 bytevec csr;
833
834 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700835 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700836
837 auto result = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
838 ASSERT_TRUE(result) << result.message();
839}
840
841/**
842 * Generate a non-empty certificate request, but with the MAC corrupted on the keypair.
843 */
844TEST_P(CertificateRequestV2Test, NonEmptyRequestCorruptMac) {
845 generateKeys(false /* testMode */, 1 /* numKeys */);
846 auto result = corrupt_maced_key(keysToSign_[0]);
847 ASSERT_TRUE(result) << result.moveMessage();
848 MacedPublicKey keyWithCorruptMac = result.moveValue();
849
850 bytevec csr;
851 auto status =
852 provisionable_->generateCertificateRequestV2({keyWithCorruptMac}, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700853 ASSERT_FALSE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700854 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
855}
856
857/**
Andrew Scullf2ae1932023-04-24 19:09:09 +0000858 * Call generateCertificateRequest(). Make sure it's removed.
Tri Vo0d6204e2022-09-29 16:15:34 -0700859 */
Andrew Scullf2ae1932023-04-24 19:09:09 +0000860TEST_P(CertificateRequestV2Test, CertificateRequestV1Removed_prodMode) {
861 bytevec keysToSignMac;
862 DeviceInfo deviceInfo;
863 ProtectedData protectedData;
864 auto status = provisionable_->generateCertificateRequest(
865 false /* testMode */, {} /* keysToSign */, {} /* EEK chain */, challenge_, &deviceInfo,
866 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700867 ASSERT_FALSE(status.isOk()) << status.getDescription();
Andrew Scullf2ae1932023-04-24 19:09:09 +0000868 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
Tri Vo0d6204e2022-09-29 16:15:34 -0700869}
870
Andrew Scull95b31312023-03-27 19:16:07 +0000871/**
Andrew Scullf2ae1932023-04-24 19:09:09 +0000872 * Call generateCertificateRequest() in test mode. Make sure it's removed.
Andrew Scull95b31312023-03-27 19:16:07 +0000873 */
Andrew Scullf2ae1932023-04-24 19:09:09 +0000874TEST_P(CertificateRequestV2Test, CertificateRequestV1Removed_testMode) {
Andrew Scull95b31312023-03-27 19:16:07 +0000875 bytevec keysToSignMac;
876 DeviceInfo deviceInfo;
877 ProtectedData protectedData;
878 auto status = provisionable_->generateCertificateRequest(
879 true /* testMode */, {} /* keysToSign */, {} /* EEK chain */, challenge_, &deviceInfo,
880 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700881 ASSERT_FALSE(status.isOk()) << status.getDescription();
Andrew Scull95b31312023-03-27 19:16:07 +0000882 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
883}
884
Tri Voec50ee12023-02-14 16:29:53 -0800885void parse_root_of_trust(const vector<uint8_t>& attestation_cert,
886 vector<uint8_t>* verified_boot_key, VerifiedBoot* verified_boot_state,
887 bool* device_locked, vector<uint8_t>* verified_boot_hash) {
888 X509_Ptr cert(parse_cert_blob(attestation_cert));
889 ASSERT_TRUE(cert.get());
890
891 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
892 ASSERT_TRUE(attest_rec);
893
894 auto error = parse_root_of_trust(attest_rec->data, attest_rec->length, verified_boot_key,
895 verified_boot_state, device_locked, verified_boot_hash);
896 ASSERT_EQ(error, ErrorCode::OK);
897}
898
899/**
900 * Generate a CSR and verify DeviceInfo against IDs attested by KeyMint.
901 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700902// @VsrTest = 3.10-015
Tri Voec50ee12023-02-14 16:29:53 -0800903TEST_P(CertificateRequestV2Test, DeviceInfo) {
904 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
905 std::shared_ptr<IKeyMintDevice> keyMint;
906 if (!matching_keymint_device(GetParam(), &keyMint)) {
907 // No matching IKeyMintDevice.
908 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
909 return;
910 }
911 KeyMintHardwareInfo info;
912 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
913
914 // Get IDs attested by KeyMint.
915 MacedPublicKey macedPubKey;
916 bytevec privateKeyBlob;
917 auto irpcStatus =
918 provisionable_->generateEcdsaP256KeyPair(false, &macedPubKey, &privateKeyBlob);
919 ASSERT_TRUE(irpcStatus.isOk());
920
921 AttestationKey attestKey;
922 attestKey.keyBlob = std::move(privateKeyBlob);
923 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
924
925 // Generate an ECDSA key that is attested by the generated P256 keypair.
926 AuthorizationSet keyDesc = AuthorizationSetBuilder()
927 .Authorization(TAG_NO_AUTH_REQUIRED)
928 .EcdsaSigningKey(EcCurve::P_256)
929 .AttestationChallenge("foo")
930 .AttestationApplicationId("bar")
931 .Digest(Digest::NONE)
932 .SetDefaultValidity();
933 KeyCreationResult creationResult;
934 auto kmStatus = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
935 ASSERT_TRUE(kmStatus.isOk());
936
937 vector<KeyCharacteristics> key_characteristics = std::move(creationResult.keyCharacteristics);
938 vector<Certificate> key_cert_chain = std::move(creationResult.certificateChain);
939 // We didn't provision the attestation key.
940 ASSERT_EQ(key_cert_chain.size(), 1);
941
942 // Parse attested patch levels.
943 auto auths = HwEnforcedAuthorizations(key_characteristics);
944
945 auto attestedSystemPatchLevel = auths.GetTagValue(TAG_OS_PATCHLEVEL);
946 auto attestedVendorPatchLevel = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
947 auto attestedBootPatchLevel = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
948
949 ASSERT_TRUE(attestedSystemPatchLevel.has_value());
950 ASSERT_TRUE(attestedVendorPatchLevel.has_value());
951 ASSERT_TRUE(attestedBootPatchLevel.has_value());
952
953 // Parse attested AVB values.
954 vector<uint8_t> key;
955 VerifiedBoot attestedVbState;
956 bool attestedBootloaderState;
957 vector<uint8_t> attestedVbmetaDigest;
958 parse_root_of_trust(key_cert_chain[0].encodedCertificate, &key, &attestedVbState,
959 &attestedBootloaderState, &attestedVbmetaDigest);
960
961 // Get IDs from DeviceInfo.
962 bytevec csr;
963 irpcStatus =
964 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700965 ASSERT_TRUE(irpcStatus.isOk()) << irpcStatus.getDescription();
Tri Voec50ee12023-02-14 16:29:53 -0800966
967 auto result = verifyProductionCsr(cppbor::Array(), csr, provisionable_.get(), challenge_);
968 ASSERT_TRUE(result) << result.message();
969
970 std::unique_ptr<cppbor::Array> csrPayload = std::move(*result);
971 ASSERT_TRUE(csrPayload);
972
973 auto deviceInfo = csrPayload->get(2)->asMap();
974 ASSERT_TRUE(deviceInfo);
975
976 auto vbState = deviceInfo->get("vb_state")->asTstr();
977 auto bootloaderState = deviceInfo->get("bootloader_state")->asTstr();
978 auto vbmetaDigest = deviceInfo->get("vbmeta_digest")->asBstr();
979 auto systemPatchLevel = deviceInfo->get("system_patch_level")->asUint();
980 auto vendorPatchLevel = deviceInfo->get("vendor_patch_level")->asUint();
981 auto bootPatchLevel = deviceInfo->get("boot_patch_level")->asUint();
982 auto securityLevel = deviceInfo->get("security_level")->asTstr();
983
984 ASSERT_TRUE(vbState);
985 ASSERT_TRUE(bootloaderState);
986 ASSERT_TRUE(vbmetaDigest);
987 ASSERT_TRUE(systemPatchLevel);
988 ASSERT_TRUE(vendorPatchLevel);
989 ASSERT_TRUE(bootPatchLevel);
990 ASSERT_TRUE(securityLevel);
991
992 auto kmDeviceName = device_suffix(GetParam());
993
994 // Compare DeviceInfo against IDs attested by KeyMint.
995 ASSERT_TRUE((securityLevel->value() == "tee" && kmDeviceName == "default") ||
996 (securityLevel->value() == "strongbox" && kmDeviceName == "strongbox"));
997 ASSERT_TRUE((vbState->value() == "green" && attestedVbState == VerifiedBoot::VERIFIED) ||
998 (vbState->value() == "yellow" && attestedVbState == VerifiedBoot::SELF_SIGNED) ||
999 (vbState->value() == "orange" && attestedVbState == VerifiedBoot::UNVERIFIED));
1000 ASSERT_TRUE((bootloaderState->value() == "locked" && attestedBootloaderState) ||
1001 (bootloaderState->value() == "unlocked" && !attestedBootloaderState));
1002 ASSERT_EQ(vbmetaDigest->value(), attestedVbmetaDigest);
1003 ASSERT_EQ(systemPatchLevel->value(), attestedSystemPatchLevel.value());
1004 ASSERT_EQ(vendorPatchLevel->value(), attestedVendorPatchLevel.value());
1005 ASSERT_EQ(bootPatchLevel->value(), attestedBootPatchLevel.value());
1006}
1007
Tri Vo0d6204e2022-09-29 16:15:34 -07001008INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestV2Test);
1009
Max Biresa9b3bb92022-11-21 23:02:09 -08001010using VsrRequirementTest = VtsRemotelyProvisionedComponentTests;
1011
1012INSTANTIATE_REM_PROV_AIDL_TEST(VsrRequirementTest);
1013
1014TEST_P(VsrRequirementTest, VsrEnforcementTest) {
1015 RpcHardwareInfo hwInfo;
1016 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
1017 int vsr_api_level = get_vsr_api_level();
1018 if (vsr_api_level < 34) {
1019 GTEST_SKIP() << "Applies only to VSR API level 34 or newer, this device is: "
1020 << vsr_api_level;
1021 }
1022 EXPECT_GE(hwInfo.versionNumber, 3)
1023 << "VSR 14+ requires IRemotelyProvisionedComponent v3 or newer.";
1024}
1025
Shawn Willden274bb552020-09-30 22:39:22 -06001026} // namespace aidl::android::hardware::security::keymint::test