• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*******************************************************************************
2  *
3  *  Copyright 2018 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 #define LOG_TAG "LSClient"
19 #include <LsClient.h>
20 #include <LsLib.h>
21 #include <errno.h>
22 #include <log/log.h>
23 #include <stdlib.h>
24 #include <string.h>
25 
26 extern bool ese_debug_enabled;
27 
28 static int32_t gsTransceiveTimeout = 120000;
29 static uint8_t gsCmd_Buffer[64 * 1024];
30 static int32_t gsCmd_count = 0;
31 static bool gsIslastcmdLoad;
32 static bool gsSendBack_cmds = false;
33 static uint8_t* gspBuffer;
34 static uint8_t gsStoreData[22];
35 static uint8_t gsTag42Arr[17];
36 static uint8_t gsTag45Arr[9];
37 static uint8_t gsLsExecuteResp[4];
38 static int32_t gsResp_len = 0;
39 
40 LSCSTATUS(*Applet_load_seqhandler[])
41 (Lsc_ImageInfo_t* pContext, LSCSTATUS status, Lsc_TranscieveInfo_t* pInfo) = {
42     LSC_OpenChannel, LSC_ResetChannel, LSC_SelectLsc,
43     LSC_StoreData,   LSC_loadapplet,   NULL};
44 
45 /*******************************************************************************
46 **
47 ** Function:        Perform_LSC
48 **
49 ** Description:     Performs the LSC download sequence
50 **
51 ** Returns:         Success if ok.
52 **
53 *******************************************************************************/
Perform_LSC(const char * name,const char * dest,const uint8_t * pdata,uint16_t len,uint8_t * respSW)54 LSCSTATUS Perform_LSC(const char* name, const char* dest, const uint8_t* pdata,
55                       uint16_t len, uint8_t* respSW) {
56   static const char fn[] = "Perform_LSC";
57   ALOGD_IF(ese_debug_enabled, "%s: enter; sha-len=%d", fn, len);
58   if ((pdata == NULL) || (len == 0x00)) {
59     ALOGE("%s: Invalid SHA-data", fn);
60     return LSCSTATUS_FAILED;
61   }
62   gsStoreData[0] = STORE_DATA_TAG;
63   gsStoreData[1] = len;
64   memcpy(&gsStoreData[2], pdata, len);
65   LSCSTATUS status = LSC_update_seq_handler(Applet_load_seqhandler, name, dest);
66   if ((status != LSCSTATUS_SUCCESS) && (gsLsExecuteResp[2] == 0x90) &&
67       (gsLsExecuteResp[3] == 0x00)) {
68     gsLsExecuteResp[2] = LS_ABORT_SW1;
69     gsLsExecuteResp[3] = LS_ABORT_SW2;
70   }
71   memcpy(&respSW[0], &gsLsExecuteResp[0], 4);
72   ALOGD_IF(ese_debug_enabled, "%s: lsExecuteScript Response SW=%2x%2x", fn,
73            gsLsExecuteResp[2], gsLsExecuteResp[3]);
74 
75   ALOGD_IF(ese_debug_enabled, "%s: exit; status=0x0%x", fn, status);
76   return status;
77 }
78 
79 /*******************************************************************************
80 **
81 ** Function:        LSC_update_seq_handler
82 **
83 ** Description:     Performs the LSC update sequence handler sequence
84 **
85 ** Returns:         Success if ok.
86 **
87 *******************************************************************************/
LSC_update_seq_handler(LSCSTATUS (* seq_handler[])(Lsc_ImageInfo_t * pContext,LSCSTATUS status,Lsc_TranscieveInfo_t * pInfo),const char * name,const char * dest)88 LSCSTATUS LSC_update_seq_handler(
89     LSCSTATUS (*seq_handler[])(Lsc_ImageInfo_t* pContext, LSCSTATUS status,
90                                Lsc_TranscieveInfo_t* pInfo),
91     const char* name, const char* dest) {
92   static const char fn[] = "LSC_update_seq_handler";
93   Lsc_ImageInfo_t update_info;
94 
95   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
96   memset(&update_info, 0, sizeof(Lsc_ImageInfo_t));
97   if (dest != NULL) {
98     strcat(update_info.fls_RespPath, dest);
99     ALOGD_IF(ese_debug_enabled,
100              "%s: Loader Service response data path/destination: %s", fn, dest);
101     update_info.bytes_wrote = 0xAA;
102   } else {
103     update_info.bytes_wrote = 0x55;
104   }
105   if ((LSC_UpdateExeStatus(LS_DEFAULT_STATUS)) != true) {
106     return LSCSTATUS_FAILED;
107   }
108   // memcpy(update_info.fls_path, (char*)Lsc_path, sizeof(Lsc_path));
109   strcat(update_info.fls_path, name);
110   ALOGD_IF(ese_debug_enabled, "Selected applet to install is: %s",
111            update_info.fls_path);
112 
113   uint16_t seq_counter = 0;
114   LSCSTATUS status = LSCSTATUS_FAILED;
115   Lsc_TranscieveInfo_t trans_info;
116   memset(&trans_info, 0, sizeof(Lsc_TranscieveInfo_t));
117   while ((seq_handler[seq_counter]) != NULL) {
118     status = (*(seq_handler[seq_counter]))(&update_info, status, &trans_info);
119     if (LSCSTATUS_SUCCESS != status) {
120       ALOGE("%s: exiting; status=0x0%X", fn, status);
121       break;
122     }
123 
124     if ((seq_counter == 0x00) &&
125         update_info.Channel_Info[update_info.channel_cnt - 1].isOpend) {
126       update_info.initChannelNum =
127           update_info.Channel_Info[update_info.channel_cnt - 1].channel_id;
128     }
129     seq_counter++;
130   }
131 
132   LSC_CloseChannel(&update_info, LSCSTATUS_FAILED, &trans_info);
133   ALOGD_IF(ese_debug_enabled, "%s: exit; status=0x%x", fn, status);
134   return status;
135 }
136 
137 /*******************************************************************************
138 **
139 ** Function:        LSC_OpenChannel
140 **
141 ** Description:     Creates the logical channel with lsc
142 **
143 ** Returns:         Success if ok.
144 **
145 *******************************************************************************/
LSC_OpenChannel(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)146 LSCSTATUS LSC_OpenChannel(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
147                           Lsc_TranscieveInfo_t* pTranscv_Info) {
148   static const char fn[] = "LSC_OpenChannel";
149 
150   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
151   if (Os_info == NULL || pTranscv_Info == NULL) {
152     ALOGE("%s: Invalid parameter", fn);
153     return LSCSTATUS_FAILED;
154   }
155   phNxpEse_data cmdApdu;
156   phNxpEse_data rspApdu;
157   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
158   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
159   cmdApdu.len = (int32_t)sizeof(OpenChannel);
160   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
161   memcpy(cmdApdu.p_data, OpenChannel, cmdApdu.len);
162 
163   ALOGD_IF(ese_debug_enabled, "%s: Calling Secure Element Transceive", fn);
164   ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
165 
166   if (eseStat != ESESTATUS_SUCCESS && (rspApdu.len < 0x03)) {
167     if (rspApdu.len == 0x02)
168       memcpy(&gsLsExecuteResp[2], &rspApdu.p_data[rspApdu.len - 2], 2);
169     status = LSCSTATUS_FAILED;
170     ALOGE("%s: SE transceive failed status = 0x%X", fn, status);
171   } else if (((rspApdu.p_data[rspApdu.len - 2] != 0x90) &&
172               (rspApdu.p_data[rspApdu.len - 1] != 0x00))) {
173     memcpy(&gsLsExecuteResp[2], &rspApdu.p_data[rspApdu.len - 2], 2);
174     status = LSCSTATUS_FAILED;
175     ALOGE("%s: invalid response = 0x%X", fn, status);
176   } else {
177     uint8_t cnt = Os_info->channel_cnt;
178     Os_info->Channel_Info[cnt].channel_id = rspApdu.p_data[rspApdu.len - 3];
179     Os_info->Channel_Info[cnt].isOpend = true;
180     Os_info->channel_cnt++;
181     status = LSCSTATUS_SUCCESS;
182   }
183 
184   phNxpEse_free(cmdApdu.p_data);
185   phNxpEse_free(rspApdu.p_data);
186   ALOGD_IF(ese_debug_enabled, "%s: exit; status=0x%x", fn, status);
187   return status;
188 }
189 /*******************************************************************************
190 **
191 ** Function:        LSC_ResetChannel
192 **
193 ** Description:     Reset(Open & Close) next available logical channel
194 **
195 ** Returns:         Success if ok.
196 **
197 *******************************************************************************/
LSC_ResetChannel(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)198 LSCSTATUS LSC_ResetChannel(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
199                            Lsc_TranscieveInfo_t* pTranscv_Info) {
200   static const char fn[] = "LSC_ResetChannel";
201 
202   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
203   if (Os_info == NULL || pTranscv_Info == NULL) {
204     ALOGE("%s: Invalid parameter", fn);
205     return LSCSTATUS_FAILED;
206   }
207 
208   ESESTATUS eseStat = ESESTATUS_FAILED;
209   bool bResetCompleted = false;
210   phNxpEse_data cmdApdu;
211   phNxpEse_data rspApdu;
212   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
213   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
214   cmdApdu.len = (int32_t)sizeof(OpenChannel);
215   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
216   memcpy(cmdApdu.p_data, OpenChannel, cmdApdu.len);
217 
218   do {
219     ALOGD_IF(ese_debug_enabled, "%s: Calling Secure Element Transceive", fn);
220     eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
221     if (eseStat != ESESTATUS_SUCCESS && (rspApdu.len < 0x03)) {
222       status = LSCSTATUS_FAILED;
223       ALOGE("%s: SE transceive failed status = 0x%X", fn, status);
224     } else if (((rspApdu.p_data[rspApdu.len - 2] != 0x90) &&
225                 (rspApdu.p_data[rspApdu.len - 1] != 0x00))) {
226       status = LSCSTATUS_FAILED;
227       ALOGE("%s: invalid response = 0x%X", fn, status);
228     } else if (!bResetCompleted) {
229       /*close the previously opened channel*/
230       uint8_t xx = 0;
231       cmdApdu.p_data[xx++] = rspApdu.p_data[rspApdu.len - 3]; /*channel id*/
232       cmdApdu.p_data[xx++] = 0x70;
233       cmdApdu.p_data[xx++] = 0x80;
234       cmdApdu.p_data[xx++] = rspApdu.p_data[rspApdu.len - 3];
235       cmdApdu.p_data[xx++] = 0x00;
236       cmdApdu.len = 5;
237       bResetCompleted = true;
238       phNxpEse_free(rspApdu.p_data);
239       status = LSCSTATUS_SUCCESS;
240     } else {
241       ALOGD_IF(ese_debug_enabled, "%s: Channel reset success", fn);
242       status = LSCSTATUS_SUCCESS;
243       break;
244     }
245   } while (status == LSCSTATUS_SUCCESS);
246 
247   phNxpEse_free(cmdApdu.p_data);
248   phNxpEse_free(rspApdu.p_data);
249   ALOGD_IF(ese_debug_enabled, "%s: exit; status=0x%x", fn, status);
250   return status;
251 }
252 
253 /*******************************************************************************
254 **
255 ** Function:        LSC_SelectLsc
256 **
257 ** Description:     Creates the logical channel with lsc
258 **                  Channel_id will be used for any communication with Lsc
259 **
260 ** Returns:         Success if ok.
261 **
262 *******************************************************************************/
LSC_SelectLsc(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)263 LSCSTATUS LSC_SelectLsc(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
264                         Lsc_TranscieveInfo_t* pTranscv_Info) {
265   static const char fn[] = "LSC_SelectLsc";
266 
267   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
268 
269   if (Os_info == NULL || pTranscv_Info == NULL) {
270     ALOGE("%s: Invalid parameter", fn);
271     return LSCSTATUS_FAILED;
272   }
273 
274   phNxpEse_data cmdApdu;
275   phNxpEse_data rspApdu;
276 
277   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
278   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
279 
280   /*p_data will have channel_id (1 byte) + SelectLsc APDU*/
281   cmdApdu.len = (int32_t)(sizeof(SelectLsc) + 1);
282   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
283   cmdApdu.p_data[0] = Os_info->Channel_Info[0].channel_id;
284 
285   memcpy(&(cmdApdu.p_data[1]), SelectLsc, sizeof(SelectLsc));
286 
287   ALOGD_IF(ese_debug_enabled,
288            "%s: Calling Secure Element Transceive with Loader service AID", fn);
289 
290   ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
291 
292   if (eseStat != ESESTATUS_SUCCESS && (rspApdu.len == 0x00)) {
293     status = LSCSTATUS_FAILED;
294     ALOGE("%s: SE transceive failed status = 0x%X", fn, status);
295   } else if (((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
296               (rspApdu.p_data[rspApdu.len - 1] == 0x00))) {
297     status = Process_SelectRsp(rspApdu.p_data, (rspApdu.len - 2));
298     if (status != LSCSTATUS_SUCCESS) {
299       ALOGE("%s: Select Lsc Rsp doesnt have a valid key; status = 0x%X", fn,
300             status);
301     }
302   } else if (((rspApdu.p_data[rspApdu.len - 2] != 0x90))) {
303     /*Copy the response SW in failure case*/
304     memcpy(&gsLsExecuteResp[2], &(rspApdu.p_data[rspApdu.len - 2]), 2);
305   } else {
306     status = LSCSTATUS_FAILED;
307   }
308   phNxpEse_free(cmdApdu.p_data);
309   phNxpEse_free(rspApdu.p_data);
310   ALOGD_IF(ese_debug_enabled, "%s: exit; status=0x%x", fn, status);
311   return status;
312 }
313 
314 /*******************************************************************************
315 **
316 ** Function:        LSC_StoreData
317 **
318 ** Description:     It is used to provide the LSC with an Unique
319 **                  Identifier of the Application that has triggered the LSC
320 *script.
321 **
322 ** Returns:         Success if ok.
323 **
324 *******************************************************************************/
LSC_StoreData(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)325 LSCSTATUS LSC_StoreData(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
326                         Lsc_TranscieveInfo_t* pTranscv_Info) {
327   static const char fn[] = "LSC_StoreData";
328   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
329   if (Os_info == NULL || pTranscv_Info == NULL) {
330     ALOGE("%s: Invalid parameter", fn);
331     return LSCSTATUS_FAILED;
332   }
333 
334   phNxpEse_data cmdApdu;
335   phNxpEse_data rspApdu;
336   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
337   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
338   cmdApdu.len = (int32_t)(5 + sizeof(gsStoreData));
339   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
340 
341   uint32_t xx = 0;
342   int32_t len =
343       gsStoreData[1] + 2;  //+2 offset is for tag value and length byte
344   cmdApdu.p_data[xx++] = STORE_DATA_CLA | (Os_info->Channel_Info[0].channel_id);
345   cmdApdu.p_data[xx++] = STORE_DATA_INS;
346   cmdApdu.p_data[xx++] = 0x00;  // P1
347   cmdApdu.p_data[xx++] = 0x00;  // P2
348   cmdApdu.p_data[xx++] = len;
349   memcpy(&(cmdApdu.p_data[xx]), gsStoreData, len);
350 
351   ALOGD_IF(ese_debug_enabled, "%s: Calling Secure Element Transceive", fn);
352   ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
353 
354   if ((eseStat != ESESTATUS_SUCCESS) && (rspApdu.len == 0x00)) {
355     status = LSCSTATUS_FAILED;
356     ALOGE("%s: SE transceive failed status = 0x%X", fn, status);
357   } else if ((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
358              (rspApdu.p_data[rspApdu.len - 1] == 0x00)) {
359     ALOGD_IF(ese_debug_enabled, "%s: STORE CMD is successful", fn);
360     status = LSCSTATUS_SUCCESS;
361   } else {
362     /*Copy the response SW in failure case*/
363     memcpy(&gsLsExecuteResp[2], &(rspApdu.p_data[rspApdu.len - 2]), 2);
364     status = LSCSTATUS_FAILED;
365   }
366   phNxpEse_free(cmdApdu.p_data);
367   phNxpEse_free(rspApdu.p_data);
368   ALOGD_IF(ese_debug_enabled, "%s: exit; status=0x%x", fn, status);
369   return status;
370 }
371 
372 /*******************************************************************************
373 **
374 ** Function:        LSC_loadapplet
375 **
376 ** Description:     Reads the script from the file and sent to Lsc
377 **
378 ** Returns:         Success if ok.
379 **
380 *******************************************************************************/
LSC_loadapplet(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)381 LSCSTATUS LSC_loadapplet(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
382                          Lsc_TranscieveInfo_t* pTranscv_Info) {
383   static const char fn[] = "LSC_loadapplet";
384   bool reachEOFCheck = false;
385 
386   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
387   if (Os_info == NULL || pTranscv_Info == NULL) {
388     ALOGE("%s: Invalid parameter", fn);
389     return LSCSTATUS_FAILED;
390   }
391   if (Os_info->bytes_wrote == 0xAA) {
392     Os_info->fResp = fopen(Os_info->fls_RespPath, "a+");
393     if (Os_info->fResp == NULL) {
394       ALOGE("%s: Error opening response recording file <%s> for reading: %s",
395             fn, Os_info->fls_path, strerror(errno));
396       return LSCSTATUS_FAILED;
397     }
398     ALOGD_IF(ese_debug_enabled,
399              "%s: Response OUT FILE path is successfully created", fn);
400   } else {
401     ALOGD_IF(ese_debug_enabled,
402              "%s: Response Out file is optional as per input", fn);
403   }
404 
405   Os_info->fp = fopen(Os_info->fls_path, "r");
406   if (Os_info->fp == NULL) {
407     ALOGE("%s: Error opening OS image file <%s> for reading: %s", fn,
408           Os_info->fls_path, strerror(errno));
409     return LSCSTATUS_FAILED;
410   }
411   int wResult = fseek(Os_info->fp, 0L, SEEK_END);
412   if (wResult) {
413     ALOGE("%s: Error seeking end OS image file %s", fn, strerror(errno));
414     goto exit;
415   }
416   Os_info->fls_size = ftell(Os_info->fp);
417   if (Os_info->fls_size < 0) {
418     ALOGE("%s: Error ftelling file %s", fn, strerror(errno));
419     goto exit;
420   }
421   wResult = fseek(Os_info->fp, 0L, SEEK_SET);
422   if (wResult) {
423     ALOGE("%s: Error seeking start image file %s", fn, strerror(errno));
424     goto exit;
425   }
426 
427   Os_info->bytes_read = 0;
428   status = LSC_Check_KeyIdentifier(Os_info, status, pTranscv_Info, NULL,
429                                    LSCSTATUS_FAILED, 0);
430   if (status != LSCSTATUS_SUCCESS) {
431     goto exit;
432   }
433 
434   uint8_t len_byte, offset;
435   while (!feof(Os_info->fp) && (Os_info->bytes_read < Os_info->fls_size)) {
436     len_byte = 0;
437     offset = 0;
438     /*Check if the certificate/ is verified or not*/
439     if (status != LSCSTATUS_SUCCESS) {
440       goto exit;
441     }
442 
443     uint8_t temp_buf[1024];
444     memset(temp_buf, 0, sizeof(temp_buf));
445     status = LSC_ReadScript(Os_info, temp_buf);
446     if (status != LSCSTATUS_SUCCESS) {
447       goto exit;
448     }
449     /*Reset the flag in case further commands exists*/
450     reachEOFCheck = false;
451 
452     int32_t wLen = 0;
453     LSCSTATUS tag40_found = LSCSTATUS_SUCCESS;
454     if (temp_buf[offset] == TAG_LSC_CMD_ID) {
455       /* start sending the packet to Lsc */
456       offset = offset + 1;
457       len_byte = Numof_lengthbytes(&temp_buf[offset], &wLen);
458       /* If the len data not present or len is less than or equal to 32 */
459       if ((len_byte == 0) || (wLen <= 32)) {
460         ALOGE("%s: Invalid length zero", fn);
461         goto exit;
462       }
463 
464       tag40_found = LSCSTATUS_SUCCESS;
465       offset = offset + len_byte;
466       pTranscv_Info->sSendlength = wLen;
467       memcpy(pTranscv_Info->sSendData, &temp_buf[offset], wLen);
468 
469       status = LSC_SendtoLsc(Os_info, status, pTranscv_Info, LS_Comm);
470       if (status != LSCSTATUS_SUCCESS) {
471         /*When the switching of LS 6320 case*/
472         if (status == LSCSTATUS_SELF_UPDATE_DONE) {
473           status = LSC_CloseAllLogicalChannels(Os_info);
474           if (status != LSCSTATUS_SUCCESS) {
475             ALOGE("%s: CleanupLsUpdaterChannels failed", fn);
476           }
477           status = LSCSTATUS_SUCCESS;
478           goto exit;
479         }
480         ALOGE("%s: Sending packet to lsc failed", fn);
481         goto exit;
482       }
483     } else if ((temp_buf[offset] == (0x7F)) &&
484                (temp_buf[offset + 1] == (0x21))) {
485       ALOGD_IF(ese_debug_enabled,
486                "%s: TAGID: Encountered again certificate tag 7F21", fn);
487       if (tag40_found == LSCSTATUS_SUCCESS) {
488         ALOGD_IF(ese_debug_enabled,
489                  "%s: 2nd Script processing starts with reselect", fn);
490         status = LSCSTATUS_FAILED;
491         status = LSC_SelectLsc(Os_info, status, pTranscv_Info);
492         if (status == LSCSTATUS_SUCCESS) {
493           ALOGD_IF(ese_debug_enabled,
494                    "%s: 2nd Script select success next store data command", fn);
495           status = LSCSTATUS_FAILED;
496           status = LSC_StoreData(Os_info, status, pTranscv_Info);
497           if (status == LSCSTATUS_SUCCESS) {
498             ALOGD_IF(ese_debug_enabled,
499                      "%s: 2nd Script store data success next certificate "
500                      "verification",
501                      fn);
502             offset = offset + 2;
503             len_byte = Numof_lengthbytes(&temp_buf[offset], &wLen);
504             status = LSC_Check_KeyIdentifier(Os_info, status, pTranscv_Info,
505                                              temp_buf, LSCSTATUS_SUCCESS,
506                                              wLen + len_byte + 2);
507           }
508         }
509         /*If the certificate and signature is verified*/
510         if (status == LSCSTATUS_SUCCESS) {
511           /*If the certificate is verified for 6320 then new script starts*/
512           tag40_found = LSCSTATUS_FAILED;
513         } else {
514           /*If the certificate or signature verification failed*/
515           goto exit;
516         }
517       } else {
518         /*Already certificate&Sginature verified previously skip 7f21& tag 60*/
519         memset(temp_buf, 0, sizeof(temp_buf));
520         status = LSC_ReadScript(Os_info, temp_buf);
521         if (status != LSCSTATUS_SUCCESS) {
522           ALOGE("%s: Next Tag has to TAG 60 not found", fn);
523           goto exit;
524         }
525         if (temp_buf[offset] == TAG_JSBL_HDR_ID)
526           continue;
527         else
528           goto exit;
529       }
530     } else {
531       /*
532        * Invalid packet received in between stop processing packet
533        * return failed status
534        */
535       status = LSCSTATUS_FAILED;
536       break;
537     }
538   }
539   if (Os_info->bytes_wrote == 0xAA) {
540     fclose(Os_info->fResp);
541   }
542   LSC_UpdateExeStatus(LS_SUCCESS_STATUS);
543   wResult = fclose(Os_info->fp);
544   ALOGD_IF(ese_debug_enabled, "%s: exit, status=0x%x", fn, status);
545   return status;
546 exit:
547   wResult = fclose(Os_info->fp);
548   if (Os_info->bytes_wrote == 0xAA) {
549     fclose(Os_info->fResp);
550   }
551   /*Script ends with SW 6320 and reached END OF FILE*/
552   if (reachEOFCheck == true) {
553     status = LSCSTATUS_SUCCESS;
554     LSC_UpdateExeStatus(LS_SUCCESS_STATUS);
555   }
556   ALOGD_IF(ese_debug_enabled, "%s: exit; status= 0x%X", fn, status);
557   return status;
558 }
559 
560 /*******************************************************************************
561 **
562 ** Function:        LSC_Check_KeyIdentifier
563 **
564 ** Description:     Checks and validates certificate
565 **
566 ** Returns:         Success if ok.
567 **
568 *******************************************************************************/
LSC_Check_KeyIdentifier(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info,uint8_t * temp_buf,LSCSTATUS flag,int32_t wNewLen)569 LSCSTATUS LSC_Check_KeyIdentifier(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
570                                   Lsc_TranscieveInfo_t* pTranscv_Info,
571                                   uint8_t* temp_buf, LSCSTATUS flag,
572                                   int32_t wNewLen) {
573   static const char fn[] = "LSC_Check_KeyIdentifier";
574   status = LSCSTATUS_FAILED;
575   uint8_t read_buf[1024];
576   uint16_t offset = 0, len_byte = 0;
577   int32_t wLen;
578   uint8_t certf_found = LSCSTATUS_FAILED;
579 
580   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
581 
582   while (!feof(Os_info->fp) && (Os_info->bytes_read < Os_info->fls_size)) {
583     offset = 0x00;
584     wLen = 0;
585     if (flag == LSCSTATUS_SUCCESS) {
586       /*If the 7F21 TAG is already read: After TAG 40*/
587       memcpy(read_buf, temp_buf, wNewLen);
588       status = LSCSTATUS_SUCCESS;
589       flag = LSCSTATUS_FAILED;
590     } else {
591       /*If the 7F21 TAG is not read: Before TAG 40*/
592       status = LSC_ReadScript(Os_info, read_buf);
593     }
594     if (status != LSCSTATUS_SUCCESS) return status;
595     if (LSCSTATUS_SUCCESS ==
596         Check_Complete_7F21_Tag(Os_info, pTranscv_Info, read_buf, &offset)) {
597       ALOGD_IF(ese_debug_enabled, "%s: Certificate is verified", fn);
598       certf_found = LSCSTATUS_SUCCESS;
599       break;
600     }
601     /*
602      * The Loader Service Client ignores all subsequent commands starting by tag
603      * 7F21 or tag 60 until the first command starting by tag 40 is found
604      */
605     else if (((read_buf[offset] == TAG_LSC_CMD_ID) &&
606               (certf_found != LSCSTATUS_SUCCESS))) {
607       ALOGE("%s: NOT FOUND Root entity identifier's certificate", fn);
608       status = LSCSTATUS_FAILED;
609       return status;
610     }
611   }
612   memset(read_buf, 0, sizeof(read_buf));
613   if (certf_found == LSCSTATUS_SUCCESS) {
614     offset = 0x00;
615     wLen = 0;
616     status = LSC_ReadScript(Os_info, read_buf);
617     if (status != LSCSTATUS_SUCCESS) return status;
618     if ((read_buf[offset] == TAG_JSBL_HDR_ID) &&
619         (certf_found != LSCSTATUS_FAILED)) {
620       // TODO check the SElect cmd response and return status accordingly
621       ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_JSBL_HDR_ID", fn);
622       offset = offset + 1;
623       len_byte = Numof_lengthbytes(&read_buf[offset], &wLen);
624       offset = offset + len_byte;
625       if (read_buf[offset] == TAG_SIGNATURE_ID) {
626         offset = offset + 1;
627         len_byte = Numof_lengthbytes(&read_buf[offset], &wLen);
628         offset = offset + len_byte;
629         ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_SIGNATURE_ID", fn);
630 
631         pTranscv_Info->sSendlength = wLen + 5;
632 
633         pTranscv_Info->sSendData[0] = 0x00;
634         pTranscv_Info->sSendData[1] = 0xA0;
635         pTranscv_Info->sSendData[2] = 0x00;
636         pTranscv_Info->sSendData[3] = 0x00;
637         pTranscv_Info->sSendData[4] = wLen;
638 
639         memcpy(&(pTranscv_Info->sSendData[5]), &read_buf[offset], wLen);
640         ALOGD_IF(ese_debug_enabled, "%s: start transceive for length %ld", fn,
641                  (long)pTranscv_Info->sSendlength);
642         status = LSC_SendtoLsc(Os_info, status, pTranscv_Info, LS_Sign);
643         if (status != LSCSTATUS_SUCCESS) {
644           return status;
645         }
646       }
647     } else if (read_buf[offset] != TAG_JSBL_HDR_ID) {
648       status = LSCSTATUS_FAILED;
649     }
650   } else {
651     ALOGE("%s : Exit certificate verification failed", fn);
652   }
653 
654   ALOGD_IF(ese_debug_enabled, "%s: exit: status=0x%x", fn, status);
655   return status;
656 }
657 
658 /*******************************************************************************
659 **
660 ** Function:        LSC_ReadScript
661 **
662 ** Description:     Reads the current line if the script
663 **
664 ** Returns:         Success if ok.
665 **
666 *******************************************************************************/
LSC_ReadScript(Lsc_ImageInfo_t * Os_info,uint8_t * read_buf)667 LSCSTATUS LSC_ReadScript(Lsc_ImageInfo_t* Os_info, uint8_t* read_buf) {
668   static const char fn[] = "LSC_ReadScript";
669   int32_t wResult = 0, wCount, wIndex = 0;
670 
671   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
672 
673   for (wCount = 0; (wCount < 2 && !feof(Os_info->fp)); wCount++, wIndex++) {
674     wResult = FSCANF_BYTE(Os_info->fp, "%2X", (unsigned int*)&read_buf[wIndex]);
675   }
676   if (wResult == 0) return LSCSTATUS_FAILED;
677 
678   Os_info->bytes_read = Os_info->bytes_read + (wCount * 2);
679 
680   int32_t lenOff = 1;
681   if ((read_buf[0] == 0x7f) && (read_buf[1] == 0x21)) {
682     for (wCount = 0; (wCount < 1 && !feof(Os_info->fp)); wCount++, wIndex++) {
683       wResult =
684           FSCANF_BYTE(Os_info->fp, "%2X", (unsigned int*)&read_buf[wIndex]);
685     }
686     if (wResult == 0) {
687       ALOGE("%s: Exit Read Script failed in 7F21 ", fn);
688       return LSCSTATUS_FAILED;
689     }
690     /*Read_Script from wCount*2 to wCount*1 */
691     Os_info->bytes_read = Os_info->bytes_read + (wCount * 2);
692     lenOff = 2;
693   } else if ((read_buf[0] == 0x40) || (read_buf[0] == 0x60)) {
694     lenOff = 1;
695   } else {
696     /*If TAG is neither 7F21 nor 60 nor 40 then ABORT execution*/
697     ALOGE("%s: Invalid TAG 0x%X found in the script", fn, read_buf[0]);
698     return LSCSTATUS_FAILED;
699   }
700 
701   uint8_t len_byte = 0;
702   int32_t wLen;
703   if (read_buf[lenOff] == 0x00) {
704     ALOGE("%s: Invalid length zero", fn);
705     len_byte = 0x00;
706     return LSCSTATUS_FAILED;
707   } else if ((read_buf[lenOff] & 0x80) == 0x80) {
708     len_byte = read_buf[lenOff] & 0x0F;
709     len_byte = len_byte + 1;  // 1 byte added for byte 0x81
710 
711     ALOGD_IF(ese_debug_enabled, "%s: Length byte Read from 0x80 is 0x%x ", fn,
712              len_byte);
713 
714     if (len_byte == 0x02) {
715       for (wCount = 0; (wCount < 1 && !feof(Os_info->fp)); wCount++, wIndex++) {
716         wResult =
717             FSCANF_BYTE(Os_info->fp, "%2X", (unsigned int*)&read_buf[wIndex]);
718       }
719       if (wResult == 0) {
720         ALOGE("%s: Exit Read Script failed in length 0x02 ", fn);
721         return LSCSTATUS_FAILED;
722       }
723 
724       wLen = read_buf[lenOff + 1];
725       Os_info->bytes_read = Os_info->bytes_read + (wCount * 2);
726       ALOGD_IF(ese_debug_enabled,
727                "%s: Length of Read Script in len_byte= 0x02 is 0x%x ", fn,
728                wLen);
729     } else if (len_byte == 0x03) {
730       for (wCount = 0; (wCount < 2 && !feof(Os_info->fp)); wCount++, wIndex++) {
731         wResult =
732             FSCANF_BYTE(Os_info->fp, "%2X", (unsigned int*)&read_buf[wIndex]);
733       }
734       if (wResult == 0) {
735         ALOGE("%s: Exit Read Script failed in length 0x03 ", fn);
736         return LSCSTATUS_FAILED;
737       }
738 
739       Os_info->bytes_read = Os_info->bytes_read + (wCount * 2);
740       wLen = read_buf[lenOff + 1];  // Length of the packet send to LSC
741       wLen = ((wLen << 8) | (read_buf[lenOff + 2]));
742       ALOGD_IF(ese_debug_enabled,
743                "%s: Length of Read Script in len_byte= 0x03 is 0x%x ", fn,
744                wLen);
745     } else {
746       /*Need to provide the support if length is more than 2 bytes*/
747       ALOGE("Length recived is greater than 3");
748       return LSCSTATUS_FAILED;
749     }
750   } else {
751     len_byte = 0x01;
752     wLen = read_buf[lenOff];
753     ALOGE("%s: Length of Read Script in len_byte= 0x01 is 0x%x ", fn, wLen);
754   }
755 
756   for (wCount = 0; (wCount < wLen && !feof(Os_info->fp)); wCount++, wIndex++) {
757     wResult = FSCANF_BYTE(Os_info->fp, "%2X", (unsigned int*)&read_buf[wIndex]);
758   }
759 
760   if (wResult == 0) {
761     ALOGE("%s: Exit Read Script failed in fscanf function ", fn);
762     return LSCSTATUS_FAILED;
763   }
764   Os_info->bytes_read =
765       Os_info->bytes_read + (wCount * 2) + 1;  // not sure why 2 added
766 
767   ALOGD_IF(ese_debug_enabled, "%s: exit: Num of bytes read=%d and index=%d", fn,
768            Os_info->bytes_read, wIndex);
769 
770   return LSCSTATUS_SUCCESS;
771 }
772 
773 /*******************************************************************************
774 **
775 ** Function:        LSC_SendtoEse
776 **
777 ** Description:     It is used to send the packet to p61
778 **
779 ** Returns:         Success if ok.
780 **
781 *******************************************************************************/
LSC_SendtoEse(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)782 LSCSTATUS LSC_SendtoEse(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
783                         Lsc_TranscieveInfo_t* pTranscv_Info) {
784   static const char fn[] = "LSC_SendtoEse";
785   bool chanl_open_cmd = false;
786 
787   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
788 
789   /* Bufferize_load_cmds function is implemented in JCOP */
790   status = Bufferize_load_cmds(Os_info, status, pTranscv_Info);
791   if (status != LSCSTATUS_FAILED) {
792     if (pTranscv_Info->sSendData[1] == 0x70) {
793       if (pTranscv_Info->sSendData[2] == 0x00) {
794         chanl_open_cmd = true;
795       } else {
796         for (uint8_t cnt = 0; cnt < Os_info->channel_cnt; cnt++) {
797           if (Os_info->Channel_Info[cnt].channel_id ==
798               pTranscv_Info->sSendData[3]) {
799             ALOGD_IF(ese_debug_enabled, "%s: channel 0%x closed", fn,
800                      Os_info->Channel_Info[cnt].channel_id);
801             Os_info->Channel_Info[cnt].isOpend = false;
802           }
803         }
804       }
805     }
806 
807     phNxpEse_data cmdApdu;
808     phNxpEse_data rspApdu;
809     phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
810     phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
811 
812     cmdApdu.len = (int32_t)(pTranscv_Info->sSendlength);
813     cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
814     memcpy(cmdApdu.p_data, pTranscv_Info->sSendData, cmdApdu.len);
815 
816     ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
817 
818     if (eseStat != ESESTATUS_SUCCESS) {
819       ALOGE("%s: Transceive failed; status=0x%X", fn, eseStat);
820       status = LSCSTATUS_FAILED;
821     } else {
822       if (chanl_open_cmd && (rspApdu.len == 0x03) &&
823           ((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
824            (rspApdu.p_data[rspApdu.len - 1] == 0x00))) {
825         ALOGD_IF(ese_debug_enabled, "%s: open channel success", fn);
826         uint8_t cnt = Os_info->channel_cnt;
827         Os_info->Channel_Info[cnt].channel_id = rspApdu.p_data[rspApdu.len - 3];
828         Os_info->Channel_Info[cnt].isOpend = true;
829         Os_info->channel_cnt++;
830       }
831       memcpy(pTranscv_Info->sRecvData, rspApdu.p_data, rspApdu.len);
832       status = Process_EseResponse(pTranscv_Info, rspApdu.len, Os_info);
833       phNxpEse_free(cmdApdu.p_data);
834       phNxpEse_free(rspApdu.p_data);
835     }
836   } else if (gsSendBack_cmds == false) {
837     /* Workaround for issue in JCOP, send the fake response back */
838     int32_t recvBufferActualSize = 0x03;
839     pTranscv_Info->sRecvData[0] = 0x00;
840     pTranscv_Info->sRecvData[1] = 0x90;
841     pTranscv_Info->sRecvData[2] = 0x00;
842     status = Process_EseResponse(pTranscv_Info, recvBufferActualSize, Os_info);
843   } else {
844     if (gsIslastcmdLoad == true) {
845       status = Send_Backall_Loadcmds(Os_info, status, pTranscv_Info);
846       gsSendBack_cmds = false;
847     } else {
848       memset(gsCmd_Buffer, 0, sizeof(gsCmd_Buffer));
849       gsSendBack_cmds = false;
850       status = LSCSTATUS_FAILED;
851     }
852   }
853 
854   ALOGD_IF(ese_debug_enabled, "%s: exit: status=0x%x", fn, status);
855   return status;
856 }
857 
858 /*******************************************************************************
859 **
860 ** Function:        LSC_SendtoLsc
861 **
862 ** Description:     It is used to forward the packet to Lsc
863 **
864 ** Returns:         Success if ok.
865 **
866 *******************************************************************************/
LSC_SendtoLsc(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info,Ls_TagType tType)867 LSCSTATUS LSC_SendtoLsc(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
868                         Lsc_TranscieveInfo_t* pTranscv_Info, Ls_TagType tType) {
869   static const char fn[] = "LSC_SendtoLsc";
870 
871   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
872   pTranscv_Info->sSendData[0] = (0x80 | Os_info->Channel_Info[0].channel_id);
873   pTranscv_Info->timeout = gsTransceiveTimeout;
874   pTranscv_Info->sRecvlength = 1024;
875 
876   phNxpEse_data cmdApdu;
877   phNxpEse_data rspApdu;
878   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
879   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
880   cmdApdu.len = pTranscv_Info->sSendlength;
881   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
882   memcpy(cmdApdu.p_data, pTranscv_Info->sSendData, cmdApdu.len);
883 
884   ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
885 
886   if (eseStat != ESESTATUS_SUCCESS) {
887     ALOGE("%s: Transceive failed; status=0x%X", fn, eseStat);
888     status = LSCSTATUS_FAILED;
889   } else {
890     memcpy(pTranscv_Info->sRecvData, rspApdu.p_data, rspApdu.len);
891     status = LSC_ProcessResp(Os_info, rspApdu.len, pTranscv_Info, tType);
892   }
893   phNxpEse_free(cmdApdu.p_data);
894   phNxpEse_free(rspApdu.p_data);
895   ALOGD_IF(ese_debug_enabled, "%s: exit: status=0x%x", fn, status);
896   return status;
897 }
898 
899 /*******************************************************************************
900 **
901 ** Function:        LSC_CloseChannel
902 **
903 ** Description:     Closes the previously opened logical channel
904 **
905 ** Returns:         Success if ok.
906 **
907 *******************************************************************************/
LSC_CloseChannel(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)908 LSCSTATUS LSC_CloseChannel(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
909                            Lsc_TranscieveInfo_t* pTranscv_Info) {
910   static const char fn[] = "LSC_CloseChannel";
911   status = LSCSTATUS_FAILED;
912 
913   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
914 
915   if (Os_info == NULL || pTranscv_Info == NULL) {
916     ALOGE("%s: Invalid parameter", fn);
917     return LSCSTATUS_FAILED;
918   }
919   for (uint8_t cnt = 0; (cnt < Os_info->channel_cnt); cnt++) {
920     phNxpEse_data cmdApdu;
921     phNxpEse_data rspApdu;
922 
923     phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
924     phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
925 
926     cmdApdu.len = 5;
927     cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
928     if (!Os_info->Channel_Info[cnt].isOpend) continue;
929     uint8_t xx = 0;
930     cmdApdu.p_data[xx++] = Os_info->Channel_Info[cnt].channel_id;
931     cmdApdu.p_data[xx++] = 0x70;
932     cmdApdu.p_data[xx++] = 0x80;
933     cmdApdu.p_data[xx++] = Os_info->Channel_Info[cnt].channel_id;
934     cmdApdu.p_data[xx++] = 0x00;
935 
936     ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
937 
938     if (eseStat != ESESTATUS_SUCCESS || rspApdu.len < 2) {
939       ALOGD_IF(ese_debug_enabled, "%s: Transceive failed; status=0x%X", fn,
940                eseStat);
941     } else if ((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
942                (rspApdu.p_data[rspApdu.len - 1] == 0x00)) {
943       ALOGD_IF(ese_debug_enabled, "%s: Close channel id = 0x0%x success", fn,
944                Os_info->Channel_Info[cnt].channel_id);
945       if (Os_info->Channel_Info[cnt].channel_id == Os_info->initChannelNum) {
946         Os_info->initChannelNum = 0x00;
947       }
948       status = LSCSTATUS_SUCCESS;
949     } else {
950       ALOGD_IF(ese_debug_enabled, "%s: Close channel id = 0x0%x failed", fn,
951                Os_info->Channel_Info[cnt].channel_id);
952     }
953     phNxpEse_free(cmdApdu.p_data);
954     phNxpEse_free(rspApdu.p_data);
955   }
956   ALOGD_IF(ese_debug_enabled, "%s: exit; status=0x0%x", fn, status);
957   return status;
958 }
959 
960 /*******************************************************************************
961 **
962 ** Function:        LSC_ProcessResp
963 **
964 ** Description:     Process the response packet received from Lsc
965 **
966 ** Returns:         Success if ok.
967 **
968 *******************************************************************************/
LSC_ProcessResp(Lsc_ImageInfo_t * image_info,int32_t recvlen,Lsc_TranscieveInfo_t * trans_info,Ls_TagType tType)969 LSCSTATUS LSC_ProcessResp(Lsc_ImageInfo_t* image_info, int32_t recvlen,
970                           Lsc_TranscieveInfo_t* trans_info, Ls_TagType tType) {
971   static const char fn[] = "LSC_ProcessResp";
972   uint8_t* RecvData = trans_info->sRecvData;
973 
974   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
975 
976   if (RecvData == NULL && recvlen == 0x00) {
977     ALOGE("%s: Invalid parameter.", fn);
978     return LSCSTATUS_FAILED;
979   } else if (recvlen < 2) {
980     ALOGE("%s: Invalid response.", fn);
981     return LSCSTATUS_FAILED;
982   }
983 
984   char sw[2];
985   sw[0] = RecvData[recvlen - 2];
986   sw[1] = RecvData[recvlen - 1];
987   ALOGD_IF(ese_debug_enabled, "%s: Process Response SW, status = 0x%2X%2X", fn,
988            sw[0], sw[1]);
989 
990   /*Update the Global variable for storing response length*/
991   gsResp_len = recvlen;
992   if (sw[0] != 0x63) {
993     gsLsExecuteResp[2] = sw[0];
994     gsLsExecuteResp[3] = sw[1];
995   }
996 
997   LSCSTATUS status = LSCSTATUS_FAILED;
998   if ((recvlen == 0x02) && (sw[0] == 0x90) && (sw[1] == 0x00)) {
999     status = Write_Response_To_OutFile(image_info, RecvData, recvlen, tType);
1000   } else if ((recvlen > 0x02) && (sw[0] == 0x90) && (sw[1] == 0x00)) {
1001     status = Write_Response_To_OutFile(image_info, RecvData, recvlen, tType);
1002   } else if ((recvlen > 0x02) && (sw[0] == 0x63) && (sw[1] == 0x10)) {
1003     static int32_t temp_len = 0;
1004     if (temp_len != 0) {
1005       memcpy((trans_info->sTemp_recvbuf + temp_len), RecvData, (recvlen - 2));
1006       trans_info->sSendlength = temp_len + (recvlen - 2);
1007       memcpy(trans_info->sSendData, trans_info->sTemp_recvbuf,
1008              trans_info->sSendlength);
1009       temp_len = 0;
1010     } else {
1011       memcpy(trans_info->sSendData, RecvData, (recvlen - 2));
1012       trans_info->sSendlength = recvlen - 2;
1013     }
1014     status = LSC_SendtoEse(image_info, status, trans_info);
1015   } else if ((recvlen > 0x02) && (sw[0] == 0x63) && (sw[1] == 0x20)) {
1016     /*In case of self update, status 0x6320 indicates script execution success
1017     and response data has new AID*/
1018     status = LSCSTATUS_SELF_UPDATE_DONE;
1019   } else if ((recvlen >= 0x02) &&
1020              ((sw[0] != 0x90) && (sw[0] != 0x63) && (sw[0] != 0x61))) {
1021     Write_Response_To_OutFile(image_info, RecvData, recvlen, tType);
1022   }
1023   ALOGD_IF(ese_debug_enabled, "%s: exit: status=0x%x", fn, status);
1024   return status;
1025 }
1026 
1027 /*******************************************************************************
1028 **
1029 ** Function:        Process_EseResponse
1030 **
1031 ** Description:     It is used to process the received response packet from ESE
1032 **
1033 ** Returns:         Success if ok.
1034 **
1035 *******************************************************************************/
Process_EseResponse(Lsc_TranscieveInfo_t * pTranscv_Info,int32_t recv_len,Lsc_ImageInfo_t * Os_info)1036 LSCSTATUS Process_EseResponse(Lsc_TranscieveInfo_t* pTranscv_Info,
1037                               int32_t recv_len, Lsc_ImageInfo_t* Os_info) {
1038   static const char fn[] = "Process_EseResponse";
1039   LSCSTATUS status = LSCSTATUS_SUCCESS;
1040   uint8_t xx = 0;
1041   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
1042 
1043   pTranscv_Info->sSendData[xx++] =
1044       (CLA_BYTE | Os_info->Channel_Info[0].channel_id);
1045   pTranscv_Info->sSendData[xx++] = 0xA2;
1046 
1047   if (recv_len <= 0xFF) {
1048     pTranscv_Info->sSendData[xx++] = 0x80;
1049     pTranscv_Info->sSendData[xx++] = 0x00;
1050     pTranscv_Info->sSendData[xx++] = (uint8_t)recv_len;
1051     memcpy(&(pTranscv_Info->sSendData[xx]), pTranscv_Info->sRecvData, recv_len);
1052     pTranscv_Info->sSendlength = xx + recv_len;
1053     status = LSC_SendtoLsc(Os_info, status, pTranscv_Info, LS_Comm);
1054   } else {
1055     while (recv_len > MAX_SIZE) {
1056       xx = PARAM_P1_OFFSET;
1057       pTranscv_Info->sSendData[xx++] = 0x00;
1058       pTranscv_Info->sSendData[xx++] = 0x00;
1059       pTranscv_Info->sSendData[xx++] = MAX_SIZE;
1060       recv_len = recv_len - MAX_SIZE;
1061       memcpy(&(pTranscv_Info->sSendData[xx]), pTranscv_Info->sRecvData,
1062              MAX_SIZE);
1063       pTranscv_Info->sSendlength = xx + MAX_SIZE;
1064       /*
1065        * Need not store Process eSE response's response in the out file so
1066        * LS_Comm = 0
1067        */
1068       status = LSC_SendtoLsc(Os_info, status, pTranscv_Info, LS_Comm);
1069       if (status != LSCSTATUS_SUCCESS) {
1070         ALOGE("%s: Sending packet to Lsc failed: status=0x%x", fn, status);
1071         return status;
1072       }
1073     }
1074     xx = PARAM_P1_OFFSET;
1075     pTranscv_Info->sSendData[xx++] = LAST_BLOCK;
1076     pTranscv_Info->sSendData[xx++] = 0x01;
1077     pTranscv_Info->sSendData[xx++] = recv_len;
1078     memcpy(&(pTranscv_Info->sSendData[xx]), pTranscv_Info->sRecvData, recv_len);
1079     pTranscv_Info->sSendlength = xx + recv_len;
1080     status = LSC_SendtoLsc(Os_info, status, pTranscv_Info, LS_Comm);
1081   }
1082   ALOGD_IF(ese_debug_enabled, "%s: exit: status=0x%x", fn, status);
1083   return status;
1084 }
1085 
1086 /*******************************************************************************
1087 **
1088 ** Function:        Process_SelectRsp
1089 **
1090 ** Description:    It is used to process the received response for SELECT LSC
1091 **                 cmd.
1092 **
1093 ** Returns:         Success if ok.
1094 **
1095 *******************************************************************************/
Process_SelectRsp(uint8_t * Recv_data,int32_t Recv_len)1096 LSCSTATUS Process_SelectRsp(uint8_t* Recv_data, int32_t Recv_len) {
1097   static const char fn[] = "Process_SelectRsp";
1098   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
1099 
1100   if (Recv_len < 2) {
1101     ALOGE("%s: Invalid response length %d", fn, Recv_len);
1102     return LSCSTATUS_FAILED;
1103   }
1104 
1105   int i = 0;
1106   if (Recv_data[i] != TAG_SELECT_ID) {
1107     ALOGE("%s: Invalid FCI TAG = 0x%x", fn, Recv_data[i]);
1108     return LSCSTATUS_FAILED;
1109   }
1110   i++;
1111   int len = Recv_data[i++];
1112   if (Recv_len < len + 2) {
1113     ALOGE("%s: Invalid response length %d", fn, Recv_len);
1114     return LSCSTATUS_FAILED;
1115   }
1116   if (Recv_data[i] != TAG_LSC_ID) {
1117     ALOGE("%s: Invalid Loader Service AID TAG ID = 0x%x", fn, Recv_data[i]);
1118     return LSCSTATUS_FAILED;
1119   }
1120   i++;
1121   len = Recv_data[i];
1122   i = i + 1 + len;  // points to next tag name A5
1123   // points to TAG 9F08 for LS application version
1124   if ((Recv_data[i] != TAG_LS_VER1) || (Recv_data[i + 1] != TAG_LS_VER2)) {
1125     ALOGE("%s: Invalid LS Version = 0x%2X%2X", fn, Recv_data[i],
1126           Recv_data[i + 1]);
1127     return LSCSTATUS_FAILED;
1128   }
1129   uint8_t lsaVersionLen = 0;
1130   i = i + 2;
1131   lsaVersionLen = Recv_data[i];
1132   // points to TAG 9F08 LS application version
1133   i++;
1134   // points to Identifier of the Root Entity key set identifier
1135   i = i + lsaVersionLen;
1136 
1137   if (Recv_data[i] != TAG_RE_KEYID) {
1138     ALOGE("%s: Invalid Root entity key set TAG ID = 0x%x", fn, Recv_data[i]);
1139     return LSCSTATUS_FAILED;
1140   }
1141 
1142   i = i + 2;
1143   if (Recv_data[i] != TAG_LSRE_ID) {
1144     ALOGE("%s: Invalid Root entity for TAG 42 = 0x%x", fn, Recv_data[i]);
1145     return LSCSTATUS_FAILED;
1146   }
1147   i++;
1148   uint8_t tag42Len = Recv_data[i];
1149   // copy the data including length
1150   memcpy(gsTag42Arr, &Recv_data[i], tag42Len + 1);
1151   i = i + tag42Len + 1;
1152   ALOGD_IF(ese_debug_enabled, "%s: gsTag42Arr %s", fn, gsTag42Arr);
1153   if (Recv_data[i] != TAG_LSRE_SIGNID) {
1154     ALOGE("%s: Invalid Root entity for TAG 45 = 0x%x", fn, Recv_data[i]);
1155     return LSCSTATUS_FAILED;
1156   }
1157   uint8_t tag45Len = Recv_data[i + 1];
1158   memcpy(gsTag45Arr, &Recv_data[i + 1], tag45Len + 1);
1159   ALOGD_IF(ese_debug_enabled, "%s: Exiting", fn);
1160   return LSCSTATUS_SUCCESS;
1161 }
1162 
Bufferize_load_cmds(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)1163 LSCSTATUS Bufferize_load_cmds(__attribute__((unused)) Lsc_ImageInfo_t* Os_info,
1164                               __attribute__((unused)) LSCSTATUS status,
1165                               Lsc_TranscieveInfo_t* pTranscv_Info) {
1166   static const char fn[] = "Bufferize_load_cmds";
1167 
1168   if (gsCmd_count == 0x00) {
1169     if ((pTranscv_Info->sSendData[1] == INSTAL_LOAD_ID) &&
1170         (pTranscv_Info->sSendData[2] == PARAM_P1_OFFSET) &&
1171         (pTranscv_Info->sSendData[3] == 0x00)) {
1172       ALOGD_IF(ese_debug_enabled, "%s: BUffer: install for load", fn);
1173       gspBuffer[0] = pTranscv_Info->sSendlength;
1174       memcpy(&gspBuffer[1], &(pTranscv_Info->sSendData[0]),
1175              pTranscv_Info->sSendlength);
1176       gspBuffer = gspBuffer + pTranscv_Info->sSendlength + 1;
1177       gsCmd_count++;
1178       return LSCSTATUS_FAILED;
1179     }
1180     /* Do not buffer this cmd, Send to eSE */
1181     return LSCSTATUS_SUCCESS;
1182   } else {
1183     uint8_t Param_P2 = gsCmd_count - 1;
1184     if ((pTranscv_Info->sSendData[1] == LOAD_CMD_ID) &&
1185         (pTranscv_Info->sSendData[2] == LOAD_MORE_BLOCKS) &&
1186         (pTranscv_Info->sSendData[3] == Param_P2)) {
1187       ALOGD_IF(ese_debug_enabled, "%s: BUffer: load", fn);
1188       gspBuffer[0] = pTranscv_Info->sSendlength;
1189       memcpy(&gspBuffer[1], &(pTranscv_Info->sSendData[0]),
1190              pTranscv_Info->sSendlength);
1191       gspBuffer = gspBuffer + pTranscv_Info->sSendlength + 1;
1192       gsCmd_count++;
1193     } else if ((pTranscv_Info->sSendData[1] == LOAD_CMD_ID) &&
1194                (pTranscv_Info->sSendData[2] == LOAD_LAST_BLOCK) &&
1195                (pTranscv_Info->sSendData[3] == Param_P2)) {
1196       ALOGD_IF(ese_debug_enabled, "%s: BUffer: last load", fn);
1197       gsSendBack_cmds = true;
1198       gspBuffer[0] = pTranscv_Info->sSendlength;
1199       memcpy(&gspBuffer[1], &(pTranscv_Info->sSendData[0]),
1200              pTranscv_Info->sSendlength);
1201       gspBuffer = gspBuffer + pTranscv_Info->sSendlength + 1;
1202       gsCmd_count++;
1203       gsIslastcmdLoad = true;
1204     } else {
1205       ALOGD_IF(ese_debug_enabled, "%s: BUffer: Not a load cmd", fn);
1206       gsSendBack_cmds = true;
1207       gspBuffer[0] = pTranscv_Info->sSendlength;
1208       memcpy(&gspBuffer[1], &(pTranscv_Info->sSendData[0]),
1209              pTranscv_Info->sSendlength);
1210       gspBuffer = gspBuffer + pTranscv_Info->sSendlength + 1;
1211       gsIslastcmdLoad = false;
1212       gsCmd_count++;
1213     }
1214   }
1215   ALOGD_IF(ese_debug_enabled, "%s: exit", fn);
1216   return LSCSTATUS_FAILED;
1217 }
1218 
Send_Backall_Loadcmds(Lsc_ImageInfo_t * Os_info,LSCSTATUS status,Lsc_TranscieveInfo_t * pTranscv_Info)1219 LSCSTATUS Send_Backall_Loadcmds(Lsc_ImageInfo_t* Os_info, LSCSTATUS status,
1220                                 Lsc_TranscieveInfo_t* pTranscv_Info) {
1221   static const char fn[] = "Send_Backall_Loadcmds";
1222   status = LSCSTATUS_FAILED;
1223 
1224   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
1225   gspBuffer = gsCmd_Buffer;  // Points to start of first cmd to send
1226   if (gsCmd_count == 0x00) {
1227     ALOGD_IF(ese_debug_enabled, "%s: No cmds stored to send to eSE", fn);
1228   } else {
1229     while (gsCmd_count-- > 0) {
1230       phNxpEse_data cmdApdu;
1231       phNxpEse_data rspApdu;
1232       phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
1233       phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
1234 
1235       cmdApdu.len = (int32_t)(gspBuffer[0]);
1236       cmdApdu.p_data =
1237           (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
1238       gspBuffer = gspBuffer + 1 + cmdApdu.len;
1239 
1240       memcpy(cmdApdu.p_data, &gspBuffer[1], cmdApdu.len);
1241 
1242       ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
1243       memcpy(pTranscv_Info->sRecvData, rspApdu.p_data, rspApdu.len);
1244       int32_t recvBufferActualSize = rspApdu.len;
1245       phNxpEse_free(cmdApdu.p_data);
1246       phNxpEse_free(rspApdu.p_data);
1247 
1248       if (eseStat != ESESTATUS_SUCCESS || (recvBufferActualSize < 2)) {
1249         ALOGE("%s: Transceive failed; status=0x%X", fn, eseStat);
1250       } else if (gsCmd_count == 0x00) {
1251         // Last command in the buffer
1252         if (gsIslastcmdLoad == false) {
1253           status =
1254               Process_EseResponse(pTranscv_Info, recvBufferActualSize, Os_info);
1255         } else if ((recvBufferActualSize == 0x02) &&
1256                    (pTranscv_Info->sRecvData[recvBufferActualSize - 2] ==
1257                     0x90) &&
1258                    (pTranscv_Info->sRecvData[recvBufferActualSize - 1] ==
1259                     0x00)) {
1260           recvBufferActualSize = 0x03;
1261           pTranscv_Info->sRecvData[0] = 0x00;
1262           pTranscv_Info->sRecvData[1] = 0x90;
1263           pTranscv_Info->sRecvData[2] = 0x00;
1264           status =
1265               Process_EseResponse(pTranscv_Info, recvBufferActualSize, Os_info);
1266         } else {
1267           status =
1268               Process_EseResponse(pTranscv_Info, recvBufferActualSize, Os_info);
1269         }
1270       } else if ((recvBufferActualSize == 0x02) &&
1271                  (pTranscv_Info->sRecvData[0] == 0x90) &&
1272                  (pTranscv_Info->sRecvData[1] == 0x00)) {
1273         /*response ok without data, send next command in the buffer*/
1274       } else if ((recvBufferActualSize == 0x03) &&
1275                  (pTranscv_Info->sRecvData[0] == 0x00) &&
1276                  (pTranscv_Info->sRecvData[1] == 0x90) &&
1277                  (pTranscv_Info->sRecvData[2] == 0x00)) {
1278         /*response ok without data, send next command in the buffer*/
1279       } else if ((pTranscv_Info->sRecvData[recvBufferActualSize - 2] != 0x90) &&
1280                  (pTranscv_Info->sRecvData[recvBufferActualSize - 1] != 0x00)) {
1281         /*Error condition hence exiting the loop*/
1282         status =
1283             Process_EseResponse(pTranscv_Info, recvBufferActualSize, Os_info);
1284         /*If the sending of Load fails reset the count*/
1285         gsCmd_count = 0;
1286         break;
1287       }
1288     }
1289   }
1290   memset(gsCmd_Buffer, 0, sizeof(gsCmd_Buffer));
1291   gspBuffer = gsCmd_Buffer;  // point back to start of line
1292   gsCmd_count = 0x00;
1293   ALOGD_IF(ese_debug_enabled, "%s: exit: status=0x%x", fn, status);
1294   return status;
1295 }
1296 /*******************************************************************************
1297 **
1298 ** Function:        Numof_lengthbytes
1299 **
1300 ** Description:     Checks the number of length bytes and assigns
1301 **                  length value to wLen.
1302 **
1303 ** Returns:         Number of Length bytes
1304 **
1305 *******************************************************************************/
Numof_lengthbytes(uint8_t * read_buf,int32_t * pLen)1306 uint8_t Numof_lengthbytes(uint8_t* read_buf, int32_t* pLen) {
1307   static const char fn[] = "Numof_lengthbytes";
1308   uint8_t len_byte = 0;
1309   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
1310 
1311   if (read_buf[0] == 0x00) {
1312     ALOGE("%s: Invalid length zero", fn);
1313     len_byte = 0x00;
1314   } else if ((read_buf[0] & 0x80) == 0x80) {
1315     len_byte = read_buf[0] & 0x0F;
1316     len_byte = len_byte + 1;  // 1 byte added for byte 0x81
1317   } else {
1318     len_byte = 0x01;
1319   }
1320 
1321   /* To get the length of the value field */
1322   int32_t wLen = 0;
1323   switch (len_byte) {
1324     case 0:
1325       wLen = read_buf[0];
1326       break;
1327     case 1:
1328       /*1st byte is the length*/
1329       wLen = read_buf[0];
1330       break;
1331     case 2:
1332       /*2nd byte is the length*/
1333       wLen = read_buf[1];
1334       break;
1335     case 3:
1336       /*1st and 2nd bytes are length*/
1337       wLen = read_buf[1];
1338       wLen = ((wLen << 8) | (read_buf[2]));
1339       break;
1340     case 4:
1341       /*3bytes are the length*/
1342       wLen = read_buf[1];
1343       wLen = ((wLen << 16) | (read_buf[2] << 8));
1344       wLen = (wLen | (read_buf[3]));
1345       break;
1346     default:
1347       ALOGE("%s: Invalid length %d.", fn, len_byte);
1348       break;
1349   }
1350 
1351   *pLen = wLen;
1352   ALOGD_IF(ese_debug_enabled, "%s: exit; len_bytes=0x0%x, Length=%d", fn,
1353            len_byte, *pLen);
1354   return len_byte;
1355 }
1356 
1357 /*******************************************************************************
1358 **
1359 ** Function:        Write_Response_To_OutFile
1360 **
1361 ** Description:     Write the response to Out file
1362 **                  with length recvlen from buffer RecvData.
1363 **
1364 ** Returns:         Success if OK
1365 **
1366 *******************************************************************************/
Write_Response_To_OutFile(Lsc_ImageInfo_t * image_info,uint8_t * RecvData,int32_t recvlen,Ls_TagType tType)1367 LSCSTATUS Write_Response_To_OutFile(Lsc_ImageInfo_t* image_info,
1368                                     uint8_t* RecvData, int32_t recvlen,
1369                                     Ls_TagType tType) {
1370   static const char fn[] = "Write_Response_to_OutFile";
1371 
1372   ALOGD_IF(ese_debug_enabled, "%s: Enter", fn);
1373   /*If the Response out file is NULL or Other than LS commands*/
1374   if ((image_info->bytes_wrote == 0x55) || (tType == LS_Default)) {
1375     return LSCSTATUS_SUCCESS;
1376   }
1377 
1378   uint8_t tag43Len = 1;
1379   /*Certificate TAG occupies 2 bytes*/
1380   if (tType == LS_Cert) {
1381     tag43Len = 2;
1382   }
1383 
1384   /* |TAG|LEN|                      VAL                      |
1385    * |61 |XX |TAG|LEN|    VAL   |TAG|    LEN    |     VAL    |
1386    *         |43 |1/2|7F21/60/40|44 |apduRespLen|apduResponse|
1387    */
1388   int32_t tag44Len = 0;
1389   uint8_t ucTag44[3] = {0x00, 0x00, 0x00};
1390   int32_t tag61Len = 0;
1391   uint8_t tag43off = 0;
1392   uint8_t tag44off = 0;
1393   uint8_t tagLen = 0;
1394   uint8_t tagBuffer[12] = {0x61, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1395   if (recvlen < 0x80) {
1396     tag44Len = 1;
1397     ucTag44[0] = recvlen;
1398     tag61Len = recvlen + 4 + tag43Len;
1399 
1400     if (tag61Len & 0x80) {
1401       tagBuffer[1] = 0x81;
1402       tagBuffer[2] = tag61Len;
1403       tag43off = 3;
1404       tag44off = 5 + tag43Len;
1405       tagLen = tag44off + 2;
1406     } else {
1407       tagBuffer[1] = tag61Len;
1408       tag43off = 2;
1409       tag44off = 4 + tag43Len;
1410       tagLen = tag44off + 2;
1411     }
1412   } else if ((recvlen >= 0x80) && (recvlen <= 0xFF)) {
1413     ucTag44[0] = 0x81;
1414     ucTag44[1] = recvlen;
1415     tag61Len = recvlen + 5 + tag43Len;
1416     tag44Len = 2;
1417 
1418     if ((tag61Len & 0xFF00) != 0) {
1419       tagBuffer[1] = 0x82;
1420       tagBuffer[2] = (tag61Len & 0xFF00) >> 8;
1421       tagBuffer[3] = (tag61Len & 0xFF);
1422       tag43off = 4;
1423       tag44off = 6 + tag43Len;
1424       tagLen = tag44off + 3;
1425     } else {
1426       tagBuffer[1] = 0x81;
1427       tagBuffer[2] = (tag61Len & 0xFF);
1428       tag43off = 3;
1429       tag44off = 5 + tag43Len;
1430       tagLen = tag44off + 3;
1431     }
1432   } else if ((recvlen > 0xFF) && (recvlen <= 0xFFFF)) {
1433     ucTag44[0] = 0x82;
1434     ucTag44[1] = (recvlen & 0xFF00) >> 8;
1435     ucTag44[2] = (recvlen & 0xFF);
1436     tag44Len = 3;
1437 
1438     tag61Len = recvlen + 6 + tag43Len;
1439 
1440     if ((tag61Len & 0xFF00) != 0) {
1441       tagBuffer[1] = 0x82;
1442       tagBuffer[2] = (tag61Len & 0xFF00) >> 8;
1443       tagBuffer[3] = (tag61Len & 0xFF);
1444       tag43off = 4;
1445       tag44off = 6 + tag43Len;
1446       tagLen = tag44off + 4;
1447     }
1448   }
1449   tagBuffer[tag43off] = 0x43;
1450   tagBuffer[tag43off + 1] = tag43Len;
1451   tagBuffer[tag44off] = 0x44;
1452   memcpy(&tagBuffer[tag44off + 1], &ucTag44[0], tag44Len);
1453 
1454   if (tType == LS_Cert) {
1455     tagBuffer[tag43off + 2] = 0x7F;
1456     tagBuffer[tag43off + 3] = 0x21;
1457   } else if (tType == LS_Sign) {
1458     tagBuffer[tag43off + 2] = 0x60;
1459   } else if (tType == LS_Comm) {
1460     tagBuffer[tag43off + 2] = 0x40;
1461   } else {
1462     /*Do nothing*/
1463   }
1464 
1465   uint8_t tempLen = 0;
1466   LSCSTATUS wStatus = LSCSTATUS_FAILED;
1467   int32_t status = 0;
1468   while (tempLen < tagLen) {
1469     status = fprintf(image_info->fResp, "%02X", tagBuffer[tempLen++]);
1470     if (status != 2) {
1471       ALOGE("%s: Invalid Response during fprintf; status=0x%x", fn, (status));
1472       wStatus = LSCSTATUS_FAILED;
1473       break;
1474     }
1475   }
1476   /*Updating the response data into out script*/
1477   int32_t respLen = 0;
1478   while (respLen < recvlen) {
1479     status = fprintf(image_info->fResp, "%02X", RecvData[respLen++]);
1480     if (status != 2) {
1481       ALOGE("%s: Invalid Response during fprintf; status=0x%x", fn, (status));
1482       wStatus = LSCSTATUS_FAILED;
1483       break;
1484     }
1485   }
1486   if (status == 2) {
1487     fprintf(image_info->fResp, "%s\n", "");
1488     ALOGD_IF(ese_debug_enabled,
1489              "%s: SUCCESS Response written to script out file", fn);
1490     wStatus = LSCSTATUS_SUCCESS;
1491   }
1492   fflush(image_info->fResp);
1493   return wStatus;
1494 }
1495 
1496 /*******************************************************************************
1497 **
1498 ** Function:        Check_Certificate_Tag
1499 **
1500 ** Description:     Check certificate Tag presence in script
1501 **                  by 7F21 .
1502 **
1503 ** Returns:         Success if Tag found
1504 **
1505 *******************************************************************************/
Check_Certificate_Tag(uint8_t * read_buf,uint16_t * offset1)1506 LSCSTATUS Check_Certificate_Tag(uint8_t* read_buf, uint16_t* offset1) {
1507   static const char fn[] = "Check_Certificate_Tag";
1508   uint16_t offset = *offset1;
1509 
1510   if (((read_buf[offset] << 8 | read_buf[offset + 1]) == TAG_CERTIFICATE)) {
1511     ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_CERTIFICATE", fn);
1512     int32_t wLen;
1513     offset = offset + 2;
1514     uint16_t len_byte = Numof_lengthbytes(&read_buf[offset], &wLen);
1515     offset = offset + len_byte;
1516     *offset1 = offset;
1517     if (wLen <= MAX_CERT_LEN) return LSCSTATUS_SUCCESS;
1518   }
1519   return LSCSTATUS_FAILED;
1520 }
1521 
1522 /*******************************************************************************
1523 **
1524 ** Function:        Check_SerialNo_Tag
1525 **
1526 ** Description:     Check Serial number Tag presence in script
1527 **                  by 0x93 .
1528 **
1529 ** Returns:         Success if Tag found
1530 **
1531 *******************************************************************************/
Check_SerialNo_Tag(uint8_t * read_buf,uint16_t * offset1)1532 LSCSTATUS Check_SerialNo_Tag(uint8_t* read_buf, uint16_t* offset1) {
1533   static const char fn[] = "Check_SerialNo_Tag";
1534   uint16_t offset = *offset1;
1535 
1536   if (read_buf[offset] == TAG_SERIAL_NO) {
1537     ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_SERIAL_NO", fn);
1538     uint8_t serNoLen = read_buf[offset + 1];
1539     offset = offset + serNoLen + 2;
1540     *offset1 = offset;
1541     ALOGD_IF(ese_debug_enabled, "%s: TAG_LSROOT_ENTITY is %x", fn,
1542              read_buf[offset]);
1543     return LSCSTATUS_SUCCESS;
1544   }
1545   return LSCSTATUS_FAILED;
1546 }
1547 
1548 /*******************************************************************************
1549 **
1550 ** Function:        Check_LSRootID_Tag
1551 **
1552 ** Description:     Check LS root ID tag presence in script and compare with
1553 **                  select response root ID value.
1554 **
1555 ** Returns:         Success if Tag found
1556 **
1557 *******************************************************************************/
Check_LSRootID_Tag(uint8_t * read_buf,uint16_t * offset1)1558 LSCSTATUS Check_LSRootID_Tag(uint8_t* read_buf, uint16_t* offset1) {
1559   static const char fn[] = "Check_LSRootID_Tag";
1560   uint16_t offset = *offset1;
1561 
1562   if (read_buf[offset] == TAG_LSRE_ID) {
1563     ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_LSROOT_ENTITY", fn);
1564     if (gsTag42Arr[0] == read_buf[offset + 1]) {
1565       uint8_t tag42Len = read_buf[offset + 1];
1566       offset = offset + 2;
1567       if (!memcmp(&read_buf[offset], &gsTag42Arr[1], gsTag42Arr[0])) {
1568         ALOGD_IF(ese_debug_enabled, "%s : TAG 42 verified", fn);
1569         offset = offset + tag42Len;
1570         *offset1 = offset;
1571         return LSCSTATUS_SUCCESS;
1572       }
1573     }
1574   }
1575   return LSCSTATUS_FAILED;
1576 }
1577 
1578 /*******************************************************************************
1579 **
1580 ** Function:        Check_CertHoldID_Tag
1581 **
1582 ** Description:     Check certificate holder ID tag presence in script.
1583 **
1584 ** Returns:         Success if Tag found
1585 **
1586 *******************************************************************************/
Check_CertHoldID_Tag(uint8_t * read_buf,uint16_t * offset1)1587 LSCSTATUS Check_CertHoldID_Tag(uint8_t* read_buf, uint16_t* offset1) {
1588   static const char fn[] = "Check_CertHoldID_Tag";
1589   uint16_t offset = *offset1;
1590 
1591   if ((read_buf[offset] << 8 | read_buf[offset + 1]) == TAG_CERTFHOLD_ID) {
1592     uint8_t certfHoldIDLen = 0;
1593     ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_CERTFHOLD_ID", fn);
1594     certfHoldIDLen = read_buf[offset + 2];
1595     offset = offset + certfHoldIDLen + 3;
1596     if (read_buf[offset] == TAG_KEY_USAGE) {
1597       ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_KEY_USAGE", fn);
1598       uint8_t keyusgLen = read_buf[offset + 1];
1599       offset = offset + keyusgLen + 2;
1600       *offset1 = offset;
1601       return LSCSTATUS_SUCCESS;
1602     }
1603   }
1604   return LSCSTATUS_FAILED;
1605 }
1606 
1607 /*******************************************************************************
1608 **
1609 ** Function:        Check_Date_Tag
1610 **
1611 ** Description:     Check date tags presence in script.
1612 **
1613 ** Returns:         Success if Tag found
1614 **
1615 *******************************************************************************/
Check_Date_Tag(uint8_t * read_buf,uint16_t * offset1)1616 LSCSTATUS Check_Date_Tag(uint8_t* read_buf, uint16_t* offset1) {
1617   static const char fn[] = "Check_Date_Tag";
1618   LSCSTATUS status = LSCSTATUS_FAILED;
1619   uint16_t offset = *offset1;
1620 
1621   if ((read_buf[offset] << 8 | read_buf[offset + 1]) == TAG_EFF_DATE) {
1622     uint8_t effDateLen = read_buf[offset + 2];
1623     offset = offset + 3 + effDateLen;
1624     ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_EFF_DATE", fn);
1625     if ((read_buf[offset] << 8 | read_buf[offset + 1]) == TAG_EXP_DATE) {
1626       uint8_t effExpLen = read_buf[offset + 2];
1627       offset = offset + 3 + effExpLen;
1628       ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_EXP_DATE", fn);
1629       status = LSCSTATUS_SUCCESS;
1630     } else if (read_buf[offset] == TAG_LSRE_SIGNID) {
1631       status = LSCSTATUS_SUCCESS;
1632     }
1633   } else if ((read_buf[offset] << 8 | read_buf[offset + 1]) == TAG_EXP_DATE) {
1634     uint8_t effExpLen = read_buf[offset + 2];
1635     offset = offset + 3 + effExpLen;
1636     ALOGD_IF(ese_debug_enabled, "%s: TAGID: TAG_EXP_DATE", fn);
1637     status = LSCSTATUS_SUCCESS;
1638   } else if (read_buf[offset] == TAG_LSRE_SIGNID) {
1639     status = LSCSTATUS_SUCCESS;
1640   } else {
1641     /*LSCSTATUS_FAILED*/
1642   }
1643   *offset1 = offset;
1644   return status;
1645 }
1646 
1647 /*******************************************************************************
1648 **
1649 ** Function:        Check_45_Tag
1650 **
1651 ** Description:     Check 45 tags presence in script and compare the value
1652 **                  with select response tag 45 value
1653 **
1654 ** Returns:         Success if Tag found
1655 **
1656 *******************************************************************************/
Check_45_Tag(uint8_t * read_buf,uint16_t * offset1,uint8_t * tag45Len)1657 LSCSTATUS Check_45_Tag(uint8_t* read_buf, uint16_t* offset1,
1658                        uint8_t* tag45Len) {
1659   static const char fn[] = "Check_45_Tag";
1660   uint16_t offset = *offset1;
1661   if (read_buf[offset] == TAG_LSRE_SIGNID) {
1662     *tag45Len = read_buf[offset + 1];
1663     offset = offset + 2;
1664     if (gsTag45Arr[0] == *tag45Len) {
1665       if (!memcmp(&read_buf[offset], &gsTag45Arr[1], gsTag45Arr[0])) {
1666         *offset1 = offset;
1667         ALOGD_IF(ese_debug_enabled,
1668                  "%s: LSC_Check_KeyIdentifier : TAG 45 verified", fn);
1669         return LSCSTATUS_SUCCESS;
1670       }
1671     }
1672   }
1673   return LSCSTATUS_FAILED;
1674 }
1675 
1676 /*******************************************************************************
1677 **
1678 ** Function:        Certificate_Verification
1679 **
1680 ** Description:     Perform the certificate verification by forwarding it to
1681 **                  LS applet.
1682 **
1683 ** Returns:         Success if certificate is verified
1684 **
1685 *******************************************************************************/
Certificate_Verification(Lsc_ImageInfo_t * Os_info,Lsc_TranscieveInfo_t * pTranscv_Info,uint8_t * read_buf,uint16_t * offset1,uint8_t * tag45Len)1686 LSCSTATUS Certificate_Verification(Lsc_ImageInfo_t* Os_info,
1687                                    Lsc_TranscieveInfo_t* pTranscv_Info,
1688                                    uint8_t* read_buf, uint16_t* offset1,
1689                                    uint8_t* tag45Len) {
1690   static const char fn[] = "Certificate_Verification";
1691 
1692   pTranscv_Info->sSendData[0] = 0x80;
1693   pTranscv_Info->sSendData[1] = 0xA0;
1694   pTranscv_Info->sSendData[2] = 0x01;
1695   pTranscv_Info->sSendData[3] = 0x00;
1696 
1697   int32_t wCertfLen = (read_buf[2] << 8 | read_buf[3]);
1698   uint16_t offset = *offset1;
1699   /*If the certificate is less than 255 bytes*/
1700   if (wCertfLen <= 251) {
1701     uint8_t tag7f49Off = 0;
1702     uint8_t u7f49Len = 0;
1703     uint8_t tag5f37Len = 0;
1704     ALOGD_IF(ese_debug_enabled, "%s: Certificate is less than 255", fn);
1705     offset = offset + *tag45Len;
1706     ALOGD_IF(ese_debug_enabled, "%s: Before TAG_CCM_PERMISSION = %x", fn,
1707              read_buf[offset]);
1708     if (read_buf[offset] != TAG_CCM_PERMISSION) {
1709       return LSCSTATUS_FAILED;
1710     }
1711     int32_t tag53Len = 0;
1712     uint8_t len_byte = 0;
1713     offset = offset + 1;
1714     len_byte = Numof_lengthbytes(&read_buf[offset], &tag53Len);
1715     offset = offset + tag53Len + len_byte;
1716     ALOGD_IF(ese_debug_enabled, "%s: Verified TAG TAG_CCM_PERMISSION = 0x53",
1717              fn);
1718     if ((uint16_t)(read_buf[offset] << 8 | read_buf[offset + 1]) !=
1719         TAG_SIG_RNS_COMP) {
1720       return LSCSTATUS_FAILED;
1721     }
1722     tag7f49Off = offset;
1723     u7f49Len = read_buf[offset + 2];
1724     offset = offset + 3 + u7f49Len;
1725     if (u7f49Len != 64) {
1726       return LSCSTATUS_FAILED;
1727     }
1728     if ((uint16_t)(read_buf[offset] << 8 | read_buf[offset + 1]) != 0x7f49) {
1729       return LSCSTATUS_FAILED;
1730     }
1731     tag5f37Len = read_buf[offset + 2];
1732     if (read_buf[offset + 3] != 0x86 || (read_buf[offset + 4] != 65)) {
1733       return LSCSTATUS_FAILED;
1734     }
1735     uint8_t tag_len_byte = Numof_lengthbytes(&read_buf[2], &wCertfLen);
1736     pTranscv_Info->sSendData[4] = wCertfLen + 2 + tag_len_byte;
1737     pTranscv_Info->sSendlength = wCertfLen + 7 + tag_len_byte;
1738     memcpy(&(pTranscv_Info->sSendData[5]), &read_buf[0],
1739            wCertfLen + 2 + tag_len_byte);
1740 
1741     ALOGD_IF(ese_debug_enabled, "%s: start transceive for length %d", fn,
1742              pTranscv_Info->sSendlength);
1743     LSCSTATUS status = LSCSTATUS_FAILED;
1744     status = LSC_SendtoLsc(Os_info, status, pTranscv_Info, LS_Cert);
1745     if (status == LSCSTATUS_SUCCESS) {
1746       ALOGD_IF(ese_debug_enabled, "%s: Certificate is verified", fn);
1747     }
1748     return status;
1749   } else {
1750     /*If the certificate is more than 255 bytes*/
1751     uint8_t tag7f49Off = 0;
1752     uint8_t u7f49Len = 0;
1753     uint8_t tag5f37Len = 0;
1754     ALOGD_IF(ese_debug_enabled, "%s: Certificate is greater than 255", fn);
1755     offset = offset + *tag45Len;
1756     ALOGD_IF(ese_debug_enabled, "%s: Before TAG_CCM_PERMISSION = %x", fn,
1757              read_buf[offset]);
1758     if (read_buf[offset] != TAG_CCM_PERMISSION) {
1759       return LSCSTATUS_FAILED;
1760     }
1761     int32_t tag53Len = 0;
1762     uint8_t len_byte = 0;
1763     offset = offset + 1;
1764     len_byte = Numof_lengthbytes(&read_buf[offset], &tag53Len);
1765     offset = offset + tag53Len + len_byte;
1766     ALOGD_IF(ese_debug_enabled, "%s: Verified TAG TAG_CCM_PERMISSION = 0x53",
1767              fn);
1768     if ((uint16_t)(read_buf[offset] << 8 | read_buf[offset + 1]) !=
1769         TAG_SIG_RNS_COMP) {
1770       return LSCSTATUS_FAILED;
1771     }
1772     tag7f49Off = offset;
1773     u7f49Len = read_buf[offset + 2];
1774     offset = offset + 3 + u7f49Len;
1775     if (u7f49Len != 64) {
1776       return LSCSTATUS_FAILED;
1777     }
1778     if ((uint16_t)(read_buf[offset] << 8 | read_buf[offset + 1]) != 0x7f49) {
1779       return LSCSTATUS_FAILED;
1780     }
1781     tag5f37Len = read_buf[offset + 2];
1782     if (read_buf[offset + 3] != 0x86 || (read_buf[offset + 4] != 65)) {
1783       return LSCSTATUS_FAILED;
1784     }
1785     pTranscv_Info->sSendData[4] = tag7f49Off;
1786     memcpy(&(pTranscv_Info->sSendData[5]), &read_buf[0], tag7f49Off);
1787     pTranscv_Info->sSendlength = tag7f49Off + 5;
1788     ALOGD_IF(ese_debug_enabled, "%s: start transceive for length %d", fn,
1789              pTranscv_Info->sSendlength);
1790 
1791     LSCSTATUS status = LSCSTATUS_FAILED;
1792     status = LSC_SendtoLsc(Os_info, status, pTranscv_Info, LS_Default);
1793     if (status != LSCSTATUS_SUCCESS) {
1794       uint8_t* RecvData = pTranscv_Info->sRecvData;
1795       Write_Response_To_OutFile(Os_info, RecvData, gsResp_len, LS_Cert);
1796       return status;
1797     }
1798 
1799     pTranscv_Info->sSendData[2] = 0x00;
1800     pTranscv_Info->sSendData[4] = u7f49Len + tag5f37Len + 6;
1801     memcpy(&(pTranscv_Info->sSendData[5]), &read_buf[tag7f49Off],
1802            u7f49Len + tag5f37Len + 6);
1803     pTranscv_Info->sSendlength = u7f49Len + tag5f37Len + 11;
1804     ALOGD_IF(ese_debug_enabled, "%s: start transceive for length %d", fn,
1805              pTranscv_Info->sSendlength);
1806 
1807     status = LSC_SendtoLsc(Os_info, status, pTranscv_Info, LS_Cert);
1808     if (status == LSCSTATUS_SUCCESS) {
1809       ALOGD_IF(ese_debug_enabled, "Certificate is verified");
1810     }
1811     return status;
1812   }
1813   return LSCSTATUS_FAILED;
1814 }
1815 
1816 /*******************************************************************************
1817 **
1818 ** Function:        Check_Complete_7F21_Tag
1819 **
1820 ** Description:     Traverses the 7F21 tag for verification of each sub tag with
1821 **                  in the 7F21 tag.
1822 **
1823 ** Returns:         Success if all tags are verified
1824 **
1825 *******************************************************************************/
Check_Complete_7F21_Tag(Lsc_ImageInfo_t * Os_info,Lsc_TranscieveInfo_t * pTranscv_Info,uint8_t * read_buf,uint16_t * offset)1826 LSCSTATUS Check_Complete_7F21_Tag(Lsc_ImageInfo_t* Os_info,
1827                                   Lsc_TranscieveInfo_t* pTranscv_Info,
1828                                   uint8_t* read_buf, uint16_t* offset) {
1829   static const char fn[] = "Check_Complete_7F21_Tag";
1830 
1831   if (LSCSTATUS_SUCCESS != Check_Certificate_Tag(read_buf, offset)) {
1832     ALOGE("%s: FAILED in Check_Certificate_Tag", fn);
1833     return LSCSTATUS_FAILED;
1834   }
1835   if (LSCSTATUS_SUCCESS != Check_SerialNo_Tag(read_buf, offset)) {
1836     ALOGE("%s: FAILED in Check_SerialNo_Tag", fn);
1837     return LSCSTATUS_FAILED;
1838   }
1839   if (LSCSTATUS_SUCCESS != Check_LSRootID_Tag(read_buf, offset)) {
1840     ALOGE("%s: FAILED in Check_LSRootID_Tag", fn);
1841     return LSCSTATUS_FAILED;
1842   }
1843   if (LSCSTATUS_SUCCESS != Check_CertHoldID_Tag(read_buf, offset)) {
1844     ALOGE("%s: FAILED in Check_CertHoldID_Tag", fn);
1845     return LSCSTATUS_FAILED;
1846   }
1847   if (LSCSTATUS_SUCCESS != Check_Date_Tag(read_buf, offset)) {
1848     ALOGE("%s: FAILED in Check_CertHoldID_Tag", fn);
1849     return LSCSTATUS_FAILED;
1850   }
1851   uint8_t tag45Len = 0;
1852   if (LSCSTATUS_SUCCESS != Check_45_Tag(read_buf, offset, &tag45Len)) {
1853     ALOGE("%s: FAILED in Check_CertHoldID_Tag", fn);
1854     return LSCSTATUS_FAILED;
1855   }
1856   if (LSCSTATUS_SUCCESS != Certificate_Verification(Os_info, pTranscv_Info,
1857                                                     read_buf, offset,
1858                                                     &tag45Len)) {
1859     ALOGE("%s: FAILED in Certificate_Verification", fn);
1860     return LSCSTATUS_FAILED;
1861   }
1862   return LSCSTATUS_SUCCESS;
1863 }
1864 
1865 /*******************************************************************************
1866 **
1867 ** Function:        LSC_UpdateExeStatus
1868 **
1869 ** Description:     Updates LSC status to a file
1870 **
1871 ** Returns:         true if success else false
1872 **
1873 *******************************************************************************/
LSC_UpdateExeStatus(uint16_t status)1874 bool LSC_UpdateExeStatus(uint16_t status) {
1875   static const char fn[] = "LSC_UpdateExeStatus";
1876 
1877   ALOGD_IF(ese_debug_enabled, "%s: enter", fn);
1878 
1879   FILE* fLsStatus = fopen(LS_STATUS_PATH, "w+");
1880   if (fLsStatus == NULL) {
1881     ALOGE("%s: Error opening LS Status file for backup: %s", fn,
1882           strerror(errno));
1883     return false;
1884   }
1885   if ((fprintf(fLsStatus, "%04x", status)) != 4) {
1886     ALOGE("%s: Error updating LS Status backup: %s", fn, strerror(errno));
1887     fclose(fLsStatus);
1888     return false;
1889   }
1890   fclose(fLsStatus);
1891   ALOGD_IF(ese_debug_enabled, "%s: exit", fn);
1892   return true;
1893 }
1894 
1895 /*******************************************************************************
1896 **
1897 ** Function:        Get_LsStatus
1898 **
1899 ** Description:     Interface to fetch Loader service client status to JNI,
1900 **                  Services
1901 **
1902 ** Returns:         SUCCESS/FAILURE
1903 **
1904 *******************************************************************************/
Get_LsStatus(uint8_t * pStatus)1905 LSCSTATUS Get_LsStatus(uint8_t* pStatus) {
1906   static const char fn[] = "Get_LsStatus";
1907 
1908   FILE* fLsStatus = fopen(LS_STATUS_PATH, "r");
1909   if (fLsStatus == NULL) {
1910     ALOGE("%s: Error opening LS Status file for backup: %s", fn,
1911           strerror(errno));
1912     return LSCSTATUS_FAILED;
1913   }
1914 
1915   uint8_t lsStatus[2] = {0x63, 0x40};
1916   for (uint8_t loopcnt = 0; loopcnt < 2; loopcnt++) {
1917     if ((FSCANF_BYTE(fLsStatus, "%2x", &lsStatus[loopcnt])) == 0) {
1918       ALOGE("%s: Error updating LS Status backup: %s", fn, strerror(errno));
1919       fclose(fLsStatus);
1920       return LSCSTATUS_FAILED;
1921     }
1922   }
1923   ALOGD_IF(ese_debug_enabled, "%s: LS Status 0x%X 0x%X", fn, lsStatus[0],
1924            lsStatus[1]);
1925   memcpy(pStatus, lsStatus, 2);
1926   fclose(fLsStatus);
1927   return LSCSTATUS_SUCCESS;
1928 }
1929 
1930 /*******************************************************************************
1931 **
1932 ** Function:        LSC_CloseAllLogicalChannels
1933 **
1934 ** Description:     Close all opened logical channels
1935 **
1936 ** Returns:         SUCCESS/FAILURE
1937 **
1938 *******************************************************************************/
LSC_CloseAllLogicalChannels(Lsc_ImageInfo_t * Os_info)1939 LSCSTATUS LSC_CloseAllLogicalChannels(Lsc_ImageInfo_t* Os_info) {
1940   ESESTATUS status = ESESTATUS_FAILED;
1941   LSCSTATUS lsStatus = LSCSTATUS_FAILED;
1942   phNxpEse_data cmdApdu;
1943   phNxpEse_data rspApdu;
1944 
1945   ALOGD_IF(ese_debug_enabled, "%s: Enter", __func__);
1946   for (uint8_t channelNumber = 0x01; channelNumber < 0x04; channelNumber++) {
1947     if (channelNumber == Os_info->initChannelNum) continue;
1948     phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
1949     phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
1950     cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(5 * sizeof(uint8_t));
1951     if (cmdApdu.p_data != NULL) {
1952       uint8_t xx = 0;
1953 
1954       cmdApdu.p_data[xx++] = channelNumber;
1955       cmdApdu.p_data[xx++] = 0x70;           // INS
1956       cmdApdu.p_data[xx++] = 0x80;           // P1
1957       cmdApdu.p_data[xx++] = channelNumber;  // P2
1958       cmdApdu.p_data[xx++] = 0x00;           // Lc
1959       cmdApdu.len = xx;
1960 
1961       status = phNxpEse_Transceive(&cmdApdu, &rspApdu);
1962     }
1963     if (status != ESESTATUS_SUCCESS) {
1964       lsStatus = LSCSTATUS_FAILED;
1965     } else if ((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
1966                (rspApdu.p_data[rspApdu.len - 1] == 0x00)) {
1967       lsStatus = LSCSTATUS_SUCCESS;
1968     } else {
1969       lsStatus = LSCSTATUS_FAILED;
1970     }
1971 
1972     phNxpEse_free(cmdApdu.p_data);
1973     phNxpEse_free(rspApdu.p_data);
1974   }
1975   return lsStatus;
1976 }
1977 
1978 /*******************************************************************************
1979 **
1980 ** Function:        LSC_SelectLsHash
1981 **
1982 ** Description:     Selects LS Hash applet
1983 **
1984 ** Returns:         SUCCESS/FAILURE
1985 **
1986 *******************************************************************************/
LSC_SelectLsHash()1987 LSCSTATUS LSC_SelectLsHash() {
1988   phNxpEse_data cmdApdu;
1989   phNxpEse_data rspApdu;
1990   LSCSTATUS lsStatus = LSCSTATUS_FAILED;
1991   ALOGD_IF(ese_debug_enabled, "%s: Enter ", __func__);
1992   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
1993   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
1994 
1995   cmdApdu.len = (int32_t)(sizeof(SelectLscSlotHash));
1996   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
1997   memcpy(cmdApdu.p_data, SelectLscSlotHash, sizeof(SelectLscSlotHash));
1998 
1999   ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
2000 
2001   if ((eseStat != ESESTATUS_SUCCESS) ||
2002       ((rspApdu.p_data[rspApdu.len - 2] != 0x90) &&
2003        (rspApdu.p_data[rspApdu.len - 1] != 0x00))) {
2004     lsStatus = LSCSTATUS_FAILED;
2005   } else {
2006     lsStatus = LSCSTATUS_SUCCESS;
2007   }
2008 
2009   phNxpEse_free(cmdApdu.p_data);
2010   phNxpEse_free(rspApdu.p_data);
2011   return lsStatus;
2012 }
2013 /*******************************************************************************
2014 **
2015 ** Function:        LSC_ReadLsHash
2016 **
2017 ** Description:     Read the LS SHA1 for the intended slot
2018 **
2019 ** Returns:         SUCCESS/FAILURE
2020 **
2021 *******************************************************************************/
LSC_ReadLsHash(uint8_t * hash,uint16_t * readHashLen,uint8_t slotId)2022 LSCSTATUS LSC_ReadLsHash(uint8_t* hash, uint16_t* readHashLen, uint8_t slotId) {
2023   phNxpEse_data cmdApdu;
2024   phNxpEse_data rspApdu;
2025   LSCSTATUS lsStatus = LSCSTATUS_FAILED;
2026 
2027   lsStatus = LSC_SelectLsHash();
2028   if (lsStatus != LSCSTATUS_SUCCESS) {
2029     return lsStatus;
2030   }
2031 
2032   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
2033   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
2034   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(5 * sizeof(uint8_t));
2035 
2036   if (cmdApdu.p_data != NULL) {
2037     uint8_t xx = 0;
2038     cmdApdu.p_data[xx++] = 0x80;    // CLA
2039     cmdApdu.p_data[xx++] = 0x02;    // INS
2040     cmdApdu.p_data[xx++] = slotId;  // P1
2041     cmdApdu.p_data[xx++] = 0x00;    // P2
2042     cmdApdu.len = xx;
2043 
2044     ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
2045 
2046     if ((eseStat == ESESTATUS_SUCCESS) &&
2047         ((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
2048          (rspApdu.p_data[rspApdu.len - 1] == 0x00))) {
2049       ALOGD_IF(ese_debug_enabled, "%s: rspApdu.len : %u", __func__,
2050                rspApdu.len);
2051       *readHashLen = rspApdu.len - 2;
2052       if (*readHashLen <= HASH_DATA_LENGTH) {
2053         memcpy(hash, rspApdu.p_data, *readHashLen);
2054         lsStatus = LSCSTATUS_SUCCESS;
2055       } else {
2056         ALOGE("%s:Invalid LS HASH data received", __func__);
2057         lsStatus = LSCSTATUS_FAILED;
2058       }
2059     } else {
2060       if ((rspApdu.p_data[rspApdu.len - 2] == 0x6A) &&
2061           (rspApdu.p_data[rspApdu.len - 1] == 0x86)) {
2062         ALOGD_IF(ese_debug_enabled, "%s: slot id is invalid", __func__);
2063         lsStatus = LSCSTATUS_HASH_SLOT_INVALID;
2064       } else if ((rspApdu.p_data[rspApdu.len - 2] == 0x6A) &&
2065                  (rspApdu.p_data[rspApdu.len - 1] == 0x83)) {
2066         ALOGD_IF(ese_debug_enabled, "%s: slot is empty", __func__);
2067         lsStatus = LSCSTATUS_HASH_SLOT_EMPTY;
2068       } else {
2069         lsStatus = LSCSTATUS_FAILED;
2070       }
2071     }
2072     phNxpEse_free(cmdApdu.p_data);
2073     phNxpEse_free(rspApdu.p_data);
2074   }
2075   return lsStatus;
2076 }
2077 
2078 /*******************************************************************************
2079 **
2080 ** Function:        LSC_UpdateLsHash
2081 **
2082 ** Description:     Updates the SHA1 for the intended slot
2083 **
2084 ** Returns:         SUCCESS/FAILURE
2085 **
2086 *******************************************************************************/
LSC_UpdateLsHash(uint8_t * hash,long hashLen,uint8_t slotId)2087 LSCSTATUS LSC_UpdateLsHash(uint8_t* hash, long hashLen, uint8_t slotId) {
2088   phNxpEse_data cmdApdu;
2089   phNxpEse_data rspApdu;
2090   LSCSTATUS lsStatus = LSCSTATUS_FAILED;
2091   ALOGD_IF(ese_debug_enabled, "%s: Enter ", __func__);
2092 
2093   lsStatus = LSC_SelectLsHash();
2094   if (lsStatus != LSCSTATUS_SUCCESS) {
2095     return lsStatus;
2096   }
2097 
2098   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
2099   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
2100 
2101   cmdApdu.len = (int32_t)(5 + hashLen);
2102   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
2103 
2104   if (cmdApdu.p_data != NULL) {
2105     uint8_t xx = 0;
2106     cmdApdu.p_data[xx++] = 0x80;
2107     cmdApdu.p_data[xx++] = 0x01;     // INS
2108     cmdApdu.p_data[xx++] = slotId;   // P1
2109     cmdApdu.p_data[xx++] = 0x00;     // P2
2110     cmdApdu.p_data[xx++] = hashLen;  // Lc
2111     memcpy(&cmdApdu.p_data[xx], hash, hashLen);
2112 
2113     ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
2114 
2115     if ((eseStat == ESESTATUS_SUCCESS) &&
2116         ((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
2117          (rspApdu.p_data[rspApdu.len - 1] == 0x00))) {
2118       lsStatus = LSCSTATUS_SUCCESS;
2119     } else {
2120       if ((rspApdu.p_data[rspApdu.len - 2] == 0x6A) &&
2121           (rspApdu.p_data[rspApdu.len - 1] == 0x86)) {
2122         ALOGD_IF(ese_debug_enabled, "%s: if slot id is invalid", __func__);
2123       }
2124       lsStatus = LSCSTATUS_FAILED;
2125     }
2126   }
2127 
2128   ALOGD_IF(ese_debug_enabled, "%s: Exit ", __func__);
2129   phNxpEse_free(cmdApdu.p_data);
2130   phNxpEse_free(rspApdu.p_data);
2131   return lsStatus;
2132 }
2133 
2134 /*******************************************************************************
2135 **
2136 ** Function:        LSC_ReadLscInfo
2137 **
2138 ** Description:     Read the state of LS applet
2139 **
2140 ** Returns:         SUCCESS/FAILURE
2141 **
2142 *******************************************************************************/
LSC_ReadLscInfo(uint8_t * state,uint16_t * version)2143 LSCSTATUS LSC_ReadLscInfo(uint8_t* state, uint16_t* version) {
2144   static const char fn[] = "LSC_ReadLscInfo";
2145   phNxpEse_data cmdApdu;
2146   phNxpEse_data rspApdu;
2147   LSCSTATUS status = LSCSTATUS_FAILED;
2148   ALOGD_IF(ese_debug_enabled, "%s: Enter ", __func__);
2149 
2150   phNxpEse_memset(&cmdApdu, 0x00, sizeof(phNxpEse_data));
2151   phNxpEse_memset(&rspApdu, 0x00, sizeof(phNxpEse_data));
2152 
2153   /*p_data will have channel_id (1 byte) + SelectLsc APDU*/
2154   cmdApdu.len = (int32_t)(sizeof(SelectLsc) + 1);
2155   cmdApdu.p_data = (uint8_t*)phNxpEse_memalloc(cmdApdu.len * sizeof(uint8_t));
2156   cmdApdu.p_data[0] = 0x00;  // fchannel 0
2157 
2158   memcpy(&(cmdApdu.p_data[1]), SelectLsc, sizeof(SelectLsc));
2159 
2160   ALOGD_IF(ese_debug_enabled, "%s: Selecting Loader service applet", fn);
2161 
2162   ESESTATUS eseStat = phNxpEse_Transceive(&cmdApdu, &rspApdu);
2163 
2164   if (eseStat != ESESTATUS_SUCCESS && (rspApdu.len == 0x00)) {
2165     status = LSCSTATUS_FAILED;
2166     ALOGE("%s: SE transceive failed status = 0x%X", fn, status);
2167   } else if (((rspApdu.p_data[rspApdu.len - 2] == 0x90) &&
2168               (rspApdu.p_data[rspApdu.len - 1] == 0x00))) {
2169     status = Process_SelectRsp(rspApdu.p_data, (rspApdu.len - 2));
2170     if (status != LSCSTATUS_SUCCESS) {
2171       ALOGE("%s: Select Lsc Rsp doesnt have a valid key; status = 0x%X", fn,
2172             status);
2173     } else {
2174       *state = rspApdu.p_data[18];
2175       *version = (rspApdu.p_data[22] << 8) | rspApdu.p_data[23];
2176     }
2177   } else if (rspApdu.p_data[rspApdu.len - 2] != 0x90) {
2178     ALOGE("%s: Selecting Loader service applet failed", fn);
2179     status = LSCSTATUS_FAILED;
2180   }
2181 
2182   ALOGD_IF(ese_debug_enabled, "%s: Exit ", __func__);
2183   phNxpEse_free(cmdApdu.p_data);
2184   phNxpEse_free(rspApdu.p_data);
2185   return status;
2186 }
2187