blob: 32765ad460a974b564db213d909782cc7067ec4e [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
17#define LOG_TAG "VtsRemotelyProvisionableComponentTests"
18
Max Bires261a0492021-04-19 18:55:56 -070019#include <AndroidRemotelyProvisionedComponentDevice.h>
Shawn Willden274bb552020-09-30 22:39:22 -060020#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
21#include <aidl/android/hardware/security/keymint/SecurityLevel.h>
22#include <android/binder_manager.h>
23#include <cppbor_parse.h>
Shawn Willden274bb552020-09-30 22:39:22 -060024#include <gmock/gmock.h>
Max Bires9704ff62021-04-07 11:12:01 -070025#include <keymaster/cppcose/cppcose.h>
Shawn Willden274bb552020-09-30 22:39:22 -060026#include <keymaster/keymaster_configuration.h>
David Drysdalef0d516d2021-03-22 07:51:43 +000027#include <keymint_support/authorization_set.h>
28#include <openssl/ec.h>
29#include <openssl/ec_key.h>
30#include <openssl/x509.h>
Shawn Willden274bb552020-09-30 22:39:22 -060031#include <remote_prov/remote_prov_utils.h>
Seth Moore42c11332021-07-02 15:38:17 -070032#include <vector>
Shawn Willden274bb552020-09-30 22:39:22 -060033
David Drysdalef0d516d2021-03-22 07:51:43 +000034#include "KeyMintAidlTestBase.h"
35
Shawn Willden274bb552020-09-30 22:39:22 -060036namespace aidl::android::hardware::security::keymint::test {
37
38using ::std::string;
39using ::std::vector;
40
41namespace {
42
43#define INSTANTIATE_REM_PROV_AIDL_TEST(name) \
44 INSTANTIATE_TEST_SUITE_P( \
45 PerInstance, name, \
46 testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
47 ::android::PrintInstanceNameToString)
48
49using bytevec = std::vector<uint8_t>;
50using testing::MatchesRegex;
51using namespace remote_prov;
52using namespace keymaster;
53
54bytevec string_to_bytevec(const char* s) {
55 const uint8_t* p = reinterpret_cast<const uint8_t*>(s);
56 return bytevec(p, p + strlen(s));
57}
58
David Drysdalee99ed862021-03-15 16:43:06 +000059ErrMsgOr<MacedPublicKey> corrupt_maced_key(const MacedPublicKey& macedPubKey) {
60 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
61 if (!coseMac0 || coseMac0->asArray()->size() != kCoseMac0EntryCount) {
62 return "COSE Mac0 parse failed";
63 }
64 auto protParams = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
65 auto unprotParams = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
66 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
67 auto tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
68 if (!protParams || !unprotParams || !payload || !tag) {
69 return "Invalid COSE_Sign1: missing content";
70 }
71 auto corruptMac0 = cppbor::Array();
72 corruptMac0.add(protParams->clone());
73 corruptMac0.add(unprotParams->clone());
74 corruptMac0.add(payload->clone());
75 vector<uint8_t> tagData = tag->value();
76 tagData[0] ^= 0x08;
77 tagData[tagData.size() - 1] ^= 0x80;
78 corruptMac0.add(cppbor::Bstr(tagData));
79
80 return MacedPublicKey{corruptMac0.encode()};
81}
82
David Drysdalecceca9f2021-03-12 15:49:47 +000083ErrMsgOr<cppbor::Array> corrupt_sig(const cppbor::Array* coseSign1) {
84 if (coseSign1->size() != kCoseSign1EntryCount) {
85 return "Invalid COSE_Sign1, wrong entry count";
86 }
87 const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
88 const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
89 const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
90 const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
91 if (!protectedParams || !unprotectedParams || !payload || !signature) {
92 return "Invalid COSE_Sign1: missing content";
93 }
94
95 auto corruptSig = cppbor::Array();
96 corruptSig.add(protectedParams->clone());
97 corruptSig.add(unprotectedParams->clone());
98 corruptSig.add(payload->clone());
99 vector<uint8_t> sigData = signature->value();
100 sigData[0] ^= 0x08;
101 corruptSig.add(cppbor::Bstr(sigData));
102
103 return std::move(corruptSig);
104}
105
106ErrMsgOr<EekChain> corrupt_sig_chain(const EekChain& eek, int which) {
107 auto [chain, _, parseErr] = cppbor::parse(eek.chain);
108 if (!chain || !chain->asArray()) {
109 return "EekChain parse failed";
110 }
111
112 cppbor::Array* eekChain = chain->asArray();
113 if (which >= eekChain->size()) {
114 return "selected sig out of range";
115 }
116 auto corruptChain = cppbor::Array();
117
118 for (int ii = 0; ii < eekChain->size(); ++ii) {
119 if (ii == which) {
120 auto sig = corrupt_sig(eekChain->get(which)->asArray());
121 if (!sig) {
122 return "Failed to build corrupted signature" + sig.moveMessage();
123 }
124 corruptChain.add(sig.moveValue());
125 } else {
126 corruptChain.add(eekChain->get(ii)->clone());
127 }
128 }
129 return EekChain{corruptChain.encode(), eek.last_pubkey, eek.last_privkey};
130}
131
David Drysdale4d3c2982021-03-31 18:21:40 +0100132string device_suffix(const string& name) {
133 size_t pos = name.find('/');
134 if (pos == string::npos) {
135 return name;
136 }
137 return name.substr(pos + 1);
138}
139
140bool matching_keymint_device(const string& rp_name, std::shared_ptr<IKeyMintDevice>* keyMint) {
141 string rp_suffix = device_suffix(rp_name);
142
143 vector<string> km_names = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
144 for (const string& km_name : km_names) {
145 // If the suffix of the KeyMint instance equals the suffix of the
146 // RemotelyProvisionedComponent instance, assume they match.
147 if (device_suffix(km_name) == rp_suffix && AServiceManager_isDeclared(km_name.c_str())) {
148 ::ndk::SpAIBinder binder(AServiceManager_waitForService(km_name.c_str()));
149 *keyMint = IKeyMintDevice::fromBinder(binder);
150 return true;
151 }
152 }
153 return false;
154}
155
Shawn Willden274bb552020-09-30 22:39:22 -0600156} // namespace
157
158class VtsRemotelyProvisionedComponentTests : public testing::TestWithParam<std::string> {
159 public:
160 virtual void SetUp() override {
161 if (AServiceManager_isDeclared(GetParam().c_str())) {
162 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
163 provisionable_ = IRemotelyProvisionedComponent::fromBinder(binder);
164 }
165 ASSERT_NE(provisionable_, nullptr);
166 }
167
168 static vector<string> build_params() {
169 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
170 return params;
171 }
172
173 protected:
174 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
175};
176
177using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
178
179INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
180
181/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000182 * Generate and validate a production-mode key. MAC tag can't be verified, but
183 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600184 */
Max Bires126869a2021-02-21 18:32:59 -0800185TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600186 MacedPublicKey macedPubKey;
187 bytevec privateKeyBlob;
188 bool testMode = false;
189 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
190 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000191 vector<uint8_t> coseKeyData;
192 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
David Drysdale4d3c2982021-03-31 18:21:40 +0100193}
194
195/**
196 * Generate and validate a production-mode key, then use it as a KeyMint attestation key.
197 */
198TEST_P(GenerateKeyTests, generateAndUseEcdsaP256Key_prodMode) {
199 // See if there is a matching IKeyMintDevice for this IRemotelyProvisionedComponent.
200 std::shared_ptr<IKeyMintDevice> keyMint;
201 if (!matching_keymint_device(GetParam(), &keyMint)) {
202 // No matching IKeyMintDevice.
203 GTEST_SKIP() << "Skipping key use test as no matching KeyMint device found";
204 return;
205 }
206 KeyMintHardwareInfo info;
207 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
208
209 MacedPublicKey macedPubKey;
210 bytevec privateKeyBlob;
211 bool testMode = false;
212 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
213 ASSERT_TRUE(status.isOk());
214 vector<uint8_t> coseKeyData;
215 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
216
David Drysdalef0d516d2021-03-22 07:51:43 +0000217 AttestationKey attestKey;
218 attestKey.keyBlob = std::move(privateKeyBlob);
219 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600220
David Drysdalef0d516d2021-03-22 07:51:43 +0000221 // Generate an ECDSA key that is attested by the generated P256 keypair.
222 AuthorizationSet keyDesc = AuthorizationSetBuilder()
223 .Authorization(TAG_NO_AUTH_REQUIRED)
224 .EcdsaSigningKey(256)
225 .AttestationChallenge("foo")
226 .AttestationApplicationId("bar")
227 .Digest(Digest::NONE)
228 .SetDefaultValidity();
229 KeyCreationResult creationResult;
230 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
231 ASSERT_TRUE(result.isOk());
232 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
233 vector<KeyCharacteristics> attested_key_characteristics =
234 std::move(creationResult.keyCharacteristics);
235 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
236 EXPECT_EQ(attested_key_cert_chain.size(), 1);
237
238 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
239 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
240 EXPECT_TRUE(verify_attestation_record("foo", "bar", sw_enforced, hw_enforced,
241 info.securityLevel,
242 attested_key_cert_chain[0].encodedCertificate));
243
244 // Attestation by itself is not valid (last entry is not self-signed).
245 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
246
247 // The signature over the attested key should correspond to the P256 public key.
248 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
249 ASSERT_TRUE(key_cert.get());
250 EVP_PKEY_Ptr signing_pubkey;
251 p256_pub_key(coseKeyData, &signing_pubkey);
252 ASSERT_TRUE(signing_pubkey.get());
253
254 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
255 << "Verification of attested certificate failed "
256 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600257}
258
259/**
260 * Generate and validate a test-mode key.
261 */
Max Bires126869a2021-02-21 18:32:59 -0800262TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600263 MacedPublicKey macedPubKey;
264 bytevec privateKeyBlob;
265 bool testMode = true;
266 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
267 ASSERT_TRUE(status.isOk());
268
David Drysdalec8400772021-03-11 12:35:11 +0000269 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600270}
271
272class CertificateRequestTest : public VtsRemotelyProvisionedComponentTests {
273 protected:
David Drysdalec8400772021-03-11 12:35:11 +0000274 CertificateRequestTest() : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(32)) {
David Drysdalecceca9f2021-03-12 15:49:47 +0000275 generateEek(3);
276 }
277
278 void generateEek(size_t eekLength) {
279 auto chain = generateEekChain(eekLength, eekId_);
Shawn Willden274bb552020-09-30 22:39:22 -0600280 EXPECT_TRUE(chain) << chain.message();
281 if (chain) eekChain_ = chain.moveValue();
David Drysdalecceca9f2021-03-12 15:49:47 +0000282 eekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600283 }
284
285 void generateKeys(bool testMode, size_t numKeys) {
286 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
287 cborKeysToSign_ = cppbor::Array();
288
289 for (auto& key : keysToSign_) {
290 bytevec privateKeyBlob;
291 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
292 ASSERT_TRUE(status.isOk()) << status.getMessage();
293
David Drysdalec8400772021-03-11 12:35:11 +0000294 vector<uint8_t> payload_value;
295 check_maced_pubkey(key, testMode, &payload_value);
296 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600297 }
298 }
299
David Drysdalef6fc5a62021-03-31 16:14:31 +0100300 void checkProtectedData(const DeviceInfo& deviceInfo, const cppbor::Array& keysToSign,
Seth Moore42c11332021-07-02 15:38:17 -0700301 const bytevec& keysToSignMac, const ProtectedData& protectedData,
302 std::vector<BccEntryData>* bccOutput = nullptr) {
David Drysdalec8400772021-03-11 12:35:11 +0000303 auto [parsedProtectedData, _, protDataErrMsg] = cppbor::parse(protectedData.protectedData);
304 ASSERT_TRUE(parsedProtectedData) << protDataErrMsg;
305 ASSERT_TRUE(parsedProtectedData->asArray());
306 ASSERT_EQ(parsedProtectedData->asArray()->size(), kCoseEncryptEntryCount);
307
308 auto senderPubkey = getSenderPubKeyFromCoseEncrypt(parsedProtectedData);
309 ASSERT_TRUE(senderPubkey) << senderPubkey.message();
310 EXPECT_EQ(senderPubkey->second, eekId_);
311
312 auto sessionKey = x25519_HKDF_DeriveKey(eekChain_.last_pubkey, eekChain_.last_privkey,
313 senderPubkey->first, false /* senderIsA */);
314 ASSERT_TRUE(sessionKey) << sessionKey.message();
315
316 auto protectedDataPayload =
317 decryptCoseEncrypt(*sessionKey, parsedProtectedData.get(), bytevec{} /* aad */);
318 ASSERT_TRUE(protectedDataPayload) << protectedDataPayload.message();
319
320 auto [parsedPayload, __, payloadErrMsg] = cppbor::parse(*protectedDataPayload);
321 ASSERT_TRUE(parsedPayload) << "Failed to parse payload: " << payloadErrMsg;
322 ASSERT_TRUE(parsedPayload->asArray());
323 EXPECT_EQ(parsedPayload->asArray()->size(), 2U);
324
325 auto& signedMac = parsedPayload->asArray()->get(0);
326 auto& bcc = parsedPayload->asArray()->get(1);
327 ASSERT_TRUE(signedMac && signedMac->asArray());
328 ASSERT_TRUE(bcc && bcc->asArray());
329
330 // BCC is [ pubkey, + BccEntry]
331 auto bccContents = validateBcc(bcc->asArray());
332 ASSERT_TRUE(bccContents) << "\n" << bccContents.message() << "\n" << prettyPrint(bcc.get());
333 ASSERT_GT(bccContents->size(), 0U);
334
David Drysdalef6fc5a62021-03-31 16:14:31 +0100335 auto [deviceInfoMap, __2, deviceInfoErrMsg] = cppbor::parse(deviceInfo.deviceInfo);
336 ASSERT_TRUE(deviceInfoMap) << "Failed to parse deviceInfo: " << deviceInfoErrMsg;
337 ASSERT_TRUE(deviceInfoMap->asMap());
338
David Drysdalec8400772021-03-11 12:35:11 +0000339 auto& signingKey = bccContents->back().pubKey;
Seth Moore798188a2021-06-17 10:58:27 -0700340 auto macKey = verifyAndParseCoseSign1(signedMac->asArray(), signingKey,
David Drysdalef6fc5a62021-03-31 16:14:31 +0100341 cppbor::Array() // SignedMacAad
David Drysdalec8400772021-03-11 12:35:11 +0000342 .add(challenge_)
David Drysdalef6fc5a62021-03-31 16:14:31 +0100343 .add(std::move(deviceInfoMap))
Max Bires8dff0b32021-05-26 13:05:09 -0700344 .add(keysToSignMac)
David Drysdalec8400772021-03-11 12:35:11 +0000345 .encode());
346 ASSERT_TRUE(macKey) << macKey.message();
347
348 auto coseMac0 = cppbor::Array()
349 .add(cppbor::Map() // protected
350 .add(ALGORITHM, HMAC_256)
351 .canonicalize()
352 .encode())
353 .add(cppbor::Map()) // unprotected
354 .add(keysToSign.encode()) // payload (keysToSign)
355 .add(keysToSignMac); // tag
356
357 auto macPayload = verifyAndParseCoseMac0(&coseMac0, *macKey);
358 ASSERT_TRUE(macPayload) << macPayload.message();
Seth Moore42c11332021-07-02 15:38:17 -0700359
360 if (bccOutput) {
361 *bccOutput = std::move(*bccContents);
362 }
David Drysdalec8400772021-03-11 12:35:11 +0000363 }
364
Shawn Willden274bb552020-09-30 22:39:22 -0600365 bytevec eekId_;
David Drysdalecceca9f2021-03-12 15:49:47 +0000366 size_t eekLength_;
Shawn Willden274bb552020-09-30 22:39:22 -0600367 EekChain eekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000368 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600369 std::vector<MacedPublicKey> keysToSign_;
370 cppbor::Array cborKeysToSign_;
371};
372
373/**
374 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
375 * content.
376 */
Max Bires126869a2021-02-21 18:32:59 -0800377TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600378 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000379 for (size_t eekLength : {2, 3, 7}) {
380 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
381 generateEek(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600382
David Drysdalecceca9f2021-03-12 15:49:47 +0000383 bytevec keysToSignMac;
384 DeviceInfo deviceInfo;
385 ProtectedData protectedData;
386 auto status = provisionable_->generateCertificateRequest(
387 testMode, {} /* keysToSign */, eekChain_.chain, challenge_, &deviceInfo,
388 &protectedData, &keysToSignMac);
389 ASSERT_TRUE(status.isOk()) << status.getMessage();
390
David Drysdalef6fc5a62021-03-31 16:14:31 +0100391 checkProtectedData(deviceInfo, cppbor::Array(), keysToSignMac, protectedData);
David Drysdalecceca9f2021-03-12 15:49:47 +0000392 }
Shawn Willden274bb552020-09-30 22:39:22 -0600393}
394
395/**
Seth Moore42c11332021-07-02 15:38:17 -0700396 * Ensure that test mode outputs a unique BCC root key every time we request a
397 * certificate request. Else, it's possible that the test mode API could be used
398 * to fingerprint devices. Only the GEEK should be allowed to decrypt the same
399 * device public key multiple times.
400 */
401TEST_P(CertificateRequestTest, NewKeyPerCallInTestMode) {
402 constexpr bool testMode = true;
403 constexpr size_t eekLength = 2;
404
405 generateEek(eekLength);
406
407 bytevec keysToSignMac;
408 DeviceInfo deviceInfo;
409 ProtectedData protectedData;
410 auto status = provisionable_->generateCertificateRequest(
411 testMode, {} /* keysToSign */, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
412 &keysToSignMac);
413 ASSERT_TRUE(status.isOk()) << status.getMessage();
414
415 std::vector<BccEntryData> firstBcc;
416 checkProtectedData(deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData,
417 &firstBcc);
418
419 status = provisionable_->generateCertificateRequest(testMode, {} /* keysToSign */,
420 eekChain_.chain, challenge_, &deviceInfo,
421 &protectedData, &keysToSignMac);
422 ASSERT_TRUE(status.isOk()) << status.getMessage();
423
424 std::vector<BccEntryData> secondBcc;
425 checkProtectedData(deviceInfo, /*keysToSign=*/cppbor::Array(), keysToSignMac, protectedData,
426 &secondBcc);
427
428 // Verify that none of the keys in the first BCC are repeated in the second one.
429 for (const auto& i : firstBcc) {
430 for (auto& j : secondBcc) {
431 ASSERT_THAT(i.pubKey, testing::Not(testing::ElementsAreArray(j.pubKey)))
432 << "Found a repeated pubkey in two generateCertificateRequest test mode calls";
433 }
434 }
435}
436
437/**
Shawn Willden274bb552020-09-30 22:39:22 -0600438 * Generate an empty certificate request in prod mode. Generation will fail because we don't have a
439 * valid GEEK.
440 *
441 * TODO(swillden): Get a valid GEEK and use it so the generation can succeed, though we won't be
442 * able to decrypt.
443 */
Max Bires126869a2021-02-21 18:32:59 -0800444TEST_P(CertificateRequestTest, EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600445 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000446 for (size_t eekLength : {2, 3, 7}) {
447 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
448 generateEek(eekLength);
449
450 bytevec keysToSignMac;
451 DeviceInfo deviceInfo;
452 ProtectedData protectedData;
453 auto status = provisionable_->generateCertificateRequest(
454 testMode, {} /* keysToSign */, eekChain_.chain, challenge_, &deviceInfo,
455 &protectedData, &keysToSignMac);
456 EXPECT_FALSE(status.isOk());
457 EXPECT_EQ(status.getServiceSpecificError(),
458 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
459 }
Shawn Willden274bb552020-09-30 22:39:22 -0600460}
461
462/**
463 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
464 */
Max Bires126869a2021-02-21 18:32:59 -0800465TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600466 bool testMode = true;
467 generateKeys(testMode, 4 /* numKeys */);
468
David Drysdalecceca9f2021-03-12 15:49:47 +0000469 for (size_t eekLength : {2, 3, 7}) {
470 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
471 generateEek(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600472
David Drysdalecceca9f2021-03-12 15:49:47 +0000473 bytevec keysToSignMac;
474 DeviceInfo deviceInfo;
475 ProtectedData protectedData;
476 auto status = provisionable_->generateCertificateRequest(
477 testMode, keysToSign_, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
478 &keysToSignMac);
479 ASSERT_TRUE(status.isOk()) << status.getMessage();
480
David Drysdalef6fc5a62021-03-31 16:14:31 +0100481 checkProtectedData(deviceInfo, cborKeysToSign_, keysToSignMac, protectedData);
David Drysdalecceca9f2021-03-12 15:49:47 +0000482 }
Shawn Willden274bb552020-09-30 22:39:22 -0600483}
484
485/**
486 * Generate a non-empty certificate request in prod mode. Must fail because we don't have a valid
487 * GEEK.
488 *
489 * TODO(swillden): Get a valid GEEK and use it so the generation can succeed, though we won't be
490 * able to decrypt.
491 */
Max Bires126869a2021-02-21 18:32:59 -0800492TEST_P(CertificateRequestTest, NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600493 bool testMode = false;
494 generateKeys(testMode, 4 /* numKeys */);
495
David Drysdalecceca9f2021-03-12 15:49:47 +0000496 for (size_t eekLength : {2, 3, 7}) {
497 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
498 generateEek(eekLength);
499
500 bytevec keysToSignMac;
501 DeviceInfo deviceInfo;
502 ProtectedData protectedData;
503 auto status = provisionable_->generateCertificateRequest(
504 testMode, keysToSign_, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
505 &keysToSignMac);
506 EXPECT_FALSE(status.isOk());
507 EXPECT_EQ(status.getServiceSpecificError(),
508 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
509 }
510}
511
512/**
David Drysdalee99ed862021-03-15 16:43:06 +0000513 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
514 */
515TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
516 bool testMode = true;
517 generateKeys(testMode, 1 /* numKeys */);
518 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
519
520 bytevec keysToSignMac;
521 DeviceInfo deviceInfo;
522 ProtectedData protectedData;
523 auto status = provisionable_->generateCertificateRequest(
524 testMode, {keyWithCorruptMac}, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
525 &keysToSignMac);
526 ASSERT_FALSE(status.isOk()) << status.getMessage();
527 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
528}
529
530/**
531 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
532 */
533TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
534 bool testMode = true;
535 generateKeys(testMode, 1 /* numKeys */);
536 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
537
538 bytevec keysToSignMac;
539 DeviceInfo deviceInfo;
540 ProtectedData protectedData;
541 auto status = provisionable_->generateCertificateRequest(
542 testMode, {keyWithCorruptMac}, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
543 &keysToSignMac);
544 ASSERT_FALSE(status.isOk()) << status.getMessage();
545 auto rc = status.getServiceSpecificError();
546
547 // TODO(drysdale): drop the INVALID_EEK potential error code when a real GEEK is available.
548 EXPECT_TRUE(rc == BnRemotelyProvisionedComponent::STATUS_INVALID_EEK ||
549 rc == BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
550}
551
552/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000553 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
554 * Confirm that the request is rejected.
555 *
556 * TODO(drysdale): Update to use a valid GEEK, so that the test actually confirms that the
557 * implementation is checking signatures.
558 */
559TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
560 bool testMode = false;
561 generateKeys(testMode, 4 /* numKeys */);
562
563 for (size_t ii = 0; ii < eekLength_; ii++) {
564 auto chain = corrupt_sig_chain(eekChain_, ii);
565 ASSERT_TRUE(chain) << chain.message();
566 EekChain corruptEek = chain.moveValue();
567
568 bytevec keysToSignMac;
569 DeviceInfo deviceInfo;
570 ProtectedData protectedData;
571 auto status = provisionable_->generateCertificateRequest(
572 testMode, keysToSign_, corruptEek.chain, challenge_, &deviceInfo, &protectedData,
573 &keysToSignMac);
574 ASSERT_FALSE(status.isOk());
575 ASSERT_EQ(status.getServiceSpecificError(),
576 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
577 }
578}
579
580/**
581 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
582 * Confirm that the request is rejected.
583 *
584 * TODO(drysdale): Update to use a valid GEEK, so that the test actually confirms that the
585 * implementation is checking signatures.
586 */
587TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
588 bool testMode = false;
589 generateKeys(testMode, 4 /* numKeys */);
590
591 // Build an EEK chain that omits the first self-signed cert.
592 auto truncatedChain = cppbor::Array();
593 auto [chain, _, parseErr] = cppbor::parse(eekChain_.chain);
594 ASSERT_TRUE(chain);
595 auto eekChain = chain->asArray();
596 ASSERT_NE(eekChain, nullptr);
597 for (size_t ii = 1; ii < eekChain->size(); ii++) {
598 truncatedChain.add(eekChain->get(ii)->clone());
599 }
600
Shawn Willden274bb552020-09-30 22:39:22 -0600601 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700602 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600603 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000604 auto status = provisionable_->generateCertificateRequest(
605 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
606 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600607 ASSERT_FALSE(status.isOk());
608 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
609}
610
611/**
612 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
613 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
614 */
Max Bires126869a2021-02-21 18:32:59 -0800615TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600616 generateKeys(false /* testMode */, 2 /* numKeys */);
617
618 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700619 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600620 ProtectedData protectedData;
Max Biresfdbb9042021-03-23 12:43:38 -0700621 auto status = provisionable_->generateCertificateRequest(
David Drysdalec8400772021-03-11 12:35:11 +0000622 true /* testMode */, keysToSign_, eekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700623 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600624 ASSERT_FALSE(status.isOk());
625 ASSERT_EQ(status.getServiceSpecificError(),
626 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
627}
628
629/**
630 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
631 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
632 */
Max Bires126869a2021-02-21 18:32:59 -0800633TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600634 generateKeys(true /* testMode */, 2 /* numKeys */);
635
636 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700637 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600638 ProtectedData protectedData;
639 auto status = provisionable_->generateCertificateRequest(
David Drysdalec8400772021-03-11 12:35:11 +0000640 false /* testMode */, keysToSign_, eekChain_.chain, challenge_, &deviceInfo,
641 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600642 ASSERT_FALSE(status.isOk());
643 ASSERT_EQ(status.getServiceSpecificError(),
644 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
645}
646
647INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
648
649} // namespace aidl::android::hardware::security::keymint::test