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