Improve AGF PDU integrity check to prevent OOB error

Test: Nfc Enable/Disable; Android Beam; Tag reading
Bug: 116791157
Change-Id: I981e867301007b7398d59727f60892824b722735
(cherry picked from commit eae50694637df88e9d834e9a9c5539c1dd367f63)
(cherry picked from commit 064f65733004170f13f400d1283e49ed70253f49)
diff --git a/src/nfc/llcp/llcp_link.cc b/src/nfc/llcp/llcp_link.cc
index 8a5ddf2..f144d45 100644
--- a/src/nfc/llcp/llcp_link.cc
+++ b/src/nfc/llcp/llcp_link.cc
@@ -26,7 +26,7 @@
 
 #include <android-base/stringprintf.h>
 #include <base/logging.h>
-
+#include <log/log.h>
 #include "bt_types.h"
 #include "gki.h"
 #include "llcp_defs.h"
@@ -1091,7 +1091,7 @@
 static void llcp_link_proc_agf_pdu(NFC_HDR* p_agf) {
   uint16_t agf_length;
   uint8_t *p, *p_info, *p_pdu_length;
-  uint16_t pdu_hdr, pdu_length;
+  uint16_t pdu_hdr, pdu_length, pdu_num;
   uint8_t dsap, ptype, ssap;
 
   p_agf->len -= LLCP_PDU_HEADER_SIZE;
@@ -1102,10 +1102,15 @@
   */
   agf_length = p_agf->len;
   p = (uint8_t*)(p_agf + 1) + p_agf->offset;
+  pdu_num = 0;
 
   while (agf_length > 0) {
     if (agf_length > LLCP_PDU_AGF_LEN_SIZE) {
       BE_STREAM_TO_UINT16(pdu_length, p);
+      if (pdu_length < LLCP_PDU_HEADER_SIZE) {
+        LOG(ERROR) << StringPrintf("Received invalid encapsulated PDU");
+        break;
+      }
       agf_length -= LLCP_PDU_AGF_LEN_SIZE;
     } else {
       break;
@@ -1114,12 +1119,14 @@
     if (pdu_length <= agf_length) {
       p += pdu_length;
       agf_length -= pdu_length;
+      pdu_num++;
     } else {
       break;
     }
   }
 
-  if (agf_length != 0) {
+  if (agf_length != 0 || pdu_num < 2) {
+    android_errorWriteLog(0x534e4554, "116791157");
     LOG(ERROR) << StringPrintf("Received invalid AGF PDU");
     GKI_freebuf(p_agf);
     return;
@@ -1155,6 +1162,8 @@
       GKI_freebuf(p_agf);
       llcp_link_deactivate(LLCP_LINK_REMOTE_INITIATED);
       return;
+    } else if (ptype == LLCP_PDU_AGF_TYPE) {
+      LOG(ERROR) << StringPrintf("AGF PDU shall not be in AGF");
     } else if (ptype == LLCP_PDU_SYMM_TYPE) {
       LOG(ERROR) << StringPrintf("SYMM PDU exchange shall not be in AGF");
     } else if (ptype == LLCP_PDU_PAX_TYPE) {