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