blob: 2dbc73f8e395a262a5f3540a4fb3a45302d06421 [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);
Alice Wang46ff2862024-05-14 07:07:05 +0000191 if (GetParam() == RKP_VM_INSTANCE_NAME) {
192 if (status.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
193 GTEST_SKIP() << "The RKP VM is not supported on this system.";
194 }
195 int apiLevel = get_vsr_api_level();
196 if (apiLevel < __ANDROID_API_V__) {
197 GTEST_SKIP() << "The RKP VM is supported only on V+ devices. Vendor API level: "
198 << apiLevel;
199 }
Alice Wang895f4b32023-11-14 07:38:18 +0000200 }
201 ASSERT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600202 }
203
204 static vector<string> build_params() {
205 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
206 return params;
207 }
208
209 protected:
210 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000211 RpcHardwareInfo rpcHardwareInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600212};
213
Seth Moorefc86bf42021-12-09 14:07:04 -0800214/**
215 * Verify that every implementation reports a different unique id.
216 */
217TEST(NonParameterizedTests, eachRpcHasAUniqueId) {
218 std::set<std::string> uniqueIds;
219 for (auto hal : ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor)) {
220 ASSERT_TRUE(AServiceManager_isDeclared(hal.c_str()));
221 ::ndk::SpAIBinder binder(AServiceManager_waitForService(hal.c_str()));
222 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
223 IRemotelyProvisionedComponent::fromBinder(binder);
224 ASSERT_NE(rpc, nullptr);
225
226 RpcHardwareInfo hwInfo;
Alice Wang895f4b32023-11-14 07:38:18 +0000227 auto status = rpc->getHardwareInfo(&hwInfo);
228 if (hal == RKP_VM_INSTANCE_NAME && status.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
229 GTEST_SKIP() << "The RKP VM is not supported on this system.";
230 }
231 ASSERT_TRUE(status.isOk());
Seth Moorefc86bf42021-12-09 14:07:04 -0800232
Tri Vodd12c482022-10-12 22:41:28 +0000233 if (hwInfo.versionNumber >= VERSION_WITH_UNIQUE_ID_SUPPORT) {
Seth Moorefc86bf42021-12-09 14:07:04 -0800234 ASSERT_TRUE(hwInfo.uniqueId);
235 auto [_, wasInserted] = uniqueIds.insert(*hwInfo.uniqueId);
236 EXPECT_TRUE(wasInserted);
237 } else {
238 ASSERT_FALSE(hwInfo.uniqueId);
239 }
240 }
241}
242
Andrew Scull21461522024-03-25 15:08:08 +0000243/**
244 * Verify that the default implementation supports DICE if there is a StrongBox KeyMint instance
245 * on the device.
246 */
247// @VsrTest = 3.10-015
248TEST(NonParameterizedTests, requireDiceOnDefaultInstanceIfStrongboxPresent) {
249 int vsr_api_level = get_vsr_api_level();
250 if (vsr_api_level < 35) {
251 GTEST_SKIP() << "Applies only to VSR API level 35 or newer, this device is: "
252 << vsr_api_level;
253 }
254
255 if (!AServiceManager_isDeclared(KEYMINT_STRONGBOX_INSTANCE_NAME.c_str())) {
256 GTEST_SKIP() << "Strongbox is not present on this device.";
257 }
258
259 ::ndk::SpAIBinder binder(AServiceManager_waitForService(DEFAULT_INSTANCE_NAME.c_str()));
260 std::shared_ptr<IRemotelyProvisionedComponent> rpc =
261 IRemotelyProvisionedComponent::fromBinder(binder);
262 ASSERT_NE(rpc, nullptr);
263
264 bytevec challenge = randomBytes(64);
265 bytevec csr;
266 auto status = rpc->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
267 EXPECT_TRUE(status.isOk()) << status.getDescription();
268
269 auto result = isCsrWithProperDiceChain(csr);
270 ASSERT_TRUE(result) << result.message();
271 ASSERT_TRUE(*result);
272}
273
Seth Moorefc86bf42021-12-09 14:07:04 -0800274using GetHardwareInfoTests = VtsRemotelyProvisionedComponentTests;
275
276INSTANTIATE_REM_PROV_AIDL_TEST(GetHardwareInfoTests);
277
278/**
279 * Verify that a valid curve is reported by the implementation.
280 */
281TEST_P(GetHardwareInfoTests, supportsValidCurve) {
282 RpcHardwareInfo hwInfo;
283 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
284
Andrew Scullf2ae1932023-04-24 19:09:09 +0000285 if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_EEK) {
286 ASSERT_EQ(hwInfo.supportedEekCurve, RpcHardwareInfo::CURVE_NONE)
287 << "Invalid curve: " << hwInfo.supportedEekCurve;
288 return;
Hasini Gunasinghe666b2712023-01-05 21:35:51 +0000289 }
Andrew Scullf2ae1932023-04-24 19:09:09 +0000290
291 const std::set<int> validCurves = {RpcHardwareInfo::CURVE_P256, RpcHardwareInfo::CURVE_25519};
Seth Moorefc86bf42021-12-09 14:07:04 -0800292 ASSERT_EQ(validCurves.count(hwInfo.supportedEekCurve), 1)
293 << "Invalid curve: " << hwInfo.supportedEekCurve;
294}
295
296/**
297 * Verify that the unique id is within the length limits as described in RpcHardwareInfo.aidl.
298 */
299TEST_P(GetHardwareInfoTests, uniqueId) {
Tri Vodd12c482022-10-12 22:41:28 +0000300 if (rpcHardwareInfo.versionNumber < VERSION_WITH_UNIQUE_ID_SUPPORT) {
Seth Moorefc86bf42021-12-09 14:07:04 -0800301 return;
302 }
303
304 RpcHardwareInfo hwInfo;
305 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
306 ASSERT_TRUE(hwInfo.uniqueId);
307 EXPECT_GE(hwInfo.uniqueId->size(), 1);
308 EXPECT_LE(hwInfo.uniqueId->size(), 32);
309}
310
Tri Vo9cab73c2022-10-28 13:40:24 -0700311/**
312 * Verify implementation supports at least MIN_SUPPORTED_NUM_KEYS_IN_CSR keys in a CSR.
313 */
314TEST_P(GetHardwareInfoTests, supportedNumKeysInCsr) {
Andrew Scullf2ae1932023-04-24 19:09:09 +0000315 if (rpcHardwareInfo.versionNumber < VERSION_WITH_SUPPORTED_NUM_KEYS_IN_CSR) {
Tri Vo9cab73c2022-10-28 13:40:24 -0700316 return;
317 }
318
319 RpcHardwareInfo hwInfo;
320 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
321 ASSERT_GE(hwInfo.supportedNumKeysInCsr, RpcHardwareInfo::MIN_SUPPORTED_NUM_KEYS_IN_CSR);
322}
323
Shawn Willden274bb552020-09-30 22:39:22 -0600324using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
325
326INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
327
328/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000329 * Generate and validate a production-mode key. MAC tag can't be verified, but
330 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600331 */
Max Bires126869a2021-02-21 18:32:59 -0800332TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600333 MacedPublicKey macedPubKey;
334 bytevec privateKeyBlob;
335 bool testMode = false;
336 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
337 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000338 vector<uint8_t> coseKeyData;
Tri Vob0b8acc2022-11-30 16:22:23 -0800339 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100340}
341
342/**
343 * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
344 */
345TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
346 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
347 std::shared_ptr<IKeyMintDevice> keyMint;
348 if (!matching_keymint_device(GetParam(), &keyMint)) {
349 // No matching IKeyMintDevice.
350 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
351 return;
352 }
353 KeyMintHardwareInfo info;
354 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
355
356 MacedPublicKey macedPubKey;
357 bytevec privateKeyBlob;
358 bool testMode = false;
359 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
360 ASSERT_TRUE(status.isOk());
361 vector<uint8_t> coseKeyData;
Tri Vob0b8acc2022-11-30 16:22:23 -0800362 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100363
David Drysdalef0d516d2021-03-22 07:51:43 +0000364 AttestationKey attestKey;
365 attestKey.keyBlob = std::move(privateKeyBlob);
366 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600367
David Drysdalef0d516d2021-03-22 07:51:43 +0000368 // Generate an ECDSA key that is attested by the generated P256 keypair.
369 AuthorizationSet keyDesc = AuthorizationSetBuilder()
370 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale915ce252021-10-14 15:17:36 +0100371 .EcdsaSigningKey(EcCurve::P_256)
David Drysdalef0d516d2021-03-22 07:51:43 +0000372 .AttestationChallenge("foo")
373 .AttestationApplicationId("bar")
374 .Digest(Digest::NONE)
375 .SetDefaultValidity();
376 KeyCreationResult creationResult;
377 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
378 ASSERT_TRUE(result.isOk());
379 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
380 vector<KeyCharacteristics> attested_key_characteristics =
381 std::move(creationResult.keyCharacteristics);
382 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
383 EXPECT_EQ(attested_key_cert_chain.size(), 1);
384
David Drysdale7dff4fc2021-12-10 10:10:52 +0000385 int32_t aidl_version = 0;
386 ASSERT_TRUE(keyMint->getInterfaceVersion(&aidl_version).isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000387 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
388 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +0000389 EXPECT_TRUE(verify_attestation_record(aidl_version, "foo", "bar", sw_enforced, hw_enforced,
David Drysdalef0d516d2021-03-22 07:51:43 +0000390 info.securityLevel,
391 attested_key_cert_chain[0].encodedCertificate));
392
393 // Attestation by itself is not valid (last entry is not self-signed).
394 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
395
396 // The signature over the attested key should correspond to the P256 public key.
397 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
398 ASSERT_TRUE(key_cert.get());
399 EVP_PKEY_Ptr signing_pubkey;
400 p256_pub_key(coseKeyData, &signing_pubkey);
401 ASSERT_TRUE(signing_pubkey.get());
402
403 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
404 << "Verification of attested certificate failed "
405 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600406}
407
408/**
409 * Generate and validate a test-mode key.
410 */
Max Bires126869a2021-02-21 18:32:59 -0800411TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600412 MacedPublicKey macedPubKey;
413 bytevec privateKeyBlob;
414 bool testMode = true;
415 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
Andrew Scullf2ae1932023-04-24 19:09:09 +0000416
417 if (rpcHardwareInfo.versionNumber >= VERSION_WITHOUT_TEST_MODE) {
418 ASSERT_FALSE(status.isOk());
419 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
420 return;
421 }
422
Shawn Willden274bb552020-09-30 22:39:22 -0600423 ASSERT_TRUE(status.isOk());
Tri Vob0b8acc2022-11-30 16:22:23 -0800424 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600425}
426
Tri Vo0d6204e2022-09-29 16:15:34 -0700427class CertificateRequestTestBase : public VtsRemotelyProvisionedComponentTests {
Shawn Willden274bb552020-09-30 22:39:22 -0600428 protected:
Tri Vo0d6204e2022-09-29 16:15:34 -0700429 CertificateRequestTestBase()
430 : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(64)) {}
David Drysdalecceca9f2021-03-12 15:49:47 +0000431
Seth Moore19acbe92021-06-23 15:15:52 -0700432 void generateTestEekChain(size_t eekLength) {
subrahmanyamanfb213d62022-02-02 23:10:55 +0000433 auto chain = generateEekChain(rpcHardwareInfo.supportedEekCurve, eekLength, eekId_);
David Drysdale08696a72022-03-10 10:43:25 +0000434 ASSERT_TRUE(chain) << chain.message();
Seth Moore19acbe92021-06-23 15:15:52 -0700435 if (chain) testEekChain_ = chain.moveValue();
436 testEekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600437 }
438
439 void generateKeys(bool testMode, size_t numKeys) {
440 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
441 cborKeysToSign_ = cppbor::Array();
442
443 for (auto& key : keysToSign_) {
444 bytevec privateKeyBlob;
445 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
Frederick Mayle9891be02023-11-03 14:39:24 -0700446 ASSERT_TRUE(status.isOk()) << status.getDescription();
Shawn Willden274bb552020-09-30 22:39:22 -0600447
David Drysdalec8400772021-03-11 12:35:11 +0000448 vector<uint8_t> payload_value;
Tri Vob0b8acc2022-11-30 16:22:23 -0800449 check_maced_pubkey(key, testMode, &payload_value);
David Drysdalec8400772021-03-11 12:35:11 +0000450 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600451 }
452 }
453
454 bytevec eekId_;
Seth Moore19acbe92021-06-23 15:15:52 -0700455 size_t testEekLength_;
456 EekChain testEekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000457 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600458 std::vector<MacedPublicKey> keysToSign_;
459 cppbor::Array cborKeysToSign_;
460};
461
Tri Vo0d6204e2022-09-29 16:15:34 -0700462class CertificateRequestTest : public CertificateRequestTestBase {
463 protected:
464 void SetUp() override {
465 CertificateRequestTestBase::SetUp();
Andrew Scull1bcb6022022-12-27 10:43:27 +0000466 ASSERT_FALSE(HasFatalFailure());
Tri Vo0d6204e2022-09-29 16:15:34 -0700467
Andrew Scullf2ae1932023-04-24 19:09:09 +0000468 if (rpcHardwareInfo.versionNumber >= VERSION_WITH_CERTIFICATE_REQUEST_V2) {
Andrew Scull95b31312023-03-27 19:16:07 +0000469 GTEST_SKIP() << "This test case only applies to RKP v1 and v2. "
470 << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
Tri Vo0d6204e2022-09-29 16:15:34 -0700471 }
472 }
473};
474
Shawn Willden274bb552020-09-30 22:39:22 -0600475/**
476 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
477 * content.
478 */
Max Bires126869a2021-02-21 18:32:59 -0800479TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600480 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000481 for (size_t eekLength : {2, 3, 7}) {
482 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700483 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600484
David Drysdalecceca9f2021-03-12 15:49:47 +0000485 bytevec keysToSignMac;
486 DeviceInfo deviceInfo;
487 ProtectedData protectedData;
488 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700489 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalecceca9f2021-03-12 15:49:47 +0000490 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700491 ASSERT_TRUE(status.isOk()) << status.getDescription();
David Drysdalecceca9f2021-03-12 15:49:47 +0000492
Seth Moore2fc6f832022-09-13 16:10:11 -0700493 auto result = verifyProductionProtectedData(
494 deviceInfo, cppbor::Array(), keysToSignMac, protectedData, testEekChain_, eekId_,
495 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
496 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000497 }
Shawn Willden274bb552020-09-30 22:39:22 -0600498}
499
500/**
Seth Moore42c11332021-07-02 15:38:17 -0700501 * Ensure that test mode outputs a unique BCC root key every time we request a
502 * certificate request. Else, it's possible that the test mode API could be used
503 * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
504 * device public key multiple times.
505 */
506TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
507 constexpr bool testMode = true;
Seth Moore42c11332021-07-02 15:38:17 -0700508
509 bytevec keysToSignMac;
510 DeviceInfo deviceInfo;
511 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000512 generateTestEekChain(3);
Seth Moore42c11332021-07-02 15:38:17 -0700513 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700514 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
515 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700516 ASSERT_TRUE(status.isOk()) << status.getDescription();
Seth Moore42c11332021-07-02 15:38:17 -0700517
Seth Moore2fc6f832022-09-13 16:10:11 -0700518 auto firstBcc = verifyProductionProtectedData(
519 deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
520 eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
521 ASSERT_TRUE(firstBcc) << firstBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700522
Seth Moore19acbe92021-06-23 15:15:52 -0700523 status = provisionable_->generateCertificateRequest(
524 testMode, {} /* keysToSign */, testEekChain_.chain, challenge_, &deviceInfo,
525 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700526 ASSERT_TRUE(status.isOk()) << status.getDescription();
Seth Moore42c11332021-07-02 15:38:17 -0700527
Seth Moore2fc6f832022-09-13 16:10:11 -0700528 auto secondBcc = verifyProductionProtectedData(
529 deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData, testEekChain_,
530 eekId_, rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
531 ASSERT_TRUE(secondBcc) << secondBcc.message();
Seth Moore42c11332021-07-02 15:38:17 -0700532
533 // Verify that none of the keys in the first BCC are repeated in the second one.
Seth Moore2fc6f832022-09-13 16:10:11 -0700534 for (const auto& i : *firstBcc) {
535 for (auto& j : *secondBcc) {
Seth Moore42c11332021-07-02 15:38:17 -0700536 ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
537 << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
538 }
539 }
540}
541
542/**
Seth Moore19acbe92021-06-23 15:15:52 -0700543 * Generate an empty certificate request in prod mode. This test must be run explicitly, and
544 * is not run by default. Not all devices are GMS devices, and therefore they do not all
545 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600546 */
Seth Moore19acbe92021-06-23 15:15:52 -0700547TEST_P(CertificateRequestTest, DISABLED_EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600548 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000549
Seth Moore19acbe92021-06-23 15:15:52 -0700550 bytevec keysToSignMac;
551 DeviceInfo deviceInfo;
552 ProtectedData protectedData;
553 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000554 testMode, {} /* keysToSign */, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
555 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700556 EXPECT_TRUE(status.isOk());
Shawn Willden274bb552020-09-30 22:39:22 -0600557}
558
559/**
560 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
561 */
Max Bires126869a2021-02-21 18:32:59 -0800562TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600563 bool testMode = true;
564 generateKeys(testMode, 4 /* numKeys */);
565
David Drysdalecceca9f2021-03-12 15:49:47 +0000566 for (size_t eekLength : {2, 3, 7}) {
567 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
Seth Moore19acbe92021-06-23 15:15:52 -0700568 generateTestEekChain(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600569
David Drysdalecceca9f2021-03-12 15:49:47 +0000570 bytevec keysToSignMac;
571 DeviceInfo deviceInfo;
572 ProtectedData protectedData;
573 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700574 testMode, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo, &protectedData,
David Drysdalecceca9f2021-03-12 15:49:47 +0000575 &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700576 ASSERT_TRUE(status.isOk()) << status.getDescription();
David Drysdalecceca9f2021-03-12 15:49:47 +0000577
Seth Moore2fc6f832022-09-13 16:10:11 -0700578 auto result = verifyProductionProtectedData(
579 deviceInfo, cborKeysToSign_, keysToSignMac, protectedData, testEekChain_, eekId_,
580 rpcHardwareInfo.supportedEekCurve, provisionable_.get(), challenge_);
581 ASSERT_TRUE(result) << result.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000582 }
Shawn Willden274bb552020-09-30 22:39:22 -0600583}
584
585/**
Seth Moore19acbe92021-06-23 15:15:52 -0700586 * Generate a non-empty certificate request in prod mode. This test must be run explicitly, and
587 * is not run by default. Not all devices are GMS devices, and therefore they do not all
588 * trust the Google EEK root.
Shawn Willden274bb552020-09-30 22:39:22 -0600589 */
Seth Moore19acbe92021-06-23 15:15:52 -0700590TEST_P(CertificateRequestTest, DISABLED_NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600591 bool testMode = false;
592 generateKeys(testMode, 4 /* numKeys */);
593
Seth Moore19acbe92021-06-23 15:15:52 -0700594 bytevec keysToSignMac;
595 DeviceInfo deviceInfo;
596 ProtectedData protectedData;
597 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000598 testMode, keysToSign_, getProdEekChain(rpcHardwareInfo.supportedEekCurve), challenge_,
599 &deviceInfo, &protectedData, &keysToSignMac);
Seth Moore19acbe92021-06-23 15:15:52 -0700600 EXPECT_TRUE(status.isOk());
David Drysdalecceca9f2021-03-12 15:49:47 +0000601}
602
603/**
David Drysdalee99ed862021-03-15 16:43:06 +0000604 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
605 */
606TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
607 bool testMode = true;
608 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000609 auto result = corrupt_maced_key(keysToSign_[0]);
610 ASSERT_TRUE(result) << result.moveMessage();
611 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000612
613 bytevec keysToSignMac;
614 DeviceInfo deviceInfo;
615 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000616 generateTestEekChain(3);
David Drysdalee99ed862021-03-15 16:43:06 +0000617 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700618 testMode, {keyWithCorruptMac}, testEekChain_.chain, challenge_, &deviceInfo,
619 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700620 ASSERT_FALSE(status.isOk()) << status.getDescription();
David Drysdalee99ed862021-03-15 16:43:06 +0000621 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
622}
623
624/**
625 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
626 */
627TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
Seth Moore19acbe92021-06-23 15:15:52 -0700628 bool testMode = false;
David Drysdalee99ed862021-03-15 16:43:06 +0000629 generateKeys(testMode, 1 /* numKeys */);
David Drysdale08696a72022-03-10 10:43:25 +0000630 auto result = corrupt_maced_key(keysToSign_[0]);
631 ASSERT_TRUE(result) << result.moveMessage();
632 MacedPublicKey keyWithCorruptMac = result.moveValue();
David Drysdalee99ed862021-03-15 16:43:06 +0000633
634 bytevec keysToSignMac;
635 DeviceInfo deviceInfo;
636 ProtectedData protectedData;
637 auto status = provisionable_->generateCertificateRequest(
subrahmanyamanfb213d62022-02-02 23:10:55 +0000638 testMode, {keyWithCorruptMac}, getProdEekChain(rpcHardwareInfo.supportedEekCurve),
639 challenge_, &deviceInfo, &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700640 ASSERT_FALSE(status.isOk()) << status.getDescription();
Seth Moore19acbe92021-06-23 15:15:52 -0700641 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
David Drysdalee99ed862021-03-15 16:43:06 +0000642}
643
644/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000645 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
646 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000647 */
648TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
649 bool testMode = false;
650 generateKeys(testMode, 4 /* numKeys */);
651
subrahmanyamanfb213d62022-02-02 23:10:55 +0000652 auto prodEekChain = getProdEekChain(rpcHardwareInfo.supportedEekCurve);
Seth Moore19acbe92021-06-23 15:15:52 -0700653 auto [parsedChain, _, parseErr] = cppbor::parse(prodEekChain);
654 ASSERT_NE(parsedChain, nullptr) << parseErr;
655 ASSERT_NE(parsedChain->asArray(), nullptr);
656
657 for (int ii = 0; ii < parsedChain->asArray()->size(); ++ii) {
658 auto chain = corrupt_sig_chain(prodEekChain, ii);
David Drysdalecceca9f2021-03-12 15:49:47 +0000659 ASSERT_TRUE(chain) << chain.message();
David Drysdalecceca9f2021-03-12 15:49:47 +0000660
661 bytevec keysToSignMac;
662 DeviceInfo deviceInfo;
663 ProtectedData protectedData;
Seth Moore19acbe92021-06-23 15:15:52 -0700664 auto status = provisionable_->generateCertificateRequest(testMode, keysToSign_, *chain,
665 challenge_, &deviceInfo,
666 &protectedData, &keysToSignMac);
David Drysdalecceca9f2021-03-12 15:49:47 +0000667 ASSERT_FALSE(status.isOk());
668 ASSERT_EQ(status.getServiceSpecificError(),
669 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
670 }
671}
672
673/**
674 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
675 * Confirm that the request is rejected.
David Drysdalecceca9f2021-03-12 15:49:47 +0000676 */
677TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
678 bool testMode = false;
679 generateKeys(testMode, 4 /* numKeys */);
680
681 // Build an EEK chain that omits the first self-signed cert.
682 auto truncatedChain = cppbor::Array();
subrahmanyamanfb213d62022-02-02 23:10:55 +0000683 auto [chain, _, parseErr] = cppbor::parse(getProdEekChain(rpcHardwareInfo.supportedEekCurve));
David Drysdalecceca9f2021-03-12 15:49:47 +0000684 ASSERT_TRUE(chain);
685 auto eekChain = chain->asArray();
686 ASSERT_NE(eekChain, nullptr);
687 for (size_t ii = 1; ii < eekChain->size(); ii++) {
688 truncatedChain.add(eekChain->get(ii)->clone());
689 }
690
Shawn Willden274bb552020-09-30 22:39:22 -0600691 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700692 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600693 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000694 auto status = provisionable_->generateCertificateRequest(
695 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
696 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600697 ASSERT_FALSE(status.isOk());
698 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
699}
700
701/**
702 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
703 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
704 */
Max Bires126869a2021-02-21 18:32:59 -0800705TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600706 generateKeys(false /* testMode */, 2 /* numKeys */);
707
708 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700709 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600710 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000711 generateTestEekChain(3);
Max Biresfdbb9042021-03-23 12:43:38 -0700712 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700713 true /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700714 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600715 ASSERT_FALSE(status.isOk());
716 ASSERT_EQ(status.getServiceSpecificError(),
717 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
718}
719
720/**
721 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
722 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
723 */
Max Bires126869a2021-02-21 18:32:59 -0800724TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600725 generateKeys(true /* testMode */, 2 /* numKeys */);
726
727 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700728 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600729 ProtectedData protectedData;
subrahmanyamanfb213d62022-02-02 23:10:55 +0000730 generateTestEekChain(3);
Shawn Willden274bb552020-09-30 22:39:22 -0600731 auto status = provisionable_->generateCertificateRequest(
Seth Moore19acbe92021-06-23 15:15:52 -0700732 false /* testMode */, keysToSign_, testEekChain_.chain, challenge_, &deviceInfo,
David Drysdalec8400772021-03-11 12:35:11 +0000733 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600734 ASSERT_FALSE(status.isOk());
735 ASSERT_EQ(status.getServiceSpecificError(),
736 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
737}
738
739INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
740
Tri Vo0d6204e2022-09-29 16:15:34 -0700741class CertificateRequestV2Test : public CertificateRequestTestBase {
742 void SetUp() override {
743 CertificateRequestTestBase::SetUp();
Andrew Scull1bcb6022022-12-27 10:43:27 +0000744 ASSERT_FALSE(HasFatalFailure());
Tri Vo0d6204e2022-09-29 16:15:34 -0700745
Andrew Scullf2ae1932023-04-24 19:09:09 +0000746 if (rpcHardwareInfo.versionNumber < VERSION_WITH_CERTIFICATE_REQUEST_V2) {
Tri Vo0d6204e2022-09-29 16:15:34 -0700747 GTEST_SKIP() << "This test case only applies to RKP v3 and above. "
748 << "RKP version discovered: " << rpcHardwareInfo.versionNumber;
749 }
750 }
751};
752
753/**
Tommy Chiufde3ad12023-03-17 05:58:28 +0000754 * Generate an empty certificate request with all possible length of challenge, and decrypt and
755 * verify the structure and content.
Tri Vo0d6204e2022-09-29 16:15:34 -0700756 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700757// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700758TEST_P(CertificateRequestV2Test, EmptyRequest) {
759 bytevec csr;
760
Tommy Chiufde3ad12023-03-17 05:58:28 +0000761 for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
762 SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
763 auto challenge = randomBytes(size);
764 auto status =
765 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700766 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700767
Tommy Chiufde3ad12023-03-17 05:58:28 +0000768 auto result = verifyProductionCsr(cppbor::Array(), csr, provisionable_.get(), challenge);
769 ASSERT_TRUE(result) << result.message();
770 }
Tri Vo0d6204e2022-09-29 16:15:34 -0700771}
772
773/**
Tommy Chiufde3ad12023-03-17 05:58:28 +0000774 * Generate a non-empty certificate request with all possible length of challenge. Decrypt, parse
775 * and validate the contents.
Tri Vo0d6204e2022-09-29 16:15:34 -0700776 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700777// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700778TEST_P(CertificateRequestV2Test, NonEmptyRequest) {
779 generateKeys(false /* testMode */, 1 /* numKeys */);
780
781 bytevec csr;
782
Tommy Chiufde3ad12023-03-17 05:58:28 +0000783 for (auto size = MIN_CHALLENGE_SIZE; size <= MAX_CHALLENGE_SIZE; size++) {
784 SCOPED_TRACE(testing::Message() << "challenge[" << size << "]");
785 auto challenge = randomBytes(size);
786 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700787 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700788
Tommy Chiufde3ad12023-03-17 05:58:28 +0000789 auto result = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge);
790 ASSERT_TRUE(result) << result.message();
791 }
792}
793
794/**
795 * Generate an empty certificate request with invalid size of challenge
796 */
797TEST_P(CertificateRequestV2Test, EmptyRequestWithInvalidChallengeFail) {
798 bytevec csr;
799
800 auto status = provisionable_->generateCertificateRequestV2(
801 /* keysToSign */ {}, randomBytes(MAX_CHALLENGE_SIZE + 1), &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700802 EXPECT_FALSE(status.isOk()) << status.getDescription();
Tommy Chiufde3ad12023-03-17 05:58:28 +0000803 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_FAILED);
Tri Vo0d6204e2022-09-29 16:15:34 -0700804}
805
806/**
Andrew Scullfb49ad22022-11-09 21:02:48 +0000807 * Generate a non-empty certificate request. Make sure contents are reproducible but allow for the
808 * signature to be different since algorithms including ECDSA P-256 can include a random value.
Tri Vo0d6204e2022-09-29 16:15:34 -0700809 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700810// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700811TEST_P(CertificateRequestV2Test, NonEmptyRequestReproducible) {
812 generateKeys(false /* testMode */, 1 /* numKeys */);
813
814 bytevec csr;
815
816 auto 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 firstCsr = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
820 ASSERT_TRUE(firstCsr) << firstCsr.message();
Tri Vo0d6204e2022-09-29 16:15:34 -0700821
822 status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700823 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700824
Andrew Scullfb49ad22022-11-09 21:02:48 +0000825 auto secondCsr = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
826 ASSERT_TRUE(secondCsr) << secondCsr.message();
Tri Vo0d6204e2022-09-29 16:15:34 -0700827
Andrew Scullfb49ad22022-11-09 21:02:48 +0000828 ASSERT_EQ(**firstCsr, **secondCsr);
Tri Vo0d6204e2022-09-29 16:15:34 -0700829}
830
831/**
832 * Generate a non-empty certificate request with multiple keys.
833 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700834// @VsrTest = 3.10-015
Tri Vo0d6204e2022-09-29 16:15:34 -0700835TEST_P(CertificateRequestV2Test, NonEmptyRequestMultipleKeys) {
Tri Vo9cab73c2022-10-28 13:40:24 -0700836 generateKeys(false /* testMode */, rpcHardwareInfo.supportedNumKeysInCsr /* numKeys */);
Tri Vo0d6204e2022-09-29 16:15:34 -0700837
838 bytevec csr;
839
840 auto status = provisionable_->generateCertificateRequestV2(keysToSign_, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700841 ASSERT_TRUE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700842
843 auto result = verifyProductionCsr(cborKeysToSign_, csr, provisionable_.get(), challenge_);
844 ASSERT_TRUE(result) << result.message();
845}
846
847/**
848 * Generate a non-empty certificate request, but with the MAC corrupted on the keypair.
849 */
850TEST_P(CertificateRequestV2Test, NonEmptyRequestCorruptMac) {
851 generateKeys(false /* testMode */, 1 /* numKeys */);
852 auto result = corrupt_maced_key(keysToSign_[0]);
853 ASSERT_TRUE(result) << result.moveMessage();
854 MacedPublicKey keyWithCorruptMac = result.moveValue();
855
856 bytevec csr;
857 auto status =
858 provisionable_->generateCertificateRequestV2({keyWithCorruptMac}, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700859 ASSERT_FALSE(status.isOk()) << status.getDescription();
Tri Vo0d6204e2022-09-29 16:15:34 -0700860 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
861}
862
863/**
Andrew Scullf2ae1932023-04-24 19:09:09 +0000864 * Call generateCertificateRequest(). Make sure it's removed.
Tri Vo0d6204e2022-09-29 16:15:34 -0700865 */
Andrew Scullf2ae1932023-04-24 19:09:09 +0000866TEST_P(CertificateRequestV2Test, CertificateRequestV1Removed_prodMode) {
867 bytevec keysToSignMac;
868 DeviceInfo deviceInfo;
869 ProtectedData protectedData;
870 auto status = provisionable_->generateCertificateRequest(
871 false /* testMode */, {} /* keysToSign */, {} /* EEK chain */, challenge_, &deviceInfo,
872 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700873 ASSERT_FALSE(status.isOk()) << status.getDescription();
Andrew Scullf2ae1932023-04-24 19:09:09 +0000874 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
Tri Vo0d6204e2022-09-29 16:15:34 -0700875}
876
Andrew Scull95b31312023-03-27 19:16:07 +0000877/**
Andrew Scullf2ae1932023-04-24 19:09:09 +0000878 * Call generateCertificateRequest() in test mode. Make sure it's removed.
Andrew Scull95b31312023-03-27 19:16:07 +0000879 */
Andrew Scullf2ae1932023-04-24 19:09:09 +0000880TEST_P(CertificateRequestV2Test, CertificateRequestV1Removed_testMode) {
Andrew Scull95b31312023-03-27 19:16:07 +0000881 bytevec keysToSignMac;
882 DeviceInfo deviceInfo;
883 ProtectedData protectedData;
884 auto status = provisionable_->generateCertificateRequest(
885 true /* testMode */, {} /* keysToSign */, {} /* EEK chain */, challenge_, &deviceInfo,
886 &protectedData, &keysToSignMac);
Frederick Mayle9891be02023-11-03 14:39:24 -0700887 ASSERT_FALSE(status.isOk()) << status.getDescription();
Andrew Scull95b31312023-03-27 19:16:07 +0000888 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_REMOVED);
889}
890
Tri Voec50ee12023-02-14 16:29:53 -0800891void parse_root_of_trust(const vector<uint8_t>& attestation_cert,
892 vector<uint8_t>* verified_boot_key, VerifiedBoot* verified_boot_state,
893 bool* device_locked, vector<uint8_t>* verified_boot_hash) {
894 X509_Ptr cert(parse_cert_blob(attestation_cert));
895 ASSERT_TRUE(cert.get());
896
897 ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
898 ASSERT_TRUE(attest_rec);
899
900 auto error = parse_root_of_trust(attest_rec->data, attest_rec->length, verified_boot_key,
901 verified_boot_state, device_locked, verified_boot_hash);
902 ASSERT_EQ(error, ErrorCode::OK);
903}
904
905/**
906 * Generate a CSR and verify DeviceInfo against IDs attested by KeyMint.
907 */
Seth Mooreac1639f2023-04-27 11:14:11 -0700908// @VsrTest = 3.10-015
Tri Voec50ee12023-02-14 16:29:53 -0800909TEST_P(CertificateRequestV2Test, DeviceInfo) {
910 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
911 std::shared_ptr<IKeyMintDevice> keyMint;
912 if (!matching_keymint_device(GetParam(), &keyMint)) {
913 // No matching IKeyMintDevice.
914 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
915 return;
916 }
917 KeyMintHardwareInfo info;
918 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
919
920 // Get IDs attested by KeyMint.
921 MacedPublicKey macedPubKey;
922 bytevec privateKeyBlob;
923 auto irpcStatus =
924 provisionable_->generateEcdsaP256KeyPair(false, &macedPubKey, &privateKeyBlob);
925 ASSERT_TRUE(irpcStatus.isOk());
926
927 AttestationKey attestKey;
928 attestKey.keyBlob = std::move(privateKeyBlob);
929 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
930
931 // Generate an ECDSA key that is attested by the generated P256 keypair.
932 AuthorizationSet keyDesc = AuthorizationSetBuilder()
933 .Authorization(TAG_NO_AUTH_REQUIRED)
934 .EcdsaSigningKey(EcCurve::P_256)
935 .AttestationChallenge("foo")
936 .AttestationApplicationId("bar")
937 .Digest(Digest::NONE)
938 .SetDefaultValidity();
939 KeyCreationResult creationResult;
940 auto kmStatus = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
941 ASSERT_TRUE(kmStatus.isOk());
942
943 vector<KeyCharacteristics> key_characteristics = std::move(creationResult.keyCharacteristics);
944 vector<Certificate> key_cert_chain = std::move(creationResult.certificateChain);
945 // We didn't provision the attestation key.
946 ASSERT_EQ(key_cert_chain.size(), 1);
947
948 // Parse attested patch levels.
949 auto auths = HwEnforcedAuthorizations(key_characteristics);
950
951 auto attestedSystemPatchLevel = auths.GetTagValue(TAG_OS_PATCHLEVEL);
952 auto attestedVendorPatchLevel = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
953 auto attestedBootPatchLevel = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
954
955 ASSERT_TRUE(attestedSystemPatchLevel.has_value());
956 ASSERT_TRUE(attestedVendorPatchLevel.has_value());
957 ASSERT_TRUE(attestedBootPatchLevel.has_value());
958
959 // Parse attested AVB values.
960 vector<uint8_t> key;
961 VerifiedBoot attestedVbState;
962 bool attestedBootloaderState;
963 vector<uint8_t> attestedVbmetaDigest;
964 parse_root_of_trust(key_cert_chain[0].encodedCertificate, &key, &attestedVbState,
965 &attestedBootloaderState, &attestedVbmetaDigest);
966
967 // Get IDs from DeviceInfo.
968 bytevec csr;
969 irpcStatus =
970 provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge_, &csr);
Frederick Mayle9891be02023-11-03 14:39:24 -0700971 ASSERT_TRUE(irpcStatus.isOk()) << irpcStatus.getDescription();
Tri Voec50ee12023-02-14 16:29:53 -0800972
973 auto result = verifyProductionCsr(cppbor::Array(), csr, provisionable_.get(), challenge_);
974 ASSERT_TRUE(result) << result.message();
975
976 std::unique_ptr<cppbor::Array> csrPayload = std::move(*result);
977 ASSERT_TRUE(csrPayload);
978
979 auto deviceInfo = csrPayload->get(2)->asMap();
980 ASSERT_TRUE(deviceInfo);
981
982 auto vbState = deviceInfo->get("vb_state")->asTstr();
983 auto bootloaderState = deviceInfo->get("bootloader_state")->asTstr();
984 auto vbmetaDigest = deviceInfo->get("vbmeta_digest")->asBstr();
985 auto systemPatchLevel = deviceInfo->get("system_patch_level")->asUint();
986 auto vendorPatchLevel = deviceInfo->get("vendor_patch_level")->asUint();
987 auto bootPatchLevel = deviceInfo->get("boot_patch_level")->asUint();
988 auto securityLevel = deviceInfo->get("security_level")->asTstr();
989
990 ASSERT_TRUE(vbState);
991 ASSERT_TRUE(bootloaderState);
992 ASSERT_TRUE(vbmetaDigest);
993 ASSERT_TRUE(systemPatchLevel);
994 ASSERT_TRUE(vendorPatchLevel);
995 ASSERT_TRUE(bootPatchLevel);
996 ASSERT_TRUE(securityLevel);
997
998 auto kmDeviceName = device_suffix(GetParam());
999
1000 // Compare DeviceInfo against IDs attested by KeyMint.
1001 ASSERT_TRUE((securityLevel->value() == "tee" && kmDeviceName == "default") ||
1002 (securityLevel->value() == "strongbox" && kmDeviceName == "strongbox"));
1003 ASSERT_TRUE((vbState->value() == "green" && attestedVbState == VerifiedBoot::VERIFIED) ||
1004 (vbState->value() == "yellow" && attestedVbState == VerifiedBoot::SELF_SIGNED) ||
1005 (vbState->value() == "orange" && attestedVbState == VerifiedBoot::UNVERIFIED));
1006 ASSERT_TRUE((bootloaderState->value() == "locked" && attestedBootloaderState) ||
1007 (bootloaderState->value() == "unlocked" && !attestedBootloaderState));
1008 ASSERT_EQ(vbmetaDigest->value(), attestedVbmetaDigest);
1009 ASSERT_EQ(systemPatchLevel->value(), attestedSystemPatchLevel.value());
1010 ASSERT_EQ(vendorPatchLevel->value(), attestedVendorPatchLevel.value());
1011 ASSERT_EQ(bootPatchLevel->value(), attestedBootPatchLevel.value());
1012}
1013
Tri Vo0d6204e2022-09-29 16:15:34 -07001014INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestV2Test);
1015
Max Biresa9b3bb92022-11-21 23:02:09 -08001016using VsrRequirementTest = VtsRemotelyProvisionedComponentTests;
1017
1018INSTANTIATE_REM_PROV_AIDL_TEST(VsrRequirementTest);
1019
1020TEST_P(VsrRequirementTest, VsrEnforcementTest) {
1021 RpcHardwareInfo hwInfo;
1022 ASSERT_TRUE(provisionable_->getHardwareInfo(&hwInfo).isOk());
1023 int vsr_api_level = get_vsr_api_level();
1024 if (vsr_api_level < 34) {
1025 GTEST_SKIP() << "Applies only to VSR API level 34 or newer, this device is: "
1026 << vsr_api_level;
1027 }
1028 EXPECT_GE(hwInfo.versionNumber, 3)
1029 << "VSR 14+ requires IRemotelyProvisionedComponent v3 or newer.";
1030}
1031
Shawn Willden274bb552020-09-30 22:39:22 -06001032} // namespace aidl::android::hardware::security::keymint::test