blob: 516be3bddeac609371c3fb65bce707bd9dc42105 [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 Drysdalef6fc5a62021-03-31 16:14:31 +0100373 void checkProtectedData(const DeviceInfo& deviceInfo, const cppbor::Array& keysToSign,
David Drysdalec8400772021-03-11 12:35:11 +0000374 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
David Drysdalef6fc5a62021-03-31 16:14:31 +0100407 auto [deviceInfoMap, __2, deviceInfoErrMsg] = cppbor::parse(deviceInfo.deviceInfo);
408 ASSERT_TRUE(deviceInfoMap) << "Failed to parse deviceInfo: " << deviceInfoErrMsg;
409 ASSERT_TRUE(deviceInfoMap->asMap());
410
David Drysdalec8400772021-03-11 12:35:11 +0000411 auto& signingKey = bccContents->back().pubKey;
David Drysdalef6fc5a62021-03-31 16:14:31 +0100412 auto macKey = verifyAndParseCoseSign1(/* ignore_signature = */ false, signedMac->asArray(),
413 signingKey,
414 cppbor::Array() // SignedMacAad
David Drysdalec8400772021-03-11 12:35:11 +0000415 .add(challenge_)
David Drysdalef6fc5a62021-03-31 16:14:31 +0100416 .add(std::move(deviceInfoMap))
David Drysdalec8400772021-03-11 12:35:11 +0000417 .encode());
418 ASSERT_TRUE(macKey) << macKey.message();
419
420 auto coseMac0 = cppbor::Array()
421 .add(cppbor::Map() // protected
422 .add(ALGORITHM, HMAC_256)
423 .canonicalize()
424 .encode())
425 .add(cppbor::Map()) // unprotected
426 .add(keysToSign.encode()) // payload (keysToSign)
427 .add(keysToSignMac); // tag
428
429 auto macPayload = verifyAndParseCoseMac0(&coseMac0, *macKey);
430 ASSERT_TRUE(macPayload) << macPayload.message();
431 }
432
Shawn Willden274bb552020-09-30 22:39:22 -0600433 bytevec eekId_;
David Drysdalecceca9f2021-03-12 15:49:47 +0000434 size_t eekLength_;
Shawn Willden274bb552020-09-30 22:39:22 -0600435 EekChain eekChain_;
David Drysdalec8400772021-03-11 12:35:11 +0000436 bytevec challenge_;
Shawn Willden274bb552020-09-30 22:39:22 -0600437 std::vector<MacedPublicKey> keysToSign_;
438 cppbor::Array cborKeysToSign_;
439};
440
441/**
442 * Generate an empty certificate request in test mode, and decrypt and verify the structure and
443 * content.
444 */
Max Bires126869a2021-02-21 18:32:59 -0800445TEST_P(CertificateRequestTest, EmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600446 bool testMode = true;
David Drysdalecceca9f2021-03-12 15:49:47 +0000447 for (size_t eekLength : {2, 3, 7}) {
448 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
449 generateEek(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600450
David Drysdalecceca9f2021-03-12 15:49:47 +0000451 bytevec keysToSignMac;
452 DeviceInfo deviceInfo;
453 ProtectedData protectedData;
454 auto status = provisionable_->generateCertificateRequest(
455 testMode, {} /* keysToSign */, eekChain_.chain, challenge_, &deviceInfo,
456 &protectedData, &keysToSignMac);
457 ASSERT_TRUE(status.isOk()) << status.getMessage();
458
David Drysdalef6fc5a62021-03-31 16:14:31 +0100459 checkProtectedData(deviceInfo, cppbor::Array(), keysToSignMac, protectedData);
David Drysdalecceca9f2021-03-12 15:49:47 +0000460 }
Shawn Willden274bb552020-09-30 22:39:22 -0600461}
462
463/**
464 * Generate an empty certificate request in prod mode. Generation will fail because we don't have a
465 * valid GEEK.
466 *
467 * TODO(swillden): Get a valid GEEK and use it so the generation can succeed, though we won't be
468 * able to decrypt.
469 */
Max Bires126869a2021-02-21 18:32:59 -0800470TEST_P(CertificateRequestTest, EmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600471 bool testMode = false;
David Drysdalecceca9f2021-03-12 15:49:47 +0000472 for (size_t eekLength : {2, 3, 7}) {
473 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
474 generateEek(eekLength);
475
476 bytevec keysToSignMac;
477 DeviceInfo deviceInfo;
478 ProtectedData protectedData;
479 auto status = provisionable_->generateCertificateRequest(
480 testMode, {} /* keysToSign */, eekChain_.chain, challenge_, &deviceInfo,
481 &protectedData, &keysToSignMac);
482 EXPECT_FALSE(status.isOk());
483 EXPECT_EQ(status.getServiceSpecificError(),
484 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
485 }
Shawn Willden274bb552020-09-30 22:39:22 -0600486}
487
488/**
489 * Generate a non-empty certificate request in test mode. Decrypt, parse and validate the contents.
490 */
Max Bires126869a2021-02-21 18:32:59 -0800491TEST_P(CertificateRequestTest, NonEmptyRequest_testMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600492 bool testMode = true;
493 generateKeys(testMode, 4 /* numKeys */);
494
David Drysdalecceca9f2021-03-12 15:49:47 +0000495 for (size_t eekLength : {2, 3, 7}) {
496 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
497 generateEek(eekLength);
Shawn Willden274bb552020-09-30 22:39:22 -0600498
David Drysdalecceca9f2021-03-12 15:49:47 +0000499 bytevec keysToSignMac;
500 DeviceInfo deviceInfo;
501 ProtectedData protectedData;
502 auto status = provisionable_->generateCertificateRequest(
503 testMode, keysToSign_, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
504 &keysToSignMac);
505 ASSERT_TRUE(status.isOk()) << status.getMessage();
506
David Drysdalef6fc5a62021-03-31 16:14:31 +0100507 checkProtectedData(deviceInfo, cborKeysToSign_, keysToSignMac, protectedData);
David Drysdalecceca9f2021-03-12 15:49:47 +0000508 }
Shawn Willden274bb552020-09-30 22:39:22 -0600509}
510
511/**
512 * Generate a non-empty certificate request in prod mode. Must fail because we don't have a valid
513 * GEEK.
514 *
515 * TODO(swillden): Get a valid GEEK and use it so the generation can succeed, though we won't be
516 * able to decrypt.
517 */
Max Bires126869a2021-02-21 18:32:59 -0800518TEST_P(CertificateRequestTest, NonEmptyRequest_prodMode) {
Shawn Willden274bb552020-09-30 22:39:22 -0600519 bool testMode = false;
520 generateKeys(testMode, 4 /* numKeys */);
521
David Drysdalecceca9f2021-03-12 15:49:47 +0000522 for (size_t eekLength : {2, 3, 7}) {
523 SCOPED_TRACE(testing::Message() << "EEK of length " << eekLength);
524 generateEek(eekLength);
525
526 bytevec keysToSignMac;
527 DeviceInfo deviceInfo;
528 ProtectedData protectedData;
529 auto status = provisionable_->generateCertificateRequest(
530 testMode, keysToSign_, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
531 &keysToSignMac);
532 EXPECT_FALSE(status.isOk());
533 EXPECT_EQ(status.getServiceSpecificError(),
534 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
535 }
536}
537
538/**
David Drysdalee99ed862021-03-15 16:43:06 +0000539 * Generate a non-empty certificate request in test mode, but with the MAC corrupted on the keypair.
540 */
541TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_testMode) {
542 bool testMode = true;
543 generateKeys(testMode, 1 /* numKeys */);
544 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
545
546 bytevec keysToSignMac;
547 DeviceInfo deviceInfo;
548 ProtectedData protectedData;
549 auto status = provisionable_->generateCertificateRequest(
550 testMode, {keyWithCorruptMac}, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
551 &keysToSignMac);
552 ASSERT_FALSE(status.isOk()) << status.getMessage();
553 EXPECT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
554}
555
556/**
557 * Generate a non-empty certificate request in prod mode, but with the MAC corrupted on the keypair.
558 */
559TEST_P(CertificateRequestTest, NonEmptyRequestCorruptMac_prodMode) {
560 bool testMode = true;
561 generateKeys(testMode, 1 /* numKeys */);
562 MacedPublicKey keyWithCorruptMac = corrupt_maced_key(keysToSign_[0]).moveValue();
563
564 bytevec keysToSignMac;
565 DeviceInfo deviceInfo;
566 ProtectedData protectedData;
567 auto status = provisionable_->generateCertificateRequest(
568 testMode, {keyWithCorruptMac}, eekChain_.chain, challenge_, &deviceInfo, &protectedData,
569 &keysToSignMac);
570 ASSERT_FALSE(status.isOk()) << status.getMessage();
571 auto rc = status.getServiceSpecificError();
572
573 // TODO(drysdale): drop the INVALID_EEK potential error code when a real GEEK is available.
574 EXPECT_TRUE(rc == BnRemotelyProvisionedComponent::STATUS_INVALID_EEK ||
575 rc == BnRemotelyProvisionedComponent::STATUS_INVALID_MAC);
576}
577
578/**
David Drysdalecceca9f2021-03-12 15:49:47 +0000579 * Generate a non-empty certificate request in prod mode that has a corrupt EEK chain.
580 * Confirm that the request is rejected.
581 *
582 * TODO(drysdale): Update to use a valid GEEK, so that the test actually confirms that the
583 * implementation is checking signatures.
584 */
585TEST_P(CertificateRequestTest, NonEmptyCorruptEekRequest_prodMode) {
586 bool testMode = false;
587 generateKeys(testMode, 4 /* numKeys */);
588
589 for (size_t ii = 0; ii < eekLength_; ii++) {
590 auto chain = corrupt_sig_chain(eekChain_, ii);
591 ASSERT_TRUE(chain) << chain.message();
592 EekChain corruptEek = chain.moveValue();
593
594 bytevec keysToSignMac;
595 DeviceInfo deviceInfo;
596 ProtectedData protectedData;
597 auto status = provisionable_->generateCertificateRequest(
598 testMode, keysToSign_, corruptEek.chain, challenge_, &deviceInfo, &protectedData,
599 &keysToSignMac);
600 ASSERT_FALSE(status.isOk());
601 ASSERT_EQ(status.getServiceSpecificError(),
602 BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
603 }
604}
605
606/**
607 * Generate a non-empty certificate request in prod mode that has an incomplete EEK chain.
608 * Confirm that the request is rejected.
609 *
610 * TODO(drysdale): Update to use a valid GEEK, so that the test actually confirms that the
611 * implementation is checking signatures.
612 */
613TEST_P(CertificateRequestTest, NonEmptyIncompleteEekRequest_prodMode) {
614 bool testMode = false;
615 generateKeys(testMode, 4 /* numKeys */);
616
617 // Build an EEK chain that omits the first self-signed cert.
618 auto truncatedChain = cppbor::Array();
619 auto [chain, _, parseErr] = cppbor::parse(eekChain_.chain);
620 ASSERT_TRUE(chain);
621 auto eekChain = chain->asArray();
622 ASSERT_NE(eekChain, nullptr);
623 for (size_t ii = 1; ii < eekChain->size(); ii++) {
624 truncatedChain.add(eekChain->get(ii)->clone());
625 }
626
Shawn Willden274bb552020-09-30 22:39:22 -0600627 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700628 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600629 ProtectedData protectedData;
David Drysdalecceca9f2021-03-12 15:49:47 +0000630 auto status = provisionable_->generateCertificateRequest(
631 testMode, keysToSign_, truncatedChain.encode(), challenge_, &deviceInfo, &protectedData,
632 &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600633 ASSERT_FALSE(status.isOk());
634 ASSERT_EQ(status.getServiceSpecificError(), BnRemotelyProvisionedComponent::STATUS_INVALID_EEK);
635}
636
637/**
638 * Generate a non-empty certificate request in test mode, with prod keys. Must fail with
639 * STATUS_PRODUCTION_KEY_IN_TEST_REQUEST.
640 */
Max Bires126869a2021-02-21 18:32:59 -0800641TEST_P(CertificateRequestTest, NonEmptyRequest_prodKeyInTestCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600642 generateKeys(false /* testMode */, 2 /* numKeys */);
643
644 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700645 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600646 ProtectedData protectedData;
Max Biresfdbb9042021-03-23 12:43:38 -0700647 auto status = provisionable_->generateCertificateRequest(
David Drysdalec8400772021-03-11 12:35:11 +0000648 true /* testMode */, keysToSign_, eekChain_.chain, challenge_, &deviceInfo,
Max Biresfdbb9042021-03-23 12:43:38 -0700649 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600650 ASSERT_FALSE(status.isOk());
651 ASSERT_EQ(status.getServiceSpecificError(),
652 BnRemotelyProvisionedComponent::STATUS_PRODUCTION_KEY_IN_TEST_REQUEST);
653}
654
655/**
656 * Generate a non-empty certificate request in prod mode, with test keys. Must fail with
657 * STATUS_TEST_KEY_IN_PRODUCTION_REQUEST.
658 */
Max Bires126869a2021-02-21 18:32:59 -0800659TEST_P(CertificateRequestTest, NonEmptyRequest_testKeyInProdCert) {
Shawn Willden274bb552020-09-30 22:39:22 -0600660 generateKeys(true /* testMode */, 2 /* numKeys */);
661
662 bytevec keysToSignMac;
Max Biresfdbb9042021-03-23 12:43:38 -0700663 DeviceInfo deviceInfo;
Shawn Willden274bb552020-09-30 22:39:22 -0600664 ProtectedData protectedData;
665 auto status = provisionable_->generateCertificateRequest(
David Drysdalec8400772021-03-11 12:35:11 +0000666 false /* testMode */, keysToSign_, eekChain_.chain, challenge_, &deviceInfo,
667 &protectedData, &keysToSignMac);
Shawn Willden274bb552020-09-30 22:39:22 -0600668 ASSERT_FALSE(status.isOk());
669 ASSERT_EQ(status.getServiceSpecificError(),
670 BnRemotelyProvisionedComponent::STATUS_TEST_KEY_IN_PRODUCTION_REQUEST);
671}
672
673INSTANTIATE_REM_PROV_AIDL_TEST(CertificateRequestTest);
674
675} // namespace aidl::android::hardware::security::keymint::test