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