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