blob: e4c4a22243d42673b1e42a6b0b6afce02e1645bd [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
19#include <RemotelyProvisionedComponent.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>
24#include <cppcose/cppcose.h>
25#include <gmock/gmock.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>
32
David Drysdalef0d516d2021-03-22 07:51:43 +000033#include "KeyMintAidlTestBase.h"
34
Shawn Willden274bb552020-09-30 22:39:22 -060035namespace aidl::android::hardware::security::keymint::test {
36
37using ::std::string;
38using ::std::vector;
39
40namespace {
41
42#define INSTANTIATE_REM_PROV_AIDL_TEST(name) \
43 INSTANTIATE_TEST_SUITE_P( \
44 PerInstance, name, \
45 testing::ValuesIn(VtsRemotelyProvisionedComponentTests::build_params()), \
46 ::android::PrintInstanceNameToString)
47
48using bytevec = std::vector<uint8_t>;
49using testing::MatchesRegex;
50using namespace remote_prov;
51using namespace keymaster;
52
53bytevec string_to_bytevec(const char* s) {
54 const uint8_t* p = reinterpret_cast<const uint8_t*>(s);
55 return bytevec(p, p + strlen(s));
56}
57
David Drysdalef0d516d2021-03-22 07:51:43 +000058void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey) {
59 // Extract x and y affine coordinates from the encoded Cose_Key.
60 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(coseKeyData);
61 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
62 auto coseKey = parsedPayload->asMap();
63 const std::unique_ptr<cppbor::Item>& xItem = coseKey->get(cppcose::CoseKey::PUBKEY_X);
64 ASSERT_NE(xItem->asBstr(), nullptr);
65 vector<uint8_t> x = xItem->asBstr()->value();
66 const std::unique_ptr<cppbor::Item>& yItem = coseKey->get(cppcose::CoseKey::PUBKEY_Y);
67 ASSERT_NE(yItem->asBstr(), nullptr);
68 vector<uint8_t> y = yItem->asBstr()->value();
69
70 // Concatenate: 0x04 (uncompressed form marker) | x | y
71 vector<uint8_t> pubKeyData{0x04};
72 pubKeyData.insert(pubKeyData.end(), x.begin(), x.end());
73 pubKeyData.insert(pubKeyData.end(), y.begin(), y.end());
74
75 EC_KEY_Ptr ecKey = EC_KEY_Ptr(EC_KEY_new());
76 ASSERT_NE(ecKey, nullptr);
77 EC_GROUP_Ptr group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
78 ASSERT_NE(group, nullptr);
79 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
80 EC_POINT_Ptr point = EC_POINT_Ptr(EC_POINT_new(group.get()));
81 ASSERT_NE(point, nullptr);
82 ASSERT_EQ(EC_POINT_oct2point(group.get(), point.get(), pubKeyData.data(), pubKeyData.size(),
83 nullptr),
84 1);
85 ASSERT_EQ(EC_KEY_set_public_key(ecKey.get(), point.get()), 1);
86
87 EVP_PKEY_Ptr pubKey = EVP_PKEY_Ptr(EVP_PKEY_new());
88 ASSERT_NE(pubKey, nullptr);
89 EVP_PKEY_assign_EC_KEY(pubKey.get(), ecKey.release());
90 *signingKey = std::move(pubKey);
91}
92
David Drysdalec8400772021-03-11 12:35:11 +000093void check_cose_key(const vector<uint8_t>& data, bool testMode) {
94 auto [parsedPayload, __, payloadParseErr] = cppbor::parse(data);
95 ASSERT_TRUE(parsedPayload) << "Key parse failed: " << payloadParseErr;
96
97 // The following check assumes that canonical CBOR encoding is used for the COSE_Key.
98 if (testMode) {
99 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
100 MatchesRegex("{\n"
101 " 1 : 2,\n" // kty: EC2
102 " 3 : -7,\n" // alg: ES256
103 " -1 : 1,\n" // EC id: P256
104 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
105 // sequence of 32 hexadecimal bytes, enclosed in braces and
106 // separated by commas. In this case, some Ed25519 public key.
107 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
108 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
109 " -70000 : null,\n" // test marker
110 "}"));
111 } else {
112 EXPECT_THAT(cppbor::prettyPrint(parsedPayload.get()),
113 MatchesRegex("{\n"
114 " 1 : 2,\n" // kty: EC2
115 " 3 : -7,\n" // alg: ES256
116 " -1 : 1,\n" // EC id: P256
117 // The regex {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}} matches a
118 // sequence of 32 hexadecimal bytes, enclosed in braces and
119 // separated by commas. In this case, some Ed25519 public key.
120 " -2 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_x: data
121 " -3 : {(0x[0-9a-f]{2}, ){31}0x[0-9a-f]{2}},\n" // pub_y: data
122 "}"));
123 }
124}
125
126void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
127 vector<uint8_t>* payload_value) {
128 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
129 ASSERT_TRUE(coseMac0) << "COSE Mac0 parse failed " << mac0ParseErr;
130
131 ASSERT_NE(coseMac0->asArray(), nullptr);
132 ASSERT_EQ(coseMac0->asArray()->size(), kCoseMac0EntryCount);
133
134 auto protParms = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
135 ASSERT_NE(protParms, nullptr);
136
137 // Header label:value of 'alg': HMAC-256
138 ASSERT_EQ(cppbor::prettyPrint(protParms->value()), "{\n 1 : 5,\n}");
139
140 auto unprotParms = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
141 ASSERT_NE(unprotParms, nullptr);
142 ASSERT_EQ(unprotParms->size(), 0);
143
144 // The payload is a bstr holding an encoded COSE_Key
145 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
146 ASSERT_NE(payload, nullptr);
147 check_cose_key(payload->value(), testMode);
148
149 auto coseMac0Tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
150 ASSERT_TRUE(coseMac0Tag);
151 auto extractedTag = coseMac0Tag->value();
152 EXPECT_EQ(extractedTag.size(), 32U);
153
154 // Compare with tag generated with kTestMacKey. Should only match in test mode
155 auto testTag = cppcose::generateCoseMac0Mac(remote_prov::kTestMacKey, {} /* external_aad */,
156 payload->value());
157 ASSERT_TRUE(testTag) << "Tag calculation failed: " << testTag.message();
158
159 if (testMode) {
160 EXPECT_EQ(*testTag, extractedTag);
161 } else {
162 EXPECT_NE(*testTag, extractedTag);
163 }
164 if (payload_value != nullptr) {
165 *payload_value = payload->value();
166 }
167}
168
David Drysdalee99ed862021-03-15 16:43:06 +0000169ErrMsgOr<MacedPublicKey> corrupt_maced_key(const MacedPublicKey& macedPubKey) {
170 auto [coseMac0, _, mac0ParseErr] = cppbor::parse(macedPubKey.macedKey);
171 if (!coseMac0 || coseMac0->asArray()->size() != kCoseMac0EntryCount) {
172 return "COSE Mac0 parse failed";
173 }
174 auto protParams = coseMac0->asArray()->get(kCoseMac0ProtectedParams)->asBstr();
175 auto unprotParams = coseMac0->asArray()->get(kCoseMac0UnprotectedParams)->asMap();
176 auto payload = coseMac0->asArray()->get(kCoseMac0Payload)->asBstr();
177 auto tag = coseMac0->asArray()->get(kCoseMac0Tag)->asBstr();
178 if (!protParams || !unprotParams || !payload || !tag) {
179 return "Invalid COSE_Sign1: missing content";
180 }
181 auto corruptMac0 = cppbor::Array();
182 corruptMac0.add(protParams->clone());
183 corruptMac0.add(unprotParams->clone());
184 corruptMac0.add(payload->clone());
185 vector<uint8_t> tagData = tag->value();
186 tagData[0] ^= 0x08;
187 tagData[tagData.size() - 1] ^= 0x80;
188 corruptMac0.add(cppbor::Bstr(tagData));
189
190 return MacedPublicKey{corruptMac0.encode()};
191}
192
David Drysdalecceca9f2021-03-12 15:49:47 +0000193ErrMsgOr<cppbor::Array> corrupt_sig(const cppbor::Array* coseSign1) {
194 if (coseSign1->size() != kCoseSign1EntryCount) {
195 return "Invalid COSE_Sign1, wrong entry count";
196 }
197 const cppbor::Bstr* protectedParams = coseSign1->get(kCoseSign1ProtectedParams)->asBstr();
198 const cppbor::Map* unprotectedParams = coseSign1->get(kCoseSign1UnprotectedParams)->asMap();
199 const cppbor::Bstr* payload = coseSign1->get(kCoseSign1Payload)->asBstr();
200 const cppbor::Bstr* signature = coseSign1->get(kCoseSign1Signature)->asBstr();
201 if (!protectedParams || !unprotectedParams || !payload || !signature) {
202 return "Invalid COSE_Sign1: missing content";
203 }
204
205 auto corruptSig = cppbor::Array();
206 corruptSig.add(protectedParams->clone());
207 corruptSig.add(unprotectedParams->clone());
208 corruptSig.add(payload->clone());
209 vector<uint8_t> sigData = signature->value();
210 sigData[0] ^= 0x08;
211 corruptSig.add(cppbor::Bstr(sigData));
212
213 return std::move(corruptSig);
214}
215
216ErrMsgOr<EekChain> corrupt_sig_chain(const EekChain& eek, int which) {
217 auto [chain, _, parseErr] = cppbor::parse(eek.chain);
218 if (!chain || !chain->asArray()) {
219 return "EekChain parse failed";
220 }
221
222 cppbor::Array* eekChain = chain->asArray();
223 if (which >= eekChain->size()) {
224 return "selected sig out of range";
225 }
226 auto corruptChain = cppbor::Array();
227
228 for (int ii = 0; ii < eekChain->size(); ++ii) {
229 if (ii == which) {
230 auto sig = corrupt_sig(eekChain->get(which)->asArray());
231 if (!sig) {
232 return "Failed to build corrupted signature" + sig.moveMessage();
233 }
234 corruptChain.add(sig.moveValue());
235 } else {
236 corruptChain.add(eekChain->get(ii)->clone());
237 }
238 }
239 return EekChain{corruptChain.encode(), eek.last_pubkey, eek.last_privkey};
240}
241
Shawn Willden274bb552020-09-30 22:39:22 -0600242} // namespace
243
244class VtsRemotelyProvisionedComponentTests : public testing::TestWithParam<std::string> {
245 public:
246 virtual void SetUp() override {
247 if (AServiceManager_isDeclared(GetParam().c_str())) {
248 ::ndk::SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
249 provisionable_ = IRemotelyProvisionedComponent::fromBinder(binder);
250 }
251 ASSERT_NE(provisionable_, nullptr);
252 }
253
254 static vector<string> build_params() {
255 auto params = ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
256 return params;
257 }
258
259 protected:
260 std::shared_ptr<IRemotelyProvisionedComponent> provisionable_;
261};
262
263using GenerateKeyTests = VtsRemotelyProvisionedComponentTests;
264
265INSTANTIATE_REM_PROV_AIDL_TEST(GenerateKeyTests);
266
267/**
David Drysdalef0d516d2021-03-22 07:51:43 +0000268 * Generate and validate a production-mode key. MAC tag can't be verified, but
269 * the private key blob should be usable in KeyMint operations.
Shawn Willden274bb552020-09-30 22:39:22 -0600270 */
Max Bires126869a2021-02-21 18:32:59 -0800271TEST_P(GenerateKeyTests, generateEcdsaP256Key_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600272 MacedPublicKey macedPubKey;
273 bytevec privateKeyBlob;
274 bool testMode = false;
275 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
276 ASSERT_TRUE(status.isOk());
David Drysdalef0d516d2021-03-22 07:51:43 +0000277 vector<uint8_t> coseKeyData;
278 check_maced_pubkey(macedPubKey, testMode, &coseKeyData);
279 AttestationKey attestKey;
280 attestKey.keyBlob = std::move(privateKeyBlob);
281 attestKey.issuerSubjectName = make_name_from_str("Android Keystore Key");
Shawn Willden274bb552020-09-30 22:39:22 -0600282
David Drysdalef0d516d2021-03-22 07:51:43 +0000283 // Also talk to an IKeyMintDevice.
284 // TODO: if there were multiple instances of IRemotelyProvisionedComponent and IKeyMintDevice,
285 // what should the correlation between them be?
286 vector<string> params = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
287 ASSERT_GT(params.size(), 0U);
288 ASSERT_TRUE(AServiceManager_isDeclared(params[0].c_str()));
289 ::ndk::SpAIBinder binder(AServiceManager_waitForService(params[0].c_str()));
290 std::shared_ptr<IKeyMintDevice> keyMint = IKeyMintDevice::fromBinder(binder);
291 KeyMintHardwareInfo info;
292 ASSERT_TRUE(keyMint->getHardwareInfo(&info).isOk());
293
294 // Generate an ECDSA key that is attested by the generated P256 keypair.
295 AuthorizationSet keyDesc = AuthorizationSetBuilder()
296 .Authorization(TAG_NO_AUTH_REQUIRED)
297 .EcdsaSigningKey(256)
298 .AttestationChallenge("foo")
299 .AttestationApplicationId("bar")
300 .Digest(Digest::NONE)
301 .SetDefaultValidity();
302 KeyCreationResult creationResult;
303 auto result = keyMint->generateKey(keyDesc.vector_data(), attestKey, &creationResult);
304 ASSERT_TRUE(result.isOk());
305 vector<uint8_t> attested_key_blob = std::move(creationResult.keyBlob);
306 vector<KeyCharacteristics> attested_key_characteristics =
307 std::move(creationResult.keyCharacteristics);
308 vector<Certificate> attested_key_cert_chain = std::move(creationResult.certificateChain);
309 EXPECT_EQ(attested_key_cert_chain.size(), 1);
310
311 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(attested_key_characteristics);
312 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(attested_key_characteristics);
313 EXPECT_TRUE(verify_attestation_record("foo", "bar", sw_enforced, hw_enforced,
314 info.securityLevel,
315 attested_key_cert_chain[0].encodedCertificate));
316
317 // Attestation by itself is not valid (last entry is not self-signed).
318 EXPECT_FALSE(ChainSignaturesAreValid(attested_key_cert_chain));
319
320 // The signature over the attested key should correspond to the P256 public key.
321 X509_Ptr key_cert(parse_cert_blob(attested_key_cert_chain[0].encodedCertificate));
322 ASSERT_TRUE(key_cert.get());
323 EVP_PKEY_Ptr signing_pubkey;
324 p256_pub_key(coseKeyData, &signing_pubkey);
325 ASSERT_TRUE(signing_pubkey.get());
326
327 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
328 << "Verification of attested certificate failed "
329 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Shawn Willden274bb552020-09-30 22:39:22 -0600330}
331
332/**
333 * Generate and validate a test-mode key.
334 */
Max Bires126869a2021-02-21 18:32:59 -0800335TEST_P(GenerateKeyTests, generateEcdsaP256Key_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600336 MacedPublicKey macedPubKey;
337 bytevec privateKeyBlob;
338 bool testMode = true;
339 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &macedPubKey, &privateKeyBlob);
340 ASSERT_TRUE(status.isOk());
341
David Drysdalec8400772021-03-11 12:35:11 +0000342 check_maced_pubkey(macedPubKey, testMode, nullptr);
Shawn Willden274bb552020-09-30 22:39:22 -0600343}
344
345class CertificateRequestTest : public VtsRemotelyProvisionedComponentTests {
346 protected:
David Drysdalec8400772021-03-11 12:35:11 +0000347 CertificateRequestTest() : eekId_(string_to_bytevec("eekid")), challenge_(randomBytes(32)) {
David Drysdalecceca9f2021-03-12 15:49:47 +0000348 generateEek(3);
349 }
350
351 void generateEek(size_t eekLength) {
352 auto chain = generateEekChain(eekLength, eekId_);
Shawn Willden274bb552020-09-30 22:39:22 -0600353 EXPECT_TRUE(chain) << chain.message();
354 if (chain) eekChain_ = chain.moveValue();
David Drysdalecceca9f2021-03-12 15:49:47 +0000355 eekLength_ = eekLength;
Shawn Willden274bb552020-09-30 22:39:22 -0600356 }
357
358 void generateKeys(bool testMode, size_t numKeys) {
359 keysToSign_ = std::vector<MacedPublicKey>(numKeys);
360 cborKeysToSign_ = cppbor::Array();
361
362 for (auto& key : keysToSign_) {
363 bytevec privateKeyBlob;
364 auto status = provisionable_->generateEcdsaP256KeyPair(testMode, &key, &privateKeyBlob);
365 ASSERT_TRUE(status.isOk()) << status.getMessage();
366
David Drysdalec8400772021-03-11 12:35:11 +0000367 vector<uint8_t> payload_value;
368 check_maced_pubkey(key, testMode, &payload_value);
369 cborKeysToSign_.add(cppbor::EncodedItem(payload_value));
Shawn Willden274bb552020-09-30 22:39:22 -0600370 }
371 }
372
David Drysdalec8400772021-03-11 12:35:11 +0000373 void checkProtectedData(bool testMode, const cppbor::Array& keysToSign,
374 const bytevec& keysToSignMac, const ProtectedData& protectedData) {
375 auto [parsedProtectedData, _, protDataErrMsg] = cppbor::parse(protectedData.protectedData);
376 ASSERT_TRUE(parsedProtectedData) << protDataErrMsg;
377 ASSERT_TRUE(parsedProtectedData->asArray());
378 ASSERT_EQ(parsedProtectedData->asArray()->size(), kCoseEncryptEntryCount);
379
380 auto senderPubkey = getSenderPubKeyFromCoseEncrypt(parsedProtectedData);
381 ASSERT_TRUE(senderPubkey) << senderPubkey.message();
382 EXPECT_EQ(senderPubkey->second, eekId_);
383
384 auto sessionKey = x25519_HKDF_DeriveKey(eekChain_.last_pubkey, eekChain_.last_privkey,
385 senderPubkey->first, false /* senderIsA */);
386 ASSERT_TRUE(sessionKey) << sessionKey.message();
387
388 auto protectedDataPayload =
389 decryptCoseEncrypt(*sessionKey, parsedProtectedData.get(), bytevec{} /* aad */);
390 ASSERT_TRUE(protectedDataPayload) << protectedDataPayload.message();
391
392 auto [parsedPayload, __, payloadErrMsg] = cppbor::parse(*protectedDataPayload);
393 ASSERT_TRUE(parsedPayload) << "Failed to parse payload: " << payloadErrMsg;
394 ASSERT_TRUE(parsedPayload->asArray());
395 EXPECT_EQ(parsedPayload->asArray()->size(), 2U);
396
397 auto& signedMac = parsedPayload->asArray()->get(0);
398 auto& bcc = parsedPayload->asArray()->get(1);
399 ASSERT_TRUE(signedMac && signedMac->asArray());
400 ASSERT_TRUE(bcc && bcc->asArray());
401
402 // BCC is [ pubkey, + BccEntry]
403 auto bccContents = validateBcc(bcc->asArray());
404 ASSERT_TRUE(bccContents) << "\n" << bccContents.message() << "\n" << prettyPrint(bcc.get());
405 ASSERT_GT(bccContents->size(), 0U);
406
407 auto& signingKey = bccContents->back().pubKey;
408 auto macKey = verifyAndParseCoseSign1(testMode, signedMac->asArray(), signingKey,
409 cppbor::Array() // DeviceInfo
410 .add(challenge_)
411 .add(cppbor::Map())
412 .encode());
413 ASSERT_TRUE(macKey) << macKey.message();
414
415 auto coseMac0 = cppbor::Array()
416 .add(cppbor::Map() // protected
417 .add(ALGORITHM, HMAC_256)
418 .canonicalize()
419 .encode())
420 .add(cppbor::Map()) // unprotected
421 .add(keysToSign.encode()) // payload (keysToSign)
422 .add(keysToSignMac); // tag
423
424 auto macPayload = verifyAndParseCoseMac0(&coseMac0, *macKey);
425 ASSERT_TRUE(macPayload) << macPayload.message();
426 }
427
Shawn Willden274bb552020-09-30 22:39:22 -0600428 bytevec eekId_;
David Drysdalecceca9f2021-03-12 15:49:47 +0000429 size_t eekLength_;
Shawn Willden274bb552020-09-30 22:39:22 -0600430 EekChain eekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000431 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600432 std::vector<MacedPublicKey> keysToSign_;
433 cppbor::Array cborKeysToSign_;
434};
435
436/**
437 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
438 * content.
439 */
Max Bires126869a2021-02-21 18:32:59 -0800440TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600441 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000442 for (size_t eekLength : {2, 3, 7}) {
443 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
444 generateEek(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600445
David Drysdalecceca9f2021-03-12 15:49:47 +0000446 bytevec keysToSignMac;
447 DeviceInfo deviceInfo;
448 ProtectedData protectedData;
449 auto status = provisionable_->generateCertificateRequest(
450 testMode, {} /* keysToSign */, eekChain_.chain, challenge_, &deviceInfo,
451 &protectedData, &keysToSignMac);
452 ASSERT_TRUE(status.isOk()) << status.getMessage();
453
454 checkProtectedData(testMode, cppbor::Array(), keysToSignMac, protectedData);
455 }
Shawn Willden274bb552020-09-30 22:39:22 -0600456}
457
458/**
459 * Generate an empty certificate request in prod mode. Generation will fail because we don't have a
460 * valid GEEK.
461 *
462 * TODO(swillden): Get a valid GEEK and use it so the generation can succeed, though we won't be
463 * able to decrypt.
464 */
Max Bires126869a2021-02-21 18:32:59 -0800465TEST_P(CertificateRequestTest, EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600466 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000467 for (size_t eekLength : {2, 3, 7}) {
468 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
469 generateEek(eekLength);
470
471 bytevec keysToSignMac;
472 DeviceInfo deviceInfo;
473 ProtectedData protectedData;
474 auto status = provisionable_->generateCertificateRequest(
475 testMode, {} /* keysToSign */, eekChain_.chain, challenge_, &deviceInfo,
476 &protectedData, &keysToSignMac);
477 EXPECT_FALSE(status.isOk());
478 EXPECT_EQ(status.getServiceSpecificError(),
479 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
480 }
Shawn Willden274bb552020-09-30 22:39:22 -0600481}
482
483/**
484 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
485 */
Max Bires126869a2021-02-21 18:32:59 -0800486TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600487 bool testMode = true;
488 generateKeys(testMode, 4 /* numKeys */);
489
David Drysdalecceca9f2021-03-12 15:49:47 +0000490 for (size_t eekLength : {2, 3, 7}) {
491 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
492 generateEek(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600493
David Drysdalecceca9f2021-03-12 15:49:47 +0000494 bytevec keysToSignMac;
495 DeviceInfo deviceInfo;
496 ProtectedData protectedData;
497 auto status = provisionable_->generateCertificateRequest(
498 testMode, keysToSign_, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
499 &keysToSignMac);
500 ASSERT_TRUE(status.isOk()) << status.getMessage();
501
502 checkProtectedData(testMode, cborKeysToSign_, keysToSignMac, protectedData);
503 }
Shawn Willden274bb552020-09-30 22:39:22 -0600504}
505
506/**
507 * Generate a non-empty certificate request in prod mode. Must fail because we don't have a valid
508 * GEEK.
509 *
510 * TODO(swillden): Get a valid GEEK and use it so the generation can succeed, though we won't be
511 * able to decrypt.
512 */
Max Bires126869a2021-02-21 18:32:59 -0800513TEST_P(CertificateRequestTest, NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600514 bool testMode = false;
515 generateKeys(testMode, 4 /* numKeys */);
516
David Drysdalecceca9f2021-03-12 15:49:47 +0000517 for (size_t eekLength : {2, 3, 7}) {
518 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
519 generateEek(eekLength);
520
521 bytevec keysToSignMac;
522 DeviceInfo deviceInfo;
523 ProtectedData protectedData;
524 auto status = provisionable_->generateCertificateRequest(
525 testMode, keysToSign_, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
526 &keysToSignMac);
527 EXPECT_FALSE(status.isOk());
528 EXPECT_EQ(status.getServiceSpecificError(),
529 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
530 }
531}
532
533/**
David Drysdalee99ed862021-03-15 16:43:06 +0000534 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
535 */
536TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
537 bool testMode = true;
538 generateKeys(testMode, 1 /* numKeys */);
539 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
540
541 bytevec keysToSignMac;
542 DeviceInfo deviceInfo;
543 ProtectedData protectedData;
544 auto status = provisionable_->generateCertificateRequest(
545 testMode, {keyWithCorruptMac}, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
546 &keysToSignMac);
547 ASSERT_FALSE(status.isOk()) << status.getMessage();
548 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
549}
550
551/**
552 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
553 */
554TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
555 bool testMode = true;
556 generateKeys(testMode, 1 /* numKeys */);
557 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
558
559 bytevec keysToSignMac;
560 DeviceInfo deviceInfo;
561 ProtectedData protectedData;
562 auto status = provisionable_->generateCertificateRequest(
563 testMode, {keyWithCorruptMac}, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
564 &keysToSignMac);
565 ASSERT_FALSE(status.isOk()) << status.getMessage();
566 auto rc = status.getServiceSpecificError();
567
568 // TODO(drysdale): drop the INVALID_EEK potential error code when a real GEEK is available.
569 EXPECT_TRUE(rc == BnRemotelyProvisionedComponent::STATUS_INVALID_EEK ||
570 rc == BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
571}
572
573/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000574 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
575 * Confirm that the request is rejected.
576 *
577 * TODO(drysdale): Update to use a valid GEEK, so that the test actually confirms that the
578 * implementation is checking signatures.
579 */
580TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
581 bool testMode = false;
582 generateKeys(testMode, 4 /* numKeys */);
583
584 for (size_t ii = 0; ii < eekLength_; ii++) {
585 auto chain = corrupt_sig_chain(eekChain_, ii);
586 ASSERT_TRUE(chain) << chain.message();
587 EekChain corruptEek = chain.moveValue();
588
589 bytevec keysToSignMac;
590 DeviceInfo deviceInfo;
591 ProtectedData protectedData;
592 auto status = provisionable_->generateCertificateRequest(
593 testMode, keysToSign_, corruptEek.chain, challenge_, &deviceInfo, &protectedData,
594 &keysToSignMac);
595 ASSERT_FALSE(status.isOk());
596 ASSERT_EQ(status.getServiceSpecificError(),
597 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
598 }
599}
600
601/**
602 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
603 * Confirm that the request is rejected.
604 *
605 * TODO(drysdale): Update to use a valid GEEK, so that the test actually confirms that the
606 * implementation is checking signatures.
607 */
608TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
609 bool testMode = false;
610 generateKeys(testMode, 4 /* numKeys */);
611
612 // Build an EEK chain that omits the first self-signed cert.
613 auto truncatedChain = cppbor::Array();
614 auto [chain, _, parseErr] = cppbor::parse(eekChain_.chain);
615 ASSERT_TRUE(chain);
616 auto eekChain = chain->asArray();
617 ASSERT_NE(eekChain, nullptr);
618 for (size_t ii = 1; ii < eekChain->size(); ii++) {
619 truncatedChain.add(eekChain->get(ii)->clone());
620 }
621
Shawn Willden274bb552020-09-30 22:39:22 -0600622 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700623 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600624 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000625 auto status = provisionable_->generateCertificateRequest(
626 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
627 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600628 ASSERT_FALSE(status.isOk());
629 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
630}
631
632/**
633 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
634 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
635 */
Max Bires126869a2021-02-21 18:32:59 -0800636TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600637 generateKeys(false /* testMode */, 2 /* numKeys */);
638
639 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700640 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600641 ProtectedData protectedData;
Max Biresfdbb9042021-03-23 12:43:38 -0700642 auto status = provisionable_->generateCertificateRequest(
David Drysdalec8400772021-03-11 12:35:11 +0000643 true /* testMode */, keysToSign_, eekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700644 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600645 ASSERT_FALSE(status.isOk());
646 ASSERT_EQ(status.getServiceSpecificError(),
647 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
648}
649
650/**
651 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
652 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
653 */
Max Bires126869a2021-02-21 18:32:59 -0800654TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600655 generateKeys(true /* testMode */, 2 /* numKeys */);
656
657 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700658 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600659 ProtectedData protectedData;
660 auto status = provisionable_->generateCertificateRequest(
David Drysdalec8400772021-03-11 12:35:11 +0000661 false /* testMode */, keysToSign_, eekChain_.chain, challenge_, &deviceInfo,
662 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600663 ASSERT_FALSE(status.isOk());
664 ASSERT_EQ(status.getServiceSpecificError(),
665 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
666}
667
668INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
669
670} // namespace aidl::android::hardware::security::keymint::test