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