Prevent Out of bounds read in ce_t4t.cc

Test: Nfc Enable/Disable; Send wrong length AID to HCE
Bug: 115635871
Merged-In: Ie522424d5d9e611fac5875a0cf1f8cbd640528ff
Change-Id: Ie522424d5d9e611fac5875a0cf1f8cbd640528ff
(cherry picked from commit f910f969c52a846110331a44b15e789b7001d770)
diff --git a/src/nfc/tags/ce_t4t.c b/src/nfc/tags/ce_t4t.c
index f641c77..f204c8a 100644
--- a/src/nfc/tags/ce_t4t.c
+++ b/src/nfc/tags/ce_t4t.c
@@ -22,6 +22,7 @@
  *  mode.
  *
  ******************************************************************************/
+#include <log/log.h>
 #include <string.h>
 #include "bt_types.h"
 #include "nfc_target.h"
@@ -389,6 +390,14 @@
   /* Lc Byte */
   BE_STREAM_TO_UINT8(data_len, p_cmd);
 
+  /*CLS+INS+P1+P2+Lc+Data*/
+  if (data_len > (p_c_apdu->len - T4T_CMD_MAX_HDR_SIZE)) {
+    CE_TRACE_ERROR0("Wrong length in ce_t4t_process_select_app_cmd");
+    android_errorWriteLog(0x534e4554, "115635871");
+    ce_t4t_send_status(T4T_RSP_WRONG_LENGTH);
+    GKI_freebuf(p_c_apdu);
+    return;
+  }
 #if (CE_TEST_INCLUDED == TRUE)
   if (mapping_aid_test_enabled) {
     if ((data_len == T4T_V20_NDEF_TAG_AID_LEN) &&
@@ -541,7 +550,7 @@
                               tNFC_CONN* p_data) {
   NFC_HDR* p_c_apdu;
   uint8_t* p_cmd;
-  uint8_t cla, instruct, select_type = 0, length;
+  uint8_t cla = 0, instruct = 0, select_type = 0, length = 0;
   uint16_t offset, max_file_size;
   tCE_DATA ce_data;
 
@@ -563,6 +572,14 @@
 
   p_cmd = (uint8_t*)(p_c_apdu + 1) + p_c_apdu->offset;
 
+  if (p_c_apdu->len == 0) {
+    CE_TRACE_ERROR0("Wrong length in ce_t4t_data_cback");
+    android_errorWriteLog(0x534e4554, "115635871");
+    ce_t4t_send_status(T4T_RSP_WRONG_LENGTH);
+    if (p_c_apdu) GKI_freebuf(p_c_apdu);
+    return;
+  }
+
   /* Class Byte */
   BE_STREAM_TO_UINT8(cla, p_cmd);
 
@@ -575,16 +592,28 @@
     return;
   }
 
-  /* Instruction Byte */
-  BE_STREAM_TO_UINT8(instruct, p_cmd);
+  /*CLA+INS+P1+P2 = 4 bytes*/
+  if (p_c_apdu->len >= T4T_CMD_MIN_HDR_SIZE) {
+    /* Instruction Byte */
+    BE_STREAM_TO_UINT8(instruct, p_cmd);
 
-  if ((cla == T4T_CMD_CLASS) && (instruct == T4T_CMD_INS_SELECT)) {
-    /* P1 Byte */
-    BE_STREAM_TO_UINT8(select_type, p_cmd);
+    if ((cla == T4T_CMD_CLASS) && (instruct == T4T_CMD_INS_SELECT)) {
+      /* P1 Byte */
+      BE_STREAM_TO_UINT8(select_type, p_cmd);
 
-    if (select_type == T4T_CMD_P1_SELECT_BY_NAME) {
-      ce_t4t_process_select_app_cmd(p_cmd, p_c_apdu);
-      return;
+      if (select_type == T4T_CMD_P1_SELECT_BY_NAME) {
+        /*CLA+INS+P1+P2+Lc = 5 bytes*/
+        if (p_c_apdu->len >= T4T_CMD_MAX_HDR_SIZE) {
+          ce_t4t_process_select_app_cmd(p_cmd, p_c_apdu);
+          return;
+        } else {
+          CE_TRACE_ERROR0("Wrong length in select app cmd");
+          android_errorWriteLog(0x534e4554, "115635871");
+          ce_t4t_send_status(T4T_RSP_NOT_FOUND);
+          if (p_c_apdu) GKI_freebuf(p_c_apdu);
+          return;
+        }
+      }
     }
   }