Prevent OOB read in rw_t4t.cc

Bug: 120865977
Bug: 120274615
Bug: 124462242
Test: Read T4T Tag
Merged-In: Id1b07fa79edabaf27e18a7147d1e7ae66cf3c4b3
Change-Id: Id1b07fa79edabaf27e18a7147d1e7ae66cf3c4b3
(cherry picked from commit a8d5d162ed306e7291e7dd216a27607fe5af3241)
diff --git a/src/nfc/include/tags_defs.h b/src/nfc/include/tags_defs.h
index 6ac16ed..a5a9547 100644
--- a/src/nfc/include/tags_defs.h
+++ b/src/nfc/include/tags_defs.h
@@ -532,6 +532,7 @@
 
 #define T4T_FILE_LENGTH_SIZE 0x02
 #define T4T_ADDI_FRAME_RESP 0xAFU
+#define T4T_DES_GET_VERSION_LEN 0x09
 #define T4T_SIZE_IDENTIFIER_2K 0x16U
 #define T4T_SIZE_IDENTIFIER_4K 0x18U
 #define T4T_SIZE_IDENTIFIER_8K 0x1AU
diff --git a/src/nfc/tags/rw_t4t.c b/src/nfc/tags/rw_t4t.c
index e7b3c96..60fed64 100644
--- a/src/nfc/tags/rw_t4t.c
+++ b/src/nfc/tags/rw_t4t.c
@@ -22,6 +22,7 @@
  *  mode.
  *
  ******************************************************************************/
+#include <log/log.h>
 #include <string.h>
 #include "bt_types.h"
 #include "nfc_target.h"
@@ -227,6 +228,12 @@
   uint8_t* p;
   uint16_t major_version, minor_version;
 
+  if (p_r_apdu->len < T4T_DES_GET_VERSION_LEN) {
+    RW_TRACE_ERROR1("%s incorrect p_r_apdu length", __func__);
+    android_errorWriteLog(0x534e4554, "120865977");
+    return false;
+  }
+
   p = (uint8_t*)(p_r_apdu + 1) + p_r_apdu->offset;
   major_version = *(p + 3);
   minor_version = *(p + 4);
@@ -1012,6 +1019,8 @@
 
     rw_data.t4t_sw.sw1 = sw1;
     rw_data.t4t_sw.sw2 = sw2;
+    rw_data.ndef.cur_size = 0;
+    rw_data.ndef.max_size = 0;
 
     switch (p_t4t->state) {
       case RW_T4T_STATE_DETECT_NDEF:
@@ -1821,6 +1830,16 @@
   RW_TRACE_DEBUG1("RW T4T state: %d", p_t4t->state);
 #endif
 
+  if (p_t4t->state != RW_T4T_STATE_IDLE &&
+      p_t4t->state != RW_T4T_STATE_PRESENCE_CHECK &&
+      p_r_apdu->len < T4T_RSP_STATUS_WORDS_SIZE) {
+    RW_TRACE_ERROR1("%s incorrect p_r_apdu length", __func__);
+    android_errorWriteLog(0x534e4554, "120865977");
+    rw_t4t_handle_error(NFC_STATUS_FAILED, 0, 0);
+    GKI_freebuf(p_r_apdu);
+    return;
+  }
+
   switch (p_t4t->state) {
     case RW_T4T_STATE_IDLE:
 /* Unexpected R-APDU, it should be raw frame response */