1 /*
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 "UpdateCredentialTests"
18 
19 #include <aidl/Gtest.h>
20 #include <aidl/Vintf.h>
21 #include <aidl/android/hardware/keymaster/HardwareAuthToken.h>
22 #include <aidl/android/hardware/keymaster/VerificationToken.h>
23 #include <android-base/logging.h>
24 #include <android/hardware/identity/IIdentityCredentialStore.h>
25 #include <android/hardware/identity/support/IdentityCredentialSupport.h>
26 #include <binder/IServiceManager.h>
27 #include <binder/ProcessState.h>
28 #include <cppbor.h>
29 #include <cppbor_parse.h>
30 #include <gtest/gtest.h>
31 #include <future>
32 #include <map>
33 #include <utility>
34 
35 #include "Util.h"
36 
37 namespace android::hardware::identity {
38 
39 using std::endl;
40 using std::make_pair;
41 using std::map;
42 using std::optional;
43 using std::pair;
44 using std::string;
45 using std::tie;
46 using std::vector;
47 
48 using ::android::sp;
49 using ::android::String16;
50 using ::android::binder::Status;
51 
52 using ::android::hardware::keymaster::HardwareAuthToken;
53 using ::android::hardware::keymaster::VerificationToken;
54 
55 class UpdateCredentialTests : public testing::TestWithParam<string> {
56   public:
SetUp()57     virtual void SetUp() override {
58         credentialStore_ = android::waitForDeclaredService<IIdentityCredentialStore>(
59                 String16(GetParam().c_str()));
60         ASSERT_NE(credentialStore_, nullptr);
61         halApiVersion_ = credentialStore_->getInterfaceVersion();
62     }
63 
64     void provisionData();
65 
66     // Set by provisionData
67     vector<uint8_t> credentialData_;
68     vector<uint8_t> credentialPubKey_;
69 
70     sp<IIdentityCredentialStore> credentialStore_;
71     int halApiVersion_;
72 };
73 
provisionData()74 void UpdateCredentialTests::provisionData() {
75     string docType = "org.iso.18013-5.2019.mdl";
76     bool testCredential = true;
77     sp<IWritableIdentityCredential> wc;
78     ASSERT_TRUE(credentialStore_->createCredential(docType, testCredential, &wc).isOk());
79 
80     vector<uint8_t> attestationApplicationId = {};
81     vector<uint8_t> attestationChallenge = {1};
82     vector<Certificate> certChain;
83     ASSERT_TRUE(wc->getAttestationCertificate(attestationApplicationId, attestationChallenge,
84                                               &certChain)
85                         .isOk());
86 
87     optional<vector<uint8_t>> optCredentialPubKey =
88             support::certificateChainGetTopMostKey(certChain[0].encodedCertificate);
89     ASSERT_TRUE(optCredentialPubKey);
90     credentialPubKey_ = optCredentialPubKey.value();
91 
92     size_t proofOfProvisioningSize = 112;
93     // Not in v1 HAL, may fail
94     wc->setExpectedProofOfProvisioningSize(proofOfProvisioningSize);
95 
96     ASSERT_TRUE(wc->startPersonalization(1 /* numAccessControlProfiles */,
97                                          {1} /* numDataElementsPerNamespace */)
98                         .isOk());
99 
100     // Access control profile 0: open access - don't care about the returned SACP
101     SecureAccessControlProfile sacp;
102     ASSERT_TRUE(wc->addAccessControlProfile(1, {}, false, 0, 0, &sacp).isOk());
103 
104     // Single entry - don't care about the returned encrypted data
105     vector<uint8_t> encryptedData;
106     vector<uint8_t> tstrLastName = cppbor::Tstr("Prince").encode();
107     ASSERT_TRUE(wc->beginAddEntry({1}, "ns", "Last name", tstrLastName.size()).isOk());
108     ASSERT_TRUE(wc->addEntryValue(tstrLastName, &encryptedData).isOk());
109 
110     vector<uint8_t> proofOfProvisioningSignature;
111     Status status = wc->finishAddingEntries(&credentialData_, &proofOfProvisioningSignature);
112     EXPECT_TRUE(status.isOk()) << status.exceptionCode() << ": " << status.exceptionMessage();
113 
114     optional<vector<uint8_t>> proofOfProvisioning =
115             support::coseSignGetPayload(proofOfProvisioningSignature);
116     ASSERT_TRUE(proofOfProvisioning);
117     string cborPretty = cppbor::prettyPrint(proofOfProvisioning.value(), 32, {});
118     EXPECT_EQ(
119             "[\n"
120             "  'ProofOfProvisioning',\n"
121             "  'org.iso.18013-5.2019.mdl',\n"
122             "  [\n"
123             "    {\n"
124             "      'id' : 1,\n"
125             "    },\n"
126             "  ],\n"
127             "  {\n"
128             "    'ns' : [\n"
129             "      {\n"
130             "        'name' : 'Last name',\n"
131             "        'value' : 'Prince',\n"
132             "        'accessControlProfiles' : [1, ],\n"
133             "      },\n"
134             "    ],\n"
135             "  },\n"
136             "  true,\n"
137             "]",
138             cborPretty);
139     // Make sure it's signed by the CredentialKey in the returned cert chain.
140     EXPECT_TRUE(support::coseCheckEcDsaSignature(proofOfProvisioningSignature,
141                                                  {},  // Additional data
142                                                  credentialPubKey_));
143 }
144 
TEST_P(UpdateCredentialTests,updateCredential)145 TEST_P(UpdateCredentialTests, updateCredential) {
146     if (halApiVersion_ < 3) {
147         GTEST_SKIP() << "Need HAL API version 3, have " << halApiVersion_;
148     }
149 
150     provisionData();
151 
152     sp<IIdentityCredential> credential;
153     ASSERT_TRUE(credentialStore_
154                         ->getCredential(
155                                 CipherSuite::CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256,
156                                 credentialData_, &credential)
157                         .isOk());
158 
159     sp<IWritableIdentityCredential> wc;
160     ASSERT_TRUE(credential->updateCredential(&wc).isOk());
161 
162     // Getting an attestation cert should fail (because it's an update).
163     vector<uint8_t> attestationApplicationId = {};
164     vector<uint8_t> attestationChallenge = {1};
165     vector<Certificate> certChain;
166     Status result = wc->getAttestationCertificate(attestationApplicationId, attestationChallenge,
167                                                   &certChain);
168     ASSERT_FALSE(result.isOk());
169     EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, result.exceptionCode());
170     EXPECT_EQ(IIdentityCredentialStore::STATUS_FAILED, result.serviceSpecificErrorCode());
171 
172     // Now provision some new data...
173     //
174     size_t proofOfProvisioningSize = 117;
175     // Not in v1 HAL, may fail
176     wc->setExpectedProofOfProvisioningSize(proofOfProvisioningSize);
177 
178     ASSERT_TRUE(wc->startPersonalization(1 /* numAccessControlProfiles */,
179                                          {1} /* numDataElementsPerNamespace */)
180                         .isOk());
181 
182     // Access control profile 0: open access - don't care about the returned SACP
183     SecureAccessControlProfile sacp;
184     ASSERT_TRUE(wc->addAccessControlProfile(2, {}, false, 0, 0, &sacp).isOk());
185 
186     // Single entry - don't care about the returned encrypted data
187     vector<uint8_t> encryptedData;
188     vector<uint8_t> tstrLastName = cppbor::Tstr("T.A.F.K.A.P").encode();
189     ASSERT_TRUE(wc->beginAddEntry({2}, "ns", "Last name", tstrLastName.size()).isOk());
190     ASSERT_TRUE(wc->addEntryValue(tstrLastName, &encryptedData).isOk());
191 
192     vector<uint8_t> proofOfProvisioningSignature;
193     Status status = wc->finishAddingEntries(&credentialData_, &proofOfProvisioningSignature);
194     EXPECT_TRUE(status.isOk()) << status.exceptionCode() << ": " << status.exceptionMessage();
195     optional<vector<uint8_t>> proofOfProvisioning =
196             support::coseSignGetPayload(proofOfProvisioningSignature);
197     ASSERT_TRUE(proofOfProvisioning);
198     string cborPretty = cppbor::prettyPrint(proofOfProvisioning.value(), 32, {});
199     EXPECT_EQ(
200             "[\n"
201             "  'ProofOfProvisioning',\n"
202             "  'org.iso.18013-5.2019.mdl',\n"
203             "  [\n"
204             "    {\n"
205             "      'id' : 2,\n"
206             "    },\n"
207             "  ],\n"
208             "  {\n"
209             "    'ns' : [\n"
210             "      {\n"
211             "        'name' : 'Last name',\n"
212             "        'value' : 'T.A.F.K.A.P',\n"
213             "        'accessControlProfiles' : [2, ],\n"
214             "      },\n"
215             "    ],\n"
216             "  },\n"
217             "  true,\n"
218             "]",
219             cborPretty);
220     // Make sure it's signed by the same CredentialKey we originally provisioned with.
221     EXPECT_TRUE(support::coseCheckEcDsaSignature(proofOfProvisioningSignature,
222                                                  {},  // Additional data
223                                                  credentialPubKey_));
224 }
225 
226 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(UpdateCredentialTests);
227 INSTANTIATE_TEST_SUITE_P(
228         Identity, UpdateCredentialTests,
229         testing::ValuesIn(android::getAidlHalInstanceNames(IIdentityCredentialStore::descriptor)),
230         android::PrintInstanceNameToString);
231 
232 }  // namespace android::hardware::identity
233