Improve AGF PDU integrity check to prevent OOB error

Test: Nfc Enable/Disable; Android Beam; Tag reading
Bug: 116791157
(cherry picked from commit 1e1bf327eac157409279ede5ec874c5112be9d9b)

Change-Id: I75b89e3dd542e40197263593aa2608e1187afae5
diff --git a/src/nfc/llcp/llcp_link.c b/src/nfc/llcp/llcp_link.c
index d70349c..ff81f6b 100644
--- a/src/nfc/llcp/llcp_link.c
+++ b/src/nfc/llcp/llcp_link.c
@@ -23,6 +23,7 @@
  *
  ******************************************************************************/
 
+#include <log/log.h>
 #include <string.h>
 #include "gki.h"
 #include "nfc_target.h"
@@ -1132,7 +1133,7 @@
 {
     UINT16 agf_length;
     UINT8 *p, *p_info, *p_pdu_length;
-    UINT16 pdu_hdr, pdu_length;
+    UINT16 pdu_hdr, pdu_length, pdu_num;
     UINT8  dsap, ptype, ssap;
 
     p_agf->len    -= LLCP_PDU_HEADER_SIZE;
@@ -1143,12 +1144,18 @@
     */
     agf_length = p_agf->len;
     p = (UINT8 *) (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) {
+              LLCP_TRACE_ERROR0(
+                  "llcp_link_proc_agf_pdu (): Received invalid encapsulated PDU");
+              break;
+            }
             agf_length -= LLCP_PDU_AGF_LEN_SIZE;
         }
         else
@@ -1160,6 +1167,7 @@
         {
             p += pdu_length;
             agf_length -= pdu_length;
+            pdu_num++;
         }
         else
         {
@@ -1167,8 +1175,9 @@
         }
     }
 
-    if (agf_length != 0)
+    if (agf_length != 0 || pdu_num < 2)
     {
+        android_errorWriteLog(0x534e4554, "116791157");
         LLCP_TRACE_ERROR0 ("llcp_link_proc_agf_pdu (): Received invalid AGF PDU");
         GKI_freebuf (p_agf);
         return;
@@ -1207,6 +1216,9 @@
             GKI_freebuf (p_agf);
             llcp_link_deactivate (LLCP_LINK_REMOTE_INITIATED);
             return;
+        } else if (ptype == LLCP_PDU_AGF_TYPE)
+        {
+            LLCP_TRACE_ERROR0 ("llcp_link_proc_agf_pdu (): AGF PDU shall not be in AGF");
         }
         else if (ptype == LLCP_PDU_SYMM_TYPE)
         {