From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Brian Delwiche <delwiche@google.com>
Date: Thu, 5 Oct 2023 00:01:03 +0000
Subject: [PATCH] Fix UAF in ~CallbackEnv

com_android_bluetooth_btservice_AdapterService does not null its local
JNI environment variable after detaching the thread (which frees the
environment context), allowing UAF under certain conditions.

Null the variable in this case.

Testing here was done through a custom unit test; see patchsets 4-6 for
contents.  However, unit testing of the JNI layer is problematic in
production, so that part of the patch is omitted for final merge.

Bug: 291500341
Test: atest bluetooth_test_gd_unit, atest net_test_stack_btm
Tag: #security
Ignore-AOSP-First: Security
(cherry picked from https://googleplex-android-review.googlesource.com/q/commit:5f543d919c4067f2f4925580fd8a690ba3440e80)
Merged-In: I3e5e3c51412640aa19f0981caaa809313d6ad030
Change-Id: I3e5e3c51412640aa19f0981caaa809313d6ad030
---
 jni/com_android_bluetooth_btservice_AdapterService.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/jni/com_android_bluetooth_btservice_AdapterService.cpp b/jni/com_android_bluetooth_btservice_AdapterService.cpp
index 1768ef51b..4a579e0ca 100644
--- a/jni/com_android_bluetooth_btservice_AdapterService.cpp
+++ b/jni/com_android_bluetooth_btservice_AdapterService.cpp
@@ -465,6 +465,7 @@ static void callback_thread_event(bt_cb_thread_evt event) {
             return;
         }
         vm->DetachCurrentThread();
+        callbackEnv = NULL;
     }
 }
 
