From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Chris Manton <cmanton@google.com>
Date: Mon, 8 Nov 2021 16:45:42 -0800
Subject: [PATCH] security: Use-After-Free in btm_sec_[dis]connected

Bug: 201083442
Tag: #security
Test: gd/cert/run
Ignore-AOSP-First: Security

Change-Id: I69c362d1eb644a3b7fd967cd526a8a58c3b4d975
(cherry picked from commit 4f3fdf141b248cacd7c7dd09c06d058931726c98)
Merged-In:I69c362d1eb644a3b7fd967cd526a8a58c3b4d975
---
 stack/btm/btm_sec.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/stack/btm/btm_sec.c b/stack/btm/btm_sec.c
index b27b7e071..175fefeae 100644
--- a/stack/btm/btm_sec.c
+++ b/stack/btm/btm_sec.c
@@ -4472,7 +4472,6 @@ static void btm_sec_connect_after_cc_page_tout (UNUSED_ATTR void *data)
 *******************************************************************************/
 void btm_sec_connected (UINT8 *bda, UINT16 handle, UINT8 status, UINT8 enc_mode)
 {
-    tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bda);
     UINT8            res;
     BOOLEAN          is_pairing_device = FALSE;
     tACL_CONN        *p_acl_cb;
@@ -4480,6 +4479,7 @@ void btm_sec_connected (UINT8 *bda, UINT16 handle, UINT8 status, UINT8 enc_mode)
 
     btm_acl_resubmit_page();
 
+    tBTM_SEC_DEV_REC *p_dev_rec = btm_find_dev (bda);
     /* Commenting out trace due to obf/compilation problems.
     */
 #if (BT_USE_TRACES == TRUE)
@@ -4836,7 +4836,6 @@ tBTM_STATUS btm_sec_disconnect (UINT16 handle, UINT8 reason)
 *******************************************************************************/
 void btm_sec_disconnected (UINT16 handle, UINT8 reason)
 {
-    tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev_by_handle (handle);
     UINT8             old_pairing_flags = btm_cb.pairing_flags;
     int               result = HCI_ERR_AUTH_FAILURE;
     tBTM_SEC_CALLBACK   *p_callback = NULL;
@@ -4847,6 +4846,7 @@ void btm_sec_disconnected (UINT16 handle, UINT8 reason)
 
     btm_acl_resubmit_page();
 
+    tBTM_SEC_DEV_REC  *p_dev_rec = btm_find_dev_by_handle (handle);
     if (!p_dev_rec)
         return;
 
