From 024980bad7055b9acf07ec6d0fa955cdcd704b13 Mon Sep 17 00:00:00 2001
From: Brian Delwiche <delwiche@google.com>
Date: Mon, 22 Apr 2024 21:56:48 +0000
Subject: [PATCH] Disallow connect with key length downgrade

As a guard against the BLUFFS attack, check security parameters of
incoming connections against cached values and disallow connection if
these parameters are downgraded or changed from their cached values.

This CL adds the connection-time check for session key length.

To test, please validate that bonding can be established and
reestablished against devices with session key lengths of 7 and 16 bits,
that session key lengths of less than 7 bits are refused, and that basic
LE bonding functionality still works.  If it is possible to configure a
remote device to establish a bond with a session key length of 16 bits
and then reduce that key length to <16 bits before reconnection, this
should fail.

Bug: 314331379
Test: m libbluetooth
Test: manual

Tag: #security
Ignore-AOSP-First: Security
(cherry picked from https://googleplex-android-review.googlesource.com/q/commit:d6e9fdf182afb57cecac6c56603aa20d758090a4)
Merged-In: I27be1f93598820a0f2a7154ba83f5b041878c21f
Change-Id: I27be1f93598820a0f2a7154ba83f5b041878c21f
---
 system/stack/btu/btu_hcif.cc | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/system/stack/btu/btu_hcif.cc b/system/stack/btu/btu_hcif.cc
index 605e95e15d3..c71534499dc 100644
--- a/system/stack/btu/btu_hcif.cc
+++ b/system/stack/btu/btu_hcif.cc
@@ -918,6 +918,20 @@ static void read_encryption_key_size_complete_after_encryption_change(uint8_t st
     return;
   }
 
+  if (btm_sec_is_session_key_size_downgrade(handle, key_size)) {
+    LOG_ERROR(
+        "encryption key size lower than cached value, disconnecting. "
+        "handle: 0x%x attempted key size: %d",
+        handle, key_size);
+    acl_disconnect_from_handle(
+        handle, HCI_ERR_HOST_REJECT_SECURITY,
+        "stack::btu::btu_hcif::read_encryption_key_size_complete_after_"
+        "encryption_change Key Size Downgrade");
+    return;
+  }
+
+  btm_sec_update_session_key_size(handle, key_size);
+
   // good key size - succeed
   btm_acl_encrypt_change(handle, static_cast<tHCI_STATUS>(status),
                          1 /* enable */);
-- 
GitLab