1 /*****************************************************************************
2  * Copyright ©2017-2023 Gemalto – a Thales Company. All rights Reserved.
3  *
4  * This copy is 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  *     http://www.apache.org/licenses/LICENSE-2.0 or https://www.apache.org/licenses/LICENSE-2.0.html
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10  * See the License for the specific language governing permissions and limitations under the License.
11 
12  ****************************************************************************/
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <ctype.h>
17 #include <inttypes.h>
18 #include <errno.h>
19 #include <getopt.h>
20 #include <libgen.h>
21 #include <signal.h>
22 #include <limits.h>
23 #include <log/log.h>
24 #include <android-base/properties.h>
25 #include <dlfcn.h>
26 
27 #include "se-gto/libse-gto.h"
28 #include "SecureElement.h"
29 
30 #if defined(ST_LIB_32)
31 #define VENDOR_LIB_PATH "/vendor/lib/"
32 #else
33 #define VENDOR_LIB_PATH "/vendor/lib64/"
34 #endif
35 #define VENDOR_LIB_EXT ".so"
36 
37 namespace se {
38 
39 #ifndef MAX_CHANNELS
40 #define MAX_CHANNELS 0x04
41 #endif
42 
43 #ifndef BASIC_CHANNEL
44 #define BASIC_CHANNEL 0x00
45 #endif
46 
47 #ifndef LOG_HAL_LEVEL
48 #define LOG_HAL_LEVEL 4
49 #endif
50 
51 #ifndef SUCCESS
52 #define SUCCESS 0
53 #endif
54 
55 #ifndef MAX_AID_LEN
56 #define MAX_AID_LEN 16
57 #endif
58 
59 uint8_t getResponse[5] = {0x00, 0xC0, 0x00, 0x00, 0x00};
60 static struct se_gto_ctx *ctx;
61 bool debug_log_enabled = false;
62 
SecureElement(const char * ese_name)63 SecureElement::SecureElement(const char* ese_name){
64     nbrOpenChannel = 0;
65     ctx = NULL;
66 
67     strncpy(ese_flag_name, ese_name, 4);
68     if (strncmp(ese_flag_name, "eSE2", 4) == 0) {
69         strncpy(config_filename, "/vendor/etc/libse-gto-hal2.conf", 31);
70     } else {
71         strncpy(config_filename, "/vendor/etc/libse-gto-hal.conf", 30);
72     }
73 }
74 
resetSE()75 int SecureElement::resetSE(){
76     int n;
77 
78     isBasicChannelOpen = false;
79     nbrOpenChannel = 0;
80 
81     ALOGD("SecureElement:%s se_gto_reset start", __func__);
82     n = se_gto_reset(ctx, atr, sizeof(atr));
83     if (n >= 0) {
84         atr_size = n;
85         ALOGD("SecureElement:%s received ATR of %d bytes\n", __func__, n);
86         dump_bytes("ATR: ", ':',  atr, n, stdout);
87     } else {
88         ALOGE("SecureElement:%s Failed to reset and get ATR: %s\n", __func__, strerror(errno));
89     }
90 
91     return n;
92 }
93 
initializeSE()94 int SecureElement::initializeSE() {
95 
96     int n;
97     int ret = 0;
98 
99     ALOGD("SecureElement:%s start", __func__);
100 
101     if (checkSeUp) {
102         ALOGD("SecureElement:%s Already initialized", __func__);
103         ALOGD("SecureElement:%s end", __func__);
104         return EXIT_SUCCESS;
105     }
106 
107     if (se_gto_new(&ctx) < 0) {
108         ALOGE("SecureElement:%s se_gto_new FATAL:%s", __func__,strerror(errno));
109 
110         return EXIT_FAILURE;
111     }
112     se_gto_set_log_level(ctx, 3);
113 
114     openConfigFile(1);
115 
116     if (se_gto_open(ctx) < 0) {
117         ALOGE("SecureElement:%s se_gto_open FATAL:%s", __func__,strerror(errno));
118         return EXIT_FAILURE;
119     }
120 
121     ret = resetSE();
122 
123     if (ret < 0 && (strncmp(ese_flag_name, "eSE2", 4) == 0)) {
124         sleep(6);
125         ALOGE("SecureElement:%s retry resetSE", __func__);
126         ret = resetSE();
127     }
128     if (ret < 0) {
129         se_gto_close(ctx);
130         ctx = NULL;
131         return EXIT_FAILURE;
132     }
133 
134     checkSeUp = true;
135 
136     ALOGD("SecureElement:%s end", __func__);
137     return EXIT_SUCCESS;
138 }
139 
init(const std::shared_ptr<ISecureElementCallback> & clientCallback)140 ScopedAStatus SecureElement::init(const std::shared_ptr<ISecureElementCallback>& clientCallback) {
141 
142     ALOGD("SecureElement:%s start", __func__);
143     if (clientCallback == nullptr) {
144         ALOGE("SecureElement:%s clientCallback == nullptr", __func__);
145         return ScopedAStatus::fromExceptionCode(EX_NULL_POINTER);
146     } else {
147         internalClientCallback = clientCallback;
148     }
149 
150     if (initializeSE() != EXIT_SUCCESS) {
151         ALOGE("SecureElement:%s initializeSE Failed", __func__);
152         notify(false, "SE Initialized failed");
153     } else {
154         ALOGD("SecureElement:%s initializeSE Success", __func__);
155         notify(true, "SE Initialized");
156     }
157 
158     ALOGD("SecureElement:%s end", __func__);
159 
160     return ScopedAStatus::ok();
161 }
162 
getAtr(std::vector<uint8_t> * aidl_return)163 ScopedAStatus SecureElement::getAtr(std::vector<uint8_t>* aidl_return) {
164     std::vector<uint8_t> response;
165     response.resize(atr_size);
166     memcpy(&response[0], atr, atr_size);
167     *aidl_return = response;
168     return ScopedAStatus::ok();
169 }
170 
isCardPresent(bool * aidl_return)171 ScopedAStatus SecureElement::isCardPresent(bool* aidl_return) {
172     *aidl_return = true;
173     return ScopedAStatus::ok();
174 }
175 
transmit(const std::vector<uint8_t> & data,std::vector<uint8_t> * aidl_return)176 ScopedAStatus SecureElement::transmit(const std::vector<uint8_t>& data, std::vector<uint8_t>* aidl_return) {
177 
178     uint8_t *apdu;
179     uint8_t *resp;
180     int apdu_len = data.size();
181     int resp_len = 0;
182     ScopedAStatus status = ScopedAStatus::fromServiceSpecificError(FAILED);
183 
184     apdu = (uint8_t*)malloc(apdu_len * sizeof(uint8_t));
185     resp = (uint8_t*)malloc(65536 * sizeof(uint8_t));
186 
187     std::vector<uint8_t> result;
188 
189     if (checkSeUp && nbrOpenChannel != 0) {
190         if (apdu != NULL) {
191             memcpy(apdu, data.data(), data.size());
192             dump_bytes("CMD: ", ':', apdu, apdu_len, stdout);
193             resp_len = se_gto_apdu_transmit(ctx, apdu, apdu_len, resp, 65536);
194         }
195 
196         if (resp_len < 0) {
197             ALOGE("SecureElement:%s: transmit failed", __func__);
198             if (deinitializeSE() != SUCCESS) {
199                 ALOGE("SecureElement:%s deinitializeSE Failed", __func__);
200             }
201         } else {
202             dump_bytes("RESP: ", ':', resp, resp_len, stdout);
203             result.resize(resp_len);
204             memcpy(&result[0], resp, resp_len);
205         }
206         status = ScopedAStatus::ok();
207     } else {
208         ALOGE("SecureElement:%s: transmit failed! No channel is open", __func__);
209         status = ScopedAStatus::fromServiceSpecificError(CHANNEL_NOT_AVAILABLE);
210     }
211     aidl_return->assign(result.begin(), result.end());
212     if(apdu) free(apdu);
213     if(resp) free(resp);
214     return status;
215 }
216 
openLogicalChannel(const std::vector<uint8_t> & aid,int8_t p2,::aidl::android::hardware::secure_element::LogicalChannelResponse * aidl_return)217 ScopedAStatus SecureElement::openLogicalChannel(const std::vector<uint8_t>& aid, int8_t p2, ::aidl::android::hardware::secure_element::LogicalChannelResponse* aidl_return) {
218     ALOGD("SecureElement:%s start", __func__);
219 
220     std::vector<uint8_t> resApduBuff;
221     size_t channelNumber = 0xff;
222     memset(&resApduBuff, 0x00, sizeof(resApduBuff));
223 
224     if (internalClientCallback == nullptr) {
225         return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
226     }
227 
228     if (!checkSeUp) {
229         if (initializeSE() != EXIT_SUCCESS) {
230             ALOGE("SecureElement:%s: Failed to re-initialise the eSE HAL", __func__);
231             notify(false, "SE Initialized failed");
232             return ScopedAStatus::fromServiceSpecificError(IOERROR);
233         }
234     }
235 
236     if (aid.size() > MAX_AID_LEN) {
237         ALOGE("SecureElement:%s: Bad AID size", __func__);
238         return ScopedAStatus::fromServiceSpecificError(FAILED);
239     }
240 
241     int mSecureElementStatus = IOERROR;
242 
243     uint8_t *apdu; //65536
244     int apdu_len = 0;
245     uint8_t *resp;
246     int resp_len = 0;
247     uint8_t index = 0;
248     int getResponseOffset = 0;
249 
250     apdu_len = 5;
251     apdu = (uint8_t*)malloc(apdu_len * sizeof(uint8_t));
252     resp = (uint8_t*)malloc(65536 * sizeof(uint8_t));
253 
254     if (apdu != NULL && resp!=NULL) {
255         index = 0;
256         apdu[index++] = 0x00;
257         apdu[index++] = 0x70;
258         apdu[index++] = 0x00;
259         apdu[index++] = 0x00;
260         apdu[index++] = 0x01;
261 
262         dump_bytes("CMD: ", ':', apdu, apdu_len, stdout);
263 
264         resp_len = se_gto_apdu_transmit(ctx, apdu, apdu_len, resp, 65536);
265         ALOGD("SecureElement:%s Manage channel resp_len = %d", __func__,resp_len);
266     }
267 
268     if (resp_len >= 0)
269         dump_bytes("RESP: ", ':', resp, resp_len, stdout);
270 
271 
272     if (resp_len < 0) {
273         if (deinitializeSE() != SUCCESS) {
274              ALOGE("SecureElement:%s deinitializeSE Failed", __func__);
275         }
276         mSecureElementStatus = IOERROR;
277         ALOGD("SecureElement:%s Free memory after manage channel after ERROR", __func__);
278         if(apdu) free(apdu);
279         if(resp) free(resp);
280         return ScopedAStatus::fromServiceSpecificError(mSecureElementStatus);
281     } else if (resp[resp_len - 2] == 0x90 && resp[resp_len - 1] == 0x00) {
282         channelNumber = resp[0];
283         nbrOpenChannel++;
284         mSecureElementStatus = SUCCESS;
285     } else {
286         if (resp[resp_len - 2] == 0x6A && resp[resp_len - 1] == 0x81) {
287             mSecureElementStatus = CHANNEL_NOT_AVAILABLE;
288         }else if (resp[resp_len - 2] == 0x68 && resp[resp_len - 1] == 0x81) {
289             mSecureElementStatus = CHANNEL_NOT_AVAILABLE;
290         } else {
291             mSecureElementStatus = IOERROR;
292         }
293         ALOGD("SecureElement:%s Free memory after manage channel after ERROR", __func__);
294         if(apdu) free(apdu);
295         if(resp) free(resp);
296         return ScopedAStatus::fromServiceSpecificError(mSecureElementStatus);
297     }
298 
299     if(apdu) free(apdu);
300     if(resp) free(resp);
301     ALOGD("SecureElement:%s Free memory after manage channel", __func__);
302     ALOGD("SecureElement:%s mSecureElementStatus = %d", __func__, (int)mSecureElementStatus);
303 
304     /*Start Sending select command after Manage Channel is successful.*/
305     ALOGD("SecureElement:%s Sending selectApdu", __func__);
306 
307     mSecureElementStatus = IOERROR;
308 
309     apdu_len = (int32_t)(6 + aid.size());
310     resp_len = 0;
311     apdu = (uint8_t*)malloc(apdu_len * sizeof(uint8_t));
312     resp = (uint8_t*)malloc(65536 * sizeof(uint8_t));
313 
314     if (apdu != NULL && resp!=NULL) {
315         index = 0;
316         apdu[index++] = channelNumber;
317         apdu[index++] = 0xA4;
318         apdu[index++] = 0x04;
319         apdu[index++] = p2;
320         apdu[index++] = aid.size();
321         memcpy(&apdu[index], aid.data(), aid.size());
322         index += aid.size();
323         apdu[index] = 0x00;
324 
325 send_logical:
326         dump_bytes("CMD: ", ':', apdu, apdu_len, stdout);
327         resp_len = se_gto_apdu_transmit(ctx, apdu, apdu_len, resp, 65536);
328         ALOGD("SecureElement:%s selectApdu resp_len = %d", __func__,resp_len);
329     }
330 
331     if (resp_len < 0) {
332         ALOGE("SecureElement:%s selectApdu resp_len = %d", __func__,resp_len);
333         if (deinitializeSE() != SUCCESS) {
334              ALOGE("SecureElement:%s deinitializeSE Failed", __func__);
335         }
336         mSecureElementStatus = IOERROR;
337     } else {
338         dump_bytes("RESP: ", ':', resp, resp_len, stdout);
339 
340         if (resp[resp_len - 2] == 0x90 || resp[resp_len - 2] == 0x62 || resp[resp_len - 2] == 0x63) {
341             resApduBuff.resize(getResponseOffset + resp_len);
342             memcpy(&resApduBuff[getResponseOffset], resp, resp_len);
343             mSecureElementStatus = SUCCESS;
344         }
345         else if (resp[resp_len - 2] == 0x61) {
346             resApduBuff.resize(getResponseOffset + resp_len - 2);
347             memcpy(&resApduBuff[getResponseOffset], resp, resp_len - 2);
348             getResponseOffset += (resp_len - 2);
349             getResponse[4] = resp[resp_len - 1];
350             getResponse[0] = apdu[0];
351             dump_bytes("getResponse CMD: ", ':', getResponse, 5, stdout);
352             free(apdu);
353             apdu_len = 5;
354             apdu = (uint8_t*)malloc(apdu_len * sizeof(uint8_t));
355             memset(resp, 0, resp_len);
356             memcpy(apdu, getResponse, apdu_len);
357             apdu[0] = channelNumber;
358             goto send_logical;
359         }
360         else if (resp[resp_len - 2] == 0x6C) {
361             resApduBuff.resize(getResponseOffset + resp_len - 2);
362             memcpy(&resApduBuff[getResponseOffset], resp, resp_len - 2);
363             getResponseOffset += (resp_len - 2);
364             apdu[4] = resp[resp_len - 1];
365             dump_bytes("case2 getResponse CMD: ", ':', apdu, 5, stdout);
366             memset(resp, 0, resp_len);
367             goto send_logical;
368         }
369         else if (resp[resp_len - 2] == 0x6A && resp[resp_len - 1] == 0x80) {
370             mSecureElementStatus = IOERROR;
371         }
372         else if (resp[resp_len - 2] == 0x6A && resp[resp_len - 1] == 0x81) {
373             mSecureElementStatus = IOERROR;
374         }
375         else if (resp[resp_len - 2] == 0x6A && resp[resp_len - 1] == 0x82) {
376             mSecureElementStatus = NO_SUCH_ELEMENT_ERROR;
377         }
378         else if (resp[resp_len - 2] == 0x6A && resp[resp_len - 1] == 0x86) {
379             mSecureElementStatus = UNSUPPORTED_OPERATION;
380         }
381         else if (resp[resp_len - 2] == 0x6A && resp[resp_len - 1] == 0x87) {
382             mSecureElementStatus = UNSUPPORTED_OPERATION;
383         }
384     }
385 
386     /*Check if SELECT command failed, close oppened channel*/
387     if (mSecureElementStatus != SUCCESS) {
388         closeChannel(channelNumber);
389     }
390 
391     ALOGD("SecureElement:%s mSecureElementStatus = %d", __func__, (int)mSecureElementStatus);
392     *aidl_return = LogicalChannelResponse{
393         .channelNumber = static_cast<int8_t>(channelNumber),
394         .selectResponse = resApduBuff,
395     };
396 
397     ALOGD("SecureElement:%s Free memory after selectApdu", __func__);
398     if(apdu) free(apdu);
399     if(resp) free(resp);
400 
401     if(mSecureElementStatus != SUCCESS) return ScopedAStatus::fromServiceSpecificError(mSecureElementStatus);
402     else return ScopedAStatus::ok();
403 }
404 
openBasicChannel(const std::vector<uint8_t> & aid,int8_t p2,std::vector<uint8_t> * aidl_return)405 ScopedAStatus SecureElement::openBasicChannel(const std::vector<uint8_t>& aid, int8_t p2, std::vector<uint8_t>* aidl_return) {
406     std::vector<uint8_t> result;
407 
408     int mSecureElementStatus = IOERROR;
409 
410     uint8_t *apdu; //65536
411     int apdu_len = 0;
412     uint8_t *resp;
413     int resp_len = 0;
414     int getResponseOffset = 0;
415     uint8_t index = 0;
416 
417     if (internalClientCallback == nullptr) {
418         return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
419     }
420     if (isBasicChannelOpen) {
421         ALOGE("SecureElement:%s: Basic Channel already open", __func__);
422         return ScopedAStatus::fromServiceSpecificError(CHANNEL_NOT_AVAILABLE);
423     }
424 
425     if (!checkSeUp) {
426         if (initializeSE() != EXIT_SUCCESS) {
427             ALOGE("SecureElement:%s: Failed to re-initialise the eSE HAL", __func__);
428             notify(false, "SE Initialized failed");
429             return ScopedAStatus::fromServiceSpecificError(IOERROR);
430         }
431     }
432 
433     if (aid.size() > MAX_AID_LEN) {
434         ALOGE("SecureElement:%s: Bad AID size", __func__);
435         return ScopedAStatus::fromServiceSpecificError(FAILED);
436     }
437 
438     apdu_len = (int32_t)(6 + aid.size());
439     resp_len = 0;
440     apdu = (uint8_t*)malloc(apdu_len * sizeof(uint8_t));
441     resp = (uint8_t*)malloc(65536 * sizeof(uint8_t));
442 
443 
444     if (apdu != NULL) {
445         index = 0;
446         apdu[index++] = 0x00;
447         apdu[index++] = 0xA4;
448         apdu[index++] = 0x04;
449         apdu[index++] = p2;
450         apdu[index++] = aid.size();
451         memcpy(&apdu[index], aid.data(), aid.size());
452         index += aid.size();
453         apdu[index] = 0x00;
454 
455 send_basic:
456         dump_bytes("CMD: ", ':', apdu, apdu_len, stdout);
457         resp_len = se_gto_apdu_transmit(ctx, apdu, apdu_len, resp, 65536);
458         ALOGD("SecureElement:%s selectApdu resp_len = %d", __func__,resp_len);
459     }
460 
461     if (resp_len < 0) {
462         if (deinitializeSE() != SUCCESS) {
463              ALOGE("SecureElement:%s deinitializeSE Failed", __func__);
464         }
465         mSecureElementStatus = IOERROR;
466     } else {
467         dump_bytes("RESP: ", ':', resp, resp_len, stdout);
468 
469         if (resp[resp_len - 2] == 0x90 || resp[resp_len - 2] == 0x62 || resp[resp_len - 2] == 0x63) {
470             result.resize(getResponseOffset + resp_len);
471             memcpy(&result[getResponseOffset], resp, resp_len);
472 
473             isBasicChannelOpen = true;
474             nbrOpenChannel++;
475             mSecureElementStatus = SUCCESS;
476         }
477         else if (resp[resp_len - 2] == 0x61) {
478             result.resize(getResponseOffset + resp_len - 2);
479             memcpy(&result[getResponseOffset], resp, resp_len - 2);
480             getResponseOffset += (resp_len - 2);
481             getResponse[4] = resp[resp_len - 1];
482             getResponse[0] = apdu[0];
483             dump_bytes("getResponse CMD: ", ':', getResponse, 5, stdout);
484             free(apdu);
485             apdu_len = 5;
486             apdu = (uint8_t*)malloc(apdu_len * sizeof(uint8_t));
487             memset(resp, 0, resp_len);
488             memcpy(apdu, getResponse, apdu_len);
489             goto send_basic;
490         }
491         else if (resp[resp_len - 2] == 0x6C) {
492             result.resize(getResponseOffset + resp_len - 2);
493             memcpy(&result[getResponseOffset], resp, resp_len - 2);
494             getResponseOffset += (resp_len - 2);
495             apdu[4] = resp[resp_len - 1];
496             dump_bytes("case2 getResponse CMD: ", ':', apdu, 5, stdout);
497             apdu_len = 5;
498             memset(resp, 0, resp_len);
499             goto send_basic;
500         }
501         else if (resp[resp_len - 2] == 0x68 && resp[resp_len - 1] == 0x81) {
502             mSecureElementStatus = CHANNEL_NOT_AVAILABLE;
503         }
504         else if (resp[resp_len - 2] == 0x6A && resp[resp_len - 1] == 0x81) {
505             mSecureElementStatus = CHANNEL_NOT_AVAILABLE;
506         }
507     }
508 
509     if ((mSecureElementStatus != SUCCESS) && isBasicChannelOpen) {
510       closeChannel(BASIC_CHANNEL);
511     }
512 
513     ALOGD("SecureElement:%s mSecureElementStatus = %d", __func__, (int)mSecureElementStatus);
514     *aidl_return = result;
515 
516     ALOGD("SecureElement:%s Free memory after openBasicChannel", __func__);
517     if(apdu) free(apdu);
518     if(resp) free(resp);
519     if(mSecureElementStatus != SUCCESS) return ScopedAStatus::fromServiceSpecificError(mSecureElementStatus);
520     else return ScopedAStatus::ok();
521 }
522 
closeChannel(int8_t channelNumber)523 ScopedAStatus SecureElement::closeChannel(int8_t channelNumber) {
524     ALOGD("SecureElement:%s start", __func__);
525     int mSecureElementStatus = FAILED;
526 
527     uint8_t *apdu; //65536
528     int apdu_len = 10;
529     uint8_t *resp;
530     int resp_len = 0;
531 
532     if (!checkSeUp) {
533         ALOGE("SecureElement:%s cannot closeChannel, HAL is deinitialized", __func__);
534         mSecureElementStatus = FAILED;
535         ALOGD("SecureElement:%s end", __func__);
536         return ScopedAStatus::fromServiceSpecificError(mSecureElementStatus);
537     }
538 
539     if ((channelNumber < 0) || (channelNumber >= MAX_CHANNELS)) {
540         ALOGE("SecureElement:%s Channel not supported", __func__);
541         mSecureElementStatus = FAILED;
542     } else if (channelNumber == 0) {
543         isBasicChannelOpen = false;
544         mSecureElementStatus = SUCCESS;
545         nbrOpenChannel--;
546     } else {
547         apdu = (uint8_t*)malloc(apdu_len * sizeof(uint8_t));
548         resp = (uint8_t*)malloc(65536 * sizeof(uint8_t));
549 
550         if (apdu != NULL) {
551             uint8_t index = 0;
552 
553             apdu[index++] = channelNumber;
554             apdu[index++] = 0x70;
555             apdu[index++] = 0x80;
556             apdu[index++] = channelNumber;
557             apdu[index++] = 0x00;
558             apdu_len = index;
559 
560             resp_len = se_gto_apdu_transmit(ctx, apdu, apdu_len, resp, 65536);
561         }
562         if (resp_len < 0) {
563             mSecureElementStatus = FAILED;
564             if (deinitializeSE() != SUCCESS) {
565                 ALOGE("SecureElement:%s deinitializeSE Failed", __func__);
566             }
567         } else if ((resp[resp_len - 2] == 0x90) && (resp[resp_len - 1] == 0x00)) {
568             mSecureElementStatus = SUCCESS;
569             nbrOpenChannel--;
570         } else {
571             mSecureElementStatus = FAILED;
572         }
573         if(apdu) free(apdu);
574         if(resp) free(resp);
575     }
576 
577     if (nbrOpenChannel == 0 && isBasicChannelOpen == false) {
578         ALOGD("SecureElement:%s All Channels are closed", __func__);
579         if (deinitializeSE() != SUCCESS) {
580             ALOGE("SecureElement:%s deinitializeSE Failed", __func__);
581         }
582     }
583     ALOGD("SecureElement:%s end", __func__);
584     if(mSecureElementStatus != SUCCESS) return ScopedAStatus::fromServiceSpecificError(mSecureElementStatus);
585     else return ScopedAStatus::ok();
586 }
587 
588 void
notify(bool state,const char * message)589 SecureElement::notify(bool state, const char *message)
590 {
591     auto ret = internalClientCallback->onStateChange(state, message);
592     if (!ret.isOk()) {
593         ALOGW("failed to send onStateChange event!");
594     }
595 }
596 
597 void
dump_bytes(const char * pf,char sep,const uint8_t * p,int n,FILE * out)598 SecureElement::dump_bytes(const char *pf, char sep, const uint8_t *p, int n, FILE *out)
599 {
600     const uint8_t *s = p;
601     char *msg;
602     int len = 0;
603     int input_len = n;
604 
605     if (!debug_log_enabled) return;
606 
607     msg = (char*) malloc ( (pf ? strlen(pf) : 0) + input_len * 3 + 1);
608     if(!msg) {
609         errno = ENOMEM;
610         return;
611     }
612 
613     if (pf) {
614         len += sprintf(msg , "%s" , pf);
615     }
616     while (input_len--) {
617         len += sprintf(msg + len, "%02X" , *s++);
618         if (input_len && sep) {
619             len += sprintf(msg + len, ":");
620         }
621     }
622     sprintf(msg + len, "\n");
623     ALOGD("SecureElement:%s ==> size = %d data = %s", __func__, n, msg);
624 
625     if(msg) free(msg);
626 }
627 
628 int
toint(char c)629 SecureElement::toint(char c)
630 {
631     if ((c >= '0') && (c <= '9'))
632         return c - '0';
633 
634     if ((c >= 'A') && (c <= 'F'))
635         return c - 'A' + 10;
636 
637     if ((c >= 'a') && (c <= 'f'))
638         return c - 'a' + 10;
639 
640     return 0;
641 }
642 
643 int
run_apdu(struct se_gto_ctx * ctx,const uint8_t * apdu,uint8_t * resp,int n,int verbose)644 SecureElement::run_apdu(struct se_gto_ctx *ctx, const uint8_t *apdu, uint8_t *resp, int n, int verbose)
645 {
646     int sw;
647 
648     if (verbose)
649         dump_bytes("APDU: ", ':', apdu, n, stdout);
650 
651 
652     n = se_gto_apdu_transmit(ctx, apdu, n, resp, sizeof(resp));
653     if (n < 0) {
654         ALOGE("SecureElement:%s FAILED: APDU transmit (%s).\n\n", __func__, strerror(errno));
655         return -2;
656     } else if (n < 2) {
657         dump_bytes("RESP: ", ':', resp, n, stdout);
658         ALOGE("SecureElement:%s FAILED: not enough data to have a status word.\n", __func__);
659         return -2;
660     }
661 
662     if (verbose) {
663         sw = (resp[n - 2] << 8) | resp[n - 1];
664         printf("%d bytes, SW=0x%04x\n", n - 2, sw);
665         if (n > 2)
666             dump_bytes("RESP: ", ':', resp, n - 2, stdout);
667     }
668     return 0;
669 }
670 
671 int
parseConfigFile(FILE * f,int verbose)672 SecureElement::parseConfigFile(FILE *f, int verbose)
673 {
674     static char    buf[65536 * 2 + 2];
675 
676     int line;
677     char * pch;
678 
679     line = 0;
680     while (feof(f) == 0) {
681         char *s;
682 
683         s = fgets(buf, sizeof buf, f);
684         if (s == NULL)
685             break;
686         if (s[0] == '#') {
687             continue;
688         }
689 
690         pch = strtok(s," =;");
691         if (strcmp("GTO_DEV", pch) == 0) {
692             pch = strtok (NULL, " =;");
693             ALOGD("SecureElement:%s Defined node : %s", __func__, pch);
694             if (strlen(pch) > 0 && strcmp("\n", pch) != 0 && strcmp("\0", pch) != 0 ) {
695                 se_gto_set_gtodev(ctx, pch);
696             }
697         } else if (strcmp("GTO_DEBUG", pch) == 0) {
698             pch = strtok(NULL, " =;");
699             ALOGD("SecureElement:%s Log state : %s", __func__, pch);
700             if (strlen(pch) > 0 && strcmp("\n", pch) != 0 && strcmp("\0", pch) != 0 ) {
701                 if (strcmp(pch, "enable") == 0) {
702                     debug_log_enabled = true;
703                     se_gto_set_log_level(ctx, 4);
704                 } else {
705                     debug_log_enabled = false;
706                     se_gto_set_log_level(ctx, 3);
707                 }
708             }
709         }
710     }
711     return 0;
712 }
713 
714 int
openConfigFile(int verbose)715 SecureElement::openConfigFile(int verbose)
716 {
717     int   r;
718     FILE *f;
719 
720 
721     /* filename is not NULL */
722     ALOGD("SecureElement:%s Open Config file : %s", __func__, config_filename);
723     f = fopen(config_filename, "r");
724     if (f) {
725         r = parseConfigFile(f, verbose);
726         if (r == -1) {
727             perror(config_filename);
728             ALOGE("SecureElement:%s Error parse %s Failed", __func__, config_filename);
729         }
730         if (fclose(f) != 0) {
731             r = -1;
732             ALOGE("SecureElement:%s Error close %s Failed", __func__, config_filename);
733         }
734     } else {
735         r = -1;
736         ALOGE("SecureElement:%s Error open %s Failed", __func__, config_filename);
737     }
738     return r;
739 }
740 
deinitializeSE()741 int SecureElement::deinitializeSE() {
742     int mSecureElementStatus = FAILED;
743 
744     ALOGD("SecureElement:%s start", __func__);
745 
746     if(checkSeUp){
747         if (se_gto_close(ctx) < 0) {
748             mSecureElementStatus = FAILED;
749             notify(false, "SE Initialized failed");
750         } else {
751             ctx = NULL;
752             mSecureElementStatus = SUCCESS;
753             isBasicChannelOpen = false;
754             nbrOpenChannel = 0;
755         }
756         checkSeUp = false;
757     }else{
758         ALOGD("SecureElement:%s No need to deinitialize SE", __func__);
759         mSecureElementStatus = SUCCESS;
760     }
761 
762     ALOGD("SecureElement:%s end", __func__);
763     return mSecureElementStatus;
764 }
765 
reset()766 ScopedAStatus SecureElement::reset() {
767 
768     int status = FAILED;
769     std::string eSE1ResetToolStr;
770 
771     int ret = 0;
772 
773     ALOGD("SecureElement:%s start", __func__);
774     if (strncmp(ese_flag_name, "eSE1", 4) == 0) {
775         eSE1ResetToolStr = android::base::GetProperty("persist.vendor.se.streset", "");
776     }
777     if (deinitializeSE() != SUCCESS) {
778         ALOGE("SecureElement:%s deinitializeSE Failed", __func__);
779     }
780 
781     if (internalClientCallback == nullptr) {
782         return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
783     }
784 
785     notify(false, "reset the SE");
786 
787     if (eSE1ResetToolStr.length() > 0) {
788         typedef int (*STEseReset)();
789         eSE1ResetToolStr = VENDOR_LIB_PATH + eSE1ResetToolStr + VENDOR_LIB_EXT;
790         void *stdll = dlopen(eSE1ResetToolStr.c_str(), RTLD_NOW);
791         STEseReset fn = (STEseReset)dlsym(stdll, "direct_reset");
792         ret = fn();
793 
794         ALOGD("SecureElement:%s STResetTool ret : %d", __func__, ret);
795         if (ret == 0) {
796             ALOGD("SecureElement:%s STResetTool Success", __func__);
797             if (initializeSE() == EXIT_SUCCESS) {
798                 status = SUCCESS;
799                 notify(true, "SE Initialized");
800             }
801         } else {
802             ALOGE("SecureElement:%s STResetTool Failed!", __func__);
803         }
804 
805         dlclose(stdll);
806     } else {
807         if (initializeSE() == EXIT_SUCCESS) {
808             notify(true, "SE Initialized");
809             status = SUCCESS;
810         }
811     }
812 
813     ALOGD("SecureElement:%s end", __func__);
814 
815     if(status != SUCCESS) return ScopedAStatus::fromServiceSpecificError(status);
816     else return ScopedAStatus::ok();
817 }
818 
819 }
820