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