1 /*
2  * Copyright (C) 2022 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 #include <aidl/Gtest.h>
18 #include <aidl/Vintf.h>
19 #include <aidl/android/hardware/secure_element/BnSecureElementCallback.h>
20 #include <aidl/android/hardware/secure_element/ISecureElement.h>
21 #include <android-base/logging.h>
22 #include <android/binder_manager.h>
23 #include <android/binder_process.h>
24 #include <gmock/gmock.h>
25 #include <gtest/gtest.h>
26 
27 #include <chrono>
28 #include <condition_variable>
29 #include <mutex>
30 
31 using namespace std::chrono_literals;
32 
33 using aidl::android::hardware::secure_element::BnSecureElementCallback;
34 using aidl::android::hardware::secure_element::ISecureElement;
35 using aidl::android::hardware::secure_element::LogicalChannelResponse;
36 using ndk::ScopedAStatus;
37 using ndk::SharedRefBase;
38 using ndk::SpAIBinder;
39 using testing::ElementsAre;
40 using testing::ElementsAreArray;
41 
42 #define EXPECT_OK(status)                                                \
43     do {                                                                 \
44         auto status_impl = (status);                                     \
45         EXPECT_TRUE(status_impl.isOk()) << status_impl.getDescription(); \
46     } while (false)
47 
48 #define EXPECT_ERR(status)                                                \
49     do {                                                                  \
50         auto status_impl = (status);                                      \
51         EXPECT_FALSE(status_impl.isOk()) << status_impl.getDescription(); \
52     } while (false)
53 
54 // APDU defined in CTS tests.
55 // The applet selected with kSelectableAid will return 256 bytes of data
56 // in response.
57 static const std::vector<uint8_t> kDataApdu = {
58         0x00, 0x08, 0x00, 0x00, 0x00,
59 };
60 
61 // Selectable test AID defined in CTS tests.
62 static const std::vector<uint8_t> kSelectableAid = {
63         0xA0, 0x00, 0x00, 0x04, 0x76, 0x41, 0x6E, 0x64,
64         0x72, 0x6F, 0x69, 0x64, 0x43, 0x54, 0x53, 0x31,
65 };
66 // Non-selectable test AID defined in CTS tests.
67 static const std::vector<uint8_t> kNonSelectableAid = {
68         0xA0, 0x00, 0x00, 0x04, 0x76, 0x41, 0x6E, 0x64,
69         0x72, 0x6F, 0x69, 0x64, 0x43, 0x54, 0x53, 0xFF,
70 };
71 
72 class MySecureElementCallback : public BnSecureElementCallback {
73   public:
onStateChange(bool state,const std::string & debugReason)74     ScopedAStatus onStateChange(bool state, const std::string& debugReason) override {
75         {
76             std::unique_lock<std::mutex> l(m);
77             (void)debugReason;
78             history.push_back(state);
79         }
80         cv.notify_one();
81         return ScopedAStatus::ok();
82     };
83 
expectCallbackHistory(std::vector<bool> && want)84     void expectCallbackHistory(std::vector<bool>&& want) {
85         std::unique_lock<std::mutex> l(m);
86         cv.wait_for(l, 5s, [&]() { return history.size() >= want.size(); });
87         EXPECT_THAT(history, ElementsAreArray(want));
88     }
89 
resetCallbackHistory()90     void resetCallbackHistory() {
91         std::unique_lock<std::mutex> l(m);
92         history.clear();
93     }
94 
95   private:
96     std::mutex m;  // guards history
97     std::condition_variable cv;
98     std::vector<bool> history;
99 };
100 
101 class SecureElementAidl : public ::testing::TestWithParam<std::string> {
102   public:
SetUp()103     void SetUp() override {
104         SpAIBinder binder = SpAIBinder(AServiceManager_waitForService(GetParam().c_str()));
105 
106         secure_element_ = ISecureElement::fromBinder(binder);
107         ASSERT_NE(secure_element_, nullptr);
108 
109         secure_element_callback_ = SharedRefBase::make<MySecureElementCallback>();
110         ASSERT_NE(secure_element_callback_, nullptr);
111 
112         EXPECT_OK(secure_element_->init(secure_element_callback_));
113         secure_element_callback_->expectCallbackHistory({true});
114 
115         // Check if the basic channel is supported by the bound SE.
116         std::vector<uint8_t> basic_channel_response;
117         auto status =
118                 secure_element_->openBasicChannel(kSelectableAid, 0x00, &basic_channel_response);
119         if (status.isOk()) {
120             basic_channel_supported_ = true;
121             secure_element_->closeChannel(0);
122         }
123     }
124 
TearDown()125     void TearDown() override {
126         secure_element_callback_->resetCallbackHistory();
127         EXPECT_OK(secure_element_->reset());
128         secure_element_callback_->expectCallbackHistory({false, true});
129         secure_element_ = nullptr;
130         secure_element_callback_ = nullptr;
131     }
132 
133     // Call transmit with kDataApdu and the selected channel number.
134     // Return the response sstatus code.
transmit(uint8_t channel_number)135     uint16_t transmit(uint8_t channel_number) {
136         std::vector<uint8_t> apdu = kDataApdu;
137         std::vector<uint8_t> response;
138 
139         // Edit the channel number into the CLA header byte.
140         if (channel_number < 4) {
141             apdu[0] |= channel_number;
142         } else {
143             apdu[0] |= (channel_number - 4) | 0x40;
144         }
145 
146         // transmit() will return an empty response with the error
147         // code CHANNEL_NOT_AVAILABLE when the SE cannot be
148         // communicated with.
149         auto status = secure_element_->transmit(apdu, &response);
150         if (!status.isOk()) {
151             return 0x6881;
152         }
153 
154         // transmit() will return a response containing at least
155         // the APDU response status otherwise.
156         EXPECT_GE(response.size(), 2u);
157         uint16_t apdu_status =
158                 (response[response.size() - 2] << 8) | (response[response.size() - 1] << 0);
159 
160         // When the command is successful the response
161         // must contain 256 bytes of data.
162         if (apdu_status == 0x9000) {
163             EXPECT_EQ(response.size(), 258);
164         }
165 
166         return apdu_status;
167     }
168 
169     std::shared_ptr<ISecureElement> secure_element_;
170     std::shared_ptr<MySecureElementCallback> secure_element_callback_;
171     bool basic_channel_supported_{false};
172 };
173 
TEST_P(SecureElementAidl,init)174 TEST_P(SecureElementAidl, init) {
175     // init(nullptr) shall fail.
176     EXPECT_ERR(secure_element_->init(nullptr));
177 
178     // init with a valid callback pointer shall succeed.
179     EXPECT_OK(secure_element_->init(secure_element_callback_));
180     secure_element_callback_->expectCallbackHistory({true, true});
181 }
182 
TEST_P(SecureElementAidl,reset)183 TEST_P(SecureElementAidl, reset) {
184     std::vector<uint8_t> basic_channel_response;
185     LogicalChannelResponse logical_channel_response;
186 
187     // reset called after init shall succeed.
188     if (basic_channel_supported_) {
189         EXPECT_OK(secure_element_->openBasicChannel(kSelectableAid, 0x00, &basic_channel_response));
190     }
191     EXPECT_OK(secure_element_->openLogicalChannel(kSelectableAid, 0x00, &logical_channel_response));
192 
193     EXPECT_OK(secure_element_->reset());
194     secure_element_callback_->expectCallbackHistory({true, false, true});
195 
196     // All opened channels must be closed.
197     if (basic_channel_supported_) {
198         EXPECT_NE(transmit(0), 0x9000);
199     }
200     EXPECT_NE(transmit(logical_channel_response.channelNumber), 0x9000);
201 }
202 
TEST_P(SecureElementAidl,isCardPresent)203 TEST_P(SecureElementAidl, isCardPresent) {
204     bool res = false;
205 
206     // isCardPresent called after init shall succeed.
207     EXPECT_OK(secure_element_->isCardPresent(&res));
208     EXPECT_TRUE(res);
209 }
210 
TEST_P(SecureElementAidl,getAtr)211 TEST_P(SecureElementAidl, getAtr) {
212     std::vector<uint8_t> atr;
213 
214     // getAtr called after init shall succeed.
215     // The ATR has size between 0 and 32 bytes.
216     EXPECT_OK(secure_element_->getAtr(&atr));
217     EXPECT_LE(atr.size(), 32u);
218 }
219 
TEST_P(SecureElementAidl,openBasicChannel)220 TEST_P(SecureElementAidl, openBasicChannel) {
221     std::vector<uint8_t> response;
222 
223     if (!basic_channel_supported_) {
224         return;
225     }
226 
227     // openBasicChannel called with an invalid AID shall fail.
228     EXPECT_ERR(secure_element_->openBasicChannel(kNonSelectableAid, 0x00, &response));
229 
230     // openBasicChannel called after init shall succeed.
231     // The response size must be larger than 2 bytes as it includes the
232     // status code.
233     EXPECT_OK(secure_element_->openBasicChannel(kSelectableAid, 0x00, &response));
234     EXPECT_GE(response.size(), 2u);
235 
236     // transmit called on the basic channel should succeed.
237     EXPECT_EQ(transmit(0), 0x9000);
238 
239     // openBasicChannel called a second time shall fail.
240     // The basic channel can only be opened once.
241     EXPECT_ERR(secure_element_->openBasicChannel(kSelectableAid, 0x00, &response));
242 
243     // openBasicChannel called after closing the basic channel shall succeed.
244     EXPECT_OK(secure_element_->closeChannel(0));
245     EXPECT_OK(secure_element_->openBasicChannel(kSelectableAid, 0x00, &response));
246 }
247 
TEST_P(SecureElementAidl,openLogicalChannel)248 TEST_P(SecureElementAidl, openLogicalChannel) {
249     LogicalChannelResponse response;
250 
251     // openLogicalChannel called with an invalid AID shall fail.
252     EXPECT_ERR(secure_element_->openLogicalChannel(kNonSelectableAid, 0x00, &response));
253 
254     // openLogicalChannel called after init shall succeed.
255     // The response size must be larger than 2 bytes as it includes the
256     // status code. The channel number must be in the range 1-19.
257     EXPECT_OK(secure_element_->openLogicalChannel(kSelectableAid, 0x00, &response));
258     EXPECT_GE(response.selectResponse.size(), 2u);
259     EXPECT_GE(response.channelNumber, 1u);
260     EXPECT_LE(response.channelNumber, 19u);
261 
262     // transmit called on the logical channel should succeed.
263     EXPECT_EQ(transmit(response.channelNumber), 0x9000);
264 }
265 
TEST_P(SecureElementAidl,closeChannel)266 TEST_P(SecureElementAidl, closeChannel) {
267     std::vector<uint8_t> basic_channel_response;
268     LogicalChannelResponse logical_channel_response;
269 
270     // closeChannel called on non-existing basic or logical channel
271     // shall fail.
272     EXPECT_ERR(secure_element_->closeChannel(0));
273     EXPECT_ERR(secure_element_->closeChannel(1));
274 
275     // closeChannel called on basic channel closes the basic channel.
276     if (basic_channel_supported_) {
277         EXPECT_OK(secure_element_->openBasicChannel(kSelectableAid, 0x00, &basic_channel_response));
278         EXPECT_OK(secure_element_->closeChannel(0));
279 
280         // transmit called on the basic channel should fail.
281         EXPECT_NE(transmit(0), 0x9000);
282     }
283 
284     // closeChannel called on logical channel closes the logical channel.
285     EXPECT_OK(secure_element_->openLogicalChannel(kSelectableAid, 0x00, &logical_channel_response));
286     EXPECT_OK(secure_element_->closeChannel(logical_channel_response.channelNumber));
287 
288     // transmit called on the logical channel should fail.
289     EXPECT_NE(transmit(logical_channel_response.channelNumber), 0x9000);
290 }
291 
TEST_P(SecureElementAidl,transmit)292 TEST_P(SecureElementAidl, transmit) {
293     std::vector<uint8_t> response;
294     LogicalChannelResponse logical_channel_response;
295 
296     /* Temporaly disable this check to clarify Basic Channel behavior (b/300502872)
297     // Note: no channel is opened for this test
298     // transmit() will return an empty response with the error
299     // code CHANNEL_NOT_AVAILABLE when the SE cannot be
300     // communicated with.
301     EXPECT_ERR(secure_element_->transmit(kDataApdu, &response));
302     */
303 
304     EXPECT_OK(secure_element_->openLogicalChannel(kSelectableAid, 0x00, &logical_channel_response));
305     EXPECT_GE(logical_channel_response.selectResponse.size(), 2u);
306     EXPECT_GE(logical_channel_response.channelNumber, 1u);
307     EXPECT_LE(logical_channel_response.channelNumber, 19u);
308 
309     // transmit called on the logical channel should succeed.
310     EXPECT_EQ(transmit(logical_channel_response.channelNumber), 0x9000);
311 }
312 
313 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SecureElementAidl);
314 INSTANTIATE_TEST_SUITE_P(
315         SecureElement, SecureElementAidl,
316         testing::ValuesIn(android::getAidlHalInstanceNames(ISecureElement::descriptor)),
317         android::PrintInstanceNameToString);
318 
main(int argc,char ** argv)319 int main(int argc, char** argv) {
320     ::testing::InitGoogleTest(&argc, argv);
321     ABinderProcess_setThreadPoolMaxThreadCount(1);
322     ABinderProcess_startThreadPool();
323     return RUN_ALL_TESTS();
324 }
325