| Age | Commit message (Collapse) | Author |
|
rfcomm_kill_listener() walks session_list and deletes every session
without holding rfcomm_mutex, unlike the normal session processing and
connect error paths.
Under normal operation, an open RFCOMM socket pins rfcomm.ko, so
rfcomm_kill_listener() does not run concurrently with rfcomm_dlc_open().
However, forced module unload via delete_module(O_TRUNC) can stop
krfcommd while a failed connect is still unwinding.
connect task forced unload / krfcommd
------------ ------------------------
rfcomm_lock()
rfcomm_session_add()
delete_module("rfcomm", O_TRUNC)
rfcomm_kill_listener()
fetch session from session_list
kernel_connect() fails
rfcomm_session_del()
remove and free session
rfcomm_session_del(session)
The final call then reads the freed session and may corrupt the list.
KASAN reported with mdelay() to enlarge critical window:
BUG: KASAN: slab-use-after-free in rfcomm_run+0x3802/0x3f00 [rfcomm]
Read of size 8 at addr ffff888111058d40 by task krfcommd/79
Tainted: [R]=FORCED_RMMOD
Allocated by task 86:
rfcomm_session_add+0xa1/0x300 [rfcomm]
rfcomm_dlc_open+0x8b2/0xf30 [rfcomm]
rfcomm_sock_connect+0x34c/0x530 [rfcomm]
Freed by task 86:
kfree+0x121/0x3c0
rfcomm_dlc_open+0xab7/0xf30 [rfcomm]
rfcomm_sock_connect+0x34c/0x530 [rfcomm]
Hold rfcomm_mutex across the teardown traversal so every reachable
session_list walk uses the same serialization.
Reviewed-by: Ali Ahmet Memis <ali@iusegentoo.com>
Tested-by: Ali Ahmet Memis <ali@iusegentoo.com>
Reviewed-by: Pauli Virtanen <pav@iki.fi>
Signed-off-by: Chengfeng Ye <nicoyip.dev@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
create_le_conn_complete() decides whether the failed connection is
still pending by comparing it against hci_lookup_le_connect(), which
returns the first LE connection in BT_CONNECT. That is the same
connection only while at most one is pending.
Two can be pending. Connections created on the passive scan path sit
in BT_CONNECT with HCI_CONN_SCANNING set and are invisible to
hci_lookup_le_connect() until hci_le_create_conn_sync() clears the
flag when their command is issued, so the -EBUSY guard in
hci_connect_le() does not prevent a second connection from being
queued while the first is still on the scan path. Whenever two
connections are in BT_CONNECT at once, the lookup may return one
connection while create_le_conn_complete() is reporting the failure
of the other; the early exit then drops the error and hci_conn_failed()
never runs on the connection that failed.
The controller also rejects a second HCI_OP_LE_CREATE_CONN issued
while another connection creation is still outstanding, per Core Spec
Vol 4, Part E. The spec calls for Command Disallowed there; the
bcm43438 observed here answers with an LMP/LL error code instead,
which bt_to_errno() maps to the -EPROTO (-71) in the log below.
The leaked connection stays in BT_CONNECT forever, and because
hci_connect_le() refuses to dial while hci_lookup_le_connect() finds
anything, every subsequent attempt to reach any peer fails with
-EBUSY and no command reaches the controller at all.
Seen on a bcm43438 with two BLE peers polled on the same interval
(state 5 is BT_CONNECT; both handles are UNSET ones, allocated from
the ida above HCI_CONN_HANDLE_MAX):
Bluetooth: hci1: Opcode 0x2013 failed: -71
# hcitool con
< LE 14:9C:EF:03:68:81 handle 3840 state 5 lm CENTRAL
< LE C4:D3:6A:8C:B5:38 handle 3841 state 5 lm CENTRAL
A btmon capture across the next ten minutes of connect attempts
contains no HCI_OP_LE_CREATE_CONN at all; outgoing LE connections
do not recover until the adapter is reset. With this change the same
scenario fails the rejected connection cleanly and further connects
to both peers go through.
Ask about the connection itself instead of about the device.
Fixes: c9f73a2178c1 ("Bluetooth: hci_conn: Fix hci_connect_le_sync")
Signed-off-by: Radek Podgorny <radek@podgorny.cz>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
rfcomm_security_cfm() looks up a session on session_list and then walks
its DLC list without holding rfcomm_mutex. Since RFCOMM session teardown
uses rfcomm_mutex, krfcommd can close and free the same session and DLCs
concurrently:
hci_rx_work krfcommd
----------- ---------
rfcomm_session_get()
rfcomm_lock()
rfcomm_session_close()
rfcomm_dlc_unlink()
rfcomm_session_del()
kfree(s)
rfcomm_unlock()
walk s->dlcs
The callback can then read a freed session list head and touch freed DLCs
while updating their flags or timers.
Serialize the session lookup and DLC traversal in rfcomm_security_cfm()
with rfcomm_mutex. This matches the existing RFCOMM session lifetime
rules and prevents concurrent rfcomm_session_del() / rfcomm_dlc_unlink()
from tearing the objects down while the callback is using them.
KASAN reported:
BUG: KASAN: slab-use-after-free in rfcomm_security_cfm+0x41c/0x440
Read of size 8 at addr ffff888111fb3960 by task kworker/u17:1/89
Workqueue: hci0 hci_rx_work
Call Trace:
rfcomm_security_cfm+0x41c/0x440
hci_encrypt_cfm+0x139/0x590
hci_encrypt_change_evt+0x37b/0xc40
hci_event_packet+0x71b/0xb20
hci_rx_work+0x293/0x730
Allocated by task 69:
rfcomm_session_add+0x9e/0x2f0
rfcomm_run+0x44b/0x41e0
Freed by task 69:
kfree+0x131/0x3c0
rfcomm_session_del+0x188/0x220
rfcomm_run+0x1985/0x41e0
Fixes: 08c30aca9e698faddebd34f81e1196295f9dc063 ("Bluetooth: Remove RFCOMM session refcnt")
Cc: stable@vger.kernel.org
Signed-off-by: Chengfeng Ye <nicoyip.dev@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
rfcomm_apply_pn() accepts the MTU value from a remote PN (Parameter
Negotiation) frame without checking for zero. When the remote peer
sends an MTU of zero, d->mtu is set to 0. This causes the sendmsg
path to enter an infinite loop when fragmenting data, as each fragment
has size == min_t(size_t, len, 0) == 0, so the remaining length never
decreases. The infinite allocation of zero-length skbs exhausts all
system memory.
Fix by clamping d->mtu to RFCOMM_DEFAULT_MTU when the negotiated
value is zero, consistent with the initial value assigned in
rfcomm_dlc_alloc().
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Hyunwoo Kim <imv4bel@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
iso_conn_ready() looks up the BIS listener socket with iso_get_sock(),
which takes a reference, and then, without re-checking its state,
creates a child socket from it:
parent = iso_get_sock(hdev, ...);
if (!parent)
return;
lock_sock(parent);
sk = iso_sock_alloc(sock_net(parent), NULL, BTPROTO_ISO, ...);
...
iso_chan_add(conn, sk, parent);
...
release_sock(parent);
sock_put(parent);
If the listener socket is closed concurrently, between iso_get_sock()
and lock_sock(), the reference taken by iso_get_sock() may be the last
one: the close path drops the link-list reference, and once
iso_conn_ready() drops its own reference at the end of the function the
socket is freed. The child socket, however, is already linked to the
freed parent, and a later disconnect of the child runs iso_chan_del()
-> bt_accept_unlink(), which dereferences the dangling parent pointer
into the freed accept queue (a use-after-free). The same dangling
pointer is also dereferenced through parent->***() in
iso_chan_del().
Fix it the same way the connected (non-BIS) path was fixed in commit
0d255e63fcf3 ("Bluetooth: ISO: hold sk properly in iso_conn_ready"):
after taking the socket lock, re-check that the parent is still a
listening, alive socket, and bail out otherwise.
Fixes: ccf74f2390d60 ("Bluetooth: Add BTPROTO_ISO socket type")
Cc: stable@vger.kernel.org
Signed-off-by: Hang Nan <2122295973@qq.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
BT enable fails intermittently with -ETIMEDOUT (-110). The kernel log
shows the HCI Read Local Version command was sent and the firmware
replied with status 0x00 (logged by hci_req_cmd_complete() BT_DBG),
but the waiter in __hci_cmd_sync_sk() never woke up and timed out
after 10 s:
bluetooth hci0: Opcode 0xfc00 // __hci_cmd_sync_sk
bluetooth hci0: opcode 0xfc00 plen 1 // hci_cmd_sync_add
bluetooth hci0: skb len 4 // hci_cmd_sync_alloc
bluetooth hci0: length 1 // hci_req_sync_run
Bluetooth: hci0 cmd_cnt 1 cmd queued 1 // hci_cmd_work
Bluetooth: hci0 type 1 len 4 // hci_send_frame
Bluetooth: opcode 0xfc00 status 0x00 // hci_req_cmd_complete
<-- req_skb NULL: req_complete_skb not set,
hci_cmd_sync_complete() never called,
req_status stays HCI_REQ_PEND -->
<-- 10 s later: wait_event_interruptible_timeout expires -->
bluetooth hci0: end: err -110 // __hci_cmd_sync_sk
The root cause is that hci_send_cmd_sync() clones the sent command
into hdev->req_skb so that hci_req_cmd_complete() can locate the
registered completion callback. Under memory pressure this
skb_clone() fails, leaving hdev->req_skb NULL. The firmware reply
is received and processed, but hci_req_cmd_complete() finds NULL
req_skb, so hci_cmd_sync_complete() is never called, req_status
stays HCI_REQ_PEND, and the waiter times out with -ETIMEDOUT.
req_skb is only used to read bt_cb(skb)->hci callbacks and opcode --
it is never modified. Replace skb_clone() with skb_get(), which
simply increments the reference count of hdev->sent_cmd without
allocating new memory and therefore cannot fail.
This issue was first observed as a use-after-free in ttyport_close()
when ttyport_open() failed, which was investigated in an earlier
patch series [1]. That investigation led to the discovery of the
true root cause described above.
[1] https://lore.kernel.org/all/20250430111617.1151390-1-quic_cxin@quicinc.com/
Fixes: 2615fd9a7c25 ("Bluetooth: hci_sync: Fix overwriting request callback")
Cc: stable@vger.kernel.org
Signed-off-by: Xin Chen <xin.chen2@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
le_conn_complete_evt() clears HCI_LE_ADV before looking at the event
status, on the premise stated in its comment that all controllers stop
advertising when a connection is created.
That premise only holds when a connection was actually created. On a
non-zero status none was, and the controller is still advertising: after
the host issues LE Create Connection Cancel the event arrives with
Unknown Connection Identifier (0x02), and a connection timeout behaves
the same way. Clearing the flag there leaves the host believing
advertising is off while the controller has it on.
It is also wrong for extended advertising, where several sets can be
advertising at once. hci_cc_le_set_ext_adv_enable() is careful about
this - on disabling one set it walks hdev->adv_instances and only clears
HCI_LE_ADV once no instance is still enabled. The unconditional clear
here discards that bookkeeping, so one set connecting drops the flag
while the others keep advertising.
The direction of the error matters. A flag left set is self-correcting:
hci_disable_advertising_sync() sends LE Set Advertising Enable(0) and
the command complete puts the state back. A flag left clear is not,
because that same function returns early without sending anything while
the flag is clear:
- LE Set Advertising Parameters is then sent to a controller that is
still advertising, and is correctly rejected with Command Disallowed
(0x0c);
- hci_enable_advertising_sync() returns at that point, before the
LE Set Advertising Enable that would set HCI_LE_ADV again.
On a controller without LE Extended Advertising that is reachable from
here: hci_schedule_adv_instance_sync() re-arms adv_instance_expire every
HCI_DEFAULT_ADV_DURATION (2 s) and its "already advertising" shortcut
tests HCI_LE_ADV, which can no longer become true, so the parameter
write is retried for as long as advertising is configured:
Bluetooth: hci0: Opcode 0x2006 failed: -16
Only clear the flag when a connection was established.
Note this is not on its own sufficient to stop that retry loop - the
redundant enable queued by hci_le_conn_failed() clears HCI_LE_ADV itself
and recreates the same mismatch, which patch 1 addresses. This patch
fixes the event handler reporting a state the controller is not in.
Verified on the affected device (BCM43455, legacy advertising only) with
this patch and patch 1 applied. A 221 s btmon capture with an out-of-range
peer at -90 dBm contains two outgoing connection attempts that the host
cancelled, each producing exactly the event this patch changes:
< LE Set Advertising Parameters 0x2006 Success
< LE Set Advertising Enable 0x200a Success
< LE Create Connection Cancel 0x200e Success
> LE Connection Complete Unknown Connection Identifier (0x02), central
Nothing follows either one; the next command is an unrelated scan restart
70 ms later. Over the whole capture: 7 LE Set Advertising Parameters sent,
all Success; 10 LE Set Advertising Enable, all Success; no Command
Disallowed of any opcode, and no 2 s cadence anywhere. Two central
connections to other peers completed normally afterwards, with feature
exchange and a connection parameter update, so advertising was still live
across the cancelled attempts.
The extended advertising case above is a code argument, not a measurement:
this controller has no LE Extended Advertising, so that path is not
exercised by the capture.
Fixes: fbd96c151cdc ("Bluetooth: Fix clearing HCI_LE_ADV for LE connections")
Cc: stable@vger.kernel.org
Assisted-by: Claude:claude-opus-5 btmon
Signed-off-by: Valentin Kindschi <valentin.kindschi@fiveco.ch>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_le_conn_failed() unconditionally calls hci_enable_advertising(),
although its own comment states advertising should be re-enabled only
when the failed attempt was made as a peripheral.
hci_le_conn_failed() is reached from hci_conn_failed() for every failed
LE connection, including outgoing central connections. For a central
attempt this enable is redundant: hci_le_create_conn_sync() already
restores advertising via hci_resume_advertising_sync() in its done:
block. Because hci_enable_advertising() only queues the work on
cmd_sync_work, it runs *after* that resume has already succeeded and
set HCI_LE_ADV.
The resulting HCI sequence, captured on a BCM43455 (no LE Extended
Advertising, so legacy advertising is used):
LE Create Connection Status Success
... 13.8 s, peer never answers ...
LE Set Advertising Parameters (0x2006) Success <- done: resume,
LE Set Advertising Enable (0x200a) Success HCI_LE_ADV set
LE Create Connection Cancel (0x200e) Success
LE Connection Complete Unknown Conn Id
LE Set Advertising Parameters (0x2006) Command Disallowed (0x0c)
The last command is the queued enable from hci_le_conn_failed() running
as a second hci_enable_advertising_sync() pass. It clears HCI_LE_ADV
(hci_sync.c, "Clear the HCI_LE_ADV bit temporarily"), then sends
LE Set Advertising Parameters while the controller is still advertising,
which the controller correctly rejects with Command Disallowed.
The disable-first call at the top of hci_enable_advertising_sync()
cannot prevent this: hci_disable_advertising_sync() returns early
without sending anything when HCI_LE_ADV is clear, so it is a no-op
exactly when the flag is wrong.
hci_enable_advertising_sync() then returns without sending LE Set
Advertising Enable, so HCI_LE_ADV is never set again. The legacy
software rotation loop re-arms hci_schedule_adv_instance_sync() every
HCI_DEFAULT_ADV_DURATION (2 s), and its "already advertising" shortcut
tests HCI_LE_ADV, which can no longer become true. The command is
therefore retried every 2 s indefinitely:
Bluetooth: hci0: Opcode 0x2006 failed: -16
Observed on a gateway as 5326 occurrences over 3 hours, ending only when
bluetoothd was restarted. Connection attempts that succeed do not call
hci_le_conn_failed() and never trigger this.
Add the role test the comment already describes. Both other
hci_enable_advertising() call sites reached from a failed/closed LE
connection (hci_cs_disconnect() and hci_disconn_complete_evt()) already
guard on conn->role == HCI_ROLE_SLAVE; this one was missed.
Reproducing needs legacy advertising (ext_adv_capable() false, so the
software rotation loop is used), simultaneous peripheral advertising and
outgoing central connects, and a central connect that times out rather
than failing fast.
The Fixes tag points at the commit that introduced the advertising
restart into this path for the directed-advertising (peripheral) case;
the role test that the later commit 0b1db38ca26b ("Bluetooth: Fix check
for direct advertising") added to the sibling paths was never applied
here.
Fixes: 3c857757ef6e ("Bluetooth: Add directed advertising support through connect()")
Cc: stable@vger.kernel.org
Assisted-by: Claude:claude-opus-5 btmon
Signed-off-by: Valentin Kindschi <valentin.kindschi@fiveco.ch>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
eir_get_service_data() walks the advertising data for a Service Data
field with a matching UUID. On a mismatch it advances:
eir += dlen;
eir_len -= dlen;
eir_get_data() reports dlen as the field's data length, but the field
spans dlen + 2 bytes once its length and type bytes count, and more
when non-Service-Data fields were skipped to reach it. The pointer
lands correctly on the next field. eir_len does not, and the shortfall
compounds across fields until eir_get_data() reads the length and type
bytes of a "field" past the end of the buffer.
For an ISO broadcast sink that buffer is hcon->le_per_adv_data[], filled
from the periodic advertising reports of a remote broadcaster. A PA
payload packed with mismatching Service Data fields walks off the array
into the rest of struct hci_conn. A drifted field that matches the BAA
UUID puts those bytes in iso_pi(sk)->base, where user space reads them
back with getsockopt(BT_ISO_BASE).
Recompute eir_len from the end of the buffer each iteration.
Fixes: 8f9ae5b3ae80 ("Bluetooth: eir: Add helpers for managing service data")
Cc: stable@vger.kernel.org
Assisted-by: Claude:claude-opus-5
Signed-off-by: HyeongJun An <sammiee5311@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Add context analysis annotations to functions doing conditional locking,
to suppress analysis warnings.
Fixes: cdc36db204ff ("Bluetooth: hci_sync: Fix advertising data UAFs")
Tested-by: Nathan Chancellor <nathan@kernel.org> # build
Signed-off-by: Pauli Virtanen <pav@iki.fi>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
For L2CAP sockets without owning sk->sk_socket, reading
l2cap_pi(sk)->chan may race against concurrent l2cap_sock_kill() ->
l2cap_sock_put_chan(). This excludes simultaneous proto_ops callbacks,
but access in l2cap_sock_cleanup_listen() has unsafe lockless read.
[Task 1] [Task 2 (hdev->workqueue)]
l2cap_sock_release(parent) l2cap_disconn_cfm
l2cap_sock_cleanup_listen l2cap_conn_del
bt_accept_dequeue l2cap_chan_del
lock_sock(sk) l2cap_sock_teardown_cb
bt_accept_unlink
bt_sk(sk)->parent = NULL
release_sock(sk) ----------------> lock_sock(sk)
parent = /* NULL */
lock_sock(sk) <--------------------- release_sock(sk)
sock_set_flag(sk, SOCK_ZAPPED)
l2cap_sock_close_cb
l2cap_sock_kill(sk)
l2cap_sock_put_chan
chan = READ l2cap_pi(sk)->chan l2cap_pi(sk)->chan = NULL
l2cap_chan_hold_unless_zero l2cap_put_chan(chan)
kref_get_unless_zero(&chan->ref)
Task 1 may observe NULL which causes null-ptr-deref.
Fix the race by taking lock_sock() in l2cap_sock_kill() to
synchronize with l2cap_sock_cleanup_listen(). hold_unless_zero() is not
needed here, l2cap_pi(sk)->chan owns reference if it is non-NULL.
Clarify code comments vs. locking.
Fixes: 6fef032af009 ("Bluetooth: L2CAP: Fix use-after-free in l2cap_sock_new_connection_cb()")
Reported-by: syzbot+e6382a2f53f5fc7453ac@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=e6382a2f53f5fc7453ac
Signed-off-by: Pauli Virtanen <pav@iki.fi>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
'uuid_count' member of struct 'discovery_state' is assigned and read
without any locks, so there is a chance of situation when
uuid_count != 0, but uuids is NULL and there will be NULL pointer
dereference.
Possible race:
'hci_update_passive_scan_sync'
'hci_discovery_filter_clear'
hdev->discovery.uuid_count = 0;
<----------------------preempted----------------------------->
'start_service_discovery'
// Set uuid_count to value != 0
hdev->discovery.uuid_count = uuid_count;
hdev->discovery.uuids = kmemdup(...);
<----------------------preempted----------------------------->
spin_lock(&hdev->discovery.lock);
kfree(hdev->discovery.uuids);
hdev->discovery.uuids = NULL;
spin_unlock(&hdev->discovery.lock);
Now uuids == NULL and uuid_count != 0.
So 'mgmt_device_found' -> 'is_filter_match' -> 'eir_has_uuids' receives
non consistent discovery state, where NULL dereference of uuids happens.
To fix it let's add discovery.lock around every read/write of uuid_count,
uuids pair of struct members. It is also important to assign uuid_count
value only after success kmemdup() allocation in
start_service_discovery(), otherwise uuids is NULL, because kmemdup failed,
but uuid_count is already assigned to non zero value.
The following panic happens:
[ ] ------------[ cut here ]------------
[ ] Unable to handle kernel NULL pointer dereference at virtual
address 0000000000000000
[ ] Internal error: Oops: 0000000096000006 [#1] PREEMPT SMP
[ ] CPU: 0 PID: 15056 Comm: kworker/u9:2
[ ] Workqueue: hci0 hci_rx_work
[ ] pstate: 10400009 (nzcV daif +PAN -UAO -TCO -DIT -SSBS BTYPE=--)
[ ] pc : eir_has_uuids+0x2d8/0x590
[ ] lr : is_filter_match+0x258/0x320
...
[ ] Call trace:
[ ] eir_has_uuids+0x2d8/0x590
[ ] is_filter_match+0x258/0x320
[ ] mgmt_device_found+0x5b0/0xafc
[ ] process_adv_report.part.0+0x8c8/0xf14
[ ] hci_le_adv_report_evt+0x338/0x3f0
[ ] hci_le_meta_evt+0x1f0/0x4c8
[ ] hci_event_packet+0x440/0xc9c
[ ] hci_rx_work+0x44c/0xaf8
[ ] process_one_work+0x54c/0x103c
[ ] worker_thread+0x6c4/0x10c4
[ ] kthread+0x274/0x2ec
[ ] ret_from_fork+0x10/0x20
[ ] Code: 14000004 91004021 eb14003f 54000180 (f9400024)
[ ] ---[ end trace 0000000000000000 ]---
Fixes: 2935e556850e ("Bluetooth: hci_sync: fix double free in 'hci_discovery_filter_clear()'")
Signed-off-by: Pavel Shpakovskiy <pashpakovskii@salutedevices.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
New sk should not be added to parent socket accept queue after last
l2cap_sock_cleanup_listen() has run in l2cap_sock_teardown_cb() and
state set to BT_CLOSED, as that can result to UAF on dereferencing the
dangling parent reference.
l2cap_sock_new_connection_cb() may race with parent l2cap_chan teardown,
due to chan->state accessed without consistent locking:
[Task 1] [Task 2]
l2cap_sock_release(parent) l2cap_connect
l2cap_sock_shutdown pchan = l2cap_global_chan_by_psm
l2cap_chan_lock(pchan)
l2cap_chan_close
l2cap_sock_teardown_cb
pchan->state = BT_CLOSED
l2cap_chan_unlock(pchan) ------> l2cap_chan_lock(pchan)
l2cap_new_connection
l2cap_sock_new_connection_cb
l2cap_chan_lock(pchan) <-------- l2cap_chan_unlock(pchan)
l2cap_sock_kill(parent) /* bt_sk(sk)->parent dangling */
Fix by adding check for sk_state == BT_LISTEN after acquiring sk lock in
l2cap_sock_new_connection_cb(). Add lock_sock() around sk_state writes
where missing, to avoid data races.
Although the data races on pchan->state should be fixed too, this
defensive sk_state check probably makes sense in any case.
Fixes: 2ff1a41a912d ("Bluetooth: L2CAP: Fix null-ptr-deref in l2cap_sock_state_change_cb()")
Reported-by: syzbot+9265e754091c2d27ea29@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=9265e754091c2d27ea29
Signed-off-by: Pauli Virtanen <pav@iki.fi>
Reported-by: syzbot+9265e754091c2d27ea29@syzkaller.appspotmail.com
Tested-by: syzbot+9265e754091c2d27ea29@syzkaller.appspotmail.com
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Since commit b66774b48dd9 ("Bluetooth: L2CAP: Fix UAF in channel timeout by holding conn ref")
l2cap_chan::conn has held reference and remains non-NULL also after the
corresponding hci_conn is deleted. In this state accessing various
fields eg. hci_conn::hdev is invalid, which leads to KASAN crash in
l2cap_sock_setsockopt() access of conn->hcon->hdev.
Check l2cap_chan::conn.hcon corresponds to an alive hci_conn before
trying to use it in l2cap_sock.c. Hold l2cap_chan_lock() in
getsockopt/setsockopt to ensure it stays alive, and to avoid data races
in l2cap_chan fields.
Fixes: b66774b48dd9 ("Bluetooth: L2CAP: Fix UAF in channel timeout by holding conn ref")
Reported-by: syzbot+b106284c2a0b7bc80cf9@syzkaller.appspotmail.com
Link: https://syzkaller.appspot.com/bug?extid=b106284c2a0b7bc80cf9
Signed-off-by: Pauli Virtanen <pav@iki.fi>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
A synchronous HCI command that never receives a response leaves
HCI_CMD_PENDING set: hci_req_cmd_complete() is the only place that clears
it, and it only runs when a response matching the last command sent
arrives.
hci_send_cmd_sync() populates hdev->req_skb only when the flag transitions
from clear to set, while hci_dev_open_sync() and hci_dev_close_sync() drop
req_skb without clearing the flag. After a timeout followed by either, the
two disagree: the flag claims a request is outstanding while req_skb is
NULL. Subsequent synchronous commands are then sent with no req_skb, so
hci_event_packet() has nothing to match an arriving event against, and the
caller times out even though the controller answered.
Commands answered by Command Complete recover on their own, since
hci_req_cmd_complete() clears the flag as a side effect. Drivers using
__hci_cmd_sync_ev() with a custom event do not, because a vendor event
never reaches that path. On a WCN3988 (hci_qca over UART) this makes a
controller firmware hang unrecoverable: the driver injects a hardware
error and re-runs qca_setup(), qca_read_soc_version() waits for
HCI_EV_VENDOR, the reply arrives within 4 ms and is discarded, and every
retry fails the same way. The adapter is left down until the driver is
unbound and rebound, or power is removed.
Clear the flag wherever the last request is dropped, restoring the
invariant that req_skb is non-NULL exactly when HCI_CMD_PENDING is set.
Verified on hardware by forcing a command timeout: without this change
setup fails on every attempt, with it setup succeeds on the first.
Fixes: 2615fd9a7c25 ("Bluetooth: hci_sync: Fix overwriting request callback")
Cc: stable@vger.kernel.org
Signed-off-by: Ibrahim Abdelkader <iabdelka@qti.qualcomm.com>
Signed-off-by: Hans de Goede <johannes.goede@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net-next
Pull networking updates from Jakub Kicinski:
"One of the 'small improvements all over the place' releases for us.
It's hard to draw any direct comparisons because summer vacations
disrupted our patch processing (and presumably - generation) quite a
bit.
Quick and dirty count suggests we (Paolo and I) merged a very similar
number of net (632) and net-next (648) patches. This is not telling
the full story either because 1/3 to 1/2 of the net-next patches also
*seem* like AI-driven low priority fixes, cleanups and clarifications.
We are completely overwhelmed, of course. The glimmer of hope is that
we secured sufficient LLM budget and access (thank you Meta!) to run
reviews with multiple frontier models on each patch. This eliminates
some hallucinations. That said, in terms of review, the LLMs can only
do so much.
The sad truth is that our APIs (especially for rare events like PCIe
errors, timeouts etc) have always been racy, and now LLMs don't let us
ignore that. I expect our direction for the next release will be to
tweak the reviews a little bit more, but start shifting focus to
letting the LLMs take care of the busy work - managing patchwork,
automating common process complaints, editing commit messages, and
maybe applying patches which already got "reviewed-by" tags from
people we trust...
Core & protocols:
- A few steps lowering rtnl_lock dependence:
- per-netns netdev unregistration for select SW drivers (e.g.
veth, ipvlan, tunnels)
- rtnl_lock-less FIB rule changes (RTM_NEWRULE and RTM_DELRULE)
- prepare software drivers and TC qdiscs for rtnl_lock-less GET
- Support BIG TCP (>64kB TSO) in UDP tunnels (vxlan, geneve)
- Support buffers larger than PAGE_SIZE in devmem zero-copy API
- Improve MPTCP handling of extreme memory pressure handling, when
out-of-order queue had to be pruned
- Report the per-group user count via RTM_GETMULTICAST
- Expose the route deletion reason in RTM_DELROUTE
- Add a SO_RIGHTS_NOTRUNC option to UNIX sockets to enable more
useful handling of LSM denials when receiving SCM_RIGHTS messages:
instead of truncating the message at the first blocked fd, keep
every fd slot and store the LSM errno in the blocked slot
- IPv6 Segment Routing - support looking up the post-encap SID
(address) in a different/specified routing table
- Support PRP RedBox (interlink) creation
- Support per-nexthop UDP dst port in VXLAN
- Continue converting getsockopt callbacks in a number of protocols
to iov_iter
Ethernet:
- Merge initial CXL support for AMD/Solarflare NICs (shared branch
with the CXL tree)
- New drivers:
- ADIN1140 10BASE-T1S MACPHY
- Initial skeleton of Intel iXD and ZTE Dinghai drivers
- High-speed NICs:
- AMD/Pensando:
- support firmware flashing
- Cisco (enic):
- SR-IOV V2 admin channel and MBOX protocol
- Huawei (hns3):
- support for ethtool pfc_prevention_tout
- nVidia/Mellanox:
- support sharing bandwidth control across interfaces
of the same device
- Marvell (octeontx2-pf):
- link RQ page pools to netdev for Netlink stats
- Google vNIC:
- XDP metadata support for DQ RDA
- Microsoft vNIC:
- support forcing full-page RX buffers
- Other NICs:
- Synopsys IP:
- eic7700: support for eth1
- Microchip (lan743x):
- support for RMII interface
- Wangxun:
- support for ethtool -G and -C for VFs
- add Tx timeout and PCIe error handling
- Intel (igb/igc):
- RSS key get/set support
- support for forcing link speed without auto-negotiation
- Switches:
- NXP (dpaa2):
- support bonding/LAG offload
- Mediatek:
- mt7530: EN7528 support
- initial support for MT7628
- Micrel (ksz8/9):
- refactoring work to move towards library model
- PTP support for KSZ8463
- nVidia/Mellanox:
- support rtnl-lock-less ethtool callbacks
- Realtek:
- rtl8366rb: use generic RTL83xx code
- support SGMII and HSGMII for RTL8367S
- PHYs:
- Airoha:
- EcoNet EN7528 PHY support
- DAPU Telecom
- DAPU Telecom DAP8211R(I) Gigabit PHY support
- Realtek:
- support RTL8261C_CG
- support RTL8261D
Wireless:
- nl80211: per-link statistics support for multi-link operation
- mac80211: AQL/airtime-fairness support for multicast
- Merge Peripheral Authentication Service (PAS) / TEE support for
ath12k (shared branch with the firmware/qcom tree)
- New drivers:
- mm81x for Morse Micro Long-Range S1G devices
- nxpwifi for NXP devices (mostly forked off from mwifiex)
- Driver changes:
- Broadcom (brcmfmac):
- DPP support, some Cypress part update
- MediaTek (mt76):
- mt7928 support
- mt7925 NAN support
- mt7996 AP powersave improvements
- Qualcomm (ath12k):
- much kernel infrastructure integration work
- AHB platform MultiPD support
- Realtek (rt89):
- LED support
- RTL8922DE support
- dual-BT coex for RTL8922D
- Intel:
- new FW version support
Bluetooth:
- HCI: add support for Shorter Connection Interval (SCI) feature
- af_bluetooth: add minimal context analysis annotations
- Driver changes:
- Intel:
- add Bluetooth SAR revision 2 support
- add vendor_reset PCI sysfs for PLDR
- Mediatek:
- add USB IDs for MT7902 and MT7922 devices
- Realtek:
- add USB IDs for 8761CU and 8852BE devices
- NXP:
- add M.2 Bluetooth device support using pwrseq
Misc:
- DPLL support for manual/numerical oscillator control (NCO)
(implement in zl3073x)
- MCTP support for MCTP over USB v1.1 (DMTF DSP0283)
- Power-over-Ethernet: support Realtek PSE controllers
- Remove the IBM EHEA driver
- Remove tulip/xircom_cb driver"
* tag 'net-next-7.3' of git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net-next: (1433 commits)
net/mlx5e: do not HW-GRO coalesce small frames
net: openvswitch: fix nf_connlabels leak in ovs_ct_init
net: add missing ref_tracker_dir_exit() to alloc_netdev_mqs()
net: openvswitch: fix flow mask use-after-free on flow deletion
sctp: stop processing a packet once its association is deleted
dpll: zl3073x: add PTP clock support
dpll: zl3073x: add channel ToD, phase step and TIE operations
dpll: zl3073x: scale poll interval proportionally to timeout
ptp: vmclock: prevent read-only mappings from becoming writable
ipv4: reject undersized MTUs in ip_do_fragment()
bonding: initialize err for empty target lists
net: dsa: initial support for MT7628 embedded switch
net: dsa: initial MT7628 tagging driver
net: phy: mediatek: add phy driver for MT7628 built-in Fast Ethernet PHYs
dt-bindings: net: dsa: add MT7628 ESW
net: pse-pd: realtek-pse-mcu: add UART transport
net: pse-pd: realtek-pse-mcu: add I2C transport
net: pse-pd: add Realtek PSE MCU core
dt-bindings: net: pse-pd: add bindings for Realtek PSE MCU
vsock: use sock_error() to consume sk_err after a failed connect
...
|
|
git://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux
Pull crypto library updates from Eric Biggers:
"Add library APIs for most AES encryption modes that are used in the
kernel (ECB, CBC, CBC-CTS, CTR, XCTR, XTS, GCM, CCM).
These AES modes have many in-kernel users that are currently using the
crypto_skcipher or crypto_aead APIs. These existing APIs are difficult
to use and inefficient. Until now, the lack of proper library support
for these has been the main gap in the crypto library.
This set of changes is the next stage of addressing it:
- Implement the new APIs on top of the existing support for
single-block AES in the library.
- Fully document the new APIs.
- Migrate the only user of the old AES-GCM library API to the new,
more flexible API; then remove the old API and its implementation.
- Wire up the new APIs to the traditional crypto API by adding
crypto_skcipher and crypto_aead algorithms.
This makes the new APIs be covered by the traditional crypto API's
self-tests. It also makes them be already used for real on systems
that don't have architecture-optimized code for these modes.
But most importantly, this is a prerequisite for migrating the
architecture-optimized code for these AES modes (i.e.
arch/*/crypto/aes*) into the library, which as usual will eliminate
a lot of redundant "glue" code.
Note that unlike some of the other algorithms that have been migrated
to the library, e.g. SHA-512, for these AES modes there was too much
to get done in one cycle. Nor did it make sense to handle these modes
one at a time, because they tend to be coupled together or depend on
each other, especially in the architecture-optimized AES code.
Thus, most of the benefits (reductions in lines of code, performance
improvements, etc.) will follow in later cycles when
architecture-optimized code is migrated into the library and users of
crypto_skcipher and crypto_aead are updated to use the new APIs.
The design of the new APIs was informed by writing proof-of-concept
patches for many kernel subsystems currently accessing these same
algorithms via crypto_skcipher or crypto_aead (patches 18-33 of
https://lore.kernel.org/r/20260707053503.209874-1-ebiggers@kernel.org/).
While those patches will be resent for real later, the total diffstat
for them was negative 1905 lines. So clearly the new APIs are quite a
bit easier to use and align better with what users actually need.
Besides the new AES encryption APIs, there are also a few changes for
improved AES-CMAC key and context zeroization"
* tag 'libcrypto-updates-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux:
mac80211: fils_aead: Use __cleanup() instead of memzero_explicit()
Bluetooth: SMP: clear the aes_cmac_key when done
smb: clear the aes_cmac_key and aes_cmac_ctx when done
lib/crypto: aes-cmac: Add zeroization functions
lib/crypto: aesgcm: Remove old AES-GCM library
x86/sev: Remove obsolete virtual address check
x86/sev: Use new AES-GCM library
crypto: aes - Add CCM support using library
crypto: aes - Add GCM support using library
crypto: aes - Add XTS support using library
crypto: aes - Add CTR and XCTR support using library
crypto: aes - Add CBC and CBC-CTS support using library
crypto: aes - Add ECB support using library
lib/crypto: aes: Add CCM support
lib/crypto: aes: Add GCM support
lib/crypto: aes: Add XTS support
lib/crypto: aes: Add CTR and XCTR support
lib/crypto: aes: Add CBC and CBC-CTS support
lib/crypto: aes: Add ECB support
crypto: xts - Split out __xts_verify_key() helper
|
|
Clear the local aes_cmac_key structure via __cleanup() function
when we're done with it to avoid that sensitive data could leak on
the stack.
While we're at it, also clear the tmp[] array here that is populated
with a raw version of the original key and thus would leak the same
information via the stack otherwise.
Signed-off-by: Thomas Huth <thuth@redhat.com>
Link: https://patch.msgid.link/20260807125845.1477067-5-thuth@redhat.com
Signed-off-by: Eric Biggers <ebiggers@kernel.org>
|
|
rfcomm_sock_recvmsg() completes a deferred setup by calling
rfcomm_dlc_accept() without holding any RFCOMM lock:
if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {
rfcomm_dlc_accept(d);
return 0;
}
and rfcomm_dlc_accept() dereferences the session on its first line:
struct sock *sk = d->session->sock->sk;
Every other path that touches d->session runs under rfcomm_mutex:
rfcomm_dlc_open(), rfcomm_dlc_close(), rfcomm_dlc_exists(),
rfcomm_dlc_send_rpn(), and the RFCOMM thread through
rfcomm_process_sessions(). rfcomm_connect_ind() is even documented as
"called under rfcomm_lock()". This call site is the only one that skips
it.
The RFCOMM_DEFER_SETUP bit looks like it serialises the accept against
teardown, since __rfcomm_dlc_close() returns early when it wins the
test_and_clear. But rfcomm_recv_disc() forces the state first:
d->state = BT_CLOSED;
__rfcomm_dlc_close(d, err);
and the early return only covers BT_CONNECT, BT_CONFIG, BT_OPEN and
BT_CONNECT2. With the state already BT_CLOSED that switch does not
match, the bit is never consulted, and __rfcomm_dlc_close() falls
through to rfcomm_dlc_unlink(), which sets d->session = NULL.
So a remote DISC on a deferred dlc clears the session while leaving
RFCOMM_DEFER_SETUP set. The next recvmsg() then passes the
test_and_clear and dereferences a NULL session. No timing window is
needed: once the DISC has been processed, the dereference is
unconditional.
Give rfcomm_dlc_accept() the same shape as rfcomm_dlc_open() and
rfcomm_dlc_close(): an exported wrapper that takes rfcomm_mutex and
re-checks the session, around a __rfcomm_dlc_accept() that the two
in-core callers, which already hold the mutex, keep using.
Reproduced on a KASAN + PROVE_LOCKING kernel with a BR/EDR peer emulated
over /dev/vhci: the peer brings up an ACL link, opens L2CAP on the
RFCOMM PSM, starts a session, opens a dlc on a channel bound with
BT_DEFER_SETUP, and sends DISC after the socket is accepted. recv() on
the accepted socket then hits:
Oops: general protection fault
KASAN: null-ptr-deref in range [0x0000000000000010-0x0000000000000017]
RIP: 0010:rfcomm_dlc_accept+0x54/0x350
Call Trace:
rfcomm_sock_recvmsg+0x1cd/0x230
sock_recvmsg+0x166/0x1c0
__sys_recvfrom+0x20d/0x300
0x10 is the offset of sock in struct rfcomm_session. With this patch the
same run completes with recv() returning 0 and no report, and lockdep
stays quiet, confirming rfcomm_mutex is still taken before lock_sock on
this path as it is on the thread side.
Fixes: bb23c0ab8246 ("Bluetooth: Add support for deferring RFCOMM connection setup")
Cc: stable@vger.kernel.org
Signed-off-by: Ali Ahmet Memis <ali@iusegentoo.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
read_supported_features() only checks that the response covers the fixed
part of struct msft_rp_read_supported_features, which is 11 bytes:
if (skb->len < sizeof(*rp)) {
bt_dev_err(hdev, "MSFT supported features length mismatch");
goto failed;
}
evt_prefix[] is a flexible array member and rp->evt_prefix_len is an
unvalidated u8 taken straight out of that response, so
msft->evt_prefix = kmemdup(rp->evt_prefix, rp->evt_prefix_len,
GFP_KERNEL);
copies up to 255 bytes from a reply that may have carried none of them.
What is copied is data the controller never sent, and it is then used to
match incoming vendor events in msft_vendor_evt().
This is not an out-of-bounds access. An skb data allocation always has
at least SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) bytes past the
payload, which is more than the 255 byte maximum, so the read stays
inside the allocation and KASAN does not report it. It is still a read
of bytes the host was never given, with the length fully controlled by
the controller.
Reject a response that is too short for the prefix it declares.
Verified with an emulated controller over /dev/vhci on a KASAN kernel,
with vhci made to advertise an MSFT opcode the way btintel, btqca, btmtk
and btrtl do unconditionally. A reply of exactly 11 bytes declaring
evt_prefix_len = 255 reaches kmemdup and copies 255 bytes
("skb->len=11 evt_prefix_len=255", with the copied buffer dumped); since
the reply ends at the fixed part, all 255 come from past the end of the
response. No KASAN report is produced, as expected from the allocation
slack described above. With this patch the response is rejected with
"MSFT event prefix length mismatch" and msft->evt_prefix is left unset.
Fixes: 145373cb1b1f ("Bluetooth: Add framework for Microsoft vendor extension")
Signed-off-by: Ali Ahmet Memis <ali@iusegentoo.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
iso_sock_getname() fills a struct sockaddr_iso in place and returns its
size without clearing it first, so bytes it does not write are copied to
user space from the kernel stack. The getsockname(2) and getpeername(2)
paths both run through do_getsockname(), which hands getname() an
uninitialized sockaddr_storage on the stack and copies back up to the
number of bytes getname() returns, so the driver has to initialize every
byte it accounts for.
Two ranges are left uninitialized:
- struct sockaddr_iso is 10 bytes but only 9 are written (family,
iso_bdaddr, iso_bdaddr_type), leaking the trailing pad byte on every
call.
- for a broadcast peer (BIS_LINK or PA_LINK) the returned length grows
by sizeof(struct sockaddr_iso_bc), but only bc_sid, bc_num_bis and
bc_bis are filled; bc_bdaddr and bc_bdaddr_type, the first 7 bytes of
that structure, are never written.
An unprivileged process can open a BTPROTO_ISO socket and reach the pad
leak with getsockname(); the broadcast leak needs an established BIS/PA
connection. l2cap and rfcomm already memset their sockaddr in getname
for the same reason; do the same here.
Fixes: ccf74f2390d6 ("Bluetooth: Add BTPROTO_ISO socket type")
Fixes: 0a766a0affb5 ("Bluetooth: ISO: Fix getpeername not returning sockaddr_iso_bc fields")
Cc: stable@vger.kernel.org
Signed-off-by: Ali Ahmet Memis <ali@iusegentoo.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
iso_sock_recvmsg() handles the deferred setup of a broadcast sink by
dropping the socket lock, calling iso_conn_big_sync() and taking the
lock again:
release_sock(sk);
iso_conn_big_sync(sk);
lock_sock(sk);
sk->sk_state = BT_LISTEN;
The state is written unconditionally, but iso_conn_big_sync() returns
void and has paths that do nothing at all: hci_get_route() may fail, and
after re-acquiring the socket lock the connection may already be gone,
in which case it bails out without ever issuing an LE BIG Create Sync.
While the lock is dropped the connection can be torn down, for example
when the controller reports HCI_EV_LE_PA_SYNC_LOST:
hci_le_pa_sync_lost_evt()
hci_disconn_cfm() -> iso_disconn_cfm() -> iso_conn_del()
iso_chan_del()
iso_pi(sk)->conn = NULL
sk->sk_state = BT_CLOSED
sock_set_flag(sk, SOCK_ZAPPED)
iso_conn_big_sync() then finds conn == NULL and returns, but the caller
still overwrites the BT_CLOSED that iso_chan_del() has just set. The
socket ends up marked BT_LISTEN with no connection, so recvmsg() reports
success for a setup that never happened and a later accept() waits for
BIS connections that can never arrive instead of failing.
A concurrent shutdown() reaches the same write by another route:
__iso_sock_close() takes the BT_CONNECT2 PA sync path to
iso_sock_disconn(), which sets BT_DISCONN but leaves conn and
conn->hcon in place, so iso_conn_big_sync() succeeds and BT_LISTEN is
written over BT_DISCONN. Both the BT_CONNECT2 and the BT_CONNECTED case
write the state the same way.
Let iso_conn_big_sync() report whether the BIG sync was started, and
only move the socket to BT_LISTEN when it was and when the state has not
changed while the lock was dropped, mirroring what the BT_CONNECT case
of the same switch already does with iso_connect_cis(). Both conditions
are needed, the error alone does not cover the shutdown() race.
This corrupts the socket state machine only, it is not a memory safety
issue. KASAN and lockdep stayed quiet in all of the runs below.
Reproduced with an emulated controller over /dev/vhci on a KASAN +
PROVE_LOCKING kernel. A PA sync broadcast sink socket is driven to
BT_CONNECT2 and recvmsg() on it is raced against teardown, with a debug
delay inside the lock-dropped section to widen the window:
- HCI_EV_LE_PA_SYNC_LOST injected: 64 of 64 rounds left the socket in
BT_LISTEN with the connection gone, recvmsg() returned 0 and accept()
on that fd returned EAGAIN, which iso_sock_accept() can only do while
the socket is BT_LISTEN. With this patch, 0 of 64, recvmsg() returns
an error and accept() returns EBADFD.
- shutdown() instead of a controller event: 24 of 32 rounds wedged in
BT_LISTEN, 0 of 32 with this patch. With only the error check in
place and a short window, one round still wedged while recvmsg()
returned 0, which is the case the state re-check covers.
An unraced control round behaves the same before and after: recvmsg()
returns 0, the socket reaches BT_LISTEN and an LE BIG Create Sync is
issued.
Fixes: 7a17308c1788 ("Bluetooth: iso: Fix circular lock in iso_conn_big_sync")
Cc: stable@vger.kernel.org
Signed-off-by: Ali Ahmet Memis <ali@iusegentoo.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_setup_ext_adv_instance_sync(...) only disabled
HCI_OP_LE_SET_EXT_ADV_ENABLE before setup snapshot in case of non-legacy
instances (instance > 0) and never disabled the same for legacy instance
(instance == 0). This would lead to failure in setting ext adv params
with HCI_ERROR_COMMAND_DISALLOWED (0x0c) error like below, when toggling
the discoverable/connectable property of a controller with advertising
enabled.
```
$ btmgmt advertising off
hci0 Set Advertising complete, settings: powered ssp br/edr le
secure-conn wide-band-speech cis-central cis-peripheral
$ btmgmt connectable on
hci0 Set Connectable complete, settings: powered connectable ssp br/edr
le secure-conn wide-band-speech cis-central cis-peripheral
$ btmgmt connectable off
hci0 Set Connectable complete, settings: powered ssp br/edr le
secure-conn wide-band-speech cis-central cis-peripheral
$ btmgmt advertising on
hci0 Set Advertising complete, settings: powered connectable ssp br/edr
le advertising secure-conn wide-band-speech cis-central cis-peripheral
$ btmgmt connectable on
Set Connectable for hci0 failed with status 0x0a (Busy)
$ btmgmt connectable off
Set Connectable for hci0 failed with status 0x0a (Busy)
$ dmesg
...
[ 21.970527] hci0: Opcode 0x2036
[ 21.970529] hci0: opcode 0x2036 plen 25
[ 21.970537] hci0: skb len 28
[ 21.970539] hci0: length 1
[ 21.976099] hci0: result 0x0c
[ 21.976105] hci0: end: err -16
[ 21.976114] Bluetooth: hci0: Opcode 0x2036 failed: -16
```
Signed-off-by: Muhammad Saheed <muhammad.saheed.iam@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_le_per_adv_report_evt() is dispatched with a minimum length of
sizeof(struct hci_ev_le_per_adv_report), which only covers the fixed
part of the event and not the trailing data[] array:
struct hci_ev_le_per_adv_report {
__le16 sync_handle;
__u8 tx_power;
__u8 rssi;
__u8 cte_type;
__u8 data_status;
__u8 length;
__u8 data[];
} __packed;
The handler notifies the ISO layer via hci_proto_connect_ind(), which
reaches iso_connect_ind(). That function retrieves the stored event with
hci_recv_event_data() and, while reassembling the periodic advertising
data, does:
memcpy(hcon->le_per_adv_data + hcon->le_per_adv_data_offset,
ev->data, ev->length);
ev->length is taken directly from the event and is never validated
against the amount of data the event actually carries. A controller
that reports a length larger than the received event therefore causes
the memcpy() to read past the end of the event buffer. The leaked bytes
are stored in hcon->le_per_adv_data and can subsequently be read back
from user space via getsockopt(BT_ISO_BASE).
Validate that the event contains ev->length data bytes before it is
consumed, mirroring the check already performed by
hci_le_ext_adv_report_evt() and hci_le_adv_report_evt().
Signed-off-by: Laxman Acharya <acharyalaxman8848@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
mgmt_hci_cmd_sync() checks that the message length agrees with params_len
but puts no upper bound on it. params_len is __le16 while the parameter
length in the HCI command header is a u8:
struct hci_command_hdr {
__le16 opcode;
__u8 plen;
} __packed;
hci_cmd_sync_alloc() assigns one to the other:
hdr->plen = plen;
if (plen)
skb_put_data(skb, param, plen);
so a params_len of 256 leaves plen at 0 while all 256 bytes are still
appended. The frame handed to the driver then declares no parameters and
carries 256 of them. On a length framed transport such as H:4 the
controller takes the trailing bytes as the start of the next packet.
The mgmt socket MTU is HCI_MAX_FRAME_SIZE, so params_len can reach about
1KB this way. Commit 03f1700b9b4d ("Bluetooth: MGMT: reject malformed
HCI_CMD_SYNC commands") only made params_len agree with the message
length, a value that fits the message but not the header field is still
accepted.
Reject params_len that does not fit the header field.
Fixes: 827af4787e74 ("Bluetooth: MGMT: Add initial implementation of MGMT_OP_HCI_CMD_SYNC")
Cc: stable@vger.kernel.org
Signed-off-by: Ali Ahmet Memis <ali@iusegentoo.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
mgmt_hci_cmd_sync() queues the pending command with a NULL destroy
callback, so it is only freed if send_hci_cmd_sync() runs. A cancelled
entry is leaked, as _hci_cmd_sync_cancel_entry() does not release
entry->data when there is no destroy callback, and hci_cmd_sync_clear()
cancels every pending entry when the controller is unregistered. Nothing
else reclaims it either: mgmt_pending_new() does not put the command on
hdev->mgmt_pending.
The leak also pins the socket reference taken by mgmt_pending_new(), so
the mgmt socket is never released.
Free the command from a destroy callback. The now-empty done label is
replaced by a direct return.
Fixes: 827af4787e74 ("Bluetooth: MGMT: Add initial implementation of MGMT_OP_HCI_CMD_SYNC")
Signed-off-by: Linmao Li <lilinmao@kylinos.cn>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
mesh_send_cancel() queues the pending command with a NULL destroy
callback, so it is only freed if send_cancel() runs. A cancelled entry is
leaked, as _hci_cmd_sync_cancel_entry() does not release entry->data when
there is no destroy callback, and hci_cmd_sync_clear() cancels every
pending entry when the controller is unregistered. Nothing else reclaims
it either: mgmt_pending_new() does not put the command on
hdev->mgmt_pending.
The leak also pins the socket reference taken by mgmt_pending_new(), so
the mgmt socket is never released.
Free the command from a destroy callback.
Fixes: b338d91703fa ("Bluetooth: Implement support for Mesh")
Signed-off-by: Linmao Li <lilinmao@kylinos.cn>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
paths
adv_timeout_expire() hands a kmalloc()ed instance byte to
hci_cmd_sync_queue() with a NULL destroy callback, and only
adv_timeout_expire_sync() frees it. That leaks on two paths:
- the return value is not checked, and hci_cmd_sync_queue() does not
take ownership when it fails (-ENETDOWN, -ENODEV, -ENOMEM);
- a cancelled entry is not released, as _hci_cmd_sync_cancel_entry()
does not free entry->data when there is no destroy callback.
hci_cmd_sync_clear() cancels every pending entry when the controller
is unregistered.
Free the buffer from a destroy callback, and in the caller when the entry
could not be queued at all.
Fixes: c249ea9b4309 ("Bluetooth: Move Adv Instance timer to hci_sync")
Signed-off-by: Linmao Li <lilinmao@kylinos.cn>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_setup_sync() queues a conn_handle_t with a NULL destroy callback, so
the context is only freed if hci_enhanced_setup_sync() actually runs. An
entry that is cancelled instead is leaked, as
_hci_cmd_sync_cancel_entry() does not release entry->data when there is
no destroy callback, and hci_cmd_sync_clear() cancels every pending entry
when the controller is unregistered.
The context also stores a bare hci_conn pointer, so the connection can be
freed while the work is queued. The dequeue in hci_conn_del() does not
cover it either, as it matches on entry->data == conn and entry->data is
the wrapper here. Same problem as commit 2f5d635ad590 ("Bluetooth:
hci_sync: hold conn in hci_connect_acl/le_sync() callbacks").
Hold the connection and release both from a destroy callback. The
submission failure path drops both, since hci_cmd_sync_submit() does not
call the destroy callback when it fails to queue.
Fixes: e07a06b4eb41 ("Bluetooth: Convert SCO configure_datapath to hci_sync")
Signed-off-by: Linmao Li <lilinmao@kylinos.cn>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_update_event_filter_sync() walks hdev->accept_list while sending a
synchronous HCI command for each remote-wakeup device. The suspend path
holds hdev->req_lock, but accept-list updates are serialized by hdev->lock.
Consequently, remove_device() can free the current list entry during the
controller wait.
The following interleaving causes the use-after-free:
hci_update_event_filter_sync() remove_device()
fetch accept-list entry
hci_set_event_filter_sync()
wait for controller response hci_dev_lock()
list_del()
kfree()
hci_dev_unlock()
read the freed list.next
KASAN reported:
BUG: KASAN: slab-use-after-free in hci_suspend_sync+0x835/0x910
Read of size 8 at addr ffff88810bec8440 by task kworker/0:1/10
Workqueue: events vhci_suspend_work
Call Trace:
hci_suspend_sync+0x835/0x910
hci_suspend_dev+0x182/0x450
process_one_work+0x661/0x1090
worker_thread+0x45b/0xd10
Allocated by task 86:
hci_bdaddr_list_add_with_flags+0x1a8/0x400
add_device+0x381/0x820
hci_sock_sendmsg+0x1033/0x1ea0
Freed by task 91:
kfree+0x131/0x3c0
remove_device+0x429/0xb70
hci_sock_sendmsg+0x1033/0x1ea0
Snapshot the remote-wakeup addresses under hdev->lock. Release the lock
before sending HCI commands. Clear the controller event filter before
building the snapshot, and skip allocation and the second list traversal
when there are no matching entries. This preserves the original filter
and scan-state updates without retaining an accept-list node across a
controller wait.
Fixes: 182ee45da083 ("Bluetooth: hci_sync: Rework hci_suspend_notifier")
Cc: stable@vger.kernel.org
Link: https://lore.kernel.org/linux-bluetooth/20260730092331.2069741-1-nicoyip.dev@gmail.com/
Signed-off-by: Chengfeng Ye <nicoyip.dev@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_event_func() validates skb->len against ev->max_len from the
entry in hci_ev_table[]. By then, the header has already been
stripped by skb_pull(). So the max event payload is 255, but
hci_ev_table[] still uses HCI_MAX_EVENT_SIZE (260) for it, which is
imprecise.
Fix by introducing HCI_MAX_EVENT_PLEN (255) and using it instead.
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Introduce the hook to solve issues below:
msft_vendor_evt(), the current handler for all VSEs, is unsuitable
since:
- many VSEs are not MSFT ones;
- it always corrupts the non-MSFT VSEs by calling skb_pull_data()
once the MSFT extension is enabled.
Several issues are caused by many transport drivers pre-processing
VSEs in their RX path, often an IRQ-disabled atomic context. Take
the two typical cases below as examples:
Case 1:
// no btmon log, no way to reach userspace
Step 1: handle and free @original_skb directly
Case 2:
// hurts performance and consumes GFP_ATOMIC memory
Step 1: cloned_skb = skb_clone(original_skb, GFP_ATOMIC);
// the VSE is handled here
Step 2: handle and free @cloned_skb
Step 3: hci_recv_frame(hdev, original_skb);
// already handled, but re-enters the stack's event-handling path
Step 4: hci_event_packet(hdev, original_skb);
Fix by introducing the hook with usage:
1) the transport driver registers the hook for VSEs of interest;
2) the stack calls it in process context, handling the VSE like any
other event:
- if interested, handle the VSE - no need to free it - and
return true;
- otherwise return false.
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_reset_dev() injects a constant hardware error code 0x00 to restart
the device. But a transport driver may need a different error code.
Fix by introducing __hci_reset_dev(hdev, hw_err_code), which will be
used by a follow-up patch.
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
To separate the coredump header and data far more easily, give a
vendor driver the option to pad its header to a fixed size, by
moving the header size limit and ending marker to coredump.h:
- HCI_DEVCD_HDR_SIZE_MAX: the max header size
- HCI_DEVCD_HDR_END_MARKER: the header-ending marker
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
The Command Complete dispatch validates only the fixed part of the LE Set
CIG Parameters response. After that part is pulled from the skb,
hci_cc_le_set_cig_params() trusts num_handles and reads each entry in the
trailing handle array.
Matching num_handles against the command's num_cis does not guarantee
that the response contains the advertised handles. A truncated response
from a malfunctioning controller can therefore make the handler read
beyond the skb data.
Validate that the remaining skb data contains all advertised handles.
Include this in the existing response validation so malformed responses
also follow the established CIG failure handling.
Fixes: 26afbd826ee3 ("Bluetooth: Add initial implementation of CIS connections")
Cc: stable@vger.kernel.org
Signed-off-by: Laxman Acharya Padhya <acharyalaxman8848@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Add context analysis annotations for hci_conn::l2cap_data locking.
Also add necessary lockdep_assert_held() and __must_hold annotations
to prove the access is safe.
The access in smp_conn_security() is supposed to be guarded by the
caller holding lock that blocks concurrent l2cap_conn_del() eg.
hdev->lock, conn->lock or chan->lock. Mark unsafe as can't be
automatically checked now.
Signed-off-by: Pauli Virtanen <pav@iki.fi>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_conn::l2cap_data is accessed without locks in l2cap_disconn_ind via
hci_conn_timeout (disc_work) -> hci_proto_disconn_ind ->
l2cap_disconn_ind. This is UAF if the l2cap_conn is deleted
concurrently.
disc_work is disabled sync in hci_conn_del(), so we cannot take
hci_dev_lock in disc_work.
Fix by using proto_lock to guard l2cap_data, in addition to hdev->lock
which is held in other access paths.
Fixes: ab4eedb790ca ("Bluetooth: L2CAP: Fix corrupted list in hci_chan_del")
Reported-by: syzbot+9c40ad7c6ed7165e46e8@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=9c40ad7c6ed7165e46e8
Signed-off-by: Pauli Virtanen <pav@iki.fi>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_cc_reset() clears the LE accept and resolving lists without taking
hdev->lock. Other command-complete handlers serialize updates to these
lists with that lock, and the debugfs readers hold it while walking them.
This permits the reset completion and a debugfs read to interleave as
follows:
hci_rx_work debugfs reader
----------- --------------
lock hdev->lock
fetch current entry
list_del(entry)
kfree(entry)
read entry fields
The reader then dereferences a freed list entry and may follow its stale
next pointer.
KASAN reported:
BUG: KASAN: slab-use-after-free in white_list_show+0x15f/0x180
Read of size 1 at addr ffff8881015dab16 by task poc/95
Call Trace:
white_list_show+0x15f/0x180
seq_read_iter+0x3ff/0x1190
seq_read+0x267/0x3d0
vfs_read+0x177/0xa20
ksys_read+0xf7/0x1c0
Allocated by task 91:
hci_bdaddr_list_add+0x1a6/0x3a0
hci_cc_le_add_to_accept_list+0xab/0x140
hci_cmd_complete_evt+0x26c/0x9a0
hci_event_packet+0x454/0xb20
hci_rx_work+0x293/0x730
Freed by task 90:
kfree+0x131/0x3c0
hci_bdaddr_list_clear+0xd8/0x160
hci_cc_reset+0x28a/0x370
hci_cmd_complete_evt+0x26c/0x9a0
hci_event_packet+0x454/0xb20
hci_rx_work+0x293/0x730
Take hdev->lock around both list clears. This matches the existing
mutation and traversal locking convention.
Fixes: a4d5504d5c39 ("Bluetooth: Clear LE white list when resetting controller")
Fixes: cfdb0c2d095a ("Bluetooth: Store Resolv list size")
Cc: stable@vger.kernel.org
Signed-off-by: Chengfeng Ye <nicoyip.dev@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Add MGMT_OP_LOAD_CONN_SUBRATE (0x005C) command to load per-device
connection subrate parameters when the SCI feature is supported.
Add MGMT_EV_CONN_SUBRATE (0x0033) event to notify userspace when
connection rate changes occur via the LE Connection Rate Change HCI
event.
Add subrate fields (subrate_min, subrate_max, max_latency, cont_num)
to struct hci_conn_params to store the loaded subrate parameters, and
the corresponding le_rate_* fields to struct hci_conn to track the
parameters currently in use.
When a single entry is loaded for an already-connected central, or on
connection completion, the LE Connection Rate Request procedure is
initiated to apply the parameters.
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Add MGMT_SETTING_SCI (bit 25) to advertise support for the Shorter
Connection Interval (SCI) feature. It is reported in the supported
settings whenever the controller is SCI capable, and in the current
settings whenever LE is enabled and the controller is SCI capable
(SCI has no separate enable command, so it is a passive capability).
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Add HCI command, event and feature bit definitions for the Bluetooth
6.2 Shorter Connection Interval feature:
Commands:
- HCI_OP_LE_CONN_RATE (0x20a1) - Connection Rate Request
- HCI_OP_LE_SET_DEF_RATE (0x20a2) - Set Default Rate Parameters
- HCI_OP_LE_READ_CONN_INTERVAL (0x20a3) - Read Min Supported
Connection Interval
Events:
- HCI_EVT_LE_CONN_RATE_CHANGE (0x37) - Connection Rate Change
Feature bits:
- HCI_LE_SCI - Shorter Connection Intervals
- HCI_LE_SCI_HOST - Shorter Connection Intervals (Host Support)
During controller init, when SCI is supported:
- Set Shorter Connection Intervals (Host Support) feature via
LE Set Host Feature
- Read Minimum Supported Connection Interval
- Set Default Rate Parameters
The Connection Rate Change event handler updates the connection
interval, latency and supervision timeout on the hci_conn.
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Simplify hci_recv_frame() by using hci_acl_handle() instead of:
__u16 handle = __le16_to_cpu(hci_acl_hdr(skb)->handle);
... hci_handle(handle) ...
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Introduce hci_devcd_state_name() to describe the devcoredump state by a
string name instead of a plain number, for several reasons:
1) Applying it in coredump.c makes the devcoredump state in log messages
more readable than a plain number.
2) Transport drivers may need to show the devcoredump state name too.
3) In future, the universal state name could be notified to userspace
via uevent, allowing a universal application (e.g. a daemon) to be
developed to save the coredump, which is otherwise discarded by the
device coredump core after 5 minutes (DEVCD_TIMEOUT); see
nxp_coredump_notify().
Also drop a trailing space from two bt_dev_dbg() format strings while
applying it in coredump.c.
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
The modules rfcomm (BT_RFCOMM), bnep (BT_BNEP), hidp (BT_HIDP), and
bluetooth_6lowpan (BT_6LOWPAN) are dependent on the bluetooth module
(BT, tristate) only transitively through the boolean BT_BREDR for the
first three and through the boolean BT_LE for the bluetooth_6lowpan.
Therefore, the modules can be selected as built-in even if the BT=m.
The combination of BT=m and =y for the said modules leads to the kernel
build system silently ignoring those modules, without ever compiling
them as built-in or as loadable modules.
Add BT as a direct dependency to the Kconfig of rfcomm, bnep, hidp, and
bluetooth_6lowpan. The modules set to =y when BT=m will default to =m,
rather then getting silently ignored by the build system.
Signed-off-by: Iva Kasprzaková <iva@yenya.net>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Do not export both functions since they are only used internally
within the bluetooth module.
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
HCI_Reset is a critical command, but hci_cc_reset() uses bt_dev_dbg()
to log it, so a non-zero error status response may not be noticed.
Fix by using bt_dev_err() when a status error occurs.
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Return the reset command status directly instead of storing it in a
local variable and using an if/return pattern.
Reviewed-by: Bartosz Golaszewski <bartosz.golaszewski@oss.qualcomm.com>
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Several vendor drivers have a requirement to send a synchronous raw HCI
reset with HCI_INIT_TIMEOUT.
Add a dedicated __hci_reset_sync() for them to use.
Signed-off-by: Zijun Hu <zijun.hu@oss.qualcomm.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
hci_cmd_sync_dequeue_once() had a single in-tree caller,
hci_cancel_connect_sync(), which now holds cmd_sync_work_lock across the
in-flight create flag test and the dequeue and so open-codes the lookup
and cancel under that lock. That leaves the exported
hci_cmd_sync_dequeue_once() with no in-tree user, so remove it along with
its declaration.
Signed-off-by: Siwei Zhang <oss@fourdim.xyz>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|
|
Simplify 'force_no_mitm_write()' by using the convenient
'kstrtobool_from_user()'.
Signed-off-by: Dmitry Antipov <dmantipov@yandex.ru>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
|