1 /******************************************************************************
2  *
3  *  Copyright (C) 2018 ST Microelectronics S.A.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *
18  ******************************************************************************/
19 #define LOG_TAG "StEse-SecureElement"
20 #include <android_logmsg.h>
21 
22 #include <stdlib.h>
23 #include <string.h>
24 #include "SecureElement.h"
25 
26 extern bool ese_debug_enabled;
27 static bool OpenLogicalChannelProcessing = false;
28 static bool OpenBasicChannelProcessing = false;
29 
30 namespace android {
31 namespace hardware {
32 namespace secure_element {
33 namespace V1_1 {
34 namespace implementation {
35 
36 sp<V1_1::ISecureElementHalCallback> SecureElement::mCallbackV1_1 = nullptr;
37 sp<V1_0::ISecureElementHalCallback> SecureElement::mCallbackV1_0 = nullptr;
38 
SecureElement()39 SecureElement::SecureElement()
40     : mOpenedchannelCount(0), mOpenedChannels{false, false, false, false} {}
41 
init(const sp<::android::hardware::secure_element::V1_0::ISecureElementHalCallback> & clientCallback)42 Return<void> SecureElement::init(
43     const sp<
44         ::android::hardware::secure_element::V1_0::ISecureElementHalCallback>&
45         clientCallback) {
46   ESESTATUS status = ESESTATUS_SUCCESS;
47   STLOG_HAL_D("%s: Enter", __func__);
48   if (clientCallback == nullptr) {
49     return Void();
50   } else {
51     mCallbackV1_0 = clientCallback;
52     mCallbackV1_1 = nullptr;
53     if (!mCallbackV1_0->linkToDeath(this, 0 /*cookie*/)) {
54       STLOG_HAL_E("%s: Failed to register death notification", __func__);
55     }
56   }
57 
58   if (isSeInitialized()) {
59     clientCallback->onStateChange(true);
60     return Void();
61   }
62 
63   status = seHalInit();
64   if (status != ESESTATUS_SUCCESS) {
65     clientCallback->onStateChange(false);
66     return Void();
67   } else {
68     clientCallback->onStateChange(true);
69     return Void();
70   }
71 }
init_1_1(const sp<::android::hardware::secure_element::V1_1::ISecureElementHalCallback> & clientCallback)72 Return<void> SecureElement::init_1_1(
73     const sp<
74         ::android::hardware::secure_element::V1_1::ISecureElementHalCallback>&
75         clientCallback) {
76   ESESTATUS status = ESESTATUS_SUCCESS;
77   STLOG_HAL_D("%s: Enter", __func__);
78   if (clientCallback == nullptr) {
79     return Void();
80   } else {
81     mCallbackV1_1 = clientCallback;
82     mCallbackV1_0 = nullptr;
83     if (!mCallbackV1_1->linkToDeath(this, 0 /*cookie*/)) {
84       STLOG_HAL_E("%s: Failed to register death notification", __func__);
85     }
86   }
87 
88   if (isSeInitialized()) {
89     clientCallback->onStateChange_1_1(true, "SE already initialized");
90     return Void();
91   }
92 
93   status = seHalInit();
94   if (status != ESESTATUS_SUCCESS) {
95     clientCallback->onStateChange_1_1(false, "SE initialization failed");
96     return Void();
97   } else {
98     clientCallback->onStateChange_1_1(true, "SE initialized");
99     return Void();
100   }
101 }
102 
getAtr(getAtr_cb _hidl_cb)103 Return<void> SecureElement::getAtr(getAtr_cb _hidl_cb) {
104   STLOG_HAL_D("%s: Enter", __func__);
105   hidl_vec<uint8_t> response;
106   uint8_t* ATR;
107   ATR = StEse_getAtr();
108   if (ATR != nullptr) {
109     uint8_t len = *ATR;
110     if (len) {
111       response.resize(len);
112       memcpy(&response[0], ATR, len);
113     }
114   }
115   _hidl_cb(response);
116   return Void();
117 }
118 
isCardPresent()119 Return<bool> SecureElement::isCardPresent() { return true; }
120 
transmit(const hidl_vec<uint8_t> & data,transmit_cb _hidl_cb)121 Return<void> SecureElement::transmit(const hidl_vec<uint8_t>& data,
122                                      transmit_cb _hidl_cb) {
123   ESESTATUS status = ESESTATUS_FAILED;
124   StEse_data cmdApdu;
125   StEse_data rspApdu;
126   memset(&cmdApdu, 0x00, sizeof(StEse_data));
127   memset(&rspApdu, 0x00, sizeof(StEse_data));
128 
129   STLOG_HAL_D("%s: Enter", __func__);
130   cmdApdu.len = data.size();
131   if (cmdApdu.len >= MIN_APDU_LENGTH) {
132     cmdApdu.p_data = (uint8_t*)malloc(data.size() * sizeof(uint8_t));
133     memcpy(cmdApdu.p_data, data.data(), cmdApdu.len);
134     status = StEse_Transceive(&cmdApdu, &rspApdu);
135   }
136 
137   hidl_vec<uint8_t> result;
138   if (status != ESESTATUS_SUCCESS) {
139     STLOG_HAL_E("%s: transmit failed!!!", __func__);
140     seHalResetSe();
141   } else {
142     result.resize(rspApdu.len);
143     memcpy(&result[0], rspApdu.p_data, rspApdu.len);
144   }
145   _hidl_cb(result);
146   free(cmdApdu.p_data);
147   free(rspApdu.p_data);
148   return Void();
149 }
150 
openLogicalChannel(const hidl_vec<uint8_t> & aid,uint8_t p2,openLogicalChannel_cb _hidl_cb)151 Return<void> SecureElement::openLogicalChannel(const hidl_vec<uint8_t>& aid,
152                                                uint8_t p2,
153                                                openLogicalChannel_cb _hidl_cb) {
154   hidl_vec<uint8_t> manageChannelCommand = {0x00, 0x70, 0x00, 0x00, 0x01};
155   OpenLogicalChannelProcessing = true;
156   LogicalChannelResponse resApduBuff;
157   resApduBuff.channelNumber = 0xff;
158   memset(&resApduBuff, 0x00, sizeof(resApduBuff));
159   STLOG_HAL_D("%s: Enter", __func__);
160 
161   if (!isSeInitialized()) {
162     STLOG_HAL_D("%s: Enter SeInitialized", __func__);
163     ESESTATUS status = seHalInit();
164     if (status != ESESTATUS_SUCCESS) {
165       STLOG_HAL_E("%s: seHalInit Failed!!!", __func__);
166       _hidl_cb(resApduBuff, SecureElementStatus::IOERROR);
167       OpenLogicalChannelProcessing = false;
168       return Void();
169     }
170   }
171 
172   SecureElementStatus sestatus = SecureElementStatus::FAILED;
173   ESESTATUS status = ESESTATUS_FAILED;
174   StEse_data cmdApdu;
175   StEse_data rspApdu;
176 
177   memset(&cmdApdu, 0x00, sizeof(StEse_data));
178   memset(&rspApdu, 0x00, sizeof(StEse_data));
179 
180   cmdApdu.len = manageChannelCommand.size();
181   cmdApdu.p_data =
182       (uint8_t*)malloc(manageChannelCommand.size() * sizeof(uint8_t));
183   if (cmdApdu.p_data != NULL) {
184     memcpy(cmdApdu.p_data, manageChannelCommand.data(), cmdApdu.len);
185     status = StEse_Transceive(&cmdApdu, &rspApdu);
186   }
187   if (status != ESESTATUS_SUCCESS) {
188     /*Transceive failed*/
189     sestatus = SecureElementStatus::IOERROR;
190   } else if (rspApdu.p_data[rspApdu.len - 2] == 0x90 &&
191              rspApdu.p_data[rspApdu.len - 1] == 0x00) {
192     /*ManageChannel successful*/
193     resApduBuff.channelNumber = rspApdu.p_data[0];
194     mOpenedchannelCount++;
195     mOpenedChannels[resApduBuff.channelNumber] = true;
196     sestatus = SecureElementStatus::SUCCESS;
197   } else if (rspApdu.p_data[rspApdu.len - 2] == 0x6A &&
198              rspApdu.p_data[rspApdu.len - 1] == 0x81) {
199     sestatus = SecureElementStatus::CHANNEL_NOT_AVAILABLE;
200   } else if (((rspApdu.p_data[rspApdu.len - 2] == 0x6E) ||
201               (rspApdu.p_data[rspApdu.len - 2] == 0x6D)) &&
202              rspApdu.p_data[rspApdu.len - 1] == 0x00) {
203     sestatus = SecureElementStatus::UNSUPPORTED_OPERATION;
204   }
205   /*Free the allocations*/
206   free(cmdApdu.p_data);
207   cmdApdu.p_data = NULL;
208   free(rspApdu.p_data);
209   rspApdu.p_data = NULL;
210   if (sestatus != SecureElementStatus::SUCCESS) {
211     /* if the SE is unresponsive, reset it */
212     if (sestatus == SecureElementStatus::IOERROR) {
213       seHalResetSe();
214     }
215 
216     /*If manageChannel is failed in any of above cases
217     send the callback and return*/
218     _hidl_cb(resApduBuff, sestatus);
219     STLOG_HAL_E("%s: Exit - manage channel failed!!", __func__);
220     OpenLogicalChannelProcessing = false;
221     return Void();
222   }
223 
224   STLOG_HAL_D("%s: Sending selectApdu", __func__);
225   /*Reset variables if manageChannel is success*/
226   sestatus = SecureElementStatus::FAILED;
227   status = ESESTATUS_FAILED;
228 
229   memset(&cmdApdu, 0x00, sizeof(StEse_data));
230   memset(&rspApdu, 0x00, sizeof(StEse_data));
231 
232   cmdApdu.len = (int32_t)(6 + aid.size());
233   cmdApdu.p_data = (uint8_t*)malloc(cmdApdu.len * sizeof(uint8_t));
234   if (cmdApdu.p_data != NULL) {
235     uint8_t xx = 0;
236     cmdApdu.p_data[xx++] = resApduBuff.channelNumber;
237     cmdApdu.p_data[xx++] = 0xA4;        // INS
238     cmdApdu.p_data[xx++] = 0x04;        // P1
239     cmdApdu.p_data[xx++] = p2;          // P2
240     cmdApdu.p_data[xx++] = aid.size();  // Lc
241     memcpy(&cmdApdu.p_data[xx], aid.data(), aid.size());
242     cmdApdu.p_data[xx + aid.size()] = 0x00;  // Le
243     status = StEse_Transceive(&cmdApdu, &rspApdu);
244   }
245 
246   if (status != ESESTATUS_SUCCESS) {
247     /*Transceive failed*/
248     sestatus = SecureElementStatus::IOERROR;
249   } else {
250     uint8_t sw1 = rspApdu.p_data[rspApdu.len - 2];
251     uint8_t sw2 = rspApdu.p_data[rspApdu.len - 1];
252     /*Return response on success, empty vector on failure*/
253     /*Status is success*/
254     if (sw1 == 0x90 && sw2 == 0x00) {
255       /*Copy the response including status word*/
256       resApduBuff.selectResponse.resize(rspApdu.len);
257       memcpy(&resApduBuff.selectResponse[0], rspApdu.p_data, rspApdu.len);
258       sestatus = SecureElementStatus::SUCCESS;
259     }
260     /*AID provided doesn't match any applet on the secure element*/
261     else if (sw1 == 0x6A && sw2 == 0x82) {
262       sestatus = SecureElementStatus::NO_SUCH_ELEMENT_ERROR;
263     }
264     /*Operation provided by the P2 parameter is not permitted by the applet.*/
265     else if (sw1 == 0x6A && sw2 == 0x86) {
266       sestatus = SecureElementStatus::UNSUPPORTED_OPERATION;
267     }
268   }
269 
270   if (sestatus != SecureElementStatus::SUCCESS) {
271     /* if the SE is unresponsive, reset it */
272     if (sestatus == SecureElementStatus::IOERROR) {
273       seHalResetSe();
274     } else {
275       STLOG_HAL_E("%s: Select APDU failed! Close channel..", __func__);
276       SecureElementStatus closeChannelStatus =
277           closeChannel(resApduBuff.channelNumber);
278       if (closeChannelStatus != SecureElementStatus::SUCCESS) {
279         STLOG_HAL_E("%s: closeChannel Failed", __func__);
280       } else {
281         resApduBuff.channelNumber = 0xff;
282       }
283     }
284   }
285   _hidl_cb(resApduBuff, sestatus);
286   free(cmdApdu.p_data);
287   free(rspApdu.p_data);
288   STLOG_HAL_V("%s: Exit", __func__);
289   OpenLogicalChannelProcessing = false;
290   return Void();
291 }
292 
openBasicChannel(const hidl_vec<uint8_t> & aid,uint8_t p2,openBasicChannel_cb _hidl_cb)293 Return<void> SecureElement::openBasicChannel(const hidl_vec<uint8_t>& aid,
294                                              uint8_t p2,
295                                              openBasicChannel_cb _hidl_cb) {
296   hidl_vec<uint8_t> result;
297   OpenBasicChannelProcessing = true;
298   STLOG_HAL_D("%s: Enter", __func__);
299 
300   if (!isSeInitialized()) {
301     ESESTATUS status = seHalInit();
302     if (status != ESESTATUS_SUCCESS) {
303       STLOG_HAL_E("%s: seHalInit Failed!!!", __func__);
304       _hidl_cb(result, SecureElementStatus::IOERROR);
305       OpenBasicChannelProcessing = false;
306       return Void();
307     }
308   }
309 
310   SecureElementStatus sestatus = SecureElementStatus::FAILED;
311   ESESTATUS status = ESESTATUS_FAILED;
312   StEse_data cmdApdu;
313   StEse_data rspApdu;
314 
315   memset(&cmdApdu, 0x00, sizeof(StEse_data));
316   memset(&rspApdu, 0x00, sizeof(StEse_data));
317 
318   cmdApdu.len = (int32_t)(6 + aid.size());
319   cmdApdu.p_data = (uint8_t*)malloc(cmdApdu.len * sizeof(uint8_t));
320   if (cmdApdu.p_data != NULL) {
321     uint8_t xx = 0;
322     cmdApdu.p_data[xx++] = 0x00;        // basic channel
323     cmdApdu.p_data[xx++] = 0xA4;        // INS
324     cmdApdu.p_data[xx++] = 0x04;        // P1
325     cmdApdu.p_data[xx++] = p2;          // P2
326     cmdApdu.p_data[xx++] = aid.size();  // Lc
327     memcpy(&cmdApdu.p_data[xx], aid.data(), aid.size());
328     cmdApdu.p_data[xx + aid.size()] = 0x00;  // Le
329 
330     status = StEse_Transceive(&cmdApdu, &rspApdu);
331   }
332 
333   if (status != ESESTATUS_SUCCESS) {
334     /* Transceive failed */
335     sestatus = SecureElementStatus::IOERROR;
336   } else {
337     uint8_t sw1 = rspApdu.p_data[rspApdu.len - 2];
338     uint8_t sw2 = rspApdu.p_data[rspApdu.len - 1];
339     /*Return response on success, empty vector on failure*/
340     /*Status is success*/
341     if ((sw1 == 0x90) && (sw2 == 0x00)) {
342       /*Copy the response including status word*/
343       result.resize(rspApdu.len);
344       memcpy(&result[0], rspApdu.p_data, rspApdu.len);
345       /*Set basic channel reference if it is not set */
346       if (!mOpenedChannels[0]) {
347         mOpenedChannels[0] = true;
348         mOpenedchannelCount++;
349       }
350       sestatus = SecureElementStatus::SUCCESS;
351     }
352     /*AID provided doesn't match any applet on the secure element*/
353     else if (sw1 == 0x6A && sw2 == 0x82) {
354       sestatus = SecureElementStatus::NO_SUCH_ELEMENT_ERROR;
355     }
356     /*Operation provided by the P2 parameter is not permitted by the applet.*/
357     else if (sw1 == 0x6A && sw2 == 0x86) {
358       sestatus = SecureElementStatus::UNSUPPORTED_OPERATION;
359     }
360   }
361 
362   /* if the SE is unresponsive, reset it */
363   if (sestatus == SecureElementStatus::IOERROR) {
364     seHalResetSe();
365   }
366 
367   if ((sestatus != SecureElementStatus::SUCCESS) && mOpenedChannels[0]) {
368     SecureElementStatus closeChannelStatus =
369         closeChannel(DEFAULT_BASIC_CHANNEL);
370     if (closeChannelStatus != SecureElementStatus::SUCCESS) {
371       STLOG_HAL_E("%s: closeChannel Failed", __func__);
372     }
373   }
374   _hidl_cb(result, sestatus);
375   free(cmdApdu.p_data);
376   free(rspApdu.p_data);
377   STLOG_HAL_V("%s: Exit", __func__);
378   OpenBasicChannelProcessing = false;
379   return Void();
380 }
381 
382 Return<::android::hardware::secure_element::V1_0::SecureElementStatus>
closeChannel(uint8_t channelNumber)383 SecureElement::closeChannel(uint8_t channelNumber) {
384   ESESTATUS status = ESESTATUS_FAILED;
385   SecureElementStatus sestatus = SecureElementStatus::FAILED;
386 
387   StEse_data cmdApdu;
388   StEse_data rspApdu;
389 
390   STLOG_HAL_D("%s: Enter : %d", __func__, channelNumber);
391 
392   if ((channelNumber < DEFAULT_BASIC_CHANNEL) ||
393       (channelNumber >= MAX_LOGICAL_CHANNELS) ||
394       (mOpenedChannels[channelNumber] == false)) {
395     STLOG_HAL_E("%s: invalid channel!!!", __func__);
396     sestatus = SecureElementStatus::FAILED;
397   } else if (channelNumber > DEFAULT_BASIC_CHANNEL) {
398     memset(&cmdApdu, 0x00, sizeof(StEse_data));
399     memset(&rspApdu, 0x00, sizeof(StEse_data));
400     cmdApdu.p_data = (uint8_t*)malloc(5 * sizeof(uint8_t));
401     if (cmdApdu.p_data != NULL) {
402       uint8_t xx = 0;
403 
404       cmdApdu.p_data[xx++] = channelNumber;
405       cmdApdu.p_data[xx++] = 0x70;           // INS
406       cmdApdu.p_data[xx++] = 0x80;           // P1
407       cmdApdu.p_data[xx++] = channelNumber;  // P2
408       cmdApdu.p_data[xx++] = 0x00;           // Lc
409       cmdApdu.len = xx;
410 
411       status = StEse_Transceive(&cmdApdu, &rspApdu);
412     }
413     if (status != ESESTATUS_SUCCESS) {
414       sestatus = SecureElementStatus::FAILED;
415     } else if ((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
416                (rspApdu.p_data[rspApdu.len - 1] == 0x00)) {
417       sestatus = SecureElementStatus::SUCCESS;
418     } else {
419       sestatus = SecureElementStatus::FAILED;
420     }
421     free(cmdApdu.p_data);
422     free(rspApdu.p_data);
423   }
424 
425   if ((channelNumber == DEFAULT_BASIC_CHANNEL) ||
426       (sestatus == SecureElementStatus::SUCCESS)) {
427     STLOG_HAL_D("%s: Closing channel : %d is successful ", __func__,
428                 channelNumber);
429     mOpenedChannels[channelNumber] = false;
430     mOpenedchannelCount--;
431     /*If there are no channels remaining close secureElement*/
432     if ((mOpenedchannelCount == 0) && !OpenLogicalChannelProcessing &&
433         !OpenBasicChannelProcessing) {
434       sestatus = seHalDeInit();
435     } else {
436       sestatus = SecureElementStatus::SUCCESS;
437     }
438   }
439 
440   STLOG_HAL_V("%s: Exit", __func__);
441   return sestatus;
442 }
443 
serviceDied(uint64_t,const wp<IBase> &)444 void SecureElement::serviceDied(uint64_t /*cookie*/, const wp<IBase>& /*who*/) {
445   STLOG_HAL_E("%s: SecureElement serviceDied!!!", __func__);
446   SecureElementStatus sestatus = seHalDeInit();
447   if (sestatus != SecureElementStatus::SUCCESS) {
448     STLOG_HAL_E("%s: seHalDeInit Faliled!!!", __func__);
449   }
450   if (mCallbackV1_1 != nullptr) {
451     mCallbackV1_1->unlinkToDeath(this);
452     mCallbackV1_1 = nullptr;
453   }
454 }
455 
isSeInitialized()456 bool SecureElement::isSeInitialized() { return StEseApi_isOpen(); }
457 
seHalInit()458 ESESTATUS SecureElement::seHalInit() {
459   ESESTATUS status = ESESTATUS_SUCCESS;
460 
461   STLOG_HAL_D("%s: Enter", __func__);
462   status = StEse_init();
463   if (status != ESESTATUS_SUCCESS) {
464     STLOG_HAL_E("%s: SecureElement open failed!!!", __func__);
465   }
466   STLOG_HAL_V("%s: Exit", __func__);
467   return status;
468 }
469 
seHalResetSe()470 void SecureElement::seHalResetSe() {
471   ESESTATUS status = ESESTATUS_SUCCESS;
472 
473   STLOG_HAL_D("%s: Enter", __func__);
474   if (!isSeInitialized()) {
475     ESESTATUS status = seHalInit();
476     if (status != ESESTATUS_SUCCESS) {
477       STLOG_HAL_E("%s: seHalInit Failed!!!", __func__);
478     }
479   }
480 
481   if (status == ESESTATUS_SUCCESS) {
482     mCallbackV1_1->onStateChange_1_1(false, "reset the SE");
483 
484     status = StEse_Reset();
485     if (status != ESESTATUS_SUCCESS) {
486       STLOG_HAL_E("%s: SecureElement reset failed!!", __func__);
487     } else {
488       for (uint8_t xx = 0; xx < MAX_LOGICAL_CHANNELS; xx++) {
489         mOpenedChannels[xx] = false;
490       }
491       mOpenedchannelCount = 0;
492       mCallbackV1_1->onStateChange_1_1(true, "SE initialized");
493     }
494   }
495   STLOG_HAL_V("%s: Exit", __func__);
496 }
497 
498 Return<::android::hardware::secure_element::V1_0::SecureElementStatus>
seHalDeInit()499 SecureElement::seHalDeInit() {
500   STLOG_HAL_D("%s: Enter", __func__);
501   ESESTATUS status = ESESTATUS_SUCCESS;
502   SecureElementStatus sestatus = SecureElementStatus::FAILED;
503   status = StEse_close();
504   if (status != ESESTATUS_SUCCESS) {
505     sestatus = SecureElementStatus::FAILED;
506   } else {
507     sestatus = SecureElementStatus::SUCCESS;
508 
509     for (uint8_t xx = 0; xx < MAX_LOGICAL_CHANNELS; xx++) {
510       mOpenedChannels[xx] = false;
511     }
512     mOpenedchannelCount = 0;
513   }
514   STLOG_HAL_V("%s: Exit", __func__);
515   return sestatus;
516 }
517 
518 }  // namespace implementation
519 }  // namespace V1_1
520 }  // namespace secure_element
521 }  // namespace hardware
522 }  // namespace android
523