blob: b9c742a93850b1ba908c26f25a3c4883a520bf8e [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>
Sean Thomasafbab602024-11-07 23:14:05 +000038#include <string_view>
Seth Moore42c11332021-07-02 15:38:17 -070039#include <vector>
Shawn Willden274bb552020-09-30 22:39:22 -060040
David Drysdalef0d516d2021-03-22 07:51:43 +000041#include "KeyMintAidlTestBase.h"
42
Shawn Willden274bb552020-09-30 22:39:22 -060043namespace aidl::android::hardware::security::keymint::test {
44
45using ::std::string;
46using ::std::vector;
47
48namespace {
49
Seth Moorefc86bf42021-12-09 14:07:04 -080050constexpr int32_t VERSION_WITH_UNIQUE_ID_SUPPORT = 2;
Andrew Scullf2ae1932023-04-24 19:09:09 +000051
52constexpr int32_t VERSION_WITHOUT_EEK = 3;
Tri Vo0d6204e2022-09-29 16:15:34 -070053constexpr int32_t VERSION_WITHOUT_TEST_MODE = 3;
Andrew Scullf2ae1932023-04-24 19:09:09 +000054constexpr int32_t VERSION_WITH_CERTIFICATE_REQUEST_V2 = 3;
55constexpr int32_t VERSION_WITH_SUPPORTED_NUM_KEYS_IN_CSR = 3;
Seth Moorefc86bf42021-12-09 14:07:04 -080056
Tommy Chiufde3ad12023-03-17 05:58:28 +000057constexpr uint8_t MIN_CHALLENGE_SIZE = 0;
58constexpr uint8_t MAX_CHALLENGE_SIZE = 64;
Alice Wangf112ec92024-10-08 07:30:28 +000059
Andrew Scull21461522024-03-25 15:08:08 +000060const string KEYMINT_STRONGBOX_INSTANCE_NAME =
61 "android.hardware.security.keymint.IKeyMintDevice/strongbox";
Tommy Chiufde3ad12023-03-17 05:58:28 +000062
Shawn Willden274bb552020-09-30 22:39:22 -060063#define INSTANTIATE_REM_PROV_AIDL_TEST(name) \
Seth Moore6305e232021-07-27 14:20:17 -070064 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(name); \
Shawn Willden274bb552020-09-30 22:39:22 -060065 INSTANTIATE_TEST_SUITE_P( \
66 PerInstance, name, \
67 testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
68 ::android::PrintInstanceNameToString)
69
Seth Moorefc86bf42021-12-09 14:07:04 -080070using ::android::sp;
Shawn Willden274bb552020-09-30 22:39:22 -060071using bytevec = std::vector<uint8_t>;
72using testing::MatchesRegex;
73using namespace remote_prov;
74using namespace keymaster;
75
76bytevec string_to_bytevec(const char* s) {
77 const uint8_t* p = reinterpret_cast<const uint8_t*>(s);
78 return bytevec(p, p + strlen(s));
79}
80
David Drysdalee99ed862021-03-15 16:43:06 +000081ErrMsgOr<MacedPublicKey> corrupt_maced_key(const MacedPublicKey& macedPubKey) {
82 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
83 if (!coseMac0 || coseMac0->asArray()->size() != kCoseMac0EntryCount) {
84 return "COSE Mac0 parse failed";
85 }
86 auto protParams = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
87 auto unprotParams = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
88 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
89 auto tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
90 if (!protParams || !unprotParams || !payload || !tag) {
91 return "Invalid COSE_Sign1: missing content";
92 }
93 auto corruptMac0 = cppbor::Array();
94 corruptMac0.add(protParams->clone());
95 corruptMac0.add(unprotParams->clone());
96 corruptMac0.add(payload->clone());
97 vector<uint8_t> tagData = tag->value();
98 tagData[0] ^= 0x08;
99 tagData[tagData.size() - 1] ^= 0x80;
100 corruptMac0.add(cppbor::Bstr(tagData));
101
102 return MacedPublicKey{corruptMac0.encode()};
103}
104
David Drysdalecceca9f2021-03-12 15:49:47 +0000105ErrMsgOr<cppbor::Array> corrupt_sig(const cppbor::Array* coseSign1) {
106 if (coseSign1->size() != kCoseSign1EntryCount) {
107 return "Invalid COSE_Sign1, wrong entry count";
108 }
109 const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
110 const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
111 const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
112 const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
113 if (!protectedParams || !unprotectedParams || !payload || !signature) {
114 return "Invalid COSE_Sign1: missing content";
115 }
116
117 auto corruptSig = cppbor::Array();
118 corruptSig.add(protectedParams->clone());
119 corruptSig.add(unprotectedParams->clone());
120 corruptSig.add(payload->clone());
121 vector<uint8_t> sigData = signature->value();
122 sigData[0] ^= 0x08;
123 corruptSig.add(cppbor::Bstr(sigData));
124
125 return std::move(corruptSig);
126}
127
Seth Moore19acbe92021-06-23 15:15:52 -0700128ErrMsgOr<bytevec> corrupt_sig_chain(const bytevec& encodedEekChain, int which) {
129 auto [chain, _, parseErr] = cppbor::parse(encodedEekChain);
David Drysdalecceca9f2021-03-12 15:49:47 +0000130 if (!chain || !chain->asArray()) {
131 return "EekChain parse failed";
132 }
133
134 cppbor::Array* eekChain = chain->asArray();
135 if (which >= eekChain->size()) {
136 return "selected sig out of range";
137 }
138 auto corruptChain = cppbor::Array();
139
140 for (int ii = 0; ii < eekChain->size(); ++ii) {
141 if (ii == which) {
142 auto sig = corrupt_sig(eekChain->get(which)->asArray());
143 if (!sig) {
144 return "Failed to build corrupted signature" + sig.moveMessage();
145 }
146 corruptChain.add(sig.moveValue());
147 } else {
148 corruptChain.add(eekChain->get(ii)->clone());
149 }
150 }
Seth Moore19acbe92021-06-23 15:15:52 -0700151 return corruptChain.encode();
David Drysdalecceca9f2021-03-12 15:49:47 +0000152}
153
David Drysdale4d3c2982021-03-31 18:21:40 +0100154bool matching_keymint_device(const string& rp_name, std::shared_ptr<IKeyMintDevice>* keyMint) {
Sean Thomasafbab602024-11-07 23:14:05 +0000155 auto rp_suffix = deviceSuffix(rp_name);
David Drysdale4d3c2982021-03-31 18:21:40 +0100156
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.
Sean Thomasafbab602024-11-07 23:14:05 +0000161 if (deviceSuffix(km_name) == rp_suffix && AServiceManager_isDeclared(km_name.c_str())) {
David Drysdale4d3c2982021-03-31 18:21:40 +0100162 ::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);
Alice Wang895f4b32023-11-14 07:38:18 +0000180 auto status = provisionable_->getHardwareInfo(&rpcHardwareInfo);
Alice Wangf112ec92024-10-08 07:30:28 +0000181 isRkpVmInstance_ = GetParam() == RKPVM_INSTANCE_NAME;
Karuna Wadheraca6d8cc2024-07-18 14:08:36 +0000182 if (isRkpVmInstance_) {
Alice Wang46ff2862024-05-14 07:07:05 +0000183 if (status.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
184 GTEST_SKIP() << "The RKP VM is not supported on this system.";
185 }
186 int apiLevel = get_vsr_api_level();
187 if (apiLevel < __ANDROID_API_V__) {
188 GTEST_SKIP() << "The RKP VM is supported only on V+ devices. Vendor API level: "
189 << apiLevel;
190 }
Alice Wang895f4b32023-11-14 07:38:18 +0000191 }
192 ASSERT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600193 }
194
195 static vector<string> build_params() {
196 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
197 return params;
198 }
199
200 protected:
201 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000202 RpcHardwareInfo rpcHardwareInfo;
Karuna Wadheraca6d8cc2024-07-18 14:08:36 +0000203 bool isRkpVmInstance_;
Shawn Willden274bb552020-09-30 22:39:22 -0600204};
205
Seth Moorefc86bf42021-12-09 14:07:04 -0800206/**
207 * Verify that every implementation reports a different unique id.
208 */
209TEST(NonParameterizedTests, eachRpcHasAUniqueId) {
210 std::set<std::string> uniqueIds;
211 for (auto hal : ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor)) {
212 ASSERT_TRUE(AServiceManager_isDeclared(hal.c_str()));
213 ::ndk::SpAIBinder binder(AServiceManager_waitForService(hal.c_str()));
214 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
215 IRemotelyProvisionedComponent::fromBinder(binder);
216 ASSERT_NE(rpc, nullptr);
217
218 RpcHardwareInfo hwInfo;
Alice Wang895f4b32023-11-14 07:38:18 +0000219 auto status = rpc->getHardwareInfo(&hwInfo);
Alice Wangf112ec92024-10-08 07:30:28 +0000220 if (hal == RKPVM_INSTANCE_NAME && status.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
Alice Wang895f4b32023-11-14 07:38:18 +0000221 GTEST_SKIP() << "The RKP VM is not supported on this system.";
222 }
223 ASSERT_TRUE(status.isOk());
Seth Moorefc86bf42021-12-09 14:07:04 -0800224
Tri Vodd12c482022-10-12 22:41:28 +0000225 if (hwInfo.versionNumber >= VERSION_WITH_UNIQUE_ID_SUPPORT) {
Seth Moorefc86bf42021-12-09 14:07:04 -0800226 ASSERT_TRUE(hwInfo.uniqueId);
227 auto [_, wasInserted] = uniqueIds.insert(*hwInfo.uniqueId);
228 EXPECT_TRUE(wasInserted);
229 } else {
230 ASSERT_FALSE(hwInfo.uniqueId);
231 }
232 }
233}
234
Andrew Scull21461522024-03-25 15:08:08 +0000235/**
236 * Verify that the default implementation supports DICE if there is a StrongBox KeyMint instance
237 * on the device.
238 */
239// @VsrTest = 3.10-015
240TEST(NonParameterizedTests, requireDiceOnDefaultInstanceIfStrongboxPresent) {
241 int vsr_api_level = get_vsr_api_level();
242 if (vsr_api_level < 35) {
243 GTEST_SKIP() << "Applies only to VSR API level 35 or newer, this device is: "
244 << vsr_api_level;
245 }
246
247 if (!AServiceManager_isDeclared(KEYMINT_STRONGBOX_INSTANCE_NAME.c_str())) {
248 GTEST_SKIP() << "Strongbox is not present on this device.";
249 }
250
251 ::ndk::SpAIBinder binder(AServiceManager_waitForService(DEFAULT_INSTANCE_NAME.c_str()));
252 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
253 IRemotelyProvisionedComponent::fromBinder(binder);
254 ASSERT_NE(rpc, nullptr);
255
256 bytevec challenge = randomBytes(64);
257 bytevec csr;
258 auto status = rpc->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
259 EXPECT_TRUE(status.isOk()) << status.getDescription();
260
Alice Wangf112ec92024-10-08 07:30:28 +0000261 auto result = isCsrWithProperDiceChain(csr, DEFAULT_INSTANCE_NAME);
Andrew Scull21461522024-03-25 15:08:08 +0000262 ASSERT_TRUE(result) << result.message();
263 ASSERT_TRUE(*result);
264}
265
Seth Moorefc86bf42021-12-09 14:07:04 -0800266using GetHardwareInfoTests = VtsRemotelyProvisionedComponentTests;
267
268INSTANTIATE_REM_PROV_AIDL_TEST(GetHardwareInfoTests);
269
270/**
271 * Verify that a valid curve is reported by the implementation.
272 */
273TEST_P(GetHardwareInfoTests, supportsValidCurve) {
274 RpcHardwareInfo hwInfo;
275 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
276
Andrew Scullf2ae1932023-04-24 19:09:09 +0000277 if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_EEK) {
278 ASSERT_EQ(hwInfo.supportedEekCurve, RpcHardwareInfo::CURVE_NONE)
279 << "Invalid curve: " << hwInfo.supportedEekCurve;
280 return;
Hasini Gunasinghe666b2712023-01-05 21:35:51 +0000281 }
Andrew Scullf2ae1932023-04-24 19:09:09 +0000282
283 const std::set<int> validCurves = {RpcHardwareInfo::CURVE_P256, RpcHardwareInfo::CURVE_25519};
Seth Moorefc86bf42021-12-09 14:07:04 -0800284 ASSERT_EQ(validCurves.count(hwInfo.supportedEekCurve), 1)
285 << "Invalid curve: " << hwInfo.supportedEekCurve;
286}
287
288/**
289 * Verify that the unique id is within the length limits as described in RpcHardwareInfo.aidl.
290 */
291TEST_P(GetHardwareInfoTests, uniqueId) {
Tri Vodd12c482022-10-12 22:41:28 +0000292 if (rpcHardwareInfo.versionNumber < VERSION_WITH_UNIQUE_ID_SUPPORT) {
Seth Moorefc86bf42021-12-09 14:07:04 -0800293 return;
294 }
295
296 RpcHardwareInfo hwInfo;
297 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
298 ASSERT_TRUE(hwInfo.uniqueId);
299 EXPECT_GE(hwInfo.uniqueId->size(), 1);
300 EXPECT_LE(hwInfo.uniqueId->size(), 32);
301}
302
Tri Vo9cab73c2022-10-28 13:40:24 -0700303/**
304 * Verify implementation supports at least MIN_SUPPORTED_NUM_KEYS_IN_CSR keys in a CSR.
305 */
306TEST_P(GetHardwareInfoTests, supportedNumKeysInCsr) {
Andrew Scullf2ae1932023-04-24 19:09:09 +0000307 if (rpcHardwareInfo.versionNumber < VERSION_WITH_SUPPORTED_NUM_KEYS_IN_CSR) {
Tri Vo9cab73c2022-10-28 13:40:24 -0700308 return;
309 }
310
311 RpcHardwareInfo hwInfo;
312 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
313 ASSERT_GE(hwInfo.supportedNumKeysInCsr, RpcHardwareInfo::MIN_SUPPORTED_NUM_KEYS_IN_CSR);
314}
315
Shawn Willden274bb552020-09-30 22:39:22 -0600316using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
317
318INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
319
320/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000321 * Generate and validate a production-mode key. MAC tag can't be verified, but
322 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600323 */
Max Bires126869a2021-02-21 18:32:59 -0800324TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600325 MacedPublicKey macedPubKey;
326 bytevec privateKeyBlob;
327 bool testMode = false;
328 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
329 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000330 vector<uint8_t> coseKeyData;
Tri Vob0b8acc2022-11-30 16:22:23 -0800331 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100332}
333
334/**
335 * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
336 */
337TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
338 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
339 std::shared_ptr<IKeyMintDevice> keyMint;
340 if (!matching_keymint_device(GetParam(), &keyMint)) {
341 // No matching IKeyMintDevice.
342 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
343 return;
344 }
345 KeyMintHardwareInfo info;
346 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
347
348 MacedPublicKey macedPubKey;
349 bytevec privateKeyBlob;
350 bool testMode = false;
351 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
352 ASSERT_TRUE(status.isOk());
353 vector<uint8_t> coseKeyData;
Tri Vob0b8acc2022-11-30 16:22:23 -0800354 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100355
David Drysdalef0d516d2021-03-22 07:51:43 +0000356 AttestationKey attestKey;
357 attestKey.keyBlob = std::move(privateKeyBlob);
358 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600359
David Drysdalef0d516d2021-03-22 07:51:43 +0000360 // Generate an ECDSA key that is attested by the generated P256 keypair.
361 AuthorizationSet keyDesc = AuthorizationSetBuilder()
362 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale915ce252021-10-14 15:17:36 +0100363 .EcdsaSigningKey(EcCurve::P_256)
David Drysdalef0d516d2021-03-22 07:51:43 +0000364 .AttestationChallenge("foo")
365 .AttestationApplicationId("bar")
366 .Digest(Digest::NONE)
367 .SetDefaultValidity();
368 KeyCreationResult creationResult;
369 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
370 ASSERT_TRUE(result.isOk());
371 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
372 vector<KeyCharacteristics> attested_key_characteristics =
373 std::move(creationResult.keyCharacteristics);
374 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
375 EXPECT_EQ(attested_key_cert_chain.size(), 1);
376
David Drysdale7dff4fc2021-12-10 10:10:52 +0000377 int32_t aidl_version = 0;
378 ASSERT_TRUE(keyMint->getInterfaceVersion(&aidl_version).isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000379 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
380 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +0000381 EXPECT_TRUE(verify_attestation_record(aidl_version, "foo", "bar", sw_enforced, hw_enforced,
David Drysdalef0d516d2021-03-22 07:51:43 +0000382 info.securityLevel,
383 attested_key_cert_chain[0].encodedCertificate));
384
385 // Attestation by itself is not valid (last entry is not self-signed).
386 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
387
388 // The signature over the attested key should correspond to the P256 public key.
389 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
390 ASSERT_TRUE(key_cert.get());
391 EVP_PKEY_Ptr signing_pubkey;
392 p256_pub_key(coseKeyData, &signing_pubkey);
393 ASSERT_TRUE(signing_pubkey.get());
394
395 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
396 << "Verification of attested certificate failed "
397 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600398}
399
400/**
401 * Generate and validate a test-mode key.
402 */
Max Bires126869a2021-02-21 18:32:59 -0800403TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600404 MacedPublicKey macedPubKey;
405 bytevec privateKeyBlob;
406 bool testMode = true;
407 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
Andrew Scullf2ae1932023-04-24 19:09:09 +0000408
409 if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_TEST_MODE) {
410 ASSERT_FALSE(status.isOk());
411 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
412 return;
413 }
414
Shawn Willden274bb552020-09-30 22:39:22 -0600415 ASSERT_TRUE(status.isOk());
Tri Vob0b8acc2022-11-30 16:22:23 -0800416 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600417}
418
Sean Thomasf2946ab2024-11-27 18:09:46 +0000419/**
420 * Generate and validate at most 2**16 production-mode keys. This aims to catch issues that do not
421 * deterministically show up. In practice, this will test far fewer keys, but a certain number are
422 * tested at a minimum.
423 */
424TEST_P(GenerateKeyTests, generateManyEcdsaP256KeysInProdMode) {
425 const auto start = std::chrono::steady_clock::now();
426 const auto time_bound = std::chrono::seconds(5);
427 const auto upper_bound = 1 << 16;
428 const auto lower_bound = 1 << 8;
429 for (auto iteration = 0; iteration < upper_bound; iteration++) {
430 MacedPublicKey macedPubKey;
431 bytevec privateKeyBlob;
432 bool testMode = false;
433 auto status =
434 provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
435 ASSERT_TRUE(status.isOk());
436 vector<uint8_t> coseKeyData;
437 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
438 const auto current_time = std::chrono::steady_clock::now() - start;
439 if (iteration >= lower_bound && current_time >= time_bound) {
440 break;
441 }
442 }
443}
444
Tri Vo0d6204e2022-09-29 16:15:34 -0700445class CertificateRequestTestBase : public VtsRemotelyProvisionedComponentTests {
Shawn Willden274bb552020-09-30 22:39:22 -0600446 protected:
Tri Vo0d6204e2022-09-29 16:15:34 -0700447 CertificateRequestTestBase()
448 : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(64)) {}
David Drysdalecceca9f2021-03-12 15:49:47 +0000449
Seth Moore19acbe92021-06-23 15:15:52 -0700450 void generateTestEekChain(size_t eekLength) {
subrahmanyamanfb213d62022-02-02 23:10:55 +0000451 auto chain = generateEekChain(rpcHardwareInfo.supportedEekCurve, eekLength, eekId_);
David Drysdale08696a72022-03-10 10:43:25 +0000452 ASSERT_TRUE(chain) << chain.message();
Seth Moore19acbe92021-06-23 15:15:52 -0700453 if (chain) testEekChain_ = chain.moveValue();
454 testEekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600455 }
456
457 void generateKeys(bool testMode, size_t numKeys) {
458 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
459 cborKeysToSign_ = cppbor::Array();
460
461 for (auto& key : keysToSign_) {
462 bytevec privateKeyBlob;
463 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
Frederick Mayle9891be02023-11-03 14:39:24 -0700464 ASSERT_TRUE(status.isOk()) << status.getDescription();
Shawn Willden274bb552020-09-30 22:39:22 -0600465
David Drysdalec8400772021-03-11 12:35:11 +0000466 vector<uint8_t> payload_value;
Tri Vob0b8acc2022-11-30 16:22:23 -0800467 check_maced_pubkey(key, testMode, &payload_value);
David Drysdalec8400772021-03-11 12:35:11 +0000468 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600469 }
470 }
471
472 bytevec eekId_;
Seth Moore19acbe92021-06-23 15:15:52 -0700473 size_t testEekLength_;
474 EekChain testEekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000475 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600476 std::vector<MacedPublicKey> keysToSign_;
477 cppbor::Array cborKeysToSign_;
478};
479
Tri Vo0d6204e2022-09-29 16:15:34 -0700480class CertificateRequestTest : public CertificateRequestTestBase {
481 protected:
482 void SetUp() override {
483 CertificateRequestTestBase::SetUp();
Andrew Scull1bcb6022022-12-27 10:43:27 +0000484 ASSERT_FALSE(HasFatalFailure());
Tri Vo0d6204e2022-09-29 16:15:34 -0700485
Andrew Scullf2ae1932023-04-24 19:09:09 +0000486 if (rpcHardwareInfo.versionNumber >= VERSION_WITH_CERTIFICATE_REQUEST_V2) {
Andrew Scull95b31312023-03-27 19:16:07 +0000487 GTEST_SKIP() << "This test case only applies to RKP v1 and v2. "
488 << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
Tri Vo0d6204e2022-09-29 16:15:34 -0700489 }
490 }
491};
492
Shawn Willden274bb552020-09-30 22:39:22 -0600493/**
494 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
495 * content.
496 */
Max Bires126869a2021-02-21 18:32:59 -0800497TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600498 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000499 for (size_t eekLength : {2, 3, 7}) {
500 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700501 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600502
David Drysdalecceca9f2021-03-12 15:49:47 +0000503 bytevec keysToSignMac;
504 DeviceInfo deviceInfo;
505 ProtectedData protectedData;
506 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700507 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalecceca9f2021-03-12 15:49:47 +0000508 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700509 ASSERT_TRUE(status.isOk()) << status.getDescription();
David Drysdalecceca9f2021-03-12 15:49:47 +0000510
Sean Thomas2d2385b2024-11-07 23:56:03 +0000511 auto result = verifyProductionProtectedData(deviceInfo, cppbor::Array(), keysToSignMac,
512 protectedData, testEekChain_, eekId_,
513 rpcHardwareInfo, GetParam(), challenge_);
Seth Moore2fc6f832022-09-13 16:10:11 -0700514 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000515 }
Shawn Willden274bb552020-09-30 22:39:22 -0600516}
517
518/**
Seth Moore42c11332021-07-02 15:38:17 -0700519 * Ensure that test mode outputs a unique BCC root key every time we request a
520 * certificate request. Else, it's possible that the test mode API could be used
521 * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
522 * device public key multiple times.
523 */
524TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
525 constexpr bool testMode = true;
Seth Moore42c11332021-07-02 15:38:17 -0700526
527 bytevec keysToSignMac;
528 DeviceInfo deviceInfo;
529 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000530 generateTestEekChain(3);
Seth Moore42c11332021-07-02 15:38:17 -0700531 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700532 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
533 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700534 ASSERT_TRUE(status.isOk()) << status.getDescription();
Seth Moore42c11332021-07-02 15:38:17 -0700535
Alice Wangf112ec92024-10-08 07:30:28 +0000536 auto firstBcc = verifyProductionProtectedData(deviceInfo, /*keysToSign=*/cppbor::Array(),
537 keysToSignMac, protectedData, testEekChain_,
Sean Thomas2d2385b2024-11-07 23:56:03 +0000538 eekId_, rpcHardwareInfo, GetParam(), challenge_);
Seth Moore2fc6f832022-09-13 16:10:11 -0700539 ASSERT_TRUE(firstBcc) << firstBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700540
Seth Moore19acbe92021-06-23 15:15:52 -0700541 status = provisionable_->generateCertificateRequest(
542 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
543 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700544 ASSERT_TRUE(status.isOk()) << status.getDescription();
Seth Moore42c11332021-07-02 15:38:17 -0700545
Alice Wangf112ec92024-10-08 07:30:28 +0000546 auto secondBcc = verifyProductionProtectedData(deviceInfo, /*keysToSign=*/cppbor::Array(),
547 keysToSignMac, protectedData, testEekChain_,
Sean Thomas2d2385b2024-11-07 23:56:03 +0000548 eekId_, rpcHardwareInfo, GetParam(), challenge_);
Seth Moore2fc6f832022-09-13 16:10:11 -0700549 ASSERT_TRUE(secondBcc) << secondBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700550
551 // Verify that none of the keys in the first BCC are repeated in the second one.
Seth Moore2fc6f832022-09-13 16:10:11 -0700552 for (const auto& i : *firstBcc) {
553 for (auto& j : *secondBcc) {
Seth Moore42c11332021-07-02 15:38:17 -0700554 ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
555 << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
556 }
557 }
558}
559
560/**
Seth Moore19acbe92021-06-23 15:15:52 -0700561 * Generate an empty certificate request in prod mode. This test must be run explicitly, and
562 * is not run by default. Not all devices are GMS devices, and therefore they do not all
563 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600564 */
Seth Moore19acbe92021-06-23 15:15:52 -0700565TEST_P(CertificateRequestTest, DISABLED_EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600566 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000567
Seth Moore19acbe92021-06-23 15:15:52 -0700568 bytevec keysToSignMac;
569 DeviceInfo deviceInfo;
570 ProtectedData protectedData;
571 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000572 testMode, {} /* keysToSign */, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
573 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700574 EXPECT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600575}
576
577/**
578 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
579 */
Max Bires126869a2021-02-21 18:32:59 -0800580TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600581 bool testMode = true;
582 generateKeys(testMode, 4 /* numKeys */);
583
David Drysdalecceca9f2021-03-12 15:49:47 +0000584 for (size_t eekLength : {2, 3, 7}) {
585 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700586 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600587
David Drysdalecceca9f2021-03-12 15:49:47 +0000588 bytevec keysToSignMac;
589 DeviceInfo deviceInfo;
590 ProtectedData protectedData;
591 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700592 testMode, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo, &protectedData,
David Drysdalecceca9f2021-03-12 15:49:47 +0000593 &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700594 ASSERT_TRUE(status.isOk()) << status.getDescription();
David Drysdalecceca9f2021-03-12 15:49:47 +0000595
Sean Thomas2d2385b2024-11-07 23:56:03 +0000596 auto result = verifyProductionProtectedData(deviceInfo, cborKeysToSign_, keysToSignMac,
597 protectedData, testEekChain_, eekId_,
598 rpcHardwareInfo, GetParam(), challenge_);
Seth Moore2fc6f832022-09-13 16:10:11 -0700599 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000600 }
Shawn Willden274bb552020-09-30 22:39:22 -0600601}
602
603/**
Seth Moore19acbe92021-06-23 15:15:52 -0700604 * Generate a non-empty certificate request in prod mode. This test must be run explicitly, and
605 * is not run by default. Not all devices are GMS devices, and therefore they do not all
606 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600607 */
Seth Moore19acbe92021-06-23 15:15:52 -0700608TEST_P(CertificateRequestTest, DISABLED_NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600609 bool testMode = false;
610 generateKeys(testMode, 4 /* numKeys */);
611
Seth Moore19acbe92021-06-23 15:15:52 -0700612 bytevec keysToSignMac;
613 DeviceInfo deviceInfo;
614 ProtectedData protectedData;
615 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000616 testMode, keysToSign_, getProdEekChain(rpcHardwareInfo.supportedEekCurve), challenge_,
617 &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700618 EXPECT_TRUE(status.isOk());
David Drysdalecceca9f2021-03-12 15:49:47 +0000619}
620
621/**
David Drysdalee99ed862021-03-15 16:43:06 +0000622 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
623 */
624TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
625 bool testMode = true;
626 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000627 auto result = corrupt_maced_key(keysToSign_[0]);
628 ASSERT_TRUE(result) << result.moveMessage();
629 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000630
631 bytevec keysToSignMac;
632 DeviceInfo deviceInfo;
633 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000634 generateTestEekChain(3);
David Drysdalee99ed862021-03-15 16:43:06 +0000635 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700636 testMode, {keyWithCorruptMac}, testEekChain_.chain, challenge_, &deviceInfo,
637 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700638 ASSERT_FALSE(status.isOk()) << status.getDescription();
David Drysdalee99ed862021-03-15 16:43:06 +0000639 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
640}
641
642/**
643 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
644 */
645TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
Seth Moore19acbe92021-06-23 15:15:52 -0700646 bool testMode = false;
David Drysdalee99ed862021-03-15 16:43:06 +0000647 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000648 auto result = corrupt_maced_key(keysToSign_[0]);
649 ASSERT_TRUE(result) << result.moveMessage();
650 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000651
652 bytevec keysToSignMac;
653 DeviceInfo deviceInfo;
654 ProtectedData protectedData;
655 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000656 testMode, {keyWithCorruptMac}, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
657 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700658 ASSERT_FALSE(status.isOk()) << status.getDescription();
Seth Moore19acbe92021-06-23 15:15:52 -0700659 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
David Drysdalee99ed862021-03-15 16:43:06 +0000660}
661
662/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000663 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
664 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000665 */
666TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
667 bool testMode = false;
668 generateKeys(testMode, 4 /* numKeys */);
669
subrahmanyamanfb213d62022-02-02 23:10:55 +0000670 auto prodEekChain = getProdEekChain(rpcHardwareInfo.supportedEekCurve);
Seth Moore19acbe92021-06-23 15:15:52 -0700671 auto [parsedChain, _, parseErr] = cppbor::parse(prodEekChain);
672 ASSERT_NE(parsedChain, nullptr) << parseErr;
673 ASSERT_NE(parsedChain->asArray(), nullptr);
674
675 for (int ii = 0; ii < parsedChain->asArray()->size(); ++ii) {
676 auto chain = corrupt_sig_chain(prodEekChain, ii);
David Drysdalecceca9f2021-03-12 15:49:47 +0000677 ASSERT_TRUE(chain) << chain.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000678
679 bytevec keysToSignMac;
680 DeviceInfo deviceInfo;
681 ProtectedData protectedData;
Seth Moore19acbe92021-06-23 15:15:52 -0700682 auto status = provisionable_->generateCertificateRequest(testMode, keysToSign_, *chain,
683 challenge_, &deviceInfo,
684 &protectedData, &keysToSignMac);
David Drysdalecceca9f2021-03-12 15:49:47 +0000685 ASSERT_FALSE(status.isOk());
686 ASSERT_EQ(status.getServiceSpecificError(),
687 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
688 }
689}
690
691/**
692 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
693 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000694 */
695TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
696 bool testMode = false;
697 generateKeys(testMode, 4 /* numKeys */);
698
699 // Build an EEK chain that omits the first self-signed cert.
700 auto truncatedChain = cppbor::Array();
subrahmanyamanfb213d62022-02-02 23:10:55 +0000701 auto [chain, _, parseErr] = cppbor::parse(getProdEekChain(rpcHardwareInfo.supportedEekCurve));
David Drysdalecceca9f2021-03-12 15:49:47 +0000702 ASSERT_TRUE(chain);
703 auto eekChain = chain->asArray();
704 ASSERT_NE(eekChain, nullptr);
705 for (size_t ii = 1; ii < eekChain->size(); ii++) {
706 truncatedChain.add(eekChain->get(ii)->clone());
707 }
708
Shawn Willden274bb552020-09-30 22:39:22 -0600709 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700710 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600711 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000712 auto status = provisionable_->generateCertificateRequest(
713 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
714 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600715 ASSERT_FALSE(status.isOk());
716 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
717}
718
719/**
720 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
721 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
722 */
Max Bires126869a2021-02-21 18:32:59 -0800723TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600724 generateKeys(false /* testMode */, 2 /* numKeys */);
725
726 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700727 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600728 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000729 generateTestEekChain(3);
Max Biresfdbb9042021-03-23 12:43:38 -0700730 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700731 true /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700732 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600733 ASSERT_FALSE(status.isOk());
734 ASSERT_EQ(status.getServiceSpecificError(),
735 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
736}
737
738/**
739 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
740 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
741 */
Max Bires126869a2021-02-21 18:32:59 -0800742TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600743 generateKeys(true /* testMode */, 2 /* numKeys */);
744
745 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700746 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600747 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000748 generateTestEekChain(3);
Shawn Willden274bb552020-09-30 22:39:22 -0600749 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700750 false /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalec8400772021-03-11 12:35:11 +0000751 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600752 ASSERT_FALSE(status.isOk());
753 ASSERT_EQ(status.getServiceSpecificError(),
754 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
755}
756
757INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
758
Tri Vo0d6204e2022-09-29 16:15:34 -0700759class CertificateRequestV2Test : public CertificateRequestTestBase {
760 void SetUp() override {
761 CertificateRequestTestBase::SetUp();
Andrew Scull1bcb6022022-12-27 10:43:27 +0000762 ASSERT_FALSE(HasFatalFailure());
Tri Vo0d6204e2022-09-29 16:15:34 -0700763
Andrew Scullf2ae1932023-04-24 19:09:09 +0000764 if (rpcHardwareInfo.versionNumber < VERSION_WITH_CERTIFICATE_REQUEST_V2) {
Tri Vo0d6204e2022-09-29 16:15:34 -0700765 GTEST_SKIP() << "This test case only applies to RKP v3 and above. "
766 << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
767 }
768 }
769};
770
771/**
Tommy Chiufde3ad12023-03-17 05:58:28 +0000772 * Generate an empty certificate request with all possible length of challenge, and decrypt and
773 * verify the structure and content.
Tri Vo0d6204e2022-09-29 16:15:34 -0700774 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700775// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700776TEST_P(CertificateRequestV2Test, EmptyRequest) {
777 bytevec csr;
778
Tommy Chiufde3ad12023-03-17 05:58:28 +0000779 for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
780 SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
781 auto challenge = randomBytes(size);
782 auto status =
783 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700784 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700785
Sean Thomas2d2385b2024-11-07 23:56:03 +0000786 auto result = verifyProductionCsr(cppbor::Array(), csr, rpcHardwareInfo, GetParam(),
Alice Wangf112ec92024-10-08 07:30:28 +0000787 challenge, isRkpVmInstance_);
Tommy Chiufde3ad12023-03-17 05:58:28 +0000788 ASSERT_TRUE(result) << result.message();
789 }
Tri Vo0d6204e2022-09-29 16:15:34 -0700790}
791
792/**
Tommy Chiufde3ad12023-03-17 05:58:28 +0000793 * Generate a non-empty certificate request with all possible length of challenge. Decrypt, parse
794 * and validate the contents.
Tri Vo0d6204e2022-09-29 16:15:34 -0700795 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700796// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700797TEST_P(CertificateRequestV2Test, NonEmptyRequest) {
798 generateKeys(false /* testMode */, 1 /* numKeys */);
799
800 bytevec csr;
801
Tommy Chiufde3ad12023-03-17 05:58:28 +0000802 for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
803 SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
804 auto challenge = randomBytes(size);
805 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700806 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700807
Sean Thomas2d2385b2024-11-07 23:56:03 +0000808 auto result = verifyProductionCsr(cborKeysToSign_, csr, rpcHardwareInfo, GetParam(),
Alice Wangf112ec92024-10-08 07:30:28 +0000809 challenge, isRkpVmInstance_);
Tommy Chiufde3ad12023-03-17 05:58:28 +0000810 ASSERT_TRUE(result) << result.message();
811 }
812}
813
814/**
815 * Generate an empty certificate request with invalid size of challenge
816 */
817TEST_P(CertificateRequestV2Test, EmptyRequestWithInvalidChallengeFail) {
818 bytevec csr;
819
820 auto status = provisionable_->generateCertificateRequestV2(
821 /* keysToSign */ {}, randomBytes(MAX_CHALLENGE_SIZE + 1), &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700822 EXPECT_FALSE(status.isOk()) << status.getDescription();
Tommy Chiufde3ad12023-03-17 05:58:28 +0000823 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_FAILED);
Tri Vo0d6204e2022-09-29 16:15:34 -0700824}
825
826/**
Andrew Scullfb49ad22022-11-09 21:02:48 +0000827 * Generate a non-empty certificate request. Make sure contents are reproducible but allow for the
828 * signature to be different since algorithms including ECDSA P-256 can include a random value.
Tri Vo0d6204e2022-09-29 16:15:34 -0700829 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700830// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700831TEST_P(CertificateRequestV2Test, NonEmptyRequestReproducible) {
832 generateKeys(false /* testMode */, 1 /* numKeys */);
833
834 bytevec csr;
835
836 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700837 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700838
Sean Thomas2d2385b2024-11-07 23:56:03 +0000839 auto firstCsr = verifyProductionCsr(cborKeysToSign_, csr, rpcHardwareInfo, GetParam(),
Alice Wangf112ec92024-10-08 07:30:28 +0000840 challenge_, isRkpVmInstance_);
Andrew Scullfb49ad22022-11-09 21:02:48 +0000841 ASSERT_TRUE(firstCsr) << firstCsr.message();
Tri Vo0d6204e2022-09-29 16:15:34 -0700842
843 status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700844 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700845
Sean Thomas2d2385b2024-11-07 23:56:03 +0000846 auto secondCsr = verifyProductionCsr(cborKeysToSign_, csr, rpcHardwareInfo, GetParam(),
Alice Wangf112ec92024-10-08 07:30:28 +0000847 challenge_, isRkpVmInstance_);
Andrew Scullfb49ad22022-11-09 21:02:48 +0000848 ASSERT_TRUE(secondCsr) << secondCsr.message();
Tri Vo0d6204e2022-09-29 16:15:34 -0700849
Andrew Scullfb49ad22022-11-09 21:02:48 +0000850 ASSERT_EQ(**firstCsr, **secondCsr);
Tri Vo0d6204e2022-09-29 16:15:34 -0700851}
852
853/**
854 * Generate a non-empty certificate request with multiple keys.
855 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700856// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700857TEST_P(CertificateRequestV2Test, NonEmptyRequestMultipleKeys) {
Tri Vo9cab73c2022-10-28 13:40:24 -0700858 generateKeys(false /* testMode */, rpcHardwareInfo.supportedNumKeysInCsr /* numKeys */);
Tri Vo0d6204e2022-09-29 16:15:34 -0700859
860 bytevec csr;
861
862 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700863 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700864
Sean Thomas2d2385b2024-11-07 23:56:03 +0000865 auto result = verifyProductionCsr(cborKeysToSign_, csr, rpcHardwareInfo, GetParam(), challenge_,
866 isRkpVmInstance_);
Tri Vo0d6204e2022-09-29 16:15:34 -0700867 ASSERT_TRUE(result) << result.message();
868}
869
870/**
871 * Generate a non-empty certificate request, but with the MAC corrupted on the keypair.
872 */
873TEST_P(CertificateRequestV2Test, NonEmptyRequestCorruptMac) {
874 generateKeys(false /* testMode */, 1 /* numKeys */);
875 auto result = corrupt_maced_key(keysToSign_[0]);
876 ASSERT_TRUE(result) << result.moveMessage();
877 MacedPublicKey keyWithCorruptMac = result.moveValue();
878
879 bytevec csr;
880 auto status =
881 provisionable_->generateCertificateRequestV2({keyWithCorruptMac}, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700882 ASSERT_FALSE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700883 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
884}
885
886/**
Andrew Scullf2ae1932023-04-24 19:09:09 +0000887 * Call generateCertificateRequest(). Make sure it's removed.
Tri Vo0d6204e2022-09-29 16:15:34 -0700888 */
Andrew Scullf2ae1932023-04-24 19:09:09 +0000889TEST_P(CertificateRequestV2Test, CertificateRequestV1Removed_prodMode) {
890 bytevec keysToSignMac;
891 DeviceInfo deviceInfo;
892 ProtectedData protectedData;
893 auto status = provisionable_->generateCertificateRequest(
894 false /* testMode */, {} /* keysToSign */, {} /* EEK chain */, challenge_, &deviceInfo,
895 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700896 ASSERT_FALSE(status.isOk()) << status.getDescription();
Andrew Scullf2ae1932023-04-24 19:09:09 +0000897 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
Tri Vo0d6204e2022-09-29 16:15:34 -0700898}
899
Andrew Scull95b31312023-03-27 19:16:07 +0000900/**
Andrew Scullf2ae1932023-04-24 19:09:09 +0000901 * Call generateCertificateRequest() in test mode. Make sure it's removed.
Andrew Scull95b31312023-03-27 19:16:07 +0000902 */
Andrew Scullf2ae1932023-04-24 19:09:09 +0000903TEST_P(CertificateRequestV2Test, CertificateRequestV1Removed_testMode) {
Andrew Scull95b31312023-03-27 19:16:07 +0000904 bytevec keysToSignMac;
905 DeviceInfo deviceInfo;
906 ProtectedData protectedData;
907 auto status = provisionable_->generateCertificateRequest(
908 true /* testMode */, {} /* keysToSign */, {} /* EEK chain */, challenge_, &deviceInfo,
909 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700910 ASSERT_FALSE(status.isOk()) << status.getDescription();
Andrew Scull95b31312023-03-27 19:16:07 +0000911 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
912}
913
Tri Voec50ee12023-02-14 16:29:53 -0800914void parse_root_of_trust(const vector<uint8_t>& attestation_cert,
915 vector<uint8_t>* verified_boot_key, VerifiedBoot* verified_boot_state,
916 bool* device_locked, vector<uint8_t>* verified_boot_hash) {
917 X509_Ptr cert(parse_cert_blob(attestation_cert));
918 ASSERT_TRUE(cert.get());
919
920 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
921 ASSERT_TRUE(attest_rec);
922
923 auto error = parse_root_of_trust(attest_rec->data, attest_rec->length, verified_boot_key,
924 verified_boot_state, device_locked, verified_boot_hash);
925 ASSERT_EQ(error, ErrorCode::OK);
926}
927
928/**
929 * Generate a CSR and verify DeviceInfo against IDs attested by KeyMint.
930 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700931// @VsrTest = 3.10-015
Tri Voec50ee12023-02-14 16:29:53 -0800932TEST_P(CertificateRequestV2Test, DeviceInfo) {
933 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
934 std::shared_ptr<IKeyMintDevice> keyMint;
935 if (!matching_keymint_device(GetParam(), &keyMint)) {
936 // No matching IKeyMintDevice.
937 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
938 return;
939 }
940 KeyMintHardwareInfo info;
941 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
942
943 // Get IDs attested by KeyMint.
944 MacedPublicKey macedPubKey;
945 bytevec privateKeyBlob;
946 auto irpcStatus =
947 provisionable_->generateEcdsaP256KeyPair(false, &macedPubKey, &privateKeyBlob);
948 ASSERT_TRUE(irpcStatus.isOk());
949
950 AttestationKey attestKey;
951 attestKey.keyBlob = std::move(privateKeyBlob);
952 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
953
954 // Generate an ECDSA key that is attested by the generated P256 keypair.
955 AuthorizationSet keyDesc = AuthorizationSetBuilder()
956 .Authorization(TAG_NO_AUTH_REQUIRED)
957 .EcdsaSigningKey(EcCurve::P_256)
958 .AttestationChallenge("foo")
959 .AttestationApplicationId("bar")
960 .Digest(Digest::NONE)
961 .SetDefaultValidity();
962 KeyCreationResult creationResult;
963 auto kmStatus = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
964 ASSERT_TRUE(kmStatus.isOk());
965
966 vector<KeyCharacteristics> key_characteristics = std::move(creationResult.keyCharacteristics);
967 vector<Certificate> key_cert_chain = std::move(creationResult.certificateChain);
968 // We didn't provision the attestation key.
969 ASSERT_EQ(key_cert_chain.size(), 1);
970
971 // Parse attested patch levels.
972 auto auths = HwEnforcedAuthorizations(key_characteristics);
973
974 auto attestedSystemPatchLevel = auths.GetTagValue(TAG_OS_PATCHLEVEL);
975 auto attestedVendorPatchLevel = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
976 auto attestedBootPatchLevel = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
977
978 ASSERT_TRUE(attestedSystemPatchLevel.has_value());
979 ASSERT_TRUE(attestedVendorPatchLevel.has_value());
980 ASSERT_TRUE(attestedBootPatchLevel.has_value());
981
982 // Parse attested AVB values.
983 vector<uint8_t> key;
984 VerifiedBoot attestedVbState;
985 bool attestedBootloaderState;
986 vector<uint8_t> attestedVbmetaDigest;
987 parse_root_of_trust(key_cert_chain[0].encodedCertificate, &key, &attestedVbState,
988 &attestedBootloaderState, &attestedVbmetaDigest);
989
990 // Get IDs from DeviceInfo.
991 bytevec csr;
992 irpcStatus =
993 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700994 ASSERT_TRUE(irpcStatus.isOk()) << irpcStatus.getDescription();
Tri Voec50ee12023-02-14 16:29:53 -0800995
Alice Wangf112ec92024-10-08 07:30:28 +0000996 auto result =
Sean Thomas2d2385b2024-11-07 23:56:03 +0000997 verifyProductionCsr(cppbor::Array(), csr, rpcHardwareInfo, GetParam(), challenge_);
Tri Voec50ee12023-02-14 16:29:53 -0800998 ASSERT_TRUE(result) << result.message();
999
1000 std::unique_ptr<cppbor::Array> csrPayload = std::move(*result);
1001 ASSERT_TRUE(csrPayload);
1002
1003 auto deviceInfo = csrPayload->get(2)->asMap();
1004 ASSERT_TRUE(deviceInfo);
1005
1006 auto vbState = deviceInfo->get("vb_state")->asTstr();
1007 auto bootloaderState = deviceInfo->get("bootloader_state")->asTstr();
1008 auto vbmetaDigest = deviceInfo->get("vbmeta_digest")->asBstr();
1009 auto systemPatchLevel = deviceInfo->get("system_patch_level")->asUint();
1010 auto vendorPatchLevel = deviceInfo->get("vendor_patch_level")->asUint();
1011 auto bootPatchLevel = deviceInfo->get("boot_patch_level")->asUint();
1012 auto securityLevel = deviceInfo->get("security_level")->asTstr();
1013
1014 ASSERT_TRUE(vbState);
1015 ASSERT_TRUE(bootloaderState);
1016 ASSERT_TRUE(vbmetaDigest);
1017 ASSERT_TRUE(systemPatchLevel);
1018 ASSERT_TRUE(vendorPatchLevel);
1019 ASSERT_TRUE(bootPatchLevel);
1020 ASSERT_TRUE(securityLevel);
1021
Sean Thomasafbab602024-11-07 23:14:05 +00001022 auto kmDeviceName = deviceSuffix(GetParam());
Tri Voec50ee12023-02-14 16:29:53 -08001023
1024 // Compare DeviceInfo against IDs attested by KeyMint.
1025 ASSERT_TRUE((securityLevel->value() == "tee" && kmDeviceName == "default") ||
1026 (securityLevel->value() == "strongbox" && kmDeviceName == "strongbox"));
1027 ASSERT_TRUE((vbState->value() == "green" && attestedVbState == VerifiedBoot::VERIFIED) ||
1028 (vbState->value() == "yellow" && attestedVbState == VerifiedBoot::SELF_SIGNED) ||
1029 (vbState->value() == "orange" && attestedVbState == VerifiedBoot::UNVERIFIED));
1030 ASSERT_TRUE((bootloaderState->value() == "locked" && attestedBootloaderState) ||
1031 (bootloaderState->value() == "unlocked" && !attestedBootloaderState));
1032 ASSERT_EQ(vbmetaDigest->value(), attestedVbmetaDigest);
1033 ASSERT_EQ(systemPatchLevel->value(), attestedSystemPatchLevel.value());
1034 ASSERT_EQ(vendorPatchLevel->value(), attestedVendorPatchLevel.value());
1035 ASSERT_EQ(bootPatchLevel->value(), attestedBootPatchLevel.value());
1036}
1037
Tri Vo0d6204e2022-09-29 16:15:34 -07001038INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestV2Test);
1039
Max Biresa9b3bb92022-11-21 23:02:09 -08001040using VsrRequirementTest = VtsRemotelyProvisionedComponentTests;
1041
1042INSTANTIATE_REM_PROV_AIDL_TEST(VsrRequirementTest);
1043
1044TEST_P(VsrRequirementTest, VsrEnforcementTest) {
1045 RpcHardwareInfo hwInfo;
1046 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
1047 int vsr_api_level = get_vsr_api_level();
1048 if (vsr_api_level < 34) {
1049 GTEST_SKIP() << "Applies only to VSR API level 34 or newer, this device is: "
1050 << vsr_api_level;
1051 }
1052 EXPECT_GE(hwInfo.versionNumber, 3)
1053 << "VSR 14+ requires IRemotelyProvisionedComponent v3 or newer.";
1054}
1055
Shawn Willden274bb552020-09-30 22:39:22 -06001056} // namespace aidl::android::hardware::security::keymint::test