1 /******************************************************************************
2  *
3  *  Copyright 2023-2024 NXP
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 #include "SecureElement.h"
19 
20 #include <log/log.h>
21 
22 #include "phNfcStatus.h"
23 #include "phNxpEse_Apdu_Api.h"
24 #include "phNxpEse_Api.h"
25 /* Mutex to synchronize multiple transceive */
26 #include <memunreachable/memunreachable.h>
27 
28 namespace aidl {
29 namespace android {
30 namespace hardware {
31 namespace secure_element {
32 
33 #define DEFAULT_BASIC_CHANNEL 0x00
34 #define INVALID_LEN_SW1 0x64
35 #define INVALID_LEN_SW2 0xFF
36 #define SW1_BYTES_REMAINING 0x61
37 #define NUM_OF_CH4 0x04
38 #define NUM_OF_CH5 0x05
39 #define AID_SECURE_ELEMENT 1068
40 #define AID_ROOT 0
41 
42 typedef struct gsTransceiveBuffer {
43   phNxpEse_data cmdData;
44   phNxpEse_data rspData;
45   std::vector<uint8_t>* pRspDataBuff;
46 } sTransceiveBuffer_t;
47 
48 static int getResponseInternal(uint8_t cla, phNxpEse_7816_rpdu_t& rpdu,
49                                std::vector<uint8_t>& result);
50 static sTransceiveBuffer_t gsTxRxBuffer;
51 static std::vector<uint8_t> gsRspDataBuff(256);
52 std::shared_ptr<ISecureElementCallback> SecureElement::mCb = nullptr;
53 uid_t SecureElement::mCbClientUid = 0;
54 AIBinder_DeathRecipient* clientDeathRecipient = nullptr;
55 std::vector<bool> SecureElement::mOpenedChannels;
56 static const std::vector<std::vector<uint8_t>> kWeaverAIDs = {
57     {0xA0, 0x00, 0x00, 0x03, 0x96, 0x10, 0x10},  // Primary AID
58     {0xA0, 0x00, 0x00, 0x03, 0x96, 0x54, 0x53, 0x00, 0x00, 0x00, 0x01, 0x00,
59      0x23, 0x00, 0x00, 0x00},  // Alternate AID
60 };
61 
isWeaverApplet(std::vector<uint8_t> aid)62 static bool isWeaverApplet(std::vector<uint8_t> aid) {
63   if (std::find(kWeaverAIDs.begin(), kWeaverAIDs.end(), aid) !=
64       kWeaverAIDs.end()) {
65     return true;
66   }
67   return false;
68 }
69 
SecureElement()70 SecureElement::SecureElement()
71     : mMaxChannelCount(0),
72       mOpenedchannelCount(0),
73       mIsEseInitialized(false),
74       isOmapi(false) {}
75 
updateSeHalInitState(bool mstate)76 void SecureElement::updateSeHalInitState(bool mstate) {
77   mIsEseInitialized = mstate;
78 }
OnDeath(void * cookie)79 void OnDeath(void* cookie) {
80   (void)cookie;
81   LOG(ERROR) << " SecureElement serviceDied!!!";
82   SecureElement* se = static_cast<SecureElement*>(cookie);
83   se->updateSeHalInitState(false);
84   if (se->seHalDeInit() != SESTATUS_SUCCESS) {
85     LOG(ERROR) << "SE Deinit not successful";
86   }
87   se->handleStateOnDeath();
88 }
89 
NotifySeWaitExtension(phNxpEse_wtxState state)90 void SecureElement::NotifySeWaitExtension(phNxpEse_wtxState state) {
91   if (state == WTX_ONGOING) {
92     LOG(INFO) << "SecureElement::WTX ongoing";
93   } else if (state == WTX_END) {
94     LOG(INFO) << "SecureElement::WTX ended";
95   }
96 }
97 
init(const std::shared_ptr<ISecureElementCallback> & clientCallback)98 ScopedAStatus SecureElement::init(
99     const std::shared_ptr<ISecureElementCallback>& clientCallback) {
100   LOG(INFO) << __func__ << " callback: " << clientCallback.get();
101   if (!clientCallback) {
102     return ScopedAStatus::fromExceptionCode(EX_NULL_POINTER);
103   }
104   uid_t clientUid = AIBinder_getCallingUid();
105   // Allow VTS tests even if omapi acquires the lock.
106   if (!isClientVts(clientUid) && !handleClientCallback(clientCallback)) {
107     LOG(INFO) << __func__ << " client not allowed";
108     return ScopedAStatus::fromServiceSpecificError(IOERROR);
109   }
110   mCb = clientCallback;
111   mCbClientUid = clientUid;
112   ESESTATUS status = ESESTATUS_SUCCESS;
113   bool mIsInitDone = false;
114   phNxpEse_initParams initParams;
115   gsTxRxBuffer.pRspDataBuff = &gsRspDataBuff;
116   memset(&initParams, 0x00, sizeof(phNxpEse_initParams));
117   initParams.initMode = ESE_MODE_NORMAL;
118   initParams.mediaType = ESE_PROTOCOL_MEDIA_SPI_APDU_GATE;
119   initParams.fPtr_WtxNtf = SecureElement::NotifySeWaitExtension;
120 
121   if (clientCallback == nullptr) {
122     handleClientCbCleanup();
123     return ScopedAStatus::ok();
124   } else {
125     clientDeathRecipient = AIBinder_DeathRecipient_new(OnDeath);
126     auto linkRet =
127         AIBinder_linkToDeath(clientCallback->asBinder().get(),
128                              clientDeathRecipient, this /* cookie */);
129     if (linkRet != STATUS_OK) {
130       LOG(ERROR) << __func__ << ": linkToDeath failed: " << linkRet;
131       // Just ignore the error.
132     }
133   }
134 
135   LOG(INFO) << "SecureElement::init called here";
136   if (mIsEseInitialized) {
137     mCb->onStateChange(true, "NXP SE HAL init ok");
138     return ScopedAStatus::ok();
139   }
140 
141   phNxpEse_setWtxCountLimit(OsuHalExtn::getInstance().getOSUMaxWtxCount());
142   status = phNxpEse_open(initParams);
143   if (status == ESESTATUS_SUCCESS || ESESTATUS_BUSY == status) {
144     ESESTATUS initStatus = ESESTATUS_SUCCESS;
145     ESESTATUS deInitStatus = ESESTATUS_SUCCESS;
146     if (ESESTATUS_SUCCESS == phNxpEse_SetEndPoint_Cntxt(0)) {
147       initStatus = phNxpEse_init(initParams);
148       if (initStatus == ESESTATUS_SUCCESS) {
149         if (GET_CHIP_OS_VERSION() < OS_VERSION_8_9) {
150           /*update OS mode during first init*/
151           IS_OSU_MODE(OsuHalExtn::getInstance().INIT, 0);
152         }
153         if (ESESTATUS_SUCCESS == phNxpEse_ResetEndPoint_Cntxt(0)) {
154           LOG(INFO) << "ESE SPI init complete!!!";
155           mIsInitDone = true;
156         }
157         deInitStatus = phNxpEse_deInit();
158         if (ESESTATUS_SUCCESS != deInitStatus) mIsInitDone = false;
159       }
160     }
161     status = phNxpEse_close(deInitStatus);
162     /*Enable terminal post recovery(i.e. close success) from transmit failure */
163     if (status == ESESTATUS_SUCCESS &&
164         (initStatus == ESESTATUS_TRANSCEIVE_FAILED ||
165          initStatus == ESESTATUS_FAILED)) {
166       if (GET_CHIP_OS_VERSION() < OS_VERSION_8_9)
167         IS_OSU_MODE(OsuHalExtn::getInstance().INIT, 0);
168       mIsInitDone = true;
169     }
170   }
171   phNxpEse_setWtxCountLimit(RESET_APP_WTX_COUNT);
172   if (status == ESESTATUS_SUCCESS && mIsInitDone) {
173     mHasPriorityAccess = phNxpEse_isPriorityAccessEnabled();
174     mMaxChannelCount = getMaxChannelCnt();
175     mOpenedChannels.resize(mMaxChannelCount, false);
176     mCb->onStateChange(true, "NXP SE HAL init ok");
177   } else {
178     LOG(ERROR) << "eSE-Hal Init failed";
179     handleClientCbCleanup();
180     mCb->onStateChange(false, "NXP SE HAL init failed");
181   }
182   return ScopedAStatus::ok();
183 }
184 
getAtr(std::vector<uint8_t> * _aidl_return)185 ScopedAStatus SecureElement::getAtr(std::vector<uint8_t>* _aidl_return) {
186   LOG(INFO) << __func__;
187 
188   AutoMutex guard(seHalLock);
189   LOG(ERROR) << "Processing ATR.....";
190   phNxpEse_data atrData;
191   std::vector<uint8_t> response;
192   ESESTATUS status = ESESTATUS_FAILED;
193   bool mIsSeHalInitDone = false;
194 
195   // In dedicated mode getATR not allowed
196   if ((GET_CHIP_OS_VERSION() < OS_VERSION_6_2) &&
197       (IS_OSU_MODE(OsuHalExtn::getInstance().GETATR))) {
198     LOG(ERROR) << "%s: Not allowed in dedicated mode!!!" << __func__;
199     *_aidl_return = response;
200     return ndk::ScopedAStatus::ok();
201   }
202 
203   if (!mIsEseInitialized) {
204     ESESTATUS status = seHalInit();
205     if (status != ESESTATUS_SUCCESS) {
206       LOG(ERROR) << "%s: seHalInit Failed!!!" << __func__;
207       *_aidl_return = response; /*Return with empty Vector*/
208       return ndk::ScopedAStatus::ok();
209     } else {
210       mIsSeHalInitDone = true;
211     }
212   }
213   status = phNxpEse_SetEndPoint_Cntxt(0);
214   if (status != ESESTATUS_SUCCESS) {
215     LOG(ERROR) << "phNxpEse_SetEndPoint_Cntxt failed";
216   }
217   status = phNxpEse_getAtr(&atrData);
218   if (status != ESESTATUS_SUCCESS) {
219     LOG(ERROR) << "phNxpEse_getAtr failed";
220     *_aidl_return = response; /*Return with empty Vector*/
221     return ndk::ScopedAStatus::ok();
222   } else {
223     response.resize(atrData.len);
224     memcpy(&response[0], atrData.p_data, atrData.len);
225   }
226 
227   status = phNxpEse_ResetEndPoint_Cntxt(0);
228   if (status != ESESTATUS_SUCCESS) {
229     LOG(ERROR) << "phNxpEse_ResetEndPoint_Cntxt failed";
230   }
231 
232   if (status != ESESTATUS_SUCCESS) {
233     ALOGD("ATR Data[BytebyByte]=Look below for %d bytes", atrData.len);
234     for (auto i = response.begin(); i != response.end(); ++i)
235       ALOGI("0x%x\t", *i);
236   }
237 
238   *_aidl_return = std::move(response);
239   if (atrData.p_data != NULL) {
240     phNxpEse_free(atrData.p_data);
241   }
242   if (mIsSeHalInitDone) {
243     if (SESTATUS_SUCCESS != seHalDeInit())
244       LOG(ERROR) << "phNxpEse_getAtr seHalDeInit failed";
245     mIsEseInitialized = false;
246     mIsSeHalInitDone = false;
247   }
248   return ndk::ScopedAStatus::ok();
249 }
250 
isCardPresent(bool * _aidl_return)251 ScopedAStatus SecureElement::isCardPresent(bool* _aidl_return) {
252   LOG(INFO) << __func__;
253   *_aidl_return = true;
254   return ScopedAStatus::ok();
255 }
256 
transmit(const std::vector<uint8_t> & data,std::vector<uint8_t> * _aidl_return)257 ScopedAStatus SecureElement::transmit(const std::vector<uint8_t>& data,
258                                       std::vector<uint8_t>* _aidl_return) {
259   AutoMutex guard(seHalLock);
260   ESESTATUS status = ESESTATUS_FAILED;
261   std::vector<uint8_t> result;
262   if (!mOpenedchannelCount) {
263     // 0x69, 0x86 = COMMAND NOT ALLOWED
264     uint8_t sw[2] = {0x69, 0x86};
265     result.resize(sizeof(sw));
266     memcpy(&result[0], sw, sizeof(sw));
267     return ScopedAStatus::fromServiceSpecificError(CHANNEL_NOT_AVAILABLE);
268   }
269 
270   phNxpEse_memset(&gsTxRxBuffer.cmdData, 0x00, sizeof(phNxpEse_data));
271   phNxpEse_memset(&gsTxRxBuffer.rspData, 0x00, sizeof(phNxpEse_data));
272   gsTxRxBuffer.cmdData.len = (uint32_t)data.size();
273   gsTxRxBuffer.cmdData.p_data =
274       (uint8_t*)phNxpEse_memalloc(data.size() * sizeof(uint8_t));
275   if (NULL == gsTxRxBuffer.cmdData.p_data) {
276     LOG(ERROR) << "transmit failed to allocate the Memory!!!";
277     /*Return empty vec*/
278     *_aidl_return = result;
279     return ScopedAStatus::ok();
280   }
281   if (GET_CHIP_OS_VERSION() < OS_VERSION_8_9) {
282     OsuHalExtn::OsuApduMode mode = IS_OSU_MODE(
283         data, OsuHalExtn::getInstance().TRANSMIT, &gsTxRxBuffer.cmdData);
284     if (mode == OsuHalExtn::getInstance().OSU_BLOCKED_MODE) {
285       LOG(ERROR) << "Not allowed in dedicated mode!!!";
286       /*Return empty vec*/
287       *_aidl_return = result;
288       return ScopedAStatus::ok();
289     } else if (mode == OsuHalExtn::getInstance().OSU_RST_MODE) {
290       uint8_t sw[2] = {0x90, 0x00};
291       result.resize(sizeof(sw));
292       memcpy(&result[0], sw, sizeof(sw));
293       *_aidl_return = result;
294       return ScopedAStatus::ok();
295     }
296   } else {
297     memcpy(gsTxRxBuffer.cmdData.p_data, data.data(), gsTxRxBuffer.cmdData.len);
298   }
299   LOG(INFO) << "Acquired lock for SPI";
300   status = phNxpEse_SetEndPoint_Cntxt(0);
301   if (status != ESESTATUS_SUCCESS) {
302     LOG(ERROR) << "phNxpEse_SetEndPoint_Cntxt failed!!!";
303   }
304   status = phNxpEse_Transceive(&gsTxRxBuffer.cmdData, &gsTxRxBuffer.rspData);
305 
306   if (status == ESESTATUS_SUCCESS) {
307     result.resize(gsTxRxBuffer.rspData.len);
308     memcpy(&result[0], gsTxRxBuffer.rspData.p_data, gsTxRxBuffer.rspData.len);
309   } else if (status == ESESTATUS_INVALID_RECEIVE_LENGTH) {
310     uint8_t respBuf[] = {INVALID_LEN_SW1, INVALID_LEN_SW2};
311     result.resize(sizeof(respBuf));
312     memcpy(&result[0], respBuf, sizeof(respBuf));
313   } else {
314     LOG(ERROR) << "transmit failed!!!";
315   }
316   status = phNxpEse_ResetEndPoint_Cntxt(0);
317   if (status != ESESTATUS_SUCCESS) {
318     LOG(ERROR) << "phNxpEse_ResetEndPoint_Cntxt failed!!!";
319   }
320 
321   *_aidl_return = std::move(result);
322   if (NULL != gsTxRxBuffer.cmdData.p_data) {
323     phNxpEse_free(gsTxRxBuffer.cmdData.p_data);
324     gsTxRxBuffer.cmdData.p_data = NULL;
325   }
326   if (NULL != gsTxRxBuffer.rspData.p_data) {
327     phNxpEse_free(gsTxRxBuffer.rspData.p_data);
328     gsTxRxBuffer.rspData.p_data = NULL;
329   }
330 
331   return ScopedAStatus::ok();
332 }
333 
openLogicalChannel(const std::vector<uint8_t> & aid,int8_t p2,::aidl::android::hardware::secure_element::LogicalChannelResponse * _aidl_return)334 ScopedAStatus SecureElement::openLogicalChannel(
335     const std::vector<uint8_t>& aid, int8_t p2,
336     ::aidl::android::hardware::secure_element::LogicalChannelResponse*
337         _aidl_return) {
338   AutoMutex guard(seHalLock);
339   std::vector<uint8_t> manageChannelCommand = {0x00, 0x70, 0x00, 0x00, 0x01};
340 
341   LogicalChannelResponse resApduBuff;
342   resApduBuff.channelNumber = 0xff;
343   memset(&resApduBuff, 0x00, sizeof(resApduBuff));
344   if (aid.size() > MAX_AID_LENGTH) {
345     LOG(ERROR) << "%s: AID out of range!!!" << __func__;
346     *_aidl_return = resApduBuff;
347     handleClientCbCleanup();
348     return ScopedAStatus::fromServiceSpecificError(FAILED);
349   }
350 
351   /*
352    * Basic channel & reserved channel if any is removed
353    * from count
354    */
355   uint8_t maxLogicalChannelSupported =
356       mMaxChannelCount - getReserveChannelCnt(aid) - 1;
357 
358   uint8_t openedLogicalChannelCount = mOpenedchannelCount;
359   if (mOpenedChannels[0]) openedLogicalChannelCount--;
360 
361   if (openedLogicalChannelCount >= maxLogicalChannelSupported) {
362     ALOGE("%s: Reached Max supported(%d) Logical Channel", __func__,
363           openedLogicalChannelCount);
364     *_aidl_return = resApduBuff;
365     handleClientCbCleanup();
366     return ScopedAStatus::fromServiceSpecificError(CHANNEL_NOT_AVAILABLE);
367   }
368 
369   LOG(INFO) << "Acquired the lock from SPI openLogicalChannel";
370 
371   // In dedicated mode openLogical not allowed
372   if ((GET_CHIP_OS_VERSION() < OS_VERSION_8_9) &&
373       (IS_OSU_MODE(OsuHalExtn::getInstance().OPENLOGICAL))) {
374     LOG(ERROR) << "%s: Not allowed in dedicated mode!!!" << __func__;
375     *_aidl_return = resApduBuff;
376     handleClientCbCleanup();
377     return ScopedAStatus::fromServiceSpecificError(IOERROR);
378   }
379   if (!mIsEseInitialized) {
380     ESESTATUS status = seHalInit();
381     if (status != ESESTATUS_SUCCESS) {
382       LOG(ERROR) << "%s: seHalInit Failed!!!" << __func__;
383       handleClientCbCleanup();
384       *_aidl_return = resApduBuff;
385       return ScopedAStatus::fromServiceSpecificError(IOERROR);
386     }
387   }
388 
389   if (mOpenedChannels.size() == 0x00) {
390     mMaxChannelCount = getMaxChannelCnt();
391     mOpenedChannels.resize(mMaxChannelCount, false);
392   }
393 
394   int sestatus = ISecureElement::IOERROR;
395   ESESTATUS status = ESESTATUS_FAILED;
396   phNxpEse_data cmdApdu;
397   phNxpEse_data rspApdu;
398 
399   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
400 
401   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
402 
403   cmdApdu.len = (uint32_t)manageChannelCommand.size();
404   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(manageChannelCommand.size() *
405                                                sizeof(uint8_t));
406   memcpy(cmdApdu.p_data, manageChannelCommand.data(), cmdApdu.len);
407 
408   status = phNxpEse_SetEndPoint_Cntxt(0);
409   if (status != ESESTATUS_SUCCESS) {
410     LOG(ERROR) << "phNxpEse_SetEndPoint_Cntxt failed!!!";
411   }
412   status = phNxpEse_Transceive(&cmdApdu, &rspApdu);
413   if (status != ESESTATUS_SUCCESS) {
414     resApduBuff.channelNumber = 0xff;
415   } else if (rspApdu.p_data[rspApdu.len - 2] == 0x6A &&
416              rspApdu.p_data[rspApdu.len - 1] == 0x81) {
417     resApduBuff.channelNumber = 0xff;
418     sestatus = ISecureElement::CHANNEL_NOT_AVAILABLE;
419   } else if (rspApdu.p_data[rspApdu.len - 2] == 0x90 &&
420              rspApdu.p_data[rspApdu.len - 1] == 0x00) {
421     resApduBuff.channelNumber = rspApdu.p_data[0];
422     mOpenedchannelCount++;
423     mOpenedChannels[resApduBuff.channelNumber] = true;
424     sestatus = SESTATUS_SUCCESS;
425   } else if (((rspApdu.p_data[rspApdu.len - 2] == 0x6E) ||
426               (rspApdu.p_data[rspApdu.len - 2] == 0x6D)) &&
427              rspApdu.p_data[rspApdu.len - 1] == 0x00) {
428     sestatus = ISecureElement::UNSUPPORTED_OPERATION;
429   }
430   /*Free the allocations*/
431   phNxpEse_free(cmdApdu.p_data);
432   phNxpEse_free(rspApdu.p_data);
433 
434   if (sestatus != SESTATUS_SUCCESS) {
435     if (mOpenedchannelCount == 0) {
436       int deInitStatus = seHalDeInit();
437       if (deInitStatus != SESTATUS_SUCCESS) {
438         LOG(INFO) << "seDeInit Failed";
439       }
440     }
441     /*If manageChannel is failed in any of above cases
442     send the callback and return*/
443     status = phNxpEse_ResetEndPoint_Cntxt(0);
444     if (status != ESESTATUS_SUCCESS) {
445       LOG(ERROR) << "phNxpEse_ResetEndPoint_Cntxt failed!!!";
446     }
447     *_aidl_return = resApduBuff;
448     handleClientCbCleanup();
449     return ScopedAStatus::fromServiceSpecificError(sestatus);
450   }
451   LOG(INFO) << "openLogicalChannel Sending selectApdu";
452   sestatus = ISecureElement::IOERROR;
453   status = ESESTATUS_FAILED;
454 
455   phNxpEse_7816_cpdu_t cpdu;
456   phNxpEse_7816_rpdu_t rpdu;
457   phNxpEse_memset(&cpdu, 0x00, sizeof(phNxpEse_7816_cpdu_t));
458   phNxpEse_memset(&rpdu, 0x00, sizeof(phNxpEse_7816_rpdu_t));
459 
460   if ((resApduBuff.channelNumber > 0x03) &&
461       (resApduBuff.channelNumber < 0x14)) {
462     /* update CLA byte according to GP spec Table 11-12*/
463     cpdu.cla =
464         0x40 + (resApduBuff.channelNumber - 4); /* Class of instruction */
465   } else if ((resApduBuff.channelNumber > 0x00) &&
466              (resApduBuff.channelNumber < 0x04)) {
467     /* update CLA byte according to GP spec Table 11-11*/
468     cpdu.cla = resApduBuff.channelNumber; /* Class of instruction */
469   } else {
470     ALOGE("%s: Invalid Channel no: %02x", __func__, resApduBuff.channelNumber);
471     resApduBuff.channelNumber = 0xff;
472     *_aidl_return = resApduBuff;
473     handleClientCbCleanup();
474     return ScopedAStatus::fromServiceSpecificError(IOERROR);
475   }
476   cpdu.ins = 0xA4; /* Instruction code */
477   cpdu.p1 = 0x04;  /* Instruction parameter 1 */
478   cpdu.p2 = p2;    /* Instruction parameter 2 */
479   cpdu.lc = (uint16_t)aid.size();
480   cpdu.le_type = 0x01;
481   cpdu.pdata = (uint8_t*)phNxpEse_memalloc(aid.size() * sizeof(uint8_t));
482   memcpy(cpdu.pdata, aid.data(), cpdu.lc);
483   cpdu.le = 256;
484 
485   rpdu.len = 0x02;
486   rpdu.pdata = (uint8_t*)phNxpEse_memalloc(cpdu.le * sizeof(uint8_t));
487 
488   status = phNxpEse_7816_Transceive(&cpdu, &rpdu);
489 
490   if (status != ESESTATUS_SUCCESS) {
491     /*Transceive failed*/
492     if (rpdu.len > 0 && (rpdu.sw1 == 0x64 && rpdu.sw2 == 0xFF)) {
493       sestatus = ISecureElement::IOERROR;
494     } else {
495       sestatus = ISecureElement::FAILED;
496     }
497   } else {
498     /*Status word to be passed as part of response
499     So include additional length*/
500     uint16_t responseLen = rpdu.len + 2;
501     resApduBuff.selectResponse.resize(responseLen);
502     memcpy(&resApduBuff.selectResponse[0], rpdu.pdata, rpdu.len);
503     resApduBuff.selectResponse[responseLen - 1] = rpdu.sw2;
504     resApduBuff.selectResponse[responseLen - 2] = rpdu.sw1;
505 
506     if (rpdu.sw1 == SW1_BYTES_REMAINING) {
507       sestatus =
508           getResponseInternal(cpdu.cla, rpdu, resApduBuff.selectResponse);
509       if (sestatus != SESTATUS_SUCCESS) {
510         LOG(ERROR) << "%s: getResponseInternal Failed" << __func__;
511       }
512     }
513 
514     /*Status is success*/
515     if ((rpdu.sw1 == 0x90 && rpdu.sw2 == 0x00) || (rpdu.sw1 == 0x62) ||
516         (rpdu.sw1 == 0x63)) {
517       sestatus = SESTATUS_SUCCESS;
518     }
519     /*AID provided doesn't match any applet on the secure element*/
520     else if ((rpdu.sw1 == 0x6A && rpdu.sw2 == 0x82) ||
521              (rpdu.sw1 == 0x69 && (rpdu.sw2 == 0x99 || rpdu.sw2 == 0x85))) {
522       sestatus = ISecureElement::NO_SUCH_ELEMENT_ERROR;
523     }
524     /*Operation provided by the P2 parameter is not permitted by the applet.*/
525     else if (rpdu.sw1 == 0x6A && rpdu.sw2 == 0x86) {
526       sestatus = ISecureElement::UNSUPPORTED_OPERATION;
527     } else {
528       sestatus = ISecureElement::FAILED;
529     }
530   }
531   if (sestatus != SESTATUS_SUCCESS) {
532     handleClientCbCleanup();
533     int closeChannelStatus = internalCloseChannel(resApduBuff.channelNumber);
534     if (closeChannelStatus != SESTATUS_SUCCESS) {
535       LOG(ERROR) << "%s: closeChannel Failed" << __func__;
536     } else {
537       resApduBuff.channelNumber = 0xff;
538     }
539   }
540   status = phNxpEse_ResetEndPoint_Cntxt(0);
541   if (status != ESESTATUS_SUCCESS) {
542     LOG(ERROR) << "phNxpEse_ResetEndPoint_Cntxt failed!!!";
543   }
544   *_aidl_return = std::move(resApduBuff);
545   phNxpEse_free(cpdu.pdata);
546   phNxpEse_free(rpdu.pdata);
547 
548   return sestatus == SESTATUS_SUCCESS
549              ? ndk::ScopedAStatus::ok()
550              : ndk::ScopedAStatus::fromServiceSpecificError(sestatus);
551 }
552 
openBasicChannel(const std::vector<uint8_t> & aid,int8_t p2,std::vector<uint8_t> * _aidl_return)553 ScopedAStatus SecureElement::openBasicChannel(
554     const std::vector<uint8_t>& aid, int8_t p2,
555     std::vector<uint8_t>* _aidl_return) {
556   std::vector<uint8_t> result;
557   if (aid.size() > MAX_AID_LENGTH) {
558     LOG(ERROR) << "%s: AID out of range!!!" << __func__;
559     *_aidl_return = result;
560     return ScopedAStatus::fromServiceSpecificError(FAILED);
561   }
562   AutoMutex guard(seHalLock);
563   ESESTATUS status = ESESTATUS_SUCCESS;
564   phNxpEse_7816_cpdu_t cpdu;
565   phNxpEse_7816_rpdu_t rpdu;
566   std::vector<uint8_t> ls_aid = {0xA0, 0x00, 0x00, 0x03, 0x96, 0x41, 0x4C,
567                                  0x41, 0x01, 0x43, 0x4F, 0x52, 0x01};
568 
569   if (mOpenedChannels[0]) {
570     LOG(ERROR) << "openBasicChannel failed, channel already in use";
571     *_aidl_return = result;
572     return ScopedAStatus::fromServiceSpecificError(UNSUPPORTED_OPERATION);
573   }
574 
575   LOG(ERROR) << "Acquired the lock in SPI openBasicChannel";
576   if ((GET_CHIP_OS_VERSION() < OS_VERSION_8_9) &&
577       IS_OSU_MODE(aid, OsuHalExtn::getInstance().OPENBASIC) ==
578           OsuHalExtn::OSU_PROP_MODE) {
579     uint8_t sw[2] = {0x90, 0x00};
580     result.resize(sizeof(sw));
581     memcpy(&result[0], sw, 2);
582     if (mIsEseInitialized) {
583       /* Close existing sessions if any to start dedicated OSU Mode
584        * with OSU specific settings in TZ/TEE */
585       if (seHalDeInit() != SESTATUS_SUCCESS) {
586         LOG(INFO) << "seDeInit Failed";
587         *_aidl_return = result;
588         return ScopedAStatus::fromServiceSpecificError(IOERROR);
589       }
590     }
591     phNxpEse_setWtxCountLimit(OsuHalExtn::getInstance().getOSUMaxWtxCount());
592     ESESTATUS status = ESESTATUS_FAILED;
593     uint8_t retry = 0;
594     do {
595       /*For Reset Recovery*/
596       status = seHalInit();
597     } while (status != ESESTATUS_SUCCESS && retry++ < 1);
598     if (status != ESESTATUS_SUCCESS) {
599       LOG(ERROR) << "%s: seHalInit Failed!!!" << __func__;
600       phNxpEse_setWtxCountLimit(RESET_APP_WTX_COUNT);
601       *_aidl_return = result;
602       return ScopedAStatus::fromServiceSpecificError(IOERROR);
603     }
604     if (phNxpEse_doResetProtection(true) != ESESTATUS_SUCCESS) {
605       LOG(ERROR) << "%s: Enable Reset Protection Failed!!!" << __func__;
606       *_aidl_return = result;
607       return ScopedAStatus::fromServiceSpecificError(FAILED);
608     } else {
609       mOpenedChannels[0] = true;
610       mOpenedchannelCount++;
611       *_aidl_return = result;
612       return ScopedAStatus::ok();
613     }
614   }
615 
616   if (!mIsEseInitialized) {
617     ESESTATUS status = seHalInit();
618     if (status != ESESTATUS_SUCCESS) {
619       LOG(ERROR) << "%s: seHalInit Failed!!!" << __func__;
620       *_aidl_return = result;
621       return ScopedAStatus::fromServiceSpecificError(IOERROR);
622     }
623   }
624 
625   if (GET_CHIP_OS_VERSION() < OS_VERSION_8_9) {
626     phNxpEse_data atrData;
627     if (phNxpEse_getAtr(&atrData) != ESESTATUS_SUCCESS) {
628       LOG(ERROR) << "phNxpEse_getAtr failed";
629     }
630     if (atrData.p_data != NULL) {
631       phNxpEse_free(atrData.p_data);
632     }
633 
634     if (phNxpEse_GetOsMode() == OSU_MODE) {
635       if (mOpenedchannelCount == 0) {
636         if (seHalDeInit() != SESTATUS_SUCCESS) {
637           LOG(INFO) << "seDeInit Failed";
638         }
639       }
640       *_aidl_return = result;
641       return ScopedAStatus::fromServiceSpecificError(IOERROR);
642     }
643   }
644 
645   if (mOpenedChannels.size() == 0x00) {
646     mMaxChannelCount = getMaxChannelCnt();
647     mOpenedChannels.resize(mMaxChannelCount, false);
648   }
649   phNxpEse_memset(&cpdu, 0x00, sizeof(phNxpEse_7816_cpdu_t));
650   phNxpEse_memset(&rpdu, 0x00, sizeof(phNxpEse_7816_rpdu_t));
651 
652   cpdu.cla = 0x00; /* Class of instruction */
653   cpdu.ins = 0xA4; /* Instruction code */
654   cpdu.p1 = 0x04;  /* Instruction parameter 1 */
655   cpdu.p2 = p2;    /* Instruction parameter 2 */
656   cpdu.lc = (uint16_t)aid.size();
657   cpdu.le_type = 0x01;
658   cpdu.pdata = (uint8_t*)phNxpEse_memalloc(aid.size() * sizeof(uint8_t));
659   memcpy(cpdu.pdata, aid.data(), cpdu.lc);
660   cpdu.le = 256;
661 
662   rpdu.len = 0x02;
663   rpdu.pdata = (uint8_t*)phNxpEse_memalloc(cpdu.le * sizeof(uint8_t));
664 
665   status = phNxpEse_SetEndPoint_Cntxt(0);
666   if (status != ESESTATUS_SUCCESS) {
667     LOG(ERROR) << "phNxpEse_SetEndPoint_Cntxt failed!!!";
668   }
669   status = phNxpEse_7816_Transceive(&cpdu, &rpdu);
670   int sestatus;
671   sestatus = SESTATUS_SUCCESS;
672 
673   if (status != ESESTATUS_SUCCESS) {
674     /* Transceive failed */
675     if (rpdu.len > 0 && (rpdu.sw1 == 0x64 && rpdu.sw2 == 0xFF)) {
676       sestatus = ISecureElement::IOERROR;
677     } else {
678       sestatus = ISecureElement::FAILED;
679     }
680   } else {
681     /*Status word to be passed as part of response
682     So include additional length*/
683     uint16_t responseLen = rpdu.len + 2;
684     result.resize(responseLen);
685     memcpy(&result[0], rpdu.pdata, rpdu.len);
686     result[responseLen - 1] = rpdu.sw2;
687     result[responseLen - 2] = rpdu.sw1;
688     if (rpdu.sw1 == SW1_BYTES_REMAINING) {
689       sestatus = getResponseInternal(cpdu.cla, rpdu, result);
690       if (sestatus != SESTATUS_SUCCESS) {
691         LOG(ERROR) << "%s: getResponseInternal Failed " << __func__;
692       }
693     }
694 
695     /*Status is success*/
696     if (((rpdu.sw1 == 0x90) && (rpdu.sw2 == 0x00)) || (rpdu.sw1 == 0x62) ||
697         (rpdu.sw1 == 0x63)) {
698       /*Set basic channel reference if it is not set */
699       if (!mOpenedChannels[0]) {
700         mOpenedChannels[0] = true;
701         mOpenedchannelCount++;
702       }
703 
704       sestatus = SESTATUS_SUCCESS;
705     }
706     /*AID provided doesn't match any applet on the secure element*/
707     else if ((rpdu.sw1 == 0x6A && rpdu.sw2 == 0x82) ||
708              (rpdu.sw1 == 0x69 && (rpdu.sw2 == 0x99 || rpdu.sw2 == 0x85))) {
709       sestatus = ISecureElement::NO_SUCH_ELEMENT_ERROR;
710     }
711     /*Operation provided by the P2 parameter is not permitted by the applet.*/
712     else if (rpdu.sw1 == 0x6A && rpdu.sw2 == 0x86) {
713       sestatus = ISecureElement::UNSUPPORTED_OPERATION;
714     } else {
715       sestatus = ISecureElement::FAILED;
716     }
717   }
718   status = phNxpEse_ResetEndPoint_Cntxt(0);
719   if (status != ESESTATUS_SUCCESS) {
720     LOG(ERROR) << "phNxpEse_ResetEndPoint_Cntxt failed!!!";
721   }
722   if (sestatus != SESTATUS_SUCCESS) {
723     int closeChannelStatus = internalCloseChannel(DEFAULT_BASIC_CHANNEL);
724     if (closeChannelStatus != SESTATUS_SUCCESS) {
725       LOG(ERROR) << "%s: closeChannel Failed" << __func__;
726     }
727   }
728   *_aidl_return = std::move(result);
729   phNxpEse_free(cpdu.pdata);
730   phNxpEse_free(rpdu.pdata);
731   return sestatus == SESTATUS_SUCCESS
732              ? ndk::ScopedAStatus::ok()
733              : ndk::ScopedAStatus::fromServiceSpecificError(sestatus);
734 }
735 
internalCloseChannel(uint8_t channelNumber)736 int SecureElement::internalCloseChannel(uint8_t channelNumber) {
737   ESESTATUS status = ESESTATUS_SUCCESS;
738   int sestatus = ISecureElement::FAILED;
739   phNxpEse_7816_cpdu_t cpdu;
740   phNxpEse_7816_rpdu_t rpdu;
741 
742   LOG(ERROR) << "Acquired the lock in SPI internalCloseChannel";
743   ALOGD("mMaxChannelCount = %d, Closing Channel = %d", mMaxChannelCount,
744         channelNumber);
745   if (channelNumber >= mMaxChannelCount) {
746     ALOGE("invalid channel!!! %d", channelNumber);
747   } else if (channelNumber > DEFAULT_BASIC_CHANNEL &&
748              mOpenedChannels[channelNumber]) {
749     phNxpEse_memset(&cpdu, 0x00, sizeof(phNxpEse_7816_cpdu_t));
750     phNxpEse_memset(&rpdu, 0x00, sizeof(phNxpEse_7816_rpdu_t));
751     cpdu.cla = channelNumber; /* Class of instruction */
752     // For Supplementary Channel update CLA byte according to GP
753     if ((channelNumber > 0x03) && (channelNumber < 0x14)) {
754       /* update CLA byte according to GP spec Table 11-12*/
755       cpdu.cla = 0x40 + (channelNumber - 4); /* Class of instruction */
756     }
757     cpdu.ins = 0x70;         /* Instruction code */
758     cpdu.p1 = 0x80;          /* Instruction parameter 1 */
759     cpdu.p2 = channelNumber; /* Instruction parameter 2 */
760     cpdu.lc = 0x00;
761     cpdu.le = 0x9000;
762     status = phNxpEse_SetEndPoint_Cntxt(0);
763     if (status != ESESTATUS_SUCCESS) {
764       LOG(ERROR) << "phNxpEse_SetEndPoint_Cntxt failed!!!";
765     }
766     status = phNxpEse_7816_Transceive(&cpdu, &rpdu);
767     if (status == ESESTATUS_SUCCESS) {
768       if ((rpdu.sw1 == 0x90) && (rpdu.sw2 == 0x00)) {
769         sestatus = SESTATUS_SUCCESS;
770       }
771     }
772     status = phNxpEse_ResetEndPoint_Cntxt(0);
773     if (status != ESESTATUS_SUCCESS) {
774       LOG(ERROR) << "phNxpEse_ResetEndPoint_Cntxt failed!!!";
775     }
776   } else if (channelNumber == DEFAULT_BASIC_CHANNEL &&
777              mOpenedChannels[channelNumber]) {
778     sestatus = SESTATUS_SUCCESS;
779   }
780   if (channelNumber < mMaxChannelCount) {
781     if (mOpenedChannels[channelNumber]) {
782       mOpenedChannels[channelNumber] = false;
783       mOpenedchannelCount--;
784     }
785   }
786   /*If there are no channels remaining close secureElement*/
787   if (mOpenedchannelCount == 0) {
788     if (SESTATUS_SUCCESS != seHalDeInit()) {
789       LOG(ERROR) << "internalCloseChannel seHalDeInit failed";
790     }
791   } else {
792     sestatus = SESTATUS_SUCCESS;
793   }
794   return sestatus;
795 }
796 
closeChannel(int8_t channelNumber)797 ScopedAStatus SecureElement::closeChannel(int8_t channelNumber) {
798   AutoMutex guard(seHalLock);
799   int sestatus;
800   // Close internal allowed when not in dedicated Mode
801   if ((GET_CHIP_OS_VERSION() >= OS_VERSION_8_9) ||
802       (!IS_OSU_MODE(OsuHalExtn::getInstance().CLOSE, channelNumber))) {
803     sestatus = internalCloseChannel(channelNumber);
804   } else {
805     /*Decrement channel count opened to
806      * keep in sync with service */
807     if (channelNumber < mMaxChannelCount) {
808       if (mOpenedChannels[channelNumber]) {
809         mOpenedChannels[channelNumber] = false;
810         mOpenedchannelCount--;
811       }
812     }
813     sestatus = SESTATUS_SUCCESS;
814   }
815   handleClientCbCleanup();
816   return sestatus == SESTATUS_SUCCESS
817              ? ndk::ScopedAStatus::ok()
818              : ndk::ScopedAStatus::fromServiceSpecificError(sestatus);
819 }
820 
seHalInit()821 ESESTATUS SecureElement::seHalInit() {
822   ESESTATUS status = ESESTATUS_SUCCESS;
823   phNxpEse_initParams initParams;
824   ESESTATUS deInitStatus = ESESTATUS_SUCCESS;
825   memset(&initParams, 0x00, sizeof(phNxpEse_initParams));
826   initParams.initMode = ESE_MODE_NORMAL;
827   initParams.mediaType = ESE_PROTOCOL_MEDIA_SPI_APDU_GATE;
828   initParams.fPtr_WtxNtf = SecureElement::NotifySeWaitExtension;
829 
830   status = phNxpEse_open(initParams);
831   if (ESESTATUS_SUCCESS == status || ESESTATUS_BUSY == status) {
832     if (ESESTATUS_SUCCESS == phNxpEse_SetEndPoint_Cntxt(0) &&
833         ESESTATUS_SUCCESS == (status = phNxpEse_init(initParams))) {
834       if (ESESTATUS_SUCCESS == phNxpEse_ResetEndPoint_Cntxt(0)) {
835         mIsEseInitialized = true;
836         LOG(INFO) << "ESE SPI init complete!!!";
837         return ESESTATUS_SUCCESS;
838       }
839     } else {
840       LOG(INFO) << "ESE SPI init NOT successful";
841       status = ESESTATUS_FAILED;
842     }
843     deInitStatus = phNxpEse_deInit();
844     if (phNxpEse_close(deInitStatus) != ESESTATUS_SUCCESS) {
845       LOG(INFO) << "ESE close not successful";
846       status = ESESTATUS_FAILED;
847     }
848     mIsEseInitialized = false;
849   }
850   return status;
851 }
852 
seHalDeInit()853 int SecureElement::seHalDeInit() {
854   ESESTATUS status = ESESTATUS_SUCCESS;
855   ESESTATUS deInitStatus = ESESTATUS_SUCCESS;
856   bool mIsDeInitDone = true;
857   int sestatus = ISecureElement::FAILED;
858   status = phNxpEse_SetEndPoint_Cntxt(0);
859   if (status != ESESTATUS_SUCCESS) {
860     LOG(ERROR) << "phNxpEse_SetEndPoint_Cntxt failed!!!";
861     mIsDeInitDone = false;
862   }
863   deInitStatus = phNxpEse_deInit();
864   if (ESESTATUS_SUCCESS != deInitStatus) mIsDeInitDone = false;
865   status = phNxpEse_ResetEndPoint_Cntxt(0);
866   if (status != ESESTATUS_SUCCESS) {
867     LOG(ERROR) << "phNxpEse_ResetEndPoint_Cntxt failed!!!";
868     mIsDeInitDone = false;
869   }
870   status = phNxpEse_close(deInitStatus);
871   if (status == ESESTATUS_SUCCESS && mIsDeInitDone) {
872     sestatus = SESTATUS_SUCCESS;
873   } else {
874     LOG(ERROR) << "seHalDeInit: Failed";
875   }
876   mIsEseInitialized = false;
877   for (uint8_t xx = 0; xx < mMaxChannelCount; xx++) {
878     mOpenedChannels[xx] = false;
879   }
880   mOpenedchannelCount = 0;
881 
882   return sestatus;
883 }
884 
reset()885 ScopedAStatus SecureElement::reset() {
886   LOG(INFO) << __func__;
887   ESESTATUS status = ESESTATUS_SUCCESS;
888   int sestatus = ISecureElement::FAILED;
889   LOG(INFO) << __func__ << " Enter";
890   if (!mIsEseInitialized) {
891     ESESTATUS status = seHalInit();
892     if (status != ESESTATUS_SUCCESS) {
893       LOG(ERROR) << __func__ << " seHalInit Failed!!!";
894     }
895   }
896   if (status == ESESTATUS_SUCCESS) {
897     mCb->onStateChange(false, "reset");
898     status = phNxpEse_reset();
899     if (status != ESESTATUS_SUCCESS) {
900       LOG(ERROR) << __func__ << " SecureElement reset failed!!";
901     } else {
902       sestatus = SESTATUS_SUCCESS;
903       if (mOpenedChannels.size() == 0x00) {
904         mMaxChannelCount = getMaxChannelCnt();
905         mOpenedChannels.resize(mMaxChannelCount, false);
906       }
907       for (uint8_t xx = 0; xx < mMaxChannelCount; xx++) {
908         mOpenedChannels[xx] = false;
909       }
910       mOpenedchannelCount = 0;
911       mCb->onStateChange(true, "reset");
912     }
913   }
914   LOG(ERROR) << __func__ << ": Exit";
915   return sestatus == SESTATUS_SUCCESS
916              ? ndk::ScopedAStatus::ok()
917              : ndk::ScopedAStatus::fromServiceSpecificError(sestatus);
918 }
919 
getResponseInternal(uint8_t cla,phNxpEse_7816_rpdu_t & rpdu,std::vector<uint8_t> & result)920 static int getResponseInternal(uint8_t cla, phNxpEse_7816_rpdu_t& rpdu,
921                                std::vector<uint8_t>& result) {
922   int sestatus = SESTATUS_SUCCESS;
923   ESESTATUS status = ESESTATUS_SUCCESS;
924   phNxpEse_data cmdApdu;
925   phNxpEse_data rspApdu;
926   uint16_t responseLen = rpdu.len;  // Response already copied
927   uint8_t getRespLe = rpdu.sw2;     // Response pending to receive
928   uint8_t getResponse[5] = {0x00, 0xC0, 0x00, 0x00, 0x00};
929 
930   getResponse[0] = cla;
931 
932   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
933 
934   cmdApdu.len = (uint32_t)sizeof(getResponse);
935   cmdApdu.p_data = getResponse;
936 
937   do {
938     // update GET response 61 xx(Le)
939     getResponse[4] = getRespLe;
940 
941     phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
942 
943     status = phNxpEse_Transceive(&cmdApdu, &rspApdu);
944     if (status != ESESTATUS_SUCCESS) {
945       /*Transceive failed*/
946       if (rspApdu.len > 0 && (rspApdu.p_data[rspApdu.len - 2] == 0x64 &&
947                               rspApdu.p_data[rspApdu.len - 1] == 0xFF)) {
948         sestatus = ISecureElement::IOERROR;
949       } else {
950         sestatus = ISecureElement::FAILED;
951       }
952       break;
953     } else {
954       uint32_t respLen = rspApdu.len;
955 
956       // skip 2 bytes in case of 61xx SW again
957       if (rspApdu.p_data[respLen - 2] == SW1_BYTES_REMAINING) {
958         respLen -= 2;
959         getRespLe = rspApdu.p_data[respLen - 1];
960       }
961       // copy response chunk received
962       result.resize(responseLen + respLen);
963       memcpy(&result[responseLen], rspApdu.p_data, respLen);
964       responseLen += respLen;
965     }
966   } while (rspApdu.p_data[rspApdu.len - 2] == SW1_BYTES_REMAINING);
967 
968   // Propagate SW as it is received from card
969   if (sestatus == SESTATUS_SUCCESS) {
970     rpdu.sw1 = rspApdu.p_data[rspApdu.len - 2];
971     rpdu.sw2 = rspApdu.p_data[rspApdu.len - 1];
972   } else {  // Other Failure cases update failure SW:64FF
973     rpdu.sw1 = INVALID_LEN_SW1;
974     rpdu.sw2 = INVALID_LEN_SW2;
975   }
976 
977   return sestatus;
978 }
979 
getReserveChannelCnt(const std::vector<uint8_t> & aid)980 uint8_t SecureElement::getReserveChannelCnt(const std::vector<uint8_t>& aid) {
981   const std::vector<uint8_t> araAid = {0xA0, 0x00, 0x00, 0x01, 0x51,
982                                        0x41, 0x43, 0x4C, 0x00};
983   uint8_t reserveChannel = 0;
984   // Check priority access enabled then only reserve channel
985   if (mHasPriorityAccess && !isWeaverApplet(aid) && aid != araAid) {
986     // Exclude basic channel
987     reserveChannel = 1;
988   }
989   return reserveChannel;
990 }
991 
getMaxChannelCnt()992 uint8_t SecureElement::getMaxChannelCnt() {
993   /*
994    * 1) SN1xx max channel supported 4.
995    * 2) SN220 up to v2 max channel supported 5 (If priority access)
996    *    otherwise 4 channel.
997    * 3) SN220 v3 and higher shall be updated accordingly.
998    */
999   uint8_t cnt = 0;
1000   if (GET_CHIP_OS_VERSION() < OS_VERSION_6_2)
1001     cnt = NUM_OF_CH4;
1002   else if (GET_CHIP_OS_VERSION() == OS_VERSION_6_2)
1003     cnt = (mHasPriorityAccess ? NUM_OF_CH5 : NUM_OF_CH4);
1004   else
1005     cnt = NUM_OF_CH5;
1006 
1007   return cnt;
1008 }
1009 
handleStateOnDeath()1010 void SecureElement::handleStateOnDeath() {
1011   if (!isClientVts(mCbClientUid)) {
1012     seHalClientLock.unlock();
1013   }
1014 }
handleClientCbCleanup()1015 void SecureElement::handleClientCbCleanup() {
1016   if (!isClientVts(mCbClientUid) && !isOmapi) {
1017     seHalClientLock.unlock();
1018   }
1019 }
1020 
handleClientCallback(const std::shared_ptr<ISecureElementCallback> & clientCallback)1021 bool SecureElement::handleClientCallback(
1022     const std::shared_ptr<ISecureElementCallback>& clientCallback) {
1023   AutoMutex guard(initLock);
1024   LOG(INFO) << "isOmapi : " << isOmapi;
1025   uid_t currentClientUid = AIBinder_getCallingUid();
1026   if (isOmapi && (currentClientUid != AID_SECURE_ELEMENT)) {
1027     return false;
1028   }
1029   // Lock the mutex until the acquired client either closes the channel or
1030   // killed.
1031   seHalClientLock.lock();
1032   // Check if the client exists before registering the callback.
1033   if (!ndk::ScopedAStatus::fromStatus(
1034            AIBinder_ping(clientCallback->asBinder().get()))
1035            .isOk()) {
1036     LOG(INFO) << "currentClientUid: " << currentClientUid
1037               << "died, so release the mutex.";
1038     seHalClientLock.unlock();
1039     return false;
1040   }
1041   isOmapi = (currentClientUid == AID_SECURE_ELEMENT);
1042 
1043   return true;
1044 }
1045 
isClientVts(uid_t clientUid)1046 bool SecureElement::isClientVts(uid_t clientUid) {
1047   return (AID_ROOT == clientUid);
1048 }
1049 
1050 }  // namespace secure_element
1051 }  // namespace hardware
1052 }  // namespace android
1053 }  // namespace aidl
1054